@cluerise/tools 3.0.0 → 4.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.
@@ -1,14 +1,23 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+ var _options, _eslint, _eslintFixer, _FileLinter_static, preparePrettierLintResult_fn, _FileLinter_instances, prettierLint_fn, prepareESLintLintResult_fn, eslintLint_fn, _releaseSeparator, _config, _changelogPath, _Releaser_static, findLastReleaseTitle_fn, prependReleaseNotes_fn;
1
10
  import * as ActionsCore from "@actions/core";
2
11
  import { z, ZodError } from "zod";
3
- import ChildProcess from "child_process";
4
- import FileSystem from "fs/promises";
5
- import Path from "path";
12
+ import ChildProcess from "node:child_process";
13
+ import FileSystem from "node:fs/promises";
14
+ import OS from "node:os";
15
+ import Path from "node:path";
6
16
  import semanticRelease from "semantic-release";
17
+ import "@commitlint/load";
7
18
  import { ESLint } from "eslint";
8
19
  import { glob } from "glob";
9
20
  import * as Prettier from "prettier";
10
- import "@commitlint/load";
11
- import OS from "os";
12
21
  const enginesSchema = z.object({
13
22
  node: z.string()
14
23
  });
@@ -26,164 +35,253 @@ z.object({
26
35
  repository: repositorySchema.optional()
27
36
  });
