binary-collections 2.0.8 → 2.0.9

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.
@@ -0,0 +1,226 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ const fs = require("fs");
11
+ const path = require("path");
12
+ const { EOL } = require("os");
13
+ const { getArgs } = require("./utils");
14
+ const spawn = require("child_process").spawn;
15
+ const pkgPath = path.join(process.cwd(), "package.json");
16
+ if (!fs.existsSync(pkgPath)) {
17
+ throw new Error(`package.json not found at ${pkgPath}`);
18
+ }
19
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
20
+ const args = getArgs();
21
+ // Show help if no arguments or --help/-h is passed
22
+ if (args.help || args.h) {
23
+ showHelp();
24
+ }
25
+ /**
26
+ * Prints help information for the changelog script.
27
+ */
28
+ function showHelp() {
29
+ console.log(`\nUsage: node changelog.js [options]\n`);
30
+ console.log(`Options:`);
31
+ console.log(` --help, -h Show this help message and exit`);
32
+ console.log(`\nDescription:`);
33
+ console.log(` Generates a CHANGELOG.md file from git commit history.`);
34
+ console.log(` - Looks for version bumps and groups commits by version.`);
35
+ console.log(` - Skips dependabot and irrelevant commits.`);
36
+ console.log(` - Outputs the original git log to tmp/original.md for reference.`);
37
+ console.log(`\nExample:`);
38
+ console.log(` node changelog.js`);
39
+ console.log(``);
40
+ }
41
+ /**
42
+ * git
43
+ * @param {string[]} command
44
+ * @returns {Promise<string>}
45
+ */
46
+ const gitExec = (command) => new Promise((resolve, reject) => {
47
+ const thread = spawn("git", command, { stdio: ["inherit", "pipe", "pipe"] });
48
+ const stdOut = [];
49
+ const stdErr = [];
50
+ thread.stdout.on("data", (data) => {
51
+ stdOut.push(data.toString("utf8"));
52
+ });
53
+ thread.stderr.on("data", (data) => {
54
+ stdErr.push(data.toString("utf8"));
55
+ });
56
+ thread.on("close", () => {
57
+ if (stdErr.length) {
58
+ reject(stdErr.join(""));
59
+ return;
60
+ }
61
+ resolve(stdOut.join());
62
+ });
63
+ });
64
+ /**
65
+ * Extracts all version numbers in X.X.X format from a multiline string.
66
+ * @param {string} str
67
+ * @returns {string[]}
68
+ */
69
+ function extractVersions(str) {
70
+ const regex = /\bv?(\d+\.\d+\.\d+)\b/g;
71
+ const matches = [];
72
+ let match;
73
+ while ((match = regex.exec(str)) !== null) {
74
+ matches.push(match[1]);
75
+ }
76
+ return Array.from(new Set(matches));
77
+ }
78
+ // Git log format used:
79
+ // %h - Abbreviated commit hash
80
+ // %ad - Author date (formatted as "YYYY-MM-DD HH:MM:SS")
81
+ // %B - Raw body (commit message)
82
+ // %d - Ref names (branch, tag, etc.)
83
+ // Fields are separated by " !|! "
84
+ // Example: --pretty=format:"%h !|! %ad !|! %B %d" --date=format:"%Y-%m-%d %H:%M:%S"
85
+ // `--pretty=format:"%h !|! %ad !|! %B %d"`, `--date=format:"%Y-%m-%d %H:%M:%S"`
86
+ // Now includes author and committer name/email in the log format
87
+ (() => __awaiter(this, void 0, void 0, function* () {
88
+ const log = yield gitExec([
89
+ "log",
90
+ "--reverse",
91
+ `--pretty=format:"=!=%h !|! %ad !|! %an !|! %cn !|! %s !|! %B !|! %d=!="`,
92
+ `--date=format:"%Y-%m-%d %H:%M:%S"`
93
+ ]);
94
+ let markdown = `## CHANGELOG of ${pkg.name}\n\n`;
95
+ const repo = yield gitExec(["remote", "get-url", "origin"]);
96
+ const repoUrl = repo.trim().replace(/\.git$/, "");
97
+ console.log(`Repository URL: ${repoUrl}`);
98
+ const matches = [...log.matchAll(/=!=(.*?)(?:=!=|=!=,)/gs)];
99
+ const results = matches.map((m) => m[1].trim());
100
+ /** @type {Record<string, string[]>} */
101
+ const versionsCommits = {};
102
+ let currentVersionCommit = "";
103
+ for (const str of results) {
104
+ const splitx = str.split("!|!").map((s) => s.trim());
105
+ // Now splitx: [hash, date, authorName, committerName, summary, message, ref]
106
+ const o = {
107
+ hash: splitx[0] ? splitx[0] : "",
108
+ date: splitx[1] ? splitx[1].replace(/^"|"$/g, "") : "",
109
+ authorName: splitx[2] ? splitx[2] : "",
110
+ committerName: splitx[3] ? splitx[3] : "",
111
+ summary: splitx[4] ? splitx[4] : "",
112
+ message: splitx[5] ? splitx[5] : "",
113
+ ref: splitx[6] ? splitx[6] : ""
114
+ };
115
+ let isBumped = /chore\(bump\)|chore: release/i.test(o.summary) || /release/i.test(o.summary) || /tag: v/i.test(o.summary);
116
+ if (o.summary.trim().startsWith("v")) {
117
+ isBumped = true; // Treat any commit starting with 'v' as a version bump
118
+ }
119
+ if (/^\d+\.\d+\.\d+$/.test(o.summary.trim())) {
120
+ isBumped = true; // Treat commits with version format as version bumps
121
+ }
122
+ if (o.summary.trim().startsWith("fix:")) {
123
+ isBumped = false; // Do not treat 'fix:' commits as version bumps
124
+ }
125
+ if (isBumped && !extractVersions(o.summary).length > 0)
126
+ isBumped = false; // Ensure we have a version in the summary
127
+ if (o.hash && o.date && o.message) {
128
+ // Skip commits by dependabot[bot]
129
+ if (o.authorName === "dependabot[bot]") {
130
+ continue;
131
+ }
132
+ // Skip commits by regex
133
+ if (/^chore\(tarball\): update|merge pull request|merge branch|^migrate from|^update$|^update build from https?:\/\//i.test(o.message)) {
134
+ continue;
135
+ }
136
+ // Skip build summary messages like "Build Tue Dec 27 20:18:29 UTC 2022"
137
+ if (/^Build\s+\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\w+\s+\d{4}$/i.test(o.summary)) {
138
+ continue;
139
+ }
140
+ if (/initial commit/i.test(o.message)) {
141
+ versionsCommits["0.0.0"] = [];
142
+ currentVersionCommit = "0.0.0";
143
+ continue;
144
+ }
145
+ if (isBumped) {
146
+ console.log(`Detected version bump: ${o.summary}`);
147
+ const v = extractVersions(o.message).join(", ");
148
+ versionsCommits[v] = [];
149
+ currentVersionCommit = v;
150
+ }
151
+ else {
152
+ if (!currentVersionCommit) {
153
+ throw new Error(`No current version commit set for message: ${o.message} (hash: ${o.hash})`);
154
+ }
155
+ // Remove all trailing quotes, spaces, and commas from message
156
+ const cleanMsg = o.message.replace(/["'\s,]+$/g, "");
157
+ // Overwrite previous entry if message is duplicated (keep latest hash)
158
+ const commitsArr = versionsCommits[currentVersionCommit];
159
+ // Find index of previous entry with the same message (message is now on the line after the metadata)
160
+ const prevIdx = commitsArr.findIndex((entry) => {
161
+ // Extract the message part (after the first empty line)
162
+ const parts = entry.split(/\r?\n/);
163
+ // Find the first non-empty line after the metadata line
164
+ let msgLine = "";
165
+ for (let i = 1; i < parts.length; i++) {
166
+ if (parts[i].trim() !== "") {
167
+ msgLine = parts[i].trim();
168
+ break;
169
+ }
170
+ }
171
+ return msgLine === cleanMsg;
172
+ });
173
+ // Add changelog entry without author/committer info
174
+ let newEntry;
175
+ if (cleanMsg.includes("\n")) {
176
+ // Multiline message: put message on new line
177
+ newEntry = `- [ _${o.date}_ ] [${o.hash}](<${repoUrl}/commit/${o.hash}>)` + EOL + EOL + `${cleanMsg}`;
178
+ }
179
+ else {
180
+ // Single line message: put message on same line
181
+ newEntry = `- [ _${o.date}_ ] [${o.hash}](<${repoUrl}/commit/${o.hash}>) ${cleanMsg}`;
182
+ }
183
+ if (prevIdx !== -1) {
184
+ // Overwrite previous occurrence with the latest hash/date
185
+ commitsArr[prevIdx] = newEntry;
186
+ }
187
+ else {
188
+ commitsArr.push(newEntry);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ // Iterate versionsCommits in reverse order
194
+ const versions = Object.keys(versionsCommits).sort((a, b) => {
195
+ const aParts = a.split(".").map(Number);
196
+ const bParts = b.split(".").map(Number);
197
+ for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
198
+ const aPart = aParts[i] || 0; // Default to 0 if part is missing
199
+ const bPart = bParts[i] || 0; // Default to 0 if part is missing
200
+ if (aPart !== bPart) {
201
+ return bPart - aPart; // Sort in descending order
202
+ }
203
+ }
204
+ return 0; // They are equal
205
+ });
206
+ for (const version of versions) {
207
+ if (versionsCommits[version].length > 0) {
208
+ markdown += `\n### ${version}\n\n`;
209
+ markdown += versionsCommits[version]
210
+ .map((str) => {
211
+ const lines = str.trim().split(/\r?\n/);
212
+ return [lines[0], ...lines.slice(1).map((line) => " " + line)].join(EOL);
213
+ })
214
+ .join(EOL);
215
+ }
216
+ else {
217
+ markdown += `\n### ${version}\n\n`;
218
+ markdown += `- No changes recorded for this version.\n`;
219
+ }
220
+ }
221
+ fs.mkdirSync(path.join(__dirname, "tmp"), { recursive: true });
222
+ fs.writeFileSync(path.join(__dirname, "tmp/original.md"), log);
223
+ fs.writeFileSync(path.join(__dirname, "CHANGELOG.md"), markdown);
224
+ console.log(`Original log written to tmp/original.md`);
225
+ console.log(`Changelog updated successfully. You can find it at CHANGELOG.md`);
226
+ }))();
@@ -0,0 +1,199 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import {
3
+ require_utils
4
+ } from "./chunk-APBWENF6.mjs";
5
+ import {
6
+ __dirname,
7
+ __require,
8
+ init_esm_shims
9
+ } from "./chunk-AASHBCRW.mjs";
10
+
11
+ // src/changelog.js
12
+ init_esm_shims();
13
+ var fs = __require("fs");
14
+ var path = __require("path");
15
+ var { EOL } = __require("os");
16
+ var { getArgs } = require_utils();
17
+ var spawn = __require("child_process").spawn;
18
+ var pkgPath = path.join(process.cwd(), "package.json");
19
+ if (!fs.existsSync(pkgPath)) {
20
+ throw new Error(`package.json not found at ${pkgPath}`);
21
+ }
22
+ var pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
23
+ var args = getArgs();
24
+ if (args.help || args.h) {
25
+ showHelp();
26
+ }
27
+ function showHelp() {
28
+ console.log(`
29
+ Usage: node changelog.js [options]
30
+ `);
31
+ console.log(`Options:`);
32
+ console.log(` --help, -h Show this help message and exit`);
33
+ console.log(`
34
+ Description:`);
35
+ console.log(` Generates a CHANGELOG.md file from git commit history.`);
36
+ console.log(` - Looks for version bumps and groups commits by version.`);
37
+ console.log(` - Skips dependabot and irrelevant commits.`);
38
+ console.log(` - Outputs the original git log to tmp/original.md for reference.`);
39
+ console.log(`
40
+ Example:`);
41
+ console.log(` node changelog.js`);
42
+ console.log(``);
43
+ }
44
+ var gitExec = (command) => new Promise((resolve, reject) => {
45
+ const thread = spawn("git", command, { stdio: ["inherit", "pipe", "pipe"] });
46
+ const stdOut = [];
47
+ const stdErr = [];
48
+ thread.stdout.on("data", (data) => {
49
+ stdOut.push(data.toString("utf8"));
50
+ });
51
+ thread.stderr.on("data", (data) => {
52
+ stdErr.push(data.toString("utf8"));
53
+ });
54
+ thread.on("close", () => {
55
+ if (stdErr.length) {
56
+ reject(stdErr.join(""));
57
+ return;
58
+ }
59
+ resolve(stdOut.join());
60
+ });
61
+ });
62
+ function extractVersions(str) {
63
+ const regex = /\bv?(\d+\.\d+\.\d+)\b/g;
64
+ const matches = [];
65
+ let match;
66
+ while ((match = regex.exec(str)) !== null) {
67
+ matches.push(match[1]);
68
+ }
69
+ return Array.from(new Set(matches));
70
+ }
71
+ (async () => {
72
+ const log = await gitExec([
73
+ "log",
74
+ "--reverse",
75
+ `--pretty=format:"=!=%h !|! %ad !|! %an !|! %cn !|! %s !|! %B !|! %d=!="`,
76
+ `--date=format:"%Y-%m-%d %H:%M:%S"`
77
+ ]);
78
+ let markdown = `## CHANGELOG of ${pkg.name}
79
+
80
+ `;
81
+ const repo = await gitExec(["remote", "get-url", "origin"]);
82
+ const repoUrl = repo.trim().replace(/\.git$/, "");
83
+ console.log(`Repository URL: ${repoUrl}`);
84
+ const matches = [...log.matchAll(/=!=(.*?)(?:=!=|=!=,)/gs)];
85
+ const results = matches.map((m) => m[1].trim());
86
+ const versionsCommits = {};
87
+ let currentVersionCommit = "";
88
+ for (const str of results) {
89
+ const splitx = str.split("!|!").map((s) => s.trim());
90
+ const o = {
91
+ hash: splitx[0] ? splitx[0] : "",
92
+ date: splitx[1] ? splitx[1].replace(/^"|"$/g, "") : "",
93
+ authorName: splitx[2] ? splitx[2] : "",
94
+ committerName: splitx[3] ? splitx[3] : "",
95
+ summary: splitx[4] ? splitx[4] : "",
96
+ message: splitx[5] ? splitx[5] : "",
97
+ ref: splitx[6] ? splitx[6] : ""
98
+ };
99
+ let isBumped = /chore\(bump\)|chore: release/i.test(o.summary) || /release/i.test(o.summary) || /tag: v/i.test(o.summary);
100
+ if (o.summary.trim().startsWith("v")) {
101
+ isBumped = true;
102
+ }
103
+ if (/^\d+\.\d+\.\d+$/.test(o.summary.trim())) {
104
+ isBumped = true;
105
+ }
106
+ if (o.summary.trim().startsWith("fix:")) {
107
+ isBumped = false;
108
+ }
109
+ if (isBumped && !extractVersions(o.summary).length > 0) isBumped = false;
110
+ if (o.hash && o.date && o.message) {
111
+ if (o.authorName === "dependabot[bot]") {
112
+ continue;
113
+ }
114
+ if (/^chore\(tarball\): update|merge pull request|merge branch|^migrate from|^update$|^update build from https?:\/\//i.test(
115
+ o.message
116
+ )) {
117
+ continue;
118
+ }
119
+ if (/^Build\s+\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\w+\s+\d{4}$/i.test(o.summary)) {
120
+ continue;
121
+ }
122
+ if (/initial commit/i.test(o.message)) {
123
+ versionsCommits["0.0.0"] = [];
124
+ currentVersionCommit = "0.0.0";
125
+ continue;
126
+ }
127
+ if (isBumped) {
128
+ console.log(`Detected version bump: ${o.summary}`);
129
+ const v = extractVersions(o.message).join(", ");
130
+ versionsCommits[v] = [];
131
+ currentVersionCommit = v;
132
+ } else {
133
+ if (!currentVersionCommit) {
134
+ throw new Error(`No current version commit set for message: ${o.message} (hash: ${o.hash})`);
135
+ }
136
+ const cleanMsg = o.message.replace(/["'\s,]+$/g, "");
137
+ const commitsArr = versionsCommits[currentVersionCommit];
138
+ const prevIdx = commitsArr.findIndex((entry) => {
139
+ const parts = entry.split(/\r?\n/);
140
+ let msgLine = "";
141
+ for (let i = 1; i < parts.length; i++) {
142
+ if (parts[i].trim() !== "") {
143
+ msgLine = parts[i].trim();
144
+ break;
145
+ }
146
+ }
147
+ return msgLine === cleanMsg;
148
+ });
149
+ let newEntry;
150
+ if (cleanMsg.includes("\n")) {
151
+ newEntry = `- [ _${o.date}_ ] [${o.hash}](<${repoUrl}/commit/${o.hash}>)` + EOL + EOL + `${cleanMsg}`;
152
+ } else {
153
+ newEntry = `- [ _${o.date}_ ] [${o.hash}](<${repoUrl}/commit/${o.hash}>) ${cleanMsg}`;
154
+ }
155
+ if (prevIdx !== -1) {
156
+ commitsArr[prevIdx] = newEntry;
157
+ } else {
158
+ commitsArr.push(newEntry);
159
+ }
160
+ }
161
+ }
162
+ }
163
+ const versions = Object.keys(versionsCommits).sort((a, b) => {
164
+ const aParts = a.split(".").map(Number);
165
+ const bParts = b.split(".").map(Number);
166
+ for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
167
+ const aPart = aParts[i] || 0;
168
+ const bPart = bParts[i] || 0;
169
+ if (aPart !== bPart) {
170
+ return bPart - aPart;
171
+ }
172
+ }
173
+ return 0;
174
+ });
175
+ for (const version of versions) {
176
+ if (versionsCommits[version].length > 0) {
177
+ markdown += `
178
+ ### ${version}
179
+
180
+ `;
181
+ markdown += versionsCommits[version].map((str) => {
182
+ const lines = str.trim().split(/\r?\n/);
183
+ return [lines[0], ...lines.slice(1).map((line) => " " + line)].join(EOL);
184
+ }).join(EOL);
185
+ } else {
186
+ markdown += `
187
+ ### ${version}
188
+
189
+ `;
190
+ markdown += `- No changes recorded for this version.
191
+ `;
192
+ }
193
+ }
194
+ fs.mkdirSync(path.join(__dirname, "tmp"), { recursive: true });
195
+ fs.writeFileSync(path.join(__dirname, "tmp/original.md"), log);
196
+ fs.writeFileSync(path.join(__dirname, "CHANGELOG.md"), markdown);
197
+ console.log(`Original log written to tmp/original.md`);
198
+ console.log(`Changelog updated successfully. You can find it at CHANGELOG.md`);
199
+ })();
@@ -22,7 +22,7 @@ else {
22
22
  console.warn(`.env file not found at ${envPath}`);
23
23
  }
24
24
  // delete caches leaving single last cache based on creation date
25
- const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
25
+ const ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
26
26
  if (!ACCESS_TOKEN) {
27
27
  throw new Error("Access token is not provided. Please set ACCESS_TOKEN or GITHUB_TOKEN in your environment variables.");
28
28
  }
@@ -14,7 +14,7 @@ if (fs.existsSync(envPath)) {
14
14
 
15
15
  // delete caches leaving single last cache based on creation date
16
16
 
17
- const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
17
+ const ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
18
18
 
19
19
  if (!ACCESS_TOKEN) {
20
20
  throw new Error(
@@ -14,7 +14,7 @@ if (fs.existsSync(envPath)) {
14
14
 
15
15
  // delete caches leaving single last cache based on creation date
16
16
 
17
- const ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
17
+ const ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
18
18
 
19
19
  if (!ACCESS_TOKEN) {
20
20
  throw new Error(
@@ -23,7 +23,7 @@ var require_clean_github_actions_caches = __commonJS({
23
23
  } else {
24
24
  console.warn(`.env file not found at ${envPath}`);
25
25
  }
26
- var ACCESS_TOKEN = process.env.ACCESS_TOKEN || process.env.GITHUB_TOKEN;
26
+ var ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
27
27
  if (!ACCESS_TOKEN) {
28
28
  throw new Error(
29
29
  "Access token is not provided. Please set ACCESS_TOKEN or GITHUB_TOKEN in your environment variables."
package/lib/git-fix.mjs CHANGED
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
+ import {
4
+ require_pull_strategy
5
+ } from "./chunk-SH3L6HHV.mjs";
3
6
  import {
4
7
  require_user_config
5
8
  } from "./chunk-ONIBBBQ3.mjs";
@@ -13,9 +16,6 @@ import {
13
16
  import {
14
17
  require_permissions
15
18
  } from "./chunk-ZYAQRPUL.mjs";
16
- import {
17
- require_pull_strategy
18
- } from "./chunk-SH3L6HHV.mjs";
19
19
  import {
20
20
  require_utils as require_utils2
21
21
  } from "./chunk-EGSSKVDH.mjs";
@@ -4,6 +4,12 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __commonJS = (cb, mod) => function __require() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
7
13
  var __copyProps = (to, from, except, desc) => {
8
14
  if (from && typeof from === "object" || typeof from === "function") {
9
15
  for (let key of __getOwnPropNames(from))
@@ -21,15 +27,182 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
27
  mod
22
28
  ));
23
29
 
30
+ // node_modules/tsup/assets/cjs_shims.js
31
+ var init_cjs_shims = __esm({
32
+ "node_modules/tsup/assets/cjs_shims.js"() {
33
+ }
34
+ });
35
+
36
+ // src/utils.js
37
+ var require_utils = __commonJS({
38
+ "src/utils.js"(exports2, module2) {
39
+ init_cjs_shims();
40
+ var fs2 = require("fs");
41
+ var path2 = require("upath");
42
+ var argv = require("minimist")(process.argv.slice(2));
43
+ var { exec } = require("child_process");
44
+ var { URL: URL2 } = require("url");
45
+ var { promisify } = require("util");
46
+ var execAsync = promisify(exec);
47
+ async function parseGitRemotes() {
48
+ try {
49
+ const { stdout } = await execAsync("git remote -v");
50
+ const lines = stdout.split("\n");
51
+ const remotes = {};
52
+ lines.forEach((line) => {
53
+ const [name, url] = line.split(" ");
54
+ if (name && url) {
55
+ const [repoUrl] = url.split(" ");
56
+ try {
57
+ const parsedUrl = new URL2(repoUrl);
58
+ const pathParts = parsedUrl.pathname.split("/").filter(Boolean);
59
+ if (parsedUrl.hostname === "github.com" && pathParts.length === 2) {
60
+ let repoPath = pathParts.join("/");
61
+ if (repoPath.endsWith(".git")) {
62
+ repoPath = repoPath.slice(0, -4);
63
+ }
64
+ remotes[name] = repoPath;
65
+ }
66
+ } catch (e) {
67
+ console.error("URL Parsing Error:", e.message);
68
+ }
69
+ }
70
+ });
71
+ return remotes;
72
+ } catch (error) {
73
+ console.error("Error:", error.message);
74
+ return {};
75
+ }
76
+ }
77
+ module2.exports.parseGitRemotes = parseGitRemotes;
78
+ function joinPathPreserveDriveLetter(...segments) {
79
+ let fullPath = require("path").join(...segments);
80
+ if (/^[a-z]:\\/.test(fullPath)) {
81
+ fullPath = fullPath.charAt(0).toUpperCase() + fullPath.slice(1);
82
+ }
83
+ return fullPath;
84
+ }
85
+ module2.exports.joinPathPreserveDriveLetter = joinPathPreserveDriveLetter;
86
+ function getArgs2() {
87
+ return argv;
88
+ }
89
+ module2.exports.getArgs = getArgs2;
90
+ function del(fullPath) {
91
+ if (fs2.statSync(fullPath).isDirectory()) {
92
+ const subdir = fs2.readdirSync(fullPath).map((dirPath) => path2.resolve(fullPath, dirPath));
93
+ for (let i = 0; i < subdir.length; i++) {
94
+ del(subdir[i]);
95
+ }
96
+ } else {
97
+ try {
98
+ fs2.rmSync(fullPath, { recursive: true, force: true, retryDelay: 7e3 });
99
+ console.log("deleted", fullPath);
100
+ } catch (_) {
101
+ console.log("failed delete", fullPath);
102
+ }
103
+ }
104
+ }
105
+ module2.exports.del = del;
106
+ function delStream(globStream) {
107
+ globStream.stream().on("data", (result) => {
108
+ const fullPath = path2.resolve(process.cwd(), result);
109
+ if (fs2.statSync(fullPath).isDirectory()) {
110
+ const subdir = fs2.readdirSync(fullPath).map((dirPath) => path2.resolve(fullPath, dirPath));
111
+ for (let i = 0; i < subdir.length; i++) {
112
+ del(subdir[i]);
113
+ }
114
+ }
115
+ del(fullPath);
116
+ });
117
+ }
118
+ module2.exports.delStream = delStream;
119
+ function getFileTreeString(hashArray) {
120
+ const tree = {};
121
+ const hashMap = {};
122
+ for (const entry of hashArray) {
123
+ const [filePath, hash] = entry.split(" ");
124
+ hashMap[filePath] = hash;
125
+ const parts = filePath.split("/");
126
+ let current = tree;
127
+ for (let i = 0; i < parts.length; i++) {
128
+ const part = parts[i];
129
+ if (i === parts.length - 1) {
130
+ current[part] = null;
131
+ } else {
132
+ current[part] = current[part] || {};
133
+ current = current[part];
134
+ }
135
+ }
136
+ }
137
+ function printNode(node, prefix = "", parentPath = "") {
138
+ const keys = Object.keys(node).sort();
139
+ let lines = [];
140
+ keys.forEach((key, idx) => {
141
+ const isLast = idx === keys.length - 1;
142
+ const branch = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
143
+ const currentPath = parentPath ? parentPath + "/" + key : key;
144
+ if (node[key] === null) {
145
+ lines.push(prefix + branch + key + " [" + (hashMap[currentPath] || "") + "]");
146
+ } else {
147
+ lines.push(prefix + branch + key + "/");
148
+ lines = lines.concat(printNode(node[key], prefix + (isLast ? " " : "\u2502 "), currentPath));
149
+ }
150
+ });
151
+ return lines;
152
+ }
153
+ return printNode(tree, "", "").join("\n");
154
+ }
155
+ module2.exports.getFileTreeString = getFileTreeString;
156
+ var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
157
+ module2.exports.delay = delay;
158
+ }
159
+ });
160
+
24
161
  // src/package-resolutions-updater.mjs
162
+ init_cjs_shims();
25
163
  var import_ansi_colors = __toESM(require("ansi-colors"), 1);
26
164
  var dotenv = __toESM(require("dotenv"), 1);
27
165
  var import_fs = __toESM(require("fs"), 1);
28
166
  var import_https = __toESM(require("https"), 1);
29
167
  var import_os = __toESM(require("os"), 1);
30
168
  var import_path = __toESM(require("path"), 1);
169
+ var import_utils = __toESM(require_utils(), 1);
31
170
  var projectDir = process.cwd();
32
171
  var envPath = import_path.default.join(projectDir, ".env");
172
+ var args = (0, import_utils.getArgs)();
173
+ var ACCESS_TOKEN = process.env.GITHUB_TOKEN || process.env.ACCESS_TOKEN;
174
+ if (args.help || args.h) {
175
+ showHelp();
176
+ }
177
+ function showHelp() {
178
+ const helpText = `
179
+ GitHub Package Resolutions Updater
180
+ Usage:
181
+ node src/package-resolutions-updater.mjs [options]
182
+ Options:
183
+ --help, -h Show this help message
184
+ Description:
185
+ Updates the commit hashes in package.json's 'resolutions' field for GitHub tarball URLs to point to the latest commit SHA of the corresponding repository and branch.
186
+ Features:
187
+ - Parses GitHub URLs to extract repository owner, name, and branch.
188
+ - Fetches the latest commit SHA across all branches using GitHub's API.
189
+ - Replaces the old branch or commit in the URL with the latest SHA.
190
+ - Overwrites package.json with the updated URLs.
191
+ Requirements:
192
+ - GitHub Personal Access Token (GITHUB_TOKEN) via .env
193
+ - ESM support (type: "module" in package.json)
194
+ - Node.js v18+ recommended
195
+ Dependencies:
196
+ - ansi-colors \u2013 for styled terminal output
197
+ - dotenv \u2013 to load GitHub token from .env
198
+ Examples:
199
+ node src/package-resolutions-updater.mjs
200
+ node src/package-resolutions-updater.mjs --help
201
+
202
+ `;
203
+ console.log(helpText);
204
+ process.exit(0);
205
+ }
33
206
  if (import_fs.default.existsSync(envPath)) dotenv.config({ path: envPath });
34
207
  var specialPackageOverrides = [
35
208
  // SBG packages
@@ -106,7 +279,7 @@ function fetchJson(url) {
106
279
  "User-Agent": selectedUserAgent,
107
280
  Accept: "application/vnd.github.v3+json",
108
281
  "X-GitHub-Api-Version": "2022-11-28",
109
- ...process.env.GITHUB_TOKEN ? { Authorization: `token ${process.env.GITHUB_TOKEN}` } : {}
282
+ ...ACCESS_TOKEN ? { Authorization: `token ${ACCESS_TOKEN}` } : {}
110
283
  };
111
284
  return new Promise((resolve, reject) => {
112
285
  import_https.default.get(url, { headers }, (res) => {