@multisender.app/multisender-sdk 0.0.1

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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +410 -0
  3. package/dist/auth/api-key.d.ts +8 -0
  4. package/dist/auth/api-key.d.ts.map +1 -0
  5. package/dist/cli/commands/distribute.d.ts +3 -0
  6. package/dist/cli/commands/distribute.d.ts.map +1 -0
  7. package/dist/cli/commands/distributions.d.ts +3 -0
  8. package/dist/cli/commands/distributions.d.ts.map +1 -0
  9. package/dist/cli/commands/lists.d.ts +3 -0
  10. package/dist/cli/commands/lists.d.ts.map +1 -0
  11. package/dist/cli/index.cjs +4507 -0
  12. package/dist/cli/index.cjs.map +46 -0
  13. package/dist/cli/index.d.ts +3 -0
  14. package/dist/cli/index.d.ts.map +1 -0
  15. package/dist/cli/index.js +4514 -0
  16. package/dist/cli/index.js.map +46 -0
  17. package/dist/core/errors.d.ts +20 -0
  18. package/dist/core/errors.d.ts.map +1 -0
  19. package/dist/core/generated-transport.d.ts +3 -0
  20. package/dist/core/generated-transport.d.ts.map +1 -0
  21. package/dist/core/pagination.d.ts +4 -0
  22. package/dist/core/pagination.d.ts.map +1 -0
  23. package/dist/core/types.d.ts +19 -0
  24. package/dist/core/types.d.ts.map +1 -0
  25. package/dist/gen/client/client.gen.d.ts +3 -0
  26. package/dist/gen/client/client.gen.d.ts.map +1 -0
  27. package/dist/gen/client/index.d.ts +9 -0
  28. package/dist/gen/client/index.d.ts.map +1 -0
  29. package/dist/gen/client/types.gen.d.ts +118 -0
  30. package/dist/gen/client/types.gen.d.ts.map +1 -0
  31. package/dist/gen/client/utils.gen.d.ts +34 -0
  32. package/dist/gen/client/utils.gen.d.ts.map +1 -0
  33. package/dist/gen/client.gen.d.ts +13 -0
  34. package/dist/gen/client.gen.d.ts.map +1 -0
  35. package/dist/gen/core/auth.gen.d.ts +19 -0
  36. package/dist/gen/core/auth.gen.d.ts.map +1 -0
  37. package/dist/gen/core/bodySerializer.gen.d.ts +26 -0
  38. package/dist/gen/core/bodySerializer.gen.d.ts.map +1 -0
  39. package/dist/gen/core/params.gen.d.ts +44 -0
  40. package/dist/gen/core/params.gen.d.ts.map +1 -0
  41. package/dist/gen/core/pathSerializer.gen.d.ts +34 -0
  42. package/dist/gen/core/pathSerializer.gen.d.ts.map +1 -0
  43. package/dist/gen/core/queryKeySerializer.gen.d.ts +19 -0
  44. package/dist/gen/core/queryKeySerializer.gen.d.ts.map +1 -0
  45. package/dist/gen/core/serverSentEvents.gen.d.ts +72 -0
  46. package/dist/gen/core/serverSentEvents.gen.d.ts.map +1 -0
  47. package/dist/gen/core/types.gen.d.ts +79 -0
  48. package/dist/gen/core/types.gen.d.ts.map +1 -0
  49. package/dist/gen/core/utils.gen.d.ts +20 -0
  50. package/dist/gen/core/utils.gen.d.ts.map +1 -0
  51. package/dist/gen/index.d.ts +3 -0
  52. package/dist/gen/index.d.ts.map +1 -0
  53. package/dist/gen/sdk.gen.d.ts +168 -0
  54. package/dist/gen/sdk.gen.d.ts.map +1 -0
  55. package/dist/gen/types.gen.d.ts +2501 -0
  56. package/dist/gen/types.gen.d.ts.map +1 -0
  57. package/dist/index.cjs +1648 -0
  58. package/dist/index.cjs.map +31 -0
  59. package/dist/index.d.ts +16 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +1651 -0
  62. package/dist/index.js.map +31 -0
  63. package/dist/multisender.d.ts +46 -0
  64. package/dist/multisender.d.ts.map +1 -0
  65. package/dist/openapi-runtime.d.ts +10 -0
  66. package/dist/openapi-runtime.d.ts.map +1 -0
  67. package/dist/services/catalogs.d.ts +15 -0
  68. package/dist/services/catalogs.d.ts.map +1 -0
  69. package/dist/services/distributions.d.ts +17 -0
  70. package/dist/services/distributions.d.ts.map +1 -0
  71. package/dist/services/lists.d.ts +36 -0
  72. package/dist/services/lists.d.ts.map +1 -0
  73. package/dist/services/project.d.ts +19 -0
  74. package/dist/services/project.d.ts.map +1 -0
  75. package/dist/services/response-utils.d.ts +9 -0
  76. package/dist/services/response-utils.d.ts.map +1 -0
  77. package/dist/services/types.d.ts +33 -0
  78. package/dist/services/types.d.ts.map +1 -0
  79. package/dist/types.d.ts +5 -0
  80. package/dist/types.d.ts.map +1 -0
  81. package/dist/utils/csv.d.ts +9 -0
  82. package/dist/utils/csv.d.ts.map +1 -0
  83. package/dist/utils/validation.d.ts +7 -0
  84. package/dist/utils/validation.d.ts.map +1 -0
  85. package/package.json +64 -0