28
37
  const runMain = (main2) => {
29
- main2(process.argv.slice(2)).then((exitCode) => {
38
+ Promise.resolve().then(() => main2(process.argv.slice(2))).then((exitCode) => {
30
39
  process.exit(exitCode);
31
40
  }).catch((error) => {
32
- console.error(error);
41
+ console.error("Error:", error);
33
42
  process.exit(1);
34
43
  });
35
44
  };
36
- const lintCommit = (args) => {
37
- const { status } = ChildProcess.spawnSync("commitlint", args, { stdio: "inherit" });
38
- return status ?? 0;
39
- };
40
- z.union([z.literal("all"), z.literal("code")]);
41
- const scopePatterns = {
42
- all: ["**"],
43
- code: ["src/**"]
44
- };
45
- const scopeShortcuts = Object.keys(scopePatterns);
46
- const isScopeShortcut = (scope) => scopeShortcuts.includes(scope);
47
- const resolveScope = (scope) => {
48
- if (Array.isArray(scope)) {
49
- return scope;
45
+ const _FileLinter = class _FileLinter {
46
+ constructor(options) {
47
+ __privateAdd(this, _FileLinter_instances);
48
+ __privateAdd(this, _options);
49
+ __privateAdd(this, _eslint);
50
+ __privateAdd(this, _eslintFixer, null);
51
+ __privateSet(this, _options, options ?? null);
52
+ __privateSet(this, _eslint, new ESLint({
53
+ overrideConfigFile: options == null ? void 0 : options.configPath
54
+ }));
55
+ if (options == null ? void 0 : options.fix) {
56
+ __privateSet(this, _eslintFixer, new ESLint({
57
+ fix: options.fix,
58
+ overrideConfigFile: options == null ? void 0 : options.configPath
59
+ }));
60
+ }
61
+ }
62
+ /**
63
+ * Lints files using `lint-staged` with the provided arguments.
64
+ *
65
+ * @param args - An array of arguments to pass to `lint-staged`.
66
+ * @returns The exit status of the `lint-staged` command.
67
+ */
68
+ static lintStaged(args) {
69
+ const { status } = ChildProcess.spawnSync("lint-staged", args, { stdio: "inherit" });
70
+ return status ?? 0;
71
+ }
72
+ /**
73
+ * Lints files matching the provided patterns using ESLint and Prettier.
74
+ *
75
+ * @param patterns - An array of glob patterns to match files against. Defaults to ['**'] which matches all files.
76
+ * @returns A promise that resolves to a LintFilesResult indicating the success or failure of the linting process.
77
+ */
78
+ async lint(patterns = ["**"]) {
79
+ var _a;
80
+ const prettierResults = await __privateMethod(this, _FileLinter_instances, prettierLint_fn).call(this, patterns);
81
+ const eslintResults = await __privateMethod(this, _FileLinter_instances, eslintLint_fn).call(this, patterns);
82
+ const eslintResult = await __privateMethod(this, _FileLinter_instances, prepareESLintLintResult_fn).call(this, eslintResults);
83
+ if (eslintResult.status === "failure") {
84
+ return eslintResult;
85
+ }
86
+ const prettierResult = __privateMethod(_a = _FileLinter, _FileLinter_static, preparePrettierLintResult_fn).call(_a, prettierResults);
87
+ if (prettierResult.status === "failure") {
88
+ return prettierResult;
89
+ }
90
+ return {
91
+ status: "success"
92
+ };
50
93
  }
51
- if (isScopeShortcut(scope)) {
52
- return scopePatterns[scope];
94
+ };
95
+ _options = new WeakMap();
96
+ _eslint = new WeakMap();
97
+ _eslintFixer = new WeakMap();
98
+ _FileLinter_static = new WeakSet();
99
+ preparePrettierLintResult_fn = function(results) {
100
+ if (results.length === 0) {
101
+ return { status: "success" };
53
102
  }
54
- return [scope];
103
+ const title = `Linting with Prettier failed with ${results.length} problem${results.length === 1 ? "" : "s"}
104
+ `;
105
+ let message = "Prettier failed with the following files:\n";
106
+ message += results.map((result) => `- ${result.path}`).join("\n");
107
+ message += OS.EOL;
108
+ return {
109
+ status: "failure",
110
+ title,
111
+ message,
112
+ problemCount: results.length
113
+ };
55
114
  };
56
- const formatWithPrettier = async (patterns) => {
57
- const eslint = new ESLint();
115
+ _FileLinter_instances = new WeakSet();
116
+ prettierLint_fn = async function(patterns) {
58
117
  const configPath = await Prettier.resolveConfigFile();
59
118
  if (!configPath) {
60
- return false;
119
+ return [];
61
120
  }
62
121
  const config = await Prettier.resolveConfig(configPath);
63
122
  if (!config) {
64
- return false;
123
+ return [];
65
124
  }
66
125
  const paths = await glob(patterns, {
67
126
  nodir: true,
68
127
  ignore: "node_modules/**"
69
128
  });
70
- await Promise.all(
129
+ const results = await Promise.all(
71
130
  paths.map(async (path) => {
72
- if (await eslint.isPathIgnored(path)) {
73
- return;
131
+ var _a;
132
+ if (await __privateGet(this, _eslint).isPathIgnored(path)) {
133
+ return null;
134
+ }
135
+ const contentBuffer = await FileSystem.readFile(path);
136
+ const content = contentBuffer.toString();
137
+ if ((_a = __privateGet(this, _options)) == null ? void 0 : _a.fix) {
138
+ const nextContent = await Prettier.format(content, {
139
+ ...config,
140
+ filepath: path
141
+ });
142
+ await FileSystem.writeFile(path, nextContent);
143
+ return null;
74
144
  }
75
- const prevContent = (await FileSystem.readFile(path)).toString();
76
- const nextContent = await Prettier.format(prevContent, {
145
+ const result = await Prettier.check(content, {
77
146
  ...config,
78
147
  filepath: path
79
148
  });
80
- await FileSystem.writeFile(path, nextContent);
149
+ return result ? null : { path };
81
150
  })
82
151
  );
152
+ return results.filter((result) => result !== null);
83
153
  };
84
- const lintFiles = async (scope, options) => {
85
- const patterns = resolveScope(scope);
86
- if (options == null ? void 0 : options.fix) {
87
- await formatWithPrettier(patterns);
88
- }
89
- const eslint = new ESLint({
90
- fix: options == null ? void 0 : options.fix
91
- });
92
- const results = await eslint.lintFiles(patterns);
93
- const problemCount = results.reduce((sum, result) => sum + result.errorCount + result.warningCount, 0);
94
- if (options == null ? void 0 : options.fix) {
95
- await ESLint.outputFixes(results);
96
- }
97
- if (problemCount > 0) {
98
- const formatter = await eslint.loadFormatter("stylish");
99
- const resultText = formatter.format(results);
100
- console.error(resultText);
101
- const errorMessage = `Linting failed with ${problemCount} problem${problemCount === 1 ? "" : "s"}.`;
102
- throw new Error(errorMessage);
154
+ prepareESLintLintResult_fn = async function(results) {
155
+ const problemCount = results.reduce(
156
+ (sum, result) => {
157
+ var _a;
158
+ return sum + result.errorCount + result.warningCount + (((_a = __privateGet(this, _options)) == null ? void 0 : _a.fix) ? -(result.fixableErrorCount + result.fixableWarningCount) : 0);
159
+ },
160
+ 0
161
+ );
162
+ if (problemCount === 0) {
163
+ return { status: "success" };
103
164
  }
165
+ const title = `ESLint failed with ${problemCount} problem${problemCount === 1 ? "" : "s"}`;
166
+ const formatter = await __privateGet(this, _eslint).loadFormatter("stylish");
167
+ const message = await formatter.format(results);
168
+ return {
169
+ status: "failure",
170
+ title,
171
+ message,
172
+ problemCount
173
+ };
104
174
  };
105
- const lintStaged = (args) => {
106
- const { status } = ChildProcess.spawnSync("lint-staged", args, { stdio: "inherit" });
107
- return status ?? 0;
175
+ eslintLint_fn = async function(patterns) {
176
+ const results = await __privateGet(this, _eslint).lintFiles(patterns);
177
+ const errorResults = ESLint.getErrorResults(results);
178
+ if (__privateGet(this, _eslintFixer) && errorResults.length > 0) {
179
+ await ESLint.outputFixes(await __privateGet(this, _eslintFixer).lintFiles(patterns));
180
+ }
181
+ return results;
108
182
  };
109
- const LintCommands = {
110
- lintFiles,
111
- lintCommit,
112
- lintStaged
183
+ __privateAdd(_FileLinter, _FileLinter_static);
184
+ let FileLinter = _FileLinter;
185
+ const _Releaser = class _Releaser {
186
+ constructor(config, changelogPath) {
187
+ __privateAdd(this, _config);
188
+ __privateAdd(this, _changelogPath);
189
+ __privateSet(this, _config, config);
190
+ __privateSet(this, _changelogPath, changelogPath);
191
+ }
192
+ /**
193
+ * Initializes a new instance of the Releaser class with the provided configuration.
194
+ *
195
+ * The configuration is loaded from a specified file path, and the changelog path is set.
196
+ *
197
+ * @param options - Options for initializing the releaser, including paths for the config and changelog.
198
+ * @param options.configPath - The path to the semantic-release configuration file. Defaults to 'release.config.js'.
199
+ * @param options.changelogPath - The path to the changelog file. Defaults to 'CHANGELOG.md'.
200
+ * @returns A new instance of Releaser.
201
+ */
202
+ static async init({
203
+ configPath = "release.config.js",
204
+ changelogPath = "CHANGELOG.md"
205
+ } = {}) {
206
+ const configAbsolutePath = Path.join(process.cwd(), configPath);
207
+ const { default: config } = await import(`file://${configAbsolutePath}`);
208
+ return new _Releaser(config, changelogPath);
209
+ }
210
+ /**
211
+ * Creates a new release based on the semantic-release configuration.
212
+ *
213
+ * It updates the changelog with the new release notes and runs linting on the changelog file.
214
+ *
215
+ * @returns The next release information or null if no release was created.
216
+ */
217
+ async createRelease() {
218
+ var _a;
219
+ const result = await semanticRelease(__privateGet(this, _config));
220
+ if (!result) {
221
+ return null;
222
+ }
223
+ const { lastRelease, nextRelease } = result;
224
+ const oldChangelogBuffer = await FileSystem.readFile(__privateGet(this, _changelogPath), { flag: FileSystem.constants.O_CREAT });
225
+ const oldChangelog = oldChangelogBuffer.toString();
226
+ const newChangelog = __privateMethod(_a = _Releaser, _Releaser_static, prependReleaseNotes_fn).call(_a, oldChangelog, lastRelease, nextRelease);
227
+ await FileSystem.writeFile(__privateGet(this, _changelogPath), newChangelog);
228
+ const linter = new FileLinter({ fix: true });
229
+ await linter.lint([__privateGet(this, _changelogPath)]);
230
+ ChildProcess.execFileSync("pnpm", ["version", nextRelease.version, "--no-git-tag-version"]);
231
+ return nextRelease;
232
+ }
233
+ /**
234
+ * Extracts the latest release changelog from the changelog file.
235
+ *
236
+ * @returns The content of the latest release changelog.
237
+ * @throws If no release is found or if the header is not found in the changelog.
238
+ */
239
+ async extractLatestReleaseChangelog() {
240
+ const contentBuffer = await FileSystem.readFile(__privateGet(this, _changelogPath));
241
+ const content = contentBuffer.toString();
242
+ const [, latestReleaseChangelog] = content.split(__privateGet(_Releaser, _releaseSeparator));
243
+ if (!latestReleaseChangelog) {
244
+ throw new Error("No release found");
245
+ }
246
+ const indexOfFirstEOL = latestReleaseChangelog.indexOf(OS.EOL);
247
+ if (indexOfFirstEOL === -1) {
248
+ throw new Error("Header not found");
249
+ }
250
+ return latestReleaseChangelog.slice(indexOfFirstEOL).trim();
251
+ }
113
252
  };
114
- const releaseConfigFilename = "release.config.js";
115
- const releaseNotesPath = "CHANGELOG.md";
116
- const findLastReleaseTitle = (releaseNotes, lastRelease) => {
253
+ _releaseSeparator = new WeakMap();
254
+ _config = new WeakMap();
255
+ _changelogPath = new WeakMap();
256
+ _Releaser_static = new WeakSet();
257
+ findLastReleaseTitle_fn = function(changelog, lastRelease) {
117
258
  const lastReleaseTitleLink = `## [${lastRelease.version}](`;
118
- if (releaseNotes.includes(lastReleaseTitleLink)) {
259
+ if (changelog.includes(lastReleaseTitleLink)) {
119
260
  return lastReleaseTitleLink;
120
261
  }
121
262
  const lastReleaseTitle = `## ${lastRelease.version}`;
122
- if (releaseNotes.includes(lastReleaseTitle)) {
263
+ if (changelog.includes(lastReleaseTitle)) {
123
264
  return lastReleaseTitle;
124
265
  }
125
266
  return null;
126
267
  };
127
- const prependReleaseNotes = (releaseNotes, lastRelease, nextRelease) => {
268
+ prependReleaseNotes_fn = function(changelog, lastRelease, nextRelease) {
128
269
  var _a;
129
270
  const nextReleaseNotes = ((_a = nextRelease.notes) == null ? void 0 : _a.trim()) ?? "";
130
- if (releaseNotes.length === 0) {
271
+ if (changelog.length === 0) {
131
272
  return nextReleaseNotes;
132
273
  }
133
- const lastReleaseTitle = findLastReleaseTitle(releaseNotes, lastRelease);
274
+ const lastReleaseTitle = __privateMethod(this, _Releaser_static, findLastReleaseTitle_fn).call(this, changelog, lastRelease);
134
275
  if (!lastReleaseTitle) {
135
276
  return nextReleaseNotes;
136
277
  }
137
- return releaseNotes.replace(lastReleaseTitle, `${nextReleaseNotes}
278
+ return changelog.replace(lastReleaseTitle, `${nextReleaseNotes}
138
279
 
139
280
  ${lastReleaseTitle}`);
140
281
  };
141
- const createRelease = async () => {
142
- const releaseConfigPath = Path.join(process.cwd(), releaseConfigFilename);
143
- const { default: releaseConfig } = await import(`file://${releaseConfigPath}`);
144
- const result = await semanticRelease(releaseConfig);
145
- if (!result) {
146
- return null;
147
- }
148
- const { lastRelease, nextRelease } = result;
149
- const oldReleaseNotes = (await FileSystem.readFile(releaseNotesPath, {
150
- flag: FileSystem.constants.O_CREAT
151
- })).toString();
152
- const newReleaseNotes = prependReleaseNotes(oldReleaseNotes, lastRelease, nextRelease);
153
- await FileSystem.writeFile(releaseNotesPath, newReleaseNotes);
154
- await LintCommands.lintFiles(releaseNotesPath, {
155
- fix: true
156
- });
157
- ChildProcess.execFileSync("npm", [
158
- "version",
159
- nextRelease.version,
160
- "--message",
161
- "release: Version %s",
162
- "--no-git-tag-version"
163
- ]);
164
- return nextRelease;
165
- };
166
- const releaseSeparator = /^## /gm;
167
- const extractChangelog = async () => {
168
- const content = (await FileSystem.readFile("CHANGELOG.md")).toString();
169
- const [, latestReleaseChangelog] = content.split(releaseSeparator);
170
- if (!latestReleaseChangelog) {
171
- throw new Error("No release found");
172
- }
173
- const indexOfFirstEOL = latestReleaseChangelog.indexOf(OS.EOL);
174
- if (indexOfFirstEOL === -1) {
175
- throw new Error("Header not found");
176
- }
177
- const body = latestReleaseChangelog.slice(indexOfFirstEOL).trim();
178
- const changelog = {
179
- body
180
- };
181
- return changelog;
182
- };
183
- const ReleaseCommands = {
184
- createRelease,
185
- extractChangelog
186
- };
282
+ __privateAdd(_Releaser, _Releaser_static);
283
+ __privateAdd(_Releaser, _releaseSeparator, /^## /gm);
284
+ let Releaser = _Releaser;
187
285
  const commandNameArgSchema = z.union([z.literal("create"), z.literal("extract-changelog")]);
188
286
  const parseReleaseArgs = ([commandArg]) => {
189
287
  const command = commandNameArgSchema.parse(commandArg);
@@ -194,8 +292,9 @@ const parseReleaseArgs = ([commandArg]) => {
194
292
  const main = async (args) => {
195
293
  try {
196
294
  const { command } = parseReleaseArgs(args);
295
+ const releaser = await Releaser.init();
197
296
  if (command === "create") {
198
- const release = await ReleaseCommands.createRelease();
297
+ const release = await releaser.createRelease();
199
298
  if (!release) {
200
299
  return 0;
201
300
  }
@@ -203,11 +302,11 @@ const main = async (args) => {
203
302
  ActionsCore.setOutput("version", release.version);
204
303
  }
205
304
  } else if (command === "extract-changelog") {
206
- const changelog = await ReleaseCommands.extractChangelog();
305
+ const changelog = await releaser.extractLatestReleaseChangelog();
207
306
  if (process.env.GITHUB_ACTIONS === "true") {
208
- ActionsCore.setOutput("changelog", changelog.body);
307
+ ActionsCore.setOutput("changelog", changelog);
209
308
  } else {
210
- console.log(changelog.body);
309
+ console.log(changelog);
211
310
  }
212
311
  }
213
312
  return 0;
@@ -215,15 +314,15 @@ const main = async (args) => {
215
314
  if (error instanceof ZodError) {
216
315
  const firstIssue = error.issues[0];
217
316
  if ((firstIssue == null ? void 0 : firstIssue.code) === "invalid_union") {
218
- console.error("Invalid command name");
317
+ console.error("Error: Invalid command name");
219
318
  return 1;
220
319
  }
221
320
  }
222
321
  if (error instanceof Error) {
223
- console.error(error.message);
224
- return 1;
322
+ console.error("Error:", error.message);
323
+ } else {
324
+ console.error("Error:", error);
225
325
  }
226
- console.error(error);
227
326
  return 1;
228
327
  }
229
328
  };