@cardstack/boxel-cli 0.1.4 → 0.2.0-unstable.294

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,124 +1,130 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Sc=Object.create;var Zn=Object.defineProperty;var xc=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Oc=Object.getPrototypeOf,kc=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Cc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _c(e))!kc.call(r,i)&&i!==t&&Zn(r,i,{get:()=>e[i],enumerable:!(n=xc(e,i))||n.enumerable});return r};var P=(r,e,t)=>(t=r!=null?Sc(Oc(r)):{},Cc(e||!r||!r.__esModule?Zn(t,"default",{value:r,enumerable:!0}):t,r));var ei=h((nE,Ac)=>{Ac.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var si=h((iE,ce)=>{var ir=require("fs"),st=require("path"),Tc=require("os"),Pc=require("crypto"),Lc=ei(),sr=Lc.version,Ic=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Nc(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
3
- `);let n;for(;(n=Ic.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 Mc(r){r=r||{};let e=ii(r);r.path=e;let t=j.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=Dc(t,a);s=j.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=i)throw a}return j.parse(s)}function Fc(r){console.log(`[dotenv@${sr}][WARN] ${r}`)}function Fe(r){console.log(`[dotenv@${sr}][DEBUG] ${r}`)}function ri(r){console.log(`[dotenv@${sr}] ${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 Dc(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 ii(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)ir.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=st.resolve(process.cwd(),".env.vault");return ir.existsSync(e)?e:null}function ti(r){return r[0]==="~"?st.join(Tc.homedir(),r.slice(1)):r}function Uc(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&ri("Loading env from encrypted .env.vault");let n=j._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),j.populate(i,n,r),{parsed:n}}function jc(r){let e=st.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&&Fe("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[ti(r.path)];else{s=[];for(let u of r.path)s.push(ti(u))}let o,a={};for(let u of s)try{let c=j.parse(ir.readFileSync(u,{encoding:t}));j.populate(a,c,r)}catch(c){n&&Fe(`Failed to load ${u} ${c.message}`),o=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),j.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let f of s)try{let d=st.relative(process.cwd(),f);c.push(d)}catch(d){n&&Fe(`Failed to load ${f} ${d.message}`),o=d}ri(`injecting env (${u}) from ${c.join(",")}`)}return o?{parsed:a,error:o}:{parsed:a}}function qc(r){if(ni(r).length===0)return j.configDotenv(r);let e=ii(r);return e?j._configVault(r):(Fc(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),j.configDotenv(r))}function Vc(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=Pc.createDecipheriv("aes-256-gcm",t,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw o}}function Gc(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&&Fe(i===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):r[s]=e[s]}var j={configDotenv:jc,_configVault:Uc,_parseVault:Mc,config:qc,decrypt:Vc,parse:Nc,populate:Gc};ce.exports.configDotenv=j.configDotenv;ce.exports._configVault=j._configVault;ce.exports._parseVault=j._parseVault;ce.exports.config=j.config;ce.exports.decrypt=j.decrypt;ce.exports.parse=j.parse;ce.exports.populate=j.populate;ce.exports=j});var ai=h((sE,oi)=>{var be={};process.env.DOTENV_CONFIG_ENCODING!=null&&(be.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(be.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(be.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(be.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(be.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(be.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);oi.exports=be});var ci=h((oE,li)=>{var Hc=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;li.exports=function(e){let t=e.reduce(function(n,i){let s=i.match(Hc);return s&&(n[s[1]]=s[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var De=h(ar=>{var ot=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 ot{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ar.CommanderError=ot;ar.InvalidArgumentError=or});var at=h(cr=>{var{InvalidArgumentError:Wc}=De(),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 Wc(`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 Bc(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}cr.Argument=lr;cr.humanReadableArgName=Bc});var mr=h(fr=>{var{humanReadableArgName:Yc}=at(),ur=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=>Yc(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(i)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(i)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,i)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(i)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let i=e.parent;i;i=i.parent)n=i.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),i=t.helpWidth??80;function s(f,d){return t.formatItem(f,n,d,t)}let o=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(o=o.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(f=>s(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));l.length>0&&(o=o.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(f=>s(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(u.length>0&&(o=o.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(d=>s(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));f.length>0&&(o=o.concat([t.styleTitle("Global Options:"),...f,""]))}let c=t.visibleCommands(e).map(f=>s(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return c.length>0&&(o=o.concat([t.styleTitle("Commands:"),...c,""])),o.join(`
5
- `)}displayWidth(e){return ui(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,n,i){let o=" ".repeat(2);if(!n)return o+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),l=2,c=(this.helpWidth??80)-t-l-2,f;return c<this.minWidthToWrap||i.preformatted(n)?f=n:f=i.boxWrap(n,c).replace(/\n/g,`
6
- `+" ".repeat(t+l)),o+a+" ".repeat(l)+f.replace(/\n/g,`
7
- ${o}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,s=[];return n.forEach(o=>{let a=o.match(i);if(a===null){s.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let f=this.displayWidth(c);if(u+f<=t){l.push(c),u+=f;return}s.push(l.join(""));let d=c.trimStart();l=[d],u=this.displayWidth(d)}),s.push(l.join(""))}),s.join(`
8
- `)}};function ui(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}fr.Help=ur;fr.stripColor=ui});var gr=h(hr=>{var{InvalidArgumentError:Xc}=De(),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=zc(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new Xc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?fi(this.name().replace(/^no-/,"")):fi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},pr=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 fi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function zc(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}
2
+ "use strict";var Hc=Object.create;var mi=Object.defineProperty;var Wc=Object.getOwnPropertyDescriptor;var Bc=Object.getOwnPropertyNames;var Yc=Object.getPrototypeOf,Xc=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var zc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bc(e))!Xc.call(r,i)&&i!==t&&mi(r,i,{get:()=>e[i],enumerable:!(n=Wc(e,i))||n.enumerable});return r};var O=(r,e,t)=>(t=r!=null?Hc(Yc(r)):{},zc(e||!r||!r.__esModule?mi(t,"default",{value:r,enumerable:!0}):t,r));var di=g((Xw,Jc)=>{Jc.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 wi=g((zw,pe)=>{var dr=require("fs"),dt=require("path"),Kc=require("os"),Qc=require("crypto"),Zc=di(),pr=Zc.version,eu=/(?:^|^)\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=eu.exec(t))!=null;){let i=n[1],o=n[2]||"";o=o.trim();let s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),s==='"'&&(o=o.replace(/\\n/g,`
4
+ `),o=o.replace(/\\r/g,"\r")),e[i]=o}return e}function ru(r){r=r||{};let e=yi(r);r.path=e;let t=j.configDotenv(r);if(!t.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let n=gi(r).split(","),i=n.length,o;for(let s=0;s<i;s++)try{let a=n[s].trim(),l=iu(t,a);o=j.decrypt(l.ciphertext,l.key);break}catch(a){if(s+1>=i)throw a}return j.parse(o)}function nu(r){console.log(`[dotenv@${pr}][WARN] ${r}`)}function He(r){console.log(`[dotenv@${pr}][DEBUG] ${r}`)}function hi(r){console.log(`[dotenv@${pr}] ${r}`)}function gi(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 iu(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 o=`DOTENV_VAULT_${i.toUpperCase()}`,s=r.parsed[o];if(!s){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:s,key:n}}function yi(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)dr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=dt.resolve(process.cwd(),".env.vault");return dr.existsSync(e)?e:null}function pi(r){return r[0]==="~"?dt.join(Kc.homedir(),r.slice(1)):r}function ou(r){let e=!!(r&&r.debug),t=r&&"quiet"in r?r.quiet:!0;(e||!t)&&hi("Loading env from encrypted .env.vault");let n=j._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),j.populate(i,n,r),{parsed:n}}function su(r){let e=dt.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&&He("No encoding is specified. UTF-8 is used by default");let o=[e];if(r&&r.path)if(!Array.isArray(r.path))o=[pi(r.path)];else{o=[];for(let u of r.path)o.push(pi(u))}let s,a={};for(let u of o)try{let c=j.parse(dr.readFileSync(u,{encoding:t}));j.populate(a,c,r)}catch(c){n&&He(`Failed to load ${u} ${c.message}`),s=c}let l=process.env;if(r&&r.processEnv!=null&&(l=r.processEnv),j.populate(l,a,r),n||!i){let u=Object.keys(a).length,c=[];for(let m of o)try{let d=dt.relative(process.cwd(),m);c.push(d)}catch(d){n&&He(`Failed to load ${m} ${d.message}`),s=d}hi(`injecting env (${u}) from ${c.join(",")}`)}return s?{parsed:a,error:s}:{parsed:a}}function au(r){if(gi(r).length===0)return j.configDotenv(r);let e=yi(r);return e?j._configVault(r):(nu(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),j.configDotenv(r))}function lu(r,e){let t=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(r,"base64"),i=n.subarray(0,12),o=n.subarray(-16);n=n.subarray(12,-16);try{let s=Qc.createDecipheriv("aes-256-gcm",t,i);return s.setAuthTag(o),`${s.update(n)}${s.final()}`}catch(s){let a=s instanceof RangeError,l=s.message==="Invalid key length",u=s.message==="Unsupported state or unable to authenticate data";if(a||l){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(u){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw s}}function cu(r,e,t={}){let n=!!(t&&t.debug),i=!!(t&&t.override);if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(r,o)?(i===!0&&(r[o]=e[o]),n&&He(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):r[o]=e[o]}var j={configDotenv:su,_configVault:ou,_parseVault:ru,config:au,decrypt:lu,parse:tu,populate:cu};pe.exports.configDotenv=j.configDotenv;pe.exports._configVault=j._configVault;pe.exports._parseVault=j._parseVault;pe.exports.config=j.config;pe.exports.decrypt=j.decrypt;pe.exports.parse=j.parse;pe.exports.populate=j.populate;pe.exports=j});var $i=g((Jw,Ei)=>{var xe={};process.env.DOTENV_CONFIG_ENCODING!=null&&(xe.encoding=process.env.DOTENV_CONFIG_ENCODING);process.env.DOTENV_CONFIG_PATH!=null&&(xe.path=process.env.DOTENV_CONFIG_PATH);process.env.DOTENV_CONFIG_QUIET!=null&&(xe.quiet=process.env.DOTENV_CONFIG_QUIET);process.env.DOTENV_CONFIG_DEBUG!=null&&(xe.debug=process.env.DOTENV_CONFIG_DEBUG);process.env.DOTENV_CONFIG_OVERRIDE!=null&&(xe.override=process.env.DOTENV_CONFIG_OVERRIDE);process.env.DOTENV_CONFIG_DOTENV_KEY!=null&&(xe.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY);Ei.exports=xe});var Ri=g((Kw,bi)=>{var uu=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;bi.exports=function(e){let t=e.reduce(function(n,i){let o=i.match(uu);return o&&(n[o[1]]=o[2]),n},{});return"quiet"in t||(t.quiet="true"),t}});var We=g(gr=>{var pt=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}},hr=class extends pt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};gr.CommanderError=pt;gr.InvalidArgumentError=hr});var ht=g(wr=>{var{InvalidArgumentError:fu}=We(),yr=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 fu(`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 mu(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}wr.Argument=yr;wr.humanReadableArgName=mu});var br=g($r=>{var{humanReadableArgName:du}=ht(),Er=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,o)=>i.name().localeCompare(o.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),o=n.long&&e._findOption(n.long);!i&&!o?t.push(n):n.long&&!o?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(o=>!o.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=>du(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 o(m,d){return t.formatItem(m,n,d,t)}let s=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],a=t.commandDescription(e);a.length>0&&(s=s.concat([t.boxWrap(t.styleCommandDescription(a),i),""]));let l=t.visibleArguments(e).map(m=>o(t.styleArgumentTerm(t.argumentTerm(m)),t.styleArgumentDescription(t.argumentDescription(m))));l.length>0&&(s=s.concat([t.styleTitle("Arguments:"),...l,""]));let u=t.visibleOptions(e).map(m=>o(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));if(u.length>0&&(s=s.concat([t.styleTitle("Options:"),...u,""])),t.showGlobalOptions){let m=t.visibleGlobalOptions(e).map(d=>o(t.styleOptionTerm(t.optionTerm(d)),t.styleOptionDescription(t.optionDescription(d))));m.length>0&&(s=s.concat([t.styleTitle("Global Options:"),...m,""]))}let c=t.visibleCommands(e).map(m=>o(t.styleSubcommandTerm(t.subcommandTerm(m)),t.styleSubcommandDescription(t.subcommandDescription(m))));return c.length>0&&(s=s.concat([t.styleTitle("Commands:"),...c,""])),s.join(`
5
+ `)}displayWidth(e){return Si(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 s=" ".repeat(2);if(!n)return s+e;let a=e.padEnd(t+e.length-i.displayWidth(e)),l=2,c=(this.helpWidth??80)-t-l-2,m;return c<this.minWidthToWrap||i.preformatted(n)?m=n:m=i.boxWrap(n,c).replace(/\n/g,`
6
+ `+" ".repeat(t+l)),s+a+" ".repeat(l)+m.replace(/\n/g,`
7
+ ${s}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let n=e.split(/\r\n|\n/),i=/[\s]*[^\s]+/g,o=[];return n.forEach(s=>{let a=s.match(i);if(a===null){o.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(c=>{let m=this.displayWidth(c);if(u+m<=t){l.push(c),u+=m;return}o.push(l.join(""));let d=c.trimStart();l=[d],u=this.displayWidth(d)}),o.push(l.join(""))}),o.join(`
8
+ `)}};function Si(r){let e=/\x1b\[\d*(;\d*)*m/g;return r.replace(e,"")}$r.Help=Er;$r.stripColor=Si});var xr=g(vr=>{var{InvalidArgumentError:pu}=We(),Rr=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=hu(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 pu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?vi(this.name().replace(/^no-/,"")):vi(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Sr=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,o=i!==void 0?i:!1;return t.negate===(o===e)}};function vi(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function hu(r){let e,t,n=/^-[^-]$/,i=/^--[^-]/,o=r.split(/[ |,]+/).concat("guard");if(n.test(o[0])&&(e=o.shift()),i.test(o[0])&&(t=o.shift()),!e&&n.test(o[0])&&(e=o.shift()),!e&&i.test(o[0])&&(e=t,t=o.shift()),o[0].startsWith("-")){let s=o[0],a=`option creation failed due to '${s}' in option flags '${r}'`;throw/^-[^-][^-]/.test(s)?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
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
12
- - too many short flags`):i.test(o)?new Error(`${a}
11
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(s)?new Error(`${a}
12
+ - too many short flags`):i.test(s)?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}}hr.Option=dr;hr.DualOptions=pr});var di=h(mi=>{function Jc(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 Kc(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=Jc(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}}vr.Option=Rr;vr.DualOptions=Sr});var _i=g(xi=>{function gu(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 o=1;r[i-1]===e[n-1]?o=0:o=1,t[i][n]=Math.min(t[i-1][n]+1,t[i][n-1]+1,t[i-1][n-1]+o),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(s=>s.slice(2)));let n=[],i=3,o=.4;return e.forEach(s=>{if(s.length<=1)return;let a=gu(r,s),l=Math.max(r.length,s.length);(l-a)/l>o&&(a<i?(i=a,n=[s]):a===i&&n.push(s))}),n.sort((s,a)=>s.localeCompare(a)),t&&(n=n.map(s=>`--${s}`)),n.length>1?`
15
15
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
16
- (Did you mean ${n[0]}?)`:""}mi.suggestSimilar=Kc});var yi=h(Rr=>{var Qc=require("node:events").EventEmitter,yr=require("node:child_process"),ue=require("node:path"),lt=require("node:fs"),A=require("node:process"),{Argument:Zc,humanReadableArgName:eu}=at(),{CommanderError:Er}=De(),{Help:tu,stripColor:ru}=mr(),{Option:pi,DualOptions:nu}=gr(),{suggestSimilar:hi}=di(),wr=class r extends Qc{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:()=>br()??(A.stdout.isTTY&&A.stdout.hasColors?.()),getErrHasColors:()=>br()??(A.stderr.isTTY&&A.stderr.hasColors?.()),stripColor:t=>ru(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 tu,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 Zc(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 Er(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 pi(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 pi)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof i=="function")o.default(s).argParser(i);else if(i instanceof RegExp){let a=i;i=(l,u)=>{let c=a.exec(l);return c?c[0]:u},o.default(s).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){A.versions?.electron&&(t.from="electron");let i=A.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=A.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":A.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){this._prepareForParse();let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
20
- - 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(lt.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]}?)`:""}xi.suggestSimilar=yu});var Ai=g(Ar=>{var wu=require("node:events").EventEmitter,_r=require("node:child_process"),he=require("node:path"),gt=require("node:fs"),T=require("node:process"),{Argument:Eu,humanReadableArgName:$u}=ht(),{CommanderError:kr}=We(),{Help:bu,stripColor:Ru}=br(),{Option:ki,DualOptions:Su}=xr(),{suggestSimilar:Oi}=_i(),Or=class r extends wu{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=>T.stdout.write(t),writeErr:t=>T.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,getOutHasColors:()=>Cr()??(T.stdout.isTTY&&T.stdout.hasColors?.()),getErrHasColors:()=>Cr()??(T.stderr.isTTY&&T.stderr.hasColors?.()),stripColor:t=>Ru(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,o=n;typeof i=="object"&&i!==null&&(o=i,i=null),o=o||{};let[,s,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(s);return i&&(l.description(i),l._executableHandler=!0),o.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(o.noHelp||o.hidden),l._executableFile=o.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 bu,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 Eu(e,t)}argument(e,t,n,i){let o=this.createArgument(e,t);return typeof n=="function"?o.default(i).argParser(n):o.default(n),this.addArgument(o),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(/([^ ]+) *(.*)/),o=t??"display help for command",s=this.createCommand(n);return s.helpOption(!1),i&&s.arguments(i),o&&s.description(o),this._addImplicitHelpCommand=!0,this._helpCommand=s,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 kr(e,t,n)),T.exit(e)}action(e){let t=n=>{let i=this.registeredArguments.length,o=n.slice(0,i);return this._storeOptionsAsProperties?o[i]=this:o[i]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new ki(e,t)}_callParseArg(e,t,n,i){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${i} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_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("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' 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 o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let i=(o,s,a)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let l=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,l,s):o!==null&&e.variadic&&(o=e._concatValue(o,l)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,a)};return this.on("option:"+t,o=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;i(o,s,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;i(o,s,"env")}),this}_optionEx(e,t,n,i,o){if(typeof t=="object"&&t instanceof ki)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,n);if(s.makeOptionMandatory(!!e.mandatory),typeof i=="function")s.default(o).argParser(i);else if(i instanceof RegExp){let a=i;i=(l,u)=>{let c=a.exec(l);return c?c[0]:u},s.default(o).argParser(i)}else s.default(i);return this.addOption(s)}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){T.versions?.electron&&(t.from="electron");let i=T.execArgv??[];(i.includes("-e")||i.includes("--eval")||i.includes("-p")||i.includes("--print"))&&(t.from="eval")}e===void 0&&(e=T.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":T.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(gt.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",o=`'${e}' does not exist
21
21
  - if '${n}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
22
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
- - ${i}`;throw new Error(s)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,f){let d=ue.resolve(c,f);if(lt.existsSync(d))return d;if(i.includes(ue.extname(f)))return;let p=i.find(E=>lt.existsSync(`${d}${E}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=lt.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=ue.resolve(ue.dirname(c),a)}if(a){let c=s(a,o);if(!c&&!e._executableFile&&this._scriptPath){let f=ue.basename(this._scriptPath,ue.extname(this._scriptPath));f!==this._name&&(c=s(a,`${f}-${e._name}`))}o=c||o}n=i.includes(ue.extname(o));let l;A.platform!=="win32"?n?(t.unshift(o),t=gi(A.execArgv).concat(t),l=yr.spawn(A.argv[0],t,{stdio:"inherit"})):l=yr.spawn(o,t,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,e._name),t.unshift(o),t=gi(A.execArgv).concat(t),l=yr.spawn(A.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{A.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new Er(c,"commander.executeSubCommandAsync","(close)")):A.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(o,a,e._name);else if(c.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)A.exit(1);else{let f=new Er(1,"commander.executeSubCommandAsync","(error)");f.nestedError=c,u(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,i,"preSubcommand"),s=this._chainOrCall(s,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,i,s)=>{let o=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,i,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let s=n.defaultValue;n.variadic?i<this.args.length?(s=this.args.slice(i),n.parseArg&&(s=s.reduce((o,a)=>e(n,a,o),n.defaultValue))):s===void 0&&(s=[]):i<this.args.length&&(s=this.args[i],n.parseArg&&(s=e(n,s,n.defaultValue))),t[i]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,i=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{i.push({hookedCommand:s,callback:o})})}),t==="postAction"&&i.reverse(),i.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{i=this._chainOrCall(i,()=>s(this,t))}),i}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(s,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(s))i(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(i(),this._processArguments())}else this.commands.length?(i(),this.help({error:!0})):(i(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let i=n.attributeName();return this.getOptionValue(i)===void 0?!1:this.getOptionValueSource(i)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let i=e.find(s=>n.conflictsWith.includes(s.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,s=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;s.length;){let l=s.shift();if(l==="--"){i===n&&i.push(l),i.push(...s);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let u=this._findOption(l);if(u){if(u.required){let c=s.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;s.length>0&&!o(s[0])&&(c=s.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(o(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(l),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){i.push(l),s.length>0&&i.push(...s);break}i.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let i=this.options[n].attributeName();e[i]=i===this._versionOptionName?this._version:this[i]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
23
+ - ${i}`;throw new Error(o)}_executeSubCommand(e,t){t=t.slice();let n=!1,i=[".js",".ts",".tsx",".mjs",".cjs"];function o(c,m){let d=he.resolve(c,m);if(gt.existsSync(d))return d;if(i.includes(he.extname(m)))return;let p=i.find(w=>gt.existsSync(`${d}${w}`));if(p)return`${d}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let c;try{c=gt.realpathSync(this._scriptPath)}catch{c=this._scriptPath}a=he.resolve(he.dirname(c),a)}if(a){let c=o(a,s);if(!c&&!e._executableFile&&this._scriptPath){let m=he.basename(this._scriptPath,he.extname(this._scriptPath));m!==this._name&&(c=o(a,`${m}-${e._name}`))}s=c||s}n=i.includes(he.extname(s));let l;T.platform!=="win32"?n?(t.unshift(s),t=Ci(T.execArgv).concat(t),l=_r.spawn(T.argv[0],t,{stdio:"inherit"})):l=_r.spawn(s,t,{stdio:"inherit"}):(this._checkForMissingExecutable(s,a,e._name),t.unshift(s),t=Ci(T.execArgv).concat(t),l=_r.spawn(T.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{T.on(m,()=>{l.killed===!1&&l.exitCode===null&&l.kill(m)})});let u=this._exitCallback;l.on("close",c=>{c=c??1,u?u(new kr(c,"commander.executeSubCommandAsync","(close)")):T.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT")this._checkForMissingExecutable(s,a,e._name);else if(c.code==="EACCES")throw new Error(`'${s}' not executable`);if(!u)T.exit(1);else{let m=new kr(1,"commander.executeSubCommandAsync","(error)");m.nestedError=c,u(m)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let i=this._findCommand(e);i||this.help({error:!0}),i._prepareForParse();let o;return o=this._chainOrCallSubCommandHook(o,i,"preSubcommand"),o=this._chainOrCall(o,()=>{if(i._executableHandler)this._executeSubCommand(i,t.concat(n));else return i._parseCommand(t,n)}),o}_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,o)=>{let s=i;if(i!==null&&n.parseArg){let a=`error: command-argument value '${i}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,i,o,a)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,i)=>{let o=n.defaultValue;n.variadic?i<this.args.length?(o=this.args.slice(i),n.parseArg&&(o=o.reduce((s,a)=>e(n,a,s),n.defaultValue))):o===void 0&&(o=[]):i<this.args.length&&(o=this.args[i],n.parseArg&&(o=e(n,o,n.defaultValue))),t[i]=o}),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(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(s=>{i.push({hookedCommand:o,callback:s})})}),t==="postAction"&&i.reverse(),i.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let i=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{i=this._chainOrCall(i,()=>o(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])},o=`command:${this.name()}`;if(this._actionHandler){i(),this._processArguments();let s;return s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent&&(s=this._chainOrCall(s,()=>{this.parent.emit(o,e,t)})),s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(o))i(),this._processArguments(),this.parent.emit(o,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(o=>n.conflictsWith.includes(o.attributeName()));i&&this._conflictingOption(n,i)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],i=t,o=e.slice();function s(l){return l.length>1&&l[0]==="-"}let a=null;for(;o.length;){let l=o.shift();if(l==="--"){i===n&&i.push(l),i.push(...o);break}if(a&&!s(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,s(l)){let u=this._findOption(l);if(u){if(u.required){let c=o.shift();c===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;o.length>0&&!s(o[0])&&(c=o.shift()),this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),o.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),c=this._findOption(l.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(u+1));continue}}if(s(l)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(l),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){i.push(l),o.length>0&&i.push(...o);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 nu(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(i=>!t(i)).forEach(i=>{this.setOptionValueWithSource(i,n.implied[i],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),u=this.options.find(f=>f.negate&&a===f.attributeName()),c=this.options.find(f=>!f.negate&&a===f.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||o},i=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);i=i.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=hi(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=hi(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=>eu(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=ue.basename(e,ue.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),n=this._getOutputContext(e);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let i=t.formatHelp(this,t);return n.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){e=e||{};let t=!!e.error,n,i,s;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:s}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getOutputContext(e),i={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation({error:n.error});if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(A.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
28
- 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 gi(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 br(){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}Rr.Command=wr;Rr.useColor=br});var ct=h(Q=>{var{Argument:Ei}=at(),{Command:$r}=yi(),{CommanderError:iu,InvalidArgumentError:wi}=De(),{Help:su}=mr(),{Option:bi}=gr();Q.program=new $r;Q.createCommand=r=>new $r(r);Q.createOption=(r,e)=>new bi(r,e);Q.createArgument=(r,e)=>new Ei(r,e);Q.Command=$r;Q.Option=bi;Q.Argument=Ei;Q.Help=su;Q.CommanderError=iu;Q.InvalidArgumentError=wi;Q.InvalidOptionArgumentError=wi});var Oe=h((vr,$i)=>{var ut=require("buffer"),se=ut.Buffer;function Ri(r,e){for(var t in r)e[t]=r[t]}se.from&&se.alloc&&se.allocUnsafe&&se.allocUnsafeSlow?$i.exports=ut:(Ri(ut,vr),vr.Buffer=Re);function Re(r,e,t){return se(r,e,t)}Re.prototype=Object.create(se.prototype);Ri(se,Re);Re.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return se(r,e,t)};Re.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=se(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};Re.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return se(r)};Re.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ut.SlowBuffer(r)}});var Sr=h((pE,vi)=>{var ft=Oe().Buffer,ou=require("stream"),au=require("util");function mt(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=ft.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=ft.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+")")}au.inherits(mt,ou);mt.prototype.write=function(e){this.buffer=ft.concat([this.buffer,ft.from(e)]),this.emit("data",e)};mt.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};vi.exports=mt});var xi=h((hE,Si)=>{"use strict";function xr(r){var e=(r/8|0)+(r%8===0?0:1);return e}var lu={ES256:xr(256),ES384:xr(384),ES512:xr(521)};function cu(r){var e=lu[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Si.exports=cu});var Pi=h((gE,Ti)=>{"use strict";var dt=Oe().Buffer,Oi=xi(),pt=128,ki=0,uu=32,fu=16,mu=2,Ci=fu|uu|ki<<6,ht=mu|ki<<6;function du(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ai(r){if(dt.isBuffer(r))return r;if(typeof r=="string")return dt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function pu(r,e){r=Ai(r);var t=Oi(e),n=t+1,i=r.length,s=0;if(r[s++]!==Ci)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(pt|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==ht)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++]!==ht)throw new Error('Could not find expected "int" for "s"');var u=r[s++];if(i-s!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-s)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=s;if(s+=u,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,d=t-u,p=dt.allocUnsafe(f+a+d+u);for(s=0;s<f;++s)p[s]=0;r.copy(p,s,l+Math.max(-f,0),l+a),s=t;for(var E=s;s<E+d;++s)p[s]=0;return r.copy(p,s,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=du(p),p}function _i(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=pt;return i&&--n,n}function hu(r,e){r=Ai(r);var t=Oi(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=_i(r,0,t),s=_i(r,t,r.length),o=t-i,a=t-s,l=2+o+1+1+a,u=l<pt,c=dt.allocUnsafe((u?2:3)+l),f=0;return c[f++]=Ci,u?c[f++]=l:(c[f++]=pt|1,c[f++]=l&255),c[f++]=ht,c[f++]=o,i<0?(c[f++]=0,f+=r.copy(c,f,0,t)):f+=r.copy(c,f,i,t),c[f++]=ht,c[f++]=a,s<0?(c[f++]=0,r.copy(c,f,t)):r.copy(c,f,t+s),c}Ti.exports={derToJose:pu,joseToDer:hu}});var Ii=h((yE,Li)=>{"use strict";var Ue=require("buffer").Buffer,_r=require("buffer").SlowBuffer;Li.exports=gt;function gt(r,e){if(!Ue.isBuffer(r)||!Ue.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}gt.install=function(){Ue.prototype.equal=_r.prototype.equal=function(e){return gt(this,e)}};var gu=Ue.prototype.equal,yu=_r.prototype.equal;gt.restore=function(){Ue.prototype.equal=gu,_r.prototype.equal=yu}});var Ar=h((EE,Gi)=>{var Ce=Oe().Buffer,Z=require("crypto"),Mi=Pi(),Ni=require("util"),Eu=`"%s" is not a valid algorithm.
26
+ `),this.outputHelp({error:!0}));let n=t||{},i=n.exitCode||1,o=n.code||"commander.error";this._exit(i,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in T.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()}`,T.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Su(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=s=>{let a=s.attributeName(),l=this.getOptionValue(a),u=this.options.find(m=>m.negate&&a===m.attributeName()),c=this.options.find(m=>!m.negate&&a===m.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:c||s},i=s=>{let a=n(s),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},o=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let i=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter(a=>a.long).map(a=>a.long);i=i.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);t=Oi(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",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let i=[];this.createHelp().visibleCommands(this).forEach(o=>{i.push(o.name()),o.alias()&&i.push(o.alias())}),t=Oi(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=>$u(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=he.basename(e,he.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,o;return t?(n=a=>this._outputConfiguration.writeErr(a),i=this._outputConfiguration.getErrHasColors(),o=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),i=this._outputConfiguration.getOutHasColors(),o=this._outputConfiguration.getOutHelpWidth()),{error:t,write:a=>(i||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:i,helpWidth:o}}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(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let o=this.helpInformation({error:n.error});if(t&&(o=t(o),typeof o!="string"&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.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(T.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
+ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,o=>{let s;typeof t=="function"?s=t({error:o.error,command:o.command}):s=t,s&&o.write(`${s}
29
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(i=>t.is(i))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ci(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",i="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?i=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],i=o[4]),t&&i!=="0"?`${t}=${n}:${parseInt(i)+1}`:e})}function Cr(){if(T.env.NO_COLOR||T.env.FORCE_COLOR==="0"||T.env.FORCE_COLOR==="false")return!1;if(T.env.FORCE_COLOR||T.env.CLICOLOR_FORCE!==void 0)return!0}Ar.Command=Or;Ar.useColor=Cr});var yt=g(Z=>{var{Argument:Pi}=ht(),{Command:Pr}=Ai(),{CommanderError:vu,InvalidArgumentError:Ti}=We(),{Help:xu}=br(),{Option:Li}=xr();Z.program=new Pr;Z.createCommand=r=>new Pr(r);Z.createOption=(r,e)=>new Li(r,e);Z.createArgument=(r,e)=>new Pi(r,e);Z.Command=Pr;Z.Option=Li;Z.Argument=Pi;Z.Help=xu;Z.CommanderError=vu;Z.InvalidArgumentError=Ti;Z.InvalidOptionArgumentError=Ti});var Pe=g((Tr,Mi)=>{var wt=require("buffer"),ce=wt.Buffer;function Ii(r,e){for(var t in r)e[t]=r[t]}ce.from&&ce.alloc&&ce.allocUnsafe&&ce.allocUnsafeSlow?Mi.exports=wt:(Ii(wt,Tr),Tr.Buffer=_e);function _e(r,e,t){return ce(r,e,t)}_e.prototype=Object.create(ce.prototype);Ii(ce,_e);_e.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return ce(r,e,t)};_e.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=ce(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};_e.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ce(r)};_e.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return wt.SlowBuffer(r)}});var Lr=g((oE,Ni)=>{var Et=Pe().Buffer,_u=require("stream"),ku=require("util");function $t(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Et.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Et.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+")")}ku.inherits($t,_u);$t.prototype.write=function(e){this.buffer=Et.concat([this.buffer,Et.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};Ni.exports=$t});var Fi=g((sE,Di)=>{"use strict";function Ir(r){var e=(r/8|0)+(r%8===0?0:1);return e}var Ou={ES256:Ir(256),ES384:Ir(384),ES512:Ir(521)};function Cu(r){var e=Ou[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}Di.exports=Cu});var Wi=g((aE,Hi)=>{"use strict";var bt=Pe().Buffer,ji=Fi(),Rt=128,qi=0,Au=32,Pu=16,Tu=2,Gi=Pu|Au|qi<<6,St=Tu|qi<<6;function Lu(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Vi(r){if(bt.isBuffer(r))return r;if(typeof r=="string")return bt.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function Iu(r,e){r=Vi(r);var t=ji(e),n=t+1,i=r.length,o=0;if(r[o++]!==Gi)throw new Error('Could not find expected "seq"');var s=r[o++];if(s===(Rt|1)&&(s=r[o++]),i-o<s)throw new Error('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(r[o++]!==St)throw new Error('Could not find expected "int" for "r"');var a=r[o++];if(i-o-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var l=o;if(o+=a,r[o++]!==St)throw new Error('Could not find expected "int" for "s"');var u=r[o++];if(i-o!==u)throw new Error('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)throw new Error('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');var c=o;if(o+=u,o!==i)throw new Error('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');var m=t-a,d=t-u,p=bt.allocUnsafe(m+a+d+u);for(o=0;o<m;++o)p[o]=0;r.copy(p,o,l+Math.max(-m,0),l+a),o=t;for(var w=o;o<w+d;++o)p[o]=0;return r.copy(p,o,c+Math.max(-d,0),c+u),p=p.toString("base64"),p=Lu(p),p}function Ui(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Rt;return i&&--n,n}function Mu(r,e){r=Vi(r);var t=ji(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=Ui(r,0,t),o=Ui(r,t,r.length),s=t-i,a=t-o,l=2+s+1+1+a,u=l<Rt,c=bt.allocUnsafe((u?2:3)+l),m=0;return c[m++]=Gi,u?c[m++]=l:(c[m++]=Rt|1,c[m++]=l&255),c[m++]=St,c[m++]=s,i<0?(c[m++]=0,m+=r.copy(c,m,0,t)):m+=r.copy(c,m,i,t),c[m++]=St,c[m++]=a,o<0?(c[m++]=0,r.copy(c,m,t)):r.copy(c,m,t+o),c}Hi.exports={derToJose:Iu,joseToDer:Mu}});var Yi=g((lE,Bi)=>{"use strict";var Be=require("buffer").Buffer,Mr=require("buffer").SlowBuffer;Bi.exports=vt;function vt(r,e){if(!Be.isBuffer(r)||!Be.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}vt.install=function(){Be.prototype.equal=Mr.prototype.equal=function(e){return vt(this,e)}};var Nu=Be.prototype.equal,Du=Mr.prototype.equal;vt.restore=function(){Be.prototype.equal=Nu,Mr.prototype.equal=Du}});var Ur=g((cE,ro)=>{var Le=Pe().Buffer,ee=require("crypto"),zi=Wi(),Xi=require("util"),Fu=`"%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".`,je="secret must be a string or buffer",ke="key must be a string or a buffer",wu="key must be a string, a buffer or an object",kr=typeof Z.createPublicKey=="function";kr&&(ke+=" or a KeyObject",je+="or a KeyObject");function Fi(r){if(!Ce.isBuffer(r)&&typeof r!="string"&&(!kr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw ne(ke)}function Di(r){if(!Ce.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw ne(wu)}function bu(r){if(!Ce.isBuffer(r)){if(typeof r=="string")return r;if(!kr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw ne(je)}}function Cr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ui(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function ne(r){var e=[].slice.call(arguments,1),t=Ni.format.bind(Ni,r).apply(null,e);return new TypeError(t)}function Ru(r){return Ce.isBuffer(r)||typeof r=="string"}function qe(r){return Ru(r)||(r=JSON.stringify(r)),r}function ji(r){return function(t,n){bu(n),t=qe(t);var i=Z.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Cr(s)}}var Or,$u="timingSafeEqual"in Z?function(e,t){return e.byteLength!==t.byteLength?!1:Z.timingSafeEqual(e,t)}:function(e,t){return Or||(Or=Ii()),Or(e,t)};function vu(r){return function(t,n,i){var s=ji(r)(t,i);return $u(Ce.from(n),Ce.from(s))}}function qi(r){return function(t,n){Di(n),t=qe(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Cr(s)}}function Vi(r){return function(t,n,i){Fi(i),t=qe(t),n=Ui(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function Su(r){return function(t,n){Di(n),t=qe(t);var i=Z.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Cr(s)}}function xu(r){return function(t,n,i){Fi(i),t=qe(t),n=Ui(n);var s=Z.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:Z.constants.RSA_PKCS1_PSS_PADDING,saltLength:Z.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function _u(r){var e=qi(r);return function(){var n=e.apply(null,arguments);return n=Mi.derToJose(n,"ES"+r),n}}function Ou(r){var e=Vi(r);return function(n,i,s){i=Mi.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function ku(){return function(){return""}}function Cu(){return function(e,t){return t===""}}Gi.exports=function(e){var t={hs:ji,rs:qi,ps:Su,es:_u,none:ku},n={hs:vu,rs:Vi,ps:xu,es:Ou,none:Cu},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw ne(Eu,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var Tr=h((wE,Hi)=>{var Au=require("buffer").Buffer;Hi.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Au.isBuffer(e)?e.toString():JSON.stringify(e)}});var Ji=h((bE,zi)=>{var Tu=Oe().Buffer,Wi=Sr(),Pu=Ar(),Lu=require("stream"),Bi=Tr(),Pr=require("util");function Yi(r,e){return Tu.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Iu(r,e,t){t=t||"utf8";var n=Yi(Bi(r),"binary"),i=Yi(Bi(e),t);return Pr.format("%s.%s",n,i)}function Xi(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=Pu(e.alg),o=Iu(e,t,i),a=s.sign(o,n);return Pr.format("%s.%s",o,a)}function yt(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 Wi(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new Wi(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))}Pr.inherits(yt,Lu);yt.prototype.sign=function(){try{var e=Xi({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")}};yt.sign=Xi;zi.exports=yt});var os=h((RE,ss)=>{var Qi=Oe().Buffer,Ki=Sr(),Nu=Ar(),Mu=require("stream"),Zi=Tr(),Fu=require("util"),Du=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Uu(r){return Object.prototype.toString.call(r)==="[object Object]"}function ju(r){if(Uu(r))return r;try{return JSON.parse(r)}catch{return}}function es(r){var e=r.split(".",1)[0];return ju(Qi.from(e,"base64").toString("binary"))}function qu(r){return r.split(".",2).join(".")}function ts(r){return r.split(".")[2]}function Vu(r,e){e=e||"utf8";var t=r.split(".")[1];return Qi.from(t,"base64").toString(e)}function rs(r){return Du.test(r)&&!!es(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=Zi(r);var i=ts(r),s=qu(r),o=Nu(e);return o.verify(s,i,t)}function is(r,e){if(e=e||{},r=Zi(r),!rs(r))return null;var t=es(r);if(!t)return null;var n=Vu(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:ts(r)}}function Ae(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 Ki(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Ki(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))}Fu.inherits(Ae,Mu);Ae.prototype.verify=function(){try{var e=ns(this.signature.buffer,this.algorithm,this.key.buffer),t=is(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")}};Ae.decode=is;Ae.isValid=rs;Ae.verify=ns;ss.exports=Ae});var wt=h(de=>{var as=Ji(),Et=os(),Gu=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];de.ALGORITHMS=Gu;de.sign=as.sign;de.verify=Et.verify;de.decode=Et.decode;de.isValid=Et.isValid;de.createSign=function(e){return new as(e)};de.createVerify=function(e){return new Et(e)}});var Lr=h((vE,ls)=>{var Hu=wt();ls.exports=function(r,e){e=e||{};var t=Hu.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 Ve=h((SE,cs)=>{var bt=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};bt.prototype=Object.create(Error.prototype);bt.prototype.constructor=bt;cs.exports=bt});var Ir=h((xE,fs)=>{var us=Ve(),Rt=function(r,e){us.call(this,r),this.name="NotBeforeError",this.date=e};Rt.prototype=Object.create(us.prototype);Rt.prototype.constructor=Rt;fs.exports=Rt});var Nr=h((_E,ds)=>{var ms=Ve(),$t=function(r,e){ms.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};$t.prototype=Object.create(ms.prototype);$t.prototype.constructor=$t;ds.exports=$t});var hs=h((OE,ps)=>{var Te=1e3,Pe=Te*60,Le=Pe*60,$e=Le*24,Wu=$e*7,Bu=$e*365.25;ps.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return Yu(r);if(t==="number"&&isFinite(r))return e.long?zu(r):Xu(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function Yu(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*Bu;case"weeks":case"week":case"w":return t*Wu;case"days":case"day":case"d":return t*$e;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Le;case"minutes":case"minute":case"mins":case"min":case"m":return t*Pe;case"seconds":case"second":case"secs":case"sec":case"s":return t*Te;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Xu(r){var e=Math.abs(r);return e>=$e?Math.round(r/$e)+"d":e>=Le?Math.round(r/Le)+"h":e>=Pe?Math.round(r/Pe)+"m":e>=Te?Math.round(r/Te)+"s":r+"ms"}function zu(r){var e=Math.abs(r);return e>=$e?vt(r,e,$e,"day"):e>=Le?vt(r,e,Le,"hour"):e>=Pe?vt(r,e,Pe,"minute"):e>=Te?vt(r,e,Te,"second"):r+" ms"}function vt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Mr=h((kE,gs)=>{var Ju=hs();gs.exports=function(r,e){var t=e||Math.floor(Date.now()/1e3);if(typeof r=="string"){var n=Ju(r);return typeof n>"u"?void 0:Math.floor(t+n/1e3)}else return typeof r=="number"?t+r:void 0}});var Ge=h((CE,ys)=>{"use strict";var Ku="2.0.0",Qu=Number.MAX_SAFE_INTEGER||9007199254740991,Zu=16,ef=250,tf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];ys.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Zu,MAX_SAFE_BUILD_LENGTH:ef,MAX_SAFE_INTEGER:Qu,RELEASE_TYPES:tf,SEMVER_SPEC_VERSION:Ku,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var He=h((AE,Es)=>{"use strict";var rf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Es.exports=rf});var Ie=h((oe,ws)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Fr,MAX_SAFE_BUILD_LENGTH:nf,MAX_LENGTH:sf}=Ge(),of=He();oe=ws.exports={};var af=oe.re=[],lf=oe.safeRe=[],w=oe.src=[],cf=oe.safeSrc=[],b=oe.t={},uf=0,Dr="[a-zA-Z0-9-]",ff=[["\\s",1],["\\d",sf],[Dr,nf]],mf=r=>{for(let[e,t]of ff)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=mf(e),i=uf++;of(r,i,e),b[r]=i,w[i]=e,cf[i]=n,af[i]=new RegExp(e,t?"g":void 0),lf[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Dr}*`);v("MAINVERSION",`(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})\\.(${w[b.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})\\.(${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${w[b.NONNUMERICIDENTIFIER]}|${w[b.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${w[b.PRERELEASEIDENTIFIER]}(?:\\.${w[b.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${w[b.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${w[b.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${Dr}+`);v("BUILD",`(?:\\+(${w[b.BUILDIDENTIFIER]}(?:\\.${w[b.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${w[b.MAINVERSION]}${w[b.PRERELEASE]}?${w[b.BUILD]}?`);v("FULL",`^${w[b.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${w[b.MAINVERSIONLOOSE]}${w[b.PRERELEASELOOSE]}?${w[b.BUILD]}?`);v("LOOSE",`^${w[b.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${w[b.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${w[b.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:\\.(${w[b.XRANGEIDENTIFIER]})(?:${w[b.PRERELEASE]})?${w[b.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:\\.(${w[b.XRANGEIDENTIFIERLOOSE]})(?:${w[b.PRERELEASELOOSE]})?${w[b.BUILD]}?)?)?`);v("XRANGE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${w[b.GTLT]}\\s*${w[b.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Fr}})(?:\\.(\\d{1,${Fr}}))?(?:\\.(\\d{1,${Fr}}))?`);v("COERCE",`${w[b.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",w[b.COERCEPLAIN]+`(?:${w[b.PRERELEASE]})?(?:${w[b.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",w[b.COERCE],!0);v("COERCERTLFULL",w[b.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${w[b.LONETILDE]}\\s+`,!0);oe.tildeTrimReplace="$1~";v("TILDE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${w[b.LONETILDE]}${w[b.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${w[b.LONECARET]}\\s+`,!0);oe.caretTrimReplace="$1^";v("CARET",`^${w[b.LONECARET]}${w[b.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${w[b.LONECARET]}${w[b.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${w[b.GTLT]}\\s*(${w[b.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${w[b.GTLT]}\\s*(${w[b.LOOSEPLAIN]}|${w[b.XRANGEPLAIN]})`,!0);oe.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${w[b.XRANGEPLAIN]})\\s+-\\s+(${w[b.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${w[b.XRANGEPLAINLOOSE]})\\s+-\\s+(${w[b.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var St=h((TE,bs)=>{"use strict";var df=Object.freeze({loose:!0}),pf=Object.freeze({}),hf=r=>r?typeof r!="object"?df:r:pf;bs.exports=hf});var Ur=h((PE,vs)=>{"use strict";var Rs=/^[0-9]+$/,$s=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Rs.test(r),n=Rs.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},gf=(r,e)=>$s(e,r);vs.exports={compareIdentifiers:$s,rcompareIdentifiers:gf}});var H=h((LE,xs)=>{"use strict";var xt=He(),{MAX_LENGTH:Ss,MAX_SAFE_INTEGER:_t}=Ge(),{safeRe:Ot,t:kt}=Ie(),yf=St(),{compareIdentifiers:jr}=Ur(),qr=class r{constructor(e,t){if(t=yf(t),e instanceof r){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Ss)throw new TypeError(`version is longer than ${Ss} characters`);xt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Ot[kt.LOOSE]:Ot[kt.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>_t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>_t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>_t||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<_t)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(xt("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(xt("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 jr(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(xt("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 jr(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?Ot[kt.PRERELEASELOOSE]:Ot[kt.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]),jr(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}};xs.exports=qr});var ve=h((IE,Os)=>{"use strict";var _s=H(),Ef=(r,e,t=!1)=>{if(r instanceof _s)return r;try{return new _s(r,e)}catch(n){if(!t)return null;throw n}};Os.exports=Ef});var Cs=h((NE,ks)=>{"use strict";var wf=ve(),bf=(r,e)=>{let t=wf(r,e);return t?t.version:null};ks.exports=bf});var Ts=h((ME,As)=>{"use strict";var Rf=ve(),$f=(r,e)=>{let t=Rf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};As.exports=$f});var Is=h((FE,Ls)=>{"use strict";var Ps=H(),vf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Ps(r instanceof Ps?r.version:r,t).inc(e,n,i).version}catch{return null}};Ls.exports=vf});var Fs=h((DE,Ms)=>{"use strict";var Ns=ve(),Sf=(r,e)=>{let t=Ns(r,null,!0),n=Ns(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,l=!!o.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};Ms.exports=Sf});var Us=h((UE,Ds)=>{"use strict";var xf=H(),_f=(r,e)=>new xf(r,e).major;Ds.exports=_f});var qs=h((jE,js)=>{"use strict";var Of=H(),kf=(r,e)=>new Of(r,e).minor;js.exports=kf});var Gs=h((qE,Vs)=>{"use strict";var Cf=H(),Af=(r,e)=>new Cf(r,e).patch;Vs.exports=Af});var Ws=h((VE,Hs)=>{"use strict";var Tf=ve(),Pf=(r,e)=>{let t=Tf(r,e);return t&&t.prerelease.length?t.prerelease:null};Hs.exports=Pf});var ee=h((GE,Ys)=>{"use strict";var Bs=H(),Lf=(r,e,t)=>new Bs(r,t).compare(new Bs(e,t));Ys.exports=Lf});var zs=h((HE,Xs)=>{"use strict";var If=ee(),Nf=(r,e,t)=>If(e,r,t);Xs.exports=Nf});var Ks=h((WE,Js)=>{"use strict";var Mf=ee(),Ff=(r,e)=>Mf(r,e,!0);Js.exports=Ff});var Ct=h((BE,Zs)=>{"use strict";var Qs=H(),Df=(r,e,t)=>{let n=new Qs(r,t),i=new Qs(e,t);return n.compare(i)||n.compareBuild(i)};Zs.exports=Df});var to=h((YE,eo)=>{"use strict";var Uf=Ct(),jf=(r,e)=>r.sort((t,n)=>Uf(t,n,e));eo.exports=jf});var no=h((XE,ro)=>{"use strict";var qf=Ct(),Vf=(r,e)=>r.sort((t,n)=>qf(n,t,e));ro.exports=Vf});var We=h((zE,io)=>{"use strict";var Gf=ee(),Hf=(r,e,t)=>Gf(r,e,t)>0;io.exports=Hf});var At=h((JE,so)=>{"use strict";var Wf=ee(),Bf=(r,e,t)=>Wf(r,e,t)<0;so.exports=Bf});var Vr=h((KE,oo)=>{"use strict";var Yf=ee(),Xf=(r,e,t)=>Yf(r,e,t)===0;oo.exports=Xf});var Gr=h((QE,ao)=>{"use strict";var zf=ee(),Jf=(r,e,t)=>zf(r,e,t)!==0;ao.exports=Jf});var Tt=h((ZE,lo)=>{"use strict";var Kf=ee(),Qf=(r,e,t)=>Kf(r,e,t)>=0;lo.exports=Qf});var Pt=h((ew,co)=>{"use strict";var Zf=ee(),em=(r,e,t)=>Zf(r,e,t)<=0;co.exports=em});var Hr=h((tw,uo)=>{"use strict";var tm=Vr(),rm=Gr(),nm=We(),im=Tt(),sm=At(),om=Pt(),am=(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 tm(r,t,n);case"!=":return rm(r,t,n);case">":return nm(r,t,n);case">=":return im(r,t,n);case"<":return sm(r,t,n);case"<=":return om(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};uo.exports=am});var mo=h((rw,fo)=>{"use strict";var lm=H(),cm=ve(),{safeRe:Lt,t:It}=Ie(),um=(r,e)=>{if(r instanceof lm)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?Lt[It.COERCEFULL]:Lt[It.COERCE]);else{let l=e.includePrerelease?Lt[It.COERCERTLFULL]:Lt[It.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return cm(`${n}.${i}.${s}${o}${a}`,e)};fo.exports=um});var ho=h((nw,po)=>{"use strict";var Wr=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}};po.exports=Wr});var te=h((iw,wo)=>{"use strict";var fm=/\s+/g,Br=class r{constructor(e,t){if(t=dm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Yr)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(fm," "),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=>!yo(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&&bm(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&&Em)|(this.options.loose&&wm))+":"+e,i=go.get(n);if(i)return i;let s=this.options.loose,o=s?Y[W.HYPHENRANGELOOSE]:Y[W.HYPHENRANGE];e=e.replace(o,Am(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(Y[W.COMPARATORTRIM],hm),I("comparator trim",e),e=e.replace(Y[W.TILDETRIM],gm),I("tilde trim",e),e=e.replace(Y[W.CARETTRIM],ym),I("caret trim",e);let a=e.split(" ").map(f=>Rm(f,this.options)).join(" ").split(/\s+/).map(f=>Cm(f,this.options));s&&(a=a.filter(f=>(I("loose invalid filter",f,this.options),!!f.match(Y[W.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(f=>new Yr(f,this.options));for(let f of u){if(yo(f))return[f];l.set(f.value,f)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return go.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Eo(n,t)&&e.set.some(i=>Eo(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 pm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(Tm(this.set[t],e,this.options))return!0;return!1}};wo.exports=Br;var mm=ho(),go=new mm,dm=St(),Yr=Be(),I=He(),pm=H(),{safeRe:Y,t:W,comparatorTrimReplace:hm,tildeTrimReplace:gm,caretTrimReplace:ym}=Ie(),{FLAG_INCLUDE_PRERELEASE:Em,FLAG_LOOSE:wm}=Ge(),yo=r=>r.value==="<0.0.0-0",bm=r=>r.value==="",Eo=(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},Rm=(r,e)=>(r=r.replace(Y[W.BUILD],""),I("comp",r,e),r=Sm(r,e),I("caret",r),r=$m(r,e),I("tildes",r),r=_m(r,e),I("xrange",r),r=km(r,e),I("stars",r),r),X=r=>!r||r.toLowerCase()==="x"||r==="*",$m=(r,e)=>r.trim().split(/\s+/).map(t=>vm(t,e)).join(" "),vm=(r,e)=>{let t=e.loose?Y[W.TILDELOOSE]:Y[W.TILDE];return r.replace(t,(n,i,s,o,a)=>{I("tilde",r,n,i,s,o,a);let l;return X(i)?l="":X(s)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:X(o)?l=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`):l=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`,I("tilde return",l),l})},Sm=(r,e)=>r.trim().split(/\s+/).map(t=>xm(t,e)).join(" "),xm=(r,e)=>{I("caret",r,e);let t=e.loose?Y[W.CARETLOOSE]:Y[W.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,l)=>{I("caret",r,i,s,o,a,l);let u;return X(s)?u="":X(o)?u=`>=${s}.0.0${n} <${+s+1}.0.0-0`:X(a)?s==="0"?u=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:l?(I("replaceCaret pr",l),s==="0"?o==="0"?u=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(I("no pr"),s==="0"?o==="0"?u=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`:u=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`:u=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),I("caret return",u),u})},_m=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>Om(t,e)).join(" ")),Om=(r,e)=>{r=r.trim();let t=e.loose?Y[W.XRANGELOOSE]:Y[W.XRANGE];return r.replace(t,(n,i,s,o,a,l)=>{I("xRange",r,n,i,s,o,a,l);let u=X(s),c=u||X(o),f=c||X(a),d=f;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(o=0),a=0,i===">"?(i=">=",c?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",c?s=+s+1:o=+o+1),i==="<"&&(l="-0"),n=`${i+s}.${o}.${a}${l}`):c?n=`>=${s}.0.0${l} <${+s+1}.0.0-0`:f&&(n=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),I("xRange return",n),n})},km=(r,e)=>(I("replaceStars",r,e),r.trim().replace(Y[W.STAR],"")),Cm=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(Y[e.includePrerelease?W.GTE0PRE:W.GTE0],"")),Am=r=>(e,t,n,i,s,o,a,l,u,c,f,d)=>(X(n)?t="":X(i)?t=`>=${n}.0.0${r?"-0":""}`:X(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,X(u)?l="":X(c)?l=`<${+u+1}.0.0-0`:X(f)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${f}-${d}`:r?l=`<${u}.${c}.${+f+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),Tm=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==Yr.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 Be=h((sw,xo)=>{"use strict";var Ye=Symbol("SemVer ANY"),Jr=class r{static get ANY(){return Ye}constructor(e,t){if(t=bo(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),zr("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ye?this.value="":this.value=this.operator+this.semver.version,zr("comp",this)}parse(e){let t=this.options.loose?Ro[$o.COMPARATORLOOSE]:Ro[$o.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 vo(n[2],this.options.loose):this.semver=Ye}toString(){return this.value}test(e){if(zr("Comparator.test",e,this.options.loose),this.semver===Ye||e===Ye)return!0;if(typeof e=="string")try{e=new vo(e,this.options)}catch{return!1}return Xr(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 So(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new So(this.value,t).test(e.semver):(t=bo(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("=")||Xr(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Xr(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};xo.exports=Jr;var bo=St(),{safeRe:Ro,t:$o}=Ie(),Xr=Hr(),zr=He(),vo=H(),So=te()});var Xe=h((ow,_o)=>{"use strict";var Pm=te(),Lm=(r,e,t)=>{try{e=new Pm(e,t)}catch{return!1}return e.test(r)};_o.exports=Lm});var ko=h((aw,Oo)=>{"use strict";var Im=te(),Nm=(r,e)=>new Im(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Oo.exports=Nm});var Ao=h((lw,Co)=>{"use strict";var Mm=H(),Fm=te(),Dm=(r,e,t)=>{let n=null,i=null,s=null;try{s=new Fm(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new Mm(n,t))}),n};Co.exports=Dm});var Po=h((cw,To)=>{"use strict";var Um=H(),jm=te(),qm=(r,e,t)=>{let n=null,i=null,s=null;try{s=new jm(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new Um(n,t))}),n};To.exports=qm});var No=h((uw,Io)=>{"use strict";var Kr=H(),Vm=te(),Lo=We(),Gm=(r,e)=>{r=new Vm(r,e);let t=new Kr("0.0.0");if(r.test(t)||(t=new Kr("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 Kr(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Lo(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||Lo(t,s))&&(t=s)}return t&&r.test(t)?t:null};Io.exports=Gm});var Fo=h((fw,Mo)=>{"use strict";var Hm=te(),Wm=(r,e)=>{try{return new Hm(r,e).range||"*"}catch{return null}};Mo.exports=Wm});var Nt=h((mw,qo)=>{"use strict";var Bm=H(),jo=Be(),{ANY:Ym}=jo,Xm=te(),zm=Xe(),Do=We(),Uo=At(),Jm=Pt(),Km=Tt(),Qm=(r,e,t,n)=>{r=new Bm(r,n),e=new Xm(e,n);let i,s,o,a,l;switch(t){case">":i=Do,s=Jm,o=Uo,a=">",l=">=";break;case"<":i=Uo,s=Km,o=Do,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(zm(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],f=null,d=null;if(c.forEach(p=>{p.semver===Ym&&(p=new jo(">=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};qo.exports=Qm});var Go=h((dw,Vo)=>{"use strict";var Zm=Nt(),ed=(r,e,t)=>Zm(r,e,">",t);Vo.exports=ed});var Wo=h((pw,Ho)=>{"use strict";var td=Nt(),rd=(r,e,t)=>td(r,e,"<",t);Ho.exports=rd});var Xo=h((hw,Yo)=>{"use strict";var Bo=te(),nd=(r,e,t)=>(r=new Bo(r,t),e=new Bo(e,t),r.intersects(e,t));Yo.exports=nd});var Jo=h((gw,zo)=>{"use strict";var id=Xe(),sd=ee();zo.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((c,f)=>sd(c,f,t));for(let c of o)id(c,e,t)?(s=c,i||(i=c)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,f]of n)c===f?a.push(c):!f&&c===o[0]?a.push("*"):f?c===o[0]?a.push(`<=${f}`):a.push(`${c} - ${f}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ra=h((yw,ta)=>{"use strict";var Ko=te(),Zr=Be(),{ANY:Qr}=Zr,ze=Xe(),en=ee(),od=(r,e,t={})=>{if(r===e)return!0;r=new Ko(r,t),e=new Ko(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=ld(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},ad=[new Zr(">=0.0.0-0")],Qo=[new Zr(">=0.0.0")],ld=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Qr){if(e.length===1&&e[0].semver===Qr)return!0;t.includePrerelease?r=ad:r=Qo}if(e.length===1&&e[0].semver===Qr){if(t.includePrerelease)return!0;e=Qo}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=Zo(i,p,t):p.operator==="<"||p.operator==="<="?s=ea(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=en(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&&!ze(p,String(i),t)||s&&!ze(p,String(s),t))return null;for(let E of e)if(!ze(p,String(E),t))return!1;return!0}let a,l,u,c,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0&&(f=!1);for(let p of e){if(c=c||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator===">"||p.operator===">="){if(a=Zo(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!ze(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=ea(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!ze(s.semver,String(p),t))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&u&&!s&&o!==0||s&&c&&!i&&o!==0||d||f)},Zo=(r,e,t)=>{if(!r)return e;let n=en(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},ea=(r,e,t)=>{if(!r)return e;let n=en(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};ta.exports=od});var Mt=h((Ew,sa)=>{"use strict";var tn=Ie(),na=Ge(),cd=H(),ia=Ur(),ud=ve(),fd=Cs(),md=Ts(),dd=Is(),pd=Fs(),hd=Us(),gd=qs(),yd=Gs(),Ed=Ws(),wd=ee(),bd=zs(),Rd=Ks(),$d=Ct(),vd=to(),Sd=no(),xd=We(),_d=At(),Od=Vr(),kd=Gr(),Cd=Tt(),Ad=Pt(),Td=Hr(),Pd=mo(),Ld=Be(),Id=te(),Nd=Xe(),Md=ko(),Fd=Ao(),Dd=Po(),Ud=No(),jd=Fo(),qd=Nt(),Vd=Go(),Gd=Wo(),Hd=Xo(),Wd=Jo(),Bd=ra();sa.exports={parse:ud,valid:fd,clean:md,inc:dd,diff:pd,major:hd,minor:gd,patch:yd,prerelease:Ed,compare:wd,rcompare:bd,compareLoose:Rd,compareBuild:$d,sort:vd,rsort:Sd,gt:xd,lt:_d,eq:Od,neq:kd,gte:Cd,lte:Ad,cmp:Td,coerce:Pd,Comparator:Ld,Range:Id,satisfies:Nd,toComparators:Md,maxSatisfying:Fd,minSatisfying:Dd,minVersion:Ud,validRange:jd,outside:qd,gtr:Vd,ltr:Gd,intersects:Hd,simplifyRange:Wd,subset:Bd,SemVer:cd,re:tn.re,src:tn.src,tokens:tn.t,SEMVER_SPEC_VERSION:na.SEMVER_SPEC_VERSION,RELEASE_TYPES:na.RELEASE_TYPES,compareIdentifiers:ia.compareIdentifiers,rcompareIdentifiers:ia.rcompareIdentifiers}});var aa=h((ww,oa)=>{var Yd=Mt();oa.exports=Yd.satisfies(process.version,">=15.7.0")});var ca=h((bw,la)=>{var Xd=Mt();la.exports=Xd.satisfies(process.version,">=16.9.0")});var rn=h((Rw,ua)=>{var zd=aa(),Jd=ca(),Kd={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},Qd={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};ua.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=Kd[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(zd)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,s=Qd[r];if(i!==s)throw new Error(`"alg" parameter "${r}" requires curve "${s}".`);break;case"rsa-pss":if(Jd){let o=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${o}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>o>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var nn=h(($w,fa)=>{var Zd=Mt();fa.exports=Zd.satisfies(process.version,"^6.12.0 || >=8.0.0")});var pa=h((vw,da)=>{var L=Ve(),ep=Ir(),ma=Nr(),tp=Lr(),rp=Mr(),np=rn(),ip=nn(),sp=wt(),{KeyObject:op,createSecretKey:ap,createPublicKey:lp}=require("crypto"),sn=["RS256","RS384","RS512"],cp=["ES256","ES384","ES512"],on=["RS256","RS384","RS512"],up=["HS256","HS384","HS512"];ip&&(sn.splice(sn.length,0,"PS256","PS384","PS512"),on.splice(on.length,0,"PS256","PS384","PS512"));da.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,f){if(c)throw c;return f},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new L("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new L("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new L("allowInvalidAsymmetricKeyTypes must be a boolean"));let s=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new L("jwt must be provided"));if(typeof r!="string")return i(new L("jwt must be a string"));let o=r.split(".");if(o.length!==3)return i(new L("jwt malformed"));let a;try{a=tp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new L("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new L("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,f){return f(null,e)};return u(l,function(c,f){if(c)return i(new L("error in secret or public key callback: "+c.message));let d=o[2].trim()!=="";if(!d&&f)return i(new L("jwt signature is required"));if(d&&!f)return i(new L("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new L('please specify "none" in "algorithms" to verify unsigned tokens'));if(f!=null&&!(f instanceof op))try{f=lp(f)}catch{try{f=ap(typeof f=="string"?Buffer.from(f):f)}catch{return i(new L("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(f.type==="secret"?t.algorithms=up:["rsa","rsa-pss"].includes(f.asymmetricKeyType)?t.algorithms=on:f.asymmetricKeyType==="ec"?t.algorithms=cp:t.algorithms=sn),t.algorithms.indexOf(a.header.alg)===-1)return i(new L("invalid algorithm"));if(l.alg.startsWith("HS")&&f.type!=="secret")return i(new L(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&f.type!=="public")return i(new L(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{np(l.alg,f)}catch(x){return i(x)}let p;try{p=sp.verify(r,a.header.alg,f)}catch(x){return i(x)}if(!p)return i(new L("invalid signature"));let E=a.payload;if(typeof E.nbf<"u"&&!t.ignoreNotBefore){if(typeof E.nbf!="number")return i(new L("invalid nbf value"));if(E.nbf>s+(t.clockTolerance||0))return i(new ep("jwt not active",new Date(E.nbf*1e3)))}if(typeof E.exp<"u"&&!t.ignoreExpiration){if(typeof E.exp!="number")return i(new L("invalid exp value"));if(s>=E.exp+(t.clockTolerance||0))return i(new ma("jwt expired",new Date(E.exp*1e3)))}if(t.audience){let x=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(E.aud)?E.aud:[E.aud]).some(function(R){return x.some(function($){return $ instanceof RegExp?$.test(R):$===R})}))return i(new L("jwt audience invalid. expected: "+x.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&E.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(E.iss)===-1))return i(new L("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&E.sub!==t.subject)return i(new L("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&E.jti!==t.jwtid)return i(new L("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&E.nonce!==t.nonce)return i(new L("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof E.iat!="number")return i(new L("iat required when maxAge is specified"));let x=rp(t.maxAge,E.iat);if(typeof x>"u")return i(new L('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(s>=x+(t.clockTolerance||0))return i(new ma("maxAge exceeded",new Date(x*1e3)))}if(t.complete===!0){let x=a.signature;return i(null,{header:l,payload:E,signature:x})}return i(null,E)})}});var ba=h((Sw,wa)=>{var ha=1/0,ya=9007199254740991,fp=17976931348623157e292,ga=NaN,mp="[object Arguments]",dp="[object Function]",pp="[object GeneratorFunction]",hp="[object String]",gp="[object Symbol]",yp=/^\s+|\s+$/g,Ep=/^[-+]0x[0-9a-f]+$/i,wp=/^0b[01]+$/i,bp=/^0o[0-7]+$/i,Rp=/^(?:0|[1-9]\d*)$/,$p=parseInt;function vp(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 Sp(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 xp(r,e,t){if(e!==e)return Sp(r,_p,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function _p(r){return r!==r}function Op(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function kp(r,e){return vp(e,function(t){return r[t]})}function Cp(r,e){return function(t){return r(e(t))}}var Ft=Object.prototype,ln=Ft.hasOwnProperty,Dt=Ft.toString,Ap=Ft.propertyIsEnumerable,Tp=Cp(Object.keys,Object),Pp=Math.max;function Lp(r,e){var t=Ea(r)||Dp(r)?Op(r.length,String):[],n=t.length,i=!!n;for(var s in r)(e||ln.call(r,s))&&!(i&&(s=="length"||Np(s,n)))&&t.push(s);return t}function Ip(r){if(!Mp(r))return Tp(r);var e=[];for(var t in Object(r))ln.call(r,t)&&t!="constructor"&&e.push(t);return e}function Np(r,e){return e=e??ya,!!e&&(typeof r=="number"||Rp.test(r))&&r>-1&&r%1==0&&r<e}function Mp(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ft;return r===t}function Fp(r,e,t,n){r=cn(r)?r:Xp(r),t=t&&!n?Wp(t):0;var i=r.length;return t<0&&(t=Pp(i+t,0)),Vp(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&xp(r,e,t)>-1}function Dp(r){return Up(r)&&ln.call(r,"callee")&&(!Ap.call(r,"callee")||Dt.call(r)==mp)}var Ea=Array.isArray;function cn(r){return r!=null&&qp(r.length)&&!jp(r)}function Up(r){return un(r)&&cn(r)}function jp(r){var e=an(r)?Dt.call(r):"";return e==dp||e==pp}function qp(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=ya}function an(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function un(r){return!!r&&typeof r=="object"}function Vp(r){return typeof r=="string"||!Ea(r)&&un(r)&&Dt.call(r)==hp}function Gp(r){return typeof r=="symbol"||un(r)&&Dt.call(r)==gp}function Hp(r){if(!r)return r===0?r:0;if(r=Bp(r),r===ha||r===-ha){var e=r<0?-1:1;return e*fp}return r===r?r:0}function Wp(r){var e=Hp(r),t=e%1;return e===e?t?e-t:e:0}function Bp(r){if(typeof r=="number")return r;if(Gp(r))return ga;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(yp,"");var t=wp.test(r);return t||bp.test(r)?$p(r.slice(2),t?2:8):Ep.test(r)?ga:+r}function Yp(r){return cn(r)?Lp(r):Ip(r)}function Xp(r){return r?kp(r,Yp(r)):[]}wa.exports=Fp});var $a=h((xw,Ra)=>{var zp="[object Boolean]",Jp=Object.prototype,Kp=Jp.toString;function Qp(r){return r===!0||r===!1||Zp(r)&&Kp.call(r)==zp}function Zp(r){return!!r&&typeof r=="object"}Ra.exports=Qp});var Oa=h((_w,_a)=>{var va=1/0,eh=17976931348623157e292,Sa=NaN,th="[object Symbol]",rh=/^\s+|\s+$/g,nh=/^[-+]0x[0-9a-f]+$/i,ih=/^0b[01]+$/i,sh=/^0o[0-7]+$/i,oh=parseInt,ah=Object.prototype,lh=ah.toString;function ch(r){return typeof r=="number"&&r==dh(r)}function xa(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function uh(r){return!!r&&typeof r=="object"}function fh(r){return typeof r=="symbol"||uh(r)&&lh.call(r)==th}function mh(r){if(!r)return r===0?r:0;if(r=ph(r),r===va||r===-va){var e=r<0?-1:1;return e*eh}return r===r?r:0}function dh(r){var e=mh(r),t=e%1;return e===e?t?e-t:e:0}function ph(r){if(typeof r=="number")return r;if(fh(r))return Sa;if(xa(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=xa(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(rh,"");var t=ih.test(r);return t||sh.test(r)?oh(r.slice(2),t?2:8):nh.test(r)?Sa:+r}_a.exports=ch});var Ca=h((Ow,ka)=>{var hh="[object Number]",gh=Object.prototype,yh=gh.toString;function Eh(r){return!!r&&typeof r=="object"}function wh(r){return typeof r=="number"||Eh(r)&&yh.call(r)==hh}ka.exports=wh});var La=h((kw,Pa)=>{var bh="[object Object]";function Rh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function $h(r,e){return function(t){return r(e(t))}}var vh=Function.prototype,Aa=Object.prototype,Ta=vh.toString,Sh=Aa.hasOwnProperty,xh=Ta.call(Object),_h=Aa.toString,Oh=$h(Object.getPrototypeOf,Object);function kh(r){return!!r&&typeof r=="object"}function Ch(r){if(!kh(r)||_h.call(r)!=bh||Rh(r))return!1;var e=Oh(r);if(e===null)return!0;var t=Sh.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Ta.call(t)==xh}Pa.exports=Ch});var Na=h((Cw,Ia)=>{var Ah="[object String]",Th=Object.prototype,Ph=Th.toString,Lh=Array.isArray;function Ih(r){return!!r&&typeof r=="object"}function Nh(r){return typeof r=="string"||!Lh(r)&&Ih(r)&&Ph.call(r)==Ah}Ia.exports=Nh});var ja=h((Aw,Ua)=>{var Mh="Expected a function",Ma=1/0,Fh=17976931348623157e292,Fa=NaN,Dh="[object Symbol]",Uh=/^\s+|\s+$/g,jh=/^[-+]0x[0-9a-f]+$/i,qh=/^0b[01]+$/i,Vh=/^0o[0-7]+$/i,Gh=parseInt,Hh=Object.prototype,Wh=Hh.toString;function Bh(r,e){var t;if(typeof e!="function")throw new TypeError(Mh);return r=Kh(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function Yh(r){return Bh(2,r)}function Da(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Xh(r){return!!r&&typeof r=="object"}function zh(r){return typeof r=="symbol"||Xh(r)&&Wh.call(r)==Dh}function Jh(r){if(!r)return r===0?r:0;if(r=Qh(r),r===Ma||r===-Ma){var e=r<0?-1:1;return e*Fh}return r===r?r:0}function Kh(r){var e=Jh(r),t=e%1;return e===e?t?e-t:e:0}function Qh(r){if(typeof r=="number")return r;if(zh(r))return Fa;if(Da(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Da(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Uh,"");var t=qh.test(r);return t||Vh.test(r)?Gh(r.slice(2),t?2:8):jh.test(r)?Fa:+r}Ua.exports=Yh});var za=h((Tw,Xa)=>{var qa=Mr(),Zh=nn(),eg=rn(),Va=wt(),tg=ba(),Ut=$a(),Ga=Oa(),fn=Ca(),Wa=La(),pe=Na(),rg=ja(),{KeyObject:ng,createSecretKey:ig,createPrivateKey:sg}=require("crypto"),Ba=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];Zh&&Ba.splice(3,0,"PS256","PS384","PS512");var og={expiresIn:{isValid:function(r){return Ga(r)||pe(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return Ga(r)||pe(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return pe(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:tg.bind(null,Ba),message:'"algorithm" must be a valid string enum value'},header:{isValid:Wa,message:'"header" must be an object'},encoding:{isValid:pe,message:'"encoding" must be a string'},issuer:{isValid:pe,message:'"issuer" must be a string'},subject:{isValid:pe,message:'"subject" must be a string'},jwtid:{isValid:pe,message:'"jwtid" must be a string'},noTimestamp:{isValid:Ut,message:'"noTimestamp" must be a boolean'},keyid:{isValid:pe,message:'"keyid" must be a string'},mutatePayload:{isValid:Ut,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Ut,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Ut,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},ag={iat:{isValid:fn,message:'"iat" should be a number of seconds'},exp:{isValid:fn,message:'"exp" should be a number of seconds'},nbf:{isValid:fn,message:'"nbf" should be a number of seconds'}};function Ya(r,e,t,n){if(!Wa(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 lg(r){return Ya(og,!1,r,"options")}function cg(r){return Ya(ag,!0,r,"payload")}var Ha={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},ug=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];Xa.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),s=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function o(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return o(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof ng))try{e=sg(e)}catch{try{e=ig(typeof e=="string"?Buffer.from(e):e)}catch{return o(new Error("secretOrPrivateKey is not valid key material"))}}if(s.alg.startsWith("HS")&&e.type!=="secret")return o(new Error(`secretOrPrivateKey must be a symmetric key when using ${s.alg}`));if(/^(?:RS|PS|ES)/.test(s.alg)){if(e.type!=="private")return o(new Error(`secretOrPrivateKey must be an asymmetric key when using ${s.alg}`));if(!t.allowInsecureKeySizes&&!s.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return o(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`))}if(typeof r>"u")return o(new Error("payload is required"));if(i){try{cg(r)}catch(u){return o(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=ug.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return o(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return o(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return o(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{lg(t)}catch(u){return o(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{eg(s.alg,e)}catch(u){return o(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=qa(t.notBefore,a)}catch(u){return o(u)}if(typeof r.nbf>"u")return o(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(typeof t.expiresIn<"u"&&typeof r=="object"){try{r.exp=qa(t.expiresIn,a)}catch(u){return o(u)}if(typeof r.exp>"u")return o(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(Ha).forEach(function(u){let c=Ha[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return o(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&rg(n),Va.createSign({header:s,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`));n(null,u)});else{let u=Va.sign({header:s,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(s.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${s.alg}`);return u}}});var mn=h((Pw,Ja)=>{Ja.exports={decode:Lr(),verify:pa(),sign:za(),JsonWebTokenError:Ve(),NotBeforeError:Ir(),TokenExpiredError:Nr()}});var Rl=h((pb,bl)=>{function dl(r){return Array.isArray(r)?r:[r]}var xn="",pl=" ",vn="\\",Mg=/^\s+$/,Fg=/(?:[^\\]|^)\\$/,Dg=/^\\!/,Ug=/^\\#/,jg=/\r?\n/g,qg=/^\.*\/|^\.+$/,Sn="/",yl="node-ignore";typeof Symbol<"u"&&(yl=Symbol.for("node-ignore"));var hl=yl,Vg=(r,e,t)=>Object.defineProperty(r,e,{value:t}),Gg=/([0-z])-([0-z])/g,El=()=>!1,Hg=r=>r.replace(Gg,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:xn),Wg=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Bg=[[/^\uFEFF/,()=>xn],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?pl:xn)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+pl}],[/[\\$.|*+(){^]/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,()=>vn],[/\\\\/g,()=>vn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===vn?`\\[${t}${Wg(n)}${i}`:i==="]"&&n.length%2===0?`[${Hg(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],gl=Object.create(null),Yg=(r,e)=>{let t=gl[r];return t||(t=Bg.reduce((n,[i,s])=>n.replace(i,s.bind(r)),r),gl[r]=t),e?new RegExp(t,"i"):new RegExp(t)},kn=r=>typeof r=="string",Xg=r=>r&&kn(r)&&!Mg.test(r)&&!Fg.test(r)&&r.indexOf("#")!==0,zg=r=>r.split(jg),_n=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},Jg=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(Dg,"!").replace(Ug,"#");let i=Yg(r,e);return new _n(t,r,n,i)},Kg=(r,e)=>{throw new e(r)},fe=(r,e,t)=>kn(r)?r?fe.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),wl=r=>qg.test(r);fe.isNotRelative=wl;fe.convert=r=>r;var On=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){Vg(this,hl,!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[hl]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Xg(e)){let t=Jg(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,dl(kn(e)?zg(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&&fe.convert(e);return fe(s,e,this._allowRelativePaths?El:Kg),this._t(s,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Sn)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let s=this._t(i.join(Sn)+Sn,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 dl(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Yt=r=>new On(r),Qg=r=>fe(r&&fe.convert(r),r,El);Yt.isPathValid=Qg;Yt.default=Yt;bl.exports=Yt;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,"/");fe.convert=r;let e=/^[a-z]:\//i;fe.isNotRelative=t=>e.test(t)||wl(t)}});(function(){si().config(Object.assign({},ai(),ci()(process.argv)))})();var Rc=require("fs"),$c=require("path");var wc=P(ct());var ie=P(require("fs")),En=P(require("path")),tl=P(require("os")),rl=P(mn());var fg=process.stdout.isTTY===!0&&!process.env.NO_COLOR,he=r=>fg?r:"",S=he("\x1B[32m"),T=he("\x1B[33m"),k=he("\x1B[36m"),re=he("\x1B[35m"),g=he("\x1B[31m"),y=he("\x1B[2m"),z=he("\x1B[1m"),m=he("\x1B[0m");var Ka="app.boxel.realms";var mg={"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"},Iw=Object.keys(mg);function C(r){return r.endsWith("/")?r:`${r}/`}async function Qa(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 dg(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 dn(r,e){let t=await dg(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 pn(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 hn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${Ka}`,r.matrixUrl).href}async function jt(r){try{let e=await fetch(hn(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 Za(r,e){let t=await jt(r);if(!t.includes(e)){t.push(e);let n=await fetch(hn(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 el(r,e){let t=C(e),n=await jt(r),i=n.filter(o=>C(o)!==t);if(i.length===n.length)return!1;let s=await fetch(hn(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 pg=En.join(tl.homedir(),".boxel-cli"),hg="profiles.json",gg=86400;function yg(r,e=gg){let t=r.replace(/^Bearer\s+/i,""),n=rl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var N="No active profile. Run `boxel profile add` to create one.";function qt(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function Ne(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function Vt(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function ae(r){let e=Ne(r),t=Vt(r);return`${y}[${m}${k}${e}${m} ${y}\xB7${m} ${re}${t}${m}${y}]${m}`}var yn=class{config;configDir;profilesFile;constructor(e){this.configDir=e||pg,this.profilesFile=En.join(this.configDir,hg),this.config=this.loadConfig()}ensureConfigDir(){ie.existsSync(this.configDir)||ie.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ie.existsSync(this.profilesFile))try{let t=ie.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(),ie.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ie.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=qt(e),a=Ne(e);if(o==="unknown"&&(!i||!s))throw new Error(`Unknown domain in Matrix ID "${e}". You must provide explicit --matrix-url and --realm-server-url for non-standard domains.`);let l=o==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=o==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=Vt(e),f={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:s||u,password:t};this.config.profiles[e]=f,this.config.activeProfile||(this.config.activeProfile=e),this.saveConfig()}async removeProfile(e){if(!this.config.profiles[e])return!1;if(delete this.config.profiles[e],this.config.activeProfile===e){let t=Object.keys(this.config.profiles);this.config.activeProfile=t.length>0?t[0]:null}return this.saveConfig(),!0}switchProfile(e){return this.config.profiles[e]?(this.config.activeProfile=e,this.saveConfig(),!0):!1}async getActiveCredentials(){let e=this.getActiveProfile();if(e&&e.profile.password)return{matrixUrl:e.profile.matrixUrl,username:Ne(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=Ne(t);return Qa(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!yg(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=await dn(t,i);return this.setRealmServerToken(s),s}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await dn(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 pn(n,e);for(let[s,o]of Object.entries(i))this.setRealmToken(s,o)}async getRealmTokenForUrl(e){let t=this.findRealmTokenForUrl(e);if(t)return t;try{await this.fetchAndStoreAllRealmTokens()}catch{return}return this.findRealmTokenForUrl(e)}buildHeaders(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,s=new Headers(t?.headers);for(let[o,a]of s)i.set(o,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let s=this.getActiveProfile();if(s&&(s.profile.realmTokens={},s.profile.realmServerToken=void 0,this.saveConfig()),await this.fetchAndStoreAllRealmTokens(),i=this.findRealmTokenForUrl(n),!i)throw new Error(`No realm token available for ${n}. The realm may not be accessible.`);let o=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:o})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i});return s.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),s=await fetch(e,{...t,headers:i})),s}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=(await pn(i,t))[e];return o&&this.setRealmToken(e,o),o}async addToUserRealms(e){let t=await this.loginToMatrix();await Za(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return el(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return jt(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} ${ae(e.id)}`),console.log(` ${y}Display Name:${m} ${e.profile.displayName}`),console.log(` ${y}Matrix URL:${m} ${e.profile.matrixUrl}`),console.log(` ${y}Realm Server:${m} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
33
- ${z}Using environment variables${m} (no profile active)`),console.log(` ${y}Username:${m} ${process.env.MATRIX_USERNAME}`)):(console.log(`
34
- ${T}No active profile and no environment variables set.${m}`),console.log(`Run ${k}boxel profile add${m} to create a profile.`))}},gn=null;function O(){return gn||(gn=new yn),gn}var wn=P(require("readline")),nl=require("stream");function J(r){let e=wn.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function bn(r){let e=new nl.Writable({write:(n,i,s)=>s()}),t=wn.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let s=process.stdin,o=s.readableFlowing;s.isTTY&&s.setRawMode(!0);let a=()=>{s.removeListener("data",l),s.isTTY&&s.setRawMode(!1),t.close(),o||s.pause()},l=c=>{try{let f=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of f)if(d===`
31
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ye="secret must be a string or buffer",Te="key must be a string or a buffer",Uu="key must be a string, a buffer or an object",Dr=typeof ee.createPublicKey=="function";Dr&&(Te+=" or a KeyObject",Ye+="or a KeyObject");function Ji(r){if(!Le.isBuffer(r)&&typeof r!="string"&&(!Dr||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw se(Te)}function Ki(r){if(!Le.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw se(Uu)}function ju(r){if(!Le.isBuffer(r)){if(typeof r=="string")return r;if(!Dr||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw se(Ye)}}function Fr(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Qi(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 se(r){var e=[].slice.call(arguments,1),t=Xi.format.bind(Xi,r).apply(null,e);return new TypeError(t)}function qu(r){return Le.isBuffer(r)||typeof r=="string"}function Xe(r){return qu(r)||(r=JSON.stringify(r)),r}function Zi(r){return function(t,n){ju(n),t=Xe(t);var i=ee.createHmac("sha"+r,n),o=(i.update(t),i.digest("base64"));return Fr(o)}}var Nr,Gu="timingSafeEqual"in ee?function(e,t){return e.byteLength!==t.byteLength?!1:ee.timingSafeEqual(e,t)}:function(e,t){return Nr||(Nr=Yi()),Nr(e,t)};function Vu(r){return function(t,n,i){var o=Zi(r)(t,i);return Gu(Le.from(n),Le.from(o))}}function eo(r){return function(t,n){Ki(n),t=Xe(t);var i=ee.createSign("RSA-SHA"+r),o=(i.update(t),i.sign(n,"base64"));return Fr(o)}}function to(r){return function(t,n,i){Ji(i),t=Xe(t),n=Qi(n);var o=ee.createVerify("RSA-SHA"+r);return o.update(t),o.verify(i,n,"base64")}}function Hu(r){return function(t,n){Ki(n),t=Xe(t);var i=ee.createSign("RSA-SHA"+r),o=(i.update(t),i.sign({key:n,padding:ee.constants.RSA_PKCS1_PSS_PADDING,saltLength:ee.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Fr(o)}}function Wu(r){return function(t,n,i){Ji(i),t=Xe(t),n=Qi(n);var o=ee.createVerify("RSA-SHA"+r);return o.update(t),o.verify({key:i,padding:ee.constants.RSA_PKCS1_PSS_PADDING,saltLength:ee.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function Bu(r){var e=eo(r);return function(){var n=e.apply(null,arguments);return n=zi.derToJose(n,"ES"+r),n}}function Yu(r){var e=to(r);return function(n,i,o){i=zi.joseToDer(i,"ES"+r).toString("base64");var s=e(n,i,o);return s}}function Xu(){return function(){return""}}function zu(){return function(e,t){return t===""}}ro.exports=function(e){var t={hs:Zi,rs:eo,ps:Hu,es:Bu,none:Xu},n={hs:Vu,rs:to,ps:Wu,es:Yu,none:zu},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw se(Fu,e);var o=(i[1]||i[3]).toLowerCase(),s=i[2];return{sign:t[o](s),verify:n[o](s)}}});var jr=g((uE,no)=>{var Ju=require("buffer").Buffer;no.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Ju.isBuffer(e)?e.toString():JSON.stringify(e)}});var co=g((fE,lo)=>{var Ku=Pe().Buffer,io=Lr(),Qu=Ur(),Zu=require("stream"),oo=jr(),qr=require("util");function so(r,e){return Ku.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ef(r,e,t){t=t||"utf8";var n=so(oo(r),"binary"),i=so(oo(e),t);return qr.format("%s.%s",n,i)}function ao(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,o=Qu(e.alg),s=ef(e,t,i),a=o.sign(s,n);return qr.format("%s.%s",s,a)}function xt(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new io(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new io(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))}qr.inherits(xt,Zu);xt.prototype.sign=function(){try{var e=ao({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};xt.sign=ao;lo.exports=xt});var $o=g((mE,Eo)=>{var fo=Pe().Buffer,uo=Lr(),tf=Ur(),rf=require("stream"),mo=jr(),nf=require("util"),of=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function sf(r){return Object.prototype.toString.call(r)==="[object Object]"}function af(r){if(sf(r))return r;try{return JSON.parse(r)}catch{return}}function po(r){var e=r.split(".",1)[0];return af(fo.from(e,"base64").toString("binary"))}function lf(r){return r.split(".",2).join(".")}function ho(r){return r.split(".")[2]}function cf(r,e){e=e||"utf8";var t=r.split(".")[1];return fo.from(t,"base64").toString(e)}function go(r){return of.test(r)&&!!po(r)}function yo(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=mo(r);var i=ho(r),o=lf(r),s=tf(e);return s.verify(o,i,t)}function wo(r,e){if(e=e||{},r=mo(r),!go(r))return null;var t=po(r);if(!t)return null;var n=cf(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:ho(r)}}function Ie(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 uo(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new uo(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))}nf.inherits(Ie,rf);Ie.prototype.verify=function(){try{var e=yo(this.signature.buffer,this.algorithm,this.key.buffer),t=wo(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")}};Ie.decode=wo;Ie.isValid=go;Ie.verify=yo;Eo.exports=Ie});var kt=g(we=>{var bo=co(),_t=$o(),uf=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];we.ALGORITHMS=uf;we.sign=bo.sign;we.verify=_t.verify;we.decode=_t.decode;we.isValid=_t.isValid;we.createSign=function(e){return new bo(e)};we.createVerify=function(e){return new _t(e)}});var Gr=g((pE,Ro)=>{var ff=kt();Ro.exports=function(r,e){e=e||{};var t=ff.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 ze=g((hE,So)=>{var Ot=function(r,e){Error.call(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=r,e&&(this.inner=e)};Ot.prototype=Object.create(Error.prototype);Ot.prototype.constructor=Ot;So.exports=Ot});var Vr=g((gE,xo)=>{var vo=ze(),Ct=function(r,e){vo.call(this,r),this.name="NotBeforeError",this.date=e};Ct.prototype=Object.create(vo.prototype);Ct.prototype.constructor=Ct;xo.exports=Ct});var Hr=g((yE,ko)=>{var _o=ze(),At=function(r,e){_o.call(this,r),this.name="TokenExpiredError",this.expiredAt=e};At.prototype=Object.create(_o.prototype);At.prototype.constructor=At;ko.exports=At});var Co=g((wE,Oo)=>{var Me=1e3,Ne=Me*60,De=Ne*60,ke=De*24,mf=ke*7,df=ke*365.25;Oo.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return pf(r);if(t==="number"&&isFinite(r))return e.long?gf(r):hf(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function pf(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*df;case"weeks":case"week":case"w":return t*mf;case"days":case"day":case"d":return t*ke;case"hours":case"hour":case"hrs":case"hr":case"h":return t*De;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ne;case"seconds":case"second":case"secs":case"sec":case"s":return t*Me;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hf(r){var e=Math.abs(r);return e>=ke?Math.round(r/ke)+"d":e>=De?Math.round(r/De)+"h":e>=Ne?Math.round(r/Ne)+"m":e>=Me?Math.round(r/Me)+"s":r+"ms"}function gf(r){var e=Math.abs(r);return e>=ke?Pt(r,e,ke,"day"):e>=De?Pt(r,e,De,"hour"):e>=Ne?Pt(r,e,Ne,"minute"):e>=Me?Pt(r,e,Me,"second"):r+" ms"}function Pt(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var Wr=g((EE,Ao)=>{var yf=Co();Ao.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 Fe=g(($E,Po)=>{"use strict";var wf="2.0.0",Ef=Number.MAX_SAFE_INTEGER||9007199254740991,$f=16,bf=250,Rf=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Po.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:$f,MAX_SAFE_BUILD_LENGTH:bf,MAX_SAFE_INTEGER:Ef,RELEASE_TYPES:Rf,SEMVER_SPEC_VERSION:wf,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Je=g((bE,To)=>{"use strict";var Sf=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};To.exports=Sf});var Ue=g((ue,Lo)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Br,MAX_SAFE_BUILD_LENGTH:vf,MAX_LENGTH:xf}=Fe(),_f=Je();ue=Lo.exports={};var kf=ue.re=[],Of=ue.safeRe=[],E=ue.src=[],Cf=ue.safeSrc=[],$=ue.t={},Af=0,Yr="[a-zA-Z0-9-]",Pf=[["\\s",1],["\\d",xf],[Yr,vf]],Tf=r=>{for(let[e,t]of Pf)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},v=(r,e,t)=>{let n=Tf(e),i=Af++;_f(r,i,e),$[r]=i,E[i]=e,Cf[i]=n,kf[i]=new RegExp(e,t?"g":void 0),Of[i]=new RegExp(n,t?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*");v("NUMERICIDENTIFIERLOOSE","\\d+");v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Yr}*`);v("MAINVERSION",`(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})\\.(${E[$.NUMERICIDENTIFIER]})`);v("MAINVERSIONLOOSE",`(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})\\.(${E[$.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASEIDENTIFIER",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIER]})`);v("PRERELEASEIDENTIFIERLOOSE",`(?:${E[$.NONNUMERICIDENTIFIER]}|${E[$.NUMERICIDENTIFIERLOOSE]})`);v("PRERELEASE",`(?:-(${E[$.PRERELEASEIDENTIFIER]}(?:\\.${E[$.PRERELEASEIDENTIFIER]})*))`);v("PRERELEASELOOSE",`(?:-?(${E[$.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${E[$.PRERELEASEIDENTIFIERLOOSE]})*))`);v("BUILDIDENTIFIER",`${Yr}+`);v("BUILD",`(?:\\+(${E[$.BUILDIDENTIFIER]}(?:\\.${E[$.BUILDIDENTIFIER]})*))`);v("FULLPLAIN",`v?${E[$.MAINVERSION]}${E[$.PRERELEASE]}?${E[$.BUILD]}?`);v("FULL",`^${E[$.FULLPLAIN]}$`);v("LOOSEPLAIN",`[v=\\s]*${E[$.MAINVERSIONLOOSE]}${E[$.PRERELEASELOOSE]}?${E[$.BUILD]}?`);v("LOOSE",`^${E[$.LOOSEPLAIN]}$`);v("GTLT","((?:<|>)?=?)");v("XRANGEIDENTIFIERLOOSE",`${E[$.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);v("XRANGEIDENTIFIER",`${E[$.NUMERICIDENTIFIER]}|x|X|\\*`);v("XRANGEPLAIN",`[v=\\s]*(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:\\.(${E[$.XRANGEIDENTIFIER]})(?:${E[$.PRERELEASE]})?${E[$.BUILD]}?)?)?`);v("XRANGEPLAINLOOSE",`[v=\\s]*(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:\\.(${E[$.XRANGEIDENTIFIERLOOSE]})(?:${E[$.PRERELEASELOOSE]})?${E[$.BUILD]}?)?)?`);v("XRANGE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAIN]}$`);v("XRANGELOOSE",`^${E[$.GTLT]}\\s*${E[$.XRANGEPLAINLOOSE]}$`);v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Br}})(?:\\.(\\d{1,${Br}}))?(?:\\.(\\d{1,${Br}}))?`);v("COERCE",`${E[$.COERCEPLAIN]}(?:$|[^\\d])`);v("COERCEFULL",E[$.COERCEPLAIN]+`(?:${E[$.PRERELEASE]})?(?:${E[$.BUILD]})?(?:$|[^\\d])`);v("COERCERTL",E[$.COERCE],!0);v("COERCERTLFULL",E[$.COERCEFULL],!0);v("LONETILDE","(?:~>?)");v("TILDETRIM",`(\\s*)${E[$.LONETILDE]}\\s+`,!0);ue.tildeTrimReplace="$1~";v("TILDE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAIN]}$`);v("TILDELOOSE",`^${E[$.LONETILDE]}${E[$.XRANGEPLAINLOOSE]}$`);v("LONECARET","(?:\\^)");v("CARETTRIM",`(\\s*)${E[$.LONECARET]}\\s+`,!0);ue.caretTrimReplace="$1^";v("CARET",`^${E[$.LONECARET]}${E[$.XRANGEPLAIN]}$`);v("CARETLOOSE",`^${E[$.LONECARET]}${E[$.XRANGEPLAINLOOSE]}$`);v("COMPARATORLOOSE",`^${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]})$|^$`);v("COMPARATOR",`^${E[$.GTLT]}\\s*(${E[$.FULLPLAIN]})$|^$`);v("COMPARATORTRIM",`(\\s*)${E[$.GTLT]}\\s*(${E[$.LOOSEPLAIN]}|${E[$.XRANGEPLAIN]})`,!0);ue.comparatorTrimReplace="$1$2$3";v("HYPHENRANGE",`^\\s*(${E[$.XRANGEPLAIN]})\\s+-\\s+(${E[$.XRANGEPLAIN]})\\s*$`);v("HYPHENRANGELOOSE",`^\\s*(${E[$.XRANGEPLAINLOOSE]})\\s+-\\s+(${E[$.XRANGEPLAINLOOSE]})\\s*$`);v("STAR","(<|>)?=?\\s*\\*");v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Tt=g((RE,Io)=>{"use strict";var Lf=Object.freeze({loose:!0}),If=Object.freeze({}),Mf=r=>r?typeof r!="object"?Lf:r:If;Io.exports=Mf});var Xr=g((SE,Do)=>{"use strict";var Mo=/^[0-9]+$/,No=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r<e?-1:1;let t=Mo.test(r),n=Mo.test(e);return t&&n&&(r=+r,e=+e),r===e?0:t&&!n?-1:n&&!t?1:r<e?-1:1},Nf=(r,e)=>No(e,r);Do.exports={compareIdentifiers:No,rcompareIdentifiers:Nf}});var W=g((vE,Uo)=>{"use strict";var Lt=Je(),{MAX_LENGTH:Fo,MAX_SAFE_INTEGER:It}=Fe(),{safeRe:Mt,t:Nt}=Ue(),Df=Tt(),{compareIdentifiers:zr}=Xr(),Jr=class r{constructor(e,t){if(t=Df(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>Fo)throw new TypeError(`version is longer than ${Fo} characters`);Lt("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Mt[Nt.LOOSE]:Mt[Nt.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>It||this.major<0)throw new TypeError("Invalid major version");if(this.minor>It||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>It||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let o=+i;if(o>=0&&o<It)return o}return i}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Lt("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Lt("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return zr(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Lt("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return zr(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?Mt[Nt.PRERELEASELOOSE]:Mt[Nt.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 o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let o=[t,i];n===!1&&(o=[t]),zr(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Uo.exports=Jr});var Ee=g((xE,qo)=>{"use strict";var jo=W(),Ff=(r,e,t=!1)=>{if(r instanceof jo)return r;try{return new jo(r,e)}catch(n){if(!t)return null;throw n}};qo.exports=Ff});var Vo=g((_E,Go)=>{"use strict";var Uf=Ee(),jf=(r,e)=>{let t=Uf(r,e);return t?t.version:null};Go.exports=jf});var Wo=g((kE,Ho)=>{"use strict";var qf=Ee(),Gf=(r,e)=>{let t=qf(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Ho.exports=Gf});var Xo=g((OE,Yo)=>{"use strict";var Bo=W(),Vf=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Bo(r instanceof Bo?r.version:r,t).inc(e,n,i).version}catch{return null}};Yo.exports=Vf});var Ko=g((CE,Jo)=>{"use strict";var zo=Ee(),Hf=(r,e)=>{let t=zo(r,null,!0),n=zo(e,null,!0),i=t.compare(n);if(i===0)return null;let o=i>0,s=o?t:n,a=o?n:t,l=!!s.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let c=l?"pre":"";return t.major!==n.major?c+"major":t.minor!==n.minor?c+"minor":t.patch!==n.patch?c+"patch":"prerelease"};Jo.exports=Hf});var Zo=g((AE,Qo)=>{"use strict";var Wf=W(),Bf=(r,e)=>new Wf(r,e).major;Qo.exports=Bf});var ts=g((PE,es)=>{"use strict";var Yf=W(),Xf=(r,e)=>new Yf(r,e).minor;es.exports=Xf});var ns=g((TE,rs)=>{"use strict";var zf=W(),Jf=(r,e)=>new zf(r,e).patch;rs.exports=Jf});var os=g((LE,is)=>{"use strict";var Kf=Ee(),Qf=(r,e)=>{let t=Kf(r,e);return t&&t.prerelease.length?t.prerelease:null};is.exports=Qf});var te=g((IE,as)=>{"use strict";var ss=W(),Zf=(r,e,t)=>new ss(r,t).compare(new ss(e,t));as.exports=Zf});var cs=g((ME,ls)=>{"use strict";var em=te(),tm=(r,e,t)=>em(e,r,t);ls.exports=tm});var fs=g((NE,us)=>{"use strict";var rm=te(),nm=(r,e)=>rm(r,e,!0);us.exports=nm});var Dt=g((DE,ds)=>{"use strict";var ms=W(),im=(r,e,t)=>{let n=new ms(r,t),i=new ms(e,t);return n.compare(i)||n.compareBuild(i)};ds.exports=im});var hs=g((FE,ps)=>{"use strict";var om=Dt(),sm=(r,e)=>r.sort((t,n)=>om(t,n,e));ps.exports=sm});var ys=g((UE,gs)=>{"use strict";var am=Dt(),lm=(r,e)=>r.sort((t,n)=>am(n,t,e));gs.exports=lm});var Ke=g((jE,ws)=>{"use strict";var cm=te(),um=(r,e,t)=>cm(r,e,t)>0;ws.exports=um});var Ft=g((qE,Es)=>{"use strict";var fm=te(),mm=(r,e,t)=>fm(r,e,t)<0;Es.exports=mm});var Kr=g((GE,$s)=>{"use strict";var dm=te(),pm=(r,e,t)=>dm(r,e,t)===0;$s.exports=pm});var Qr=g((VE,bs)=>{"use strict";var hm=te(),gm=(r,e,t)=>hm(r,e,t)!==0;bs.exports=gm});var Ut=g((HE,Rs)=>{"use strict";var ym=te(),wm=(r,e,t)=>ym(r,e,t)>=0;Rs.exports=wm});var jt=g((WE,Ss)=>{"use strict";var Em=te(),$m=(r,e,t)=>Em(r,e,t)<=0;Ss.exports=$m});var Zr=g((BE,vs)=>{"use strict";var bm=Kr(),Rm=Qr(),Sm=Ke(),vm=Ut(),xm=Ft(),_m=jt(),km=(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 bm(r,t,n);case"!=":return Rm(r,t,n);case">":return Sm(r,t,n);case">=":return vm(r,t,n);case"<":return xm(r,t,n);case"<=":return _m(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};vs.exports=km});var _s=g((YE,xs)=>{"use strict";var Om=W(),Cm=Ee(),{safeRe:qt,t:Gt}=Ue(),Am=(r,e)=>{if(r instanceof Om)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?qt[Gt.COERCEFULL]:qt[Gt.COERCE]);else{let l=e.includePrerelease?qt[Gt.COERCERTLFULL]:qt[Gt.COERCERTL],u;for(;(u=l.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",o=t[4]||"0",s=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Cm(`${n}.${i}.${o}${s}${a}`,e)};xs.exports=Am});var Os=g((XE,ks)=>{"use strict";var Pm=Ee(),Tm=Fe(),Lm=W(),Im=(r,e,t)=>{if(!Tm.RELEASE_TYPES.includes(e))return null;let n=Mm(r,t);return n&&Nm(n,e)},Mm=(r,e)=>{let t=r instanceof Lm?r.version:r;return Pm(t,e)},Nm=(r,e)=>{if(Dm(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()},Dm=r=>r.startsWith("pre");ks.exports=Im});var As=g((zE,Cs)=>{"use strict";var en=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}};Cs.exports=en});var re=g((JE,Is)=>{"use strict";var Fm=/\s+/g,tn=class r{constructor(e,t){if(t=jm(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof rn)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(Fm," "),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=>!Ts(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&&Ym(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&&Wm)|(this.options.loose&&Bm))+":"+e,i=Ps.get(n);if(i)return i;let o=this.options.loose,s=o?X[B.HYPHENRANGELOOSE]:X[B.HYPHENRANGE];e=e.replace(s,nd(this.options.includePrerelease)),I("hyphen replace",e),e=e.replace(X[B.COMPARATORTRIM],Gm),I("comparator trim",e),e=e.replace(X[B.TILDETRIM],Vm),I("tilde trim",e),e=e.replace(X[B.CARETTRIM],Hm),I("caret trim",e);let a=e.split(" ").map(m=>Xm(m,this.options)).join(" ").split(/\s+/).map(m=>rd(m,this.options));o&&(a=a.filter(m=>(I("loose invalid filter",m,this.options),!!m.match(X[B.COMPARATORLOOSE])))),I("range list",a);let l=new Map,u=a.map(m=>new rn(m,this.options));for(let m of u){if(Ts(m))return[m];l.set(m.value,m)}l.size>1&&l.has("")&&l.delete("");let c=[...l.values()];return Ps.set(n,c),c}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Ls(n,t)&&e.set.some(i=>Ls(i,t)&&n.every(o=>i.every(s=>o.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new qm(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(id(this.set[t],e,this.options))return!0;return!1}};Is.exports=tn;var Um=As(),Ps=new Um,jm=Tt(),rn=Qe(),I=Je(),qm=W(),{safeRe:X,t:B,comparatorTrimReplace:Gm,tildeTrimReplace:Vm,caretTrimReplace:Hm}=Ue(),{FLAG_INCLUDE_PRERELEASE:Wm,FLAG_LOOSE:Bm}=Fe(),Ts=r=>r.value==="<0.0.0-0",Ym=r=>r.value==="",Ls=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(o=>i.intersects(o,e)),i=n.pop();return t},Xm=(r,e)=>(r=r.replace(X[B.BUILD],""),I("comp",r,e),r=Km(r,e),I("caret",r),r=zm(r,e),I("tildes",r),r=Zm(r,e),I("xrange",r),r=td(r,e),I("stars",r),r),z=r=>!r||r.toLowerCase()==="x"||r==="*",zm=(r,e)=>r.trim().split(/\s+/).map(t=>Jm(t,e)).join(" "),Jm=(r,e)=>{let t=e.loose?X[B.TILDELOOSE]:X[B.TILDE];return r.replace(t,(n,i,o,s,a)=>{I("tilde",r,n,i,o,s,a);let l;return z(i)?l="":z(o)?l=`>=${i}.0.0 <${+i+1}.0.0-0`:z(s)?l=`>=${i}.${o}.0 <${i}.${+o+1}.0-0`:a?(I("replaceTilde pr",a),l=`>=${i}.${o}.${s}-${a} <${i}.${+o+1}.0-0`):l=`>=${i}.${o}.${s} <${i}.${+o+1}.0-0`,I("tilde return",l),l})},Km=(r,e)=>r.trim().split(/\s+/).map(t=>Qm(t,e)).join(" "),Qm=(r,e)=>{I("caret",r,e);let t=e.loose?X[B.CARETLOOSE]:X[B.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,o,s,a,l)=>{I("caret",r,i,o,s,a,l);let u;return z(o)?u="":z(s)?u=`>=${o}.0.0${n} <${+o+1}.0.0-0`:z(a)?o==="0"?u=`>=${o}.${s}.0${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.0${n} <${+o+1}.0.0-0`:l?(I("replaceCaret pr",l),o==="0"?s==="0"?u=`>=${o}.${s}.${a}-${l} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}-${l} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a}-${l} <${+o+1}.0.0-0`):(I("no pr"),o==="0"?s==="0"?u=`>=${o}.${s}.${a}${n} <${o}.${s}.${+a+1}-0`:u=`>=${o}.${s}.${a}${n} <${o}.${+s+1}.0-0`:u=`>=${o}.${s}.${a} <${+o+1}.0.0-0`),I("caret return",u),u})},Zm=(r,e)=>(I("replaceXRanges",r,e),r.split(/\s+/).map(t=>ed(t,e)).join(" ")),ed=(r,e)=>{r=r.trim();let t=e.loose?X[B.XRANGELOOSE]:X[B.XRANGE];return r.replace(t,(n,i,o,s,a,l)=>{I("xRange",r,n,i,o,s,a,l);let u=z(o),c=u||z(s),m=c||z(a),d=m;return i==="="&&d&&(i=""),l=e.includePrerelease?"-0":"",u?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&d?(c&&(s=0),a=0,i===">"?(i=">=",c?(o=+o+1,s=0,a=0):(s=+s+1,a=0)):i==="<="&&(i="<",c?o=+o+1:s=+s+1),i==="<"&&(l="-0"),n=`${i+o}.${s}.${a}${l}`):c?n=`>=${o}.0.0${l} <${+o+1}.0.0-0`:m&&(n=`>=${o}.${s}.0${l} <${o}.${+s+1}.0-0`),I("xRange return",n),n})},td=(r,e)=>(I("replaceStars",r,e),r.trim().replace(X[B.STAR],"")),rd=(r,e)=>(I("replaceGTE0",r,e),r.trim().replace(X[e.includePrerelease?B.GTE0PRE:B.GTE0],"")),nd=r=>(e,t,n,i,o,s,a,l,u,c,m,d)=>(z(n)?t="":z(i)?t=`>=${n}.0.0${r?"-0":""}`:z(o)?t=`>=${n}.${i}.0${r?"-0":""}`:s?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,z(u)?l="":z(c)?l=`<${+u+1}.0.0-0`:z(m)?l=`<${u}.${+c+1}.0-0`:d?l=`<=${u}.${c}.${m}-${d}`:r?l=`<${u}.${c}.${+m+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),id=(r,e,t)=>{for(let n=0;n<r.length;n++)if(!r[n].test(e))return!1;if(e.prerelease.length&&!t.includePrerelease){for(let n=0;n<r.length;n++)if(I(r[n].semver),r[n].semver!==rn.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 Qe=g((KE,js)=>{"use strict";var Ze=Symbol("SemVer ANY"),sn=class r{static get ANY(){return Ze}constructor(e,t){if(t=Ms(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),on("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ze?this.value="":this.value=this.operator+this.semver.version,on("comp",this)}parse(e){let t=this.options.loose?Ns[Ds.COMPARATORLOOSE]:Ns[Ds.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 Fs(n[2],this.options.loose):this.semver=Ze}toString(){return this.value}test(e){if(on("Comparator.test",e,this.options.loose),this.semver===Ze||e===Ze)return!0;if(typeof e=="string")try{e=new Fs(e,this.options)}catch{return!1}return nn(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 Us(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Us(this.value,t).test(e.semver):(t=Ms(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("=")||nn(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||nn(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};js.exports=sn;var Ms=Tt(),{safeRe:Ns,t:Ds}=Ue(),nn=Zr(),on=Je(),Fs=W(),Us=re()});var et=g((QE,qs)=>{"use strict";var od=re(),sd=(r,e,t)=>{try{e=new od(e,t)}catch{return!1}return e.test(r)};qs.exports=sd});var Vs=g((ZE,Gs)=>{"use strict";var ad=re(),ld=(r,e)=>new ad(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Gs.exports=ld});var Ws=g((e$,Hs)=>{"use strict";var cd=W(),ud=re(),fd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new ud(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===-1)&&(n=s,i=new cd(n,t))}),n};Hs.exports=fd});var Ys=g((t$,Bs)=>{"use strict";var md=W(),dd=re(),pd=(r,e,t)=>{let n=null,i=null,o=null;try{o=new dd(e,t)}catch{return null}return r.forEach(s=>{o.test(s)&&(!n||i.compare(s)===1)&&(n=s,i=new md(n,t))}),n};Bs.exports=pd});var Js=g((r$,zs)=>{"use strict";var an=W(),hd=re(),Xs=Ke(),gd=(r,e)=>{r=new hd(r,e);let t=new an("0.0.0");if(r.test(t)||(t=new an("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],o=null;i.forEach(s=>{let a=new an(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Xs(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),o&&(!t||Xs(t,o))&&(t=o)}return t&&r.test(t)?t:null};zs.exports=gd});var Qs=g((n$,Ks)=>{"use strict";var yd=re(),wd=(r,e)=>{try{return new yd(r,e).range||"*"}catch{return null}};Ks.exports=wd});var Vt=g((i$,ra)=>{"use strict";var Ed=W(),ta=Qe(),{ANY:$d}=ta,bd=re(),Rd=et(),Zs=Ke(),ea=Ft(),Sd=jt(),vd=Ut(),xd=(r,e,t,n)=>{r=new Ed(r,n),e=new bd(e,n);let i,o,s,a,l;switch(t){case">":i=Zs,o=Sd,s=ea,a=">",l=">=";break;case"<":i=ea,o=vd,s=Zs,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Rd(r,e,n))return!1;for(let u=0;u<e.set.length;++u){let c=e.set[u],m=null,d=null;if(c.forEach(p=>{p.semver===$d&&(p=new ta(">=0.0.0")),m=m||p,d=d||p,i(p.semver,m.semver,n)?m=p:s(p.semver,d.semver,n)&&(d=p)}),m.operator===a||m.operator===l||(!d.operator||d.operator===a)&&o(r,d.semver))return!1;if(d.operator===l&&s(r,d.semver))return!1}return!0};ra.exports=xd});var ia=g((o$,na)=>{"use strict";var _d=Vt(),kd=(r,e,t)=>_d(r,e,">",t);na.exports=kd});var sa=g((s$,oa)=>{"use strict";var Od=Vt(),Cd=(r,e,t)=>Od(r,e,"<",t);oa.exports=Cd});var ca=g((a$,la)=>{"use strict";var aa=re(),Ad=(r,e,t)=>(r=new aa(r,t),e=new aa(e,t),r.intersects(e,t));la.exports=Ad});var fa=g((l$,ua)=>{"use strict";var Pd=et(),Td=te();ua.exports=(r,e,t)=>{let n=[],i=null,o=null,s=r.sort((c,m)=>Td(c,m,t));for(let c of s)Pd(c,e,t)?(o=c,i||(i=c)):(o&&n.push([i,o]),o=null,i=null);i&&n.push([i,null]);let a=[];for(let[c,m]of n)c===m?a.push(c):!m&&c===s[0]?a.push("*"):m?c===s[0]?a.push(`<=${m}`):a.push(`${c} - ${m}`):a.push(`>=${c}`);let l=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var ya=g((c$,ga)=>{"use strict";var ma=re(),cn=Qe(),{ANY:ln}=cn,tt=et(),un=te(),Ld=(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 o of e.set){let s=Md(i,o,t);if(n=n||s!==null,s)continue e}if(n)return!1}return!0},Id=[new cn(">=0.0.0-0")],da=[new cn(">=0.0.0")],Md=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ln){if(e.length===1&&e[0].semver===ln)return!0;t.includePrerelease?r=Id:r=da}if(e.length===1&&e[0].semver===ln){if(t.includePrerelease)return!0;e=da}let n=new Set,i,o;for(let p of r)p.operator===">"||p.operator===">="?i=pa(i,p,t):p.operator==="<"||p.operator==="<="?o=ha(o,p,t):n.add(p.semver);if(n.size>1)return null;let s;if(i&&o){if(s=un(i.semver,o.semver,t),s>0)return null;if(s===0&&(i.operator!==">="||o.operator!=="<="))return null}for(let p of n){if(i&&!tt(p,String(i),t)||o&&!tt(p,String(o),t))return null;for(let w of e)if(!tt(p,String(w),t))return!1;return!0}let a,l,u,c,m=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;m&&m.prerelease.length===1&&o.operator==="<"&&m.prerelease[0]===0&&(m=!1);for(let p of e){if(c=c||p.operator===">"||p.operator===">=",u=u||p.operator==="<"||p.operator==="<=",i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator===">"||p.operator===">="){if(a=pa(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!tt(i.semver,String(p),t))return!1}if(o){if(m&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch&&(m=!1),p.operator==="<"||p.operator==="<="){if(l=ha(o,p,t),l===p&&l!==o)return!1}else if(o.operator==="<="&&!tt(o.semver,String(p),t))return!1}if(!p.operator&&(o||i)&&s!==0)return!1}return!(i&&u&&!o&&s!==0||o&&c&&!i&&s!==0||d||m)},pa=(r,e,t)=>{if(!r)return e;let n=un(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},ha=(r,e,t)=>{if(!r)return e;let n=un(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};ga.exports=Ld});var Ht=g((u$,$a)=>{"use strict";var fn=Ue(),wa=Fe(),Nd=W(),Ea=Xr(),Dd=Ee(),Fd=Vo(),Ud=Wo(),jd=Xo(),qd=Ko(),Gd=Zo(),Vd=ts(),Hd=ns(),Wd=os(),Bd=te(),Yd=cs(),Xd=fs(),zd=Dt(),Jd=hs(),Kd=ys(),Qd=Ke(),Zd=Ft(),ep=Kr(),tp=Qr(),rp=Ut(),np=jt(),ip=Zr(),op=_s(),sp=Os(),ap=Qe(),lp=re(),cp=et(),up=Vs(),fp=Ws(),mp=Ys(),dp=Js(),pp=Qs(),hp=Vt(),gp=ia(),yp=sa(),wp=ca(),Ep=fa(),$p=ya();$a.exports={parse:Dd,valid:Fd,clean:Ud,inc:jd,diff:qd,major:Gd,minor:Vd,patch:Hd,prerelease:Wd,compare:Bd,rcompare:Yd,compareLoose:Xd,compareBuild:zd,sort:Jd,rsort:Kd,gt:Qd,lt:Zd,eq:ep,neq:tp,gte:rp,lte:np,cmp:ip,coerce:op,truncate:sp,Comparator:ap,Range:lp,satisfies:cp,toComparators:up,maxSatisfying:fp,minSatisfying:mp,minVersion:dp,validRange:pp,outside:hp,gtr:gp,ltr:yp,intersects:wp,simplifyRange:Ep,subset:$p,SemVer:Nd,re:fn.re,src:fn.src,tokens:fn.t,SEMVER_SPEC_VERSION:wa.SEMVER_SPEC_VERSION,RELEASE_TYPES:wa.RELEASE_TYPES,compareIdentifiers:Ea.compareIdentifiers,rcompareIdentifiers:Ea.rcompareIdentifiers}});var Ra=g((f$,ba)=>{var bp=Ht();ba.exports=bp.satisfies(process.version,">=15.7.0")});var va=g((m$,Sa)=>{var Rp=Ht();Sa.exports=Rp.satisfies(process.version,">=16.9.0")});var mn=g((d$,xa)=>{var Sp=Ra(),vp=va(),xp={ec:["ES256","ES384","ES512"],rsa:["RS256","PS256","RS384","PS384","RS512","PS512"],"rsa-pss":["PS256","PS384","PS512"]},_p={ES256:"prime256v1",ES384:"secp384r1",ES512:"secp521r1"};xa.exports=function(r,e){if(!r||!e)return;let t=e.asymmetricKeyType;if(!t)return;let n=xp[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(Sp)switch(t){case"ec":let i=e.asymmetricKeyDetails.namedCurve,o=_p[r];if(i!==o)throw new Error(`"alg" parameter "${r}" requires curve "${o}".`);break;case"rsa-pss":if(vp){let s=parseInt(r.slice(-3),10),{hashAlgorithm:a,mgf1HashAlgorithm:l,saltLength:u}=e.asymmetricKeyDetails;if(a!==`sha${s}`||l!==a)throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${r}.`);if(u!==void 0&&u>s>>3)throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${r}.`)}break}}});var dn=g((p$,_a)=>{var kp=Ht();_a.exports=kp.satisfies(process.version,"^6.12.0 || >=8.0.0")});var Ca=g((h$,Oa)=>{var L=ze(),Op=Vr(),ka=Hr(),Cp=Gr(),Ap=Wr(),Pp=mn(),Tp=dn(),Lp=kt(),{KeyObject:Ip,createSecretKey:Mp,createPublicKey:Np}=require("crypto"),pn=["RS256","RS384","RS512"],Dp=["ES256","ES384","ES512"],hn=["RS256","RS384","RS512"],Fp=["HS256","HS384","HS512"];Tp&&(pn.splice(pn.length,0,"PS256","PS384","PS512"),hn.splice(hn.length,0,"PS256","PS384","PS512"));Oa.exports=function(r,e,t,n){typeof t=="function"&&!n&&(n=t,t={}),t||(t={}),t=Object.assign({},t);let i;if(n?i=n:i=function(c,m){if(c)throw c;return m},t.clockTimestamp&&typeof t.clockTimestamp!="number")return i(new L("clockTimestamp must be a number"));if(t.nonce!==void 0&&(typeof t.nonce!="string"||t.nonce.trim()===""))return i(new L("nonce must be a non-empty string"));if(t.allowInvalidAsymmetricKeyTypes!==void 0&&typeof t.allowInvalidAsymmetricKeyTypes!="boolean")return i(new L("allowInvalidAsymmetricKeyTypes must be a boolean"));let o=t.clockTimestamp||Math.floor(Date.now()/1e3);if(!r)return i(new L("jwt must be provided"));if(typeof r!="string")return i(new L("jwt must be a string"));let s=r.split(".");if(s.length!==3)return i(new L("jwt malformed"));let a;try{a=Cp(r,{complete:!0})}catch(c){return i(c)}if(!a)return i(new L("invalid token"));let l=a.header,u;if(typeof e=="function"){if(!n)return i(new L("verify must be called asynchronous if secret or public key is provided as a callback"));u=e}else u=function(c,m){return m(null,e)};return u(l,function(c,m){if(c)return i(new L("error in secret or public key callback: "+c.message));let d=s[2].trim()!=="";if(!d&&m)return i(new L("jwt signature is required"));if(d&&!m)return i(new L("secret or public key must be provided"));if(!d&&!t.algorithms)return i(new L('please specify "none" in "algorithms" to verify unsigned tokens'));if(m!=null&&!(m instanceof Ip))try{m=Np(m)}catch{try{m=Mp(typeof m=="string"?Buffer.from(m):m)}catch{return i(new L("secretOrPublicKey is not valid key material"))}}if(t.algorithms||(m.type==="secret"?t.algorithms=Fp:["rsa","rsa-pss"].includes(m.asymmetricKeyType)?t.algorithms=hn:m.asymmetricKeyType==="ec"?t.algorithms=Dp:t.algorithms=pn),t.algorithms.indexOf(a.header.alg)===-1)return i(new L("invalid algorithm"));if(l.alg.startsWith("HS")&&m.type!=="secret")return i(new L(`secretOrPublicKey must be a symmetric key when using ${l.alg}`));if(/^(?:RS|PS|ES)/.test(l.alg)&&m.type!=="public")return i(new L(`secretOrPublicKey must be an asymmetric key when using ${l.alg}`));if(!t.allowInvalidAsymmetricKeyTypes)try{Pp(l.alg,m)}catch(x){return i(x)}let p;try{p=Lp.verify(r,a.header.alg,m)}catch(x){return i(x)}if(!p)return i(new L("invalid signature"));let w=a.payload;if(typeof w.nbf<"u"&&!t.ignoreNotBefore){if(typeof w.nbf!="number")return i(new L("invalid nbf value"));if(w.nbf>o+(t.clockTolerance||0))return i(new Op("jwt not active",new Date(w.nbf*1e3)))}if(typeof w.exp<"u"&&!t.ignoreExpiration){if(typeof w.exp!="number")return i(new L("invalid exp value"));if(o>=w.exp+(t.clockTolerance||0))return i(new ka("jwt expired",new Date(w.exp*1e3)))}if(t.audience){let x=Array.isArray(t.audience)?t.audience:[t.audience];if(!(Array.isArray(w.aud)?w.aud:[w.aud]).some(function(b){return x.some(function(R){return R instanceof RegExp?R.test(b):R===b})}))return i(new L("jwt audience invalid. expected: "+x.join(" or ")))}if(t.issuer&&(typeof t.issuer=="string"&&w.iss!==t.issuer||Array.isArray(t.issuer)&&t.issuer.indexOf(w.iss)===-1))return i(new L("jwt issuer invalid. expected: "+t.issuer));if(t.subject&&w.sub!==t.subject)return i(new L("jwt subject invalid. expected: "+t.subject));if(t.jwtid&&w.jti!==t.jwtid)return i(new L("jwt jwtid invalid. expected: "+t.jwtid));if(t.nonce&&w.nonce!==t.nonce)return i(new L("jwt nonce invalid. expected: "+t.nonce));if(t.maxAge){if(typeof w.iat!="number")return i(new L("iat required when maxAge is specified"));let x=Ap(t.maxAge,w.iat);if(typeof x>"u")return i(new L('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=x+(t.clockTolerance||0))return i(new ka("maxAge exceeded",new Date(x*1e3)))}if(t.complete===!0){let x=a.signature;return i(null,{header:l,payload:w,signature:x})}return i(null,w)})}});var Ma=g((g$,Ia)=>{var Aa=1/0,Ta=9007199254740991,Up=17976931348623157e292,Pa=NaN,jp="[object Arguments]",qp="[object Function]",Gp="[object GeneratorFunction]",Vp="[object String]",Hp="[object Symbol]",Wp=/^\s+|\s+$/g,Bp=/^[-+]0x[0-9a-f]+$/i,Yp=/^0b[01]+$/i,Xp=/^0o[0-7]+$/i,zp=/^(?:0|[1-9]\d*)$/,Jp=parseInt;function Kp(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 Qp(r,e,t,n){for(var i=r.length,o=t+(n?1:-1);n?o--:++o<i;)if(e(r[o],o,r))return o;return-1}function Zp(r,e,t){if(e!==e)return Qp(r,eh,t);for(var n=t-1,i=r.length;++n<i;)if(r[n]===e)return n;return-1}function eh(r){return r!==r}function th(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}function rh(r,e){return Kp(e,function(t){return r[t]})}function nh(r,e){return function(t){return r(e(t))}}var Wt=Object.prototype,yn=Wt.hasOwnProperty,Bt=Wt.toString,ih=Wt.propertyIsEnumerable,oh=nh(Object.keys,Object),sh=Math.max;function ah(r,e){var t=La(r)||mh(r)?th(r.length,String):[],n=t.length,i=!!n;for(var o in r)(e||yn.call(r,o))&&!(i&&(o=="length"||ch(o,n)))&&t.push(o);return t}function lh(r){if(!uh(r))return oh(r);var e=[];for(var t in Object(r))yn.call(r,t)&&t!="constructor"&&e.push(t);return e}function ch(r,e){return e=e??Ta,!!e&&(typeof r=="number"||zp.test(r))&&r>-1&&r%1==0&&r<e}function uh(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Wt;return r===t}function fh(r,e,t,n){r=wn(r)?r:Rh(r),t=t&&!n?Eh(t):0;var i=r.length;return t<0&&(t=sh(i+t,0)),gh(r)?t<=i&&r.indexOf(e,t)>-1:!!i&&Zp(r,e,t)>-1}function mh(r){return dh(r)&&yn.call(r,"callee")&&(!ih.call(r,"callee")||Bt.call(r)==jp)}var La=Array.isArray;function wn(r){return r!=null&&hh(r.length)&&!ph(r)}function dh(r){return En(r)&&wn(r)}function ph(r){var e=gn(r)?Bt.call(r):"";return e==qp||e==Gp}function hh(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ta}function gn(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function En(r){return!!r&&typeof r=="object"}function gh(r){return typeof r=="string"||!La(r)&&En(r)&&Bt.call(r)==Vp}function yh(r){return typeof r=="symbol"||En(r)&&Bt.call(r)==Hp}function wh(r){if(!r)return r===0?r:0;if(r=$h(r),r===Aa||r===-Aa){var e=r<0?-1:1;return e*Up}return r===r?r:0}function Eh(r){var e=wh(r),t=e%1;return e===e?t?e-t:e:0}function $h(r){if(typeof r=="number")return r;if(yh(r))return Pa;if(gn(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=gn(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Wp,"");var t=Yp.test(r);return t||Xp.test(r)?Jp(r.slice(2),t?2:8):Bp.test(r)?Pa:+r}function bh(r){return wn(r)?ah(r):lh(r)}function Rh(r){return r?rh(r,bh(r)):[]}Ia.exports=fh});var Da=g((y$,Na)=>{var Sh="[object Boolean]",vh=Object.prototype,xh=vh.toString;function _h(r){return r===!0||r===!1||kh(r)&&xh.call(r)==Sh}function kh(r){return!!r&&typeof r=="object"}Na.exports=_h});var Ga=g((w$,qa)=>{var Fa=1/0,Oh=17976931348623157e292,Ua=NaN,Ch="[object Symbol]",Ah=/^\s+|\s+$/g,Ph=/^[-+]0x[0-9a-f]+$/i,Th=/^0b[01]+$/i,Lh=/^0o[0-7]+$/i,Ih=parseInt,Mh=Object.prototype,Nh=Mh.toString;function Dh(r){return typeof r=="number"&&r==qh(r)}function ja(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Fh(r){return!!r&&typeof r=="object"}function Uh(r){return typeof r=="symbol"||Fh(r)&&Nh.call(r)==Ch}function jh(r){if(!r)return r===0?r:0;if(r=Gh(r),r===Fa||r===-Fa){var e=r<0?-1:1;return e*Oh}return r===r?r:0}function qh(r){var e=jh(r),t=e%1;return e===e?t?e-t:e:0}function Gh(r){if(typeof r=="number")return r;if(Uh(r))return Ua;if(ja(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=ja(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=r.replace(Ah,"");var t=Th.test(r);return t||Lh.test(r)?Ih(r.slice(2),t?2:8):Ph.test(r)?Ua:+r}qa.exports=Dh});var Ha=g((E$,Va)=>{var Vh="[object Number]",Hh=Object.prototype,Wh=Hh.toString;function Bh(r){return!!r&&typeof r=="object"}function Yh(r){return typeof r=="number"||Bh(r)&&Wh.call(r)==Vh}Va.exports=Yh});var Xa=g(($$,Ya)=>{var Xh="[object Object]";function zh(r){var e=!1;if(r!=null&&typeof r.toString!="function")try{e=!!(r+"")}catch{}return e}function Jh(r,e){return function(t){return r(e(t))}}var Kh=Function.prototype,Wa=Object.prototype,Ba=Kh.toString,Qh=Wa.hasOwnProperty,Zh=Ba.call(Object),eg=Wa.toString,tg=Jh(Object.getPrototypeOf,Object);function rg(r){return!!r&&typeof r=="object"}function ng(r){if(!rg(r)||eg.call(r)!=Xh||zh(r))return!1;var e=tg(r);if(e===null)return!0;var t=Qh.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&Ba.call(t)==Zh}Ya.exports=ng});var Ja=g((b$,za)=>{var ig="[object String]",og=Object.prototype,sg=og.toString,ag=Array.isArray;function lg(r){return!!r&&typeof r=="object"}function cg(r){return typeof r=="string"||!ag(r)&&lg(r)&&sg.call(r)==ig}za.exports=cg});var tl=g((R$,el)=>{var ug="Expected a function",Ka=1/0,fg=17976931348623157e292,Qa=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 $g(r,e){var t;if(typeof e!="function")throw new TypeError(ug);return r=xg(r),function(){return--r>0&&(t=e.apply(this,arguments)),r<=1&&(e=void 0),t}}function bg(r){return $g(2,r)}function Za(r){var e=typeof r;return!!r&&(e=="object"||e=="function")}function Rg(r){return!!r&&typeof r=="object"}function Sg(r){return typeof r=="symbol"||Rg(r)&&Eg.call(r)==mg}function vg(r){if(!r)return r===0?r:0;if(r=_g(r),r===Ka||r===-Ka){var e=r<0?-1:1;return e*fg}return r===r?r:0}function xg(r){var e=vg(r),t=e%1;return e===e?t?e-t:e:0}function _g(r){if(typeof r=="number")return r;if(Sg(r))return Qa;if(Za(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Za(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)?Qa:+r}el.exports=bg});var ul=g((S$,cl)=>{var rl=Wr(),kg=dn(),Og=mn(),nl=kt(),Cg=Ma(),Yt=Da(),il=Ga(),$n=Ha(),sl=Xa(),$e=Ja(),Ag=tl(),{KeyObject:Pg,createSecretKey:Tg,createPrivateKey:Lg}=require("crypto"),al=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];kg&&al.splice(3,0,"PS256","PS384","PS512");var Ig={expiresIn:{isValid:function(r){return il(r)||$e(r)&&r},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(r){return il(r)||$e(r)&&r},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(r){return $e(r)||Array.isArray(r)},message:'"audience" must be a string or array'},algorithm:{isValid:Cg.bind(null,al),message:'"algorithm" must be a valid string enum value'},header:{isValid:sl,message:'"header" must be an object'},encoding:{isValid:$e,message:'"encoding" must be a string'},issuer:{isValid:$e,message:'"issuer" must be a string'},subject:{isValid:$e,message:'"subject" must be a string'},jwtid:{isValid:$e,message:'"jwtid" must be a string'},noTimestamp:{isValid:Yt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:$e,message:'"keyid" must be a string'},mutatePayload:{isValid:Yt,message:'"mutatePayload" must be a boolean'},allowInsecureKeySizes:{isValid:Yt,message:'"allowInsecureKeySizes" must be a boolean'},allowInvalidAsymmetricKeyTypes:{isValid:Yt,message:'"allowInvalidAsymmetricKeyTypes" must be a boolean'}},Mg={iat:{isValid:$n,message:'"iat" should be a number of seconds'},exp:{isValid:$n,message:'"exp" should be a number of seconds'},nbf:{isValid:$n,message:'"nbf" should be a number of seconds'}};function ll(r,e,t,n){if(!sl(t))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(t).forEach(function(i){let o=r[i];if(!o){if(!e)throw new Error('"'+i+'" is not allowed in "'+n+'"');return}if(!o.isValid(t[i]))throw new Error(o.message)})}function Ng(r){return ll(Ig,!1,r,"options")}function Dg(r){return ll(Mg,!0,r,"payload")}var ol={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Fg=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];cl.exports=function(r,e,t,n){typeof t=="function"?(n=t,t={}):t=t||{};let i=typeof r=="object"&&!Buffer.isBuffer(r),o=Object.assign({alg:t.algorithm||"HS256",typ:i?"JWT":void 0,kid:t.keyid},t.header);function s(u){if(n)return n(u);throw u}if(!e&&t.algorithm!=="none")return s(new Error("secretOrPrivateKey must have a value"));if(e!=null&&!(e instanceof Pg))try{e=Lg(e)}catch{try{e=Tg(typeof e=="string"?Buffer.from(e):e)}catch{return s(new Error("secretOrPrivateKey is not valid key material"))}}if(o.alg.startsWith("HS")&&e.type!=="secret")return s(new Error(`secretOrPrivateKey must be a symmetric key when using ${o.alg}`));if(/^(?:RS|PS|ES)/.test(o.alg)){if(e.type!=="private")return s(new Error(`secretOrPrivateKey must be an asymmetric key when using ${o.alg}`));if(!t.allowInsecureKeySizes&&!o.alg.startsWith("ES")&&e.asymmetricKeyDetails!==void 0&&e.asymmetricKeyDetails.modulusLength<2048)return s(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`))}if(typeof r>"u")return s(new Error("payload is required"));if(i){try{Dg(r)}catch(u){return s(u)}t.mutatePayload||(r=Object.assign({},r))}else{let u=Fg.filter(function(c){return typeof t[c]<"u"});if(u.length>0)return s(new Error("invalid "+u.join(",")+" option for "+typeof r+" payload"))}if(typeof r.exp<"u"&&typeof t.expiresIn<"u")return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(typeof r.nbf<"u"&&typeof t.notBefore<"u")return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{Ng(t)}catch(u){return s(u)}if(!t.allowInvalidAsymmetricKeyTypes)try{Og(o.alg,e)}catch(u){return s(u)}let a=r.iat||Math.floor(Date.now()/1e3);if(t.noTimestamp?delete r.iat:i&&(r.iat=a),typeof t.notBefore<"u"){try{r.nbf=rl(t.notBefore,a)}catch(u){return s(u)}if(typeof r.nbf>"u")return s(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=rl(t.expiresIn,a)}catch(u){return s(u)}if(typeof r.exp>"u")return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(ol).forEach(function(u){let c=ol[u];if(typeof t[u]<"u"){if(typeof r[c]<"u")return s(new Error('Bad "options.'+u+'" option. The payload already has an "'+c+'" property.'));r[c]=t[u]}});let l=t.encoding||"utf8";if(typeof n=="function")n=n&&Ag(n),nl.createSign({header:o,privateKey:e,payload:r,encoding:l}).once("error",n).once("done",function(u){if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)return n(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`));n(null,u)});else{let u=nl.sign({header:o,payload:r,secret:e,encoding:l});if(!t.allowInsecureKeySizes&&/^(?:RS|PS)/.test(o.alg)&&u.length<256)throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${o.alg}`);return u}}});var bn=g((v$,fl)=>{fl.exports={decode:Gr(),verify:Ca(),sign:ul(),JsonWebTokenError:ze(),NotBeforeError:Vr(),TokenExpiredError:Hr()}});var ql=g((ub,jl)=>{function Ll(r){return Array.isArray(r)?r:[r]}var Nn="",Il=" ",In="\\",by=/^\s+$/,Ry=/(?:[^\\]|^)\\$/,Sy=/^\\!/,vy=/^\\#/,xy=/\r?\n/g,_y=/^\.*\/|^\.+$/,Mn="/",Dl="node-ignore";typeof Symbol<"u"&&(Dl=Symbol.for("node-ignore"));var Ml=Dl,ky=(r,e,t)=>Object.defineProperty(r,e,{value:t}),Oy=/([0-z])-([0-z])/g,Fl=()=>!1,Cy=r=>r.replace(Oy,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:Nn),Ay=r=>{let{length:e}=r;return r.slice(0,e-e%2)},Py=[[/^\uFEFF/,()=>Nn],[/((?:\\\\)*?)(\\?\s+)$/,(r,e,t)=>e+(t.indexOf("\\")===0?Il:Nn)],[/(\\+?)\s/g,(r,e)=>{let{length:t}=e;return e.slice(0,t-t%2)+Il}],[/[\\$.|*+(){^]/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,()=>In],[/\\\\/g,()=>In],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(r,e,t,n,i)=>e===In?`\\[${t}${Ay(n)}${i}`:i==="]"&&n.length%2===0?`[${Cy(t)}${n}]`:"[]"],[/(?:[^*])$/,r=>/\/$/.test(r)?`${r}$`:`${r}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(r,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],Nl=Object.create(null),Ty=(r,e)=>{let t=Nl[r];return t||(t=Py.reduce((n,[i,o])=>n.replace(i,o.bind(r)),r),Nl[r]=t),e?new RegExp(t,"i"):new RegExp(t)},Un=r=>typeof r=="string",Ly=r=>r&&Un(r)&&!by.test(r)&&!Ry.test(r)&&r.indexOf("#")!==0,Iy=r=>r.split(xy),Dn=class{constructor(e,t,n,i){this.origin=e,this.pattern=t,this.negative=n,this.regex=i}},My=(r,e)=>{let t=r,n=!1;r.indexOf("!")===0&&(n=!0,r=r.substr(1)),r=r.replace(Sy,"!").replace(vy,"#");let i=Ty(r,e);return new Dn(t,r,n,i)},Ny=(r,e)=>{throw new e(r)},ge=(r,e,t)=>Un(r)?r?ge.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),Ul=r=>_y.test(r);ge.isNotRelative=Ul;ge.convert=r=>r;var Fn=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){ky(this,Ml,!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[Ml]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(Ly(e)){let t=My(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,Ll(Un(e)?Iy(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(o=>{let{negative:s}=o;if(i===s&&n!==i||s&&!n&&!i&&!t)return;o.regex.test(e)&&(n=!s,i=s)}),{ignored:n,unignored:i}}_test(e,t,n,i){let o=e&&ge.convert(e);return ge(o,e,this._allowRelativePaths?Fl:Ny),this._t(o,t,n,i)}_t(e,t,n,i){if(e in t)return t[e];if(i||(i=e.split(Mn)),i.pop(),!i.length)return t[e]=this._testOne(e,n);let o=this._t(i.join(Mn)+Mn,t,n,i);return t[e]=o.ignored?o:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return Ll(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},tr=r=>new Fn(r),Dy=r=>ge(r&&ge.convert(r),r,Fl);tr.isPathValid=Dy;tr.default=tr;jl.exports=tr;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,"/");ge.convert=r;let e=/^[a-z]:\//i;ge.isNotRelative=t=>e.test(t)||Ul(t)}});(function(){wi().config(Object.assign({},$i(),Ri()(process.argv)))})();var qc=require("fs"),Gc=require("path");var Uc=O(yt());var ae=O(require("fs")),kn=O(require("path")),gl=O(require("os")),yl=O(bn());var Ug=process.stdout.isTTY===!0&&!process.env.NO_COLOR,be=r=>Ug?r:"",S=be("\x1B[32m"),C=be("\x1B[33m"),_=be("\x1B[36m"),ne=be("\x1B[35m"),h=be("\x1B[31m"),y=be("\x1B[2m"),J=be("\x1B[1m"),f=be("\x1B[0m");var ml="app.boxel.realms";var jg={"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(jg);function P(r){return r.endsWith("/")?r:`${r}/`}async function dl(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 qg(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 Rn(r,e){let t=await qg(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 s=await i.text();throw new Error(`Realm server session failed: ${i.status} ${s}`)}let o=i.headers.get("Authorization");if(!o)throw new Error("Realm server session response did not include an Authorization header");return o}async function Sn(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 vn(r){return new URL(`_matrix/client/v3/user/${encodeURIComponent(r.userId)}/account_data/${ml}`,r.matrixUrl).href}async function Xt(r){try{let e=await fetch(vn(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 pl(r,e){let t=await Xt(r);if(!t.includes(e)){t.push(e);let n=await fetch(vn(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 hl(r,e){let t=P(e),n=await Xt(r),i=n.filter(s=>P(s)!==t);if(i.length===n.length)return!1;let o=await fetch(vn(r),{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.accessToken}`},body:JSON.stringify({realms:i})});if(!o.ok){let s=await o.text();throw new Error(`Failed to update Matrix account data: ${o.status} ${s}`)}return!0}var Gg=kn.join(gl.homedir(),".boxel-cli"),Vg="profiles.json",Hg=86400;function Wg(r,e=Hg){let t=r.replace(/^Bearer\s+/i,""),n=yl.default.decode(t);if(!n?.exp)return!0;let i=Math.floor(Date.now()/1e3);return n.exp-i<e}var M="No active profile. Run `boxel profile add` to create one.";function zt(r){return r.endsWith(":stack.cards")?"staging":r.endsWith(":boxel.ai")?"production":r.endsWith(":localhost")?"local":"unknown"}function je(r){let e=r.match(/^@([^:]+):/);return e?e[1]:r}function Jt(r){let e=r.match(/:([^:]+)$/);return e?e[1]:"unknown"}function fe(r){let e=je(r),t=Jt(r);return`${y}[${f}${_}${e}${f} ${y}\xB7${f} ${ne}${t}${f}${y}]${f}`}var _n=class{config;configDir;profilesFile;constructor(e){this.configDir=e||Gg,this.profilesFile=kn.join(this.configDir,Vg),this.config=this.loadConfig()}ensureConfigDir(){ae.existsSync(this.configDir)||ae.mkdirSync(this.configDir,{recursive:!0})}loadConfig(){let e={profiles:{},activeProfile:null};if(ae.existsSync(this.profilesFile))try{let t=ae.readFileSync(this.profilesFile,"utf-8"),n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n,o=i.profiles&&typeof i.profiles=="object"&&!Array.isArray(i.profiles)?i.profiles:null,s=i.activeProfile===null||typeof i.activeProfile=="string"?i.activeProfile:null;if(o)return{profiles:o,activeProfile:s}}}catch{}return e}saveConfig(){this.ensureConfigDir(),ae.writeFileSync(this.profilesFile,JSON.stringify(this.config,null,2),{mode:384});try{ae.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,o){let s=zt(e),a=je(e);if(s==="unknown"&&(!i||!o))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=s==="production"?"https://matrix.boxel.ai":"https://matrix-staging.stack.cards",u=s==="production"?"https://app.boxel.ai/":"https://realms-staging.stack.cards/",c=Jt(e),m={displayName:n||`${a} \xB7 ${c}`,matrixUrl:i||l,realmServerUrl:o||u,password:t};this.config.profiles[e]=m,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:je(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,o=process.env.REALM_SERVER_URL;return t&&n&&i&&o?{matrixUrl:t,username:n,password:i,realmServerUrl:o,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=je(t);return dl(n.matrixUrl,i,n.password)}async getOrRefreshServerToken(){let e=this.getRealmServerToken();if(e&&!Wg(e))return e;let t=await this.loginToMatrix(),i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),o=await Rn(t,i);return this.setRealmServerToken(o),o}async refreshServerToken(){let e=await this.loginToMatrix(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Rn(e,n);return this.setRealmServerToken(i),i}findRealmTokenForUrl(e){let n=this.getActiveProfile()?.profile.realmTokens;if(n){for(let[i,o]of Object.entries(n))if(e.startsWith(i)&&o)return o}}async fetchAndStoreAllRealmTokens(){let e=await this.getOrRefreshServerToken(),n=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),i=await Sn(n,e);for(let[o,s]of Object.entries(i))this.setRealmToken(o,s)}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,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}async authedRealmFetch(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.href:e,i=await this.getRealmTokenForUrl(n);if(i){let l=this.buildHeaders(e,t,i),u=await fetch(e,{...t,headers:l});if(u.status!==401)return u}let o=this.getActiveProfile();if(o&&(o.profile.realmTokens={},o.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 s=this.buildHeaders(e,t,i);return await fetch(e,{...t,headers:s})}async authedRealmServerFetch(e,t){let n=await this.getOrRefreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i});return o.status===401&&(n=await this.refreshServerToken(),i=this.buildHeaders(e,t,n),o=await fetch(e,{...t,headers:i})),o}async fetchAndStoreRealmToken(e,t){let i=this.getActiveProfile().profile.realmServerUrl.replace(/\/$/,""),s=(await Sn(i,t))[e];return s&&this.setRealmToken(e,s),s}async addToUserRealms(e){let t=await this.loginToMatrix();await pl(t,e)}async removeFromUserRealms(e){let t=await this.loginToMatrix();return hl(t,e)}async getUserRealms(){let e=await this.loginToMatrix();return Xt(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 s=e.includes("boxel.ai")?"boxel.ai":"stack.cards",a=`@${t}:${s}`;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
+ ${J}Active Profile:${f} ${fe(e.id)}`),console.log(` ${y}Display Name:${f} ${e.profile.displayName}`),console.log(` ${y}Matrix URL:${f} ${e.profile.matrixUrl}`),console.log(` ${y}Realm Server:${f} ${e.profile.realmServerUrl}`)):process.env.MATRIX_USERNAME?(console.log(`
33
+ ${J}Using environment variables${f} (no profile active)`),console.log(` ${y}Username:${f} ${process.env.MATRIX_USERNAME}`)):(console.log(`
34
+ ${C}No active profile and no environment variables set.${f}`),console.log(`Run ${_}boxel profile add${f} to create a profile.`))}},xn=null;function A(){return xn||(xn=new _n),xn}var On=O(require("readline")),wl=require("stream");function K(r){let e=On.createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(r,n=>{e.close(),t(n.trim())})})}function Cn(r){let e=new wl.Writable({write:(n,i,o)=>o()}),t=On.createInterface({input:process.stdin,output:e,terminal:!0});return new Promise((n,i)=>{let o=process.stdin,s=o.readableFlowing;o.isTTY&&o.setRawMode(!0);let a=()=>{o.removeListener("data",l),o.isTTY&&o.setRawMode(!1),t.close(),s||o.pause()},l=c=>{try{let m=c.toString().split("\x1B[200~").join("").split("\x1B[201~").join("");for(let d of m)if(d===`
35
35
  `||d==="\r"){a(),process.stdout.write(`
36
- `),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(f){a(),i(f)}},u="";try{process.stdout.write(r),s.on("data",l),s.resume()}catch(c){a(),i(c)}})}async function 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 bn("Realm secret seed: ")}}var Rn={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 Gt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${g}Error:${m} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${g}Error:${m} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Eg(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function il(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Eg(r);return e||(console.error(`${g}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 ol(r,e,t){let n=O();switch(r){case"list":await sl(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let s=t.matrixUrl?Gt(t.matrixUrl,"--matrix-url"):void 0,o=t.realmServerUrl?Gt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(qt(t.user)!=="unknown")&&(!s||!o)?il():null;c&&console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),await vg(n,t.user,i,t.name,s??c?.matrixUrl,o??c?.realmServerUrl)}else await bg(n,il());break}case"switch":e||(console.error(`${g}Error:${m} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
37
- Available profiles:`),await sl(n),process.exit(1)),await Rg(n,e);break;case"remove":e||(console.error(`${g}Error:${m} Please specify a profile to remove.`),process.exit(1)),await $g(n,e);break;case"migrate":await Sg(n);break;default:n.printStatus(),console.log(`
38
- ${y}Commands:${m}`),console.log(` ${k}boxel profile list${m} List all profiles`),console.log(` ${k}boxel profile add${m} Add a new profile`),console.log(` ${k}boxel profile switch${m} Switch active profile`),console.log(` ${k}boxel profile remove${m} Remove a profile`),console.log(` ${k}boxel profile migrate${m} Import from .env file`)}}async function sl(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
- ${T}No profiles configured.${m}`),console.log(`Run ${k}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=qt(n),a=s?`${S}\u2605${m} `:" ",l=Vt(n),u=o==="production"?re:k;console.log(`${a}${z}${n}${m}`),console.log(` ${y}Name:${m} ${i.displayName}`),console.log(` ${y}Environment:${m} ${u}${l}${m}`),console.log(` ${y}Realm Server:${m} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${y}\u2605 = active profile${m}`)}async function wg(){console.log("Which environment?"),console.log(` ${k}1${m}) Staging (realms-staging.stack.cards)`),console.log(` ${re}2${m}) Production (app.boxel.ai)`),console.log(` ${S}3${m}) Local (localhost:4201)`),console.log(` ${T}4${m}) Custom (enter your own URLs)`);let r=await J(`
42
- Choice [1/2/3/4]: `);if(r==="4"){let e=await J("Matrix server URL: ");e||(console.error(`${g}Error:${m} Matrix server URL is required.`),process.exit(1));let t=Gt(e,"Matrix server URL"),n=await J("Realm server URL: ");n||(console.error(`${g}Error:${m} Realm server URL is required.`),process.exit(1));let i=Gt(n,"Realm server URL"),s=new URL(t).hostname||"custom";return{domain:await J(`Domain for Matrix ID [${s}]: `)||s,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...Rn.local}:r==="2"?{...Rn.production}:{...Rn.staging}}async function bg(r,e){console.log(`
43
- ${z}Add New Profile${m}
44
- `);let t,n,i;if(e)console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${m}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let f=await wg();t=f.domain,n=f.matrixUrl,i=f.realmServerUrl}console.log(`
45
- Enter your Boxel username (without @ or domain)`),console.log(`${y}Example: ctse, aallen90${m}`);let s=await J("Username: ");s||(console.error(`${g}Error:${m} Username is required.`),process.exit(1));let o=`@${s}:${t}`;if(r.getProfile(o)&&(console.log(`
46
- ${T}Profile ${o} already exists.${m}`),(await J("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await bn("Password: ");a||(console.error(`${g}Error:${m} Password is required.`),process.exit(1));let l=`${s} \xB7 ${t}`,c=await J(`Display name [${l}]: `)||l;await r.addProfile(o,a,c,n,i),console.log(`
47
- ${S}\u2713${m} Profile created: ${ae(o)}`),r.getActiveProfileId()===o?console.log(`${y}This profile is now active.${m}`):(await J("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(o),console.log(`${S}\u2713${m} Switched to ${ae(o)}`))}async function Rg(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(s=>{let o=Ne(s);return s.includes(e)||o===e});if(i.length===0){console.error(`${g}Error:${m} Profile not found: ${e}`),console.log(`
48
- Available profiles:`);for(let s of t)console.log(` ${s}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${g}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 ${ae(n)}`):(console.error(`${g}Error:${m} Failed to switch profile.`),process.exit(1))}async function $g(r,e){if(r.getProfile(e)||(console.error(`${g}Error:${m} Profile not found: ${e}`),process.exit(1)),(await J(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${S}\u2713${m} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${ae(i)}`)}else console.error(`${g}Error:${m} Failed to remove profile.`),process.exit(1)}async function vg(r,e,t,n,i,s){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${g}Error:${m} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${T}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(`${y}Updated server URLs and cleared cached realm tokens.${m}`),console.log(`${S}\u2713${m} Profile updated: ${ae(e)}`);return}try{await r.addProfile(e,t,n,i,s)}catch(a){console.error(`${g}Error:${m} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${S}\u2713${m} Profile created: ${ae(e)}`),r.getActiveProfileId()!==e&&console.log(`${y}Use 'boxel profile switch ${e}' to switch to this profile.${m}`)}async function Sg(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(`${T}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: ${ae(s.profileId)}`),console.log(`
53
- ${y}You can now remove credentials from .env if desired.${m}`)):(console.log(`${T}Profile ${ae(s.profileId)} already exists.${m} Password has been updated if it changed.`),console.log(`
54
- ${y}Use 'boxel profile add -u ${s.profileId} -p <password>' to update other fields.${m}`)):console.log(`${T}Migration failed.${m}`)}var Wt=!1,xg=console.log.bind(console),_g=console.info.bind(console),Og=console.debug.bind(console);function Bt(r){if(r!==Wt)if(Wt=r,Wt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=xg,console.info=_g,console.debug=Og}var M={info(...r){Wt||process.stderr.write(r.map(Ht).join(" ")+`
55
- `)},warn(...r){process.stderr.write(r.map(Ht).join(" ")+`
56
- `)},error(...r){process.stderr.write(r.map(Ht).join(" ")+`
57
- `)},output(...r){process.stdout.write(r.map(Ht).join(" ")+`
58
- `)}};function Ht(r){if(typeof r=="string")return r;if(r instanceof Error)return r.stack??r.message;try{return JSON.stringify(r)}catch{return String(r)}}async function kg(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function al(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 kg(t.realm,e)}catch(i){console.error(`${g}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${y}Status:${m} ${n.status??"(no status)"}`),console.error(`${g}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}async function Cg(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{ok:!1,error:N};let i=e?.cancelPending??!1,s=`${C(r)}_cancel-indexing-job`;try{let o=await t.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function ll(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 Cg(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(`${g}Error:${m} ${t.error}`),process.exit(1)})}var Ag=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"}),cl=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 $n(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return Ag[e.charAt(0)]}function ul(){let r=Math.floor(Math.random()*cl.length);return cl[r]}var Tg=/^[a-z0-9-]+$/;function ml(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 Ig(e,t,n)})}async function Pg(r,e,t={}){let n=t.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=i.profile.realmServerUrl.replace(/\/$/,""),o={endpoint:r,name:e,backgroundURL:t.background??ul(),iconURL:t.icon??$n(e)??$n(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=Ng(d,s,r),E=await fl(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:E}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=C(u),f=await fl(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&f&&await Lg(c,f),{realmUrl:c,created:!0,realmToken:f}}async function fl(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function Lg(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 Ig(r,e,t){Tg.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await Pg(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${m} ${k}${n.realmUrl}${m}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function Ng(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return C(n[1]);throw new Error(`Could not determine realm URL from server error response for endpoint "${t}" on "${e}". The response did not include an explicit realm URL.`)}var Qe=P(require("fs"));var _l=require("child_process"),B=P(require("fs/promises")),G=P(require("path"));var V=P(require("fs/promises")),q=P(require("path")),Pn=P(Rl());var Cn=class{value;next;constructor(e){this.value=e}},Je=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new Cn(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 An(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),$l(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new Je,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},s=()=>{n--,i()},o=async(u,c,f)=>{let d=(async()=>u(...f))();c(d);try{await d}catch{}s()},a=(u,c,f,d)=>{let p={reject:f};new Promise(E=>{p.run=E,t.enqueue(p)}).then(o.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((f,d)=>{a(u,f,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){$l(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let f=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(f)}}}),l}function $l(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 Zg=Pn.default.default||Pn.default,ey=new Set([".realm.json"]),Tn=1e4,ty=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return ey.has(e)}async function vl(r){try{return await V.access(r),!0}catch{return!1}}function Sl(r){try{return decodeURIComponent(r)}catch{return r}}var Ke={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},ry=10,xl=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=An(ry);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.
36
+ `),n(u);return}else d===""?(a(),process.exit()):d==="\x7F"||d==="\b"?u.length>0&&(u=u.slice(0,-1),process.stdout.write("\b \b")):d>=" "&&(u+=d,process.stdout.write("*"))}catch(m){a(),i(m)}},u="";try{process.stdout.write(r),o.on("data",l),o.resume()}catch(c){a(),i(c)}})}async function me(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 Cn("Realm secret seed: ")}}var An={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 Kt(r,e){let t=r.trim(),n;try{n=new URL(t)}catch{console.error(`${h}Error:${f} ${e} "${r}" is not a valid URL.`),process.exit(1)}return n.protocol!=="http:"&&n.protocol!=="https:"&&(console.error(`${h}Error:${f} ${e} "${r}" must use http:// or https://.`),process.exit(1)),t}function Bg(r){return r.toLowerCase().replace(/\//g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function El(){let r=process.env.BOXEL_ENVIRONMENT;if(!r||!r.trim())return null;let e=Bg(r);return e||(console.error(`${h}Error:${f} 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 bl(r,e,t){let n=A();switch(r){case"list":await $l(n);break;case"add":{let i=t?.password||process.env.BOXEL_PASSWORD;if(t?.user&&i){let o=t.matrixUrl?Kt(t.matrixUrl,"--matrix-url"):void 0,s=t.realmServerUrl?Kt(t.realmServerUrl,"--realm-server-url"):void 0,c=!(zt(t.user)!=="unknown")&&(!o||!s)?El():null;c&&console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),await Kg(n,t.user,i,t.name,o??c?.matrixUrl,s??c?.realmServerUrl)}else await Xg(n,El());break}case"switch":e||(console.error(`${h}Error:${f} Please specify a profile to switch to.`),console.log("Usage: boxel profile switch <profile-id>"),console.log(`
37
+ Available profiles:`),await $l(n),process.exit(1)),await zg(n,e);break;case"remove":e||(console.error(`${h}Error:${f} Please specify a profile to remove.`),process.exit(1)),await Jg(n,e);break;case"migrate":await Qg(n);break;default:n.printStatus(),console.log(`
38
+ ${y}Commands:${f}`),console.log(` ${_}boxel profile list${f} List all profiles`),console.log(` ${_}boxel profile add${f} Add a new profile`),console.log(` ${_}boxel profile switch${f} Switch active profile`),console.log(` ${_}boxel profile remove${f} Remove a profile`),console.log(` ${_}boxel profile migrate${f} Import from .env file`)}}async function $l(r){let e=r.listProfiles(),t=r.getActiveProfileId();if(e.length===0){console.log(`
39
+ ${C}No profiles configured.${f}`),console.log(`Run ${_}boxel profile add${f} to create one.`);return}console.log(`
40
+ ${J}Saved Profiles:${f}
41
+ `);for(let n of e){let i=r.getProfile(n),o=n===t,s=zt(n),a=o?`${S}\u2605${f} `:" ",l=Jt(n),u=s==="production"?ne:_;console.log(`${a}${J}${n}${f}`),console.log(` ${y}Name:${f} ${i.displayName}`),console.log(` ${y}Environment:${f} ${u}${l}${f}`),console.log(` ${y}Realm Server:${f} ${i.realmServerUrl}`),console.log("")}t&&console.log(`${y}\u2605 = active profile${f}`)}async function Yg(){console.log("Which environment?"),console.log(` ${_}1${f}) Staging (realms-staging.stack.cards)`),console.log(` ${ne}2${f}) Production (app.boxel.ai)`),console.log(` ${S}3${f}) Local (localhost:4201)`),console.log(` ${C}4${f}) Custom (enter your own URLs)`);let r=await K(`
42
+ Choice [1/2/3/4]: `);if(r==="4"){let e=await K("Matrix server URL: ");e||(console.error(`${h}Error:${f} Matrix server URL is required.`),process.exit(1));let t=Kt(e,"Matrix server URL"),n=await K("Realm server URL: ");n||(console.error(`${h}Error:${f} Realm server URL is required.`),process.exit(1));let i=Kt(n,"Realm server URL"),o=new URL(t).hostname||"custom";return{domain:await K(`Domain for Matrix ID [${o}]: `)||o,matrixUrl:t,realmServerUrl:i}}return r==="3"?{...An.local}:r==="2"?{...An.production}:{...An.staging}}async function Xg(r,e){console.log(`
43
+ ${J}Add New Profile${f}
44
+ `);let t,n,i;if(e)console.log(`${y}Using BOXEL_ENVIRONMENT=${process.env.BOXEL_ENVIRONMENT}${f}`),t=e.domain,n=e.matrixUrl,i=e.realmServerUrl;else{let m=await Yg();t=m.domain,n=m.matrixUrl,i=m.realmServerUrl}console.log(`
45
+ Enter your Boxel username (without @ or domain)`),console.log(`${y}Example: ctse, aallen90${f}`);let o=await K("Username: ");o||(console.error(`${h}Error:${f} Username is required.`),process.exit(1));let s=`@${o}:${t}`;if(r.getProfile(s)&&(console.log(`
46
+ ${C}Profile ${s} already exists.${f}`),(await K("Overwrite? [y/N]: ")).toLowerCase()!=="y")){console.log("Cancelled.");return}let a=await Cn("Password: ");a||(console.error(`${h}Error:${f} Password is required.`),process.exit(1));let l=`${o} \xB7 ${t}`,c=await K(`Display name [${l}]: `)||l;await r.addProfile(s,a,c,n,i),console.log(`
47
+ ${S}\u2713${f} Profile created: ${fe(s)}`),r.getActiveProfileId()===s?console.log(`${y}This profile is now active.${f}`):(await K("Switch to this profile now? [Y/n]: ")).toLowerCase()!=="n"&&(r.switchProfile(s),console.log(`${S}\u2713${f} Switched to ${fe(s)}`))}async function zg(r,e){let t=r.listProfiles(),n=e;if(!t.includes(e)){let i=t.filter(o=>{let s=je(o);return o.includes(e)||s===e});if(i.length===0){console.error(`${h}Error:${f} Profile not found: ${e}`),console.log(`
48
+ Available profiles:`);for(let o of t)console.log(` ${o}`);process.exit(1)}else if(i.length===1)n=i[0];else{console.error(`${h}Error:${f} Ambiguous profile: ${e}`),console.log(`
49
+ Matching profiles:`);for(let o of i)console.log(` ${o}`);process.exit(1)}}r.switchProfile(n)?console.log(`${S}\u2713${f} Switched to ${fe(n)}`):(console.error(`${h}Error:${f} Failed to switch profile.`),process.exit(1))}async function Jg(r,e){if(r.getProfile(e)||(console.error(`${h}Error:${f} Profile not found: ${e}`),process.exit(1)),(await K(`Remove profile ${e}? [y/N]: `)).toLowerCase()!=="y"){console.log("Cancelled.");return}if(await r.removeProfile(e)){console.log(`${S}\u2713${f} Profile removed.`);let i=r.getActiveProfileId();i&&console.log(`Active profile is now: ${fe(i)}`)}else console.error(`${h}Error:${f} Failed to remove profile.`),process.exit(1)}async function Kg(r,e,t,n,i,o){if((!e.startsWith("@")||!e.includes(":"))&&(console.error(`${h}Error:${f} Invalid Matrix ID format. Expected @user:domain`),process.exit(1)),r.getProfile(e)){console.log(`${C}Profile ${e} already exists. Updating password.${f}`),await r.updatePassword(e,t),n&&r.updateDisplayName(e,n),(i||o)&&r.updateUrls(e,{matrixUrl:i,realmServerUrl:o})&&console.log(`${y}Updated server URLs and cleared cached realm tokens.${f}`),console.log(`${S}\u2713${f} Profile updated: ${fe(e)}`);return}try{await r.addProfile(e,t,n,i,o)}catch(a){console.error(`${h}Error:${f} ${a instanceof Error?a.message:String(a)}`),process.exit(1)}console.log(`${S}\u2713${f} Profile created: ${fe(e)}`),r.getActiveProfileId()!==e&&console.log(`${y}Use 'boxel profile switch ${e}' to switch to this profile.${f}`)}async function Qg(r){console.log(`
50
+ ${J}Migrate from .env${f}
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(`${C}No complete credentials found in environment variables.${f}`),console.log(`
52
+ Required variables: MATRIX_URL, MATRIX_USERNAME, MATRIX_PASSWORD, REALM_SERVER_URL`);return}let o=await r.migrateFromEnv();o?o.created?(console.log(`${S}\u2713${f} Created profile: ${fe(o.profileId)}`),console.log(`
53
+ ${y}You can now remove credentials from .env if desired.${f}`)):(console.log(`${C}Profile ${fe(o.profileId)} already exists.${f} Password has been updated if it changed.`),console.log(`
54
+ ${y}Use 'boxel profile add -u ${o.profileId} -p <password>' to update other fields.${f}`)):console.log(`${C}Migration failed.${f}`)}var le=O(require("fs")),Oe=O(require("path"));var qe=O(require("fs")),q=O(require("path"));var rt=!1,Zg=console.log.bind(console),ey=console.info.bind(console),ty=console.debug.bind(console);function Zt(r){if(r!==rt)if(rt=r,rt){let e=()=>{};console.log=e,console.info=e,console.debug=e}else console.log=Zg,console.info=ey,console.debug=ty}function Rl(){return rt}var N={info(...r){rt||process.stderr.write(r.map(Qt).join(" ")+`
55
+ `)},warn(...r){process.stderr.write(r.map(Qt).join(" ")+`
56
+ `)},error(...r){process.stderr.write(r.map(Qt).join(" ")+`
57
+ `)},output(...r){process.stdout.write(r.map(Qt).join(" ")+`
58
+ `)}};function Qt(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 Sl=!1,ry=new Set([".git","node_modules","dist",".boxel-history",".claude"]);function ny(r){return ry.has(r)}function iy(r){return r==="stack.cards"||r.endsWith(".stack.cards")?"stack.cards":r==="boxel.ai"||r.endsWith(".boxel.ai")?"boxel.ai":r}function Pn(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 oy(r){let e;try{e=new URL(r)}catch{return null}let t=iy(e.hostname);if(!Pn(t))return null;let n=e.pathname.replace(/^\/|\/$/g,"").split("/").filter(Boolean),i=n[0]??"unknown-owner",o=n[1]??n[0]??"workspace";return!Pn(i)||!Pn(o)?null:q.join(t,i,o)}function sy(r,e){let t=oy(r);return t===null?null:q.resolve(e,t)}function ay(r){let e;try{e=qe.readFileSync(r,"utf-8")}catch{return null}let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t.realmUrl;return typeof n!="string"||n===""?null:{realmUrl:n}}function vl(r,e){let t=q.join(r,".boxel-sync.json");qe.existsSync(t)&&e.push(t)}function er(r){try{return qe.readdirSync(r,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!ny(e.name)).map(e=>q.join(r,e.name))}catch{return[]}}function ly(r){let e=[],t=q.resolve(r);for(let n of er(t))vl(n,e);for(let n of er(t))for(let i of er(n))for(let o of er(i))vl(o,e);return e}function cy(r,e){let t=q.relative(r,e);return t===""?!0:t.startsWith("..")?!1:!q.isAbsolute(t)}function Tn(r){let e=q.resolve(r),t=ly(e),n=new Set,i=[];for(let o of t){if(n.has(o))continue;n.add(o);let s=ay(o);if(!s)continue;let a=sy(s.realmUrl,e);if(a===null||!cy(e,a))continue;let l=q.dirname(o);q.resolve(l)!==q.resolve(a)&&i.push({manifestPath:o,currentDir:l,expectedDir:a,realmUrl:s.realmUrl})}return i}function xl(r){if(Sl||process.env.BOXEL_DISABLE_PATH_WARNING==="1"||Rl())return;let e=Tn(r);if(e.length===0)return;Sl=!0,console.warn(`
59
+ \u26A0\uFE0F Detected local realm directories at legacy local paths:`);let t=q.resolve(r);for(let n of e.slice(0,5)){let i=q.relative(t,n.currentDir)||".",o=q.relative(t,n.expectedDir)||".";console.warn(` - ${i} -> ${o}`)}e.length>5&&console.warn(` ...and ${e.length-5} more`),console.warn(`
60
+ Run to preview:`),console.warn(" boxel consolidate-workspaces . --dry-run"),console.warn("Then apply:"),console.warn(` boxel consolidate-workspaces .
61
+ `)}function uy(r){le.existsSync(r)||le.mkdirSync(r,{recursive:!0})}function fy(r,e){try{le.renameSync(r,e)}catch(t){let n=t;if(n.code!=="EXDEV")throw n;le.cpSync(r,e,{recursive:!0}),le.rmSync(r,{recursive:!0,force:!0})}}async function my(r,e){let t=Oe.resolve(r||"."),n=Tn(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,o=0;for(let s of n){let a=Oe.relative(t,s.currentDir)||".",l=Oe.relative(t,s.expectedDir)||".";if(console.log(`- ${a} -> ${l}`),!e.dryRun){if(le.existsSync(s.expectedDir)){console.warn(" Skipping: target path already exists"),o+=1;continue}uy(Oe.dirname(s.expectedDir));try{fy(s.currentDir,s.expectedDir),i+=1}catch(u){let c=u instanceof Error?u.message:String(u);console.warn(` Skipping: failed to move (${c})`),o+=1}}}if(e.dryRun){console.log(`
63
+ [DRY RUN] No directories moved.`);return}console.log(`
64
+ Moved ${i} director${i===1?"y":"ies"}.`),o>0&&console.log(`Skipped ${o} due to existing target paths or move failures.`)}function _l(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 my(e,t)})}async function dy(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())throw new Error("No active profile. Run `boxel profile add` to create one.");let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"*/*"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function kl(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 dy(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}async function py(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{ok:!1,error:M};let i=e?.cancelPending??!1,o=`${P(r)}_cancel-indexing-job`;try{let s=await t.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({cancelPending:i})});if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ol(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 py(e.realm,{cancelPending:e.cancelPending});if(e.json)N.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}${f}`)}else console.error(`${h}Error:${f} ${t.error}`),process.exit(1)})}var hy=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"}),Cl=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 Ln(r){if(!r)return;let e=r.toLowerCase().replace(/[^a-z0-9]/g,"").replace(/^[0-9]+/,"");return hy[e.charAt(0)]}function Al(){let r=Math.floor(Math.random()*Cl.length);return Cl[r]}var gy=/^[a-z0-9-]+$/;function Tl(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 Ey(e,t,n)})}async function yy(r,e,t={}){let n=t.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=i.profile.realmServerUrl.replace(/\/$/,""),s={endpoint:r,name:e,backgroundURL:t.background??Al(),iconURL:t.icon??Ln(e)??Ln(r)},a=await n.authedRealmServerFetch(`${o}/_create-realm`,{method:"POST",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",attributes:s}})});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=$y(d,o,r),w=await Pl(n,p);try{await n.addToUserRealms(p)}catch{}return{realmUrl:p,created:!1,realmToken:w}}throw new Error(`Realm server returned ${a.status}: ${d}`)}let u=(await a.json())?.data?.id;if(typeof u!="string"||u.trim()==="")throw new Error(`Realm server response did not include a realm URL (data.id) for "${r}".`);let c=P(u),m=await Pl(n,c);try{await n.addToUserRealms(c)}catch{}return t.waitForReady&&m&&await wy(c,m),{realmUrl:c,created:!0,realmToken:m}}async function Pl(r,e){try{let t=await r.getOrRefreshServerToken();return await r.fetchAndStoreRealmToken(e,t)}catch{return}}async function wy(r,e){let t=new URL("_readiness-check",r).href,n=15e3,i=250,o=Date.now(),s;for(;Date.now()-o<n;){try{let a=await fetch(t,{headers:{Accept:"application/vnd.api+json",Authorization:e}});if(a.ok)return;s=`HTTP ${a.status}`}catch(a){s=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${s?`: ${s}`:""}`)}async function Ey(r,e,t){gy.test(r)||(console.error("Error: realm name must contain only lowercase letters, numbers, and hyphens"),process.exit(1));try{let n=await yy(r,e,t),i=n.created?"created":"already exists";console.log(`${S}Realm ${i}:${f} ${_}${n.realmUrl}${f}`)}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}function $y(r,e,t){let n=r.match(/'(https?:\/\/[^']+)'/);if(n)return P(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 ot=O(require("fs"));var Bl=require("child_process"),Y=O(require("fs/promises")),H=O(require("path"));var V=O(require("fs/promises")),G=O(require("path")),Vn=O(ql());var jn=class{value;next;constructor(e){this.value=e}},nt=class{#e;#t;#r;constructor(){this.clear()}enqueue(e){let t=new jn(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 qn(r){let e=!1;if(typeof r=="object"&&({concurrency:r,rejectOnClear:e=!1}=r),Gl(r),typeof e!="boolean")throw new TypeError("Expected `rejectOnClear` to be a boolean");let t=new nt,n=0,i=()=>{n<r&&t.size>0&&(n++,t.dequeue().run())},o=()=>{n--,i()},s=async(u,c,m)=>{let d=(async()=>u(...m))();c(d);try{await d}catch{}o()},a=(u,c,m,d)=>{let p={reject:m};new Promise(w=>{p.run=w,t.enqueue(p)}).then(s.bind(void 0,u,c,d)),n<r&&i()},l=(u,...c)=>new Promise((m,d)=>{a(u,m,d,c)});return Object.defineProperties(l,{activeCount:{get:()=>n},pendingCount:{get:()=>t.size},clearQueue:{value(){if(!e){t.clear();return}let u=AbortSignal.abort().reason;for(;t.size>0;)t.dequeue().reject(u)}},concurrency:{get:()=>r,set(u){Gl(u),r=u,queueMicrotask(()=>{for(;n<r&&t.size>0;)i()})}},map:{async value(u,c){let m=Array.from(u,(d,p)=>this(c,d,p));return Promise.all(m)}}}),l}function Gl(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 Fy=Vn.default.default||Vn.default,Uy=new Set([".realm.json"]),Gn=1e4,jy=3e3;function D(r){let e=r.replace(/\\/g,"/").replace(/^\/+/,"");return Uy.has(e)}async function Vl(r){try{return await V.access(r),!0}catch{return!1}}function Hl(r){try{return decodeURIComponent(r)}catch{return r}}var it={CardSource:"application/vnd.card+source",DirectoryListing:"application/vnd.api+json",Mtimes:"application/vnd.api+json"},qy=10,Wl=new Set(["node_modules"]),ie=class{constructor(e,t){this.options=e;this.authenticator=t;this.normalizedRealmUrl=this.normalizeRealmUrl(e.realmUrl)}normalizedRealmUrl;ignoreCache=new Map;remoteLimit=qn(qy);normalizeRealmUrl(e){try{let t=new URL(e),n=t.pathname;return(n.split("/").filter(Boolean).pop()||"").includes(".")?console.warn(`Warning: "${e}" looks like a file URL, not a realm URL.
59
65
  Realm URLs should point to a directory (e.g., ${t.origin}${n.replace(/\/[^/]*\.[^/]*$/,"/")})`):e.endsWith("/")||console.warn(`Warning: Realm URL should end with a trailing slash.
60
- Did you mean "${e}/"?`),t.href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid workspace URL: ${e}`)}}buildDirectoryUrl(e=""){if(!e)return this.normalizedRealmUrl;let t=e.replace(/^\/+|\/+$/g,"");return`${this.normalizedRealmUrl}${t}/`}buildFileUrl(e){let t=e.replace(/^\/+/,"");return`${this.normalizedRealmUrl}${t}`}async getRemoteFileList(e=""){let t=new Map;try{let n=this.buildDirectoryUrl(e),i=await this.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,u])=>{let f=u.meta.kind==="file",d=e?q.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[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:Ke.Mtimes}});if(!n.ok){if(n.status===404)return console.log("Note: _mtimes endpoint not available, will upload all files"),e;throw new Error(`Failed to get mtimes: ${n.status} ${n.statusText}`)}let i=await n.json();if(i.data?.attributes?.mtimes){let s=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${s.length} entries`),s.length>0&&console.log(`Sample: ${s[0][0]} = ${s[0][1]}`));for(let[o,a]of s){let l=o.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=q.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=q.join(n,o.name),l=e?q.posix.join(e,o.name):o.name;if(o.isDirectory()&&xl.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile()){let u=await V.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(o.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=q.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=q.join(n,o.name),l=e?q.posix.join(e,o.name):o.name;if(o.isDirectory()&&xl.has(o.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(o.isFile())return[[l,a]];if(o.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let o of s)for(let[a,l]of o)t.set(a,l);return t}async uploadFile(e,t){if(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:Ke.CardSource},body:n});if(!s.ok)throw new Error(`Failed to upload: ${s.status} ${s.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!D(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let f=await V.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:f},meta:{}}}})),s=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,o=await this.authenticator.authedRealmFetch(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(o.status===201){let u=await o.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),f=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Sl(d)).map(d=>c.get(d)??d);for(let d of f)console.log(` Uploaded: ${d}`);return{succeeded:f}}let a={};try{a=await o.json()}catch{}let l=(a.errors??[]).map(u=>{let f=(u.detail??"").match(/Resource (\S+) /),d=f?Sl(f[1]):"";return{path:new Map(n.map(([E])=>[this.buildFileUrl(E),E])).get(d)??d,status:u.status??o.status,title:u.title??"Error"}});return{succeeded:[],error:{status:o.status,perFile:l,message:`Atomic upload failed: ${o.status} ${o.statusText}`}}}async downloadFile(e,t){if(console.log(`Downloading: ${e}`),this.options.dryRun){console.log(`[DRY RUN] Would download ${e}`);return}let n=this.buildFileUrl(e),i=await this.authenticator.authedRealmFetch(n,{headers:{Accept:Ke.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let s=await i.text(),o=q.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:Ke.CardSource},signal:AbortSignal.timeout(Tn)})}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 ${Tn}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Tn}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:Ke.CardSource},signal:AbortSignal.timeout(ty)});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=Zg(),s=e,o=this.options.localDir;for(;s.startsWith(o);){let a=q.join(s,".gitignore");if(await vl(a))try{let c=await V.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=q.join(s,".boxelignore");if(await vl(l))try{let c=await V.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=q.dirname(s);if(u===s)break;s=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=q.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=q.dirname(t),s=await this.getIgnoreInstance(i),o=e.replace(/\\/g,"/");return s.ignores(o)}shouldIgnoreRemoteFile(e){return!!q.basename(e).startsWith(".")}};async function Ln(r){try{return await B.access(r),!0}catch{return!1}}var U=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=G.resolve(e),this.gitDir=G.join(this.workspaceDir,".boxel-history")}async init(){await Ln(this.gitDir)||await B.mkdir(this.gitDir,{recursive:!0});let e=G.join(this.gitDir,".git");await Ln(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 Ln(G.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=G.join(this.gitDir,i);try{await B.unlink(s)}catch(o){if(o.code!=="ENOENT")throw o}}})),await Promise.all(e.map(async i=>{let s=G.join(this.workspaceDir,i),o=G.join(this.gitDir,i),a=G.dirname(o);await B.mkdir(a,{recursive:!0}),await B.copyFile(s,o)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let s;try{s=await B.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(G.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 B.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(G.join(n,o.name),a):e.push(a)}))};return await t(this.gitDir),e}async detectCurrentChanges(){if(!await this.isInitialized())return(await this.getWorkspaceFiles()).map(i=>({file:i,status:"added"}));await this.syncFilesToHistory();let e=(await this.git("status","--porcelain")).replace(/\n+$/,"");if(!e)return[];let t=[];for(let n of e.split(`
61
- `)){if(!n)continue;let i=n.substring(0,2),s=n.substring(3);if(i.includes("R")){let o=s.indexOf(" -> ");if(o!==-1){let a=s.substring(0,o),l=s.substring(o+4);t.push({file:a,status:"deleted"}),t.push({file:l,status:"added"});continue}}i.includes("D")?t.push({file:s,status:"deleted"}):i.includes("A")||i.includes("C")||i==="??"?t.push({file:s,status:"added"}):(i.includes("M")||i.includes("U")||i.includes("T"))&&t.push({file:s,status:"modified"})}return t}async createCheckpoint(e,t,n){if(await this.isInitialized()||await this.init(),await this.syncFilesToHistory(),await this.git("add","-A"),!(await this.git("status","--porcelain")).trim())return null;let s=this.classifyChanges(t),{message:o,description:a}=n?{message:n,description:""}:this.generateCommitMessage(e,t,s),l=s?"[MAJOR]":"[minor]",u=`[${e}]`,c=`${l} ${u} ${o}${a?`
66
+ 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 o=await i.json();if(o.data&&o.data.relationships){let s=Object.entries(o.data.relationships),a=await Promise.all(s.map(([l,u])=>{let m=u.meta.kind==="file",d=e?G.posix.join(e,l):l;return m?this.shouldIgnoreRemoteFile(d)?[]:[[d,!0]]:(async()=>{let p=await this.getRemoteFileList(d);return Array.from(p.entries())})()}));for(let l of a)for(let[u,c]of l)t.set(u,c)}}catch(n){throw n instanceof Error&&(n.message.includes("Authentication failed")||n.message.includes("Cannot access workspace")||n.message.includes("401")||n.message.includes("403"))||console.error(`Error reading remote directory ${e}:`,n),n}return t}async getRemoteMtimes(){let e=new Map;try{let t=`${this.normalizedRealmUrl}_mtimes`,n=await this.authenticator.authedRealmFetch(t,{headers:{Accept:it.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 o=Object.entries(i.data.attributes.mtimes);process.env.DEBUG&&(console.log(`Remote mtimes received: ${o.length} entries`),o.length>0&&console.log(`Sample: ${o[0][0]} = ${o[0][1]}`));for(let[s,a]of o){let l=s.replace(this.normalizedRealmUrl,""),u;try{u=decodeURIComponent(l)}catch{u=l}this.shouldIgnoreRemoteFile(u)||e.set(u,a)}}else process.env.DEBUG&&console.log("No mtimes in response:",JSON.stringify(i).slice(0,200))}catch(t){console.warn("Could not fetch remote mtimes, will upload all files:",t)}return e}async getLocalFileListWithMtimes(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile()){let u=await V.stat(a);return[[l,{path:a,mtime:u.mtimeMs}]]}else if(s.isDirectory()){let u=await this.getLocalFileListWithMtimes(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)t.set(a,l);return t}async getLocalFileList(e=""){let t=new Map,n=G.join(this.options.localDir,e),i;try{i=await V.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return t;throw s}let o=await Promise.all(i.map(async s=>{let a=G.join(n,s.name),l=e?G.posix.join(e,s.name):s.name;if(s.isDirectory()&&Wl.has(s.name))return[];if(await this.shouldIgnoreFile(l,a))return[];if(s.isFile())return[[l,a]];if(s.isDirectory()){let u=await this.getLocalFileList(l);return Array.from(u.entries())}return[]}));for(let s of o)for(let[a,l]of s)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),o=await this.authenticator.authedRealmFetch(i,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8",Accept:it.CardSource},body:n});if(!o.ok)throw new Error(`Failed to upload: ${o.status} ${o.statusText}`);console.log(` Uploaded: ${e}`)}async uploadFilesAtomic(e,t){let n=Array.from(e.entries()).filter(([u])=>!D(u));if(n.length===0)return{succeeded:[]};if(this.options.dryRun){for(let[u]of n)console.log(`[DRY RUN] Would upload ${u}`);return{succeeded:[]}}let i=await Promise.all(n.map(async([u,c])=>{let m=await V.readFile(c,"utf8");return{op:t.has(u)?"add":"update",href:this.buildFileUrl(u),data:{type:"source",attributes:{content:m},meta:{}}}})),o=this.options.waitForIndex?`${this.normalizedRealmUrl}_atomic?waitForIndex=true`:`${this.normalizedRealmUrl}_atomic`,s=await this.authenticator.authedRealmFetch(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify({"atomic:operations":i})});if(s.status===201){let u=await s.json(),c=new Map(n.map(([d])=>[this.buildFileUrl(d),d])),m=(u["atomic:results"]??[]).map(d=>d.data?.id).filter(d=>typeof d=="string").map(d=>Hl(d)).map(d=>c.get(d)??d);for(let d of m)console.log(` Uploaded: ${d}`);return{succeeded:m}}let a={};try{a=await s.json()}catch{}let l=(a.errors??[]).map(u=>{let m=(u.detail??"").match(/Resource (\S+) /),d=m?Hl(m[1]):"";return{path:new Map(n.map(([w])=>[this.buildFileUrl(w),w])).get(d)??d,status:u.status??s.status,title:u.title??"Error"}});return{succeeded:[],error:{status:s.status,perFile:l,message:`Atomic upload failed: ${s.status} ${s.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:it.CardSource}});if(!i.ok)throw new Error(`Failed to download: ${i.status} ${i.statusText}`);let o=await i.text(),s=G.dirname(t);await V.mkdir(s,{recursive:!0}),await V.writeFile(t,o,"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:it.CardSource},signal:AbortSignal.timeout(Gn)})}catch(s){let a=Date.now()-n;if(console.error(` Delete request failed after ${a}ms: ${e}`),s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")){if(await this.verifyDeleteApplied(e)===!0){console.warn(` Delete response timed out after ${Gn}ms, but ${e} is already gone on the realm; continuing`);return}throw new Error(`Timed out deleting ${e} after ${Gn}ms`,{cause:s})}throw s}let o=Date.now()-n;if(console.log(` Delete response for ${e}: ${i.status} ${i.statusText} (${o}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:it.CardSource},signal:AbortSignal.timeout(jy)});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=Fy(),o=e,s=this.options.localDir;for(;o.startsWith(s);){let a=G.join(o,".gitignore");if(await Vl(a))try{let c=await V.readFile(a,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .gitignore file at ${a}:`,c)}let l=G.join(o,".boxelignore");if(await Vl(l))try{let c=await V.readFile(l,"utf8");i.add(c)}catch(c){console.warn(`Warning: Could not read .boxelignore file at ${l}:`,c)}let u=G.dirname(o);if(u===o)break;o=u}return i})();return this.ignoreCache.set(e,n),n}async shouldIgnoreFile(e,t){let n=G.basename(e);if(n===".boxel-sync.json"||n.startsWith("."))return!0;let i=G.dirname(t),o=await this.getIgnoreInstance(i),s=e.replace(/\\/g,"/");return o.ignores(s)}shouldIgnoreRemoteFile(e){return!!G.basename(e).startsWith(".")}};async function Hn(r){try{return await Y.access(r),!0}catch{return!1}}var U=class{workspaceDir;gitDir;constructor(e){this.workspaceDir=H.resolve(e),this.gitDir=H.join(this.workspaceDir,".boxel-history")}async init(){await Hn(this.gitDir)||await Y.mkdir(this.gitDir,{recursive:!0});let e=H.join(this.gitDir,".git");await Hn(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 Hn(H.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 o=H.join(this.gitDir,i);try{await Y.unlink(o)}catch(s){if(s.code!=="ENOENT")throw s}}})),await Promise.all(e.map(async i=>{let o=H.join(this.workspaceDir,i),s=H.join(this.gitDir,i),a=H.dirname(s);await Y.mkdir(a,{recursive:!0}),await Y.copyFile(o,s)}))}async getWorkspaceFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await Y.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".boxel-history"||s.name===".boxel-sync.json"||s.name==="node_modules"||s.name.startsWith("."))return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.name),a):e.push(a)}))};return await t(this.workspaceDir),e}async getHistoryFiles(){let e=[],t=async(n,i="")=>{let o;try{o=await Y.readdir(n,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")return;throw s}await Promise.all(o.map(async s=>{if(s.name===".git")return;let a=i?`${i}/${s.name}`:s.name;s.isDirectory()?await t(H.join(n,s.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(`
67
+ `)){if(!n)continue;let i=n.substring(0,2),o=n.substring(3);if(i.includes("R")){let s=o.indexOf(" -> ");if(s!==-1){let a=o.substring(0,s),l=o.substring(s+4);t.push({file:a,status:"deleted"}),t.push({file:l,status:"added"});continue}}i.includes("D")?t.push({file:o,status:"deleted"}):i.includes("A")||i.includes("C")||i==="??"?t.push({file:o,status:"added"}):(i.includes("M")||i.includes("U")||i.includes("T"))&&t.push({file:o,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 o=this.classifyChanges(t),{message:s,description:a}=n?{message:n,description:""}:this.generateCommitMessage(e,t,o),l=o?"[MAJOR]":"[minor]",u=`[${e}]`,c=`${l} ${u} ${s}${a?`
62
68
 
63
- `+a:""}`;await this.git("commit","-m",c);let f=(await this.git("rev-parse","HEAD")).trim(),d=f.substring(0,7);return{hash:f,shortHash:d,message:o,description:a,date:new Date,isMajor:s,filesChanged:t.length,insertions:0,deletions:0,source:e,isMilestone:!1}}classifyChanges(e){if(e.length>3)return!0;for(let t of e)if(t.status==="added"||t.status==="deleted"||t.file.endsWith(".gts"))return!0;return!1}generateCommitMessage(e,t,n){let i=e==="local"?"Push":e==="remote"?"Pull":"Manual";if(t.length===0)return{message:`${i}: No changes detected`,description:""};if(t.length===1){let f=t[0],d=f.status==="added"?"Add":f.status==="deleted"?"Delete":"Update";return{message:`${i}: ${d} ${f.file}`,description:""}}let s=t.filter(f=>f.status==="added"),o=t.filter(f=>f.status==="modified"),a=t.filter(f=>f.status==="deleted"),l=[];s.length>0&&l.push(`+${s.length}`),o.length>0&&l.push(`~${o.length}`),a.length>0&&l.push(`-${a.length}`);let u=`${i}: ${t.length} files (${l.join(", ")})`,c=[];return s.length>0&&(c.push("Added:"),s.forEach(f=>c.push(` + ${f.file}`))),o.length>0&&(c.push("Modified:"),o.forEach(f=>c.push(` ~ ${f.file}`))),a.length>0&&(c.push("Deleted:"),a.forEach(f=>c.push(` - ${f.file}`))),{message:u,description:c.join(`
64
- `)}}async getCheckpoints(e=50){if(!await this.isInitialized())return[];let n=await this.git("log","--format=%H|%h|%s|%aI|%an",`-${e}`);if(!n.trim())return[];let i=await this.getAllMilestones(),s=n.trim().split(`
65
- `).filter(o=>!(o.split("|")[2]??"").startsWith("[init]"));return Promise.all(s.map(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",u=s.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),c=await this.getCommitStats(n),f=t.get(n),d=!!f;return{hash:n,shortHash:i,message:u,description:"",date:new Date(o),isMajor:a,source:l,isMilestone:d,milestoneName:f,...c}}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
66
- `),i=n[n.length-1]||"",s=i.match(/(\d+) files? changed/),o=i.match(/(\d+) insertions?/),a=i.match(/(\d+) deletions?/);return{filesChanged:s?parseInt(s[1]):0,insertions:o?parseInt(o[1]):0,deletions:a?parseInt(a[1]):0}}catch{return{filesChanged:0,insertions:0,deletions:0}}}async getChangedFiles(e){return(await this.git("show","--name-only","--format=",e)).trim().split(`
67
- `).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=G.join(this.gitDir,o);try{await B.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=G.join(this.workspaceDir,o);try{await B.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async o=>{if(D(o))return;let a=G.join(this.gitDir,o),l=G.join(this.workspaceDir,o),u=G.dirname(l);await B.mkdir(u,{recursive:!0}),await B.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(`
69
+ `+a:""}`;await this.git("commit","-m",c);let m=(await this.git("rev-parse","HEAD")).trim(),d=m.substring(0,7);return{hash:m,shortHash:d,message:s,description:a,date:new Date,isMajor:o,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 m=t[0],d=m.status==="added"?"Add":m.status==="deleted"?"Delete":"Update";return{message:`${i}: ${d} ${m.file}`,description:""}}let o=t.filter(m=>m.status==="added"),s=t.filter(m=>m.status==="modified"),a=t.filter(m=>m.status==="deleted"),l=[];o.length>0&&l.push(`+${o.length}`),s.length>0&&l.push(`~${s.length}`),a.length>0&&l.push(`-${a.length}`);let u=`${i}: ${t.length} files (${l.join(", ")})`,c=[];return o.length>0&&(c.push("Added:"),o.forEach(m=>c.push(` + ${m.file}`))),s.length>0&&(c.push("Modified:"),s.forEach(m=>c.push(` ~ ${m.file}`))),a.length>0&&(c.push("Deleted:"),a.forEach(m=>c.push(` - ${m.file}`))),{message:u,description:c.join(`
70
+ `)}}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(),o=n.trim().split(`
71
+ `).filter(s=>!(s.split("|")[2]??"").startsWith("[init]"));return Promise.all(o.map(s=>this.parseCheckpointLine(s,i)))}async parseCheckpointLine(e,t){let[n,i,o,s]=e.split("|"),a=o.includes("[MAJOR]"),l=o.includes("[local]")?"local":o.includes("[remote]")?"remote":"manual",u=o.replace(/\[(MAJOR|minor)\]\s*/i,"").replace(/\[(local|remote|manual)\]\s*/i,""),c=await this.getCommitStats(n),m=t.get(n),d=!!m;return{hash:n,shortHash:i,message:u,description:"",date:new Date(s),isMajor:a,source:l,isMilestone:d,milestoneName:m,...c}}async getCommitStats(e){try{let n=(await this.git("show","--stat","--format=",e)).trim().split(`
72
+ `),i=n[n.length-1]||"",o=i.match(/(\d+) files? changed/),s=i.match(/(\d+) insertions?/),a=i.match(/(\d+) deletions?/);return{filesChanged:o?parseInt(o[1]):0,insertions:s?parseInt(s[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(`
73
+ `).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 s=>{let a=H.join(this.gitDir,s);try{await Y.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}})),await this.git("checkout",e,"--",".");let n=await this.getHistoryFiles(),i=new Set(n),o=await this.getWorkspaceFiles();await Promise.all(o.map(async s=>{if(!D(s)&&!i.has(s)){let a=H.join(this.workspaceDir,s);try{await Y.unlink(a)}catch(l){if(l.code!=="ENOENT")throw l}}})),await Promise.all(n.map(async s=>{if(D(s))return;let a=H.join(this.gitDir,s),l=H.join(this.workspaceDir,s),u=H.dirname(l);await Y.mkdir(u,{recursive:!0}),await Y.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 o=await this.getCheckpoints(e+1);if(e<1||e>o.length)return null;n=o[e-1].hash}else n=e;let i=`milestone/${t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9\-_.]/g,"")}`;try{return await this.git("tag","-a",i,n,"-m",`Milestone: ${t}`),{hash:n,name:t}}catch{return null}}async unmarkMilestone(e){if(!await this.isInitialized())return!1;let t;if(typeof e=="number"){let i=await this.getCheckpoints(e+1);if(e<1||e>i.length)return!1;t=i[e-1].hash}else t=e;let n=await this.getMilestoneTags(t);if(n.length===0)return!1;for(let i of n)try{await this.git("tag","-d",i)}catch{}return!0}async getMilestoneTags(e){try{return(await this.git("tag","--points-at",e)).trim().split(`
68
74
  `).filter(n=>n.startsWith("milestone/")).filter(Boolean)}catch{return[]}}async getAllMilestones(){let e=new Map;try{let t=await this.git("tag","-l","milestone/*");for(let n of t.trim().split(`
69
- `).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),s=n.replace("milestone/","").replace(/-/g," ");e.set(i,s)}catch{}}catch{}return e}async getMilestones(){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(`
70
- `).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,_l.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 Xt(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 Ol=100;function zt(r){return r instanceof Error?r.message:String(r)}async function ny(r,e){if(!Qe.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(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: ${zt(t)}`}}}async function iy(r,e){if(!Qe.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 U(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: ${zt(n)}`}}}async function sy(r,e,t){if(!Qe.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new U(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=Xt(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: ${zt(n)}`}}}async function oy(r,e){if(!Qe.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(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: ${zt(t)}`}}}function ay(r){return r==="local"?`${S}LOCAL${m}`:r==="remote"?`${k}SERVER${m}`:`${re}MANUAL${m}`}function kl(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 ly(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
71
- ${z}Checkpoint History${m}
72
- `);let n=String(r.length).length;r.forEach((i,s)=>{let o=s+1,a=`${y}${String(o).padStart(n," ")}${m}`,l=i.isMajor?`${T}[MAJOR]${m}`:`${y}[minor]${m}`,u=i.isMilestone?`${T}\u2B50${m} ${re}[${i.milestoneName}]${m} `:"";console.log(`${a} ${T}${i.shortHash}${m} ${u}${ay(i.source)} ${l} ${i.message} ${y}(${i.filesChanged} files)${m}`),console.log(` ${y}${kl(i.date)}${m}
73
- `)}),e&&console.log(`${y}Showing first ${t} checkpoints. Pass --limit <n> to see more.${m}`),console.log(`${y}Restore: boxel realm history <local-dir> -r <ref>${m}`)}function cy(r){if(r===void 0)return Ol;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Se(r){console.error(`${g}Error:${m} ${r}`),process.exit(1)}function Cl(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: ${Ol})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Se("Only one of --restore or --message may be specified.");let n=cy(t.limit);if(n===null&&Se("--limit must be a positive integer."),t.message!==void 0){let s=await iy(e,t.message);s.ok||Se(s.error),console.log(`${S}\u2713${m} Checkpoint created: ${T}${s.created.shortHash}${m} ${s.created.message}`);return}if(t.restore!==void 0){let s=await sy(e,t.restore,n);s.ok||Se(s.error);let o=s.target;if(!t.yes){process.stdin.isTTY||Se("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
74
- ${z}Restoring to:${m} ${T}${o.shortHash}${m} - ${o.message}`),console.log(`${y}${kl(o.date)}${m}
75
- `);let l=await J(`${T}This will overwrite current files. Continue? (y/N) ${m}`);if(!/^y/i.test(l)){console.log(`${y}Restore cancelled.${m}`);return}}let a=await oy(e,o.hash);a.ok||Se(a.error),console.log(`${S}\u2713${m} Restored to ${T}${o.shortHash}${m} ${o.message}`),console.log(`${y}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${m}`);return}let i=await ny(e,n);i.ok||Se(i.error),ly(i.checkpoints,i.truncated,n)})}var uy="--all-accessible and --hidden are mutually exclusive";async function fy(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:uy};let e=r.profileManager??O(),t=e.getActiveProfile();if(!t)return{realms:[],error:N};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let c=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${c}`}}let s=await i.json(),o=Object.keys(s).map(C),a;try{a=await e.getUserRealms()}catch(c){return{realms:[],error:`Failed to load UI realm list: ${c instanceof Error?c.message:String(c)}`}}let l=new Set(a.map(C)),u=o.map(c=>({url:c,hidden:!l.has(c)}));return r.allAccessible||(r.hidden?u=u.filter(c=>c.hidden):u=u.filter(c=>!c.hidden)),u.sort((c,f)=>c.url.localeCompare(f.url)),{realms:u}}function Al(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 fy({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${g}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(`${g}Error:${m} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${y}No realms found.${m}`);return}console.log(`${z}${t.realms.length} realm(s):${m}`);for(let n of t.realms){let i=n.hidden?` ${y}(hidden)${m}`:"";console.log(` ${k}${n.url}${m}${i}`)}})}var Kt=P(require("fs"));var In=100;function Qt(r){return r instanceof Error?r.message:String(r)}function my(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 Tl(r,e,t){try{let n=new U(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=Xt(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: ${Qt(n)}`}}}async function dy(r){if(!Kt.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let e=new U(r);return await e.isInitialized()?{ok:!0,milestones:await e.getMilestones()}:{ok:!0,milestones:[]}}catch(e){return{ok:!1,error:`Failed to read milestones: ${Qt(e)}`}}}async function py(r,e,t,n){if(!Kt.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 Tl(r,e,n);if(!s.ok)return s;try{let o=new U(r);if(!await o.markMilestone(s.target.hash,i))return{ok:!1,error:"Could not mark milestone. The checkpoint may already have one."};let u=(await o.getCheckpoints(n)).find(c=>c.hash===s.target.hash);return u?{ok:!0,marked:u}:{ok:!1,error:"Milestone created but checkpoint could not be re-read."}}catch(o){return{ok:!1,error:`Failed to mark milestone: ${Qt(o)}`}}}async function hy(r,e,t){if(!Kt.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Tl(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 U(r).unmarkMilestone(i.hash)}}catch(s){return{ok:!1,error:`Failed to remove milestone: ${Qt(s)}`}}}async function gy(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??In;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await py(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 hy(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await dy(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function yy(r,e){if(r.length===0){console.log(`
75
+ `).filter(Boolean))try{let i=(await this.git("rev-list","-1",n)).trim(),o=n.replace("milestone/","").replace(/-/g," ");e.set(i,o)}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(`
76
+ `).map(i=>this.parseCheckpointLine(i,e))):[]}git(...e){return new Promise((t,n)=>{let i=(0,Bl.spawn)("git",e,{cwd:this.gitDir}),o="",s="";i.stdout.on("data",a=>{o+=a.toString("utf-8")}),i.stderr.on("data",a=>{s+=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: ${s}`));return}t(o)})})}};function rr(r,e){let t=r.trim();if(t==="")return{kind:"none"};if(t.length===7){let i=e.filter(o=>o.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 Yl=100;function nr(r){return r instanceof Error?r.message:String(r)}async function Gy(r,e){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(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: ${nr(t)}`}}}async function Vy(r,e){if(!ot.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 U(r);await n.isInitialized()||await n.init();let i=await n.detectCurrentChanges(),o=await n.createCheckpoint("manual",i,t);return o?{ok:!0,created:o}:{ok:!1,error:"No changes to checkpoint."}}catch(n){return{ok:!1,error:`Failed to create checkpoint: ${nr(n)}`}}}async function Hy(r,e,t){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let n=new U(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),o=rr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoint history: ${nr(n)}`}}}async function Wy(r,e){if(!ot.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let t=new U(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: ${nr(t)}`}}}function By(r){return r==="local"?`${S}LOCAL${f}`:r==="remote"?`${_}SERVER${f}`:`${ne}MANUAL${f}`}function Xl(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 Yy(r,e,t){if(r.length===0){console.log("No checkpoints found.");return}console.log(`
77
+ ${J}Checkpoint History${f}
78
+ `);let n=String(r.length).length;r.forEach((i,o)=>{let s=o+1,a=`${y}${String(s).padStart(n," ")}${f}`,l=i.isMajor?`${C}[MAJOR]${f}`:`${y}[minor]${f}`,u=i.isMilestone?`${C}\u2B50${f} ${ne}[${i.milestoneName}]${f} `:"";console.log(`${a} ${C}${i.shortHash}${f} ${u}${By(i.source)} ${l} ${i.message} ${y}(${i.filesChanged} files)${f}`),console.log(` ${y}${Xl(i.date)}${f}
79
+ `)}),e&&console.log(`${y}Showing first ${t} checkpoints. Pass --limit <n> to see more.${f}`),console.log(`${y}Restore: boxel realm history <local-dir> -r <ref>${f}`)}function Xy(r){if(r===void 0)return Yl;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Ce(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function zl(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: ${Yl})`).action(async(e,t)=>{t.restore!==void 0&&t.message!==void 0&&Ce("Only one of --restore or --message may be specified.");let n=Xy(t.limit);if(n===null&&Ce("--limit must be a positive integer."),t.message!==void 0){let o=await Vy(e,t.message);o.ok||Ce(o.error),console.log(`${S}\u2713${f} Checkpoint created: ${C}${o.created.shortHash}${f} ${o.created.message}`);return}if(t.restore!==void 0){let o=await Hy(e,t.restore,n);o.ok||Ce(o.error);let s=o.target;if(!t.yes){process.stdin.isTTY||Ce("--restore overwrites local files. Pass --yes to confirm in non-interactive mode."),console.log(`
80
+ ${J}Restoring to:${f} ${C}${s.shortHash}${f} - ${s.message}`),console.log(`${y}${Xl(s.date)}${f}
81
+ `);let l=await K(`${C}This will overwrite current files. Continue? (y/N) ${f}`);if(!/^y/i.test(l)){console.log(`${y}Restore cancelled.${f}`);return}}let a=await Wy(e,s.hash);a.ok||Ce(a.error),console.log(`${S}\u2713${f} Restored to ${C}${s.shortHash}${f} ${s.message}`),console.log(`${y}Run 'boxel realm sync <local-dir> <realm-url> --prefer-local' to push the restored state to the realm.${f}`);return}let i=await Gy(e,n);i.ok||Ce(i.error),Yy(i.checkpoints,i.truncated,n)})}var zy="--all-accessible and --hidden are mutually exclusive";async function Jy(r={}){if(r.allAccessible&&r.hidden)return{realms:[],error:zy};let e=r.profileManager??A(),t=e.getActiveProfile();if(!t)return{realms:[],error:M};let n=t.profile.realmServerUrl.replace(/\/$/,""),i=await e.authedRealmServerFetch(`${n}/_realm-auth`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!i.ok){let c=await i.text();return{realms:[],error:`Realm auth lookup failed: ${i.status} ${c}`}}let o=await i.json(),s=Object.keys(o).map(P),a;try{a=await e.getUserRealms()}catch(c){return{realms:[],error:`Failed to load UI realm list: ${c instanceof Error?c.message:String(c)}`}}let l=new Set(a.map(P)),u=s.map(c=>({url:c,hidden:!l.has(c)}));return r.allAccessible||(r.hidden?u=u.filter(c=>c.hidden):u=u.filter(c=>!c.hidden)),u.sort((c,m)=>c.url.localeCompare(m.url)),{realms:u}}function Jl(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 Jy({allAccessible:e.allAccessible,hidden:e.hidden})}catch(n){console.error(`${h}Error:${f} ${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:${f} ${t.error}`),process.exit(1)),t.realms.length===0){console.log(`${y}No realms found.${f}`);return}console.log(`${J}${t.realms.length} realm(s):${f}`);for(let n of t.realms){let i=n.hidden?` ${y}(hidden)${f}`:"";console.log(` ${_}${n.url}${f}${i}`)}})}var or=O(require("fs"));var Wn=100;function sr(r){return r instanceof Error?r.message:String(r)}function Ky(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 Kl(r,e,t){try{let n=new U(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),o=rr(e,i);if(o.kind==="none")return{ok:!1,error:`Checkpoint not found: ${e}. Use a number (1-${i.length}) or a commit hash.`};if(o.kind==="ambiguous"){let s=o.matches.slice(0,5).map(l=>l.shortHash).join(", "),a=o.matches.length>5?", \u2026":"";return{ok:!1,error:`Ambiguous reference: ${e} matches ${o.matches.length} checkpoints (${s}${a}). Use a longer prefix or full hash.`}}return{ok:!0,target:o.target}}catch(n){return{ok:!1,error:`Failed to read checkpoints: ${sr(n)}`}}}async function Qy(r){if(!or.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};try{let e=new U(r);return await e.isInitialized()?{ok:!0,milestones:await e.getMilestones()}:{ok:!0,milestones:[]}}catch(e){return{ok:!1,error:`Failed to read milestones: ${sr(e)}`}}}async function Zy(r,e,t,n){if(!or.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 o=await Kl(r,e,n);if(!o.ok)return o;try{let s=new U(r);if(!await s.markMilestone(o.target.hash,i))return{ok:!1,error:"Could not mark milestone. The checkpoint may already have one."};let u=(await s.getCheckpoints(n)).find(c=>c.hash===o.target.hash);return u?{ok:!0,marked:u}:{ok:!1,error:"Milestone created but checkpoint could not be re-read."}}catch(s){return{ok:!1,error:`Failed to mark milestone: ${sr(s)}`}}}async function ew(r,e,t){if(!or.existsSync(r))return{ok:!1,error:`Directory not found: ${r}`};let n=await Kl(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 U(r).unmarkMilestone(i.hash)}}catch(o){return{ok:!1,error:`Failed to remove milestone: ${sr(o)}`}}}async function tw(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??Wn;if(e.mark!==void 0){if(e.name===void 0)return{ok:!1,error:"--name is required when using --mark."};let i=await Zy(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 ew(r,e.remove,t);return i.ok?{ok:!0,removed:i.removed}:{ok:!1,error:i.error}}let n=await Qy(r);return n.ok?{ok:!0,milestones:n.milestones}:{ok:!1,error:n.error}}function rw(r,e){if(r.length===0){console.log(`
76
82
  No milestones marked yet.
77
- `),console.log(`Use ${k}boxel realm milestone <local-dir> --mark <ref> --name <name>${m} to mark a checkpoint.`),console.log(`Use ${k}boxel realm history <local-dir>${m} to see available checkpoints.
83
+ `),console.log(`Use ${_}boxel realm milestone <local-dir> --mark <ref> --name <name>${f} to mark a checkpoint.`),console.log(`Use ${_}boxel realm history <local-dir>${f} to see available checkpoints.
78
84
  `);return}console.log(`
79
- ${z}Milestones${m} ${y}(${e})${m}
80
- `);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?k:re;console.log(` ${T}\u2B50${m} ${T}${t.shortHash}${m} ${i}${n}${m} ${re}[${t.milestoneName}]${m} ${t.message}`),console.log(` ${y}${my(t.date)}${m}`)}console.log()}function Ey(r){if(r===void 0)return In;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function Jt(r){console.error(`${g}Error:${m} ${r}`),process.exit(1)}function Pl(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: ${In})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&Jt("Only one of --mark or --remove may be specified.");let n=Ey(t.limit);n===null&&Jt("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&Jt("--name is required when using --mark.");let i=await gy(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||Jt(i.error),i.marked){let s=i.marked;console.log(`
81
- ${S}\u2713${m} ${T}\u2B50${m} Milestone created: ${re}${s.milestoneName}${m}`),console.log(` Checkpoint: ${T}${s.shortHash}${m} ${s.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${m} Milestone removed`);return}yy(i.milestones,e)})}var Ll=P(mn()),Il="realm_server";function wy(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 by(r,e=Il){return`@${e}:${wy(r)}`}function Ry(r){return new URL(r).origin+"/"}function $y(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var Zt=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??Il,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=$y(e);return{user:this.#r??by(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:Ry(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Ll.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 Zt({seed:r.realmSecretSeed});return t.registerRealmUrl(r.realmUrl),{ok:!0,authenticator:t,mode:"seed"}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}let e=r.profileManager??O();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:N}}var er=P(require("fs/promises")),Nl=P(require("path")),Nn=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 er.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await er.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 U(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await s.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
82
- Checkpoint created before deletion: ${u.shortHash}`)}let o=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let u=Nl.join(this.options.localDir,l);return await this.downloadFile(l,u),l}catch(u){return this.hasError=!0,console.error(`Error downloading ${l}:`,u),null}})));this.downloadedFiles=o.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
83
- Deleting ${i.size} local files that don't exist in realm...`),a=(await Promise.all(Array.from(i).map(async u=>{try{let c=n.get(u);return c?(await this.deleteLocalFile(c),console.log(` Deleted: ${u}`),u):null}catch(c){return this.hasError=!0,console.error(`Error deleting local file ${u}:`,c),null}}))).filter(u=>u!==null)),!this.options.dryRun&&this.downloadedFiles.length+a.length>0){let l=[...this.downloadedFiles.map(c=>({file:c,status:"modified"})),...a.map(c=>({file:c,status:"deleted"}))],u=await s.createCheckpoint("remote",l);if(u){let c=u.isMajor?"[MAJOR]":"[minor]";console.log(`
84
- Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function Ml(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 vy(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 vy(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 Nn({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 xe=P(require("fs/promises")),Mn=P(require("path")),Fl=P(require("crypto"));function Sy(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 tr(r){try{return await xe.access(r),!0}catch{return!1}}async function me(r){let e=await xe.readFile(r);return Fl.createHash("md5").update(e).digest("hex")}async function _e(r){let e=Mn.join(r,".boxel-sync.json"),t;try{t=await xe.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return Sy(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Me(r,e){let t=Mn.join(r,".boxel-sync.json");await xe.writeFile(t,JSON.stringify(e,null,2))}var xy=new Set(["index.json","realm.json"]),Fn=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(c){throw console.error("Failed to access realm:",c),new Error("Cannot proceed with push: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let n=await this.getLocalFileList();console.log(`Found ${n.size} files in local directory`);let i=await _e(this.options.localDir),s={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},o=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[f,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,E])=>{if(D(p))return{relativePath:p,localPath:E,currentHash:"",protected:!0};let x=await me(E);return{relativePath:p,localPath:E,currentHash:x,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let E=i.files[p.relativePath],x=i.remoteMtimes?.[p.relativePath],K=f.get(p.relativePath),nt=E!==p.currentHash,R=E!==void 0&&!t.has(p.relativePath),$=x!==void 0&&K!==void 0&&K!==x;nt||R||$?(o.set(p.relativePath,p.localPath),!nt&&(R||$)&&a.add(p.relativePath)):(c++,s.files[p.relativePath]=p.currentHash,x!==void 0&&(s.remoteMtimes[p.relativePath]=x))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),E=p.slice(0,5).join(", "),x=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${E}${x}`)}}else{this.pushOptions.force?console.log("Force mode: uploading all files"):console.log(i?"Realm URL changed, will upload all files":"No sync manifest found, will upload all files");for(let[c,f]of n)D(c)||o.set(c,f)}let u=!1;if(o.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${o.size} file(s) via /_atomic...`);let c=new Set,f=this.pushOptions.force||!i;for(let p of o.keys())if(f)t.has(p)||c.add(p);else{let E=i.files[p]!==void 0,x=E&&!t.has(p);(!E||x)&&c.add(p)}let d=await this.uploadFilesAtomic(o,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let E;p.status===409?E=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?E=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:E=`${p.path}: ${p.title}`,console.error(` ${E}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async E=>({rel:E,hash:await me(o.get(E))})));for(let{rel:E,hash:x}of p)s.files[E]=x}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),f=[];for(let d of c){if(D(d)){c.delete(d);continue}xy.has(d)&&(c.delete(d),f.push(d))}for(let d of n.keys())c.delete(d);if(f.length>0&&console.log(`Skipping ${f.length} realm-managed remote artifact(s): ${f.join(", ")}`),c.size>0){let d=Array.from(c).sort();console.log(`Deleting ${d.length} remote files that don't exist locally: ${d.join(", ")}`);for(let p of d)try{await this.deleteFile(p)}catch(E){this.hasError=!0,console.error(`Error deleting ${p}:`,E)}}}if(!this.options.dryRun&&!u&&o.size>0)try{let c=await this.getRemoteMtimes();for(let f of Object.keys(s.files)){let d=c.get(f);d!==void 0&&(s.remoteMtimes[f]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(s.remoteMtimes&&Object.keys(s.remoteMtimes).length===0&&delete s.remoteMtimes,!this.options.dryRun&&!u&&await Me(this.options.localDir,s),!this.options.dryRun&&o.size>0&&!u){let c=new U(this.options.localDir),f=Array.from(o.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",f);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
85
- Checkpoint created: ${d.shortHash} ${p} ${d.message}`)}}console.log("Push completed")}};function Dl(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 _y(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function _y(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 tr(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new Fn({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 Ul(r){let e=C(r.realmUrl.trim()),t=r.profileManager??O(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:N};let i;try{i=await t.getUserRealms()}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:`Failed to load realm list: ${d instanceof Error?d.message:String(d)}`}}let s=i.map(C),o=s.length,a=s.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=o-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:l};let u=n.profile.realmServerUrl.replace(/\/$/,""),c;try{c=await t.authedRealmServerFetch(`${u}/_delete-realm`,{method:"DELETE",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",id:e}})})}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await Oy(c),p=c.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${c.status}: ${d}`;return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:o,nextCount:o,error:p}}let f;try{f=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return f?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:f,previousCount:o,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:o,nextCount:o,error:"Server delete succeeded, but Matrix account_data did not contain the URL by the time we PUT (concurrent edit?). Server-side files are gone; please refresh and check your realm list."}}async function Oy(r){try{return await r.text()}catch{return"<no response body>"}}function jl(r){r.command("remove").description("Remove a realm \u2014 deletes server-side files and unlinks it from your realm list").argument("<realm-url>","realm URL to remove").option("-y, --yes","Skip the interactive confirmation prompt").option("--dry-run","Preview the change without writing to Matrix").action(async(e,t)=>{let n=C(e.trim()),i=await Ul({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${g}Error:${m} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${g}Error:${m} ${i.error}`),process.exit(1)),console.log(`Remove target: ${k}${i.realmUrl}${m}`),console.log(`${y}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${m}`),t.dryRun){console.log(`${y}[DRY RUN] No server delete or Matrix changes sent.${m}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${g}Error:${m} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let o=await J("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(o)){console.log(`${y}Cancelled.${m}`);return}}let s=await Ul({realmUrl:n});(s.error||!s.removed)&&(console.error(`${g}Error:${m} ${s.error??"Removal did not complete."}`),s.serverDeleted&&!s.unlinked&&console.error(`${y}The realm is gone, but your account_data still references ${s.realmUrl}.${m}`),process.exit(1)),console.log(`${S}Removed:${m} ${k}${s.realmUrl}${m}`)})}var Un=P(require("path"));function ql(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 Vl(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 Gl(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 Hl(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 jn=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(R){throw console.error("Failed to access realm:",R),new Error("Cannot proceed with sync: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let[n,i,s]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),_e(this.options.localDir)]),o=new Map;for(let[R,$]of n)o.set(R,$.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[R]of t)i.set(R,0)}console.log(`Found ${o.size} local files`),console.log(`Found ${i.size} remote files`),s&&s.realmUrl!==this.normalizedRealmUrl&&console.warn(`${T}Warning:${m} Manifest realm URL (${s.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=s&&s.realmUrl===this.normalizedRealmUrl?s:null,l=new Map;await Promise.all(Array.from(o.entries()).map(async([R,$])=>{D(R)||l.set(R,await me($))}));let u=new Set;for(let R of o.keys())u.add(R);for(let R of i.keys())u.add(R);if(a){for(let R of Object.keys(a.files))u.add(R);if(a.remoteMtimes)for(let R of Object.keys(a.remoteMtimes))u.add(R)}let c=[];for(let R of u){if(D(R))continue;let $=ql(R,l,a),_=Vl(R,i,a),F=Gl($,_,this.syncOptions);c.push({relativePath:R,localStatus:$,remoteStatus:_,action:F})}let f=[],d=[],p=[],E=[],x=[],K=0;for(let R of c)switch(R.action){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":E.push(R.relativePath);break;case"conflict":x.push(R);break;case"noop":K++;break}for(let R of x)switch(Hl(R,n,i,this.conflictStrategy)){case"push":f.push(R.relativePath);break;case"pull":d.push(R.relativePath);break;case"push-delete":p.push(R.relativePath);break;case"pull-delete":E.push(R.relativePath);break;case"noop":break;default:this.skippedConflicts.push(R.relativePath);break}if(console.log(`
86
- ${y}Sync plan:${m}`),f.length>0&&console.log(` ${S}\u2191 Push:${m} ${f.length} file(s)`),d.length>0&&console.log(` ${k}\u2193 Pull:${m} ${d.length} file(s)`),p.length>0&&console.log(` ${g}\u2191 Delete remote:${m} ${p.length} file(s)`),E.length>0&&console.log(` ${g}\u2193 Delete local:${m} ${E.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${T}\u26A0 Conflicts skipped:${m} ${this.skippedConflicts.length} file(s)`);for(let R of this.skippedConflicts)console.log(` ${R}`);console.log(` ${y}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${m}`)}if(K>0&&console.log(` ${y}Unchanged: ${K} file(s)${m}`),f.length+d.length+p.length+E.length===0){console.log(`
85
+ ${J}Milestones${f} ${y}(${e})${f}
86
+ `);for(let t of r){let n=t.source==="local"?"\u2191":t.source==="remote"?"\u2193":"\u25CF",i=t.source==="local"?S:t.source==="remote"?_:ne;console.log(` ${C}\u2B50${f} ${C}${t.shortHash}${f} ${i}${n}${f} ${ne}[${t.milestoneName}]${f} ${t.message}`),console.log(` ${y}${Ky(t.date)}${f}`)}console.log()}function nw(r){if(r===void 0)return Wn;if(!/^\d+$/.test(r))return null;let e=parseInt(r,10);return e>0?e:null}function ir(r){console.error(`${h}Error:${f} ${r}`),process.exit(1)}function Ql(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: ${Wn})`).option("--json","Output result as JSON").action(async(e,t)=>{t.mark!==void 0&&t.remove!==void 0&&ir("Only one of --mark or --remove may be specified.");let n=nw(t.limit);n===null&&ir("--limit must be a positive integer."),t.mark!==void 0&&t.name===void 0&&ir("--name is required when using --mark.");let i=await tw(e,{mark:t.mark,name:t.name,remove:t.remove,limit:n});if(t.json){N.output(JSON.stringify(i,null,2)),i.ok||process.exit(1);return}if(i.ok||ir(i.error),i.marked){let o=i.marked;console.log(`
87
+ ${S}\u2713${f} ${C}\u2B50${f} Milestone created: ${ne}${o.milestoneName}${f}`),console.log(` Checkpoint: ${C}${o.shortHash}${f} ${o.message}`),console.log();return}if(i.removed!==void 0){console.log(`${S}\u2713${f} Milestone removed`);return}rw(i.milestones,e)})}var Zl=O(bn()),ec="realm_server";function iw(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 ow(r,e=ec){return`@${e}:${iw(r)}`}function sw(r){return new URL(r).origin+"/"}function aw(r){try{return new URL(r).href.replace(/\/+$/,"")+"/"}catch{throw new Error(`Invalid realm URL: ${r}`)}}var ar=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??ec,this.#r=e.botUserId,this.#i=e.expiresIn??"7d"}buildClaims(e){let t=aw(e);return{user:this.#r??ow(t,this.#t),realm:t,sessionRoom:void 0,permissions:[],realmServerURL:sw(t)}}mintTokenForRealm(e){let t=this.buildClaims(e),n=this.#n.get(t.realm);if(n)return n;let i=Zl.default.sign(t,this.#e,{expiresIn:this.#i});return this.#n.set(t.realm,i),i}#o(e){for(let o of this.#n.keys())if(e.startsWith(o))return o;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.#o(n),o=this.mintTokenForRealm(i),s=this.#s(e,t,o);return fetch(e,{...t,headers:s})}#s(e,t,n){let i=e instanceof Request?new Headers(e.headers):new Headers,o=new Headers(t?.headers);for(let[s,a]of o)i.set(s,a);return i.has("Authorization")||i.set("Authorization",n),i}registerRealmUrl(e){this.mintTokenForRealm(e)}};function de(r){if(r.realmSecretSeed)try{let t=new ar({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??A();return e.getActiveProfile()?{ok:!0,authenticator:e,mode:"profile"}:{ok:!1,error:M}}var lr=O(require("fs/promises")),tc=O(require("path")),Bn=class extends ie{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 lr.access(this.options.localDir)}catch{console.log(`[DRY RUN] Would create directory: ${this.options.localDir}`)}else await lr.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 o=new U(this.options.localDir);if(i.size>0&&!this.options.dryRun){let l=Array.from(i).map(c=>({file:c,status:"deleted"})),u=await o.createCheckpoint("remote",l,`Pre-delete checkpoint: ${i.size} files not on server`);u&&console.log(`
88
+ Checkpoint created before deletion: ${u.shortHash}`)}let s=await Promise.all(Array.from(t.keys()).map(l=>this.remoteLimit(async()=>{try{let u=tc.join(this.options.localDir,l);return await this.downloadFile(l,u),l}catch(u){return this.hasError=!0,console.error(`Error downloading ${l}:`,u),null}})));this.downloadedFiles=s.filter(l=>l!==null);let a=[];if(i.size>0&&(console.log(`
89
+ Deleting ${i.size} local files that don't exist in realm...`),a=(await Promise.all(Array.from(i).map(async u=>{try{let c=n.get(u);return c?(await this.deleteLocalFile(c),console.log(` Deleted: ${u}`),u):null}catch(c){return this.hasError=!0,console.error(`Error deleting local file ${u}:`,c),null}}))).filter(u=>u!==null)),!this.options.dryRun&&this.downloadedFiles.length+a.length>0){let l=[...this.downloadedFiles.map(c=>({file:c,status:"modified"})),...a.map(c=>({file:c,status:"deleted"}))],u=await o.createCheckpoint("remote",l);if(u){let c=u.isMajor?"[MAJOR]":"[minor]";console.log(`
90
+ Checkpoint created: ${u.shortHash} ${c} ${u.message}`)}}console.log("Pull completed")}};function rc(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 me(n.realmSecretSeed===!0),o=await lw(e,t,{delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i});o.error&&(console.error(`Error: ${o.error}`),process.exit(o.files.length>0?2:1)),console.log("Pull completed successfully")})}async function lw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:r,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!i.ok)return{files:[],error:i.error};n=i.authenticator}try{let i=new Bn({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 Ae=O(require("fs/promises")),Yn=O(require("path")),nc=O(require("crypto"));function Xn(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 Ge(r){try{return await Ae.access(r),!0}catch{return!1}}async function oe(r){let e=await Ae.readFile(r);return nc.createHash("md5").update(e).digest("hex")}async function ye(r){let e=Yn.join(r,".boxel-sync.json"),t;try{t=await Ae.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let n;try{n=JSON.parse(t)}catch{return null}return Xn(n)?n:(console.warn("Warning: .boxel-sync.json is malformed or has an unexpected shape; falling back to a full upload."),null)}async function Re(r,e){let t=Yn.join(r,".boxel-sync.json");await Ae.writeFile(t,JSON.stringify(e,null,2))}var cw=new Set(["index.json","realm.json"]),zn=class extends ie{constructor(t,n){super(t,n);this.pushOptions=t}hasError=!1;async sync(){console.log(`Starting push from ${this.options.localDir} to ${this.options.realmUrl}`),console.log("Testing realm access...");let t;try{t=await this.getRemoteFileList("")}catch(c){throw console.error("Failed to access realm:",c),new Error("Cannot proceed with push: Authentication or access failed. Please check your credentials and realm permissions.")}console.log("Realm access verified");let n=await this.getLocalFileList();console.log(`Found ${n.size} files in local directory`);let i=await ye(this.options.localDir),o={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}},s=new Map,a=new Set;if(!this.pushOptions.force&&i!==null&&i.realmUrl===this.normalizedRealmUrl){console.log("Checking for changed files...");let c=0,[m,d]=await Promise.all([this.getRemoteMtimes(),Promise.all(Array.from(n.entries()).map(async([p,w])=>{if(D(p))return{relativePath:p,localPath:w,currentHash:"",protected:!0};let x=await oe(w);return{relativePath:p,localPath:w,currentHash:x,protected:!1}}))]);for(let p of d){if(p.protected){c++;continue}let w=i.files[p.relativePath],x=i.remoteMtimes?.[p.relativePath],Q=m.get(p.relativePath),ft=w!==p.currentHash,b=w!==void 0&&!t.has(p.relativePath),R=x!==void 0&&Q!==void 0&&Q!==x;ft||b||R?(s.set(p.relativePath,p.localPath),!ft&&(b||R)&&a.add(p.relativePath)):(c++,o.files[p.relativePath]=p.currentHash,x!==void 0&&(o.remoteMtimes[p.relativePath]=x))}if(c>0&&console.log(`Skipping ${c} unchanged files`),a.size>0){let p=Array.from(a),w=p.slice(0,5).join(", "),x=p.length>5?", ...":"";console.warn(`Warning: ${a.size} file(s) changed on the realm since your last push; your local versions will overwrite them: ${w}${x}`)}}else{this.pushOptions.force?console.log("Force mode: uploading all files"):console.log(i?"Realm URL changed, will upload all files":"No sync manifest found, will upload all files");for(let[c,m]of n)D(c)||s.set(c,m)}let u=!1;if(s.size===0)console.log("No files to upload - everything is up to date");else{console.log(`Uploading ${s.size} file(s) via /_atomic...`);let c=new Set,m=this.pushOptions.force||!i;for(let p of s.keys())if(m)t.has(p)||c.add(p);else{let w=i.files[p]!==void 0,x=w&&!t.has(p);(!w||x)&&c.add(p)}let d=await this.uploadFilesAtomic(s,c);if(d.error){u=!0,this.hasError=!0,console.error(d.error.message);for(let p of d.error.perFile){let w;p.status===409?w=`${p.path} was created on the realm concurrently \u2014 run with --force to overwrite.`:p.status===404?w=`${p.path} was removed from the realm concurrently \u2014 run with --force to re-create it from your local copy.`:w=`${p.path}: ${p.title}`,console.error(` ${w}`)}}else if(d.succeeded.length>0){let p=await Promise.all(d.succeeded.map(async w=>({rel:w,hash:await oe(s.get(w))})));for(let{rel:w,hash:x}of p)o.files[w]=x}}if(this.pushOptions.deleteRemote){let c=new Set(t.keys()),m=[];for(let d of c){if(D(d)){c.delete(d);continue}cw.has(d)&&(c.delete(d),m.push(d))}for(let d of n.keys())c.delete(d);if(m.length>0&&console.log(`Skipping ${m.length} realm-managed remote artifact(s): ${m.join(", ")}`),c.size>0){let d=Array.from(c).sort();console.log(`Deleting ${d.length} remote files that don't exist locally: ${d.join(", ")}`);for(let p of d)try{await this.deleteFile(p)}catch(w){this.hasError=!0,console.error(`Error deleting ${p}:`,w)}}}if(!this.options.dryRun&&!u&&s.size>0)try{let c=await this.getRemoteMtimes();for(let m of Object.keys(o.files)){let d=c.get(m);d!==void 0&&(o.remoteMtimes[m]=d)}}catch(c){console.warn("Could not refresh remote mtimes after upload:",c)}if(o.remoteMtimes&&Object.keys(o.remoteMtimes).length===0&&delete o.remoteMtimes,!this.options.dryRun&&!u&&await Re(this.options.localDir,o),!this.options.dryRun&&s.size>0&&!u){let c=new U(this.options.localDir),m=Array.from(s.keys()).map(p=>({file:p,status:"modified"})),d=await c.createCheckpoint("local",m);if(d){let p=d.isMajor?"[MAJOR]":"[minor]";console.log(`
91
+ 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 me(n.realmSecretSeed===!0);await uw(e,t,{delete:n.delete,dryRun:n.dryRun,force:n.force,realmSecretSeed:i})})}async function uw(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let i=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});i.ok||(console.error(`Error: ${i.error}`),process.exit(1)),n=i.authenticator}await Ge(r)||(console.error(`Local directory does not exist: ${r}`),process.exit(1));try{let i=new zn({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 oc(r){let e=P(r.realmUrl.trim()),t=r.profileManager??A(),n=t.getActiveProfile();if(!n)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:0,nextCount:0,error:M};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 o=i.map(P),s=o.length,a=o.filter(d=>d===e).length;if(a===0)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,notInList:!0,error:"Realm is not in app.boxel.realms. Nothing to remove."};let l=s-a;if(r.dryRun)return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:l};let u=n.profile.realmServerUrl.replace(/\/$/,""),c;try{c=await t.authedRealmServerFetch(`${u}/_delete-realm`,{method:"DELETE",headers:{"Content-Type":"application/vnd.api+json"},body:JSON.stringify({data:{type:"realm",id:e}})})}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:`Failed to reach realm server: ${d instanceof Error?d.message:String(d)}`}}if(!c.ok){let d=await fw(c),p=c.status===403?`You do not own this realm and cannot delete it on the server. Server returned 403: ${d}`:`Realm server returned ${c.status}: ${d}`;return{realmUrl:e,removed:!1,serverDeleted:!1,unlinked:!1,previousCount:s,nextCount:s,error:p}}let m;try{m=await t.removeFromUserRealms(e)}catch(d){return{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,error:`Server delete succeeded, but Matrix unlink failed: ${d instanceof Error?d.message:String(d)}`}}return m?{realmUrl:e,removed:!0,serverDeleted:!0,unlinked:m,previousCount:s,nextCount:l}:{realmUrl:e,removed:!1,serverDeleted:!0,unlinked:!1,previousCount:s,nextCount:s,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 fw(r){try{return await r.text()}catch{return"<no response body>"}}function sc(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=P(e.trim()),i=await oc({realmUrl:n,dryRun:!0});if(i.error&&!i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),i.notInList&&(console.error(`${h}Error:${f} ${i.error}`),process.exit(1)),console.log(`Remove target: ${_}${i.realmUrl}${f}`),console.log(`${y}app.boxel.realms: ${i.previousCount} -> ${i.nextCount}${f}`),t.dryRun){console.log(`${y}[DRY RUN] No server delete or Matrix changes sent.${f}`);return}if(!t.yes){process.stdin.isTTY||(console.error(`${h}Error:${f} stdin is not a TTY. Pass --yes to confirm in non-interactive mode.`),process.exit(1));let s=await K("This will permanently delete the realm files, indexer state, and registry entry on the server. Proceed? (y/N) ");if(!/^y/i.test(s)){console.log(`${y}Cancelled.${f}`);return}}let o=await oc({realmUrl:n});(o.error||!o.removed)&&(console.error(`${h}Error:${f} ${o.error??"Removal did not complete."}`),o.serverDeleted&&!o.unlinked&&console.error(`${y}The realm is gone, but your account_data still references ${o.realmUrl}.${f}`),process.exit(1)),console.log(`${S}Removed:${f} ${_}${o.realmUrl}${f}`)})}var Ve=O(require("fs/promises")),st=O(require("path"));function cr(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 ur(r,e,t){let n=e.has(r),i=t?.remoteMtimes?.[r]!==void 0,o=t?.files[r]!==void 0,s=i||o;return n&&i?e.get(r)===t.remoteMtimes[r]?"unchanged":"changed":n&&o?"changed":n&&!s?"added":!n&&s?"deleted":"unchanged"}function ac(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 lc(r,e,t,n){let{localStatus:i,remoteStatus:o,relativePath:s}=r;if(!n)return null;switch(n){case"prefer-local":return i==="deleted"?"push-delete":"push";case"prefer-remote":return o==="deleted"?"pull-delete":"pull";case"prefer-newest":{if(i==="deleted"&&o==="changed")return"pull";if(i==="changed"&&o==="deleted")return"push";let a=e.get(s),l=t.get(s);return a&&l!==void 0?a.mtime>l*1e3?"push":"pull":"push"}}}var mw=new Set(["node_modules",".git",".boxel-history",".cache",".vscode","dist","build","tmp"]),dw=6;function pw(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 Jn=class extends ie{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 o=new Map;await Promise.all(Array.from(i.entries()).map(async([a,l])=>{D(a)||o.set(a,await oe(l))}));let s=new Set;for(let a of i.keys())s.add(a);for(let a of this.remoteMtimes.keys())s.add(a);for(let a of Object.keys(this.loadedManifest.files))s.add(a);if(this.loadedManifest.remoteMtimes)for(let a of Object.keys(this.loadedManifest.remoteMtimes))s.add(a);for(let a of s){if(D(a))continue;let l=cr(a,o,this.loadedManifest),u=ur(a,this.remoteMtimes,this.loadedManifest),c=pw(l,u);c!==null&&this.changes.push({file:a,status:c})}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 o=st.join(this.options.localDir,i.file);try{await this.downloadFile(i.file,o),this.pulled.push(i.file);let s=await oe(o);this.loadedManifest.files[i.file]=s;let a=this.remoteMtimes.get(i.file);a!==void 0&&(this.loadedManifest.remoteMtimes=this.loadedManifest.remoteMtimes??{},this.loadedManifest.remoteMtimes[i.file]=a)}catch(s){this.hasError=!0;let a=s instanceof Error?s.message:String(s);n.push({file:i.file,message:a}),console.error(` ${h}\u2717 ${i.file}${f} (${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 Re(this.options.localDir,this.loadedManifest)}};async function cc(r,e){let t={localDir:r,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!1},n=st.join(r,".boxel-sync.json");if(!await Ge(n))return{...t,hasError:!0,error:`No .boxel-sync.json found in ${r}. Run: boxel realm sync ${r} <realm-url>`};let i=await ye(r);if(!i)return{...t,hasError:!0,error:`Malformed .boxel-sync.json in ${r}`};let o;try{o=(await Ve.stat(n)).mtimeMs}catch{}let s;if(e.authenticator)s=e.authenticator;else{let l=de({realmUrl:i.realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!l.ok)return{...t,realmUrl:i.realmUrl,manifestMtime:o,hasError:!0,error:l.error};s=l.authenticator}let a=new Jn({realmUrl:i.realmUrl,localDir:r,pull:e.pull},i,s);return await a.sync(),{localDir:r,realmUrl:i.realmUrl,manifestMtime:o,changes:a.changes,pulled:a.pulled.slice().sort(),inSync:!a.hasError&&a.changes.length===0,hasError:a.hasError,error:a.error}}async function hw(r,e){let t=[];async function n(i,o){if(o>e)return;let s;try{s=await Ve.readdir(i,{withFileTypes:!0})}catch{return}if(s.some(l=>l.isFile()&&l.name===".boxel-sync.json")){t.push(i);return}for(let l of s)l.isDirectory()&&(mw.has(l.name)||await n(st.join(i,l.name),o+1))}return await n(r,0),t.sort(),t}async function gw(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:dw,o=await hw(r,i),s=[],a=!1;for(let l of o){let u=st.join(l,".boxel-sync.json"),c;try{c=await Ve.readFile(u,"utf8")}catch{s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"no-manifest"}),a=!0;continue}let m;try{m=JSON.parse(c)}catch{m=void 0}if(!Xn(m)){s.push({localDir:l,realmUrl:"",changes:[],pulled:[],inSync:!1,hasError:!0,skipped:"malformed"}),a=!0;continue}let d=await cc(l,{profileManager:e.profileManager,realmSecretSeed:e.realmSecretSeed,authenticator:e.authenticator}),p={...d};d.hasError&&(p.skipped="fetch-failed",a=!0),s.push(p)}return{rootDir:r,workspaces:s,hasError:a}}function yw(r){if(r.hasError&&r.error){console.error(`${h}Error:${f} ${r.error}`);return}if(console.log(`Realm: ${r.realmUrl}`),console.log(`Local: ${r.localDir}`),r.manifestMtime&&console.log(`${y}Manifest updated:${f} ${new Date(r.manifestMtime).toISOString()}`),console.log(""),r.changes.length===0){console.log(`${S}\u2713 In sync${f}`);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}):${f}`);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}):${f}`);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}):${f}`);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}):${f}`);for(let t of e["modified-local"])console.log(` ~ ${t}`);console.log("")}if(e.conflict.length>0){console.log(`${C}\u26A0 Conflicts (${e.conflict.length}):${f}`);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}):${f}`);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}):${f}`);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):${f}`);for(let t of r.pulled)console.log(` \u2713 ${t}`)}}function ww(r){if(r.error){console.error(`${h}Error:${f} ${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(`${C}${e.localDir}${f} [${e.skipped}]`),e.error&&console.log(` ${y}${e.error}${f}`),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} ${y}${e.realmUrl}${f}`),e.inSync)console.log(` ${S}\u2713 in sync${f}`);else{let n=[];t.newRemote>0&&n.push(`${_}\u2193+${t.newRemote}${f}`),t.modRemote>0&&n.push(`${_}\u2193~${t.modRemote}${f}`),t.newLocal>0&&n.push(`${S}\u2191+${t.newLocal}${f}`),t.modLocal>0&&n.push(`${S}\u2191~${t.modLocal}${f}`),t.conflict>0&&n.push(`${C}\u26A0${t.conflict}${f}`),t.delLocal>0&&n.push(`${h}-L${t.delLocal}${f}`),t.delRemote>0&&n.push(`${h}-R${t.delRemote}${f}`),console.log(` ${n.join(" ")}`)}console.log("")}}function uc(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 me(t.realmSecretSeed===!0);if(t.all){t.pull&&(console.error(`${h}Error:${f} Cannot use --pull with --all`),process.exit(1));let o=await gw(e??process.cwd(),{all:!0,realmSecretSeed:n});ww(o),o.hasError&&process.exit(2);return}let i=await cc(e??process.cwd(),{pull:t.pull,realmSecretSeed:n});yw(i),i.hasError&&process.exit(i.pulled.length>0?2:1)})}var Qn=O(require("path"));var Zn=class extends ie{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,o]=await Promise.all([this.getLocalFileListWithMtimes(),this.getRemoteMtimes(),ye(this.options.localDir)]),s=new Map;for(let[b,R]of n)s.set(b,R.path);if(i.size===0&&t&&t.size>0){console.log("Remote mtimes unavailable, falling back to file listing for remote detection");for(let[b]of t)i.set(b,0)}console.log(`Found ${s.size} local files`),console.log(`Found ${i.size} remote files`),o&&o.realmUrl!==this.normalizedRealmUrl&&console.warn(`${C}Warning:${f} Manifest realm URL (${o.realmUrl}) differs from target (${this.normalizedRealmUrl}). Treating as first sync.`);let a=o&&o.realmUrl===this.normalizedRealmUrl?o:null,l=new Map;await Promise.all(Array.from(s.entries()).map(async([b,R])=>{D(b)||l.set(b,await oe(R))}));let u=new Set;for(let b of s.keys())u.add(b);for(let b of i.keys())u.add(b);if(a){for(let b of Object.keys(a.files))u.add(b);if(a.remoteMtimes)for(let b of Object.keys(a.remoteMtimes))u.add(b)}let c=[];for(let b of u){if(D(b))continue;let R=cr(b,l,a),k=ur(b,i,a),F=ac(R,k,this.syncOptions);c.push({relativePath:b,localStatus:R,remoteStatus:k,action:F})}let m=[],d=[],p=[],w=[],x=[],Q=0;for(let b of c)switch(b.action){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"conflict":x.push(b);break;case"noop":Q++;break}for(let b of x)switch(lc(b,n,i,this.conflictStrategy)){case"push":m.push(b.relativePath);break;case"pull":d.push(b.relativePath);break;case"push-delete":p.push(b.relativePath);break;case"pull-delete":w.push(b.relativePath);break;case"noop":break;default:this.skippedConflicts.push(b.relativePath);break}if(console.log(`
92
+ ${y}Sync plan:${f}`),m.length>0&&console.log(` ${S}\u2191 Push:${f} ${m.length} file(s)`),d.length>0&&console.log(` ${_}\u2193 Pull:${f} ${d.length} file(s)`),p.length>0&&console.log(` ${h}\u2191 Delete remote:${f} ${p.length} file(s)`),w.length>0&&console.log(` ${h}\u2193 Delete local:${f} ${w.length} file(s)`),this.skippedConflicts.length>0){console.log(` ${C}\u26A0 Conflicts skipped:${f} ${this.skippedConflicts.length} file(s)`);for(let b of this.skippedConflicts)console.log(` ${b}`);console.log(` ${y}Use --prefer-local, --prefer-remote, or --prefer-newest to resolve.${f}`)}if(Q>0&&console.log(` ${y}Unchanged: ${Q} file(s)${f}`),m.length+d.length+p.length+w.length===0){console.log(`
87
93
  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(`
88
- Pulling ${d.length} file(s)...`);let R=await Promise.all(d.map($=>this.remoteLimit(async()=>{try{let _=Un.join(this.options.localDir,$);return await this.downloadFile($,_),$}catch(_){return this.hasError=!0,console.error(`Error downloading ${$}:`,_),null}})));this.pulledFiles.push(...R.filter($=>$!==null))}if(f.length>0){console.log(`
89
- Pushing ${f.length} file(s)...`);let R=new Map;for(let F of f){let it=o.get(F);it&&R.set(F,it)}let $=new Set;for(let F of R.keys()){let it=a?.files[F]!==void 0,vc=i.has(F);!it&&!vc&&$.add(F)}let _=await this.uploadFilesAtomic(R,$);if(_.error){this.hasError=!0,console.error(_.error.message);for(let F of _.error.perFile)console.error(` ${F.path}: ${F.title}`)}else this.pushedFiles.push(..._.succeeded)}if(p.length>0){console.log(`
90
- Deleting ${p.length} remote file(s)...`);let R=await Promise.all(p.map($=>this.remoteLimit(async()=>{try{return await this.deleteFile($),$}catch(_){return this.hasError=!0,console.error(`Error deleting remote ${$}:`,_),null}})));this.remoteDeletedFiles.push(...R.filter($=>$!==null))}if(E.length>0){console.log(`
91
- Deleting ${E.length} local file(s)...`);let R=await Promise.all(E.map(async $=>{try{let _=o.get($);return _?(await this.deleteLocalFile(_),$):null}catch(_){return this.hasError=!0,console.error(`Error deleting local ${$}:`,_),null}}));this.localDeletedFiles.push(...R.filter($=>$!==null))}if(!this.options.dryRun&&!this.hasError){let R=new Map;if(a)for(let[_,F]of Object.entries(a.files))R.set(_,F);for(let[_,F]of l)R.set(_,F);for(let _ of this.pushedFiles){let F=o.get(_);F&&R.set(_,await me(F))}for(let _ of this.pulledFiles){let F=Un.join(this.options.localDir,_);R.set(_,await me(F))}for(let _ of this.remoteDeletedFiles)R.delete(_);for(let _ of this.localDeletedFiles)R.delete(_);let $=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{$=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(R,$)}if(!this.options.dryRun){let R=[...this.pushedFiles.map($=>({file:$,status:"modified"})),...this.pulledFiles.map($=>({file:$,status:"modified"})),...this.remoteDeletedFiles.map($=>({file:$,status:"deleted"})),...this.localDeletedFiles.map($=>({file:$,status:"deleted"}))];if(R.length>0){let _=await new U(this.options.localDir).createCheckpoint("local",R);if(_){let F=_.isMajor?"[MAJOR]":"[minor]";console.log(`
92
- Checkpoint created: ${_.shortHash} ${F} ${_.message}`)}}}console.log(`
93
- 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 Me(this.options.localDir,i)}};function Wl(r){r.command("sync").description("Bidirectional sync between a local directory and a Boxel realm").argument("<local-dir>","The local directory to sync").argument("<realm-url>","The URL of the target realm (e.g., https://app.boxel.ai/demo/)").option("--prefer-local","Resolve conflicts by keeping local version").option("--prefer-remote","Resolve conflicts by keeping remote version").option("--prefer-newest","Resolve conflicts by keeping newest version").option("--delete","Sync deletions both ways").option("--dry-run","Preview without making changes").option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await ge(n.realmSecretSeed===!0),s=await ky(e,t,{preferLocal:n.preferLocal,preferRemote:n.preferRemote,preferNewest:n.preferNewest,delete:n.delete,dryRun:n.dryRun,realmSecretSeed:i}),o=Array.isArray(s.pushed)&&s.pushed.length>0||Array.isArray(s.pulled)&&s.pulled.length>0||Array.isArray(s.remoteDeleted)&&s.remoteDeleted.length>0||Array.isArray(s.localDeleted)&&s.localDeleted.length>0;s.error&&(console.error(`Error: ${s.error}`),process.exit(o?2:1)),console.log("Sync completed successfully")})}async function ky(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 Dn({error:o.error});n=o.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return Dn({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await tr(r))return Dn({error:`Local directory does not exist: ${r}`});let s;try{s=new jn({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?Cy(s):void 0}}function Cy(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 Dn(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var Bl=P(ct());function Ay(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new Bl.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Ty(r,e={}){let t=e.timeoutMs??3e4;if(!Number.isFinite(t)||t<0)return{ready:!1,error:`Invalid timeoutMs: must be a finite, non-negative number (got ${e.timeoutMs}).`};let n=e.profileManager??O();if(!n.getActiveProfile())return{ready:!1,error:N};let s=`${C(r)}_readiness-check`,o=Date.now();for(;Date.now()-o<t;){try{if((await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-o);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${s}`}}function Yl(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)",Ay).action(async e=>{let t;try{t=await Ty(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${g}Error:${m} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${S}Realm is ready.${m}`):(console.error(`${g}Error:${m} ${t.error??"Realm not ready"}`),process.exit(1))})}var Xn=P(ct()),nc=P(require("fs/promises")),et=P(require("path"));var Ee=P(require("fs/promises")),Xl=P(require("path")),Py=".boxel-watch.lock";function qn(r){return Xl.join(r,Py)}function Vn(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function Ly(r){try{let e=await Ee.readFile(qn(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 zl(r,e){await Ee.mkdir(r,{recursive:!0});let t=await Ly(r),n=!1;if(t&&Vn(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Ee.writeFile(qn(r),JSON.stringify(i,null,2)+`
94
- `),{ok:!0,staleOverwrote:n}}async function rr(r){try{await Ee.unlink(qn(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var we=P(require("fs/promises")),Jl=P(require("os")),Gn=P(require("path"));function Kl(){return Gn.join(Jl.homedir(),".boxel-cli")}function Ql(){return Gn.join(Kl(),"watch-processes.json")}async function Zl(){try{let r=await we.readFile(Ql(),"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 Hn(r){await we.mkdir(Kl(),{recursive:!0});let e=Ql(),t=`${e}.${process.pid}.tmp`;await we.writeFile(t,JSON.stringify(r,null,2)+`
95
- `),await we.rename(t,e)}async function ec(){let r=await Zl(),e=r.processes.filter(t=>Vn(t.pid));return e.length!==r.processes.length&&await Hn({processes:e}),{processes:e}}async function tc(r){let t=(await ec()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await Hn({processes:t})}async function rc(){let r=await Zl(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await Hn({processes:e})}async function Wn(){return(await ec()).processes}var Bn=class extends le{name;debounceMs;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.checkpointManager=new U(e.localDir),this.name=Fy(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 _e(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:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[];for(let[o,a]of e)if(a.status==="deleted"){let l=et.join(this.options.localDir,o);try{await nc.unlink(l)}catch(u){if(u.code!=="ENOENT")throw u}n.push(o),i.push({file:o,status:"deleted"})}else{let l=et.join(this.options.localDir,o);await this.downloadFile(o,l),t.push(o),i.push({file:o,status:a.status})}for(let[o,a]of e)a.status==="deleted"?this.lastKnownMtimes.delete(o):this.lastKnownMtimes.set(o,a.mtime);await this.persistManifest(t,n);let s=await this.checkpointManager.createCheckpoint("remote",i);return{pulled:t,deleted:n,checkpoint:s}}scheduleFlush(e){this.isShutdown||(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{this.debounceTimer=null;try{let t=await this.flushPending();e?.(t)}catch(t){console.error(`${g}[${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 _e(this.options.localDir),i=n?.files?{...n.files}:{};for(let a of t)delete i[a];for(let a of e){let l=et.join(this.options.localDir,a);try{i[a]=await me(l)}catch(u){if(u.code!=="ENOENT")throw u}}let s={};for(let[a,l]of this.lastKnownMtimes)l!==0&&(s[a]=l);let o={realmUrl:this.normalizedRealmUrl,files:i};Object.keys(s).length>0&&(o.remoteMtimes=s),await Me(this.options.localDir,o)}};async function Iy(r,e={}){if(r.length===0)return{watchers:[],error:"No realms provided to watch."};let t=e.intervalMs??3e4,n=e.debounceMs??5e3,i=e.quiet??!1;if(!Number.isFinite(t)||t<=0)return{watchers:[],error:"`intervalMs` must be a positive number."};if(!Number.isFinite(n)||n<0)return{watchers:[],error:"`debounceMs` must be a non-negative number."};let s;if(e.authenticator)s=e.authenticator;else{let d=ye({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!d.ok)return{watchers:[],error:d.error};s=d.authenticator}let o=[];for(let d of r){let p=await zl(d.localDir,d.realmUrl);if(!p.ok){for(let E of o)await rr(E);return{watchers:[],error:Ny(d.localDir,p.existing)}}p.staleOverwrote&&!i&&console.log(`${y}[${Yn()}] overwrote stale lock at ${d.localDir}${m}`),o.push(d.localDir)}let a=[];for(let d of r){let p=new Bn(d,s,{debounceMs:n});try{await p.initialize()}catch(E){for(let x of a)x.shutdown();for(let x of o)await rr(x);return{watchers:[],error:`Failed to initialize watch on ${d.realmUrl}: ${E instanceof Error?E.message:String(E)}`}}a.push(p)}if(!i){console.log(`${k}\u21C5 Watching ${a.length} realm${a.length>1?"s":""}:${m}`);for(let d of a)console.log(` ${d.name} ${y}\u2192${m} ${d.localDir}`);console.log(` ${y}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${m}`),console.log(` ${y}Press Ctrl+C to stop${m}
96
- `)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${y}[${Yn()}]${m} [${d.name}] ${T}\u26A1 ${d.pendingCount} change(s) detected${m}`),d.scheduleFlush(E=>{i||My(d.name,E)}))}catch(p){console.error(`${g}[${d.name}] poll error:${m}`,p instanceof Error?p.message:p)}}))},u=!1,c=null,f=()=>{u||(c=setTimeout(async()=>{c=null,!u&&(await l(),f())},t))};try{await tc(r.map(d=>d.localDir).join(", "))}catch{}return await l(),f(),await new Promise(d=>{let p=null,E=null,x=async()=>{if(!u){u=!0,c!==null&&(clearTimeout(c),c=null);for(let K of a)K.shutdown();p&&process.off("SIGINT",p),E&&process.off("SIGTERM",E);for(let K of o)try{await rr(K)}catch{}try{await rc()}catch{}d()}};if(e.signal){if(e.signal.aborted){x();return}e.signal.addEventListener("abort",()=>void x(),{once:!0})}else p=()=>{i||console.log(`
97
- ${k}\u21C5 Watch stopped${m}`),x()},E=p,process.on("SIGINT",p),process.on("SIGTERM",E)}),{watchers:a}}function Ny(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 ${et.join(r,".boxel-watch.lock")} if it's stale.`}function My(r,e){let t=e.pulled.length+e.deleted.length;if(t!==0&&(console.log(`${y}[${Yn()}]${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(` ${y}Checkpoint:${m} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}}function Fy(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function Yn(){return new Date().toLocaleTimeString()}function Dy(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new Xn.InvalidArgumentError(`${r} must be a positive number.`);return t}}function Uy(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new Xn.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function ic(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",Dy("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",Uy("--debounce"),5).option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await ge(n.realmSecretSeed===!0),s=await Iy([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i});s.error&&(console.error(`${g}Error:${m} ${s.error}`),process.exit(1))})}var zn=require("child_process");var jy=200;function qy(r){return new Promise(e=>setTimeout(e,r))}function sc(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,zn.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 Vy(){if(process.platform==="win32")return[];let r;try{r=(0,zn.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(`
98
- `)){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 Gy(){let r=[],e=[],t=new Set,n=await Wn();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let s=sc(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}for(let i of Vy()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let s=sc(i.pid),o={pid:i.pid,workspace:i.workspace};s.ok?r.push(o):e.push(o)}return r.length>0&&(await qy(jy),await Wn()),{stopped:r,failed:e}}function Hy(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(` ${y}\u21C5${m} Stopped: boxel realm watch ${e.workspace} (PID ${e.pid})`);for(let e of r.failed)console.log(` ${g}\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(`
99
- ${S}\u2713 Stopped ${r.stopped.length} process${e}${m}`)}}function oc(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await Gy();Hy(e)})}function ac(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");ic(e),oc(e)}function lc(r){let e=r.command("realm").description("Manage realms on the realm server");ll(e),ml(e),Cl(e),Al(e),Pl(e),Ml(e),Dl(e),jl(e),Wl(e),Yl(e),ac(e)}async function Wy(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:N};if(D(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!o.ok){let a=await o.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${o.status}: ${a.slice(0,300)}`}}return{ok:!0}}function cc(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 Wy(t.realm,e)}catch(i){console.error(`${g}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?console.log(`${y}Deleted:${m} ${e}`):console.error(`${g}Error:${m} ${n.error}`),n.ok||process.exit(1)})}async function Jn(r,e){let t=e?.profileManager??O();if(!t.getActiveProfile())return{filenames:[],error:N};let i=C(r),s=`${i}_mtimes`;try{let o=await t.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!o.ok){let c=await o.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${o.status}: ${c.slice(0,300)}`}}let a=await o.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let f=c.slice(i.length);!f||f.endsWith("/")||u.push(f)}return{filenames:u.sort()}}catch(o){return{filenames:[],error:o instanceof Error?o.message:String(o)}}}function uc(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 Jn(e.realm)}catch(n){console.error(`${g}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(`${g}Error:${m} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${y}${n}${m}`);console.log(`
100
- ${y}${t.filenames.length} file(s)${m}`)}})}var nr=require("fs");var fc=require("fs");async function rt(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:N};let o=new URL(e,C(r)).href;try{let a=await i.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/vnd.card+source","Content-Type":"application/vnd.card+source"},body:t});if(!a.ok){let l=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${l.slice(0,300)}`}}return{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function tt(r){process.stderr.write(r+`
101
- `)}async function By(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function mc(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,fc.readFileSync)(t.file,"utf-8")}catch(s){tt(`${g}Error:${m} Could not read file: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}else process.stdin.isTTY&&tt(`${y}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${m}`),n=await By(),tt(`${y}Received ${n.length} bytes. Writing to realm...${m}`);let i;try{i=await rt(t.realm,e,n)}catch(s){tt(`${g}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} ${y}\u2192${m} ${t.realm}`):tt(`${g}Error:${m} ${i.error}`),i.ok||process.exit(1)})}async function Yy(r,e,t,n){let i=n?.profileManager??O();if(!i.getActiveProfile())return{ok:!1,error:N};let o=`${C(r)}_lint`;try{let a=await i.authedRealmFetch(o,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/vnd.card+source","X-Filename":t,"X-HTTP-Method-Override":"QUERY"},body:e});if(!a.ok){let u=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${u.slice(0,300)}`}}let l=await a.json();return{ok:!0,fixed:l.fixed,output:l.output,messages:l.messages}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function dc(r){r.command("lint").description("Lint a file in a realm using the realm lint endpoint").argument("<path>","Realm-relative file path to lint (e.g., my-card.gts)").requiredOption("--realm <realm-url>","The realm URL to lint against").option("--file <local-filepath>","Read source from a local file instead of fetching from the realm").option("--json","Output raw JSON response").option("--fix","Write auto-fixed output back to the source").action(async(e,t)=>{let n=O();n.getActiveProfile()||(console.error(`${g}Error:${m} ${N}`),process.exit(1));let s;if(t.file)try{s=(0,nr.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${g}Error:${m} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,C(t.realm)).href;try{let f=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!f.ok){let d=await f.text().catch(()=>"(no body)");console.error(`${g}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(`${g}Error:${m} ${f instanceof Error?f.message:String(f)}`),process.exit(1)}}let o;try{o=await Yy(t.realm,s,e,{profileManager:n})}catch(c){console.error(`${g}Error:${m} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){M.output(JSON.stringify(o,null,2)),o.ok||process.exit(1);return}if(o.ok||(console.error(`${g}Error:${m} ${o.error}`),process.exit(1)),t.fix&&o.fixed&&o.output)if(t.file)(0,nr.writeFileSync)(t.file,o.output,"utf-8"),console.log(`${S}Fixed:${m} ${t.file}`);else{let c=await rt(t.realm,e,o.output,{profileManager:n});c.ok||(console.error(`${g}Error:${m} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${S}Fixed:${m} ${e} ${y}\u2192${m} ${t.realm}`)}let a=o.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${y}No lint issues found.${m}`);return}for(let c of a){let f=c.severity===2?g:T,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${f}${d}${m} ${c.line}:${c.column} ${c.message}${y}${p}${m}`)}console.log(`
102
- ${y}${l.length} error(s), ${u.length} warning(s)${m}`),l.length>0&&process.exit(1)})}async function Kn(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,error:N};let s=new URL(e,C(r)).href,o;try{o=await n.authedRealmFetch(s,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!o.ok){let l=await o.text().catch(()=>"(no body)");return{ok:!1,status:o.status,error:`HTTP ${o.status}: ${l.slice(0,300)}`}}let a=await o.text();return{ok:!0,status:o.status,content:a}}function pc(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 Kn(t.realm,e)}catch(i){console.error(`${g}Error:${m} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?M.output(JSON.stringify(n,null,2)):n.ok?M.output(n.content??""):(console.error(`${y}Status:${m} ${n.status??"(no status)"}`),console.error(`${g}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}var Qn="// touched for re-index";async function Xy(r,e,t){let n=t?.profileManager??O();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:N};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 Jn(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};s=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!D(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};s=e}let o=[],a=[];for(let l of s){if(!l.endsWith(".json")&&!l.endsWith(".gts")){a.push({path:l,reason:"unsupported extension"});continue}if(D(l)){a.push({path:l,reason:"protected file"});continue}let u=await Kn(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){o.push(l);continue}let c=l.endsWith(".json")?zy(u.content):Ky(u.content),f=await rt(r,l,c,{profileManager:n});if(!f.ok){a.push({path:l,reason:f.error??"write failed"});continue}o.push(l)}return{ok:a.length===0,touched:o,skipped:a}}function zy(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)+`
103
- `}catch{}return Jy(r)}function Jy(r){return r.endsWith(`
94
+ Pulling ${d.length} file(s)...`);let b=await Promise.all(d.map(R=>this.remoteLimit(async()=>{try{let k=Qn.join(this.options.localDir,R);return await this.downloadFile(R,k),R}catch(k){return this.hasError=!0,console.error(`Error downloading ${R}:`,k),null}})));this.pulledFiles.push(...b.filter(R=>R!==null))}if(m.length>0){console.log(`
95
+ Pushing ${m.length} file(s)...`);let b=new Map;for(let F of m){let mt=s.get(F);mt&&b.set(F,mt)}let R=new Set;for(let F of b.keys()){let mt=a?.files[F]!==void 0,Vc=i.has(F);!mt&&!Vc&&R.add(F)}let k=await this.uploadFilesAtomic(b,R);if(k.error){this.hasError=!0,console.error(k.error.message);for(let F of k.error.perFile)console.error(` ${F.path}: ${F.title}`)}else this.pushedFiles.push(...k.succeeded)}if(p.length>0){console.log(`
96
+ Deleting ${p.length} remote file(s)...`);let b=await Promise.all(p.map(R=>this.remoteLimit(async()=>{try{return await this.deleteFile(R),R}catch(k){return this.hasError=!0,console.error(`Error deleting remote ${R}:`,k),null}})));this.remoteDeletedFiles.push(...b.filter(R=>R!==null))}if(w.length>0){console.log(`
97
+ Deleting ${w.length} local file(s)...`);let b=await Promise.all(w.map(async R=>{try{let k=s.get(R);return k?(await this.deleteLocalFile(k),R):null}catch(k){return this.hasError=!0,console.error(`Error deleting local ${R}:`,k),null}}));this.localDeletedFiles.push(...b.filter(R=>R!==null))}if(!this.options.dryRun&&!this.hasError){let b=new Map;if(a)for(let[k,F]of Object.entries(a.files))b.set(k,F);for(let[k,F]of l)b.set(k,F);for(let k of this.pushedFiles){let F=s.get(k);F&&b.set(k,await oe(F))}for(let k of this.pulledFiles){let F=Qn.join(this.options.localDir,k);b.set(k,await oe(F))}for(let k of this.remoteDeletedFiles)b.delete(k);for(let k of this.localDeletedFiles)b.delete(k);let R=i;if(this.pushedFiles.length>0||this.remoteDeletedFiles.length>0)try{R=await this.getRemoteMtimes()}catch{console.warn("Could not refresh remote mtimes after sync")}await this.writeManifest(b,R)}if(!this.options.dryRun){let b=[...this.pushedFiles.map(R=>({file:R,status:"modified"})),...this.pulledFiles.map(R=>({file:R,status:"modified"})),...this.remoteDeletedFiles.map(R=>({file:R,status:"deleted"})),...this.localDeletedFiles.map(R=>({file:R,status:"deleted"}))];if(b.length>0){let k=await new U(this.options.localDir).createCheckpoint("local",b);if(k){let F=k.isMajor?"[MAJOR]":"[minor]";console.log(`
98
+ Checkpoint created: ${k.shortHash} ${F} ${k.message}`)}}}console.log(`
99
+ Sync completed`)}async writeManifest(t,n){let i={realmUrl:this.normalizedRealmUrl,files:{},remoteMtimes:{}};for(let[o,s]of t){i.files[o]=s;let a=n.get(o);a!==void 0&&a!==0&&(i.remoteMtimes[o]=a)}i.remoteMtimes&&Object.keys(i.remoteMtimes).length===0&&delete i.remoteMtimes,await Re(this.options.localDir,i)}};function fc(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 o=await me(i.realmSecretSeed===!0),s=await Ew(t,n,{preferLocal:i.preferLocal,preferRemote:i.preferRemote,preferNewest:i.preferNewest,delete:i.delete,dryRun:i.dryRun,realmSecretSeed:o}),a=Array.isArray(s.pushed)&&s.pushed.length>0||Array.isArray(s.pulled)&&s.pulled.length>0||Array.isArray(s.remoteDeleted)&&s.remoteDeleted.length>0||Array.isArray(s.localDeleted)&&s.localDeleted.length>0;s.error&&(console.error(`Error: ${s.error}`),process.exit(a?2:1)),console.log("Sync completed successfully")})}async function Ew(r,e,t){let n;if(t.authenticator)n=t.authenticator;else{let s=de({realmUrl:e,realmSecretSeed:t.realmSecretSeed,profileManager:t.profileManager});if(!s.ok)return Kn({error:s.error});n=s.authenticator}if([t.preferLocal,t.preferRemote,t.preferNewest].filter(Boolean).length>1)return Kn({error:"Only one conflict strategy can be specified (--prefer-local, --prefer-remote, or --prefer-newest)."});if(!await Ge(r))return Kn({error:`Local directory does not exist: ${r}`});let o;try{o=new Zn({realmUrl:e,localDir:r,preferLocal:t.preferLocal,preferRemote:t.preferRemote,preferNewest:t.preferNewest,deleteSync:t.delete,dryRun:t.dryRun,waitForIndex:t.waitForIndex},n),await o.sync()}catch(s){return{pushed:o?.pushedFiles.slice().sort()??[],pulled:o?.pulledFiles.slice().sort()??[],remoteDeleted:o?.remoteDeletedFiles.slice().sort()??[],localDeleted:o?.localDeletedFiles.slice().sort()??[],skippedConflicts:o?.skippedConflicts.slice().sort()??[],hasError:!0,error:`Sync failed: ${s instanceof Error?s.message:String(s)}`}}return{pushed:o.pushedFiles.slice().sort(),pulled:o.pulledFiles.slice().sort(),remoteDeleted:o.remoteDeletedFiles.slice().sort(),localDeleted:o.localDeletedFiles.slice().sort(),skippedConflicts:o.skippedConflicts.slice().sort(),hasError:o.hasError,error:o.hasError?$w(o):void 0}}function $w(r){return`Sync completed with errors. ${[`${r.pushedFiles.length} pushed`,`${r.pulledFiles.length} pulled`,`${r.remoteDeletedFiles.length} remote deleted`,`${r.localDeletedFiles.length} local deleted`,`${r.skippedConflicts.length} conflicts skipped`].join(", ")}.`}function Kn(r){return{pushed:[],pulled:[],remoteDeleted:[],localDeleted:[],skippedConflicts:[],hasError:!0,...r}}var mc=O(yt());function bw(r){let e=Number.parseInt(r,10);if(!Number.isFinite(e)||e<0||String(e)!==r.trim())throw new mc.InvalidArgumentError("--timeout must be a non-negative integer (milliseconds).");return e}async function Rw(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??A();if(!n.getActiveProfile())return{ready:!1,error:M};let o=`${P(r)}_readiness-check`,s=Date.now();for(;Date.now()-s<t;){try{if((await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}})).ok)return{ready:!0}}catch{}let a=t-(Date.now()-s);if(a<=0)break;await new Promise(l=>setTimeout(l,Math.min(1e3,a)))}return{ready:!1,error:`Realm not ready after ${t}ms: ${o}`}}function dc(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)",bw).action(async e=>{let t;try{t=await Rw(e.realm,{timeoutMs:e.timeout})}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}t.ready?console.log(`${S}Realm is ready.${f}`):(console.error(`${h}Error:${f} ${t.error??"Realm not ready"}`),process.exit(1))})}var ai=O(yt()),Sc=O(require("fs/promises")),lt=O(require("path"));var Se=O(require("fs/promises")),pc=O(require("path")),Sw=".boxel-watch.lock";function ei(r){return pc.join(r,Sw)}function ti(r){try{return process.kill(r,0),!0}catch(e){return e?.code==="EPERM"}}async function vw(r){try{let e=await Se.readFile(ei(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 hc(r,e){await Se.mkdir(r,{recursive:!0});let t=await vw(r),n=!1;if(t&&ti(t.pid))return{ok:!1,existing:t};t&&(n=!0);let i={pid:process.pid,startedAt:new Date().toISOString(),realmUrl:e};return await Se.writeFile(ei(r),JSON.stringify(i,null,2)+`
100
+ `),{ok:!0,staleOverwrote:n}}async function fr(r){try{await Se.unlink(ei(r))}catch(e){if(e?.code!=="ENOENT")throw e}}var ve=O(require("fs/promises")),gc=O(require("os")),ri=O(require("path"));function yc(){return ri.join(gc.homedir(),".boxel-cli")}function wc(){return ri.join(yc(),"watch-processes.json")}async function Ec(){try{let r=await ve.readFile(wc(),"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 ni(r){await ve.mkdir(yc(),{recursive:!0});let e=wc(),t=`${e}.${process.pid}.tmp`;await ve.writeFile(t,JSON.stringify(r,null,2)+`
101
+ `),await ve.rename(t,e)}async function $c(){let r=await Ec(),e=r.processes.filter(t=>ti(t.pid));return e.length!==r.processes.length&&await ni({processes:e}),{processes:e}}async function bc(r){let t=(await $c()).processes.filter(n=>n.pid!==process.pid);t.push({pid:process.pid,workspace:r,startedAt:new Date().toISOString()}),await ni({processes:t})}async function Rc(){let r=await Ec(),e=r.processes.filter(t=>t.pid!==process.pid);e.length!==r.processes.length&&await ni({processes:e})}async function ii(){return(await $c()).processes}var oi=class extends ie{name;debounceMs;checkpointManager;lastKnownMtimes=new Map;pendingChanges=new Map;debounceTimer=null;isShutdown=!1;constructor(e,t,n){super({realmUrl:e.realmUrl,localDir:e.localDir},t),this.debounceMs=n.debounceMs,this.checkpointManager=new U(e.localDir),this.name=Ow(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[o,s]of Object.entries(n.data?.attributes?.mtimes??{}))i.set(o.replace(this.normalizedRealmUrl,""),s);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 ye(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 o=this.lastKnownMtimes.get(n);o===void 0?this.recordPending(n,{status:"added",mtime:i})&&(t=!0):i>o&&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:[],checkpoint:null};let e=new Map(this.pendingChanges);this.pendingChanges.clear();let t=[],n=[],i=[];for(let[s,a]of e)if(a.status==="deleted"){let l=lt.join(this.options.localDir,s);try{await Sc.unlink(l)}catch(u){if(u.code!=="ENOENT")throw u}n.push(s),i.push({file:s,status:"deleted"})}else{let l=lt.join(this.options.localDir,s);await this.downloadFile(s,l),t.push(s),i.push({file:s,status:a.status})}for(let[s,a]of e)a.status==="deleted"?this.lastKnownMtimes.delete(s):this.lastKnownMtimes.set(s,a.mtime);await this.persistManifest(t,n);let o=await this.checkpointManager.createCheckpoint("remote",i);return{pulled:t,deleted:n,checkpoint: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:${f}`,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 ye(this.options.localDir),i=n?.files?{...n.files}:{};for(let a of t)delete i[a];for(let a of e){let l=lt.join(this.options.localDir,a);try{i[a]=await oe(l)}catch(u){if(u.code!=="ENOENT")throw u}}let o={};for(let[a,l]of this.lastKnownMtimes)l!==0&&(o[a]=l);let s={realmUrl:this.normalizedRealmUrl,files:i};Object.keys(o).length>0&&(s.remoteMtimes=o),await Re(this.options.localDir,s)}};async function xw(r,e={}){if(r.length===0)return{watchers:[],error:"No realms provided to watch."};let t=e.intervalMs??3e4,n=e.debounceMs??5e3,i=e.quiet??!1;if(!Number.isFinite(t)||t<=0)return{watchers:[],error:"`intervalMs` must be a positive number."};if(!Number.isFinite(n)||n<0)return{watchers:[],error:"`debounceMs` must be a non-negative number."};let o;if(e.authenticator)o=e.authenticator;else{let d=de({realmUrl:r[0].realmUrl,realmSecretSeed:e.realmSecretSeed,profileManager:e.profileManager});if(!d.ok)return{watchers:[],error:d.error};o=d.authenticator}let s=[];for(let d of r){let p=await hc(d.localDir,d.realmUrl);if(!p.ok){for(let w of s)await fr(w);return{watchers:[],error:_w(d.localDir,p.existing)}}p.staleOverwrote&&!i&&console.log(`${y}[${si()}] overwrote stale lock at ${d.localDir}${f}`),s.push(d.localDir)}let a=[];for(let d of r){let p=new oi(d,o,{debounceMs:n});try{await p.initialize()}catch(w){for(let x of a)x.shutdown();for(let x of s)await fr(x);return{watchers:[],error:`Failed to initialize watch on ${d.realmUrl}: ${w instanceof Error?w.message:String(w)}`}}a.push(p)}if(!i){console.log(`${_}\u21C5 Watching ${a.length} realm${a.length>1?"s":""}:${f}`);for(let d of a)console.log(` ${d.name} ${y}\u2192${f} ${d.localDir}`);console.log(` ${y}Interval: ${t/1e3}s, Debounce: ${n/1e3}s${f}`),console.log(` ${y}Press Ctrl+C to stop${f}
102
+ `)}let l=async()=>{await Promise.all(a.map(async d=>{try{await d.poll()&&(i||console.log(`${y}[${si()}]${f} [${d.name}] ${C}\u26A1 ${d.pendingCount} change(s) detected${f}`),d.scheduleFlush(w=>{i||kw(d.name,w)}))}catch(p){console.error(`${h}[${d.name}] poll error:${f}`,p instanceof Error?p.message:p)}}))},u=!1,c=null,m=()=>{u||(c=setTimeout(async()=>{c=null,!u&&(await l(),m())},t))};try{await bc(r.map(d=>d.localDir).join(", "))}catch{}return await l(),m(),await new Promise(d=>{let p=null,w=null,x=async()=>{if(!u){u=!0,c!==null&&(clearTimeout(c),c=null);for(let Q of a)Q.shutdown();p&&process.off("SIGINT",p),w&&process.off("SIGTERM",w);for(let Q of s)try{await fr(Q)}catch{}try{await Rc()}catch{}d()}};if(e.signal){if(e.signal.aborted){x();return}e.signal.addEventListener("abort",()=>void x(),{once:!0})}else p=()=>{i||console.log(`
103
+ ${_}\u21C5 Watch stopped${f}`),x()},w=p,process.on("SIGINT",p),process.on("SIGTERM",w)}),{watchers:a}}function _w(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 ${lt.join(r,".boxel-watch.lock")} if it's stale.`}function kw(r,e){let t=e.pulled.length+e.deleted.length;if(t!==0&&(console.log(`${y}[${si()}]${f} [${r}] ${S}applied ${t} change(s)${f} (${e.pulled.length} pulled, ${e.deleted.length} deleted)`),e.checkpoint)){let n=e.checkpoint.isMajor?"[MAJOR]":"[minor]";console.log(` ${y}Checkpoint:${f} ${e.checkpoint.shortHash} ${n} ${e.checkpoint.message}`)}}function Ow(r){return r.replace(/\/$/,"").split("/").slice(-2).join("/")}function si(){return new Date().toLocaleTimeString()}function Cw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<=0)throw new ai.InvalidArgumentError(`${r} must be a positive number.`);return t}}function Aw(r){return e=>{let t=Number.parseFloat(e);if(!Number.isFinite(t)||t<0)throw new ai.InvalidArgumentError(`${r} must be a non-negative number.`);return t}}function vc(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",Cw("--interval"),30).option("-d, --debounce <seconds>","Seconds to wait after a burst of changes before applying them",Aw("--debounce"),5).option("--realm-secret-seed","Administrative auth: prompt for a realm secret seed and mint a JWT locally instead of using a Matrix profile (env: BOXEL_REALM_SECRET_SEED)").action(async(e,t,n)=>{let i=await me(n.realmSecretSeed===!0),o=await xw([{realmUrl:e,localDir:t}],{intervalMs:n.interval*1e3,debounceMs:n.debounce*1e3,realmSecretSeed:i});o.error&&(console.error(`${h}Error:${f} ${o.error}`),process.exit(1))})}var li=require("child_process");var Pw=200;function Tw(r){return new Promise(e=>setTimeout(e,r))}function xc(r){try{if(process.platform==="win32")try{process.kill(r)}catch{(0,li.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 Lw(){if(process.platform==="win32")return[];let r;try{r=(0,li.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(`
104
+ `)){if(!n)continue;let i=n.trim().split(/\s+/),o=Number.parseInt(i[1]??"",10);if(!Number.isFinite(o)||t.has(o))continue;t.add(o);let s=".",a=n.match(/\bstart\s+\S+\s+(\S+)/);a&&a[1]&&!a[1].startsWith("-")&&(s=a[1]),e.push({pid:o,workspace:s})}return e}async function Iw(){let r=[],e=[],t=new Set,n=await ii();for(let i of n){if(i.pid===process.pid)continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}for(let i of Lw()){if(i.pid===process.pid||t.has(i.pid))continue;t.add(i.pid);let o=xc(i.pid),s={pid:i.pid,workspace:i.workspace};o.ok?r.push(s):e.push(s)}return r.length>0&&(await Tw(Pw),await ii()),{stopped:r,failed:e}}function Mw(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(` ${y}\u21C5${f} Stopped: boxel realm watch ${e.workspace} (PID ${e.pid})`);for(let e of r.failed)console.log(` ${h}\xD7${f} 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(`
105
+ ${S}\u2713 Stopped ${r.stopped.length} process${e}${f}`)}}function _c(r){r.command("stop").description("Stop all running boxel realm watch processes").action(async()=>{let e=await Iw();Mw(e)})}function kc(r){let e=r.command("watch").description("Watch a Boxel realm; subcommands manage watch processes");vc(e),_c(e)}function Oc(r){let e=r.command("realm").description("Manage realms on the realm server");Ol(e),Tl(e),zl(e),Jl(e),Ql(e),rc(e),ic(e),sc(e);let t=fc(e);uc(t),dc(e),kc(e)}async function Nw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};if(D(e))return{ok:!1,error:`Cannot delete protected file: ${e}`};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"DELETE",headers:{Accept:"application/vnd.card+source"}})}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}if(!s.ok){let a=await s.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${s.status}: ${a.slice(0,300)}`}}return{ok:!0}}function Cc(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 Nw(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?console.log(`${y}Deleted:${f} ${e}`):console.error(`${h}Error:${f} ${n.error}`),n.ok||process.exit(1)})}async function ci(r,e){let t=e?.profileManager??A();if(!t.getActiveProfile())return{filenames:[],error:M};let i=P(r),o=`${i}_mtimes`;try{let s=await t.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.api+json"}});if(!s.ok){let c=await s.text().catch(()=>"(no body)");return{filenames:[],error:`_mtimes returned HTTP ${s.status}: ${c.slice(0,300)}`}}let a=await s.json(),l=a?.data?.attributes?.mtimes??a,u=[];for(let c of Object.keys(l)){if(!c.startsWith(i))continue;let m=c.slice(i.length);!m||m.endsWith("/")||u.push(m)}return{filenames:u.sort()}}catch(s){return{filenames:[],error:s instanceof Error?s.message:String(s)}}}function Ac(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 ci(e.realm)}catch(n){console.error(`${h}Error:${f} ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(e.json)N.output(JSON.stringify(t,null,2)),t.error&&process.exit(1);else if(t.error)console.error(`${h}Error:${f} ${t.error}`),process.exit(1);else{for(let n of t.filenames)console.log(`${y}${n}${f}`);console.log(`
106
+ ${y}${t.filenames.length} file(s)${f}`)}})}var mr=require("fs");var Pc=require("fs");async function ut(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=new URL(e,P(r)).href;try{let a=await i.authedRealmFetch(s,{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 ct(r){process.stderr.write(r+`
107
+ `)}async function Dw(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}function Tc(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,Pc.readFileSync)(t.file,"utf-8")}catch(o){ct(`${h}Error:${f} Could not read file: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}else process.stdin.isTTY&&ct(`${y}Reading from STDIN. Type or paste content, then press Enter followed by Ctrl+D to finish.${f}`),n=await Dw(),ct(`${y}Received ${n.length} bytes. Writing to realm...${f}`);let i;try{i=await ut(t.realm,e,n)}catch(o){ct(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}t.json?N.output(JSON.stringify(i,null,2)):i.ok?console.log(`${S}Written:${f} ${e} ${y}\u2192${f} ${t.realm}`):ct(`${h}Error:${f} ${i.error}`),i.ok||process.exit(1)})}async function Fw(r,e,t,n){let i=n?.profileManager??A();if(!i.getActiveProfile())return{ok:!1,error:M};let s=`${P(r)}_lint`;try{let a=await i.authedRealmFetch(s,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/vnd.card+source","X-Filename":t,"X-HTTP-Method-Override":"QUERY"},body:e});if(!a.ok){let u=await a.text().catch(()=>"(no body)");return{ok:!1,error:`HTTP ${a.status}: ${u.slice(0,300)}`}}let l=await a.json();return{ok:!0,fixed:l.fixed,output:l.output,messages:l.messages}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}function Lc(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=A();n.getActiveProfile()||(console.error(`${h}Error:${f} ${M}`),process.exit(1));let o;if(t.file)try{o=(0,mr.readFileSync)(t.file,"utf-8")}catch(c){console.error(`${h}Error:${f} Could not read local file: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}else{let c=new URL(e,P(t.realm)).href;try{let m=await n.authedRealmFetch(c,{method:"GET",headers:{Accept:"application/vnd.card+source"}});if(!m.ok){let d=await m.text().catch(()=>"(no body)");console.error(`${h}Error:${f} Could not read file from realm: HTTP ${m.status}: ${d.slice(0,300)}`),process.exit(1)}o=await m.text()}catch(m){console.error(`${h}Error:${f} ${m instanceof Error?m.message:String(m)}`),process.exit(1)}}let s;try{s=await Fw(t.realm,o,e,{profileManager:n})}catch(c){console.error(`${h}Error:${f} ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(t.json){N.output(JSON.stringify(s,null,2)),s.ok||process.exit(1);return}if(s.ok||(console.error(`${h}Error:${f} ${s.error}`),process.exit(1)),t.fix&&s.fixed&&s.output)if(t.file)(0,mr.writeFileSync)(t.file,s.output,"utf-8"),console.log(`${S}Fixed:${f} ${t.file}`);else{let c=await ut(t.realm,e,s.output,{profileManager:n});c.ok||(console.error(`${h}Error:${f} Could not write fixed file: ${c.error}`),process.exit(1)),console.log(`${S}Fixed:${f} ${e} ${y}\u2192${f} ${t.realm}`)}let a=s.messages??[],l=a.filter(c=>c.severity===2),u=a.filter(c=>c.severity===1);if(a.length===0){console.log(`${y}No lint issues found.${f}`);return}for(let c of a){let m=c.severity===2?h:C,d=c.severity===2?"error":"warning",p=c.ruleId?` (${c.ruleId})`:"";console.log(`${m}${d}${f} ${c.line}:${c.column} ${c.message}${y}${p}${f}`)}console.log(`
108
+ ${y}${l.length} error(s), ${u.length} warning(s)${f}`),l.length>0&&process.exit(1)})}async function ui(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,error:M};let o=new URL(e,P(r)).href,s;try{s=await n.authedRealmFetch(o,{method:"GET",headers:{Accept:"application/vnd.card+source"}})}catch(l){return{ok:!1,error:l instanceof Error?l.message:String(l)}}if(!s.ok){let l=await s.text().catch(()=>"(no body)");return{ok:!1,status:s.status,error:`HTTP ${s.status}: ${l.slice(0,300)}`}}let a=await s.text();return{ok:!0,status:s.status,content:a}}function Ic(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 ui(t.realm,e)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1)}t.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(n.content??""):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}var fi="// touched for re-index";async function Uw(r,e,t){let n=t?.profileManager??A();if(!n.getActiveProfile())return{ok:!1,touched:[],skipped:[],error:M};let o;if(t?.all){if(e.length>0)return{ok:!1,touched:[],skipped:[],error:"Cannot pass file paths together with --all"};let l=await ci(r,{profileManager:n});if(l.error)return{ok:!1,touched:[],skipped:[],error:l.error};o=l.filenames.filter(u=>(u.endsWith(".json")||u.endsWith(".gts"))&&!D(u))}else{if(e.length===0)return{ok:!1,touched:[],skipped:[],error:"No file paths provided. Pass paths or use --all."};o=e}let s=[],a=[];for(let l of o){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 u=await ui(r,l,{profileManager:n});if(!u.ok||u.content==null){a.push({path:l,reason:u.error??"read failed"});continue}if(t?.dryRun){s.push(l);continue}let c=l.endsWith(".json")?jw(u.content):Gw(u.content),m=await ut(r,l,c,{profileManager:n});if(!m.ok){a.push({path:l,reason:m.error??"write failed"});continue}s.push(l)}return{ok:a.length===0,touched:s,skipped:a}}function jw(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)+`
109
+ `}catch{}return qw(r)}function qw(r){return r.endsWith(`
104
110
 
105
111
  `)?r.slice(0,-1):r+`
106
- `}function Ky(r){let e=`
107
- ${Qn}
112
+ `}function Gw(r){let e=`
113
+ ${fi}
108
114
  `;return r.endsWith(e)?r.slice(0,-e.length)+`
109
115
  `:r.endsWith(`
110
- `)?r+Qn+`
116
+ `)?r+fi+`
111
117
  `:r+`
112
- `+Qn+`
113
- `}function hc(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 Xy(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${g}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(`${g}Error:${m} ${n.error}`);else{let i=t.dryRun?`${y}[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(`${g}skipped${m} ${o} ${y}(${a})${m}`);let s=t.dryRun?"would touch":"touched";console.log(`
114
- ${y}${s} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${m}`)}n.ok||process.exit(1)})}function gc(r){let e=r.command("file").description("Read, write, and manage files in a realm");cc(e),uc(e),dc(e),pc(e),hc(e),mc(e)}async function Qy(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_run-command`,a={data:{type:"run-command",attributes:{realmURL:e,command:r,commandInput:t?.input??null}}},l;try{l=await n.authedRealmServerFetch(o,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(f){return{status:"error",error:`run-command fetch failed: ${f instanceof Error?f.message:String(f)}`}}if(!l.ok){let f=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${f}`}}let u;try{u=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let c=u.data?.attributes;return{status:c?.status??"error",result:c?.cardResultString??null,error:c?.error??null}}function yc(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(`${g}Error:${m} --input must be a JSON object, got ${Array.isArray(s)?"array":typeof s}`),process.exit(1)),n=s}catch{console.error(`${g}Error:${m} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await Qy(e,t.realm,{input:n})}catch(s){console.error(`${g}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(`${y}Status:${m} ${Zy(i.status)}${i.status}${m}`),i.result){console.log(`${y}Result:${m}`);try{M.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{M.output(i.result)}}i.error&&console.error(`${g}Error:${m} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function Zy(r){switch(r){case"ready":return S;case"error":return g;default:return k}}async function eE(r,e,t){let n=t?.profileManager??O(),i=n.getActiveProfile();if(!i)return{ok:!1,error:N};let o=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(C);try{let l=await n.authedRealmServerFetch(o,{method:"QUERY",headers:{Accept:"application/vnd.card+json","Content-Type":"application/json"},body:JSON.stringify({realms:a,...e})});if(!l.ok){let c=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${c.slice(0,300)}`}}let u=await l.json();return{ok:!0,status:l.status,data:u.data}}catch(l){return{ok:!1,status:0,error:l instanceof Error?l.message:String(l)}}}function 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(`${g}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(`${g}Error:${m} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${g}Error:${m} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await eE(e.realm,t)}catch(i){console.error(`${g}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(`${y}Status:${m} ${n.status??"(no status)"}`),console.error(`${g}Error:${m} ${n.error}`)),n.ok||process.exit(1)})}function bc(r){let e=new wc.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&&Bt(!0)}),e.command("profile").description("Manage saved profiles for different users/environments").argument("[subcommand]","list | add | switch | remove | migrate").argument("[arg]","Profile ID (for switch/remove)").option("-u, --user <matrixId>","Matrix user ID (e.g., @user:boxel.ai)").option("-p, --password <password>","Password (for add command)").option("-n, --name <displayName>","Display name (for add command)").option("-m, --matrix-url <url>","Matrix server URL (for add command with non-standard domains)").option("-r, --realm-server-url <url>","Realm server URL (for add command with non-standard domains)").addHelpText("after",`
118
+ `+fi+`
119
+ `}function Mc(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 Uw(t.realm,e,{all:t.all,dryRun:t.dryRun})}catch(i){console.error(`${h}Error:${f} ${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:${f} ${n.error}`);else{let i=t.dryRun?`${y}[dry-run]${f} `:"";for(let s of n.touched)console.log(`${i}${S}touched${f} ${s}`);for(let{path:s,reason:a}of n.skipped)console.log(`${h}skipped${f} ${s} ${y}(${a})${f}`);let o=t.dryRun?"would touch":"touched";console.log(`
120
+ ${y}${o} ${n.touched.length} file(s)${n.skipped.length>0?`, skipped ${n.skipped.length}`:""}${f}`)}n.ok||process.exit(1)})}function Nc(r){let e=r.command("file").description("Read, write, and manage files in a realm");Cc(e),Ac(e),Lc(e),Ic(e),Mc(e),Tc(e)}async function Vw(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)throw new Error("No active profile. Run `boxel profile add` to create one.");let s=`${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(s,{method:"POST",headers:{"Content-Type":"application/vnd.api+json",Accept:"application/vnd.api+json"},body:JSON.stringify(a)})}catch(m){return{status:"error",error:`run-command fetch failed: ${m instanceof Error?m.message:String(m)}`}}if(!l.ok){let m=await l.text().catch(()=>"(no body)");return{status:"error",error:`run-command HTTP ${l.status}: ${m}`}}let u;try{u=await l.json()}catch{return{status:"error",error:`run-command response was not valid JSON (HTTP ${l.status})`}}let c=u.data?.attributes;return{status:c?.status??"error",result:c?.cardResultString??null,error:c?.error??null}}function Dc(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 o=JSON.parse(t.input);(typeof o!="object"||o===null||Array.isArray(o))&&(console.error(`${h}Error:${f} --input must be a JSON object, got ${Array.isArray(o)?"array":typeof o}`),process.exit(1)),n=o}catch{console.error(`${h}Error:${f} --input is not valid JSON: ${t.input}`),process.exit(1)}let i;try{i=await Vw(e,t.realm,{input:n})}catch(o){console.error(`${h}Error:${f} ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(t.json)N.output(JSON.stringify(i,null,2));else{if(console.log(`${y}Status:${f} ${Hw(i.status)}${i.status}${f}`),i.result){console.log(`${y}Result:${f}`);try{N.output(JSON.stringify(JSON.parse(i.result),null,2))}catch{N.output(i.result)}}i.error&&console.error(`${h}Error:${f} ${i.error}`)}(i.status==="error"||i.status==="unusable")&&process.exit(1)})}function Hw(r){switch(r){case"ready":return S;case"error":return h;default:return _}}async function Ww(r,e,t){let n=t?.profileManager??A(),i=n.getActiveProfile();if(!i)return{ok:!1,error:M};let s=`${i.profile.realmServerUrl.replace(/\/$/,"")}/_federated-search`,a=(Array.isArray(r)?r:[r]).map(P);try{let l=await n.authedRealmServerFetch(s,{method:"QUERY",headers:{Accept:"application/vnd.card+json","Content-Type":"application/json"},body:JSON.stringify({realms:a,...e})});if(!l.ok){let c=await l.text();return{ok:!1,status:l.status,error:`HTTP ${l.status}: ${c.slice(0,300)}`}}let u=await l.json();return{ok:!0,status:l.status,data:u.data}}catch(l){return{ok:!1,status:0,error:l instanceof Error?l.message:String(l)}}}function Fc(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:${f} 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:${f} --query must be a JSON object, got ${Array.isArray(i)?"array":typeof i}`),process.exit(1)),t=i}catch(i){console.error(`${h}Error:${f} Invalid JSON in --query: ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}let n;try{n=await Ww(e.realm,t)}catch(i){console.error(`${h}Error:${f} ${i instanceof Error?i.message:String(i)}`),process.exit(1);return}e.json?N.output(JSON.stringify(n,null,2)):n.ok?N.output(JSON.stringify(n.data??[],null,2)):(console.error(`${y}Status:${f} ${n.status??"(no status)"}`),console.error(`${h}Error:${f} ${n.error}`)),n.ok||process.exit(1)})}function jc(r){let e=new Uc.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&&Zt(!0),xl(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",`
115
121
  Environment variables (for 'add'):
116
122
  BOXEL_PASSWORD Password; preferred over -p to avoid shell history.
117
123
  BOXEL_ENVIRONMENT An env-mode slug (e.g. a branch name), interpreted
118
124
  like scripts/env-slug.sh: URLs are derived as
119
125
  http://matrix.<slug>.localhost and
120
126
  http://realm-server.<slug>.localhost/. Overridden
121
- 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 ol(t,n,i)}),gc(e),lc(e),yc(e),Ec(e),al(e),e}var tE=JSON.parse((0,Rc.readFileSync)((0,$c.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&Bt(!0);bc(tE.version).parse();
127
+ 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 bl(t,n,i)}),Nc(e),Oc(e),Dc(e),Fc(e),kl(e),_l(e),e}var Bw=JSON.parse((0,qc.readFileSync)((0,Gc.resolve)(__dirname,"../package.json"),"utf-8"));process.argv.includes("--quiet")&&Zt(!0);jc(Bw.version).parse();
122
128
  /*! Bundled license information:
123
129
 
124
130
  safe-buffer/index.js: