@p8ec/shared 2.4.2 → 2.5.1

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/README.md CHANGED
@@ -7,6 +7,7 @@ Shared TypeScript/JavaScript libraries for P(8) products.
7
7
  Shared (**and very opinionated**) configuration for P(8) projects.
8
8
 
9
9
  **Contents:**
10
+
10
11
  - ESLint configuration
11
12
  - Prettier configuration
12
13
  - Commitlint configuration
@@ -62,9 +63,16 @@ p8-cli [command] [options]
62
63
 
63
64
  ### Commands
64
65
 
65
- - `init` - Initialize P(8) shared configuration in your project. Options: `cleanup` - remove configuration entries from `package.json`
66
- - Example: `p8-cli init --cleanup` - initializes the shared configuration and removes corresponding entries from `package.json`.
66
+ - `init` - Initialize P(8) shared configuration in your project. Options: `cleanup` - remove configuration entries from
67
+ `package.json`
68
+ - Example: `p8-cli init --cleanup` - initializes the shared configuration and removes corresponding entries from
69
+ `package.json`.
67
70
  - `dirn` - Get the directory name. Options: `0` - current directory (default), `1` - parent directory, `2` - 2 levels up
68
71
  directory, etc.
69
- - Example: `p8-cli dirn 1` - shows the parent directory name.
70
-
72
+ - Example: `p8-cli dirn 1` - shows the parent directory name.
73
+ - `run` - Returns a script string using the detected or specified package manager. Options: `script` - script name,
74
+ `packageManager` - npm, yarn, or pnpm (auto-detected by default), `workspaceMode` - mode of concurrency for workspaces
75
+ (if applicable): `seq` (default) or `par`.
76
+ - Example: `p8-cli run build` - runs the `build` script using the detected package manager.
77
+ - Example: `p8-cli run test pnpm par` - runs the `test` script using
78
+ `pnpm` in parallel mode for workspaces.
@@ -50,30 +50,35 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
50
50
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
51
  };
52
52
  Object.defineProperty(exports, "__esModule", { value: true });
53
+ exports.run = exports.dirn = exports.init = exports.detectPackageManager = exports.initCleanup = exports.cliUtils = exports.IS_DEV = void 0;
53
54
  /**
54
55
  * P8 Shared CLI tool.
55
56
  *
56
57
  * This tool is used to simplify the process of creating new P8 components.
57
58
  *
58
59
  */
59
- const path = __importStar(require("path"));
60
- const fs = __importStar(require("fs"));
60
+ const path = __importStar(require("node:path"));
61
+ const fs = __importStar(require("node:fs"));
61
62
  const ferramenta_1 = require("ferramenta");
62
63
  const yesno_1 = __importDefault(require("./utils/yesno"));
63
64
  const prompt_1 = __importDefault(require("./utils/prompt"));
64
65
  const child_process = __importStar(require("node:child_process"));
65
- const IS_DEV = process.env.NODE_ENV === 'development';
66
+ exports.IS_DEV = process.env.NODE_ENV === 'development';
66
67
  let args = ferramenta_1.processArgs.args;
67
68
  const self = path.parse(ferramenta_1.processArgs.name).name;
68
69
  const writeLn = console.log;
