@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,29 +1,225 @@
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 _packageName, _CoreConfig_static, rootDirectory_get, _command, _ConsoleStatusLogger_static, createResultMessage_fn, _origins, _names, _data, _PackageJson_instances, parseGitRepository_fn, _configDirectory, _configPackage, _ToolInitializer_instances, initCommitlint_fn, initEditorConfig_fn, initESLint_fn, initGit_fn, initLintStaged_fn, initNvm_fn, initPnpm_fn, initPrettier_fn, getReleaseConfigParams_fn, initRelease_fn, initTypeScript_fn, initVSCode_fn, _options, _eslint, _eslintFixer, _FileLinter_static, preparePrettierLintResult_fn, _FileLinter_instances, prettierLint_fn, prepareESLintLintResult_fn, eslintLint_fn;
1
10
  import { z, ZodError } from "zod";
2
- import FileSystem from "fs/promises";
3
- import Path from "path";
4
- import ChildProcess from "child_process";
11
+ import Path from "node:path";
12
+ import FileSystem from "node:fs/promises";
13
+ import OS from "node:os";
14
+ import Process from "node:process";
15
+ import "@commitlint/load";
16
+ import ChildProcess from "node:child_process";
5
17
  import { ESLint } from "eslint";
6
18
  import { glob } from "glob";
7
19
  import * as Prettier from "prettier";
