@juit/check-updates 2.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/LICENSE.md ADDED
@@ -0,0 +1,211 @@
1
+ # Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
6
+
7
+ ##### TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ ### 1. Definitions.
10
+
11
+ "**License**" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "**Licensor**" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "**Legal Entity**" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "**control**" means **(i)** the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, _or_ **(ii)** ownership of fifty percent (50%) or more of
23
+ the outstanding shares, _or_ **(iii)** beneficial ownership of such
24
+ entity.
25
+
26
+ "**You**" (or "**Your**") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "**Source**" form shall mean the preferred form for making
30
+ modifications, including but not limited to software source code,
31
+ documentation source, and configuration files.
32
+
33
+ "**Object**" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but not
35
+ limited to compiled object code, generated documentation, and
36
+ conversions to other media types.
37
+
38
+ "**Work**" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work (an example
41
+ is provided in the Appendix below).
42
+
43
+ "**Derivative Works**" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "**Contribution**" shall mean any work of authorship, including the
52
+ original version of the Work and any modifications or additions to that
53
+ Work or Derivative Works thereof, that is intentionally submitted to
54
+ Licensor for inclusion in the Work by the copyright owner or by an
55
+ individual or Legal Entity authorized to submit on behalf of the
56
+ copyright owner. For the purposes of this definition, "**submitted**"
57
+ means any form of electronic, verbal, or written communication sent to
58
+ the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "**Not a
64
+ Contribution**".
65
+
66
+ "**Contributor**" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ ### 2. Grant of Copyright License.
71
+
72
+ Subject to the terms and conditions of this License, each Contributor
73
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
74
+ royalty-free, irrevocable copyright license to reproduce, prepare
75
+ Derivative Works of, publicly display, publicly perform, sublicense,
76
+ and distribute the Work and such Derivative Works in Source or Object
77
+ form.
78
+
79
+ ### 3. Grant of Patent License.
80
+
81
+ Subject to the terms and conditions of this License, each Contributor
82
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
83
+ royalty-free, irrevocable (except as stated in this section) patent
84
+ license to make, have made, use, offer to sell, sell, import, and
85
+ otherwise transfer the Work, where such license applies only to those
86
+ patent claims licensable by such Contributor that are necessarily
87
+ infringed by their Contribution(s) alone or by combination of their
88
+ Contribution(s) with the Work to which such Contribution(s) was
89
+ submitted. If You institute patent litigation against any entity
90
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
91
+ the Work or a Contribution incorporated within the Work constitutes
92
+ direct or contributory patent infringement, then any patent licenses
93
+ granted to You under this License for that Work shall terminate as of
94
+ the date such litigation is filed.
95
+
96
+ ### 4. Redistribution.
97
+
98
+ You may reproduce and distribute copies of the Work or Derivative Works
99
+ thereof in any medium, with or without modifications, and in Source or
100
+ Object form, provided that You meet the following conditions:
101
+
102
+ <ol type="a">
103
+ <li>You must give any other recipients of the Work or Derivative Works
104
+ a copy of this License; and
105
+ <li>You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+ <li>You must retain, in the Source form of any Derivative Works that
108
+ You distribute, all copyright, patent, trademark, and attribution
109
+ notices from the Source form of the Work, excluding those notices
110
+ that do not pertain to any part of the Derivative Works; and
111
+ <li>If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained within
114
+ such NOTICE file, excluding those notices that do not pertain to any
115
+ part of the Derivative Works, in at least one of the following
116
+ places: within a NOTICE text file distributed as part of the
117
+ Derivative Works; within the Source form or documentation, if
118
+ provided along with the Derivative Works; or, within a display
119
+ generated by the Derivative Works, if and wherever such third-party
120
+ notices normally appear. The contents of the NOTICE file are for
121
+ informational purposes only and do not modify the License. You may
122
+ add Your own attribution notices within Derivative Works that You
123
+ distribute, alongside or as an addendum to the NOTICE text from the
124
+ Work, provided that such additional attribution notices cannot be
125
+ construed as modifying the License.
126
+ </ol>
127
+
128
+ You may add Your own copyright statement to Your modifications and may
129
+ provide additional or different license terms and conditions for use,
130
+ reproduction, or distribution of Your modifications, or for any such
131
+ Derivative Works as a whole, provided Your use, reproduction, and
132
+ distribution of the Work otherwise complies with the conditions stated
133
+ in this License.
134
+
135
+ ### 5. Submission of Contributions.
136
+
137
+ Unless You explicitly state otherwise, any Contribution intentionally
138
+ submitted for inclusion in the Work by You to the Licensor shall be
139
+ under the terms and conditions of this License, without any additional
140
+ terms or conditions. Notwithstanding the above, nothing herein shall
141
+ supersede or modify the terms of any separate license agreement you may
142
+ have executed with Licensor regarding such Contributions.
143
+
144
+ ### 6. Trademarks.
145
+
146
+ This License does not grant permission to use the trade names,
147
+ trademarks, service marks, or product names of the Licensor, except as
148
+ required for reasonable and customary use in describing the origin of
149
+ the Work and reproducing the content of the NOTICE file.
150
+
151
+ ### 7. Disclaimer of Warranty.
152
+
153
+ Unless required by applicable law or agreed to in writing, Licensor
154
+ provides the Work (and each Contributor provides its Contributions) on
155
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
156
+ express or implied, including, without limitation, any warranties or
157
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
158
+ A PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any risks
160
+ associated with Your exercise of permissions under this License.
161
+
162
+ ### 8. Limitation of Liability.
163
+
164
+ In no event and under no legal theory, whether in tort (including
165
+ negligence), contract, or otherwise, unless required by applicable law
166
+ (such as deliberate and grossly negligent acts) or agreed to in writing,
167
+ shall any Contributor be liable to You for damages, including any
168
+ direct, indirect, special, incidental, or consequential damages of any
169
+ character arising as a result of this License or out of the use or
170
+ inability to use the Work (including but not limited to damages for loss
171
+ of goodwill, work stoppage, computer failure or malfunction, or any and
172
+ all other commercial damages or losses), even if such Contributor has
173
+ been advised of the possibility of such damages.
174
+
175
+ ### 9. Accepting Warranty or Additional Liability.
176
+
177
+ While redistributing the Work or Derivative Works thereof, You may
178
+ choose to offer, and charge a fee for, acceptance of support, warranty,
179
+ indemnity, or other liability obligations and/or rights consistent with
180
+ this License. However, in accepting such obligations, You may act only
181
+ on Your own behalf and on Your sole responsibility, not on behalf of any
182
+ other Contributor, and only if You agree to indemnify, defend, and hold
183
+ each Contributor harmless for any liability incurred by, or claims
184
+ asserted against, such Contributor by reason of your accepting any
185
+ such warranty or additional liability.
186
+
187
+ ##### END OF TERMS AND CONDITIONS
188
+
189
+ ## APPENDIX: How to apply the Apache License to your work.
190
+
191
+ To apply the Apache License to your work, attach the following
192
+ boilerplate notice, with the fields enclosed by brackets "[]"
193
+ replaced with your own identifying information. (Don't include the
194
+ brackets!) The text should be enclosed in the appropriate comment
195
+ syntax for the file format. We also recommend that a file or class name
196
+ and description of purpose be included on the same "printed page" as the
197
+ copyright notice for easier identification within third-party archives.
198
+
199
+ > #### Copyright [yyyy] [name of copyright owner]
200
+ >
201
+ > Licensed under the Apache License, Version 2.0 (the "License");
202
+ > you may not use this file except in compliance with the License.
203
+ > You may obtain a copy of the License at
204
+ >
205
+ > [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
206
+ >
207
+ > Unless required by applicable law or agreed to in writing, software
208
+ > distributed under the License is distributed on an "AS IS" BASIS,
209
+ > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
+ > See the License for the specific language governing permissions and
211
+ > limitations under the License.
package/NOTICE.md ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright 2021-2023 Juit GmbH
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ Dependencies Update Checker
2
+ ===========================
3
+
4
+ This package contains a simple script to update the dependencies of a given
5
+ package file.
6
+
7
+ By default it will _extend_ the semantics of `semver` checking for _minor_
8
+ version updates for tilde ranges (`~x.y.z`) and checking for _major_ version
9
+ updates for caret ranges (`^x.y.z`).
10
+
11
+ To adhere to the standard `semver` rules simply specify the `--strict` option.
12
+
13
+ When installed, the `check-updates` script can be invoked directly:
14
+
15
+ ```
16
+ $ check-updates --help
17
+ check-updates [--options ...] [package.json ...]
18
+
19
+ Options:
20
+ -h, --help Show help [boolean]
21
+ -s, --strict Strictly adhere to semver rules for tilde (~x.y.z)
22
+ and caret (^x.y.z) dependency ranges [boolean]
23
+ -q, --quick Consider dev/peer/optional dependency updates if and
24
+ only if the main depenencies also had updates [boolean]
25
+ -d, --debug Output debugging informations [boolean]
26
+ -b, --bump Bump the version of the package file on changes
27
+ [choices: "major", "minor", "patch"]
28
+ -x, --dry-run Only process changes without writing to disk [boolean]
29
+ -v, --version Show version number [boolean]
30
+
31
+ Multiple files (or globs) can be specified on the command line.
32
+
33
+ When no files are specified, the default is to process the "package.json" file
34
+ in the current directory
35
+ $
36
+ ```
37
+
38
+ Legal
39
+ -----
40
+
41
+ * [Copyright Notice](NOTICE.md)
42
+ * [License](LICENSE.md)
@@ -0,0 +1,321 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __commonJS = (cb, mod) => function __require() {
5
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
6
+ };
7
+
8
+ // dist/npmrc.cjs
9
+ var require_npmrc = __commonJS({
10
+ "dist/npmrc.cjs"(exports2, module2) {
11
+ "use strict";
12
+ var __create2 = Object.create;
13
+ var __defProp2 = Object.defineProperty;
14
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
15
+ var __getOwnPropNames3 = Object.getOwnPropertyNames;
16
+ var __getProtoOf2 = Object.getPrototypeOf;
17
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
18
+ var __export = (target, all) => {
19
+ for (var name in all)
20
+ __defProp2(target, name, { get: all[name], enumerable: true });
21
+ };
22
+ var __copyProps2 = (to, from, except, desc) => {
23
+ if (from && typeof from === "object" || typeof from === "function") {
24
+ for (let key of __getOwnPropNames3(from))
25
+ if (!__hasOwnProp2.call(to, key) && key !== except)
26
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
31
+ // If the importer is in node compatibility mode or this is not an ESM
32
+ // file that has been converted to a CommonJS file using a Babel-
33
+ // compatible transform (i.e. "__esModule" has not been set), then set
34
+ // "default" to the CommonJS "module.exports" for node compatibility.
35
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
36
+ mod
37
+ ));
38
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
39
+ var npmrc_exports = {};
40
+ __export(npmrc_exports, {
41
+ readNpmRc: () => readNpmRc
42
+ });
43
+ module2.exports = __toCommonJS(npmrc_exports);
44
+ var import_promises = __toESM2(require("node:fs/promises"));
45
+ var import_node_path = __toESM2(require("node:path"));
46
+ var import_ini = require("ini");
47
+ function replaceEnvironmentVariable(token) {
48
+ return token.replace(/^\$\{?([^}]*)\}?$/, (_match, ...vars) => {
49
+ return process.env[vars[0]] || "";
50
+ });
51
+ }
52
+ async function readFile(filename) {
53
+ try {
54
+ const data = await import_promises.default.readFile(filename, "utf8");
55
+ const npmrc = (0, import_ini.parse)(data);
56
+ for (const key in npmrc) {
57
+ if (typeof npmrc[key] === "string") {
58
+ npmrc[key] = replaceEnvironmentVariable(npmrc[key]);
59
+ }
60
+ }
61
+ return npmrc;
62
+ } catch (error) {
63
+ if (error.code === "ENOENT")
64
+ return {};
65
+ throw error;
66
+ }
67
+ }
68
+ async function readNpmRc(packageJsonFile) {
69
+ const local = readFile(import_node_path.default.resolve(packageJsonFile, "..", ".npmrc"));
70
+ const user = readFile(
71
+ process.env.NPM_CONFIG_USERCONFIG ? process.env.NPM_CONFIG_USERCONFIG : process.env.HOME ? import_node_path.default.resolve(process.env.HOME, ".npmrc") : ""
72
+ );
73
+ const global = readFile(
74
+ process.env.NPM_CONFIG_GLOBALCONFIG ? process.env.NPM_CONFIG_GLOBALCONFIG : "/etc/npmrc"
75
+ );
76
+ return Object.assign({}, ...await Promise.all([global, user, local]));
77
+ }
78
+ }
79
+ });
80
+
81
+ // dist/updater.cjs
82
+ var require_updater = __commonJS({
83
+ "dist/updater.cjs"(exports2, module2) {
84
+ "use strict";
85
+ var __create2 = Object.create;
86
+ var __defProp2 = Object.defineProperty;
87
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
88
+ var __getOwnPropNames3 = Object.getOwnPropertyNames;
89
+ var __getProtoOf2 = Object.getPrototypeOf;
90
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
91
+ var __export = (target, all) => {
92
+ for (var name in all)
93
+ __defProp2(target, name, { get: all[name], enumerable: true });
94
+ };
95
+ var __copyProps2 = (to, from, except, desc) => {
96
+ if (from && typeof from === "object" || typeof from === "function") {
97
+ for (let key of __getOwnPropNames3(from))
98
+ if (!__hasOwnProp2.call(to, key) && key !== except)
99
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
100
+ }
101
+ return to;
102
+ };
103
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
104
+ // If the importer is in node compatibility mode or this is not an ESM
105
+ // file that has been converted to a CommonJS file using a Babel-
106
+ // compatible transform (i.e. "__esModule" has not been set), then set
107
+ // "default" to the CommonJS "module.exports" for node compatibility.
108
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
109
+ mod
110
+ ));
111
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
112
+ var updater_exports = {};
113
+ __export(updater_exports, {
114
+ processPackages: () => processPackages
115
+ });
116
+ module2.exports = __toCommonJS(updater_exports);
117
+ var import_promises = __toESM2(require("node:fs/promises"));
118
+ var import_glob = __toESM2(require("glob"));
119
+ var import_semver = __toESM2(require("semver"));
120
+ var import_npm_registry_fetch = __toESM2(require("npm-registry-fetch"));
121
+ var import_npmrc = require_npmrc();
122
+ var cache = {};
123
+ var { readFile, writeFile } = import_promises.default;
124
+ var [K, R, G, Y, B] = [0, 31, 32, 33, 34].map((x) => `\x1B[${x}m`);
125
+ async function processPackages(patterns, options) {
126
+ const { bump, quick, strict, debug, dryrun } = options;
127
+ function $debug(...args) {
128
+ if (debug && args)
129
+ console.log(`${R}[DEBUG]${K}`, ...args);
130
+ }
131
+ function getVersions(name, npmrc) {
132
+ if (name in cache) {
133
+ $debug(`Returning cached versions for ${Y}${name}${K}`);
134
+ return cache[name];
135
+ }
136
+ $debug(`Retrieving versions for package ${Y}${name}${K}`);
137
+ const range = new import_semver.default.Range(">=0.0.0", { includePrerelease: false });
138
+ return cache[name] = import_npm_registry_fetch.default.json(name, Object.assign({}, npmrc, { spec: name })).then((data) => {
139
+ return Object.entries(data.versions).filter(([, info]) => !info.deprecated).map(([version]) => version).filter((version) => range.test(version)).sort(import_semver.default.rcompare);
140
+ });
141
+ }
142
+ async function updateDependency(name, rangeString, npmrc) {
143
+ const match = /^\s*([~^])\s*(\d+(\.\d+(\.\d+)?)?)\s*$/.exec(rangeString);
144
+ if (!match) {
145
+ $debug(`Not processing range ${G}${rangeString}${K} for ${Y}${name}${K}`);
146
+ return rangeString;
147
+ }
148
+ const [, specifier, version] = match;
149
+ if (!strict) {
150
+ const r = rangeString;
151
+ rangeString = `>=${version}`;
152
+ if (specifier === "~")
153
+ rangeString += ` <${import_semver.default.inc(version, "major")}`;
154
+ $debug(`Extending version for ${Y}${name}${K} from ${G}${r}${K} to ${G}${rangeString}${K}`);
155
+ }
156
+ const range = new import_semver.default.Range(rangeString);
157
+ const versions = await getVersions(name, npmrc);
158
+ for (const v of versions) {
159
+ if (range.test(v))
160
+ return `${specifier}${v}`;
161
+ }
162
+ return `${specifier}${version}`;
163
+ }
164
+ async function processPackage(file) {
165
+ process.stdout.write(`Processing ${G}${file}${K} `);
166
+ const data = JSON.parse(await readFile(file, "utf8"));
167
+ if (data.name) {
168
+ process.stdout.write(`[${Y}${data.name}`);
169
+ if (data.version)
170
+ process.stdout.write(` ${data.version}`);
171
+ process.stdout.write(`${K}] `);
172
+ }
173
+ if (debug)
174
+ process.stdout.write("\n");
175
+ const npmrc = await (0, import_npmrc.readNpmRc)(file);
176
+ const changes2 = [];
177
+ let mainDependencyChanges = 0;
178
+ for (const type in data) {
179
+ if (!type.match(/[dD]ependencies$/))
180
+ continue;
181
+ if (type.match(/bundled?Dependencies/))
182
+ continue;
183
+ const kind = type.length > 12 ? ` [${type.slice(0, -12)}]` : "";
184
+ const dependencies = {};
185
+ const promises = Object.keys(data[type] || {}).sort().map(async (name) => {
186
+ const from = data[type][name];
187
+ const to = await updateDependency(name, from, npmrc);
188
+ if (!debug)
189
+ process.stdout.write(".");
190
+ if (from !== to) {
191
+ changes2.push({ name, from, to, kind });
192
+ if (type === "dependencies")
193
+ mainDependencyChanges++;
194
+ }
195
+ dependencies[name] = to;
196
+ });
197
+ await Promise.all(promises);
198
+ if (Object.keys(dependencies).length) {
199
+ data[type] = dependencies;
200
+ } else {
201
+ delete data[type];
202
+ }
203
+ }
204
+ if (debug)
205
+ process.stdout.write("Updated with");
206
+ if (!changes2.length) {
207
+ console.log(` ${R}no changes${K}`);
208
+ return 0;
209
+ }
210
+ changes2.sort(({ name: a }, { name: b }) => a < b ? -1 : a > b ? 1 : 0);
211
+ console.log(` ${R}${changes2.length} changes${K}`);
212
+ let lname = 0;
213
+ let lfrom = 0;
214
+ let lto = 0;
215
+ for (const { name, from, to } of changes2) {
216
+ lname = lname > name.length ? lname : name.length;
217
+ lfrom = lfrom > from.length ? lfrom : from.length;
218
+ lto = lto > to.length ? lto : to.length;
219
+ }
220
+ for (const { name, from, to, kind } of changes2) {
221
+ console.log(` * ${Y}${name.padEnd(lname)}${K} : ${G}${from.padStart(lfrom)}${K} -> ${G}${to.padEnd(lto)} ${B}${kind}${K}`);
222
+ }
223
+ if (quick && mainDependencyChanges === 0) {
224
+ console.log(`No changes to main dependencies, ${Y}ignoring ${changes2.length} other changes${K}`);
225
+ return 0;
226
+ }
227
+ if (bump) {
228
+ const bumped = import_semver.default.inc(data.version, bump);
229
+ console.log(` - Bumping version ${Y}${data.version}${K} -> ${G}${bumped}${K}`);
230
+ data.version = bumped;
231
+ }
232
+ if (dryrun) {
233
+ console.log(`Dry run, not writing ${G}${file}${K}`);
234
+ return 0;
235
+ } else {
236
+ await writeFile(file, JSON.stringify(data, null, 2) + "\n");
237
+ return changes2.length;
238
+ }
239
+ }
240
+ const files = await (0, import_glob.default)(patterns);
241
+ let changes = 0;
242
+ let newline = false;
243
+ for (const file of files) {
244
+ if (newline)
245
+ console.log();
246
+ const packageChanges = await processPackage(file);
247
+ newline = !!packageChanges;
248
+ changes += packageChanges;
249
+ }
250
+ return changes;
251
+ }
252
+ }
253
+ });
254
+
255
+ // dist/main.cjs
256
+ var __create = Object.create;
257
+ var __defProp = Object.defineProperty;
258
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
259
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
260
+ var __getProtoOf = Object.getPrototypeOf;
261
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
262
+ var __copyProps = (to, from, except, desc) => {
263
+ if (from && typeof from === "object" || typeof from === "function") {
264
+ for (let key of __getOwnPropNames2(from))
265
+ if (!__hasOwnProp.call(to, key) && key !== except)
266
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
267
+ }
268
+ return to;
269
+ };
270
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
271
+ // If the importer is in node compatibility mode or this is not an ESM
272
+ // file that has been converted to a CommonJS file using a Babel-
273
+ // compatible transform (i.e. "__esModule" has not been set), then set
274
+ // "default" to the CommonJS "module.exports" for node compatibility.
275
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
276
+ mod
277
+ ));
278
+ var yargs = __toESM(require("yargs"));
279
+ var import_updater = require_updater();
280
+ var parsed = yargs.usage("$0 [--options ...] [package.json ...]").help("h").alias("h", "help").alias("v", "version").option("s", {
281
+ alias: "strict",
282
+ type: "boolean",
283
+ description: [
284
+ "Strictly adhere to semver rules for tilde (~x.y.z)",
285
+ "and caret (^x.y.z) dependency ranges"
286
+ ].join("\n")
287
+ }).option("q", {
288
+ alias: "quick",
289
+ type: "boolean",
290
+ description: [
291
+ "Consider dev/peer/optional dependency updates if and",
292
+ "only if the main depenencies also had updates"
293
+ ].join("\n")
294
+ }).option("d", {
295
+ alias: "debug",
296
+ type: "boolean",
297
+ description: "Output debugging informations"
298
+ }).options("b", {
299
+ alias: "bump",
300
+ coerce: (bump) => bump == true ? "patch" : bump,
301
+ choices: ["major", "minor", "patch"],
302
+ description: "Bump the version of the package file on changes"
303
+ }).options("x", {
304
+ alias: "dry-run",
305
+ type: "boolean",
306
+ description: "Only process changes without writing to disk"
307
+ }).epilogue([
308
+ "Multiple files (or globs) can be specified on the command line.\n",
309
+ 'When no files are specified, the default is to process the "package.json" file in the current directory'
310
+ ].join("\n")).strictOptions().argv;
311
+ Promise.resolve(parsed).then(({ b: bump, s: strict, q: quick, d: debug, x: dryrun, _: args = [] }) => {
312
+ const files = args.map((arg) => arg.toString());
313
+ if (!files.length)
314
+ files.push("package.json");
315
+ (0, import_updater.processPackages)(files, { strict, quick, debug, dryrun, bump }).then((changes) => {
316
+ process.exit(changes ? 0 : 1);
317
+ }).catch((error) => {
318
+ console.error(error);
319
+ process.exit(1);
320
+ });
321
+ }).catch((error) => console.log(error));
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@juit/check-updates",
3
+ "version": "2.0.0",
4
+ "description": "Small and fast utility to update package dependencies",
5
+ "author": "Team Juit <developers@juit.com>",
6
+ "license": "Apache-2.0",
7
+ "bin": {
8
+ "check-updates": "check-updates.js"
9
+ },
10
+ "scripts": {
11
+ "build": "plug",
12
+ "coverage": "plug coverage",
13
+ "dev": "plug coverage -w src -w test",
14
+ "lint": "plug lint",
15
+ "test": "plug test",
16
+ "transpile": "plug transpile"
17
+ },
18
+ "dependencies": {
19
+ "glob": "^9.2.1",
20
+ "ini": "^3.0.1",
21
+ "npm-registry-fetch": "^14.0.3",
22
+ "semver": "^7.3.8",
23
+ "yargs": "^17.7.1"
24
+ },
25
+ "devDependencies": {
26
+ "@plugjs/build": "^0.2.4",
27
+ "@types/glob": "^8.1.0",
28
+ "@types/ini": "^1.3.31",
29
+ "@types/npm-registry-fetch": "^8.0.4",
30
+ "@types/semver": "^7.3.13",
31
+ "@types/yargs": "^17.0.22"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+ssh://git@github.com/juitnow/juit-check-updates.git"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/juitnow/juit-check-updates/issues"
39
+ },
40
+ "homepage": "https://github.com/juitnow/juit-check-updates#readme",
41
+ "files": [
42
+ "*.md",
43
+ "check-updates.js",
44
+ "src/"
45
+ ],
46
+ "directories": {
47
+ "test": "test"
48
+ },
49
+ "keywords": [
50
+ "check",
51
+ "dependencies",
52
+ "management",
53
+ "ncu",
54
+ "npm",
55
+ "package.json",
56
+ "updater",
57
+ "updates",
58
+ "upgrades",
59
+ "version"
60
+ ]
61
+ }
package/src/main.ts ADDED
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+
3
+ import * as yargs from 'yargs'
4
+
5
+ import { processPackages } from './updater'
6
+
7
+ type ReleaseType = 'major' | 'minor' | 'patch'
8
+
9
+ /* ========================================================================== *
10
+ * CALL UP MAIN() AND DEAL WITH THE ASYNC PROMISE IT RETURNS *
11
+ * ========================================================================== */
12
+
13
+ /* Parse command line arguments */
14
+ const parsed = yargs
15
+ .usage('$0 [--options ...] [package.json ...]')
16
+ .help('h').alias('h', 'help').alias('v', 'version')
17
+ .option('s', {
18
+ alias: 'strict',
19
+ type: 'boolean',
20
+ description: [
21
+ 'Strictly adhere to semver rules for tilde (~x.y.z)',
22
+ 'and caret (^x.y.z) dependency ranges',
23
+ ].join('\n'),
24
+ })
25
+ .option('q', {
26
+ alias: 'quick',
27
+ type: 'boolean',
28
+ description: [
29
+ 'Consider dev/peer/optional dependency updates if and',
30
+ 'only if the main depenencies also had updates',
31
+ ].join('\n'),
32
+ })
33
+ .option('d', {
34
+ alias: 'debug',
35
+ type: 'boolean',
36
+ description: 'Output debugging informations',
37
+ })
38
+ .options('b', {
39
+ alias: 'bump',
40
+ coerce: ((bump): ReleaseType => bump == true ? 'patch' : bump),
41
+ choices: [ 'major', 'minor', 'patch' ] as ReleaseType[],
42
+ description: 'Bump the version of the package file on changes',
43
+ })
44
+ .options('x', {
45
+ alias: 'dry-run',
46
+ type: 'boolean',
47
+ description: 'Only process changes without writing to disk',
48
+ })
49
+ .epilogue([
50
+ 'Multiple files (or globs) can be specified on the command line.\n',
51
+ 'When no files are specified, the default is to process the "package.json" file in the current directory',
52
+ ].join('\n'))
53
+ .strictOptions()
54
+ .argv
55
+
56
+ Promise.resolve(parsed).then(({ b: bump, s: strict, q: quick, d: debug, x: dryrun, _: args = [] }) => {
57
+ /* Normalize arguments and default to package.json in the current directory */
58
+ const files = args.map((arg) => arg.toString())
59
+ if (! files.length) files.push('package.json')
60
+
61
+ /* Process packages, one by one */
62
+ processPackages(files, { strict, quick, debug, dryrun, bump })
63
+ .then((changes) => {
64
+ process.exit(changes ? 0 : 1)
65
+ })
66
+ .catch((error) => {
67
+ console.error(error)
68
+ process.exit(1)
69
+ })
70
+ }).catch((error) => console.log(error))
package/src/npmrc.ts ADDED
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ import { parse } from 'ini'
5
+
6
+ function replaceEnvironmentVariable(token: string): string {
7
+ return token.replace(/^\$\{?([^}]*)\}?$/, (_match, ...vars: any[]) => {
8
+ return process.env[vars[0]] || ''
9
+ })
10
+ }
11
+
12
+ async function readFile(filename: string): Promise<Record<string, any>> {
13
+ try {
14
+ const data = await fs.readFile(filename, 'utf8')
15
+ const npmrc = parse(data)
16
+
17
+ for (const key in npmrc) {
18
+ if (typeof npmrc[key] === 'string') {
19
+ npmrc[key] = replaceEnvironmentVariable(npmrc[key])
20
+ }
21
+ }
22
+
23
+ return npmrc
24
+ } catch (error: any) {
25
+ if (error.code === 'ENOENT') return {}
26
+ throw error
27
+ }
28
+ }
29
+
30
+ export async function readNpmRc(packageJsonFile: string): Promise<Record<string, any>> {
31
+ const local = readFile(path.resolve(packageJsonFile, '..', '.npmrc'))
32
+ const user = readFile(
33
+ process.env.NPM_CONFIG_USERCONFIG ?
34
+ process.env.NPM_CONFIG_USERCONFIG :
35
+ process.env.HOME ? path.resolve(process.env.HOME, '.npmrc') : '' )
36
+ const global = readFile(
37
+ process.env.NPM_CONFIG_GLOBALCONFIG ?
38
+ process.env.NPM_CONFIG_GLOBALCONFIG :
39
+ '/etc/npmrc')
40
+ return Object.assign({}, ...await Promise.all([ global, user, local ]))
41
+ }
package/src/updater.ts ADDED
@@ -0,0 +1,210 @@
1
+ import fs from 'node:fs/promises'
2
+
3
+ import glob from 'glob'
4
+ import semver from 'semver'
5
+ import fetch from 'npm-registry-fetch'
6
+
7
+ import { readNpmRc } from './npmrc'
8
+
9
+ import type { ReleaseType } from 'semver'
10
+
11
+ export type UpdaterOptions = {
12
+ bump?: ReleaseType,
13
+ strict?: boolean,
14
+ quick?: boolean,
15
+ debug?: boolean,
16
+ dryrun?: boolean,
17
+ }
18
+
19
+ interface Change {
20
+ name: string,
21
+ from: string,
22
+ to: string,
23
+ kind: string,
24
+ }
25
+
26
+ /* Our packages cache version */
27
+ const cache: Record<string, Promise<string[]>> = {}
28
+
29
+ /* Destructuring from "fs.promises" */
30
+ const { readFile, writeFile } = fs
31
+
32
+ /* Colors */
33
+ const [ K, R, G, Y, B ] = [ 0, 31, 32, 33, 34 ].map((x) => `\u001b[${x}m`)
34
+
35
+ /* ========================================================================== *
36
+ * Process a number of package files one by one *
37
+ * ========================================================================== */
38
+ export async function processPackages(
39
+ patterns: string | string[],
40
+ options: UpdaterOptions,
41
+ ): Promise<number> {
42
+ /* Destructure our options */
43
+ const { bump, quick, strict, debug, dryrun } = options
44
+
45
+ /* ------------------------------------------------------------------------ *
46
+ * A super-simple debug function *
47
+ * ------------------------------------------------------------------------ */
48
+ function $debug(...args: string[]): void {
49
+ if (debug && args) console.log(`${R}[DEBUG]${K}`, ...args)
50
+ }
51
+
52
+ /* ------------------------------------------------------------------------ *
53
+ * Download (or return cached) versions for a package, greatest first *
54
+ * (we're upgrading, ainnit?) without any prerelease *
55
+ * ------------------------------------------------------------------------ */
56
+
57
+ function getVersions(name: string, npmrc: Record<string, any>): Promise<string[]> {
58
+ if (name in cache) {
59
+ $debug(`Returning cached versions for ${Y}${name}${K}`)
60
+ return cache[name]
61
+ }
62
+
63
+ $debug(`Retrieving versions for package ${Y}${name}${K}`)
64
+
65
+ const range = new semver.Range('>=0.0.0', { includePrerelease: false })
66
+
67
+ return cache[name] = fetch.json(name, Object.assign({}, npmrc, { spec: name }))
68
+ .then((data: any) => {
69
+ return Object.entries(data.versions as Record<string, Record<string, any>>)
70
+ .filter(([ , info ]) => ! info.deprecated) // no deprecated
71
+ .map(([ version ]) => version) // extract key (version)
72
+ .filter((version) => range.test(version)) // range match
73
+ .sort(semver.rcompare)
74
+ })
75
+ }
76
+
77
+ /* ------------------------------------------------------------------------ *
78
+ * Update the version for a single dependency *
79
+ * ------------------------------------------------------------------------ */
80
+ async function updateDependency(name: string, rangeString: string, npmrc: Record<string, any>): Promise<string> {
81
+ const match = /^\s*([~^])\s*(\d+(\.\d+(\.\d+)?)?)\s*$/.exec(rangeString)
82
+ if (! match) {
83
+ $debug(`Not processing range ${G}${rangeString}${K} for ${Y}${name}${K}`)
84
+ return rangeString
85
+ }
86
+
87
+ const [ , specifier, version ] = match
88
+
89
+ if (! strict) {
90
+ const r = rangeString
91
+ rangeString = `>=${version}`
92
+ if (specifier === '~') rangeString += ` <${semver.inc(version, 'major')}`
93
+ $debug(`Extending version for ${Y}${name}${K} from ${G}${r}${K} to ${G}${rangeString}${K}`)
94
+ }
95
+
96
+ const range = new semver.Range(rangeString)
97
+ const versions = await getVersions(name, npmrc)
98
+
99
+ for (const v of versions) {
100
+ if (range.test(v)) return `${specifier}${v}`
101
+ }
102
+ return `${specifier}${version}`
103
+ }
104
+
105
+ /* ------------------------------------------------------------------------ *
106
+ * Process all dependencies in a package file *
107
+ * ------------------------------------------------------------------------ */
108
+ async function processPackage(file: string): Promise<number> {
109
+ process.stdout.write(`Processing ${G}${file}${K} `)
110
+
111
+ const data = JSON.parse(await readFile(file, 'utf8'))
112
+ if (data.name) {
113
+ process.stdout.write(`[${Y}${data.name}`)
114
+ if (data.version) process.stdout.write(` ${data.version}`)
115
+ process.stdout.write(`${K}] `)
116
+ }
117
+ if (debug) process.stdout.write('\n')
118
+
119
+ const npmrc = await readNpmRc(file)
120
+
121
+ const changes: Change[] = []
122
+ let mainDependencyChanges = 0
123
+
124
+ for (const type in data) {
125
+ if (! type.match(/[dD]ependencies$/)) continue
126
+ if (type.match(/bundled?Dependencies/)) continue
127
+
128
+ const kind = type.length > 12 ? ` [${type.slice(0, -12)}]` : ''
129
+
130
+ const dependencies: Record<string, string> = {}
131
+ const promises = Object.keys(data[type] || {}).sort().map(async (name) => {
132
+ const from: string = data[type][name]
133
+ const to = await updateDependency(name, from, npmrc)
134
+ if (! debug) process.stdout.write('.')
135
+ if (from !== to) {
136
+ changes.push({ name, from, to, kind })
137
+ if (type === 'dependencies') mainDependencyChanges ++
138
+ }
139
+ dependencies[name] = to
140
+ })
141
+
142
+ await Promise.all(promises)
143
+
144
+ if (Object.keys(dependencies).length) {
145
+ data[type] = dependencies
146
+ } else {
147
+ delete data[type]
148
+ }
149
+ }
150
+
151
+ if (debug) process.stdout.write('Updated with')
152
+
153
+ if (! changes.length) {
154
+ console.log(` ${R}no changes${K}`)
155
+ return 0
156
+ }
157
+
158
+ /* Really pretty print */
159
+ changes.sort(({ name: a }, { name: b }) => a < b ? -1 : a > b ? 1 : 0)
160
+ console.log(` ${R}${changes.length} changes${K}`)
161
+ let lname = 0; let lfrom = 0; let lto = 0
162
+ for (const { name, from, to } of changes) {
163
+ lname = lname > name.length ? lname : name.length
164
+ lfrom = lfrom > from.length ? lfrom : from.length
165
+ lto = lto > to.length ? lto : to.length
166
+ }
167
+
168
+ for (const { name, from, to, kind } of changes) {
169
+ console.log(` * ${Y}${name.padEnd(lname)}${K} : ${G}${from.padStart(lfrom)}${K} -> ${G}${to.padEnd(lto)} ${B}${kind}${K}`)
170
+ }
171
+
172
+ /* Ignore all changes if no main changes, and in "quick" mode */
173
+ if (quick && (mainDependencyChanges === 0)) {
174
+ console.log(`No changes to main dependencies, ${Y}ignoring ${changes.length} other changes${K}`)
175
+ return 0
176
+ }
177
+
178
+ /* Bump the package if we need to */
179
+ if (bump) {
180
+ const bumped = semver.inc(data.version, bump)
181
+ console.log(` - Bumping version ${Y}${data.version}${K} -> ${G}${bumped}${K}`)
182
+ data.version = bumped
183
+ }
184
+
185
+ /* Write out the new package file */
186
+ if (dryrun) {
187
+ console.log(`Dry run, not writing ${G}${file}${K}`)
188
+ return 0
189
+ } else {
190
+ await writeFile(file, JSON.stringify(data, null, 2) + '\n')
191
+ return changes.length
192
+ }
193
+ }
194
+
195
+ /* ------------------------------------------------------------------------ *
196
+ * Process a number of package files one by one *
197
+ * ------------------------------------------------------------------------ */
198
+ const files = await glob(patterns)
199
+ let changes = 0
200
+
201
+ let newline = false
202
+ for (const file of files) {
203
+ if (newline) console.log()
204
+ const packageChanges = await processPackage(file)
205
+ newline = !! packageChanges
206
+ changes += packageChanges
207
+ }
208
+
209
+ return changes
210
+ }