@chilfish/gallery-dl-instagram 0.1.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +340 -0
- package/README.md +134 -0
- package/dist/dl-ins.mjs +5014 -0
- package/dist/index.cjs +192 -0
- package/dist/{sdk-B9fRyc1e.d.mts → index.d.cts} +189 -309
- package/dist/index.d.mts +502 -72
- package/dist/index.mjs +153 -39
- package/dist/node.cjs +41 -0
- package/dist/node.d.cts +47 -0
- package/dist/node.d.mts +47 -0
- package/dist/node.mjs +40 -0
- package/dist/sdk-BClg0Kv2.cjs +2268 -0
- package/dist/{extractors-Byw-2lPL.mjs → sdk-CovBsEps.mjs} +720 -670
- package/dist/sdk-DyZz22bT.d.cts +262 -0
- package/dist/sdk-DyZz22bT.d.mts +262 -0
- package/dist/storage-77hqz5Fi.mjs +24 -0
- package/dist/storage-BwGaT6XO.cjs +24 -0
- package/package.json +26 -26
- package/cli/adapter.ts +0 -284
- package/cli/cookies.ts +0 -59
- package/cli/index.ts +0 -337
- package/config.ts +0 -80
- package/core/extractor.ts +0 -217
- package/core/job.ts +0 -581
- package/dist/adapter-Bt86eL1R.mjs +0 -189
- package/dist/cli/index.d.mts +0 -1
- package/dist/cli/index.mjs +0 -3160
- package/dist/sdk.d.mts +0 -2
- package/dist/sdk.mjs +0 -93
- package/index.ts +0 -159
- package/instagram/api.ts +0 -531
- package/instagram/base.ts +0 -275
- package/instagram/extractors.ts +0 -521
- package/instagram/index.ts +0 -43
- package/instagram/parsers.ts +0 -583
- package/instagram/types.ts +0 -244
- package/message.ts +0 -31
- package/types.ts +0 -115
- package/utils/id-codec.ts +0 -39
- package/utils/text.ts +0 -178
package/dist/dl-ins.mjs
ADDED
|
@@ -0,0 +1,5014 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import childProcess from "node:child_process";
|
|
4
|
+
import path, { dirname } from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import process$1 from "node:process";
|
|
7
|
+
import { stripVTControlCharacters } from "node:util";
|
|
8
|
+
import { access, mkdir, writeFile } from "node:fs/promises";
|
|
9
|
+
//#region \0rolldown/runtime.js
|
|
10
|
+
var __defProp = Object.defineProperty;
|
|
11
|
+
var __exportAll = (all, no_symbols) => {
|
|
12
|
+
let target = {};
|
|
13
|
+
for (var name in all) __defProp(target, name, {
|
|
14
|
+
get: all[name],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
18
|
+
return target;
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region node_modules/commander/lib/error.js
|
|
22
|
+
/**
|
|
23
|
+
* CommanderError class
|
|
24
|
+
*/
|
|
25
|
+
var CommanderError = class extends Error {
|
|
26
|
+
/**
|
|
27
|
+
* Constructs the CommanderError class
|
|
28
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
29
|
+
* @param {string} code an id string representing the error
|
|
30
|
+
* @param {string} message human-readable description of the error
|
|
31
|
+
*/
|
|
32
|
+
constructor(exitCode, code, message) {
|
|
33
|
+
super(message);
|
|
34
|
+
Error.captureStackTrace(this, this.constructor);
|
|
35
|
+
this.name = this.constructor.name;
|
|
36
|
+
this.code = code;
|
|
37
|
+
this.exitCode = exitCode;
|
|
38
|
+
this.nestedError = void 0;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* InvalidArgumentError class
|
|
43
|
+
*/
|
|
44
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
45
|
+
/**
|
|
46
|
+
* Constructs the InvalidArgumentError class
|
|
47
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
48
|
+
*/
|
|
49
|
+
constructor(message) {
|
|
50
|
+
super(1, "commander.invalidArgument", message);
|
|
51
|
+
Error.captureStackTrace(this, this.constructor);
|
|
52
|
+
this.name = this.constructor.name;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region node_modules/commander/lib/argument.js
|
|
57
|
+
var Argument = class {
|
|
58
|
+
/**
|
|
59
|
+
* Initialize a new command argument with the given name and description.
|
|
60
|
+
* The default is that the argument is required, and you can explicitly
|
|
61
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} name
|
|
64
|
+
* @param {string} [description]
|
|
65
|
+
*/
|
|
66
|
+
constructor(name, description) {
|
|
67
|
+
this.description = description || "";
|
|
68
|
+
this.variadic = false;
|
|
69
|
+
this.parseArg = void 0;
|
|
70
|
+
this.defaultValue = void 0;
|
|
71
|
+
this.defaultValueDescription = void 0;
|
|
72
|
+
this.argChoices = void 0;
|
|
73
|
+
switch (name[0]) {
|
|
74
|
+
case "<":
|
|
75
|
+
this.required = true;
|
|
76
|
+
this._name = name.slice(1, -1);
|
|
77
|
+
break;
|
|
78
|
+
case "[":
|
|
79
|
+
this.required = false;
|
|
80
|
+
this._name = name.slice(1, -1);
|
|
81
|
+
break;
|
|
82
|
+
default:
|
|
83
|
+
this.required = true;
|
|
84
|
+
this._name = name;
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
if (this._name.endsWith("...")) {
|
|
88
|
+
this.variadic = true;
|
|
89
|
+
this._name = this._name.slice(0, -3);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Return argument name.
|
|
94
|
+
*
|
|
95
|
+
* @return {string}
|
|
96
|
+
*/
|
|
97
|
+
name() {
|
|
98
|
+
return this._name;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* @package
|
|
102
|
+
*/
|
|
103
|
+
_collectValue(value, previous) {
|
|
104
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
105
|
+
previous.push(value);
|
|
106
|
+
return previous;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
110
|
+
*
|
|
111
|
+
* @param {*} value
|
|
112
|
+
* @param {string} [description]
|
|
113
|
+
* @return {Argument}
|
|
114
|
+
*/
|
|
115
|
+
default(value, description) {
|
|
116
|
+
this.defaultValue = value;
|
|
117
|
+
this.defaultValueDescription = description;
|
|
118
|
+
return this;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
122
|
+
*
|
|
123
|
+
* @param {Function} [fn]
|
|
124
|
+
* @return {Argument}
|
|
125
|
+
*/
|
|
126
|
+
argParser(fn) {
|
|
127
|
+
this.parseArg = fn;
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Only allow argument value to be one of choices.
|
|
132
|
+
*
|
|
133
|
+
* @param {string[]} values
|
|
134
|
+
* @return {Argument}
|
|
135
|
+
*/
|
|
136
|
+
choices(values) {
|
|
137
|
+
this.argChoices = values.slice();
|
|
138
|
+
this.parseArg = (arg, previous) => {
|
|
139
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
140
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
141
|
+
return arg;
|
|
142
|
+
};
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Make argument required.
|
|
147
|
+
*
|
|
148
|
+
* @returns {Argument}
|
|
149
|
+
*/
|
|
150
|
+
argRequired() {
|
|
151
|
+
this.required = true;
|
|
152
|
+
return this;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Make argument optional.
|
|
156
|
+
*
|
|
157
|
+
* @returns {Argument}
|
|
158
|
+
*/
|
|
159
|
+
argOptional() {
|
|
160
|
+
this.required = false;
|
|
161
|
+
return this;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Takes an argument and returns its human readable equivalent for help usage.
|
|
166
|
+
*
|
|
167
|
+
* @param {Argument} arg
|
|
168
|
+
* @return {string}
|
|
169
|
+
* @private
|
|
170
|
+
*/
|
|
171
|
+
function humanReadableArgName(arg) {
|
|
172
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
173
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
174
|
+
}
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region node_modules/commander/lib/help.js
|
|
177
|
+
/**
|
|
178
|
+
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
|
|
179
|
+
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
|
|
180
|
+
* @typedef { import("./argument.js").Argument } Argument
|
|
181
|
+
* @typedef { import("./command.js").Command } Command
|
|
182
|
+
* @typedef { import("./option.js").Option } Option
|
|
183
|
+
*/
|
|
184
|
+
var Help = class {
|
|
185
|
+
constructor() {
|
|
186
|
+
this.helpWidth = void 0;
|
|
187
|
+
this.minWidthToWrap = 40;
|
|
188
|
+
this.sortSubcommands = false;
|
|
189
|
+
this.sortOptions = false;
|
|
190
|
+
this.showGlobalOptions = false;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
194
|
+
* and just before calling `formatHelp()`.
|
|
195
|
+
*
|
|
196
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
197
|
+
*
|
|
198
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
199
|
+
*/
|
|
200
|
+
prepareContext(contextOptions) {
|
|
201
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
205
|
+
*
|
|
206
|
+
* @param {Command} cmd
|
|
207
|
+
* @returns {Command[]}
|
|
208
|
+
*/
|
|
209
|
+
visibleCommands(cmd) {
|
|
210
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
211
|
+
const helpCommand = cmd._getHelpCommand();
|
|
212
|
+
if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
|
|
213
|
+
if (this.sortSubcommands) visibleCommands.sort((a, b) => {
|
|
214
|
+
return a.name().localeCompare(b.name());
|
|
215
|
+
});
|
|
216
|
+
return visibleCommands;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Compare options for sort.
|
|
220
|
+
*
|
|
221
|
+
* @param {Option} a
|
|
222
|
+
* @param {Option} b
|
|
223
|
+
* @returns {number}
|
|
224
|
+
*/
|
|
225
|
+
compareOptions(a, b) {
|
|
226
|
+
const getSortKey = (option) => {
|
|
227
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
228
|
+
};
|
|
229
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
233
|
+
*
|
|
234
|
+
* @param {Command} cmd
|
|
235
|
+
* @returns {Option[]}
|
|
236
|
+
*/
|
|
237
|
+
visibleOptions(cmd) {
|
|
238
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
239
|
+
const helpOption = cmd._getHelpOption();
|
|
240
|
+
if (helpOption && !helpOption.hidden) {
|
|
241
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
242
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
243
|
+
if (!removeShort && !removeLong) visibleOptions.push(helpOption);
|
|
244
|
+
else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
245
|
+
else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
246
|
+
}
|
|
247
|
+
if (this.sortOptions) visibleOptions.sort(this.compareOptions);
|
|
248
|
+
return visibleOptions;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Get an array of the visible global options. (Not including help.)
|
|
252
|
+
*
|
|
253
|
+
* @param {Command} cmd
|
|
254
|
+
* @returns {Option[]}
|
|
255
|
+
*/
|
|
256
|
+
visibleGlobalOptions(cmd) {
|
|
257
|
+
if (!this.showGlobalOptions) return [];
|
|
258
|
+
const globalOptions = [];
|
|
259
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
260
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
261
|
+
globalOptions.push(...visibleOptions);
|
|
262
|
+
}
|
|
263
|
+
if (this.sortOptions) globalOptions.sort(this.compareOptions);
|
|
264
|
+
return globalOptions;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Get an array of the arguments if any have a description.
|
|
268
|
+
*
|
|
269
|
+
* @param {Command} cmd
|
|
270
|
+
* @returns {Argument[]}
|
|
271
|
+
*/
|
|
272
|
+
visibleArguments(cmd) {
|
|
273
|
+
if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
|
|
274
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
275
|
+
});
|
|
276
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
|
|
277
|
+
return [];
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Get the command term to show in the list of subcommands.
|
|
281
|
+
*
|
|
282
|
+
* @param {Command} cmd
|
|
283
|
+
* @returns {string}
|
|
284
|
+
*/
|
|
285
|
+
subcommandTerm(cmd) {
|
|
286
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
287
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Get the option term to show in the list of options.
|
|
291
|
+
*
|
|
292
|
+
* @param {Option} option
|
|
293
|
+
* @returns {string}
|
|
294
|
+
*/
|
|
295
|
+
optionTerm(option) {
|
|
296
|
+
return option.flags;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Get the argument term to show in the list of arguments.
|
|
300
|
+
*
|
|
301
|
+
* @param {Argument} argument
|
|
302
|
+
* @returns {string}
|
|
303
|
+
*/
|
|
304
|
+
argumentTerm(argument) {
|
|
305
|
+
return argument.name();
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Get the longest command term length.
|
|
309
|
+
*
|
|
310
|
+
* @param {Command} cmd
|
|
311
|
+
* @param {Help} helper
|
|
312
|
+
* @returns {number}
|
|
313
|
+
*/
|
|
314
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
315
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
316
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
317
|
+
}, 0);
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Get the longest option term length.
|
|
321
|
+
*
|
|
322
|
+
* @param {Command} cmd
|
|
323
|
+
* @param {Help} helper
|
|
324
|
+
* @returns {number}
|
|
325
|
+
*/
|
|
326
|
+
longestOptionTermLength(cmd, helper) {
|
|
327
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
328
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
329
|
+
}, 0);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Get the longest global option term length.
|
|
333
|
+
*
|
|
334
|
+
* @param {Command} cmd
|
|
335
|
+
* @param {Help} helper
|
|
336
|
+
* @returns {number}
|
|
337
|
+
*/
|
|
338
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
339
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
340
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
341
|
+
}, 0);
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Get the longest argument term length.
|
|
345
|
+
*
|
|
346
|
+
* @param {Command} cmd
|
|
347
|
+
* @param {Help} helper
|
|
348
|
+
* @returns {number}
|
|
349
|
+
*/
|
|
350
|
+
longestArgumentTermLength(cmd, helper) {
|
|
351
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
352
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
353
|
+
}, 0);
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
357
|
+
*
|
|
358
|
+
* @param {Command} cmd
|
|
359
|
+
* @returns {string}
|
|
360
|
+
*/
|
|
361
|
+
commandUsage(cmd) {
|
|
362
|
+
let cmdName = cmd._name;
|
|
363
|
+
if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
|
|
364
|
+
let ancestorCmdNames = "";
|
|
365
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
366
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get the description for the command.
|
|
370
|
+
*
|
|
371
|
+
* @param {Command} cmd
|
|
372
|
+
* @returns {string}
|
|
373
|
+
*/
|
|
374
|
+
commandDescription(cmd) {
|
|
375
|
+
return cmd.description();
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
379
|
+
* (Fallback to description for backwards compatibility.)
|
|
380
|
+
*
|
|
381
|
+
* @param {Command} cmd
|
|
382
|
+
* @returns {string}
|
|
383
|
+
*/
|
|
384
|
+
subcommandDescription(cmd) {
|
|
385
|
+
return cmd.summary() || cmd.description();
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Get the option description to show in the list of options.
|
|
389
|
+
*
|
|
390
|
+
* @param {Option} option
|
|
391
|
+
* @return {string}
|
|
392
|
+
*/
|
|
393
|
+
optionDescription(option) {
|
|
394
|
+
const extraInfo = [];
|
|
395
|
+
if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
396
|
+
if (option.defaultValue !== void 0) {
|
|
397
|
+
if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
398
|
+
}
|
|
399
|
+
if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
400
|
+
if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
|
|
401
|
+
if (extraInfo.length > 0) {
|
|
402
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
403
|
+
if (option.description) return `${option.description} ${extraDescription}`;
|
|
404
|
+
return extraDescription;
|
|
405
|
+
}
|
|
406
|
+
return option.description;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Get the argument description to show in the list of arguments.
|
|
410
|
+
*
|
|
411
|
+
* @param {Argument} argument
|
|
412
|
+
* @return {string}
|
|
413
|
+
*/
|
|
414
|
+
argumentDescription(argument) {
|
|
415
|
+
const extraInfo = [];
|
|
416
|
+
if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
417
|
+
if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
418
|
+
if (extraInfo.length > 0) {
|
|
419
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
420
|
+
if (argument.description) return `${argument.description} ${extraDescription}`;
|
|
421
|
+
return extraDescription;
|
|
422
|
+
}
|
|
423
|
+
return argument.description;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
427
|
+
*
|
|
428
|
+
* @param {string} heading
|
|
429
|
+
* @param {string[]} items
|
|
430
|
+
* @param {Help} helper
|
|
431
|
+
* @returns string[]
|
|
432
|
+
*/
|
|
433
|
+
formatItemList(heading, items, helper) {
|
|
434
|
+
if (items.length === 0) return [];
|
|
435
|
+
return [
|
|
436
|
+
helper.styleTitle(heading),
|
|
437
|
+
...items,
|
|
438
|
+
""
|
|
439
|
+
];
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Group items by their help group heading.
|
|
443
|
+
*
|
|
444
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
445
|
+
* @param {Command[] | Option[]} visibleItems
|
|
446
|
+
* @param {Function} getGroup
|
|
447
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
448
|
+
*/
|
|
449
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
450
|
+
const result = /* @__PURE__ */ new Map();
|
|
451
|
+
unsortedItems.forEach((item) => {
|
|
452
|
+
const group = getGroup(item);
|
|
453
|
+
if (!result.has(group)) result.set(group, []);
|
|
454
|
+
});
|
|
455
|
+
visibleItems.forEach((item) => {
|
|
456
|
+
const group = getGroup(item);
|
|
457
|
+
if (!result.has(group)) result.set(group, []);
|
|
458
|
+
result.get(group).push(item);
|
|
459
|
+
});
|
|
460
|
+
return result;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Generate the built-in help text.
|
|
464
|
+
*
|
|
465
|
+
* @param {Command} cmd
|
|
466
|
+
* @param {Help} helper
|
|
467
|
+
* @returns {string}
|
|
468
|
+
*/
|
|
469
|
+
formatHelp(cmd, helper) {
|
|
470
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
471
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
472
|
+
function callFormatItem(term, description) {
|
|
473
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
474
|
+
}
|
|
475
|
+
let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
|
|
476
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
477
|
+
if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
|
|
478
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
479
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
480
|
+
});
|
|
481
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
482
|
+
this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
|
|
483
|
+
const optionList = options.map((option) => {
|
|
484
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
485
|
+
});
|
|
486
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
487
|
+
});
|
|
488
|
+
if (helper.showGlobalOptions) {
|
|
489
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
490
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
491
|
+
});
|
|
492
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
493
|
+
}
|
|
494
|
+
this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
|
|
495
|
+
const commandList = commands.map((sub) => {
|
|
496
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
497
|
+
});
|
|
498
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
499
|
+
});
|
|
500
|
+
return output.join("\n");
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
504
|
+
*
|
|
505
|
+
* @param {string} str
|
|
506
|
+
* @returns {number}
|
|
507
|
+
*/
|
|
508
|
+
displayWidth(str) {
|
|
509
|
+
return stripVTControlCharacters(str).length;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
513
|
+
*
|
|
514
|
+
* @param {string} str
|
|
515
|
+
* @returns {string}
|
|
516
|
+
*/
|
|
517
|
+
styleTitle(str) {
|
|
518
|
+
return str;
|
|
519
|
+
}
|
|
520
|
+
styleUsage(str) {
|
|
521
|
+
return str.split(" ").map((word) => {
|
|
522
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
523
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
524
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
525
|
+
return this.styleCommandText(word);
|
|
526
|
+
}).join(" ");
|
|
527
|
+
}
|
|
528
|
+
styleCommandDescription(str) {
|
|
529
|
+
return this.styleDescriptionText(str);
|
|
530
|
+
}
|
|
531
|
+
styleOptionDescription(str) {
|
|
532
|
+
return this.styleDescriptionText(str);
|
|
533
|
+
}
|
|
534
|
+
styleSubcommandDescription(str) {
|
|
535
|
+
return this.styleDescriptionText(str);
|
|
536
|
+
}
|
|
537
|
+
styleArgumentDescription(str) {
|
|
538
|
+
return this.styleDescriptionText(str);
|
|
539
|
+
}
|
|
540
|
+
styleDescriptionText(str) {
|
|
541
|
+
return str;
|
|
542
|
+
}
|
|
543
|
+
styleOptionTerm(str) {
|
|
544
|
+
return this.styleOptionText(str);
|
|
545
|
+
}
|
|
546
|
+
styleSubcommandTerm(str) {
|
|
547
|
+
return str.split(" ").map((word) => {
|
|
548
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
549
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
550
|
+
return this.styleSubcommandText(word);
|
|
551
|
+
}).join(" ");
|
|
552
|
+
}
|
|
553
|
+
styleArgumentTerm(str) {
|
|
554
|
+
return this.styleArgumentText(str);
|
|
555
|
+
}
|
|
556
|
+
styleOptionText(str) {
|
|
557
|
+
return str;
|
|
558
|
+
}
|
|
559
|
+
styleArgumentText(str) {
|
|
560
|
+
return str;
|
|
561
|
+
}
|
|
562
|
+
styleSubcommandText(str) {
|
|
563
|
+
return str;
|
|
564
|
+
}
|
|
565
|
+
styleCommandText(str) {
|
|
566
|
+
return str;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Calculate the pad width from the maximum term length.
|
|
570
|
+
*
|
|
571
|
+
* @param {Command} cmd
|
|
572
|
+
* @param {Help} helper
|
|
573
|
+
* @returns {number}
|
|
574
|
+
*/
|
|
575
|
+
padWidth(cmd, helper) {
|
|
576
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
580
|
+
*
|
|
581
|
+
* @param {string} str
|
|
582
|
+
* @returns {boolean}
|
|
583
|
+
*/
|
|
584
|
+
preformatted(str) {
|
|
585
|
+
return /\n[^\S\r\n]/.test(str);
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
589
|
+
*
|
|
590
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
591
|
+
* TTT DDD DDDD
|
|
592
|
+
* DD DDD
|
|
593
|
+
*
|
|
594
|
+
* @param {string} term
|
|
595
|
+
* @param {number} termWidth
|
|
596
|
+
* @param {string} description
|
|
597
|
+
* @param {Help} helper
|
|
598
|
+
* @returns {string}
|
|
599
|
+
*/
|
|
600
|
+
formatItem(term, termWidth, description, helper) {
|
|
601
|
+
const itemIndent = 2;
|
|
602
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
603
|
+
if (!description) return itemIndentStr + term;
|
|
604
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
605
|
+
const spacerWidth = 2;
|
|
606
|
+
const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
|
|
607
|
+
let formattedDescription;
|
|
608
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
|
|
609
|
+
else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
|
|
610
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
614
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
615
|
+
*
|
|
616
|
+
* @param {string} str
|
|
617
|
+
* @param {number} width
|
|
618
|
+
* @returns {string}
|
|
619
|
+
*/
|
|
620
|
+
boxWrap(str, width) {
|
|
621
|
+
if (width < this.minWidthToWrap) return str;
|
|
622
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
623
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
624
|
+
const wrappedLines = [];
|
|
625
|
+
rawLines.forEach((line) => {
|
|
626
|
+
const chunks = line.match(chunkPattern);
|
|
627
|
+
if (chunks === null) {
|
|
628
|
+
wrappedLines.push("");
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
let sumChunks = [chunks.shift()];
|
|
632
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
633
|
+
chunks.forEach((chunk) => {
|
|
634
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
635
|
+
if (sumWidth + visibleWidth <= width) {
|
|
636
|
+
sumChunks.push(chunk);
|
|
637
|
+
sumWidth += visibleWidth;
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
wrappedLines.push(sumChunks.join(""));
|
|
641
|
+
const nextChunk = chunk.trimStart();
|
|
642
|
+
sumChunks = [nextChunk];
|
|
643
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
644
|
+
});
|
|
645
|
+
wrappedLines.push(sumChunks.join(""));
|
|
646
|
+
});
|
|
647
|
+
return wrappedLines.join("\n");
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
//#endregion
|
|
651
|
+
//#region node_modules/commander/lib/option.js
|
|
652
|
+
var Option = class {
|
|
653
|
+
/**
|
|
654
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
655
|
+
*
|
|
656
|
+
* @param {string} flags
|
|
657
|
+
* @param {string} [description]
|
|
658
|
+
*/
|
|
659
|
+
constructor(flags, description) {
|
|
660
|
+
this.flags = flags;
|
|
661
|
+
this.description = description || "";
|
|
662
|
+
this.required = flags.includes("<");
|
|
663
|
+
this.optional = flags.includes("[");
|
|
664
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
665
|
+
this.mandatory = false;
|
|
666
|
+
const optionFlags = splitOptionFlags(flags);
|
|
667
|
+
this.short = optionFlags.shortFlag;
|
|
668
|
+
this.long = optionFlags.longFlag;
|
|
669
|
+
this.negate = false;
|
|
670
|
+
if (this.long) this.negate = this.long.startsWith("--no-");
|
|
671
|
+
this.defaultValue = void 0;
|
|
672
|
+
this.defaultValueDescription = void 0;
|
|
673
|
+
this.presetArg = void 0;
|
|
674
|
+
this.envVar = void 0;
|
|
675
|
+
this.parseArg = void 0;
|
|
676
|
+
this.hidden = false;
|
|
677
|
+
this.argChoices = void 0;
|
|
678
|
+
this.conflictsWith = [];
|
|
679
|
+
this.implied = void 0;
|
|
680
|
+
this.helpGroupHeading = void 0;
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
684
|
+
*
|
|
685
|
+
* @param {*} value
|
|
686
|
+
* @param {string} [description]
|
|
687
|
+
* @return {Option}
|
|
688
|
+
*/
|
|
689
|
+
default(value, description) {
|
|
690
|
+
this.defaultValue = value;
|
|
691
|
+
this.defaultValueDescription = description;
|
|
692
|
+
return this;
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
696
|
+
* The custom processing (parseArg) is called.
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
700
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
701
|
+
*
|
|
702
|
+
* @param {*} arg
|
|
703
|
+
* @return {Option}
|
|
704
|
+
*/
|
|
705
|
+
preset(arg) {
|
|
706
|
+
this.presetArg = arg;
|
|
707
|
+
return this;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Add option name(s) that conflict with this option.
|
|
711
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
712
|
+
*
|
|
713
|
+
* @example
|
|
714
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
715
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
716
|
+
*
|
|
717
|
+
* @param {(string | string[])} names
|
|
718
|
+
* @return {Option}
|
|
719
|
+
*/
|
|
720
|
+
conflicts(names) {
|
|
721
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
722
|
+
return this;
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
726
|
+
*
|
|
727
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
728
|
+
*
|
|
729
|
+
* @example
|
|
730
|
+
* program
|
|
731
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
732
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
733
|
+
*
|
|
734
|
+
* @param {object} impliedOptionValues
|
|
735
|
+
* @return {Option}
|
|
736
|
+
*/
|
|
737
|
+
implies(impliedOptionValues) {
|
|
738
|
+
let newImplied = impliedOptionValues;
|
|
739
|
+
if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
|
|
740
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
741
|
+
return this;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Set environment variable to check for option value.
|
|
745
|
+
*
|
|
746
|
+
* An environment variable is only used if when processed the current option value is
|
|
747
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
748
|
+
*
|
|
749
|
+
* @param {string} name
|
|
750
|
+
* @return {Option}
|
|
751
|
+
*/
|
|
752
|
+
env(name) {
|
|
753
|
+
this.envVar = name;
|
|
754
|
+
return this;
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
758
|
+
*
|
|
759
|
+
* @param {Function} [fn]
|
|
760
|
+
* @return {Option}
|
|
761
|
+
*/
|
|
762
|
+
argParser(fn) {
|
|
763
|
+
this.parseArg = fn;
|
|
764
|
+
return this;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
768
|
+
*
|
|
769
|
+
* @param {boolean} [mandatory=true]
|
|
770
|
+
* @return {Option}
|
|
771
|
+
*/
|
|
772
|
+
makeOptionMandatory(mandatory = true) {
|
|
773
|
+
this.mandatory = !!mandatory;
|
|
774
|
+
return this;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Hide option in help.
|
|
778
|
+
*
|
|
779
|
+
* @param {boolean} [hide=true]
|
|
780
|
+
* @return {Option}
|
|
781
|
+
*/
|
|
782
|
+
hideHelp(hide = true) {
|
|
783
|
+
this.hidden = !!hide;
|
|
784
|
+
return this;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* @package
|
|
788
|
+
*/
|
|
789
|
+
_collectValue(value, previous) {
|
|
790
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
791
|
+
previous.push(value);
|
|
792
|
+
return previous;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* Only allow option value to be one of choices.
|
|
796
|
+
*
|
|
797
|
+
* @param {string[]} values
|
|
798
|
+
* @return {Option}
|
|
799
|
+
*/
|
|
800
|
+
choices(values) {
|
|
801
|
+
this.argChoices = values.slice();
|
|
802
|
+
this.parseArg = (arg, previous) => {
|
|
803
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
804
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
805
|
+
return arg;
|
|
806
|
+
};
|
|
807
|
+
return this;
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Return option name.
|
|
811
|
+
*
|
|
812
|
+
* @return {string}
|
|
813
|
+
*/
|
|
814
|
+
name() {
|
|
815
|
+
if (this.long) return this.long.replace(/^--/, "");
|
|
816
|
+
return this.short.replace(/^-/, "");
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Return option name, in a camelcase format that can be used
|
|
820
|
+
* as an object attribute key.
|
|
821
|
+
*
|
|
822
|
+
* @return {string}
|
|
823
|
+
*/
|
|
824
|
+
attributeName() {
|
|
825
|
+
if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
|
|
826
|
+
return camelcase(this.name());
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Set the help group heading.
|
|
830
|
+
*
|
|
831
|
+
* @param {string} heading
|
|
832
|
+
* @return {Option}
|
|
833
|
+
*/
|
|
834
|
+
helpGroup(heading) {
|
|
835
|
+
this.helpGroupHeading = heading;
|
|
836
|
+
return this;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Check if `arg` matches the short or long flag.
|
|
840
|
+
*
|
|
841
|
+
* @param {string} arg
|
|
842
|
+
* @return {boolean}
|
|
843
|
+
* @package
|
|
844
|
+
*/
|
|
845
|
+
is(arg) {
|
|
846
|
+
return this.short === arg || this.long === arg;
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Return whether a boolean option.
|
|
850
|
+
*
|
|
851
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
852
|
+
*
|
|
853
|
+
* @return {boolean}
|
|
854
|
+
* @package
|
|
855
|
+
*/
|
|
856
|
+
isBoolean() {
|
|
857
|
+
return !this.required && !this.optional && !this.negate;
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
/**
|
|
861
|
+
* This class is to make it easier to work with dual options, without changing the existing
|
|
862
|
+
* implementation. We support separate dual options for separate positive and negative options,
|
|
863
|
+
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
|
|
864
|
+
* use cases, but is tricky for others where we want separate behaviours despite
|
|
865
|
+
* the single shared option value.
|
|
866
|
+
*/
|
|
867
|
+
var DualOptions = class {
|
|
868
|
+
/**
|
|
869
|
+
* @param {Option[]} options
|
|
870
|
+
*/
|
|
871
|
+
constructor(options) {
|
|
872
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
873
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
874
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
875
|
+
options.forEach((option) => {
|
|
876
|
+
if (option.negate) this.negativeOptions.set(option.attributeName(), option);
|
|
877
|
+
else this.positiveOptions.set(option.attributeName(), option);
|
|
878
|
+
});
|
|
879
|
+
this.negativeOptions.forEach((value, key) => {
|
|
880
|
+
if (this.positiveOptions.has(key)) this.dualOptions.add(key);
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
885
|
+
*
|
|
886
|
+
* @param {*} value
|
|
887
|
+
* @param {Option} option
|
|
888
|
+
* @returns {boolean}
|
|
889
|
+
*/
|
|
890
|
+
valueFromOption(value, option) {
|
|
891
|
+
const optionKey = option.attributeName();
|
|
892
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
893
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
894
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
895
|
+
return option.negate === (negativeValue === value);
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
/**
|
|
899
|
+
* Convert string from kebab-case to camelCase.
|
|
900
|
+
*
|
|
901
|
+
* @param {string} str
|
|
902
|
+
* @return {string}
|
|
903
|
+
* @private
|
|
904
|
+
*/
|
|
905
|
+
function camelcase(str) {
|
|
906
|
+
return str.split("-").reduce((str, word) => {
|
|
907
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Split the short and long flag out of something like '-m,--mixed <value>'
|
|
912
|
+
*
|
|
913
|
+
* @private
|
|
914
|
+
*/
|
|
915
|
+
function splitOptionFlags(flags) {
|
|
916
|
+
let shortFlag;
|
|
917
|
+
let longFlag;
|
|
918
|
+
const shortFlagExp = /^-[^-]$/;
|
|
919
|
+
const longFlagExp = /^--[^-]/;
|
|
920
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
921
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
922
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
923
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
924
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
925
|
+
shortFlag = longFlag;
|
|
926
|
+
longFlag = flagParts.shift();
|
|
927
|
+
}
|
|
928
|
+
if (flagParts[0].startsWith("-")) {
|
|
929
|
+
const unsupportedFlag = flagParts[0];
|
|
930
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
931
|
+
if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
932
|
+
- a short flag is a single dash and a single character
|
|
933
|
+
- either use a single dash and a single character (for a short flag)
|
|
934
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
935
|
+
if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
936
|
+
- too many short flags`);
|
|
937
|
+
if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
938
|
+
- too many long flags`);
|
|
939
|
+
throw new Error(`${baseError}
|
|
940
|
+
- unrecognised flag format`);
|
|
941
|
+
}
|
|
942
|
+
if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
943
|
+
return {
|
|
944
|
+
shortFlag,
|
|
945
|
+
longFlag
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
//#endregion
|
|
949
|
+
//#region node_modules/commander/lib/suggestSimilar.js
|
|
950
|
+
const maxDistance = 3;
|
|
951
|
+
function editDistance(a, b) {
|
|
952
|
+
if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
|
|
953
|
+
const d = [];
|
|
954
|
+
for (let i = 0; i <= a.length; i++) d[i] = [i];
|
|
955
|
+
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
|
956
|
+
for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
|
|
957
|
+
let cost;
|
|
958
|
+
if (a[i - 1] === b[j - 1]) cost = 0;
|
|
959
|
+
else cost = 1;
|
|
960
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
961
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
962
|
+
}
|
|
963
|
+
return d[a.length][b.length];
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* Find close matches, restricted to same number of edits.
|
|
967
|
+
*
|
|
968
|
+
* @param {string} word
|
|
969
|
+
* @param {string[]} candidates
|
|
970
|
+
* @returns {string}
|
|
971
|
+
*/
|
|
972
|
+
function suggestSimilar(word, candidates) {
|
|
973
|
+
if (!candidates || candidates.length === 0) return "";
|
|
974
|
+
candidates = Array.from(new Set(candidates));
|
|
975
|
+
const searchingOptions = word.startsWith("--");
|
|
976
|
+
if (searchingOptions) {
|
|
977
|
+
word = word.slice(2);
|
|
978
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
979
|
+
}
|
|
980
|
+
let similar = [];
|
|
981
|
+
let bestDistance = maxDistance;
|
|
982
|
+
const minSimilarity = .4;
|
|
983
|
+
candidates.forEach((candidate) => {
|
|
984
|
+
if (candidate.length <= 1) return;
|
|
985
|
+
const distance = editDistance(word, candidate);
|
|
986
|
+
const length = Math.max(word.length, candidate.length);
|
|
987
|
+
if ((length - distance) / length > minSimilarity) {
|
|
988
|
+
if (distance < bestDistance) {
|
|
989
|
+
bestDistance = distance;
|
|
990
|
+
similar = [candidate];
|
|
991
|
+
} else if (distance === bestDistance) similar.push(candidate);
|
|
992
|
+
}
|
|
993
|
+
});
|
|
994
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
995
|
+
if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
|
|
996
|
+
if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
|
|
997
|
+
if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
|
|
998
|
+
return "";
|
|
999
|
+
}
|
|
1000
|
+
//#endregion
|
|
1001
|
+
//#region node_modules/commander/lib/command.js
|
|
1002
|
+
var Command = class Command extends EventEmitter {
|
|
1003
|
+
/**
|
|
1004
|
+
* Initialize a new `Command`.
|
|
1005
|
+
*
|
|
1006
|
+
* @param {string} [name]
|
|
1007
|
+
*/
|
|
1008
|
+
constructor(name) {
|
|
1009
|
+
super();
|
|
1010
|
+
/** @type {Command[]} */
|
|
1011
|
+
this.commands = [];
|
|
1012
|
+
/** @type {Option[]} */
|
|
1013
|
+
this.options = [];
|
|
1014
|
+
this.parent = null;
|
|
1015
|
+
this._allowUnknownOption = false;
|
|
1016
|
+
this._allowExcessArguments = false;
|
|
1017
|
+
/** @type {Argument[]} */
|
|
1018
|
+
this.registeredArguments = [];
|
|
1019
|
+
this._args = this.registeredArguments;
|
|
1020
|
+
/** @type {string[]} */
|
|
1021
|
+
this.args = [];
|
|
1022
|
+
this.rawArgs = [];
|
|
1023
|
+
this.processedArgs = [];
|
|
1024
|
+
this._scriptPath = null;
|
|
1025
|
+
this._name = name || "";
|
|
1026
|
+
this._optionValues = {};
|
|
1027
|
+
this._optionValueSources = {};
|
|
1028
|
+
this._storeOptionsAsProperties = false;
|
|
1029
|
+
this._actionHandler = null;
|
|
1030
|
+
this._executableHandler = false;
|
|
1031
|
+
this._executableFile = null;
|
|
1032
|
+
this._executableDir = null;
|
|
1033
|
+
this._defaultCommandName = null;
|
|
1034
|
+
this._exitCallback = null;
|
|
1035
|
+
this._aliases = [];
|
|
1036
|
+
this._combineFlagAndOptionalValue = true;
|
|
1037
|
+
this._description = "";
|
|
1038
|
+
this._summary = "";
|
|
1039
|
+
this._argsDescription = void 0;
|
|
1040
|
+
this._enablePositionalOptions = false;
|
|
1041
|
+
this._passThroughOptions = false;
|
|
1042
|
+
this._lifeCycleHooks = {};
|
|
1043
|
+
/** @type {(boolean | string)} */
|
|
1044
|
+
this._showHelpAfterError = false;
|
|
1045
|
+
this._showSuggestionAfterError = true;
|
|
1046
|
+
this._savedState = null;
|
|
1047
|
+
this._outputConfiguration = {
|
|
1048
|
+
writeOut: (str) => process$1.stdout.write(str),
|
|
1049
|
+
writeErr: (str) => process$1.stderr.write(str),
|
|
1050
|
+
outputError: (str, write) => write(str),
|
|
1051
|
+
getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
|
|
1052
|
+
getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
|
|
1053
|
+
getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
|
|
1054
|
+
getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
|
|
1055
|
+
stripColor: (str) => stripVTControlCharacters(str)
|
|
1056
|
+
};
|
|
1057
|
+
this._hidden = false;
|
|
1058
|
+
/** @type {(Option | null | undefined)} */
|
|
1059
|
+
this._helpOption = void 0;
|
|
1060
|
+
this._addImplicitHelpCommand = void 0;
|
|
1061
|
+
/** @type {Command} */
|
|
1062
|
+
this._helpCommand = void 0;
|
|
1063
|
+
this._helpConfiguration = {};
|
|
1064
|
+
/** @type {string | undefined} */
|
|
1065
|
+
this._helpGroupHeading = void 0;
|
|
1066
|
+
/** @type {string | undefined} */
|
|
1067
|
+
this._defaultCommandGroup = void 0;
|
|
1068
|
+
/** @type {string | undefined} */
|
|
1069
|
+
this._defaultOptionGroup = void 0;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1073
|
+
*
|
|
1074
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1075
|
+
*
|
|
1076
|
+
* @param {Command} sourceCommand
|
|
1077
|
+
* @return {Command} `this` command for chaining
|
|
1078
|
+
*/
|
|
1079
|
+
copyInheritedSettings(sourceCommand) {
|
|
1080
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1081
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1082
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1083
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1084
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1085
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1086
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1087
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1088
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1089
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1090
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1091
|
+
return this;
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* @returns {Command[]}
|
|
1095
|
+
* @private
|
|
1096
|
+
*/
|
|
1097
|
+
_getCommandAndAncestors() {
|
|
1098
|
+
const result = [];
|
|
1099
|
+
for (let command = this; command; command = command.parent) result.push(command);
|
|
1100
|
+
return result;
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Define a command.
|
|
1104
|
+
*
|
|
1105
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1106
|
+
*
|
|
1107
|
+
* @example
|
|
1108
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1109
|
+
* program
|
|
1110
|
+
* .command('clone <source> [destination]')
|
|
1111
|
+
* .description('clone a repository into a newly created directory')
|
|
1112
|
+
* .action((source, destination) => {
|
|
1113
|
+
* console.log('clone command called');
|
|
1114
|
+
* });
|
|
1115
|
+
*
|
|
1116
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1117
|
+
* program
|
|
1118
|
+
* .command('start <service>', 'start named service')
|
|
1119
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1120
|
+
*
|
|
1121
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1122
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1123
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1124
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1125
|
+
*/
|
|
1126
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1127
|
+
let desc = actionOptsOrExecDesc;
|
|
1128
|
+
let opts = execOpts;
|
|
1129
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1130
|
+
opts = desc;
|
|
1131
|
+
desc = null;
|
|
1132
|
+
}
|
|
1133
|
+
opts = opts || {};
|
|
1134
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1135
|
+
const cmd = this.createCommand(name);
|
|
1136
|
+
if (desc) {
|
|
1137
|
+
cmd.description(desc);
|
|
1138
|
+
cmd._executableHandler = true;
|
|
1139
|
+
}
|
|
1140
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1141
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1142
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1143
|
+
if (args) cmd.arguments(args);
|
|
1144
|
+
this._registerCommand(cmd);
|
|
1145
|
+
cmd.parent = this;
|
|
1146
|
+
cmd.copyInheritedSettings(this);
|
|
1147
|
+
if (desc) return this;
|
|
1148
|
+
return cmd;
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* Factory routine to create a new unattached command.
|
|
1152
|
+
*
|
|
1153
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1154
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1155
|
+
*
|
|
1156
|
+
* @param {string} [name]
|
|
1157
|
+
* @return {Command} new command
|
|
1158
|
+
*/
|
|
1159
|
+
createCommand(name) {
|
|
1160
|
+
return new Command(name);
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1164
|
+
* or by overriding Help properties using configureHelp().
|
|
1165
|
+
*
|
|
1166
|
+
* @return {Help}
|
|
1167
|
+
*/
|
|
1168
|
+
createHelp() {
|
|
1169
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1173
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1174
|
+
*
|
|
1175
|
+
* @param {object} [configuration] - configuration options
|
|
1176
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1177
|
+
*/
|
|
1178
|
+
configureHelp(configuration) {
|
|
1179
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1180
|
+
this._helpConfiguration = configuration;
|
|
1181
|
+
return this;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1185
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1186
|
+
*
|
|
1187
|
+
* The configuration properties are all functions:
|
|
1188
|
+
*
|
|
1189
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1190
|
+
* writeOut(str)
|
|
1191
|
+
* writeErr(str)
|
|
1192
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1193
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1194
|
+
* // specify width for wrapping help
|
|
1195
|
+
* getOutHelpWidth()
|
|
1196
|
+
* getErrHelpWidth()
|
|
1197
|
+
* // color support, currently only used with Help
|
|
1198
|
+
* getOutHasColors()
|
|
1199
|
+
* getErrHasColors()
|
|
1200
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1201
|
+
*
|
|
1202
|
+
* @param {object} [configuration] - configuration options
|
|
1203
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1204
|
+
*/
|
|
1205
|
+
configureOutput(configuration) {
|
|
1206
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1207
|
+
this._outputConfiguration = {
|
|
1208
|
+
...this._outputConfiguration,
|
|
1209
|
+
...configuration
|
|
1210
|
+
};
|
|
1211
|
+
return this;
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Display the help or a custom message after an error occurs.
|
|
1215
|
+
*
|
|
1216
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1217
|
+
* @return {Command} `this` command for chaining
|
|
1218
|
+
*/
|
|
1219
|
+
showHelpAfterError(displayHelp = true) {
|
|
1220
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1221
|
+
this._showHelpAfterError = displayHelp;
|
|
1222
|
+
return this;
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1226
|
+
*
|
|
1227
|
+
* @param {boolean} [displaySuggestion]
|
|
1228
|
+
* @return {Command} `this` command for chaining
|
|
1229
|
+
*/
|
|
1230
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1231
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1232
|
+
return this;
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Add a prepared subcommand.
|
|
1236
|
+
*
|
|
1237
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1238
|
+
*
|
|
1239
|
+
* @param {Command} cmd - new subcommand
|
|
1240
|
+
* @param {object} [opts] - configuration options
|
|
1241
|
+
* @return {Command} `this` command for chaining
|
|
1242
|
+
*/
|
|
1243
|
+
addCommand(cmd, opts) {
|
|
1244
|
+
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
|
|
1245
|
+
- specify the name in Command constructor or using .name()`);
|
|
1246
|
+
opts = opts || {};
|
|
1247
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1248
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1249
|
+
this._registerCommand(cmd);
|
|
1250
|
+
cmd.parent = this;
|
|
1251
|
+
cmd._checkForBrokenPassThrough();
|
|
1252
|
+
return this;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Factory routine to create a new unattached argument.
|
|
1256
|
+
*
|
|
1257
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1258
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1259
|
+
*
|
|
1260
|
+
* @param {string} name
|
|
1261
|
+
* @param {string} [description]
|
|
1262
|
+
* @return {Argument} new argument
|
|
1263
|
+
*/
|
|
1264
|
+
createArgument(name, description) {
|
|
1265
|
+
return new Argument(name, description);
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Define argument syntax for command.
|
|
1269
|
+
*
|
|
1270
|
+
* The default is that the argument is required, and you can explicitly
|
|
1271
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1272
|
+
*
|
|
1273
|
+
* @example
|
|
1274
|
+
* program.argument('<input-file>');
|
|
1275
|
+
* program.argument('[output-file]');
|
|
1276
|
+
*
|
|
1277
|
+
* @param {string} name
|
|
1278
|
+
* @param {string} [description]
|
|
1279
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1280
|
+
* @param {*} [defaultValue]
|
|
1281
|
+
* @return {Command} `this` command for chaining
|
|
1282
|
+
*/
|
|
1283
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1284
|
+
const argument = this.createArgument(name, description);
|
|
1285
|
+
if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
|
|
1286
|
+
else argument.default(parseArg);
|
|
1287
|
+
this.addArgument(argument);
|
|
1288
|
+
return this;
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1292
|
+
*
|
|
1293
|
+
* See also .argument().
|
|
1294
|
+
*
|
|
1295
|
+
* @example
|
|
1296
|
+
* program.arguments('<cmd> [env]');
|
|
1297
|
+
*
|
|
1298
|
+
* @param {string} names
|
|
1299
|
+
* @return {Command} `this` command for chaining
|
|
1300
|
+
*/
|
|
1301
|
+
arguments(names) {
|
|
1302
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1303
|
+
this.argument(detail);
|
|
1304
|
+
});
|
|
1305
|
+
return this;
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1309
|
+
*
|
|
1310
|
+
* @param {Argument} argument
|
|
1311
|
+
* @return {Command} `this` command for chaining
|
|
1312
|
+
*/
|
|
1313
|
+
addArgument(argument) {
|
|
1314
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1315
|
+
if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
1316
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
1317
|
+
this.registeredArguments.push(argument);
|
|
1318
|
+
return this;
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1322
|
+
*
|
|
1323
|
+
* @example
|
|
1324
|
+
* program.helpCommand('help [cmd]');
|
|
1325
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1326
|
+
* program.helpCommand(false); // suppress default help command
|
|
1327
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1328
|
+
*
|
|
1329
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1330
|
+
* @param {string} [description] - custom description
|
|
1331
|
+
* @return {Command} `this` command for chaining
|
|
1332
|
+
*/
|
|
1333
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1334
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1335
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1336
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
|
|
1337
|
+
return this;
|
|
1338
|
+
}
|
|
1339
|
+
const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
|
|
1340
|
+
const helpDescription = description ?? "display help for command";
|
|
1341
|
+
const helpCommand = this.createCommand(helpName);
|
|
1342
|
+
helpCommand.helpOption(false);
|
|
1343
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1344
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1345
|
+
this._addImplicitHelpCommand = true;
|
|
1346
|
+
this._helpCommand = helpCommand;
|
|
1347
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1348
|
+
return this;
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Add prepared custom help command.
|
|
1352
|
+
*
|
|
1353
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1354
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1355
|
+
* @return {Command} `this` command for chaining
|
|
1356
|
+
*/
|
|
1357
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1358
|
+
if (typeof helpCommand !== "object") {
|
|
1359
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1360
|
+
return this;
|
|
1361
|
+
}
|
|
1362
|
+
this._addImplicitHelpCommand = true;
|
|
1363
|
+
this._helpCommand = helpCommand;
|
|
1364
|
+
this._initCommandGroup(helpCommand);
|
|
1365
|
+
return this;
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Lazy create help command.
|
|
1369
|
+
*
|
|
1370
|
+
* @return {(Command|null)}
|
|
1371
|
+
* @package
|
|
1372
|
+
*/
|
|
1373
|
+
_getHelpCommand() {
|
|
1374
|
+
if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
|
|
1375
|
+
if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
|
|
1376
|
+
return this._helpCommand;
|
|
1377
|
+
}
|
|
1378
|
+
return null;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Add hook for life cycle event.
|
|
1382
|
+
*
|
|
1383
|
+
* @param {string} event
|
|
1384
|
+
* @param {Function} listener
|
|
1385
|
+
* @return {Command} `this` command for chaining
|
|
1386
|
+
*/
|
|
1387
|
+
hook(event, listener) {
|
|
1388
|
+
const allowedValues = [
|
|
1389
|
+
"preSubcommand",
|
|
1390
|
+
"preAction",
|
|
1391
|
+
"postAction"
|
|
1392
|
+
];
|
|
1393
|
+
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1394
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1395
|
+
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
|
|
1396
|
+
else this._lifeCycleHooks[event] = [listener];
|
|
1397
|
+
return this;
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1401
|
+
*
|
|
1402
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1403
|
+
* @return {Command} `this` command for chaining
|
|
1404
|
+
*/
|
|
1405
|
+
exitOverride(fn) {
|
|
1406
|
+
if (fn) this._exitCallback = fn;
|
|
1407
|
+
else this._exitCallback = (err) => {
|
|
1408
|
+
if (err.code !== "commander.executeSubCommandAsync") throw err;
|
|
1409
|
+
};
|
|
1410
|
+
return this;
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1414
|
+
*
|
|
1415
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1416
|
+
* @param {string} code an id string representing the error
|
|
1417
|
+
* @param {string} message human-readable description of the error
|
|
1418
|
+
* @return never
|
|
1419
|
+
* @private
|
|
1420
|
+
*/
|
|
1421
|
+
_exit(exitCode, code, message) {
|
|
1422
|
+
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1423
|
+
process$1.exit(exitCode);
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Register callback `fn` for the command.
|
|
1427
|
+
*
|
|
1428
|
+
* @example
|
|
1429
|
+
* program
|
|
1430
|
+
* .command('serve')
|
|
1431
|
+
* .description('start service')
|
|
1432
|
+
* .action(function() {
|
|
1433
|
+
* // do work here
|
|
1434
|
+
* });
|
|
1435
|
+
*
|
|
1436
|
+
* @param {Function} fn
|
|
1437
|
+
* @return {Command} `this` command for chaining
|
|
1438
|
+
*/
|
|
1439
|
+
action(fn) {
|
|
1440
|
+
const listener = (args) => {
|
|
1441
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1442
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1443
|
+
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
|
|
1444
|
+
else actionArgs[expectedArgsCount] = this.opts();
|
|
1445
|
+
actionArgs.push(this);
|
|
1446
|
+
return fn.apply(this, actionArgs);
|
|
1447
|
+
};
|
|
1448
|
+
this._actionHandler = listener;
|
|
1449
|
+
return this;
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Factory routine to create a new unattached option.
|
|
1453
|
+
*
|
|
1454
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1455
|
+
* create the option. You can override createOption to return a custom option.
|
|
1456
|
+
*
|
|
1457
|
+
* @param {string} flags
|
|
1458
|
+
* @param {string} [description]
|
|
1459
|
+
* @return {Option} new option
|
|
1460
|
+
*/
|
|
1461
|
+
createOption(flags, description) {
|
|
1462
|
+
return new Option(flags, description);
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1466
|
+
*
|
|
1467
|
+
* @param {(Option | Argument)} target
|
|
1468
|
+
* @param {string} value
|
|
1469
|
+
* @param {*} previous
|
|
1470
|
+
* @param {string} invalidArgumentMessage
|
|
1471
|
+
* @private
|
|
1472
|
+
*/
|
|
1473
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1474
|
+
try {
|
|
1475
|
+
return target.parseArg(value, previous);
|
|
1476
|
+
} catch (err) {
|
|
1477
|
+
if (err.code === "commander.invalidArgument") {
|
|
1478
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1479
|
+
this.error(message, {
|
|
1480
|
+
exitCode: err.exitCode,
|
|
1481
|
+
code: err.code
|
|
1482
|
+
});
|
|
1483
|
+
}
|
|
1484
|
+
throw err;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Check for option flag conflicts.
|
|
1489
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1490
|
+
*
|
|
1491
|
+
* @param {Option} option
|
|
1492
|
+
* @private
|
|
1493
|
+
*/
|
|
1494
|
+
_registerOption(option) {
|
|
1495
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1496
|
+
if (matchingOption) {
|
|
1497
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1498
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1499
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1500
|
+
}
|
|
1501
|
+
this._initOptionGroup(option);
|
|
1502
|
+
this.options.push(option);
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1506
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1507
|
+
*
|
|
1508
|
+
* @param {Command} command
|
|
1509
|
+
* @private
|
|
1510
|
+
*/
|
|
1511
|
+
_registerCommand(command) {
|
|
1512
|
+
const knownBy = (cmd) => {
|
|
1513
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1514
|
+
};
|
|
1515
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1516
|
+
if (alreadyUsed) {
|
|
1517
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1518
|
+
const newCmd = knownBy(command).join("|");
|
|
1519
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1520
|
+
}
|
|
1521
|
+
this._initCommandGroup(command);
|
|
1522
|
+
this.commands.push(command);
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Add an option.
|
|
1526
|
+
*
|
|
1527
|
+
* @param {Option} option
|
|
1528
|
+
* @return {Command} `this` command for chaining
|
|
1529
|
+
*/
|
|
1530
|
+
addOption(option) {
|
|
1531
|
+
this._registerOption(option);
|
|
1532
|
+
const oname = option.name();
|
|
1533
|
+
const name = option.attributeName();
|
|
1534
|
+
if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1535
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1536
|
+
if (val == null && option.presetArg !== void 0) val = option.presetArg;
|
|
1537
|
+
const oldValue = this.getOptionValue(name);
|
|
1538
|
+
if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1539
|
+
else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
|
|
1540
|
+
if (val == null) if (option.negate) val = false;
|
|
1541
|
+
else if (option.isBoolean() || option.optional) val = true;
|
|
1542
|
+
else val = "";
|
|
1543
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1544
|
+
};
|
|
1545
|
+
this.on("option:" + oname, (val) => {
|
|
1546
|
+
handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
|
|
1547
|
+
});
|
|
1548
|
+
if (option.envVar) this.on("optionEnv:" + oname, (val) => {
|
|
1549
|
+
handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
|
|
1550
|
+
});
|
|
1551
|
+
return this;
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1555
|
+
*
|
|
1556
|
+
* @return {Command} `this` command for chaining
|
|
1557
|
+
* @private
|
|
1558
|
+
*/
|
|
1559
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1560
|
+
if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1561
|
+
const option = this.createOption(flags, description);
|
|
1562
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1563
|
+
if (typeof fn === "function") option.default(defaultValue).argParser(fn);
|
|
1564
|
+
else if (fn instanceof RegExp) {
|
|
1565
|
+
const regex = fn;
|
|
1566
|
+
fn = (val, def) => {
|
|
1567
|
+
const m = regex.exec(val);
|
|
1568
|
+
return m ? m[0] : def;
|
|
1569
|
+
};
|
|
1570
|
+
option.default(defaultValue).argParser(fn);
|
|
1571
|
+
} else option.default(fn);
|
|
1572
|
+
return this.addOption(option);
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1576
|
+
*
|
|
1577
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1578
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1579
|
+
*
|
|
1580
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1581
|
+
*
|
|
1582
|
+
* @example
|
|
1583
|
+
* program
|
|
1584
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1585
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1586
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1587
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1588
|
+
*
|
|
1589
|
+
* @param {string} flags
|
|
1590
|
+
* @param {string} [description]
|
|
1591
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1592
|
+
* @param {*} [defaultValue]
|
|
1593
|
+
* @return {Command} `this` command for chaining
|
|
1594
|
+
*/
|
|
1595
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1596
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1600
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1601
|
+
*
|
|
1602
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1603
|
+
*
|
|
1604
|
+
* @param {string} flags
|
|
1605
|
+
* @param {string} [description]
|
|
1606
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1607
|
+
* @param {*} [defaultValue]
|
|
1608
|
+
* @return {Command} `this` command for chaining
|
|
1609
|
+
*/
|
|
1610
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1611
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Alter parsing of short flags with optional values.
|
|
1615
|
+
*
|
|
1616
|
+
* @example
|
|
1617
|
+
* // for `.option('-f,--flag [value]'):
|
|
1618
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1619
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1620
|
+
*
|
|
1621
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1622
|
+
* @return {Command} `this` command for chaining
|
|
1623
|
+
*/
|
|
1624
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1625
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1626
|
+
return this;
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Allow unknown options on the command line.
|
|
1630
|
+
*
|
|
1631
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1632
|
+
* @return {Command} `this` command for chaining
|
|
1633
|
+
*/
|
|
1634
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1635
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1636
|
+
return this;
|
|
1637
|
+
}
|
|
1638
|
+
/**
|
|
1639
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1640
|
+
*
|
|
1641
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1642
|
+
* @return {Command} `this` command for chaining
|
|
1643
|
+
*/
|
|
1644
|
+
allowExcessArguments(allowExcess = true) {
|
|
1645
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1646
|
+
return this;
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1650
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1651
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1652
|
+
*
|
|
1653
|
+
* @param {boolean} [positional]
|
|
1654
|
+
* @return {Command} `this` command for chaining
|
|
1655
|
+
*/
|
|
1656
|
+
enablePositionalOptions(positional = true) {
|
|
1657
|
+
this._enablePositionalOptions = !!positional;
|
|
1658
|
+
return this;
|
|
1659
|
+
}
|
|
1660
|
+
/**
|
|
1661
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1662
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1663
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1664
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1665
|
+
*
|
|
1666
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1667
|
+
* @return {Command} `this` command for chaining
|
|
1668
|
+
*/
|
|
1669
|
+
passThroughOptions(passThrough = true) {
|
|
1670
|
+
this._passThroughOptions = !!passThrough;
|
|
1671
|
+
this._checkForBrokenPassThrough();
|
|
1672
|
+
return this;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* @private
|
|
1676
|
+
*/
|
|
1677
|
+
_checkForBrokenPassThrough() {
|
|
1678
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Whether to store option values as properties on command object,
|
|
1682
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1683
|
+
*
|
|
1684
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1685
|
+
* @return {Command} `this` command for chaining
|
|
1686
|
+
*/
|
|
1687
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1688
|
+
if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1689
|
+
if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1690
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1691
|
+
return this;
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Retrieve option value.
|
|
1695
|
+
*
|
|
1696
|
+
* @param {string} key
|
|
1697
|
+
* @return {object} value
|
|
1698
|
+
*/
|
|
1699
|
+
getOptionValue(key) {
|
|
1700
|
+
if (this._storeOptionsAsProperties) return this[key];
|
|
1701
|
+
return this._optionValues[key];
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Store option value.
|
|
1705
|
+
*
|
|
1706
|
+
* @param {string} key
|
|
1707
|
+
* @param {object} value
|
|
1708
|
+
* @return {Command} `this` command for chaining
|
|
1709
|
+
*/
|
|
1710
|
+
setOptionValue(key, value) {
|
|
1711
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Store option value and where the value came from.
|
|
1715
|
+
*
|
|
1716
|
+
* @param {string} key
|
|
1717
|
+
* @param {object} value
|
|
1718
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1719
|
+
* @return {Command} `this` command for chaining
|
|
1720
|
+
*/
|
|
1721
|
+
setOptionValueWithSource(key, value, source) {
|
|
1722
|
+
if (this._storeOptionsAsProperties) this[key] = value;
|
|
1723
|
+
else this._optionValues[key] = value;
|
|
1724
|
+
this._optionValueSources[key] = source;
|
|
1725
|
+
return this;
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Get source of option value.
|
|
1729
|
+
* Expected values are default | config | env | cli | implied
|
|
1730
|
+
*
|
|
1731
|
+
* @param {string} key
|
|
1732
|
+
* @return {string}
|
|
1733
|
+
*/
|
|
1734
|
+
getOptionValueSource(key) {
|
|
1735
|
+
return this._optionValueSources[key];
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1739
|
+
* Expected values are default | config | env | cli | implied
|
|
1740
|
+
*
|
|
1741
|
+
* @param {string} key
|
|
1742
|
+
* @return {string}
|
|
1743
|
+
*/
|
|
1744
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1745
|
+
let source;
|
|
1746
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1747
|
+
if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
|
|
1748
|
+
});
|
|
1749
|
+
return source;
|
|
1750
|
+
}
|
|
1751
|
+
/**
|
|
1752
|
+
* Get user arguments from implied or explicit arguments.
|
|
1753
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1754
|
+
*
|
|
1755
|
+
* @private
|
|
1756
|
+
*/
|
|
1757
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1758
|
+
if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
|
|
1759
|
+
parseOptions = parseOptions || {};
|
|
1760
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1761
|
+
if (process$1.versions?.electron) parseOptions.from = "electron";
|
|
1762
|
+
const execArgv = process$1.execArgv ?? [];
|
|
1763
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
|
|
1764
|
+
}
|
|
1765
|
+
if (argv === void 0) argv = process$1.argv;
|
|
1766
|
+
this.rawArgs = argv.slice();
|
|
1767
|
+
let userArgs;
|
|
1768
|
+
switch (parseOptions.from) {
|
|
1769
|
+
case void 0:
|
|
1770
|
+
case "node":
|
|
1771
|
+
this._scriptPath = argv[1];
|
|
1772
|
+
userArgs = argv.slice(2);
|
|
1773
|
+
break;
|
|
1774
|
+
case "electron":
|
|
1775
|
+
if (process$1.defaultApp) {
|
|
1776
|
+
this._scriptPath = argv[1];
|
|
1777
|
+
userArgs = argv.slice(2);
|
|
1778
|
+
} else userArgs = argv.slice(1);
|
|
1779
|
+
break;
|
|
1780
|
+
case "user":
|
|
1781
|
+
userArgs = argv.slice(0);
|
|
1782
|
+
break;
|
|
1783
|
+
case "eval":
|
|
1784
|
+
userArgs = argv.slice(1);
|
|
1785
|
+
break;
|
|
1786
|
+
default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1787
|
+
}
|
|
1788
|
+
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
|
|
1789
|
+
this._name = this._name || "program";
|
|
1790
|
+
return userArgs;
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1794
|
+
*
|
|
1795
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
1796
|
+
*
|
|
1797
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1798
|
+
*
|
|
1799
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1800
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1801
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1802
|
+
* - `'user'`: just user arguments
|
|
1803
|
+
*
|
|
1804
|
+
* @example
|
|
1805
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
1806
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1807
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1808
|
+
*
|
|
1809
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1810
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1811
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1812
|
+
* @return {Command} `this` command for chaining
|
|
1813
|
+
*/
|
|
1814
|
+
parse(argv, parseOptions) {
|
|
1815
|
+
this._prepareForParse();
|
|
1816
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1817
|
+
this._parseCommand([], userArgs);
|
|
1818
|
+
return this;
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1822
|
+
*
|
|
1823
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1824
|
+
*
|
|
1825
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1826
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1827
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1828
|
+
* - `'user'`: just user arguments
|
|
1829
|
+
*
|
|
1830
|
+
* @example
|
|
1831
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
1832
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1833
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1834
|
+
*
|
|
1835
|
+
* @param {string[]} [argv]
|
|
1836
|
+
* @param {object} [parseOptions]
|
|
1837
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1838
|
+
* @return {Promise}
|
|
1839
|
+
*/
|
|
1840
|
+
async parseAsync(argv, parseOptions) {
|
|
1841
|
+
this._prepareForParse();
|
|
1842
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1843
|
+
await this._parseCommand([], userArgs);
|
|
1844
|
+
return this;
|
|
1845
|
+
}
|
|
1846
|
+
_prepareForParse() {
|
|
1847
|
+
if (this._savedState === null) {
|
|
1848
|
+
this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
|
|
1849
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1850
|
+
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
|
|
1851
|
+
});
|
|
1852
|
+
this.saveStateBeforeParse();
|
|
1853
|
+
} else this.restoreStateBeforeParse();
|
|
1854
|
+
}
|
|
1855
|
+
/**
|
|
1856
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
1857
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1858
|
+
*
|
|
1859
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
1860
|
+
*/
|
|
1861
|
+
saveStateBeforeParse() {
|
|
1862
|
+
this._savedState = {
|
|
1863
|
+
_name: this._name,
|
|
1864
|
+
_optionValues: { ...this._optionValues },
|
|
1865
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Restore state before parse for calls after the first.
|
|
1870
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1871
|
+
*
|
|
1872
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
1873
|
+
*/
|
|
1874
|
+
restoreStateBeforeParse() {
|
|
1875
|
+
if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1876
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1877
|
+
this._name = this._savedState._name;
|
|
1878
|
+
this._scriptPath = null;
|
|
1879
|
+
this.rawArgs = [];
|
|
1880
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1881
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1882
|
+
this.args = [];
|
|
1883
|
+
this.processedArgs = [];
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
1887
|
+
*
|
|
1888
|
+
* @param {string} executableFile
|
|
1889
|
+
* @param {string} executableDir
|
|
1890
|
+
* @param {string} subcommandName
|
|
1891
|
+
*/
|
|
1892
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1893
|
+
if (fs.existsSync(executableFile)) return;
|
|
1894
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1895
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1896
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1897
|
+
- ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
|
|
1898
|
+
throw new Error(executableMissing);
|
|
1899
|
+
}
|
|
1900
|
+
/**
|
|
1901
|
+
* Execute a sub-command executable.
|
|
1902
|
+
*
|
|
1903
|
+
* @private
|
|
1904
|
+
*/
|
|
1905
|
+
_executeSubCommand(subcommand, args) {
|
|
1906
|
+
args = args.slice();
|
|
1907
|
+
const sourceExt = [
|
|
1908
|
+
".js",
|
|
1909
|
+
".ts",
|
|
1910
|
+
".tsx",
|
|
1911
|
+
".mjs",
|
|
1912
|
+
".cjs"
|
|
1913
|
+
];
|
|
1914
|
+
function findFile(baseDir, baseName) {
|
|
1915
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1916
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
1917
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
1918
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1919
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1920
|
+
}
|
|
1921
|
+
this._checkForMissingMandatoryOptions();
|
|
1922
|
+
this._checkForConflictingOptions();
|
|
1923
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1924
|
+
let executableDir = this._executableDir || "";
|
|
1925
|
+
if (this._scriptPath) {
|
|
1926
|
+
let resolvedScriptPath;
|
|
1927
|
+
try {
|
|
1928
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1929
|
+
} catch {
|
|
1930
|
+
resolvedScriptPath = this._scriptPath;
|
|
1931
|
+
}
|
|
1932
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1933
|
+
}
|
|
1934
|
+
if (executableDir) {
|
|
1935
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1936
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1937
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1938
|
+
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1939
|
+
}
|
|
1940
|
+
executableFile = localFile || executableFile;
|
|
1941
|
+
}
|
|
1942
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1943
|
+
let proc;
|
|
1944
|
+
if (process$1.platform !== "win32") if (launchWithNode) {
|
|
1945
|
+
args.unshift(executableFile);
|
|
1946
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1947
|
+
proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
|
|
1948
|
+
} else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1949
|
+
else {
|
|
1950
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1951
|
+
args.unshift(executableFile);
|
|
1952
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1953
|
+
proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
|
|
1954
|
+
}
|
|
1955
|
+
if (!proc.killed) [
|
|
1956
|
+
"SIGUSR1",
|
|
1957
|
+
"SIGUSR2",
|
|
1958
|
+
"SIGTERM",
|
|
1959
|
+
"SIGINT",
|
|
1960
|
+
"SIGHUP"
|
|
1961
|
+
].forEach((signal) => {
|
|
1962
|
+
process$1.on(signal, () => {
|
|
1963
|
+
if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
|
|
1964
|
+
});
|
|
1965
|
+
});
|
|
1966
|
+
const exitCallback = this._exitCallback;
|
|
1967
|
+
proc.on("close", (code) => {
|
|
1968
|
+
code = code ?? 1;
|
|
1969
|
+
if (!exitCallback) process$1.exit(code);
|
|
1970
|
+
else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1971
|
+
});
|
|
1972
|
+
proc.on("error", (err) => {
|
|
1973
|
+
if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1974
|
+
else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
|
|
1975
|
+
if (!exitCallback) process$1.exit(1);
|
|
1976
|
+
else {
|
|
1977
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1978
|
+
wrappedError.nestedError = err;
|
|
1979
|
+
exitCallback(wrappedError);
|
|
1980
|
+
}
|
|
1981
|
+
});
|
|
1982
|
+
this.runningCommand = proc;
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* @private
|
|
1986
|
+
*/
|
|
1987
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1988
|
+
const subCommand = this._findCommand(commandName);
|
|
1989
|
+
if (!subCommand) this.help({ error: true });
|
|
1990
|
+
subCommand._prepareForParse();
|
|
1991
|
+
let promiseChain;
|
|
1992
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1993
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1994
|
+
if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1995
|
+
else return subCommand._parseCommand(operands, unknown);
|
|
1996
|
+
});
|
|
1997
|
+
return promiseChain;
|
|
1998
|
+
}
|
|
1999
|
+
/**
|
|
2000
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2001
|
+
* e.g. help foo
|
|
2002
|
+
*
|
|
2003
|
+
* @private
|
|
2004
|
+
*/
|
|
2005
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2006
|
+
if (!subcommandName) this.help();
|
|
2007
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2008
|
+
if (subCommand && !subCommand._executableHandler) subCommand.help();
|
|
2009
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Check this.args against expected this.registeredArguments.
|
|
2013
|
+
*
|
|
2014
|
+
* @private
|
|
2015
|
+
*/
|
|
2016
|
+
_checkNumberOfArguments() {
|
|
2017
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2018
|
+
if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
|
|
2019
|
+
});
|
|
2020
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
|
|
2021
|
+
if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
|
|
2022
|
+
}
|
|
2023
|
+
/**
|
|
2024
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2025
|
+
*
|
|
2026
|
+
* @private
|
|
2027
|
+
*/
|
|
2028
|
+
_processArguments() {
|
|
2029
|
+
const myParseArg = (argument, value, previous) => {
|
|
2030
|
+
let parsedValue = value;
|
|
2031
|
+
if (value !== null && argument.parseArg) {
|
|
2032
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2033
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
2034
|
+
}
|
|
2035
|
+
return parsedValue;
|
|
2036
|
+
};
|
|
2037
|
+
this._checkNumberOfArguments();
|
|
2038
|
+
const processedArgs = [];
|
|
2039
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2040
|
+
let value = declaredArg.defaultValue;
|
|
2041
|
+
if (declaredArg.variadic) {
|
|
2042
|
+
if (index < this.args.length) {
|
|
2043
|
+
value = this.args.slice(index);
|
|
2044
|
+
if (declaredArg.parseArg) value = value.reduce((processed, v) => {
|
|
2045
|
+
return myParseArg(declaredArg, v, processed);
|
|
2046
|
+
}, declaredArg.defaultValue);
|
|
2047
|
+
} else if (value === void 0) value = [];
|
|
2048
|
+
} else if (index < this.args.length) {
|
|
2049
|
+
value = this.args[index];
|
|
2050
|
+
if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2051
|
+
}
|
|
2052
|
+
processedArgs[index] = value;
|
|
2053
|
+
});
|
|
2054
|
+
this.processedArgs = processedArgs;
|
|
2055
|
+
}
|
|
2056
|
+
/**
|
|
2057
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2058
|
+
*
|
|
2059
|
+
* @param {(Promise|undefined)} promise
|
|
2060
|
+
* @param {Function} fn
|
|
2061
|
+
* @return {(Promise|undefined)}
|
|
2062
|
+
* @private
|
|
2063
|
+
*/
|
|
2064
|
+
_chainOrCall(promise, fn) {
|
|
2065
|
+
if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
|
|
2066
|
+
return fn();
|
|
2067
|
+
}
|
|
2068
|
+
/**
|
|
2069
|
+
*
|
|
2070
|
+
* @param {(Promise|undefined)} promise
|
|
2071
|
+
* @param {string} event
|
|
2072
|
+
* @return {(Promise|undefined)}
|
|
2073
|
+
* @private
|
|
2074
|
+
*/
|
|
2075
|
+
_chainOrCallHooks(promise, event) {
|
|
2076
|
+
let result = promise;
|
|
2077
|
+
const hooks = [];
|
|
2078
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2079
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2080
|
+
hooks.push({
|
|
2081
|
+
hookedCommand,
|
|
2082
|
+
callback
|
|
2083
|
+
});
|
|
2084
|
+
});
|
|
2085
|
+
});
|
|
2086
|
+
if (event === "postAction") hooks.reverse();
|
|
2087
|
+
hooks.forEach((hookDetail) => {
|
|
2088
|
+
result = this._chainOrCall(result, () => {
|
|
2089
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2090
|
+
});
|
|
2091
|
+
});
|
|
2092
|
+
return result;
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
*
|
|
2096
|
+
* @param {(Promise|undefined)} promise
|
|
2097
|
+
* @param {Command} subCommand
|
|
2098
|
+
* @param {string} event
|
|
2099
|
+
* @return {(Promise|undefined)}
|
|
2100
|
+
* @private
|
|
2101
|
+
*/
|
|
2102
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2103
|
+
let result = promise;
|
|
2104
|
+
if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
|
|
2105
|
+
result = this._chainOrCall(result, () => {
|
|
2106
|
+
return hook(this, subCommand);
|
|
2107
|
+
});
|
|
2108
|
+
});
|
|
2109
|
+
return result;
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* Process arguments in context of this command.
|
|
2113
|
+
* Returns action result, in case it is a promise.
|
|
2114
|
+
*
|
|
2115
|
+
* @private
|
|
2116
|
+
*/
|
|
2117
|
+
_parseCommand(operands, unknown) {
|
|
2118
|
+
const parsed = this.parseOptions(unknown);
|
|
2119
|
+
this._parseOptionsEnv();
|
|
2120
|
+
this._parseOptionsImplied();
|
|
2121
|
+
operands = operands.concat(parsed.operands);
|
|
2122
|
+
unknown = parsed.unknown;
|
|
2123
|
+
this.args = operands.concat(unknown);
|
|
2124
|
+
if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2125
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
|
|
2126
|
+
if (this._defaultCommandName) {
|
|
2127
|
+
this._outputHelpIfRequested(unknown);
|
|
2128
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
2129
|
+
}
|
|
2130
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
|
|
2131
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2132
|
+
this._checkForMissingMandatoryOptions();
|
|
2133
|
+
this._checkForConflictingOptions();
|
|
2134
|
+
const checkForUnknownOptions = () => {
|
|
2135
|
+
if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
|
|
2136
|
+
};
|
|
2137
|
+
const commandEvent = `command:${this.name()}`;
|
|
2138
|
+
if (this._actionHandler) {
|
|
2139
|
+
checkForUnknownOptions();
|
|
2140
|
+
this._processArguments();
|
|
2141
|
+
let promiseChain;
|
|
2142
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2143
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
2144
|
+
if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2145
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2146
|
+
});
|
|
2147
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2148
|
+
return promiseChain;
|
|
2149
|
+
}
|
|
2150
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2151
|
+
checkForUnknownOptions();
|
|
2152
|
+
this._processArguments();
|
|
2153
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2154
|
+
} else if (operands.length) {
|
|
2155
|
+
if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
|
|
2156
|
+
if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
|
|
2157
|
+
else if (this.commands.length) this.unknownCommand();
|
|
2158
|
+
else {
|
|
2159
|
+
checkForUnknownOptions();
|
|
2160
|
+
this._processArguments();
|
|
2161
|
+
}
|
|
2162
|
+
} else if (this.commands.length) {
|
|
2163
|
+
checkForUnknownOptions();
|
|
2164
|
+
this.help({ error: true });
|
|
2165
|
+
} else {
|
|
2166
|
+
checkForUnknownOptions();
|
|
2167
|
+
this._processArguments();
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
/**
|
|
2171
|
+
* Find matching command.
|
|
2172
|
+
*
|
|
2173
|
+
* @private
|
|
2174
|
+
* @return {Command | undefined}
|
|
2175
|
+
*/
|
|
2176
|
+
_findCommand(name) {
|
|
2177
|
+
if (!name) return void 0;
|
|
2178
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Return an option matching `arg` if any.
|
|
2182
|
+
*
|
|
2183
|
+
* @param {string} arg
|
|
2184
|
+
* @return {Option}
|
|
2185
|
+
* @package
|
|
2186
|
+
*/
|
|
2187
|
+
_findOption(arg) {
|
|
2188
|
+
return this.options.find((option) => option.is(arg));
|
|
2189
|
+
}
|
|
2190
|
+
/**
|
|
2191
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2192
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2193
|
+
*
|
|
2194
|
+
* @private
|
|
2195
|
+
*/
|
|
2196
|
+
_checkForMissingMandatoryOptions() {
|
|
2197
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2198
|
+
cmd.options.forEach((anOption) => {
|
|
2199
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
|
|
2200
|
+
});
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
/**
|
|
2204
|
+
* Display an error message if conflicting options are used together in this.
|
|
2205
|
+
*
|
|
2206
|
+
* @private
|
|
2207
|
+
*/
|
|
2208
|
+
_checkForConflictingLocalOptions() {
|
|
2209
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2210
|
+
const optionKey = option.attributeName();
|
|
2211
|
+
if (this.getOptionValue(optionKey) === void 0) return false;
|
|
2212
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2213
|
+
});
|
|
2214
|
+
definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
|
|
2215
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
2216
|
+
if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
/**
|
|
2220
|
+
* Display an error message if conflicting options are used together.
|
|
2221
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2222
|
+
*
|
|
2223
|
+
* @private
|
|
2224
|
+
*/
|
|
2225
|
+
_checkForConflictingOptions() {
|
|
2226
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2227
|
+
cmd._checkForConflictingLocalOptions();
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
/**
|
|
2231
|
+
* Parse options from `argv` removing known options,
|
|
2232
|
+
* and return argv split into operands and unknown arguments.
|
|
2233
|
+
*
|
|
2234
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2235
|
+
*
|
|
2236
|
+
* Examples:
|
|
2237
|
+
*
|
|
2238
|
+
* argv => operands, unknown
|
|
2239
|
+
* --known kkk op => [op], []
|
|
2240
|
+
* op --known kkk => [op], []
|
|
2241
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2242
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2243
|
+
*
|
|
2244
|
+
* @param {string[]} args
|
|
2245
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2246
|
+
*/
|
|
2247
|
+
parseOptions(args) {
|
|
2248
|
+
const operands = [];
|
|
2249
|
+
const unknown = [];
|
|
2250
|
+
let dest = operands;
|
|
2251
|
+
function maybeOption(arg) {
|
|
2252
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2253
|
+
}
|
|
2254
|
+
const negativeNumberArg = (arg) => {
|
|
2255
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2256
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
2257
|
+
};
|
|
2258
|
+
let activeVariadicOption = null;
|
|
2259
|
+
let activeGroup = null;
|
|
2260
|
+
let i = 0;
|
|
2261
|
+
while (i < args.length || activeGroup) {
|
|
2262
|
+
const arg = activeGroup ?? args[i++];
|
|
2263
|
+
activeGroup = null;
|
|
2264
|
+
if (arg === "--") {
|
|
2265
|
+
if (dest === unknown) dest.push(arg);
|
|
2266
|
+
dest.push(...args.slice(i));
|
|
2267
|
+
break;
|
|
2268
|
+
}
|
|
2269
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2270
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2271
|
+
continue;
|
|
2272
|
+
}
|
|
2273
|
+
activeVariadicOption = null;
|
|
2274
|
+
if (maybeOption(arg)) {
|
|
2275
|
+
const option = this._findOption(arg);
|
|
2276
|
+
if (option) {
|
|
2277
|
+
if (option.required) {
|
|
2278
|
+
const value = args[i++];
|
|
2279
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2280
|
+
this.emit(`option:${option.name()}`, value);
|
|
2281
|
+
} else if (option.optional) {
|
|
2282
|
+
let value = null;
|
|
2283
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
|
|
2284
|
+
this.emit(`option:${option.name()}`, value);
|
|
2285
|
+
} else this.emit(`option:${option.name()}`);
|
|
2286
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2287
|
+
continue;
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2291
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2292
|
+
if (option) {
|
|
2293
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2294
|
+
else {
|
|
2295
|
+
this.emit(`option:${option.name()}`);
|
|
2296
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2297
|
+
}
|
|
2298
|
+
continue;
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2302
|
+
const index = arg.indexOf("=");
|
|
2303
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2304
|
+
if (option && (option.required || option.optional)) {
|
|
2305
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2306
|
+
continue;
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
|
|
2310
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2311
|
+
if (this._findCommand(arg)) {
|
|
2312
|
+
operands.push(arg);
|
|
2313
|
+
unknown.push(...args.slice(i));
|
|
2314
|
+
break;
|
|
2315
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2316
|
+
operands.push(arg, ...args.slice(i));
|
|
2317
|
+
break;
|
|
2318
|
+
} else if (this._defaultCommandName) {
|
|
2319
|
+
unknown.push(arg, ...args.slice(i));
|
|
2320
|
+
break;
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
if (this._passThroughOptions) {
|
|
2324
|
+
dest.push(arg, ...args.slice(i));
|
|
2325
|
+
break;
|
|
2326
|
+
}
|
|
2327
|
+
dest.push(arg);
|
|
2328
|
+
}
|
|
2329
|
+
return {
|
|
2330
|
+
operands,
|
|
2331
|
+
unknown
|
|
2332
|
+
};
|
|
2333
|
+
}
|
|
2334
|
+
/**
|
|
2335
|
+
* Return an object containing local option values as key-value pairs.
|
|
2336
|
+
*
|
|
2337
|
+
* @return {object}
|
|
2338
|
+
*/
|
|
2339
|
+
opts() {
|
|
2340
|
+
if (this._storeOptionsAsProperties) {
|
|
2341
|
+
const result = {};
|
|
2342
|
+
const len = this.options.length;
|
|
2343
|
+
for (let i = 0; i < len; i++) {
|
|
2344
|
+
const key = this.options[i].attributeName();
|
|
2345
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2346
|
+
}
|
|
2347
|
+
return result;
|
|
2348
|
+
}
|
|
2349
|
+
return this._optionValues;
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2353
|
+
*
|
|
2354
|
+
* @return {object}
|
|
2355
|
+
*/
|
|
2356
|
+
optsWithGlobals() {
|
|
2357
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Display error message and exit (or call exitOverride).
|
|
2361
|
+
*
|
|
2362
|
+
* @param {string} message
|
|
2363
|
+
* @param {object} [errorOptions]
|
|
2364
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2365
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2366
|
+
*/
|
|
2367
|
+
error(message, errorOptions) {
|
|
2368
|
+
this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
|
|
2369
|
+
if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
|
|
2370
|
+
else if (this._showHelpAfterError) {
|
|
2371
|
+
this._outputConfiguration.writeErr("\n");
|
|
2372
|
+
this.outputHelp({ error: true });
|
|
2373
|
+
}
|
|
2374
|
+
const config = errorOptions || {};
|
|
2375
|
+
const exitCode = config.exitCode || 1;
|
|
2376
|
+
const code = config.code || "commander.error";
|
|
2377
|
+
this._exit(exitCode, code, message);
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Apply any option related environment variables, if option does
|
|
2381
|
+
* not have a value from cli or client code.
|
|
2382
|
+
*
|
|
2383
|
+
* @private
|
|
2384
|
+
*/
|
|
2385
|
+
_parseOptionsEnv() {
|
|
2386
|
+
this.options.forEach((option) => {
|
|
2387
|
+
if (option.envVar && option.envVar in process$1.env) {
|
|
2388
|
+
const optionKey = option.attributeName();
|
|
2389
|
+
if (this.getOptionValue(optionKey) === void 0 || [
|
|
2390
|
+
"default",
|
|
2391
|
+
"config",
|
|
2392
|
+
"env"
|
|
2393
|
+
].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
|
|
2394
|
+
else this.emit(`optionEnv:${option.name()}`);
|
|
2395
|
+
}
|
|
2396
|
+
});
|
|
2397
|
+
}
|
|
2398
|
+
/**
|
|
2399
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2400
|
+
*
|
|
2401
|
+
* @private
|
|
2402
|
+
*/
|
|
2403
|
+
_parseOptionsImplied() {
|
|
2404
|
+
const dualHelper = new DualOptions(this.options);
|
|
2405
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2406
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2407
|
+
};
|
|
2408
|
+
this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
2409
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2410
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
2411
|
+
});
|
|
2412
|
+
});
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* Argument `name` is missing.
|
|
2416
|
+
*
|
|
2417
|
+
* @param {string} name
|
|
2418
|
+
* @private
|
|
2419
|
+
*/
|
|
2420
|
+
missingArgument(name) {
|
|
2421
|
+
const message = `error: missing required argument '${name}'`;
|
|
2422
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* `Option` is missing an argument.
|
|
2426
|
+
*
|
|
2427
|
+
* @param {Option} option
|
|
2428
|
+
* @private
|
|
2429
|
+
*/
|
|
2430
|
+
optionMissingArgument(option) {
|
|
2431
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2432
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2436
|
+
*
|
|
2437
|
+
* @param {Option} option
|
|
2438
|
+
* @private
|
|
2439
|
+
*/
|
|
2440
|
+
missingMandatoryOptionValue(option) {
|
|
2441
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2442
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* `Option` conflicts with another option.
|
|
2446
|
+
*
|
|
2447
|
+
* @param {Option} option
|
|
2448
|
+
* @param {Option} conflictingOption
|
|
2449
|
+
* @private
|
|
2450
|
+
*/
|
|
2451
|
+
_conflictingOption(option, conflictingOption) {
|
|
2452
|
+
const findBestOptionFromValue = (option) => {
|
|
2453
|
+
const optionKey = option.attributeName();
|
|
2454
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2455
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
2456
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
2457
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
|
|
2458
|
+
return positiveOption || option;
|
|
2459
|
+
};
|
|
2460
|
+
const getErrorMessage = (option) => {
|
|
2461
|
+
const bestOption = findBestOptionFromValue(option);
|
|
2462
|
+
const optionKey = bestOption.attributeName();
|
|
2463
|
+
if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
|
|
2464
|
+
return `option '${bestOption.flags}'`;
|
|
2465
|
+
};
|
|
2466
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2467
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2468
|
+
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Unknown option `flag`.
|
|
2471
|
+
*
|
|
2472
|
+
* @param {string} flag
|
|
2473
|
+
* @private
|
|
2474
|
+
*/
|
|
2475
|
+
unknownOption(flag) {
|
|
2476
|
+
if (this._allowUnknownOption) return;
|
|
2477
|
+
let suggestion = "";
|
|
2478
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2479
|
+
let candidateFlags = [];
|
|
2480
|
+
let command = this;
|
|
2481
|
+
do {
|
|
2482
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2483
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2484
|
+
command = command.parent;
|
|
2485
|
+
} while (command && !command._enablePositionalOptions);
|
|
2486
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2487
|
+
}
|
|
2488
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2489
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2490
|
+
}
|
|
2491
|
+
/**
|
|
2492
|
+
* Excess arguments, more than expected.
|
|
2493
|
+
*
|
|
2494
|
+
* @param {string[]} receivedArgs
|
|
2495
|
+
* @private
|
|
2496
|
+
*/
|
|
2497
|
+
_excessArguments(receivedArgs) {
|
|
2498
|
+
if (this._allowExcessArguments) return;
|
|
2499
|
+
const expected = this.registeredArguments.length;
|
|
2500
|
+
const s = expected === 1 ? "" : "s";
|
|
2501
|
+
const received = receivedArgs.length;
|
|
2502
|
+
const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
|
|
2503
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2504
|
+
}
|
|
2505
|
+
/**
|
|
2506
|
+
* Unknown command.
|
|
2507
|
+
*
|
|
2508
|
+
* @private
|
|
2509
|
+
*/
|
|
2510
|
+
unknownCommand() {
|
|
2511
|
+
const unknownName = this.args[0];
|
|
2512
|
+
let suggestion = "";
|
|
2513
|
+
if (this._showSuggestionAfterError) {
|
|
2514
|
+
const candidateNames = [];
|
|
2515
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2516
|
+
candidateNames.push(command.name());
|
|
2517
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2518
|
+
});
|
|
2519
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2520
|
+
}
|
|
2521
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2522
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2523
|
+
}
|
|
2524
|
+
/**
|
|
2525
|
+
* Get or set the program version.
|
|
2526
|
+
*
|
|
2527
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2528
|
+
*
|
|
2529
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2530
|
+
*
|
|
2531
|
+
* @param {string} [str]
|
|
2532
|
+
* @param {string} [flags]
|
|
2533
|
+
* @param {string} [description]
|
|
2534
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2535
|
+
*/
|
|
2536
|
+
version(str, flags, description) {
|
|
2537
|
+
if (str === void 0) return this._version;
|
|
2538
|
+
this._version = str;
|
|
2539
|
+
flags = flags || "-V, --version";
|
|
2540
|
+
description = description || "output the version number";
|
|
2541
|
+
const versionOption = this.createOption(flags, description);
|
|
2542
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2543
|
+
this._registerOption(versionOption);
|
|
2544
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2545
|
+
this._outputConfiguration.writeOut(`${str}\n`);
|
|
2546
|
+
this._exit(0, "commander.version", str);
|
|
2547
|
+
});
|
|
2548
|
+
return this;
|
|
2549
|
+
}
|
|
2550
|
+
/**
|
|
2551
|
+
* Set the description.
|
|
2552
|
+
*
|
|
2553
|
+
* @param {string} [str]
|
|
2554
|
+
* @param {object} [argsDescription]
|
|
2555
|
+
* @return {(string|Command)}
|
|
2556
|
+
*/
|
|
2557
|
+
description(str, argsDescription) {
|
|
2558
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
2559
|
+
this._description = str;
|
|
2560
|
+
if (argsDescription) this._argsDescription = argsDescription;
|
|
2561
|
+
return this;
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2565
|
+
*
|
|
2566
|
+
* @param {string} [str]
|
|
2567
|
+
* @return {(string|Command)}
|
|
2568
|
+
*/
|
|
2569
|
+
summary(str) {
|
|
2570
|
+
if (str === void 0) return this._summary;
|
|
2571
|
+
this._summary = str;
|
|
2572
|
+
return this;
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Set an alias for the command.
|
|
2576
|
+
*
|
|
2577
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2578
|
+
*
|
|
2579
|
+
* @param {string} [alias]
|
|
2580
|
+
* @return {(string|Command)}
|
|
2581
|
+
*/
|
|
2582
|
+
alias(alias) {
|
|
2583
|
+
if (alias === void 0) return this._aliases[0];
|
|
2584
|
+
/** @type {Command} */
|
|
2585
|
+
let command = this;
|
|
2586
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
|
|
2587
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
2588
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2589
|
+
if (matchingCommand) {
|
|
2590
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2591
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
2592
|
+
}
|
|
2593
|
+
command._aliases.push(alias);
|
|
2594
|
+
return this;
|
|
2595
|
+
}
|
|
2596
|
+
/**
|
|
2597
|
+
* Set aliases for the command.
|
|
2598
|
+
*
|
|
2599
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2600
|
+
*
|
|
2601
|
+
* @param {string[]} [aliases]
|
|
2602
|
+
* @return {(string[]|Command)}
|
|
2603
|
+
*/
|
|
2604
|
+
aliases(aliases) {
|
|
2605
|
+
if (aliases === void 0) return this._aliases;
|
|
2606
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2607
|
+
return this;
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* Set / get the command usage `str`.
|
|
2611
|
+
*
|
|
2612
|
+
* @param {string} [str]
|
|
2613
|
+
* @return {(string|Command)}
|
|
2614
|
+
*/
|
|
2615
|
+
usage(str) {
|
|
2616
|
+
if (str === void 0) {
|
|
2617
|
+
if (this._usage) return this._usage;
|
|
2618
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2619
|
+
return humanReadableArgName(arg);
|
|
2620
|
+
});
|
|
2621
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
2622
|
+
}
|
|
2623
|
+
this._usage = str;
|
|
2624
|
+
return this;
|
|
2625
|
+
}
|
|
2626
|
+
/**
|
|
2627
|
+
* Get or set the name of the command.
|
|
2628
|
+
*
|
|
2629
|
+
* @param {string} [str]
|
|
2630
|
+
* @return {(string|Command)}
|
|
2631
|
+
*/
|
|
2632
|
+
name(str) {
|
|
2633
|
+
if (str === void 0) return this._name;
|
|
2634
|
+
this._name = str;
|
|
2635
|
+
return this;
|
|
2636
|
+
}
|
|
2637
|
+
/**
|
|
2638
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
2639
|
+
*
|
|
2640
|
+
* @param {string} [heading]
|
|
2641
|
+
* @return {Command | string}
|
|
2642
|
+
*/
|
|
2643
|
+
helpGroup(heading) {
|
|
2644
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
2645
|
+
this._helpGroupHeading = heading;
|
|
2646
|
+
return this;
|
|
2647
|
+
}
|
|
2648
|
+
/**
|
|
2649
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
2650
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
2651
|
+
*
|
|
2652
|
+
* @example
|
|
2653
|
+
* program.commandsGroup('Development Commands:);
|
|
2654
|
+
* program.command('watch')...
|
|
2655
|
+
* program.command('lint')...
|
|
2656
|
+
* ...
|
|
2657
|
+
*
|
|
2658
|
+
* @param {string} [heading]
|
|
2659
|
+
* @returns {Command | string}
|
|
2660
|
+
*/
|
|
2661
|
+
commandsGroup(heading) {
|
|
2662
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
2663
|
+
this._defaultCommandGroup = heading;
|
|
2664
|
+
return this;
|
|
2665
|
+
}
|
|
2666
|
+
/**
|
|
2667
|
+
* Set/get the default help group heading for options added to this command.
|
|
2668
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
2669
|
+
*
|
|
2670
|
+
* @example
|
|
2671
|
+
* program
|
|
2672
|
+
* .optionsGroup('Development Options:')
|
|
2673
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
2674
|
+
* .option('-p, --profile', 'output profiling information')
|
|
2675
|
+
*
|
|
2676
|
+
* @param {string} [heading]
|
|
2677
|
+
* @returns {Command | string}
|
|
2678
|
+
*/
|
|
2679
|
+
optionsGroup(heading) {
|
|
2680
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
2681
|
+
this._defaultOptionGroup = heading;
|
|
2682
|
+
return this;
|
|
2683
|
+
}
|
|
2684
|
+
/**
|
|
2685
|
+
* @param {Option} option
|
|
2686
|
+
* @private
|
|
2687
|
+
*/
|
|
2688
|
+
_initOptionGroup(option) {
|
|
2689
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
|
|
2690
|
+
}
|
|
2691
|
+
/**
|
|
2692
|
+
* @param {Command} cmd
|
|
2693
|
+
* @private
|
|
2694
|
+
*/
|
|
2695
|
+
_initCommandGroup(cmd) {
|
|
2696
|
+
if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2700
|
+
* or import.meta.filename.
|
|
2701
|
+
*
|
|
2702
|
+
* (Used internally and public although not documented in README.)
|
|
2703
|
+
*
|
|
2704
|
+
* @example
|
|
2705
|
+
* program.nameFromFilename(import.meta.filename);
|
|
2706
|
+
*
|
|
2707
|
+
* @param {string} filename
|
|
2708
|
+
* @return {Command}
|
|
2709
|
+
*/
|
|
2710
|
+
nameFromFilename(filename) {
|
|
2711
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
2712
|
+
return this;
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2716
|
+
*
|
|
2717
|
+
* @example
|
|
2718
|
+
* program.executableDir(import.meta.dirname);
|
|
2719
|
+
* // or
|
|
2720
|
+
* program.executableDir('subcommands');
|
|
2721
|
+
*
|
|
2722
|
+
* @param {string} [path]
|
|
2723
|
+
* @return {(string|null|Command)}
|
|
2724
|
+
*/
|
|
2725
|
+
executableDir(path) {
|
|
2726
|
+
if (path === void 0) return this._executableDir;
|
|
2727
|
+
this._executableDir = path;
|
|
2728
|
+
return this;
|
|
2729
|
+
}
|
|
2730
|
+
/**
|
|
2731
|
+
* Return program help documentation.
|
|
2732
|
+
*
|
|
2733
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2734
|
+
* @return {string}
|
|
2735
|
+
*/
|
|
2736
|
+
helpInformation(contextOptions) {
|
|
2737
|
+
const helper = this.createHelp();
|
|
2738
|
+
const context = this._getOutputContext(contextOptions);
|
|
2739
|
+
helper.prepareContext({
|
|
2740
|
+
error: context.error,
|
|
2741
|
+
helpWidth: context.helpWidth,
|
|
2742
|
+
outputHasColors: context.hasColors
|
|
2743
|
+
});
|
|
2744
|
+
const text = helper.formatHelp(this, helper);
|
|
2745
|
+
if (context.hasColors) return text;
|
|
2746
|
+
return this._outputConfiguration.stripColor(text);
|
|
2747
|
+
}
|
|
2748
|
+
/**
|
|
2749
|
+
* @typedef HelpContext
|
|
2750
|
+
* @type {object}
|
|
2751
|
+
* @property {boolean} error
|
|
2752
|
+
* @property {number} helpWidth
|
|
2753
|
+
* @property {boolean} hasColors
|
|
2754
|
+
* @property {function} write - includes stripColor if needed
|
|
2755
|
+
*
|
|
2756
|
+
* @returns {HelpContext}
|
|
2757
|
+
* @private
|
|
2758
|
+
*/
|
|
2759
|
+
_getOutputContext(contextOptions) {
|
|
2760
|
+
contextOptions = contextOptions || {};
|
|
2761
|
+
const error = !!contextOptions.error;
|
|
2762
|
+
let baseWrite;
|
|
2763
|
+
let hasColors;
|
|
2764
|
+
let helpWidth;
|
|
2765
|
+
if (error) {
|
|
2766
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
2767
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
2768
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
2769
|
+
} else {
|
|
2770
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
2771
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
2772
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
2773
|
+
}
|
|
2774
|
+
const write = (str) => {
|
|
2775
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
2776
|
+
return baseWrite(str);
|
|
2777
|
+
};
|
|
2778
|
+
return {
|
|
2779
|
+
error,
|
|
2780
|
+
write,
|
|
2781
|
+
hasColors,
|
|
2782
|
+
helpWidth
|
|
2783
|
+
};
|
|
2784
|
+
}
|
|
2785
|
+
/**
|
|
2786
|
+
* Output help information for this command.
|
|
2787
|
+
*
|
|
2788
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2789
|
+
*
|
|
2790
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2791
|
+
*/
|
|
2792
|
+
outputHelp(contextOptions) {
|
|
2793
|
+
let deprecatedCallback;
|
|
2794
|
+
if (typeof contextOptions === "function") {
|
|
2795
|
+
deprecatedCallback = contextOptions;
|
|
2796
|
+
contextOptions = void 0;
|
|
2797
|
+
}
|
|
2798
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
2799
|
+
/** @type {HelpTextEventContext} */
|
|
2800
|
+
const eventContext = {
|
|
2801
|
+
error: outputContext.error,
|
|
2802
|
+
write: outputContext.write,
|
|
2803
|
+
command: this
|
|
2804
|
+
};
|
|
2805
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
2806
|
+
this.emit("beforeHelp", eventContext);
|
|
2807
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
2808
|
+
if (deprecatedCallback) {
|
|
2809
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2810
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2811
|
+
}
|
|
2812
|
+
outputContext.write(helpInformation);
|
|
2813
|
+
if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
|
|
2814
|
+
this.emit("afterHelp", eventContext);
|
|
2815
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2819
|
+
* Pass in false to disable the built-in help option.
|
|
2820
|
+
*
|
|
2821
|
+
* @example
|
|
2822
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2823
|
+
* program.helpOption(false); // disable
|
|
2824
|
+
*
|
|
2825
|
+
* @param {(string | boolean)} flags
|
|
2826
|
+
* @param {string} [description]
|
|
2827
|
+
* @return {Command} `this` command for chaining
|
|
2828
|
+
*/
|
|
2829
|
+
helpOption(flags, description) {
|
|
2830
|
+
if (typeof flags === "boolean") {
|
|
2831
|
+
if (flags) {
|
|
2832
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
2833
|
+
if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
|
|
2834
|
+
} else this._helpOption = null;
|
|
2835
|
+
return this;
|
|
2836
|
+
}
|
|
2837
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
2838
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
2839
|
+
return this;
|
|
2840
|
+
}
|
|
2841
|
+
/**
|
|
2842
|
+
* Lazy create help option.
|
|
2843
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2844
|
+
*
|
|
2845
|
+
* @returns {(Option | null)} the help option
|
|
2846
|
+
* @package
|
|
2847
|
+
*/
|
|
2848
|
+
_getHelpOption() {
|
|
2849
|
+
if (this._helpOption === void 0) this.helpOption(void 0, void 0);
|
|
2850
|
+
return this._helpOption;
|
|
2851
|
+
}
|
|
2852
|
+
/**
|
|
2853
|
+
* Supply your own option to use for the built-in help option.
|
|
2854
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2855
|
+
*
|
|
2856
|
+
* @param {Option} option
|
|
2857
|
+
* @return {Command} `this` command for chaining
|
|
2858
|
+
*/
|
|
2859
|
+
addHelpOption(option) {
|
|
2860
|
+
this._helpOption = option;
|
|
2861
|
+
this._initOptionGroup(option);
|
|
2862
|
+
return this;
|
|
2863
|
+
}
|
|
2864
|
+
/**
|
|
2865
|
+
* Output help information and exit.
|
|
2866
|
+
*
|
|
2867
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2868
|
+
*
|
|
2869
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2870
|
+
*/
|
|
2871
|
+
help(contextOptions) {
|
|
2872
|
+
this.outputHelp(contextOptions);
|
|
2873
|
+
let exitCode = Number(process$1.exitCode ?? 0);
|
|
2874
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
|
|
2875
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2876
|
+
}
|
|
2877
|
+
/**
|
|
2878
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
2879
|
+
* @typedef HelpTextEventContext
|
|
2880
|
+
* @type {object}
|
|
2881
|
+
* @property {boolean} error
|
|
2882
|
+
* @property {Command} command
|
|
2883
|
+
* @property {function} write
|
|
2884
|
+
*/
|
|
2885
|
+
/**
|
|
2886
|
+
* Add additional text to be displayed with the built-in help.
|
|
2887
|
+
*
|
|
2888
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2889
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2890
|
+
*
|
|
2891
|
+
* @param {string} position - before or after built-in help
|
|
2892
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2893
|
+
* @return {Command} `this` command for chaining
|
|
2894
|
+
*/
|
|
2895
|
+
addHelpText(position, text) {
|
|
2896
|
+
const allowedValues = [
|
|
2897
|
+
"beforeAll",
|
|
2898
|
+
"before",
|
|
2899
|
+
"after",
|
|
2900
|
+
"afterAll"
|
|
2901
|
+
];
|
|
2902
|
+
if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
|
|
2903
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2904
|
+
const helpEvent = `${position}Help`;
|
|
2905
|
+
this.on(helpEvent, (context) => {
|
|
2906
|
+
let helpStr;
|
|
2907
|
+
if (typeof text === "function") helpStr = text({
|
|
2908
|
+
error: context.error,
|
|
2909
|
+
command: context.command
|
|
2910
|
+
});
|
|
2911
|
+
else helpStr = text;
|
|
2912
|
+
if (helpStr) context.write(`${helpStr}\n`);
|
|
2913
|
+
});
|
|
2914
|
+
return this;
|
|
2915
|
+
}
|
|
2916
|
+
/**
|
|
2917
|
+
* Output help information if help flags specified
|
|
2918
|
+
*
|
|
2919
|
+
* @param {Array} args - array of options to search for help flags
|
|
2920
|
+
* @private
|
|
2921
|
+
*/
|
|
2922
|
+
_outputHelpIfRequested(args) {
|
|
2923
|
+
const helpOption = this._getHelpOption();
|
|
2924
|
+
if (helpOption && args.find((arg) => helpOption.is(arg))) {
|
|
2925
|
+
this.outputHelp();
|
|
2926
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
};
|
|
2930
|
+
/**
|
|
2931
|
+
* Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
|
|
2932
|
+
*
|
|
2933
|
+
* @param {string[]} args - array of arguments from node.execArgv
|
|
2934
|
+
* @returns {string[]}
|
|
2935
|
+
* @private
|
|
2936
|
+
*/
|
|
2937
|
+
function incrementNodeInspectorPort(args) {
|
|
2938
|
+
return args.map((arg) => {
|
|
2939
|
+
if (!arg.startsWith("--inspect")) return arg;
|
|
2940
|
+
let debugOption;
|
|
2941
|
+
let debugHost = "127.0.0.1";
|
|
2942
|
+
let debugPort = "9229";
|
|
2943
|
+
let match;
|
|
2944
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
|
|
2945
|
+
else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2946
|
+
debugOption = match[1];
|
|
2947
|
+
if (/^\d+$/.test(match[3])) debugPort = match[3];
|
|
2948
|
+
else debugHost = match[3];
|
|
2949
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2950
|
+
debugOption = match[1];
|
|
2951
|
+
debugHost = match[3];
|
|
2952
|
+
debugPort = match[4];
|
|
2953
|
+
}
|
|
2954
|
+
if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2955
|
+
return arg;
|
|
2956
|
+
});
|
|
2957
|
+
}
|
|
2958
|
+
/**
|
|
2959
|
+
* Exported for using from tests, not otherwise used outside this file.
|
|
2960
|
+
*
|
|
2961
|
+
* @returns {boolean | undefined}
|
|
2962
|
+
* @package
|
|
2963
|
+
*/
|
|
2964
|
+
function useColor() {
|
|
2965
|
+
if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
|
|
2966
|
+
if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
|
|
2967
|
+
}
|
|
2968
|
+
new Command();
|
|
2969
|
+
//#endregion
|
|
2970
|
+
//#region package.json
|
|
2971
|
+
var version = "0.2.1";
|
|
2972
|
+
//#endregion
|
|
2973
|
+
//#region src/utils/id-codec.ts
|
|
2974
|
+
/**
|
|
2975
|
+
* Instagram-style Base64-variant ID ↔ shortcode conversion.
|
|
2976
|
+
*/
|
|
2977
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
2978
|
+
/** Pre-built index for O(1) character lookup during decode. */
|
|
2979
|
+
const CHAR_INDEX = {};
|
|
2980
|
+
for (let i = 0; i < 64; i++) CHAR_INDEX[ALPHABET[i]] = i;
|
|
2981
|
+
const BASE = BigInt(64);
|
|
2982
|
+
/**
|
|
2983
|
+
* Decode an Instagram shortcode into its numeric post ID.
|
|
2984
|
+
*/
|
|
2985
|
+
function idFromShortcode(shortcode) {
|
|
2986
|
+
let num = 0n;
|
|
2987
|
+
for (const ch of shortcode) num = num * BASE + BigInt(CHAR_INDEX[ch] ?? 0);
|
|
2988
|
+
return num.toString();
|
|
2989
|
+
}
|
|
2990
|
+
/**
|
|
2991
|
+
* Encode a numeric post ID into an Instagram shortcode.
|
|
2992
|
+
*/
|
|
2993
|
+
function shortcodeFromId(postId) {
|
|
2994
|
+
let num = BigInt(postId);
|
|
2995
|
+
const chars = [];
|
|
2996
|
+
while (num > 0n) {
|
|
2997
|
+
const remainder = Number(num % BASE);
|
|
2998
|
+
chars.push(ALPHABET[remainder]);
|
|
2999
|
+
num = num / BASE;
|
|
3000
|
+
}
|
|
3001
|
+
return chars.reverse().join("");
|
|
3002
|
+
}
|
|
3003
|
+
//#endregion
|
|
3004
|
+
//#region src/core/extractor.ts
|
|
3005
|
+
var Extractor = class {
|
|
3006
|
+
/** Regex pattern to match against URLs */
|
|
3007
|
+
static pattern = /^$/;
|
|
3008
|
+
/** The input URL */
|
|
3009
|
+
url;
|
|
3010
|
+
/** Regex match groups from ``fromURL`` */
|
|
3011
|
+
groups;
|
|
3012
|
+
config;
|
|
3013
|
+
/** HTTP client — public so Job can access for downloads */
|
|
3014
|
+
http;
|
|
3015
|
+
/** Storage backend — public so Job can access for writes */
|
|
3016
|
+
storage;
|
|
3017
|
+
/** Logger instance — public so Job can access for reporting */
|
|
3018
|
+
log;
|
|
3019
|
+
/** Delay range in seconds — random between [min, max] before each request */
|
|
3020
|
+
requestInterval = [6, 12];
|
|
3021
|
+
_initialized = false;
|
|
3022
|
+
constructor(opts) {
|
|
3023
|
+
this.url = opts.url;
|
|
3024
|
+
this.groups = opts.match ? [...opts.match].slice(1) : [];
|
|
3025
|
+
this.config = opts.config;
|
|
3026
|
+
this.http = opts.http;
|
|
3027
|
+
this.storage = opts.storage;
|
|
3028
|
+
this.log = opts.log;
|
|
3029
|
+
}
|
|
3030
|
+
/** Initialization */
|
|
3031
|
+
/**
|
|
3032
|
+
* One-time async setup (cookies, session, internal state).
|
|
3033
|
+
* Safe to call multiple times — after the first call it becomes a no-op.
|
|
3034
|
+
*/
|
|
3035
|
+
async initialize() {
|
|
3036
|
+
if (this._initialized) return;
|
|
3037
|
+
await this._init();
|
|
3038
|
+
this._initialized = true;
|
|
3039
|
+
this.initialize = async () => {};
|
|
3040
|
+
}
|
|
3041
|
+
/**
|
|
3042
|
+
* Subclass hook for one-time setup.
|
|
3043
|
+
*/
|
|
3044
|
+
async _init() {}
|
|
3045
|
+
/** Async iteration */
|
|
3046
|
+
async *[Symbol.asyncIterator]() {
|
|
3047
|
+
await this.initialize();
|
|
3048
|
+
yield* this.items();
|
|
3049
|
+
}
|
|
3050
|
+
/** Config helpers */
|
|
3051
|
+
/**
|
|
3052
|
+
* Read a config value using the interpolated hierarchy.
|
|
3053
|
+
*/
|
|
3054
|
+
_cfg(key, defaultVal) {
|
|
3055
|
+
const path = [
|
|
3056
|
+
"extractor",
|
|
3057
|
+
this.category,
|
|
3058
|
+
this.subcategory
|
|
3059
|
+
];
|
|
3060
|
+
return this.config.interpolate(path, key, defaultVal);
|
|
3061
|
+
}
|
|
3062
|
+
/** HTTP */
|
|
3063
|
+
_lastRequestTime = 0;
|
|
3064
|
+
/**
|
|
3065
|
+
* Rate-limited HTTP request wrapper.
|
|
3066
|
+
*/
|
|
3067
|
+
async request(url, cfg = {}) {
|
|
3068
|
+
await this._throttle();
|
|
3069
|
+
const response = await this.http.request({
|
|
3070
|
+
url,
|
|
3071
|
+
...cfg
|
|
3072
|
+
});
|
|
3073
|
+
this._lastRequestTime = Date.now();
|
|
3074
|
+
return response;
|
|
3075
|
+
}
|
|
3076
|
+
/**
|
|
3077
|
+
* Convenience: request + parse JSON body.
|
|
3078
|
+
*/
|
|
3079
|
+
async requestJSON(url, cfg = {}) {
|
|
3080
|
+
const resp = await this.request(url, cfg);
|
|
3081
|
+
if (typeof resp.data === "object") return resp.data;
|
|
3082
|
+
try {
|
|
3083
|
+
return JSON.parse(resp.data);
|
|
3084
|
+
} catch {
|
|
3085
|
+
return {};
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
/** Rate limiting */
|
|
3089
|
+
/**
|
|
3090
|
+
* Sleep long enough to keep the minimum interval between requests.
|
|
3091
|
+
*/
|
|
3092
|
+
async _throttle() {
|
|
3093
|
+
const elapsed = Date.now() - this._lastRequestTime;
|
|
3094
|
+
const [min, max] = this.requestInterval;
|
|
3095
|
+
const target = min + Math.random() * (max - min);
|
|
3096
|
+
const waitMs = Math.max(0, target * 1e3 - elapsed);
|
|
3097
|
+
if (waitMs > 0) await new Promise((r) => setTimeout(r, waitMs));
|
|
3098
|
+
}
|
|
3099
|
+
/** Utility */
|
|
3100
|
+
/**
|
|
3101
|
+
* Convert a Unix timestamp (seconds or ms) to an ISO-8601 string.
|
|
3102
|
+
*/
|
|
3103
|
+
parseTimestamp(ts) {
|
|
3104
|
+
if (ts == null) return "";
|
|
3105
|
+
const asMs = ts > 25e8 ? ts : ts * 1e3;
|
|
3106
|
+
return new Date(asMs).toISOString();
|
|
3107
|
+
}
|
|
3108
|
+
/**
|
|
3109
|
+
* Generate a random hex token (used for CSRF).
|
|
3110
|
+
*/
|
|
3111
|
+
static generateToken(size = 16) {
|
|
3112
|
+
const bytes = new Uint8Array(size);
|
|
3113
|
+
if (typeof crypto !== "undefined" && crypto.getRandomValues) crypto.getRandomValues(bytes);
|
|
3114
|
+
else for (let i = 0; i < size; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
3115
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
3116
|
+
}
|
|
3117
|
+
};
|
|
3118
|
+
//#endregion
|
|
3119
|
+
//#region src/message.ts
|
|
3120
|
+
function url(u, metadata = {}) {
|
|
3121
|
+
return {
|
|
3122
|
+
type: "url",
|
|
3123
|
+
url: u,
|
|
3124
|
+
metadata
|
|
3125
|
+
};
|
|
3126
|
+
}
|
|
3127
|
+
function queue(u, metadata = {}) {
|
|
3128
|
+
return {
|
|
3129
|
+
type: "queue",
|
|
3130
|
+
url: u,
|
|
3131
|
+
metadata
|
|
3132
|
+
};
|
|
3133
|
+
}
|
|
3134
|
+
//#endregion
|
|
3135
|
+
//#region src/utils/text.ts
|
|
3136
|
+
/** URL helpers */
|
|
3137
|
+
/**
|
|
3138
|
+
* URL-decode a string.
|
|
3139
|
+
*/
|
|
3140
|
+
function unquote(text) {
|
|
3141
|
+
try {
|
|
3142
|
+
return decodeURIComponent(text);
|
|
3143
|
+
} catch {
|
|
3144
|
+
return text.replace(/%[0-9a-f]{2}/gi, (m) => {
|
|
3145
|
+
try {
|
|
3146
|
+
return decodeURIComponent(m);
|
|
3147
|
+
} catch {
|
|
3148
|
+
return m;
|
|
3149
|
+
}
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* Ensure a URL starts with ``https://`` (or ``http://``).
|
|
3155
|
+
*/
|
|
3156
|
+
function ensureHttpScheme(url, scheme = "https://") {
|
|
3157
|
+
if (!url) return url;
|
|
3158
|
+
if (url.startsWith("https://") || url.startsWith("http://")) return url;
|
|
3159
|
+
return scheme + url.replace(/^[/:]+/, "");
|
|
3160
|
+
}
|
|
3161
|
+
/**
|
|
3162
|
+
* Extract filename + extension from a URL and write into ``meta``.
|
|
3163
|
+
*/
|
|
3164
|
+
function nameExtFromURL(url, meta) {
|
|
3165
|
+
const filename = filenameFromURL(url);
|
|
3166
|
+
const dot = filename.lastIndexOf(".");
|
|
3167
|
+
if (dot > 0 && filename.length - dot - 1 <= 16) {
|
|
3168
|
+
meta.filename = unquote(filename.slice(0, dot));
|
|
3169
|
+
meta.extension = unquote(filename.slice(dot + 1)).toLowerCase();
|
|
3170
|
+
} else {
|
|
3171
|
+
meta.filename = unquote(filename);
|
|
3172
|
+
meta.extension = "";
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
/**
|
|
3176
|
+
* Extract the file-name portion of a URL (before query string).
|
|
3177
|
+
*/
|
|
3178
|
+
function filenameFromURL(url) {
|
|
3179
|
+
try {
|
|
3180
|
+
return url.split("?")[0].split("/").pop() ?? "";
|
|
3181
|
+
} catch {
|
|
3182
|
+
return "";
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
function tagRe(pattern) {
|
|
3186
|
+
const re = new RegExp(pattern, "g");
|
|
3187
|
+
return (text) => {
|
|
3188
|
+
const matches = text.match(re);
|
|
3189
|
+
return matches ? [...new Set(matches)] : [];
|
|
3190
|
+
};
|
|
3191
|
+
}
|
|
3192
|
+
/** Pre-configured hashtag regex. */
|
|
3193
|
+
const findTags = tagRe("#\\w+");
|
|
3194
|
+
//#endregion
|
|
3195
|
+
//#region src/instagram/api.ts
|
|
3196
|
+
const APP_ID = "936619743392459";
|
|
3197
|
+
const ASBD_ID = "129477";
|
|
3198
|
+
var InstagramRestAPI = class {
|
|
3199
|
+
http;
|
|
3200
|
+
root;
|
|
3201
|
+
getCsrf;
|
|
3202
|
+
getWwwClaim;
|
|
3203
|
+
setWwwClaim;
|
|
3204
|
+
setCsrf;
|
|
3205
|
+
/** A ref to the extractor's cursor. */
|
|
3206
|
+
getCursor;
|
|
3207
|
+
setCursor;
|
|
3208
|
+
constructor(opts) {
|
|
3209
|
+
this.http = opts.http;
|
|
3210
|
+
this.root = opts.root;
|
|
3211
|
+
this.getCsrf = () => opts.csrfToken.value;
|
|
3212
|
+
this.setCsrf = (v) => {
|
|
3213
|
+
opts.csrfToken.value = v;
|
|
3214
|
+
};
|
|
3215
|
+
this.getWwwClaim = () => opts.wwwClaim.value;
|
|
3216
|
+
this.setWwwClaim = (v) => {
|
|
3217
|
+
opts.wwwClaim.value = v;
|
|
3218
|
+
};
|
|
3219
|
+
this.getCursor = () => opts.cursor.value;
|
|
3220
|
+
this.setCursor = (v) => {
|
|
3221
|
+
opts.cursor.value = v;
|
|
3222
|
+
return v;
|
|
3223
|
+
};
|
|
3224
|
+
}
|
|
3225
|
+
/** Public endpoint methods */
|
|
3226
|
+
/** Single post by shortcode. */
|
|
3227
|
+
async *media(shortcode) {
|
|
3228
|
+
const endpoint = `/v1/media/${idFromShortcode(shortcode.length > 28 ? shortcode.slice(0, -28) : shortcode)}/info/`;
|
|
3229
|
+
yield* this._pagination(endpoint);
|
|
3230
|
+
}
|
|
3231
|
+
/** Paginated user feed. */
|
|
3232
|
+
userFeed(userId) {
|
|
3233
|
+
return this._pagination(`/v1/feed/user/${userId}/`, { count: 30 });
|
|
3234
|
+
}
|
|
3235
|
+
/** Paginated user reels (POST endpoint). */
|
|
3236
|
+
userClips(userId) {
|
|
3237
|
+
const data = {
|
|
3238
|
+
target_user_id: userId,
|
|
3239
|
+
page_size: "50",
|
|
3240
|
+
max_id: null,
|
|
3241
|
+
include_feed_video: "true"
|
|
3242
|
+
};
|
|
3243
|
+
return this._paginationPost("/v1/clips/user/", data);
|
|
3244
|
+
}
|
|
3245
|
+
/** Paginated tagged posts. */
|
|
3246
|
+
userTagged(userId) {
|
|
3247
|
+
return this._pagination(`/v1/usertags/${userId}/feed/`, { count: 20 });
|
|
3248
|
+
}
|
|
3249
|
+
/** Paginated saved posts (media wrapper). */
|
|
3250
|
+
userSaved() {
|
|
3251
|
+
return this._pagination("/v1/feed/saved/posts/", { count: 50 }, true);
|
|
3252
|
+
}
|
|
3253
|
+
/** Paginated collection. */
|
|
3254
|
+
userCollection(collectionId) {
|
|
3255
|
+
return this._pagination(`/v1/feed/collection/${collectionId}/posts/`, { count: 50 }, true);
|
|
3256
|
+
}
|
|
3257
|
+
/** Reels media — batch call, returns full reel objects. */
|
|
3258
|
+
async reelsMedia(reelIds) {
|
|
3259
|
+
const data = await this._call("/v1/feed/reels_media/", { params: { reel_ids: reelIds } });
|
|
3260
|
+
if (data && typeof data === "object") {
|
|
3261
|
+
const reels = data.reels_media;
|
|
3262
|
+
if (Array.isArray(reels)) return reels;
|
|
3263
|
+
}
|
|
3264
|
+
throw new Error("Auth required — authenticated cookies needed for reels");
|
|
3265
|
+
}
|
|
3266
|
+
/** Story tray. */
|
|
3267
|
+
async reelsTray() {
|
|
3268
|
+
const data = await this._call("/v1/feed/reels_tray/");
|
|
3269
|
+
if (data && typeof data === "object") {
|
|
3270
|
+
const tray = data.tray;
|
|
3271
|
+
if (Array.isArray(tray)) return tray;
|
|
3272
|
+
}
|
|
3273
|
+
return [];
|
|
3274
|
+
}
|
|
3275
|
+
/** Highlights list (tray). */
|
|
3276
|
+
async highlightsTray(userId) {
|
|
3277
|
+
const data = await this._call(`/v1/highlights/${userId}/highlights_tray/`);
|
|
3278
|
+
if (data && typeof data === "object") return data.tray ?? [];
|
|
3279
|
+
return [];
|
|
3280
|
+
}
|
|
3281
|
+
/** All highlights' media batched by ``chunkSize``. */
|
|
3282
|
+
async *highlightsMedia(userId, chunkSize = 5) {
|
|
3283
|
+
const ids = (await this.highlightsTray(userId)).map((hl) => hl.id);
|
|
3284
|
+
for (let i = 0; i < ids.length; i += chunkSize) {
|
|
3285
|
+
const chunk = ids.slice(i, i + chunkSize);
|
|
3286
|
+
yield* await this.reelsMedia(chunk);
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
/** Hashtag posts (via sections). */
|
|
3290
|
+
async *tagsMedia(tag) {
|
|
3291
|
+
for await (const section of this.tagsSections(tag)) {
|
|
3292
|
+
const medias = section.layout_content?.medias ?? [];
|
|
3293
|
+
for (const m of medias) if (m.media) yield m.media;
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
async *tagsSections(tag) {
|
|
3297
|
+
yield* this._paginationSections(`/v1/tags/${tag}/sections/`, {
|
|
3298
|
+
include_persistent: "0",
|
|
3299
|
+
max_id: null,
|
|
3300
|
+
page: null,
|
|
3301
|
+
surface: "grid",
|
|
3302
|
+
tab: "recent"
|
|
3303
|
+
});
|
|
3304
|
+
}
|
|
3305
|
+
/** User by numeric ID. */
|
|
3306
|
+
async userById(userId) {
|
|
3307
|
+
const data = await this._call(`/v1/users/${userId}/info/`);
|
|
3308
|
+
if (data && typeof data === "object") return data.user;
|
|
3309
|
+
throw new Error("User not found");
|
|
3310
|
+
}
|
|
3311
|
+
/** User by username (web_profile_info). */
|
|
3312
|
+
async userByName(username) {
|
|
3313
|
+
const data = await this._call("/v1/users/web_profile_info/", { params: { username } });
|
|
3314
|
+
if (data && typeof data === "object") return data.data;
|
|
3315
|
+
throw new Error("User not found");
|
|
3316
|
+
}
|
|
3317
|
+
/** Search user by username. */
|
|
3318
|
+
async userBySearch(username) {
|
|
3319
|
+
const data = await this._call("https://www.instagram.com/web/search/topsearch/", { params: { query: username } });
|
|
3320
|
+
if (data && typeof data === "object") {
|
|
3321
|
+
const users = data.users;
|
|
3322
|
+
if (users) {
|
|
3323
|
+
const name = username.toLowerCase();
|
|
3324
|
+
for (const result of users) if (result.user.username.toLowerCase() === name) return result.user;
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
throw new Error("User not found");
|
|
3328
|
+
}
|
|
3329
|
+
/** Scrape user ID from HTML profile page. */
|
|
3330
|
+
async userByWeb(username) {
|
|
3331
|
+
const resp = await this.http.request({
|
|
3332
|
+
url: `https://www.instagram.com/${username}`,
|
|
3333
|
+
headers: {
|
|
3334
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
|
3335
|
+
"Accept-Language": "en-US,en;q=0.5",
|
|
3336
|
+
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
3337
|
+
"Alt-Used": "www.instagram.com",
|
|
3338
|
+
"Connection": "keep-alive",
|
|
3339
|
+
"Sec-Fetch-Dest": "document",
|
|
3340
|
+
"Sec-Fetch-Mode": "navigate",
|
|
3341
|
+
"Sec-Fetch-Site": "none",
|
|
3342
|
+
"Priority": "u=0, i"
|
|
3343
|
+
}
|
|
3344
|
+
});
|
|
3345
|
+
const text = typeof resp.data === "string" ? resp.data : "";
|
|
3346
|
+
const idx = text.indexOf("\"profile_id\":\"");
|
|
3347
|
+
if (idx >= 0) {
|
|
3348
|
+
const start = idx + 15;
|
|
3349
|
+
const end = text.indexOf("\"", start);
|
|
3350
|
+
if (end > start) return { id: text.slice(start, end) };
|
|
3351
|
+
}
|
|
3352
|
+
throw new Error("User not found");
|
|
3353
|
+
}
|
|
3354
|
+
/** Resolve screen name via fallback chain: search → info → web. */
|
|
3355
|
+
async userByScreenName(screenName) {
|
|
3356
|
+
for (const strategy of [
|
|
3357
|
+
"search",
|
|
3358
|
+
"info",
|
|
3359
|
+
"web"
|
|
3360
|
+
]) try {
|
|
3361
|
+
if (strategy === "search") return await this.userBySearch(screenName);
|
|
3362
|
+
if (strategy === "info") return await this.userByName(screenName);
|
|
3363
|
+
if (strategy === "web") {
|
|
3364
|
+
const result = await this.userByWeb(screenName);
|
|
3365
|
+
return {
|
|
3366
|
+
pk: result.id,
|
|
3367
|
+
id: result.id,
|
|
3368
|
+
username: screenName,
|
|
3369
|
+
full_name: ""
|
|
3370
|
+
};
|
|
3371
|
+
}
|
|
3372
|
+
} catch {}
|
|
3373
|
+
throw new Error("User not found");
|
|
3374
|
+
}
|
|
3375
|
+
/** Resolve username/id to numeric user ID string. */
|
|
3376
|
+
async userId(screenName, checkPrivate = true) {
|
|
3377
|
+
if (screenName.startsWith("id:")) return screenName.slice(3);
|
|
3378
|
+
const user = await this.userByScreenName(screenName);
|
|
3379
|
+
if (checkPrivate && user.is_private && !user.followed_by_viewer) {}
|
|
3380
|
+
return user.id ?? user.pk;
|
|
3381
|
+
}
|
|
3382
|
+
/** Followers (paginated). */
|
|
3383
|
+
async *userFollowers(userId) {
|
|
3384
|
+
yield* this._paginationFollowing(`/v1/friendships/${userId}/followers/`, {
|
|
3385
|
+
count: 12,
|
|
3386
|
+
max_id: null
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
/** Following (paginated). */
|
|
3390
|
+
async *userFollowing(userId) {
|
|
3391
|
+
yield* this._paginationFollowing(`/v1/friendships/${userId}/following/`, {
|
|
3392
|
+
count: 12,
|
|
3393
|
+
max_id: null
|
|
3394
|
+
});
|
|
3395
|
+
}
|
|
3396
|
+
/** Internal — HTTP call */
|
|
3397
|
+
async _call(endpoint, opts = {}) {
|
|
3398
|
+
const url = endpoint.startsWith("/") ? `https://www.instagram.com/api${endpoint}` : endpoint;
|
|
3399
|
+
const csrf = this.getCsrf();
|
|
3400
|
+
const headers = {
|
|
3401
|
+
"Accept": "*/*",
|
|
3402
|
+
"Cookie": `csrftoken=${csrf}`,
|
|
3403
|
+
"X-CSRFToken": csrf,
|
|
3404
|
+
"X-IG-App-ID": APP_ID,
|
|
3405
|
+
"X-ASBD-ID": ASBD_ID,
|
|
3406
|
+
"X-IG-WWW-Claim": this.getWwwClaim(),
|
|
3407
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
3408
|
+
"Connection": "keep-alive",
|
|
3409
|
+
"Referer": `${this.root}/`,
|
|
3410
|
+
"Sec-Fetch-Dest": "empty",
|
|
3411
|
+
"Sec-Fetch-Mode": "cors",
|
|
3412
|
+
"Sec-Fetch-Site": "same-origin"
|
|
3413
|
+
};
|
|
3414
|
+
const resp = await this.http.request({
|
|
3415
|
+
url,
|
|
3416
|
+
method: opts.method ?? "GET",
|
|
3417
|
+
headers,
|
|
3418
|
+
params: opts.params ? Object.fromEntries(Object.entries(opts.params).filter(([, v]) => v != null)) : void 0,
|
|
3419
|
+
data: opts.data
|
|
3420
|
+
});
|
|
3421
|
+
const finalUrl = resp.url;
|
|
3422
|
+
if (finalUrl.includes("/accounts/login/")) throw new Error("Instagram redirected to login page — you need a valid sessionid. Export it from your browser (F12 → Application → Cookies → sessionid) and pass --sessionid=<value> or set INSTAGRAM_SESSIONID env var.");
|
|
3423
|
+
if (finalUrl.includes("/challenge/")) throw new Error("Instagram redirected to challenge page — account flagged. Log in via browser to resolve the challenge, then export a fresh sessionid.");
|
|
3424
|
+
const rawCookie = resp.headers["set-cookie"];
|
|
3425
|
+
const csrfCookie = (Array.isArray(rawCookie) ? rawCookie.join("; ") : rawCookie ?? "").split(";").find((c) => c.trim().startsWith("csrftoken="));
|
|
3426
|
+
if (csrfCookie) {
|
|
3427
|
+
const val = csrfCookie.split("=")[1]?.trim();
|
|
3428
|
+
if (val) this.setCsrf(val);
|
|
3429
|
+
}
|
|
3430
|
+
const claim = resp.headers["x-ig-set-www-claim"];
|
|
3431
|
+
if (claim != null) this.setWwwClaim(String(claim));
|
|
3432
|
+
return resp.data;
|
|
3433
|
+
}
|
|
3434
|
+
/** Pagination engines */
|
|
3435
|
+
async *_pagination(endpoint, params = {}, media = false) {
|
|
3436
|
+
let maxId = this.getCursor();
|
|
3437
|
+
const reqParams = { ...params };
|
|
3438
|
+
while (true) {
|
|
3439
|
+
reqParams.max_id = maxId;
|
|
3440
|
+
const data = await this._call(endpoint, { params: reqParams });
|
|
3441
|
+
if (data) {
|
|
3442
|
+
const items = data.items;
|
|
3443
|
+
if (items) for (const item of items) if (media) yield item.media ?? item;
|
|
3444
|
+
else yield item;
|
|
3445
|
+
if (!data.more_available) {
|
|
3446
|
+
this.setCursor(null);
|
|
3447
|
+
return;
|
|
3448
|
+
}
|
|
3449
|
+
maxId = this.setCursor(data.next_max_id);
|
|
3450
|
+
} else {
|
|
3451
|
+
this.setCursor(null);
|
|
3452
|
+
return;
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
}
|
|
3456
|
+
async *_paginationPost(endpoint, reqData) {
|
|
3457
|
+
let maxId = this.getCursor();
|
|
3458
|
+
const data = { ...reqData };
|
|
3459
|
+
while (true) {
|
|
3460
|
+
data.max_id = maxId;
|
|
3461
|
+
const resp = await this._call(endpoint, {
|
|
3462
|
+
method: "POST",
|
|
3463
|
+
data
|
|
3464
|
+
});
|
|
3465
|
+
if (resp) {
|
|
3466
|
+
const items = resp.items;
|
|
3467
|
+
if (items) for (const item of items) yield item.media ?? item;
|
|
3468
|
+
const info = resp.paging_info;
|
|
3469
|
+
if (!info || !info.more_available) {
|
|
3470
|
+
this.setCursor(null);
|
|
3471
|
+
return;
|
|
3472
|
+
}
|
|
3473
|
+
maxId = this.setCursor(info.max_id);
|
|
3474
|
+
} else {
|
|
3475
|
+
this.setCursor(null);
|
|
3476
|
+
return;
|
|
3477
|
+
}
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
async *_paginationSections(endpoint, reqData) {
|
|
3481
|
+
let maxId = this.getCursor();
|
|
3482
|
+
let page = null;
|
|
3483
|
+
const data = { ...reqData };
|
|
3484
|
+
while (true) {
|
|
3485
|
+
data.max_id = maxId;
|
|
3486
|
+
data.page = page;
|
|
3487
|
+
const info = await this._call(endpoint, {
|
|
3488
|
+
method: "POST",
|
|
3489
|
+
data
|
|
3490
|
+
});
|
|
3491
|
+
if (info) {
|
|
3492
|
+
const sections = info.sections;
|
|
3493
|
+
if (sections) yield* sections;
|
|
3494
|
+
if (!info.more_available) {
|
|
3495
|
+
this.setCursor(null);
|
|
3496
|
+
return;
|
|
3497
|
+
}
|
|
3498
|
+
page = info.next_page;
|
|
3499
|
+
maxId = this.setCursor(info.next_max_id);
|
|
3500
|
+
} else {
|
|
3501
|
+
this.setCursor(null);
|
|
3502
|
+
return;
|
|
3503
|
+
}
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
async *_paginationFollowing(endpoint, params) {
|
|
3507
|
+
let maxId = this._parseIntCursor(this.getCursor());
|
|
3508
|
+
const reqParams = { ...params };
|
|
3509
|
+
while (true) {
|
|
3510
|
+
reqParams.max_id = maxId;
|
|
3511
|
+
const data = await this._call(endpoint, { params: reqParams });
|
|
3512
|
+
if (data) {
|
|
3513
|
+
const users = data.users;
|
|
3514
|
+
if (users) yield* users;
|
|
3515
|
+
const nextMaxId = data.next_max_id;
|
|
3516
|
+
if (nextMaxId == null) {
|
|
3517
|
+
this.setCursor(null);
|
|
3518
|
+
return;
|
|
3519
|
+
}
|
|
3520
|
+
maxId = this._parseIntCursor(String(nextMaxId));
|
|
3521
|
+
this.setCursor(String(maxId));
|
|
3522
|
+
} else {
|
|
3523
|
+
this.setCursor(null);
|
|
3524
|
+
return;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
}
|
|
3528
|
+
_parseIntCursor(v) {
|
|
3529
|
+
if (v == null || v === "") return null;
|
|
3530
|
+
const n = Number(v);
|
|
3531
|
+
return Number.isFinite(n) ? n : null;
|
|
3532
|
+
}
|
|
3533
|
+
};
|
|
3534
|
+
//#endregion
|
|
3535
|
+
//#region src/instagram/parsers/rest.ts
|
|
3536
|
+
/** Main entry — parse a REST post response. */
|
|
3537
|
+
function parsePostRest(post, cfg) {
|
|
3538
|
+
if (post.items) return parseStoryRest(post, cfg);
|
|
3539
|
+
const owner = post.user;
|
|
3540
|
+
const caption = post.caption;
|
|
3541
|
+
const ts = post.taken_at ?? post.created_at;
|
|
3542
|
+
const date = cfg.parseTimestamp(ts ?? null);
|
|
3543
|
+
const data = {
|
|
3544
|
+
post_id: post.pk,
|
|
3545
|
+
post_shortcode: post.code,
|
|
3546
|
+
post_url: `${cfg.root}/p/${post.code}/`,
|
|
3547
|
+
likes: post.like_count ?? 0,
|
|
3548
|
+
liked: post.has_liked ?? false,
|
|
3549
|
+
pinned: extractPinned(post),
|
|
3550
|
+
owner_id: owner.pk,
|
|
3551
|
+
username: owner.username ?? "",
|
|
3552
|
+
fullname: owner.full_name ?? "",
|
|
3553
|
+
post_date: date,
|
|
3554
|
+
date,
|
|
3555
|
+
description: caption ? caption.text : "",
|
|
3556
|
+
type: "post",
|
|
3557
|
+
count: 0,
|
|
3558
|
+
_files: []
|
|
3559
|
+
};
|
|
3560
|
+
const tags = cfg.findTags(data.description);
|
|
3561
|
+
if (tags.length > 0) data.tags = [...new Set(tags)].sort();
|
|
3562
|
+
if (post.location) {
|
|
3563
|
+
const loc = post.location;
|
|
3564
|
+
data.location_id = loc.pk;
|
|
3565
|
+
data.location_slug = loc.short_name.replace(/\s+/g, "-").toLowerCase();
|
|
3566
|
+
data.location_url = `${cfg.root}/explore/locations/${loc.pk}/${data.location_slug}/`;
|
|
3567
|
+
}
|
|
3568
|
+
if (post.coauthor_producers) data.coauthors = post.coauthor_producers.map((u) => ({
|
|
3569
|
+
id: u.pk,
|
|
3570
|
+
username: u.username,
|
|
3571
|
+
full_name: u.full_name
|
|
3572
|
+
}));
|
|
3573
|
+
let items;
|
|
3574
|
+
if (post.carousel_media?.length) {
|
|
3575
|
+
data.sidecar_media_id = data.post_id;
|
|
3576
|
+
data.sidecar_shortcode = data.post_shortcode;
|
|
3577
|
+
items = post.carousel_media;
|
|
3578
|
+
} else items = [post];
|
|
3579
|
+
for (let num = 0; num < items.length; num++) {
|
|
3580
|
+
const item = items[num];
|
|
3581
|
+
const media = parseMediaItem(item, post, cfg, num + 1);
|
|
3582
|
+
if (!media) continue;
|
|
3583
|
+
const itemRec = item;
|
|
3584
|
+
extractTaggedUsers(itemRec, media);
|
|
3585
|
+
data._files.push(media);
|
|
3586
|
+
const stickers = itemRec.story_music_stickers;
|
|
3587
|
+
if (stickers?.[0]) {
|
|
3588
|
+
const audio = extractAudio(itemRec, data, stickers[0], cfg);
|
|
3589
|
+
if (audio) {
|
|
3590
|
+
audio.num = num + 1;
|
|
3591
|
+
data._files.push(audio);
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
}
|
|
3595
|
+
if (post.music_metadata) {
|
|
3596
|
+
const info = post.music_metadata.music_info;
|
|
3597
|
+
if (info) {
|
|
3598
|
+
const audio = extractAudio(post, data, { music_asset_info: info }, cfg);
|
|
3599
|
+
if (audio) {
|
|
3600
|
+
audio.num = items.length;
|
|
3601
|
+
data._files.push(audio);
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
const files = data._files;
|
|
3606
|
+
if (files.length === 1 && files[0].video_url) {
|
|
3607
|
+
data.type = "reel";
|
|
3608
|
+
data.post_url = `${cfg.root}/reel/${post.code}/`;
|
|
3609
|
+
}
|
|
3610
|
+
if (post.subscription_media_visibility) data.subscription = post.subscription_media_visibility;
|
|
3611
|
+
return data;
|
|
3612
|
+
}
|
|
3613
|
+
/** Parse a story or highlight REST response. */
|
|
3614
|
+
function parseStoryRest(post, cfg) {
|
|
3615
|
+
const items = post.items;
|
|
3616
|
+
const reelId = String(post.id).split(":").pop() ?? "0";
|
|
3617
|
+
const date = cfg.parseTimestamp(post.taken_at ?? post.created_at ?? post.seen ?? null);
|
|
3618
|
+
const expires = post.expiring_at;
|
|
3619
|
+
const isStory = !!expires;
|
|
3620
|
+
const data = {
|
|
3621
|
+
post_id: reelId,
|
|
3622
|
+
post_shortcode: shortcodeFromId(reelId),
|
|
3623
|
+
post_url: isStory ? `${cfg.root}/stories/${post.user.username}/` : `${cfg.root}/stories/highlights/${reelId}/`,
|
|
3624
|
+
likes: 0,
|
|
3625
|
+
liked: false,
|
|
3626
|
+
pinned: [],
|
|
3627
|
+
owner_id: post.user.pk,
|
|
3628
|
+
username: post.user.username ?? "",
|
|
3629
|
+
fullname: post.user.full_name ?? "",
|
|
3630
|
+
post_date: date,
|
|
3631
|
+
date,
|
|
3632
|
+
description: "",
|
|
3633
|
+
type: isStory ? "story" : "highlight",
|
|
3634
|
+
count: 0,
|
|
3635
|
+
_files: [],
|
|
3636
|
+
expires: expires ? cfg.parseTimestamp(expires) : void 0,
|
|
3637
|
+
user: post.user
|
|
3638
|
+
};
|
|
3639
|
+
if (!isStory && post.title) data.highlight_title = post.title;
|
|
3640
|
+
else if (!post.seen) post.seen = expires - 86400;
|
|
3641
|
+
for (let num = 0; num < items.length; num++) {
|
|
3642
|
+
const item = items[num];
|
|
3643
|
+
const media = parseMediaItem(item, post, cfg, num + 1);
|
|
3644
|
+
if (!media) continue;
|
|
3645
|
+
extractTaggedUsers(item, media);
|
|
3646
|
+
data._files.push(media);
|
|
3647
|
+
}
|
|
3648
|
+
return data;
|
|
3649
|
+
}
|
|
3650
|
+
/** Parse a single media item (image/video) from a carousel or story. */
|
|
3651
|
+
function parseMediaItem(item, parent, cfg, num) {
|
|
3652
|
+
let image;
|
|
3653
|
+
try {
|
|
3654
|
+
image = item.image_versions2.candidates[0];
|
|
3655
|
+
} catch {
|
|
3656
|
+
return null;
|
|
3657
|
+
}
|
|
3658
|
+
const itemRec = item;
|
|
3659
|
+
if (!cfg.staticVideo && item.original_media_type != null && item.original_media_type === 1 && item.original_media_type !== item.media_type) {
|
|
3660
|
+
delete itemRec.video_versions;
|
|
3661
|
+
if (image) {
|
|
3662
|
+
item.original_width = image.width;
|
|
3663
|
+
item.original_height = image.height;
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
3666
|
+
const widthOrig = item.original_width ?? 0;
|
|
3667
|
+
const heightOrig = item.original_height ?? 0;
|
|
3668
|
+
let video = null;
|
|
3669
|
+
let manifest = null;
|
|
3670
|
+
let width;
|
|
3671
|
+
let height;
|
|
3672
|
+
if (item.video_versions?.length) {
|
|
3673
|
+
video = item.video_versions.reduce((best, v) => v.width * v.height * v.type > best.width * best.height * best.type ? v : best);
|
|
3674
|
+
if (item.video_dash_manifest && cfg.videosDash) {
|
|
3675
|
+
manifest = item.video_dash_manifest;
|
|
3676
|
+
width = widthOrig;
|
|
3677
|
+
height = heightOrig;
|
|
3678
|
+
} else {
|
|
3679
|
+
width = video.width;
|
|
3680
|
+
height = video.height;
|
|
3681
|
+
}
|
|
3682
|
+
} else {
|
|
3683
|
+
video = null;
|
|
3684
|
+
manifest = null;
|
|
3685
|
+
width = image.width;
|
|
3686
|
+
height = image.height;
|
|
3687
|
+
}
|
|
3688
|
+
const media = {
|
|
3689
|
+
num,
|
|
3690
|
+
date: cfg.parseTimestamp(itemRec.taken_at ?? video?.taken_at ?? parent.taken_at ?? null),
|
|
3691
|
+
media_id: item.pk,
|
|
3692
|
+
shortcode: item.code ?? shortcodeFromId(item.pk),
|
|
3693
|
+
display_url: image.url,
|
|
3694
|
+
video_url: video?.url ?? null,
|
|
3695
|
+
width,
|
|
3696
|
+
width_original: widthOrig,
|
|
3697
|
+
height,
|
|
3698
|
+
height_original: heightOrig,
|
|
3699
|
+
tagged_users: []
|
|
3700
|
+
};
|
|
3701
|
+
if (manifest != null) media._ytdl_manifest_data = manifest;
|
|
3702
|
+
if (item.owner) media.owner = item.owner;
|
|
3703
|
+
if (item.reshared_story_media_author) media.author = item.reshared_story_media_author;
|
|
3704
|
+
if (item.expiring_at != null) media.expires = cfg.parseTimestamp(item.expiring_at);
|
|
3705
|
+
if (item.subscription_media_visibility) media.subscription = item.subscription_media_visibility;
|
|
3706
|
+
if (itemRec.audience) media.audience = itemRec.audience;
|
|
3707
|
+
return media;
|
|
3708
|
+
}
|
|
3709
|
+
/** Extract tagged users from various field formats. */
|
|
3710
|
+
function extractTaggedUsers(src, dest) {
|
|
3711
|
+
dest.tagged_users = [];
|
|
3712
|
+
const edges = src.edge_media_to_tagged_user;
|
|
3713
|
+
if (edges?.edges) for (const edge of edges.edges) {
|
|
3714
|
+
const u = edge.node.user;
|
|
3715
|
+
dest.tagged_users.push({
|
|
3716
|
+
id: u.id ?? u.pk,
|
|
3717
|
+
username: u.username,
|
|
3718
|
+
full_name: u.full_name
|
|
3719
|
+
});
|
|
3720
|
+
}
|
|
3721
|
+
const usertags = src.usertags;
|
|
3722
|
+
if (usertags?.in) for (const tag of usertags.in) {
|
|
3723
|
+
const u = tag.user;
|
|
3724
|
+
dest.tagged_users.push({
|
|
3725
|
+
id: u.pk,
|
|
3726
|
+
username: u.username,
|
|
3727
|
+
full_name: u.full_name
|
|
3728
|
+
});
|
|
3729
|
+
}
|
|
3730
|
+
const mentions = src.reel_mentions;
|
|
3731
|
+
if (mentions) for (const m of mentions) {
|
|
3732
|
+
const u = m.user;
|
|
3733
|
+
dest.tagged_users.push({
|
|
3734
|
+
id: u.pk ?? u.id ?? "",
|
|
3735
|
+
username: u.username,
|
|
3736
|
+
full_name: u.full_name
|
|
3737
|
+
});
|
|
3738
|
+
}
|
|
3739
|
+
const bloks = src.story_bloks_stickers;
|
|
3740
|
+
if (bloks) for (const sticker of bloks) {
|
|
3741
|
+
const s = sticker.bloks_sticker;
|
|
3742
|
+
if (s.bloks_sticker_type === "mention") {
|
|
3743
|
+
const m = s.sticker_data.ig_mention;
|
|
3744
|
+
dest.tagged_users.push({
|
|
3745
|
+
id: m.account_id,
|
|
3746
|
+
username: m.username,
|
|
3747
|
+
full_name: m.full_name
|
|
3748
|
+
});
|
|
3749
|
+
}
|
|
3750
|
+
}
|
|
3751
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3752
|
+
dest.tagged_users = dest.tagged_users.filter((t) => seen.has(t.id) ? false : (seen.add(t.id), true));
|
|
3753
|
+
}
|
|
3754
|
+
/** Extract audio/music metadata from a story sticker. */
|
|
3755
|
+
function extractAudio(src, dest, sticker, cfg) {
|
|
3756
|
+
const info = sticker.music_asset_info;
|
|
3757
|
+
if (!info) return null;
|
|
3758
|
+
const cinfo = sticker.music_consumption_info ?? info;
|
|
3759
|
+
dest.audio_title = info.title;
|
|
3760
|
+
dest.audio_duration = (info.duration_in_ms ?? 0) / 1e3;
|
|
3761
|
+
dest.audio_timestamps = info.highlight_start_times_in_ms;
|
|
3762
|
+
dest.audio_artist = info.display_artist ?? cinfo.display_artist;
|
|
3763
|
+
dest.audio_user = info.ig_artist ?? cinfo.ig_artist;
|
|
3764
|
+
const url = info.progressive_download_url;
|
|
3765
|
+
if (!url) return null;
|
|
3766
|
+
return {
|
|
3767
|
+
num: 0,
|
|
3768
|
+
date: cfg.parseTimestamp(src.taken_at ?? null),
|
|
3769
|
+
media_id: info.id,
|
|
3770
|
+
shortcode: shortcodeFromId(info.id),
|
|
3771
|
+
display_url: info.cover_artwork_uri ?? "",
|
|
3772
|
+
video_url: null,
|
|
3773
|
+
audio_url: url,
|
|
3774
|
+
width: 0,
|
|
3775
|
+
width_original: 0,
|
|
3776
|
+
height: 0,
|
|
3777
|
+
height_original: 0,
|
|
3778
|
+
tagged_users: [],
|
|
3779
|
+
audio_user: info.ig_artist ?? cinfo.ig_artist,
|
|
3780
|
+
audio_title: info.title,
|
|
3781
|
+
audio_artist: info.display_artist ?? cinfo.display_artist,
|
|
3782
|
+
audio_duration: (info.duration_in_ms ?? 0) / 1e3,
|
|
3783
|
+
audio_timestamps: info.highlight_start_times_in_ms
|
|
3784
|
+
};
|
|
3785
|
+
}
|
|
3786
|
+
function extractPinned(post) {
|
|
3787
|
+
if (post.timeline_pinned_user_ids) return post.timeline_pinned_user_ids;
|
|
3788
|
+
if (post.clips_tab_pinned_user_ids) return post.clips_tab_pinned_user_ids;
|
|
3789
|
+
return [];
|
|
3790
|
+
}
|
|
3791
|
+
//#endregion
|
|
3792
|
+
//#region src/instagram/parsers/graphql.ts
|
|
3793
|
+
/** Parse a GraphQL post/edge response. */
|
|
3794
|
+
function parsePostGraphql(post, cfg) {
|
|
3795
|
+
const typename = post.__typename ?? "GraphImage";
|
|
3796
|
+
const owner = post.owner;
|
|
3797
|
+
const date = cfg.parseTimestamp(post.taken_at_timestamp);
|
|
3798
|
+
const data = {
|
|
3799
|
+
typename,
|
|
3800
|
+
likes: post.edge_media_preview_like?.count ?? 0,
|
|
3801
|
+
liked: post.viewer_has_liked ?? false,
|
|
3802
|
+
pinned: post.pinned_for_users?.map((u) => Number(u.id)) ?? [],
|
|
3803
|
+
owner_id: owner.id ?? owner.pk,
|
|
3804
|
+
username: owner.username ?? "",
|
|
3805
|
+
fullname: owner.full_name ?? "",
|
|
3806
|
+
post_id: post.id,
|
|
3807
|
+
post_shortcode: post.shortcode,
|
|
3808
|
+
post_url: `${cfg.root}/p/${post.shortcode}/`,
|
|
3809
|
+
post_date: date,
|
|
3810
|
+
date,
|
|
3811
|
+
description: "",
|
|
3812
|
+
type: "post",
|
|
3813
|
+
count: 0,
|
|
3814
|
+
_files: []
|
|
3815
|
+
};
|
|
3816
|
+
data.description = post.edge_media_to_caption?.edges?.map((e) => e.node.text).join("\n") ?? "";
|
|
3817
|
+
data.description = parseUnicodeEscapes(data.description);
|
|
3818
|
+
const tags = cfg.findTags(data.description);
|
|
3819
|
+
if (tags.length > 0) data.tags = [...new Set(tags)].sort();
|
|
3820
|
+
const location = post.location;
|
|
3821
|
+
if (location) {
|
|
3822
|
+
data.location_id = location.pk;
|
|
3823
|
+
data.location_slug = location.short_name;
|
|
3824
|
+
data.location_url = `${cfg.root}/explore/locations/${location.pk}/${location.short_name}/`;
|
|
3825
|
+
}
|
|
3826
|
+
const coauthors = post.coauthor_producers;
|
|
3827
|
+
if (coauthors?.length) data.coauthors = coauthors.map((u) => ({
|
|
3828
|
+
id: u.id ?? u.pk,
|
|
3829
|
+
username: u.username
|
|
3830
|
+
}));
|
|
3831
|
+
const sidecar = post.edge_sidecar_to_children;
|
|
3832
|
+
if (sidecar?.edges) {
|
|
3833
|
+
data.sidecar_media_id = data.post_id;
|
|
3834
|
+
data.sidecar_shortcode = data.post_shortcode;
|
|
3835
|
+
let num = 0;
|
|
3836
|
+
for (const edge of sidecar.edges) {
|
|
3837
|
+
num++;
|
|
3838
|
+
const node = edge.node;
|
|
3839
|
+
const dimensions = node.dimensions;
|
|
3840
|
+
const media = {
|
|
3841
|
+
num,
|
|
3842
|
+
date: data.date,
|
|
3843
|
+
media_id: node.id,
|
|
3844
|
+
shortcode: node.shortcode ?? shortcodeFromId(node.id),
|
|
3845
|
+
display_url: node.display_url,
|
|
3846
|
+
video_url: node.video_url ?? null,
|
|
3847
|
+
width: dimensions.width,
|
|
3848
|
+
height: dimensions.height,
|
|
3849
|
+
sidecar_media_id: data.post_id,
|
|
3850
|
+
sidecar_shortcode: data.post_shortcode,
|
|
3851
|
+
tagged_users: [],
|
|
3852
|
+
width_original: dimensions.width,
|
|
3853
|
+
height_original: dimensions.height
|
|
3854
|
+
};
|
|
3855
|
+
extractTaggedUsers(node, media);
|
|
3856
|
+
data._files.push(media);
|
|
3857
|
+
}
|
|
3858
|
+
} else {
|
|
3859
|
+
const dimensions = post.dimensions;
|
|
3860
|
+
const media = {
|
|
3861
|
+
num: 1,
|
|
3862
|
+
date: data.date,
|
|
3863
|
+
media_id: post.id,
|
|
3864
|
+
shortcode: post.shortcode,
|
|
3865
|
+
display_url: post.display_url,
|
|
3866
|
+
video_url: post.video_url ?? null,
|
|
3867
|
+
width: dimensions.width,
|
|
3868
|
+
height: dimensions.height,
|
|
3869
|
+
tagged_users: [],
|
|
3870
|
+
width_original: dimensions.width,
|
|
3871
|
+
height_original: dimensions.height
|
|
3872
|
+
};
|
|
3873
|
+
extractTaggedUsers(post, media);
|
|
3874
|
+
data._files.push(media);
|
|
3875
|
+
}
|
|
3876
|
+
return data;
|
|
3877
|
+
}
|
|
3878
|
+
function parseUnicodeEscapes(text) {
|
|
3879
|
+
if (!text.includes("\\u")) return text;
|
|
3880
|
+
return text.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
3881
|
+
}
|
|
3882
|
+
//#endregion
|
|
3883
|
+
//#region src/instagram/base.ts
|
|
3884
|
+
var Ref = class {
|
|
3885
|
+
value;
|
|
3886
|
+
constructor(v) {
|
|
3887
|
+
this.value = v;
|
|
3888
|
+
}
|
|
3889
|
+
};
|
|
3890
|
+
var InstagramExtractor = class extends Extractor {
|
|
3891
|
+
category = "instagram";
|
|
3892
|
+
root = "https://www.instagram.com";
|
|
3893
|
+
api;
|
|
3894
|
+
csrfToken = new Ref("");
|
|
3895
|
+
wwwClaim = new Ref("0");
|
|
3896
|
+
cursor = new Ref(null);
|
|
3897
|
+
_loggedIn = true;
|
|
3898
|
+
_user = null;
|
|
3899
|
+
_findTags = findTags;
|
|
3900
|
+
_csrfSeed;
|
|
3901
|
+
constructor(opts) {
|
|
3902
|
+
super(opts);
|
|
3903
|
+
this._csrfSeed = opts.csrfToken;
|
|
3904
|
+
}
|
|
3905
|
+
/** Initialization */
|
|
3906
|
+
async _init() {
|
|
3907
|
+
this.csrfToken.value = this._csrfSeed || Extractor.generateToken(16);
|
|
3908
|
+
this.api = new InstagramRestAPI({
|
|
3909
|
+
http: this.http,
|
|
3910
|
+
root: this.root,
|
|
3911
|
+
csrfToken: this.csrfToken,
|
|
3912
|
+
wwwClaim: this.wwwClaim,
|
|
3913
|
+
cursor: this.cursor
|
|
3914
|
+
});
|
|
3915
|
+
}
|
|
3916
|
+
/** Request override */
|
|
3917
|
+
async request(url, cfg = {}) {
|
|
3918
|
+
const response = await super.request(url, cfg);
|
|
3919
|
+
const finalUrl = response.url;
|
|
3920
|
+
if (finalUrl.includes("/accounts/login/")) throw new Error("HTTP redirect to login page — cookies expired or invalid");
|
|
3921
|
+
if (finalUrl.includes("/challenge/")) throw new Error("HTTP redirect to challenge page — account flagged");
|
|
3922
|
+
const claim = response.headers["x-ig-set-www-claim"];
|
|
3923
|
+
if (claim != null) this.wwwClaim.value = String(claim);
|
|
3924
|
+
return response;
|
|
3925
|
+
}
|
|
3926
|
+
/** Login */
|
|
3927
|
+
async login() {
|
|
3928
|
+
this._loggedIn = true;
|
|
3929
|
+
}
|
|
3930
|
+
/** Core pipeline */
|
|
3931
|
+
async *items() {
|
|
3932
|
+
await this.login();
|
|
3933
|
+
const meta = await this.metadata() ?? {};
|
|
3934
|
+
const videos = this._cfg("videos", true);
|
|
3935
|
+
const videosDash = videos !== "merged";
|
|
3936
|
+
const shouldDownloadVideos = !!videos;
|
|
3937
|
+
const previews = this._cfg("previews", false);
|
|
3938
|
+
const previewsVid = typeof previews === "object" ? previews.includes("video") : false;
|
|
3939
|
+
const previewsAud = typeof previews === "object" ? previews.includes("audio") : false;
|
|
3940
|
+
const audio = this._cfg("audio", false);
|
|
3941
|
+
const maxPosts = this._cfg("max-posts");
|
|
3942
|
+
const orderFiles = this._cfg("order-files");
|
|
3943
|
+
const reverse = orderFiles ? ["r", "d"].includes(orderFiles[0]) : false;
|
|
3944
|
+
const parserCfg = {
|
|
3945
|
+
root: this.root,
|
|
3946
|
+
findTags: this._findTags,
|
|
3947
|
+
parseTimestamp: this.parseTimestamp.bind(this),
|
|
3948
|
+
staticVideo: this._cfg("static-videos", true) ?? true,
|
|
3949
|
+
warnVideo: !previews && shouldDownloadVideos,
|
|
3950
|
+
warnImage: 1,
|
|
3951
|
+
videosDash
|
|
3952
|
+
};
|
|
3953
|
+
this.log.debug(`cfg: videos=${shouldDownloadVideos} previews=${!!previews} audio=${audio} maxPosts=${maxPosts ?? "∞"} staticVideos=${parserCfg.staticVideo}`);
|
|
3954
|
+
let count = 0;
|
|
3955
|
+
for await (const post of this.posts()) {
|
|
3956
|
+
if (maxPosts != null && count >= maxPosts) break;
|
|
3957
|
+
count++;
|
|
3958
|
+
const parsed = "__typename" in post ? parsePostGraphql(post, parserCfg) : parsePostRest(post, parserCfg);
|
|
3959
|
+
if (this._user) parsed.user = this._user;
|
|
3960
|
+
Object.assign(parsed, meta);
|
|
3961
|
+
const files = parsed._files;
|
|
3962
|
+
parsed.count = files.length;
|
|
3963
|
+
yield {
|
|
3964
|
+
type: "directory",
|
|
3965
|
+
metadata: parsed
|
|
3966
|
+
};
|
|
3967
|
+
const ordered = reverse ? [...files].reverse() : files;
|
|
3968
|
+
for (const file of ordered) {
|
|
3969
|
+
const combined = {
|
|
3970
|
+
...parsed,
|
|
3971
|
+
...file
|
|
3972
|
+
};
|
|
3973
|
+
if (file.audio_url) {
|
|
3974
|
+
if (audio) {
|
|
3975
|
+
nameExtFromURL(file.audio_url, combined);
|
|
3976
|
+
yield url(file.audio_url, combined);
|
|
3977
|
+
}
|
|
3978
|
+
if (previewsAud) combined.media_id = `${combined.media_id}p`;
|
|
3979
|
+
else continue;
|
|
3980
|
+
}
|
|
3981
|
+
if (file.video_url) {
|
|
3982
|
+
if (shouldDownloadVideos) {
|
|
3983
|
+
nameExtFromURL(file.video_url, combined);
|
|
3984
|
+
yield url(file.video_url, combined);
|
|
3985
|
+
}
|
|
3986
|
+
if (previewsVid) combined.media_id = `${combined.media_id}p`;
|
|
3987
|
+
else continue;
|
|
3988
|
+
}
|
|
3989
|
+
const imgUrl = file.display_url;
|
|
3990
|
+
nameExtFromURL(imgUrl, combined);
|
|
3991
|
+
if (combined.extension === "webp" && imgUrl.includes("stp=dst-jpg")) combined.extension = "jpg";
|
|
3992
|
+
yield url(imgUrl, combined);
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
if (count === 0) this.log.warn("No posts returned — API may have returned empty data (check sessionid or post visibility)");
|
|
3996
|
+
}
|
|
3997
|
+
/** Subclass hooks */
|
|
3998
|
+
/** @virtual */
|
|
3999
|
+
async metadata() {
|
|
4000
|
+
return {};
|
|
4001
|
+
}
|
|
4002
|
+
/** Cursor management */
|
|
4003
|
+
_initCursor() {
|
|
4004
|
+
const cursor = this._cfg("cursor", true);
|
|
4005
|
+
if (cursor === true) return null;
|
|
4006
|
+
if (!cursor) return null;
|
|
4007
|
+
return cursor;
|
|
4008
|
+
}
|
|
4009
|
+
_updateCursor(cursor) {
|
|
4010
|
+
if (cursor) this.log.debug(`Cursor: ${cursor}`);
|
|
4011
|
+
this.cursor.value = cursor;
|
|
4012
|
+
return cursor;
|
|
4013
|
+
}
|
|
4014
|
+
/** User assignment */
|
|
4015
|
+
_assignUser(user) {
|
|
4016
|
+
this._user = user;
|
|
4017
|
+
const mappings = [
|
|
4018
|
+
["count_media", "edge_owner_to_timeline_media"],
|
|
4019
|
+
["count_video", "edge_felix_video_timeline"],
|
|
4020
|
+
["count_saved", "edge_saved_media"],
|
|
4021
|
+
["count_mutual", "edge_mutual_followed_by"],
|
|
4022
|
+
["count_follow", "edge_follow"],
|
|
4023
|
+
["count_followed", "edge_followed_by"],
|
|
4024
|
+
["count_collection", "edge_media_collections"]
|
|
4025
|
+
];
|
|
4026
|
+
const rec = user;
|
|
4027
|
+
for (const [newKey, oldKey] of mappings) try {
|
|
4028
|
+
rec[newKey] = rec[oldKey]?.count ?? 0;
|
|
4029
|
+
delete rec[oldKey];
|
|
4030
|
+
} catch {
|
|
4031
|
+
rec[newKey] = 0;
|
|
4032
|
+
}
|
|
4033
|
+
}
|
|
4034
|
+
};
|
|
4035
|
+
//#endregion
|
|
4036
|
+
//#region src/instagram/extractors/helpers.ts
|
|
4037
|
+
/** Shared regex utilities for Instagram extractor URL patterns. */
|
|
4038
|
+
const BASE_RE = /^(?:https?:\/\/)?(?:www\.)?instagram\.com/;
|
|
4039
|
+
function re(base, path) {
|
|
4040
|
+
const pathSrc = typeof path === "string" ? path : path.source;
|
|
4041
|
+
return new RegExp(base.source + pathSrc, "i");
|
|
4042
|
+
}
|
|
4043
|
+
//#endregion
|
|
4044
|
+
//#region src/instagram/extractors/registry.ts
|
|
4045
|
+
const _registry = /* @__PURE__ */ new Map();
|
|
4046
|
+
function register(subcategory, cls) {
|
|
4047
|
+
_registry.set(subcategory, cls);
|
|
4048
|
+
}
|
|
4049
|
+
function get(subcategory) {
|
|
4050
|
+
return _registry.get(subcategory);
|
|
4051
|
+
}
|
|
4052
|
+
//#endregion
|
|
4053
|
+
//#region src/instagram/extractors/highlights.ts
|
|
4054
|
+
var InstagramHighlightsExtractor = class InstagramHighlightsExtractor extends InstagramExtractor {
|
|
4055
|
+
static subcategory = "highlights";
|
|
4056
|
+
static pattern = re(BASE_RE, /(\/[^/?#]+)\/highlights/);
|
|
4057
|
+
subcategory = InstagramHighlightsExtractor.subcategory;
|
|
4058
|
+
constructor(opts) {
|
|
4059
|
+
super(opts);
|
|
4060
|
+
}
|
|
4061
|
+
static fromURL(url, opts) {
|
|
4062
|
+
const match = InstagramHighlightsExtractor.pattern.exec(url);
|
|
4063
|
+
if (!match) return null;
|
|
4064
|
+
return new InstagramHighlightsExtractor({
|
|
4065
|
+
...opts,
|
|
4066
|
+
url,
|
|
4067
|
+
match
|
|
4068
|
+
});
|
|
4069
|
+
}
|
|
4070
|
+
async *posts() {
|
|
4071
|
+
const screenName = (this.groups[0] ?? "").replace(/^\//, "");
|
|
4072
|
+
const uid = await this.api.userId(screenName);
|
|
4073
|
+
yield* this.api.highlightsMedia(uid);
|
|
4074
|
+
}
|
|
4075
|
+
};
|
|
4076
|
+
register(InstagramHighlightsExtractor.subcategory, InstagramHighlightsExtractor);
|
|
4077
|
+
//#endregion
|
|
4078
|
+
//#region src/instagram/extractors/post.ts
|
|
4079
|
+
var InstagramPostExtractor = class InstagramPostExtractor extends InstagramExtractor {
|
|
4080
|
+
static subcategory = "post";
|
|
4081
|
+
static pattern = re(/^(?:https?:\/\/)?(?:www\.)?instagram\.com\//, /(?:share(?:\/(?:p|tv|reels?))?|(?:[^/?#]+\/)?(?:p|tv|reels?))\/([^/?#]+)/);
|
|
4082
|
+
subcategory = InstagramPostExtractor.subcategory;
|
|
4083
|
+
constructor(opts) {
|
|
4084
|
+
super(opts);
|
|
4085
|
+
if (opts.match[2] != null || opts.match[3] != null) this.subcategory = "reel";
|
|
4086
|
+
}
|
|
4087
|
+
static fromURL(url, opts) {
|
|
4088
|
+
const match = InstagramPostExtractor.pattern.exec(url);
|
|
4089
|
+
if (!match) return null;
|
|
4090
|
+
return new InstagramPostExtractor({
|
|
4091
|
+
...opts,
|
|
4092
|
+
url,
|
|
4093
|
+
match
|
|
4094
|
+
});
|
|
4095
|
+
}
|
|
4096
|
+
async *posts() {
|
|
4097
|
+
const groups = this.groups;
|
|
4098
|
+
let shortcode = groups[0];
|
|
4099
|
+
if (!shortcode) return;
|
|
4100
|
+
if (groups[1] === "") {
|
|
4101
|
+
this.log.info(`Resolving share link: ${this.url}`);
|
|
4102
|
+
const parts = (await this.request(ensureHttpScheme(this.url), { headers: {
|
|
4103
|
+
"Sec-Fetch-Dest": "empty",
|
|
4104
|
+
"Sec-Fetch-Mode": "navigate",
|
|
4105
|
+
"Sec-Fetch-Site": "same-origin"
|
|
4106
|
+
} })).url?.split("/");
|
|
4107
|
+
shortcode = parts?.[parts.length - 2] ?? shortcode;
|
|
4108
|
+
}
|
|
4109
|
+
this.log.debug(`Fetching post: ${shortcode}`);
|
|
4110
|
+
yield* this.api.media(shortcode);
|
|
4111
|
+
}
|
|
4112
|
+
};
|
|
4113
|
+
register(InstagramPostExtractor.subcategory, InstagramPostExtractor);
|
|
4114
|
+
//#endregion
|
|
4115
|
+
//#region src/instagram/extractors/saved.ts
|
|
4116
|
+
var InstagramSavedExtractor = class InstagramSavedExtractor extends InstagramExtractor {
|
|
4117
|
+
static subcategory = "saved";
|
|
4118
|
+
static pattern = re(BASE_RE, /(\/[^/?#]+)\/saved(?:\/all-posts)?\/?$/);
|
|
4119
|
+
subcategory = InstagramSavedExtractor.subcategory;
|
|
4120
|
+
constructor(opts) {
|
|
4121
|
+
super(opts);
|
|
4122
|
+
}
|
|
4123
|
+
static fromURL(url, opts) {
|
|
4124
|
+
const match = InstagramSavedExtractor.pattern.exec(url);
|
|
4125
|
+
if (!match) return null;
|
|
4126
|
+
return new InstagramSavedExtractor({
|
|
4127
|
+
...opts,
|
|
4128
|
+
url,
|
|
4129
|
+
match
|
|
4130
|
+
});
|
|
4131
|
+
}
|
|
4132
|
+
async *posts() {
|
|
4133
|
+
yield* this.api.userSaved();
|
|
4134
|
+
}
|
|
4135
|
+
};
|
|
4136
|
+
register(InstagramSavedExtractor.subcategory, InstagramSavedExtractor);
|
|
4137
|
+
//#endregion
|
|
4138
|
+
//#region src/instagram/extractors/stories.ts
|
|
4139
|
+
var InstagramStoriesExtractor = class InstagramStoriesExtractor extends InstagramExtractor {
|
|
4140
|
+
static subcategory = "stories";
|
|
4141
|
+
static pattern = /^(?:https?:\/\/)?(?:www\.)?instagram\.com\/(?:stories\/(?:highlights\/(\d+)|([^/?#]+)(?:\/(\d+))?)|\/(aGlnaGxpZ2h0[^?#]+)(?:\?story_media_id=(\d+))?)/;
|
|
4142
|
+
subcategory = InstagramStoriesExtractor.subcategory;
|
|
4143
|
+
highlightId = null;
|
|
4144
|
+
mediaId = null;
|
|
4145
|
+
constructor(opts) {
|
|
4146
|
+
super(opts);
|
|
4147
|
+
const groups = this.groups;
|
|
4148
|
+
const h1 = groups[0];
|
|
4149
|
+
const user = groups[1];
|
|
4150
|
+
const m1 = groups[2];
|
|
4151
|
+
const h2 = groups[3];
|
|
4152
|
+
const m2 = groups[4];
|
|
4153
|
+
if (user) {
|
|
4154
|
+
this.subcategory = "stories";
|
|
4155
|
+
this.highlightId = null;
|
|
4156
|
+
} else {
|
|
4157
|
+
this.subcategory = "highlights";
|
|
4158
|
+
this.highlightId = h1 ? `highlight:${h1}` : `highlight:${Buffer.from(h2 ?? "", "base64").toString("utf-8")}`;
|
|
4159
|
+
}
|
|
4160
|
+
this.mediaId = m1 ?? m2 ?? null;
|
|
4161
|
+
}
|
|
4162
|
+
static fromURL(url, opts) {
|
|
4163
|
+
const match = InstagramStoriesExtractor.pattern.exec(url);
|
|
4164
|
+
if (!match) return null;
|
|
4165
|
+
return new InstagramStoriesExtractor({
|
|
4166
|
+
...opts,
|
|
4167
|
+
url,
|
|
4168
|
+
match
|
|
4169
|
+
});
|
|
4170
|
+
}
|
|
4171
|
+
async *posts() {
|
|
4172
|
+
const reelId = this.highlightId ? this.highlightId : await this.api.userId((this.groups[1] ?? "").toString());
|
|
4173
|
+
const reels = await this.api.reelsMedia([reelId]);
|
|
4174
|
+
if (!reels.length) return;
|
|
4175
|
+
if (this.mediaId) {
|
|
4176
|
+
const reel = reels[0];
|
|
4177
|
+
for (const item of reel.items ?? []) if (item.pk === this.mediaId) {
|
|
4178
|
+
reel.items = [item];
|
|
4179
|
+
break;
|
|
4180
|
+
}
|
|
4181
|
+
yield reel;
|
|
4182
|
+
return;
|
|
4183
|
+
}
|
|
4184
|
+
if (this._cfg("split", false)) {
|
|
4185
|
+
const reel = reels[0];
|
|
4186
|
+
for (const item of reel.items ?? []) {
|
|
4187
|
+
const copy = { ...reel };
|
|
4188
|
+
copy.items = [item];
|
|
4189
|
+
yield copy;
|
|
4190
|
+
}
|
|
4191
|
+
} else yield* reels;
|
|
4192
|
+
}
|
|
4193
|
+
};
|
|
4194
|
+
register(InstagramStoriesExtractor.subcategory, InstagramStoriesExtractor);
|
|
4195
|
+
//#endregion
|
|
4196
|
+
//#region src/instagram/extractors/tag.ts
|
|
4197
|
+
var InstagramTagExtractor = class InstagramTagExtractor extends InstagramExtractor {
|
|
4198
|
+
static subcategory = "tag";
|
|
4199
|
+
static pattern = re(BASE_RE, /\/explore\/tags\/([^/?#]+)/);
|
|
4200
|
+
subcategory = InstagramTagExtractor.subcategory;
|
|
4201
|
+
constructor(opts) {
|
|
4202
|
+
super(opts);
|
|
4203
|
+
}
|
|
4204
|
+
static fromURL(url, opts) {
|
|
4205
|
+
const match = InstagramTagExtractor.pattern.exec(url);
|
|
4206
|
+
if (!match) return null;
|
|
4207
|
+
return new InstagramTagExtractor({
|
|
4208
|
+
...opts,
|
|
4209
|
+
url,
|
|
4210
|
+
match
|
|
4211
|
+
});
|
|
4212
|
+
}
|
|
4213
|
+
async metadata() {
|
|
4214
|
+
const tag = this.groups[0] ?? "";
|
|
4215
|
+
return { tag: decodeURIComponent(tag) };
|
|
4216
|
+
}
|
|
4217
|
+
async *posts() {
|
|
4218
|
+
const tag = this.groups[0] ?? "";
|
|
4219
|
+
yield* this.api.tagsMedia(decodeURIComponent(tag));
|
|
4220
|
+
}
|
|
4221
|
+
};
|
|
4222
|
+
register(InstagramTagExtractor.subcategory, InstagramTagExtractor);
|
|
4223
|
+
//#endregion
|
|
4224
|
+
//#region src/instagram/extractors/user.ts
|
|
4225
|
+
var InstagramUserExtractor = class InstagramUserExtractor extends InstagramExtractor {
|
|
4226
|
+
static subcategory = "user";
|
|
4227
|
+
static pattern = re(BASE_RE, /(\/[^/?#]+)\/?(?:$|[?#])/);
|
|
4228
|
+
subcategory = InstagramUserExtractor.subcategory;
|
|
4229
|
+
constructor(opts) {
|
|
4230
|
+
super(opts);
|
|
4231
|
+
}
|
|
4232
|
+
static fromURL(url, opts) {
|
|
4233
|
+
const match = InstagramUserExtractor.pattern.exec(url);
|
|
4234
|
+
if (!match) return null;
|
|
4235
|
+
return new InstagramUserExtractor({
|
|
4236
|
+
...opts,
|
|
4237
|
+
url,
|
|
4238
|
+
match
|
|
4239
|
+
});
|
|
4240
|
+
}
|
|
4241
|
+
async *items() {
|
|
4242
|
+
await this.login();
|
|
4243
|
+
const userPath = this.groups[0] ?? "/";
|
|
4244
|
+
const base = `${this.root}${userPath}/`;
|
|
4245
|
+
const storiesUrl = `${this.root}/stories/${userPath.slice(1)}/`;
|
|
4246
|
+
const include = this._cfg("include", ["posts"]);
|
|
4247
|
+
const categories = include === "all" ? [
|
|
4248
|
+
"posts",
|
|
4249
|
+
"reels",
|
|
4250
|
+
"tagged",
|
|
4251
|
+
"stories",
|
|
4252
|
+
"highlights",
|
|
4253
|
+
"info",
|
|
4254
|
+
"avatar"
|
|
4255
|
+
] : typeof include === "string" ? include.replace(/\s+/g, "").split(",") : include;
|
|
4256
|
+
const urls = {
|
|
4257
|
+
info: `${base}info/`,
|
|
4258
|
+
avatar: `${base}avatar/`,
|
|
4259
|
+
stories: storiesUrl,
|
|
4260
|
+
highlights: `${base}highlights/`,
|
|
4261
|
+
posts: `${base}posts/`,
|
|
4262
|
+
reels: `${base}reels/`,
|
|
4263
|
+
tagged: `${base}tagged/`
|
|
4264
|
+
};
|
|
4265
|
+
for (const cat of categories) {
|
|
4266
|
+
const cls = get(cat);
|
|
4267
|
+
const url = urls[cat];
|
|
4268
|
+
if (cls && url) yield queue(url, { _extractor: cls });
|
|
4269
|
+
else this.log.warn(`Invalid include '${cat}'`);
|
|
4270
|
+
}
|
|
4271
|
+
}
|
|
4272
|
+
async *posts() {}
|
|
4273
|
+
};
|
|
4274
|
+
register(InstagramUserExtractor.subcategory, InstagramUserExtractor);
|
|
4275
|
+
//#endregion
|
|
4276
|
+
//#region src/config.ts
|
|
4277
|
+
var ConfigManager = class {
|
|
4278
|
+
data;
|
|
4279
|
+
constructor(data = {}) {
|
|
4280
|
+
this.data = data;
|
|
4281
|
+
}
|
|
4282
|
+
/**
|
|
4283
|
+
* Read a value at a dot-path like ``'extractor.instagram.videos'``.
|
|
4284
|
+
* Returns ``undefined`` when the path doesn't exist.
|
|
4285
|
+
*/
|
|
4286
|
+
get(path, defaultValue) {
|
|
4287
|
+
const keys = path.split(".");
|
|
4288
|
+
let node = this.data;
|
|
4289
|
+
for (const key of keys) {
|
|
4290
|
+
if (node == null || typeof node !== "object" || Array.isArray(node)) return defaultValue;
|
|
4291
|
+
node = node[key];
|
|
4292
|
+
}
|
|
4293
|
+
if (node === void 0) return defaultValue;
|
|
4294
|
+
return node;
|
|
4295
|
+
}
|
|
4296
|
+
/**
|
|
4297
|
+
* Interpolate a config key through a hierarchy of paths.
|
|
4298
|
+
*/
|
|
4299
|
+
interpolate(cfgPath, key, defaultVal) {
|
|
4300
|
+
let node = this.data;
|
|
4301
|
+
for (let i = 0; i < cfgPath.length; i++) {
|
|
4302
|
+
if (node != null && typeof node === "object" && !Array.isArray(node)) {
|
|
4303
|
+
const v = node[key];
|
|
4304
|
+
if (v !== void 0) return v;
|
|
4305
|
+
}
|
|
4306
|
+
if (node == null || typeof node !== "object" || Array.isArray(node)) break;
|
|
4307
|
+
node = node[cfgPath[i]];
|
|
4308
|
+
}
|
|
4309
|
+
return defaultVal;
|
|
4310
|
+
}
|
|
4311
|
+
/**
|
|
4312
|
+
* Mutate the config at a given dot-path.
|
|
4313
|
+
*/
|
|
4314
|
+
set(path, value) {
|
|
4315
|
+
const keys = path.split(".");
|
|
4316
|
+
let node = this.data;
|
|
4317
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
4318
|
+
const key = keys[i];
|
|
4319
|
+
let child = node[key];
|
|
4320
|
+
if (child == null || typeof child !== "object" || Array.isArray(child)) {
|
|
4321
|
+
child = {};
|
|
4322
|
+
node[key] = child;
|
|
4323
|
+
}
|
|
4324
|
+
node = child;
|
|
4325
|
+
}
|
|
4326
|
+
node[keys[keys.length - 1]] = value;
|
|
4327
|
+
}
|
|
4328
|
+
};
|
|
4329
|
+
//#endregion
|
|
4330
|
+
//#region src/cli/options.ts
|
|
4331
|
+
function addSharedOptions(cmd) {
|
|
4332
|
+
return cmd.option("--sessionid <cookie>", "Instagram sessionid cookie value (from browser)", process.env.INSTAGRAM_SESSIONID).option("--cookies <string>", "Full Cookie header string from browser", process.env.INSTAGRAM_COOKIES).option("-o, --output <dir>", "Output directory", "./data").option("--videos <mode>", "Download videos: true, false, or merged (yt-dlp)", "true").option("--previews <types>", "Download only previews: video,audio (comma-separated)").option("--audio", "Download standalone audio tracks", false).option("--max-posts <n>", "Maximum number of posts to download", Number.parseInt).option("--cursor <cursor>", "Resume from pagination cursor").option("--order-posts <order>", "Post ordering: asc, desc, id, id_asc, id_desc").option("--order-files <order>", "File ordering: r, d (reverse), or empty for natural order").option("--static-videos", "Download static video cover images instead of actual videos", false).option("--no-static-videos", "Do not force static video covers").option("--api <backend>", "API backend: rest (default) or graphql", "rest").option("-v, --verbose", "Verbose debug output", false).option("--include <list>", "For user: comma-separated sub-extractors (posts,reels,tagged,stories,highlights,info,avatar)", "posts").option("--split", "For stories: split each frame into a separate post", false).option("-i, --info", "Print structured post info to terminal (no download)", false);
|
|
4333
|
+
}
|
|
4334
|
+
function buildConfig(opts) {
|
|
4335
|
+
const config = new ConfigManager();
|
|
4336
|
+
const ig = {};
|
|
4337
|
+
if (opts.videos) ig.videos = opts.videos;
|
|
4338
|
+
if (opts.previews) ig.previews = opts.previews.split(",");
|
|
4339
|
+
if (opts.audio) ig.audio = true;
|
|
4340
|
+
if (opts.maxPosts) ig["max-posts"] = opts.maxPosts;
|
|
4341
|
+
if (opts.cursor) ig.cursor = opts.cursor;
|
|
4342
|
+
if (opts.orderPosts) ig["order-posts"] = opts.orderPosts;
|
|
4343
|
+
if (opts.orderFiles) ig["order-files"] = opts.orderFiles;
|
|
4344
|
+
if (opts.staticVideos) ig["static-videos"] = true;
|
|
4345
|
+
if (opts.api) ig.api = opts.api;
|
|
4346
|
+
if (opts.include) ig.include = opts.include;
|
|
4347
|
+
if (opts.split) ig.split = true;
|
|
4348
|
+
if (Object.keys(ig).length > 0) config.set("extractor.instagram", ig);
|
|
4349
|
+
return config;
|
|
4350
|
+
}
|
|
4351
|
+
//#endregion
|
|
4352
|
+
//#region src/core/format.ts
|
|
4353
|
+
/** Shared ANSI formatting and display utilities. */
|
|
4354
|
+
function formatBytes(bytes) {
|
|
4355
|
+
if (bytes === 0) return "0 B";
|
|
4356
|
+
const units = [
|
|
4357
|
+
"B",
|
|
4358
|
+
"KB",
|
|
4359
|
+
"MB",
|
|
4360
|
+
"GB"
|
|
4361
|
+
];
|
|
4362
|
+
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
|
|
4363
|
+
return `${(bytes / 1024 ** i).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
|
|
4364
|
+
}
|
|
4365
|
+
const BOLD = "\x1B[1m";
|
|
4366
|
+
const DIM = "\x1B[2m";
|
|
4367
|
+
const CYAN = "\x1B[36m";
|
|
4368
|
+
const GREEN = "\x1B[32m";
|
|
4369
|
+
const YELLOW = "\x1B[33m";
|
|
4370
|
+
const RESET = "\x1B[0m";
|
|
4371
|
+
function b(s) {
|
|
4372
|
+
return `${BOLD}${s}${RESET}`;
|
|
4373
|
+
}
|
|
4374
|
+
function dim(s) {
|
|
4375
|
+
return `${DIM}${s}${RESET}`;
|
|
4376
|
+
}
|
|
4377
|
+
function c(s) {
|
|
4378
|
+
return `${CYAN}${s}${RESET}`;
|
|
4379
|
+
}
|
|
4380
|
+
function g(s) {
|
|
4381
|
+
return `${GREEN}${s}${RESET}`;
|
|
4382
|
+
}
|
|
4383
|
+
const _YELLOW = YELLOW;
|
|
4384
|
+
const _RESET = RESET;
|
|
4385
|
+
function pad(s, n) {
|
|
4386
|
+
return s.length >= n ? s : s + " ".repeat(n - s.length);
|
|
4387
|
+
}
|
|
4388
|
+
//#endregion
|
|
4389
|
+
//#region src/core/job.ts
|
|
4390
|
+
var Job = class {
|
|
4391
|
+
extractor;
|
|
4392
|
+
status = 0;
|
|
4393
|
+
constructor(extractor) {
|
|
4394
|
+
this.extractor = extractor;
|
|
4395
|
+
}
|
|
4396
|
+
/** Main entry point. Dispatches every yielded message. */
|
|
4397
|
+
async run() {
|
|
4398
|
+
this.extractor.log.info(`Starting ${this.extractor.category}/${this.extractor.subcategory} — ${this.extractor.url}`);
|
|
4399
|
+
await this.extractor.initialize();
|
|
4400
|
+
for await (const msg of this.extractor) switch (msg.type) {
|
|
4401
|
+
case "directory":
|
|
4402
|
+
await this.handleDirectory(msg);
|
|
4403
|
+
break;
|
|
4404
|
+
case "url":
|
|
4405
|
+
await this.handleUrl(msg);
|
|
4406
|
+
break;
|
|
4407
|
+
case "queue":
|
|
4408
|
+
await this.handleQueue(msg);
|
|
4409
|
+
break;
|
|
4410
|
+
}
|
|
4411
|
+
this._report();
|
|
4412
|
+
return this.status;
|
|
4413
|
+
}
|
|
4414
|
+
/** Override in subclasses to print a summary. */
|
|
4415
|
+
_report() {}
|
|
4416
|
+
};
|
|
4417
|
+
//#endregion
|
|
4418
|
+
//#region src/core/download-job.ts
|
|
4419
|
+
var DownloadJob = class DownloadJob extends Job {
|
|
4420
|
+
/** Base output directory (prepended to all paths). */
|
|
4421
|
+
basePath = "";
|
|
4422
|
+
/** Current target directory metadata (set by directory messages). */
|
|
4423
|
+
_currentDir = {};
|
|
4424
|
+
/** In-memory archive keyed by archive format. */
|
|
4425
|
+
archive = /* @__PURE__ */ new Map();
|
|
4426
|
+
_archiveFmts = /* @__PURE__ */ new Map();
|
|
4427
|
+
_postCount = 0;
|
|
4428
|
+
_fileCount = 0;
|
|
4429
|
+
_downloadedBytes = 0;
|
|
4430
|
+
_skippedCount = 0;
|
|
4431
|
+
registerArchive(category, format) {
|
|
4432
|
+
this._archiveFmts.set(category, format);
|
|
4433
|
+
}
|
|
4434
|
+
_interp(fmt, meta) {
|
|
4435
|
+
return fmt.replace(/\{(\w+)\}/g, (_, key) => {
|
|
4436
|
+
const v = meta[key];
|
|
4437
|
+
return v == null ? "" : String(v);
|
|
4438
|
+
});
|
|
4439
|
+
}
|
|
4440
|
+
_isArchived(meta) {
|
|
4441
|
+
const cat = meta.category ?? this.extractor.category;
|
|
4442
|
+
const fmt = this._archiveFmts.get(cat) ?? "{media_id}";
|
|
4443
|
+
const key = this._interp(fmt, meta);
|
|
4444
|
+
return !!this.archive.get(cat)?.has(key);
|
|
4445
|
+
}
|
|
4446
|
+
_archive(meta) {
|
|
4447
|
+
const cat = meta.category ?? this.extractor.category;
|
|
4448
|
+
const fmt = this._archiveFmts.get(cat) ?? "{media_id}";
|
|
4449
|
+
const key = this._interp(fmt, meta);
|
|
4450
|
+
let set = this.archive.get(cat);
|
|
4451
|
+
if (!set) {
|
|
4452
|
+
set = /* @__PURE__ */ new Set();
|
|
4453
|
+
this.archive.set(cat, set);
|
|
4454
|
+
}
|
|
4455
|
+
set.add(key);
|
|
4456
|
+
}
|
|
4457
|
+
async handleDirectory(msg) {
|
|
4458
|
+
this._currentDir = { ...msg.metadata };
|
|
4459
|
+
this._postCount++;
|
|
4460
|
+
const dirPath = this.basePath ? `${this.basePath}/${this._buildDirPath(msg.metadata)}` : this._buildDirPath(msg.metadata);
|
|
4461
|
+
await this.extractor.storage.mkdir(dirPath);
|
|
4462
|
+
this.extractor.log.info(`#${this._postCount} ${msg.metadata.username ?? "?"}/${msg.metadata.post_shortcode ?? "?"} → ${dirPath}/`);
|
|
4463
|
+
}
|
|
4464
|
+
async handleUrl(msg) {
|
|
4465
|
+
const meta = {
|
|
4466
|
+
...this._currentDir,
|
|
4467
|
+
...msg.metadata
|
|
4468
|
+
};
|
|
4469
|
+
if (this._isArchived(meta)) {
|
|
4470
|
+
this._skippedCount++;
|
|
4471
|
+
return;
|
|
4472
|
+
}
|
|
4473
|
+
const filename = this._buildFilename(meta);
|
|
4474
|
+
const fullPath = `${this.basePath ? `${this.basePath}/${this._buildDirPath(meta)}` : this._buildDirPath(meta)}/${filename}`;
|
|
4475
|
+
try {
|
|
4476
|
+
const resp = await this.extractor.http.request({
|
|
4477
|
+
url: msg.url,
|
|
4478
|
+
method: "GET",
|
|
4479
|
+
responseType: "arraybuffer"
|
|
4480
|
+
});
|
|
4481
|
+
let data;
|
|
4482
|
+
if (resp.data instanceof Uint8Array) data = resp.data;
|
|
4483
|
+
else if (resp.data instanceof ArrayBuffer) data = new Uint8Array(resp.data);
|
|
4484
|
+
else if (typeof resp.data === "string") data = resp.data;
|
|
4485
|
+
else data = JSON.stringify(resp.data);
|
|
4486
|
+
await this.extractor.storage.write(fullPath, data);
|
|
4487
|
+
this._fileCount++;
|
|
4488
|
+
const size = data instanceof Uint8Array ? data.byteLength : data.length;
|
|
4489
|
+
this._downloadedBytes += size;
|
|
4490
|
+
this.extractor.log.info(` └─ ${filename} (${formatBytes(size)})`);
|
|
4491
|
+
this._archive(meta);
|
|
4492
|
+
} catch (err) {
|
|
4493
|
+
this.extractor.log.error(`Failed to download ${filename}: ${String(err)}`);
|
|
4494
|
+
this.status |= 4;
|
|
4495
|
+
}
|
|
4496
|
+
}
|
|
4497
|
+
async handleQueue(msg) {
|
|
4498
|
+
const meta = {
|
|
4499
|
+
...this._currentDir,
|
|
4500
|
+
...msg.metadata
|
|
4501
|
+
};
|
|
4502
|
+
const extrClass = meta._extractor;
|
|
4503
|
+
if (!extrClass || typeof extrClass !== "object") return;
|
|
4504
|
+
const cls = extrClass;
|
|
4505
|
+
const match = cls.pattern.exec(msg.url);
|
|
4506
|
+
if (!match) return;
|
|
4507
|
+
const parentExtr = this.extractor;
|
|
4508
|
+
const childJob = new DownloadJob(Reflect.construct(cls, [{
|
|
4509
|
+
url: msg.url,
|
|
4510
|
+
match,
|
|
4511
|
+
config: parentExtr.config,
|
|
4512
|
+
http: parentExtr.http,
|
|
4513
|
+
storage: parentExtr.storage,
|
|
4514
|
+
log: parentExtr.log
|
|
4515
|
+
}]));
|
|
4516
|
+
childJob.basePath = this.basePath;
|
|
4517
|
+
childJob._currentDir = meta;
|
|
4518
|
+
for (const [cat, set] of this.archive) childJob.archive.set(cat, new Set(set));
|
|
4519
|
+
for (const [cat, fmt] of this._archiveFmts) childJob._archiveFmts.set(cat, fmt);
|
|
4520
|
+
const childStatus = await childJob.run();
|
|
4521
|
+
this.status |= childStatus;
|
|
4522
|
+
for (const [cat, set] of childJob.archive) {
|
|
4523
|
+
const mine = this.archive.get(cat);
|
|
4524
|
+
if (mine) for (const k of set) mine.add(k);
|
|
4525
|
+
else this.archive.set(cat, set);
|
|
4526
|
+
}
|
|
4527
|
+
}
|
|
4528
|
+
_report() {
|
|
4529
|
+
const log = this.extractor.log;
|
|
4530
|
+
log.info(`Done — ${this._postCount} post(s), ${this._fileCount} file(s) downloaded (${formatBytes(this._downloadedBytes)})`);
|
|
4531
|
+
if (this._skippedCount > 0) log.info(` ${this._skippedCount} file(s) skipped (already archived)`);
|
|
4532
|
+
}
|
|
4533
|
+
_buildDirPath(meta) {
|
|
4534
|
+
return `${meta.category ?? this.extractor.category}/${meta.username ?? "_"}`;
|
|
4535
|
+
}
|
|
4536
|
+
_buildFilename(meta) {
|
|
4537
|
+
const mid = meta.media_id ?? "0";
|
|
4538
|
+
const ext = meta.extension ?? "jpg";
|
|
4539
|
+
return `${mid}${meta.num ? `_${meta.num}` : ""}.${ext}`;
|
|
4540
|
+
}
|
|
4541
|
+
};
|
|
4542
|
+
//#endregion
|
|
4543
|
+
//#region src/core/print-job.ts
|
|
4544
|
+
var PrintJob = class PrintJob extends Job {
|
|
4545
|
+
_currentDir = {};
|
|
4546
|
+
_files = [];
|
|
4547
|
+
_postCount = 0;
|
|
4548
|
+
_fileCount = 0;
|
|
4549
|
+
_width;
|
|
4550
|
+
constructor(extractor) {
|
|
4551
|
+
super(extractor);
|
|
4552
|
+
this._width = Math.min(process.stdout.columns ?? 80, 100);
|
|
4553
|
+
}
|
|
4554
|
+
async handleDirectory(msg) {
|
|
4555
|
+
if (this._postCount > 0) this._flushPost();
|
|
4556
|
+
this._currentDir = { ...msg.metadata };
|
|
4557
|
+
this._postCount++;
|
|
4558
|
+
this._files = [];
|
|
4559
|
+
}
|
|
4560
|
+
async handleUrl(msg) {
|
|
4561
|
+
const meta = {
|
|
4562
|
+
...this._currentDir,
|
|
4563
|
+
...msg.metadata
|
|
4564
|
+
};
|
|
4565
|
+
this._fileCount++;
|
|
4566
|
+
const ext = meta.extension ?? "jpg";
|
|
4567
|
+
const mid = meta.media_id ?? "?";
|
|
4568
|
+
this._files.push({
|
|
4569
|
+
num: meta.num ?? this._files.length + 1,
|
|
4570
|
+
filename: `${mid}.${ext}`,
|
|
4571
|
+
width: meta.width ?? 0,
|
|
4572
|
+
height: meta.height ?? 0,
|
|
4573
|
+
videoUrl: meta.video_url ?? null,
|
|
4574
|
+
audioUrl: meta.audio_url ?? null
|
|
4575
|
+
});
|
|
4576
|
+
}
|
|
4577
|
+
async handleQueue(msg) {
|
|
4578
|
+
if (this._files.length > 0 || this._postCount > 0) this._flushPost();
|
|
4579
|
+
this._postCount = 0;
|
|
4580
|
+
this._files = [];
|
|
4581
|
+
const extrClass = {
|
|
4582
|
+
...this._currentDir,
|
|
4583
|
+
...msg.metadata
|
|
4584
|
+
}._extractor;
|
|
4585
|
+
if (!extrClass || typeof extrClass !== "object") return;
|
|
4586
|
+
const cls = extrClass;
|
|
4587
|
+
const match = cls.pattern.exec(msg.url);
|
|
4588
|
+
if (!match) return;
|
|
4589
|
+
const parentExtr = this.extractor;
|
|
4590
|
+
const childJob = new PrintJob(Reflect.construct(cls, [{
|
|
4591
|
+
url: msg.url,
|
|
4592
|
+
match,
|
|
4593
|
+
config: parentExtr.config,
|
|
4594
|
+
http: parentExtr.http,
|
|
4595
|
+
storage: parentExtr.storage,
|
|
4596
|
+
log: parentExtr.log
|
|
4597
|
+
}]));
|
|
4598
|
+
const childStatus = await childJob.run();
|
|
4599
|
+
this.status |= childStatus;
|
|
4600
|
+
this._postCount += childJob._postCount;
|
|
4601
|
+
this._fileCount += childJob._fileCount;
|
|
4602
|
+
}
|
|
4603
|
+
_flushPost() {
|
|
4604
|
+
const m = this._currentDir;
|
|
4605
|
+
if (Object.keys(m).length === 0) return;
|
|
4606
|
+
const w = this._width;
|
|
4607
|
+
const labelW = 14;
|
|
4608
|
+
const shortcode = m.post_shortcode ?? "?";
|
|
4609
|
+
const header = ` Post #${this._postCount}: ${shortcode} `;
|
|
4610
|
+
const padTotal = w - 2 - header.length;
|
|
4611
|
+
const padL = Math.floor(padTotal / 2);
|
|
4612
|
+
const padR = padTotal - padL;
|
|
4613
|
+
process.stdout.write(`\n${dim("┌")}${"─".repeat(padL)}${b(header)}${"─".repeat(padR)}${dim("┐")}\n`);
|
|
4614
|
+
const row = (label, value, color) => {
|
|
4615
|
+
const colored = typeof color === "function" ? color(value) : color ? `${color}${value}${_RESET}` : value;
|
|
4616
|
+
process.stdout.write(` ${dim("│")} ${c(pad(label, labelW))} ${colored}\n`);
|
|
4617
|
+
};
|
|
4618
|
+
const username = m.username ?? "?";
|
|
4619
|
+
const fullname = m.fullname ?? "";
|
|
4620
|
+
row("Author:", fullname ? `${username} (${fullname})` : username, g);
|
|
4621
|
+
row("Date:", m.date ?? m.post_date ?? "?");
|
|
4622
|
+
row("Likes:", `${typeof m.likes === "number" ? m.likes.toLocaleString() : "?"} | Liked: ${m.liked ? "yes" : "no"}`);
|
|
4623
|
+
row("Type:", `${m.type ?? "?"} (${this._files.length} files)`);
|
|
4624
|
+
row("URL:", m.post_url ?? "?");
|
|
4625
|
+
const desc = m.description ?? "";
|
|
4626
|
+
if (desc) {
|
|
4627
|
+
process.stdout.write(` ${dim("│")}\n`);
|
|
4628
|
+
process.stdout.write(` ${dim("│")} ${b("Description:")}\n`);
|
|
4629
|
+
for (const line of desc.split("\n")) for (const wl of this._wrap(line, w - 8)) process.stdout.write(` ${dim("│")} ${dim(wl)}\n`);
|
|
4630
|
+
}
|
|
4631
|
+
const tags = m.tags;
|
|
4632
|
+
if (tags && tags.length > 0) {
|
|
4633
|
+
process.stdout.write(` ${dim("│")}\n`);
|
|
4634
|
+
process.stdout.write(` ${dim("│")} ${b("Tags:")} ${dim(tags.map((t) => `#${t}`).join(" "))}\n`);
|
|
4635
|
+
}
|
|
4636
|
+
const locName = m.location_slug ?? "";
|
|
4637
|
+
const locId = m.location_id ?? "";
|
|
4638
|
+
if (locName || locId) row("Location:", locId ? `${locName} (ID: ${locId})` : locName);
|
|
4639
|
+
const coauthors = m.coauthors;
|
|
4640
|
+
if (coauthors && coauthors.length > 0) row("Co-authors:", coauthors.map((c) => c.full_name ? `${c.username} (${c.full_name})` : c.username).join(", "));
|
|
4641
|
+
const pinned = m.pinned;
|
|
4642
|
+
if (pinned && pinned.length > 0) row("Pinned:", pinned.join(", "));
|
|
4643
|
+
const expires = m.expires;
|
|
4644
|
+
if (expires) row("Expires:", expires, _YELLOW);
|
|
4645
|
+
const hlTitle = m.highlight_title;
|
|
4646
|
+
if (hlTitle) row("Highlight:", hlTitle);
|
|
4647
|
+
const taggedUser = m.tagged_username ?? "";
|
|
4648
|
+
if (taggedUser) {
|
|
4649
|
+
const taggedFull = m.tagged_full_name ?? "";
|
|
4650
|
+
row("Tagged by:", taggedFull ? `${taggedUser} (${taggedFull})` : taggedUser);
|
|
4651
|
+
}
|
|
4652
|
+
if (this._files.length > 0) {
|
|
4653
|
+
process.stdout.write(` ${dim("│")}\n`);
|
|
4654
|
+
process.stdout.write(` ${dim("│")} ${b(`Media (${this._files.length} files):`)}\n`);
|
|
4655
|
+
const maxNumW = String(this._files.length).length;
|
|
4656
|
+
const maxFileW = Math.max(...this._files.map((f) => f.filename.length));
|
|
4657
|
+
const dimW = Math.min(maxFileW, 40);
|
|
4658
|
+
for (const f of this._files) {
|
|
4659
|
+
const numStr = `[${String(f.num).padStart(maxNumW)}]`;
|
|
4660
|
+
const dimStr = f.filename.length > 40 ? `${f.filename.slice(0, 37)}...` : pad(f.filename, dimW);
|
|
4661
|
+
const res = f.width ? `${f.width}x${f.height}` : "?x?";
|
|
4662
|
+
const badges = [];
|
|
4663
|
+
if (f.videoUrl) badges.push("video");
|
|
4664
|
+
if (f.audioUrl) badges.push("audio");
|
|
4665
|
+
let line = ` ${dim("│")} ${g(numStr)} ${dimStr} ${res}`;
|
|
4666
|
+
if (badges.length > 0) line += ` ${_YELLOW}(${badges.join("+")})${_RESET}`;
|
|
4667
|
+
process.stdout.write(`${line}\n`);
|
|
4668
|
+
}
|
|
4669
|
+
}
|
|
4670
|
+
process.stdout.write(` ${dim("└")}${"─".repeat(w - 2)}${dim("┘")}\n`);
|
|
4671
|
+
}
|
|
4672
|
+
_wrap(text, maxLen) {
|
|
4673
|
+
if (text.length <= maxLen) return [text];
|
|
4674
|
+
const lines = [];
|
|
4675
|
+
let remaining = text;
|
|
4676
|
+
while (remaining.length > maxLen) {
|
|
4677
|
+
let cut = maxLen;
|
|
4678
|
+
while (cut > 0 && remaining[cut] !== " ") cut--;
|
|
4679
|
+
if (cut === 0) cut = maxLen;
|
|
4680
|
+
lines.push(remaining.slice(0, cut).trimEnd());
|
|
4681
|
+
remaining = remaining.slice(cut).trimStart();
|
|
4682
|
+
}
|
|
4683
|
+
if (remaining) lines.push(remaining);
|
|
4684
|
+
return lines;
|
|
4685
|
+
}
|
|
4686
|
+
_report() {
|
|
4687
|
+
this._flushPost();
|
|
4688
|
+
process.stdout.write(`\n${dim("──")} ${b("Summary")} ${dim("───")}\n`);
|
|
4689
|
+
process.stdout.write(` Posts: ${g(String(this._postCount))}\n`);
|
|
4690
|
+
process.stdout.write(` Files: ${g(String(this._fileCount))}\n`);
|
|
4691
|
+
process.stdout.write(`\n`);
|
|
4692
|
+
}
|
|
4693
|
+
};
|
|
4694
|
+
//#endregion
|
|
4695
|
+
//#region src/fetcher.ts
|
|
4696
|
+
var fetcher_exports = /* @__PURE__ */ __exportAll({
|
|
4697
|
+
buildUrl: () => buildUrl,
|
|
4698
|
+
createFetchHttpClient: () => createFetchHttpClient,
|
|
4699
|
+
extractCsrf: () => extractCsrf,
|
|
4700
|
+
headersToRecord: () => headersToRecord,
|
|
4701
|
+
mergeCookie: () => mergeCookie,
|
|
4702
|
+
readBody: () => readBody,
|
|
4703
|
+
serializeBody: () => serializeBody
|
|
4704
|
+
});
|
|
4705
|
+
/** Build URL with query params appended as URLSearchParams. */
|
|
4706
|
+
function buildUrl(base, params) {
|
|
4707
|
+
if (!params) return base;
|
|
4708
|
+
const cleaned = {};
|
|
4709
|
+
for (const [k, v] of Object.entries(params)) if (v != null) cleaned[k] = String(v);
|
|
4710
|
+
const entries = Object.entries(cleaned);
|
|
4711
|
+
if (entries.length === 0) return base;
|
|
4712
|
+
const qs = new URLSearchParams(entries).toString();
|
|
4713
|
+
return `${base}${base.includes("?") ? "&" : "?"}${qs}`;
|
|
4714
|
+
}
|
|
4715
|
+
/** Merge cookie strings with append semantics: a=1 + b=2 → a=1; b=2 */
|
|
4716
|
+
function mergeCookie(base, extra) {
|
|
4717
|
+
if (!base) return extra;
|
|
4718
|
+
return `${base}; ${extra}`;
|
|
4719
|
+
}
|
|
4720
|
+
/** Extract csrftoken value from a Cookie header string. */
|
|
4721
|
+
function extractCsrf(cookies) {
|
|
4722
|
+
return cookies.match(/(?:^|;\s*)csrftoken=([^;]+)/)?.[1] ?? "";
|
|
4723
|
+
}
|
|
4724
|
+
/** Convert fetch Headers to a plain Record. */
|
|
4725
|
+
function headersToRecord(headers) {
|
|
4726
|
+
const rec = {};
|
|
4727
|
+
headers.forEach((v, k) => {
|
|
4728
|
+
rec[k] = v;
|
|
4729
|
+
});
|
|
4730
|
+
return rec;
|
|
4731
|
+
}
|
|
4732
|
+
/** Read response body according to the requested type. */
|
|
4733
|
+
async function readBody(resp, responseType) {
|
|
4734
|
+
switch (responseType) {
|
|
4735
|
+
case "arraybuffer": {
|
|
4736
|
+
const buf = await resp.arrayBuffer();
|
|
4737
|
+
return Buffer.from(buf);
|
|
4738
|
+
}
|
|
4739
|
+
case "text": return resp.text();
|
|
4740
|
+
default: return resp.json();
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
/** Serialize a request body value for fetch. */
|
|
4744
|
+
function serializeBody(data) {
|
|
4745
|
+
if (data == null) return void 0;
|
|
4746
|
+
if (typeof data === "string") return data;
|
|
4747
|
+
if (data instanceof URLSearchParams) return data;
|
|
4748
|
+
return JSON.stringify(data);
|
|
4749
|
+
}
|
|
4750
|
+
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
|
4751
|
+
/**
|
|
4752
|
+
* Create a platform-agnostic HttpClient backed by native ``fetch``.
|
|
4753
|
+
*
|
|
4754
|
+
* Zero dependencies — works in Node.js 18+, browsers, Deno, and Edge.
|
|
4755
|
+
*
|
|
4756
|
+
* @example Plain (no cookies)
|
|
4757
|
+
* ```ts
|
|
4758
|
+
* const http = createFetchHttpClient()
|
|
4759
|
+
* ```
|
|
4760
|
+
*
|
|
4761
|
+
* @example With static cookies (CLI session mode)
|
|
4762
|
+
* ```ts
|
|
4763
|
+
* const http = createFetchHttpClient({ cookie: 'sessionid=abc; csrftoken=xyz' })
|
|
4764
|
+
* ```
|
|
4765
|
+
*
|
|
4766
|
+
* @example With cookie jar (anonymous session)
|
|
4767
|
+
* ```ts
|
|
4768
|
+
* const jar = createCookieJar()
|
|
4769
|
+
* const http = createFetchHttpClient({
|
|
4770
|
+
* cookieProvider: () => jar.getCookieHeader(),
|
|
4771
|
+
* onResponse: (headers) => jar.setFromResponse(headers),
|
|
4772
|
+
* })
|
|
4773
|
+
* ```
|
|
4774
|
+
*/
|
|
4775
|
+
function createFetchHttpClient(opts = {}) {
|
|
4776
|
+
const { cookie, cookieProvider, userAgent = UA, timeout = 3e4, onResponse } = opts;
|
|
4777
|
+
return { async request(config) {
|
|
4778
|
+
const method = config.method ?? "GET";
|
|
4779
|
+
const url = buildUrl(config.url, config.params);
|
|
4780
|
+
const headers = new Headers(config.headers);
|
|
4781
|
+
const reqCookie = cookieProvider?.() ?? cookie;
|
|
4782
|
+
if (reqCookie) {
|
|
4783
|
+
const existing = headers.get("Cookie");
|
|
4784
|
+
headers.set("Cookie", existing ? mergeCookie(reqCookie, existing) : reqCookie);
|
|
4785
|
+
}
|
|
4786
|
+
if (!headers.has("User-Agent")) headers.set("User-Agent", userAgent);
|
|
4787
|
+
const body = serializeBody(config.data);
|
|
4788
|
+
if (typeof body === "string" && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
|
|
4789
|
+
let controller = null;
|
|
4790
|
+
let timer = null;
|
|
4791
|
+
let signal = config.signal ?? null;
|
|
4792
|
+
const timeoutMs = config.timeout ?? timeout;
|
|
4793
|
+
if (!signal) {
|
|
4794
|
+
controller = new AbortController();
|
|
4795
|
+
timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
4796
|
+
signal = controller.signal;
|
|
4797
|
+
}
|
|
4798
|
+
try {
|
|
4799
|
+
const resp = await fetch(url, {
|
|
4800
|
+
method,
|
|
4801
|
+
headers,
|
|
4802
|
+
body,
|
|
4803
|
+
signal
|
|
4804
|
+
});
|
|
4805
|
+
onResponse?.(headersToRecord(resp.headers));
|
|
4806
|
+
const data = await readBody(resp, config.responseType);
|
|
4807
|
+
return {
|
|
4808
|
+
status: resp.status,
|
|
4809
|
+
data,
|
|
4810
|
+
headers: headersToRecord(resp.headers),
|
|
4811
|
+
url: resp.url
|
|
4812
|
+
};
|
|
4813
|
+
} catch (err) {
|
|
4814
|
+
if (controller?.signal.aborted && !config.signal?.aborted) throw new Error(`Request timeout after ${timeoutMs}ms: ${url}`);
|
|
4815
|
+
if (String(err).includes("too many redirect")) throw new Error("Too many redirects — session may be expired or invalid. Export a fresh session from your browser.");
|
|
4816
|
+
throw err;
|
|
4817
|
+
} finally {
|
|
4818
|
+
if (timer) clearTimeout(timer);
|
|
4819
|
+
}
|
|
4820
|
+
} };
|
|
4821
|
+
}
|
|
4822
|
+
//#endregion
|
|
4823
|
+
//#region src/cli/cookies.ts
|
|
4824
|
+
function createCookieJar() {
|
|
4825
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
4826
|
+
let cookieString = "";
|
|
4827
|
+
return {
|
|
4828
|
+
setFromResponse(headers) {
|
|
4829
|
+
const raw = headers["set-cookie"];
|
|
4830
|
+
if (!raw) return;
|
|
4831
|
+
const cookieHeaders = Array.isArray(raw) ? raw : [raw];
|
|
4832
|
+
for (const header of cookieHeaders) {
|
|
4833
|
+
const parts = header.split(";");
|
|
4834
|
+
if (parts.length === 0) continue;
|
|
4835
|
+
const [nameValue] = parts;
|
|
4836
|
+
const eqIdx = nameValue.indexOf("=");
|
|
4837
|
+
if (eqIdx <= 0) continue;
|
|
4838
|
+
const name = nameValue.slice(0, eqIdx).trim();
|
|
4839
|
+
const value = nameValue.slice(eqIdx + 1).trim();
|
|
4840
|
+
if (parts.slice(1).map((s) => s.trim().toLowerCase()).includes("max-age=0")) continue;
|
|
4841
|
+
cookies.set(name, value);
|
|
4842
|
+
}
|
|
4843
|
+
cookieString = Array.from(cookies.entries()).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
4844
|
+
},
|
|
4845
|
+
getCookieHeader() {
|
|
4846
|
+
return cookieString;
|
|
4847
|
+
}
|
|
4848
|
+
};
|
|
4849
|
+
}
|
|
4850
|
+
//#endregion
|
|
4851
|
+
//#region src/cli/adapter.ts
|
|
4852
|
+
/**
|
|
4853
|
+
* Create an HttpClient with a static cookie string (sessionid cookie).
|
|
4854
|
+
*
|
|
4855
|
+
* Used by the CLI when ``--cookies`` or ``--sessionid`` is provided.
|
|
4856
|
+
*/
|
|
4857
|
+
function createHttpClient(sessionId, fullCookies, _logger) {
|
|
4858
|
+
return createFetchHttpClient({ cookie: (fullCookies || (sessionId ? `sessionid=${sessionId}` : null)) ?? void 0 });
|
|
4859
|
+
}
|
|
4860
|
+
/**
|
|
4861
|
+
* Create an HTTP client backed by an in-memory cookie jar.
|
|
4862
|
+
*
|
|
4863
|
+
* Seeds cookies by visiting instagram.com first, then uses those
|
|
4864
|
+
* anonymous cookies for subsequent API calls (like incognito browsing).
|
|
4865
|
+
*
|
|
4866
|
+
* Returns the client + the initial CSRF token extracted from cookies.
|
|
4867
|
+
*/
|
|
4868
|
+
async function createWebClient(logger) {
|
|
4869
|
+
const jar = createCookieJar();
|
|
4870
|
+
logger?.info("Seeding anonymous session (visiting instagram.com)…");
|
|
4871
|
+
const seedResp = await fetch("https://www.instagram.com/", { headers: {
|
|
4872
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
|
4873
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
|
|
4874
|
+
} });
|
|
4875
|
+
const { headersToRecord } = await Promise.resolve().then(() => fetcher_exports);
|
|
4876
|
+
jar.setFromResponse(headersToRecord(seedResp.headers));
|
|
4877
|
+
const cookieCount = jar.getCookieHeader().split(";").length;
|
|
4878
|
+
logger?.debug(` ← ${seedResp.status} — got ${cookieCount} cookies`);
|
|
4879
|
+
const csrfToken = extractCsrf(jar.getCookieHeader());
|
|
4880
|
+
return {
|
|
4881
|
+
http: createFetchHttpClient({
|
|
4882
|
+
cookieProvider: () => jar.getCookieHeader(),
|
|
4883
|
+
onResponse: (headers) => jar.setFromResponse(headers)
|
|
4884
|
+
}),
|
|
4885
|
+
csrfToken
|
|
4886
|
+
};
|
|
4887
|
+
}
|
|
4888
|
+
/** Node.js console-based logger. */
|
|
4889
|
+
function createLogger(verbose) {
|
|
4890
|
+
return {
|
|
4891
|
+
debug(message, ...args) {
|
|
4892
|
+
if (verbose) console.debug(`[debug] ${message}`, ...args);
|
|
4893
|
+
},
|
|
4894
|
+
info(message, ...args) {
|
|
4895
|
+
console.info(`[info] ${message}`, ...args);
|
|
4896
|
+
},
|
|
4897
|
+
warn(message, ...args) {
|
|
4898
|
+
console.warn(`[warn] ${message}`, ...args);
|
|
4899
|
+
},
|
|
4900
|
+
error(message, ...args) {
|
|
4901
|
+
console.error(`[error] ${message}`, ...args);
|
|
4902
|
+
}
|
|
4903
|
+
};
|
|
4904
|
+
}
|
|
4905
|
+
//#endregion
|
|
4906
|
+
//#region src/cli/storage.ts
|
|
4907
|
+
function createStorage() {
|
|
4908
|
+
return {
|
|
4909
|
+
async exists(path) {
|
|
4910
|
+
try {
|
|
4911
|
+
await access(path);
|
|
4912
|
+
return true;
|
|
4913
|
+
} catch {
|
|
4914
|
+
return false;
|
|
4915
|
+
}
|
|
4916
|
+
},
|
|
4917
|
+
async write(path, data) {
|
|
4918
|
+
await mkdir(dirname(path), { recursive: true });
|
|
4919
|
+
await writeFile(path, data);
|
|
4920
|
+
},
|
|
4921
|
+
async mkdir(path) {
|
|
4922
|
+
await mkdir(path, { recursive: true });
|
|
4923
|
+
}
|
|
4924
|
+
};
|
|
4925
|
+
}
|
|
4926
|
+
//#endregion
|
|
4927
|
+
//#region src/cli/runner.ts
|
|
4928
|
+
function resolveExtractor(url) {
|
|
4929
|
+
for (const Cls of [
|
|
4930
|
+
InstagramPostExtractor,
|
|
4931
|
+
InstagramStoriesExtractor,
|
|
4932
|
+
InstagramHighlightsExtractor,
|
|
4933
|
+
InstagramTagExtractor,
|
|
4934
|
+
InstagramSavedExtractor,
|
|
4935
|
+
InstagramUserExtractor
|
|
4936
|
+
]) if (Cls.pattern.test(url)) return Cls;
|
|
4937
|
+
throw new Error(`No extractor matched URL: ${url}. Supported: /p/, /reel/, /{user}/, /stories/, /highlights/, /explore/tags/, /saved/`);
|
|
4938
|
+
}
|
|
4939
|
+
async function runExtractor(url, extrClass, opts) {
|
|
4940
|
+
const config = buildConfig(opts);
|
|
4941
|
+
const log = createLogger(opts.verbose ?? false);
|
|
4942
|
+
let http;
|
|
4943
|
+
let webCsrf;
|
|
4944
|
+
if (opts.cookies) {
|
|
4945
|
+
http = createHttpClient(void 0, opts.cookies, log);
|
|
4946
|
+
webCsrf = extractCsrf(opts.cookies);
|
|
4947
|
+
} else if (opts.sessionid) http = createHttpClient(opts.sessionid, void 0, log);
|
|
4948
|
+
else {
|
|
4949
|
+
const wc = await createWebClient(log);
|
|
4950
|
+
http = wc.http;
|
|
4951
|
+
webCsrf = wc.csrfToken;
|
|
4952
|
+
}
|
|
4953
|
+
const storage = createStorage();
|
|
4954
|
+
const match = extrClass.pattern.exec(url);
|
|
4955
|
+
if (!match) {
|
|
4956
|
+
console.error(`URL did not match expected pattern: ${url}`);
|
|
4957
|
+
process.exit(1);
|
|
4958
|
+
}
|
|
4959
|
+
const extractor = new extrClass({
|
|
4960
|
+
url,
|
|
4961
|
+
match,
|
|
4962
|
+
config,
|
|
4963
|
+
http,
|
|
4964
|
+
storage,
|
|
4965
|
+
log,
|
|
4966
|
+
sessionId: opts.sessionid,
|
|
4967
|
+
csrfToken: webCsrf
|
|
4968
|
+
});
|
|
4969
|
+
if (opts.info) {
|
|
4970
|
+
const job = new PrintJob(extractor);
|
|
4971
|
+
const start = Date.now();
|
|
4972
|
+
try {
|
|
4973
|
+
const status = await job.run();
|
|
4974
|
+
const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
|
|
4975
|
+
if (status !== 0) log.warn(`Finished with status ${status} in ${elapsed}s`);
|
|
4976
|
+
} catch (err) {
|
|
4977
|
+
log.error(String(err));
|
|
4978
|
+
process.exit(1);
|
|
4979
|
+
}
|
|
4980
|
+
return;
|
|
4981
|
+
}
|
|
4982
|
+
const job = new DownloadJob(extractor);
|
|
4983
|
+
job.basePath = opts.output ?? "./data";
|
|
4984
|
+
const start = Date.now();
|
|
4985
|
+
try {
|
|
4986
|
+
const status = await job.run();
|
|
4987
|
+
const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
|
|
4988
|
+
if (status === 0) log.info(`Done in ${elapsed}s`);
|
|
4989
|
+
else log.warn(`Finished with status ${status} in ${elapsed}s`);
|
|
4990
|
+
} catch (err) {
|
|
4991
|
+
log.error(String(err));
|
|
4992
|
+
process.exit(1);
|
|
4993
|
+
}
|
|
4994
|
+
}
|
|
4995
|
+
//#endregion
|
|
4996
|
+
//#region src/cli/index.ts
|
|
4997
|
+
const program = new Command();
|
|
4998
|
+
program.name("gdl-instagram").description("Download images and videos from Instagram.\n\nUses gallery-dl's extraction pipeline — supports posts, reels,\nstories, highlights, tagged posts, saved collections, and more.\n\nRequires a sessionid cookie exported from your browser.\nSet via --sessionid or INSTAGRAM_SESSIONID environment variable.").version(version);
|
|
4999
|
+
addSharedOptions(program.command("dl", { isDefault: true }).argument("[url]", "Instagram URL to download (auto-detects type)").description("Download media from an Instagram URL (auto-detects post/user/stories/…)\n\nExamples:\n gdl-instagram https://www.instagram.com/p/CxAbCdEfGh/\n gdl-instagram https://www.instagram.com/username/ --include=posts,reels\n gdl-instagram https://www.instagram.com/stories/username/").action(async (url, opts) => {
|
|
5000
|
+
if (!url) {
|
|
5001
|
+
program.help();
|
|
5002
|
+
return;
|
|
5003
|
+
}
|
|
5004
|
+
await runExtractor(url, resolveExtractor(url), opts);
|
|
5005
|
+
}));
|
|
5006
|
+
addSharedOptions(program.command("tag <hashtag>").description("Download posts from an Instagram hashtag\n\nExamples:\n gdl-instagram tag cats\n gdl-instagram tag https://www.instagram.com/explore/tags/cats/").action(async (hashtag, opts) => {
|
|
5007
|
+
await runExtractor(hashtag.startsWith("http") ? hashtag : `https://www.instagram.com/explore/tags/${hashtag}/`, InstagramTagExtractor, opts);
|
|
5008
|
+
}));
|
|
5009
|
+
addSharedOptions(program.command("saved").description("Download your saved (bookmarked) posts\n\nRequires authentication via --sessionid.\n\nExamples:\n gdl-instagram saved --sessionid=abc123").action(async (opts) => {
|
|
5010
|
+
await runExtractor("https://www.instagram.com/me/saved/", InstagramSavedExtractor, opts);
|
|
5011
|
+
}));
|
|
5012
|
+
program.parse();
|
|
5013
|
+
//#endregion
|
|
5014
|
+
export {};
|