8
- import "@commitlint/load";
9
- class ParseGitRepositoryError extends Error {
20
+ class CoreConfig {
21
+ /**
22
+ * Determines if the application is running in production mode.
23
+ *
24
+ * This is based on the environment variable `import.meta.env.PROD`.
25
+ *
26
+ * @returns True if in production mode, false otherwise.
27
+ */
28
+ static get isProd() {
29
+ return true;
30
+ }
31
+ /**
32
+ * Returns the package and its path to the configuration files.
33
+ *
34
+ * This is used to load configurations from the package in production mode.
35
+ *
36
+ * @returns The path to the configuration files in the package.
37
+ */
38
+ static get configPackage() {
39
+ return `${__privateGet(this, _packageName)}/dist/configs`;
40
+ }
41
+ /**
42
+ * Returns the directory where configuration files are stored.
43
+ *
44
+ * In production mode, this points to the `dist/configs` directory within the package.
45
+ * In development mode, it points to the root directory.
46
+ *
47
+ * @returns The path to the configuration directory.
48
+ */
49
+ static get configDirectory() {
50
+ return this.isProd ? `${__privateGet(this, _CoreConfig_static, rootDirectory_get)}/dist/configs` : __privateGet(this, _CoreConfig_static, rootDirectory_get);
51
+ }
10
52
  }
53
+ _packageName = new WeakMap();
54
+ _CoreConfig_static = new WeakSet();
55
+ rootDirectory_get = function() {
56
+ return this.isProd ? `./node_modules/${__privateGet(this, _packageName)}` : ".";
57
+ };
58
+ __privateAdd(CoreConfig, _CoreConfig_static);
59
+ __privateAdd(CoreConfig, _packageName, "@cluerise/tools");
60
+ const _ConsoleStatusLogger = class _ConsoleStatusLogger {
61
+ constructor(command) {
62
+ __privateAdd(this, _command);
63
+ __privateSet(this, _command, command);
64
+ }
65
+ /**
66
+ * Begins logging for a command with the specified argument.
67
+ *
68
+ * @param argument - The argument for the command.
69
+ *
70
+ * @example
71
+ * const logger = new ConsoleStatusLogger('Linting');
72
+ * logger.begin('src/index.ts'); // Logs: "Linting src/index.ts..."
73
+ */
74
+ begin(argument) {
75
+ console.info(`${__privateGet(this, _command)} ${argument}...`);
76
+ }
77
+ /**
78
+ * Ends logging for a command with the specified argument and exit code.
79
+ *
80
+ * @param argument - The argument for the command.
81
+ * @param exitCode - The exit code of the command execution. If null, it indicates completion without an error.
82
+ *
83
+ * @example
84
+ * const logger = new ConsoleStatusLogger('Linting');
85
+ * logger.end('src/index.ts'); // Logs: "Linting src/index.ts... Done"
86
+ * logger.end('src/index.ts', 0); // Logs: "Linting src/index.ts... OK"
87
+ * logger.end('src/index.ts', 1); // Logs: "Linting src/index.ts... Failed"
88
+ */
89
+ end(argument, exitCode = null) {
90
+ var _a;
91
+ console.info(`${__privateGet(this, _command)} ${argument}... ${__privateMethod(_a = _ConsoleStatusLogger, _ConsoleStatusLogger_static, createResultMessage_fn).call(_a, exitCode)}`);
92
+ }
93
+ };
94
+ _command = new WeakMap();
95
+ _ConsoleStatusLogger_static = new WeakSet();
96
+ createResultMessage_fn = function(exitCode) {
97
+ if (exitCode === null) {
98
+ return "Done";
99
+ }
100
+ return exitCode === 0 ? "OK" : "Failed";
101
+ };
102
+ __privateAdd(_ConsoleStatusLogger, _ConsoleStatusLogger_static);
103
+ let ConsoleStatusLogger = _ConsoleStatusLogger;
11
104
  const gitProviderOrigins = {
12
105
  github: "https://github.com"
13
106
  };
14
- const gitProviderNames = Object.keys(gitProviderOrigins);
15
- const isGitProviderName = (name) => gitProviderNames.includes(name);
16
- const parseRepositoryUrl = (urlString) => {
107
+ const _GitProvider = class _GitProvider {
108
+ /**
109
+ * Checks if the provided name is a valid Git provider name.
110
+ *
111
+ * @param name - The name of the Git provider to validate.
112
+ * @returns True if the name is valid, false otherwise.
113
+ */
114
+ static isValidName(name) {
115
+ return __privateGet(this, _names).includes(name);
116
+ }
117
+ /**
118
+ * Returns a Git provider origin.
119
+ *
120
+ * @param name - The name of the Git provider.
121
+ * @returns The origin URL of the Git provider.
122
+ */
123
+ static getOrigin(name) {
124
+ return __privateGet(this, _origins)[name];
125
+ }
126
+ };
127
+ _origins = new WeakMap();
128
+ _names = new WeakMap();
129
+ __privateAdd(_GitProvider, _origins, gitProviderOrigins);
130
+ __privateAdd(_GitProvider, _names, Object.keys(__privateGet(_GitProvider, _origins)));
131
+ let GitProvider = _GitProvider;
132
+ const enginesSchema = z.object({
133
+ node: z.string()
134
+ });
135
+ const repositoryObjectSchema = z.object({
136
+ type: z.string(),
137
+ url: z.string(),
138
+ directory: z.ostring()
139
+ });
140
+ const repositorySchema = z.union([z.string(), repositoryObjectSchema]);
141
+ const packageJsonDataSchema = z.object({
142
+ name: z.string(),
143
+ version: z.string(),
144
+ description: z.string(),
145
+ engines: enginesSchema.optional(),
146
+ repository: repositorySchema.optional()
147
+ });
148
+ const _PackageJson = class _PackageJson {
149
+ constructor(data) {
150
+ __privateAdd(this, _PackageJson_instances);
151
+ __privateAdd(this, _data);
152
+ __privateSet(this, _data, data);
153
+ }
154
+ static async init() {
155
+ const content = await FileSystem.readFile("package.json", { encoding: "utf8" });
156
+ const data = JsonUtils.parse(content);
157
+ const parseResult = packageJsonDataSchema.safeParse(data);
158
+ if (!parseResult.success) {
159
+ throw new Error("Invalid package.json", {
160
+ cause: parseResult.error
161
+ });
162
+ }
163
+ return new _PackageJson(parseResult.data);
164
+ }
165
+ /**
166
+ * Returns the required engines.
167
+ */
168
+ get engines() {
169
+ return __privateGet(this, _data).engines;
170
+ }
171
+ /**
172
+ * Sets the required engines.
173
+ *
174
+ * @param engines - The engines to set.
175
+ */
176
+ set engines(engines) {
177
+ __privateGet(this, _data).engines = engines;
178
+ }
179
+ /**
180
+ * Returns the repository information.
181
+ */
182
+ get repository() {
183
+ return __privateGet(this, _data).repository;
184
+ }
185
+ /**
186
+ * Parses the repository information from package.json.
187
+ *
188
+ * @returns The parsed GitRepository or null if no repository is defined.
189
+ */
190
+ parseGitRepository() {
191
+ if (!this.repository) {
192
+ return null;
193
+ }
194
+ if (typeof this.repository === "string") {
195
+ return __privateMethod(this, _PackageJson_instances, parseGitRepository_fn).call(this, this.repository);
196
+ }
197
+ return __privateMethod(this, _PackageJson_instances, parseGitRepository_fn).call(this, this.repository.url);
198
+ }
199
+ /**
200
+ * Saves the package.json file with the current data.
201
+ */
202
+ async save() {
203
+ const content = JsonUtils.prettify(__privateGet(this, _data)) + "\n";
204
+ await FileSystem.writeFile("package.json", content, { encoding: "utf8" });
205
+ }
206
+ };
207
+ _data = new WeakMap();
208
+ _PackageJson_instances = new WeakSet();
209
+ parseGitRepository_fn = function(urlString) {
210
+ if (!urlString) {
211
+ return null;
212
+ }
17
213
  const urlValue = urlString.includes(":") ? urlString : `https://${urlString}`;
18
214
  const url = new URL(urlValue);
19
215
  const scheme = url.protocol.slice(0, -1);
20
- if (isGitProviderName(scheme)) {
216
+ if (GitProvider.isValidName(scheme)) {
21
217
  const [owner, repositoryName] = url.pathname.split("/");
22
218
  if (!owner || !repositoryName) {
23
- throw new ParseGitRepositoryError("Unknown owner or repositoryName");
219
+ throw new Error("Unknown owner or repositoryName");
24
220
  }
25
221
  return {
26
- origin: gitProviderOrigins[scheme],
222
+ origin: GitProvider.getOrigin(scheme),
27
223
  owner,
28
224
  repositoryName
29
225
  };
@@ -31,7 +227,7 @@ const parseRepositoryUrl = (urlString) => {
31
227
  if (scheme === "https") {
32
228
  const [, owner, repositoryName] = url.pathname.split("/");
33
229
  if (!owner || !repositoryName) {
34
- throw new ParseGitRepositoryError("Unknown owner or repositoryName");
230
+ throw new Error("Unknown owner or repositoryName");
35
231
  }
36
232
  return {
37
233
  origin: url.origin,
@@ -39,313 +235,358 @@ const parseRepositoryUrl = (urlString) => {
39
235
  repositoryName: repositoryName.endsWith(".git") ? repositoryName.slice(0, -4) : repositoryName
40
236
  };
41
237
  }
42
- throw new ParseGitRepositoryError("Unsupported repository URL");
43
- };
44
- const parsePackageJsonRepository = (repository) => {
45
- if (typeof repository === "string") {
46
- return parseRepositoryUrl(repository);
47
- }
48
- return parseRepositoryUrl(repository.url);
49
- };
50
- const enginesSchema = z.object({
51
- node: z.string()
52
- });
53
- const repositoryObjectSchema = z.object({
54
- type: z.string(),
55
- url: z.string(),
56
- directory: z.ostring()
57
- });
58
- const repositorySchema = z.union([z.string(), repositoryObjectSchema]);
59
- const packageJsonSchema = z.object({
60
- name: z.string(),
61
- version: z.string(),
62
- description: z.string(),
63
- engines: enginesSchema.optional(),
64
- repository: repositorySchema.optional()
65
- });
66
- const readPackageJson = async () => {
67
- const packageJsonData = await FileSystem.readFile("package.json", { encoding: "utf8" });
68
- const packageJson = JSON.parse(packageJsonData);
69
- const parseResult = packageJsonSchema.safeParse(packageJson);
70
- if (!parseResult.success) {
71
- throw parseResult.error;
72
- }
73
- return packageJson;
74
- };
75
- const CoreCommands = {
76
- readPackageJson,
77
- parsePackageJsonRepository
238
+ throw new Error("Unsupported repository URL");
78
239
  };
240
+ let PackageJson = _PackageJson;
79
241
  const runMain = (main2) => {
80
- main2(process.argv.slice(2)).then((exitCode) => {
242
+ Promise.resolve().then(() => main2(process.argv.slice(2))).then((exitCode) => {
81
243
  process.exit(exitCode);
82
244
  }).catch((error) => {
83
- console.error(error);
245
+ console.error("Error:", error);
84
246
  process.exit(1);
85
247
  });
86
248
  };
87
- const createResultMessage = (exitCode) => {
88
- if (exitCode === null) {
89
- return "Done";
249
+ class FileUtils {
250
+ static async createFile(path, content, options = {}) {
251
+ const absolutePath = Path.resolve(Process.cwd(), path);
252
+ const { trailingNewline = true } = options;
253
+ const fileContent = trailingNewline && !content.endsWith(OS.EOL) ? `${content}${OS.EOL}` : content;
254
+ await FileSystem.mkdir(Path.dirname(absolutePath), { recursive: true });
255
+ return FileSystem.writeFile(absolutePath, fileContent);
90
256
  }
91
- return exitCode === 0 ? "OK" : "Failed";
92
- };
93
- const createStatusConsole = (command) => ({
94
- printBegin: (arg) => console.info(`${command} ${arg}...`),
95
- printEnd: (arg, exitCode = null) => console.info(`${command} ${arg}... ${createResultMessage(exitCode)}`)
96
- });
97
- const packageName = "@cluerise/tools";
98
- const rootAppDirectory = `./node_modules/${packageName}`;
99
- const toolsConfigPackage = `${packageName}/dist/configs`;
100
- const toolsConfigDirectory = `${rootAppDirectory}/dist/configs`;
101
- const AppConfig = {
102
- toolsConfigPackage,
103
- toolsConfigDirectory
104
- };
105
- const copyFile = async (sourceDirectory, filePath, destinationFilePath) => {
106
- const sourcePath = Path.resolve(sourceDirectory, filePath);
107
- const destinationPath = Path.resolve(process.cwd(), destinationFilePath ?? filePath);
108
- await FileSystem.mkdir(Path.dirname(destinationPath), { recursive: true });
109
- return FileSystem.copyFile(sourcePath, destinationPath);
110
- };
111
- const createFile = async (path, content) => {
112
- const destinationPath = Path.resolve(process.cwd(), path);
113
- await FileSystem.mkdir(Path.dirname(destinationPath), { recursive: true });
114
- return FileSystem.writeFile(destinationPath, content);
115
- };
116
- const ConfigCommands = {
117
- copyFile,
118
- createFile
119
- };
120
- const commitlintConfigName = "commitlint.config";
121
- const commitlintConfigPath = `${commitlintConfigName}.ts`;
122
- const initCommitlint = async ({ configPackage }) => {
123
- const configContent = `export { default } from '${configPackage}/${commitlintConfigName}';
257
+ static async copyFile(sourceDirectory, filePath, destinationFilePath) {
258
+ const sourcePath = Path.resolve(sourceDirectory, filePath);
259
+ const destinationPath = Path.resolve(Process.cwd(), destinationFilePath ?? filePath);
260
+ await FileSystem.mkdir(Path.dirname(destinationPath), { recursive: true });
261
+ return FileSystem.copyFile(sourcePath, destinationPath);
262
+ }
263
+ }
264
+ class JsonUtils {
265
+ static stringify(value) {
266
+ return JSON.stringify(value);
267
+ }
268
+ static prettify(value) {
269
+ return JSON.stringify(value, null, 2);
270
+ }
271
+ static parse(value) {
272
+ return JSON.parse(value);
273
+ }
274
+ }
275
+ const toolNameSchema = z.union([
276
+ z.literal("commitlint"),
277
+ z.literal("editorconfig"),
278
+ z.literal("eslint"),
279
+ z.literal("git"),
280
+ z.literal("lint-staged"),
281
+ z.literal("nvm"),
282
+ z.literal("pnpm"),
283
+ z.literal("prettier"),
284
+ z.literal("release"),
285
+ z.literal("typescript"),
286
+ z.literal("vscode")
287
+ ]);
288
+ class ToolInitializer {
289
+ constructor(configDirectory, configPackage) {
290
+ __privateAdd(this, _ToolInitializer_instances);
291
+ __privateAdd(this, _configDirectory);
292
+ __privateAdd(this, _configPackage);
293
+ __privateSet(this, _configDirectory, configDirectory);
294
+ __privateSet(this, _configPackage, configPackage);
295
+ }
296
+ /**
297
+ * Returns the names of all available tools.
298
+ *
299
+ * @returns An array of tool names.
300
+ */
301
+ get toolNames() {
302
+ return toolNameSchema.options.map((option) => option.value);
303
+ }
304
+ /**
305
+ * Initializes the specified tool.
306
+ *
307
+ * @param toolName - The name of the tool to initialize.
308
+ * @returns A promise that resolves when the tool is initialized.
309
+ */
310
+ async initTool(toolName) {
311
+ switch (toolName) {
312
+ case "commitlint":
313
+ return __privateMethod(this, _ToolInitializer_instances, initCommitlint_fn).call(this);
314
+ case "editorconfig":
315
+ return __privateMethod(this, _ToolInitializer_instances, initEditorConfig_fn).call(this);
316
+ case "eslint":
317
+ return __privateMethod(this, _ToolInitializer_instances, initESLint_fn).call(this);
318
+ case "git":
319
+ return __privateMethod(this, _ToolInitializer_instances, initGit_fn).call(this);
320
+ case "lint-staged":
321
+ return __privateMethod(this, _ToolInitializer_instances, initLintStaged_fn).call(this);
322
+ case "nvm":
323
+ return __privateMethod(this, _ToolInitializer_instances, initNvm_fn).call(this);
324
+ case "pnpm":
325
+ return __privateMethod(this, _ToolInitializer_instances, initPnpm_fn).call(this);
326
+ case "prettier":
327
+ return __privateMethod(this, _ToolInitializer_instances, initPrettier_fn).call(this);
328
+ case "release":
329
+ return __privateMethod(this, _ToolInitializer_instances, initRelease_fn).call(this);
330
+ case "typescript":
331
+ return __privateMethod(this, _ToolInitializer_instances, initTypeScript_fn).call(this);
332
+ case "vscode":
333
+ return __privateMethod(this, _ToolInitializer_instances, initVSCode_fn).call(this);
334
+ default: {
335
+ const unhandledToolName = toolName;
336
+ throw new Error(`Unknown tool name: ${unhandledToolName}`);
337
+ }
338
+ }
339
+ }
340
+ }
341
+ _configDirectory = new WeakMap();
342
+ _configPackage = new WeakMap();
343
+ _ToolInitializer_instances = new WeakSet();
344
+ initCommitlint_fn = async function() {
345
+ const configName = "commitlint.config";
346
+ const configPath = `${configName}.ts`;
347
+ const configContent = `export { default } from '${__privateGet(this, _configPackage)}/${configName}';
124
348
  `;
125
- await ConfigCommands.createFile(commitlintConfigPath, configContent);
349
+ await FileUtils.createFile(configPath, configContent);
126
350
  };
127
- const editorConfigPath = ".editorconfig";
128
- const initEditorConfig = async ({ configDirectory }) => {
129
- await ConfigCommands.copyFile(configDirectory, editorConfigPath);
130
- };
131
- const eslintConfigPath = ".eslintrc.cjs";
132
- const eslintIgnorePath = ".eslintignore";
133
- const initEslint = async ({ configDirectory }) => {
134
- const configContent = `module.exports = {
135
- extends: '${configDirectory}/${eslintConfigPath}'
351
+ initEditorConfig_fn = async function() {
352
+ await FileUtils.copyFile(__privateGet(this, _configDirectory), ".editorconfig");
136
353
  };
354
+ initESLint_fn = async function() {
355
+ const configName = "eslint.config";
356
+ const configPath = `${configName}.js`;
357
+ const markdownConfigName = "eslint-markdown.config";
358
+ const markdownConfigPath = `${markdownConfigName}.js`;
359
+ const configContent = `export { default } from '${__privateGet(this, _configPackage)}/${configName}';
137
360
  `;
138
- await ConfigCommands.createFile(eslintConfigPath, configContent);
139
- await ConfigCommands.copyFile(configDirectory, eslintIgnorePath);
140
- };
141
- const sourceGitignorePath = "_gitignore";
142
- const destinationGitignorePath = ".gitignore";
143
- const gitHookDirectory = "hooks";
144
- const gitHookPaths = [
145
- Path.join(gitHookDirectory, "commit-msg"),
146
- Path.join(gitHookDirectory, "post-commit"),
147
- Path.join(gitHookDirectory, "pre-commit"),
148
- Path.join(gitHookDirectory, "prepare-commit-msg")
149
- ];
150
- const initGit = async ({ configDirectory }) => {
151
- await ConfigCommands.copyFile(configDirectory, sourceGitignorePath, destinationGitignorePath);
152
- await Promise.all(gitHookPaths.map((gitHookPath) => ConfigCommands.copyFile(configDirectory, gitHookPath)));
153
- };
154
- const lintStagedConfigPath = "lint-staged.config.js";
155
- const initLintStaged = async ({ configPackage }) => {
156
- const configContent = `export { default } from '${configPackage}/${lintStagedConfigPath}';
361
+ const markdownConfigContent = `export { default } from '${__privateGet(this, _configPackage)}/${markdownConfigName}';
157
362
  `;
158
- await ConfigCommands.createFile(lintStagedConfigPath, configContent);
159
- };
160
- const sourceNpmrcPath = "_npmrc";
161
- const destinationNpmrcPath = ".npmrc";
162
- const initNpm = async ({ configDirectory }) => {
163
- await ConfigCommands.copyFile(configDirectory, sourceNpmrcPath, destinationNpmrcPath);
363
+ await FileUtils.createFile(configPath, configContent);
364
+ await FileUtils.createFile(markdownConfigPath, markdownConfigContent);
365
+ };
366
+ initGit_fn = async function() {
367
+ const sourceGitignorePath = "_gitignore";
368
+ const destinationGitignorePath = ".gitignore";
369
+ await FileUtils.copyFile(__privateGet(this, _configDirectory), sourceGitignorePath, destinationGitignorePath);
370
+ const gitHookDirectory = "hooks";
371
+ const gitHookPaths = [
372
+ Path.join(gitHookDirectory, "commit-msg"),
373
+ Path.join(gitHookDirectory, "post-commit"),
374
+ Path.join(gitHookDirectory, "pre-commit"),
375
+ Path.join(gitHookDirectory, "prepare-commit-msg")
376
+ ];
377
+ await Promise.all(gitHookPaths.map((gitHookPath) => FileUtils.copyFile(__privateGet(this, _configDirectory), gitHookPath)));
378
+ };
379
+ initLintStaged_fn = async function() {
380
+ const configName = "lint-staged.config";
381
+ const configPath = `${configName}.js`;
382
+ const configContent = `export { default } from '${__privateGet(this, _configPackage)}/${configName}';
383
+ `;
384
+ await FileUtils.createFile(configPath, configContent);
164
385
  };
165
- const nvmrcPath = ".nvmrc";
166
- const initNvm = async ({ configDirectory }) => {
167
- await ConfigCommands.copyFile(configDirectory, nvmrcPath);
386
+ initNvm_fn = async function() {
387
+ await FileUtils.copyFile(__privateGet(this, _configDirectory), ".nvmrc");
168
388
  };
169
- const prettierConfigPath = "prettier.config.js";
170
- const initPrettier = async ({ configPackage }) => {
171
- const configContent = `export { default } from '${configPackage}/${prettierConfigPath}';
389
+ initPnpm_fn = async function() {
390
+ const workspacePath = "pnpm-workspace.yaml";
391
+ const workspaceContent = `engineStrict: true
172
392
  `;
173
- await ConfigCommands.createFile(prettierConfigPath, configContent);
393
+ await FileUtils.createFile(workspacePath, workspaceContent);
174
394
  };
175
- const releaseConfigPath = "release.config.js";
176
- const defaultReleaseConfigParams = {
177
- host: "<host>",
178
- owner: "<owner>",
179
- repository: "<repository>"
395
+ initPrettier_fn = async function() {
396
+ const configName = "prettier.config";
397
+ const configPath = `${configName}.js`;
398
+ const configContent = `export { default } from '${__privateGet(this, _configPackage)}/${configName}';
399
+ `;
400
+ await FileUtils.createFile(configPath, configContent);
180
401
  };
181
- const getReleaseConfigParams = async () => {
402
+ getReleaseConfigParams_fn = async function() {
403
+ const defaultConfigParams = {
404
+ host: "<host>",
405
+ owner: "<owner>",
406
+ repository: "<repository>"
407
+ };
182
408
  try {
183
- const { repository } = await CoreCommands.readPackageJson();
409
+ const packageJson = await PackageJson.init();
410
+ const repository = packageJson.parseGitRepository();
184
411
  if (!repository) {
185
- return defaultReleaseConfigParams;
412
+ return defaultConfigParams;
186
413
  }
187
- const { origin, owner, repositoryName } = CoreCommands.parsePackageJsonRepository(repository);
414
+ const { origin, owner, repositoryName } = repository;
188
415
  return {
189
416
  host: origin,
190
417
  owner,
191
418
  repository: repositoryName
192
419
  };
193
420
  } catch {
194
- return defaultReleaseConfigParams;
421
+ return defaultConfigParams;
195
422
  }
196
423
  };
197
- const initRelease = async ({ configPackage }) => {
198
- const releaseConfigParams = await getReleaseConfigParams();
199
- const configContent = `import { createReleaseConfig } from '${configPackage}/${releaseConfigPath}';
424
+ initRelease_fn = async function() {
425
+ const configName = "release.config";
426
+ const configPath = `${configName}.js`;
427
+ const configParams = await __privateMethod(this, _ToolInitializer_instances, getReleaseConfigParams_fn).call(this);
428
+ const configContent = `import { createReleaseConfig } from '${__privateGet(this, _configPackage)}/${configName}';
200
429
 
201
- export default createReleaseConfig(${JSON.stringify(releaseConfigParams, null, 2)});
430
+ export default createReleaseConfig(${JsonUtils.prettify(configParams)});
202
431
  `;
203
- await ConfigCommands.createFile(releaseConfigPath, configContent);
432
+ await FileUtils.createFile(configPath, configContent);
204
433
  };
205
- const typescriptConfigPath = "tsconfig.json";
206
- const initTypescript = async ({ configDirectory }) => {
434
+ initTypeScript_fn = async function() {
435
+ const configPath = "tsconfig.json";
207
436
  const configContent = `{
208
- "extends": "${configDirectory}/${typescriptConfigPath}",
437
+ "extends": "${__privateGet(this, _configDirectory)}/${configPath}",
209
438
  "compilerOptions": {
210
439
  "baseUrl": "./"
211
440
  }
212
441
  }
213
442
  `;
214
- await ConfigCommands.createFile(typescriptConfigPath, configContent);
215
- };
216
- const vscodeSettingsPath = Path.join(".vscode", "settings.json");
217
- const initVscode = async () => {
218
- const configContent = `{
219
- "prettier.ignorePath": "node_modules/@cluerise/tools/dist/configs/.prettierignore",
220
- "typescript.tsdk": "node_modules/typescript/lib"
221
- }
222
- `;
223
- await ConfigCommands.createFile(vscodeSettingsPath, configContent);
224
- };
225
- const toolInitializers = {
226
- commitlint: initCommitlint,
227
- editorconfig: initEditorConfig,
228
- eslint: initEslint,
229
- git: initGit,
230
- "lint-staged": initLintStaged,
231
- npm: initNpm,
232
- nvm: initNvm,
233
- prettier: initPrettier,
234
- release: initRelease,
235
- typescript: initTypescript,
236
- vscode: initVscode
237
- };
238
- const toolInitializerNames = Object.keys(toolInitializers);
239
- const toolNameSchema = z.union([
240
- z.literal("commitlint"),
241
- z.literal("editorconfig"),
242
- z.literal("eslint"),
243
- z.literal("git"),
244
- z.literal("lint-staged"),
245
- z.literal("npm"),
246
- z.literal("nvm"),
247
- z.literal("prettier"),
248
- z.literal("release"),
249
- z.literal("typescript"),
250
- z.literal("vscode")
251
- ]);
252
- const initializingConsole = createStatusConsole("Initializing");
253
- const initTool = async (name, params) => {
254
- const toolInitializer = toolInitializers[name];
255
- if (!toolInitializer) {
256
- throw new Error(`Tool "${name}" is not supported.`);
257
- }
258
- initializingConsole.printBegin(name);
259
- await toolInitializer(params);
260
- initializingConsole.printEnd(name);
261
- };
262
- const initAllTools = async (params) => {
263
- for (const name of toolInitializerNames) {
264
- await initTool(name, params);
443
+ await FileUtils.createFile(configPath, configContent);
444
+ };
445
+ initVSCode_fn = async function() {
446
+ const settingsPath = Path.join(".vscode", "settings.json");
447
+ const settingsContent = '{\n "editor.codeActionsOnSave": {\n "source.fixAll.eslint": "explicit"\n },\n "prettier.ignorePath": "node_modules/@cluerise/tools/dist/configs/.prettierignore",\n "typescript.tsdk": "node_modules/typescript/lib"\n}\n';
448
+ await FileUtils.createFile(settingsPath, settingsContent);
449
+ };
450
+ const _FileLinter = class _FileLinter {
451
+ constructor(options) {
452
+ __privateAdd(this, _FileLinter_instances);
453
+ __privateAdd(this, _options);
454
+ __privateAdd(this, _eslint);
455
+ __privateAdd(this, _eslintFixer, null);
456
+ __privateSet(this, _options, options ?? null);
457
+ __privateSet(this, _eslint, new ESLint({
458
+ overrideConfigFile: options == null ? void 0 : options.configPath
459
+ }));
460
+ if (options == null ? void 0 : options.fix) {
461
+ __privateSet(this, _eslintFixer, new ESLint({
462
+ fix: options.fix,
463
+ overrideConfigFile: options == null ? void 0 : options.configPath
464
+ }));
465
+ }
265
466
  }
266
- };
267
- const InitCommands = {
268
- initAllTools,
269
- initTool
270
- };
271
- const lintCommit = (args) => {
272
- const { status } = ChildProcess.spawnSync("commitlint", args, { stdio: "inherit" });
273
- return status ?? 0;
274
- };
275
- z.union([z.literal("all"), z.literal("code")]);
276
- const scopePatterns = {
277
- all: ["**"],
278
- code: ["src/**"]
279
- };
280
- const scopeShortcuts = Object.keys(scopePatterns);
281
- const isScopeShortcut = (scope) => scopeShortcuts.includes(scope);
282
- const resolveScope = (scope) => {
283
- if (Array.isArray(scope)) {
284
- return scope;
467
+ /**
468
+ * Lints files using `lint-staged` with the provided arguments.
469
+ *
470
+ * @param args - An array of arguments to pass to `lint-staged`.
471
+ * @returns The exit status of the `lint-staged` command.
472
+ */
473
+ static lintStaged(args) {
474
+ const { status } = ChildProcess.spawnSync("lint-staged", args, { stdio: "inherit" });
475
+ return status ?? 0;
285
476
  }
286
- if (isScopeShortcut(scope)) {
287
- return scopePatterns[scope];
477
+ /**
478
+ * Lints files matching the provided patterns using ESLint and Prettier.
479
+ *
480
+ * @param patterns - An array of glob patterns to match files against. Defaults to ['**'] which matches all files.
481
+ * @returns A promise that resolves to a LintFilesResult indicating the success or failure of the linting process.
482
+ */
483
+ async lint(patterns = ["**"]) {
484
+ var _a;
485
+ const prettierResults = await __privateMethod(this, _FileLinter_instances, prettierLint_fn).call(this, patterns);
486
+ const eslintResults = await __privateMethod(this, _FileLinter_instances, eslintLint_fn).call(this, patterns);
487
+ const eslintResult = await __privateMethod(this, _FileLinter_instances, prepareESLintLintResult_fn).call(this, eslintResults);
488
+ if (eslintResult.status === "failure") {
489
+ return eslintResult;
490
+ }
491
+ const prettierResult = __privateMethod(_a = _FileLinter, _FileLinter_static, preparePrettierLintResult_fn).call(_a, prettierResults);
492
+ if (prettierResult.status === "failure") {
493
+ return prettierResult;
494
+ }
495
+ return {
496
+ status: "success"
497
+ };
288
498
  }
289
- return [scope];
290
499
  };
291
- const formatWithPrettier = async (patterns) => {
292
- const eslint = new ESLint();
500
+ _options = new WeakMap();
501
+ _eslint = new WeakMap();
502
+ _eslintFixer = new WeakMap();
503
+ _FileLinter_static = new WeakSet();
504
+ preparePrettierLintResult_fn = function(results) {
505
+ if (results.length === 0) {
506
+ return { status: "success" };
507
+ }
508
+ const title = `Linting with Prettier failed with ${results.length} problem${results.length === 1 ? "" : "s"}
509
+ `;
510
+ let message = "Prettier failed with the following files:\n";
511
+ message += results.map((result) => `- ${result.path}`).join("\n");
512
+ message += OS.EOL;
513
+ return {
514
+ status: "failure",
515
+ title,
516
+ message,
517
+ problemCount: results.length
518
+ };
519
+ };
520
+ _FileLinter_instances = new WeakSet();
521
+ prettierLint_fn = async function(patterns) {
293
522
  const configPath = await Prettier.resolveConfigFile();
294
523
  if (!configPath) {
295
- return false;
524
+ return [];
296
525
  }
297
526
  const config = await Prettier.resolveConfig(configPath);
298
527
  if (!config) {
299
- return false;
528
+ return [];
300
529
  }
301
530
  const paths = await glob(patterns, {
302
531
  nodir: true,
303
532
  ignore: "node_modules/**"
304
533
  });
305
- await Promise.all(
534
+ const results = await Promise.all(
306
535
  paths.map(async (path) => {
307
- if (await eslint.isPathIgnored(path)) {
308
- return;
536
+ var _a;
537
+ if (await __privateGet(this, _eslint).isPathIgnored(path)) {
538
+ return null;
539
+ }
540
+ const contentBuffer = await FileSystem.readFile(path);
541
+ const content = contentBuffer.toString();
542
+ if ((_a = __privateGet(this, _options)) == null ? void 0 : _a.fix) {
543
+ const nextContent = await Prettier.format(content, {
544
+ ...config,
545
+ filepath: path
546
+ });
547
+ await FileSystem.writeFile(path, nextContent);
548
+ return null;
309
549
  }
310
- const prevContent = (await FileSystem.readFile(path)).toString();
311
- const nextContent = await Prettier.format(prevContent, {
550
+ const result = await Prettier.check(content, {
312
551
  ...config,
313
552
  filepath: path
314
553
  });
315
- await FileSystem.writeFile(path, nextContent);
554
+ return result ? null : { path };
316
555
  })
317
556
  );
318
- };
319
- const lintFiles = async (scope, options) => {
320
- const patterns = resolveScope(scope);
321
- if (options == null ? void 0 : options.fix) {
322
- await formatWithPrettier(patterns);
323
- }
324
- const eslint = new ESLint({
325
- fix: options == null ? void 0 : options.fix
326
- });
327
- const results = await eslint.lintFiles(patterns);
328
- const problemCount = results.reduce((sum, result) => sum + result.errorCount + result.warningCount, 0);
329
- if (options == null ? void 0 : options.fix) {
330
- await ESLint.outputFixes(results);
331
- }
332
- if (problemCount > 0) {
333
- const formatter = await eslint.loadFormatter("stylish");
334
- const resultText = formatter.format(results);
335
- console.error(resultText);
336
- const errorMessage = `Linting failed with ${problemCount} problem${problemCount === 1 ? "" : "s"}.`;
337
- throw new Error(errorMessage);
557
+ return results.filter((result) => result !== null);
558
+ };
559
+ prepareESLintLintResult_fn = async function(results) {
560
+ const problemCount = results.reduce(
561
+ (sum, result) => {
562
+ var _a;
563
+ return sum + result.errorCount + result.warningCount + (((_a = __privateGet(this, _options)) == null ? void 0 : _a.fix) ? -(result.fixableErrorCount + result.fixableWarningCount) : 0);
564
+ },
565
+ 0
566
+ );
567
+ if (problemCount === 0) {
568
+ return { status: "success" };
338
569
  }
570
+ const title = `ESLint failed with ${problemCount} problem${problemCount === 1 ? "" : "s"}`;
571
+ const formatter = await __privateGet(this, _eslint).loadFormatter("stylish");
572
+ const message = await formatter.format(results);
573
+ return {
574
+ status: "failure",
575
+ title,
576
+ message,
577
+ problemCount
578
+ };
339
579
  };
340
- const lintStaged = (args) => {
341
- const { status } = ChildProcess.spawnSync("lint-staged", args, { stdio: "inherit" });
342
- return status ?? 0;
343
- };
344
- const LintCommands = {
345
- lintFiles,
346
- lintCommit,
347
- lintStaged
580
+ eslintLint_fn = async function(patterns) {
581
+ const results = await __privateGet(this, _eslint).lintFiles(patterns);
582
+ const errorResults = ESLint.getErrorResults(results);
583
+ if (__privateGet(this, _eslintFixer) && errorResults.length > 0) {
584
+ await ESLint.outputFixes(await __privateGet(this, _eslintFixer).lintFiles(patterns));
585
+ }
586
+ return results;
348
587
  };
588
+ __privateAdd(_FileLinter, _FileLinter_static);
589
+ let FileLinter = _FileLinter;
349
590
  const toolNameArgSchema = z.union([z.literal("all"), toolNameSchema]);
350
591
  const parseInitArgs = ([nameArg]) => {
351
592
  const name = toolNameArgSchema.parse(nameArg);
@@ -353,33 +594,33 @@ const parseInitArgs = ([nameArg]) => {
353
594
  name
354
595
  };
355
596
  };
356
- const toolInitializerParams = {
357
- configDirectory: AppConfig.toolsConfigDirectory,
358
- configPackage: AppConfig.toolsConfigPackage
359
- };
360
597
  const main = async (args) => {
361
598
  try {
362
599
  const { name } = parseInitArgs(args);
363
- if (name === "all") {
364
- await InitCommands.initAllTools(toolInitializerParams);
365
- } else {
366
- await InitCommands.initTool(name, toolInitializerParams);
600
+ const toolInitializer = new ToolInitializer(CoreConfig.configDirectory, CoreConfig.configPackage);
601
+ const fileLinter = new FileLinter({ fix: true });
602
+ const statusLogger = new ConsoleStatusLogger("Initializing");
603
+ const toolNames = name === "all" ? toolInitializer.toolNames : [name];
604
+ for (const toolName of toolNames) {
605
+ statusLogger.begin(toolName);
606
+ await toolInitializer.initTool(toolName);
607
+ statusLogger.end(toolName);
367
608
  }
368
- await LintCommands.lintFiles("all", { fix: true });
609
+ await fileLinter.lint();
369
610
  return 0;
370
611
  } catch (error) {
371
612
  if (error instanceof ZodError) {
372
613
  const firstIssue = error.issues[0];
373
614
  if ((firstIssue == null ? void 0 : firstIssue.code) === "invalid_union") {
374
- console.error("Invalid tool name");
615
+ console.error("Error: Invalid tool name");
375
616
  return 1;
376
617
  }
377
618
  }
378
619
  if (error instanceof Error) {
379
- console.error(error.message);
380
- return 1;
620
+ console.error("Error:", error.message);
621
+ } else {
622
+ console.error("Error:", error);
381
623
  }
382
- console.error(error);
383
624
  return 1;
384
625
  }
385
626
  };