69
- const execShell = (command) => IS_DEV ? writeLn(`DEV: execShell ${command}`) : child_process.execSync(command).toString();
70
- const writeFile = (name, data) => IS_DEV ? writeLn(`DEV: writeFile name=${name} data=${data}`) : fs.writeFileSync(path.join(process.cwd(), name), data);
71
- const copyAsset = (name) => IS_DEV
72
- ? writeLn(`DEV: copyAsset name=${name}`)
73
- : fs.copyFileSync(path.join(__dirname, '..', '..', 'assets', name), path.join(process.cwd(), name));
74
- if (args.length === 0 && !IS_DEV) {
70
+ exports.cliUtils = {
71
+ execShell: (command) => exports.IS_DEV ? writeLn(`DEV: execShell ${command}`) : child_process.execSync(command).toString(),
72
+ writeFile: (name, data) => exports.IS_DEV
73
+ ? writeLn(`DEV: writeFile name=${name} data=${data}`)
74
+ : fs.writeFileSync(path.join(process.cwd(), name), data),
75
+ copyAsset: (name) => exports.IS_DEV
76
+ ? writeLn(`DEV: copyAsset name=${name}`)
77
+ : fs.copyFileSync(path.join(__dirname, '..', '..', 'assets', name), path.join(process.cwd(), name)),
78
+ };
79
+ if (args.length === 0 && !exports.IS_DEV && require.main === module) {
75
80
  writeLn(`
76
- Usage: ${self} [command] [options]
81
+ Usage: ${self} {command} [options]
77
82
 
78
83
  Commands:
79
84
  init [cleanup]
@@ -84,8 +89,22 @@ Commands:
84
89
  Returns the directory name of the caller.
85
90
  Options:
86
91
  levelsUp: The number of levels up to return the directory name.
92
+ run [script [packageManager [workspaceMode]]]
93
+ Returns a command to run a script with the specified package manager.
94
+ Options:
95
+ script: The script to run.
96
+ - 'start': Starts the application.
97
+ - 'build': Builds the application.
98
+ - 'test': Runs tests.
99
+ - 'lint': Lints the application.
100
+ - 'start-workspace': Starts the workspace.
101
+ - 'build-workspace': Builds the workspace.
102
+ - 'test-workspace': Runs tests in the workspace.
103
+ - 'lint-workspace': Lints the workspace.
104
+ packageManager: The package manager to use (npm, yarn, pnpm). Defaults to npm.
105
+ workspaceMode: Whether to run in workspace mode (seq or par for pnpm). Defaults to none.
87
106
  `);
88
- if (IS_DEV) {
107
+ if (exports.IS_DEV) {
89
108
  writeLn(`DEVELOPMENT MODE`);
90
109
  }
91
110
  process.exit(1);
@@ -102,21 +121,48 @@ const initCleanup = (packageJson) => {
102
121
  delete packageJson[section];
103
122
  }
104
123
  });
105
- writeFile(`${configBackupFile}`, JSON.stringify(configBackup, null, 2));
106
- writeFile('package.json', JSON.stringify(packageJson, null, 2));
124
+ exports.cliUtils.writeFile(`${configBackupFile}`, JSON.stringify(configBackup, null, 2));
125
+ exports.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
107
126
  };
127
+ exports.initCleanup = initCleanup;
128
+ /**
129
+ * Detects the package manager used in the project.
130
+ */
131
+ const detectPackageManager = (cwd = process.cwd()) => {
132
+ if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) {
133
+ return 'pnpm';
134
+ }
135
+ if (fs.existsSync(path.join(cwd, 'yarn.lock'))) {
136
+ return 'yarn';
137
+ }
138
+ return 'npm';
139
+ };
140
+ exports.detectPackageManager = detectPackageManager;
108
141
  /**
109
142
  * Initializes a TypeScript project with P8 shared configurations.
110
143
  */
