@w5s/managed-script 1.0.0-alpha.4 → 1.0.0-alpha.5
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 +37 -0
- package/dist/ManagedScript-B8d632d3.js +321 -0
- package/dist/ManagedScript-B8d632d3.js.map +1 -0
- package/dist/cli.js +27 -43
- package/dist/cli.js.map +1 -1
- package/dist/{defaultContext-BthxLDX3.js → defaultContext-Xl2iA7UM.js} +38 -9
- package/dist/defaultContext-Xl2iA7UM.js.map +1 -0
- package/dist/index.d.ts +27 -54
- package/dist/index.js +23 -8
- package/dist/index.js.map +1 -1
- package/dist/type-hvsy_R0f.d.ts +103 -0
- package/dist/zx.d.ts +45 -14
- package/dist/zx.js +47 -17
- package/dist/zx.js.map +1 -1
- package/package.json +3 -2
- package/src/ManagedScript/defaultContext.ts +2 -4
- package/src/ManagedScript/execute.ts +45 -24
- package/src/ManagedScript/resolveScripts.ts +52 -5
- package/src/cli/RootCommand.ts +2 -3
- package/src/internal/Executor.ts +27 -10
- package/src/internal/Logger.ts +10 -3
- package/src/internal/PackageScriptOverride.ts +43 -0
- package/src/internal/ScriptInvocation.ts +55 -0
- package/src/internal/ScriptNameResolver.ts +5 -4
- package/src/internal/Stdio.ts +41 -0
- package/src/internal/lazy.ts +7 -0
- package/src/mergeConfig.ts +28 -0
- package/src/type/CommandContext.ts +6 -7
- package/src/type/ResolvedConfig.ts +27 -8
- package/src/type/StdOptions.ts +1 -0
- package/src/type/UserConfig.ts +38 -1
- package/src/type.ts +1 -0
- package/src/zx/ZXOptions.ts +73 -1
- package/src/zx/ZXShell.ts +18 -1
- package/src/zx/defaults.ts +6 -0
- package/src/zx/isCI.ts +26 -0
- package/src/zx/zx.ts +7 -13
- package/src/zx.ts +2 -0
- package/dist/ManagedScript-CLp9a43o.js +0 -193
- package/dist/ManagedScript-CLp9a43o.js.map +0 -1
- package/dist/defaultContext-BthxLDX3.js.map +0 -1
- package/dist/type-DQiyX1q_.d.ts +0 -53
- package/src/zx/defaultZXOptions.ts +0 -58
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@w5s/managed-script",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.5",
|
|
4
4
|
"description": "CLI tool to run project scripts from a shared configuration",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -42,6 +42,7 @@
|
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"c12": "^3.2.0",
|
|
45
|
+
"envalid": "^9.0.0",
|
|
45
46
|
"zx": "8.8.5-lite"
|
|
46
47
|
},
|
|
47
48
|
"engines": {
|
|
@@ -50,5 +51,5 @@
|
|
|
50
51
|
"publishConfig": {
|
|
51
52
|
"access": "public"
|
|
52
53
|
},
|
|
53
|
-
"gitHead": "
|
|
54
|
+
"gitHead": "8c839f967fbc4477af3e767c4ecfa2d8a693eda0"
|
|
54
55
|
}
|
|
@@ -11,8 +11,7 @@ export function defaultContext(context: Partial<CommandContext> | undefined): Co
|
|
|
11
11
|
dryRun,
|
|
12
12
|
env = process.env,
|
|
13
13
|
logLevel,
|
|
14
|
-
|
|
15
|
-
stdout = process.stdout,
|
|
14
|
+
stdio = 'inherit',
|
|
16
15
|
} = context ?? {};
|
|
17
16
|
const envLogLevel = env[ManagedScriptEnv.LogLevel];
|
|
18
17
|
return {
|
|
@@ -22,8 +21,7 @@ export function defaultContext(context: Partial<CommandContext> | undefined): Co
|
|
|
22
21
|
dryRun: dryRun ?? cli.dryRun ?? false,
|
|
23
22
|
env,
|
|
24
23
|
logLevel: logLevel ?? cli.logLevel ?? (isLogLevel(envLogLevel) ? envLogLevel : 'info'),
|
|
25
|
-
|
|
26
|
-
stdout,
|
|
24
|
+
stdio,
|
|
27
25
|
};
|
|
28
26
|
}
|
|
29
27
|
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
|
|
3
3
|
import type { ManagedScriptCommand } from '../type.js';
|
|
4
|
+
import type { ResolvedConfig } from '../type/ResolvedConfig.js';
|
|
4
5
|
|
|
5
6
|
import { ConfigLoader } from '../internal/ConfigLoader.js';
|
|
6
7
|
import { Executor } from '../internal/Executor.js';
|
|
7
8
|
import { Logger } from '../internal/Logger.js';
|
|
9
|
+
import { PackageScriptOverride } from '../internal/PackageScriptOverride.js';
|
|
10
|
+
import { ScriptInvocation } from '../internal/ScriptInvocation.js';
|
|
8
11
|
import { ScriptNameResolver } from '../internal/ScriptNameResolver.js';
|
|
12
|
+
import { Stdio } from '../internal/Stdio.js';
|
|
9
13
|
import { ManagedScriptEnv } from '../ManagedScriptEnv.js';
|
|
10
14
|
import { defaultContext } from './defaultContext.js';
|
|
11
15
|
import { resolveScripts } from './resolveScripts.js';
|
|
@@ -13,10 +17,11 @@ import { resolveScripts } from './resolveScripts.js';
|
|
|
13
17
|
const handlers = {
|
|
14
18
|
RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {
|
|
15
19
|
const {
|
|
16
|
-
context: { color, cwd, dryRun, env, logLevel,
|
|
20
|
+
context: { color, cwd, dryRun, env, logLevel, stdio },
|
|
17
21
|
parameters: { scriptArgs = [], scriptName },
|
|
18
22
|
} = command;
|
|
19
|
-
const
|
|
23
|
+
const { stdout } = Stdio.resolve(stdio);
|
|
24
|
+
const logger = Logger.create({ color, level: logLevel, stdio });
|
|
20
25
|
const loaded = await ConfigLoader.load({ cwd });
|
|
21
26
|
logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}`);
|
|
22
27
|
const resolved = resolveScripts(loaded);
|
|
@@ -25,29 +30,45 @@ const handlers = {
|
|
|
25
30
|
const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });
|
|
26
31
|
if (name == null) {
|
|
27
32
|
throw new Error(
|
|
28
|
-
'Unable to resolve the script name. Pass it as the first argument
|
|
33
|
+
'Unable to resolve the script name. Pass it as the first argument or run through an npm/pnpm script (npm_lifecycle_event).',
|
|
29
34
|
);
|
|
30
35
|
}
|
|
31
36
|
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
const overrideName = await PackageScriptOverride.find({ cwd, name });
|
|
38
|
+
let invocation: ScriptInvocation;
|
|
39
|
+
let scriptLabel: string;
|
|
40
|
+
let origin: ResolvedConfig.Script;
|
|
41
|
+
if (overrideName == null) {
|
|
42
|
+
const script = scripts[name];
|
|
43
|
+
if (script == null) {
|
|
44
|
+
const available = Object.keys(scripts);
|
|
45
|
+
throw new Error(
|
|
46
|
+
`No script named "${name}" found in the configuration.${
|
|
47
|
+
available.length > 0 ? ` Available scripts: ${available.join(', ')}.` : ' No scripts are configured.'
|
|
48
|
+
}`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
41
51
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
52
|
+
invocation = ScriptInvocation.create(script, scriptArgs);
|
|
53
|
+
scriptLabel = name;
|
|
54
|
+
origin = script;
|
|
55
|
+
// relative to cwd
|
|
56
|
+
// eslint-disable-next-line ts/no-non-null-assertion
|
|
57
|
+
logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile!)}`);
|
|
58
|
+
} else {
|
|
59
|
+
// Run through npm so the override behaves exactly like a regular package.json script
|
|
60
|
+
origin = {
|
|
61
|
+
args: ['run', overrideName, ...(scriptArgs.length > 0 ? ['--'] : [])],
|
|
62
|
+
configDir: undefined,
|
|
63
|
+
configFile: undefined,
|
|
64
|
+
runner: 'npm',
|
|
65
|
+
};
|
|
66
|
+
invocation = ScriptInvocation.create(origin, scriptArgs);
|
|
67
|
+
scriptLabel = overrideName;
|
|
68
|
+
logger.debug(`Script "${name}" overridden by package.json script "${overrideName}"`);
|
|
69
|
+
}
|
|
46
70
|
|
|
47
|
-
|
|
48
|
-
// eslint-disable-next-line ts/no-non-null-assertion
|
|
49
|
-
logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile!)}`);
|
|
50
|
-
stdout.write(`$ ${commandLine}\n`);
|
|
71
|
+
stdout.write(`$ ${ScriptInvocation.format(invocation)}\n`);
|
|
51
72
|
if (dryRun) {
|
|
52
73
|
return 0;
|
|
53
74
|
}
|
|
@@ -55,16 +76,16 @@ const handlers = {
|
|
|
55
76
|
// Prepare the environment variables for the script execution.
|
|
56
77
|
const scriptEnv = {
|
|
57
78
|
[ManagedScriptEnv.Color]: color,
|
|
58
|
-
[ManagedScriptEnv.ConfigDir]:
|
|
59
|
-
[ManagedScriptEnv.ConfigFile]:
|
|
79
|
+
[ManagedScriptEnv.ConfigDir]: origin.configDir,
|
|
80
|
+
[ManagedScriptEnv.ConfigFile]: origin.configFile,
|
|
60
81
|
[ManagedScriptEnv.Cwd]: cwd,
|
|
61
82
|
[ManagedScriptEnv.LogLevel]: logLevel,
|
|
62
83
|
[ManagedScriptEnv.Name]: name,
|
|
63
84
|
};
|
|
64
|
-
const exitCode = await Executor.run(
|
|
85
|
+
const exitCode = await Executor.run({ ...invocation.target, cwd, env: scriptEnv });
|
|
65
86
|
|
|
66
87
|
if (exitCode !== 0) {
|
|
67
|
-
throw new Error(`Script "${
|
|
88
|
+
throw new Error(`Script "${scriptLabel}" exited with code ${exitCode}.`);
|
|
68
89
|
}
|
|
69
90
|
|
|
70
91
|
return exitCode;
|
|
@@ -3,6 +3,8 @@ import path from 'node:path/win32';
|
|
|
3
3
|
import type { ConfigLoaderResult } from '../internal/ConfigLoader.js';
|
|
4
4
|
import type { ResolvedConfig } from '../type/ResolvedConfig.js';
|
|
5
5
|
|
|
6
|
+
type NormalizedScript = Pick<ResolvedConfig.RunnerScript, 'args' | 'run' | 'runner'> | Pick<ResolvedConfig.ShellScript, 'args' | 'run' | 'runner'>;
|
|
7
|
+
|
|
6
8
|
export function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {
|
|
7
9
|
const scripts: ResolvedConfig['scripts'] = {};
|
|
8
10
|
const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];
|
|
@@ -11,11 +13,7 @@ export function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {
|
|
|
11
13
|
for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {
|
|
12
14
|
const configFile = layer.configFile ?? loaded.configFile;
|
|
13
15
|
const configDir = configFile == null ? undefined : path.dirname(configFile);
|
|
14
|
-
scripts[name] ??= {
|
|
15
|
-
command,
|
|
16
|
-
configDir,
|
|
17
|
-
configFile,
|
|
18
|
-
};
|
|
16
|
+
scripts[name] ??= { ...normalizeScript(name, command), configDir, configFile };
|
|
19
17
|
}
|
|
20
18
|
}
|
|
21
19
|
|
|
@@ -23,3 +21,52 @@ export function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {
|
|
|
23
21
|
scripts,
|
|
24
22
|
};
|
|
25
23
|
}
|
|
24
|
+
|
|
25
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
26
|
+
return Object.prototype.toString.call(value) === '[object Object]';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isStringArray(value: unknown): value is ReadonlyArray<string> {
|
|
30
|
+
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const allowedKeys = new Set(['args', 'run', 'runner']);
|
|
34
|
+
|
|
35
|
+
function normalizeScript(name: string, definition: unknown): NormalizedScript {
|
|
36
|
+
if (typeof definition === 'string') {
|
|
37
|
+
return requireRun(name, definition);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!isPlainObject(definition)) {
|
|
41
|
+
throw new TypeError(`Script "${name}" must be a shell command string or an object with "run", or "runner" and "args".`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const unknownKeys = Object.keys(definition).filter((key) => !allowedKeys.has(key));
|
|
45
|
+
if (unknownKeys.length > 0) {
|
|
46
|
+
throw new TypeError(`Script "${name}" has unknown option(s): ${unknownKeys.join(', ')}.`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const { args, run, runner } = definition;
|
|
50
|
+
if (run !== undefined) {
|
|
51
|
+
if (runner !== undefined || args !== undefined) {
|
|
52
|
+
throw new TypeError(`Script "${name}" cannot mix "run" with "runner" or "args".`);
|
|
53
|
+
}
|
|
54
|
+
return requireRun(name, run);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (typeof runner !== 'string' || runner.trim().length === 0) {
|
|
58
|
+
throw new TypeError(`Script "${name}" runner must be a non-empty string.`);
|
|
59
|
+
}
|
|
60
|
+
if (args !== undefined && !isStringArray(args)) {
|
|
61
|
+
throw new TypeError(`Script "${name}" args must be an array of strings.`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return { args: [...(args ?? [])], runner };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function requireRun(name: string, run: unknown): NormalizedScript {
|
|
68
|
+
if (typeof run !== 'string' || run.trim().length === 0) {
|
|
69
|
+
throw new TypeError(`Script "${name}" run must be a non-empty string.`);
|
|
70
|
+
}
|
|
71
|
+
return { run };
|
|
72
|
+
}
|
package/src/cli/RootCommand.ts
CHANGED
|
@@ -13,7 +13,7 @@ export class RootCommand extends Command {
|
|
|
13
13
|
static override paths = [Command.Default];
|
|
14
14
|
static override usage = Command.Usage({
|
|
15
15
|
description: 'Run a script from the managed-script configuration.',
|
|
16
|
-
details: 'Resolves the script name from the first positional argument
|
|
16
|
+
details: 'Resolves the script name from the first positional argument or npm_lifecycle_event, then executes it. Use --dry-run,-n to print the resolved command without executing it. Use --loglevel, --silent,-s or --verbose,-v to control status messages, forwarded to the script as MANAGED_SCRIPT_LOGLEVEL. Use --color[=WHEN] or --no-color to control ANSI colors (WHEN: auto, always, never).',
|
|
17
17
|
});
|
|
18
18
|
|
|
19
19
|
readonly color = Option.String('--color', {
|
|
@@ -71,8 +71,7 @@ export class RootCommand extends Command {
|
|
|
71
71
|
await ManagedScript.runScript({
|
|
72
72
|
context: {
|
|
73
73
|
cli: { color, cwd: this.cwd, dryRun: this.dryRun, logLevel },
|
|
74
|
-
|
|
75
|
-
stdout: this.context.stdout,
|
|
74
|
+
stdio: ['inherit', this.context.stdout, this.context.stderr],
|
|
76
75
|
},
|
|
77
76
|
parameters: {
|
|
78
77
|
scriptArgs,
|
package/src/internal/Executor.ts
CHANGED
|
@@ -1,23 +1,40 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
|
|
3
|
-
export
|
|
3
|
+
export type ExecutorRequest = ExecutorTarget & {
|
|
4
4
|
readonly cwd?: string | undefined;
|
|
5
5
|
readonly env?: NodeJS.ProcessEnv | undefined;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export interface ExecutorRun {
|
|
9
|
+
readonly args?: undefined;
|
|
10
|
+
readonly run: string;
|
|
11
|
+
readonly runner?: undefined;
|
|
6
12
|
}
|
|
7
13
|
|
|
14
|
+
export interface ExecutorRunner {
|
|
15
|
+
readonly args?: ReadonlyArray<string> | undefined;
|
|
16
|
+
readonly run?: undefined;
|
|
17
|
+
readonly runner: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Same shape as a lefthook job: either a shell command (`run`) or a program with arguments (`runner` + `args`).
|
|
22
|
+
*/
|
|
23
|
+
export type ExecutorTarget = ExecutorRun | ExecutorRunner;
|
|
24
|
+
|
|
8
25
|
/**
|
|
9
|
-
*
|
|
26
|
+
* Runs a shell command (`run`), or a program spawned directly without a shell (`runner`).
|
|
27
|
+
* Stdio is inherited and the exit code is forwarded.
|
|
10
28
|
*/
|
|
11
29
|
export const Executor = {
|
|
12
|
-
async run(
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
stdio: 'inherit',
|
|
19
|
-
});
|
|
30
|
+
async run(request: ExecutorRequest): Promise<number> {
|
|
31
|
+
const env = request.env == null ? process.env : { ...process.env, ...request.env };
|
|
32
|
+
const options = { cwd: request.cwd, env, stdio: 'inherit' } as const;
|
|
33
|
+
const child = request.runner == null
|
|
34
|
+
? spawn(request.run, { ...options, shell: true })
|
|
35
|
+
: spawn(request.runner, request.args ?? [], { ...options, shell: false });
|
|
20
36
|
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
21
38
|
child.on('error', reject);
|
|
22
39
|
child.on('close', (code, signal) => {
|
|
23
40
|
resolve(code ?? (signal == null ? 1 : 128));
|
package/src/internal/Logger.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import type { StdioOptions } from '../type.js';
|
|
2
|
+
|
|
1
3
|
import { meta } from '../meta.js';
|
|
4
|
+
import { Stdio } from './Stdio.js';
|
|
2
5
|
|
|
3
6
|
export type ColorMode = 'always' | 'auto' | 'never';
|
|
4
7
|
export type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';
|
|
@@ -22,8 +25,11 @@ export interface CreateLoggerOptions {
|
|
|
22
25
|
* Program name used as message prefix (default: binary name)
|
|
23
26
|
*/
|
|
24
27
|
readonly name?: string;
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Standard I/O, messages are written to index `2` (stderr)
|
|
31
|
+
*/
|
|
32
|
+
readonly stdio: StdioOptions;
|
|
27
33
|
}
|
|
28
34
|
|
|
29
35
|
export interface Logger {
|
|
@@ -37,7 +43,8 @@ export interface Logger {
|
|
|
37
43
|
* Creates a logger writing to `stream`, filtering out messages above the configured `level`.
|
|
38
44
|
*/
|
|
39
45
|
export const Logger = {
|
|
40
|
-
create({ color = 'auto', level, name = meta.binaryName,
|
|
46
|
+
create({ color = 'auto', level, name = meta.binaryName, stdio }: CreateLoggerOptions): Logger {
|
|
47
|
+
const { stderr } = Stdio.resolve(stdio);
|
|
41
48
|
const write = (messageLevel: LogLevel, message: string) => {
|
|
42
49
|
if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {
|
|
43
50
|
return;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Suffix marking a package.json script as an override of the managed script with the same name.
|
|
6
|
+
*/
|
|
7
|
+
const OVERRIDE_MARKER = '!';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @namespace
|
|
11
|
+
*/
|
|
12
|
+
export const PackageScriptOverride = {
|
|
13
|
+
/**
|
|
14
|
+
* Returns the name of the override script (`<name>!`) if it is defined in `<cwd>/package.json`.
|
|
15
|
+
*
|
|
16
|
+
* @param options
|
|
17
|
+
* @param options.cwd
|
|
18
|
+
* @param options.name
|
|
19
|
+
*/
|
|
20
|
+
async find({ cwd, name }: { readonly cwd: string; readonly name: string }): Promise<string | undefined> {
|
|
21
|
+
const overrideName = `${name}${OVERRIDE_MARKER}`;
|
|
22
|
+
try {
|
|
23
|
+
const content = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8')) as null | {
|
|
24
|
+
scripts?: Record<string, unknown>;
|
|
25
|
+
};
|
|
26
|
+
const scripts = content?.scripts;
|
|
27
|
+
return scripts != null &&
|
|
28
|
+
typeof scripts === 'object' &&
|
|
29
|
+
Object.hasOwn(scripts, overrideName) &&
|
|
30
|
+
typeof scripts[overrideName] === 'string'
|
|
31
|
+
? overrideName
|
|
32
|
+
: undefined;
|
|
33
|
+
} catch {
|
|
34
|
+
// missing or invalid package.json: no override
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The marker used to identify override scripts in `package.json`.
|
|
41
|
+
*/
|
|
42
|
+
marker: OVERRIDE_MARKER,
|
|
43
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ResolvedConfig } from '../type/ResolvedConfig.js';
|
|
2
|
+
import type { ExecutorTarget } from './Executor.js';
|
|
3
|
+
|
|
4
|
+
const shellSafe = /^[\w@%+=:,./-]+$/;
|
|
5
|
+
|
|
6
|
+
export interface ScriptInvocation {
|
|
7
|
+
/**
|
|
8
|
+
* What the executor runs
|
|
9
|
+
*/
|
|
10
|
+
readonly target: ExecutorTarget;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @namespace
|
|
15
|
+
*/
|
|
16
|
+
export const ScriptInvocation = {
|
|
17
|
+
/**
|
|
18
|
+
* Builds the command line shown to the user and the target passed to the executor.
|
|
19
|
+
* A `run` script stays one command string. A `runner` script receives real arguments.
|
|
20
|
+
*
|
|
21
|
+
* @param script
|
|
22
|
+
* @param scriptArgs
|
|
23
|
+
*/
|
|
24
|
+
create(script: ResolvedConfig.Script, scriptArgs: ReadonlyArray<string>): ScriptInvocation {
|
|
25
|
+
if (script.runner != null) {
|
|
26
|
+
const args = [...script.args, ...scriptArgs];
|
|
27
|
+
return {
|
|
28
|
+
target: { args, runner: script.runner },
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const run = [script.run, ...scriptArgs.map((argument) => quoteShell(argument))].join(' ');
|
|
33
|
+
return {
|
|
34
|
+
target: { run },
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns the command line as a string suitable for display.
|
|
40
|
+
*
|
|
41
|
+
* @param self
|
|
42
|
+
*/
|
|
43
|
+
format(self: ScriptInvocation): string {
|
|
44
|
+
const { args, run, runner } = self.target;
|
|
45
|
+
return runner == null ? run : formatArgv([runner, ...args ?? []]);
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
function formatArgv(argv: ReadonlyArray<string>): string {
|
|
50
|
+
return argv.map((part) => shellSafe.test(part) ? part : quoteShell(part)).join(' ');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function quoteShell(value: string): string {
|
|
54
|
+
return `'${value.replaceAll("'", String.raw`'\''`)}'`;
|
|
55
|
+
}
|
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { ManagedScriptEnv } from '../ManagedScriptEnv.js';
|
|
2
|
-
|
|
3
1
|
export interface ScriptNameResolverOptions {
|
|
4
2
|
readonly env: NodeJS.ProcessEnv;
|
|
5
3
|
readonly scriptName: string | undefined;
|
|
@@ -8,10 +6,13 @@ export interface ScriptNameResolverOptions {
|
|
|
8
6
|
/**
|
|
9
7
|
* Resolves the script name to run.
|
|
10
8
|
*
|
|
11
|
-
* Priority: first positional CLI argument > `
|
|
9
|
+
* Priority: first positional CLI argument > `npm_lifecycle_event` env var.
|
|
10
|
+
*
|
|
11
|
+
* `MANAGED_SCRIPT_NAME` is deliberately not read: it is only provided to the spawned script, so that
|
|
12
|
+
* an inherited value can never shadow the name of a nested invocation.
|
|
12
13
|
*/
|
|
13
14
|
export const ScriptNameResolver = {
|
|
14
15
|
resolve({ env, scriptName }: ScriptNameResolverOptions): string | undefined {
|
|
15
|
-
return scriptName ?? env[
|
|
16
|
+
return scriptName ?? env['npm_lifecycle_event'];
|
|
16
17
|
},
|
|
17
18
|
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { StdioOptions } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
import { Writable } from 'node:stream';
|
|
4
|
+
|
|
5
|
+
export interface StdioStreams {
|
|
6
|
+
readonly stderr: NodeJS.WritableStream;
|
|
7
|
+
readonly stdout: NodeJS.WritableStream;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function createSink(): NodeJS.WritableStream {
|
|
11
|
+
return new Writable({
|
|
12
|
+
write(_chunk, _encoding, callback) {
|
|
13
|
+
callback();
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function resolveEntry(entry: StdioOptions[number] | undefined, fd: 1 | 2): NodeJS.WritableStream {
|
|
19
|
+
const parent = fd === 1 ? process.stdout : process.stderr;
|
|
20
|
+
if (entry === 'inherit' || entry === fd) {
|
|
21
|
+
return parent;
|
|
22
|
+
}
|
|
23
|
+
// `ignore`, `pipe`, `ipc`, other file descriptors and unset entries have no stream to write to
|
|
24
|
+
return (typeof entry === 'object' && entry != null && 'write' in entry && typeof entry.write === 'function') ? entry as unknown as NodeJS.WritableStream : createSink();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Helpers for Node.js {@link StdioOptions}
|
|
29
|
+
*
|
|
30
|
+
* @namespace
|
|
31
|
+
*/
|
|
32
|
+
export const Stdio = {
|
|
33
|
+
/**
|
|
34
|
+
* Resolve the writable streams (stdout is index 1, stderr is index 2) described by `stdio`.
|
|
35
|
+
*
|
|
36
|
+
* @param stdio
|
|
37
|
+
*/
|
|
38
|
+
resolve(stdio: StdioOptions): StdioStreams {
|
|
39
|
+
return typeof stdio === 'string' ? { stderr: resolveEntry(stdio, 2), stdout: resolveEntry(stdio, 1) } : { stderr: resolveEntry(stdio[2], 2), stdout: resolveEntry(stdio[1], 1) };
|
|
40
|
+
},
|
|
41
|
+
};
|
package/src/mergeConfig.ts
CHANGED
|
@@ -49,6 +49,11 @@ function mergeConfigRecursively(
|
|
|
49
49
|
continue;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
if (key === 'scripts' && isObject(existing) && isObject(value)) {
|
|
53
|
+
merged[key] = replaceEntries(existing, value);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
|
|
52
57
|
if (Array.isArray(existing) || Array.isArray(value)) {
|
|
53
58
|
merged[key] = [...toArray(existing), ...toArray(value)];
|
|
54
59
|
continue;
|
|
@@ -65,6 +70,29 @@ function mergeConfigRecursively(
|
|
|
65
70
|
return merged;
|
|
66
71
|
}
|
|
67
72
|
|
|
73
|
+
/**
|
|
74
|
+
* Script definitions replace each other. A runner's `args` array is not concatenated with the previous one.
|
|
75
|
+
*
|
|
76
|
+
* @param defaults
|
|
77
|
+
* @param overrides
|
|
78
|
+
*/
|
|
79
|
+
function replaceEntries(
|
|
80
|
+
defaults: Record<string, unknown>,
|
|
81
|
+
overrides: Record<string, unknown>,
|
|
82
|
+
): Record<string, unknown> {
|
|
83
|
+
const merged: Record<string, unknown> = { ...defaults };
|
|
84
|
+
|
|
85
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
86
|
+
if (DANGEROUS_KEYS.has(key) || value == null) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
merged[key] = value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
|
|
68
96
|
function toArray<T>(target: Array<T> | T): Array<T> {
|
|
69
97
|
return Array.isArray(target) ? target : [target];
|
|
70
98
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ColorMode, LogLevel } from '../internal/Logger.js';
|
|
2
|
+
import type { StdioOptions } from './StdOptions.js';
|
|
2
3
|
|
|
3
4
|
export interface CommandContext {
|
|
4
5
|
/**
|
|
@@ -37,12 +38,10 @@ export interface CommandContext {
|
|
|
37
38
|
readonly logLevel: LogLevel;
|
|
38
39
|
|
|
39
40
|
/**
|
|
40
|
-
*
|
|
41
|
+
* Standard I/O configuration. Index `1` is used to write standard output (resolved command)
|
|
42
|
+
* and index `2` to write status messages (stderr).
|
|
43
|
+
*
|
|
44
|
+
* @default 'inherit'
|
|
41
45
|
*/
|
|
42
|
-
readonly
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Stream used to write standard log messages.
|
|
46
|
-
*/
|
|
47
|
-
readonly stdout: NodeJS.WritableStream;
|
|
46
|
+
readonly stdio: StdioOptions;
|
|
48
47
|
}
|
|
@@ -1,18 +1,37 @@
|
|
|
1
1
|
export interface ResolvedConfig {
|
|
2
|
-
readonly scripts: Record<string,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
readonly scripts: Record<string, ResolvedConfig.Script>;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export namespace ResolvedConfig {
|
|
6
|
+
/**
|
|
7
|
+
* Direct executable invocation. Extra CLI arguments are appended to {@link args}.
|
|
8
|
+
*/
|
|
9
|
+
export interface RunnerScript extends Origin {
|
|
10
|
+
readonly args: ReadonlyArray<string>;
|
|
11
|
+
readonly run?: undefined;
|
|
12
|
+
readonly runner: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type Script = RunnerScript | ShellScript;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Shell command. Extra CLI arguments are appended to the command string.
|
|
19
|
+
*/
|
|
20
|
+
export interface ShellScript extends Origin {
|
|
21
|
+
readonly args?: undefined;
|
|
22
|
+
readonly run: string;
|
|
23
|
+
readonly runner?: undefined;
|
|
24
|
+
}
|
|
7
25
|
|
|
26
|
+
interface Origin {
|
|
8
27
|
/**
|
|
9
|
-
*
|
|
28
|
+
* Directory of the configuration file that defined this script.
|
|
10
29
|
*/
|
|
11
30
|
readonly configDir: string | undefined;
|
|
12
31
|
|
|
13
32
|
/**
|
|
14
|
-
*
|
|
33
|
+
* File path of the configuration file that defined this script.
|
|
15
34
|
*/
|
|
16
35
|
readonly configFile: string | undefined;
|
|
17
|
-
}
|
|
36
|
+
}
|
|
18
37
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type { StdioOptions } from 'node:child_process';
|
package/src/type/UserConfig.ts
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
1
|
import type { InputConfig } from 'c12';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Run an executable directly, in the same way a lefthook script uses `runner` and `args`.
|
|
5
|
+
*
|
|
6
|
+
* `runner` is the program, such as `node` or `bash`. `args` are its arguments.
|
|
7
|
+
* Arguments passed to the managed-script CLI are appended after `args`.
|
|
8
|
+
* The process is spawned directly, so the shell does not parse the arguments.
|
|
9
|
+
*/
|
|
10
|
+
export interface RunnerScript {
|
|
11
|
+
/**
|
|
12
|
+
* Arguments passed to {@link RunnerScript.runner}.
|
|
13
|
+
*/
|
|
14
|
+
readonly args?: ReadonlyArray<string> | undefined;
|
|
15
|
+
|
|
16
|
+
readonly run?: undefined;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Executable name or path. A multi-word command belongs in {@link RunnerScript.args}:
|
|
20
|
+
* `{ runner: "go", args: ["run", "main.go"] }`.
|
|
21
|
+
*/
|
|
22
|
+
readonly runner: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A shell command string (shorthand for `{ run }`), a {@link ShellScript} or a direct {@link RunnerScript}.
|
|
27
|
+
*/
|
|
28
|
+
export type ScriptDefinition = RunnerScript | ShellScript | string;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Run a shell command, in the same way as a lefthook `run`.
|
|
32
|
+
* Arguments passed to the managed-script CLI are appended (shell-quoted).
|
|
33
|
+
*/
|
|
34
|
+
export interface ShellScript {
|
|
35
|
+
readonly args?: undefined;
|
|
36
|
+
readonly run: string;
|
|
37
|
+
readonly runner?: undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
3
40
|
export interface UserConfig extends InputConfig<{
|
|
4
|
-
readonly scripts?: Record<string,
|
|
41
|
+
readonly scripts?: Record<string, ScriptDefinition> | undefined;
|
|
5
42
|
}> {}
|