@w5s/managed-script 1.0.0-alpha.2 → 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/LICENSE +21 -0
- 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-Xl2iA7UM.js +91 -0
- package/dist/defaultContext-Xl2iA7UM.js.map +1 -0
- package/dist/index.d.ts +27 -54
- package/dist/index.js +27 -12
- 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 +67 -26
- package/dist/zx.js.map +1 -1
- package/package.json +4 -2
- package/src/ManagedScript/defaultContext.ts +2 -4
- package/src/ManagedScript/execute.ts +48 -25
- 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 +25 -7
- 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-DIacNHCc.js +0 -149
- package/dist/ManagedScript-DIacNHCc.js.map +0 -1
- package/dist/defaultContext-D_QWP9aF.js +0 -98
- package/dist/defaultContext-D_QWP9aF.js.map +0 -1
- package/dist/type-DQiyX1q_.d.ts +0 -53
- package/src/zx/defaultZXOptions.ts +0 -37
package/dist/zx.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zx.js","names":["
|
|
1
|
+
{"version":3,"file":"zx.js","names":["zxLog","zxFn"],"sources":["../src/zx/ZXOptions.ts","../src/zx/zx.ts","../src/zx/defaults.ts","../src/internal/lazy.ts","../src/zx/isCI.ts","../src/zx.ts"],"sourcesContent":["import { stripVTControlCharacters } from 'node:util';\nimport { chalk, log as zxLog } from 'zx';\n\nimport type { LogLevel } from '../internal/Logger.js';\nimport type { ZXDefaultOptions } from '../zx.js';\n\nimport { Stdio } from '../internal/Stdio.js';\nimport { defaultContext } from '../ManagedScript/defaultContext.js';\n\nexport type { Options as ZXDefaultOptions } from 'zx';\n\nexport interface ZXOptions extends ZXDefaultOptions {\n /**\n *\n */\n logLevel?: LogLevel | undefined;\n}\n\n/**\n * @namespace\n */\nexport const ZXOptions = {\n create(options: Partial<ZXOptions>): Partial<ZXOptions> {\n const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stdio: optionsStdio, ...optionsRest } = options;\n const env = optionsEnv == null ? process.env : { ...process.env, ...optionsEnv };\n const context = defaultContext({\n env,\n ...(optionsCwd == null ? {} : { cwd: optionsCwd }),\n ...(optionsLogLevel == null ? {} : { logLevel: optionsLogLevel }),\n ...(optionsStdio == null ? {} : { stdio: optionsStdio }),\n });\n const { stderr, stdout } = Stdio.resolve(context.stdio);\n\n return {\n cwd: context.cwd,\n env: context.env,\n log: (entry) => {\n const target = (entry.kind === 'cmd' || entry.kind === 'stdout' ? stdout : stderr) as NodeJS.WriteStream;\n const colorEnabled = context.color === 'always' || (context.color === 'auto' && autoColor(context.env, target));\n const previousOutput = zxLog.output;\n const previousLevel = chalk.level;\n zxLog.output = colorEnabled\n ? target\n : ({ write: (chunk: string) => target.write(stripVTControlCharacters(chunk)) } as unknown as NodeJS.WriteStream);\n if (colorEnabled && !chalk.level) {\n chalk.level = 1;\n } else if (!colorEnabled) {\n chalk.level = 0;\n }\n try {\n zxLog(entry.kind === 'cmd' && (context.logLevel === 'info' || context.logLevel === 'debug') ? { ...entry, verbose: true } : entry);\n } finally {\n // eslint-disable-next-line ts/no-non-null-assertion\n zxLog.output = previousOutput!;\n chalk.level = previousLevel;\n }\n },\n preferLocal: true,\n quiet: context.logLevel === 'silent',\n stdio: 'inherit',\n verbose: context.logLevel === 'debug',\n ...optionsRest,\n };\n },\n};\n\nfunction autoColor(env: NodeJS.ProcessEnv, stream: NodeJS.WriteStream): boolean {\n if (env['NO_COLOR'] != null && env['NO_COLOR'] !== '') {\n return false;\n }\n const force = env['FORCE_COLOR'];\n return force == null ? stream.isTTY === true : force !== '0' && force !== 'false';\n}\n","import { $ as zxFn } from 'zx';\n\nimport type { CommandContext, StdioOptions } from '../type.js';\nimport type { ZXShell } from './ZXShell.js';\n\nimport { ZXOptions } from './ZXOptions.js';\n\nexport interface CreateZXOptions {\n /**\n * Working directory for spawned commands. Defaults to `MANAGED_SCRIPT_CWD`, then `process.cwd()`.\n */\n readonly cwd?: string | undefined;\n\n /**\n * Environment variables passed to spawned commands. Merged over `process.env`.\n */\n readonly env?: NodeJS.ProcessEnv | undefined;\n\n /**\n * Log level used to derive zx `verbose` / `quiet` and command instrumentation.\n * Defaults to `MANAGED_SCRIPT_LOGLEVEL`, then `info`.\n */\n readonly logLevel?: CommandContext['logLevel'] | undefined;\n\n /**\n * Standard I/O used to write instrumented command logs (index `1` for command lines and output, index `2` for the rest).\n */\n readonly stdio?: StdioOptions | undefined;\n}\n\n/**\n * Creates a zx `$` preset configured from managed-script context and environment variables.\n *\n * @param options\n */\nexport function zx(options: CreateZXOptions = {}): ZXShell {\n const env = options.env == null ? process.env : { ...process.env, ...options.env };\n\n return zxFn(ZXOptions.create({\n env,\n ...(options.cwd == null ? {} : { cwd: options.cwd }),\n ...(options.logLevel == null ? {} : { logLevel: options.logLevel }),\n ...(options.stdio == null ? {} : { stdio: options.stdio }),\n }));\n}\n","import { ZXOptions } from './ZXOptions.js';\n\n/**\n * Default ZX options for the managed script environment.\n */\nexport const defaults = ZXOptions.create({});\n","export function lazy<T>(fn: () => T): () => T {\n let cached: T | undefined;\n return () => {\n cached ??= fn();\n return cached;\n };\n}\n","import { bool, cleanEnv } from 'envalid';\n\nimport { lazy } from '../internal/lazy.js';\n\nconst envSchema = {\n CI: bool({ default: false }),\n CONTINUOUS_INTEGRATION: bool({ default: false }),\n};\n\nconst getEnvClean = lazy(() =>\n cleanEnv(process.env, envSchema, {\n reporter: null,\n }),\n);\n\n/**\n * Determines if the current environment is a CI (Continuous Integration) environment.\n * Checks the `CI` and `CONTINUOUS_INTEGRATION` environment variables to determine if the current environment is a CI environment.\n *\n * @example\n * ```ts\n * const ci = isCI();\n * ```\n * @returns `true` if the current environment is a CI environment, otherwise `false`\n */\nexport const isCI = lazy(() => getEnvClean().CI || getEnvClean().CONTINUOUS_INTEGRATION);\n","import type { ZXShell } from './zx/ZXShell.js';\n\nimport { zx } from './zx/zx.js';\n\nexport * from './zx/defaults.js';\nexport * from './zx/isCI.js';\nexport * from './zx/zx.js';\nexport type * from './zx/ZXOptions.js';\nexport type * from './zx/ZXShell.js';\n\n/**\n * Default `$` preset for scripts launched by managed-script.\n * Reads `MANAGED_SCRIPT_*` from the process environment at import time.\n *\n * @example\n * ```ts\n * import { $ } from '@w5s/managed-script/zx';\n * await $`echo Hello, world!`;\n * ```\n */\nexport const $: ZXShell = zx();\n"],"mappings":";;;;;;;;AAqBA,MAAa,YAAY,EACvB,OAAO,SAAiD;CACtD,MAAM,EAAE,KAAK,YAAY,KAAK,YAAY,UAAU,iBAAiB,OAAO,cAAc,GAAG,gBAAgB;CAC7G,MAAM,MAAM,cAAc,OAAO,QAAQ,MAAM;EAAE,GAAG,QAAQ;EAAK,GAAG;CAAW;CAC/E,MAAM,UAAU,eAAe;EAC7B;EACA,GAAI,cAAc,OAAO,CAAC,IAAI,EAAE,KAAK,WAAW;EAChD,GAAI,mBAAmB,OAAO,CAAC,IAAI,EAAE,UAAU,gBAAgB;EAC/D,GAAI,gBAAgB,OAAO,CAAC,IAAI,EAAE,OAAO,aAAa;CACxD,CAAC;CACD,MAAM,EAAE,QAAQ,WAAW,MAAM,QAAQ,QAAQ,KAAK;CAEtD,OAAO;EACL,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,MAAM,UAAU;GACd,MAAM,SAAU,MAAM,SAAS,SAAS,MAAM,SAAS,WAAW,SAAS;GAC3E,MAAM,eAAe,QAAQ,UAAU,YAAa,QAAQ,UAAU,UAAU,UAAU,QAAQ,KAAK,MAAM;GAC7G,MAAM,iBAAiBA,IAAM;GAC7B,MAAM,gBAAgB,MAAM;GAC5BA,IAAM,SAAS,eACX,SACC,EAAE,QAAQ,UAAkB,OAAO,MAAM,yBAAyB,KAAK,CAAC,EAAE;GAC/E,IAAI,gBAAgB,CAAC,MAAM,OACzB,MAAM,QAAQ;QACT,IAAI,CAAC,cACV,MAAM,QAAQ;GAEhB,IAAI;IACFA,IAAM,MAAM,SAAS,UAAU,QAAQ,aAAa,UAAU,QAAQ,aAAa,WAAW;KAAE,GAAG;KAAO,SAAS;IAAK,IAAI,KAAK;GACnI,UAAU;IAERA,IAAM,SAAS;IACf,MAAM,QAAQ;GAChB;EACF;EACA,aAAa;EACb,OAAO,QAAQ,aAAa;EAC5B,OAAO;EACP,SAAS,QAAQ,aAAa;EAC9B,GAAG;CACL;AACF,EACF;AAEA,SAAS,UAAU,KAAwB,QAAqC;CAC9E,IAAI,IAAI,eAAe,QAAQ,IAAI,gBAAgB,IACjD,OAAO;CAET,MAAM,QAAQ,IAAI;CAClB,OAAO,SAAS,OAAO,OAAO,UAAU,OAAO,UAAU,OAAO,UAAU;AAC5E;;;;;;;ACrCA,SAAgB,GAAG,UAA2B,CAAC,GAAY;CACzD,MAAM,MAAM,QAAQ,OAAO,OAAO,QAAQ,MAAM;EAAE,GAAG,QAAQ;EAAK,GAAG,QAAQ;CAAI;CAEjF,OAAOC,IAAK,UAAU,OAAO;EAC3B;EACA,GAAI,QAAQ,OAAO,OAAO,CAAC,IAAI,EAAE,KAAK,QAAQ,IAAI;EAClD,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EACjE,GAAI,QAAQ,SAAS,OAAO,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;CAC1D,CAAC,CAAC;AACJ;;;;;ACvCA,MAAa,WAAW,UAAU,OAAO,CAAC,CAAC;;ACL3C,SAAgB,KAAQ,IAAsB;CAC5C,IAAI;CACJ,aAAa;EACX,WAAW,GAAG;EACd,OAAO;CACT;AACF;;ACFA,MAAM,YAAY;CAChB,IAAI,KAAK,EAAE,SAAS,MAAM,CAAC;CAC3B,wBAAwB,KAAK,EAAE,SAAS,MAAM,CAAC;AACjD;AAEA,MAAM,cAAc,WAClB,SAAS,QAAQ,KAAK,WAAW,EAC/B,UAAU,KACZ,CAAC,CACH;;;;;;;;;;;AAYA,MAAa,OAAO,WAAW,YAAY,CAAC,CAAC,MAAM,YAAY,CAAC,CAAC,sBAAsB;;;;;;;;;;;;ACLvF,MAAa,IAAa,GAAG"}
|
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": {
|
|
@@ -49,5 +50,6 @@
|
|
|
49
50
|
},
|
|
50
51
|
"publishConfig": {
|
|
51
52
|
"access": "public"
|
|
52
|
-
}
|
|
53
|
+
},
|
|
54
|
+
"gitHead": "8c839f967fbc4477af3e767c4ecfa2d8a693eda0"
|
|
53
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,9 +1,15 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
1
3
|
import type { ManagedScriptCommand } from '../type.js';
|
|
4
|
+
import type { ResolvedConfig } from '../type/ResolvedConfig.js';
|
|
2
5
|
|
|
3
6
|
import { ConfigLoader } from '../internal/ConfigLoader.js';
|
|
4
7
|
import { Executor } from '../internal/Executor.js';
|
|
5
8
|
import { Logger } from '../internal/Logger.js';
|
|
9
|
+
import { PackageScriptOverride } from '../internal/PackageScriptOverride.js';
|
|
10
|
+
import { ScriptInvocation } from '../internal/ScriptInvocation.js';
|
|
6
11
|
import { ScriptNameResolver } from '../internal/ScriptNameResolver.js';
|
|
12
|
+
import { Stdio } from '../internal/Stdio.js';
|
|
7
13
|
import { ManagedScriptEnv } from '../ManagedScriptEnv.js';
|
|
8
14
|
import { defaultContext } from './defaultContext.js';
|
|
9
15
|
import { resolveScripts } from './resolveScripts.js';
|
|
@@ -11,58 +17,75 @@ import { resolveScripts } from './resolveScripts.js';
|
|
|
11
17
|
const handlers = {
|
|
12
18
|
RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {
|
|
13
19
|
const {
|
|
14
|
-
context: { color, cwd, dryRun, env, logLevel,
|
|
20
|
+
context: { color, cwd, dryRun, env, logLevel, stdio },
|
|
15
21
|
parameters: { scriptArgs = [], scriptName },
|
|
16
22
|
} = command;
|
|
17
|
-
const
|
|
23
|
+
const { stdout } = Stdio.resolve(stdio);
|
|
24
|
+
const logger = Logger.create({ color, level: logLevel, stdio });
|
|
18
25
|
const loaded = await ConfigLoader.load({ cwd });
|
|
19
|
-
logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}
|
|
26
|
+
logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}`);
|
|
20
27
|
const resolved = resolveScripts(loaded);
|
|
21
28
|
const { scripts } = resolved;
|
|
22
29
|
|
|
23
30
|
const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });
|
|
24
31
|
if (name == null) {
|
|
25
32
|
throw new Error(
|
|
26
|
-
'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).',
|
|
27
34
|
);
|
|
28
35
|
}
|
|
29
36
|
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
+
}
|
|
39
51
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
+
}
|
|
44
70
|
|
|
71
|
+
stdout.write(`$ ${ScriptInvocation.format(invocation)}\n`);
|
|
45
72
|
if (dryRun) {
|
|
46
|
-
stdout.write(`${commandLine}\n`);
|
|
47
73
|
return 0;
|
|
48
74
|
}
|
|
49
75
|
|
|
50
|
-
logger.info(`Running script "${name}": ${commandLine}`);
|
|
51
|
-
|
|
52
76
|
// Prepare the environment variables for the script execution.
|
|
53
77
|
const scriptEnv = {
|
|
54
78
|
[ManagedScriptEnv.Color]: color,
|
|
55
|
-
[ManagedScriptEnv.ConfigDir]:
|
|
56
|
-
[ManagedScriptEnv.ConfigFile]:
|
|
79
|
+
[ManagedScriptEnv.ConfigDir]: origin.configDir,
|
|
80
|
+
[ManagedScriptEnv.ConfigFile]: origin.configFile,
|
|
57
81
|
[ManagedScriptEnv.Cwd]: cwd,
|
|
58
82
|
[ManagedScriptEnv.LogLevel]: logLevel,
|
|
59
83
|
[ManagedScriptEnv.Name]: name,
|
|
60
84
|
};
|
|
61
|
-
|
|
62
|
-
const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });
|
|
85
|
+
const exitCode = await Executor.run({ ...invocation.target, cwd, env: scriptEnv });
|
|
63
86
|
|
|
64
87
|
if (exitCode !== 0) {
|
|
65
|
-
throw new Error(`Script "${
|
|
88
|
+
throw new Error(`Script "${scriptLabel}" exited with code ${exitCode}.`);
|
|
66
89
|
}
|
|
67
90
|
|
|
68
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,3 +1,8 @@
|
|
|
1
|
+
import type { StdioOptions } from '../type.js';
|
|
2
|
+
|
|
3
|
+
import { meta } from '../meta.js';
|
|
4
|
+
import { Stdio } from './Stdio.js';
|
|
5
|
+
|
|
1
6
|
export type ColorMode = 'always' | 'auto' | 'never';
|
|
2
7
|
export type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';
|
|
3
8
|
|
|
@@ -15,8 +20,16 @@ const logLevelRank: Record<LogLevel, number> = {
|
|
|
15
20
|
export interface CreateLoggerOptions {
|
|
16
21
|
readonly color?: ColorMode;
|
|
17
22
|
readonly level: LogLevel;
|
|
18
|
-
|
|
19
|
-
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Program name used as message prefix (default: binary name)
|
|
26
|
+
*/
|
|
27
|
+
readonly name?: string;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Standard I/O, messages are written to index `2` (stderr)
|
|
31
|
+
*/
|
|
32
|
+
readonly stdio: StdioOptions;
|
|
20
33
|
}
|
|
21
34
|
|
|
22
35
|
export interface Logger {
|
|
@@ -30,22 +43,27 @@ export interface Logger {
|
|
|
30
43
|
* Creates a logger writing to `stream`, filtering out messages above the configured `level`.
|
|
31
44
|
*/
|
|
32
45
|
export const Logger = {
|
|
33
|
-
create({ color = 'auto', level,
|
|
46
|
+
create({ color = 'auto', level, name = meta.binaryName, stdio }: CreateLoggerOptions): Logger {
|
|
47
|
+
const { stderr } = Stdio.resolve(stdio);
|
|
34
48
|
const write = (messageLevel: LogLevel, message: string) => {
|
|
35
49
|
if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {
|
|
36
50
|
return;
|
|
37
51
|
}
|
|
38
|
-
//
|
|
39
|
-
const outputStream =
|
|
52
|
+
// Keep stdout free for command output that may be consumed by another process.
|
|
53
|
+
const outputStream = stderr;
|
|
40
54
|
const shouldColor = color === 'always' || (color === 'auto' && 'isTTY' in outputStream && outputStream.isTTY === true);
|
|
41
55
|
const colorCode = {
|
|
42
56
|
debug: '\u{1B}[36m',
|
|
43
57
|
error: '\u{1B}[31m',
|
|
44
|
-
info: '
|
|
58
|
+
info: '',
|
|
45
59
|
silent: '',
|
|
46
60
|
warn: '\u{1B}[33m',
|
|
47
61
|
}[messageLevel];
|
|
48
|
-
|
|
62
|
+
// Unix convention: `program: [level: ]message`, info has no level label
|
|
63
|
+
const label = { debug: 'debug', error: 'error', info: '', silent: '', warn: 'warning' }[messageLevel];
|
|
64
|
+
const coloredLabel = shouldColor && colorCode !== '' ? `${colorCode}${label}\u{1B}[0m` : label;
|
|
65
|
+
const prefix = label === '' ? `${name}: ` : `${name}: ${coloredLabel}: `;
|
|
66
|
+
outputStream.write(`${prefix}${message}\n`);
|
|
49
67
|
};
|
|
50
68
|
|
|
51
69
|
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
|
}
|