fast-npm-meta 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,741 @@
1
+ #!/usr/bin/env node
2
+ import process$1 from "node:process";
3
+ import { EventEmitter } from "events";
4
+
5
+ //#region ../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
6
+ function toArr(any) {
7
+ return any == null ? [] : Array.isArray(any) ? any : [any];
8
+ }
9
+ function toVal(out, key, val, opts) {
10
+ var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
11
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
12
+ }
13
+ function mri2(args, opts) {
14
+ args = args || [];
15
+ opts = opts || {};
16
+ var k, arr, arg, name, val, out = { _: [] };
17
+ var i = 0, j = 0, idx = 0, len = args.length;
18
+ const alibi = opts.alias !== void 0;
19
+ const strict = opts.unknown !== void 0;
20
+ const defaults = opts.default !== void 0;
21
+ opts.alias = opts.alias || {};
22
+ opts.string = toArr(opts.string);
23
+ opts.boolean = toArr(opts.boolean);
24
+ if (alibi) for (k in opts.alias) {
25
+ arr = opts.alias[k] = toArr(opts.alias[k]);
26
+ for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
27
+ }
28
+ for (i = opts.boolean.length; i-- > 0;) {
29
+ arr = opts.alias[opts.boolean[i]] || [];
30
+ for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
31
+ }
32
+ for (i = opts.string.length; i-- > 0;) {
33
+ arr = opts.alias[opts.string[i]] || [];
34
+ for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
35
+ }
36
+ if (defaults) for (k in opts.default) {
37
+ name = typeof opts.default[k];
38
+ arr = opts.alias[k] = opts.alias[k] || [];
39
+ if (opts[name] !== void 0) {
40
+ opts[name].push(k);
41
+ for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
42
+ }
43
+ }
44
+ const keys = strict ? Object.keys(opts.alias) : [];
45
+ for (i = 0; i < len; i++) {
46
+ arg = args[i];
47
+ if (arg === "--") {
48
+ out._ = out._.concat(args.slice(++i));
49
+ break;
50
+ }
51
+ for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
52
+ if (j === 0) out._.push(arg);
53
+ else if (arg.substring(j, j + 3) === "no-") {
54
+ name = arg.substring(j + 3);
55
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
56
+ out[name] = false;
57
+ } else {
58
+ for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
59
+ name = arg.substring(j, idx);
60
+ val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
61
+ arr = j === 2 ? [name] : name;
62
+ for (idx = 0; idx < arr.length; idx++) {
63
+ name = arr[idx];
64
+ if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
65
+ toVal(out, name, idx + 1 < arr.length || val, opts);
66
+ }
67
+ }
68
+ }
69
+ if (defaults) {
70
+ for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
71
+ }
72
+ if (alibi) for (k in out) {
73
+ arr = opts.alias[k] || [];
74
+ while (arr.length > 0) out[arr.shift()] = out[k];
75
+ }
76
+ return out;
77
+ }
78
+ const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
79
+ const findAllBrackets = (v) => {
80
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
81
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
82
+ const res = [];
83
+ const parse = (match) => {
84
+ let variadic = false;
85
+ let value = match[1];
86
+ if (value.startsWith("...")) {
87
+ value = value.slice(3);
88
+ variadic = true;
89
+ }
90
+ return {
91
+ required: match[0].startsWith("<"),
92
+ value,
93
+ variadic
94
+ };
95
+ };
96
+ let angledMatch;
97
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
98
+ let squareMatch;
99
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
100
+ return res;
101
+ };
102
+ const getMriOptions = (options) => {
103
+ const result = {
104
+ alias: {},
105
+ boolean: []
106
+ };
107
+ for (const [index, option] of options.entries()) {
108
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
109
+ if (option.isBoolean) if (option.negated) {
110
+ if (!options.some((o, i) => {
111
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
112
+ })) result.boolean.push(option.names[0]);
113
+ } else result.boolean.push(option.names[0]);
114
+ }
115
+ return result;
116
+ };
117
+ const findLongest = (arr) => {
118
+ return arr.sort((a, b) => {
119
+ return a.length > b.length ? -1 : 1;
120
+ })[0];
121
+ };
122
+ const padRight = (str, length) => {
123
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
124
+ };
125
+ const camelcase = (input) => {
126
+ return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
127
+ return p1 + p2.toUpperCase();
128
+ });
129
+ };
130
+ const setDotProp = (obj, keys, val) => {
131
+ let i = 0;
132
+ let length = keys.length;
133
+ let t = obj;
134
+ let x;
135
+ for (; i < length; ++i) {
136
+ x = t[keys[i]];
137
+ t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
138
+ }
139
+ };
140
+ const setByType = (obj, transforms) => {
141
+ for (const key of Object.keys(transforms)) {
142
+ const transform = transforms[key];
143
+ if (transform.shouldTransform) {
144
+ obj[key] = Array.prototype.concat.call([], obj[key]);
145
+ if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
146
+ }
147
+ }
148
+ };
149
+ const getFileName = (input) => {
150
+ const m = /([^\\\/]+)$/.exec(input);
151
+ return m ? m[1] : "";
152
+ };
153
+ const camelcaseOptionName = (name) => {
154
+ return name.split(".").map((v, i) => {
155
+ return i === 0 ? camelcase(v) : v;
156
+ }).join(".");
157
+ };
158
+ var CACError = class extends Error {
159
+ constructor(message) {
160
+ super(message);
161
+ this.name = this.constructor.name;
162
+ if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, this.constructor);
163
+ else this.stack = new Error(message).stack;
164
+ }
165
+ };
166
+ var Option = class {
167
+ constructor(rawName, description, config) {
168
+ this.rawName = rawName;
169
+ this.description = description;
170
+ this.config = Object.assign({}, config);
171
+ rawName = rawName.replace(/\.\*/g, "");
172
+ this.negated = false;
173
+ this.names = removeBrackets(rawName).split(",").map((v) => {
174
+ let name = v.trim().replace(/^-{1,2}/, "");
175
+ if (name.startsWith("no-")) {
176
+ this.negated = true;
177
+ name = name.replace(/^no-/, "");
178
+ }
179
+ return camelcaseOptionName(name);
180
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
181
+ this.name = this.names[this.names.length - 1];
182
+ if (this.negated && this.config.default == null) this.config.default = true;
183
+ if (rawName.includes("<")) this.required = true;
184
+ else if (rawName.includes("[")) this.required = false;
185
+ else this.isBoolean = true;
186
+ }
187
+ };
188
+ const processArgs = process.argv;
189
+ const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
190
+ var Command = class {
191
+ constructor(rawName, description, config = {}, cli) {
192
+ this.rawName = rawName;
193
+ this.description = description;
194
+ this.config = config;
195
+ this.cli = cli;
196
+ this.options = [];
197
+ this.aliasNames = [];
198
+ this.name = removeBrackets(rawName);
199
+ this.args = findAllBrackets(rawName);
200
+ this.examples = [];
201
+ }
202
+ usage(text) {
203
+ this.usageText = text;
204
+ return this;
205
+ }
206
+ allowUnknownOptions() {
207
+ this.config.allowUnknownOptions = true;
208
+ return this;
209
+ }
210
+ ignoreOptionDefaultValue() {
211
+ this.config.ignoreOptionDefaultValue = true;
212
+ return this;
213
+ }
214
+ version(version, customFlags = "-v, --version") {
215
+ this.versionNumber = version;
216
+ this.option(customFlags, "Display version number");
217
+ return this;
218
+ }
219
+ example(example) {
220
+ this.examples.push(example);
221
+ return this;
222
+ }
223
+ option(rawName, description, config) {
224
+ const option = new Option(rawName, description, config);
225
+ this.options.push(option);
226
+ return this;
227
+ }
228
+ alias(name) {
229
+ this.aliasNames.push(name);
230
+ return this;
231
+ }
232
+ action(callback) {
233
+ this.commandAction = callback;
234
+ return this;
235
+ }
236
+ isMatched(name) {
237
+ return this.name === name || this.aliasNames.includes(name);
238
+ }
239
+ get isDefaultCommand() {
240
+ return this.name === "" || this.aliasNames.includes("!");
241
+ }
242
+ get isGlobalCommand() {
243
+ return this instanceof GlobalCommand;
244
+ }
245
+ hasOption(name) {
246
+ name = name.split(".")[0];
247
+ return this.options.find((option) => {
248
+ return option.names.includes(name);
249
+ });
250
+ }
251
+ outputHelp() {
252
+ const { name, commands } = this.cli;
253
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
254
+ let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
255
+ sections.push({
256
+ title: "Usage",
257
+ body: ` $ ${name} ${this.usageText || this.rawName}`
258
+ });
259
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
260
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
261
+ sections.push({
262
+ title: "Commands",
263
+ body: commands.map((command) => {
264
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
265
+ }).join("\n")
266
+ });
267
+ sections.push({
268
+ title: `For more info, run any command with the \`--help\` flag`,
269
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
270
+ });
271
+ }
272
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
273
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
274
+ if (options.length > 0) {
275
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
276
+ sections.push({
277
+ title: "Options",
278
+ body: options.map((option) => {
279
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
280
+ }).join("\n")
281
+ });
282
+ }
283
+ if (this.examples.length > 0) sections.push({
284
+ title: "Examples",
285
+ body: this.examples.map((example) => {
286
+ if (typeof example === "function") return example(name);
287
+ return example;
288
+ }).join("\n")
289
+ });
290
+ if (helpCallback) sections = helpCallback(sections) || sections;
291
+ console.log(sections.map((section) => {
292
+ return section.title ? `${section.title}:
293
+ ${section.body}` : section.body;
294
+ }).join("\n\n"));
295
+ }
296
+ outputVersion() {
297
+ const { name } = this.cli;
298
+ const { versionNumber } = this.cli.globalCommand;
299
+ if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
300
+ }
301
+ checkRequiredArgs() {
302
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
303
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
304
+ }
305
+ checkUnknownOptions() {
306
+ const { options, globalCommand } = this.cli;
307
+ if (!this.config.allowUnknownOptions) {
308
+ for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
309
+ }
310
+ }
311
+ checkOptionValue() {
312
+ const { options: parsedOptions, globalCommand } = this.cli;
313
+ const options = [...globalCommand.options, ...this.options];
314
+ for (const option of options) {
315
+ const value = parsedOptions[option.name.split(".")[0]];
316
+ if (option.required) {
317
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
318
+ if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
319
+ }
320
+ }
321
+ }
322
+ };
323
+ var GlobalCommand = class extends Command {
324
+ constructor(cli) {
325
+ super("@@global@@", "", {}, cli);
326
+ }
327
+ };
328
+ var __assign = Object.assign;
329
+ var CAC = class extends EventEmitter {
330
+ constructor(name = "") {
331
+ super();
332
+ this.name = name;
333
+ this.commands = [];
334
+ this.rawArgs = [];
335
+ this.args = [];
336
+ this.options = {};
337
+ this.globalCommand = new GlobalCommand(this);
338
+ this.globalCommand.usage("<command> [options]");
339
+ }
340
+ usage(text) {
341
+ this.globalCommand.usage(text);
342
+ return this;
343
+ }
344
+ command(rawName, description, config) {
345
+ const command = new Command(rawName, description || "", config, this);
346
+ command.globalCommand = this.globalCommand;
347
+ this.commands.push(command);
348
+ return command;
349
+ }
350
+ option(rawName, description, config) {
351
+ this.globalCommand.option(rawName, description, config);
352
+ return this;
353
+ }
354
+ help(callback) {
355
+ this.globalCommand.option("-h, --help", "Display this message");
356
+ this.globalCommand.helpCallback = callback;
357
+ this.showHelpOnExit = true;
358
+ return this;
359
+ }
360
+ version(version, customFlags = "-v, --version") {
361
+ this.globalCommand.version(version, customFlags);
362
+ this.showVersionOnExit = true;
363
+ return this;
364
+ }
365
+ example(example) {
366
+ this.globalCommand.example(example);
367
+ return this;
368
+ }
369
+ outputHelp() {
370
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
371
+ else this.globalCommand.outputHelp();
372
+ }
373
+ outputVersion() {
374
+ this.globalCommand.outputVersion();
375
+ }
376
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
377
+ this.args = args;
378
+ this.options = options;
379
+ if (matchedCommand) this.matchedCommand = matchedCommand;
380
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
381
+ return this;
382
+ }
383
+ unsetMatchedCommand() {
384
+ this.matchedCommand = void 0;
385
+ this.matchedCommandName = void 0;
386
+ }
387
+ parse(argv = processArgs, { run = true } = {}) {
388
+ this.rawArgs = argv;
389
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
390
+ let shouldParse = true;
391
+ for (const command of this.commands) {
392
+ const parsed = this.mri(argv.slice(2), command);
393
+ const commandName = parsed.args[0];
394
+ if (command.isMatched(commandName)) {
395
+ shouldParse = false;
396
+ const parsedInfo = __assign(__assign({}, parsed), { args: parsed.args.slice(1) });
397
+ this.setParsedInfo(parsedInfo, command, commandName);
398
+ this.emit(`command:${commandName}`, command);
399
+ }
400
+ }
401
+ if (shouldParse) {
402
+ for (const command of this.commands) if (command.name === "") {
403
+ shouldParse = false;
404
+ const parsed = this.mri(argv.slice(2), command);
405
+ this.setParsedInfo(parsed, command);
406
+ this.emit(`command:!`, command);
407
+ }
408
+ }
409
+ if (shouldParse) {
410
+ const parsed = this.mri(argv.slice(2));
411
+ this.setParsedInfo(parsed);
412
+ }
413
+ if (this.options.help && this.showHelpOnExit) {
414
+ this.outputHelp();
415
+ run = false;
416
+ this.unsetMatchedCommand();
417
+ }
418
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
419
+ this.outputVersion();
420
+ run = false;
421
+ this.unsetMatchedCommand();
422
+ }
423
+ const parsedArgv = {
424
+ args: this.args,
425
+ options: this.options
426
+ };
427
+ if (run) this.runMatchedCommand();
428
+ if (!this.matchedCommand && this.args[0]) this.emit("command:*");
429
+ return parsedArgv;
430
+ }
431
+ mri(argv, command) {
432
+ const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
433
+ const mriOptions = getMriOptions(cliOptions);
434
+ let argsAfterDoubleDashes = [];
435
+ const doubleDashesIndex = argv.indexOf("--");
436
+ if (doubleDashesIndex > -1) {
437
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
438
+ argv = argv.slice(0, doubleDashesIndex);
439
+ }
440
+ let parsed = mri2(argv, mriOptions);
441
+ parsed = Object.keys(parsed).reduce((res, name) => {
442
+ return __assign(__assign({}, res), { [camelcaseOptionName(name)]: parsed[name] });
443
+ }, { _: [] });
444
+ const args = parsed._;
445
+ const options = { "--": argsAfterDoubleDashes };
446
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
447
+ let transforms = Object.create(null);
448
+ for (const cliOption of cliOptions) {
449
+ if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
450
+ if (Array.isArray(cliOption.config.type)) {
451
+ if (transforms[cliOption.name] === void 0) {
452
+ transforms[cliOption.name] = Object.create(null);
453
+ transforms[cliOption.name]["shouldTransform"] = true;
454
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
455
+ }
456
+ }
457
+ }
458
+ for (const key of Object.keys(parsed)) if (key !== "_") {
459
+ setDotProp(options, key.split("."), parsed[key]);
460
+ setByType(options, transforms);
461
+ }
462
+ return {
463
+ args,
464
+ options
465
+ };
466
+ }
467
+ runMatchedCommand() {
468
+ const { args, options, matchedCommand: command } = this;
469
+ if (!command || !command.commandAction) return;
470
+ command.checkUnknownOptions();
471
+ command.checkOptionValue();
472
+ command.checkRequiredArgs();
473
+ const actionArgs = [];
474
+ command.args.forEach((arg, index) => {
475
+ if (arg.variadic) actionArgs.push(args.slice(index));
476
+ else actionArgs.push(args[index]);
477
+ });
478
+ actionArgs.push(options);
479
+ return command.commandAction.apply(this, actionArgs);
480
+ }
481
+ };
482
+ const cac = (name = "") => new CAC(name);
483
+
484
+ //#endregion
485
+ //#region package.json
486
+ var version = "1.3.0";
487
+
488
+ //#endregion
489
+ //#region ../node_modules/.pnpm/is-network-error@1.3.0/node_modules/is-network-error/index.js
490
+ const objectToString = Object.prototype.toString;
491
+ const isError = (value) => objectToString.call(value) === "[object Error]";
492
+ const errorMessages = new Set([
493
+ "network error",
494
+ "Failed to fetch",
495
+ "NetworkError when attempting to fetch resource.",
496
+ "The Internet connection appears to be offline.",
497
+ "Network request failed",
498
+ "fetch failed",
499
+ "terminated",
500
+ " A network error occurred.",
501
+ "Network connection lost"
502
+ ]);
503
+ function isNetworkError(error) {
504
+ if (!(error && isError(error) && error.name === "TypeError" && typeof error.message === "string")) return false;
505
+ const { message, stack } = error;
506
+ if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error;
507
+ if (message.startsWith("error sending request for url")) return true;
508
+ return errorMessages.has(message);
509
+ }
510
+
511
+ //#endregion
512
+ //#region ../node_modules/.pnpm/p-retry@7.1.1/node_modules/p-retry/index.js
513
+ function validateRetries(retries) {
514
+ if (typeof retries === "number") {
515
+ if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number.");
516
+ if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
517
+ } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity.");
518
+ }
519
+ function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
520
+ if (value === void 0) return;
521
+ if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
522
+ if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`);
523
+ if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`);
524
+ }
525
+ var AbortError = class extends Error {
526
+ constructor(message) {
527
+ super();
528
+ if (message instanceof Error) {
529
+ this.originalError = message;
530
+ ({message} = message);
531
+ } else {
532
+ this.originalError = new Error(message);
533
+ this.originalError.stack = this.stack;
534
+ }
535
+ this.name = "AbortError";
536
+ this.message = message;
537
+ }
538
+ };
539
+ function calculateDelay(retriesConsumed, options) {
540
+ const attempt = Math.max(1, retriesConsumed + 1);
541
+ const random = options.randomize ? Math.random() + 1 : 1;
542
+ let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
543
+ timeout = Math.min(timeout, options.maxTimeout);
544
+ return timeout;
545
+ }
546
+ function calculateRemainingTime(start, max) {
547
+ if (!Number.isFinite(max)) return max;
548
+ return max - (performance.now() - start);
549
+ }
550
+ async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
551
+ const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
552
+ if (normalizedError instanceof AbortError) throw normalizedError.originalError;
553
+ const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
554
+ const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
555
+ const context = Object.freeze({
556
+ error: normalizedError,
557
+ attemptNumber,
558
+ retriesLeft,
559
+ retriesConsumed
560
+ });
561
+ await options.onFailedAttempt(context);
562
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError;
563
+ const consumeRetry = await options.shouldConsumeRetry(context);
564
+ const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
565
+ if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError;
566
+ if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {
567
+ if (consumeRetry) throw normalizedError;
568
+ options.signal?.throwIfAborted();
569
+ return false;
570
+ }
571
+ if (!await options.shouldRetry(context)) throw normalizedError;
572
+ if (!consumeRetry) {
573
+ options.signal?.throwIfAborted();
574
+ return false;
575
+ }
576
+ const delayTime = calculateDelay(retriesConsumed, options);
577
+ const finalDelay = Math.min(delayTime, remainingTime);
578
+ options.signal?.throwIfAborted();
579
+ if (finalDelay > 0) await new Promise((resolve, reject) => {
580
+ const onAbort = () => {
581
+ clearTimeout(timeoutToken);
582
+ options.signal?.removeEventListener("abort", onAbort);
583
+ reject(options.signal.reason);
584
+ };
585
+ const timeoutToken = setTimeout(() => {
586
+ options.signal?.removeEventListener("abort", onAbort);
587
+ resolve();
588
+ }, finalDelay);
589
+ if (options.unref) timeoutToken.unref?.();
590
+ options.signal?.addEventListener("abort", onAbort, { once: true });
591
+ });
592
+ options.signal?.throwIfAborted();
593
+ return true;
594
+ }
595
+ async function pRetry(input, options = {}) {
596
+ options = { ...options };
597
+ validateRetries(options.retries);
598
+ if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
599
+ options.retries ??= 10;
600
+ options.factor ??= 2;
601
+ options.minTimeout ??= 1e3;
602
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
603
+ options.maxRetryTime ??= Number.POSITIVE_INFINITY;
604
+ options.randomize ??= false;
605
+ options.onFailedAttempt ??= () => {};
606
+ options.shouldRetry ??= () => true;
607
+ options.shouldConsumeRetry ??= () => true;
608
+ validateNumberOption("factor", options.factor, {
609
+ min: 0,
610
+ allowInfinity: false
611
+ });
612
+ validateNumberOption("minTimeout", options.minTimeout, {
613
+ min: 0,
614
+ allowInfinity: false
615
+ });
616
+ validateNumberOption("maxTimeout", options.maxTimeout, {
617
+ min: 0,
618
+ allowInfinity: true
619
+ });
620
+ validateNumberOption("maxRetryTime", options.maxRetryTime, {
621
+ min: 0,
622
+ allowInfinity: true
623
+ });
624
+ if (!(options.factor > 0)) options.factor = 1;
625
+ options.signal?.throwIfAborted();
626
+ let attemptNumber = 0;
627
+ let retriesConsumed = 0;
628
+ const startTime = performance.now();
629
+ while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
630
+ attemptNumber++;
631
+ try {
632
+ options.signal?.throwIfAborted();
633
+ const result = await input(attemptNumber);
634
+ options.signal?.throwIfAborted();
635
+ return result;
636
+ } catch (error) {
637
+ if (await onAttemptFailure({
638
+ error,
639
+ attemptNumber,
640
+ retriesConsumed,
641
+ startTime,
642
+ options
643
+ })) retriesConsumed++;
644
+ }
645
+ }
646
+ throw new Error("Retry attempts exhausted without throwing an error.");
647
+ }
648
+
649
+ //#endregion
650
+ //#region src/api.ts
651
+ const defaultRetryOptions = {
652
+ retries: 5,
653
+ factor: 2,
654
+ minTimeout: 1e3,
655
+ maxTimeout: Infinity,
656
+ randomize: false
657
+ };
658
+ const defaultOptions = { apiEndpoint: "https://npm.antfu.dev/" };
659
+ async function getLatestVersionBatch(packages, options = {}) {
660
+ const { apiEndpoint = defaultOptions.apiEndpoint, fetch: fetchApi = fetch, throw: throwError = true, retry = defaultRetryOptions } = options;
661
+ let query = [
662
+ options.force ? "force=true" : "",
663
+ options.metadata ? "metadata=true" : "",
664
+ throwError ? "" : "throw=false"
665
+ ].filter(Boolean).join("&");
666
+ if (query) query = `?${query}`;
667
+ const fetchFn = () => fetchApi(new URL(packages.join("+") + query, apiEndpoint)).then((r) => r.json());
668
+ const retryOptions = typeof retry === "number" ? {
669
+ ...defaultRetryOptions,
670
+ retries: retry
671
+ } : retry;
672
+ const list = toArray(await (retryOptions === false ? fetchFn() : pRetry(fetchFn, retryOptions)));
673
+ return throwError ? throwErrorObject(list) : list;
674
+ }
675
+ async function getVersionsBatch(packages, options = {}) {
676
+ const { apiEndpoint = defaultOptions.apiEndpoint, fetch: fetchApi = fetch, throw: throwError = true, retry = defaultRetryOptions } = options;
677
+ let query = [
678
+ options.force ? "force=true" : "",
679
+ options.loose ? "loose=true" : "",
680
+ options.metadata ? "metadata=true" : "",
681
+ options.after ? `after=${encodeURIComponent(options.after)}` : "",
682
+ throwError ? "" : "throw=false"
683
+ ].filter(Boolean).join("&");
684
+ if (query) query = `?${query}`;
685
+ const fetchFn = () => fetchApi(new URL(`/versions/${packages.join("+")}${query}`, apiEndpoint)).then((r) => r.json());
686
+ const list = toArray(await (retry === false ? fetchFn() : pRetry(fetchFn, typeof retry === "number" ? {
687
+ ...defaultRetryOptions,
688
+ retries: retry
689
+ } : retry)));
690
+ return throwError ? throwErrorObject(list) : list;
691
+ }
692
+ function throwErrorObject(data) {
693
+ for (const item of toArray(data)) if (item && "error" in item) throw new Error(item.message || item.error);
694
+ return data;
695
+ }
696
+ function toArray(data) {
697
+ if (Array.isArray(data)) return data;
698
+ return [data];
699
+ }
700
+
701
+ //#endregion
702
+ //#region src/cli.ts
703
+ const cli = cac("fast-npm-meta");
704
+ cli.command("version <...pkgs>", "Get the latest version of one or more packages").option("--json", "Output as JSON").option("--force", "Bypass cache and get the latest data").option("--metadata", "Include version metadata (engines, deprecated, etc.)").option("--api-endpoint <url>", "API endpoint URL").action(async (pkgs, options) => {
705
+ try {
706
+ const results = await getLatestVersionBatch(pkgs, {
707
+ force: options.force,
708
+ metadata: options.metadata,
709
+ apiEndpoint: options.apiEndpoint
710
+ });
711
+ if (options.json) {
712
+ const output = results.length === 1 ? results[0] : results;
713
+ console.log(JSON.stringify(output, null, 2));
714
+ } else for (const result of results) console.log(result.version);
715
+ } catch (e) {
716
+ console.error(e.message);
717
+ process$1.exit(1);
718
+ }
719
+ });
720
+ cli.command("full <...pkgs>", "Get full package metadata (versions list, dist-tags, etc.)").option("--force", "Bypass cache and get the latest data").option("--loose", "Include all versions that are newer than the specified version").option("--metadata", "Include per-version metadata (time, engines, deprecated, etc.)").option("--after <date>", "Only return versions published after this ISO date-time").option("--api-endpoint <url>", "API endpoint URL").action(async (pkgs, options) => {
721
+ try {
722
+ const results = await getVersionsBatch(pkgs, {
723
+ force: options.force,
724
+ loose: options.loose,
725
+ metadata: options.metadata,
726
+ after: options.after,
727
+ apiEndpoint: options.apiEndpoint
728
+ });
729
+ const output = results.length === 1 ? results[0] : results;
730
+ console.log(JSON.stringify(output, null, 2));
731
+ } catch (e) {
732
+ console.error(e.message);
733
+ process$1.exit(1);
734
+ }
735
+ });
736
+ cli.help();
737
+ cli.version(version);
738
+ cli.parse();
739
+
740
+ //#endregion
741
+ export { };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fast-npm-meta",
3
3
  "type": "module",