@@ -0,0 +1,4514 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ if (canCache)
30
+ cache.set(mod, to);
31
+ return to;
32
+ };
33
+ var __toCommonJS = (from) => {
34
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
35
+ if (entry)
36
+ return entry;
37
+ entry = __defProp({}, "__esModule", { value: true });
38
+ if (from && typeof from === "object" || typeof from === "function") {
39
+ for (var key of __getOwnPropNames(from))
40
+ if (!__hasOwnProp.call(entry, key))
41
+ __defProp(entry, key, {
42
+ get: __accessProp.bind(from, key),
43
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
44
+ });
45
+ }
46
+ __moduleCache.set(from, entry);
47
+ return entry;
48
+ };
49
+ var __moduleCache;
50
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
51
+ var __returnValue = (v) => v;
52
+ function __exportSetter(name, newValue) {
53
+ this[name] = __returnValue.bind(null, newValue);
54
+ }
55
+ var __export = (target, all) => {
56
+ for (var name in all)
57
+ __defProp(target, name, {
58
+ get: all[name],
59
+ enumerable: true,
60
+ configurable: true,
61
+ set: __exportSetter.bind(all, name)
62
+ });
63
+ };
64
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
65
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
66
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
67
+ }) : x)(function(x) {
68
+ if (typeof require !== "undefined")
69
+ return require.apply(this, arguments);
70
+ throw Error('Dynamic require of "' + x + '" is not supported');
71
+ });
72
+
73
+ // node_modules/commander/lib/error.js
74
+ var require_error = __commonJS((exports) => {
75
+ class CommanderError extends Error {
76
+ constructor(exitCode, code, message) {
77
+ super(message);
78
+ Error.captureStackTrace(this, this.constructor);
79
+ this.name = this.constructor.name;
80
+ this.code = code;
81
+ this.exitCode = exitCode;
82
+ this.nestedError = undefined;
83
+ }
84
+ }
85
+
86
+ class InvalidArgumentError extends CommanderError {
87
+ constructor(message) {
88
+ super(1, "commander.invalidArgument", message);
89
+ Error.captureStackTrace(this, this.constructor);
90
+ this.name = this.constructor.name;
91
+ }
92
+ }
93
+ exports.CommanderError = CommanderError;
94
+ exports.InvalidArgumentError = InvalidArgumentError;
95
+ });
96
+
97
+ // node_modules/commander/lib/argument.js
98
+ var require_argument = __commonJS((exports) => {
99
+ var { InvalidArgumentError } = require_error();
100
+
101
+ class Argument {
102
+ constructor(name, description) {
103
+ this.description = description || "";
104
+ this.variadic = false;
105
+ this.parseArg = undefined;
106
+ this.defaultValue = undefined;
107
+ this.defaultValueDescription = undefined;
108
+ this.argChoices = undefined;
109
+ switch (name[0]) {
110
+ case "<":
111
+ this.required = true;
112
+ this._name = name.slice(1, -1);
113
+ break;
114
+ case "[":
115
+ this.required = false;
116
+ this._name = name.slice(1, -1);
117
+ break;
118
+ default:
119
+ this.required = true;
120
+ this._name = name;
121
+ break;
122
+ }
123
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
124
+ this.variadic = true;
125
+ this._name = this._name.slice(0, -3);
126
+ }
127
+ }
128
+ name() {
129
+ return this._name;
130
+ }
131
+ _concatValue(value, previous) {
132
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
133
+ return [value];
134
+ }
135
+ return previous.concat(value);
136
+ }
137
+ default(value, description) {
138
+ this.defaultValue = value;
139
+ this.defaultValueDescription = description;
140
+ return this;
141
+ }
142
+ argParser(fn) {
143
+ this.parseArg = fn;
144
+ return this;
145
+ }
146
+ choices(values) {
147
+ this.argChoices = values.slice();
148
+ this.parseArg = (arg, previous) => {
149
+ if (!this.argChoices.includes(arg)) {
150
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
151
+ }
152
+ if (this.variadic) {
153
+ return this._concatValue(arg, previous);
154
+ }
155
+ return arg;
156
+ };
157
+ return this;
158
+ }
159
+ argRequired() {
160
+ this.required = true;
161
+ return this;
162
+ }
163
+ argOptional() {
164
+ this.required = false;
165
+ return this;
166
+ }
167
+ }
168
+ function humanReadableArgName(arg) {
169
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
170
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
171
+ }
172
+ exports.Argument = Argument;
173
+ exports.humanReadableArgName = humanReadableArgName;
174
+ });
175
+
176
+ // node:events
177
+ var exports_events = {};
178
+ __export(exports_events, {
179
+ setMaxListeners: () => setMaxListeners2,
180
+ once: () => once2,
181
+ listenerCount: () => listenerCount2,
182
+ init: () => EventEmitter,
183
+ getMaxListeners: () => getMaxListeners2,
184
+ getEventListeners: () => getEventListeners,
185
+ default: () => events_default,
186
+ captureRejectionSymbol: () => captureRejectionSymbol,
187
+ addAbortListener: () => addAbortListener,
188
+ EventEmitter: () => EventEmitter
189
+ });
190
+ function emitError(emitter, args) {
191
+ var { _events: events } = emitter;
192
+ if (args[0] ??= Error("Unhandled error."), !events)
193
+ throw args[0];
194
+ var errorMonitor = events[kErrorMonitor];
195
+ if (errorMonitor)
196
+ for (var handler of ArrayPrototypeSlice.call(errorMonitor))
197
+ handler.apply(emitter, args);
198
+ var handlers = events.error;
199
+ if (!handlers)
200
+ throw args[0];
201
+ for (var handler of ArrayPrototypeSlice.call(handlers))
202
+ handler.apply(emitter, args);
203
+ return true;
204
+ }
205
+ function addCatch(emitter, promise, type, args) {
206
+ promise.then(undefined, function(err) {
207
+ queueMicrotask(() => emitUnhandledRejectionOrErr(emitter, err, type, args));
208
+ });
209
+ }
210
+ function emitUnhandledRejectionOrErr(emitter, err, type, args) {
211
+ if (typeof emitter[kRejection] === "function")
212
+ emitter[kRejection](err, type, ...args);
213
+ else
214
+ try {
215
+ emitter[kCapture] = false, emitter.emit("error", err);
216
+ } finally {
217
+ emitter[kCapture] = true;
218
+ }
219
+ }
220
+ function overflowWarning(emitter, type, handlers) {
221
+ handlers.warned = true;
222
+ let warn = Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);
223
+ warn.name = "MaxListenersExceededWarning", warn.emitter = emitter, warn.type = type, warn.count = handlers.length, console.warn(warn);
224
+ }
225
+ function onceWrapper(type, listener, ...args) {
226
+ this.removeListener(type, listener), listener.apply(this, args);
227
+ }
228
+ function once2(emitter, type, options) {
229
+ var signal = options?.signal;
230
+ if (validateAbortSignal(signal, "options.signal"), signal?.aborted)
231
+ throw new AbortError(undefined, { cause: signal?.reason });
232
+ let { resolve, reject, promise } = $newPromiseCapability(Promise), errorListener = (err) => {
233
+ if (emitter.removeListener(type, resolver), signal != null)
234
+ eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
235
+ reject(err);
236
+ }, resolver = (...args) => {
237
+ if (typeof emitter.removeListener === "function")
238
+ emitter.removeListener("error", errorListener);
239
+ if (signal != null)
240
+ eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
241
+ resolve(args);
242
+ };
243
+ if (eventTargetAgnosticAddListener(emitter, type, resolver, { once: true }), type !== "error" && typeof emitter.once === "function")
244
+ emitter.once("error", errorListener);
245
+ function abortListener() {
246
+ eventTargetAgnosticRemoveListener(emitter, type, resolver), eventTargetAgnosticRemoveListener(emitter, "error", errorListener), reject(new AbortError(undefined, { cause: signal?.reason }));
247
+ }
248
+ if (signal != null)
249
+ eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true });
250
+ return promise;
251
+ }
252
+ function getEventListeners(emitter, type) {
253
+ return emitter.listeners(type);
254
+ }
255
+ function setMaxListeners2(n, ...eventTargets) {
256
+ validateNumber(n, "setMaxListeners", 0);
257
+ var length;
258
+ if (eventTargets && (length = eventTargets.length))
259
+ for (let i = 0;i < length; i++)
260
+ eventTargets[i].setMaxListeners(n);
261
+ else
262
+ defaultMaxListeners = n;
263
+ }
264
+ function listenerCount2(emitter, type) {
265
+ return emitter.listenerCount(type);
266
+ }
267
+ function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) {
268
+ if (typeof emitter.removeListener === "function")
269
+ emitter.removeListener(name, listener);
270
+ else
271
+ emitter.removeEventListener(name, listener, flags);
272
+ }
273
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
274
+ if (typeof emitter.on === "function")
275
+ if (flags.once)
276
+ emitter.once(name, listener);
277
+ else
278
+ emitter.on(name, listener);
279
+ else
280
+ emitter.addEventListener(name, listener, flags);
281
+ }
282
+ function ERR_INVALID_ARG_TYPE(name, type, value) {
283
+ let err = TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`);
284
+ return err.code = "ERR_INVALID_ARG_TYPE", err;
285
+ }
286
+ function ERR_OUT_OF_RANGE(name, range, value) {
287
+ let err = RangeError(`The "${name}" argument is out of range. It must be ${range}. Received ${value}`);
288
+ return err.code = "ERR_OUT_OF_RANGE", err;
289
+ }
290
+ function validateAbortSignal(signal, name) {
291
+ if (signal !== undefined && (signal === null || typeof signal !== "object" || !("aborted" in signal)))
292
+ throw ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
293
+ }
294
+ function validateNumber(value, name, min, max) {
295
+ if (typeof value !== "number")
296
+ throw ERR_INVALID_ARG_TYPE(name, "number", value);
297
+ if (min != null && value < min || max != null && value > max || (min != null || max != null) && Number.isNaN(value))
298
+ throw ERR_OUT_OF_RANGE(name, `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, value);
299
+ }
300
+ function checkListener(listener) {
301
+ if (typeof listener !== "function")
302
+ throw TypeError("The listener must be a function");
303
+ }
304
+ function validateBoolean(value, name) {
305
+ if (typeof value !== "boolean")
306
+ throw ERR_INVALID_ARG_TYPE(name, "boolean", value);
307
+ }
308
+ function getMaxListeners2(emitterOrTarget) {
309
+ return emitterOrTarget?._maxListeners ?? defaultMaxListeners;
310
+ }
311
+ function addAbortListener(signal, listener) {
312
+ if (signal === undefined)
313
+ throw ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal);
314
+ if (validateAbortSignal(signal, "signal"), typeof listener !== "function")
315
+ throw ERR_INVALID_ARG_TYPE("listener", "function", listener);
316
+ let removeEventListener;
317
+ if (signal.aborted)
318
+ queueMicrotask(() => listener());
319
+ else
320
+ signal.addEventListener("abort", listener, { __proto__: null, once: true }), removeEventListener = () => {
321
+ signal.removeEventListener("abort", listener);
322
+ };
323
+ return { __proto__: null, [Symbol.dispose]() {
324
+ removeEventListener?.();
325
+ } };
326
+ }
327
+ var SymbolFor, kCapture, kErrorMonitor, kMaxEventTargetListeners, kMaxEventTargetListenersWarned, kRejection, captureRejectionSymbol, ArrayPrototypeSlice, defaultMaxListeners = 10, EventEmitter = function(opts) {
328
+ if (this._events === undefined || this._events === this.__proto__._events)
329
+ this._events = { __proto__: null }, this._eventsCount = 0;
330
+ if (this._maxListeners ??= undefined, this[kCapture] = opts?.captureRejections ? Boolean(opts?.captureRejections) : EventEmitterPrototype[kCapture])
331
+ this.emit = emitWithRejectionCapture;
332
+ }, EventEmitterPrototype, emitWithoutRejectionCapture = function(type, ...args) {
333
+ if (type === "error")
334
+ return emitError(this, args);
335
+ var { _events: events } = this;
336
+ if (events === undefined)
337
+ return false;
338
+ var handlers = events[type];
339
+ if (handlers === undefined)
340
+ return false;
341
+ let maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
342
+ for (let i = 0, { length } = maybeClonedHandlers;i < length; i++) {
343
+ let handler = maybeClonedHandlers[i];
344
+ switch (args.length) {
345
+ case 0:
346
+ handler.call(this);
347
+ break;
348
+ case 1:
349
+ handler.call(this, args[0]);
350
+ break;
351
+ case 2:
352
+ handler.call(this, args[0], args[1]);
353
+ break;
354
+ case 3:
355
+ handler.call(this, args[0], args[1], args[2]);
356
+ break;
357
+ default:
358
+ handler.apply(this, args);
359
+ break;
360
+ }
361
+ }
362
+ return true;
363
+ }, emitWithRejectionCapture = function(type, ...args) {
364
+ if (type === "error")
365
+ return emitError(this, args);
366
+ var { _events: events } = this;
367
+ if (events === undefined)
368
+ return false;
369
+ var handlers = events[type];
370
+ if (handlers === undefined)
371
+ return false;
372
+ let maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
373
+ for (let i = 0, { length } = maybeClonedHandlers;i < length; i++) {
374
+ let handler = maybeClonedHandlers[i], result;
375
+ switch (args.length) {
376
+ case 0:
377
+ result = handler.call(this);
378
+ break;
379
+ case 1:
380
+ result = handler.call(this, args[0]);
381
+ break;
382
+ case 2:
383
+ result = handler.call(this, args[0], args[1]);
384
+ break;
385
+ case 3:
386
+ result = handler.call(this, args[0], args[1], args[2]);
387
+ break;
388
+ default:
389
+ result = handler.apply(this, args);
390
+ break;
391
+ }
392
+ if (result !== undefined && typeof result?.then === "function" && result.then === Promise.prototype.then)
393
+ addCatch(this, result, type, args);
394
+ }
395
+ return true;
396
+ }, AbortError, events_default;
397
+ var init_events = __esm(() => {
398
+ SymbolFor = Symbol.for;
399
+ kCapture = Symbol("kCapture");
400
+ kErrorMonitor = SymbolFor("events.errorMonitor");
401
+ kMaxEventTargetListeners = Symbol("events.maxEventTargetListeners");
402
+ kMaxEventTargetListenersWarned = Symbol("events.maxEventTargetListenersWarned");
403
+ kRejection = SymbolFor("nodejs.rejection");
404
+ captureRejectionSymbol = SymbolFor("nodejs.rejection");
405
+ ArrayPrototypeSlice = Array.prototype.slice;
406
+ EventEmitterPrototype = EventEmitter.prototype = {};
407
+ EventEmitterPrototype._events = undefined;
408
+ EventEmitterPrototype._eventsCount = 0;
409
+ EventEmitterPrototype._maxListeners = undefined;
410
+ EventEmitterPrototype.setMaxListeners = function(n) {
411
+ return validateNumber(n, "setMaxListeners", 0), this._maxListeners = n, this;
412
+ };
413
+ EventEmitterPrototype.constructor = EventEmitter;
414
+ EventEmitterPrototype.getMaxListeners = function() {
415
+ return this?._maxListeners ?? defaultMaxListeners;
416
+ };
417
+ EventEmitterPrototype.emit = emitWithoutRejectionCapture;
418
+ EventEmitterPrototype.addListener = function(type, fn) {
419
+ checkListener(fn);
420
+ var events = this._events;
421
+ if (!events)
422
+ events = this._events = { __proto__: null }, this._eventsCount = 0;
423
+ else if (events.newListener)
424
+ this.emit("newListener", type, fn.listener ?? fn);
425
+ var handlers = events[type];
426
+ if (!handlers)
427
+ events[type] = [fn], this._eventsCount++;
428
+ else {
429
+ handlers.push(fn);
430
+ var m = this._maxListeners ?? defaultMaxListeners;
431
+ if (m > 0 && handlers.length > m && !handlers.warned)
432
+ overflowWarning(this, type, handlers);
433
+ }
434
+ return this;
435
+ };
436
+ EventEmitterPrototype.on = EventEmitterPrototype.addListener;
437
+ EventEmitterPrototype.prependListener = function(type, fn) {
438
+ checkListener(fn);
439
+ var events = this._events;
440
+ if (!events)
441
+ events = this._events = { __proto__: null }, this._eventsCount = 0;
442
+ else if (events.newListener)
443
+ this.emit("newListener", type, fn.listener ?? fn);
444
+ var handlers = events[type];
445
+ if (!handlers)
446
+ events[type] = [fn], this._eventsCount++;
447
+ else {
448
+ handlers.unshift(fn);
449
+ var m = this._maxListeners ?? defaultMaxListeners;
450
+ if (m > 0 && handlers.length > m && !handlers.warned)
451
+ overflowWarning(this, type, handlers);
452
+ }
453
+ return this;
454
+ };
455
+ EventEmitterPrototype.once = function(type, fn) {
456
+ checkListener(fn);
457
+ let bound = onceWrapper.bind(this, type, fn);
458
+ return bound.listener = fn, this.addListener(type, bound), this;
459
+ };
460
+ EventEmitterPrototype.prependOnceListener = function(type, fn) {
461
+ checkListener(fn);
462
+ let bound = onceWrapper.bind(this, type, fn);
463
+ return bound.listener = fn, this.prependListener(type, bound), this;
464
+ };
465
+ EventEmitterPrototype.removeListener = function(type, fn) {
466
+ checkListener(fn);
467
+ var { _events: events } = this;
468
+ if (!events)
469
+ return this;
470
+ var handlers = events[type];
471
+ if (!handlers)
472
+ return this;
473
+ var length = handlers.length;
474
+ let position = -1;
475
+ for (let i = length - 1;i >= 0; i--)
476
+ if (handlers[i] === fn || handlers[i].listener === fn) {
477
+ position = i;
478
+ break;
479
+ }
480
+ if (position < 0)
481
+ return this;
482
+ if (position === 0)
483
+ handlers.shift();
484
+ else
485
+ handlers.splice(position, 1);
486
+ if (handlers.length === 0)
487
+ delete events[type], this._eventsCount--;
488
+ return this;
489
+ };
490
+ EventEmitterPrototype.off = EventEmitterPrototype.removeListener;
491
+ EventEmitterPrototype.removeAllListeners = function(type) {
492
+ var { _events: events } = this;
493
+ if (type && events) {
494
+ if (events[type])
495
+ delete events[type], this._eventsCount--;
496
+ } else
497
+ this._events = { __proto__: null };
498
+ return this;
499
+ };
500
+ EventEmitterPrototype.listeners = function(type) {
501
+ var { _events: events } = this;
502
+ if (!events)
503
+ return [];
504
+ var handlers = events[type];
505
+ if (!handlers)
506
+ return [];
507
+ return handlers.map((x) => x.listener ?? x);
508
+ };
509
+ EventEmitterPrototype.rawListeners = function(type) {
510
+ var { _events } = this;
511
+ if (!_events)
512
+ return [];
513
+ var handlers = _events[type];
514
+ if (!handlers)
515
+ return [];
516
+ return handlers.slice();
517
+ };
518
+ EventEmitterPrototype.listenerCount = function(type) {
519
+ var { _events: events } = this;
520
+ if (!events)
521
+ return 0;
522
+ return events[type]?.length ?? 0;
523
+ };
524
+ EventEmitterPrototype.eventNames = function() {
525
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
526
+ };
527
+ EventEmitterPrototype[kCapture] = false;
528
+ AbortError = class AbortError extends Error {
529
+ constructor(message = "The operation was aborted", options = undefined) {
530
+ if (options !== undefined && typeof options !== "object")
531
+ throw ERR_INVALID_ARG_TYPE("options", "Object", options);
532
+ super(message, options);
533
+ this.code = "ABORT_ERR", this.name = "AbortError";
534
+ }
535
+ };
536
+ Object.defineProperties(EventEmitter, { captureRejections: { get() {
537
+ return EventEmitterPrototype[kCapture];
538
+ }, set(value) {
539
+ validateBoolean(value, "EventEmitter.captureRejections"), EventEmitterPrototype[kCapture] = value;
540
+ }, enumerable: true }, defaultMaxListeners: { enumerable: true, get: () => {
541
+ return defaultMaxListeners;
542
+ }, set: (arg) => {
543
+ validateNumber(arg, "defaultMaxListeners", 0), defaultMaxListeners = arg;
544
+ } }, kMaxEventTargetListeners: { value: kMaxEventTargetListeners, enumerable: false, configurable: false, writable: false }, kMaxEventTargetListenersWarned: { value: kMaxEventTargetListenersWarned, enumerable: false, configurable: false, writable: false } });
545
+ Object.assign(EventEmitter, { once: once2, getEventListeners, getMaxListeners: getMaxListeners2, setMaxListeners: setMaxListeners2, EventEmitter, usingDomains: false, captureRejectionSymbol, errorMonitor: kErrorMonitor, addAbortListener, init: EventEmitter, listenerCount: listenerCount2 });
546
+ events_default = EventEmitter;
547
+ });
548
+
549
+ // node:path
550
+ var exports_path = {};
551
+ __export(exports_path, {
552
+ sep: () => sep,
553
+ resolve: () => resolve,
554
+ relative: () => relative,
555
+ posix: () => posix,
556
+ parse: () => parse,
557
+ normalize: () => normalize,
558
+ join: () => join,
559
+ isAbsolute: () => isAbsolute,
560
+ format: () => format,
561
+ extname: () => extname,
562
+ dirname: () => dirname,
563
+ delimiter: () => delimiter,
564
+ default: () => path_default,
565
+ basename: () => basename,
566
+ _makeLong: () => _makeLong
567
+ });
568
+ function assertPath(path) {
569
+ if (typeof path !== "string")
570
+ throw TypeError("Path must be a string. Received " + JSON.stringify(path));
571
+ }
572
+ function normalizeStringPosix(path, allowAboveRoot) {
573
+ var res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, code;
574
+ for (var i = 0;i <= path.length; ++i) {
575
+ if (i < path.length)
576
+ code = path.charCodeAt(i);
577
+ else if (code === 47)
578
+ break;
579
+ else
580
+ code = 47;
581
+ if (code === 47) {
582
+ if (lastSlash === i - 1 || dots === 1)
583
+ ;
584
+ else if (lastSlash !== i - 1 && dots === 2) {
585
+ if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) {
586
+ if (res.length > 2) {
587
+ var lastSlashIndex = res.lastIndexOf("/");
588
+ if (lastSlashIndex !== res.length - 1) {
589
+ if (lastSlashIndex === -1)
590
+ res = "", lastSegmentLength = 0;
591
+ else
592
+ res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
593
+ lastSlash = i, dots = 0;
594
+ continue;
595
+ }
596
+ } else if (res.length === 2 || res.length === 1) {
597
+ res = "", lastSegmentLength = 0, lastSlash = i, dots = 0;
598
+ continue;
599
+ }
600
+ }
601
+ if (allowAboveRoot) {
602
+ if (res.length > 0)
603
+ res += "/..";
604
+ else
605
+ res = "..";
606
+ lastSegmentLength = 2;
607
+ }
608
+ } else {
609
+ if (res.length > 0)
610
+ res += "/" + path.slice(lastSlash + 1, i);
611
+ else
612
+ res = path.slice(lastSlash + 1, i);
613
+ lastSegmentLength = i - lastSlash - 1;
614
+ }
615
+ lastSlash = i, dots = 0;
616
+ } else if (code === 46 && dots !== -1)
617
+ ++dots;
618
+ else
619
+ dots = -1;
620
+ }
621
+ return res;
622
+ }
623
+ function _format(sep, pathObject) {
624
+ var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
625
+ if (!dir)
626
+ return base;
627
+ if (dir === pathObject.root)
628
+ return dir + base;
629
+ return dir + sep + base;
630
+ }
631
+ function resolve() {
632
+ var resolvedPath = "", resolvedAbsolute = false, cwd;
633
+ for (var i = arguments.length - 1;i >= -1 && !resolvedAbsolute; i--) {
634
+ var path;
635
+ if (i >= 0)
636
+ path = arguments[i];
637
+ else {
638
+ if (cwd === undefined)
639
+ cwd = process.cwd();
640
+ path = cwd;
641
+ }
642
+ if (assertPath(path), path.length === 0)
643
+ continue;
644
+ resolvedPath = path + "/" + resolvedPath, resolvedAbsolute = path.charCodeAt(0) === 47;
645
+ }
646
+ if (resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute)
647
+ if (resolvedPath.length > 0)
648
+ return "/" + resolvedPath;
649
+ else
650
+ return "/";
651
+ else if (resolvedPath.length > 0)
652
+ return resolvedPath;
653
+ else
654
+ return ".";
655
+ }
656
+ function normalize(path) {
657
+ if (assertPath(path), path.length === 0)
658
+ return ".";
659
+ var isAbsolute = path.charCodeAt(0) === 47, trailingSeparator = path.charCodeAt(path.length - 1) === 47;
660
+ if (path = normalizeStringPosix(path, !isAbsolute), path.length === 0 && !isAbsolute)
661
+ path = ".";
662
+ if (path.length > 0 && trailingSeparator)
663
+ path += "/";
664
+ if (isAbsolute)
665
+ return "/" + path;
666
+ return path;
667
+ }
668
+ function isAbsolute(path) {
669
+ return assertPath(path), path.length > 0 && path.charCodeAt(0) === 47;
670
+ }
671
+ function join() {
672
+ if (arguments.length === 0)
673
+ return ".";
674
+ var joined;
675
+ for (var i = 0;i < arguments.length; ++i) {
676
+ var arg = arguments[i];
677
+ if (assertPath(arg), arg.length > 0)
678
+ if (joined === undefined)
679
+ joined = arg;
680
+ else
681
+ joined += "/" + arg;
682
+ }
683
+ if (joined === undefined)
684
+ return ".";
685
+ return normalize(joined);
686
+ }
687
+ function relative(from, to) {
688
+ if (assertPath(from), assertPath(to), from === to)
689
+ return "";
690
+ if (from = resolve(from), to = resolve(to), from === to)
691
+ return "";
692
+ var fromStart = 1;
693
+ for (;fromStart < from.length; ++fromStart)
694
+ if (from.charCodeAt(fromStart) !== 47)
695
+ break;
696
+ var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1;
697
+ for (;toStart < to.length; ++toStart)
698
+ if (to.charCodeAt(toStart) !== 47)
699
+ break;
700
+ var toEnd = to.length, toLen = toEnd - toStart, length = fromLen < toLen ? fromLen : toLen, lastCommonSep = -1, i = 0;
701
+ for (;i <= length; ++i) {
702
+ if (i === length) {
703
+ if (toLen > length) {
704
+ if (to.charCodeAt(toStart + i) === 47)
705
+ return to.slice(toStart + i + 1);
706
+ else if (i === 0)
707
+ return to.slice(toStart + i);
708
+ } else if (fromLen > length) {
709
+ if (from.charCodeAt(fromStart + i) === 47)
710
+ lastCommonSep = i;
711
+ else if (i === 0)
712
+ lastCommonSep = 0;
713
+ }
714
+ break;
715
+ }
716
+ var fromCode = from.charCodeAt(fromStart + i), toCode = to.charCodeAt(toStart + i);
717
+ if (fromCode !== toCode)
718
+ break;
719
+ else if (fromCode === 47)
720
+ lastCommonSep = i;
721
+ }
722
+ var out = "";
723
+ for (i = fromStart + lastCommonSep + 1;i <= fromEnd; ++i)
724
+ if (i === fromEnd || from.charCodeAt(i) === 47)
725
+ if (out.length === 0)
726
+ out += "..";
727
+ else
728
+ out += "/..";
729
+ if (out.length > 0)
730
+ return out + to.slice(toStart + lastCommonSep);
731
+ else {
732
+ if (toStart += lastCommonSep, to.charCodeAt(toStart) === 47)
733
+ ++toStart;
734
+ return to.slice(toStart);
735
+ }
736
+ }
737
+ function _makeLong(path) {
738
+ return path;
739
+ }
740
+ function dirname(path) {
741
+ if (assertPath(path), path.length === 0)
742
+ return ".";
743
+ var code = path.charCodeAt(0), hasRoot = code === 47, end = -1, matchedSlash = true;
744
+ for (var i = path.length - 1;i >= 1; --i)
745
+ if (code = path.charCodeAt(i), code === 47) {
746
+ if (!matchedSlash) {
747
+ end = i;
748
+ break;
749
+ }
750
+ } else
751
+ matchedSlash = false;
752
+ if (end === -1)
753
+ return hasRoot ? "/" : ".";
754
+ if (hasRoot && end === 1)
755
+ return "//";
756
+ return path.slice(0, end);
757
+ }
758
+ function basename(path, ext) {
759
+ if (ext !== undefined && typeof ext !== "string")
760
+ throw TypeError('"ext" argument must be a string');
761
+ assertPath(path);
762
+ var start = 0, end = -1, matchedSlash = true, i;
763
+ if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
764
+ if (ext.length === path.length && ext === path)
765
+ return "";
766
+ var extIdx = ext.length - 1, firstNonSlashEnd = -1;
767
+ for (i = path.length - 1;i >= 0; --i) {
768
+ var code = path.charCodeAt(i);
769
+ if (code === 47) {
770
+ if (!matchedSlash) {
771
+ start = i + 1;
772
+ break;
773
+ }
774
+ } else {
775
+ if (firstNonSlashEnd === -1)
776
+ matchedSlash = false, firstNonSlashEnd = i + 1;
777
+ if (extIdx >= 0)
778
+ if (code === ext.charCodeAt(extIdx)) {
779
+ if (--extIdx === -1)
780
+ end = i;
781
+ } else
782
+ extIdx = -1, end = firstNonSlashEnd;
783
+ }
784
+ }
785
+ if (start === end)
786
+ end = firstNonSlashEnd;
787
+ else if (end === -1)
788
+ end = path.length;
789
+ return path.slice(start, end);
790
+ } else {
791
+ for (i = path.length - 1;i >= 0; --i)
792
+ if (path.charCodeAt(i) === 47) {
793
+ if (!matchedSlash) {
794
+ start = i + 1;
795
+ break;
796
+ }
797
+ } else if (end === -1)
798
+ matchedSlash = false, end = i + 1;
799
+ if (end === -1)
800
+ return "";
801
+ return path.slice(start, end);
802
+ }
803
+ }
804
+ function extname(path) {
805
+ assertPath(path);
806
+ var startDot = -1, startPart = 0, end = -1, matchedSlash = true, preDotState = 0;
807
+ for (var i = path.length - 1;i >= 0; --i) {
808
+ var code = path.charCodeAt(i);
809
+ if (code === 47) {
810
+ if (!matchedSlash) {
811
+ startPart = i + 1;
812
+ break;
813
+ }
814
+ continue;
815
+ }
816
+ if (end === -1)
817
+ matchedSlash = false, end = i + 1;
818
+ if (code === 46) {
819
+ if (startDot === -1)
820
+ startDot = i;
821
+ else if (preDotState !== 1)
822
+ preDotState = 1;
823
+ } else if (startDot !== -1)
824
+ preDotState = -1;
825
+ }
826
+ if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
827
+ return "";
828
+ return path.slice(startDot, end);
829
+ }
830
+ function format(pathObject) {
831
+ if (pathObject === null || typeof pathObject !== "object")
832
+ throw TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
833
+ return _format("/", pathObject);
834
+ }
835
+ function parse(path) {
836
+ assertPath(path);
837
+ var ret = { root: "", dir: "", base: "", ext: "", name: "" };
838
+ if (path.length === 0)
839
+ return ret;
840
+ var code = path.charCodeAt(0), isAbsolute2 = code === 47, start;
841
+ if (isAbsolute2)
842
+ ret.root = "/", start = 1;
843
+ else
844
+ start = 0;
845
+ var startDot = -1, startPart = 0, end = -1, matchedSlash = true, i = path.length - 1, preDotState = 0;
846
+ for (;i >= start; --i) {
847
+ if (code = path.charCodeAt(i), code === 47) {
848
+ if (!matchedSlash) {
849
+ startPart = i + 1;
850
+ break;
851
+ }
852
+ continue;
853
+ }
854
+ if (end === -1)
855
+ matchedSlash = false, end = i + 1;
856
+ if (code === 46) {
857
+ if (startDot === -1)
858
+ startDot = i;
859
+ else if (preDotState !== 1)
860
+ preDotState = 1;
861
+ } else if (startDot !== -1)
862
+ preDotState = -1;
863
+ }
864
+ if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
865
+ if (end !== -1)
866
+ if (startPart === 0 && isAbsolute2)
867
+ ret.base = ret.name = path.slice(1, end);
868
+ else
869
+ ret.base = ret.name = path.slice(startPart, end);
870
+ } else {
871
+ if (startPart === 0 && isAbsolute2)
872
+ ret.name = path.slice(1, startDot), ret.base = path.slice(1, end);
873
+ else
874
+ ret.name = path.slice(startPart, startDot), ret.base = path.slice(startPart, end);
875
+ ret.ext = path.slice(startDot, end);
876
+ }
877
+ if (startPart > 0)
878
+ ret.dir = path.slice(0, startPart - 1);
879
+ else if (isAbsolute2)
880
+ ret.dir = "/";
881
+ return ret;
882
+ }
883
+ var sep = "/", delimiter = ":", posix, path_default;
884
+ var init_path = __esm(() => {
885
+ posix = ((p) => (p.posix = p, p))({ resolve, normalize, isAbsolute, join, relative, _makeLong, dirname, basename, extname, format, parse, sep, delimiter, win32: null, posix: null });
886
+ path_default = posix;
887
+ });
888
+
889
+ // node:process
890
+ var exports_process = {};
891
+ __export(exports_process, {
892
+ versions: () => versions,
893
+ version: () => version,
894
+ umask: () => umask,
895
+ title: () => title,
896
+ removeListener: () => removeListener,
897
+ removeAllListeners: () => removeAllListeners,
898
+ prependOnceListener: () => prependOnceListener,
899
+ prependListener: () => prependListener,
900
+ once: () => once,
901
+ on: () => on,
902
+ off: () => off,
903
+ nextTick: () => nextTick,
904
+ listeners: () => listeners,
905
+ env: () => env,
906
+ emit: () => emit,
907
+ cwd: () => cwd,
908
+ chdir: () => chdir,
909
+ browser: () => browser,
910
+ binding: () => binding,
911
+ argv: () => argv,
912
+ addListener: () => addListener
913
+ });
914
+ function cleanUpNextTick() {
915
+ if (!draining || !currentQueue)
916
+ return;
917
+ if (draining = false, currentQueue.length)
918
+ queue = currentQueue.concat(queue);
919
+ else
920
+ queueIndex = -1;
921
+ if (queue.length)
922
+ drainQueue();
923
+ }
924
+ function drainQueue() {
925
+ if (draining)
926
+ return;
927
+ var timeout = setTimeout(cleanUpNextTick, 0);
928
+ draining = true;
929
+ var len = queue.length;
930
+ while (len) {
931
+ currentQueue = queue, queue = [];
932
+ while (++queueIndex < len)
933
+ if (currentQueue) {
934
+ var item = currentQueue[queueIndex];
935
+ item.fun.apply(null, item.array);
936
+ }
937
+ queueIndex = -1, len = queue.length;
938
+ }
939
+ currentQueue = null, draining = false, clearTimeout(timeout, 0);
940
+ }
941
+ function nextTick(fun) {
942
+ var args = Array(arguments.length - 1);
943
+ if (arguments.length > 1)
944
+ for (var i = 1;i < arguments.length; i++)
945
+ args[i - 1] = arguments[i];
946
+ if (queue.push({ fun, args }), queue.length === 1 && !draining)
947
+ setTimeout(drainQueue, 0);
948
+ }
949
+ function noop() {}
950
+ var queue, draining = false, currentQueue, queueIndex = -1, title = "browser", browser = true, env, argv, version = "", versions, on, addListener, once, off, removeListener, removeAllListeners, emit, prependListener, prependOnceListener, listeners = function(name) {
951
+ return [];
952
+ }, binding = function(name) {
953
+ throw Error("process.binding is not supported in browser polyfill");
954
+ }, cwd = function() {
955
+ return "/";
956
+ }, chdir = function(dir) {
957
+ throw Error("process.chdir is not supported in browser polyfill");
958
+ }, umask = function() {
959
+ return 0;
960
+ };
961
+ var init_process = __esm(() => {
962
+ queue = [];
963
+ env = {};
964
+ argv = [];
965
+ versions = {};
966
+ on = noop;
967
+ addListener = noop;
968
+ once = noop;
969
+ off = noop;
970
+ removeListener = noop;
971
+ removeAllListeners = noop;
972
+ emit = noop;
973
+ prependListener = noop;
974
+ prependOnceListener = noop;
975
+ });
976
+
977
+ // node_modules/commander/lib/help.js
978
+ var require_help = __commonJS((exports) => {
979
+ var { humanReadableArgName } = require_argument();
980
+
981
+ class Help {
982
+ constructor() {
983
+ this.helpWidth = undefined;
984
+ this.sortSubcommands = false;
985
+ this.sortOptions = false;
986
+ this.showGlobalOptions = false;
987
+ }
988
+ visibleCommands(cmd) {
989
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
990
+ const helpCommand = cmd._getHelpCommand();
991
+ if (helpCommand && !helpCommand._hidden) {
992
+ visibleCommands.push(helpCommand);
993
+ }
994
+ if (this.sortSubcommands) {
995
+ visibleCommands.sort((a, b) => {
996
+ return a.name().localeCompare(b.name());
997
+ });
998
+ }
999
+ return visibleCommands;
1000
+ }
1001
+ compareOptions(a, b) {
1002
+ const getSortKey = (option) => {
1003
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
1004
+ };
1005
+ return getSortKey(a).localeCompare(getSortKey(b));
1006
+ }
1007
+ visibleOptions(cmd) {
1008
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
1009
+ const helpOption = cmd._getHelpOption();
1010
+ if (helpOption && !helpOption.hidden) {
1011
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
1012
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
1013
+ if (!removeShort && !removeLong) {
1014
+ visibleOptions.push(helpOption);
1015
+ } else if (helpOption.long && !removeLong) {
1016
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
1017
+ } else if (helpOption.short && !removeShort) {
1018
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
1019
+ }
1020
+ }
1021
+ if (this.sortOptions) {
1022
+ visibleOptions.sort(this.compareOptions);
1023
+ }
1024
+ return visibleOptions;
1025
+ }
1026
+ visibleGlobalOptions(cmd) {
1027
+ if (!this.showGlobalOptions)
1028
+ return [];
1029
+ const globalOptions = [];
1030
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1031
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
1032
+ globalOptions.push(...visibleOptions);
1033
+ }
1034
+ if (this.sortOptions) {
1035
+ globalOptions.sort(this.compareOptions);
1036
+ }
1037
+ return globalOptions;
1038
+ }
1039
+ visibleArguments(cmd) {
1040
+ if (cmd._argsDescription) {
1041
+ cmd.registeredArguments.forEach((argument) => {
1042
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
1043
+ });
1044
+ }
1045
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
1046
+ return cmd.registeredArguments;
1047
+ }
1048
+ return [];
1049
+ }
1050
+ subcommandTerm(cmd) {
1051
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
1052
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
1053
+ }
1054
+ optionTerm(option) {
1055
+ return option.flags;
1056
+ }
1057
+ argumentTerm(argument) {
1058
+ return argument.name();
1059
+ }
1060
+ longestSubcommandTermLength(cmd, helper) {
1061
+ return helper.visibleCommands(cmd).reduce((max, command) => {
1062
+ return Math.max(max, helper.subcommandTerm(command).length);
1063
+ }, 0);
1064
+ }
1065
+ longestOptionTermLength(cmd, helper) {
1066
+ return helper.visibleOptions(cmd).reduce((max, option) => {
1067
+ return Math.max(max, helper.optionTerm(option).length);
1068
+ }, 0);
1069
+ }
1070
+ longestGlobalOptionTermLength(cmd, helper) {
1071
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
1072
+ return Math.max(max, helper.optionTerm(option).length);
1073
+ }, 0);
1074
+ }
1075
+ longestArgumentTermLength(cmd, helper) {
1076
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
1077
+ return Math.max(max, helper.argumentTerm(argument).length);
1078
+ }, 0);
1079
+ }
1080
+ commandUsage(cmd) {
1081
+ let cmdName = cmd._name;
1082
+ if (cmd._aliases[0]) {
1083
+ cmdName = cmdName + "|" + cmd._aliases[0];
1084
+ }
1085
+ let ancestorCmdNames = "";
1086
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1087
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
1088
+ }
1089
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
1090
+ }
1091
+ commandDescription(cmd) {
1092
+ return cmd.description();
1093
+ }
1094
+ subcommandDescription(cmd) {
1095
+ return cmd.summary() || cmd.description();
1096
+ }
1097
+ optionDescription(option) {
1098
+ const extraInfo = [];
1099
+ if (option.argChoices) {
1100
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1101
+ }
1102
+ if (option.defaultValue !== undefined) {
1103
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
1104
+ if (showDefault) {
1105
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
1106
+ }
1107
+ }
1108
+ if (option.presetArg !== undefined && option.optional) {
1109
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
1110
+ }
1111
+ if (option.envVar !== undefined) {
1112
+ extraInfo.push(`env: ${option.envVar}`);
1113
+ }
1114
+ if (extraInfo.length > 0) {
1115
+ return `${option.description} (${extraInfo.join(", ")})`;
1116
+ }
1117
+ return option.description;
1118
+ }
1119
+ argumentDescription(argument) {
1120
+ const extraInfo = [];
1121
+ if (argument.argChoices) {
1122
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1123
+ }
1124
+ if (argument.defaultValue !== undefined) {
1125
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
1126
+ }
1127
+ if (extraInfo.length > 0) {
1128
+ const extraDescripton = `(${extraInfo.join(", ")})`;
1129
+ if (argument.description) {
1130
+ return `${argument.description} ${extraDescripton}`;
1131
+ }
1132
+ return extraDescripton;
1133
+ }
1134
+ return argument.description;
1135
+ }
1136
+ formatHelp(cmd, helper) {
1137
+ const termWidth = helper.padWidth(cmd, helper);
1138
+ const helpWidth = helper.helpWidth || 80;
1139
+ const itemIndentWidth = 2;
1140
+ const itemSeparatorWidth = 2;
1141
+ function formatItem(term, description) {
1142
+ if (description) {
1143
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
1144
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
1145
+ }
1146
+ return term;
1147
+ }
1148
+ function formatList(textArray) {
1149
+ return textArray.join(`
1150
+ `).replace(/^/gm, " ".repeat(itemIndentWidth));
1151
+ }
1152
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
1153
+ const commandDescription = helper.commandDescription(cmd);
1154
+ if (commandDescription.length > 0) {
1155
+ output = output.concat([
1156
+ helper.wrap(commandDescription, helpWidth, 0),
1157
+ ""
1158
+ ]);
1159
+ }
1160
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
1161
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
1162
+ });
1163
+ if (argumentList.length > 0) {
1164
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
1165
+ }
1166
+ const optionList = helper.visibleOptions(cmd).map((option) => {
1167
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
1168
+ });
1169
+ if (optionList.length > 0) {
1170
+ output = output.concat(["Options:", formatList(optionList), ""]);
1171
+ }
1172
+ if (this.showGlobalOptions) {
1173
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
1174
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
1175
+ });
1176
+ if (globalOptionList.length > 0) {
1177
+ output = output.concat([
1178
+ "Global Options:",
1179
+ formatList(globalOptionList),
1180
+ ""
1181
+ ]);
1182
+ }
1183
+ }
1184
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
1185
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
1186
+ });
1187
+ if (commandList.length > 0) {
1188
+ output = output.concat(["Commands:", formatList(commandList), ""]);
1189
+ }
1190
+ return output.join(`
1191
+ `);
1192
+ }
1193
+ padWidth(cmd, helper) {
1194
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
1195
+ }
1196
+ wrap(str, width, indent, minColumnWidth = 40) {
1197
+ const indents = " \\f\\t\\v   -    \uFEFF";
1198
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
1199
+ if (str.match(manualIndent))
1200
+ return str;
1201
+ const columnWidth = width - indent;
1202
+ if (columnWidth < minColumnWidth)
1203
+ return str;
1204
+ const leadingStr = str.slice(0, indent);
1205
+ const columnText = str.slice(indent).replace(`\r
1206
+ `, `
1207
+ `);
1208
+ const indentString = " ".repeat(indent);
1209
+ const zeroWidthSpace = "​";
1210
+ const breaks = `\\s${zeroWidthSpace}`;
1211
+ const regex = new RegExp(`
1212
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
1213
+ const lines = columnText.match(regex) || [];
1214
+ return leadingStr + lines.map((line, i) => {
1215
+ if (line === `
1216
+ `)
1217
+ return "";
1218
+ return (i > 0 ? indentString : "") + line.trimEnd();
1219
+ }).join(`
1220
+ `);
1221
+ }
1222
+ }
1223
+ exports.Help = Help;
1224
+ });
1225
+
1226
+ // node_modules/commander/lib/option.js
1227
+ var require_option = __commonJS((exports) => {
1228
+ var { InvalidArgumentError } = require_error();
1229
+
1230
+ class Option {
1231
+ constructor(flags, description) {
1232
+ this.flags = flags;
1233
+ this.description = description || "";
1234
+ this.required = flags.includes("<");
1235
+ this.optional = flags.includes("[");
1236
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1237
+ this.mandatory = false;
1238
+ const optionFlags = splitOptionFlags(flags);
1239
+ this.short = optionFlags.shortFlag;
1240
+ this.long = optionFlags.longFlag;
1241
+ this.negate = false;
1242
+ if (this.long) {
1243
+ this.negate = this.long.startsWith("--no-");
1244
+ }
1245
+ this.defaultValue = undefined;
1246
+ this.defaultValueDescription = undefined;
1247
+ this.presetArg = undefined;
1248
+ this.envVar = undefined;
1249
+ this.parseArg = undefined;
1250
+ this.hidden = false;
1251
+ this.argChoices = undefined;
1252
+ this.conflictsWith = [];
1253
+ this.implied = undefined;
1254
+ }
1255
+ default(value, description) {
1256
+ this.defaultValue = value;
1257
+ this.defaultValueDescription = description;
1258
+ return this;
1259
+ }
1260
+ preset(arg) {
1261
+ this.presetArg = arg;
1262
+ return this;
1263
+ }
1264
+ conflicts(names) {
1265
+ this.conflictsWith = this.conflictsWith.concat(names);
1266
+ return this;
1267
+ }
1268
+ implies(impliedOptionValues) {
1269
+ let newImplied = impliedOptionValues;
1270
+ if (typeof impliedOptionValues === "string") {
1271
+ newImplied = { [impliedOptionValues]: true };
1272
+ }
1273
+ this.implied = Object.assign(this.implied || {}, newImplied);
1274
+ return this;
1275
+ }
1276
+ env(name) {
1277
+ this.envVar = name;
1278
+ return this;
1279
+ }
1280
+ argParser(fn) {
1281
+ this.parseArg = fn;
1282
+ return this;
1283
+ }
1284
+ makeOptionMandatory(mandatory = true) {
1285
+ this.mandatory = !!mandatory;
1286
+ return this;
1287
+ }
1288
+ hideHelp(hide = true) {
1289
+ this.hidden = !!hide;
1290
+ return this;
1291
+ }
1292
+ _concatValue(value, previous) {
1293
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1294
+ return [value];
1295
+ }
1296
+ return previous.concat(value);
1297
+ }
1298
+ choices(values) {
1299
+ this.argChoices = values.slice();
1300
+ this.parseArg = (arg, previous) => {
1301
+ if (!this.argChoices.includes(arg)) {
1302
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
1303
+ }
1304
+ if (this.variadic) {
1305
+ return this._concatValue(arg, previous);
1306
+ }
1307
+ return arg;
1308
+ };
1309
+ return this;
1310
+ }
1311
+ name() {
1312
+ if (this.long) {
1313
+ return this.long.replace(/^--/, "");
1314
+ }
1315
+ return this.short.replace(/^-/, "");
1316
+ }
1317
+ attributeName() {
1318
+ return camelcase(this.name().replace(/^no-/, ""));
1319
+ }
1320
+ is(arg) {
1321
+ return this.short === arg || this.long === arg;
1322
+ }
1323
+ isBoolean() {
1324
+ return !this.required && !this.optional && !this.negate;
1325
+ }
1326
+ }
1327
+
1328
+ class DualOptions {
1329
+ constructor(options) {
1330
+ this.positiveOptions = new Map;
1331
+ this.negativeOptions = new Map;
1332
+ this.dualOptions = new Set;
1333
+ options.forEach((option) => {
1334
+ if (option.negate) {
1335
+ this.negativeOptions.set(option.attributeName(), option);
1336
+ } else {
1337
+ this.positiveOptions.set(option.attributeName(), option);
1338
+ }
1339
+ });
1340
+ this.negativeOptions.forEach((value, key) => {
1341
+ if (this.positiveOptions.has(key)) {
1342
+ this.dualOptions.add(key);
1343
+ }
1344
+ });
1345
+ }
1346
+ valueFromOption(value, option) {
1347
+ const optionKey = option.attributeName();
1348
+ if (!this.dualOptions.has(optionKey))
1349
+ return true;
1350
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1351
+ const negativeValue = preset !== undefined ? preset : false;
1352
+ return option.negate === (negativeValue === value);
1353
+ }
1354
+ }
1355
+ function camelcase(str) {
1356
+ return str.split("-").reduce((str2, word) => {
1357
+ return str2 + word[0].toUpperCase() + word.slice(1);
1358
+ });
1359
+ }
1360
+ function splitOptionFlags(flags) {
1361
+ let shortFlag;
1362
+ let longFlag;
1363
+ const flagParts = flags.split(/[ |,]+/);
1364
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
1365
+ shortFlag = flagParts.shift();
1366
+ longFlag = flagParts.shift();
1367
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
1368
+ shortFlag = longFlag;
1369
+ longFlag = undefined;
1370
+ }
1371
+ return { shortFlag, longFlag };
1372
+ }
1373
+ exports.Option = Option;
1374
+ exports.DualOptions = DualOptions;
1375
+ });
1376
+
1377
+ // node_modules/commander/lib/suggestSimilar.js
1378
+ var require_suggestSimilar = __commonJS((exports) => {
1379
+ var maxDistance = 3;
1380
+ function editDistance(a, b) {
1381
+ if (Math.abs(a.length - b.length) > maxDistance)
1382
+ return Math.max(a.length, b.length);
1383
+ const d = [];
1384
+ for (let i = 0;i <= a.length; i++) {
1385
+ d[i] = [i];
1386
+ }
1387
+ for (let j = 0;j <= b.length; j++) {
1388
+ d[0][j] = j;
1389
+ }
1390
+ for (let j = 1;j <= b.length; j++) {
1391
+ for (let i = 1;i <= a.length; i++) {
1392
+ let cost = 1;
1393
+ if (a[i - 1] === b[j - 1]) {
1394
+ cost = 0;
1395
+ } else {
1396
+ cost = 1;
1397
+ }
1398
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1399
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1400
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1401
+ }
1402
+ }
1403
+ }
1404
+ return d[a.length][b.length];
1405
+ }
1406
+ function suggestSimilar(word, candidates) {
1407
+ if (!candidates || candidates.length === 0)
1408
+ return "";
1409
+ candidates = Array.from(new Set(candidates));
1410
+ const searchingOptions = word.startsWith("--");
1411
+ if (searchingOptions) {
1412
+ word = word.slice(2);
1413
+ candidates = candidates.map((candidate) => candidate.slice(2));
1414
+ }
1415
+ let similar = [];
1416
+ let bestDistance = maxDistance;
1417
+ const minSimilarity = 0.4;
1418
+ candidates.forEach((candidate) => {
1419
+ if (candidate.length <= 1)
1420
+ return;
1421
+ const distance = editDistance(word, candidate);
1422
+ const length = Math.max(word.length, candidate.length);
1423
+ const similarity = (length - distance) / length;
1424
+ if (similarity > minSimilarity) {
1425
+ if (distance < bestDistance) {
1426
+ bestDistance = distance;
1427
+ similar = [candidate];
1428
+ } else if (distance === bestDistance) {
1429
+ similar.push(candidate);
1430
+ }
1431
+ }
1432
+ });
1433
+ similar.sort((a, b) => a.localeCompare(b));
1434
+ if (searchingOptions) {
1435
+ similar = similar.map((candidate) => `--${candidate}`);
1436
+ }
1437
+ if (similar.length > 1) {
1438
+ return `
1439
+ (Did you mean one of ${similar.join(", ")}?)`;
1440
+ }
1441
+ if (similar.length === 1) {
1442
+ return `
1443
+ (Did you mean ${similar[0]}?)`;
1444
+ }
1445
+ return "";
1446
+ }
1447
+ exports.suggestSimilar = suggestSimilar;
1448
+ });
1449
+
1450
+ // node_modules/commander/lib/command.js
1451
+ var require_command = __commonJS((exports) => {
1452
+ var EventEmitter2 = (init_events(), __toCommonJS(exports_events)).EventEmitter;
1453
+ var childProcess = (() => ({}));
1454
+ var path = (init_path(), __toCommonJS(exports_path));
1455
+ var fs = (() => ({}));
1456
+ var process2 = (init_process(), __toCommonJS(exports_process));
1457
+ var { Argument, humanReadableArgName } = require_argument();
1458
+ var { CommanderError } = require_error();
1459
+ var { Help } = require_help();
1460
+ var { Option, DualOptions } = require_option();
1461
+ var { suggestSimilar } = require_suggestSimilar();
1462
+
1463
+ class Command extends EventEmitter2 {
1464
+ constructor(name) {
1465
+ super();
1466
+ this.commands = [];
1467
+ this.options = [];
1468
+ this.parent = null;
1469
+ this._allowUnknownOption = false;
1470
+ this._allowExcessArguments = true;
1471
+ this.registeredArguments = [];
1472
+ this._args = this.registeredArguments;
1473
+ this.args = [];
1474
+ this.rawArgs = [];
1475
+ this.processedArgs = [];
1476
+ this._scriptPath = null;
1477
+ this._name = name || "";
1478
+ this._optionValues = {};
1479
+ this._optionValueSources = {};
1480
+ this._storeOptionsAsProperties = false;
1481
+ this._actionHandler = null;
1482
+ this._executableHandler = false;
1483
+ this._executableFile = null;
1484
+ this._executableDir = null;
1485
+ this._defaultCommandName = null;
1486
+ this._exitCallback = null;
1487
+ this._aliases = [];
1488
+ this._combineFlagAndOptionalValue = true;
1489
+ this._description = "";
1490
+ this._summary = "";
1491
+ this._argsDescription = undefined;
1492
+ this._enablePositionalOptions = false;
1493
+ this._passThroughOptions = false;
1494
+ this._lifeCycleHooks = {};
1495
+ this._showHelpAfterError = false;
1496
+ this._showSuggestionAfterError = true;
1497
+ this._outputConfiguration = {
1498
+ writeOut: (str) => process2.stdout.write(str),
1499
+ writeErr: (str) => process2.stderr.write(str),
1500
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
1501
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
1502
+ outputError: (str, write) => write(str)
1503
+ };
1504
+ this._hidden = false;
1505
+ this._helpOption = undefined;
1506
+ this._addImplicitHelpCommand = undefined;
1507
+ this._helpCommand = undefined;
1508
+ this._helpConfiguration = {};
1509
+ }
1510
+ copyInheritedSettings(sourceCommand) {
1511
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1512
+ this._helpOption = sourceCommand._helpOption;
1513
+ this._helpCommand = sourceCommand._helpCommand;
1514
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1515
+ this._exitCallback = sourceCommand._exitCallback;
1516
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1517
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1518
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1519
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1520
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1521
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1522
+ return this;
1523
+ }
1524
+ _getCommandAndAncestors() {
1525
+ const result = [];
1526
+ for (let command = this;command; command = command.parent) {
1527
+ result.push(command);
1528
+ }
1529
+ return result;
1530
+ }
1531
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1532
+ let desc = actionOptsOrExecDesc;
1533
+ let opts = execOpts;
1534
+ if (typeof desc === "object" && desc !== null) {
1535
+ opts = desc;
1536
+ desc = null;
1537
+ }
1538
+ opts = opts || {};
1539
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1540
+ const cmd = this.createCommand(name);
1541
+ if (desc) {
1542
+ cmd.description(desc);
1543
+ cmd._executableHandler = true;
1544
+ }
1545
+ if (opts.isDefault)
1546
+ this._defaultCommandName = cmd._name;
1547
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1548
+ cmd._executableFile = opts.executableFile || null;
1549
+ if (args)
1550
+ cmd.arguments(args);
1551
+ this._registerCommand(cmd);
1552
+ cmd.parent = this;
1553
+ cmd.copyInheritedSettings(this);
1554
+ if (desc)
1555
+ return this;
1556
+ return cmd;
1557
+ }
1558
+ createCommand(name) {
1559
+ return new Command(name);
1560
+ }
1561
+ createHelp() {
1562
+ return Object.assign(new Help, this.configureHelp());
1563
+ }
1564
+ configureHelp(configuration) {
1565
+ if (configuration === undefined)
1566
+ return this._helpConfiguration;
1567
+ this._helpConfiguration = configuration;
1568
+ return this;
1569
+ }
1570
+ configureOutput(configuration) {
1571
+ if (configuration === undefined)
1572
+ return this._outputConfiguration;
1573
+ Object.assign(this._outputConfiguration, configuration);
1574
+ return this;
1575
+ }
1576
+ showHelpAfterError(displayHelp = true) {
1577
+ if (typeof displayHelp !== "string")
1578
+ displayHelp = !!displayHelp;
1579
+ this._showHelpAfterError = displayHelp;
1580
+ return this;
1581
+ }
1582
+ showSuggestionAfterError(displaySuggestion = true) {
1583
+ this._showSuggestionAfterError = !!displaySuggestion;
1584
+ return this;
1585
+ }
1586
+ addCommand(cmd, opts) {
1587
+ if (!cmd._name) {
1588
+ throw new Error(`Command passed to .addCommand() must have a name
1589
+ - specify the name in Command constructor or using .name()`);
1590
+ }
1591
+ opts = opts || {};
1592
+ if (opts.isDefault)
1593
+ this._defaultCommandName = cmd._name;
1594
+ if (opts.noHelp || opts.hidden)
1595
+ cmd._hidden = true;
1596
+ this._registerCommand(cmd);
1597
+ cmd.parent = this;
1598
+ cmd._checkForBrokenPassThrough();
1599
+ return this;
1600
+ }
1601
+ createArgument(name, description) {
1602
+ return new Argument(name, description);
1603
+ }
1604
+ argument(name, description, fn, defaultValue) {
1605
+ const argument = this.createArgument(name, description);
1606
+ if (typeof fn === "function") {
1607
+ argument.default(defaultValue).argParser(fn);
1608
+ } else {
1609
+ argument.default(fn);
1610
+ }
1611
+ this.addArgument(argument);
1612
+ return this;
1613
+ }
1614
+ arguments(names) {
1615
+ names.trim().split(/ +/).forEach((detail) => {
1616
+ this.argument(detail);
1617
+ });
1618
+ return this;
1619
+ }
1620
+ addArgument(argument) {
1621
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1622
+ if (previousArgument && previousArgument.variadic) {
1623
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1624
+ }
1625
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
1626
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1627
+ }
1628
+ this.registeredArguments.push(argument);
1629
+ return this;
1630
+ }
1631
+ helpCommand(enableOrNameAndArgs, description) {
1632
+ if (typeof enableOrNameAndArgs === "boolean") {
1633
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1634
+ return this;
1635
+ }
1636
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1637
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1638
+ const helpDescription = description ?? "display help for command";
1639
+ const helpCommand = this.createCommand(helpName);
1640
+ helpCommand.helpOption(false);
1641
+ if (helpArgs)
1642
+ helpCommand.arguments(helpArgs);
1643
+ if (helpDescription)
1644
+ helpCommand.description(helpDescription);
1645
+ this._addImplicitHelpCommand = true;
1646
+ this._helpCommand = helpCommand;
1647
+ return this;
1648
+ }
1649
+ addHelpCommand(helpCommand, deprecatedDescription) {
1650
+ if (typeof helpCommand !== "object") {
1651
+ this.helpCommand(helpCommand, deprecatedDescription);
1652
+ return this;
1653
+ }
1654
+ this._addImplicitHelpCommand = true;
1655
+ this._helpCommand = helpCommand;
1656
+ return this;
1657
+ }
1658
+ _getHelpCommand() {
1659
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1660
+ if (hasImplicitHelpCommand) {
1661
+ if (this._helpCommand === undefined) {
1662
+ this.helpCommand(undefined, undefined);
1663
+ }
1664
+ return this._helpCommand;
1665
+ }
1666
+ return null;
1667
+ }
1668
+ hook(event, listener) {
1669
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1670
+ if (!allowedValues.includes(event)) {
1671
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1672
+ Expecting one of '${allowedValues.join("', '")}'`);
1673
+ }
1674
+ if (this._lifeCycleHooks[event]) {
1675
+ this._lifeCycleHooks[event].push(listener);
1676
+ } else {
1677
+ this._lifeCycleHooks[event] = [listener];
1678
+ }
1679
+ return this;
1680
+ }
1681
+ exitOverride(fn) {
1682
+ if (fn) {
1683
+ this._exitCallback = fn;
1684
+ } else {
1685
+ this._exitCallback = (err) => {
1686
+ if (err.code !== "commander.executeSubCommandAsync") {
1687
+ throw err;
1688
+ } else {}
1689
+ };
1690
+ }
1691
+ return this;
1692
+ }
1693
+ _exit(exitCode, code, message) {
1694
+ if (this._exitCallback) {
1695
+ this._exitCallback(new CommanderError(exitCode, code, message));
1696
+ }
1697
+ process2.exit(exitCode);
1698
+ }
1699
+ action(fn) {
1700
+ const listener = (args) => {
1701
+ const expectedArgsCount = this.registeredArguments.length;
1702
+ const actionArgs = args.slice(0, expectedArgsCount);
1703
+ if (this._storeOptionsAsProperties) {
1704
+ actionArgs[expectedArgsCount] = this;
1705
+ } else {
1706
+ actionArgs[expectedArgsCount] = this.opts();
1707
+ }
1708
+ actionArgs.push(this);
1709
+ return fn.apply(this, actionArgs);
1710
+ };
1711
+ this._actionHandler = listener;
1712
+ return this;
1713
+ }
1714
+ createOption(flags, description) {
1715
+ return new Option(flags, description);
1716
+ }
1717
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1718
+ try {
1719
+ return target.parseArg(value, previous);
1720
+ } catch (err) {
1721
+ if (err.code === "commander.invalidArgument") {
1722
+ const message = `${invalidArgumentMessage} ${err.message}`;
1723
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1724
+ }
1725
+ throw err;
1726
+ }
1727
+ }
1728
+ _registerOption(option) {
1729
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1730
+ if (matchingOption) {
1731
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1732
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1733
+ - already used by option '${matchingOption.flags}'`);
1734
+ }
1735
+ this.options.push(option);
1736
+ }
1737
+ _registerCommand(command) {
1738
+ const knownBy = (cmd) => {
1739
+ return [cmd.name()].concat(cmd.aliases());
1740
+ };
1741
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1742
+ if (alreadyUsed) {
1743
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1744
+ const newCmd = knownBy(command).join("|");
1745
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1746
+ }
1747
+ this.commands.push(command);
1748
+ }
1749
+ addOption(option) {
1750
+ this._registerOption(option);
1751
+ const oname = option.name();
1752
+ const name = option.attributeName();
1753
+ if (option.negate) {
1754
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1755
+ if (!this._findOption(positiveLongFlag)) {
1756
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1757
+ }
1758
+ } else if (option.defaultValue !== undefined) {
1759
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1760
+ }
1761
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1762
+ if (val == null && option.presetArg !== undefined) {
1763
+ val = option.presetArg;
1764
+ }
1765
+ const oldValue = this.getOptionValue(name);
1766
+ if (val !== null && option.parseArg) {
1767
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1768
+ } else if (val !== null && option.variadic) {
1769
+ val = option._concatValue(val, oldValue);
1770
+ }
1771
+ if (val == null) {
1772
+ if (option.negate) {
1773
+ val = false;
1774
+ } else if (option.isBoolean() || option.optional) {
1775
+ val = true;
1776
+ } else {
1777
+ val = "";
1778
+ }
1779
+ }
1780
+ this.setOptionValueWithSource(name, val, valueSource);
1781
+ };
1782
+ this.on("option:" + oname, (val) => {
1783
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1784
+ handleOptionValue(val, invalidValueMessage, "cli");
1785
+ });
1786
+ if (option.envVar) {
1787
+ this.on("optionEnv:" + oname, (val) => {
1788
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1789
+ handleOptionValue(val, invalidValueMessage, "env");
1790
+ });
1791
+ }
1792
+ return this;
1793
+ }
1794
+ _optionEx(config, flags, description, fn, defaultValue) {
1795
+ if (typeof flags === "object" && flags instanceof Option) {
1796
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1797
+ }
1798
+ const option = this.createOption(flags, description);
1799
+ option.makeOptionMandatory(!!config.mandatory);
1800
+ if (typeof fn === "function") {
1801
+ option.default(defaultValue).argParser(fn);
1802
+ } else if (fn instanceof RegExp) {
1803
+ const regex = fn;
1804
+ fn = (val, def) => {
1805
+ const m = regex.exec(val);
1806
+ return m ? m[0] : def;
1807
+ };
1808
+ option.default(defaultValue).argParser(fn);
1809
+ } else {
1810
+ option.default(fn);
1811
+ }
1812
+ return this.addOption(option);
1813
+ }
1814
+ option(flags, description, parseArg, defaultValue) {
1815
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1816
+ }
1817
+ requiredOption(flags, description, parseArg, defaultValue) {
1818
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1819
+ }
1820
+ combineFlagAndOptionalValue(combine = true) {
1821
+ this._combineFlagAndOptionalValue = !!combine;
1822
+ return this;
1823
+ }
1824
+ allowUnknownOption(allowUnknown = true) {
1825
+ this._allowUnknownOption = !!allowUnknown;
1826
+ return this;
1827
+ }
1828
+ allowExcessArguments(allowExcess = true) {
1829
+ this._allowExcessArguments = !!allowExcess;
1830
+ return this;
1831
+ }
1832
+ enablePositionalOptions(positional = true) {
1833
+ this._enablePositionalOptions = !!positional;
1834
+ return this;
1835
+ }
1836
+ passThroughOptions(passThrough = true) {
1837
+ this._passThroughOptions = !!passThrough;
1838
+ this._checkForBrokenPassThrough();
1839
+ return this;
1840
+ }
1841
+ _checkForBrokenPassThrough() {
1842
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1843
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1844
+ }
1845
+ }
1846
+ storeOptionsAsProperties(storeAsProperties = true) {
1847
+ if (this.options.length) {
1848
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1849
+ }
1850
+ if (Object.keys(this._optionValues).length) {
1851
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1852
+ }
1853
+ this._storeOptionsAsProperties = !!storeAsProperties;
1854
+ return this;
1855
+ }
1856
+ getOptionValue(key) {
1857
+ if (this._storeOptionsAsProperties) {
1858
+ return this[key];
1859
+ }
1860
+ return this._optionValues[key];
1861
+ }
1862
+ setOptionValue(key, value) {
1863
+ return this.setOptionValueWithSource(key, value, undefined);
1864
+ }
1865
+ setOptionValueWithSource(key, value, source) {
1866
+ if (this._storeOptionsAsProperties) {
1867
+ this[key] = value;
1868
+ } else {
1869
+ this._optionValues[key] = value;
1870
+ }
1871
+ this._optionValueSources[key] = source;
1872
+ return this;
1873
+ }
1874
+ getOptionValueSource(key) {
1875
+ return this._optionValueSources[key];
1876
+ }
1877
+ getOptionValueSourceWithGlobals(key) {
1878
+ let source;
1879
+ this._getCommandAndAncestors().forEach((cmd) => {
1880
+ if (cmd.getOptionValueSource(key) !== undefined) {
1881
+ source = cmd.getOptionValueSource(key);
1882
+ }
1883
+ });
1884
+ return source;
1885
+ }
1886
+ _prepareUserArgs(argv2, parseOptions) {
1887
+ if (argv2 !== undefined && !Array.isArray(argv2)) {
1888
+ throw new Error("first parameter to parse must be array or undefined");
1889
+ }
1890
+ parseOptions = parseOptions || {};
1891
+ if (argv2 === undefined && parseOptions.from === undefined) {
1892
+ if (process2.versions?.electron) {
1893
+ parseOptions.from = "electron";
1894
+ }
1895
+ const execArgv = process2.execArgv ?? [];
1896
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1897
+ parseOptions.from = "eval";
1898
+ }
1899
+ }
1900
+ if (argv2 === undefined) {
1901
+ argv2 = process2.argv;
1902
+ }
1903
+ this.rawArgs = argv2.slice();
1904
+ let userArgs;
1905
+ switch (parseOptions.from) {
1906
+ case undefined:
1907
+ case "node":
1908
+ this._scriptPath = argv2[1];
1909
+ userArgs = argv2.slice(2);
1910
+ break;
1911
+ case "electron":
1912
+ if (process2.defaultApp) {
1913
+ this._scriptPath = argv2[1];
1914
+ userArgs = argv2.slice(2);
1915
+ } else {
1916
+ userArgs = argv2.slice(1);
1917
+ }
1918
+ break;
1919
+ case "user":
1920
+ userArgs = argv2.slice(0);
1921
+ break;
1922
+ case "eval":
1923
+ userArgs = argv2.slice(1);
1924
+ break;
1925
+ default:
1926
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1927
+ }
1928
+ if (!this._name && this._scriptPath)
1929
+ this.nameFromFilename(this._scriptPath);
1930
+ this._name = this._name || "program";
1931
+ return userArgs;
1932
+ }
1933
+ parse(argv2, parseOptions) {
1934
+ const userArgs = this._prepareUserArgs(argv2, parseOptions);
1935
+ this._parseCommand([], userArgs);
1936
+ return this;
1937
+ }
1938
+ async parseAsync(argv2, parseOptions) {
1939
+ const userArgs = this._prepareUserArgs(argv2, parseOptions);
1940
+ await this._parseCommand([], userArgs);
1941
+ return this;
1942
+ }
1943
+ _executeSubCommand(subcommand, args) {
1944
+ args = args.slice();
1945
+ let launchWithNode = false;
1946
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1947
+ function findFile(baseDir, baseName) {
1948
+ const localBin = path.resolve(baseDir, baseName);
1949
+ if (fs.existsSync(localBin))
1950
+ return localBin;
1951
+ if (sourceExt.includes(path.extname(baseName)))
1952
+ return;
1953
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1954
+ if (foundExt)
1955
+ return `${localBin}${foundExt}`;
1956
+ return;
1957
+ }
1958
+ this._checkForMissingMandatoryOptions();
1959
+ this._checkForConflictingOptions();
1960
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1961
+ let executableDir = this._executableDir || "";
1962
+ if (this._scriptPath) {
1963
+ let resolvedScriptPath;
1964
+ try {
1965
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1966
+ } catch (err) {
1967
+ resolvedScriptPath = this._scriptPath;
1968
+ }
1969
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1970
+ }
1971
+ if (executableDir) {
1972
+ let localFile = findFile(executableDir, executableFile);
1973
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1974
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1975
+ if (legacyName !== this._name) {
1976
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1977
+ }
1978
+ }
1979
+ executableFile = localFile || executableFile;
1980
+ }
1981
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1982
+ let proc;
1983
+ if (process2.platform !== "win32") {
1984
+ if (launchWithNode) {
1985
+ args.unshift(executableFile);
1986
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1987
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1988
+ } else {
1989
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1990
+ }
1991
+ } else {
1992
+ args.unshift(executableFile);
1993
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1994
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1995
+ }
1996
+ if (!proc.killed) {
1997
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1998
+ signals.forEach((signal) => {
1999
+ process2.on(signal, () => {
2000
+ if (proc.killed === false && proc.exitCode === null) {
2001
+ proc.kill(signal);
2002
+ }
2003
+ });
2004
+ });
2005
+ }
2006
+ const exitCallback = this._exitCallback;
2007
+ proc.on("close", (code) => {
2008
+ code = code ?? 1;
2009
+ if (!exitCallback) {
2010
+ process2.exit(code);
2011
+ } else {
2012
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2013
+ }
2014
+ });
2015
+ proc.on("error", (err) => {
2016
+ if (err.code === "ENOENT") {
2017
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2018
+ const executableMissing = `'${executableFile}' does not exist
2019
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2020
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2021
+ - ${executableDirMessage}`;
2022
+ throw new Error(executableMissing);
2023
+ } else if (err.code === "EACCES") {
2024
+ throw new Error(`'${executableFile}' not executable`);
2025
+ }
2026
+ if (!exitCallback) {
2027
+ process2.exit(1);
2028
+ } else {
2029
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2030
+ wrappedError.nestedError = err;
2031
+ exitCallback(wrappedError);
2032
+ }
2033
+ });
2034
+ this.runningCommand = proc;
2035
+ }
2036
+ _dispatchSubcommand(commandName, operands, unknown) {
2037
+ const subCommand = this._findCommand(commandName);
2038
+ if (!subCommand)
2039
+ this.help({ error: true });
2040
+ let promiseChain;
2041
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2042
+ promiseChain = this._chainOrCall(promiseChain, () => {
2043
+ if (subCommand._executableHandler) {
2044
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2045
+ } else {
2046
+ return subCommand._parseCommand(operands, unknown);
2047
+ }
2048
+ });
2049
+ return promiseChain;
2050
+ }
2051
+ _dispatchHelpCommand(subcommandName) {
2052
+ if (!subcommandName) {
2053
+ this.help();
2054
+ }
2055
+ const subCommand = this._findCommand(subcommandName);
2056
+ if (subCommand && !subCommand._executableHandler) {
2057
+ subCommand.help();
2058
+ }
2059
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2060
+ }
2061
+ _checkNumberOfArguments() {
2062
+ this.registeredArguments.forEach((arg, i) => {
2063
+ if (arg.required && this.args[i] == null) {
2064
+ this.missingArgument(arg.name());
2065
+ }
2066
+ });
2067
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2068
+ return;
2069
+ }
2070
+ if (this.args.length > this.registeredArguments.length) {
2071
+ this._excessArguments(this.args);
2072
+ }
2073
+ }
2074
+ _processArguments() {
2075
+ const myParseArg = (argument, value, previous) => {
2076
+ let parsedValue = value;
2077
+ if (value !== null && argument.parseArg) {
2078
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2079
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2080
+ }
2081
+ return parsedValue;
2082
+ };
2083
+ this._checkNumberOfArguments();
2084
+ const processedArgs = [];
2085
+ this.registeredArguments.forEach((declaredArg, index) => {
2086
+ let value = declaredArg.defaultValue;
2087
+ if (declaredArg.variadic) {
2088
+ if (index < this.args.length) {
2089
+ value = this.args.slice(index);
2090
+ if (declaredArg.parseArg) {
2091
+ value = value.reduce((processed, v) => {
2092
+ return myParseArg(declaredArg, v, processed);
2093
+ }, declaredArg.defaultValue);
2094
+ }
2095
+ } else if (value === undefined) {
2096
+ value = [];
2097
+ }
2098
+ } else if (index < this.args.length) {
2099
+ value = this.args[index];
2100
+ if (declaredArg.parseArg) {
2101
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2102
+ }
2103
+ }
2104
+ processedArgs[index] = value;
2105
+ });
2106
+ this.processedArgs = processedArgs;
2107
+ }
2108
+ _chainOrCall(promise, fn) {
2109
+ if (promise && promise.then && typeof promise.then === "function") {
2110
+ return promise.then(() => fn());
2111
+ }
2112
+ return fn();
2113
+ }
2114
+ _chainOrCallHooks(promise, event) {
2115
+ let result = promise;
2116
+ const hooks = [];
2117
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
2118
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2119
+ hooks.push({ hookedCommand, callback });
2120
+ });
2121
+ });
2122
+ if (event === "postAction") {
2123
+ hooks.reverse();
2124
+ }
2125
+ hooks.forEach((hookDetail) => {
2126
+ result = this._chainOrCall(result, () => {
2127
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2128
+ });
2129
+ });
2130
+ return result;
2131
+ }
2132
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2133
+ let result = promise;
2134
+ if (this._lifeCycleHooks[event] !== undefined) {
2135
+ this._lifeCycleHooks[event].forEach((hook) => {
2136
+ result = this._chainOrCall(result, () => {
2137
+ return hook(this, subCommand);
2138
+ });
2139
+ });
2140
+ }
2141
+ return result;
2142
+ }
2143
+ _parseCommand(operands, unknown) {
2144
+ const parsed = this.parseOptions(unknown);
2145
+ this._parseOptionsEnv();
2146
+ this._parseOptionsImplied();
2147
+ operands = operands.concat(parsed.operands);
2148
+ unknown = parsed.unknown;
2149
+ this.args = operands.concat(unknown);
2150
+ if (operands && this._findCommand(operands[0])) {
2151
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2152
+ }
2153
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2154
+ return this._dispatchHelpCommand(operands[1]);
2155
+ }
2156
+ if (this._defaultCommandName) {
2157
+ this._outputHelpIfRequested(unknown);
2158
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2159
+ }
2160
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2161
+ this.help({ error: true });
2162
+ }
2163
+ this._outputHelpIfRequested(parsed.unknown);
2164
+ this._checkForMissingMandatoryOptions();
2165
+ this._checkForConflictingOptions();
2166
+ const checkForUnknownOptions = () => {
2167
+ if (parsed.unknown.length > 0) {
2168
+ this.unknownOption(parsed.unknown[0]);
2169
+ }
2170
+ };
2171
+ const commandEvent = `command:${this.name()}`;
2172
+ if (this._actionHandler) {
2173
+ checkForUnknownOptions();
2174
+ this._processArguments();
2175
+ let promiseChain;
2176
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2177
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2178
+ if (this.parent) {
2179
+ promiseChain = this._chainOrCall(promiseChain, () => {
2180
+ this.parent.emit(commandEvent, operands, unknown);
2181
+ });
2182
+ }
2183
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2184
+ return promiseChain;
2185
+ }
2186
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2187
+ checkForUnknownOptions();
2188
+ this._processArguments();
2189
+ this.parent.emit(commandEvent, operands, unknown);
2190
+ } else if (operands.length) {
2191
+ if (this._findCommand("*")) {
2192
+ return this._dispatchSubcommand("*", operands, unknown);
2193
+ }
2194
+ if (this.listenerCount("command:*")) {
2195
+ this.emit("command:*", operands, unknown);
2196
+ } else if (this.commands.length) {
2197
+ this.unknownCommand();
2198
+ } else {
2199
+ checkForUnknownOptions();
2200
+ this._processArguments();
2201
+ }
2202
+ } else if (this.commands.length) {
2203
+ checkForUnknownOptions();
2204
+ this.help({ error: true });
2205
+ } else {
2206
+ checkForUnknownOptions();
2207
+ this._processArguments();
2208
+ }
2209
+ }
2210
+ _findCommand(name) {
2211
+ if (!name)
2212
+ return;
2213
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2214
+ }
2215
+ _findOption(arg) {
2216
+ return this.options.find((option) => option.is(arg));
2217
+ }
2218
+ _checkForMissingMandatoryOptions() {
2219
+ this._getCommandAndAncestors().forEach((cmd) => {
2220
+ cmd.options.forEach((anOption) => {
2221
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
2222
+ cmd.missingMandatoryOptionValue(anOption);
2223
+ }
2224
+ });
2225
+ });
2226
+ }
2227
+ _checkForConflictingLocalOptions() {
2228
+ const definedNonDefaultOptions = this.options.filter((option) => {
2229
+ const optionKey = option.attributeName();
2230
+ if (this.getOptionValue(optionKey) === undefined) {
2231
+ return false;
2232
+ }
2233
+ return this.getOptionValueSource(optionKey) !== "default";
2234
+ });
2235
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
2236
+ optionsWithConflicting.forEach((option) => {
2237
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2238
+ if (conflictingAndDefined) {
2239
+ this._conflictingOption(option, conflictingAndDefined);
2240
+ }
2241
+ });
2242
+ }
2243
+ _checkForConflictingOptions() {
2244
+ this._getCommandAndAncestors().forEach((cmd) => {
2245
+ cmd._checkForConflictingLocalOptions();
2246
+ });
2247
+ }
2248
+ parseOptions(argv2) {
2249
+ const operands = [];
2250
+ const unknown = [];
2251
+ let dest = operands;
2252
+ const args = argv2.slice();
2253
+ function maybeOption(arg) {
2254
+ return arg.length > 1 && arg[0] === "-";
2255
+ }
2256
+ let activeVariadicOption = null;
2257
+ while (args.length) {
2258
+ const arg = args.shift();
2259
+ if (arg === "--") {
2260
+ if (dest === unknown)
2261
+ dest.push(arg);
2262
+ dest.push(...args);
2263
+ break;
2264
+ }
2265
+ if (activeVariadicOption && !maybeOption(arg)) {
2266
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2267
+ continue;
2268
+ }
2269
+ activeVariadicOption = null;
2270
+ if (maybeOption(arg)) {
2271
+ const option = this._findOption(arg);
2272
+ if (option) {
2273
+ if (option.required) {
2274
+ const value = args.shift();
2275
+ if (value === undefined)
2276
+ this.optionMissingArgument(option);
2277
+ this.emit(`option:${option.name()}`, value);
2278
+ } else if (option.optional) {
2279
+ let value = null;
2280
+ if (args.length > 0 && !maybeOption(args[0])) {
2281
+ value = args.shift();
2282
+ }
2283
+ this.emit(`option:${option.name()}`, value);
2284
+ } else {
2285
+ this.emit(`option:${option.name()}`);
2286
+ }
2287
+ activeVariadicOption = option.variadic ? option : null;
2288
+ continue;
2289
+ }
2290
+ }
2291
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2292
+ const option = this._findOption(`-${arg[1]}`);
2293
+ if (option) {
2294
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2295
+ this.emit(`option:${option.name()}`, arg.slice(2));
2296
+ } else {
2297
+ this.emit(`option:${option.name()}`);
2298
+ args.unshift(`-${arg.slice(2)}`);
2299
+ }
2300
+ continue;
2301
+ }
2302
+ }
2303
+ if (/^--[^=]+=/.test(arg)) {
2304
+ const index = arg.indexOf("=");
2305
+ const option = this._findOption(arg.slice(0, index));
2306
+ if (option && (option.required || option.optional)) {
2307
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2308
+ continue;
2309
+ }
2310
+ }
2311
+ if (maybeOption(arg)) {
2312
+ dest = unknown;
2313
+ }
2314
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2315
+ if (this._findCommand(arg)) {
2316
+ operands.push(arg);
2317
+ if (args.length > 0)
2318
+ unknown.push(...args);
2319
+ break;
2320
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2321
+ operands.push(arg);
2322
+ if (args.length > 0)
2323
+ operands.push(...args);
2324
+ break;
2325
+ } else if (this._defaultCommandName) {
2326
+ unknown.push(arg);
2327
+ if (args.length > 0)
2328
+ unknown.push(...args);
2329
+ break;
2330
+ }
2331
+ }
2332
+ if (this._passThroughOptions) {
2333
+ dest.push(arg);
2334
+ if (args.length > 0)
2335
+ dest.push(...args);
2336
+ break;
2337
+ }
2338
+ dest.push(arg);
2339
+ }
2340
+ return { operands, unknown };
2341
+ }
2342
+ opts() {
2343
+ if (this._storeOptionsAsProperties) {
2344
+ const result = {};
2345
+ const len = this.options.length;
2346
+ for (let i = 0;i < len; i++) {
2347
+ const key = this.options[i].attributeName();
2348
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2349
+ }
2350
+ return result;
2351
+ }
2352
+ return this._optionValues;
2353
+ }
2354
+ optsWithGlobals() {
2355
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2356
+ }
2357
+ error(message, errorOptions) {
2358
+ this._outputConfiguration.outputError(`${message}
2359
+ `, this._outputConfiguration.writeErr);
2360
+ if (typeof this._showHelpAfterError === "string") {
2361
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2362
+ `);
2363
+ } else if (this._showHelpAfterError) {
2364
+ this._outputConfiguration.writeErr(`
2365
+ `);
2366
+ this.outputHelp({ error: true });
2367
+ }
2368
+ const config = errorOptions || {};
2369
+ const exitCode = config.exitCode || 1;
2370
+ const code = config.code || "commander.error";
2371
+ this._exit(exitCode, code, message);
2372
+ }
2373
+ _parseOptionsEnv() {
2374
+ this.options.forEach((option) => {
2375
+ if (option.envVar && option.envVar in process2.env) {
2376
+ const optionKey = option.attributeName();
2377
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2378
+ if (option.required || option.optional) {
2379
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2380
+ } else {
2381
+ this.emit(`optionEnv:${option.name()}`);
2382
+ }
2383
+ }
2384
+ }
2385
+ });
2386
+ }
2387
+ _parseOptionsImplied() {
2388
+ const dualHelper = new DualOptions(this.options);
2389
+ const hasCustomOptionValue = (optionKey) => {
2390
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2391
+ };
2392
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2393
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2394
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2395
+ });
2396
+ });
2397
+ }
2398
+ missingArgument(name) {
2399
+ const message = `error: missing required argument '${name}'`;
2400
+ this.error(message, { code: "commander.missingArgument" });
2401
+ }
2402
+ optionMissingArgument(option) {
2403
+ const message = `error: option '${option.flags}' argument missing`;
2404
+ this.error(message, { code: "commander.optionMissingArgument" });
2405
+ }
2406
+ missingMandatoryOptionValue(option) {
2407
+ const message = `error: required option '${option.flags}' not specified`;
2408
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2409
+ }
2410
+ _conflictingOption(option, conflictingOption) {
2411
+ const findBestOptionFromValue = (option2) => {
2412
+ const optionKey = option2.attributeName();
2413
+ const optionValue = this.getOptionValue(optionKey);
2414
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2415
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2416
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
2417
+ return negativeOption;
2418
+ }
2419
+ return positiveOption || option2;
2420
+ };
2421
+ const getErrorMessage = (option2) => {
2422
+ const bestOption = findBestOptionFromValue(option2);
2423
+ const optionKey = bestOption.attributeName();
2424
+ const source = this.getOptionValueSource(optionKey);
2425
+ if (source === "env") {
2426
+ return `environment variable '${bestOption.envVar}'`;
2427
+ }
2428
+ return `option '${bestOption.flags}'`;
2429
+ };
2430
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2431
+ this.error(message, { code: "commander.conflictingOption" });
2432
+ }
2433
+ unknownOption(flag) {
2434
+ if (this._allowUnknownOption)
2435
+ return;
2436
+ let suggestion = "";
2437
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2438
+ let candidateFlags = [];
2439
+ let command = this;
2440
+ do {
2441
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2442
+ candidateFlags = candidateFlags.concat(moreFlags);
2443
+ command = command.parent;
2444
+ } while (command && !command._enablePositionalOptions);
2445
+ suggestion = suggestSimilar(flag, candidateFlags);
2446
+ }
2447
+ const message = `error: unknown option '${flag}'${suggestion}`;
2448
+ this.error(message, { code: "commander.unknownOption" });
2449
+ }
2450
+ _excessArguments(receivedArgs) {
2451
+ if (this._allowExcessArguments)
2452
+ return;
2453
+ const expected = this.registeredArguments.length;
2454
+ const s = expected === 1 ? "" : "s";
2455
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2456
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2457
+ this.error(message, { code: "commander.excessArguments" });
2458
+ }
2459
+ unknownCommand() {
2460
+ const unknownName = this.args[0];
2461
+ let suggestion = "";
2462
+ if (this._showSuggestionAfterError) {
2463
+ const candidateNames = [];
2464
+ this.createHelp().visibleCommands(this).forEach((command) => {
2465
+ candidateNames.push(command.name());
2466
+ if (command.alias())
2467
+ candidateNames.push(command.alias());
2468
+ });
2469
+ suggestion = suggestSimilar(unknownName, candidateNames);
2470
+ }
2471
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2472
+ this.error(message, { code: "commander.unknownCommand" });
2473
+ }
2474
+ version(str, flags, description) {
2475
+ if (str === undefined)
2476
+ return this._version;
2477
+ this._version = str;
2478
+ flags = flags || "-V, --version";
2479
+ description = description || "output the version number";
2480
+ const versionOption = this.createOption(flags, description);
2481
+ this._versionOptionName = versionOption.attributeName();
2482
+ this._registerOption(versionOption);
2483
+ this.on("option:" + versionOption.name(), () => {
2484
+ this._outputConfiguration.writeOut(`${str}
2485
+ `);
2486
+ this._exit(0, "commander.version", str);
2487
+ });
2488
+ return this;
2489
+ }
2490
+ description(str, argsDescription) {
2491
+ if (str === undefined && argsDescription === undefined)
2492
+ return this._description;
2493
+ this._description = str;
2494
+ if (argsDescription) {
2495
+ this._argsDescription = argsDescription;
2496
+ }
2497
+ return this;
2498
+ }
2499
+ summary(str) {
2500
+ if (str === undefined)
2501
+ return this._summary;
2502
+ this._summary = str;
2503
+ return this;
2504
+ }
2505
+ alias(alias) {
2506
+ if (alias === undefined)
2507
+ return this._aliases[0];
2508
+ let command = this;
2509
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2510
+ command = this.commands[this.commands.length - 1];
2511
+ }
2512
+ if (alias === command._name)
2513
+ throw new Error("Command alias can't be the same as its name");
2514
+ const matchingCommand = this.parent?._findCommand(alias);
2515
+ if (matchingCommand) {
2516
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2517
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2518
+ }
2519
+ command._aliases.push(alias);
2520
+ return this;
2521
+ }
2522
+ aliases(aliases) {
2523
+ if (aliases === undefined)
2524
+ return this._aliases;
2525
+ aliases.forEach((alias) => this.alias(alias));
2526
+ return this;
2527
+ }
2528
+ usage(str) {
2529
+ if (str === undefined) {
2530
+ if (this._usage)
2531
+ return this._usage;
2532
+ const args = this.registeredArguments.map((arg) => {
2533
+ return humanReadableArgName(arg);
2534
+ });
2535
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2536
+ }
2537
+ this._usage = str;
2538
+ return this;
2539
+ }
2540
+ name(str) {
2541
+ if (str === undefined)
2542
+ return this._name;
2543
+ this._name = str;
2544
+ return this;
2545
+ }
2546
+ nameFromFilename(filename) {
2547
+ this._name = path.basename(filename, path.extname(filename));
2548
+ return this;
2549
+ }
2550
+ executableDir(path2) {
2551
+ if (path2 === undefined)
2552
+ return this._executableDir;
2553
+ this._executableDir = path2;
2554
+ return this;
2555
+ }
2556
+ helpInformation(contextOptions) {
2557
+ const helper = this.createHelp();
2558
+ if (helper.helpWidth === undefined) {
2559
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2560
+ }
2561
+ return helper.formatHelp(this, helper);
2562
+ }
2563
+ _getHelpContext(contextOptions) {
2564
+ contextOptions = contextOptions || {};
2565
+ const context = { error: !!contextOptions.error };
2566
+ let write;
2567
+ if (context.error) {
2568
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2569
+ } else {
2570
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2571
+ }
2572
+ context.write = contextOptions.write || write;
2573
+ context.command = this;
2574
+ return context;
2575
+ }
2576
+ outputHelp(contextOptions) {
2577
+ let deprecatedCallback;
2578
+ if (typeof contextOptions === "function") {
2579
+ deprecatedCallback = contextOptions;
2580
+ contextOptions = undefined;
2581
+ }
2582
+ const context = this._getHelpContext(contextOptions);
2583
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2584
+ this.emit("beforeHelp", context);
2585
+ let helpInformation = this.helpInformation(context);
2586
+ if (deprecatedCallback) {
2587
+ helpInformation = deprecatedCallback(helpInformation);
2588
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2589
+ throw new Error("outputHelp callback must return a string or a Buffer");
2590
+ }
2591
+ }
2592
+ context.write(helpInformation);
2593
+ if (this._getHelpOption()?.long) {
2594
+ this.emit(this._getHelpOption().long);
2595
+ }
2596
+ this.emit("afterHelp", context);
2597
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
2598
+ }
2599
+ helpOption(flags, description) {
2600
+ if (typeof flags === "boolean") {
2601
+ if (flags) {
2602
+ this._helpOption = this._helpOption ?? undefined;
2603
+ } else {
2604
+ this._helpOption = null;
2605
+ }
2606
+ return this;
2607
+ }
2608
+ flags = flags ?? "-h, --help";
2609
+ description = description ?? "display help for command";
2610
+ this._helpOption = this.createOption(flags, description);
2611
+ return this;
2612
+ }
2613
+ _getHelpOption() {
2614
+ if (this._helpOption === undefined) {
2615
+ this.helpOption(undefined, undefined);
2616
+ }
2617
+ return this._helpOption;
2618
+ }
2619
+ addHelpOption(option) {
2620
+ this._helpOption = option;
2621
+ return this;
2622
+ }
2623
+ help(contextOptions) {
2624
+ this.outputHelp(contextOptions);
2625
+ let exitCode = process2.exitCode || 0;
2626
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2627
+ exitCode = 1;
2628
+ }
2629
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2630
+ }
2631
+ addHelpText(position, text) {
2632
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2633
+ if (!allowedValues.includes(position)) {
2634
+ throw new Error(`Unexpected value for position to addHelpText.
2635
+ Expecting one of '${allowedValues.join("', '")}'`);
2636
+ }
2637
+ const helpEvent = `${position}Help`;
2638
+ this.on(helpEvent, (context) => {
2639
+ let helpStr;
2640
+ if (typeof text === "function") {
2641
+ helpStr = text({ error: context.error, command: context.command });
2642
+ } else {
2643
+ helpStr = text;
2644
+ }
2645
+ if (helpStr) {
2646
+ context.write(`${helpStr}
2647
+ `);
2648
+ }
2649
+ });
2650
+ return this;
2651
+ }
2652
+ _outputHelpIfRequested(args) {
2653
+ const helpOption = this._getHelpOption();
2654
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2655
+ if (helpRequested) {
2656
+ this.outputHelp();
2657
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2658
+ }
2659
+ }
2660
+ }
2661
+ function incrementNodeInspectorPort(args) {
2662
+ return args.map((arg) => {
2663
+ if (!arg.startsWith("--inspect")) {
2664
+ return arg;
2665
+ }
2666
+ let debugOption;
2667
+ let debugHost = "127.0.0.1";
2668
+ let debugPort = "9229";
2669
+ let match;
2670
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2671
+ debugOption = match[1];
2672
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2673
+ debugOption = match[1];
2674
+ if (/^\d+$/.test(match[3])) {
2675
+ debugPort = match[3];
2676
+ } else {
2677
+ debugHost = match[3];
2678
+ }
2679
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2680
+ debugOption = match[1];
2681
+ debugHost = match[3];
2682
+ debugPort = match[4];
2683
+ }
2684
+ if (debugOption && debugPort !== "0") {
2685
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2686
+ }
2687
+ return arg;
2688
+ });
2689
+ }
2690
+ exports.Command = Command;
2691
+ });
2692
+
2693
+ // node_modules/commander/index.js
2694
+ var require_commander = __commonJS((exports) => {
2695
+ var { Argument } = require_argument();
2696
+ var { Command } = require_command();
2697
+ var { CommanderError, InvalidArgumentError } = require_error();
2698
+ var { Help } = require_help();
2699
+ var { Option } = require_option();
2700
+ exports.program = new Command;
2701
+ exports.createCommand = (name) => new Command(name);
2702
+ exports.createOption = (flags, description) => new Option(flags, description);
2703
+ exports.createArgument = (name, description) => new Argument(name, description);
2704
+ exports.Command = Command;
2705
+ exports.Option = Option;
2706
+ exports.Argument = Argument;
2707
+ exports.Help = Help;
2708
+ exports.CommanderError = CommanderError;
2709
+ exports.InvalidArgumentError = InvalidArgumentError;
2710
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2711
+ });
2712
+
2713
+ // node_modules/commander/esm.mjs
2714
+ var import__ = __toESM(require_commander(), 1);
2715
+ var {
2716
+ program,
2717
+ createCommand,
2718
+ createArgument,
2719
+ createOption,
2720
+ CommanderError,
2721
+ InvalidArgumentError,
2722
+ InvalidOptionArgumentError,
2723
+ Command,
2724
+ Argument,
2725
+ Option,
2726
+ Help
2727
+ } = import__.default;
2728
+
2729
+ // src/gen/core/bodySerializer.gen.ts
2730
+ var jsonBodySerializer = {
2731
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
2732
+ };
2733
+ // src/gen/core/params.gen.ts
2734
+ var extraPrefixesMap = {
2735
+ $body_: "body",
2736
+ $headers_: "headers",
2737
+ $path_: "path",
2738
+ $query_: "query"
2739
+ };
2740
+ var extraPrefixes = Object.entries(extraPrefixesMap);
2741
+ // src/gen/core/serverSentEvents.gen.ts
2742
+ var createSseClient = ({
2743
+ onRequest,
2744
+ onSseError,
2745
+ onSseEvent,
2746
+ responseTransformer,
2747
+ responseValidator,
2748
+ sseDefaultRetryDelay,
2749
+ sseMaxRetryAttempts,
2750
+ sseMaxRetryDelay,
2751
+ sseSleepFn,
2752
+ url,
2753
+ ...options
2754
+ }) => {
2755
+ let lastEventId;
2756
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
2757
+ const createStream = async function* () {
2758
+ let retryDelay = sseDefaultRetryDelay ?? 3000;
2759
+ let attempt = 0;
2760
+ const signal = options.signal ?? new AbortController().signal;
2761
+ while (true) {
2762
+ if (signal.aborted)
2763
+ break;
2764
+ attempt++;
2765
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
2766
+ if (lastEventId !== undefined) {
2767
+ headers.set("Last-Event-ID", lastEventId);
2768
+ }
2769
+ try {
2770
+ const requestInit = {
2771
+ redirect: "follow",
2772
+ ...options,
2773
+ body: options.serializedBody,
2774
+ headers,
2775
+ signal
2776
+ };
2777
+ let request = new Request(url, requestInit);
2778
+ if (onRequest) {
2779
+ request = await onRequest(url, requestInit);
2780
+ }
2781
+ const _fetch = options.fetch ?? globalThis.fetch;
2782
+ const response = await _fetch(request);
2783
+ if (!response.ok)
2784
+ throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
2785
+ if (!response.body)
2786
+ throw new Error("No body in SSE response");
2787
+ const reader = response.body.pipeThrough(new TextDecoderStream).getReader();
2788
+ let buffer = "";
2789
+ const abortHandler = () => {
2790
+ try {
2791
+ reader.cancel();
2792
+ } catch {}
2793
+ };
2794
+ signal.addEventListener("abort", abortHandler);
2795
+ try {
2796
+ while (true) {
2797
+ const { done, value } = await reader.read();
2798
+ if (done)
2799
+ break;
2800
+ buffer += value;
2801
+ buffer = buffer.replace(/\r\n/g, `
2802
+ `).replace(/\r/g, `
2803
+ `);
2804
+ const chunks = buffer.split(`
2805
+
2806
+ `);
2807
+ buffer = chunks.pop() ?? "";
2808
+ for (const chunk of chunks) {
2809
+ const lines = chunk.split(`
2810
+ `);
2811
+ const dataLines = [];
2812
+ let eventName;
2813
+ for (const line of lines) {
2814
+ if (line.startsWith("data:")) {
2815
+ dataLines.push(line.replace(/^data:\s*/, ""));
2816
+ } else if (line.startsWith("event:")) {
2817
+ eventName = line.replace(/^event:\s*/, "");
2818
+ } else if (line.startsWith("id:")) {
2819
+ lastEventId = line.replace(/^id:\s*/, "");
2820
+ } else if (line.startsWith("retry:")) {
2821
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
2822
+ if (!Number.isNaN(parsed)) {
2823
+ retryDelay = parsed;
2824
+ }
2825
+ }
2826
+ }
2827
+ let data;
2828
+ let parsedJson = false;
2829
+ if (dataLines.length) {
2830
+ const rawData = dataLines.join(`
2831
+ `);
2832
+ try {
2833
+ data = JSON.parse(rawData);
2834
+ parsedJson = true;
2835
+ } catch {
2836
+ data = rawData;
2837
+ }
2838
+ }
2839
+ if (parsedJson) {
2840
+ if (responseValidator) {
2841
+ await responseValidator(data);
2842
+ }
2843
+ if (responseTransformer) {
2844
+ data = await responseTransformer(data);
2845
+ }
2846
+ }
2847
+ onSseEvent?.({
2848
+ data,
2849
+ event: eventName,
2850
+ id: lastEventId,
2851
+ retry: retryDelay
2852
+ });
2853
+ if (dataLines.length) {
2854
+ yield data;
2855
+ }
2856
+ }
2857
+ }
2858
+ } finally {
2859
+ signal.removeEventListener("abort", abortHandler);
2860
+ reader.releaseLock();
2861
+ }
2862
+ break;
2863
+ } catch (error) {
2864
+ onSseError?.(error);
2865
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
2866
+ break;
2867
+ }
2868
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
2869
+ await sleep(backoff);
2870
+ }
2871
+ }
2872
+ };
2873
+ const stream = createStream();
2874
+ return { stream };
2875
+ };
2876
+
2877
+ // src/gen/core/pathSerializer.gen.ts
2878
+ var separatorArrayExplode = (style) => {
2879
+ switch (style) {
2880
+ case "label":
2881
+ return ".";
2882
+ case "matrix":
2883
+ return ";";
2884
+ case "simple":
2885
+ return ",";
2886
+ default:
2887
+ return "&";
2888
+ }
2889
+ };
2890
+ var separatorArrayNoExplode = (style) => {
2891
+ switch (style) {
2892
+ case "form":
2893
+ return ",";
2894
+ case "pipeDelimited":
2895
+ return "|";
2896
+ case "spaceDelimited":
2897
+ return "%20";
2898
+ default:
2899
+ return ",";
2900
+ }
2901
+ };
2902
+ var separatorObjectExplode = (style) => {
2903
+ switch (style) {
2904
+ case "label":
2905
+ return ".";
2906
+ case "matrix":
2907
+ return ";";
2908
+ case "simple":
2909
+ return ",";
2910
+ default:
2911
+ return "&";
2912
+ }
2913
+ };
2914
+ var serializeArrayParam = ({
2915
+ allowReserved,
2916
+ explode,
2917
+ name,
2918
+ style,
2919
+ value
2920
+ }) => {
2921
+ if (!explode) {
2922
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
2923
+ switch (style) {
2924
+ case "label":
2925
+ return `.${joinedValues2}`;
2926
+ case "matrix":
2927
+ return `;${name}=${joinedValues2}`;
2928
+ case "simple":
2929
+ return joinedValues2;
2930
+ default:
2931
+ return `${name}=${joinedValues2}`;
2932
+ }
2933
+ }
2934
+ const separator = separatorArrayExplode(style);
2935
+ const joinedValues = value.map((v) => {
2936
+ if (style === "label" || style === "simple") {
2937
+ return allowReserved ? v : encodeURIComponent(v);
2938
+ }
2939
+ return serializePrimitiveParam({
2940
+ allowReserved,
2941
+ name,
2942
+ value: v
2943
+ });
2944
+ }).join(separator);
2945
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
2946
+ };
2947
+ var serializePrimitiveParam = ({
2948
+ allowReserved,
2949
+ name,
2950
+ value
2951
+ }) => {
2952
+ if (value === undefined || value === null) {
2953
+ return "";
2954
+ }
2955
+ if (typeof value === "object") {
2956
+ throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
2957
+ }
2958
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
2959
+ };
2960
+ var serializeObjectParam = ({
2961
+ allowReserved,
2962
+ explode,
2963
+ name,
2964
+ style,
2965
+ value,
2966
+ valueOnly
2967
+ }) => {
2968
+ if (value instanceof Date) {
2969
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
2970
+ }
2971
+ if (style !== "deepObject" && !explode) {
2972
+ let values = [];
2973
+ Object.entries(value).forEach(([key, v]) => {
2974
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
2975
+ });
2976
+ const joinedValues2 = values.join(",");
2977
+ switch (style) {
2978
+ case "form":
2979
+ return `${name}=${joinedValues2}`;
2980
+ case "label":
2981
+ return `.${joinedValues2}`;
2982
+ case "matrix":
2983
+ return `;${name}=${joinedValues2}`;
2984
+ default:
2985
+ return joinedValues2;
2986
+ }
2987
+ }
2988
+ const separator = separatorObjectExplode(style);
2989
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
2990
+ allowReserved,
2991
+ name: style === "deepObject" ? `${name}[${key}]` : key,
2992
+ value: v
2993
+ })).join(separator);
2994
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
2995
+ };
2996
+
2997
+ // src/gen/core/utils.gen.ts
2998
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
2999
+ var defaultPathSerializer = ({ path, url: _url }) => {
3000
+ let url = _url;
3001
+ const matches = _url.match(PATH_PARAM_RE);
3002
+ if (matches) {
3003
+ for (const match of matches) {
3004
+ let explode = false;
3005
+ let name = match.substring(1, match.length - 1);
3006
+ let style = "simple";
3007
+ if (name.endsWith("*")) {
3008
+ explode = true;
3009
+ name = name.substring(0, name.length - 1);
3010
+ }
3011
+ if (name.startsWith(".")) {
3012
+ name = name.substring(1);
3013
+ style = "label";
3014
+ } else if (name.startsWith(";")) {
3015
+ name = name.substring(1);
3016
+ style = "matrix";
3017
+ }
3018
+ const value = path[name];
3019
+ if (value === undefined || value === null) {
3020
+ continue;
3021
+ }
3022
+ if (Array.isArray(value)) {
3023
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
3024
+ continue;
3025
+ }
3026
+ if (typeof value === "object") {
3027
+ url = url.replace(match, serializeObjectParam({
3028
+ explode,
3029
+ name,
3030
+ style,
3031
+ value,
3032
+ valueOnly: true
3033
+ }));
3034
+ continue;
3035
+ }
3036
+ if (style === "matrix") {
3037
+ url = url.replace(match, `;${serializePrimitiveParam({
3038
+ name,
3039
+ value
3040
+ })}`);
3041
+ continue;
3042
+ }
3043
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
3044
+ url = url.replace(match, replaceValue);
3045
+ }
3046
+ }
3047
+ return url;
3048
+ };
3049
+ var getUrl = ({
3050
+ baseUrl,
3051
+ path,
3052
+ query,
3053
+ querySerializer,
3054
+ url: _url
3055
+ }) => {
3056
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
3057
+ let url = (baseUrl ?? "") + pathUrl;
3058
+ if (path) {
3059
+ url = defaultPathSerializer({ path, url });
3060
+ }
3061
+ let search = query ? querySerializer(query) : "";
3062
+ if (search.startsWith("?")) {
3063
+ search = search.substring(1);
3064
+ }
3065
+ if (search) {
3066
+ url += `?${search}`;
3067
+ }
3068
+ return url;
3069
+ };
3070
+ function getValidRequestBody(options) {
3071
+ const hasBody = options.body !== undefined;
3072
+ const isSerializedBody = hasBody && options.bodySerializer;
3073
+ if (isSerializedBody) {
3074
+ if ("serializedBody" in options) {
3075
+ const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== "";
3076
+ return hasSerializedBody ? options.serializedBody : null;
3077
+ }
3078
+ return options.body !== "" ? options.body : null;
3079
+ }
3080
+ if (hasBody) {
3081
+ return options.body;
3082
+ }
3083
+ return;
3084
+ }
3085
+
3086
+ // src/gen/core/auth.gen.ts
3087
+ var getAuthToken = async (auth, callback) => {
3088
+ const token = typeof callback === "function" ? await callback(auth) : callback;
3089
+ if (!token) {
3090
+ return;
3091
+ }
3092
+ if (auth.scheme === "bearer") {
3093
+ return `Bearer ${token}`;
3094
+ }
3095
+ if (auth.scheme === "basic") {
3096
+ return `Basic ${btoa(token)}`;
3097
+ }
3098
+ return token;
3099
+ };
3100
+
3101
+ // src/gen/client/utils.gen.ts
3102
+ var createQuerySerializer = ({
3103
+ parameters = {},
3104
+ ...args
3105
+ } = {}) => {
3106
+ const querySerializer = (queryParams) => {
3107
+ const search = [];
3108
+ if (queryParams && typeof queryParams === "object") {
3109
+ for (const name in queryParams) {
3110
+ const value = queryParams[name];
3111
+ if (value === undefined || value === null) {
3112
+ continue;
3113
+ }
3114
+ const options = parameters[name] || args;
3115
+ if (Array.isArray(value)) {
3116
+ const serializedArray = serializeArrayParam({
3117
+ allowReserved: options.allowReserved,
3118
+ explode: true,
3119
+ name,
3120
+ style: "form",
3121
+ value,
3122
+ ...options.array
3123
+ });
3124
+ if (serializedArray)
3125
+ search.push(serializedArray);
3126
+ } else if (typeof value === "object") {
3127
+ const serializedObject = serializeObjectParam({
3128
+ allowReserved: options.allowReserved,
3129
+ explode: true,
3130
+ name,
3131
+ style: "deepObject",
3132
+ value,
3133
+ ...options.object
3134
+ });
3135
+ if (serializedObject)
3136
+ search.push(serializedObject);
3137
+ } else {
3138
+ const serializedPrimitive = serializePrimitiveParam({
3139
+ allowReserved: options.allowReserved,
3140
+ name,
3141
+ value
3142
+ });
3143
+ if (serializedPrimitive)
3144
+ search.push(serializedPrimitive);
3145
+ }
3146
+ }
3147
+ }
3148
+ return search.join("&");
3149
+ };
3150
+ return querySerializer;
3151
+ };
3152
+ var getParseAs = (contentType) => {
3153
+ if (!contentType) {
3154
+ return "stream";
3155
+ }
3156
+ const cleanContent = contentType.split(";")[0]?.trim();
3157
+ if (!cleanContent) {
3158
+ return;
3159
+ }
3160
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
3161
+ return "json";
3162
+ }
3163
+ if (cleanContent === "multipart/form-data") {
3164
+ return "formData";
3165
+ }
3166
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
3167
+ return "blob";
3168
+ }
3169
+ if (cleanContent.startsWith("text/")) {
3170
+ return "text";
3171
+ }
3172
+ return;
3173
+ };
3174
+ var checkForExistence = (options, name) => {
3175
+ if (!name) {
3176
+ return false;
3177
+ }
3178
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
3179
+ return true;
3180
+ }
3181
+ return false;
3182
+ };
3183
+ var setAuthParams = async ({
3184
+ security,
3185
+ ...options
3186
+ }) => {
3187
+ for (const auth of security) {
3188
+ if (checkForExistence(options, auth.name)) {
3189
+ continue;
3190
+ }
3191
+ const token = await getAuthToken(auth, options.auth);
3192
+ if (!token) {
3193
+ continue;
3194
+ }
3195
+ const name = auth.name ?? "Authorization";
3196
+ switch (auth.in) {
3197
+ case "query":
3198
+ if (!options.query) {
3199
+ options.query = {};
3200
+ }
3201
+ options.query[name] = token;
3202
+ break;
3203
+ case "cookie":
3204
+ options.headers.append("Cookie", `${name}=${token}`);
3205
+ break;
3206
+ case "header":
3207
+ default:
3208
+ options.headers.set(name, token);
3209
+ break;
3210
+ }
3211
+ }
3212
+ };
3213
+ var buildUrl = (options) => getUrl({
3214
+ baseUrl: options.baseUrl,
3215
+ path: options.path,
3216
+ query: options.query,
3217
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
3218
+ url: options.url
3219
+ });
3220
+ var mergeConfigs = (a, b) => {
3221
+ const config = { ...a, ...b };
3222
+ if (config.baseUrl?.endsWith("/")) {
3223
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
3224
+ }
3225
+ config.headers = mergeHeaders(a.headers, b.headers);
3226
+ return config;
3227
+ };
3228
+ var headersEntries = (headers) => {
3229
+ const entries = [];
3230
+ headers.forEach((value, key) => {
3231
+ entries.push([key, value]);
3232
+ });
3233
+ return entries;
3234
+ };
3235
+ var mergeHeaders = (...headers) => {
3236
+ const mergedHeaders = new Headers;
3237
+ for (const header of headers) {
3238
+ if (!header) {
3239
+ continue;
3240
+ }
3241
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
3242
+ for (const [key, value] of iterator) {
3243
+ if (value === null) {
3244
+ mergedHeaders.delete(key);
3245
+ } else if (Array.isArray(value)) {
3246
+ for (const v of value) {
3247
+ mergedHeaders.append(key, v);
3248
+ }
3249
+ } else if (value !== undefined) {
3250
+ mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
3251
+ }
3252
+ }
3253
+ }
3254
+ return mergedHeaders;
3255
+ };
3256
+
3257
+ class Interceptors {
3258
+ fns = [];
3259
+ clear() {
3260
+ this.fns = [];
3261
+ }
3262
+ eject(id) {
3263
+ const index = this.getInterceptorIndex(id);
3264
+ if (this.fns[index]) {
3265
+ this.fns[index] = null;
3266
+ }
3267
+ }
3268
+ exists(id) {
3269
+ const index = this.getInterceptorIndex(id);
3270
+ return Boolean(this.fns[index]);
3271
+ }
3272
+ getInterceptorIndex(id) {
3273
+ if (typeof id === "number") {
3274
+ return this.fns[id] ? id : -1;
3275
+ }
3276
+ return this.fns.indexOf(id);
3277
+ }
3278
+ update(id, fn) {
3279
+ const index = this.getInterceptorIndex(id);
3280
+ if (this.fns[index]) {
3281
+ this.fns[index] = fn;
3282
+ return id;
3283
+ }
3284
+ return false;
3285
+ }
3286
+ use(fn) {
3287
+ this.fns.push(fn);
3288
+ return this.fns.length - 1;
3289
+ }
3290
+ }
3291
+ var createInterceptors = () => ({
3292
+ error: new Interceptors,
3293
+ request: new Interceptors,
3294
+ response: new Interceptors
3295
+ });
3296
+ var defaultQuerySerializer = createQuerySerializer({
3297
+ allowReserved: false,
3298
+ array: {
3299
+ explode: true,
3300
+ style: "form"
3301
+ },
3302
+ object: {
3303
+ explode: true,
3304
+ style: "deepObject"
3305
+ }
3306
+ });
3307
+ var defaultHeaders = {
3308
+ "Content-Type": "application/json"
3309
+ };
3310
+ var createConfig = (override = {}) => ({
3311
+ ...jsonBodySerializer,
3312
+ headers: defaultHeaders,
3313
+ parseAs: "auto",
3314
+ querySerializer: defaultQuerySerializer,
3315
+ ...override
3316
+ });
3317
+
3318
+ // src/gen/client/client.gen.ts
3319
+ var createClient = (config = {}) => {
3320
+ let _config = mergeConfigs(createConfig(), config);
3321
+ const getConfig = () => ({ ..._config });
3322
+ const setConfig = (config2) => {
3323
+ _config = mergeConfigs(_config, config2);
3324
+ return getConfig();
3325
+ };
3326
+ const interceptors = createInterceptors();
3327
+ const beforeRequest = async (options) => {
3328
+ const opts = {
3329
+ ..._config,
3330
+ ...options,
3331
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
3332
+ headers: mergeHeaders(_config.headers, options.headers),
3333
+ serializedBody: undefined
3334
+ };
3335
+ if (opts.security) {
3336
+ await setAuthParams({
3337
+ ...opts,
3338
+ security: opts.security
3339
+ });
3340
+ }
3341
+ if (opts.requestValidator) {
3342
+ await opts.requestValidator(opts);
3343
+ }
3344
+ if (opts.body !== undefined && opts.bodySerializer) {
3345
+ opts.serializedBody = opts.bodySerializer(opts.body);
3346
+ }
3347
+ if (opts.body === undefined || opts.serializedBody === "") {
3348
+ opts.headers.delete("Content-Type");
3349
+ }
3350
+ const url = buildUrl(opts);
3351
+ return { opts, url };
3352
+ };
3353
+ const request = async (options) => {
3354
+ const { opts, url } = await beforeRequest(options);
3355
+ const requestInit = {
3356
+ redirect: "follow",
3357
+ ...opts,
3358
+ body: getValidRequestBody(opts)
3359
+ };
3360
+ let request2 = new Request(url, requestInit);
3361
+ for (const fn of interceptors.request.fns) {
3362
+ if (fn) {
3363
+ request2 = await fn(request2, opts);
3364
+ }
3365
+ }
3366
+ const _fetch = opts.fetch;
3367
+ let response;
3368
+ try {
3369
+ response = await _fetch(request2);
3370
+ } catch (error2) {
3371
+ let finalError2 = error2;
3372
+ for (const fn of interceptors.error.fns) {
3373
+ if (fn) {
3374
+ finalError2 = await fn(error2, undefined, request2, opts);
3375
+ }
3376
+ }
3377
+ finalError2 = finalError2 || {};
3378
+ if (opts.throwOnError) {
3379
+ throw finalError2;
3380
+ }
3381
+ return opts.responseStyle === "data" ? undefined : {
3382
+ error: finalError2,
3383
+ request: request2,
3384
+ response: undefined
3385
+ };
3386
+ }
3387
+ for (const fn of interceptors.response.fns) {
3388
+ if (fn) {
3389
+ response = await fn(response, request2, opts);
3390
+ }
3391
+ }
3392
+ const result = {
3393
+ request: request2,
3394
+ response
3395
+ };
3396
+ if (response.ok) {
3397
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
3398
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
3399
+ let emptyData;
3400
+ switch (parseAs) {
3401
+ case "arrayBuffer":
3402
+ case "blob":
3403
+ case "text":
3404
+ emptyData = await response[parseAs]();
3405
+ break;
3406
+ case "formData":
3407
+ emptyData = new FormData;
3408
+ break;
3409
+ case "stream":
3410
+ emptyData = response.body;
3411
+ break;
3412
+ case "json":
3413
+ default:
3414
+ emptyData = {};
3415
+ break;
3416
+ }
3417
+ return opts.responseStyle === "data" ? emptyData : {
3418
+ data: emptyData,
3419
+ ...result
3420
+ };
3421
+ }
3422
+ let data;
3423
+ switch (parseAs) {
3424
+ case "arrayBuffer":
3425
+ case "blob":
3426
+ case "formData":
3427
+ case "text":
3428
+ data = await response[parseAs]();
3429
+ break;
3430
+ case "json": {
3431
+ const text = await response.text();
3432
+ data = text ? JSON.parse(text) : {};
3433
+ break;
3434
+ }
3435
+ case "stream":
3436
+ return opts.responseStyle === "data" ? response.body : {
3437
+ data: response.body,
3438
+ ...result
3439
+ };
3440
+ }
3441
+ if (parseAs === "json") {
3442
+ if (opts.responseValidator) {
3443
+ await opts.responseValidator(data);
3444
+ }
3445
+ if (opts.responseTransformer) {
3446
+ data = await opts.responseTransformer(data);
3447
+ }
3448
+ }
3449
+ return opts.responseStyle === "data" ? data : {
3450
+ data,
3451
+ ...result
3452
+ };
3453
+ }
3454
+ const textError = await response.text();
3455
+ let jsonError;
3456
+ try {
3457
+ jsonError = JSON.parse(textError);
3458
+ } catch {}
3459
+ const error = jsonError ?? textError;
3460
+ let finalError = error;
3461
+ for (const fn of interceptors.error.fns) {
3462
+ if (fn) {
3463
+ finalError = await fn(error, response, request2, opts);
3464
+ }
3465
+ }
3466
+ finalError = finalError || {};
3467
+ if (opts.throwOnError) {
3468
+ throw finalError;
3469
+ }
3470
+ return opts.responseStyle === "data" ? undefined : {
3471
+ error: finalError,
3472
+ ...result
3473
+ };
3474
+ };
3475
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
3476
+ const makeSseFn = (method) => async (options) => {
3477
+ const { opts, url } = await beforeRequest(options);
3478
+ return createSseClient({
3479
+ ...opts,
3480
+ body: opts.body,
3481
+ headers: opts.headers,
3482
+ method,
3483
+ onRequest: async (url2, init) => {
3484
+ let request2 = new Request(url2, init);
3485
+ for (const fn of interceptors.request.fns) {
3486
+ if (fn) {
3487
+ request2 = await fn(request2, opts);
3488
+ }
3489
+ }
3490
+ return request2;
3491
+ },
3492
+ serializedBody: getValidRequestBody(opts),
3493
+ url
3494
+ });
3495
+ };
3496
+ return {
3497
+ buildUrl,
3498
+ connect: makeMethodFn("CONNECT"),
3499
+ delete: makeMethodFn("DELETE"),
3500
+ get: makeMethodFn("GET"),
3501
+ getConfig,
3502
+ head: makeMethodFn("HEAD"),
3503
+ interceptors,
3504
+ options: makeMethodFn("OPTIONS"),
3505
+ patch: makeMethodFn("PATCH"),
3506
+ post: makeMethodFn("POST"),
3507
+ put: makeMethodFn("PUT"),
3508
+ request,
3509
+ setConfig,
3510
+ sse: {
3511
+ connect: makeSseFn("CONNECT"),
3512
+ delete: makeSseFn("DELETE"),
3513
+ get: makeSseFn("GET"),
3514
+ head: makeSseFn("HEAD"),
3515
+ options: makeSseFn("OPTIONS"),
3516
+ patch: makeSseFn("PATCH"),
3517
+ post: makeSseFn("POST"),
3518
+ put: makeSseFn("PUT"),
3519
+ trace: makeSseFn("TRACE")
3520
+ },
3521
+ trace: makeMethodFn("TRACE")
3522
+ };
3523
+ };
3524
+ // src/openapi-runtime.ts
3525
+ var DEFAULT_BASE_URL = "https://api.multisender.app";
3526
+ var DEFAULT_TIMEOUT = 30000;
3527
+ var defaultRuntimeConfig = {
3528
+ apiKey: "",
3529
+ baseUrl: DEFAULT_BASE_URL,
3530
+ timeout: DEFAULT_TIMEOUT,
3531
+ headers: {}
3532
+ };
3533
+ var mergeHeaders2 = (headers) => ({
3534
+ ...headers
3535
+ });
3536
+ var withTimeoutFetch = (timeoutMs) => {
3537
+ const timeout = timeoutMs ?? DEFAULT_TIMEOUT;
3538
+ return async (input, init) => {
3539
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
3540
+ const timeoutSignal = AbortSignal.timeout(timeout);
3541
+ if (!init?.signal) {
3542
+ return fetch(input, { ...init, signal: timeoutSignal });
3543
+ }
3544
+ const controller2 = new AbortController;
3545
+ const abort = () => controller2.abort();
3546
+ timeoutSignal.addEventListener("abort", abort, { once: true });
3547
+ init.signal.addEventListener("abort", abort, { once: true });
3548
+ const signal2 = controller2.signal;
3549
+ return fetch(input, { ...init, signal: signal2 });
3550
+ }
3551
+ const controller = new AbortController;
3552
+ const timer = setTimeout(() => controller.abort(), timeout);
3553
+ init?.signal?.addEventListener("abort", () => controller.abort(), { once: true });
3554
+ const signal = controller.signal;
3555
+ try {
3556
+ return await fetch(input, { ...init, signal });
3557
+ } finally {
3558
+ clearTimeout(timer);
3559
+ }
3560
+ };
3561
+ };
3562
+ var toClientConfig = (config) => ({
3563
+ baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
3564
+ fetch: withTimeoutFetch(config.timeout),
3565
+ headers: {
3566
+ ...mergeHeaders2(config.headers),
3567
+ ...config.apiKey ? { "X-API-Key": config.apiKey } : {}
3568
+ }
3569
+ });
3570
+ var setRuntimeConfig = (config) => {
3571
+ return toClientConfig({
3572
+ ...defaultRuntimeConfig,
3573
+ ...config,
3574
+ headers: {
3575
+ ...defaultRuntimeConfig.headers,
3576
+ ...mergeHeaders2(config.headers)
3577
+ }
3578
+ });
3579
+ };
3580
+ var createClientConfig = (override = {}) => ({
3581
+ ...toClientConfig(defaultRuntimeConfig),
3582
+ ...override,
3583
+ headers: {
3584
+ ...toClientConfig(defaultRuntimeConfig).headers,
3585
+ ...override.headers ?? {}
3586
+ }
3587
+ });
3588
+
3589
+ // src/core/errors.ts
3590
+ class MultisenderError extends Error {
3591
+ constructor(message) {
3592
+ super(message);
3593
+ this.name = "MultisenderError";
3594
+ Object.setPrototypeOf(this, MultisenderError.prototype);
3595
+ }
3596
+ }
3597
+
3598
+ class ApiError extends MultisenderError {
3599
+ status;
3600
+ body;
3601
+ constructor(status, body, message) {
3602
+ super(message || `API request failed with status ${status}`);
3603
+ this.status = status;
3604
+ this.body = body;
3605
+ this.name = "ApiError";
3606
+ Object.setPrototypeOf(this, ApiError.prototype);
3607
+ }
3608
+ }
3609
+
3610
+ class NetworkError extends MultisenderError {
3611
+ cause;
3612
+ constructor(message, cause) {
3613
+ super(message);
3614
+ this.cause = cause;
3615
+ this.name = "NetworkError";
3616
+ Object.setPrototypeOf(this, NetworkError.prototype);
3617
+ }
3618
+ }
3619
+
3620
+ class ValidationError extends MultisenderError {
3621
+ fields;
3622
+ constructor(message, fields) {
3623
+ super(message);
3624
+ this.fields = fields;
3625
+ this.name = "ValidationError";
3626
+ Object.setPrototypeOf(this, ValidationError.prototype);
3627
+ }
3628
+ }
3629
+
3630
+ class TimeoutError extends MultisenderError {
3631
+ constructor(message = "Request timeout") {
3632
+ super(message);
3633
+ this.name = "TimeoutError";
3634
+ Object.setPrototypeOf(this, TimeoutError.prototype);
3635
+ }
3636
+ }
3637
+
3638
+ // src/core/generated-transport.ts
3639
+ var isGeneratedHttpError = (error) => typeof error === "object" && error !== null && (("status" in error) || ("body" in error));
3640
+ var isGeneratedWrappedResponse = (value) => typeof value === "object" && value !== null && ("data" in value);
3641
+ var mapGeneratedError = (error) => {
3642
+ if (error instanceof Error) {
3643
+ if (error.name === "AbortError" || error.name === "TimeoutError") {
3644
+ throw new TimeoutError("Request timeout");
3645
+ }
3646
+ throw new NetworkError(error.message, error);
3647
+ }
3648
+ if (isGeneratedHttpError(error)) {
3649
+ throw new ApiError(error.status ?? 500, error.body ?? error);
3650
+ }
3651
+ if (typeof error === "string") {
3652
+ throw new ApiError(500, { message: error }, error);
3653
+ }
3654
+ throw new ApiError(500, error, "Unexpected API error");
3655
+ };
3656
+ var executeGenerated = async (operation) => {
3657
+ try {
3658
+ const result = await operation;
3659
+ return isGeneratedWrappedResponse(result) ? result.data : result;
3660
+ } catch (error) {
3661
+ return mapGeneratedError(error);
3662
+ }
3663
+ };
3664
+
3665
+ // src/core/pagination.ts
3666
+ function buildPaginationQuery(params) {
3667
+ if (!params)
3668
+ return {};
3669
+ const query = {};
3670
+ if (params.page !== undefined) {
3671
+ query.page = params.page.toString();
3672
+ }
3673
+ if (params.limit !== undefined) {
3674
+ query.limit = params.limit.toString();
3675
+ }
3676
+ if (params.orderBy) {
3677
+ query.orderBy = params.orderBy;
3678
+ }
3679
+ if (params.orderDir) {
3680
+ query.orderDir = params.orderDir;
3681
+ }
3682
+ if (params.search) {
3683
+ query.search = params.search;
3684
+ }
3685
+ return query;
3686
+ }
3687
+
3688
+ // src/gen/client.gen.ts
3689
+ var client = createClient(createClientConfig(createConfig()));
3690
+
3691
+ // src/gen/sdk.gen.ts
3692
+ var getProjectInfo = (options) => (options.client ?? client).get({ url: "/api/v1/project", ...options });
3693
+ var getProjectMembers = (options) => (options.client ?? client).get({ url: "/api/v1/project/members", ...options });
3694
+ var getApiKeys = (options) => (options.client ?? client).get({ url: "/api/v1/project/api-keys", ...options });
3695
+ var createApiKey = (options) => (options.client ?? client).post({
3696
+ url: "/api/v1/project/api-keys",
3697
+ ...options,
3698
+ headers: {
3699
+ "Content-Type": "application/json",
3700
+ ...options.headers
3701
+ }
3702
+ });
3703
+ var deleteApiKey = (options) => (options.client ?? client).delete({ url: "/api/v1/project/api-keys/{apiKeyId}", ...options });
3704
+ var updateApiKey = (options) => (options.client ?? client).patch({
3705
+ url: "/api/v1/project/api-keys/{apiKeyId}",
3706
+ ...options,
3707
+ headers: {
3708
+ "Content-Type": "application/json",
3709
+ ...options.headers
3710
+ }
3711
+ });
3712
+ var findAll = (options) => (options.client ?? client).get({ url: "/api/v1/lists", ...options });
3713
+ var create = (options) => (options.client ?? client).post({
3714
+ url: "/api/v1/lists",
3715
+ ...options,
3716
+ headers: {
3717
+ "Content-Type": "application/json",
3718
+ ...options.headers
3719
+ }
3720
+ });
3721
+ var remove = (options) => (options.client ?? client).delete({ url: "/api/v1/lists/{listId}", ...options });
3722
+ var findOne = (options) => (options.client ?? client).get({ url: "/api/v1/lists/{listId}", ...options });
3723
+ var update = (options) => (options.client ?? client).patch({
3724
+ url: "/api/v1/lists/{listId}",
3725
+ ...options,
3726
+ headers: {
3727
+ "Content-Type": "application/json",
3728
+ ...options.headers
3729
+ }
3730
+ });
3731
+ var getRecipients = (options) => (options.client ?? client).get({ url: "/api/v1/lists/{listId}/recipients", ...options });
3732
+ var addRecipient = (options) => (options.client ?? client).post({
3733
+ url: "/api/v1/lists/{listId}/recipients",
3734
+ ...options,
3735
+ headers: {
3736
+ "Content-Type": "application/json",
3737
+ ...options.headers
3738
+ }
3739
+ });
3740
+ var addRecipientsBulk = (options) => (options.client ?? client).post({
3741
+ url: "/api/v1/lists/{listId}/recipients/bulk",
3742
+ ...options,
3743
+ headers: {
3744
+ "Content-Type": "application/json",
3745
+ ...options.headers
3746
+ }
3747
+ });
3748
+ var removeRecipient = (options) => (options.client ?? client).delete({ url: "/api/v1/lists/{listId}/recipients/{recipientId}", ...options });
3749
+ var importFromFile = (options) => (options.client ?? client).post({ url: "/api/v1/lists/{listId}/import", ...options });
3750
+ var createDistributionList = (options) => (options.client ?? client).post({
3751
+ url: "/api/v1/lists/distribution",
3752
+ ...options,
3753
+ headers: {
3754
+ "Content-Type": "application/json",
3755
+ ...options.headers
3756
+ }
3757
+ });
3758
+ var importCsvDistribution = (options) => (options.client ?? client).post({
3759
+ url: "/api/v1/lists/distribution/csv",
3760
+ ...options,
3761
+ headers: {
3762
+ "Content-Type": "application/json",
3763
+ ...options.headers
3764
+ }
3765
+ });
3766
+ var distribute = (options) => (options.client ?? client).post({
3767
+ url: "/api/v1/distribute",
3768
+ ...options,
3769
+ headers: {
3770
+ "Content-Type": "application/json",
3771
+ ...options.headers
3772
+ }
3773
+ });
3774
+ var findAll2 = (options) => (options.client ?? client).get({ url: "/api/v1/distributions", ...options });
3775
+ var findOne2 = (options) => (options.client ?? client).get({ url: "/api/v1/distributions/{id}", ...options });
3776
+ var getTransactions = (options) => (options.client ?? client).get({ url: "/api/v1/distributions/{id}/transactions", ...options });
3777
+ var getStats = (options) => (options.client ?? client).get({ url: "/api/v1/distributions/{id}/stats", ...options });
3778
+ var cancel = (options) => (options.client ?? client).post({ url: "/api/v1/distributions/{id}/cancel", ...options });
3779
+ var getChains = (options) => (options.client ?? client).get({ url: "/api/v1/catalogs/chains", ...options });
3780
+ var getChain = (options) => (options.client ?? client).get({ url: "/api/v1/catalogs/chains/{chainId}", ...options });
3781
+ var getTokens = (options) => (options.client ?? client).get({ url: "/api/v1/catalogs/tokens", ...options });
3782
+ var searchTokens = (options) => (options.client ?? client).get({ url: "/api/v1/catalogs/tokens/search", ...options });
3783
+ var getToken = (options) => (options.client ?? client).get({ url: "/api/v1/catalogs/tokens/{chainId}/{address}", ...options });
3784
+ // src/services/response-utils.ts
3785
+ function unwrapData(result) {
3786
+ const raw = result;
3787
+ if (raw?.data != null)
3788
+ return raw.data;
3789
+ return result;
3790
+ }
3791
+ function unwrapDistribution(result) {
3792
+ const raw = result;
3793
+ if (raw?.data?.distribution != null)
3794
+ return raw.data.distribution;
3795
+ if (raw?.distribution != null)
3796
+ return raw.distribution;
3797
+ return result;
3798
+ }
3799
+ function normalizePaginatedResponse(result, page, limit) {
3800
+ const raw = result;
3801
+ if ("meta" in raw && raw.meta != null && Array.isArray(raw.data)) {
3802
+ return raw;
3803
+ }
3804
+ const inner = raw.data && typeof raw.data === "object" && "data" in raw.data ? raw.data : null;
3805
+ const items = inner && Array.isArray(inner.data) ? inner.data : [];
3806
+ const total = inner && typeof inner.total === "number" ? inner.total : items.length;
3807
+ return {
3808
+ data: items,
3809
+ meta: {
3810
+ page,
3811
+ limit,
3812
+ total,
3813
+ totalPages: Math.ceil(total / limit) || 1
3814
+ }
3815
+ };
3816
+ }
3817
+
3818
+ // src/services/distributions.ts
3819
+ class DistributionsService {
3820
+ headers;
3821
+ client;
3822
+ constructor(headers, client2) {
3823
+ this.headers = headers;
3824
+ this.client = client2;
3825
+ }
3826
+ async distribute(request) {
3827
+ const result = await executeGenerated(distribute({
3828
+ body: request,
3829
+ client: this.client,
3830
+ headers: this.headers,
3831
+ throwOnError: true
3832
+ }));
3833
+ return unwrapDistribution(result);
3834
+ }
3835
+ async list(params) {
3836
+ const query = buildPaginationQuery(params);
3837
+ const page = params?.page ?? 1;
3838
+ const limit = params?.limit ?? 20;
3839
+ const result = await executeGenerated(findAll2({
3840
+ client: this.client,
3841
+ headers: this.headers,
3842
+ query,
3843
+ throwOnError: true
3844
+ }));
3845
+ return normalizePaginatedResponse(result, page, limit);
3846
+ }
3847
+ async get(id) {
3848
+ const result = await executeGenerated(findOne2({
3849
+ client: this.client,
3850
+ headers: this.headers,
3851
+ path: { id },
3852
+ throwOnError: true
3853
+ }));
3854
+ return unwrapData(result);
3855
+ }
3856
+ async getTransactions(id, params) {
3857
+ const query = buildPaginationQuery(params);
3858
+ const page = params?.page ?? 1;
3859
+ const limit = params?.limit ?? 20;
3860
+ const result = await executeGenerated(getTransactions({
3861
+ client: this.client,
3862
+ headers: this.headers,
3863
+ path: { id },
3864
+ query,
3865
+ throwOnError: true
3866
+ }));
3867
+ return normalizePaginatedResponse(result, page, limit);
3868
+ }
3869
+ async getStats(id) {
3870
+ const result = await executeGenerated(getStats({
3871
+ client: this.client,
3872
+ headers: this.headers,
3873
+ path: { id },
3874
+ throwOnError: true
3875
+ }));
3876
+ return unwrapData(result);
3877
+ }
3878
+ async cancel(id) {
3879
+ const result = await executeGenerated(cancel({
3880
+ client: this.client,
3881
+ headers: this.headers,
3882
+ path: { id },
3883
+ throwOnError: true
3884
+ }));
3885
+ return unwrapData(result);
3886
+ }
3887
+ }
3888
+
3889
+ // src/services/lists.ts
3890
+ class ListsService {
3891
+ headers;
3892
+ client;
3893
+ constructor(headers, client2) {
3894
+ this.headers = headers;
3895
+ this.client = client2;
3896
+ }
3897
+ async list(params) {
3898
+ const query = buildPaginationQuery(params);
3899
+ const page = params?.page ?? 1;
3900
+ const limit = params?.limit ?? 20;
3901
+ const result = await executeGenerated(findAll({
3902
+ client: this.client,
3903
+ headers: this.headers,
3904
+ query,
3905
+ throwOnError: true
3906
+ }));
3907
+ return normalizePaginatedResponse(result, page, limit);
3908
+ }
3909
+ async create(request) {
3910
+ const result = await executeGenerated(create({
3911
+ body: request,
3912
+ client: this.client,
3913
+ headers: this.headers,
3914
+ throwOnError: true
3915
+ }));
3916
+ return unwrapData(result);
3917
+ }
3918
+ async get(listId) {
3919
+ const result = await executeGenerated(findOne({
3920
+ client: this.client,
3921
+ headers: this.headers,
3922
+ path: { listId },
3923
+ throwOnError: true
3924
+ }));
3925
+ return unwrapData(result);
3926
+ }
3927
+ async update(listId, request) {
3928
+ const result = await executeGenerated(update({
3929
+ body: request,
3930
+ client: this.client,
3931
+ headers: this.headers,
3932
+ path: { listId },
3933
+ throwOnError: true
3934
+ }));
3935
+ return unwrapData(result);
3936
+ }
3937
+ async delete(listId) {
3938
+ await executeGenerated(remove({
3939
+ client: this.client,
3940
+ headers: this.headers,
3941
+ path: { listId },
3942
+ throwOnError: true
3943
+ }));
3944
+ }
3945
+ async getRecipients(listId, params) {
3946
+ const query = buildPaginationQuery(params);
3947
+ const page = params?.page ?? 1;
3948
+ const limit = params?.limit ?? 20;
3949
+ const result = await executeGenerated(getRecipients({
3950
+ client: this.client,
3951
+ headers: this.headers,
3952
+ path: { listId },
3953
+ query,
3954
+ throwOnError: true
3955
+ }));
3956
+ return normalizePaginatedResponse(result, page, limit);
3957
+ }
3958
+ async addRecipient(listId, request) {
3959
+ const result = await executeGenerated(addRecipient({
3960
+ body: request,
3961
+ client: this.client,
3962
+ headers: this.headers,
3963
+ path: { listId },
3964
+ throwOnError: true
3965
+ }));
3966
+ return unwrapData(result);
3967
+ }
3968
+ async addRecipientsBulk(listId, request) {
3969
+ const result = await executeGenerated(addRecipientsBulk({
3970
+ body: request,
3971
+ client: this.client,
3972
+ headers: this.headers,
3973
+ path: { listId },
3974
+ throwOnError: true
3975
+ }));
3976
+ return {
3977
+ added: result.added ?? 0,
3978
+ skippedAddresses: result.skippedAddresses ?? [],
3979
+ errors: result.errors ?? []
3980
+ };
3981
+ }
3982
+ async removeRecipient(listId, recipientId) {
3983
+ await executeGenerated(removeRecipient({
3984
+ client: this.client,
3985
+ headers: this.headers,
3986
+ path: { listId, recipientId },
3987
+ throwOnError: true
3988
+ }));
3989
+ }
3990
+ async importFromCsv(listId, file) {
3991
+ if (!file) {
3992
+ throw new Error("importFromCsv: file is required");
3993
+ }
3994
+ const formData = new FormData;
3995
+ if (file instanceof Buffer) {
3996
+ formData.append("file", new Blob([new Uint8Array(file)]), "import.csv");
3997
+ } else {
3998
+ const f = file;
3999
+ formData.append("file", f, f.name);
4000
+ }
4001
+ const result = await executeGenerated(importFromFile({
4002
+ path: { listId },
4003
+ body: formData,
4004
+ bodySerializer: (b) => b,
4005
+ client: this.client,
4006
+ headers: this.headers,
4007
+ throwOnError: true
4008
+ }));
4009
+ return unwrapData(result);
4010
+ }
4011
+ async createDistributionList(request) {
4012
+ const result = await executeGenerated(createDistributionList({
4013
+ body: request,
4014
+ client: this.client,
4015
+ headers: this.headers,
4016
+ throwOnError: true
4017
+ }));
4018
+ const raw = unwrapData(result);
4019
+ if (raw?.list == null)
4020
+ throw new Error("API response missing list");
4021
+ return raw.list;
4022
+ }
4023
+ async importCsvDistribution(request) {
4024
+ const result = await executeGenerated(importCsvDistribution({
4025
+ body: request,
4026
+ client: this.client,
4027
+ headers: this.headers,
4028
+ throwOnError: true
4029
+ }));
4030
+ const raw = unwrapData(result);
4031
+ if (raw?.list == null)
4032
+ throw new Error("API response missing list");
4033
+ return raw.list;
4034
+ }
4035
+ }
4036
+
4037
+ // src/services/project.ts
4038
+ class ProjectService {
4039
+ headers;
4040
+ client;
4041
+ constructor(headers, client2) {
4042
+ this.headers = headers;
4043
+ this.client = client2;
4044
+ }
4045
+ async getInfo() {
4046
+ const result = await executeGenerated(getProjectInfo({
4047
+ client: this.client,
4048
+ headers: this.headers,
4049
+ throwOnError: true
4050
+ }));
4051
+ return unwrapData(result);
4052
+ }
4053
+ async getMembers() {
4054
+ const result = await executeGenerated(getProjectMembers({
4055
+ client: this.client,
4056
+ headers: this.headers,
4057
+ throwOnError: true
4058
+ }));
4059
+ const members = unwrapData(result);
4060
+ return Array.isArray(members) ? members : [members];
4061
+ }
4062
+ async listApiKeys() {
4063
+ const result = await executeGenerated(getApiKeys({
4064
+ client: this.client,
4065
+ headers: this.headers,
4066
+ throwOnError: true
4067
+ }));
4068
+ const data = unwrapData(result);
4069
+ return Array.isArray(data) ? data : result;
4070
+ }
4071
+ async createApiKey(request) {
4072
+ const result = await executeGenerated(createApiKey({
4073
+ body: request,
4074
+ client: this.client,
4075
+ headers: this.headers,
4076
+ throwOnError: true
4077
+ }));
4078
+ return unwrapData(result);
4079
+ }
4080
+ async updateApiKey(apiKeyId, request) {
4081
+ const result = await executeGenerated(updateApiKey({
4082
+ body: request,
4083
+ client: this.client,
4084
+ headers: this.headers,
4085
+ path: { apiKeyId },
4086
+ throwOnError: true
4087
+ }));
4088
+ return unwrapData(result);
4089
+ }
4090
+ async deleteApiKey(apiKeyId) {
4091
+ await executeGenerated(deleteApiKey({
4092
+ client: this.client,
4093
+ headers: this.headers,
4094
+ path: { apiKeyId },
4095
+ throwOnError: true
4096
+ }));
4097
+ }
4098
+ }
4099
+
4100
+ // src/utils/validation.ts
4101
+ function validateEthereumAddress(address) {
4102
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
4103
+ }
4104
+ function validatePositiveNumber(value) {
4105
+ const num = typeof value === "string" ? parseFloat(value) : value;
4106
+ return !isNaN(num) && num > 0;
4107
+ }
4108
+ function validateChainId(chainId) {
4109
+ if (!Number.isInteger(chainId) || chainId <= 0) {
4110
+ throw new ValidationError("Chain ID must be a positive integer");
4111
+ }
4112
+ }
4113
+ function validateRecipients(recipients) {
4114
+ if (!Array.isArray(recipients) || recipients.length === 0) {
4115
+ throw new ValidationError("Recipients must be a non-empty array");
4116
+ }
4117
+ for (let i = 0;i < recipients.length; i++) {
4118
+ const [address, amount] = recipients[i];
4119
+ if (!address || typeof address !== "string") {
4120
+ throw new ValidationError(`Invalid address at index ${i}`);
4121
+ }
4122
+ if (!validateEthereumAddress(address)) {
4123
+ throw new ValidationError(`Invalid Ethereum address at index ${i}: ${address}`);
4124
+ }
4125
+ if (!validatePositiveNumber(amount)) {
4126
+ throw new ValidationError(`Invalid amount at index ${i}: ${amount}`);
4127
+ }
4128
+ }
4129
+ }
4130
+ function validateTokenAddress(address) {
4131
+ if (!validateEthereumAddress(address)) {
4132
+ throw new ValidationError(`Invalid token address: ${address}`);
4133
+ }
4134
+ }
4135
+ function validateApiKey(apiKey) {
4136
+ if (!apiKey || apiKey.trim().length < 10) {
4137
+ throw new ValidationError("Invalid API key format");
4138
+ }
4139
+ }
4140
+
4141
+ // src/services/catalogs.ts
4142
+ class CatalogsService {
4143
+ headers;
4144
+ client;
4145
+ constructor(headers, client2) {
4146
+ this.headers = headers;
4147
+ this.client = client2;
4148
+ }
4149
+ async getChains() {
4150
+ return executeGenerated(getChains({
4151
+ client: this.client,
4152
+ headers: this.headers,
4153
+ throwOnError: true
4154
+ }));
4155
+ }
4156
+ async getChain(chainId) {
4157
+ const parsedChainId = Number(chainId);
4158
+ validateChainId(parsedChainId);
4159
+ return executeGenerated(getChain({
4160
+ client: this.client,
4161
+ headers: this.headers,
4162
+ path: { chainId: parsedChainId },
4163
+ throwOnError: true
4164
+ }));
4165
+ }
4166
+ async getTokens(chainId) {
4167
+ const parsedChainId = chainId !== undefined ? Number(chainId) : undefined;
4168
+ if (parsedChainId !== undefined)
4169
+ validateChainId(parsedChainId);
4170
+ return executeGenerated(getTokens({
4171
+ client: this.client,
4172
+ headers: this.headers,
4173
+ query: parsedChainId !== undefined ? { chainId: parsedChainId } : undefined,
4174
+ throwOnError: true
4175
+ }));
4176
+ }
4177
+ async getToken(chainId, address) {
4178
+ const parsedChainId = Number(chainId);
4179
+ validateChainId(parsedChainId);
4180
+ return executeGenerated(getToken({
4181
+ client: this.client,
4182
+ headers: this.headers,
4183
+ path: { address, chainId: parsedChainId },
4184
+ throwOnError: true
4185
+ }));
4186
+ }
4187
+ async searchTokens(symbol, chainId) {
4188
+ const parsedChainId = Number(chainId);
4189
+ validateChainId(parsedChainId);
4190
+ return executeGenerated(searchTokens({
4191
+ client: this.client,
4192
+ headers: this.headers,
4193
+ query: {
4194
+ chainId: parsedChainId,
4195
+ symbol
4196
+ },
4197
+ throwOnError: true
4198
+ }));
4199
+ }
4200
+ }
4201
+
4202
+ // src/multisender.ts
4203
+ class Multisender {
4204
+ distributions;
4205
+ lists;
4206
+ project;
4207
+ catalogs;
4208
+ client;
4209
+ authHeaders;
4210
+ constructor(config) {
4211
+ validateApiKey(config.apiKey);
4212
+ const resolvedConfig = {
4213
+ baseUrl: config.baseUrl || "https://api.multisender.app",
4214
+ apiKey: config.apiKey,
4215
+ timeout: config.timeout,
4216
+ headers: config.headers
4217
+ };
4218
+ this.client = createClient(setRuntimeConfig(resolvedConfig));
4219
+ this.authHeaders = { "X-API-Key": config.apiKey };
4220
+ this.client.interceptors.error.use((error, response) => {
4221
+ if (!response) {
4222
+ return error;
4223
+ }
4224
+ return {
4225
+ body: error,
4226
+ status: response.status
4227
+ };
4228
+ });
4229
+ this.distributions = new DistributionsService(this.authHeaders, this.client);
4230
+ this.lists = new ListsService(this.authHeaders, this.client);
4231
+ this.project = new ProjectService(this.authHeaders, this.client);
4232
+ this.catalogs = new CatalogsService(this.authHeaders, this.client);
4233
+ }
4234
+ static getVersion() {
4235
+ return "1.0.0";
4236
+ }
4237
+ }
4238
+
4239
+ // src/utils/csv.ts
4240
+ function parseCsv(csvData, options = {}) {
4241
+ const { delimiter: delimiter2 = ",", skipRows = 0, hasHeader = true } = options;
4242
+ const lines = csvData.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
4243
+ if (lines.length === 0) {
4244
+ throw new ValidationError("CSV data is empty");
4245
+ }
4246
+ let startIndex = skipRows;
4247
+ if (hasHeader) {
4248
+ startIndex += 1;
4249
+ }
4250
+ const recipients = [];
4251
+ for (let i = startIndex;i < lines.length; i++) {
4252
+ const line = lines[i];
4253
+ const parts = line.split(delimiter2).map((p) => p.trim());
4254
+ if (parts.length < 2) {
4255
+ throw new ValidationError(`Invalid CSV format at line ${i + 1}: expected at least 2 columns`);
4256
+ }
4257
+ const [address, amount] = parts;
4258
+ if (!address || !amount) {
4259
+ throw new ValidationError(`Invalid CSV format at line ${i + 1}: address and amount are required`);
4260
+ }
4261
+ recipients.push([address, amount]);
4262
+ }
4263
+ if (recipients.length === 0) {
4264
+ throw new ValidationError("CSV must contain at least one recipient");
4265
+ }
4266
+ return recipients;
4267
+ }
4268
+ function toCsv(recipients, includeHeader = true) {
4269
+ const lines = [];
4270
+ if (includeHeader) {
4271
+ lines.push("address,amount");
4272
+ }
4273
+ for (const [address, amount] of recipients) {
4274
+ lines.push(`${address},${amount}`);
4275
+ }
4276
+ return lines.join(`
4277
+ `);
4278
+ }
4279
+ function validateCsv(csvData, options = {}) {
4280
+ try {
4281
+ parseCsv(csvData, options);
4282
+ return true;
4283
+ } catch {
4284
+ return false;
4285
+ }
4286
+ }
4287
+
4288
+ // src/cli/commands/distribute.ts
4289
+ var {readFileSync} = (() => ({}));
4290
+ function createDistributeCommand() {
4291
+ const command = new Command("distribute");
4292
+ command.description("Create and execute a token distribution").requiredOption("-k, --api-key <key>", "API key for authentication").requiredOption("-c, --chain <chainId>", "Blockchain chain ID (1=Ethereum, 137=Polygon, etc.)", parseInt).requiredOption("-t, --token <address>", "Token contract address").requiredOption("-s, --symbol <symbol>", "Token symbol").option("-r, --recipients <file>", "CSV file with recipients (address,amount)").option("-a, --account <address>", "Sender wallet address").option("--base-url <url>", "Custom API base URL").action(async (options) => {
4293
+ try {
4294
+ if (!options.recipients) {
4295
+ console.error("Error: --recipients flag is required");
4296
+ process.exit(1);
4297
+ }
4298
+ const csvContent = readFileSync(options.recipients, "utf-8");
4299
+ const recipients = parseCsv(csvContent, { hasHeader: true });
4300
+ console.log(`\uD83D\uDCCB Loaded ${recipients.length} recipients from ${options.recipients}`);
4301
+ const sdk = new Multisender({
4302
+ apiKey: options.apiKey,
4303
+ baseUrl: options.baseUrl
4304
+ });
4305
+ console.log("\uD83D\uDE80 Creating distribution...");
4306
+ const distribution = await sdk.distributions.distribute({
4307
+ chainId: options.chain,
4308
+ tokenAddress: options.token,
4309
+ tokenSymbol: options.symbol,
4310
+ recipients,
4311
+ account: options.account
4312
+ });
4313
+ console.log("✅ Distribution created successfully!");
4314
+ console.log(` ID: ${distribution.id}`);
4315
+ console.log(` Name: ${distribution.name}`);
4316
+ console.log(` Status: ${distribution.status}`);
4317
+ console.log(` Total Recipients: ${distribution.totalRecipients}`);
4318
+ console.log(` Total Amount: ${distribution.totalAmount}`);
4319
+ } catch (error) {
4320
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4321
+ process.exit(1);
4322
+ }
4323
+ });
4324
+ return command;
4325
+ }
4326
+
4327
+ // src/cli/commands/lists.ts
4328
+ function createListsCommand() {
4329
+ const command = new Command("lists");
4330
+ command.description("Manage recipient lists");
4331
+ command.command("list").description("List all recipient lists").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").option("-p, --page <number>", "Page number", parseInt, 1).option("-l, --limit <number>", "Items per page", parseInt, 20).action(async (options) => {
4332
+ try {
4333
+ const sdk = new Multisender({
4334
+ apiKey: options.apiKey,
4335
+ baseUrl: options.baseUrl
4336
+ });
4337
+ const response = await sdk.lists.list({
4338
+ page: options.page,
4339
+ limit: options.limit
4340
+ });
4341
+ console.log(`\uD83D\uDCCB Recipient Lists (Page ${response.meta.page} of ${response.meta.totalPages}):
4342
+ `);
4343
+ for (const list of response.data) {
4344
+ console.log(` • ${list.name} (ID: ${list.id})`);
4345
+ console.log(` Recipients: ${list.totalItems}`);
4346
+ console.log(` Created: ${new Date(list.createdAt).toLocaleDateString()}`);
4347
+ if (list.notes) {
4348
+ console.log(` Notes: ${list.notes}`);
4349
+ }
4350
+ console.log();
4351
+ }
4352
+ console.log(`Total: ${response.meta.total} lists`);
4353
+ } catch (error) {
4354
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4355
+ process.exit(1);
4356
+ }
4357
+ });
4358
+ command.command("create").description("Create a new recipient list").requiredOption("-k, --api-key <key>", "API key for authentication").requiredOption("-n, --name <name>", "List name").option("--notes <notes>", "Optional notes about the list").option("--base-url <url>", "Custom API base URL").action(async (options) => {
4359
+ try {
4360
+ const sdk = new Multisender({
4361
+ apiKey: options.apiKey,
4362
+ baseUrl: options.baseUrl
4363
+ });
4364
+ const list = await sdk.lists.create({
4365
+ name: options.name,
4366
+ notes: options.notes
4367
+ });
4368
+ console.log("✅ List created successfully!");
4369
+ console.log(` ID: ${list.id}`);
4370
+ console.log(` Name: ${list.name}`);
4371
+ } catch (error) {
4372
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4373
+ process.exit(1);
4374
+ }
4375
+ });
4376
+ command.command("get <id>").description("Get details of a specific list").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").action(async (id, options) => {
4377
+ try {
4378
+ const sdk = new Multisender({
4379
+ apiKey: options.apiKey,
4380
+ baseUrl: options.baseUrl
4381
+ });
4382
+ const list = await sdk.lists.get(id);
4383
+ console.log(`\uD83D\uDCCB List Details:
4384
+ `);
4385
+ console.log(` ID: ${list.id}`);
4386
+ console.log(` Name: ${list.name}`);
4387
+ console.log(` Recipients: ${list.totalItems}`);
4388
+ console.log(` Created: ${new Date(list.createdAt).toLocaleDateString()}`);
4389
+ if (list.notes) {
4390
+ console.log(` Notes: ${list.notes}`);
4391
+ }
4392
+ } catch (error) {
4393
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4394
+ process.exit(1);
4395
+ }
4396
+ });
4397
+ command.command("delete <id>").description("Delete a recipient list").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").action(async (id, options) => {
4398
+ try {
4399
+ const sdk = new Multisender({
4400
+ apiKey: options.apiKey,
4401
+ baseUrl: options.baseUrl
4402
+ });
4403
+ await sdk.lists.delete(id);
4404
+ console.log("✅ List deleted successfully!");
4405
+ } catch (error) {
4406
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4407
+ process.exit(1);
4408
+ }
4409
+ });
4410
+ return command;
4411
+ }
4412
+
4413
+ // src/cli/commands/distributions.ts
4414
+ function createDistributionsCommand() {
4415
+ const command = new Command("distributions");
4416
+ command.description("Manage token distributions");
4417
+ command.command("list").description("List all distributions").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").option("-p, --page <number>", "Page number", parseInt, 1).option("-l, --limit <number>", "Items per page", parseInt, 20).action(async (options) => {
4418
+ try {
4419
+ const sdk = new Multisender({
4420
+ apiKey: options.apiKey,
4421
+ baseUrl: options.baseUrl
4422
+ });
4423
+ const response = await sdk.distributions.list({
4424
+ page: options.page,
4425
+ limit: options.limit
4426
+ });
4427
+ console.log(`\uD83D\uDE80 Distributions (Page ${response.meta.page} of ${response.meta.totalPages}):
4428
+ `);
4429
+ for (const dist of response.data) {
4430
+ console.log(` • ${dist.name} (ID: ${dist.id})`);
4431
+ console.log(` Status: ${dist.status}`);
4432
+ console.log(` Chain: ${dist.chainId} | Token: ${dist.tokenSymbol}`);
4433
+ console.log(` Recipients: ${dist.totalRecipients} | Amount: ${dist.totalAmount}`);
4434
+ console.log(` Created: ${new Date(dist.createdAt).toLocaleDateString()}`);
4435
+ console.log();
4436
+ }
4437
+ console.log(`Total: ${response.meta.total} distributions`);
4438
+ } catch (error) {
4439
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4440
+ process.exit(1);
4441
+ }
4442
+ });
4443
+ command.command("get <id>").description("Get details of a specific distribution").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").action(async (id, options) => {
4444
+ try {
4445
+ const sdk = new Multisender({
4446
+ apiKey: options.apiKey,
4447
+ baseUrl: options.baseUrl
4448
+ });
4449
+ const dist = await sdk.distributions.get(id);
4450
+ console.log(`\uD83D\uDE80 Distribution Details:
4451
+ `);
4452
+ console.log(` ID: ${dist.id}`);
4453
+ console.log(` Name: ${dist.name}`);
4454
+ console.log(` Status: ${dist.status}`);
4455
+ console.log(` Chain ID: ${dist.chainId}`);
4456
+ console.log(` Token: ${dist.tokenSymbol} (${dist.tokenAddress})`);
4457
+ console.log(` Recipients: ${dist.totalRecipients}`);
4458
+ console.log(` Total Amount: ${dist.totalAmount}`);
4459
+ console.log(` Created: ${new Date(dist.createdAt).toLocaleDateString()}`);
4460
+ if (dist.notes) {
4461
+ console.log(` Notes: ${dist.notes}`);
4462
+ }
4463
+ } catch (error) {
4464
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4465
+ process.exit(1);
4466
+ }
4467
+ });
4468
+ command.command("stats <id>").description("Get statistics for a distribution").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").action(async (id, options) => {
4469
+ try {
4470
+ const sdk = new Multisender({
4471
+ apiKey: options.apiKey,
4472
+ baseUrl: options.baseUrl
4473
+ });
4474
+ const stats = await sdk.distributions.getStats(id);
4475
+ console.log(`\uD83D\uDCCA Distribution Statistics:
4476
+ `);
4477
+ console.log(` Total: ${stats.total}`);
4478
+ console.log(` Pending: ${stats.pending}`);
4479
+ console.log(` Submitted: ${stats.submitted}`);
4480
+ console.log(` Confirmed: ${stats.confirmed}`);
4481
+ console.log(` Failed: ${stats.failed}`);
4482
+ } catch (error) {
4483
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4484
+ process.exit(1);
4485
+ }
4486
+ });
4487
+ command.command("cancel <id>").description("Cancel a distribution").requiredOption("-k, --api-key <key>", "API key for authentication").option("--base-url <url>", "Custom API base URL").action(async (id, options) => {
4488
+ try {
4489
+ const sdk = new Multisender({
4490
+ apiKey: options.apiKey,
4491
+ baseUrl: options.baseUrl
4492
+ });
4493
+ await sdk.distributions.cancel(id);
4494
+ console.log("✅ Distribution cancelled successfully!");
4495
+ } catch (error) {
4496
+ console.error("❌ Error:", error instanceof Error ? error.message : String(error));
4497
+ process.exit(1);
4498
+ }
4499
+ });
4500
+ return command;
4501
+ }
4502
+
4503
+ // src/cli/index.ts
4504
+ function main() {
4505
+ const program2 = new Command;
4506
+ program2.name("multisender").description("Multisender SDK CLI - Manage token distributions across EVM chains").version("1.0.0");
4507
+ program2.addCommand(createDistributeCommand());
4508
+ program2.addCommand(createListsCommand());
4509
+ program2.addCommand(createDistributionsCommand());
4510
+ program2.parse(process.argv);
4511
+ }
4512
+ main();
4513
+
4514
+ //# debugId=DAB00AC65560094464756E2164756E21