@cardstack/boxel-cli 0.2.0-unstable.327 → 0.2.0-unstable.446

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 CHANGED
@@ -1,130 +1,130 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Ru=Object.create;var Ai=Object.defineProperty;var $u=Object.getOwnPropertyDescriptor;var bu=Object.getOwnPropertyNames;var Su=Object.getPrototypeOf,vu=Object.prototype.hasOwnProperty;var w=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var xu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bu(e))!vu.call(r,i)&&i!==t&&Ai(r,i,{get:()=>e[i],enumerable:!(n=$u(e,i))||n.enumerable});return r};var T=(r,e,t)=>(t=r!=null?Ru(Su(r)):{},xu(e||!r||!r.__esModule?Ai(t,"default",{value:r,enumerable:!0}):t,r));var Li=w((HE,ku)=>{ku.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 Fi=w((WE,Ee)=>{var _r=require("fs"),Rt=require("path"),_u=require("os"),Cu=require("crypto"),Ou=Li(),Cr=Ou.version,Pu=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Tu(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
3
- `);let n;for(;(n=Pu.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 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 Hi(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,`
2
+ "use strict";var _u=Object.create;var Mi=Object.defineProperty;var Cu=Object.getOwnPropertyDescriptor;var Ou=Object.getOwnPropertyNames;var Pu=Object.getPrototypeOf,Tu=Object.prototype.hasOwnProperty;var w=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Au=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ou(e))!Tu.call(r,i)&&i!==t&&Mi(r,i,{get:()=>e[i],enumerable:!(n=Cu(e,i))||n.enumerable});return r};var T=(r,e,t)=>(t=r!=null?_u(Pu(r)):{},Au(e||!r||!r.__esModule?Mi(t,"default",{value:r,enumerable:!0}):t,r));var Ii=w((rb,Lu)=>{Lu.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 ji=w((nb,Ee)=>{var Or=require("fs"),$t=require("path"),Mu=require("os"),Iu=require("crypto"),Nu=Ii(),Pr=Nu.version,Fu=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Du(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
3
+ `);let n;for(;(n=Fu.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 Uu(r){r=r||{};let e=Ui(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=Di(r).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let a=n[o].trim(),l=qu(t,a);s=G.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return G.parse(s)}function ju(r){console.log(`[dotenv@${Pr}][WARN] ${r}`)}function Xe(r){console.log(`[dotenv@${Pr}][DEBUG] ${r}`)}function Fi(r){console.log(`[dotenv@${Pr}] ${r}`)}function Di(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 qu(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 Ui(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Or.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=$t.resolve(process.cwd(),".env.vault");return Or.existsSync(e)?e:null}function Ni(r){return r[0]==="~"?$t.join(Mu.homedir(),r.slice(1)):r}function Gu(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&Fi("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 Hu(r){let e=$t.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=[Ni(r.path)];else{s=[];for(let c of r.path)s.push(Ni(c))}let o,a={};for(let c of s)try{let u=G.parse(Or.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=$t.relative(process.cwd(),f);u.push(d)}catch(d){n&&Xe(`Failed to load ${f} ${d.message}`),o=d}Fi(`injecting env (${c}) from ${u.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function Wu(r){if(Di(r).length===0)return G.configDotenv(r);let e=Ui(r);return e?G._configVault(r):(ju(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),G.configDotenv(r))}function Vu(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=Iu.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 Bu(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:Hu,_configVault:Gu,_parseVault:Uu,config:Wu,decrypt:Vu,parse:Du,populate:Bu};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 Gi=w((ib,qi)=>{var Pe={};process.env.DOTENV_CONFIG_ENCODING!=null&&(Pe.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(Pe.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(Pe.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(Pe.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(Pe.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(Pe.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);qi.exports=Pe});var Wi=w((sb,Hi)=>{var Yu=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Hi.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(Yu);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var Ke=w(Ar=>{var St=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Tr=class extends St{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Ar.CommanderError=St;Ar.InvalidArgumentError=Tr});var vt=w(Mr=>{var{InvalidArgumentError:Ju}=Ke(),Lr=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 Ju(`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 zu(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Mr.Argument=Lr;Mr.humanReadableArgName=zu});var Fr=w(Nr=>{var{humanReadableArgName:Xu}=vt(),Ir=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=>Xu(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 Vi(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 Hi(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}Mr.Help=Lr;Mr.stripColor=Hi});var Ur=w(Fr=>{var{InvalidArgumentError:Wu}=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=Vu(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 Wu(`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?Wi(this.name().replace(/^no-/,"")):Wi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Dr=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 Wi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Vu(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}
8
+ `)}};function Vi(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}Nr.Help=Ir;Nr.stripColor=Vi});var qr=w(jr=>{var{InvalidArgumentError:Ku}=Ke(),Dr=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=Qu(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 Ku(`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?Bi(this.name().replace(/^no-/,"")):Bi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ur=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 Bi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Qu(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}}Fr.Option=Nr;Fr.DualOptions=Dr});var Bi=w(Vi=>{function Bu(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 Yu(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=Bu(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?`
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}}jr.Option=Dr;jr.DualOptions=Ur});var Ji=w(Yi=>{function Zu(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 ef(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=Zu(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]}?)`:""}Vi.suggestSimilar=Yu});var zi=w(Wr=>{var Ju=require("node:events").EventEmitter,jr=require("node:child_process"),Re=require("node:path"),St=require("node:fs"),A=require("node:process"),{Argument:Xu,humanReadableArgName:zu}=bt(),{CommanderError:qr}=Ke(),{Help:Ku,stripColor:Qu}=Ir(),{Option:Yi,DualOptions:Zu}=Ur(),{suggestSimilar:Ji}=Bi(),Gr=class r extends Ju{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>A.stdout.write(t),writeErr:t=>A.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>A.stdout.isTTY?A.stdout.columns:void 0,getErrHelpWidth:()=>A.stderr.isTTY?A.stderr.columns:void 0,getOutHasColors:()=>Hr()??(A.stdout.isTTY&&A.stdout.hasColors?.()),getErrHasColors:()=>Hr()??(A.stderr.isTTY&&A.stderr.hasColors?.()),stripColor:t=>Qu(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 Ku,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 Xu(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)),A.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,s=n.slice(0,i);return this._storeOptionsAsProperties?s[i]=this:s[i]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new Yi(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 Yi)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){A.versions?.electron&&(t.from="electron");let i=A.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=A.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":A.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
- - 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
16
+ (Did you mean ${n[0]}?)`:""}Yi.suggestSimilar=ef});var Qi=w(Br=>{var tf=require("node:events").EventEmitter,Gr=require("node:child_process"),be=require("node:path"),xt=require("node:fs"),L=require("node:process"),{Argument:rf,humanReadableArgName:nf}=vt(),{CommanderError:Hr}=Ke(),{Help:sf,stripColor:of}=Fr(),{Option:zi,DualOptions:af}=qr(),{suggestSimilar:Xi}=Ji(),Wr=class r extends tf{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:()=>Vr()??(L.stdout.isTTY&&L.stdout.hasColors?.()),getErrHasColors:()=>Vr()??(L.stderr.isTTY&&L.stderr.hasColors?.()),stripColor:t=>of(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 sf,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 rf(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 Hr(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 zi(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 zi)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
+ - 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(xt.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=Re.resolve(u,f);if(St.existsSync(d))return d;if(i.includes(Re.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=Re.resolve(Re.dirname(u),a)}if(a){let u=s(a,o);if(!u&&!e._executableFile&&this._scriptPath){let f=Re.basename(this._scriptPath,Re.extname(this._scriptPath));f!==this._name&&(u=s(a,`${f}-${e._name}`))}o=u||o}n=i.includes(Re.extname(o));let l;A.platform!=="win32"?n?(t.unshift(o),t=Xi(A.execArgv).concat(t),l=jr.spawn(A.argv[0],t,{stdio:"inherit"})):l=jr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=Xi(A.execArgv).concat(t),l=jr.spawn(A.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{A.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new qr(u,"commander.executeSubCommandAsync","(close)")):A.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)A.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}
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(xt.existsSync(d))return d;if(i.includes(be.extname(f)))return;let p=i.find(y=>xt.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=xt.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=Ki(L.execArgv).concat(t),l=Gr.spawn(L.argv[0],t,{stdio:"inherit"})):l=Gr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=Ki(L.execArgv).concat(t),l=Gr.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 Hr(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 Hr(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 A.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,A.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Zu(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=Ji(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=Ji(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=>zu(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=Re.basename(e,Re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,s;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(A.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
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 af(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=Xi(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=Xi(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=>nf(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(A.env.NO_COLOR||A.env.FORCE_COLOR==="0"||A.env.FORCE_COLOR==="false")return!1;if(A.env.FORCE_COLOR||A.env.CLICOLOR_FORCE!==void 0)return!0}Wr.Command=Gr;Wr.useColor=Hr});var vt=w(ne=>{var{Argument:Ki}=bt(),{Command:Vr}=zi(),{CommanderError:ef,InvalidArgumentError:Qi}=Ke(),{Help:tf}=Ir(),{Option:Zi}=Ur();ne.program=new Vr;ne.createCommand=r=>new Vr(r);ne.createOption=(r,e)=>new Zi(r,e);ne.createArgument=(r,e)=>new Ki(r,e);ne.Command=Vr;ne.Option=Zi;ne.Argument=Ki;ne.Help=tf;ne.CommanderError=ef;ne.InvalidArgumentError=Qi;ne.InvalidOptionArgumentError=Qi});var De=w((Br,ts)=>{var xt=require("buffer"),de=xt.Buffer;function es(r,e){for(var t in r)e[t]=r[t]}de.from&&de.alloc&&de.allocUnsafe&&de.allocUnsafeSlow?ts.exports=xt:(es(xt,Br),Br.Buffer=Pe);function Pe(r,e,t){return de(r,e,t)}Pe.prototype=Object.create(de.prototype);es(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((eR,rs)=>{var kt=De().Buffer,rf=require("stream"),nf=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+")")}nf.inherits(_t,rf);_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};rs.exports=_t});var is=w((tR,ns)=>{"use strict";function Jr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var sf={ES256:Jr(256),ES384:Jr(384),ES512:Jr(521)};function of(r){var e=sf[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}ns.exports=of});var fs=w((rR,us)=>{"use strict";var Ct=De().Buffer,os=is(),Ot=128,as=0,af=32,lf=16,cf=2,ls=lf|af|as<<6,Pt=cf|as<<6;function uf(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function cs(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 ff(r,e){r=cs(r);var t=os(e),n=t+1,i=r.length,s=0;if(r[s++]!==ls)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=uf(p),p}function ss(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 mf(r,e){r=cs(r);var t=os(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=ss(r,0,t),s=ss(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++]=ls,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}us.exports={derToJose:ff,joseToDer:mf}});var ds=w((nR,ms)=>{"use strict";var Qe=require("buffer").Buffer,Xr=require("buffer").SlowBuffer;ms.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=Xr.prototype.equal=function(e){return Tt(this,e)}};var df=Qe.prototype.equal,pf=Xr.prototype.equal;Tt.restore=function(){Qe.prototype.equal=df,Xr.prototype.equal=pf}});var Zr=w((iR,bs)=>{var Ue=De().Buffer,ie=require("crypto"),hs=fs(),ps=require("util"),hf=`"%s" is not a valid algorithm.
29
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ki(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 Vr(){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}Br.Command=Wr;Br.useColor=Vr});var kt=w(ne=>{var{Argument:Zi}=vt(),{Command:Yr}=Qi(),{CommanderError:lf,InvalidArgumentError:es}=Ke(),{Help:cf}=Fr(),{Option:ts}=qr();ne.program=new Yr;ne.createCommand=r=>new Yr(r);ne.createOption=(r,e)=>new ts(r,e);ne.createArgument=(r,e)=>new Zi(r,e);ne.Command=Yr;ne.Option=ts;ne.Argument=Zi;ne.Help=cf;ne.CommanderError=lf;ne.InvalidArgumentError=es;ne.InvalidOptionArgumentError=es});var De=w((Jr,ns)=>{var _t=require("buffer"),pe=_t.Buffer;function rs(r,e){for(var t in r)e[t]=r[t]}pe.from&&pe.alloc&&pe.allocUnsafe&&pe.allocUnsafeSlow?ns.exports=_t:(rs(_t,Jr),Jr.Buffer=Te);function Te(r,e,t){return pe(r,e,t)}Te.prototype=Object.create(pe.prototype);rs(pe,Te);Te.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return pe(r,e,t)};Te.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=pe(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};Te.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return pe(r)};Te.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return _t.SlowBuffer(r)}});var zr=w((db,is)=>{var Ct=De().Buffer,uf=require("stream"),ff=require("util");function Ot(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Ct.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Ct.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+")")}ff.inherits(Ot,uf);Ot.prototype.write=function(e){this.buffer=Ct.concat([this.buffer,Ct.from(e)]),this.emit("data",e)};Ot.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};is.exports=Ot});var os=w((pb,ss)=>{"use strict";function Xr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var mf={ES256:Xr(256),ES384:Xr(384),ES512:Xr(521)};function df(r){var e=mf[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}ss.exports=df});var ds=w((hb,ms)=>{"use strict";var Pt=De().Buffer,ls=os(),Tt=128,cs=0,pf=32,hf=16,gf=2,us=hf|pf|cs<<6,At=gf|cs<<6;function yf(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function fs(r){if(Pt.isBuffer(r))return r;if(typeof r=="string")return Pt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function wf(r,e){r=fs(r);var t=ls(e),n=t+1,i=r.length,s=0;if(r[s++]!==us)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(Tt|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==At)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++]!==At)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=Pt.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=yf(p),p}function as(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Tt;return i&&--n,n}function Ef(r,e){r=fs(r);var t=ls(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=as(r,0,t),s=as(r,t,r.length),o=t-i,a=t-s,l=2+o+1+1+a,c=l<Tt,u=Pt.allocUnsafe((c?2:3)+l),f=0;return u[f++]=us,c?u[f++]=l:(u[f++]=Tt|1,u[f++]=l&255),u[f++]=At,u[f++]=o,i<0?(u[f++]=0,f+=r.copy(u,f,0,t)):f+=r.copy(u,f,i,t),u[f++]=At,u[f++]=a,s<0?(u[f++]=0,r.copy(u,f,t)):r.copy(u,f,t+s),u}ms.exports={derToJose:wf,joseToDer:Ef}});var hs=w((gb,ps)=>{"use strict";var Qe=require("buffer").Buffer,Kr=require("buffer").SlowBuffer;ps.exports=Lt;function Lt(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}Lt.install=function(){Qe.prototype.equal=Kr.prototype.equal=function(e){return Lt(this,e)}};var bf=Qe.prototype.equal,Rf=Kr.prototype.equal;Lt.restore=function(){Qe.prototype.equal=bf,Kr.prototype.equal=Rf}});var tn=w((yb,vs)=>{var je=De().Buffer,ie=require("crypto"),ys=ds(),gs=require("util"),$f=`"%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(`
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
- ${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 ${C}boxel profile add${m} to create a profile.`))}},Un=null;function _(){return Un||(Un=new jn),Un}var Gn=T(require("readline")),Fl=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 Fl.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===`
31
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ze="secret must be a string or buffer",Ue="key must be a string or a buffer",Sf="key must be a string, a buffer or an object",Zr=typeof ie.createPublicKey=="function";Zr&&(Ue+=" or a KeyObject",Ze+="or a KeyObject");function ws(r){if(!je.isBuffer(r)&&typeof r!="string"&&(!Zr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ce(Ue)}function Es(r){if(!je.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ce(Sf)}function vf(r){if(!je.isBuffer(r)){if(typeof r=="string")return r;if(!Zr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ce(Ze)}}function en(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function bs(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=gs.format.bind(gs,r).apply(null,e);return new TypeError(t)}function xf(r){return je.isBuffer(r)||typeof r=="string"}function et(r){return xf(r)||(r=JSON.stringify(r)),r}function Rs(r){return function(t,n){vf(n),t=et(t);var i=ie.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return en(s)}}var Qr,kf="timingSafeEqual"in ie?function(e,t){return e.byteLength!==t.byteLength?!1:ie.timingSafeEqual(e,t)}:function(e,t){return Qr||(Qr=hs()),Qr(e,t)};function _f(r){return function(t,n,i){var s=Rs(r)(t,i);return kf(je.from(n),je.from(s))}}function $s(r){return function(t,n){Es(n),t=et(t);var i=ie.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return en(s)}}function Ss(r){return function(t,n,i){ws(i),t=et(t),n=bs(n);var s=ie.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function Cf(r){return function(t,n){Es(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 en(s)}}function Of(r){return function(t,n,i){ws(i),t=et(t),n=bs(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 Pf(r){var e=$s(r);return function(){var n=e.apply(null,arguments);return n=ys.derToJose(n,"ES"+r),n}}function Tf(r){var e=Ss(r);return function(n,i,s){i=ys.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function Af(){return function(){return""}}function Lf(){return function(e,t){return t===""}}vs.exports=function(e){var t={hs:Rs,rs:$s,ps:Cf,es:Pf,none:Af},n={hs:_f,rs:Ss,ps:Of,es:Tf,none:Lf},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ce($f,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var rn=w((wb,xs)=>{var Mf=require("buffer").Buffer;xs.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Mf.isBuffer(e)?e.toString():JSON.stringify(e)}});var Ts=w((Eb,Ps)=>{var If=De().Buffer,ks=zr(),Nf=tn(),Ff=require("stream"),_s=rn(),nn=require("util");function Cs(r,e){return If.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Df(r,e,t){t=t||"utf8";var n=Cs(_s(r),"binary"),i=Cs(_s(e),t);return nn.format("%s.%s",n,i)}function Os(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=Nf(e.alg),o=Df(e,t,i),a=s.sign(o,n);return nn.format("%s.%s",o,a)}function Mt(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 ks(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new ks(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))}nn.inherits(Mt,Ff);Mt.prototype.sign=function(){try{var e=Os({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")}};Mt.sign=Os;Ps.exports=Mt});var qs=w((bb,js)=>{var Ls=De().Buffer,As=zr(),Uf=tn(),jf=require("stream"),Ms=rn(),qf=require("util"),Gf=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Hf(r){return Object.prototype.toString.call(r)==="[object Object]"}function Wf(r){if(Hf(r))return r;try{return JSON.parse(r)}catch{return}}function Is(r){var e=r.split(".",1)[0];return Wf(Ls.from(e,"base64").toString("binary"))}function Vf(r){return r.split(".",2).join(".")}function Ns(r){return r.split(".")[2]}function Bf(r,e){e=e||"utf8";var t=r.split(".")[1];return Ls.from(t,"base64").toString(e)}function Fs(r){return Gf.test(r)&&!!Is(r)}function Ds(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Ms(r);var i=Ns(r),s=Vf(r),o=Uf(e);return o.verify(s,i,t)}function Us(r,e){if(e=e||{},r=Ms(r),!Fs(r))return null;var t=Is(r);if(!t)return null;var n=Bf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Ns(r)}}function qe(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 As(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new As(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))}qf.inherits(qe,jf);qe.prototype.verify=function(){try{var e=Ds(this.signature.buffer,this.algorithm,this.key.buffer),t=Us(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")}};qe.decode=Us;qe.isValid=Fs;qe.verify=Ds;js.exports=qe});var Nt=w(Se=>{var Gs=Ts(),It=qs(),Yf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Se.ALGORITHMS=Yf;Se.sign=Gs.sign;Se.verify=It.verify;Se.decode=It.decode;Se.isValid=It.isValid;Se.createSign=function(e){return new Gs(e)};Se.createVerify=function(e){return new It(e)}});var sn=w(($b,Hs)=>{var Jf=Nt();Hs.exports=function(r,e){e=e||{};var t=Jf.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((Sb,Ws)=>{var Ft=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ft.prototype=Object.create(Error.prototype);Ft.prototype.constructor=Ft;Ws.exports=Ft});var on=w((vb,Bs)=>{var Vs=tt(),Dt=function(r,e){Vs.call(this,r),this.name="NotBeforeError",this.date=e};Dt.prototype=Object.create(Vs.prototype);Dt.prototype.constructor=Dt;Bs.exports=Dt});var an=w((xb,Js)=>{var Ys=tt(),Ut=function(r,e){Ys.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};Ut.prototype=Object.create(Ys.prototype);Ut.prototype.constructor=Ut;Js.exports=Ut});var Xs=w((kb,zs)=>{var Ge=1e3,He=Ge*60,We=He*60,Ae=We*24,zf=Ae*7,Xf=Ae*365.25;zs.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Kf(r);if(t==="number"&&isFinite(r))return e.long?Zf(r):Qf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Kf(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*Xf;case"weeks":case"week":case"w":return t*zf;case"days":case"day":case"d":return t*Ae;case"hours":case"hour":case"hrs":case"hr":case"h":return t*We;case"minutes":case"minute":case"mins":case"min":case"m":return t*He;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ge;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Qf(r){var e=Math.abs(r);return e>=Ae?Math.round(r/Ae)+"d":e>=We?Math.round(r/We)+"h":e>=He?Math.round(r/He)+"m":e>=Ge?Math.round(r/Ge)+"s":r+"ms"}function Zf(r){var e=Math.abs(r);return e>=Ae?jt(r,e,Ae,"day"):e>=We?jt(r,e,We,"hour"):e>=He?jt(r,e,He,"minute"):e>=Ge?jt(r,e,Ge,"second"):r+" ms"}function jt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var ln=w((_b,Ks)=>{var em=Xs();Ks.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=em(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var Ve=w((Cb,Qs)=>{"use strict";var tm="2.0.0",rm=Number.MAX_SAFE_INTEGER||9007199254740991,nm=16,im=250,sm=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Qs.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:nm,MAX_SAFE_BUILD_LENGTH:im,MAX_SAFE_INTEGER:rm,RELEASE_TYPES:sm,SEMVER_SPEC_VERSION:tm,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var rt=w((Ob,Zs)=>{"use strict";var om=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Zs.exports=om});var Be=w((he,eo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:cn,MAX_SAFE_BUILD_LENGTH:am,MAX_LENGTH:lm}=Ve(),cm=rt();he=eo.exports={};var um=he.re=[],fm=he.safeRe=[],E=he.src=[],mm=he.safeSrc=[],b=he.t={},dm=0,un="[a-zA-Z0-9-]",pm=[["\\s",1],["\\d",lm],[un,am]],hm=r=>{for(let[e,t]of pm)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},k=(r,e,t)=>{let n=hm(e),i=dm++;cm(r,i,e),b[r]=i,E[i]=e,mm[i]=n,um[i]=new RegExp(e,t?"g":void 0),fm[i]=new RegExp(n,t?"g":void 0)};k("NUMERICIDENTIFIER","0|[1-9]\\d*");k("NUMERICIDENTIFIERLOOSE","\\d+");k("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${un}*`);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",`${un}+`);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,${cn}})(?:\\.(\\d{1,${cn}}))?(?:\\.(\\d{1,${cn}}))?`);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);he.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);he.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);he.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 qt=w((Pb,to)=>{"use strict";var gm=Object.freeze({loose:!0}),ym=Object.freeze({}),wm=r=>r?typeof r!="object"?gm:r:ym;to.exports=wm});var fn=w((Tb,io)=>{"use strict";var ro=/^[0-9]+$/,no=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=ro.test(r),n=ro.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Em=(r,e)=>no(e,r);io.exports={compareIdentifiers:no,rcompareIdentifiers:Em}});var Y=w((Ab,oo)=>{"use strict";var Gt=rt(),{MAX_LENGTH:so,MAX_SAFE_INTEGER:Ht}=Ve(),{safeRe:Wt,t:Vt}=Be(),bm=qt(),{compareIdentifiers:mn}=fn(),dn=class r{constructor(e,t){if(t=bm(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>so)throw new TypeError(`version is longer than ${so} characters`);Gt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Wt[Vt.LOOSE]:Wt[Vt.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>Ht||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Ht||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Ht||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<Ht)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(Gt("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(Gt("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 mn(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(Gt("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 mn(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?Wt[Vt.PRERELEASELOOSE]:Wt[Vt.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]),mn(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}};oo.exports=dn});var ve=w((Lb,lo)=>{"use strict";var ao=Y(),Rm=(r,e,t=!1)=>{if(r instanceof ao)return r;try{return new ao(r,e)}catch(n){if(!t)return null;throw n}};lo.exports=Rm});var uo=w((Mb,co)=>{"use strict";var $m=ve(),Sm=(r,e)=>{let t=$m(r,e);return t?t.version:null};co.exports=Sm});var mo=w((Ib,fo)=>{"use strict";var vm=ve(),xm=(r,e)=>{let t=vm(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};fo.exports=xm});var go=w((Nb,ho)=>{"use strict";var po=Y(),km=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new po(r instanceof po?r.version:r,t).inc(e,n,i).version}catch{return null}};ho.exports=km});var Eo=w((Fb,wo)=>{"use strict";var yo=ve(),_m=(r,e)=>{let t=yo(r,null,!0),n=yo(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"};wo.exports=_m});var Ro=w((Db,bo)=>{"use strict";var Cm=Y(),Om=(r,e)=>new Cm(r,e).major;bo.exports=Om});var So=w((Ub,$o)=>{"use strict";var Pm=Y(),Tm=(r,e)=>new Pm(r,e).minor;$o.exports=Tm});var xo=w((jb,vo)=>{"use strict";var Am=Y(),Lm=(r,e)=>new Am(r,e).patch;vo.exports=Lm});var _o=w((qb,ko)=>{"use strict";var Mm=ve(),Im=(r,e)=>{let t=Mm(r,e);return t&&t.prerelease.length?t.prerelease:null};ko.exports=Im});var se=w((Gb,Oo)=>{"use strict";var Co=Y(),Nm=(r,e,t)=>new Co(r,t).compare(new Co(e,t));Oo.exports=Nm});var To=w((Hb,Po)=>{"use strict";var Fm=se(),Dm=(r,e,t)=>Fm(e,r,t);Po.exports=Dm});var Lo=w((Wb,Ao)=>{"use strict";var Um=se(),jm=(r,e)=>Um(r,e,!0);Ao.exports=jm});var Bt=w((Vb,Io)=>{"use strict";var Mo=Y(),qm=(r,e,t)=>{let n=new Mo(r,t),i=new Mo(e,t);return n.compare(i)||n.compareBuild(i)};Io.exports=qm});var Fo=w((Bb,No)=>{"use strict";var Gm=Bt(),Hm=(r,e)=>r.sort((t,n)=>Gm(t,n,e));No.exports=Hm});var Uo=w((Yb,Do)=>{"use strict";var Wm=Bt(),Vm=(r,e)=>r.sort((t,n)=>Wm(n,t,e));Do.exports=Vm});var nt=w((Jb,jo)=>{"use strict";var Bm=se(),Ym=(r,e,t)=>Bm(r,e,t)>0;jo.exports=Ym});var Yt=w((zb,qo)=>{"use strict";var Jm=se(),zm=(r,e,t)=>Jm(r,e,t)<0;qo.exports=zm});var pn=w((Xb,Go)=>{"use strict";var Xm=se(),Km=(r,e,t)=>Xm(r,e,t)===0;Go.exports=Km});var hn=w((Kb,Ho)=>{"use strict";var Qm=se(),Zm=(r,e,t)=>Qm(r,e,t)!==0;Ho.exports=Zm});var Jt=w((Qb,Wo)=>{"use strict";var ed=se(),td=(r,e,t)=>ed(r,e,t)>=0;Wo.exports=td});var zt=w((Zb,Vo)=>{"use strict";var rd=se(),nd=(r,e,t)=>rd(r,e,t)<=0;Vo.exports=nd});var gn=w((eR,Bo)=>{"use strict";var id=pn(),sd=hn(),od=nt(),ad=Jt(),ld=Yt(),cd=zt(),ud=(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 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);case"<=":return cd(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Bo.exports=ud});var Jo=w((tR,Yo)=>{"use strict";var fd=Y(),md=ve(),{safeRe:Xt,t:Kt}=Be(),dd=(r,e)=>{if(r instanceof fd)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?Xt[Kt.COERCEFULL]:Xt[Kt.COERCE]);else{let l=e.includePrerelease?Xt[Kt.COERCERTLFULL]:Xt[Kt.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 md(`${n}.${i}.${s}${o}${a}`,e)};Yo.exports=dd});var Xo=w((rR,zo)=>{"use strict";var pd=ve(),hd=Ve(),gd=Y(),yd=(r,e,t)=>{if(!hd.RELEASE_TYPES.includes(e))return null;let n=wd(r,t);return n&&Ed(n,e)},wd=(r,e)=>{let t=r instanceof gd?r.version:r;return pd(t,e)},Ed=(r,e)=>{if(bd(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()},bd=r=>r.startsWith("pre");zo.exports=yd});var Qo=w((nR,Ko)=>{"use strict";var yn=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}};Ko.exports=yn});var oe=w((iR,ra)=>{"use strict";var Rd=/\s+/g,wn=class r{constructor(e,t){if(t=Sd(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof En)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(Rd," "),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=>!ea(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&&Pd(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&&Cd)|(this.options.loose&&Od))+":"+e,i=Zo.get(n);if(i)return i;let s=this.options.loose,o=s?K[z.HYPHENRANGELOOSE]:K[z.HYPHENRANGE];e=e.replace(o,jd(this.options.includePrerelease)),F("hyphen replace",e),e=e.replace(K[z.COMPARATORTRIM],xd),F("comparator trim",e),e=e.replace(K[z.TILDETRIM],kd),F("tilde trim",e),e=e.replace(K[z.CARETTRIM],_d),F("caret trim",e);let a=e.split(" ").map(f=>Td(f,this.options)).join(" ").split(/\s+/).map(f=>Ud(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 En(f,this.options));for(let f of c){if(ea(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let u=[...l.values()];return Zo.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>ta(n,t)&&e.set.some(i=>ta(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 vd(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(qd(this.set[t],e,this.options))return!0;return!1}};ra.exports=wn;var $d=Qo(),Zo=new $d,Sd=qt(),En=it(),F=rt(),vd=Y(),{safeRe:K,t:z,comparatorTrimReplace:xd,tildeTrimReplace:kd,caretTrimReplace:_d}=Be(),{FLAG_INCLUDE_PRERELEASE:Cd,FLAG_LOOSE:Od}=Ve(),ea=r=>r.value==="<0.0.0-0",Pd=r=>r.value==="",ta=(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},Td=(r,e)=>(r=r.replace(K[z.BUILD],""),F("comp",r,e),r=Md(r,e),F("caret",r),r=Ad(r,e),F("tildes",r),r=Nd(r,e),F("xrange",r),r=Dd(r,e),F("stars",r),r),Q=r=>!r||r.toLowerCase()==="x"||r==="*",Ad=(r,e)=>r.trim().split(/\s+/).map(t=>Ld(t,e)).join(" "),Ld=(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})},Md=(r,e)=>r.trim().split(/\s+/).map(t=>Id(t,e)).join(" "),Id=(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})},Nd=(r,e)=>(F("replaceXRanges",r,e),r.split(/\s+/).map(t=>Fd(t,e)).join(" ")),Fd=(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})},Dd=(r,e)=>(F("replaceStars",r,e),r.trim().replace(K[z.STAR],"")),Ud=(r,e)=>(F("replaceGTE0",r,e),r.trim().replace(K[e.includePrerelease?z.GTE0PRE:z.GTE0],"")),jd=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()),qd=(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!==En.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((sR,la)=>{"use strict";var st=Symbol("SemVer ANY"),$n=class r{static get ANY(){return st}constructor(e,t){if(t=na(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Rn("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,Rn("comp",this)}parse(e){let t=this.options.loose?ia[sa.COMPARATORLOOSE]:ia[sa.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 oa(n[2],this.options.loose):this.semver=st}toString(){return this.value}test(e){if(Rn("Comparator.test",e,this.options.loose),this.semver===st||e===st)return!0;if(typeof e=="string")try{e=new oa(e,this.options)}catch{return!1}return bn(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 aa(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new aa(this.value,t).test(e.semver):(t=na(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("=")||bn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||bn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};la.exports=$n;var na=qt(),{safeRe:ia,t:sa}=Be(),bn=gn(),Rn=rt(),oa=Y(),aa=oe()});var ot=w((oR,ca)=>{"use strict";var Gd=oe(),Hd=(r,e,t)=>{try{e=new Gd(e,t)}catch{return!1}return e.test(r)};ca.exports=Hd});var fa=w((aR,ua)=>{"use strict";var Wd=oe(),Vd=(r,e)=>new Wd(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));ua.exports=Vd});var da=w((lR,ma)=>{"use strict";var Bd=Y(),Yd=oe(),Jd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new Yd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new Bd(n,t))}),n};ma.exports=Jd});var ha=w((cR,pa)=>{"use strict";var zd=Y(),Xd=oe(),Kd=(r,e,t)=>{let n=null,i=null,s=null;try{s=new Xd(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new zd(n,t))}),n};pa.exports=Kd});var wa=w((uR,ya)=>{"use strict";var Sn=Y(),Qd=oe(),ga=nt(),Zd=(r,e)=>{r=new Qd(r,e);let t=new Sn("0.0.0");if(r.test(t)||(t=new Sn("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 Sn(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||ga(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||ga(t,s))&&(t=s)}return t&&r.test(t)?t:null};ya.exports=Zd});var ba=w((fR,Ea)=>{"use strict";var ep=oe(),tp=(r,e)=>{try{return new ep(r,e).range||"*"}catch{return null}};Ea.exports=tp});var Qt=w((mR,va)=>{"use strict";var rp=Y(),Sa=it(),{ANY:np}=Sa,ip=oe(),sp=ot(),Ra=nt(),$a=Yt(),op=zt(),ap=Jt(),lp=(r,e,t,n)=>{r=new rp(r,n),e=new ip(e,n);let i,s,o,a,l;switch(t){case">":i=Ra,s=op,o=$a,a=">",l=">=";break;case"<":i=$a,s=ap,o=Ra,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(sp(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===np&&(p=new Sa(">=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};va.exports=lp});var ka=w((dR,xa)=>{"use strict";var cp=Qt(),up=(r,e,t)=>cp(r,e,">",t);xa.exports=up});var Ca=w((pR,_a)=>{"use strict";var fp=Qt(),mp=(r,e,t)=>fp(r,e,"<",t);_a.exports=mp});var Ta=w((hR,Pa)=>{"use strict";var Oa=oe(),dp=(r,e,t)=>(r=new Oa(r,t),e=new Oa(e,t),r.intersects(e,t));Pa.exports=dp});var La=w((gR,Aa)=>{"use strict";var pp=ot(),hp=se();Aa.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,f)=>hp(u,f,t));for(let u of o)pp(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 Ua=w((yR,Da)=>{"use strict";var Ma=oe(),xn=it(),{ANY:vn}=xn,at=ot(),kn=se(),gp=(r,e,t={})=>{if(r===e)return!0;r=new Ma(r,t),e=new Ma(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=wp(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},yp=[new xn(">=0.0.0-0")],Ia=[new xn(">=0.0.0")],wp=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===vn){if(e.length===1&&e[0].semver===vn)return!0;t.includePrerelease?r=yp:r=Ia}if(e.length===1&&e[0].semver===vn){if(t.includePrerelease)return!0;e=Ia}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Na(i,p,t):p.operator==="<"||p.operator==="<="?s=Fa(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=kn(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=Na(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=Fa(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)},Na=(r,e,t)=>{if(!r)return e;let n=kn(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},Fa=(r,e,t)=>{if(!r)return e;let n=kn(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};Da.exports=gp});var Zt=w((wR,Ga)=>{"use strict";var _n=Be(),ja=Ve(),Ep=Y(),qa=fn(),bp=ve(),Rp=uo(),$p=mo(),Sp=go(),vp=Eo(),xp=Ro(),kp=So(),_p=xo(),Cp=_o(),Op=se(),Pp=To(),Tp=Lo(),Ap=Bt(),Lp=Fo(),Mp=Uo(),Ip=nt(),Np=Yt(),Fp=pn(),Dp=hn(),Up=Jt(),jp=zt(),qp=gn(),Gp=Jo(),Hp=Xo(),Wp=it(),Vp=oe(),Bp=ot(),Yp=fa(),Jp=da(),zp=ha(),Xp=wa(),Kp=ba(),Qp=Qt(),Zp=ka(),eh=Ca(),th=Ta(),rh=La(),nh=Ua();Ga.exports={parse:bp,valid:Rp,clean:$p,inc:Sp,diff:vp,major:xp,minor:kp,patch:_p,prerelease:Cp,compare:Op,rcompare:Pp,compareLoose:Tp,compareBuild:Ap,sort:Lp,rsort:Mp,gt:Ip,lt:Np,eq:Fp,neq:Dp,gte:Up,lte:jp,cmp:qp,coerce:Gp,truncate:Hp,Comparator:Wp,Range:Vp,satisfies:Bp,toComparators:Yp,maxSatisfying:Jp,minSatisfying:zp,minVersion:Xp,validRange:Kp,outside:Qp,gtr:Zp,ltr:eh,intersects:th,simplifyRange:rh,subset:nh,SemVer:Ep,re:_n.re,src:_n.src,tokens:_n.t,SEMVER_SPEC_VERSION:ja.SEMVER_SPEC_VERSION,RELEASE_TYPES:ja.RELEASE_TYPES,compareIdentifiers:qa.compareIdentifiers,rcompareIdentifiers:qa.rcompareIdentifiers}});var Wa=w((ER,Ha)=>{var ih=Zt();Ha.exports=ih.satisfies(process.version,">=15.7.0")});var Ba=w((bR,Va)=>{var sh=Zt();Va.exports=sh.satisfies(process.version,">=16.9.0")});var Cn=w((RR,Ya)=>{var oh=Wa(),ah=Ba(),lh={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},ch={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};Ya.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=lh[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(oh)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=ch[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(ah){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 On=w(($R,Ja)=>{var uh=Zt();Ja.exports=uh.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ka=w((SR,Xa)=>{var N=tt(),fh=on(),za=an(),mh=sn(),dh=ln(),ph=Cn(),hh=On(),gh=Nt(),{KeyObject:yh,createSecretKey:wh,createPublicKey:Eh}=require("crypto"),Pn=["RS256","RS384","RS512"],bh=["ES256","ES384","ES512"],Tn=["RS256","RS384","RS512"],Rh=["HS256","HS384","HS512"];hh&&(Pn.splice(Pn.length,0,"PS256","PS384","PS512"),Tn.splice(Tn.length,0,"PS256","PS384","PS512"));Xa.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=mh(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 yh))try{f=Eh(f)}catch{try{f=wh(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=Rh:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=Tn:f.asymmetricKeyType==="ec"?t.algorithms=bh:t.algorithms=Pn),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{ph(l.alg,f)}catch(R){return i(R)}let p;try{p=gh.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 fh("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 za("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=dh(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 za("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 nl=w((vR,rl)=>{var Qa=1/0,el=9007199254740991,$h=17976931348623157e292,Za=NaN,Sh="[object Arguments]",vh="[object Function]",xh="[object GeneratorFunction]",kh="[object String]",_h="[object Symbol]",Ch=/^\s+|\s+$/g,Oh=/^[-+]0x[0-9a-f]+$/i,Ph=/^0b[01]+$/i,Th=/^0o[0-7]+$/i,Ah=/^(?:0|[1-9]\d*)$/,Lh=parseInt;function Mh(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 Ih(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 Nh(r,e,t){if(e!==e)return Ih(r,Fh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function Fh(r){return r!==r}function Dh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function Uh(r,e){return Mh(e,function(t){return r[t]})}function jh(r,e){return function(t){return r(e(t))}}var er=Object.prototype,Ln=er.hasOwnProperty,tr=er.toString,qh=er.propertyIsEnumerable,Gh=jh(Object.keys,Object),Hh=Math.max;function Wh(r,e){var t=tl(r)||zh(r)?Dh(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||Ln.call(r,s))&&!(i&&(s=="length"||Bh(s,n)))&&t.push(s);return t}function Vh(r){if(!Yh(r))return Gh(r);var e=[];for(var t in Object(r))Ln.call(r,t)&&t!="constructor"&&e.push(t);return e}function Bh(r,e){return e=e??el,!!e&&(typeof r=="number"||Ah.test(r))&&r>-1&&r%1==0&&r<e}function Yh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||er;return r===t}function Jh(r,e,t,n){r=Mn(r)?r:sg(r),t=t&&!n?rg(t):0;var i=r.length;return t<0&&(t=Hh(i+t,0)),Zh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Nh(r,e,t)>-1}function zh(r){return Xh(r)&&Ln.call(r,"callee")&&(!qh.call(r,"callee")||tr.call(r)==Sh)}var tl=Array.isArray;function Mn(r){return r!=null&&Qh(r.length)&&!Kh(r)}function Xh(r){return In(r)&&Mn(r)}function Kh(r){var e=An(r)?tr.call(r):"";return e==vh||e==xh}function Qh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=el}function An(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function In(r){return!!r&&typeof r=="object"}function Zh(r){return typeof r=="string"||!tl(r)&&In(r)&&tr.call(r)==kh}function eg(r){return typeof r=="symbol"||In(r)&&tr.call(r)==_h}function tg(r){if(!r)return r===0?r:0;if(r=ng(r),r===Qa||r===-Qa){var e=r<0?-1:1;return e*$h}return r===r?r:0}function rg(r){var e=tg(r),t=e%1;return e===e?t?e-t:e:0}function ng(r){if(typeof r=="number")return r;if(eg(r))return Za;if(An(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=An(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ch,"");var t=Ph.test(r);return t||Th.test(r)?Lh(r.slice(2),t?2:8):Oh.test(r)?Za:+r}function ig(r){return Mn(r)?Wh(r):Vh(r)}function sg(r){return r?Uh(r,ig(r)):[]}rl.exports=Jh});var sl=w((xR,il)=>{var og="[object Boolean]",ag=Object.prototype,lg=ag.toString;function cg(r){return r===!0||r===!1||ug(r)&&lg.call(r)==og}function ug(r){return!!r&&typeof r=="object"}il.exports=cg});var ul=w((kR,cl)=>{var ol=1/0,fg=17976931348623157e292,al=NaN,mg="[object Symbol]",dg=/^\s+|\s+$/g,pg=/^[-+]0x[0-9a-f]+$/i,hg=/^0b[01]+$/i,gg=/^0o[0-7]+$/i,yg=parseInt,wg=Object.prototype,Eg=wg.toString;function bg(r){return typeof r=="number"&&r==vg(r)}function ll(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Rg(r){return!!r&&typeof r=="object"}function $g(r){return typeof r=="symbol"||Rg(r)&&Eg.call(r)==mg}function Sg(r){if(!r)return r===0?r:0;if(r=xg(r),r===ol||r===-ol){var e=r<0?-1:1;return e*fg}return r===r?r:0}function vg(r){var e=Sg(r),t=e%1;return e===e?t?e-t:e:0}function xg(r){if(typeof r=="number")return r;if($g(r))return al;if(ll(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ll(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(dg,"");var t=hg.test(r);return t||gg.test(r)?yg(r.slice(2),t?2:8):pg.test(r)?al:+r}cl.exports=bg});var ml=w((_R,fl)=>{var kg="[object Number]",_g=Object.prototype,Cg=_g.toString;function Og(r){return!!r&&typeof r=="object"}function Pg(r){return typeof r=="number"||Og(r)&&Cg.call(r)==kg}fl.exports=Pg});var gl=w((CR,hl)=>{var Tg="[object Object]";function Ag(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Lg(r,e){return function(t){return r(e(t))}}var Mg=Function.prototype,dl=Object.prototype,pl=Mg.toString,Ig=dl.hasOwnProperty,Ng=pl.call(Object),Fg=dl.toString,Dg=Lg(Object.getPrototypeOf,Object);function Ug(r){return!!r&&typeof r=="object"}function jg(r){if(!Ug(r)||Fg.call(r)!=Tg||Ag(r))return!1;var e=Dg(r);if(e===null)return!0;var t=Ig.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&pl.call(t)==Ng}hl.exports=jg});var wl=w((OR,yl)=>{var qg="[object String]",Gg=Object.prototype,Hg=Gg.toString,Wg=Array.isArray;function Vg(r){return!!r&&typeof r=="object"}function Bg(r){return typeof r=="string"||!Wg(r)&&Vg(r)&&Hg.call(r)==qg}yl.exports=Bg});var Sl=w((PR,$l)=>{var Yg="Expected a function",El=1/0,Jg=17976931348623157e292,bl=NaN,zg="[object Symbol]",Xg=/^\s+|\s+$/g,Kg=/^[-+]0x[0-9a-f]+$/i,Qg=/^0b[01]+$/i,Zg=/^0o[0-7]+$/i,ey=parseInt,ty=Object.prototype,ry=ty.toString;function ny(r,e){var t;if(typeof e!="function")throw new TypeError(Yg);return r=ly(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function iy(r){return ny(2,r)}function Rl(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function sy(r){return!!r&&typeof r=="object"}function oy(r){return typeof r=="symbol"||sy(r)&&ry.call(r)==zg}function ay(r){if(!r)return r===0?r:0;if(r=cy(r),r===El||r===-El){var e=r<0?-1:1;return e*Jg}return r===r?r:0}function ly(r){var e=ay(r),t=e%1;return e===e?t?e-t:e:0}function cy(r){if(typeof r=="number")return r;if(oy(r))return bl;if(Rl(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Rl(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Xg,"");var t=Qg.test(r);return t||Zg.test(r)?ey(r.slice(2),t?2:8):Kg.test(r)?bl:+r}$l.exports=iy});var Al=w((TR,Tl)=>{var vl=ln(),uy=On(),fy=Cn(),xl=Nt(),my=nl(),rr=sl(),kl=ul(),Nn=ml(),Cl=gl(),xe=wl(),dy=Sl(),{KeyObject:py,createSecretKey:hy,createPrivateKey:gy}=require("crypto"),Ol=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];uy&&Ol.splice(3,0,"PS256","PS384","PS512");var yy={expiresIn:{isValid:function(r){return kl(r)||xe(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return kl(r)||xe(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return xe(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:my.bind(null,Ol),message:'"algorithm" must be a valid string enum value'},header:{isValid:Cl,message:'"header" must be an object'},encoding:{isValid:xe,message:'"encoding" must be a string'},issuer:{isValid:xe,message:'"issuer" must be a string'},subject:{isValid:xe,message:'"subject" must be a string'},jwtid:{isValid:xe,message:'"jwtid" must be a string'},noTimestamp:{isValid:rr,message:'"noTimestamp" must be a boolean'},keyid:{isValid:xe,message:'"keyid" must be a string'},mutatePayload:{isValid:rr,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:rr,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:rr,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},wy={iat:{isValid:Nn,message:'"iat" should be a number of seconds'},exp:{isValid:Nn,message:'"exp" should be a number of seconds'},nbf:{isValid:Nn,message:'"nbf" should be a number of seconds'}};function Pl(r,e,t,n){if(!Cl(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 Ey(r){return Pl(yy,!1,r,"options")}function by(r){return Pl(wy,!0,r,"payload")}var _l={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Ry=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];Tl.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 py))try{e=gy(e)}catch{try{e=hy(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{by(r)}catch(c){return o(c)}t.mutatePayload||(r=Object.assign({},r))}else{let c=Ry.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{Ey(t)}catch(c){return o(c)}if(!t.allowInvalidAsymmetricKeyTypes)try{fy(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=vl(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=vl(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(_l).forEach(function(c){let u=_l[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&&dy(n),xl.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=xl.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 Fn=w((AR,Ll)=>{Ll.exports={decode:sn(),verify:Ka(),sign:Al(),JsonWebTokenError:tt(),NotBeforeError:on(),TokenExpiredError:an()}});var bc=w((uS,Ec)=>{function mc(r){return Array.isArray(r)?r:[r]}var ii="",dc=" ",ri="\\",ww=/^\s+$/,Ew=/(?:[^\\]|^)\\$/,bw=/^\\!/,Rw=/^\\#/,$w=/\r?\n/g,Sw=/^\.*\/|^\.+$/,ni="/",gc="node-ignore";typeof Symbol<"u"&&(gc=Symbol.for("node-ignore"));var pc=gc,vw=(r,e,t)=>Object.defineProperty(r,e,{value:t}),xw=/([0-z])-([0-z])/g,yc=()=>!1,kw=r=>r.replace(xw,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:ii),_w=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Cw=[[/^\uFEFF/,()=>ii],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?dc:ii)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+dc}],[/[\\$.|*+(){^]/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,()=>ri],[/\\\\/g,()=>ri],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===ri?`\\[${t}${_w(n)}${i}`:i==="]"&&n.length%2===0?`[${kw(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],hc=Object.create(null),Ow=(r,e)=>{let t=hc[r];return t||(t=Cw.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),hc[r]=t),e?new RegExp(t,"i"):new RegExp(t)},ai=r=>typeof r=="string",Pw=r=>r&&ai(r)&&!ww.test(r)&&!Ew.test(r)&&r.indexOf("#")!==0,Tw=r=>r.split($w),si=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},Aw=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(bw,"!").replace(Rw,"#");let i=Ow(r,e);return new si(t,r,n,i)},Lw=(r,e)=>{throw new e(r)},$e=(r,e,t)=>ai(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),wc=r=>Sw.test(r);$e.isNotRelative=wc;$e.convert=r=>r;var oi=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){vw(this,pc,!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[pc]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Pw(e)){let t=Aw(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,mc(ai(e)?Tw(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?yc:Lw),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(ni)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(ni)+ni,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 mc(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},gr=r=>new oi(r),Mw=r=>$e(r&&$e.convert(r),r,yc);gr.isPathValid=Mw;gr.default=gr;Ec.exports=gr;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)||wc(t)}});(function(){ji().config(Object.assign({},Gi(),Wi()(process.argv)))})();var vu=require("fs"),xu=require("path");var $u=T(kt());var ue=T(require("fs")),Wn=T(require("path")),Ul=T(require("os")),jl=T(Fn());var $y=process.stdout.isTTY===!0&&!process.env.NO_COLOR,ke=r=>$y?r:"",S=ke("\x1B[32m"),A=ke("\x1B[33m"),_=ke("\x1B[36m"),ae=ke("\x1B[35m"),h=ke("\x1B[31m"),g=ke("\x1B[2m"),ee=ke("\x1B[1m"),m=ke("\x1B[0m");var Ml="app.boxel.realms";var Sy={"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"},MR=Object.keys(Sy);function x(r){return r.endsWith("/")?r:`${r}/`}var Re=class extends Error{status;constructor(e,t){super(t),this.name="MatrixAuthError",this.status=e}};async function Il(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 vy(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 e.status===401||e.status===403?new Re(e.status,`OpenID token request failed: ${e.status} ${t}`):new Error(`OpenID token request failed: ${e.status} ${t}`)}return await e.json()}async function Dn(r,e){let t=await vy(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 Un(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 jn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${Ml}`,r.matrixUrl).href}async function nr(r){let e;try{e=await fetch(jn(r),{headers:{Authorization:`Bearer ${r.accessToken}`}})}catch{return[]}if(e.status===401||e.status===403){let t=await e.text();throw new Re(e.status,`Matrix account_data fetch failed: ${e.status} ${t}`)}if(!e.ok)return[];try{let t=await e.json();return Array.isArray(t.realms)?[...t.realms]:[]}catch{return[]}}async function Nl(r,e){let t=await nr(r);if(!t.includes(e)){t.push(e);let n=await fetch(jn(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 n.status===401||n.status===403?new Re(n.status,`Failed to update Matrix account data: ${n.status} ${i}`):new Error(`Failed to update Matrix account data: ${n.status} ${i}`)}}}async function Fl(r,e){let t=x(e),n=await nr(r),i=n.filter(o=>x(o)!==t);if(i.length===n.length)return!1;let s=await fetch(jn(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 s.status===401||s.status===403?new Re(s.status,`Failed to update Matrix account data: ${s.status} ${o}`):new Error(`Failed to update Matrix account data: ${s.status} ${o}`)}return!0}var qn=T(require("readline")),Dl=require("stream");function te(r){let e=qn.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function lt(r){let e=new Dl.Writable({write:(n,i,s)=>s()}),t=qn.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
32
  `||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 by(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Ul(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=by(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 ql(r,e,t){let n=_();switch(r){case"list":await jl(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)?Ul():null;u&&console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await _y(n,t.user,i,t.name,s??u?.matrixUrl,o??u?.realmServerUrl)}else await vy(n,Ul());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 jl(n),process.exit(1)),await xy(n,e);break;case"remove":e||(console.error(`${h}Error:${m} Please specify a profile to remove.`),process.exit(1)),await ky(n,e);break;case"migrate":await Cy(n);break;default:n.printStatus(),console.log(`
38
- ${g}Commands:${m}`),console.log(` ${C}boxel profile list${m} List all profiles`),console.log(` ${C}boxel profile add${m} Add a new profile`),console.log(` ${C}boxel profile switch${m} Switch active profile`),console.log(` ${C}boxel profile remove${m} Remove a profile`),console.log(` ${C}boxel profile migrate${m} Import from .env file`)}}async function jl(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
- ${P}No profiles configured.${m}`),console.log(`Run ${C}boxel profile add${m} to create one.`);return}console.log(`
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:C;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 Sy(){console.log("Which environment?"),console.log(` ${C}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 vy(r,e){console.log(`
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 Sy();t=f.domain,n=f.matrixUrl,i=f.realmServerUrl}console.log(`
33
+ `),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 lt("Realm secret seed: ")}}var xy=Wn.join(Ul.homedir(),".boxel-cli"),ky="profiles.json",_y=86400;function Cy(r,e=_y){let t=r.replace(/^Bearer\s+/i,""),n=jl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var P="No active profile. Run `boxel profile add` to create one.";function ir(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function ct(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function sr(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function fe(r){let e=ct(r),t=sr(r);return`${g}[${m}${_}${e}${m} ${g}\xB7${m} ${ae}${t}${m}${g}]${m}`}var Hn=class{config;configDir;profilesFile;matrixLoginFn;promptPasswordFn;isTtyFn;constructor(e,t){this.configDir=e||xy,this.profilesFile=Wn.join(this.configDir,ky),this.config=this.loadConfig(),this.matrixLoginFn=t?.matrixLogin??Il,this.promptPasswordFn=t?.promptPassword??lt,this.isTtyFn=t?.isTty??(()=>!!process.stdin.isTTY)}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}resolveProfileSlots(e,t,n,i){let s=ir(e),o=ct(e);if(s==="unknown"&&(!n||!i))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let a,l;s==="production"?(a="https://matrix.boxel.ai",l="https://app.boxel.ai/"):s==="local"?(a="http://localhost:8008",l="http://localhost:4201/"):(a="https://matrix-staging.stack.cards",l="https://realms-staging.stack.cards/");let c=sr(e);return{matrixUrl:n||a,realmServerUrl:i||l,displayName:t||`${o} \xB7 ${c}`,username:o}}async addProfileWithAuth(e,t,n,i){let s=this.resolveProfileSlots(e,n,t.matrixUrl,i),o=this.config.profiles[e],a=!!o&&(o.matrixUrl!==s.matrixUrl||o.realmServerUrl!==s.realmServerUrl),l={displayName:s.displayName,matrixUrl:s.matrixUrl,realmServerUrl:s.realmServerUrl,matrixAccessToken:t.accessToken,matrixUserId:t.userId,matrixDeviceId:t.deviceId,realmTokens:a?void 0:o?.realmTokens,realmServerToken:a?void 0:o?.realmServerToken};this.config.profiles[e]=l,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async addProfile(e,t,n,i,s){let o=this.config.profiles[e],a=this.resolveProfileSlots(e,n??o?.displayName,i??o?.matrixUrl,s??o?.realmServerUrl),l=await this.matrixLoginFn(a.matrixUrl,a.username,t);if(l.userId!==e)throw new Error(`Matrix returned userId "${l.userId}" but profile was added as "${e}". Check the Matrix ID and try again.`);await this.addProfileWithAuth(e,l,a.displayName,a.realmServerUrl)}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}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}getStoredMatrixAuth(e){let t=e??this.config.activeProfile??void 0,n=t?this.config.profiles[t]:void 0;if(!t||!n)throw new Error(P);if(!n.matrixAccessToken)throw new Error(`Profile "${t}" has no stored Matrix access token. Run \`boxel profile add\` to re-authenticate.`);return{accessToken:n.matrixAccessToken,userId:n.matrixUserId,deviceId:n.matrixDeviceId,matrixUrl:n.matrixUrl}}async reAuthenticate(e){let t=e??this.config.activeProfile??void 0,n=t?this.config.profiles[t]:void 0;if(!t||!n)throw new Error(P);if(!this.isTtyFn())throw new Error(`Stored Matrix token for "${t}" is no longer valid. Run \`boxel profile add -u ${t} -p <password>\` to re-authenticate.`);console.log(`
34
+ ${A}Stored Matrix session for ${fe(t)} has expired.${m}`);let i=await this.promptPasswordFn(`Password for ${t}: `);if(!i)throw new Error("Re-authentication cancelled: password is required.");let s=ct(t),o=await this.matrixLoginFn(n.matrixUrl,s,i);return await this.addProfileWithAuth(t,o,n.displayName,n.realmServerUrl),this.getStoredMatrixAuth(t)}async fetchRealmServerTokenWithReauth(){let e=this.getStoredMatrixAuth(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,"");try{let i=await Dn(e,n);return this.setRealmServerToken(i),i}catch(i){if(!(i instanceof Re))throw i;let s=await this.reAuthenticate(),o=await Dn(s,n);return this.setRealmServerToken(o),o}}async getOrRefreshServerToken(){let e=this.getRealmServerToken();return e&&!Cy(e)?e:this.fetchRealmServerTokenWithReauth()}async refreshServerToken(){return this.fetchRealmServerTokenWithReauth()}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 Un(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 Un(i,t))[e];return o&&this.setRealmToken(e,o),o}async withMatrixAuthRecovery(e){try{return await e(this.getStoredMatrixAuth())}catch(t){if(!(t instanceof Re))throw t;let n=await this.reAuthenticate();return e(n)}}async addToUserRealms(e){await this.withMatrixAuthRecovery(t=>Nl(t,e))}async removeFromUserRealms(e){return this.withMatrixAuthRecovery(t=>Fl(t,e))}async getUserRealms(){return this.withMatrixAuthRecovery(e=>nr(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}`,l=!this.config.profiles[a];return await this.addProfile(a,n,void 0,e,i),{profileId:a,created:l}}printStatus(){let e=this.getActiveProfile();e?(console.log(`
35
+ ${ee}Active Profile:${m} ${fe(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}`)):(console.log(`
36
+ ${A}No active profile and no environment variables set.${m}`),console.log(`Run ${_}boxel profile add${m} to create a profile.`))}},Gn=null;function C(){return Gn||(Gn=new Hn),Gn}var Vn={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 or(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 Oy(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function ql(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Oy(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 Hl(r,e,t){let n=C();switch(r){case"list":await Gl(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let s=t.matrixUrl?or(t.matrixUrl,"--matrix-url"):void 0,o=t.realmServerUrl?or(t.realmServerUrl,"--realm-server-url"):void 0,u=!(ir(t.user)!=="unknown")&&(!s||!o)?ql():null;u&&console.log(`${g}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await My(n,t.user,i,t.name,s??u?.matrixUrl,o??u?.realmServerUrl)}else await Ty(n,ql());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 Gl(n),process.exit(1)),await Ay(n,e);break;case"remove":e||(console.error(`${h}Error:${m} Please specify a profile to remove.`),process.exit(1)),await Ly(n,e);break;case"migrate":await Iy(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 Gl(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
+ ${A}No profiles configured.${m}`),console.log(`Run ${_}boxel profile add${m} to create one.`);return}console.log(`
40
+ ${ee}Saved Profiles:${m}
41
+ `);for(let n of e){let i=r.getProfile(n),s=n===t,o=ir(n),a=s?`${S}\u2605${m} `:" ",l=sr(n),c=o==="production"?ae:_;console.log(`${a}${ee}${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 Py(){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(` ${A}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=or(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=or(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"?{...Vn.local}:r==="2"?{...Vn.production}:{...Vn.staging}}async function Ty(r,e){console.log(`
43
+ ${ee}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 Py();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
- ${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 xy(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(`
46
+ ${A}Profile ${o} already exists.${m}`),(await te("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await lt("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: ${fe(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 ${fe(o)}`))}async function Ay(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(s=>{let o=ct(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 ky(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 _y(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 Cy(r){console.log(`
50
- ${Z}Migrate from .env${m}
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
- 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
- ${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,Oy=console.log.bind(console),Py=console.info.bind(console),Ty=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=Oy,console.info=Py,console.debug=Ty}function Gl(){return lt}var M={info(...r){lt||process.stderr.write(r.map(sr).join(" ")+`
55
- `)},warn(...r){process.stderr.write(r.map(sr).join(" ")+`
56
- `)},error(...r){process.stderr.write(r.map(sr).join(" ")+`
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 Hl=!1,Ay=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function Ly(r){return Ay.has(r)}function My(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 Iy(r){let e;try{e=new URL(r)}catch{return null}let t=My(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 Ny(r,e){let t=Iy(r);return t===null?null:H.resolve(e,t)}function Dy(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 Wl(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()&&!Ly(e.name)).map(e=>H.join(r,e.name))}catch{return[]}}function Fy(r){let e=[],t=H.resolve(r);for(let n of ar(t))Wl(n,e);for(let n of ar(t))for(let i of ar(n))for(let s of ar(i))Wl(s,e);return e}function Uy(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=Fy(e),n=new Set,i=[];for(let s of t){if(n.has(s))continue;n.add(s);let o=Dy(s);if(!o)continue;let a=Ny(o.realmUrl,e);if(a===null||!Uy(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 Vl(r){if(Hl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Gl())return;let e=Bn(r);if(e.length===0)return;Hl=!0,console.warn(`
49
+ Matching profiles:`);for(let s of i)console.log(` ${s}`);process.exit(1)}}r.switchProfile(n)?console.log(`${S}\u2713${m} Switched to ${fe(n)}`):(console.error(`${h}Error:${m} Failed to switch profile.`),process.exit(1))}async function Ly(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: ${fe(i)}`)}else console.error(`${h}Error:${m} Failed to remove profile.`),process.exit(1)}async function My(r,e,t,n,i,s){(!e.startsWith("@")||!e.includes(":"))&&(console.error(`${h}Error:${m} Invalid Matrix ID format. Expected @user:domain`),process.exit(1));let o=!!r.getProfile(e);try{await r.addProfile(e,t,n,i,s)}catch(l){console.error(`${h}Error:${m} ${l instanceof Error?l.message:String(l)}`),process.exit(1)}if(o){(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: ${fe(e)}`);return}console.log(`${S}\u2713${m} Profile created: ${fe(e)}`),r.getActiveProfileId()!==e&&console.log(`${g}Use 'boxel profile switch ${e}' to switch to this profile.${m}`)}async function Iy(r){console.log(`
50
+ ${ee}Migrate from .env${m}
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(`${A}No complete credentials found in environment variables.${m}`),console.log(`
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: ${fe(s.profileId)}`),console.log(`
53
+ ${g}You can now remove credentials from .env if desired.${m}`)):(console.log(`${S}\u2713${m} Refreshed profile: ${fe(s.profileId)}`),console.log(`
54
+ ${g}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${A}Migration failed.${m}`)}var me=T(require("fs")),Le=T(require("path"));var Ye=T(require("fs")),H=T(require("path"));var ut=!1,Ny=console.log.bind(console),Fy=console.info.bind(console),Dy=console.debug.bind(console);function lr(r){if(r!==ut)if(ut=r,ut){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=Ny,console.info=Fy,console.debug=Dy}function Wl(){return ut}var M={info(...r){ut||process.stderr.write(r.map(ar).join(" ")+`
55
+ `)},warn(...r){process.stderr.write(r.map(ar).join(" ")+`
56
+ `)},error(...r){process.stderr.write(r.map(ar).join(" ")+`
57
+ `)},output(...r){process.stdout.write(r.map(ar).join(" ")+`
58
+ `)}};function ar(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 Vl=!1,Uy=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function jy(r){return Uy.has(r)}function qy(r){return r==="stack.cards"||r.endsWith(".stack.cards")?"stack.cards":r==="boxel.ai"||r.endsWith(".boxel.ai")?"boxel.ai":r}function Bn(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 Gy(r){let e;try{e=new URL(r)}catch{return null}let t=qy(e.hostname);if(!Bn(t))return null;let n=e.pathname.replace(/^\/|\/$/g,"").split("/").filter(Boolean),i=n[0]??"unknown-owner",s=n[1]??n[0]??"workspace";return!Bn(i)||!Bn(s)?null:H.join(t,i,s)}function Hy(r,e){let t=Gy(r);return t===null?null:H.resolve(e,t)}function Wy(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 Bl(r,e){let t=H.join(r,".boxel-sync.json");Ye.existsSync(t)&&e.push(t)}function cr(r){try{return Ye.readdirSync(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!jy(e.name)).map(e=>H.join(r,e.name))}catch{return[]}}function Vy(r){let e=[],t=H.resolve(r);for(let n of cr(t))Bl(n,e);for(let n of cr(t))for(let i of cr(n))for(let s of cr(i))Bl(s,e);return e}function By(r,e){let t=H.relative(r,e);return t===""?!0:t.startsWith("..")?!1:!H.isAbsolute(t)}function Yn(r){let e=H.resolve(r),t=Vy(e),n=new Set,i=[];for(let s of t){if(n.has(s))continue;n.add(s);let o=Wy(s);if(!o)continue;let a=Hy(o.realmUrl,e);if(a===null||!By(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 Yl(r){if(Vl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Wl())return;let e=Yn(r);if(e.length===0)return;Vl=!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 jy(r){fe.existsSync(r)||fe.mkdirSync(r,{recursive:!0})}function qy(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 Gy(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}jy(Ae.dirname(o.expectedDir));try{qy(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(`
61
+ `)}function Yy(r){me.existsSync(r)||me.mkdirSync(r,{recursive:!0})}function Jy(r,e){try{me.renameSync(r,e)}catch(t){let n=t;if(n.code!=="EXDEV")throw n;me.cpSync(r,e,{recursive:!0}),me.rmSync(r,{recursive:!0,force:!0})}}async function zy(r,e){let t=Le.resolve(r||"."),n=Yn(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=Le.relative(t,o.currentDir)||".",l=Le.relative(t,o.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(me.existsSync(o.expectedDir)){console.warn(" Skipping: target path already exists"),s+=1;continue}Yy(Le.dirname(o.expectedDir));try{Jy(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 Bl(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 Gy(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 Yl=require("fs");async function ft(r,e,t,n){let i=n?.profileManager??_();if(!i.getActiveProfile())return{ok:!1,error:L};let o=new URL(e,k(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 Hy(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Jl(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,Yl.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 Hy(),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??_();if(!i.getActiveProfile())return{ok:!1,error:L};let o=`${k(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=_();n.getActiveProfile()||(console.error(`${h}Error:${m} ${L}`),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,k(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??_();if(!t.getActiveProfile())return{filenames:[],error:L};let i=k(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 zl(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 Wy(r,e){let t=e?.profileManager??_();if(!t.getActiveProfile())return cr(L);let i=k(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 $=new URL(f,i).href,I=await t.authedRealmFetch($,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!I.ok){let ee=await I.text().catch(()=>"(no body)");Xn(f,`HTTP ${I.status}: ${ee.slice(0,300)}`,a),l+=1,c+=1;continue}d=await I.text()}catch($){Xn(f,$ instanceof Error?$.message:String($),a),l+=1,c+=1;continue}let p=await Yn(i,d,f,{profileManager:t});if(!p.ok){Xn(f,p.error??"lint failed",a),l+=1,c+=1;continue}let y=!1;for(let $ of p.messages??[]){let I=$.severity===2?"error":"warning";a.push({rule:$.ruleId,file:f,line:$.line,column:$.column,message:$.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 Xn(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 Kl(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 Wy(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
- ${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 ec=require("node:child_process"),me=require("node:fs"),tc=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 zn(r,e,t){let n=t?.profileManager??_(),i=n.getActiveProfile();if(!i)return{ok:!1,error:L};let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(k);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 Ql(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 zn(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 Vy={module:"https://cardstack.com/base/spec",name:"Spec"},Qn=[".gts",".gjs",".ts"],dr=".json",rc=mt(__dirname),Zn=(0,J.resolve)(rc,".."),By=(0,J.join)(Zn,"base"),dt=(0,J.join)(Zn,"host"),Yy=(0,J.join)(Zn,"boxel-ui","addon","src"),Jy=(0,J.join)(dt,"node_modules"),Kn;async function Xy(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 zy(r,e){let t=e?.profileManager??_();if(!t.getActiveProfile())return mr(L);let i=k(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([Ky(i,t),Qy(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 Zl(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 ew(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 Zl(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=tw(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 Ky(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 Qy(r,e){let t=await Xy(()=>zn(r,{filter:{type:Vy}},{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=Zy(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 Zy(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 Zl(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 ew(r){let e=(0,me.mkdtempSync)((0,J.join)((0,tc.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/*":[`${By}/*`],"@cardstack/host/tests/*":[`${dt}/tests/*`],"@cardstack/host/*":[`${dt}/app/*`],"@cardstack/boxel-host/commands/*":[`${dt}/app/commands/*`],"@cardstack/boxel-ui/*":[`${Yy}/*`],"*":[`${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)(Jy,(0,J.join)(e,"node_modules"));let t=(0,J.join)(rc,"node_modules",".bin","ember-tsc"),{output:n,exitedWithError:i}=await new Promise((a,l)=>{let c=(0,ec.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 $=y.slice(e.length+1),I=r.find(ee=>ee.path===$);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 tw(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"}]:rw(r,t)}function rw(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 nc(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 zy(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(`
64
+ Moved ${i} director${i===1?"y":"ies"}.`),s>0&&console.log(`Skipped ${s} due to existing target paths or move failures.`)}function Jl(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 zy(e,t)})}function ft(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 ur=require("fs");var zl=require("fs");async function dt(r,e,t,n){let i=n?.profileManager??C();if(!i.getActiveProfile())return{ok:!1,error:P};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 mt(r){process.stderr.write(r+`
65
+ `)}async function Xy(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Xl(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,zl.readFileSync)(t.file,"utf-8")}catch(s){mt(`${h}Error:${m} Could not read file: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}else process.stdin.isTTY&&mt(`${g}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${m}`),n=await Xy(),mt(`${g}Received ${n.length} bytes. Writing to realm...${m}`);let i;try{i=await dt(t.realm,e,n)}catch(s){mt(`${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}`):mt(`${h}Error:${m} ${i.error}`),i.ok||process.exit(1)})}async function Jn(r,e,t,n){let i=n?.profileManager??C();if(!i.getActiveProfile())return{ok:!1,error:P};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 Kl(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} ${P}`),process.exit(1));let s;if(t.file)try{s=(0,ur.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 Jn(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,ur.writeFileSync)(t.file,o.output,"utf-8"),console.log(`${S}Fixed:${m} ${t.file}`);else{let u=await dt(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:A,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 Ie(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return{filenames:[],error:P};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 Ql(r){r.command("list").alias("ls").description("List all files in a realm").requiredOption("--realm <realm-url>","The realm URL to list files from").option("--json","Output raw JSON response").action(async e=>{let t;try{t=await Ie(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 zn=[".gts",".gjs",".ts",".js"];async function Ky(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return fr(P);let i=x(r),s=Date.now(),o;if(e?.path){let f=e.path,d=ft(f);if(d)return fr(d);if(!zn.some(p=>f.endsWith(p)))return fr(`Path "${f}" is not lintable \u2014 must end with one of ${zn.join(", ")}`);o=[f]}else{let f=await Ie(i,{profileManager:t});if(f.error)return fr(`Failed to list realm files: ${f.error}`);o=f.filenames.filter(d=>zn.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 Z=await I.text().catch(()=>"(no body)");Xn(f,`HTTP ${I.status}: ${Z.slice(0,300)}`,a),l+=1,c+=1;continue}d=await I.text()}catch(R){Xn(f,R instanceof Error?R.message:String(R),a),l+=1,c+=1;continue}let p=await Jn(i,d,f,{profileManager:t});if(!p.ok){Xn(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 Xn(r,e,t){t.push({rule:"lint-error",file:r,line:0,column:0,message:e,severity:"error"})}function fr(r){return{status:"error",filesChecked:0,filesWithErrors:0,errorCount:0,warningCount:0,durationMs:0,lintableFiles:[],violations:[],errorMessage:r}}function Zl(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 Ky(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
+ ${g}${s.file}${m}`));let o=s.severity==="error"?h:A,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 rc=require("node:child_process"),de=require("node:fs"),nc=require("node:os"),J=require("node:path");var mr=require("node:fs"),dr=require("node:path");function pt(r){let e=r;for(;;){let t=(0,dr.join)(e,"package.json");if((0,mr.existsSync)(t))try{if(JSON.parse((0,mr.readFileSync)(t,"utf8"))?.name==="@cardstack/boxel-cli")return e}catch{}let n=(0,dr.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 Kn(r,e,t){let n=t?.profileManager??C(),i=n.getActiveProfile();if(!i)return{ok:!1,error:P};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 ec(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 Kn(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 Qy={module:"https://cardstack.com/base/spec",name:"Spec"},Zn=[".gts",".gjs",".ts"],hr=".json",ic=pt(__dirname),ei=(0,J.resolve)(ic,".."),Zy=(0,J.join)(ei,"base"),ht=(0,J.join)(ei,"host"),ew=(0,J.join)(ei,"boxel-ui","addon","src"),tw=(0,J.join)(ht,"node_modules"),Qn;async function rw(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 nw(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return pr(P);let i=x(r),s=Date.now(),o=[],a=[];if(e?.path){let f=e.path,d=ft(f);if(d)return pr(d);if(Zn.some(p=>f.endsWith(p)))o=[f];else if(f.endsWith(hr))a=[f];else return pr(`Path "${f}" is not parseable \u2014 must end with one of ${Zn.join(", ")}, or ${hr}`)}else try{[o,a]=await Promise.all([iw(i,t),sw(i,t)])}catch(f){return pr(`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 tc(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 aw(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 tc(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=lw(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 iw(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("/")||Zn.some(c=>l.endsWith(c))&&o.push(l)}return o.sort()}async function sw(r,e){let t=await rw(()=>Kn(r,{filter:{type:Qy}},{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=ow(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(hr)?o:`${o}${hr}`;i.includes(a)||i.push(a)}return i.sort()}function ow(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 tc(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 aw(r){let e=(0,de.mkdtempSync)((0,J.join)((0,nc.tmpdir)(),"boxel-parse-"));try{for(let a of r){let l=ft(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,de.mkdirSync)((0,J.dirname)(u),{recursive:!0}),(0,de.writeFileSync)(u,a.content,"utf8")}if(!Qn){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/*":[`${Zy}/*`],"@cardstack/host/tests/*":[`${ht}/tests/*`],"@cardstack/host/*":[`${ht}/app/*`],"@cardstack/boxel-host/commands/*":[`${ht}/app/commands/*`],"@cardstack/boxel-ui/*":[`${ew}/*`],"*":[`${ht}/types/*`]}},include:["**/*.ts","**/*.gts","**/*.gjs"],exclude:["node_modules"]};Qn=JSON.stringify(a,null,2)}(0,de.writeFileSync)((0,J.join)(e,"tsconfig.json"),Qn,"utf8"),(0,de.symlinkSync)(tw,(0,J.join)(e,"node_modules"));let t=(0,J.join)(ic,"node_modules",".bin","ember-tsc"),{output:n,exitedWithError:i}=await new Promise((a,l)=>{let c=(0,rc.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(Z=>Z.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,de.rmSync)(e,{recursive:!0,force:!0})}catch{}}}function lw(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"}]:cw(r,t)}function cw(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 pr(r){return{status:"error",filesChecked:0,filesWithErrors:0,errorCount:0,durationMs:0,parseableFiles:[],errors:[],errorMessage:r}}function sc(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 nw(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 uw(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 oc(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 uw(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 fw(r,e){let t=e?.profileManager??C();if(!t.getActiveProfile())return{ok:!1,error:P};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 ac(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 fw(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 mw=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"}),lc=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 ti(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return mw[e.charAt(0)]}function cc(){let r=Math.floor(Math.random()*lc.length);return lc[r]}var dw=/^[a-z0-9-]+$/;function fc(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 gw(e,t,n)})}async function pw(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??cc(),iconURL:t.icon??ti(e)??ti(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=yw(d,s,r),y=await uc(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 uc(n,u);try{await n.addToUserRealms(u)}catch{}return t.waitForReady&&f&&await hw(u,f),{realmUrl:u,created:!0,realmToken:f}}async function uc(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function hw(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 gw(r,e,t){dw.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await pw(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 yw(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 wt=T(require("fs"));var xc=require("child_process"),X=T(require("fs/promises")),B=T(require("path"));var V=T(require("fs/promises")),W=T(require("path")),fi=T(bc());var li=class{value;next;constructor(e){this.value=e}},gt=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new li(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 ci(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Rc(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new gt,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){Rc(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 Rc(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 Iw=fi.default.default||fi.default,Nw=new Set([".realm.json"]),ui=1e4,Fw=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Nw.has(e)}async function $c(r){try{return await V.access(r),!0}catch{return!1}}function Sc(r){try{return decodeURIComponent(r)}catch{return r}}var yt={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},Dw=10,vc=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=ci(Dw);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:yt.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()&&vc.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()&&vc.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:yt.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=>Sc(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?Sc(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:yt.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:yt.CardSource},signal:AbortSignal.timeout(ui)})}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 ${ui}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${ui}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:yt.CardSource},signal:AbortSignal.timeout(Fw)});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=Iw(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=W.join(s,".gitignore");if(await $c(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 $c(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 mi(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 mi(this.gitDir)||await X.mkdir(this.gitDir,{recursive:!0});let e=B.join(this.gitDir,".git");await mi(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 mi(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 z.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),s=await this.getWorkspaceFiles();await Promise.all(s.map(async o=>{if(!F(o)&&!i.has(o)){let a=B.join(this.workspaceDir,o);try{await z.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async o=>{if(F(o))return;let a=B.join(this.gitDir,o),l=B.join(this.workspaceDir,o),c=B.dirname(l);await z.mkdir(c,{recursive:!0}),await z.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(`
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,Sc.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 vc=100;function gr(r){return r instanceof Error?r.message:String(r)}async function Aw(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 Lw(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 Mw(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 Iw(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 Nw(r){return r==="local"?`${S}LOCAL${m}`:r==="remote"?`${C}SERVER${m}`:`${ae}MANUAL${m}`}function xc(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 Dw(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
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}${Nw(i.source)} ${l} ${i.message} ${g}(${i.filesChanged} files)${m}`),console.log(` ${g}${xc(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 Fw(r){if(r===void 0)return vc;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 kc(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: ${vc})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ie("Only one of --restore or --message may be specified.");let n=Fw(t.limit);if(n===null&&Ie("--limit must be a positive integer."),t.message!==void 0){let s=await Lw(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 Mw(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}${xc(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 Iw(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 Aw(e,n);i.ok||Ie(i.error),Dw(i.checkpoints,i.truncated,n)})}var Uw="--all-accessible and --hidden are mutually exclusive";async function jw(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:Uw};let e=r.profileManager??_(),t=e.getActiveProfile();if(!t)return{realms:[],error:L};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let u=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${u}`}}let s=await i.json(),o=Object.keys(s).map(k),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(k)),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 _c(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 jw({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(` ${C}${n.url}${m}${i}`)}})}var wr=T(require("fs"));var mi=100;function Er(r){return r instanceof Error?r.message:String(r)}function qw(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 Cc(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 Gw(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 Hw(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 Cc(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 Ww(r,e,t){if(!wr.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Cc(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 Vw(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 Hw(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 Ww(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await Gw(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function Bw(r,e){if(r.length===0){console.log(`
84
+ `).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,xc.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 yr(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 kc=100;function wr(r){return r instanceof Error?r.message:String(r)}async function Uw(r,e){if(!wt.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: ${wr(t)}`}}}async function jw(r,e){if(!wt.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: ${wr(n)}`}}}async function qw(r,e,t){if(!wt.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=yr(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: ${wr(n)}`}}}async function Gw(r,e){if(!wt.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: ${wr(t)}`}}}function Hw(r){return r==="local"?`${S}LOCAL${m}`:r==="remote"?`${_}SERVER${m}`:`${ae}MANUAL${m}`}function _c(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 Ww(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
85
+ ${ee}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?`${A}[MAJOR]${m}`:`${g}[minor]${m}`,c=i.isMilestone?`${A}\u2B50${m} ${ae}[${i.milestoneName}]${m} `:"";console.log(`${a} ${A}${i.shortHash}${m} ${c}${Hw(i.source)} ${l} ${i.message} ${g}(${i.filesChanged} files)${m}`),console.log(` ${g}${_c(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 Vw(r){if(r===void 0)return kc;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Ne(r){console.error(`${h}Error:${m} ${r}`),process.exit(1)}function Cc(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: ${kc})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ne("Only one of --restore or --message may be specified.");let n=Vw(t.limit);if(n===null&&Ne("--limit must be a positive integer."),t.message!==void 0){let s=await jw(e,t.message);s.ok||Ne(s.error),console.log(`${S}\u2713${m} Checkpoint created: ${A}${s.created.shortHash}${m} ${s.created.message}`);return}if(t.restore!==void 0){let s=await qw(e,t.restore,n);s.ok||Ne(s.error);let o=s.target;if(!t.yes){process.stdin.isTTY||Ne("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
88
+ ${ee}Restoring to:${m} ${A}${o.shortHash}${m} - ${o.message}`),console.log(`${g}${_c(o.date)}${m}
89
+ `);let l=await te(`${A}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${g}Restore cancelled.${m}`);return}}let a=await Gw(e,o.hash);a.ok||Ne(a.error),console.log(`${S}\u2713${m} Restored to ${A}${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 Uw(e,n);i.ok||Ne(i.error),Ww(i.checkpoints,i.truncated,n)})}var Bw="--all-accessible and --hidden are mutually exclusive";async function Yw(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:Bw};let e=r.profileManager??C(),t=e.getActiveProfile();if(!t)return{realms:[],error:P};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 Oc(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 Yw({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(`${ee}${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 br=T(require("fs"));var di=100;function Rr(r){return r instanceof Error?r.message:String(r)}function Jw(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 Pc(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=yr(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: ${Rr(n)}`}}}async function zw(r){if(!br.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: ${Rr(e)}`}}}async function Xw(r,e,t,n){if(!br.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 Pc(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: ${Rr(o)}`}}}async function Kw(r,e,t){if(!br.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Pc(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: ${Rr(s)}`}}}async function Qw(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??di;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await Xw(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 Kw(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await zw(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function Zw(r,e){if(r.length===0){console.log(`
90
90
  No milestones marked yet.
91
- `),console.log(`Use ${C}boxel realm milestone <local-dir> --mark <ref> --name <name>${m} to mark a checkpoint.`),console.log(`Use ${C}boxel realm history <local-dir>${m} to see available checkpoints.
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
- ${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"?C:ae;console.log(` ${P}\u2B50${m} ${P}${t.shortHash}${m} ${i}${n}${m} ${ae}[${t.milestoneName}]${m} ${t.message}`),console.log(` ${g}${qw(t.date)}${m}`)}console.log()}function Yw(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 Oc(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=Yw(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 Vw(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}Bw(i.milestones,e)})}var Pc=T(In()),Tc="realm_server";function Jw(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 Xw(r,e=Tc){return`@${e}:${Jw(r)}`}function zw(r){return new URL(r).origin+"/"}function Kw(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var Rr=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??Tc,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=Kw(e);return{user:this.#r??Xw(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:zw(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Pc.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 Rr({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??_();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:L}}var $r=T(require("fs/promises")),Ac=T(require("path")),di=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 $r.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await $r.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=Ac.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(`
93
+ ${ee}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"?_:ae;console.log(` ${A}\u2B50${m} ${A}${t.shortHash}${m} ${i}${n}${m} ${ae}[${t.milestoneName}]${m} ${t.message}`),console.log(` ${g}${Jw(t.date)}${m}`)}console.log()}function eE(r){if(r===void 0)return di;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Er(r){console.error(`${h}Error:${m} ${r}`),process.exit(1)}function Tc(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: ${di})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&Er("Only one of --mark or --remove may be specified.");let n=eE(t.limit);n===null&&Er("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&Er("--name is required when using --mark.");let i=await Qw(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||Er(i.error),i.marked){let s=i.marked;console.log(`
95
+ ${S}\u2713${m} ${A}\u2B50${m} Milestone created: ${ae}${s.milestoneName}${m}`),console.log(` Checkpoint: ${A}${s.shortHash}${m} ${s.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${m} Milestone removed`);return}Zw(i.milestones,e)})}async function pi(r,e={}){let t=x(r),n=e.profileManager??C(),i=n.getActiveProfile();if(!i)return{publishedRealmURL:t,unpublished:!1,error:P};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 tE(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 tE(r){try{return await r.text()}catch{return"<no response body>"}}function Ac(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 pi(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 Ic=3e5,rE=1e3;async function nE(r,e,t={}){let n=t.profileManager??C(),i=n.getActiveProfile();if(!i)throw new Error(P);let s=x(r),o=x(e),a=i.profile.realmServerUrl.replace(/\/$/,""),l=await Lc(n,a,s,o);if((l.status===400||l.status===409)&&t.republish!==!1){let d=await Mc(l);console.log(`Publish returned ${l.status} (${d.slice(0,200)}). Unpublishing and retrying.`);let p=await pi(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 Lc(n,a,s,o)}if(l.status!==200&&l.status!==201&&l.status!==202){let d=await Mc(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??Ic,p;try{let y=await n.getOrRefreshServerToken();p=await n.fetchAndStoreRealmToken(f.publishedRealmURL,y)}catch{}await iE(f.publishedRealmURL,p,d)}return f}async function Lc(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 iE(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(rE,o)))}throw new Error(`Timed out after ${t}ms waiting for ${r} to pass readiness check${s?`: ${s}`:""}`)}async function Mc(r){try{return await r.text()}catch{return"<no response body>"}}function sE(r){return{waitForReady:r.wait!==!1,timeoutMs:r.timeout,republish:r.republish!==!1}}function Nc(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: ${Ic})`,oE).option("--no-republish","Do not auto-unpublish + retry when the server returns 400/409").action(async(e,t,n)=>{try{let i=await nE(e,t,sE(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 oE(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 Fc=T(Fn()),Dc="realm_server";function aE(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 lE(r,e=Dc){return`@${e}:${aE(r)}`}function cE(r){return new URL(r).origin+"/"}function uE(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var $r=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??Dc,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=uE(e);return{user:this.#r??lE(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:cE(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Fc.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 $r({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:P}}var Sr=T(require("fs/promises")),Uc=T(require("path")),hi=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 Sr.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await Sr.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=Uc.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 Lc(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 Qw(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 Qw(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 di({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")),pi=T(require("path")),Mc=T(require("crypto"));function hi(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 Mc.createHash("md5").update(e).digest("hex")}async function we(r){let e=pi.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 hi(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=pi.join(r,".boxel-sync.json");await Ne.writeFile(t,JSON.stringify(e,null,2))}var Zw=new Set(["index.json","realm.json"]),gi=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(F(p))return{relativePath:p,localPath:y,currentHash:"",protected:!0};let $=await re(y);return{relativePath:p,localPath:y,currentHash:$,protected:!1}}))]);for(let p of d){if(p.protected){u++;continue}let y=i.files[p.relativePath],$=i.remoteMtimes?.[p.relativePath],I=f.get(p.relativePath),ee=y!==p.currentHash,b=y!==void 0&&!t.has(p.relativePath),v=$!==void 0&&I!==void 0&&I!==$;ee||b||v?(o.set(p.relativePath,p.localPath),!ee&&(b||v)&&a.add(p.relativePath)):(u++,s.files[p.relativePath]=p.currentHash,$!==void 0&&(s.remoteMtimes[p.relativePath]=$))}if(u>0&&console.log(`Skipping ${u} unchanged files`),a.size>0){let p=Array.from(a),y=p.slice(0,5).join(", "),$=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}${$}`)}}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)F(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,$=y&&!t.has(p);(!y||$)&&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:$}of p)s.files[y]=$}}if(this.pushOptions.deleteRemote){let u=new Set(t.keys()),f=[];for(let d of u){if(F(d)){u.delete(d);continue}Zw.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 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(` ${C}\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 b of this.skippedConflicts)console.log(` ${b}`);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(`
98
+ Checkpoint created: ${c.shortHash} ${u} ${c.message}`)}}console.log("Pull completed")}};function jc(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 fE(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 fE(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 hi({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 Fe=T(require("fs/promises")),gi=T(require("path")),qc=T(require("crypto"));function yi(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 Fe.access(r),!0}catch{return!1}}async function re(r){let e=await Fe.readFile(r);return qc.createHash("md5").update(e).digest("hex")}async function we(r){let e=gi.join(r,".boxel-sync.json"),t;try{t=await Fe.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return yi(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function _e(r,e){let t=gi.join(r,".boxel-sync.json");await Fe.writeFile(t,JSON.stringify(e,null,2))}var mE=new Set(["index.json","realm.json"]),wi=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),Z=y!==p.currentHash,$=y!==void 0&&!t.has(p.relativePath),v=R!==void 0&&I!==void 0&&I!==R;Z||$||v?(o.set(p.relativePath,p.localPath),!Z&&($||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}mE.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 _e(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 Gc(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 dE(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function dE(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 wi({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 Hc(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:P};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 pE(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 pE(r){try{return await r.text()}catch{return"<no response body>"}}function Wc(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 Hc({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 Hc({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")),Et=T(require("path"));function vr(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 xr(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 Vc(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 Bc(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 hE=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),gE=6;function yE(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 Ei=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=vr(a,s,this.loadedManifest),c=xr(a,this.remoteMtimes,this.loadedManifest),u=yE(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=Et.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 _e(this.options.localDir,this.loadedManifest)}};async function Yc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=Et.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 Ei({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 wE(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()&&(hE.has(l.name)||await n(Et.join(i,l.name),s+1))}return await n(r,0),t.sort(),t}async function EE(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:gE,s=await wE(r,i),o=[],a=!1;for(let l of s){let c=Et.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(!yi(f)){o.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await Yc(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 bE(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(`${A}\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 RE(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(`${A}${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(`${A}\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 Jc(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 EE(e??process.cwd(),{all:!0,realmSecretSeed:n});RE(s),s.hasError&&process.exit(2);return}let i=await Yc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});bE(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var Ri=T(require("path"));var $i=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(`${A}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=vr($,l,a),O=xr($,i,a),U=Vc(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(Bc($,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(` ${A}\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 b=await Promise.all(d.map(v=>this.remoteLimit(async()=>{try{let O=Ei.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(...b.filter(v=>v!==null))}if(f.length>0){console.log(`
103
- Pushing ${f.length} file(s)...`);let b=new Map;for(let U of f){let Et=o.get(U);Et&&b.set(U,Et)}let v=new Set;for(let U of b.keys()){let Et=a?.files[U]!==void 0,Eu=i.has(U);!Et&&!Eu&&v.add(U)}let O=await this.uploadFilesAtomic(b,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 b=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(...b.filter(v=>v!==null))}if(y.length>0){console.log(`
105
- Deleting ${y.length} local file(s)...`);let b=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(...b.filter(v=>v!==null))}if(!this.options.dryRun&&!this.hasError){let b=new Map;if(a)for(let[O,U]of Object.entries(a.files))b.set(O,U);for(let[O,U]of l)b.set(O,U);for(let O of this.pushedFiles){let U=o.get(O);U&&b.set(O,await re(U))}for(let O of this.pulledFiles){let U=Ei.join(this.options.localDir,O);b.set(O,await re(U))}for(let O of this.remoteDeletedFiles)b.delete(O);for(let O of this.localDeletedFiles)b.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(b,v)}if(!this.options.dryRun){let b=[...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(b.length>0){let O=await new j(this.options.localDir).createCheckpoint("local",b);if(O){let U=O.isMajor?"[MAJOR]":"[minor]";console.log(`
102
+ Pulling ${d.length} file(s)...`);let $=await Promise.all(d.map(v=>this.remoteLimit(async()=>{try{let O=Ri.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 Rt=o.get(U);Rt&&$.set(U,Rt)}let v=new Set;for(let U of $.keys()){let Rt=a?.files[U]!==void 0,ku=i.has(U);!Rt&&!ku&&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=Ri.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 Gc(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 cE(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 cE(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 wi({error:o.error});n=o.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return wi({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Je(r))return wi({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?uE(s):void 0}}function uE(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 wi(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var Hc=T(vt());function fE(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Hc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function mE(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??_();if(!n.getActiveProfile())return{ready:!1,error:L};let s=`${k(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 Wc(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)",fE).action(async e=>{let t;try{t=await mE(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 _i=T(vt()),eu=T(require("fs/promises")),xr=T(require("path"));var _e=T(require("fs/promises")),Vc=T(require("path")),dE=".boxel-watch.lock";function $i(r){return Vc.join(r,dE)}function bi(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function pE(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 Bc(r,e){await _e.mkdir(r,{recursive:!0});let t=await pE(r),n=!1;if(t&&bi(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")),Yc=T(require("os")),Si=T(require("path"));function Jc(){return Si.join(Yc.homedir(),".boxel-cli")}function Xc(){return Si.join(Jc(),"watch-processes.json")}async function zc(){try{let r=await Ce.readFile(Xc(),"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 vi(r){await Ce.mkdir(Jc(),{recursive:!0});let e=Xc(),t=`${e}.${process.pid}.tmp`;await Ce.writeFile(t,JSON.stringify(r,null,2)+`
109
- `),await Ce.rename(t,e)}async function Kc(){let r=await zc(),e=r.processes.filter(t=>bi(t.pid));return e.length!==r.processes.length&&await vi({processes:e}),{processes:e}}async function Qc(r){let t=(await Kc()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await vi({processes:t})}async function Zc(){let r=await zc(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await vi({processes:e})}async function xi(){return(await Kc()).processes}var ki=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=wE(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(F(n))continue;let s=this.lastKnownMtimes.get(n);s===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>s&&this.recordPending(n,{status:"modified",mtime:i})&&(t=!0)}for(let n of this.lastKnownMtimes.keys())F(n)||e.has(n)||this.pendingChanges.get(n)?.status!=="deleted"&&(this.pendingChanges.set(n,{status:"deleted",mtime:0}),t=!0);return t}async flushPending(){if(this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingChanges.size===0)return{pulled:[],deleted:[],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 eu.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 hE(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 Bc(p.localDir,p.realmUrl);if(!y.ok){for(let $ of a)await vr($);return{watchers:[],error:gE(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 ki(p,o,{debounceMs:n,overwriteLocal:s});try{await y.initialize()}catch($){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}: ${$ instanceof Error?$.message:String($)}`}}l.push(y)}if(!i){console.log(`${C}\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($=>{i||yE(p.name,$)}))}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 Qc(r.map(p=>p.localDir).join(", "))}catch{}return await c(),d(),await new Promise(p=>{let y=null,$=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),$&&process.off("SIGTERM",$);for(let ee of a)try{await vr(ee)}catch{}try{await Zc()}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
- ${C}\u21C5 Watch stopped${m}`),I()},$=y,process.on("SIGINT",y),process.on("SIGTERM",$)}),{watchers:l}}function gE(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 yE(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 wE(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function kr(){return new Date().toLocaleTimeString()}function EE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new _i.InvalidArgumentError(`${r} must be a positive number.`);return t}}function RE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new _i.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function tu(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",EE("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",RE("--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 hE([{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 Ci=require("child_process");var $E=200;function bE(r){return new Promise(e=>setTimeout(e,r))}function ru(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,Ci.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 SE(){if(process.platform==="win32")return[];let r;try{r=(0,Ci.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 vE(){let r=[],e=[],t=new Set,n=await xi();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let s=ru(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}for(let i of SE()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let s=ru(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}return r.length>0&&(await bE($E),await xi()),{stopped:r,failed:e}}function xE(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 nu(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await vE();xE(e)})}function iu(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");tu(e),nu(e)}function su(r){let e=r.command("realm").description("Manage realms on the realm server");sc(e),cc(e),kc(e),_c(e),Oc(e),Lc(e),Ic(e),Dc(e);let t=Gc(e);qc(t),Wc(e),iu(e)}async function kE(r,e,t){let n=t?.profileManager??_();if(!n.getActiveProfile())return{ok:!1,error:L};if(F(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let s=new URL(e,k(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 ou(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 kE(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 Oi(r,e,t){let n=t?.profileManager??_();if(!n.getActiveProfile())return{ok:!1,error:L};let s=new URL(e,k(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 au(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 Oi(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 Pi="// touched for re-index";async function _E(r,e,t){let n=t?.profileManager??_();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:L};let s;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await 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"))&&!F(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(F(l)){a.push({path:l,reason:"protected file"});continue}let c=await Oi(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")?CE(c.content):PE(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 CE(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 OE(r)}function OE(r){return r.endsWith(`
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 _e(this.options.localDir,i)}};function zc(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 $E(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 $E(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 bi({error:o.error});n=o.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return bi({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Je(r))return bi({error:`Local directory does not exist: ${r}`});let s;try{s=new $i({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?SE(s):void 0}}function SE(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 bi(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var Xc=T(kt());function vE(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Xc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function xE(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:P};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 Kc(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)",vE).action(async e=>{let t;try{t=await xE(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 Oi=T(kt()),au=T(require("fs/promises")),_r=T(require("path"));var Ce=T(require("fs/promises")),Qc=T(require("path")),kE=".boxel-watch.lock";function Si(r){return Qc.join(r,kE)}function vi(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function _E(r){try{let e=await Ce.readFile(Si(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 Zc(r,e){await Ce.mkdir(r,{recursive:!0});let t=await _E(r),n=!1;if(t&&vi(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Ce.writeFile(Si(r),JSON.stringify(i,null,2)+`
108
+ `),{ok:!0,staleOverwrote:n}}async function kr(r){try{await Ce.unlink(Si(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var Oe=T(require("fs/promises")),eu=T(require("os")),xi=T(require("path"));function tu(){return xi.join(eu.homedir(),".boxel-cli")}function ru(){return xi.join(tu(),"watch-processes.json")}async function nu(){try{let r=await Oe.readFile(ru(),"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 ki(r){await Oe.mkdir(tu(),{recursive:!0});let e=ru(),t=`${e}.${process.pid}.tmp`;await Oe.writeFile(t,JSON.stringify(r,null,2)+`
109
+ `),await Oe.rename(t,e)}async function iu(){let r=await nu(),e=r.processes.filter(t=>vi(t.pid));return e.length!==r.processes.length&&await ki({processes:e}),{processes:e}}async function su(r){let t=(await iu()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await ki({processes:t})}async function ou(){let r=await nu(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await ki({processes:e})}async function _i(){return(await iu()).processes}var Ci=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=TE(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=_r.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 au.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=_r.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 _e(this.options.localDir,a)}};async function CE(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 Zc(p.localDir,p.realmUrl);if(!y.ok){for(let R of a)await kr(R);return{watchers:[],error:OE(p.localDir,y.existing)}}y.staleOverwrote&&!i&&console.log(`${g}[${Cr()}] overwrote stale lock at ${p.localDir}${m}`),a.push(p.localDir)}let l=[];for(let p of r){let y=new Ci(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 kr(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}[${Cr()}]${m} [${p.name}] ${A}\u26A1 ${p.pendingCount} change(s) detected${m}`),p.scheduleFlush(R=>{i||PE(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 su(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 Z of l)Z.shutdown();y&&process.off("SIGINT",y),R&&process.off("SIGTERM",R);for(let Z of a)try{await kr(Z)}catch{}try{await ou()}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 OE(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 ${_r.join(r,".boxel-watch.lock")} if it's stale.`}function PE(r,e){let t=e.pulled.length+e.deleted.length;if(t>0&&(console.log(`${g}[${Cr()}]${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}[${Cr()}]${m} [${r}] ${A}\u26A0 skipped ${n}: local diverges from sync manifest (rerun with --overwrite-local to discard, or \`boxel realm sync\` to reconcile)${m}`)}function TE(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function Cr(){return new Date().toLocaleTimeString()}function AE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new Oi.InvalidArgumentError(`${r} must be a positive number.`);return t}}function LE(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new Oi.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function lu(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",AE("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",LE("--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 CE([{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 Pi=require("child_process");var ME=200;function IE(r){return new Promise(e=>setTimeout(e,r))}function cu(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,Pi.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 NE(){if(process.platform==="win32")return[];let r;try{r=(0,Pi.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 FE(){let r=[],e=[],t=new Set,n=await _i();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let s=cu(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}for(let i of NE()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let s=cu(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}return r.length>0&&(await IE(ME),await _i()),{stopped:r,failed:e}}function DE(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 uu(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await FE();DE(e)})}function fu(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");lu(e),uu(e)}function mu(r){let e=r.command("realm").description("Manage realms on the realm server");ac(e),fc(e),Cc(e),Oc(e),Tc(e),Nc(e),jc(e),Gc(e),Wc(e);let t=zc(e);Jc(t),Ac(e),Kc(e),fu(e)}async function UE(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,error:P};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 du(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 UE(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 Ti(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,error:P};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 pu(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 Ti(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 Ai="// touched for re-index";async function jE(r,e,t){let n=t?.profileManager??C();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:P};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 Ie(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 Ti(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")?qE(c.content):HE(c.content),f=await dt(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 qE(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 GE(r)}function GE(r){return r.endsWith(`
115
115
 
116
116
  `)?r.slice(0,-1):r+`
117
- `}function PE(r){let e=`
118
- ${Pi}
117
+ `}function HE(r){let e=`
118
+ ${Ai}
119
119
  `;return r.endsWith(e)?r.slice(0,-e.length)+`
120
120
  `:r.endsWith(`
121
- `)?r+Pi+`
121
+ `)?r+Ai+`
122
122
  `:r+`
123
- `+Pi+`
124
- `}function lu(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 _E(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 cu(r){let e=r.command("file").description("Read, write, and manage files in a realm");ou(e),zl(e),Xl(e),au(e),lu(e),Jl(e)}async function TE(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 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 uu(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 TE(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} ${AE(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 AE(r){switch(r){case"ready":return S;case"error":return h;default:return C}}var fu=require("node:child_process"),wt=require("node:fs"),mu=require("node:http"),q=require("node:path");async function LE(){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 ME(r,e){let t=e?.profileManager??_(),n=t.getActiveProfile();if(!n)return Ti(L);let i=k(r),s=k(e?.hostAppUrl??n.profile.realmServerUrl),o;try{let a=await Me(i,{profileManager:t});if(a.error)return Ti(`Failed to discover test files: ${a.error}`);o=a.filenames.filter(l=>l.endsWith(".test.gts"))}catch(a){return Ti(`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 IE({pm:t,targetRealm:i,hostAppUrl:s,hostDistDir:e?.hostDistDir,debug:e?.debug});return{...jE(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 IE(r){let e=Date.now(),t,n;try{let i=r.hostDistDir??(0,q.join)(FE()??(0,q.join)((0,q.resolve)(mt(__dirname),".."),"host"),"dist");if(!du((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 DE(i);n=o;let l=NE({assetServerUrl:s,hostDistDir:i,realmProxyUrl:r.hostAppUrl});a(l),t=await(await LE()).launch({headless:!0});let u=await t.newPage();r.debug&&(u.on("console",$=>{process.stderr.write(`[browser ${$.type()}] ${$.text()}
126
- `)}),u.on("pageerror",$=>{process.stderr.write(`[browser pageerror] ${$.message}
127
- `)}));let f=r.pm.getRealmToken(r.targetRealm);if(f){let $=new URL(r.targetRealm).origin;await u.route(`${$}/**`,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 NE(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>
123
+ `+Ai+`
124
+ `}function hu(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 jE(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 gu(r){let e=r.command("file").description("Read, write, and manage files in a realm");du(e),Ql(e),Kl(e),pu(e),hu(e),Xl(e)}async function WE(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 yu(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 WE(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} ${VE(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 VE(r){switch(r){case"ready":return S;case"error":return h;default:return _}}var wu=require("node:child_process"),bt=require("node:fs"),Eu=require("node:http"),q=require("node:path");async function BE(){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 YE(r,e){let t=e?.profileManager??C(),n=t.getActiveProfile();if(!n)return Li(P);let i=x(r),s=x(e?.hostAppUrl??n.profile.realmServerUrl),o;try{let a=await Ie(i,{profileManager:t});if(a.error)return Li(`Failed to discover test files: ${a.error}`);o=a.filenames.filter(l=>l.endsWith(".test.gts"))}catch(a){return Li(`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 JE({pm:t,targetRealm:i,hostAppUrl:s,hostDistDir:e?.hostDistDir,debug:e?.debug});return{...ZE(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 JE(r){let e=Date.now(),t,n;try{let i=r.hostDistDir??(0,q.join)(KE()??(0,q.join)((0,q.resolve)(pt(__dirname),".."),"host"),"dist");if(!bu((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 XE(i);n=o;let l=zE({assetServerUrl:s,hostDistDir:i,realmProxyUrl:r.hostAppUrl});a(l),t=await(await BE()).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 Z={...I.request().headers(),Authorization:f};I.continue({headers:Z})})}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 zE(r){let e=r.assetServerUrl.replace(/\/$/,""),t=r.realmProxyUrl.replace(/\/$/,""),n=(0,q.resolve)(r.hostDistDir,"tests","index.html"),i;try{i=(0,bt.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 DE(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,mu.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 du(r){try{return(0,wt.statSync)(r).isFile()}catch{return!1}}function FE(){let r=mt(__dirname),e=(0,q.resolve)(r,".."),t=(0,q.resolve)(e,".."),n=(0,q.join)(e,"host"),i=UE(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),du((0,q.join)(l,"dist","index.html"))))return l}function UE(r){let e=(0,fu.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 jE(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 Ti(r){return{status:"error",passedCount:0,failedCount:0,skippedCount:0,durationMs:0,testFiles:[],failures:[],errorMessage:r}}function pu(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 ME(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(`
175
+ </html>`}async function XE(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,Eu.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,bt.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 bu(r){try{return(0,bt.statSync)(r).isFile()}catch{return!1}}function KE(){let r=pt(__dirname),e=(0,q.resolve)(r,".."),t=(0,q.resolve)(e,".."),n=(0,q.join)(e,"host"),i=QE(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),bu((0,q.join)(l,"dist","index.html"))))return l}function QE(r){let e=(0,wu.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 ZE(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 Li(r){return{status:"error",passedCount:0,failedCount:0,skippedCount:0,durationMs:0,testFiles:[],failures:[],errorMessage:r}}function Ru(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 YE(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 gu(r){let e=new hu.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),Vl(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",`
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 Su(r){let e=new $u.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&&lr(!0),Yl(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 ql(t,n,i)}),cu(e),Kl(e),nc(e),su(e),uu(e),Ql(e),pu(e),ic(e),Bl(e),e}var qE=JSON.parse((0,yu.readFileSync)((0,wu.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&or(!0);gu(qE.version).parse();
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 Hl(t,n,i)}),gu(e),Zl(e),sc(e),mu(e),yu(e),ec(e),Ru(e),oc(e),Jl(e),e}var eb=JSON.parse((0,vu.readFileSync)((0,xu.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&lr(!0);Su(eb.version).parse();
187
187
  /*! Bundled license information:
188
188
 
189
189
  safe-buffer/index.js: