@p8ec/shared 2.6.1 → 3.0.3

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
@@ -69,3 +69,5 @@ p8-cli [command] [options]
69
69
  - Example: `p8-cli run build` - returns the `build` script using the detected package manager.
70
70
  - Example: `p8-cli run test auto par` - returns the `test` script using the detected
71
71
  package manager in parallel mode for workspaces.
72
+ - `pm` - Returns the detected package manager (`npm`, `yarn`, or `pnpm`).
73
+ - `ws` - Returns `true` if the project is a workspace, `false` otherwise.
@@ -7,10 +7,34 @@ pre-commit:
7
7
  commands:
8
8
  git:
9
9
  run: |
10
- if [[ $(git rev-parse --abbrev-ref HEAD) =~ ^(main|master|release)$ ]]; then
11
- echo "Direct commits to main, master, and release branches are not allowed."
12
- exit 1
10
+ if [[ $(git rev-parse --abbrev-ref HEAD) =~ ^(main|master|release)$ ]]; then
11
+ # Allow direct commits on protected branches ONLY if the staged changes are package.json
12
+ STAGED_FILES=$(git diff --cached --name-only)
13
+
14
+ if [[ -z "$STAGED_FILES" ]]; then
15
+ exit 0
13
16
  fi
17
+
18
+ ALLOWED_FILES=${ALLOWED_FILES:-"package.json"}
19
+ IFS=',' read -r -a ALLOWED_ARRAY <<< "$ALLOWED_FILES"
20
+
21
+ # Check every staged file; if any differs from the allowed files, block the commit
22
+ for f in $STAGED_FILES; do
23
+ MATCHED=false
24
+ for allowed in "${ALLOWED_ARRAY[@]}"; do
25
+ if [[ "$f" == "$allowed" || "$f" == */"$allowed" ]]; then
26
+ MATCHED=true
27
+ break
28
+ fi
29
+ done
30
+
31
+ if [[ "$MATCHED" == "false" ]]; then
32
+ echo "Direct commits to main, master, and release branches are not allowed, except for: $ALLOWED_FILES"
33
+ exit 1
34
+ fi
35
+ done
36
+ fi
37
+
14
38
 
15
39
  ### Commit message hook ###
16
40
  # 1. Allow only commit messages that follow a conventional commit format
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.dirn = void 0;
41
+ const path = __importStar(require("node:path"));
42
+ /**
43
+ * Returns the directory name of the caller, optionally returns a directory name specified levels up.
44
+ */
45
+ const dirn = (levelsUp) => {
46
+ const DEFAULT_LEVELS_UP = 0;
47
+ levelsUp !== null && levelsUp !== void 0 ? levelsUp : (levelsUp = `${DEFAULT_LEVELS_UP}`);
48
+ const levels = parseInt(levelsUp) || DEFAULT_LEVELS_UP;
49
+ return process.cwd().split(path.sep).reverse()[levels];
50
+ };
51
+ exports.dirn = dirn;
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
40
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
41
+ return new (P || (P = Promise))(function (resolve, reject) {
42
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
43
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
44
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
45
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
46
+ });
47
+ };
48
+ var __importDefault = (this && this.__importDefault) || function (mod) {
49
+ return (mod && mod.__esModule) ? mod : { "default": mod };
50
+ };
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.init = exports.initCleanup = void 0;
53
+ const fs = __importStar(require("node:fs"));
54
+ const path = __importStar(require("node:path"));
55
+ const yesno_1 = __importDefault(require("../utils/yesno"));
56
+ const detect_1 = require("../utils/detect");
57
+ const p8_shared_cli_1 = require("../p8-shared-cli");
58
+ const writeLn = console.log;
59
+ const initCleanup = (packageJson) => {
60
+ writeLn('Removing eslintConfig and prettier from package.json...');
61
+ const configBackup = {};
62
+ const configBackupFile = 'p8-package-backup.json';
63
+ const configBackupSections = ['eslintConfig', 'prettier', 'commitlint'];
64
+ configBackupSections.forEach((section) => {
65
+ if (packageJson[section]) {
66
+ writeLn(`Backing up ${section} to ${section}.${configBackupFile}...`);
67
+ configBackup[section] = packageJson[section];
68
+ delete packageJson[section];
69
+ }
70
+ });
71
+ p8_shared_cli_1.cliUtils.writeFile(`${configBackupFile}`, JSON.stringify(configBackup, null, 2));
72
+ p8_shared_cli_1.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
73
+ };
74
+ exports.initCleanup = initCleanup;
75
+ /**
76
+ * Initializes a TypeScript project with P8 shared configurations.
77
+ */
78
+ const init = (option_1, ...args_1) => __awaiter(void 0, [option_1, ...args_1], void 0, function* (option, pm = 'auto') {
79
+ const packageJsonData = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
80
+ const packageJson = JSON.parse(packageJsonData);
81
+ const moduleType = packageJson['type'] === 'module' ? 'mjs' : 'cjs';
82
+ const packageManager = pm === 'auto' ? (0, detect_1.detectPackageManager)() : pm;
83
+ writeLn(`Creating eslint.config.${moduleType}...`);
84
+ p8_shared_cli_1.cliUtils.copyAsset(`eslint.config.${moduleType}`);
85
+ writeLn(`Creating prettier.config.${moduleType}...`);
86
+ p8_shared_cli_1.cliUtils.copyAsset(`prettier.config.${moduleType}`);
87
+ const scripts = [
88
+ {
89
+ name: 'reset',
90
+ command: {
91
+ pnpm: 'rm -rf ./**/node_modules && rm -rf ./**/pnpm-lock.yaml && pnpm install',
92
+ yarn: 'rm -rf ./**/node_modules && rm -rf ./**/yarn.lock && yarn install',
93
+ npm: 'rm -rf ./**/node_modules && rm -rf ./**/package-lock.json && npm install',
94
+ },
95
+ },
96
+ {
97
+ name: 'audit',
98
+ command: {
99
+ pnpm: 'pnpm audit',
100
+ yarn: 'yarn npm audit',
101
+ npm: 'npm audit --audit-level=moderate',
102
+ },
103
+ },
104
+ ];
105
+ scripts.forEach((script) => {
106
+ var _a;
107
+ (_a = packageJson.scripts) !== null && _a !== void 0 ? _a : (packageJson.scripts = {});
108
+ packageJson.scripts[`${packageManager}:${script.name}`] = script.command[packageManager];
109
+ });
110
+ const lefthook = yield (0, yesno_1.default)({
111
+ question: 'Do you want to use commitlint/lefthook? [y]n',
112
+ defaultValue: true,
113
+ yesValues: ['yes', 'y'],
114
+ noValues: ['no', 'n'],
115
+ });
116
+ if (lefthook) {
117
+ writeLn(`Creating commitlint.config.${moduleType}...`);
118
+ p8_shared_cli_1.cliUtils.copyAsset(`commitlint.config.${moduleType}`);
119
+ writeLn('Creating lefthook.yml...');
120
+ p8_shared_cli_1.cliUtils.copyAsset('lefthook.yml');
121
+ writeLn('Adding lefthook install to postinstall...');
122
+ const lefthookInstall = 'lefthook install';
123
+ packageJson.scripts.postinstall = lefthookInstall;
124
+ const installCommands = {
125
+ npm: 'npm install --save-dev @commitlint/{config-conventional,cli} commitlint lefthook',
126
+ pnpm: 'pnpm install -D @commitlint/{config-conventional,cli} commitlint lefthook',
127
+ yarn: 'yarn add -D @commitlint/config-conventional @commitlint/cli commitlint lefthook',
128
+ };
129
+ const installCommand = installCommands[packageManager];
130
+ if (yield (0, yesno_1.default)({
131
+ question: `Do you want to run "${installCommand}" now? [y]n`,
132
+ defaultValue: true,
133
+ yesValues: ['yes', 'y'],
134
+ noValues: ['no', 'n'],
135
+ })) {
136
+ writeLn(`Executing ${installCommand}...`);
137
+ p8_shared_cli_1.cliUtils.execShell(installCommand);
138
+ }
139
+ else {
140
+ writeLn('You could run the following command to install needed dependencies:');
141
+ writeLn(installCommand);
142
+ }
143
+ if (yield (0, yesno_1.default)({
144
+ question: `Do you want to run "${lefthookInstall}" now? [y]n`,
145
+ defaultValue: true,
146
+ yesValues: ['yes', 'y'],
147
+ noValues: ['no', 'n'],
148
+ })) {
149
+ writeLn(`Executing ${lefthookInstall}...`);
150
+ p8_shared_cli_1.cliUtils.execShell(lefthookInstall);
151
+ }
152
+ }
153
+ if (option === null || option === void 0 ? void 0 : option.split(',').includes('cleanup')) {
154
+ (0, exports.initCleanup)(packageJson);
155
+ }
156
+ else {
157
+ writeLn('Skipping cleanup...');
158
+ p8_shared_cli_1.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
159
+ }
160
+ });
161
+ exports.init = init;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.root = void 0;
8
+ const detect_1 = require("../utils/detect");
9
+ /**
10
+ * Returns the root directory of the project.
11
+ */
12
+ const root = (cwd = process.cwd()) => {
13
+ return (0, detect_1.detectRoot)(cwd);
14
+ };
15
+ exports.root = root;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.run = void 0;
8
+ const detect_1 = require("../utils/detect");
9
+ const run = (script, packageManager, workspaceMode) => {
10
+ var _a;
11
+ if (!workspaceMode || workspaceMode === 'auto') {
12
+ workspaceMode = (0, detect_1.detectWorkspace)() ? 'seq' : 'none';
13
+ }
14
+ if (!packageManager || packageManager === 'auto') {
15
+ packageManager = (0, detect_1.detectPackageManager)();
16
+ }
17
+ const pnpmWorkspaceSeq = '-r --workspace-concurrency=1 --if-present --reporter-hide-prefix';
18
+ const pnpmWorkspacePar = '-r --if-present --parallel';
19
+ const yarnWorkspaceSeq = 'workspaces foreach -A';
20
+ const yarnWorkspacePar = 'workspaces foreach -A -p';
21
+ const commands = {
22
+ npm: {
23
+ none: `npm run ${script}`,
24
+ seq: `npm run ${script} --workspaces --if-present`,
25
+ },
26
+ yarn: {
27
+ none: `yarn run ${script}`,
28
+ seq: `yarn ${yarnWorkspaceSeq} run ${script}`,
29
+ par: `yarn ${yarnWorkspacePar} run ${script}`,
30
+ },
31
+ pnpm: {
32
+ none: `pnpm run ${script}`,
33
+ seq: `pnpm ${pnpmWorkspaceSeq} run ${script}`,
34
+ par: `pnpm ${pnpmWorkspacePar} run ${script}`,
35
+ },
36
+ };
37
+ if (!commands[packageManager]) {
38
+ throw new Error(`Unknown package manager: ${packageManager}`);
39
+ }
40
+ if (!((_a = commands[packageManager]) === null || _a === void 0 ? void 0 : _a[workspaceMode])) {
41
+ throw new Error(`Unknown workspace mode: ${workspaceMode}`);
42
+ }
43
+ return commands[packageManager][workspaceMode];
44
+ };
45
+ exports.run = run;
@@ -50,7 +50,7 @@ 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.detectWorkspace = exports.detectPackageManager = exports.initCleanup = exports.cliUtils = exports.IS_DEV = void 0;
53
+ exports.main = exports.cliUtils = exports.IS_DEV = exports.detectWorkspace = exports.detectPackageManager = exports.root = exports.run = exports.dirn = exports.initCleanup = exports.init = void 0;
54
54
  /**
55
55
  * P8 Shared CLI tool.
56
56
  *
@@ -60,20 +60,37 @@ exports.run = exports.dirn = exports.init = exports.detectWorkspace = exports.de
60
60
  const path = __importStar(require("node:path"));
61
61
  const fs = __importStar(require("node:fs"));
62
62
  const ferramenta_1 = require("ferramenta");
63
- const yesno_1 = __importDefault(require("./utils/yesno"));
64
63
  const prompt_1 = __importDefault(require("./utils/prompt"));
64
+ const args_1 = __importDefault(require("./utils/args"));
65
65
  const child_process = __importStar(require("node:child_process"));
66
+ const init_1 = require("./cmds/init");
67
+ Object.defineProperty(exports, "init", { enumerable: true, get: function () { return init_1.init; } });
68
+ Object.defineProperty(exports, "initCleanup", { enumerable: true, get: function () { return init_1.initCleanup; } });
69
+ const dirn_1 = require("./cmds/dirn");
70
+ Object.defineProperty(exports, "dirn", { enumerable: true, get: function () { return dirn_1.dirn; } });
71
+ const run_1 = require("./cmds/run");
72
+ Object.defineProperty(exports, "run", { enumerable: true, get: function () { return run_1.run; } });
73
+ const root_1 = require("./cmds/root");
74
+ Object.defineProperty(exports, "root", { enumerable: true, get: function () { return root_1.root; } });
75
+ const detect_1 = require("./utils/detect");
76
+ Object.defineProperty(exports, "detectPackageManager", { enumerable: true, get: function () { return detect_1.detectPackageManager; } });
77
+ Object.defineProperty(exports, "detectWorkspace", { enumerable: true, get: function () { return detect_1.detectWorkspace; } });
66
78
  exports.IS_DEV = process.env.NODE_ENV === 'development';
67
79
  let args = ferramenta_1.processArgs.args;
68
80
  const self = path.parse(ferramenta_1.processArgs.name).name;
69
- const writeLn = console.log;
81
+ const writeLn = (...args) => {
82
+ console.log(...args);
83
+ };
70
84
  exports.cliUtils = {
71
- execShell: (command) => exports.IS_DEV ? writeLn(`DEV: execShell ${command}`) : child_process.execSync(command).toString(),
85
+ writeLn: (...args) => {
86
+ writeLn(...args);
87
+ },
88
+ execShell: (command) => exports.IS_DEV ? exports.cliUtils.writeLn(`DEV: execShell ${command}`) : child_process.execSync(command).toString(),
72
89
  writeFile: (name, data) => exports.IS_DEV
73
- ? writeLn(`DEV: writeFile name=${name} data=${data}`)
90
+ ? console.log(`DEV: writeFile name=${name} data=${data}`)
74
91
  : fs.writeFileSync(path.join(process.cwd(), name), data),
75
92
  copyAsset: (name) => exports.IS_DEV
76
- ? writeLn(`DEV: copyAsset name=${name}`)
93
+ ? console.log(`DEV: copyAsset name=${name}`)
77
94
  : fs.copyFileSync(path.join(__dirname, '..', '..', 'assets', name), path.join(process.cwd(), name)),
78
95
  };
79
96
  if (args.length === 0 && !exports.IS_DEV && require.main === module) {
@@ -81,223 +98,69 @@ if (args.length === 0 && !exports.IS_DEV && require.main === module) {
81
98
  Usage: ${self} {command} [options]
82
99
 
83
100
  Commands:
84
- init [cleanup]
101
+ init [options]
85
102
  Initializes a new P8 repo.
86
103
  Options:
87
- cleanup: Removes redundant configurations from package.json.
104
+ --cleanup: Flag to remove redundant configurations from package.json.
88
105
  dirn [levelsUp]
89
106
  Returns the directory name of the caller.
90
- Options:
107
+ Arguments:
91
108
  levelsUp: The number of levels up to return the directory name.
92
- run [script [packageManager [workspaceMode]]]
109
+ run script [options]
93
110
  Returns a command to run a script with the specified package manager.
94
- Options:
111
+ Arguments:
95
112
  script: The script to run.
96
- packageManager: The package manager to use ('npm', 'yarn', 'pnpm' or 'auto'). Defaults to npm.
97
- workspaceMode: Whether to run in workspace mode ('seq', 'par', 'auto' for pnpm and yarn, and 'seq' for npm). Defaults to none.
113
+ Options:
114
+ -p {value}, --packageManager={value}: The package manager to use, where {value} is one of 'npm', 'pnpm', 'yarn', or 'auto' (defaults to 'auto').
115
+ -w {value}, --workspaceMode={value}: The workspace mode to use, where {value} is one of 'none', 'seq', 'par', or 'auto' (defaults to 'auto').
116
+ root
117
+ Returns path to the root of the repo.
118
+ pm
119
+ Returns the detected package manager.
120
+ ws
121
+ Returns true or false for detected workspace.
98
122
  `);
99
123
  if (exports.IS_DEV) {
100
124
  writeLn(`DEVELOPMENT MODE`);
101
125
  }
102
126
  process.exit(1);
103
127
  }
104
- const initCleanup = (packageJson) => {
105
- writeLn('Removing eslintConfig and prettier from package.json...');
106
- const configBackup = {};
107
- const configBackupFile = 'p8-package-backup.json';
108
- const configBackupSections = ['eslintConfig', 'prettier', 'commitlint'];
109
- configBackupSections.forEach((section) => {
110
- if (packageJson[section]) {
111
- writeLn(`Backing up ${section} to ${section}.${configBackupFile}...`);
112
- configBackup[section] = packageJson[section];
113
- delete packageJson[section];
114
- }
115
- });
116
- exports.cliUtils.writeFile(`${configBackupFile}`, JSON.stringify(configBackup, null, 2));
117
- exports.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
118
- };
119
- exports.initCleanup = initCleanup;
120
- /**
121
- * Detects the package manager used in the project.
122
- */
123
- const detectPackageManager = (cwd = process.cwd()) => {
124
- if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) {
125
- return 'pnpm';
126
- }
127
- if (fs.existsSync(path.join(cwd, 'yarn.lock'))) {
128
- return 'yarn';
129
- }
130
- return 'npm';
131
- };
132
- exports.detectPackageManager = detectPackageManager;
133
- /**
134
- * Detects if the project is a workspace.
135
- */
136
- const detectWorkspace = (cwd = process.cwd()) => {
137
- if (fs.existsSync(path.join(cwd, 'pnpm-workspace.yaml'))) {
138
- return true;
139
- }
140
- const packageJsonPath = path.join(cwd, 'package.json');
141
- if (fs.existsSync(packageJsonPath)) {
142
- try {
143
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
144
- if (packageJson.workspaces) {
145
- return true;
146
- }
147
- }
148
- catch (_a) {
149
- return false;
150
- }
151
- }
152
- return false;
153
- };
154
- exports.detectWorkspace = detectWorkspace;
155
- /**
156
- * Initializes a TypeScript project with P8 shared configurations.
157
- */
158
- const init = (option_1, ...args_1) => __awaiter(void 0, [option_1, ...args_1], void 0, function* (option, packageManager = (0, exports.detectPackageManager)()) {
159
- var _a;
160
- const packageJsonData = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
161
- const packageJson = JSON.parse(packageJsonData);
162
- const moduleType = packageJson['type'] === 'module' ? 'mjs' : 'cjs';
163
- writeLn(`Creating eslint.config.${moduleType}...`);
164
- exports.cliUtils.copyAsset(`eslint.config.${moduleType}`);
165
- writeLn(`Creating prettier.config.${moduleType}...`);
166
- exports.cliUtils.copyAsset(`prettier.config.${moduleType}`);
167
- (_a = packageJson.scripts) !== null && _a !== void 0 ? _a : (packageJson.scripts = {});
168
- packageJson.scripts[`${packageManager}:reset`] =
169
- packageManager === 'pnpm'
170
- ? 'rm -rf ./**/node_modules && rm -rf ./**/pnpm-lock.yaml && pnpm install'
171
- : packageManager === 'yarn'
172
- ? 'rm -rf ./**/node_modules && rm -rf ./**/yarn.lock && yarn install'
173
- : 'rm -rf ./**/node_modules && rm -rf ./**/package-lock.json && npm install';
174
- packageJson.scripts[`${packageManager}:audit`] =
175
- packageManager === 'pnpm'
176
- ? 'pnpm audit'
177
- : packageManager === 'yarn'
178
- ? 'yarn npm audit'
179
- : 'npm audit --audit-level=moderate';
180
- const lefthook = yield (0, yesno_1.default)({
181
- question: 'Do you want to use commitlint/lefthook? [y]n',
182
- defaultValue: true,
183
- yesValues: ['yes', 'y'],
184
- noValues: ['no', 'n'],
185
- });
186
- if (lefthook) {
187
- writeLn(`Creating commitlint.config.${moduleType}...`);
188
- exports.cliUtils.copyAsset(`commitlint.config.${moduleType}`);
189
- writeLn('Creating lefthook.yml...');
190
- exports.cliUtils.copyAsset('lefthook.yml');
191
- writeLn('Adding lefthook install to postinstall...');
192
- const lefthookInstall = 'lefthook install';
193
- packageJson.scripts.postinstall = lefthookInstall;
194
- const installCommands = {
195
- npm: 'npm install --save-dev @commitlint/{config-conventional,cli} commitlint lefthook',
196
- pnpm: 'pnpm install -D @commitlint/{config-conventional,cli} commitlint lefthook',
197
- yarn: 'yarn add -D @commitlint/config-conventional @commitlint/cli commitlint lefthook',
198
- };
199
- const installCommand = installCommands[packageManager];
200
- if (yield (0, yesno_1.default)({
201
- question: `Do you want to run "${installCommand}" now? [y]n`,
202
- defaultValue: true,
203
- yesValues: ['yes', 'y'],
204
- noValues: ['no', 'n'],
205
- })) {
206
- writeLn(`Executing ${installCommand}...`);
207
- exports.cliUtils.execShell(installCommand);
208
- }
209
- else {
210
- writeLn('You could run the following command to install needed dependencies:');
211
- writeLn(installCommand);
212
- }
213
- if (yield (0, yesno_1.default)({
214
- question: `Do you want to run "${lefthookInstall}" now? [y]n`,
215
- defaultValue: true,
216
- yesValues: ['yes', 'y'],
217
- noValues: ['no', 'n'],
218
- })) {
219
- writeLn(`Executing ${lefthookInstall}...`);
220
- exports.cliUtils.execShell(lefthookInstall);
221
- }
222
- }
223
- if (option === null || option === void 0 ? void 0 : option.split(',').includes('cleanup')) {
224
- (0, exports.initCleanup)(packageJson);
225
- }
226
- else {
227
- writeLn('Skipping cleanup...');
228
- exports.cliUtils.writeFile('package.json', JSON.stringify(packageJson, null, 2));
229
- }
230
- });
231
- exports.init = init;
232
- /**
233
- * Returns the directory name of the caller, optionally returns a directory name specified levels up.
234
- */
235
- const dirn = (levelsUp) => {
236
- const DEFAULT_LEVELS_UP = 0;
237
- levelsUp !== null && levelsUp !== void 0 ? levelsUp : (levelsUp = `${DEFAULT_LEVELS_UP}`);
238
- const levels = parseInt(levelsUp) || DEFAULT_LEVELS_UP;
239
- return process.cwd().split(path.sep).reverse()[levels];
240
- };
241
- exports.dirn = dirn;
242
- const run = (script, packageManager, workspaceMode) => {
243
- var _a;
244
- if (!workspaceMode || workspaceMode === 'auto') {
245
- workspaceMode = (0, exports.detectWorkspace)() ? 'seq' : 'none';
246
- }
247
- if (!packageManager || packageManager === 'auto') {
248
- packageManager = (0, exports.detectPackageManager)();
249
- }
250
- const pnpmWorkspaceSeq = '-r --workspace-concurrency=1 --if-present --reporter-hide-prefix';
251
- const pnpmWorkspacePar = '-r --if-present --parallel';
252
- const yarnWorkspaceSeq = 'workspaces foreach -A';
253
- const yarnWorkspacePar = 'workspaces foreach -A -p';
254
- const commands = {
255
- npm: {
256
- none: `npm run ${script}`,
257
- seq: `npm run ${script} --workspaces --if-present`,
258
- },
259
- yarn: {
260
- none: `yarn run ${script}`,
261
- seq: `yarn ${yarnWorkspaceSeq} run ${script}`,
262
- par: `yarn ${yarnWorkspacePar} run ${script}`,
263
- },
264
- pnpm: {
265
- none: `pnpm run ${script}`,
266
- seq: `pnpm ${pnpmWorkspaceSeq} run ${script}`,
267
- par: `pnpm ${pnpmWorkspacePar} run ${script}`,
268
- },
269
- };
270
- if (!commands[packageManager]) {
271
- throw new Error(`Unknown package manager: ${packageManager}`);
272
- }
273
- if (!((_a = commands[packageManager]) === null || _a === void 0 ? void 0 : _a[workspaceMode])) {
274
- throw new Error(`Unknown workspace mode: ${workspaceMode}`);
275
- }
276
- return commands[packageManager][workspaceMode];
277
- };
278
- exports.run = run;
279
- const main = () => __awaiter(void 0, void 0, void 0, function* () {
128
+ const main = (customArgs) => __awaiter(void 0, void 0, void 0, function* () {
280
129
  // Ask the user for arguments if IS_DEV is true
281
- if (exports.IS_DEV) {
130
+ if (exports.IS_DEV && !customArgs) {
282
131
  args = (yield (0, prompt_1.default)('Enter arguments:')).split(' ');
283
132
  }
284
- switch (args[0]) {
133
+ else if (customArgs) {
134
+ args = customArgs;
135
+ }
136
+ const parsed = (0, args_1.default)(args);
137
+ switch (parsed.command) {
285
138
  case 'init':
286
- yield (0, exports.init)(args[1]);
139
+ yield (0, init_1.init)(parsed.positional[0] || (parsed.options.cleanup ? 'cleanup' : ''));
287
140
  break;
288
141
  case 'dirn':
289
- writeLn((0, exports.dirn)(args[1]));
142
+ exports.cliUtils.writeLn((0, dirn_1.dirn)(parsed.positional[0]));
290
143
  break;
291
144
  case 'run':
292
- writeLn((0, exports.run)(args[1], args[2], args[3]));
145
+ exports.cliUtils.writeLn((0, run_1.run)(parsed.positional[0], (parsed.positional[1] || parsed.options.p || parsed.options.packageManager), (parsed.positional[2] || parsed.options.w || parsed.options.workspaceMode)));
146
+ break;
147
+ case 'root':
148
+ exports.cliUtils.writeLn((0, root_1.root)());
149
+ break;
150
+ case 'pm':
151
+ exports.cliUtils.writeLn((0, detect_1.detectPackageManager)());
152
+ break;
153
+ case 'ws':
154
+ exports.cliUtils.writeLn((0, detect_1.detectWorkspace)());
293
155
  break;
294
156
  default:
295
- console.error(`Unknown command: ${args[0]}`);
157
+ console.error(`Unknown command: ${parsed.command}`);
296
158
  process.exit(1);
297
159
  }
298
160
  });
161
+ exports.main = main;
299
162
  if (require.main === module) {
300
- main()
163
+ (0, exports.main)()
301
164
  .then((r) => {
302
165
  if (exports.IS_DEV) {
303
166
  writeLn(`DEV: setup completed successfully with result: ${JSON.stringify(r)}`);
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.parseArgs = void 0;
8
+ /**
9
+ * Robust command line argument parser.
10
+ *
11
+ * @param args - Array of command line arguments.
12
+ * @returns An object containing parsed commands, options, and positional arguments.
13
+ * @example
14
+ * ```ts
15
+ * const args = ['build', '--env=production', '-f', 'config.json', 'input.txt'];
16
+ * const parsed = parseArgs(args);
17
+ * // parsed = {
18
+ * // command: 'build',
19
+ * // options: { env: 'production', f: 'config.json' },
20
+ * // positional: ['input.txt']
21
+ * // }
22
+ * ```
23
+ */
24
+ const parseArgs = (args) => {
25
+ const result = {
26
+ command: '',
27
+ options: {},
28
+ positional: [],
29
+ };
30
+ let isCommandSet = false;
31
+ for (let i = 0; i < args.length; i++) {
32
+ const arg = args[i];
33
+ if (arg.startsWith('--')) {
34
+ const [key, value] = arg.slice(2).split('=');
35
+ if (value !== undefined) {
36
+ result.options[key] = value;
37
+ }
38
+ else {
39
+ const nextArg = args[i + 1];
40
+ if (nextArg && !nextArg.startsWith('-')) {
41
+ result.options[key] = nextArg;
42
+ i++;
43
+ }
44
+ else {
45
+ result.options[key] = true;
46
+ }
47
+ }
48
+ }
49
+ else if (arg.startsWith('-')) {
50
+ const keys = arg.slice(1).split('');
51
+ keys.forEach((key, index) => {
52
+ if (index === keys.length - 1) {
53
+ const nextArg = args[i + 1];
54
+ if (nextArg && !nextArg.startsWith('-')) {
55
+ result.options[key] = nextArg;
56
+ i++;
57
+ }
58
+ else {
59
+ result.options[key] = true;
60
+ }
61
+ }
62
+ else {
63
+ result.options[key] = true;
64
+ }
65
+ });
66
+ }
67
+ else {
68
+ if (!isCommandSet) {
69
+ result.command = arg;
70
+ isCommandSet = true;
71
+ }
72
+ else {
73
+ result.positional.push(arg);
74
+ }
75
+ }
76
+ }
77
+ return result;
78
+ };
79
+ exports.parseArgs = parseArgs;
80
+ exports.default = exports.parseArgs;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * 2026 Copyright P8 Enterprise Components, Inc.
4
+ * All Rights Reserved.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.detectWorkspace = exports.detectPackageManager = exports.detectRoot = void 0;
41
+ const fs = __importStar(require("node:fs"));
42
+ const path = __importStar(require("node:path"));
43
+ /**
44
+ * Finds the TOPMOST directory containing package.json
45
+ * by walking up the directory tree.
46
+ * @param startDir Directory to start from (defaults to cwd)
47
+ * @returns Absolute path to monorepo root, or null if none found
48
+ */
49
+ const detectRoot = (startDir = process.cwd()) => {
50
+ let currentDir = path.resolve(startDir);
51
+ // Avoid symlink loops
52
+ try {
53
+ currentDir = fs.realpathSync(currentDir);
54
+ }
55
+ catch (_a) {
56
+ // ignore
57
+ }
58
+ let lastMatch = startDir;
59
+ while (true) {
60
+ const pkgPath = path.join(currentDir, 'package.json');
61
+ try {
62
+ if (fs.existsSync(pkgPath)) {
63
+ lastMatch = currentDir;
64
+ }
65
+ }
66
+ catch (_b) {
67
+ // ignore fs errors and continue walking up
68
+ }
69
+ const parentDir = path.dirname(currentDir);
70
+ if (parentDir === currentDir) {
71
+ break; // filesystem root reached
72
+ }
73
+ currentDir = parentDir;
74
+ }
75
+ return lastMatch;
76
+ };
77
+ exports.detectRoot = detectRoot;
78
+ /**
79
+ * Detects the package manager used in the project.
80
+ */
81
+ const detectPackageManager = (cwd = process.cwd()) => {
82
+ const root = (0, exports.detectRoot)(cwd);
83
+ if (fs.existsSync(path.join(root, 'pnpm-lock.yaml'))) {
84
+ return 'pnpm';
85
+ }
86
+ if (fs.existsSync(path.join(root, 'yarn.lock'))) {
87
+ return 'yarn';
88
+ }
89
+ return 'npm';
90
+ };
91
+ exports.detectPackageManager = detectPackageManager;
92
+ /**
93
+ * Detects if the project is a workspace.
94
+ */
95
+ const detectWorkspace = (cwd = process.cwd()) => {
96
+ const root = (0, exports.detectRoot)(cwd);
97
+ if (fs.existsSync(path.join(root, 'pnpm-workspace.yaml'))) {
98
+ return true;
99
+ }
100
+ const packageJsonPath = path.join(root, 'package.json');
101
+ if (fs.existsSync(packageJsonPath)) {
102
+ try {
103
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
104
+ if (packageJson.workspaces) {
105
+ return true;
106
+ }
107
+ }
108
+ catch (_a) {
109
+ return false;
110
+ }
111
+ }
112
+ return false;
113
+ };
114
+ exports.detectWorkspace = detectWorkspace;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p8ec/shared",
3
- "version": "2.6.1",
3
+ "version": "3.0.3",
4
4
  "description": "P(8) Global Shared Library for Javascript",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  "docs:clean": "rm -rf docs"
30
30
  },
31
31
  "bin": {
32
- "p8-cli": "dist/cjs/bin/p8-shared-cli.js"
32
+ "p8cli": "dist/cjs/bin/p8-shared-cli.js"
33
33
  },
34
34
  "main": "dist/cjs/index.js",
35
35
  "module": "dist/esm/index.js",