engagelab-email-cli 1.0.0 → 1.1.0

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.
Files changed (3) hide show
  1. package/README.md +211 -0
  2. package/dist/index.cjs +44 -25
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,211 @@
1
+ # EngageLab Email CLI
2
+
3
+ Pure JavaScript ES Modules CLI for EngageLab Email Agent/Skill workflows.
4
+
5
+ ## Install
6
+
7
+ Install dependencies for local development:
8
+
9
+ ```bash
10
+ pnpm install
11
+ ```
12
+
13
+ Install from npm after publishing:
14
+
15
+ ```bash
16
+ npm install -g engagelab-email-cli
17
+ ```
18
+
19
+ ## Test
20
+
21
+ ```bash
22
+ npm test
23
+ ```
24
+
25
+ The test command runs CLI smoke tests. The console prints each CLI command, the mocked HTTP request, the HTTP status code, and the CLI output summary.
26
+
27
+ ## Build And Publish
28
+
29
+ Build the CLI package locally:
30
+
31
+ ```bash
32
+ npm run build
33
+ ```
34
+
35
+ Check the package contents before publishing:
36
+
37
+ ```bash
38
+ npm run packcheck
39
+ ```
40
+
41
+ Publish manually to the public npm registry:
42
+
43
+ ```bash
44
+ npm login
45
+ npm run publish:npm
46
+ ```
47
+
48
+ GitHub Actions can also publish the package from `.github/workflows/publish-npm.yml`. The workflow runs tests before publishing.
49
+
50
+ Current package name and CLI command:
51
+
52
+ ```text
53
+ engagelab-email-cli
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ ```bash
59
+ engagelab-email-cli config set --base-url http://localhost:8087 --secret-key sk_xxx
60
+ engagelab-email-cli config list
61
+ ```
62
+
63
+ Runtime config precedence:
64
+
65
+ 1. CLI options: `--base-url`, `--secret-key`
66
+ 2. Environment variables: `ENGAGELAB_EMAIL_BASE_URL`, `ENGAGELAB_EMAIL_SECRET_KEY`
67
+ 3. Local config file
68
+
69
+ `config list` masks the Secret Key and never prints the full value.
70
+
71
+ ## Skill-Friendly Usage
72
+
73
+ For Agent/Skill integrations, prefer JSON input files and JSON output:
74
+
75
+ ```bash
76
+ engagelab-email-cli emails receiving listen --limit 10 --interval 5 --json
77
+ engagelab-email-cli threads messages <thread-id> --include-content --json
78
+ engagelab-email-cli emails receiving reply <message-uid> --body-file reply.json --json
79
+ engagelab-email-cli emails send --body-file send.json --json
80
+ ```
81
+
82
+ `listen` is a long-running polling command. It prints each new message as it arrives and exits when you press `Ctrl+C`.
83
+ With `--json`, `listen` outputs NDJSON: one JSON object per message line. JSON input files avoid shell quoting issues with long text, HTML, arrays, and newlines.
84
+
85
+ ## Threads
86
+
87
+ ```bash
88
+ engagelab-email-cli threads list \
89
+ --mailbox-id 1001 \
90
+ --subject refund \
91
+ --participant alice@example.com \
92
+ --page-no 1 \
93
+ --page-size 20
94
+
95
+ engagelab-email-cli threads get <thread-id> --json
96
+
97
+ engagelab-email-cli threads messages <thread-id> \
98
+ --limit 50 \
99
+ --include-content \
100
+ --json
101
+ ```
102
+
103
+ ## Receiving
104
+
105
+ ```bash
106
+ engagelab-email-cli emails receiving list \
107
+ --mailbox-id 1001 \
108
+ --keyword refund \
109
+ --json
110
+
111
+ engagelab-email-cli emails receiving get <message-uid> --json
112
+
113
+ engagelab-email-cli emails receiving listen \
114
+ --limit 10 \
115
+ --interval 5 \
116
+ --json
117
+
118
+ engagelab-email-cli emails receiving listen \
119
+ --after 1500 \
120
+ --limit 10 \
121
+ --interval 5
122
+ ```
123
+
124
+ `emails receiving listen` follows the Resend-style CLI polling model:
125
+
126
+ - It seeds the cursor from the latest message when `--after` is not provided, so historical messages are not printed on startup.
127
+ - It polls `GET /v1/message/listen` every `--interval` seconds; the default is `5`, and the minimum is `2`.
128
+ - It sends `after=<cursor>` on later polls and updates the cursor from the newest returned message.
129
+ - It keeps running until `Ctrl+C` or process termination.
130
+ - In `--json` mode, each new message is printed as one compact JSON line.
131
+
132
+ ## Reply
133
+
134
+ Short manual reply:
135
+
136
+ ```bash
137
+ engagelab-email-cli emails receiving reply <message-uid> \
138
+ --text "您好,您的邮件已收到。" \
139
+ --json
140
+ ```
141
+
142
+ Skill-friendly reply:
143
+
144
+ ```bash
145
+ engagelab-email-cli emails receiving reply <message-uid> --body-file reply.json --json
146
+ ```
147
+
148
+ `reply.json`:
149
+
150
+ ```json
151
+ {
152
+ "subject": "Re: Refund request",
153
+ "text": "您好,您的退款申请已收到。",
154
+ "html": "<p>您好,您的退款申请已收到。</p>",
155
+ "cc": ["ops@example.com"],
156
+ "bcc": []
157
+ }
158
+ ```
159
+
160
+ ## Send
161
+
162
+ Manual send:
163
+
164
+ ```bash
165
+ engagelab-email-cli emails send \
166
+ --mailbox-id 1001 \
167
+ --to alice@example.com \
168
+ --subject "Refund update" \
169
+ --text "您的退款申请已经处理完成。" \
170
+ --json
171
+ ```
172
+
173
+ Skill-friendly send:
174
+
175
+ ```bash
176
+ engagelab-email-cli emails send --body-file send.json --json
177
+ ```
178
+
179
+ `send.json`:
180
+
181
+ ```json
182
+ {
183
+ "mailboxId": 1001,
184
+ "to": ["alice@example.com"],
185
+ "subject": "Refund update",
186
+ "text": "您的退款申请已经处理完成。",
187
+ "html": "<p>您的退款申请已经处理完成。</p>",
188
+ "cc": [],
189
+ "bcc": []
190
+ }
191
+ ```
192
+
193
+ ## Body Input Rules
194
+
195
+ - `--body-file` and `--body-json` are mutually exclusive.
196
+ - `--body-file` / `--body-json` cannot be combined with field-level body options.
197
+ - `--text` and `--text-file` are mutually exclusive.
198
+ - `--html` and `--html-file` are mutually exclusive.
199
+ - `emails send` requires `mailboxId`, at least one `to`, `subject`, and at least one of `text` or `html`.
200
+ - `emails receiving reply` requires at least one of `text` or `html`.
201
+
202
+ ## Exit Codes
203
+
204
+ | Code | Meaning |
205
+ | --- | --- |
206
+ | `0` | Success |
207
+ | `1` | Invalid arguments or missing config |
208
+ | `2` | Authentication failure |
209
+ | `3` | Resource not found |
210
+ | `4` | State conflict |
211
+ | `5` | Server, network, invalid JSON, or unknown request failure |
package/dist/index.cjs CHANGED
@@ -1,34 +1,53 @@
1
1
  #!/usr/bin/env node
2
- var Yt=Object.create;var Ue=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var Qt=Object.getPrototypeOf,er=Object.prototype.hasOwnProperty;var $=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var tr=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zt(e))!er.call(r,s)&&s!==t&&Ue(r,s,{get:()=>e[s],enumerable:!(i=Xt(e,s))||i.enumerable});return r};var de=(r,e,t)=>(t=r!=null?Yt(Qt(r)):{},tr(e||!r||!r.__esModule?Ue(t,"default",{value:r,enumerable:!0}):t,r));var J=$(me=>{var ee=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},fe=class extends ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};me.CommanderError=ee;me.InvalidArgumentError=fe});var te=$(ge=>{var{InvalidArgumentError:rr}=J(),pe=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,i)=>{if(!this.argChoices.includes(t))throw new rr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ir(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}ge.Argument=pe;ge.humanReadableArgName=ir});var be=$(Je=>{var{humanReadableArgName:sr}=te(),ye=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((s,n)=>s.name().localeCompare(n.name())),t}compareOptions(e,t){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),i=e._getHelpOption();if(i&&!i.hidden){let s=i.short&&e._findOption(i.short),n=i.long&&e._findOption(i.long);!s&&!n?t.push(i):i.long&&!n?t.push(e.createOption(i.long,i.description)):i.short&&!s&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let s=i.options.filter(n=>!n.hidden);t.push(...s)}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(i=>sr(i)).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((i,s)=>Math.max(i,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,s)=>Math.max(i,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,s)=>Math.max(i,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,s)=>Math.max(i,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let s=e.parent;s;s=s.parent)i=s.name()+" "+i;return i+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(i=>JSON.stringify(i)).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(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),s=t.helpWidth||80,n=2,o=2;function u(f,T){if(T){let he=`${f.padEnd(i+o)}${T}`;return t.wrap(he,s-n,i+o)}return f}function a(f){return f.join(`
3
- `).replace(/^/gm," ".repeat(n))}let c=[`Usage: ${t.commandUsage(e)}`,""],l=t.commandDescription(e);l.length>0&&(c=c.concat([t.wrap(l,s,0),""]));let h=t.visibleArguments(e).map(f=>u(t.argumentTerm(f),t.argumentDescription(f)));h.length>0&&(c=c.concat(["Arguments:",a(h),""]));let d=t.visibleOptions(e).map(f=>u(t.optionTerm(f),t.optionDescription(f)));if(d.length>0&&(c=c.concat(["Options:",a(d),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(T=>u(t.optionTerm(T),t.optionDescription(T)));f.length>0&&(c=c.concat(["Global Options:",a(f),""]))}let g=t.visibleCommands(e).map(f=>u(t.subcommandTerm(f),t.subcommandDescription(f)));return g.length>0&&(c=c.concat(["Commands:",a(g),""])),c.join(`
4
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,s=40){let n=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${n}]+`);if(e.match(o))return e;let u=t-i;if(u<s)return e;let a=e.slice(0,i),c=e.slice(i).replace(`\r
2
+ var Ui=Object.create;var St=Object.defineProperty;var Gi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var zi=Object.getPrototypeOf,Ki=Object.prototype.hasOwnProperty;var b=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var Yi=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ji(e))!Ki.call(r,n)&&n!==t&&St(r,n,{get:()=>e[n],enumerable:!(i=Gi(e,n))||i.enumerable});return r};var V=(r,e,t)=>(t=r!=null?Ui(zi(r)):{},Yi(e||!r||!r.__esModule?St(t,"default",{value:r,enumerable:!0}):t,r));var se=b(He=>{var Ee=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Ne=class extends Ee{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};He.CommanderError=Ee;He.InvalidArgumentError=Ne});var Fe=b(Ve=>{var{InvalidArgumentError:Xi}=se(),Pe=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,i)=>{if(!this.argChoices.includes(t))throw new Xi(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Zi(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Ve.Argument=Pe;Ve.humanReadableArgName=Zi});var Ue=b(Bt=>{var{humanReadableArgName:Qi}=Fe(),We=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,s)=>n.name().localeCompare(s.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!n&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);t.push(...n)}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(i=>Qi(i)).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((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+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(i=>JSON.stringify(i)).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(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,s=2,o=2;function a(c,d){if(d){let p=`${c.padEnd(i+o)}${d}`;return t.wrap(p,n-s,i+o)}return c}function u(c){return c.join(`
3
+ `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${t.commandUsage(e)}`,""],h=t.commandDescription(e);h.length>0&&(l=l.concat([t.wrap(h,n,0),""]));let f=t.visibleArguments(e).map(c=>a(t.argumentTerm(c),t.argumentDescription(c)));f.length>0&&(l=l.concat(["Arguments:",u(f),""]));let m=t.visibleOptions(e).map(c=>a(t.optionTerm(c),t.optionDescription(c)));if(m.length>0&&(l=l.concat(["Options:",u(m),""])),this.showGlobalOptions){let c=t.visibleGlobalOptions(e).map(d=>a(t.optionTerm(d),t.optionDescription(d)));c.length>0&&(l=l.concat(["Global Options:",u(c),""]))}let D=t.visibleCommands(e).map(c=>a(t.subcommandTerm(c),t.subcommandDescription(c)));return D.length>0&&(l=l.concat(["Commands:",u(D),""])),l.join(`
4
+ `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,n=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${s}]+`);if(e.match(o))return e;let a=t-i;if(a<n)return e;let u=e.slice(0,i),l=e.slice(i).replace(`\r
5
5
  `,`
6
- `),l=" ".repeat(i),d="\\s\u200B",g=new RegExp(`
7
- |.{1,${u-1}}([${d}]|$)|[^${d}]+?([${d}]|$)`,"g"),f=c.match(g)||[];return a+f.map((T,he)=>T===`
8
- `?"":(he>0?l:"")+T.trimEnd()).join(`
9
- `)}};Je.Help=ye});var xe=$(Oe=>{var{InvalidArgumentError:nr}=J(),we=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 i=ar(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(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,i)=>{if(!this.argChoices.includes(t))throw new nr(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return or(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},_e=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,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let s=this.negativeOptions.get(i).presetArg,n=s!==void 0?s:!1;return t.negate===(n===e)}};function or(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ar(r){let e,t,i=r.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Oe.Option=we;Oe.DualOptions=_e});var Be=$(We=>{function ur(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let i=0;i<=r.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=r.length;s++){let n=1;r[s-1]===e[i-1]?n=0:n=1,t[s][i]=Math.min(t[s-1][i]+1,t[s][i-1]+1,t[s-1][i-1]+n),s>1&&i>1&&r[s-1]===e[i-2]&&r[s-2]===e[i-1]&&(t[s][i]=Math.min(t[s][i],t[s-2][i-2]+1))}return t[r.length][e.length]}function cr(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 i=[],s=3,n=.4;return e.forEach(o=>{if(o.length<=1)return;let u=ur(r,o),a=Math.max(r.length,o.length);(a-u)/a>n&&(u<s?(s=u,i=[o]):u===s&&i.push(o))}),i.sort((o,u)=>o.localeCompare(u)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
6
+ `),h=" ".repeat(i),m="\\s\u200B",D=new RegExp(`
7
+ |.{1,${a-1}}([${m}]|$)|[^${m}]+?([${m}]|$)`,"g"),c=l.match(D)||[];return u+c.map((d,p)=>d===`
8
+ `?"":(p>0?h:"")+d.trimEnd()).join(`
9
+ `)}};Bt.Help=We});var Ke=b(ze=>{var{InvalidArgumentError:en}=se(),Ge=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 i=rn(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(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,i)=>{if(!this.argChoices.includes(t))throw new en(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return tn(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Je=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,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return t.negate===(s===e)}};function tn(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function rn(r){let e,t,i=r.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}ze.Option=Ge;ze.DualOptions=Je});var Tt=b(Rt=>{function nn(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let i=0;i<=r.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=r.length;n++){let s=1;r[n-1]===e[i-1]?s=0:s=1,t[n][i]=Math.min(t[n-1][i]+1,t[n][i-1]+1,t[n-1][i-1]+s),n>1&&i>1&&r[n-1]===e[i-2]&&r[n-2]===e[i-1]&&(t[n][i]=Math.min(t[n][i],t[n-2][i-2]+1))}return t[r.length][e.length]}function sn(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 i=[],n=3,s=.4;return e.forEach(o=>{if(o.length<=1)return;let a=nn(r,o),u=Math.max(r.length,o.length);(u-a)/u>s&&(a<n?(n=a,i=[o]):a===n&&i.push(o))}),i.sort((o,a)=>o.localeCompare(a)),t&&(i=i.map(o=>`--${o}`)),i.length>1?`
10
10
  (Did you mean one of ${i.join(", ")}?)`:i.length===1?`
11
- (Did you mean ${i[0]}?)`:""}We.suggestSimilar=cr});var Xe=$(Ye=>{var lr=require("node:events").EventEmitter,Ee=require("node:child_process"),S=require("node:path"),Ce=require("node:fs"),m=require("node:process"),{Argument:hr,humanReadableArgName:dr}=te(),{CommanderError:Ae}=J(),{Help:fr}=be(),{Option:Ge,DualOptions:mr}=xe(),{suggestSimilar:ze}=Be(),Se=class r extends lr{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,outputError:(t,i)=>i(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,i){let s=t,n=i;typeof s=="object"&&s!==null&&(n=s,s=null),n=n||{};let[,o,u]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),n.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(n.noHelp||n.hidden),a._executableFile=n.executableFile||null,u&&a.arguments(u),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new fr,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
12
- - 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 hr(e,t)}argument(e,t,i,s){let n=this.createArgument(e,t);return typeof i=="function"?n.default(s).argParser(i):n.default(i),this.addArgument(n),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[,i,s]=e.match(/([^ ]+) *(.*)/),n=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),s&&o.arguments(s),n&&o.description(n),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 i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${i.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,i){this._exitCallback&&this._exitCallback(new Ae(e,t,i)),m.exit(e)}action(e){let t=i=>{let s=this.registeredArguments.length,n=i.slice(0,s);return this._storeOptionsAsProperties?n[s]=this:n[s]=this.opts(),n.push(this),e.apply(this,n)};return this._actionHandler=t,this}createOption(e,t){return new Ge(e,t)}_callParseArg(e,t,i,s){try{return e.parseArg(t,i)}catch(n){if(n.code==="commander.invalidArgument"){let o=`${s} ${n.message}`;this.error(o,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=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 '${i}'
14
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),i=t(e).find(s=>this._findCommand(s));if(i){let s=t(this._findCommand(i)).join("|"),n=t(e).join("|");throw new Error(`cannot add command '${n}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let n=e.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let s=(n,o,u)=>{n==null&&e.presetArg!==void 0&&(n=e.presetArg);let a=this.getOptionValue(i);n!==null&&e.parseArg?n=this._callParseArg(e,n,a,o):n!==null&&e.variadic&&(n=e._concatValue(n,a)),n==null&&(e.negate?n=!1:e.isBoolean()||e.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,u)};return this.on("option:"+t,n=>{let o=`error: option '${e.flags}' argument '${n}' is invalid.`;s(n,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,n=>{let o=`error: option '${e.flags}' value '${n}' from env '${e.envVar}' is invalid.`;s(n,o,"env")}),this}_optionEx(e,t,i,s,n){if(typeof t=="object"&&t instanceof Ge)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(n).argParser(s);else if(s instanceof RegExp){let u=s;s=(a,c)=>{let l=u.exec(a);return l?l[0]:c},o.default(n).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,i,s){return this._optionEx({},e,t,i,s)}requiredOption(e,t,i,s){return this._optionEx({mandatory:!0},e,t,i,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.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){m.versions?.electron&&(t.from="electron");let s=m.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=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",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,h){let d=S.resolve(l,h);if(Ce.existsSync(d))return d;if(s.includes(S.extname(h)))return;let g=s.find(f=>Ce.existsSync(`${d}${f}`));if(g)return`${d}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,u=this._executableDir||"";if(this._scriptPath){let l;try{l=Ce.realpathSync(this._scriptPath)}catch{l=this._scriptPath}u=S.resolve(S.dirname(l),u)}if(u){let l=n(u,o);if(!l&&!e._executableFile&&this._scriptPath){let h=S.basename(this._scriptPath,S.extname(this._scriptPath));h!==this._name&&(l=n(u,`${h}-${e._name}`))}o=l||o}i=s.includes(S.extname(o));let a;m.platform!=="win32"?i?(t.unshift(o),t=Ke(m.execArgv).concat(t),a=Ee.spawn(m.argv[0],t,{stdio:"inherit"})):a=Ee.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Ke(m.execArgv).concat(t),a=Ee.spawn(m.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{m.on(h,()=>{a.killed===!1&&a.exitCode===null&&a.kill(h)})});let c=this._exitCallback;a.on("close",l=>{l=l??1,c?c(new Ae(l,"commander.executeSubCommandAsync","(close)")):m.exit(l)}),a.on("error",l=>{if(l.code==="ENOENT"){let h=u?`searched for local subcommand relative to directory '${u}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",d=`'${o}' does not exist
11
+ (Did you mean ${i[0]}?)`:""}Rt.suggestSimilar=sn});var qt=b(jt=>{var on=require("node:events").EventEmitter,Ye=require("node:child_process"),I=require("node:path"),Xe=require("node:fs"),F=require("node:process"),{Argument:un,humanReadableArgName:an}=Fe(),{CommanderError:Ze}=se(),{Help:ln}=Ue(),{Option:vt,DualOptions:cn}=Ke(),{suggestSimilar:kt}=Tt(),Qe=class r extends on{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,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._outputConfiguration={writeOut:t=>F.stdout.write(t),writeErr:t=>F.stderr.write(t),getOutHelpWidth:()=>F.stdout.isTTY?F.stdout.columns:void 0,getErrHelpWidth:()=>F.stderr.isTTY?F.stderr.columns:void 0,outputError:(t,i)=>i(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,i){let n=t,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(o);return n&&(u.description(n),u._executableHandler=!0),s.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(s.noHelp||s.hidden),u._executableFile=s.executableFile||null,a&&u.arguments(a),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),n?this:u}createCommand(e){return new r(e)}createHelp(){return Object.assign(new ln,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
12
+ - 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 un(e,t)}argument(e,t,i,n){let s=this.createArgument(e,t);return typeof i=="function"?s.default(n).argParser(i):s.default(i),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[,i,n]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",o=this.createCommand(i);return o.helpOption(!1),n&&o.arguments(n),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 i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${i.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,i){this._exitCallback&&this._exitCallback(new Ze(e,t,i)),F.exit(e)}action(e){let t=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new vt(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let o=`${n} ${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 i=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 '${i}'
14
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),i=t(e).find(n=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(s,o,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let u=this.getOptionValue(i);s!==null&&e.parseArg?s=this._callParseArg(e,s,u,o):s!==null&&e.variadic&&(s=e._concatValue(s,u)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+t,s=>{let o=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let o=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,o,"env")}),this}_optionEx(e,t,i,n,s){if(typeof t=="object"&&t instanceof vt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,i);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(u,l)=>{let h=a.exec(u);return h?h[0]:l},o.default(s).argParser(n)}else o.default(n);return this.addOption(o)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}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,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.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){F.versions?.electron&&(t.from="electron");let n=F.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=F.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":F.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=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",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(h,f){let m=I.resolve(h,f);if(Xe.existsSync(m))return m;if(n.includes(I.extname(f)))return;let D=n.find(c=>Xe.existsSync(`${m}${c}`));if(D)return`${m}${D}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let h;try{h=Xe.realpathSync(this._scriptPath)}catch{h=this._scriptPath}a=I.resolve(I.dirname(h),a)}if(a){let h=s(a,o);if(!h&&!e._executableFile&&this._scriptPath){let f=I.basename(this._scriptPath,I.extname(this._scriptPath));f!==this._name&&(h=s(a,`${f}-${e._name}`))}o=h||o}i=n.includes(I.extname(o));let u;F.platform!=="win32"?i?(t.unshift(o),t=$t(F.execArgv).concat(t),u=Ye.spawn(F.argv[0],t,{stdio:"inherit"})):u=Ye.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=$t(F.execArgv).concat(t),u=Ye.spawn(F.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{F.on(f,()=>{u.killed===!1&&u.exitCode===null&&u.kill(f)})});let l=this._exitCallback;u.on("close",h=>{h=h??1,l?l(new Ze(h,"commander.executeSubCommandAsync","(close)")):F.exit(h)}),u.on("error",h=>{if(h.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",m=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${h}`;throw new Error(d)}else if(l.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)m.exit(1);else{let h=new Ae(1,"commander.executeSubCommandAsync","(error)");h.nestedError=l,c(h)}}),this.runningCommand=a}_dispatchSubcommand(e,t,i){let s=this._findCommand(e);s||this.help({error:!0});let n;return n=this._chainOrCallSubCommandHook(n,s,"preSubcommand"),n=this._chainOrCall(n,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(i));else return s._parseCommand(t,i)}),n}_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=(i,s,n)=>{let o=s;if(s!==null&&i.parseArg){let u=`error: command-argument value '${s}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,s,n,u)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,s)=>{let n=i.defaultValue;i.variadic?s<this.args.length?(n=this.args.slice(s),i.parseArg&&(n=n.reduce((o,u)=>e(i,u,o),i.defaultValue))):n===void 0&&(n=[]):s<this.args.length&&(n=this.args[s],i.parseArg&&(n=e(i,n,i.defaultValue))),t[s]=n}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,s=[];return this._getCommandAndAncestors().reverse().filter(n=>n._lifeCycleHooks[t]!==void 0).forEach(n=>{n._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:n,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(n=>{i=this._chainOrCall(i,()=>n.callback(n.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let s=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(n=>{s=this._chainOrCall(s,()=>n(this,t))}),s}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.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(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){s(),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(n,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(n))s(),this._processArguments(),this.parent.emit(n,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let s=i.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let s=e.find(n=>i.conflictsWith.includes(n.attributeName()));s&&this._conflictingOption(i,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],s=t,n=e.slice();function o(a){return a.length>1&&a[0]==="-"}let u=null;for(;n.length;){let a=n.shift();if(a==="--"){s===i&&s.push(a),s.push(...n);break}if(u&&!o(a)){this.emit(`option:${u.name()}`,a);continue}if(u=null,o(a)){let c=this._findOption(a);if(c){if(c.required){let l=n.shift();l===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,l)}else if(c.optional){let l=null;n.length>0&&!o(n[0])&&(l=n.shift()),this.emit(`option:${c.name()}`,l)}else this.emit(`option:${c.name()}`);u=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,a.slice(2)):(this.emit(`option:${c.name()}`),n.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),l=this._findOption(a.slice(0,c));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,a.slice(c+1));continue}}if(o(a)&&(s=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(a)){t.push(a),n.length>0&&i.push(...n);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),n.length>0&&t.push(...n);break}else if(this._defaultCommandName){i.push(a),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){s.push(a),n.length>0&&s.push(...n);break}s.push(a)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let s=this.options[i].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
17
+ - ${f}`;throw new Error(m)}else if(h.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)F.exit(1);else{let f=new Ze(1,"commander.executeSubCommandAsync","(error)");f.nestedError=h,l(f)}}),this.runningCommand=u}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);n||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),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=(i,n,s)=>{let o=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;o=this._callParseArg(i,n,s,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((o,a)=>e(i,a,o),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=e(i,s,i.defaultValue))),t[n]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(o=>{n.push({hookedCommand:s,callback:o})})}),t==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,t))}),n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.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(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),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))n(),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():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),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(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t,s=e.slice();function o(u){return u.length>1&&u[0]==="-"}let a=null;for(;s.length;){let u=s.shift();if(u==="--"){n===i&&n.push(u),n.push(...s);break}if(a&&!o(u)){this.emit(`option:${a.name()}`,u);continue}if(a=null,o(u)){let l=this._findOption(u);if(l){if(l.required){let h=s.shift();h===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,h)}else if(l.optional){let h=null;s.length>0&&!o(s[0])&&(h=s.shift()),this.emit(`option:${l.name()}`,h)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let l=this._findOption(`-${u[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,u.slice(2)):(this.emit(`option:${l.name()}`),s.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let l=u.indexOf("="),h=this._findOption(u.slice(0,l));if(h&&(h.required||h.optional)){this.emit(`option:${h.name()}`,u.slice(l+1));continue}}if(o(u)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(u)){t.push(u),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){i.push(u),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){n.push(u),s.length>0&&n.push(...s);break}n.push(u)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let i=t||{},s=i.exitCode||1,n=i.code||"commander.error";this._exit(s,n,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.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()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new mr(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"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 i=o=>{let u=o.attributeName(),a=this.getOptionValue(u),c=this.options.find(h=>h.negate&&u===h.attributeName()),l=this.options.find(h=>!h.negate&&u===h.attributeName());return c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg)?c:l||o},s=o=>{let u=i(o),a=u.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${u.envVar}'`:`option '${u.flags}'`},n=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],n=this;do{let o=n.createHelp().visibleOptions(n).filter(u=>u.long).map(u=>u.long);s=s.concat(o),n=n.parent}while(n&&!n._enablePositionalOptions);t=ze(e,s)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(n=>{s.push(n.name()),n.alias()&&s.push(n.alias())}),t=ze(e,s)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let s=this.createOption(t,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),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 i=this.parent?._findCommand(e);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}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(i=>dr(i));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=S.basename(e,S.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=s=>this._outputConfiguration.writeErr(s):i=s=>this._outputConfiguration.writeOut(s),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(n=>n.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let s=this.helpInformation(i);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(n=>n.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=m.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
- Expecting one of '${i.join("', '")}'`);let s=`${e}Help`;return this.on(s,n=>{let o;typeof t=="function"?o=t({error:n.error,command:n.command}):o=t,o&&n.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ke(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",s="9229",n;return(n=e.match(/^(--inspect(-brk)?)$/))!==null?t=n[1]:(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=n[1],/^\d+$/.test(n[3])?s=n[3]:i=n[3]):(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=n[1],i=n[3],s=n[4]),t&&s!=="0"?`${t}=${i}:${parseInt(s)+1}`:e})}Ye.Command=Se});var tt=$(w=>{var{Argument:Ze}=te(),{Command:Re}=Xe(),{CommanderError:pr,InvalidArgumentError:Qe}=J(),{Help:gr}=be(),{Option:et}=xe();w.program=new Re;w.createCommand=r=>new Re(r);w.createOption=(r,e)=>new et(r,e);w.createArgument=(r,e)=>new Ze(r,e);w.Command=Re;w.Option=et;w.Argument=Ze;w.Help=gr;w.CommanderError=pr;w.InvalidArgumentError=Qe;w.InvalidOptionArgumentError=Qe});var rt=de(tt(),1),{program:ti,createCommand:ri,createArgument:ii,createOption:si,CommanderError:ni,InvalidArgumentError:oi,InvalidOptionArgumentError:ai,Command:it,Argument:ui,Option:ci,Help:li}=rt.default;var q=require("node:fs/promises"),W=de(require("node:path"),1),Te=de(require("node:os"),1);async function B({configPath:r=nt()}={}){try{return JSON.parse(await(0,q.readFile)(r,"utf8"))}catch(e){if(e.code==="ENOENT")return{};throw e}}async function st(r,{configPath:e=nt()}={}){await(0,q.mkdir)(W.default.dirname(e),{recursive:!0}),await(0,q.writeFile)(e,`${JSON.stringify(r,null,2)}
24
- `,{encoding:"utf8",mode:384})}function nt(r=process.env,e=process.platform){if(r.ENGAGELAB_EMAIL_CONFIG)return r.ENGAGELAB_EMAIL_CONFIG;let t=r.XDG_CONFIG_HOME||(e==="win32"?r.APPDATA||W.default.join(Te.default.homedir(),"AppData","Roaming"):W.default.join(Te.default.homedir(),".config"));return W.default.join(t,"engagelab-email-cli","config.json")}function ot(r){return r?`${r.slice(0,7)}****`:""}var E=class extends Error{constructor(e,{code:t="cli_error",exitCode:i=1,status:s,data:n,cause:o}={}){super(e,{cause:o}),this.name="CliError",this.code=t,this.exitCode=i,this.status=s,this.data=n}};function ke(r){return r===401||r===403?2:r===404?3:r===409?4:5}function at(r){return r instanceof E?r:new E(r?.message||"Command failed",{code:"unknown_error",exitCode:5,cause:r})}function p(r){return new E(r,{code:"validation_error",exitCode:1})}function re(r){return new E(r,{code:"config_error",exitCode:1})}function ut(r){let e=r.command("config").description("Manage local EngageLab Email CLI config");e.command("set").description("Save local CLI configuration").option("--base-url <url>","EngageLab Email API base URL").option("--secret-key <key>","EngageLab Email Secret Key").action(async(t,i)=>{if(t={...i.optsWithGlobals(),...t},!t.baseUrl&&!t.secretKey)throw p("Provide at least one of --base-url or --secret-key");if(t.secretKey&&!t.secretKey.startsWith("sk_"))throw p("Secret Key must start with sk_");let s=await B();await st({...s,...yr(t)}),process.stdout.write(`Config saved
25
- `)}),e.command("list").description("Show local CLI configuration").action(async()=>{let t=await B();process.stdout.write(`baseUrl: ${t.baseUrl||""}
26
- `),process.stdout.write(`secretKey: ${ot(t.secretKey)}
27
- `)})}function yr(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var ht=require("node:fs/promises");var dt=new Set(["bodyFile","bodyJson"]),ft=[["text","textFile"],["html","htmlFile"]];async function ve(r={},{readFile:e=ht.readFile}={}){if(br(r),r.bodyFile)return ct(await e(r.bodyFile,"utf8"),`Invalid JSON in ${r.bodyFile}`);if(r.bodyJson)return ct(r.bodyJson,"Invalid JSON in --body-json");let t={};for(let[i,s]of Object.entries(r))dt.has(i)||i.endsWith("File")||s===void 0||(t[i]=s);for(let[i,s]of ft)r[s]&&(t[i]=await e(r[s],"utf8"));return t}function br(r){if(r.bodyFile&&r.bodyJson)throw p("--body-file and --body-json are mutually exclusive");if((r.bodyFile||r.bodyJson)&&Object.entries(r).filter(([t,i])=>i!==void 0&&!dt.has(t)).length>0)throw p("--body-file/--body-json cannot be combined with field-level body options");for(let[e,t]of ft)if(r[e]&&r[t])throw p(`--${lt(e)} and --${lt(t)} are mutually exclusive`)}function ct(r,e){try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON body must be an object");return t}catch(t){throw p(`${e}: ${t.message}`)}}function lt(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function y(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<=0)throw p("Expected a positive integer");return e}function P(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<0)throw p("Expected a non-negative integer");return e}function H(r,e=[]){return[...e,r]}function mt(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!=null&&e!==""))}function k(r,e){if(r==null||r==="")throw p(e);return r}function $e(r,e){if(!r||r.length===0)return"No results";let t=r.map(u=>e.map(a=>wr(a.value(u)))),i=e.map((u,a)=>Math.max(u.header.length,...t.map(c=>c[a].length))),s=e.map((u,a)=>pt(u.header,i[a])).join(" "),n=i.map(u=>"-".repeat(u)).join(" "),o=t.map(u=>u.map((a,c)=>pt(a,i[c])).join(" "));return[s,n,...o].join(`
28
- `)}function wr(r){return Array.isArray(r)?r.join(", "):r==null?"":String(r)}function pt(r,e){return r.padEnd(e," ")}function gt(r){return{0:"received",1:"parsing",2:"parsed",3:"parse_failed",4:"replied"}[r]??r}function yt(r){return{0:"pending",1:"processing",2:"done",3:"failed"}[r]??r}function bt(r){return $e(r.data?.list||[],[{header:"Thread ID",value:e=>e.threadId},{header:"Subject",value:e=>e.subject},{header:"Participants",value:e=>e.participants},{header:"Last Message",value:e=>e.lastMessageAt},{header:"Count",value:e=>e.messageCount},{header:"Status",value:e=>e.status}])}function G(r){return $e(r.data?.list||r.data||[],[{header:"Message UID",value:e=>e.messageUid},{header:"Thread ID",value:e=>e.threadId},{header:"From",value:e=>e.fromEmail||e.envelopeFrom},{header:"Subject",value:e=>e.subject},{header:"Status",value:e=>gt(e.status)},{header:"Agent",value:e=>yt(e.agentConsumeStatus)},{header:"Received",value:e=>e.receivedAt}])}function I(r){return JSON.stringify(r.data??r,null,2)}function je(r){let e=r.data||{};return["Sent",e.messageUid?`messageUid: ${e.messageUid}`:null,e.requestId?`requestId: ${e.requestId}`:null,e.emailIds?`emailIds: ${e.emailIds.join(", ")}`:null].filter(Boolean).join(`
29
- `)}function _r(r,{httpStatus:e}={}){if(!r||typeof r!="object"||typeof r.code!="number")throw new E("Invalid server response format",{code:"invalid_response",exitCode:5,status:e,data:r});if(r.code!==200)throw new E(r.message||"Request failed",{code:wt(r.code),exitCode:ke(r.code),status:r.code,data:r});return r}async function b(r){let e;try{e=await r.json()}catch(t){throw new E("Invalid server response format",{code:"invalid_response",exitCode:5,status:r.status,cause:t})}if(r.status<200||r.status>=300)throw new E(e?.message||`Request failed with status code ${r.status}`,{code:wt(r.status),exitCode:ke(r.status),status:r.status,data:e});return _r(e,{httpStatus:r.status})}function wt(r){return r===401||r===403?"auth_error":r===404?"not_found":r===409?"state_conflict":r===400?"validation_error":"server_error"}var R=class{constructor(e){this.client=e}listMessages(e={}){return this.client.get("v1/message",{searchParams:e}).then(b)}getMessage(e){return this.client.get(`v1/message/${encodeURIComponent(e)}`).then(b)}listenMessages(e={}){return this.client.get("v1/message/listen",{searchParams:e}).then(b)}ackMessage(e){return this.client.post(`v1/message/${encodeURIComponent(e)}/ack`).then(b)}failMessage(e){return this.client.post(`v1/message/${encodeURIComponent(e)}/fail`).then(b)}replyMessage(e,t){return this.client.post(`v1/message/${encodeURIComponent(e)}/reply`,{json:t}).then(b)}};var ie=class{constructor(e){this.client=e}sendEmail(e){return this.client.post("v1/mail/send",{json:e}).then(b)}};var C=class extends Error{name="KyError";get isKyError(){return!0}};var N=class extends C{name="HTTPError";response;request;options;data;constructor(e,t,i){let s=e.status||e.status===0?e.status:"",n=e.statusText??"",o=`${s} ${n}`.trim(),u=o?`status code ${o}`:"an unknown error";super(`Request failed with ${u}: ${t.method} ${t.url}`),this.response=e,this.request=t,this.options=i}};var M=class extends C{name="NetworkError";request;constructor(e,t){super(`Request failed due to a network error: ${e.method} ${e.url}`,t),this.request=e}};var V=class extends Error{name="NonError";value;constructor(e){let t="Non-error value was thrown";try{typeof e=="string"?t=e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"&&(t=e.message)}catch{}super(t),this.value=e}};var j=class extends C{name="ForceRetryError";customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new V(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};var se=class extends Error{name="SchemaValidationError";issues;constructor(e){super("Response schema validation failed"),this.issues=e}};var _=class extends C{name="TimeoutError";request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.request=e}};var qe=(()=>{let r=!1,e=!1,t=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(t&&i)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(s){if(s instanceof Error&&s.message==="unsupported BodyInit type")return!1;throw s}return r&&!e})(),_t=typeof globalThis.AbortController=="function",ne=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",Ot=typeof globalThis.ReadableStream=="function",xt=typeof globalThis.FormData=="function",oe=["get","post","put","patch","head","delete"],Or=()=>{};Or();var Et={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},L=2147483647,Ct=40,ae=Symbol("stop"),z=class{options;constructor(e){this.options=e}},At=r=>new z(r),St={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Rt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var ue=new TextEncoder,xr=r=>{if(!r)return 0;if(r instanceof FormData){let e=0;for(let[t,i]of r)e+=Ct,e+=ue.encode(`Content-Disposition: form-data; name="${t}"`).byteLength,e+=typeof i=="string"?ue.encode(i).byteLength:i.size;return e}return r instanceof Blob?r.size:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength:typeof r=="string"?ue.encode(r).byteLength:r instanceof URLSearchParams?ue.encode(r.toString()).byteLength:0},Tt=(r,e,t)=>{let i,s=0;return r.pipeThrough(new TransformStream({transform(n,o){if(o.enqueue(n),i){s+=i.byteLength;let u=e===0?0:s/e;u>=1&&(u=1-Number.EPSILON),t?.({percent:u,totalBytes:Math.max(e,s),transferredBytes:s},i)}i=n},flush(){i&&(s+=i.byteLength,t?.({percent:1,totalBytes:Math.max(e,s),transferredBytes:s},i))}}))},kt=(r,e)=>{if(!r.body)return r;let t={status:r.status,statusText:r.statusText,headers:r.headers};if(r.status===204)return new Response(null,t);let i=Math.max(0,Number(r.headers.get("content-length"))||0);return new Response(Tt(r.body,i,e),t)},vt=(r,e,t)=>{if(!r.body)return r;let i=xr(t??r.body);return new Request(r,{duplex:"half",body:Tt(r.body,i,e)})};var A=r=>r!==null&&typeof r=="object";var Er=Symbol("replaceOption"),Pe=r=>A(r)&&r[Er]===!0?{isReplace:!0,value:r.value}:{isReplace:!1,value:r};var Y=(...r)=>{for(let e of r)if((!A(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Ne({},...r)},Ie=(r={},e={})=>{let t=new globalThis.Headers(r),i=e instanceof globalThis.Headers,s=new globalThis.Headers(e);for(let[n,o]of s.entries())i&&o==="undefined"||o===void 0?t.delete(n):t.set(n,o);return t},He=r=>{if(!A(r)||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},F=r=>{if(r instanceof URLSearchParams){let e=new URLSearchParams(r),t=r[v];return t&&(e[v]=new Set(t)),e}return r instanceof globalThis.Headers?new globalThis.Headers(r):Array.isArray(r)?[...r]:He(r)?{...r}:r},Cr=r=>Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),Ar=(r,e)=>He(r)&&He(e)?Cr({...r,...e}):Ie(r,e);function K(r,e,t){return Object.hasOwn(e,t)&&e[t]===void 0?[]:Ne(r[t]??[],e[t]??[])}var ce=(r={},e={})=>({init:K(r,e,"init"),beforeRequest:K(r,e,"beforeRequest"),beforeRetry:K(r,e,"beforeRetry"),beforeError:K(r,e,"beforeError"),afterResponse:K(r,e,"afterResponse")}),v=Symbol("deletedParameters"),Sr=(r,e)=>{let t=new URLSearchParams,i=new Set;for(let s of[r,e])if(s!==void 0)if(s instanceof URLSearchParams){for(let[o,u]of s.entries())t.append(o,u),i.delete(o);let n=s[v];if(n)for(let o of n)t.delete(o),i.add(o)}else if(Array.isArray(s))for(let n of s){if(!Array.isArray(n)||n.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");t.append(String(n[0]),String(n[1])),i.delete(String(n[0]))}else if(A(s))for(let[n,o]of Object.entries(s))o===void 0?(t.delete(n),i.add(n)):(t.append(n,String(o)),i.delete(n));else{let n=new URLSearchParams(s);for(let[o,u]of n.entries())t.append(o,u),i.delete(o)}return i.size>0&&(t[v]=i),t},Ne=(...r)=>{let e={},t={},i={},s,n=[];for(let o of r)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(A(o)){for(let[u,a]of Object.entries(o)){if(u==="signal"&&a instanceof globalThis.AbortSignal){n.push(a);continue}let c=Pe(a),{isReplace:l}=c;if(a=c.value,u==="context"){if(a!=null&&(!A(a)||Array.isArray(a)))throw new TypeError("The `context` option must be an object");e={...e,context:a==null?{}:l?{...a}:{...e.context,...a}};continue}if(u==="searchParams"){a==null?s=void 0:l?s=a:s=s===void 0?a:Sr(s,a);continue}A(a)&&!l&&u in e&&(a=Ne(e[u],a)),e={...e,[u]:a}}if(A(o.hooks)){let{value:u,isReplace:a}=Pe(o.hooks);i=ce(a?{}:i,u),e.hooks=i}if(A(o.headers)){let{value:u,isReplace:a}=Pe(o.headers);t=a?F(u):Ar(t,u),e.headers=t}}return s!==void 0&&(e.searchParams=s),n.length>0&&(n.length===1?e.signal=n[0]:ne?e.signal=AbortSignal.any(n):e.signal=n.at(-1)),e};var jt=r=>oe.includes(r)?r.toUpperCase():r,Rr=["get","put","head","delete","options","trace"],Tr=[408,413,429,500,502,503,504],kr=[413,429,503],$t={limit:2,methods:Rr,statusCodes:Tr,afterStatusCodes:kr,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3,jitter:void 0,retryOnTimeout:!1},qt=(r={})=>{if(typeof r=="number")return{...$t,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");let e=Object.fromEntries(Object.entries({...r,methods:r.methods?.map(t=>t.toLowerCase())}).filter(([,t])=>t!==void 0));return{...$t,...e}};async function Me(r,e,t,i){return new Promise((s,n)=>{let o=setTimeout(()=>{t&&t.abort(),n(new _(r))},i.timeout);i.fetch(r,e).then(s).catch(n).then(()=>{clearTimeout(o)})})}async function le(r,{signal:e}){return new Promise((t,i)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",s,{once:!0}));function s(){clearTimeout(n),i(e.reason)}let n=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r)})}var Pt=r=>{let e={};for(let t in r)Object.hasOwn(r,t)&&!(t in Rt)&&!(t in St)&&(e[t]=r[t]);return e},Ht=r=>r===void 0?!1:Array.isArray(r)?r.length>0:r instanceof URLSearchParams?r.size>0||!!r[v]?.size:typeof r=="object"?Object.keys(r).length>0:typeof r=="string"?r.trim().length>0:!!r;var vr=Object.prototype.toString,$r=r=>vr.call(r)==="[object Error]",jr=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function Ve(r){if(!(r&&$r(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:i}=r;return t==="Load failed"?i===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:jr.has(t)}var Le=(r,e)=>r instanceof e||r?.name===e.name;function It(r){return Le(r,N)}function Nt(r){return Le(r,M)}function Mt(r){return Le(r,_)}var qr=10*1024*1024,Pr="The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl",X=Symbol("timedOutResponseData"),Hr=r=>{let e=/;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(r),t=e?.[1]??e?.[2];if(t)try{return new TextDecoder(t)}catch{}return new TextDecoder},Vt="The `schema` argument must follow the Standard Schema specification",Ir=r=>typeof r!="object"?r:{...r,...r.methods&&{methods:[...r.methods]},...r.statusCodes&&{statusCodes:[...r.statusCodes]},...r.afterStatusCodes&&{afterStatusCodes:[...r.afterStatusCodes]}},Dt=Object.prototype.toString,Lt=r=>r instanceof globalThis.Request||Dt.call(r)==="[object Request]",Z=r=>r instanceof globalThis.Response||Dt.call(r)==="[object Response]",Nr=r=>Array.isArray(r)?r.map(e=>[...e]):F(r);function Mr(r){let e={...r,json:F(r.json),context:F(r.context),headers:F(r.headers),searchParams:Nr(r.searchParams)};return r.retry!==void 0&&(e.retry=Ir(r.retry)),e}var Ft=async(r,e)=>{if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(Vt);let t=e["~standard"];if(typeof t!="object"||t===null||typeof t.validate!="function")throw new TypeError(Vt);let i=await t.validate(r);if(i.issues)throw new se(i.issues);return i.value},Q=class r{static create(e,t){let i=t.hooks?.init??[],s=i.length>0?Mr(t):t;for(let a of i)a(s);let n=new r(e,s),o=async()=>{if(typeof n.#e.timeout=="number"&&n.#e.timeout>L)throw new RangeError(`The \`timeout\` option cannot be greater than ${L}`);if(typeof n.#e.totalTimeout=="number"&&n.#e.totalTimeout>L)throw new RangeError(`The \`totalTimeout\` option cannot be greater than ${L}`);await Promise.resolve();let a=await n.#P(),c=a??await n.#S(async()=>n.#y()),l=a!==void 0||n.#g();for(;;){if(c===void 0)return c;if(Z(c))try{c=await n.#H(c)}catch(d){if(!(d instanceof j))throw d;let g=await n.#p(d,async()=>n.#y());if(g===void 0)return g;c=g,l=n.#g();continue}let h=c;if(!h.ok&&h.type!=="opaque"&&(typeof n.#e.throwHttpErrors=="function"?n.#e.throwHttpErrors(h.status):n.#e.throwHttpErrors)){let d=new N(h,n.#a(h),n.#o()),g=d;if(d.data=await n.#v(h),l)throw g;let f=await n.#p(d,async()=>n.#y());if(f===void 0)return f;c=f,l=n.#g();continue}break}if(!Z(c))return c;if(n.#E(c),n.#e.onDownloadProgress){if(typeof n.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Ot)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let h=c.clone();return n.#i(c),kt(h,n.#e.onDownloadProgress)}return c},u=(async()=>{try{return await o()}catch(a){if(!(a instanceof Error)||n.#O.has(a))throw a;let c=a;for(let l of n.#e.hooks.beforeError){let h=await l({request:n.request,options:n.#o(),error:c,retryCount:n.#r});h instanceof Error&&(c=h)}throw c}finally{let a=n.#_;n.#m(a?.body??void 0),n.request!==a&&n.#m(n.request.body??void 0)}})();for(let[a,c]of Object.entries(Et))a==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(u[a]=async l=>{n.request.headers.set("accept",n.request.headers.get("accept")||c);let h=await u;if(a!=="json")return h[a]();let d=await h.text();if(d==="")return l!==void 0?Ft(void 0,l):JSON.parse(d);let g=s.parseJson?await s.parseJson(d,{request:n.#a(h),response:h}):JSON.parse(d);return l===void 0?g:Ft(g,l)});return u}static#T(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)):e}request;#s;#r=0;#t;#e;#_;#u;#O=new WeakSet;#c;#f;#l=!1;#x=new WeakMap;constructor(e,t={}){if(this.#t=e,Object.hasOwn(t,"prefixUrl"))throw new Error(Pr);if(this.#e={...t,headers:Ie(this.#t.headers,t.headers),hooks:ce({},t.hooks),method:jt(t.method??this.#t.method??"GET"),prefix:String(t.prefix||""),retry:qt(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,totalTimeout:t.totalTimeout??!1,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(typeof this.#t=="string"){if(this.#e.prefix){let s=this.#e.prefix.replace(/\/+$/,""),n=this.#t.replace(/^\/+/,"");this.#t=`${s}/${n}`}if(this.#e.baseUrl){let s;try{s=new URL(this.#t)}catch{}s||(this.#t=new URL(this.#t,new Request(this.#e.baseUrl).url))}}_t&&ne&&(this.#u=this.#e.signal??this.#t.signal,this.#s=new globalThis.AbortController,this.#e.signal=this.#A()),qe&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));let i=t.headers&&new globalThis.Headers(t.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(xt&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!i&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),Ht(this.#e.searchParams)){let s=new URL(this.request.url),n=this.#e.searchParams?.[v];if(n)for(let o of n)s.searchParams.delete(o);if(typeof this.#e.searchParams=="string"){let o=this.#e.searchParams.replace(/^\?/,"");o!==""&&(s.search=s.search?`${s.search}&${o}`:`?${o}`)}else{let o=new URLSearchParams(r.#T(this.#e.searchParams));for(let[u,a]of o.entries())s.searchParams.append(u,a)}if(this.#e.searchParams&&typeof this.#e.searchParams=="object"&&!Array.isArray(this.#e.searchParams)&&!(this.#e.searchParams instanceof URLSearchParams))for(let[o,u]of Object.entries(this.#e.searchParams))u===void 0&&s.searchParams.delete(o);this.request=new globalThis.Request(s,this.#e)}if(this.#e.onUploadProgress&&typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");this.#f=typeof this.#e.totalTimeout=="number"?this.#R():void 0}#n(){let e=this.#e.retry.delay(this.#r+1),t=e;return this.#e.retry.jitter===!0?t=Math.random()*e:typeof this.#e.retry.jitter=="function"&&(t=this.#e.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e)),Math.min(this.#e.retry.backoffLimit,t)}async#k(e){if(this.#r>=this.#e.retry.limit)throw e;let t=e instanceof Error?e:new V(e);if(t instanceof j)return t.customDelay??this.#n();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#e.retry.shouldRetry!==void 0){let i=await this.#e.retry.shouldRetry({error:t,retryCount:this.#r+1});if(i===!1)throw e;if(i===!0)return this.#n()}if(Mt(e)){if(!this.#e.retry.retryOnTimeout)throw e;return this.#n()}if(It(e)){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;let i=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(i&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let s=Number(i)*1e3;return Number.isNaN(s)?s=Date.parse(i)-Date.now():s>=Date.parse("2024-01-01")&&(s-=Date.now()),Number.isFinite(s)?(s=Math.max(0,s),Math.min(this.#e.retry.maxRetryAfter,s)):Math.min(this.#e.retry.maxRetryAfter,this.#n())}if(e.response.status===413)throw e;return this.#n()}if(!Nt(e))throw e;return this.#n()}#E(e){let t=this.#a(e);return this.#e.parseJson&&(e.json=async()=>{let i=await e.text();return i===""?JSON.parse(i):this.#e.parseJson(i,{request:t,response:e})}),e}async#v(e){let t=await this.#j(e,this.#C());if(t===X){this.#h();return}if(!t)return;if(!this.#$(e.headers.get("content-type")??""))return t;let i=await this.#q(t,e,this.#C(),this.#a(e));if(i===X){this.#h();return}return i}#C(){let e=this.#e.timeout===!1?1e4:this.#e.timeout,t=this.#d();if(t===void 0)return e;if(t<=0)throw new _(this.request);return Math.min(e,t)}#$(e){let t=(e.split(";",1)[0]??"").trim().toLowerCase();return/\/(?:.*[.+-])?json$/.test(t)}async#j(e,t){let{body:i}=e;if(!i)try{return await e.text()}catch{return}let s;try{s=i.getReader()}catch{return}let n=Hr(e.headers.get("content-type")??""),o=[],u=0,a=(async()=>{try{for(;;){let{done:h,value:d}=await s.read();if(h)break;if(u+=d.byteLength,u>qr){s.cancel().catch(()=>{});return}o.push(n.decode(d,{stream:!0}))}}catch{return}return o.push(n.decode()),o.join("")})(),c=new Promise(h=>{let d=setTimeout(()=>{h(X)},t);a.finally(()=>{clearTimeout(d)})}),l=await Promise.race([a,c]);return l===X&&s.cancel().catch(()=>{}),l}async#q(e,t,i,s){let n;try{return await Promise.race([Promise.resolve().then(()=>this.#e.parseJson?this.#e.parseJson(e,{request:s,response:t}):JSON.parse(e)),new Promise(o=>{n=setTimeout(()=>{o(X)},i)})])}catch{return}finally{clearTimeout(n)}}#m(e){e&&e.cancel().catch(()=>{})}#i(e){this.#m(e.body??void 0)}#A(){return this.#u?AbortSignal.any([this.#u,this.#s.signal]):this.#s.signal}#h(){let e=this.#d();if(e!==void 0&&e<=0)throw new _(this.request)}async#P(){for(let e of this.#e.hooks.beforeRequest){let t=await e({request:this.request,options:this.#o(),retryCount:0});if(Lt(t))this.#b(t);else if(Z(t))return t}}async#H(e){let t=this.#a(e);for(let i of this.#e.hooks.afterResponse){let s=this.#w(e.clone(),t);this.#E(s);let n;try{n=await i({request:this.request,options:this.#o(),response:s,retryCount:this.#r})}catch(u){throw s!==e&&this.#i(s),this.#i(e),u}if(n instanceof z)throw s!==e&&this.#i(s),this.#i(e),new j(n.options);let o=Z(n)?this.#w(n,t):e;s!==e&&s!==o&&s.body!==o.body&&this.#i(s),e!==o&&e.body!==o.body&&this.#i(e),e=o}return e}async#S(e){try{return await e()}catch(t){return this.#p(t,e)}}async#p(e,t){this.#l=!1;let i=Math.min(await this.#k(e),L),s={signal:this.#u},n=this.#d();if(n!==void 0){if(n<=0)throw new _(this.request);if(i>=n)throw await le(n,s),new _(this.request)}if(await le(i,s),this.#h(),e instanceof j&&e.customRequest){let o=new globalThis.Request(e.customRequest,this.#e.signal?{signal:this.#e.signal}:void 0);this.#b(o)}for(let o of this.#e.hooks.beforeRetry){let u;try{u=await o({request:this.request,options:this.#o(),error:e,retryCount:this.#r+1})}catch(a){throw a instanceof Error&&a!==e&&this.#O.add(a),a}if(Lt(u)){this.#b(u);break}if(Z(u))return this.#l=!0,this.#r++,u;if(u===ae)return}return this.#h(),this.#r++,this.#S(t)}#g(){let e=this.#l;return this.#l=!1,e}async#y(){this.#s?.signal.aborted&&(this.#s=new globalThis.AbortController,this.#e.signal=this.#A(),this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));let e=Pt(this.#e),t=this.#e.retry.limit>0?this.request.clone():void 0,i=this.#I(this.request,this.#e.body??void 0);this.#_=i,t&&(this.request=t);try{let s=this.#d();if(s!==void 0&&s<=0)throw new _(this.request);let n=this.#e.timeout===!1?s:s===void 0?this.#e.timeout:Math.min(this.#e.timeout,s),o=n===void 0?await this.#e.fetch(i,e):await Me(i,e,this.#s,{timeout:n,fetch:this.#e.fetch});return this.#w(o,i)}catch(s){throw Ve(s)?new M(this.request,{cause:s}):s}}#d(){if(this.#f===void 0)return;let e=this.#R()-this.#f;return Math.max(0,this.#e.totalTimeout-e)}#R(){return globalThis.performance?.now()??Date.now()}#o(){if(!this.#c){let{hooks:e,json:t,parseJson:i,stringifyJson:s,searchParams:n,timeout:o,totalTimeout:u,throwHttpErrors:a,fetch:c,...l}=this.#e;this.#c=Object.freeze(l)}return this.#c}#b(e){this.#c=void 0,this.request=e}#a(e){return this.#x.get(e)??this.request}#w(e,t){return this.#x.set(e,t),e}#I(e,t){return!this.#e.onUploadProgress||!e.body||!qe?e:vt(e,this.#e.onUploadProgress,t??this.#e.body??void 0)}};var Fe=r=>{let e=(t,i)=>Q.create(t,Y(r,i));for(let t of oe)e[t]=(i,s)=>Q.create(i,Y(r,s,{method:t}));return e.create=t=>Fe(Y(t)),e.extend=t=>(typeof t=="function"&&(t=t(r??{})),Fe(Y(r,t))),e.stop=ae,e.retry=At,e},Vr=Fe(),Ut=Vr;async function Jt({cliOptions:r={},env:e=process.env,readConfig:t=B,requireSecretKey:i=!0}={}){let s=await t(),n=r.baseUrl||e.ENGAGELAB_EMAIL_BASE_URL||s.baseUrl,o=r.secretKey||e.ENGAGELAB_EMAIL_SECRET_KEY||s.secretKey;if(!n)throw re("Missing base URL. Set --base-url, ENGAGELAB_EMAIL_BASE_URL, or config set.");if(i&&!o)throw re("Missing Secret Key. Set --secret-key, ENGAGELAB_EMAIL_SECRET_KEY, or config set.");if(i&&!o.startsWith("sk_"))throw re("Secret Key must start with sk_");return{baseUrl:n,secretKey:o}}async function O(r){let e=await Jt({cliOptions:r.optsWithGlobals()});return Ut.extend({prefix:Lr(e.baseUrl),headers:{Authorization:`Bearer ${e.secretKey}`},timeout:3e4,throwHttpErrors:!1})}function x(r,e,t){r.opts().json&&r.parent?.parent?.stdout?.write?.("");let i=r.programOutput?.stdout||process.stdout;if(r.opts().json){i.write(`${JSON.stringify(e,null,2)}
20
+ `),this.outputHelp({error:!0}));let i=t||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in F.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()}`,F.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new cn(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"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 i=o=>{let a=o.attributeName(),u=this.getOptionValue(a),l=this.options.find(f=>f.negate&&a===f.attributeName()),h=this.options.find(f=>!f.negate&&a===f.attributeName());return l&&(l.presetArg===void 0&&u===!1||l.presetArg!==void 0&&u===l.presetArg)?l:h||o},n=o=>{let a=i(o),u=a.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(o),s=s.parent}while(s&&!s._enablePositionalOptions);t=kt(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),t=kt(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),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 i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}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(i=>an(i));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=I.basename(e,I.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=n=>this._outputConfiguration.writeErr(n):i=n=>this._outputConfiguration.writeOut(n),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation(i);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),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=F.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
+ Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,s=>{let o;typeof t=="function"?o=t({error:s.error,command:s.command}):o=t,o&&s.write(`${o}
23
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function $t(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",n="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])?n=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],n=s[4]),t&&n!=="0"?`${t}=${i}:${parseInt(n)+1}`:e})}jt.Command=Qe});var Nt=b(S=>{var{Argument:Mt}=Fe(),{Command:et}=qt(),{CommanderError:hn,InvalidArgumentError:It}=se(),{Help:Dn}=Ue(),{Option:Lt}=Ke();S.program=new et;S.createCommand=r=>new et(r);S.createOption=(r,e)=>new Lt(r,e);S.createArgument=(r,e)=>new Mt(r,e);S.Command=et;S.Option=Lt;S.Argument=Mt;S.Help=Dn;S.CommanderError=hn;S.InvalidArgumentError=It;S.InvalidOptionArgumentError=It});var Ae=b((Do,nt)=>{var xe=process||{},Qt=xe.argv||[],we=xe.env||{},mn=!(we.NO_COLOR||Qt.includes("--no-color"))&&(!!we.FORCE_COLOR||Qt.includes("--color")||xe.platform==="win32"||(xe.stdout||{}).isTTY&&we.TERM!=="dumb"||!!we.CI),pn=(r,e,t=r)=>i=>{let n=""+i,s=n.indexOf(e,r.length);return~s?r+gn(n,e,t,s)+e:r+n+e},gn=(r,e,t,i)=>{let n="",s=0;do n+=r.substring(s,i)+t,s=i+e.length,i=r.indexOf(e,s);while(~i);return n+r.substring(s)},er=(r=mn)=>{let e=r?pn:()=>String;return{isColorSupported:r,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};nt.exports=er();nt.exports.createColors=er});var _e=b((po,ir)=>{var st=[],rr=0,w=(r,e)=>{rr>=e&&st.push(r)};w.WARN=1;w.INFO=2;w.DEBUG=3;w.reset=()=>{st=[]};w.setDebugLevel=r=>{rr=r};w.warn=r=>w(r,w.WARN);w.info=r=>w(r,w.INFO);w.debug=r=>w(r,w.DEBUG);w.debugMessages=()=>st;ir.exports=w});var sr=b((go,nr)=>{"use strict";nr.exports=({onlyFirst:r=!1}={})=>{let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,r?void 0:"g")}});var ur=b((Co,or)=>{"use strict";var Cn=sr();or.exports=r=>typeof r=="string"?r.replace(Cn(),""):r});var lr=b((bo,ot)=>{"use strict";var ar=r=>Number.isNaN(r)?!1:r>=4352&&(r<=4447||r===9001||r===9002||11904<=r&&r<=12871&&r!==12351||12880<=r&&r<=19903||19968<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65131||65281<=r&&r<=65376||65504<=r&&r<=65510||110592<=r&&r<=110593||127488<=r&&r<=127569||131072<=r&&r<=262141);ot.exports=ar;ot.exports.default=ar});var hr=b((Eo,cr)=>{"use strict";cr.exports=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g}});var fr=b((Fo,ut)=>{"use strict";var bn=ur(),En=lr(),Fn=hr(),Dr=r=>{if(typeof r!="string"||r.length===0||(r=bn(r),r.length===0))return 0;r=r.replace(Fn()," ");let e=0;for(let t=0;t<r.length;t++){let i=r.codePointAt(t);i<=31||i>=127&&i<=159||i>=768&&i<=879||(i>65535&&t++,e+=En(i)?2:1)}return e};ut.exports=Dr;ut.exports.default=Dr});var at=b((yo,gr)=>{var dr=fr();function Oe(r){return r?/\u001b\[((?:\d*;){0,5}\d*)m/g:/\u001b\[(?:\d*;){0,5}\d*m/g}function $(r){let e=Oe();return(""+r).replace(e,"").split(`
24
+ `).reduce(function(n,s){return dr(s)>n?dr(s):n},0)}function le(r,e){return Array(e+1).join(r)}function yn(r,e,t,i){let n=$(r);if(e+1>=n){let s=e-n;switch(i){case"right":{r=le(t,s)+r;break}case"center":{let o=Math.ceil(s/2),a=s-o;r=le(t,a)+r+le(t,o);break}default:{r=r+le(t,s);break}}}return r}var Y={};function ce(r,e,t){e="\x1B["+e+"m",t="\x1B["+t+"m",Y[e]={set:r,to:!0},Y[t]={set:r,to:!1},Y[r]={on:e,off:t}}ce("bold",1,22);ce("italics",3,23);ce("underline",4,24);ce("inverse",7,27);ce("strikethrough",9,29);function mr(r,e){let t=e[1]?parseInt(e[1].split(";")[0]):0;if(t>=30&&t<=39||t>=90&&t<=97){r.lastForegroundAdded=e[0];return}if(t>=40&&t<=49||t>=100&&t<=107){r.lastBackgroundAdded=e[0];return}if(t===0){for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return}let i=Y[e[0]];i&&(r[i.set]=i.to)}function wn(r){let e=Oe(!0),t=e.exec(r),i={};for(;t!==null;)mr(i,t),t=e.exec(r);return i}function pr(r,e){let t=r.lastBackgroundAdded,i=r.lastForegroundAdded;return delete r.lastBackgroundAdded,delete r.lastForegroundAdded,Object.keys(r).forEach(function(n){r[n]&&(e+=Y[n].off)}),t&&t!="\x1B[49m"&&(e+="\x1B[49m"),i&&i!="\x1B[39m"&&(e+="\x1B[39m"),e}function xn(r,e){let t=r.lastBackgroundAdded,i=r.lastForegroundAdded;return delete r.lastBackgroundAdded,delete r.lastForegroundAdded,Object.keys(r).forEach(function(n){r[n]&&(e=Y[n].on+e)}),t&&t!="\x1B[49m"&&(e=t+e),i&&i!="\x1B[39m"&&(e=i+e),e}function An(r,e){if(r.length===$(r))return r.substr(0,e);for(;$(r)>e;)r=r.slice(0,-1);return r}function _n(r,e){let t=Oe(!0),i=r.split(Oe()),n=0,s=0,o="",a,u={};for(;s<e;){a=t.exec(r);let l=i[n];if(n++,s+$(l)>e&&(l=An(l,e-s)),o+=l,s+=$(l),s<e){if(!a)break;o+=a[0],mr(u,a)}}return pr(u,o)}function On(r,e,t){if(t=t||"\u2026",$(r)<=e)return r;e-=$(t);let n=_n(r,e);n+=t;let s="\x1B]8;;\x07";return r.includes(s)&&!n.includes(s)&&(n+=s),n}function Sn(){return{chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},truncate:"\u2026",colWidths:[],rowHeights:[],colAligns:[],rowAligns:[],style:{"padding-left":1,"padding-right":1,head:["red"],border:["grey"],compact:!1},head:[]}}function Bn(r,e){r=r||{},e=e||Sn();let t=Object.assign({},e,r);return t.chars=Object.assign({},e.chars,r.chars),t.style=Object.assign({},e.style,r.style),t}function Rn(r,e){let t=[],i=e.split(/(\s+)/g),n=[],s=0,o;for(let a=0;a<i.length;a+=2){let u=i[a],l=s+$(u);s>0&&o&&(l+=o.length),l>r?(s!==0&&t.push(n.join("")),n=[u],s=$(u)):(n.push(o||"",u),s=l),o=i[a+1]}return s&&t.push(n.join("")),t}function Tn(r,e){let t=[],i="";function n(o,a){for(i.length&&a&&(i+=a),i+=o;i.length>r;)t.push(i.slice(0,r)),i=i.slice(r)}let s=e.split(/(\s+)/g);for(let o=0;o<s.length;o+=2)n(s[o],o&&s[o-1]);return i.length&&t.push(i),t}function vn(r,e,t=!0){let i=[];e=e.split(`
25
+ `);let n=t?Rn:Tn;for(let s=0;s<e.length;s++)i.push.apply(i,n(r,e[s]));return i}function kn(r){let e={},t=[];for(let i=0;i<r.length;i++){let n=xn(e,r[i]);e=wn(n);let s=Object.assign({},e);t.push(pr(s,n))}return t}function $n(r,e){return["\x1B]","8",";",";",r||e,"\x07",e,"\x1B]","8",";",";","\x07"].join("")}gr.exports={strlen:$,repeat:le,pad:yn,truncate:On,mergeOptions:Bn,wordWrap:vn,colorizeLines:kn,hyperlink:$n}});var Fr=b((wo,Er)=>{var br={};Er.exports=br;var Cr={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(Cr).forEach(function(r){var e=Cr[r],t=br[r]=[];t.open="\x1B["+e[0]+"m",t.close="\x1B["+e[1]+"m"})});var wr=b((xo,yr)=>{"use strict";yr.exports=function(r,e){e=e||process.argv;var t=e.indexOf("--"),i=/^-{1,2}/.test(r)?"":"--",n=e.indexOf(i+r);return n!==-1&&(t===-1?!0:n<t)}});var Ar=b((Ao,xr)=>{"use strict";var jn=require("os"),v=wr(),A=process.env,X=void 0;v("no-color")||v("no-colors")||v("color=false")?X=!1:(v("color")||v("colors")||v("color=true")||v("color=always"))&&(X=!0);"FORCE_COLOR"in A&&(X=A.FORCE_COLOR.length===0||parseInt(A.FORCE_COLOR,10)!==0);function qn(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Mn(r){if(X===!1)return 0;if(v("color=16m")||v("color=full")||v("color=truecolor"))return 3;if(v("color=256"))return 2;if(r&&!r.isTTY&&X!==!0)return 0;var e=X?1:0;if(process.platform==="win32"){var t=jn.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in A)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(n){return n in A})||A.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in A)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(A.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in A){var i=parseInt((A.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(A.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(A.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(A.TERM)||"COLORTERM"in A?1:(A.TERM==="dumb",e)}function lt(r){var e=Mn(r);return qn(e)}xr.exports={supportsColor:lt,stdout:lt(process.stdout),stderr:lt(process.stderr)}});var Or=b((_o,_r)=>{_r.exports=function(e,t){var i="";e=e||"Run the trap, drop the bass",e=e.split("");var n={a:["@","\u0104","\u023A","\u0245","\u0394","\u039B","\u0414"],b:["\xDF","\u0181","\u0243","\u026E","\u03B2","\u0E3F"],c:["\xA9","\u023B","\u03FE"],d:["\xD0","\u018A","\u0500","\u0501","\u0502","\u0503"],e:["\xCB","\u0115","\u018E","\u0258","\u03A3","\u03BE","\u04BC","\u0A6C"],f:["\u04FA"],g:["\u0262"],h:["\u0126","\u0195","\u04A2","\u04BA","\u04C7","\u050A"],i:["\u0F0F"],j:["\u0134"],k:["\u0138","\u04A0","\u04C3","\u051E"],l:["\u0139"],m:["\u028D","\u04CD","\u04CE","\u0520","\u0521","\u0D69"],n:["\xD1","\u014B","\u019D","\u0376","\u03A0","\u048A"],o:["\xD8","\xF5","\xF8","\u01FE","\u0298","\u047A","\u05DD","\u06DD","\u0E4F"],p:["\u01F7","\u048E"],q:["\u09CD"],r:["\xAE","\u01A6","\u0210","\u024C","\u0280","\u042F"],s:["\xA7","\u03DE","\u03DF","\u03E8"],t:["\u0141","\u0166","\u0373"],u:["\u01B1","\u054D"],v:["\u05D8"],w:["\u0428","\u0460","\u047C","\u0D70"],x:["\u04B2","\u04FE","\u04FC","\u04FD"],y:["\xA5","\u04B0","\u04CB"],z:["\u01B5","\u0240"]};return e.forEach(function(s){s=s.toLowerCase();var o=n[s]||[" "],a=Math.floor(Math.random()*o.length);typeof n[s]<"u"?i+=n[s][a]:i+=s}),i}});var Br=b((Oo,Sr)=>{Sr.exports=function(e,t){e=e||" he is here ";var i={up:["\u030D","\u030E","\u0304","\u0305","\u033F","\u0311","\u0306","\u0310","\u0352","\u0357","\u0351","\u0307","\u0308","\u030A","\u0342","\u0313","\u0308","\u034A","\u034B","\u034C","\u0303","\u0302","\u030C","\u0350","\u0300","\u0301","\u030B","\u030F","\u0312","\u0313","\u0314","\u033D","\u0309","\u0363","\u0364","\u0365","\u0366","\u0367","\u0368","\u0369","\u036A","\u036B","\u036C","\u036D","\u036E","\u036F","\u033E","\u035B","\u0346","\u031A"],down:["\u0316","\u0317","\u0318","\u0319","\u031C","\u031D","\u031E","\u031F","\u0320","\u0324","\u0325","\u0326","\u0329","\u032A","\u032B","\u032C","\u032D","\u032E","\u032F","\u0330","\u0331","\u0332","\u0333","\u0339","\u033A","\u033B","\u033C","\u0345","\u0347","\u0348","\u0349","\u034D","\u034E","\u0353","\u0354","\u0355","\u0356","\u0359","\u035A","\u0323"],mid:["\u0315","\u031B","\u0300","\u0301","\u0358","\u0321","\u0322","\u0327","\u0328","\u0334","\u0335","\u0336","\u035C","\u035D","\u035E","\u035F","\u0360","\u0362","\u0338","\u0337","\u0361"," \u0489"]},n=[].concat(i.up,i.down,i.mid);function s(u){var l=Math.floor(Math.random()*u);return l}function o(u){var l=!1;return n.filter(function(h){l=h===u}),l}function a(u,l){var h="",f,m;l=l||{},l.up=typeof l.up<"u"?l.up:!0,l.mid=typeof l.mid<"u"?l.mid:!0,l.down=typeof l.down<"u"?l.down:!0,l.size=typeof l.size<"u"?l.size:"maxi",u=u.split("");for(m in u)if(!o(m)){switch(h=h+u[m],f={up:0,down:0,mid:0},l.size){case"mini":f.up=s(8),f.mid=s(2),f.down=s(8);break;case"maxi":f.up=s(16)+3,f.mid=s(4)+1,f.down=s(64)+3;break;default:f.up=s(8)+1,f.mid=s(6)/2,f.down=s(8)+1;break}var D=["up","mid","down"];for(var c in D)for(var d=D[c],p=0;p<=f[d];p++)l[d]&&(h=h+i[d][s(i[d].length)])}return h}return a(e,t)}});var Tr=b((So,Rr)=>{Rr.exports=function(r){return function(e,t,i){if(e===" ")return e;switch(t%3){case 0:return r.red(e);case 1:return r.white(e);case 2:return r.blue(e)}}}});var kr=b((Bo,vr)=>{vr.exports=function(r){return function(e,t,i){return t%2===0?e:r.inverse(e)}}});var jr=b((Ro,$r)=>{$r.exports=function(r){var e=["red","yellow","green","blue","magenta"];return function(t,i,n){return t===" "?t:r[e[i++%e.length]](t)}}});var Mr=b((To,qr)=>{qr.exports=function(r){var e=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(t,i,n){return t===" "?t:r[e[Math.round(Math.random()*(e.length-2))]](t)}}});var Vr=b((ko,Pr)=>{var g={};Pr.exports=g;g.themes={};var In=require("util"),W=g.styles=Fr(),Lr=Object.defineProperties,Ln=new RegExp(/[\r\n]+/g);g.supportsColor=Ar().supportsColor;typeof g.enabled>"u"&&(g.enabled=g.supportsColor()!==!1);g.enable=function(){g.enabled=!0};g.disable=function(){g.enabled=!1};g.stripColors=g.strip=function(r){return(""+r).replace(/\x1B\[\d+m/g,"")};var vo=g.stylize=function(e,t){if(!g.enabled)return e+"";var i=W[t];return!i&&t in g?g[t](e):i.open+e+i.close},Nn=/[|\\{}()[\]^$+*?.]/g,Hn=function(r){if(typeof r!="string")throw new TypeError("Expected a string");return r.replace(Nn,"\\$&")};function Nr(r){var e=function t(){return Vn.apply(t,arguments)};return e._styles=r,e.__proto__=Pn,e}var Hr=(function(){var r={};return W.grey=W.gray,Object.keys(W).forEach(function(e){W[e].closeRe=new RegExp(Hn(W[e].close),"g"),r[e]={get:function(){return Nr(this._styles.concat(e))}}}),r})(),Pn=Lr(function(){},Hr);function Vn(){var r=Array.prototype.slice.call(arguments),e=r.map(function(o){return o!=null&&o.constructor===String?o:In.inspect(o)}).join(" ");if(!g.enabled||!e)return e;for(var t=e.indexOf(`
26
+ `)!=-1,i=this._styles,n=i.length;n--;){var s=W[i[n]];e=s.open+e.replace(s.closeRe,s.open)+s.close,t&&(e=e.replace(Ln,function(o){return s.close+o+s.open}))}return e}g.setTheme=function(r){if(typeof r=="string"){console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");return}for(var e in r)(function(t){g[t]=function(i){if(typeof r[t]=="object"){var n=i;for(var s in r[t])n=g[r[t][s]](n);return n}return g[r[t]](i)}})(e)};function Wn(){var r={};return Object.keys(Hr).forEach(function(e){r[e]={get:function(){return Nr([e])}}}),r}var Un=function(e,t){var i=t.split("");return i=i.map(e),i.join("")};g.trap=Or();g.zalgo=Br();g.maps={};g.maps.america=Tr()(g);g.maps.zebra=kr()(g);g.maps.rainbow=jr()(g);g.maps.random=Mr()(g);for(Ir in g.maps)(function(r){g[r]=function(e){return Un(g.maps[r],e)}})(Ir);var Ir;Lr(g,Wn())});var Ur=b(($o,Wr)=>{var Gn=Vr();Wr.exports=Gn});var Kr=b((jo,Se)=>{var{info:Jn,debug:zr}=_e(),O=at(),ht=class r{constructor(e){this.setOptions(e),this.x=null,this.y=null}setOptions(e){["boolean","number","bigint","string"].indexOf(typeof e)!==-1&&(e={content:""+e}),e=e||{},this.options=e;let t=e.content;if(["boolean","number","bigint","string"].indexOf(typeof t)!==-1)this.content=String(t);else if(!t)this.content=this.options.href||"";else throw new Error("Content needs to be a primitive, got: "+typeof t);this.colSpan=e.colSpan||1,this.rowSpan=e.rowSpan||1,this.options.href&&Object.defineProperty(this,"href",{get(){return this.options.href}})}mergeTableOptions(e,t){this.cells=t;let i=this.options.chars||{},n=e.chars,s=this.chars={};Kn.forEach(function(u){ct(i,n,u,s)}),this.truncate=this.options.truncate||e.truncate;let o=this.options.style=this.options.style||{},a=e.style;ct(o,a,"padding-left",this),ct(o,a,"padding-right",this),this.head=o.head||a.head,this.border=o.border||a.border,this.fixedWidth=e.colWidths[this.x],this.lines=this.computeLines(e),this.desiredWidth=O.strlen(this.content)+this.paddingLeft+this.paddingRight,this.desiredHeight=this.lines.length}computeLines(e){let t=e.wordWrap||e.textWrap,{wordWrap:i=t}=this.options;if(this.fixedWidth&&i){if(this.fixedWidth-=this.paddingLeft+this.paddingRight,this.colSpan){let o=1;for(;o<this.colSpan;)this.fixedWidth+=e.colWidths[this.x+o],o++}let{wrapOnWordBoundary:n=!0}=e,{wrapOnWordBoundary:s=n}=this.options;return this.wrapLines(O.wordWrap(this.fixedWidth,this.content,s))}return this.wrapLines(this.content.split(`
27
+ `))}wrapLines(e){let t=O.colorizeLines(e);return this.href?t.map(i=>O.hyperlink(this.href,i)):t}init(e){let t=this.x,i=this.y;this.widths=e.colWidths.slice(t,t+this.colSpan),this.heights=e.rowHeights.slice(i,i+this.rowSpan),this.width=this.widths.reduce(Jr,-1),this.height=this.heights.reduce(Jr,-1),this.hAlign=this.options.hAlign||e.colAligns[t],this.vAlign=this.options.vAlign||e.rowAligns[i],this.drawRight=t+this.colSpan==e.colWidths.length}draw(e,t){if(e=="top")return this.drawTop(this.drawRight);if(e=="bottom")return this.drawBottom(this.drawRight);let i=O.truncate(this.content,10,this.truncate);e||Jn(`${this.y}-${this.x}: ${this.rowSpan-e}x${this.colSpan} Cell ${i}`);let n=Math.max(this.height-this.lines.length,0),s;switch(this.vAlign){case"center":s=Math.ceil(n/2);break;case"bottom":s=n;break;default:s=0}if(e<s||e>=s+this.lines.length)return this.drawEmpty(this.drawRight,t);let o=this.lines.length>this.height&&e+1>=this.height;return this.drawLine(e-s,this.drawRight,o,t)}drawTop(e){let t=[];return this.cells?this.widths.forEach(function(i,n){t.push(this._topLeftChar(n)),t.push(O.repeat(this.chars[this.y==0?"top":"mid"],i))},this):(t.push(this._topLeftChar(0)),t.push(O.repeat(this.chars[this.y==0?"top":"mid"],this.width))),e&&t.push(this.chars[this.y==0?"topRight":"rightMid"]),this.wrapWithStyleColors("border",t.join(""))}_topLeftChar(e){let t=this.x+e,i;if(this.y==0)i=t==0?"topLeft":e==0?"topMid":"top";else if(t==0)i="leftMid";else if(i=e==0?"midMid":"bottomMid",this.cells&&(this.cells[this.y-1][t]instanceof r.ColSpanCell&&(i=e==0?"topMid":"mid"),e==0)){let s=1;for(;this.cells[this.y][t-s]instanceof r.ColSpanCell;)s++;this.cells[this.y][t-s]instanceof r.RowSpanCell&&(i="leftMid")}return this.chars[i]}wrapWithStyleColors(e,t){if(this[e]&&this[e].length)try{let i=Ur();for(let n=this[e].length-1;n>=0;n--)i=i[this[e][n]];return i(t)}catch{return t}else return t}drawLine(e,t,i,n){let s=this.chars[this.x==0?"left":"middle"];if(this.x&&n&&this.cells){let m=this.cells[this.y+n][this.x-1];for(;m instanceof he;)m=this.cells[m.y][m.x-1];m instanceof De||(s=this.chars.rightMid)}let o=O.repeat(" ",this.paddingLeft),a=t?this.chars.right:"",u=O.repeat(" ",this.paddingRight),l=this.lines[e],h=this.width-(this.paddingLeft+this.paddingRight);i&&(l+=this.truncate||"\u2026");let f=O.truncate(l,h,this.truncate);return f=O.pad(f,h," ",this.hAlign),f=o+f+u,this.stylizeLine(s,f,a)}stylizeLine(e,t,i){return e=this.wrapWithStyleColors("border",e),i=this.wrapWithStyleColors("border",i),this.y===0&&(t=this.wrapWithStyleColors("head",t)),e+t+i}drawBottom(e){let t=this.chars[this.x==0?"bottomLeft":"bottomMid"],i=O.repeat(this.chars.bottom,this.width),n=e?this.chars.bottomRight:"";return this.wrapWithStyleColors("border",t+i+n)}drawEmpty(e,t){let i=this.chars[this.x==0?"left":"middle"];if(this.x&&t&&this.cells){let o=this.cells[this.y+t][this.x-1];for(;o instanceof he;)o=this.cells[o.y][o.x-1];o instanceof De||(i=this.chars.rightMid)}let n=e?this.chars.right:"",s=O.repeat(" ",this.width);return this.stylizeLine(i,s,n)}},he=class{constructor(){}draw(e){return typeof e=="number"&&zr(`${this.y}-${this.x}: 1x1 ColSpanCell`),""}init(){}mergeTableOptions(){}},De=class{constructor(e){this.originalCell=e}init(e){let t=this.y,i=this.originalCell.y;this.cellOffset=t-i,this.offset=zn(e.rowHeights,i,this.cellOffset)}draw(e){return e=="top"?this.originalCell.draw(this.offset,this.cellOffset):e=="bottom"?this.originalCell.draw("bottom"):(zr(`${this.y}-${this.x}: 1x${this.colSpan} RowSpanCell for ${this.originalCell.content}`),this.originalCell.draw(this.offset+1+e))}mergeTableOptions(){}};function Gr(...r){return r.filter(e=>e!=null).shift()}function ct(r,e,t,i){let n=t.split("-");n.length>1?(n[1]=n[1].charAt(0).toUpperCase()+n[1].substr(1),n=n.join(""),i[n]=Gr(r[n],r[t],e[n],e[t])):i[t]=Gr(r[t],e[t])}function zn(r,e,t){let i=r[e];for(let n=1;n<t;n++)i+=1+r[e+n];return i}function Jr(r,e){return r+e+1}var Kn=["top","top-mid","top-left","top-right","bottom","bottom-mid","bottom-left","bottom-right","left","left-mid","mid","mid-mid","right","right-mid","middle"];Se.exports=ht;Se.exports.ColSpanCell=he;Se.exports.RowSpanCell=De});var Zr=b((qo,Xr)=>{var{warn:Yn,debug:Xn}=_e(),Dt=Kr(),{ColSpanCell:Zn,RowSpanCell:Qn}=Dt;(function(){function r(D,c){return D[c]>0?r(D,c+1):c}function e(D){let c={};D.forEach(function(d,p){let E=0;d.forEach(function(C){C.y=p,C.x=p?r(c,E):E;let x=C.rowSpan||1,_=C.colSpan||1;if(x>1)for(let ne=0;ne<_;ne++)c[C.x+ne]=x;E=C.x+_}),Object.keys(c).forEach(C=>{c[C]--,c[C]<1&&delete c[C]})})}function t(D){let c=0;return D.forEach(function(d){d.forEach(function(p){c=Math.max(c,p.x+(p.colSpan||1))})}),c}function i(D){return D.length}function n(D,c){let d=D.y,p=D.y-1+(D.rowSpan||1),E=c.y,C=c.y-1+(c.rowSpan||1),x=!(d>C||E>p),_=D.x,ne=D.x-1+(D.colSpan||1),Pi=c.x,Vi=c.x-1+(c.colSpan||1),Wi=!(_>Vi||Pi>ne);return x&&Wi}function s(D,c,d){let p=Math.min(D.length-1,d),E={x:c,y:d};for(let C=0;C<=p;C++){let x=D[C];for(let _=0;_<x.length;_++)if(n(E,x[_]))return!0}return!1}function o(D,c,d,p){for(let E=d;E<p;E++)if(s(D,E,c))return!1;return!0}function a(D){D.forEach(function(c,d){c.forEach(function(p){for(let E=1;E<p.rowSpan;E++){let C=new Qn(p);C.x=p.x,C.y=p.y+E,C.colSpan=p.colSpan,l(C,D[d+E])}})})}function u(D){for(let c=D.length-1;c>=0;c--){let d=D[c];for(let p=0;p<d.length;p++){let E=d[p];for(let C=1;C<E.colSpan;C++){let x=new Zn;x.x=E.x+C,x.y=E.y,d.splice(p+1,0,x)}}}}function l(D,c){let d=0;for(;d<c.length&&c[d].x<D.x;)d++;c.splice(d,0,D)}function h(D){let c=i(D),d=t(D);Xn(`Max rows: ${c}; Max cols: ${d}`);for(let p=0;p<c;p++)for(let E=0;E<d;E++)if(!s(D,E,p)){let C={x:E,y:p,colSpan:1,rowSpan:1};for(E++;E<d&&!s(D,E,p);)C.colSpan++,E++;let x=p+1;for(;x<c&&o(D,x,C.x,C.x+C.colSpan);)C.rowSpan++,x++;let _=new Dt(C);_.x=C.x,_.y=C.y,Yn(`Missing cell at ${_.y}-${_.x}.`),l(_,D[p])}}function f(D){return D.map(function(c){if(!Array.isArray(c)){let d=Object.keys(c)[0];c=c[d],Array.isArray(c)?(c=c.slice(),c.unshift(d)):c=[d,c]}return c.map(function(d){return new Dt(d)})})}function m(D){let c=f(D);return e(c),h(c),a(c),u(c),c}Xr.exports={makeTableLayout:m,layoutTable:e,addRowSpanCells:a,maxWidth:t,fillInTable:h,computeWidths:Yr("colSpan","desiredWidth","x",1),computeHeights:Yr("rowSpan","desiredHeight","y",1)}})();function Yr(r,e,t,i){return function(n,s){let o=[],a=[],u={};s.forEach(function(l){l.forEach(function(h){(h[r]||1)>1?a.push(h):o[h[t]]=Math.max(o[h[t]]||0,h[e]||0,i)})}),n.forEach(function(l,h){typeof l=="number"&&(o[h]=l)});for(let l=a.length-1;l>=0;l--){let h=a[l],f=h[r],m=h[t],D=o[m],c=typeof n[m]=="number"?0:1;if(typeof D=="number")for(let d=1;d<f;d++)D+=1+o[m+d],typeof n[m+d]!="number"&&c++;else D=e==="desiredWidth"?h.desiredWidth-1:1,(!u[m]||u[m]<D)&&(u[m]=D);if(h[e]>D){let d=0;for(;c>0&&h[e]>D;){if(typeof n[m+d]!="number"){let p=Math.round((h[e]-D)/c);D+=p,o[m+d]+=p,c--}d++}}}Object.assign(n,o,u);for(let l=0;l<n.length;l++)n[l]=Math.max(i,n[l]||0)}}});var ei=b((Mo,Qr)=>{var L=_e(),es=at(),ft=Zr(),Be=class extends Array{constructor(e){super();let t=es.mergeOptions(e);if(Object.defineProperty(this,"options",{value:t,enumerable:t.debug}),t.debug){switch(typeof t.debug){case"boolean":L.setDebugLevel(L.WARN);break;case"number":L.setDebugLevel(t.debug);break;case"string":L.setDebugLevel(parseInt(t.debug,10));break;default:L.setDebugLevel(L.WARN),L.warn(`Debug option is expected to be boolean, number, or string. Received a ${typeof t.debug}`)}Object.defineProperty(this,"messages",{get(){return L.debugMessages()}})}}toString(){let e=this,t=this.options.head&&this.options.head.length;t?(e=[this.options.head],this.length&&e.push.apply(e,this)):this.options.style.head=[];let i=ft.makeTableLayout(e);i.forEach(function(s){s.forEach(function(o){o.mergeTableOptions(this.options,i)},this)},this),ft.computeWidths(this.options.colWidths,i),ft.computeHeights(this.options.rowHeights,i),i.forEach(function(s){s.forEach(function(o){o.init(this.options)},this)},this);let n=[];for(let s=0;s<i.length;s++){let o=i[s],a=this.options.rowHeights[s];(s===0||!this.options.style.compact||s==1&&t)&&dt(o,"top",n);for(let u=0;u<a;u++)dt(o,u,n);s+1==i.length&&dt(o,"bottom",n)}return n.join(`
28
+ `)}get width(){return this.toString().split(`
29
+ `)[0].length}};Be.reset=()=>L.reset();function dt(r,e,t){let i=[];r.forEach(function(s){i.push(s.draw(e))});let n=i.join("");n.length&&t.push(n)}Qr.exports=Be});var ri=b((Io,ti)=>{ti.exports=ei()});var Ht=V(Nt(),1),{program:zs,createCommand:Ks,createArgument:Ys,createOption:Xs,CommanderError:Zs,InvalidArgumentError:Qs,InvalidOptionArgumentError:eo,Command:Pt,Argument:to,Option:ro,Help:io}=Ht.default;var J=require("node:fs/promises"),oe=V(require("node:path"),1),tt=V(require("node:os"),1);async function ue({configPath:r=Wt()}={}){try{return JSON.parse(await(0,J.readFile)(r,"utf8"))}catch(e){if(e.code==="ENOENT")return{};throw e}}async function Vt(r,{configPath:e=Wt()}={}){await(0,J.mkdir)(oe.default.dirname(e),{recursive:!0}),await(0,J.writeFile)(e,`${JSON.stringify(r,null,2)}
30
+ `,{encoding:"utf8",mode:384})}function Wt(r=process.env,e=process.platform){if(r.ENGAGELAB_EMAIL_CONFIG)return r.ENGAGELAB_EMAIL_CONFIG;let t=r.XDG_CONFIG_HOME||(e==="win32"?r.APPDATA||oe.default.join(tt.default.homedir(),"AppData","Roaming"):oe.default.join(tt.default.homedir(),".config"));return oe.default.join(t,"engagelab-email-cli","config.json")}function Ut(r){return r?`${r.slice(0,7)}****`:""}var T=class extends Error{constructor(e,{code:t="cli_error",exitCode:i=1,status:n,data:s,cause:o}={}){super(e,{cause:o}),this.name="CliError",this.code=t,this.exitCode=i,this.status=n,this.data=s}};function rt(r){return r===401||r===403?2:r===404?3:r===409?4:5}function Gt(r){return r instanceof T?r:new T(r?.message||"Command failed",{code:"unknown_error",exitCode:5,cause:r})}function y(r){return new T(r,{code:"validation_error",exitCode:1})}function ye(r){return new T(r,{code:"config_error",exitCode:1})}function Jt(r){let e=r.command("config").description("Manage local EngageLab Email CLI config");e.command("set").description("Save local CLI configuration").option("--base-url <url>","EngageLab Email API base URL").option("--secret-key <key>","EngageLab Email Secret Key").action(async(t,i)=>{if(t={...i.optsWithGlobals(),...t},!t.baseUrl&&!t.secretKey)throw y("Provide at least one of --base-url or --secret-key");if(t.secretKey&&!t.secretKey.startsWith("sk_"))throw y("Secret Key must start with sk_");let n=await ue();await Vt({...n,...fn(t)}),process.stdout.write(`Config saved
31
+ `)}),e.command("list").description("Show local CLI configuration").action(async()=>{let t=await ue();process.stdout.write(`baseUrl: ${t.baseUrl||""}
32
+ `),process.stdout.write(`secretKey: ${Ut(t.secretKey)}
33
+ `)})}function fn(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var Yt=require("node:fs/promises");var Xt=new Set(["bodyFile","bodyJson"]),Zt=[["text","textFile"],["html","htmlFile"]];async function it(r={},{readFile:e=Yt.readFile}={}){if(dn(r),r.bodyFile)return zt(await e(r.bodyFile,"utf8"),`Invalid JSON in ${r.bodyFile}`);if(r.bodyJson)return zt(r.bodyJson,"Invalid JSON in --body-json");let t={};for(let[i,n]of Object.entries(r))Xt.has(i)||i.endsWith("File")||n===void 0||(t[i]=n);for(let[i,n]of Zt)r[n]&&(t[i]=await e(r[n],"utf8"));return t}function dn(r){if(r.bodyFile&&r.bodyJson)throw y("--body-file and --body-json are mutually exclusive");if((r.bodyFile||r.bodyJson)&&Object.entries(r).filter(([t,i])=>i!==void 0&&!Xt.has(t)).length>0)throw y("--body-file/--body-json cannot be combined with field-level body options");for(let[e,t]of Zt)if(r[e]&&r[t])throw y(`--${Kt(e)} and --${Kt(t)} are mutually exclusive`)}function zt(r,e){try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("JSON body must be an object");return t}catch(t){throw y(`${e}: ${t.message}`)}}function Kt(r){return r.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}var H=V(Ae(),1);function B(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<=0)throw y("Expected a positive integer");return e}function ae(r){let e=Number.parseInt(r,10);if(!Number.isInteger(e)||e<0)throw y("Expected a non-negative integer");return e}function z(r,e=[]){return[...e,r]}function tr(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!=null&&e!==""))}function K(r,e){if(r==null||r==="")throw y(e);return r}var oi=V(Ae(),1);var ii=V(ri(),1),mt=V(Ae(),1);function pt(r,e){if(!r||r.length===0)return mt.default.dim("No results");let t=new ii.default({head:e.map(i=>mt.default.bold(i.header)),style:{border:[],head:[]},chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"}});return t.push(...r.map(i=>e.map(n=>ts(n.value(i))))),t.toString()}function ts(r){return Array.isArray(r)?r.join(", "):r==null?"":String(r)}function ni(r){return{0:"received",1:"parsing",2:"parsed",3:"parse_failed",4:"replied"}[r]??r}function si(r){return{0:"pending",1:"processing",2:"done",3:"failed"}[r]??r}function ui(r){return pt(r.data?.list||[],[{header:"Thread ID",value:e=>e.threadId},{header:"Subject",value:e=>e.subject},{header:"Participants",value:e=>e.participants},{header:"Last Message",value:e=>e.lastMessageAt},{header:"Count",value:e=>e.messageCount},{header:"Status",value:e=>e.status}])}function Re(r){return pt(r.data?.list||r.data||[],[{header:"Message UID",value:e=>e.messageUid},{header:"Thread ID",value:e=>e.threadId},{header:"From",value:e=>e.fromEmail||e.envelopeFrom},{header:"Subject",value:e=>e.subject},{header:"Status",value:e=>ni(e.status)},{header:"Agent",value:e=>si(e.agentConsumeStatus)},{header:"Received",value:e=>e.receivedAt}])}function Te(r){return JSON.stringify(r.data??r,null,2)}function gt(r){let e=r.data||{};return[`${oi.default.green("\u2713")} Sent`,e.messageUid?`messageUid: ${e.messageUid}`:null,e.requestId?`requestId: ${e.requestId}`:null,e.emailIds?`emailIds: ${e.emailIds.join(", ")}`:null].filter(Boolean).join(`
34
+ `)}function rs(r,{httpStatus:e}={}){if(!r||typeof r!="object"||typeof r.code!="number")throw new T("Invalid server response format",{code:"invalid_response",exitCode:5,status:e,data:r});if(r.code!==200)throw new T(r.message||"Request failed",{code:ai(r.code),exitCode:rt(r.code),status:r.code,data:r});return r}async function k(r){let e;try{e=await r.json()}catch(t){throw new T("Invalid server response format",{code:"invalid_response",exitCode:5,status:r.status,cause:t})}if(r.status<200||r.status>=300)throw new T(e?.message||`Request failed with status code ${r.status}`,{code:ai(r.status),exitCode:rt(r.status),status:r.status,data:e});return rs(e,{httpStatus:r.status})}function ai(r){return r===401||r===403?"auth_error":r===404?"not_found":r===409?"state_conflict":r===400?"validation_error":"server_error"}var U=class{constructor(e){this.client=e}listMessages(e={}){return this.client.get("/v1/message/list",{searchParams:e}).then(k)}getMessage(e){return this.client.get("/v1/message/get",{searchParams:{messageUid:e}}).then(k)}listenMessages(e={}){return this.client.get("/v1/message/listen",{searchParams:e}).then(k)}replyMessage(e,t){return this.client.post("/v1/message/reply",{searchParams:{messageUid:e},json:t}).then(k)}};var ve=class{constructor(e){this.client=e}sendEmail(e){return this.client.post("/v1/mail/send",{json:e}).then(k)}};var j=class extends Error{name="KyError";get isKyError(){return!0}};var Z=class extends j{name="HTTPError";response;request;options;data;constructor(e,t,i){let n=e.status||e.status===0?e.status:"",s=e.statusText??"",o=`${n} ${s}`.trim(),a=o?`status code ${o}`:"an unknown error";super(`Request failed with ${a}: ${t.method} ${t.url}`),this.response=e,this.request=t,this.options=i}};var Q=class extends j{name="NetworkError";request;constructor(e,t){super(`Request failed due to a network error: ${e.method} ${e.url}`,t),this.request=e}};var ee=class extends Error{name="NonError";value;constructor(e){let t="Non-error value was thrown";try{typeof e=="string"?t=e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"&&(t=e.message)}catch{}super(t),this.value=e}};var G=class extends j{name="ForceRetryError";customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new ee(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:"Forced retry",t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};var ke=class extends Error{name="SchemaValidationError";issues;constructor(e){super("Response schema validation failed"),this.issues=e}};var R=class extends j{name="TimeoutError";request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.request=e}};var Ct=(()=>{let r=!1,e=!1,t=typeof globalThis.ReadableStream=="function",i=typeof globalThis.Request=="function";if(t&&i)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return r&&!e})(),li=typeof globalThis.AbortController=="function",$e=typeof globalThis.AbortSignal=="function"&&typeof globalThis.AbortSignal.any=="function",ci=typeof globalThis.ReadableStream=="function",hi=typeof globalThis.FormData=="function",je=["get","post","put","patch","head","delete"],is=()=>{};is();var Di={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},te=2147483647,fi=40,qe=Symbol("stop"),fe=class{options;constructor(e){this.options=e}},di=r=>new fe(r),mi={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},pi={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var Me=new TextEncoder,ns=r=>{if(!r)return 0;if(r instanceof FormData){let e=0;for(let[t,i]of r)e+=fi,e+=Me.encode(`Content-Disposition: form-data; name="${t}"`).byteLength,e+=typeof i=="string"?Me.encode(i).byteLength:i.size;return e}return r instanceof Blob?r.size:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength:typeof r=="string"?Me.encode(r).byteLength:r instanceof URLSearchParams?Me.encode(r.toString()).byteLength:0},gi=(r,e,t)=>{let i,n=0;return r.pipeThrough(new TransformStream({transform(s,o){if(o.enqueue(s),i){n+=i.byteLength;let a=e===0?0:n/e;a>=1&&(a=1-Number.EPSILON),t?.({percent:a,totalBytes:Math.max(e,n),transferredBytes:n},i)}i=s},flush(){i&&(n+=i.byteLength,t?.({percent:1,totalBytes:Math.max(e,n),transferredBytes:n},i))}}))},Ci=(r,e)=>{if(!r.body)return r;let t={status:r.status,statusText:r.statusText,headers:r.headers};if(r.status===204)return new Response(null,t);let i=Math.max(0,Number(r.headers.get("content-length"))||0);return new Response(gi(r.body,i,e),t)},bi=(r,e,t)=>{if(!r.body)return r;let i=ns(t??r.body);return new Request(r,{duplex:"half",body:gi(r.body,i,e)})};var q=r=>r!==null&&typeof r=="object";var ss=Symbol("replaceOption"),bt=r=>q(r)&&r[ss]===!0?{isReplace:!0,value:r.value}:{isReplace:!1,value:r};var me=(...r)=>{for(let e of r)if((!q(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return yt({},...r)},Ft=(r={},e={})=>{let t=new globalThis.Headers(r),i=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(let[s,o]of n.entries())i&&o==="undefined"||o===void 0?t.delete(s):t.set(s,o);return t},Et=r=>{if(!q(r)||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null},re=r=>{if(r instanceof URLSearchParams){let e=new URLSearchParams(r),t=r[P];return t&&(e[P]=new Set(t)),e}return r instanceof globalThis.Headers?new globalThis.Headers(r):Array.isArray(r)?[...r]:Et(r)?{...r}:r},os=r=>Object.fromEntries(Object.entries(r).filter(e=>e[1]!==void 0)),us=(r,e)=>Et(r)&&Et(e)?os({...r,...e}):Ft(r,e);function de(r,e,t){return Object.hasOwn(e,t)&&e[t]===void 0?[]:yt(r[t]??[],e[t]??[])}var Ie=(r={},e={})=>({init:de(r,e,"init"),beforeRequest:de(r,e,"beforeRequest"),beforeRetry:de(r,e,"beforeRetry"),beforeError:de(r,e,"beforeError"),afterResponse:de(r,e,"afterResponse")}),P=Symbol("deletedParameters"),as=(r,e)=>{let t=new URLSearchParams,i=new Set;for(let n of[r,e])if(n!==void 0)if(n instanceof URLSearchParams){for(let[o,a]of n.entries())t.append(o,a),i.delete(o);let s=n[P];if(s)for(let o of s)t.delete(o),i.add(o)}else if(Array.isArray(n))for(let s of n){if(!Array.isArray(s)||s.length!==2)throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");t.append(String(s[0]),String(s[1])),i.delete(String(s[0]))}else if(q(n))for(let[s,o]of Object.entries(n))o===void 0?(t.delete(s),i.add(s)):(t.append(s,String(o)),i.delete(s));else{let s=new URLSearchParams(n);for(let[o,a]of s.entries())t.append(o,a),i.delete(o)}return i.size>0&&(t[P]=i),t},yt=(...r)=>{let e={},t={},i={},n,s=[];for(let o of r)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(q(o)){for(let[a,u]of Object.entries(o)){if(a==="signal"&&u instanceof globalThis.AbortSignal){s.push(u);continue}let l=bt(u),{isReplace:h}=l;if(u=l.value,a==="context"){if(u!=null&&(!q(u)||Array.isArray(u)))throw new TypeError("The `context` option must be an object");e={...e,context:u==null?{}:h?{...u}:{...e.context,...u}};continue}if(a==="searchParams"){u==null?n=void 0:h?n=u:n=n===void 0?u:as(n,u);continue}q(u)&&!h&&a in e&&(u=yt(e[a],u)),e={...e,[a]:u}}if(q(o.hooks)){let{value:a,isReplace:u}=bt(o.hooks);i=Ie(u?{}:i,a),e.hooks=i}if(q(o.headers)){let{value:a,isReplace:u}=bt(o.headers);t=u?re(a):us(t,a),e.headers=t}}return n!==void 0&&(e.searchParams=n),s.length>0&&(s.length===1?e.signal=s[0]:$e?e.signal=AbortSignal.any(s):e.signal=s.at(-1)),e};var Fi=r=>je.includes(r)?r.toUpperCase():r,ls=["get","put","head","delete","options","trace"],cs=[408,413,429,500,502,503,504],hs=[413,429,503],Ei={limit:2,methods:ls,statusCodes:cs,afterStatusCodes:hs,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:r=>.3*2**(r-1)*1e3,jitter:void 0,retryOnTimeout:!1},yi=(r={})=>{if(typeof r=="number")return{...Ei,limit:r};if(r.methods&&!Array.isArray(r.methods))throw new Error("retry.methods must be an array");if(r.statusCodes&&!Array.isArray(r.statusCodes))throw new Error("retry.statusCodes must be an array");let e=Object.fromEntries(Object.entries({...r,methods:r.methods?.map(t=>t.toLowerCase())}).filter(([,t])=>t!==void 0));return{...Ei,...e}};async function wt(r,e,t,i){return new Promise((n,s)=>{let o=setTimeout(()=>{t&&t.abort(),s(new R(r))},i.timeout);i.fetch(r,e).then(n).catch(s).then(()=>{clearTimeout(o)})})}async function Le(r,{signal:e}){return new Promise((t,i)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(s),i(e.reason)}let s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r)})}var wi=r=>{let e={};for(let t in r)Object.hasOwn(r,t)&&!(t in pi)&&!(t in mi)&&(e[t]=r[t]);return e},xi=r=>r===void 0?!1:Array.isArray(r)?r.length>0:r instanceof URLSearchParams?r.size>0||!!r[P]?.size:typeof r=="object"?Object.keys(r).length>0:typeof r=="string"?r.trim().length>0:!!r;var Ds=Object.prototype.toString,fs=r=>Ds.call(r)==="[object Error]",ds=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function xt(r){if(!(r&&fs(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:i}=r;return t==="Load failed"?i===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")||t==="Failed to fetch"||t.startsWith("Failed to fetch (")&&t.endsWith(")")?!0:ds.has(t)}var At=(r,e)=>r instanceof e||r?.name===e.name;function Ai(r){return At(r,Z)}function _i(r){return At(r,Q)}function Oi(r){return At(r,R)}var ms=10*1024*1024,ps="The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl",pe=Symbol("timedOutResponseData"),gs=r=>{let e=/;\s*charset\s*=\s*(?:"([^"]+)"|([^;,\s]+))/i.exec(r),t=e?.[1]??e?.[2];if(t)try{return new TextDecoder(t)}catch{}return new TextDecoder},Si="The `schema` argument must follow the Standard Schema specification",Cs=r=>typeof r!="object"?r:{...r,...r.methods&&{methods:[...r.methods]},...r.statusCodes&&{statusCodes:[...r.statusCodes]},...r.afterStatusCodes&&{afterStatusCodes:[...r.afterStatusCodes]}},Ti=Object.prototype.toString,Bi=r=>r instanceof globalThis.Request||Ti.call(r)==="[object Request]",ge=r=>r instanceof globalThis.Response||Ti.call(r)==="[object Response]",bs=r=>Array.isArray(r)?r.map(e=>[...e]):re(r);function Es(r){let e={...r,json:re(r.json),context:re(r.context),headers:re(r.headers),searchParams:bs(r.searchParams)};return r.retry!==void 0&&(e.retry=Cs(r.retry)),e}var Ri=async(r,e)=>{if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(Si);let t=e["~standard"];if(typeof t!="object"||t===null||typeof t.validate!="function")throw new TypeError(Si);let i=await t.validate(r);if(i.issues)throw new ke(i.issues);return i.value},Ce=class r{static create(e,t){let i=t.hooks?.init??[],n=i.length>0?Es(t):t;for(let u of i)u(n);let s=new r(e,n),o=async()=>{if(typeof s.#e.timeout=="number"&&s.#e.timeout>te)throw new RangeError(`The \`timeout\` option cannot be greater than ${te}`);if(typeof s.#e.totalTimeout=="number"&&s.#e.totalTimeout>te)throw new RangeError(`The \`totalTimeout\` option cannot be greater than ${te}`);await Promise.resolve();let u=await s.#$(),l=u??await s.#_(async()=>s.#g()),h=u!==void 0||s.#p();for(;;){if(l===void 0)return l;if(ge(l))try{l=await s.#j(l)}catch(m){if(!(m instanceof G))throw m;let D=await s.#m(m,async()=>s.#g());if(D===void 0)return D;l=D,h=s.#p();continue}let f=l;if(!f.ok&&f.type!=="opaque"&&(typeof s.#e.throwHttpErrors=="function"?s.#e.throwHttpErrors(f.status):s.#e.throwHttpErrors)){let m=new Z(f,s.#u(f),s.#o()),D=m;if(m.data=await s.#R(f),h)throw D;let c=await s.#m(m,async()=>s.#g());if(c===void 0)return c;l=c,h=s.#p();continue}break}if(!ge(l))return l;if(s.#w(l),s.#e.onDownloadProgress){if(typeof s.#e.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!ci)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");let f=l.clone();return s.#i(l),Ci(f,s.#e.onDownloadProgress)}return l},a=(async()=>{try{return await o()}catch(u){if(!(u instanceof Error)||s.#F.has(u))throw u;let l=u;for(let h of s.#e.hooks.beforeError){let f=await h({request:s.request,options:s.#o(),error:l,retryCount:s.#r});f instanceof Error&&(l=f)}throw l}finally{let u=s.#E;s.#d(u?.body??void 0),s.request!==u&&s.#d(s.request.body??void 0)}})();for(let[u,l]of Object.entries(Di))u==="bytes"&&typeof globalThis.Response?.prototype?.bytes!="function"||(a[u]=async h=>{s.request.headers.set("accept",s.request.headers.get("accept")||l);let f=await a;if(u!=="json")return f[u]();let m=await f.text();if(m==="")return h!==void 0?Ri(void 0,h):JSON.parse(m);let D=n.parseJson?await n.parseJson(m,{request:s.#u(f),response:f}):JSON.parse(m);return h===void 0?D:Ri(D,h)});return a}static#S(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)):e}request;#n;#r=0;#t;#e;#E;#a;#F=new WeakSet;#l;#f;#c=!1;#y=new WeakMap;constructor(e,t={}){if(this.#t=e,Object.hasOwn(t,"prefixUrl"))throw new Error(ps);if(this.#e={...t,headers:Ft(this.#t.headers,t.headers),hooks:Ie({},t.hooks),method:Fi(t.method??this.#t.method??"GET"),prefix:String(t.prefix||""),retry:yi(t.retry),throwHttpErrors:t.throwHttpErrors??!0,timeout:t.timeout??1e4,totalTimeout:t.totalTimeout??!1,fetch:t.fetch??globalThis.fetch.bind(globalThis),context:t.context??{}},typeof this.#t!="string"&&!(this.#t instanceof URL||this.#t instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(typeof this.#t=="string"){if(this.#e.prefix){let n=this.#e.prefix.replace(/\/+$/,""),s=this.#t.replace(/^\/+/,"");this.#t=`${n}/${s}`}if(this.#e.baseUrl){let n;try{n=new URL(this.#t)}catch{}n||(this.#t=new URL(this.#t,new Request(this.#e.baseUrl).url))}}li&&$e&&(this.#a=this.#e.signal??this.#t.signal,this.#n=new globalThis.AbortController,this.#e.signal=this.#A()),Ct&&(this.#e.duplex="half"),this.#e.json!==void 0&&(this.#e.body=this.#e.stringifyJson?.(this.#e.json)??JSON.stringify(this.#e.json),this.#e.headers.set("content-type",this.#e.headers.get("content-type")??"application/json"));let i=t.headers&&new globalThis.Headers(t.headers).has("content-type");if(this.#t instanceof globalThis.Request&&(hi&&this.#e.body instanceof globalThis.FormData||this.#e.body instanceof URLSearchParams)&&!i&&this.#e.headers.delete("content-type"),this.request=new globalThis.Request(this.#t,this.#e),xi(this.#e.searchParams)){let n=new URL(this.request.url),s=this.#e.searchParams?.[P];if(s)for(let o of s)n.searchParams.delete(o);if(typeof this.#e.searchParams=="string"){let o=this.#e.searchParams.replace(/^\?/,"");o!==""&&(n.search=n.search?`${n.search}&${o}`:`?${o}`)}else{let o=new URLSearchParams(r.#S(this.#e.searchParams));for(let[a,u]of o.entries())n.searchParams.append(a,u)}if(this.#e.searchParams&&typeof this.#e.searchParams=="object"&&!Array.isArray(this.#e.searchParams)&&!(this.#e.searchParams instanceof URLSearchParams))for(let[o,a]of Object.entries(this.#e.searchParams))a===void 0&&n.searchParams.delete(o);this.request=new globalThis.Request(n,this.#e)}if(this.#e.onUploadProgress&&typeof this.#e.onUploadProgress!="function")throw new TypeError("The `onUploadProgress` option must be a function");this.#f=typeof this.#e.totalTimeout=="number"?this.#O():void 0}#s(){let e=this.#e.retry.delay(this.#r+1),t=e;return this.#e.retry.jitter===!0?t=Math.random()*e:typeof this.#e.retry.jitter=="function"&&(t=this.#e.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e)),Math.min(this.#e.retry.backoffLimit,t)}async#B(e){if(this.#r>=this.#e.retry.limit)throw e;let t=e instanceof Error?e:new ee(e);if(t instanceof G)return t.customDelay??this.#s();if(!this.#e.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#e.retry.shouldRetry!==void 0){let i=await this.#e.retry.shouldRetry({error:t,retryCount:this.#r+1});if(i===!1)throw e;if(i===!0)return this.#s()}if(Oi(e)){if(!this.#e.retry.retryOnTimeout)throw e;return this.#s()}if(Ai(e)){if(!this.#e.retry.statusCodes.includes(e.response.status))throw e;let i=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Retry-After")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(i&&this.#e.retry.afterStatusCodes.includes(e.response.status)){let n=Number(i)*1e3;return Number.isNaN(n)?n=Date.parse(i)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now()),Number.isFinite(n)?(n=Math.max(0,n),Math.min(this.#e.retry.maxRetryAfter,n)):Math.min(this.#e.retry.maxRetryAfter,this.#s())}if(e.response.status===413)throw e;return this.#s()}if(!_i(e))throw e;return this.#s()}#w(e){let t=this.#u(e);return this.#e.parseJson&&(e.json=async()=>{let i=await e.text();return i===""?JSON.parse(i):this.#e.parseJson(i,{request:t,response:e})}),e}async#R(e){let t=await this.#v(e,this.#x());if(t===pe){this.#h();return}if(!t)return;if(!this.#T(e.headers.get("content-type")??""))return t;let i=await this.#k(t,e,this.#x(),this.#u(e));if(i===pe){this.#h();return}return i}#x(){let e=this.#e.timeout===!1?1e4:this.#e.timeout,t=this.#D();if(t===void 0)return e;if(t<=0)throw new R(this.request);return Math.min(e,t)}#T(e){let t=(e.split(";",1)[0]??"").trim().toLowerCase();return/\/(?:.*[.+-])?json$/.test(t)}async#v(e,t){let{body:i}=e;if(!i)try{return await e.text()}catch{return}let n;try{n=i.getReader()}catch{return}let s=gs(e.headers.get("content-type")??""),o=[],a=0,u=(async()=>{try{for(;;){let{done:f,value:m}=await n.read();if(f)break;if(a+=m.byteLength,a>ms){n.cancel().catch(()=>{});return}o.push(s.decode(m,{stream:!0}))}}catch{return}return o.push(s.decode()),o.join("")})(),l=new Promise(f=>{let m=setTimeout(()=>{f(pe)},t);u.finally(()=>{clearTimeout(m)})}),h=await Promise.race([u,l]);return h===pe&&n.cancel().catch(()=>{}),h}async#k(e,t,i,n){let s;try{return await Promise.race([Promise.resolve().then(()=>this.#e.parseJson?this.#e.parseJson(e,{request:n,response:t}):JSON.parse(e)),new Promise(o=>{s=setTimeout(()=>{o(pe)},i)})])}catch{return}finally{clearTimeout(s)}}#d(e){e&&e.cancel().catch(()=>{})}#i(e){this.#d(e.body??void 0)}#A(){return this.#a?AbortSignal.any([this.#a,this.#n.signal]):this.#n.signal}#h(){let e=this.#D();if(e!==void 0&&e<=0)throw new R(this.request)}async#$(){for(let e of this.#e.hooks.beforeRequest){let t=await e({request:this.request,options:this.#o(),retryCount:0});if(Bi(t))this.#C(t);else if(ge(t))return t}}async#j(e){let t=this.#u(e);for(let i of this.#e.hooks.afterResponse){let n=this.#b(e.clone(),t);this.#w(n);let s;try{s=await i({request:this.request,options:this.#o(),response:n,retryCount:this.#r})}catch(a){throw n!==e&&this.#i(n),this.#i(e),a}if(s instanceof fe)throw n!==e&&this.#i(n),this.#i(e),new G(s.options);let o=ge(s)?this.#b(s,t):e;n!==e&&n!==o&&n.body!==o.body&&this.#i(n),e!==o&&e.body!==o.body&&this.#i(e),e=o}return e}async#_(e){try{return await e()}catch(t){return this.#m(t,e)}}async#m(e,t){this.#c=!1;let i=Math.min(await this.#B(e),te),n={signal:this.#a},s=this.#D();if(s!==void 0){if(s<=0)throw new R(this.request);if(i>=s)throw await Le(s,n),new R(this.request)}if(await Le(i,n),this.#h(),e instanceof G&&e.customRequest){let o=new globalThis.Request(e.customRequest,this.#e.signal?{signal:this.#e.signal}:void 0);this.#C(o)}for(let o of this.#e.hooks.beforeRetry){let a;try{a=await o({request:this.request,options:this.#o(),error:e,retryCount:this.#r+1})}catch(u){throw u instanceof Error&&u!==e&&this.#F.add(u),u}if(Bi(a)){this.#C(a);break}if(ge(a))return this.#c=!0,this.#r++,a;if(a===qe)return}return this.#h(),this.#r++,this.#_(t)}#p(){let e=this.#c;return this.#c=!1,e}async#g(){this.#n?.signal.aborted&&(this.#n=new globalThis.AbortController,this.#e.signal=this.#A(),this.request=new globalThis.Request(this.request,{signal:this.#e.signal}));let e=wi(this.#e),t=this.#e.retry.limit>0?this.request.clone():void 0,i=this.#q(this.request,this.#e.body??void 0);this.#E=i,t&&(this.request=t);try{let n=this.#D();if(n!==void 0&&n<=0)throw new R(this.request);let s=this.#e.timeout===!1?n:n===void 0?this.#e.timeout:Math.min(this.#e.timeout,n),o=s===void 0?await this.#e.fetch(i,e):await wt(i,e,this.#n,{timeout:s,fetch:this.#e.fetch});return this.#b(o,i)}catch(n){throw xt(n)?new Q(this.request,{cause:n}):n}}#D(){if(this.#f===void 0)return;let e=this.#O()-this.#f;return Math.max(0,this.#e.totalTimeout-e)}#O(){return globalThis.performance?.now()??Date.now()}#o(){if(!this.#l){let{hooks:e,json:t,parseJson:i,stringifyJson:n,searchParams:s,timeout:o,totalTimeout:a,throwHttpErrors:u,fetch:l,...h}=this.#e;this.#l=Object.freeze(h)}return this.#l}#C(e){this.#l=void 0,this.request=e}#u(e){return this.#y.get(e)??this.request}#b(e,t){return this.#y.set(e,t),e}#q(e,t){return!this.#e.onUploadProgress||!e.body||!Ct?e:bi(e,this.#e.onUploadProgress,t??this.#e.body??void 0)}};var _t=r=>{let e=(t,i)=>Ce.create(t,me(r,i));for(let t of je)e[t]=(i,n)=>Ce.create(i,me(r,n,{method:t}));return e.create=t=>_t(me(t)),e.extend=t=>(typeof t=="function"&&(t=t(r??{})),_t(me(r,t))),e.stop=qe,e.retry=di,e},Fs=_t(),vi=Fs;async function ki({cliOptions:r={},env:e=process.env,readConfig:t=ue,requireSecretKey:i=!0}={}){let n=await t(),s=r.baseUrl||e.ENGAGELAB_EMAIL_BASE_URL||n.baseUrl,o=r.secretKey||e.ENGAGELAB_EMAIL_SECRET_KEY||n.secretKey;if(!s)throw ye("Missing base URL. Set --base-url, ENGAGELAB_EMAIL_BASE_URL, or config set.");if(i&&!o)throw ye("Missing Secret Key. Set --secret-key, ENGAGELAB_EMAIL_SECRET_KEY, or config set.");if(i&&!o.startsWith("sk_"))throw ye("Secret Key must start with sk_");return{baseUrl:s,secretKey:o}}async function M(r){let e=await ki({cliOptions:r.optsWithGlobals()});return vi.extend({prefix:ys(e.baseUrl),headers:{Authorization:`Bearer ${e.secretKey}`},timeout:3e4,throwHttpErrors:!1})}function N(r,e,t){r.opts().json&&r.parent?.parent?.stdout?.write?.("");let i=r.programOutput?.stdout||process.stdout;if(r.opts().json){i.write(`${JSON.stringify(e,null,2)}
30
35
  `);return}i.write(`${t(e)}
31
- `)}function D(r,e){let t={};for(let[i,s=i]of Object.entries(e))t[s]=r[i];return mt(t)}function De(r,e){let t={};for(let i of e)r[i]!==void 0&&(t[i]=r[i]);return t}function Lr(r){return r.endsWith("/")?r.slice(0,-1):r}var Fr=["bodyFile","bodyJson","mailboxId","to","subject","text","html","textFile","htmlFile","cc","bcc"];function Wt(r){let e=r.command("emails").description("Work with email messages");Dr(e),Ur(e)}function Dr(r){r.command("send").description("Send a new email").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--mailbox-id <id>","Mailbox ID",y).option("--to <email>","Recipient email address",H).option("--subject <text>","Email subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",H).option("--bcc <email>","BCC address",H).option("--json","Output raw JSON").action(async(e,t)=>{let i=await ve(De(e,Fr));Jr(i);let s=new ie(await O(t));x(t,await s.sendEmail(i),je)})}function Ur(r){let e=r.command("receiving").description("Work with inbound email");e.command("list").description("List inbound messages").option("--mailbox-id <id>","Filter by mailbox ID",y).option("--status <number>","Message status",P).option("--agent-consume-status <number>","Agent consume status",P).option("--keyword <text>","Search keyword").option("--page-no <number>","Page number",y).option("--page-size <number>","Page size",y).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new R(await O(i)).listMessages(D(t,{mailboxId:"mailboxId",status:"status",agentConsumeStatus:"agentConsumeStatus",keyword:"keyword",pageNo:"pageNo",pageSize:"pageSize"}));x(i,n,G)}),e.command("get").description("Get inbound message details").argument("<message-uid>","Message UID").option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Message UID is required");let n=new R(await O(s));x(s,await n.getMessage(t),I)}),e.command("listen").description("Long-poll and claim messages for Agent processing").option("--mailbox-id <id>","Filter by mailbox ID",y).option("--limit <number>","Message limit",y).option("--timeout-seconds <number>","Long poll timeout seconds",P).option("--interval-millis <number>","Poll interval milliseconds",y).option("--claim-ttl-seconds <number>","Claim TTL seconds",y).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new R(await O(i)).listenMessages(D(t,{mailboxId:"mailboxId",limit:"limit",timeoutSeconds:"timeoutSeconds",intervalMillis:"intervalMillis",claimTtlSeconds:"claimTtlSeconds"}));x(i,n,G)}),e.command("ack").description("Mark a claimed message as consumed").argument("<message-uid>","Message UID").option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Message UID is required");let n=new R(await O(s));x(s,await n.ackMessage(t),I)}),e.command("fail").description("Mark a claimed message as failed").argument("<message-uid>","Message UID").option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Message UID is required");let n=new R(await O(s));x(s,await n.failMessage(t),I)}),e.command("reply").description("Reply to an inbound message").argument("<message-uid>","Message UID").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--subject <text>","Reply subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",H).option("--bcc <email>","BCC address",H).option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Message UID is required");let n=await ve(De(i,["bodyFile","bodyJson","subject","text","html","textFile","htmlFile","cc","bcc"]));Wr(n);let o=new R(await O(s));x(s,await o.replyMessage(t,n),je)})}function Jr(r){if(!r.mailboxId)throw p("mailboxId is required");if(!Array.isArray(r.to)||r.to.length===0)throw p("At least one recipient is required");if(!r.subject)throw p("subject is required");Bt(r)}function Wr(r){Bt(r)}function Bt(r){if(!r.text&&!r.html)throw p("At least one of text or html is required")}var U=class{constructor(e){this.client=e}listThreads(e={}){return this.client.get("v1/thread",{searchParams:e}).then(b)}getThread(e){return this.client.get(`v1/thread/${encodeURIComponent(e)}`).then(b)}listThreadMessages(e,t={}){return this.client.get(`v1/thread/${encodeURIComponent(e)}/messages`,{searchParams:t}).then(b)}};function Gt(r){let e=r.command("threads").description("Work with email threads");e.command("list").description("List threads").option("--mailbox-id <id>","Filter by mailbox ID",y).option("--status <number>","Filter by thread status",P).option("--keyword <text>","Search keyword").option("--subject <text>","Search normalized subject").option("--participant <email>","Search participant").option("--sender <email>","Search sender").option("--target-mailbox <email>","Search target mailbox").option("--start-time <datetime>","Latest message start time").option("--end-time <datetime>","Latest message end time").option("--page-no <number>","Page number",y).option("--page-size <number>","Page size",y).option("--json","Output raw JSON").action(async(t,i)=>{let n=await new U(await O(i)).listThreads(D(t,{mailboxId:"mailboxId",status:"status",keyword:"keyword",subject:"subject",participant:"participant",sender:"sender",targetMailbox:"targetMailbox",startTime:"startTime",endTime:"endTime",pageNo:"pageNo",pageSize:"pageSize"}));x(i,n,bt)}),e.command("get").description("Get thread details").argument("<thread-id>","Thread ID").option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Thread ID is required");let n=new U(await O(s));x(s,await n.getThread(t),I)}),e.command("messages").description("List messages in a thread").argument("<thread-id>","Thread ID").option("--limit <number>","Message limit",y).option("--include-content","Include text/html/headers/attachments").option("--json","Output raw JSON").action(async(t,i,s)=>{k(t,"Thread ID is required");let o=await new U(await O(s)).listThreadMessages(t,D(i,{limit:"limit",includeContent:"includeContent"}));x(s,o,G)})}function zt(r,e){r.write(`${JSON.stringify({error:{code:e.code||"unknown_error",message:e.message||"Command failed"}},null,2)}
32
- `)}function Br(r=new it){return r.name("engagelab-email-cli").description("CLI for EngageLab Email Agent workflows").version("0.1.0").option("-u, --base-url <url>","EngageLab Email API base URL",process.env.ENGAGELAB_EMAIL_BASE_URL).option("--secret-key <key>","EngageLab Email Secret Key",process.env.ENGAGELAB_EMAIL_SECRET_KEY),ut(r),Gt(r),Wt(r),r}async function Kt(r=process.argv){let e=Br();try{await e.parseAsync(r)}catch(t){let i=at(t);r.includes("--json")?zt(process.stderr,i):process.stderr.write(`${i.message}
33
- `),process.exitCode=i.exitCode}}Kt().catch(r=>{process.stderr.write(`${r instanceof Error?r.message:String(r)}
36
+ `)}function be(r,e){let t={};for(let[i,n=i]of Object.entries(e))t[n]=r[i];return tr(t)}function Ot(r,e){let t={};for(let i of e)r[i]!==void 0&&(t[i]=r[i]);return t}function ys(r){return r.endsWith("/")?r.slice(0,-1):r}var ws=["bodyFile","bodyJson","mailboxId","to","subject","text","html","textFile","htmlFile","cc","bcc"],xs=10,As=5,_s=2,Os=5;function qi(r){let e=r.command("emails").description("Work with email messages");Ss(e),Bs(e)}function Ss(r){r.command("send").description("Send a new email").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--mailbox-id <id>","Mailbox ID",B).option("--to <email>","Recipient email address",z).option("--subject <text>","Email subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",z).option("--bcc <email>","BCC address",z).option("--json","Output raw JSON").action(async(e,t)=>{let i=await it(Ot(e,ws));Rs(i);let n=new ve(await M(t));N(t,await n.sendEmail(i),gt)})}function Bs(r){let e=r.command("receiving").description("Work with inbound email");e.command("list").description("List inbound messages").option("--mailbox-id <id>","Filter by mailbox ID",B).option("--keyword <text>","Search keyword").option("--page-no <number>","Page number",B).option("--page-size <number>","Page size",B).option("--json","Output raw JSON").action(async(t,i)=>{let s=await new U(await M(i)).listMessages(be(t,{mailboxId:"mailboxId",keyword:"keyword",pageNo:"pageNo",pageSize:"pageSize"}));N(i,s,Re)}),e.command("get").description("Get inbound message details").argument("<message-uid>","Message UID").option("--json","Output raw JSON").action(async(t,i,n)=>{K(t,"Message UID is required");let s=new U(await M(n));N(n,await s.getMessage(t),Te)}),e.command("listen").description("Poll new inbound messages for Agent processing").option("--after <id>","Cursor ID from the previous result",ae).option("--limit <number>","Message limit",B).option("--interval <seconds>","Polling interval in seconds (minimum 2)",B).option("--json","Output raw JSON").action(async(t,i)=>{let n=new U(await M(i));await vs(n,t,i)}),e.command("reply").description("Reply to an inbound message").argument("<message-uid>","Message UID").option("--body-file <path>","Read full JSON request body from file").option("--body-json <json>","Read full JSON request body from inline JSON").option("--subject <text>","Reply subject").option("--text <text>","Plain text body").option("--html <html>","HTML body").option("--text-file <path>","Read plain text body from file").option("--html-file <path>","Read HTML body from file").option("--cc <email>","CC address",z).option("--bcc <email>","BCC address",z).option("--json","Output raw JSON").action(async(t,i,n)=>{K(t,"Message UID is required");let s=await it(Ot(i,["bodyFile","bodyJson","subject","text","html","textFile","htmlFile","cc","bcc"]));Ts(s);let o=new U(await M(n));N(n,await o.replyMessage(t,s),gt)})}function Rs(r){if(!r.mailboxId)throw y("mailboxId is required");if(!Array.isArray(r.to)||r.to.length===0)throw y("At least one recipient is required");if(!r.subject)throw y("subject is required");Mi(r)}function Ts(r){Mi(r)}function Mi(r){if(!r.text&&!r.html)throw y("At least one of text or html is required")}async function vs(r,e,t){let i=process.stdout,n=process.stderr,s=!!e.json,o=e.limit??xs,a=e.interval??As;ks(a);let u=e.after,l=0,h,f=!1,m=()=>{f=!0,h&&clearTimeout(h),s||n.write(`
37
+ Stopped listening.
38
+ `),process.exit(130)};if(process.once("SIGINT",m),process.once("SIGTERM",m),s||n.write(`${H.default.dim("Connecting...")}
39
+ `),u===void 0){let c=await r.listenMessages({limit:1});u=ji($i(c))}s||(n.write(`${H.default.green("\u2713")} Ready
40
+
41
+ `),n.write(`${H.default.bold("Polling:")} every ${a}s
42
+ `),n.write(`Listening for new inbound emails. Press Ctrl+C to stop.
43
+
44
+ `));let D=async()=>{if(!f)try{let c=u===void 0?{limit:o}:{after:u,limit:o},d=await r.listenMessages(c),p=$i(d);p.length>0&&(u=ji(p)??u,js(i,p,s)),l=0}catch(c){l+=1;let d=c instanceof Error?c.message:String(c);if(s?n.write(`${JSON.stringify({error:{code:"poll_error",message:d}})}
45
+ `):n.write(`${H.default.dim(`[${Ii()}]`)} ${H.default.yellow("Warning:")} ${d}
46
+ `),l>=Os)throw y("Exiting after 5 consecutive API failures.")}finally{f||(h=setTimeout(()=>{D().catch(c=>{let d=c instanceof Error?c.message:String(c);n.write(`${d}
47
+ `),process.exit(5)})},a*1e3))}};h=setTimeout(()=>{D().catch(c=>{let d=c instanceof Error?c.message:String(c);n.write(`${d}
48
+ `),process.exit(5)})},a*1e3),await new Promise(()=>{})}function ks(r){if(!Number.isInteger(r)||r<_s)throw y("Polling interval must be at least 2 seconds.")}function $i(r){return Array.isArray(r.data)?r.data:Array.isArray(r.data?.list)?r.data.list:[]}function ji(r){let e=r.map($s).filter(i=>i!==void 0);if(e.length===0)return;let t=e.map(Number).filter(Number.isFinite);return t.length===e.length?Math.max(...t):e.at(-1)}function $s(r){return r.id??r.messageId??r.messageUid}function js(r,e,t){if(t){for(let i of e)r.write(`${JSON.stringify(i)}
49
+ `);return}for(let i of e)r.write(`${qs(i)}
50
+ `)}function Ii(){return new Date().toLocaleTimeString("en-GB",{hour12:!1})}function qs(r){let e=r.fromEmail||r.envelopeFrom||"(unknown sender)",t=Ms(r.to||r.toEmail||r.recipients),i=Is(r.subject||"(no subject)",60),n=r.messageUid||r.id||"",s=t?`${e} -> ${t}`:e;return[H.default.dim(`[${Ii()}]`),s,H.default.bold(`"${i}"`),n?H.default.dim(String(n)):null].filter(Boolean).join(" ")}function Ms(r){return Array.isArray(r)?r.join(", "):r||""}function Is(r,e){let t=String(r);return t.length<=e?t:`${t.slice(0,e-3)}...`}var ie=class{constructor(e){this.client=e}listThreads(e={}){return this.client.get("/v1/thread/list",{searchParams:e}).then(k)}getThread(e){return this.client.get("/v1/thread/get",{searchParams:{threadId:e}}).then(k)}listThreadMessages(e,t={}){return this.client.get("/v1/thread/messages",{searchParams:{threadId:e,...t}}).then(k)}};function Li(r){let e=r.command("threads").description("Work with email threads");e.command("list").description("List threads").option("--mailbox-id <id>","Filter by mailbox ID",B).option("--subject <text>","Search normalized subject").option("--participant <email>","Search participant").option("--start-time <timestamp>","Latest message start timestamp in milliseconds",ae).option("--end-time <timestamp>","Latest message end timestamp in milliseconds",ae).option("--page-no <number>","Page number",B).option("--page-size <number>","Page size",B).option("--json","Output raw JSON").action(async(t,i)=>{let s=await new ie(await M(i)).listThreads(be(t,{mailboxId:"mailboxId",subject:"subject",participant:"participant",startTime:"startTime",endTime:"endTime",pageNo:"pageNo",pageSize:"pageSize"}));N(i,s,ui)}),e.command("get").description("Get thread details").argument("<thread-id>","Thread ID").option("--json","Output raw JSON").action(async(t,i,n)=>{K(t,"Thread ID is required");let s=new ie(await M(n));N(n,await s.getThread(t),Te)}),e.command("messages").description("List messages in a thread").argument("<thread-id>","Thread ID").option("--limit <number>","Message limit",B).option("--include-content","Include text/html/headers/attachments").option("--json","Output raw JSON").action(async(t,i,n)=>{K(t,"Thread ID is required");let o=await new ie(await M(n)).listThreadMessages(t,be(i,{limit:"limit",includeContent:"includeContent"}));N(n,o,Re)})}function Ni(r,e){r.write(`${JSON.stringify({error:{code:e.code||"unknown_error",message:e.message||"Command failed"}},null,2)}
51
+ `)}function Ls(r=new Pt){return r.name("engagelab-email-cli").description("CLI for EngageLab Email Agent workflows").version("0.1.0").option("-u, --base-url <url>","EngageLab Email API base URL",process.env.ENGAGELAB_EMAIL_BASE_URL).option("--secret-key <key>","EngageLab Email Secret Key",process.env.ENGAGELAB_EMAIL_SECRET_KEY),Jt(r),Li(r),qi(r),r}async function Hi(r=process.argv){let e=Ls();try{await e.parseAsync(r)}catch(t){let i=Gt(t);r.includes("--json")?Ni(process.stderr,i):process.stderr.write(`${i.message}
52
+ `),process.exitCode=i.exitCode}}Hi().catch(r=>{process.stderr.write(`${r instanceof Error?r.message:String(r)}
34
53
  `),process.exitCode=1});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "engagelab-email-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "CLI for EngageLab Email Agent and Skill workflows",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",