@badisi/latest-version 8.0.5 → 9.0.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/index.mjs ADDED
@@ -0,0 +1,201 @@
1
+ import { npm, yarn } from "global-dirs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join, parse, resolve } from "node:path";
4
+ import gt from "semver/functions/gt.js";
5
+ import maxSatisfying from "semver/ranges/max-satisfying.js";
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { get } from "node:http";
9
+ import { get as get$1 } from "node:https";
10
+ import { URL } from "node:url";
11
+ import registryAuthToken from "registry-auth-token";
12
+ import getRegistryUrl from "registry-auth-token/registry-url.js";
13
+ //#region src/cache.ts
14
+ const ONE_DAY = 1e3 * 60 * 60 * 24;
15
+ const getCacheDir = (name = "@badisi/latest-version") => {
16
+ const homeDir = homedir();
17
+ switch (process.platform) {
18
+ case "darwin": return join(homeDir, "Library", "Caches", name);
19
+ case "win32": return join(process.env["LOCALAPPDATA"] ?? join(homeDir, "AppData", "Local"), name, "Cache");
20
+ default: return join(process.env["XDG_CACHE_HOME"] ?? join(homeDir, ".cache"), name);
21
+ }
22
+ };
23
+ const saveMetadataToCache = (pkg) => {
24
+ const filePath = join(getCacheDir(), `${pkg.name}.json`);
25
+ if (!existsSync(dirname(filePath))) mkdirSync(dirname(filePath), { recursive: true });
26
+ writeFileSync(filePath, JSON.stringify(pkg));
27
+ };
28
+ const getMetadataFromCache = (pkgName, options) => {
29
+ const maxAge = options?.cacheMaxAge ?? 864e5;
30
+ if (maxAge !== 0) {
31
+ const pkgCacheFilePath = join(getCacheDir(), `${pkgName}.json`);
32
+ if (existsSync(pkgCacheFilePath)) {
33
+ const pkg = JSON.parse(readFileSync(pkgCacheFilePath).toString());
34
+ if (Date.now() - pkg.lastUpdateDate < maxAge) return pkg;
35
+ }
36
+ }
37
+ };
38
+ //#endregion
39
+ //#region src/metadata.ts
40
+ const downloadMetadata = (pkgName, options) => new Promise((resolve, reject) => {
41
+ const i = pkgName.indexOf("/");
42
+ const pkgScope = i !== -1 ? pkgName.slice(0, i) : "";
43
+ const registryUrl = options?.registryUrl ?? getRegistryUrl(pkgScope);
44
+ const pkgUrl = new URL(encodeURIComponent(pkgName).replace(/^%40/, "@"), registryUrl);
45
+ let requestOptions = {
46
+ headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*" },
47
+ host: pkgUrl.hostname,
48
+ path: pkgUrl.pathname,
49
+ port: pkgUrl.port
50
+ };
51
+ const authInfo = registryAuthToken(pkgUrl.toString(), { recursive: true });
52
+ if (authInfo && requestOptions.headers) requestOptions.headers.authorization = `${authInfo.type} ${authInfo.token}`;
53
+ if (options?.requestOptions) requestOptions = {
54
+ ...requestOptions,
55
+ ...options.requestOptions
56
+ };
57
+ const request = (pkgUrl.protocol === "https:" ? get$1 : get)(requestOptions, (res) => {
58
+ if (res.statusCode === 200) {
59
+ let rawData = "";
60
+ res.setEncoding("utf8");
61
+ res.on("data", (chunk) => rawData += chunk);
62
+ res.once("error", (err) => {
63
+ res.removeAllListeners();
64
+ reject(/* @__PURE__ */ new Error(`Request error (${err.message}): ${pkgUrl.toString()}`));
65
+ });
66
+ res.once("end", () => {
67
+ res.removeAllListeners();
68
+ try {
69
+ const pkgMetadata = JSON.parse(rawData);
70
+ resolve({
71
+ name: pkgName,
72
+ lastUpdateDate: Date.now(),
73
+ versions: Object.keys(pkgMetadata["versions"]),
74
+ distTags: pkgMetadata["dist-tags"]
75
+ });
76
+ return;
77
+ } catch (error) {
78
+ if (typeof error === "string") reject(new Error(error));
79
+ else if (error instanceof Error) reject(error);
80
+ else reject(/* @__PURE__ */ new Error("Metadata extraction error"));
81
+ return;
82
+ }
83
+ });
84
+ } else {
85
+ res.removeAllListeners();
86
+ res.resume();
87
+ reject(/* @__PURE__ */ new Error(`Request error (${res.statusCode ?? "unknown"}): ${pkgUrl.toString()}`));
88
+ return;
89
+ }
90
+ });
91
+ const abort = (error) => {
92
+ request.destroy();
93
+ reject(typeof error === "string" ? new Error(error) : error);
94
+ };
95
+ request.once("timeout", () => {
96
+ abort(`Request timed out: ${pkgUrl.toString()}`);
97
+ });
98
+ request.once("error", (err) => {
99
+ abort(err);
100
+ });
101
+ request.once("close", () => {
102
+ request.removeAllListeners();
103
+ });
104
+ });
105
+ //#endregion
106
+ //#region src/index.ts
107
+ const isPackageJson = (obj) => obj.dependencies !== void 0 || obj.devDependencies !== void 0 || obj.peerDependencies !== void 0;
108
+ const getRegistryVersions = async (pkgName, tagOrRange, options) => {
109
+ let pkgMetadata;
110
+ if (pkgName.length && options?.useCache) {
111
+ pkgMetadata = getMetadataFromCache(pkgName, options);
112
+ if (!pkgMetadata) {
113
+ pkgMetadata = await downloadMetadata(pkgName, options);
114
+ saveMetadataToCache(pkgMetadata);
115
+ }
116
+ } else if (pkgName.length) pkgMetadata = await downloadMetadata(pkgName, options);
117
+ const versions = {
118
+ latest: pkgMetadata?.distTags["latest"],
119
+ next: pkgMetadata?.distTags["next"]
120
+ };
121
+ if (tagOrRange && pkgMetadata?.distTags[tagOrRange]) versions.wanted = pkgMetadata.distTags[tagOrRange];
122
+ else if (tagOrRange && pkgMetadata?.versions.length) versions.wanted = maxSatisfying(pkgMetadata.versions, tagOrRange) ?? void 0;
123
+ return versions;
124
+ };
125
+ const getInstalledVersion = async (pkgName, location = "local") => {
126
+ try {
127
+ const readPackageJson = async (path) => JSON.parse(await readFile(path, "utf8"));
128
+ if (location === "globalNpm") return (await readPackageJson(join(npm.packages, pkgName, "package.json"))).version;
129
+ else if (location === "globalYarn") {
130
+ if (!(pkgName in (await readPackageJson(resolve(yarn.packages, "..", "package.json"))).dependencies)) return;
131
+ return (await readPackageJson(join(yarn.packages, pkgName, "package.json"))).version;
132
+ } else {
133
+ /**
134
+ * Compute the local paths manually as require.resolve() and require.resolve.paths()
135
+ * cannot be trusted anymore.
136
+ * @see https://github.com/nodejs/node/issues/33460
137
+ * @see https://github.com/nodejs/loaders/issues/26
138
+ */
139
+ const startPath = process.cwd();
140
+ const { root } = parse(startPath);
141
+ const findPackageVersion = async (path, rootPath, name) => {
142
+ const pkgPath = join(path, "node_modules", name, "package.json");
143
+ try {
144
+ return (await readPackageJson(pkgPath)).version;
145
+ } catch {}
146
+ if (path === rootPath) return;
147
+ return await findPackageVersion(dirname(path), rootPath, name);
148
+ };
149
+ return await findPackageVersion(startPath, root, pkgName);
150
+ }
151
+ } catch {
152
+ return;
153
+ }
154
+ };
155
+ const getInfo = async (pkg, options) => {
156
+ const i = pkg.lastIndexOf("@");
157
+ let pkgInfo = {
158
+ name: i > 1 ? pkg.slice(0, i) : pkg,
159
+ wantedTagOrRange: i > 1 ? pkg.slice(i + 1) : "latest",
160
+ updatesAvailable: false
161
+ };
162
+ try {
163
+ pkgInfo = {
164
+ ...pkgInfo,
165
+ local: await getInstalledVersion(pkgInfo.name, "local"),
166
+ globalNpm: await getInstalledVersion(pkgInfo.name, "globalNpm"),
167
+ globalYarn: await getInstalledVersion(pkgInfo.name, "globalYarn"),
168
+ ...await getRegistryVersions(pkgInfo.name, pkgInfo.wantedTagOrRange, options)
169
+ };
170
+ const local = pkgInfo.local && pkgInfo.wanted ? gt(pkgInfo.wanted, pkgInfo.local) ? pkgInfo.wanted : false : false;
171
+ const globalNpm = pkgInfo.globalNpm && pkgInfo.wanted ? gt(pkgInfo.wanted, pkgInfo.globalNpm) ? pkgInfo.wanted : false : false;
172
+ const globalYarn = pkgInfo.globalYarn && pkgInfo.wanted ? gt(pkgInfo.wanted, pkgInfo.globalYarn) ? pkgInfo.wanted : false : false;
173
+ pkgInfo.updatesAvailable = local || globalNpm || globalYarn ? {
174
+ local,
175
+ globalNpm,
176
+ globalYarn
177
+ } : false;
178
+ } catch (err) {
179
+ if (typeof err === "string") pkgInfo.error = new Error(err);
180
+ else if (err instanceof Error) pkgInfo.error = err;
181
+ else pkgInfo.error = /* @__PURE__ */ new Error("Unknown error");
182
+ }
183
+ return pkgInfo;
184
+ };
185
+ const latestVersion = async (arg, options) => {
186
+ const pkgs = [];
187
+ if (typeof arg === "string") pkgs.push(arg);
188
+ else if (Array.isArray(arg)) pkgs.push(...arg);
189
+ else if (isPackageJson(arg)) {
190
+ const addDeps = (deps) => {
191
+ if (deps) pkgs.push(...Object.keys(deps).map((key) => `${key}@${deps[key]}`));
192
+ };
193
+ addDeps(arg.dependencies);
194
+ addDeps(arg.devDependencies);
195
+ addDeps(arg.peerDependencies);
196
+ }
197
+ const results = (await Promise.allSettled(pkgs.map((pkg) => getInfo(pkg, options)))).map((jobResult) => jobResult.value);
198
+ return typeof arg === "string" ? results[0] : results;
199
+ };
200
+ //#endregion
201
+ export { ONE_DAY, latestVersion };
package/package.json CHANGED
@@ -1,27 +1,29 @@
1
1
  {
2
2
  "name": "@badisi/latest-version",
3
- "version": "8.0.5",
3
+ "version": "9.0.0",
4
4
  "description": "Get latest versions of packages",
5
5
  "homepage": "https://github.com/Badisi/latest-version",
6
6
  "license": "MIT",
7
7
  "author": {
8
8
  "name": "Badisi"
9
9
  },
10
- "type": "commonjs",
11
- "main": "index.js",
12
- "typings": "index.d.ts",
10
+ "type": "module",
11
+ "main": "./index.cjs",
12
+ "module": "./index.mjs",
13
+ "types": "./index.d.mts",
13
14
  "exports": {
14
15
  ".": {
15
- "require": "./index.js",
16
- "types": "./index.d.ts",
17
- "default": "./index.js"
16
+ "import": {
17
+ "types": "./index.d.mts",
18
+ "default": "./index.mjs"
19
+ },
20
+ "require": {
21
+ "types": "./index.d.cts",
22
+ "default": "./index.cjs"
23
+ }
18
24
  },
19
25
  "./package.json": "./package.json"
20
26
  },
21
- "bin": {
22
- "latest-version": "bin/latest-version",
23
- "lv": "bin/latest-version"
24
- },
25
27
  "repository": {
26
28
  "type": "git",
27
29
  "url": "https://github.com/Badisi/latest-version"
@@ -33,6 +35,7 @@
33
35
  "latest",
34
36
  "current",
35
37
  "next",
38
+ "outdated",
36
39
  "version",
37
40
  "pkg",
38
41
  "package",
@@ -44,9 +47,12 @@
44
47
  "node": ">= 20.12.0"
45
48
  },
46
49
  "dependencies": {
47
- "global-dirs": "3.0.1",
48
- "ora": "^9.3.0",
50
+ "global-dirs": "^3.0.1",
49
51
  "registry-auth-token": "^5.1.1",
50
- "semver": "^7.7.4"
52
+ "semver": "^7.8.5"
53
+ },
54
+ "allowScripts": {
55
+ "@hug/eslint-config@26.0.0": true,
56
+ "fsevents@2.3.3": true
51
57
  }
52
58
  }
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- 'use strict';
4
-
5
- require('../cli.js');
package/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/cli.js DELETED
@@ -1,239 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
-
25
- // src/cli.ts
26
- var import_node_util = require("node:util");
27
- var import_node_fs = require("node:fs");
28
- var import_node_path = require("node:path");
29
- var import_major = __toESM(require("semver/functions/major"));
30
- var import_diff = __toESM(require("semver/functions/diff"));
31
- var import_index = __toESM(require("./index"));
32
- var colorizeDiff = (from, to) => {
33
- const toParts = to.split(".");
34
- const diffIndex = from.split(".").findIndex((part, i) => part !== toParts[i]);
35
- if (diffIndex !== -1) {
36
- let color = "magenta";
37
- if (toParts[0] !== "0") {
38
- color = diffIndex === 0 ? "red" : diffIndex === 1 ? "cyan" : "green";
39
- }
40
- const start = toParts.slice(0, diffIndex).join(".");
41
- const mid = diffIndex === 0 ? "" : ".";
42
- const end = (0, import_node_util.styleText)(color, toParts.slice(diffIndex).join("."));
43
- return `${start}${mid}${end}`;
44
- }
45
- return to;
46
- };
47
- var columnCellRenderer = (column, row) => {
48
- let text = row[column.attrName];
49
- const gap = text.length < column.maxLength ? " ".repeat(column.maxLength - text.length) : "";
50
- switch (column.attrName) {
51
- case "name":
52
- text = (0, import_node_util.styleText)("yellow", text);
53
- break;
54
- case "installed":
55
- case "separator":
56
- text = (0, import_node_util.styleText)("blue", text);
57
- break;
58
- case "location":
59
- case "tagOrRange":
60
- text = (0, import_node_util.styleText)("gray", text);
61
- break;
62
- case "wanted":
63
- text = colorizeDiff(row.installed, text);
64
- break;
65
- case "latest":
66
- if (text !== row.wanted) {
67
- text = colorizeDiff(row.installed, text);
68
- }
69
- break;
70
- default:
71
- break;
72
- }
73
- return column.align === "right" ? `${gap}${text}` : `${text}${gap}`;
74
- };
75
- var columnHeaderRenderer = (column) => {
76
- const text = column.label;
77
- const gap = text.length < column.maxLength ? " ".repeat(column.maxLength - text.length) : "";
78
- return column.align === "right" ? `${gap}${(0, import_node_util.styleText)("underline", text)}` : `${(0, import_node_util.styleText)("underline", text)}${gap}`;
79
- };
80
- var drawBox = (lines, color = "yellow", horizontalPadding = 3) => {
81
- const maxLineWidth = lines.reduce((max, row) => Math.max(max, (0, import_node_util.stripVTControlCharacters)(row).length), 0);
82
- console.log((0, import_node_util.styleText)(color, `\u250C${"\u2500".repeat(maxLineWidth + horizontalPadding * 2)}\u2510`));
83
- lines.forEach((row) => {
84
- const padding = " ".repeat(horizontalPadding);
85
- const fullRow = `${row}${" ".repeat(maxLineWidth - (0, import_node_util.stripVTControlCharacters)(row).length)}`;
86
- console.log(`${(0, import_node_util.styleText)(color, "\u2502")}${padding}${fullRow}${padding}${(0, import_node_util.styleText)(color, "\u2502")}`);
87
- });
88
- console.log((0, import_node_util.styleText)(color, `\u2514${"\u2500".repeat(maxLineWidth + horizontalPadding * 2)}\u2518`));
89
- };
90
- var getTableColumns = (rows) => {
91
- const columns = [
92
- { label: "Package", attrName: "name", align: "left", maxLength: 0, items: [] },
93
- { label: "Location", attrName: "location", align: "left", maxLength: 0, items: [] },
94
- { label: "Installed", attrName: "installed", align: "right", maxLength: 0, items: [] },
95
- { label: "", attrName: "separator", align: "center", maxLength: 0, items: [] },
96
- { label: "Range", attrName: "tagOrRange", align: "right", maxLength: 0, items: [] },
97
- { label: "", attrName: "separator", align: "center", maxLength: 0, items: [] },
98
- { label: "Wanted", attrName: "wanted", align: "right", maxLength: 0, items: [] },
99
- { label: "Latest", attrName: "latest", align: "right", maxLength: 0, items: [] }
100
- ];
101
- rows.forEach((row) => {
102
- columns.forEach((column) => {
103
- column.maxLength = Math.max(column.label.length, column.maxLength, row[column.attrName].length || 0);
104
- });
105
- });
106
- return columns;
107
- };
108
- var getTableRows = (updates) => {
109
- return updates.reduce((all, pkg) => {
110
- const { name, latest, local, globalNpm, globalYarn, wantedTagOrRange, updatesAvailable } = pkg;
111
- const getGroup = (a, b) => {
112
- if (b && (0, import_major.default)(b) === 0) {
113
- return "majorVersionZero";
114
- } else if (a && b) {
115
- const releaseType = (0, import_diff.default)(a, b) ?? "";
116
- if (["major", "premajor", "prerelease"].includes(releaseType)) {
117
- return "major";
118
- } else if (["minor", "preminor"].includes(releaseType)) {
119
- return "minor";
120
- } else if (["patch", "prepatch"].includes(releaseType)) {
121
- return "patch";
122
- }
123
- }
124
- return "unknown";
125
- };
126
- const add = (group, location, installed, wanted) => all.push({
127
- name: " " + name,
128
- location,
129
- installed: installed ?? "unknown",
130
- latest: latest ?? "unknown",
131
- tagOrRange: wantedTagOrRange ?? "unknown",
132
- separator: "\u2192",
133
- wanted: wanted ?? "unknown",
134
- group
135
- });
136
- if (updatesAvailable) {
137
- if (updatesAvailable.local) {
138
- add(getGroup(local, updatesAvailable.local), "local", local, updatesAvailable.local);
139
- }
140
- if (updatesAvailable.globalNpm) {
141
- add(getGroup(globalNpm, updatesAvailable.globalNpm), "NPM global", globalNpm, updatesAvailable.globalNpm);
142
- }
143
- if (updatesAvailable.globalYarn) {
144
- add(getGroup(globalYarn, updatesAvailable.globalYarn), "YARN global", globalYarn, updatesAvailable.globalYarn);
145
- }
146
- } else {
147
- if (local && local !== latest) {
148
- add(getGroup(local, latest), "local", local, pkg.wanted);
149
- }
150
- if (globalNpm && globalNpm !== latest) {
151
- add(getGroup(globalNpm, latest), "NPM global", globalNpm, pkg.wanted);
152
- }
153
- if (globalYarn && globalYarn !== latest) {
154
- add(getGroup(globalYarn, latest), "YARN global", globalYarn, pkg.wanted);
155
- }
156
- if (!local && !globalNpm && !globalYarn) {
157
- add("unknown", "unknown", "unknown", pkg.wanted);
158
- }
159
- }
160
- return all;
161
- }, []);
162
- };
163
- var displayTable = (latestVersionPackages) => {
164
- const updates = latestVersionPackages.filter((pkg) => pkg.updatesAvailable);
165
- if (updates.length) {
166
- const rows = getTableRows(updates);
167
- const hasUpdates = rows.some((row) => row.installed !== "unknown");
168
- const columns = getTableColumns(rows);
169
- const columnGap = 2;
170
- const getGroupLines = (groupType, color, title, description) => {
171
- const items = rows.filter((row) => row.group === groupType).sort((a, b) => a.name > b.name ? 1 : -1);
172
- return !items.length ? [] : [
173
- "",
174
- (0, import_node_util.styleText)(color, `${(0, import_node_util.styleText)("bold", title)} ${(0, import_node_util.styleText)("italic", `(${description})`)}`),
175
- ...items.map((row) => columns.map((column) => columnCellRenderer(column, row)).join(" ".repeat(columnGap)))
176
- ];
177
- };
178
- drawBox([
179
- "",
180
- hasUpdates ? (0, import_node_util.styleText)("yellow", "Important updates are available.") : void 0,
181
- hasUpdates ? "" : void 0,
182
- columns.map(columnHeaderRenderer).join(" ".repeat(columnGap)),
183
- ...getGroupLines("patch", "green", "Patch", "backwards-compatible bug fixes"),
184
- ...getGroupLines("minor", "cyan", "Minor", "backwards-compatible features"),
185
- ...getGroupLines("major", "red", "Major", "potentially breaking API changes"),
186
- ...getGroupLines("majorVersionZero", "magenta", "Major version zero", "not stable, anything may change"),
187
- ...getGroupLines("unknown", "blue", "Missing", "not installed"),
188
- ""
189
- ].filter((line) => line !== void 0));
190
- } else {
191
- console.log((0, import_node_util.styleText)("green", "\u{1F389} Packages are up-to-date"));
192
- }
193
- };
194
- var checkVersions = async (packages, skipMissing, options = { useCache: true }) => {
195
- const ora = (await import("ora")).default;
196
- const spinner = ora({ text: (0, import_node_util.styleText)("cyan", "Checking versions...") });
197
- spinner.start();
198
- let latestVersionPackages = await (0, import_index.default)(packages, options);
199
- if (skipMissing) {
200
- latestVersionPackages = latestVersionPackages.filter((pkg) => pkg.local ?? pkg.globalNpm ?? pkg.globalYarn);
201
- }
202
- spinner.stop();
203
- displayTable(latestVersionPackages);
204
- };
205
- void (async () => {
206
- let args = process.argv.slice(2);
207
- const skipMissing = args.includes("--skip-missing");
208
- args = args.filter((arg) => !arg.startsWith("-"));
209
- if (args.length === 1 && args[0].endsWith("package.json")) {
210
- if ((0, import_node_fs.existsSync)(args[0])) {
211
- process.chdir((0, import_node_path.dirname)(args[0]));
212
- await checkVersions(JSON.parse((0, import_node_fs.readFileSync)(args[0]).toString()), skipMissing);
213
- } else {
214
- console.log((0, import_node_util.styleText)("cyan", "No package.json file were found"));
215
- }
216
- } else {
217
- let localPkgJson;
218
- if ((0, import_node_fs.existsSync)("package.json")) {
219
- localPkgJson = JSON.parse((0, import_node_fs.readFileSync)("package.json").toString());
220
- }
221
- if (args.length) {
222
- args = args.map((arg) => {
223
- if (localPkgJson?.dependencies?.[arg]) {
224
- return `${arg}@${localPkgJson.dependencies?.[arg]}`;
225
- } else if (localPkgJson?.devDependencies?.[arg]) {
226
- return `${arg}@${localPkgJson.devDependencies?.[arg]}`;
227
- } else if (localPkgJson?.peerDependencies?.[arg]) {
228
- return `${arg}@${localPkgJson.peerDependencies?.[arg]}`;
229
- }
230
- return arg;
231
- });
232
- await checkVersions(args, skipMissing);
233
- } else if (localPkgJson) {
234
- await checkVersions(localPkgJson, skipMissing);
235
- } else {
236
- console.log((0, import_node_util.styleText)("cyan", "No packages were found"));
237
- }
238
- }
239
- })();
package/index.d.ts DELETED
@@ -1,146 +0,0 @@
1
- import type { Agent } from 'http';
2
- interface RegistryVersions {
3
- /**
4
- * The latest version of the package found on the registry (if found).
5
- */
6
- latest?: string;
7
- /**
8
- * The next version of the package found on the registry (if found).
9
- */
10
- next?: string;
11
- /**
12
- * The latest version of the package found on the registry and satisfied by the wanted tag or version range.
13
- */
14
- wanted?: string;
15
- }
16
- interface InstalledVersions {
17
- /**
18
- * The current local installed version of the package (if installed).
19
- */
20
- local?: string;
21
- /**
22
- * The current npm global installed version of the package (if installed).
23
- */
24
- globalNpm?: string;
25
- /**
26
- * The current yarn global installed version of the package (if installed).
27
- */
28
- globalYarn?: string;
29
- }
30
- interface LatestVersionPackage extends InstalledVersions, RegistryVersions {
31
- /**
32
- * The name of the package.
33
- */
34
- name: string;
35
- /**
36
- * The tag or version range that was provided (if provided).
37
- * @default "latest"
38
- */
39
- wantedTagOrRange?: string;
40
- /**
41
- * Whether the local or global installed versions (if any) could be upgraded or not, based on the wanted version.
42
- */
43
- updatesAvailable: {
44
- local: string | false;
45
- globalNpm: string | false;
46
- globalYarn: string | false;
47
- } | false;
48
- /**
49
- * Any error that might have occurred during the process.
50
- */
51
- error?: Error;
52
- }
53
- interface RequestOptions {
54
- readonly ca?: string | Buffer | Array<string | Buffer>;
55
- readonly rejectUnauthorized?: boolean;
56
- readonly agent?: Agent | boolean;
57
- readonly timeout?: number;
58
- }
59
- interface LatestVersionOptions {
60
- /**
61
- * Awaiting the api to return might take time, depending on the network, and might impact your package loading performance.
62
- * You can use the cache mechanism to improve load performance and reduce unnecessary network requests.
63
- * If `useCache` is not supplied, the api will always check for updates and wait for every requests to return before returning itself.
64
- * If `useCache` is used, the api will always returned immediately, with either (for each provided packages):
65
- * 1) a latest/next version available if a cache was found
66
- * 2) no latest/next version available if no cache was found - in such case updates will be fetched in the background and a cache will
67
- * be created for each provided packages and made available for the next call to the api.
68
- * @default false
69
- */
70
- readonly useCache?: boolean;
71
- /**
72
- * How long the cache for the provided packages should be used before being refreshed (in milliseconds).
73
- * If `useCache` is not supplied, this option has no effect.
74
- * If `0` is used, this will force the cache to refresh immediately:
75
- * 1) The api will returned immediately (without any latest nor next version available for the provided packages)
76
- * 2) New updates will be fetched in the background
77
- * 3) The cache for each provided packages will be refreshed and made available for the next call to the api
78
- * @default ONE_DAY
79
- */
80
- readonly cacheMaxAge?: number;
81
- /**
82
- * A JavaScript package registry url that implements the CommonJS Package Registry specification.
83
- * @default "Looks at any registry urls in the .npmrc file or fallback to the default npm registry instead"
84
- * @example <caption>.npmrc</caption>
85
- * registry = 'https://custom-registry.com/'
86
- * @pkgscope:registry = 'https://custom-registry.com/'
87
- */
88
- readonly registryUrl?: string;
89
- /**
90
- * Set of options to be passed down to Node.js http/https request.
91
- * @example <caption>Behind a proxy with self-signed certificate</caption>
92
- * { ca: [ fs.readFileSync('proxy-cert.pem') ] }
93
- * @example <caption>Bypassing certificate validation</caption>
94
- * { rejectUnauthorized: false }
95
- */
96
- readonly requestOptions?: RequestOptions;
97
- }
98
- interface LatestVersion {
99
- /**
100
- * Get latest versions of packages from of a package json like object.
101
- * @param {PackageJson} item - A package json like object (with dependencies, devDependencies and peerDependencies attributes).
102
- * @example { dependencies: { 'npm': 'latest' }, devDependencies: { 'npm': '1.3.2' }, peerDependencies: { '@scope/name': '^5.0.2' } }
103
- * @param {LatestVersionOptions} [options] - An object optionally specifying the use of the cache, the max age of the cache, the registry url and the http or https options.
104
- * If `useCache` is not supplied, the default of `false` is used.
105
- * If `cacheMaxAge` is not supplied, the default of `one day` is used.
106
- * If `registryUrl` is not supplied, the default from `.npmrc` is used or a fallback to the `npm registry url` instead.
107
- * @returns {Promise<LatestVersionPackage[]>}
108
- */
109
- (item: PackageJson, options?: LatestVersionOptions): Promise<LatestVersionPackage[]>;
110
- /**
111
- * Get latest version of a single package.
112
- * @param {Package} item - A single package object (represented by a string that should match the following format: `${'@' | ''}${string}@${string}`)
113
- * @example 'npm', 'npm@1.3.2', '@scope/name@^5.0.2'
114
- * @param {LatestVersionOptions} [options] - An object optionally specifying the use of the cache, the max age of the cache, the registry url and the http or https options.
115
- * If `useCache` is not supplied, the default of `false` is used.
116
- * If `cacheMaxAge` is not supplied, the default of `one day` is used.
117
- * If `registryUrl` is not supplied, the default from `.npmrc` is used or a fallback to the npm registry url instead.
118
- * @returns {Promise<LatestVersionPackage>}
119
- */
120
- (item: Package, options?: LatestVersionOptions): Promise<LatestVersionPackage>;
121
- /**
122
- * Get latest versions of a collection of packages.
123
- * @param {Package[]} items - A collection of package object (represented by a string that should match the following format: `${'@' | ''}${string}@${string}`)
124
- * @example ['npm', 'npm@1.3.2', '@scope/name@^5.0.2']
125
- * @param {LatestVersionOptions} [options] - An object optionally specifying the use of the cache, the max age of the cache, the registry url and the http or https options.
126
- * If `useCache` is not supplied, the default of `false` is used.
127
- * If `cacheMaxAge` is not supplied, the default of `one day` is used.
128
- * If `registryUrl` is not supplied, the default from `.npmrc` is used or a fallback to the npm registry url instead.
129
- * @returns {Promise<LatestVersionPackage[]>}
130
- */
131
- (items: Package[], options?: LatestVersionOptions): Promise<LatestVersionPackage[]>;
132
- }
133
- type PackageRange = `${'@' | ''}${string}@${string}`;
134
- type Package = PackageRange | string;
135
- type PackageJsonDependencies = Record<string, string>;
136
- type PackageJson = Record<string, any> & ({
137
- dependencies: PackageJsonDependencies;
138
- } | {
139
- devDependencies: PackageJsonDependencies;
140
- } | {
141
- peerDependencies: PackageJsonDependencies;
142
- });
143
- export declare const ONE_DAY: number;
144
- declare const latestVersion: LatestVersion;
145
- export type { LatestVersion, Package, PackageRange, PackageJson, PackageJsonDependencies, RegistryVersions, LatestVersionPackage, RequestOptions, LatestVersionOptions };
146
- export default latestVersion;