111
- const init = (option) => __awaiter(void 0, void 0, void 0, function* () {
112
- const packageJson = JSON.parse(String(fs.readFileSync(path.join(process.cwd(), 'package.json'))));
144
+ const init = (option_1, ...args_1) => __awaiter(void 0, [option_1, ...args_1], void 0, function* (option, packageManager = (0, exports.detectPackageManager)()) {
145
+ var _a;
146
+ const packageJsonData = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
147
+ const packageJson = JSON.parse(packageJsonData);
113
148
  const moduleType = packageJson['type'] === 'module' ? 'mjs' : 'cjs';
114
149
  writeLn(`Creating eslint.config.${moduleType}...`);
115
- copyAsset(`eslint.config.${moduleType}`);
150
+ exports.cliUtils.copyAsset(`eslint.config.${moduleType}`);
116
151
  writeLn(`Creating prettier.config.${moduleType}...`);
117
- copyAsset(`prettier.config.${moduleType}`);
118
- packageJson.scripts['npm:reset'] = 'rm -rf ./**/node_modules && rm -rf ./**/package-lock.json && npm install';
119
- packageJson.scripts['npm:audit'] = 'npm audit --audit-level=moderate';
152
+ exports.cliUtils.copyAsset(`prettier.config.${moduleType}`);
153
+ (_a = packageJson.scripts) !== null && _a !== void 0 ? _a : (packageJson.scripts = {});
154
+ packageJson.scripts[`${packageManager}:reset`] =
155
+ packageManager === 'pnpm'
156
+ ? 'rm -rf ./**/node_modules && rm -rf ./**/pnpm-lock.yaml && pnpm install'
157
+ : packageManager === 'yarn'
158
+ ? 'rm -rf ./**/node_modules && rm -rf ./**/yarn.lock && yarn install'
159
+ : 'rm -rf ./**/node_modules && rm -rf ./**/package-lock.json && npm install';
160
+ packageJson.scripts[`${packageManager}:audit`] =
161
+ packageManager === 'pnpm'
162
+ ? 'pnpm audit'
163
+ : packageManager === 'yarn'
164
+ ? 'yarn npm audit'
165
+ : 'npm audit --audit-level=moderate';
120
166
  const lefthook = yield (0, yesno_1.default)({
121
167
  question: 'Do you want to use commitlint/lefthook? [y]n',
122
168
  defaultValue: true,
@@ -125,28 +171,30 @@ const init = (option) => __awaiter(void 0, void 0, void 0, function* () {
125
171
  });
126
172
  if (lefthook) {
127
173
  writeLn(`Creating commitlint.config.${moduleType}...`);
128
- copyAsset(`commitlint.config.${moduleType}`);
174
+ exports.cliUtils.copyAsset(`commitlint.config.${moduleType}`);
129
175
  writeLn('Creating lefthook.yml...');
130
- copyAsset('lefthook.yml');
176
+ exports.cliUtils.copyAsset('lefthook.yml');
131
177
  writeLn('Adding lefthook install to postinstall...');
132
178
  const lefthookInstall = 'lefthook install';
133
179
  packageJson.scripts.postinstall = lefthookInstall;
134
- const npmInstall = 'npm install --save-dev @commitlint/{config-conventional,cli} commitlint lefthook';
135
- const pnpmInstall = 'pnpm install -D @commitlint/{config-conventional,cli} commitlint lefthook';
180
+ const installCommands = {
181
+ npm: 'npm install --save-dev @commitlint/{config-conventional,cli} commitlint lefthook',
182
+ pnpm: 'pnpm install -D @commitlint/{config-conventional,cli} commitlint lefthook',
183
+ yarn: 'yarn add -D @commitlint/config-conventional @commitlint/cli commitlint lefthook',
184
+ };
185
+ const installCommand = installCommands[packageManager];
136
186
  if (yield (0, yesno_1.default)({
137
- question: `Do you want to run "${npmInstall}" now? [y]n`,
187
+ question: `Do you want to run "${installCommand}" now? [y]n`,
138
188
  defaultValue: true,
139
189
  yesValues: ['yes', 'y'],
140
190
  noValues: ['no', 'n'],
141
191
  })) {
142
- writeLn(`Executing ${npmInstall}...`);
143
- execShell(npmInstall);
192
+ writeLn(`Executing ${installCommand}...`);
193
+ exports.cliUtils.execShell(installCommand);
144
194
  }
145
195
  else {
146
196
  writeLn('You could run the following command to install needed dependencies:');
147
- writeLn(npmInstall);
148
- writeLn('Or, for pnpm users:');
149
- writeLn(pnpmInstall);
197
+ writeLn(installCommand);
150
198
  }
151
199
  if (yield (0, yesno_1.default)({
152
200
  question: `Do you want to run "${lefthookInstall}" now? [y]n`,
@@ -155,17 +203,18 @@ const init = (option) => __awaiter(void 0, void 0, void 0, function* () {
155
203
  noValues: ['no', 'n'],
156
204
  })) {
157
205
  writeLn(`Executing ${lefthookInstall}...`);
158
- execShell(lefthookInstall);
206
+ exports.cliUtils.execShell(lefthookInstall);
159
207
  }
160
208
  }
161
209
  if (option === null || option === void 0 ? void 0 : option.split(',').includes('cleanup')) {
162
- initCleanup(packageJson);
210
+ (0, exports.initCleanup)(packageJson);
163
211
  }
164
212
  else {
165
213
  writeLn('Skipping cleanup...');
166
- writeFile('package.json', JSON.stringify(packageJson, null, 2));
214
+ exports.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
167
215
  }
168
216
  });
217
+ exports.init = init;
169
218
  /**
170
219
  * Returns the directory name of the caller, optionally returns a directory name specified levels up.
171
220
  */
@@ -175,33 +224,70 @@ const dirn = (levelsUp) => {
175
224
  const levels = parseInt(levelsUp) || DEFAULT_LEVELS_UP;
176
225
  return process.cwd().split(path.sep).reverse()[levels];
177
226
  };
178
- const setup = () => __awaiter(void 0, void 0, void 0, function* () {
227
+ exports.dirn = dirn;
228
+ const run = (script, packageManager = (0, exports.detectPackageManager)(), workspaceMode = 'none') => {
229
+ var _a;
230
+ const pnpmWorkspaceSeq = '-r --workspace-concurrency=1 --if-present --reporter-hide-prefix';
231
+ const pnpmWorkspacePar = '-r --if-present --parallel';
232
+ const yarnWorkspaceSeq = 'workspaces foreach -A';
233
+ const yarnWorkspacePar = 'workspaces foreach -A -p';
234
+ const commands = {
235
+ npm: {
236
+ none: `npm run ${script}`,
237
+ seq: `npm run ${script} --workspaces --if-present`,
238
+ },
239
+ yarn: {
240
+ none: `yarn run ${script}`,
241
+ seq: `yarn ${yarnWorkspaceSeq} run ${script}`,
242
+ par: `yarn ${yarnWorkspacePar} run ${script}`,
243
+ },
244
+ pnpm: {
245
+ none: `pnpm run ${script}`,
246
+ seq: `pnpm ${pnpmWorkspaceSeq} run ${script}`,
247
+ par: `pnpm ${pnpmWorkspacePar} run ${script}`,
248
+ },
249
+ };
250
+ if (!commands[packageManager]) {
251
+ throw new Error(`Unknown package manager: ${packageManager}`);
252
+ }
253
+ if (!((_a = commands[packageManager]) === null || _a === void 0 ? void 0 : _a[workspaceMode])) {
254
+ throw new Error(`Unknown workspace mode: ${workspaceMode}`);
255
+ }
256
+ return commands[packageManager][workspaceMode];
257
+ };
258
+ exports.run = run;
259
+ const main = () => __awaiter(void 0, void 0, void 0, function* () {
179
260
  // Ask the user for arguments if IS_DEV is true
180
- if (IS_DEV) {
261
+ if (exports.IS_DEV) {
181
262
  args = (yield (0, prompt_1.default)('Enter arguments: ')).split(' ');
182
263
  }
183
264
  switch (args[0]) {
184
265
  case 'init':
185
- yield init(args[1]);
266
+ yield (0, exports.init)(args[1]);
186
267
  break;
187
268
  case 'dirn':
188
- writeLn(dirn(args[1]));
269
+ writeLn((0, exports.dirn)(args[1]));
270
+ break;
271
+ case 'run':
272
+ writeLn((0, exports.run)(args[1], args[2]));
189
273
  break;
190
274
  default:
191
275
  console.error(`Unknown command: ${args[0]}`);
192
276
  process.exit(1);
193
277
  }
194
278
  });
195
- setup()
196
- .then((r) => {
197
- if (IS_DEV) {
198
- writeLn(`DEV: setup completed with result: ${r}`);
199
- }
200
- })
201
- .catch((err) => {
202
- if (IS_DEV) {
203
- writeLn(`DEV: setup failed with error: ${err}`);
204
- }
205
- console.error(`Error: ${err}`);
206
- process.exit(1);
207
- });
279
+ if (require.main === module) {
280
+ main()
281
+ .then((r) => {
282
+ if (exports.IS_DEV) {
283
+ writeLn(`DEV: setup completed with result: ${r}`);
284
+ }
285
+ })
286
+ .catch((err) => {
287
+ if (exports.IS_DEV) {
288
+ writeLn(`DEV: setup failed with error: ${err}`);
289
+ }
290
+ console.error(`Error: ${err}`);
291
+ process.exit(1);
292
+ });
293
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p8ec/shared",
3
- "version": "2.4.2",
3
+ "version": "2.5.1",
4
4
  "description": "P(8) Global Shared Library for Javascript",
5
5
  "repository": {
6
6
  "type": "git",