4
- "version": "1.2.1",
4
+ "version": "1.3.0",
5
5
  "description": "Get npm package metadata",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -19,12 +19,17 @@
19
19
  "./package.json": "./package.json"
20
20
  },
21
21
  "types": "./dist/index.d.mts",
22
+ "bin": {
23
+ "fast-npm-meta": "./dist/cli.mjs"
24
+ },
22
25
  "files": [
23
- "dist"
26
+ "dist",
27
+ "skills"
24
28
  ],
25
29
  "devDependencies": {
30
+ "cac": "^6.7.14",
26
31
  "p-retry": "^7.1.1",
27
- "tsdown": "^0.20.1"
32
+ "tsdown": "^0.20.3"
28
33
  },
29
34
  "scripts": {
30
35
  "build": "tsdown",
@@ -0,0 +1,86 @@
1
+ # fast-npm-meta CLI
2
+
3
+ When querying npm package versions or metadata, **prefer `fast-npm-meta` over `npm view`**.
4
+
5
+ `npm view` fetches the full registry manifest (often 4+ MB of JSON per package). `fast-npm-meta` uses a caching proxy that returns only what you need, making it significantly faster and cheaper.
6
+
7
+ ## When to use
8
+
9
+ Use `fast-npm-meta` whenever you need to:
10
+ - Look up the latest version of a package
11
+ - Check what versions of a package exist
12
+ - Inspect dist-tags, publish dates, or engine requirements
13
+ - Resolve a version range to a specific version
14
+
15
+ ## Usage
16
+
17
+ ### Get the latest version (plain text)
18
+
19
+ One version per line — suitable for scripting.
20
+
21
+ ```sh
22
+ fast-npm-meta version vite
23
+ # 7.3.1
24
+ fast-npm-meta version vite@8
25
+ # 8.0.0
26
+ fast-npm-meta version "nuxt@^3.5"
27
+ # 3.5.22
28
+
29
+ fast-npm-meta version vite nuxt vue
30
+ # 7.3.1
31
+ # 4.3.1
32
+ # 3.5.29
33
+ ```
34
+
35
+ ### Get version as JSON
36
+
37
+ Single package returns an object; multiple packages return an array.
38
+
39
+ ```sh
40
+ fast-npm-meta version vite --json
41
+ fast-npm-meta version vite nuxt vue --json
42
+ ```
43
+
44
+ Add `--metadata` to also get engines, deprecated, and provenance fields:
45
+
46
+ ```sh
47
+ fast-npm-meta version vite --json --metadata
48
+ ```
49
+
50
+ ### Get full package metadata (all versions, dist-tags)
51
+
52
+ ```sh
53
+ fast-npm-meta full vite
54
+ fast-npm-meta full vite nuxt vue # returns an array
55
+ ```
56
+
57
+ Add `--metadata` for per-version metadata (engines, deprecated, integrity, etc.):
58
+
59
+ ```sh
60
+ fast-npm-meta full vite --metadata
61
+ ```
62
+
63
+ Filter to versions published after a date:
64
+
65
+ ```sh
66
+ fast-npm-meta full vite --after 2025-01-01T00:00:00Z
67
+ ```
68
+
69
+ ## Do NOT use these instead
70
+
71
+ | Avoid | Use instead |
72
+ |-------|-------------|
73
+ | `npm view vite version` | `fast-npm-meta version vite` |
74
+ | `npm view vite versions --json` | `fast-npm-meta full vite` |
75
+ | `npm view vite dist-tags --json` | `fast-npm-meta full vite` |
76
+
77
+ ## Flags reference
78
+
79
+ | Flag | Commands | Description |
80
+ |------|----------|-------------|
81
+ | `--json` | `version` | Output as JSON instead of plain text |
82
+ | `--force` | both | Bypass cache, fetch fresh data |
83
+ | `--metadata` | both | Include per-version metadata |
84
+ | `--loose` | `full` | Include all versions newer than the specifier |
85
+ | `--after <date>` | `full` | Only versions published after this ISO date |
86
+ | `--api-endpoint <url>` | both | Custom API endpoint |