@w5s/managed-script 1.0.0-alpha.2 → 1.0.0-alpha.4

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Julien Polo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,15 +1,16 @@
1
- import { n as ManagedScriptEnv, r as Logger, t as defaultContext } from "./defaultContext-D_QWP9aF.js";
1
+ import { n as ManagedScriptEnv, t as defaultContext } from "./defaultContext-BthxLDX3.js";
2
2
  import { loadConfig } from "c12";
3
+ import path from "node:path";
3
4
  import { spawn } from "node:child_process";
4
- import path from "node:path/win32";
5
+ import path$1 from "node:path/win32";
5
6
  //#region src/meta.ts
6
7
  const meta = Object.freeze({
7
8
  binaryLabel: "W5S Managed Script",
8
9
  binaryName: "managed-script",
9
- binaryVersion: "1.0.0-alpha.2",
10
+ binaryVersion: "1.0.0-alpha.4",
10
11
  buildNumber: 1,
11
12
  name: "@w5s/managed-script",
12
- version: "1.0.0-alpha.2"
13
+ version: "1.0.0-alpha.4"
13
14
  });
14
15
  //#endregion
15
16
  //#region src/internal/ConfigLoader.ts
@@ -48,6 +49,51 @@ const Executor = { async run(command, options = {}) {
48
49
  });
49
50
  } };
50
51
  //#endregion
52
+ //#region src/internal/Logger.ts
53
+ /**
54
+ * Rank order used to compare log levels, higher means more verbose.
55
+ */
56
+ const logLevelRank = {
57
+ debug: 4,
58
+ error: 1,
59
+ info: 3,
60
+ silent: 0,
61
+ warn: 2
62
+ };
63
+ /**
64
+ * Creates a logger writing to `stream`, filtering out messages above the configured `level`.
65
+ */
66
+ const Logger = { create({ color = "auto", level, name = meta.binaryName, stderr }) {
67
+ const write = (messageLevel, message) => {
68
+ if (!(logLevelRank[messageLevel] <= logLevelRank[level])) return;
69
+ const outputStream = stderr;
70
+ const shouldColor = color === "always" || color === "auto" && "isTTY" in outputStream && outputStream.isTTY === true;
71
+ const colorCode = {
72
+ debug: "\x1B[36m",
73
+ error: "\x1B[31m",
74
+ info: "",
75
+ silent: "",
76
+ warn: "\x1B[33m"
77
+ }[messageLevel];
78
+ const label = {
79
+ debug: "debug",
80
+ error: "error",
81
+ info: "",
82
+ silent: "",
83
+ warn: "warning"
84
+ }[messageLevel];
85
+ const coloredLabel = shouldColor && colorCode !== "" ? `${colorCode}${label}\u{1B}[0m` : label;
86
+ const prefix = label === "" ? `${name}: ` : `${name}: ${coloredLabel}: `;
87
+ outputStream.write(`${prefix}${message}\n`);
88
+ };
89
+ return {
90
+ debug: (message) => write("debug", message),
91
+ error: (message) => write("error", message),
92
+ info: (message) => write("info", message),
93
+ warn: (message) => write("warn", message)
94
+ };
95
+ } };
96
+ //#endregion
51
97
  //#region src/internal/ScriptNameResolver.ts
52
98
  /**
53
99
  * Resolves the script name to run.
@@ -64,7 +110,7 @@ function resolveScripts(loaded) {
64
110
  const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];
65
111
  for (const layer of layers) for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {
66
112
  const configFile = layer.configFile ?? loaded.configFile;
67
- const configDir = configFile == null ? void 0 : path.dirname(configFile);
113
+ const configDir = configFile == null ? void 0 : path$1.dirname(configFile);
68
114
  scripts[name] ??= {
69
115
  command,
70
116
  configDir,
@@ -84,7 +130,7 @@ const handlers = { RunScript: async (command) => {
84
130
  stdout
85
131
  });
86
132
  const loaded = await ConfigLoader.load({ cwd });
87
- logger.debug(`Resolved configuration from ${loaded.configFile ?? "defaults (no config file found)"}.`);
133
+ logger.debug(`Resolved configuration from ${loaded.configFile ?? "defaults (no config file found)"}`);
88
134
  const { scripts } = resolveScripts(loaded);
89
135
  const name = ScriptNameResolver.resolve({
90
136
  env,
@@ -97,11 +143,9 @@ const handlers = { RunScript: async (command) => {
97
143
  throw new Error(`No script named "${name}" found in the configuration.${available.length > 0 ? ` Available scripts: ${available.join(", ")}.` : " No scripts are configured."}`);
98
144
  }
99
145
  const commandLine = [script.command, ...scriptArgs.map((argument) => `'${argument.replaceAll("'", String.raw`'\''`)}'`)].join(" ");
100
- if (dryRun) {
101
- stdout.write(`${commandLine}\n`);
102
- return 0;
103
- }
104
- logger.info(`Running script "${name}": ${commandLine}`);
146
+ logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile)}`);
147
+ stdout.write(`$ ${commandLine}\n`);
148
+ if (dryRun) return 0;
105
149
  const scriptEnv = {
106
150
  [ManagedScriptEnv.Color]: color,
107
151
  [ManagedScriptEnv.ConfigDir]: script.configDir,
@@ -146,4 +190,4 @@ const ManagedScript = Object.freeze({ runScript });
146
190
  //#endregion
147
191
  export { meta as n, ManagedScript as t };
148
192
 
149
- //# sourceMappingURL=ManagedScript-DIacNHCc.js.map
193
+ //# sourceMappingURL=ManagedScript-CLp9a43o.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ManagedScript-CLp9a43o.js","names":["path"],"sources":["../src/meta.ts","../src/internal/ConfigLoader.ts","../src/internal/Executor.ts","../src/internal/Logger.ts","../src/internal/ScriptNameResolver.ts","../src/ManagedScript/resolveScripts.ts","../src/ManagedScript/execute.ts","../src/ManagedScript/runScript.ts","../src/ManagedScript.ts"],"sourcesContent":["export const meta = Object.freeze({\n binaryLabel: 'W5S Managed Script',\n binaryName: 'managed-script',\n // @ts-ignore - these variables are injected at build time\n binaryVersion: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n // @ts-ignore - these variables are injected at build time\n buildNumber: 1, // (typeof __PACKAGE_BUILD_NUMBER__ === 'undefined' ? 0 : __PACKAGE_BUILD_NUMBER__) as number,\n // @ts-ignore - these variables are injected at build time\n name: (typeof __PACKAGE_NAME__ === 'undefined' ? '' : __PACKAGE_NAME__) as string,\n // @ts-ignore - these variables are injected at build time\n version: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n});\n","import type { ConfigLayer } from 'c12';\n\nimport { loadConfig } from 'c12';\n\nimport type { UserConfig } from '../type/UserConfig.js';\n\nimport { meta } from '../meta.js';\n\nexport interface ConfigLoaderOptions {\n readonly cwd: string;\n}\n\nexport interface ConfigLoaderResult {\n readonly config: UserConfig;\n readonly configFile: string | undefined;\n readonly layers: Array<ConfigLayer<UserConfig>>;\n}\n\nexport const ConfigLoader = {\n async load(options: ConfigLoaderOptions): Promise<ConfigLoaderResult> {\n const result = await loadConfig<UserConfig>({\n cwd: options.cwd,\n name: meta.binaryName,\n packageJson: [meta.binaryName],\n });\n\n return {\n config: result.config,\n configFile: result.configFile ?? undefined,\n layers: result.layers ?? [],\n };\n },\n};\n","import { spawn } from 'node:child_process';\n\nexport interface ExecutorRunOptions {\n readonly cwd?: string | undefined;\n readonly env?: NodeJS.ProcessEnv | undefined;\n}\n\n/**\n * Executes a command via the system shell, inheriting stdio and forwarding its exit code.\n */\nexport const Executor = {\n async run(command: string, options: ExecutorRunOptions = {}): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, {\n cwd: options.cwd,\n env: options.env == null ? process.env : { ...process.env, ...options.env },\n shell: true,\n stdio: 'inherit',\n });\n\n child.on('error', reject);\n child.on('close', (code, signal) => {\n resolve(code ?? (signal == null ? 1 : 128));\n });\n });\n },\n};\n","import { meta } from '../meta.js';\n\nexport type ColorMode = 'always' | 'auto' | 'never';\nexport type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';\n\n/**\n * Rank order used to compare log levels, higher means more verbose.\n */\nconst logLevelRank: Record<LogLevel, number> = {\n debug: 4,\n error: 1,\n info: 3,\n silent: 0,\n warn: 2,\n};\n\nexport interface CreateLoggerOptions {\n readonly color?: ColorMode;\n readonly level: LogLevel;\n\n /**\n * Program name used as message prefix (default: binary name)\n */\n readonly name?: string;\n readonly stderr: NodeJS.WritableStream;\n readonly stdout?: NodeJS.WritableStream | undefined;\n}\n\nexport interface Logger {\n debug(message: string): void;\n error(message: string): void;\n info(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Creates a logger writing to `stream`, filtering out messages above the configured `level`.\n */\nexport const Logger = {\n create({ color = 'auto', level, name = meta.binaryName, stderr }: CreateLoggerOptions): Logger {\n const write = (messageLevel: LogLevel, message: string) => {\n if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {\n return;\n }\n // Keep stdout free for command output that may be consumed by another process.\n const outputStream = stderr;\n const shouldColor = color === 'always' || (color === 'auto' && 'isTTY' in outputStream && outputStream.isTTY === true);\n const colorCode = {\n debug: '\\u{1B}[36m',\n error: '\\u{1B}[31m',\n info: '',\n silent: '',\n warn: '\\u{1B}[33m',\n }[messageLevel];\n // Unix convention: `program: [level: ]message`, info has no level label\n const label = { debug: 'debug', error: 'error', info: '', silent: '', warn: 'warning' }[messageLevel];\n const coloredLabel = shouldColor && colorCode !== '' ? `${colorCode}${label}\\u{1B}[0m` : label;\n const prefix = label === '' ? `${name}: ` : `${name}: ${coloredLabel}: `;\n outputStream.write(`${prefix}${message}\\n`);\n };\n\n return {\n debug: (message) => write('debug', message),\n error: (message) => write('error', message),\n info: (message) => write('info', message),\n warn: (message) => write('warn', message),\n };\n },\n};\n","import { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport interface ScriptNameResolverOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly scriptName: string | undefined;\n}\n\n/**\n * Resolves the script name to run.\n *\n * Priority: first positional CLI argument > `MANAGED_SCRIPT_NAME` env var > `npm_lifecycle_event` env var.\n */\nexport const ScriptNameResolver = {\n resolve({ env, scriptName }: ScriptNameResolverOptions): string | undefined {\n return scriptName ?? env[ManagedScriptEnv.Name] ?? env['npm_lifecycle_event'];\n },\n};\n","import path from 'node:path/win32';\n\nimport type { ConfigLoaderResult } from '../internal/ConfigLoader.js';\nimport type { ResolvedConfig } from '../type/ResolvedConfig.js';\n\nexport function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {\n const scripts: ResolvedConfig['scripts'] = {};\n const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];\n\n for (const layer of layers) {\n for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {\n const configFile = layer.configFile ?? loaded.configFile;\n const configDir = configFile == null ? undefined : path.dirname(configFile);\n scripts[name] ??= {\n command,\n configDir,\n configFile,\n };\n }\n }\n\n return {\n scripts,\n };\n}\n","import path from 'node:path';\n\nimport type { ManagedScriptCommand } from '../type.js';\n\nimport { ConfigLoader } from '../internal/ConfigLoader.js';\nimport { Executor } from '../internal/Executor.js';\nimport { Logger } from '../internal/Logger.js';\nimport { ScriptNameResolver } from '../internal/ScriptNameResolver.js';\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\nimport { defaultContext } from './defaultContext.js';\nimport { resolveScripts } from './resolveScripts.js';\n\nconst handlers = {\n RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {\n const {\n context: { color, cwd, dryRun, env, logLevel, stderr, stdout },\n parameters: { scriptArgs = [], scriptName },\n } = command;\n const logger = Logger.create({ color, level: logLevel, stderr, stdout });\n const loaded = await ConfigLoader.load({ cwd });\n logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}`);\n const resolved = resolveScripts(loaded);\n const { scripts } = resolved;\n\n const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });\n if (name == null) {\n throw new Error(\n 'Unable to resolve the script name. Pass it as the first argument, set the MANAGED_SCRIPT_NAME environment variable, or run through an npm/pnpm script (npm_lifecycle_event).',\n );\n }\n\n const script = scripts[name];\n if (script == null) {\n const available = Object.keys(scripts);\n throw new Error(\n `No script named \"${name}\" found in the configuration.${\n available.length > 0 ? ` Available scripts: ${available.join(', ')}.` : ' No scripts are configured.'\n }`,\n );\n }\n\n const commandLine = [\n script.command,\n ...scriptArgs.map((argument) => `'${argument.replaceAll(\"'\", String.raw`'\\''`)}'`),\n ].join(' ');\n\n // relative to cwd\n // eslint-disable-next-line ts/no-non-null-assertion\n logger.debug(`Script found in configuration: ${path.relative(cwd, script.configFile!)}`);\n stdout.write(`$ ${commandLine}\\n`);\n if (dryRun) {\n return 0;\n }\n\n // Prepare the environment variables for the script execution.\n const scriptEnv = {\n [ManagedScriptEnv.Color]: color,\n [ManagedScriptEnv.ConfigDir]: script.configDir,\n [ManagedScriptEnv.ConfigFile]: script.configFile,\n [ManagedScriptEnv.Cwd]: cwd,\n [ManagedScriptEnv.LogLevel]: logLevel,\n [ManagedScriptEnv.Name]: name,\n };\n const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });\n\n if (exitCode !== 0) {\n throw new Error(`Script \"${name}\" exited with code ${exitCode}.`);\n }\n\n return exitCode;\n },\n} satisfies {\n [K in ManagedScriptCommand['_']]: (command: Extract<ManagedScriptCommand, { _: K }>) => Promise<any>;\n};\n\nexport type ExecuteCommand<T extends ManagedScriptCommand> = Omit<T, 'context'> & {\n /**\n * Context is optional\n */\n context?: Partial<ManagedScriptCommand['context']>;\n};\n\n/**\n * Extract command parameter from execute handler\n */\nexport type ExecuteCommandParameters<T extends ManagedScriptCommand> = Omit<Parameters<typeof execute<T>>[0], '_'>;\n\n/**\n * Dispatch the command to the appropriate handler based on its type.\n *\n * @param command\n */\nexport async function execute<T extends ManagedScriptCommand>(command: ExecuteCommand<T>): Promise<Awaited<ReturnType<typeof handlers[T['_']]>>> {\n const context = defaultContext(command.context);\n // @ts-ignore we know this works\n return handlers[command._]({\n ...command,\n context,\n });\n}\n","import { ManagedScriptCommand } from '../type.js';\nimport { execute, type ExecuteCommandParameters } from './execute.js';\n\nexport async function runScript(options: ExecuteCommandParameters<ManagedScriptCommand.RunScript>) {\n return execute({\n _: 'RunScript',\n ...options,\n });\n}\n","import { runScript } from './ManagedScript/runScript.js';\n\n/**\n * @namespace\n */\nexport const ManagedScript = Object.freeze({\n runScript,\n});\n"],"mappings":";;;;;;AAAA,MAAa,OAAO,OAAO,OAAO;CAChC,aAAa;CACb,YAAY;CAEZ,eAAA;CAEA,aAAa;CAEb,MAAA;CAEA,SAAA;AACF,CAAC;;;ACOD,MAAa,eAAe,EAC1B,MAAM,KAAK,SAA2D;CACpE,MAAM,SAAS,MAAM,WAAuB;EAC1C,KAAK,QAAQ;EACb,MAAM,KAAK;EACX,aAAa,CAAC,KAAK,UAAU;CAC/B,CAAC;CAED,OAAO;EACL,QAAQ,OAAO;EACf,YAAY,OAAO,cAAc,KAAA;EACjC,QAAQ,OAAO,UAAU,CAAC;CAC5B;AACF,EACF;;;;;;ACtBA,MAAa,WAAW,EACtB,MAAM,IAAI,SAAiB,UAA8B,CAAC,GAAoB;CAC5E,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,QAAQ,MAAM,SAAS;GAC3B,KAAK,QAAQ;GACb,KAAK,QAAQ,OAAO,OAAO,QAAQ,MAAM;IAAE,GAAG,QAAQ;IAAK,GAAG,QAAQ;GAAI;GAC1E,OAAO;GACP,OAAO;EACT,CAAC;EAED,MAAM,GAAG,SAAS,MAAM;EACxB,MAAM,GAAG,UAAU,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T,MAAM,YAAY;GACf,iBAAiB,QAAQ;GACzB,iBAAiB,YAAY,OAAO;GACpC,iBAAiB,aAAa,OAAO;GACrC,iBAAiB,MAAM;GACvB,iBAAiB,WAAW;GAC5B,iBAAiB,OAAO;CAC3B;CACA,MAAM,WAAW,MAAM,SAAS,IAAI,aAAa;EAAE;EAAK,KAAK;CAAU,CAAC;CAExE,IAAI,aAAa,GACf,MAAM,IAAI,MAAM,WAAW,KAAK,qBAAqB,SAAS,EAAE;CAGlE,OAAO;AACT,EACF;;;;;;AAqBA,eAAsB,QAAwC,SAAmF;CAC/I,MAAM,UAAU,eAAe,QAAQ,OAAO;CAE9C,OAAO,SAAS,QAAQ,EAAE,CAAC;EACzB,GAAG;EACH;CACF,CAAC;AACH;;;AChGA,eAAsB,UAAU,SAAmE;CACjG,OAAO,QAAQ;EACb,GAAG;EACH,GAAG;CACL,CAAC;AACH;;;;;;ACHA,MAAa,gBAAgB,OAAO,OAAO,EACzC,UACF,CAAC"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as meta, t as ManagedScript } from "./ManagedScript-DIacNHCc.js";
2
+ import { n as meta, t as ManagedScript } from "./ManagedScript-CLp9a43o.js";
3
3
  import { createRequire } from "node:module";
4
4
  import tty from "tty";
5
5
  //#region \0rolldown/runtime.js
@@ -1,39 +1,3 @@
1
- //#region src/internal/Logger.ts
2
- /**
3
- * Rank order used to compare log levels, higher means more verbose.
4
- */
5
- const logLevelRank = {
6
- debug: 4,
7
- error: 1,
8
- info: 3,
9
- silent: 0,
10
- warn: 2
11
- };
12
- /**
13
- * Creates a logger writing to `stream`, filtering out messages above the configured `level`.
14
- */
15
- const Logger = { create({ color = "auto", level, stderr, stdout }) {
16
- const write = (messageLevel, message) => {
17
- if (!(logLevelRank[messageLevel] <= logLevelRank[level])) return;
18
- const outputStream = logLevelRank[messageLevel] <= logLevelRank.warn ? stderr : stdout;
19
- const shouldColor = color === "always" || color === "auto" && "isTTY" in outputStream && outputStream.isTTY === true;
20
- const colorCode = {
21
- debug: "\x1B[36m",
22
- error: "\x1B[31m",
23
- info: "\x1B[32m",
24
- silent: "",
25
- warn: "\x1B[33m"
26
- }[messageLevel];
27
- outputStream.write(`${shouldColor ? `${colorCode}${message}\u{1B}[0m` : message}\n`);
28
- };
29
- return {
30
- debug: (message) => write("debug", message),
31
- error: (message) => write("error", message),
32
- info: (message) => write("info", message),
33
- warn: (message) => write("warn", message)
34
- };
35
- } };
36
- //#endregion
37
1
  //#region src/ManagedScriptEnv.ts
38
2
  /**
39
3
  * Enum for managed script environment variables.
@@ -93,6 +57,6 @@ function isLogLevel(value) {
93
57
  return knownLogLevels.has(value);
94
58
  }
95
59
  //#endregion
96
- export { ManagedScriptEnv as n, Logger as r, defaultContext as t };
60
+ export { ManagedScriptEnv as n, defaultContext as t };
97
61
 
98
- //# sourceMappingURL=defaultContext-D_QWP9aF.js.map
62
+ //# sourceMappingURL=defaultContext-BthxLDX3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaultContext-BthxLDX3.js","names":[],"sources":["../src/ManagedScriptEnv.ts","../src/ManagedScript/defaultContext.ts"],"sourcesContent":["/**\n * Enum for managed script environment variables.\n *\n * @enum\n */\nexport const ManagedScriptEnv = Object.freeze({\n /**\n * The color mode used for messages.\n */\n Color: 'MANAGED_SCRIPT_COLOR',\n\n /**\n * The directory where the managed script configuration is located.\n */\n ConfigDir: 'MANAGED_SCRIPT_CONFIG_DIR',\n\n /**\n * The file where the managed script configuration is located.\n */\n ConfigFile: 'MANAGED_SCRIPT_CONFIG_FILE',\n\n /**\n * The invocation directory used to resolve configuration and spawn the script.\n */\n Cwd: 'MANAGED_SCRIPT_CWD',\n\n /**\n * The resolved log level.\n */\n LogLevel: 'MANAGED_SCRIPT_LOGLEVEL',\n\n /**\n * The name of the managed script.\n */\n Name: 'MANAGED_SCRIPT_NAME',\n});\nexport type ManagedScriptEnv = typeof ManagedScriptEnv[keyof typeof ManagedScriptEnv];\n","import type { LogLevel } from '../internal/Logger.js';\nimport type { CommandContext } from '../type.js';\n\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport function defaultContext(context: Partial<CommandContext> | undefined): CommandContext {\n const {\n cli = {},\n color,\n cwd,\n dryRun,\n env = process.env,\n logLevel,\n stderr = process.stderr,\n stdout = process.stdout,\n } = context ?? {};\n const envLogLevel = env[ManagedScriptEnv.LogLevel];\n return {\n cli,\n color: color ?? cli.color ?? 'auto',\n cwd: cwd ?? cli.cwd ?? env[ManagedScriptEnv.Cwd] ?? process.cwd(),\n dryRun: dryRun ?? cli.dryRun ?? false,\n env,\n logLevel: logLevel ?? cli.logLevel ?? (isLogLevel(envLogLevel) ? envLogLevel : 'info'),\n stderr,\n stdout,\n };\n}\n\nconst knownLogLevels = new Set<LogLevel>(['debug', 'error', 'info', 'silent', 'warn']);\n\nfunction isLogLevel(value: string | undefined): value is LogLevel {\n return knownLogLevels.has(value as LogLevel);\n}\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,OAAO,OAAO;;;;CAI5C,OAAO;;;;CAKP,WAAW;;;;CAKX,YAAY;;;;CAKZ,KAAK;;;;CAKL,UAAU;;;;CAKV,MAAM;AACR,CAAC;;;AC9BD,SAAgB,eAAe,SAA8D;CAC3F,MAAM,EACJ,MAAM,CAAC,GACP,OACA,KACA,QACA,MAAM,QAAQ,KACd,UACA,SAAS,QAAQ,QACjB,SAAS,QAAQ,WACf,WAAW,CAAC;CAChB,MAAM,cAAc,IAAI,iBAAiB;CACzC,OAAO;EACL;EACA,OAAO,SAAS,IAAI,SAAS;EAC7B,KAAK,OAAO,IAAI,OAAO,IAAI,iBAAiB,QAAQ,QAAQ,IAAI;EAChE,QAAQ,UAAU,IAAI,UAAU;EAChC;EACA,UAAU,YAAY,IAAI,aAAa,WAAW,WAAW,IAAI,cAAc;EAC/E;EACA;CACF;AACF;AAEA,MAAM,iCAAiB,IAAI,IAAc;CAAC;CAAS;CAAS;CAAQ;CAAU;AAAM,CAAC;AAErF,SAAS,WAAW,OAA8C;CAChE,OAAO,eAAe,IAAI,KAAiB;AAC7C"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { n as meta, t as ManagedScript } from "./ManagedScript-DIacNHCc.js";
2
- import { n as ManagedScriptEnv } from "./defaultContext-D_QWP9aF.js";
1
+ import { n as meta, t as ManagedScript } from "./ManagedScript-CLp9a43o.js";
2
+ import { n as ManagedScriptEnv } from "./defaultContext-BthxLDX3.js";
3
3
  import { createDefineConfig } from "c12";
4
4
  //#region src/defineConfig.ts
5
5
  /**
@@ -15,12 +15,6 @@ import { createDefineConfig } from "c12";
15
15
  */
16
16
  const defineConfig = createDefineConfig();
17
17
  //#endregion
18
- //#region src/type/Command.ts
19
- const ManagedScriptCommand = Object.freeze({ RunScript: (args) => ({
20
- _: "RunScript",
21
- ...args
22
- }) });
23
- //#endregion
24
18
  //#region src/mergeConfig.ts
25
19
  const DANGEROUS_KEYS = /* @__PURE__ */ new Set([
26
20
  "__proto__",
@@ -74,6 +68,12 @@ function toArray(target) {
74
68
  return Array.isArray(target) ? target : [target];
75
69
  }
76
70
  //#endregion
71
+ //#region src/type/Command.ts
72
+ const ManagedScriptCommand = Object.freeze({ RunScript: (args) => ({
73
+ _: "RunScript",
74
+ ...args
75
+ }) });
76
+ //#endregion
77
77
  export { ManagedScript, ManagedScriptCommand, ManagedScriptEnv, defineConfig, mergeConfig, meta };
78
78
 
79
79
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/defineConfig.ts","../src/type/Command.ts","../src/mergeConfig.ts"],"sourcesContent":["import { createDefineConfig } from 'c12';\n\nimport type { UserConfig } from './type/UserConfig.js';\n\n/**\n * Define the configuration for the managed script.\n *\n * @example\n * ```ts\n * // managed-script.config.ts or @acme/managed-script-config/index.ts\n * export default defineConfig({\n * // your configuration here\n * });\n * ```\n */\nexport const defineConfig = createDefineConfig<UserConfig>();\n","import type { CommandContext } from './CommandContext.js';\n\nexport type ManagedScriptCommand =\n | ManagedScriptCommand.RunScript;\n\nexport namespace ManagedScriptCommand {\n export interface Base<TName extends string, TParameters extends object> {\n /**\n * Name of the command.\n */\n readonly _: TName;\n\n /**\n * Context in which the command is executed.\n */\n readonly context: CommandContext;\n\n /**\n * Parameters provided to the command.\n */\n readonly parameters: Readonly<TParameters>;\n }\n\n export type Parameters<T extends Base<string, object>> = Omit<T, '_'>;\n\n export interface RunScript extends Base<'RunScript', {\n scriptArgs?: ReadonlyArray<string>;\n scriptName: string | undefined;\n }> {}\n}\n\nexport const ManagedScriptCommand = Object.freeze({\n RunScript: (args: ManagedScriptCommand.Parameters<ManagedScriptCommand.RunScript>): ManagedScriptCommand.RunScript => ({\n _: 'RunScript' as const,\n ...args,\n }),\n});\n","import type { UserConfig } from './type/UserConfig.js';\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Merge two managed-script configs using the same heuristic as Vite and Vitest:\n * later values win, plain objects merge recursively, and arrays concatenate.\n *\n * @param defaults\n * @param overrides\n * @example\n * ```ts\n * export default defineConfig(mergeConfig(\n * { scripts: { build: 'echo base', test: 'echo test' } },\n * { scripts: { build: 'echo override' } },\n * ));\n * ```\n */\nexport function mergeConfig(defaults: UserConfig, overrides: UserConfig): UserConfig {\n if (typeof defaults === 'function' || typeof overrides === 'function') {\n throw new TypeError('Cannot merge config in form of callback');\n }\n\n return mergeConfigRecursively({ ...defaults }, { ...overrides });\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return Object.prototype.toString.call(value) === '[object Object]';\n}\n\nfunction mergeConfigRecursively(\n defaults: Record<string, unknown>,\n overrides: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...defaults };\n\n for (const [key, value] of Object.entries(overrides)) {\n if (DANGEROUS_KEYS.has(key)) {\n continue;\n }\n\n if (value == null) {\n continue;\n }\n\n const existing = merged[key];\n if (existing == null) {\n merged[key] = value;\n continue;\n }\n\n if (Array.isArray(existing) || Array.isArray(value)) {\n merged[key] = [...toArray(existing), ...toArray(value)];\n continue;\n }\n\n if (isObject(existing) && isObject(value)) {\n merged[key] = mergeConfigRecursively(existing, value);\n continue;\n }\n\n merged[key] = value;\n }\n\n return merged;\n}\n\nfunction toArray<T>(target: Array<T> | T): Array<T> {\n return Array.isArray(target) ? target : [target];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,eAAe,mBAA+B;;;ACgB3D,MAAa,uBAAuB,OAAO,OAAO,EAChD,YAAY,UAA2G;CACrH,GAAG;CACH,GAAG;AACL,GACF,CAAC;;;AClCD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;;;;;;;;;;;;;;AAgBxE,SAAgB,YAAY,UAAsB,WAAmC;CACnF,IAAI,OAAO,aAAa,cAAc,OAAO,cAAc,YACzD,MAAM,IAAI,UAAU,yCAAyC;CAG/D,OAAO,uBAAuB,EAAE,GAAG,SAAS,GAAG,EAAE,GAAG,UAAU,CAAC;AACjE;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AACnD;AAEA,SAAS,uBACP,UACA,WACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,SAAS;CAEtD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GAAG;EACpD,IAAI,eAAe,IAAI,GAAG,GACxB;EAGF,IAAI,SAAS,MACX;EAGF,MAAM,WAAW,OAAO;EACxB,IAAI,YAAY,MAAM;GACpB,OAAO,OAAO;GACd;EACF;EAEA,IAAI,MAAM,QAAQ,QAAQ,KAAK,MAAM,QAAQ,KAAK,GAAG;GACnD,OAAO,OAAO,CAAC,GAAG,QAAQ,QAAQ,GAAG,GAAG,QAAQ,KAAK,CAAC;GACtD;EACF;EAEA,IAAI,SAAS,QAAQ,KAAK,SAAS,KAAK,GAAG;GACzC,OAAO,OAAO,uBAAuB,UAAU,KAAK;GACpD;EACF;EAEA,OAAO,OAAO;CAChB;CAEA,OAAO;AACT;AAEA,SAAS,QAAW,QAAgC;CAClD,OAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AACjD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/defineConfig.ts","../src/mergeConfig.ts","../src/type/Command.ts"],"sourcesContent":["import { createDefineConfig } from 'c12';\n\nimport type { UserConfig } from './type/UserConfig.js';\n\n/**\n * Define the configuration for the managed script.\n *\n * @example\n * ```ts\n * // managed-script.config.ts or @acme/managed-script-config/index.ts\n * export default defineConfig({\n * // your configuration here\n * });\n * ```\n */\nexport const defineConfig = createDefineConfig<UserConfig>();\n","import type { UserConfig } from './type/UserConfig.js';\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);\n\n/**\n * Merge two managed-script configs using the same heuristic as Vite and Vitest:\n * later values win, plain objects merge recursively, and arrays concatenate.\n *\n * @param defaults\n * @param overrides\n * @example\n * ```ts\n * export default defineConfig(mergeConfig(\n * { scripts: { build: 'echo base', test: 'echo test' } },\n * { scripts: { build: 'echo override' } },\n * ));\n * ```\n */\nexport function mergeConfig(defaults: UserConfig, overrides: UserConfig): UserConfig {\n if (typeof defaults === 'function' || typeof overrides === 'function') {\n throw new TypeError('Cannot merge config in form of callback');\n }\n\n return mergeConfigRecursively({ ...defaults }, { ...overrides });\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return Object.prototype.toString.call(value) === '[object Object]';\n}\n\nfunction mergeConfigRecursively(\n defaults: Record<string, unknown>,\n overrides: Record<string, unknown>,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...defaults };\n\n for (const [key, value] of Object.entries(overrides)) {\n if (DANGEROUS_KEYS.has(key)) {\n continue;\n }\n\n if (value == null) {\n continue;\n }\n\n const existing = merged[key];\n if (existing == null) {\n merged[key] = value;\n continue;\n }\n\n if (Array.isArray(existing) || Array.isArray(value)) {\n merged[key] = [...toArray(existing), ...toArray(value)];\n continue;\n }\n\n if (isObject(existing) && isObject(value)) {\n merged[key] = mergeConfigRecursively(existing, value);\n continue;\n }\n\n merged[key] = value;\n }\n\n return merged;\n}\n\nfunction toArray<T>(target: Array<T> | T): Array<T> {\n return Array.isArray(target) ? target : [target];\n}\n","import type { CommandContext } from './CommandContext.js';\n\nexport type ManagedScriptCommand =\n | ManagedScriptCommand.RunScript;\n\nexport namespace ManagedScriptCommand {\n export interface Base<TName extends string, TParameters extends object> {\n /**\n * Name of the command.\n */\n readonly _: TName;\n\n /**\n * Context in which the command is executed.\n */\n readonly context: CommandContext;\n\n /**\n * Parameters provided to the command.\n */\n readonly parameters: Readonly<TParameters>;\n }\n\n export type Parameters<T extends Base<string, object>> = Omit<T, '_'>;\n\n export interface RunScript extends Base<'RunScript', {\n scriptArgs?: ReadonlyArray<string>;\n scriptName: string | undefined;\n }> {}\n}\n\nexport const ManagedScriptCommand = Object.freeze({\n RunScript: (args: ManagedScriptCommand.Parameters<ManagedScriptCommand.RunScript>): ManagedScriptCommand.RunScript => ({\n _: 'RunScript' as const,\n ...args,\n }),\n});\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,eAAe,mBAA+B;;;ACb3D,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;;;;;;;;;;;;;;AAgBxE,SAAgB,YAAY,UAAsB,WAAmC;CACnF,IAAI,OAAO,aAAa,cAAc,OAAO,cAAc,YACzD,MAAM,IAAI,UAAU,yCAAyC;CAG/D,OAAO,uBAAuB,EAAE,GAAG,SAAS,GAAG,EAAE,GAAG,UAAU,CAAC;AACjE;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AACnD;AAEA,SAAS,uBACP,UACA,WACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,SAAS;CAEtD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GAAG;EACpD,IAAI,eAAe,IAAI,GAAG,GACxB;EAGF,IAAI,SAAS,MACX;EAGF,MAAM,WAAW,OAAO;EACxB,IAAI,YAAY,MAAM;GACpB,OAAO,OAAO;GACd;EACF;EAEA,IAAI,MAAM,QAAQ,QAAQ,KAAK,MAAM,QAAQ,KAAK,GAAG;GACnD,OAAO,OAAO,CAAC,GAAG,QAAQ,QAAQ,GAAG,GAAG,QAAQ,KAAK,CAAC;GACtD;EACF;EAEA,IAAI,SAAS,QAAQ,KAAK,SAAS,KAAK,GAAG;GACzC,OAAO,OAAO,uBAAuB,UAAU,KAAK;GACpD;EACF;EAEA,OAAO,OAAO;CAChB;CAEA,OAAO;AACT;AAEA,SAAS,QAAW,QAAgC;CAClD,OAAO,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AACjD;;;ACtCA,MAAa,uBAAuB,OAAO,OAAO,EAChD,YAAY,UAA2G;CACrH,GAAG;CACH,GAAG;AACL,GACF,CAAC"}
package/dist/zx.js CHANGED
@@ -1,5 +1,6 @@
1
- import { r as Logger, t as defaultContext } from "./defaultContext-D_QWP9aF.js";
2
- import { $ as $$1, log } from "zx";
1
+ import { t as defaultContext } from "./defaultContext-BthxLDX3.js";
2
+ import { $ as $$1, chalk, log } from "zx";
3
+ import { stripVTControlCharacters } from "node:util";
3
4
  //#region src/zx/defaultZXOptions.ts
4
5
  function defaultZXOptions(options) {
5
6
  const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...optionsRest } = options;
@@ -14,21 +15,26 @@ function defaultZXOptions(options) {
14
15
  ...optionsStderr == null ? {} : { stderr: optionsStderr },
15
16
  ...optionsStdout == null ? {} : { stdout: optionsStdout }
16
17
  });
17
- const logger = Logger.create({
18
- color: context.color,
19
- level: context.logLevel,
20
- stderr: context.stderr,
21
- stdout: context.stdout
22
- });
23
18
  return {
24
19
  cwd: context.cwd,
25
20
  env: context.env,
26
21
  log: (entry) => {
27
- if (entry.kind === "cmd") {
28
- logger.info(entry.cmd);
29
- return;
22
+ const target = entry.kind === "cmd" || entry.kind === "stdout" ? context.stdout : context.stderr;
23
+ const colorEnabled = context.color === "always" || context.color === "auto" && autoColor(context.env, target);
24
+ const previousOutput = log.output;
25
+ const previousLevel = chalk.level;
26
+ log.output = colorEnabled ? target : { write: (chunk) => target.write(stripVTControlCharacters(chunk)) };
27
+ if (colorEnabled && !chalk.level) chalk.level = 1;
28
+ else if (!colorEnabled) chalk.level = 0;
29
+ try {
30
+ log(entry.kind === "cmd" && (context.logLevel === "info" || context.logLevel === "debug") ? {
31
+ ...entry,
32
+ verbose: true
33
+ } : entry);
34
+ } finally {
35
+ log.output = previousOutput;
36
+ chalk.level = previousLevel;
30
37
  }
31
- log(entry);
32
38
  },
33
39
  preferLocal: true,
34
40
  quiet: context.logLevel === "silent",
@@ -37,6 +43,11 @@ function defaultZXOptions(options) {
37
43
  ...optionsRest
38
44
  };
39
45
  }
46
+ function autoColor(env, stream) {
47
+ if (env["NO_COLOR"] != null && env["NO_COLOR"] !== "") return false;
48
+ const force = env["FORCE_COLOR"];
49
+ return force == null ? stream.isTTY === true : force !== "0" && force !== "false";
50
+ }
40
51
  //#endregion
41
52
  //#region src/zx/zx.ts
42
53
  /**
package/dist/zx.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"zx.js","names":["zxDefault"],"sources":["../src/zx/defaultZXOptions.ts","../src/zx/zx.ts","../src/zx.ts"],"sourcesContent":["import { log as zxLog } from 'zx';\n\nimport type { LogLevel } from '../internal/Logger.js';\nimport type { ZXOptions } from './ZXOptions.js';\n\nimport { Logger } from '../internal/Logger.js';\nimport { defaultContext } from '../ManagedScript/defaultContext.js';\n\nexport function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogLevel | undefined; stderr?: NodeJS.WritableStream | undefined; stdout?: NodeJS.WritableStream | undefined }): Partial<ZXOptions> {\n const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...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 ...(optionsStderr == null ? {} : { stderr: optionsStderr }),\n ...(optionsStdout == null ? {} : { stdout: optionsStdout }),\n });\n const logger = Logger.create({ color: context.color, level: context.logLevel, stderr: context.stderr, stdout: context.stdout });\n\n return {\n cwd: context.cwd,\n env: context.env,\n log: (entry) => {\n if (entry.kind === 'cmd') {\n logger.info(entry.cmd);\n return;\n }\n zxLog(entry);\n },\n preferLocal: true,\n quiet: context.logLevel === 'silent',\n stdio: 'inherit',\n verbose: context.logLevel === 'debug',\n ...optionsRest,\n };\n}\n","import { $ as zxDefault } from 'zx';\n\nimport type { CommandContext } from '../type.js';\nimport type { ZXShell } from './ZXShell.js';\n\nimport { defaultZXOptions } from './defaultZXOptions.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 * Stream used to write instrumented command logs at the error and warn levels.\n */\n readonly stderr?: NodeJS.WritableStream | undefined;\n\n /**\n * Stream used to write instrumented command logs at the info and debug levels.\n */\n readonly stdout?: NodeJS.WritableStream | 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 zxDefault(defaultZXOptions({\n env,\n ...(options.cwd == null ? {} : { cwd: options.cwd }),\n ...(options.logLevel == null ? {} : { logLevel: options.logLevel }),\n ...(options.stderr == null ? {} : { stderr: options.stderr }),\n ...(options.stdout == null ? {} : { stdout: options.stdout }),\n }));\n}\n","import type { ZXShell } from './zx/ZXShell.js';\n\nimport { zx } from './zx/zx.js';\n\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":";;;AAQA,SAAgB,iBAAiB,SAA+K;CAC9M,MAAM,EAAE,KAAK,YAAY,KAAK,YAAY,UAAU,iBAAiB,QAAQ,eAAe,QAAQ,eAAe,GAAG,gBAAgB;CACtI,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,iBAAiB,OAAO,CAAC,IAAI,EAAE,QAAQ,cAAc;EACzD,GAAI,iBAAiB,OAAO,CAAC,IAAI,EAAE,QAAQ,cAAc;CAC3D,CAAC;CACD,MAAM,SAAS,OAAO,OAAO;EAAE,OAAO,QAAQ;EAAO,OAAO,QAAQ;EAAU,QAAQ,QAAQ;EAAQ,QAAQ,QAAQ;CAAO,CAAC;CAE9H,OAAO;EACL,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,MAAM,UAAU;GACd,IAAI,MAAM,SAAS,OAAO;IACxB,OAAO,KAAK,MAAM,GAAG;IACrB;GACF;GACA,IAAM,KAAK;EACb;EACA,aAAa;EACb,OAAO,QAAQ,aAAa;EAC5B,OAAO;EACP,SAAS,QAAQ,aAAa;EAC9B,GAAG;CACL;AACF;;;;;;;;ACIA,SAAgB,GAAG,UAA2B,CAAC,GAAY;CACzD,MAAM,MAAM,QAAQ,OAAO,OAAO,QAAQ,MAAM;EAAE,GAAG,QAAQ;EAAK,GAAG,QAAQ;CAAI;CAEjF,OAAOA,IAAU,iBAAiB;EAChC;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,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EAC3D,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CAC7D,CAAC,CAAC;AACJ;;;;;;;;;;;;;AChCA,MAAa,IAAa,GAAG"}
1
+ {"version":3,"file":"zx.js","names":["zxLog","zxDefault"],"sources":["../src/zx/defaultZXOptions.ts","../src/zx/zx.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 { ZXOptions } from './ZXOptions.js';\n\nimport { defaultContext } from '../ManagedScript/defaultContext.js';\n\nexport function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogLevel | undefined; stderr?: NodeJS.WritableStream | undefined; stdout?: NodeJS.WritableStream | undefined }): Partial<ZXOptions> {\n const { cwd: optionsCwd, env: optionsEnv, logLevel: optionsLogLevel, stderr: optionsStderr, stdout: optionsStdout, ...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 ...(optionsStderr == null ? {} : { stderr: optionsStderr }),\n ...(optionsStdout == null ? {} : { stdout: optionsStdout }),\n });\n\n return {\n cwd: context.cwd,\n env: context.env,\n log: (entry) => {\n const target = (entry.kind === 'cmd' || entry.kind === 'stdout' ? context.stdout : context.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\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 zxDefault } from 'zx';\n\nimport type { CommandContext } from '../type.js';\nimport type { ZXShell } from './ZXShell.js';\n\nimport { defaultZXOptions } from './defaultZXOptions.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 * Stream used to write instrumented command logs at the error and warn levels.\n */\n readonly stderr?: NodeJS.WritableStream | undefined;\n\n /**\n * Stream used to write instrumented command logs at the info and debug levels.\n */\n readonly stdout?: NodeJS.WritableStream | 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 zxDefault(defaultZXOptions({\n env,\n ...(options.cwd == null ? {} : { cwd: options.cwd }),\n ...(options.logLevel == null ? {} : { logLevel: options.logLevel }),\n ...(options.stderr == null ? {} : { stderr: options.stderr }),\n ...(options.stdout == null ? {} : { stdout: options.stdout }),\n }));\n}\n","import type { ZXShell } from './zx/ZXShell.js';\n\nimport { zx } from './zx/zx.js';\n\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":";;;;AAQA,SAAgB,iBAAiB,SAA+K;CAC9M,MAAM,EAAE,KAAK,YAAY,KAAK,YAAY,UAAU,iBAAiB,QAAQ,eAAe,QAAQ,eAAe,GAAG,gBAAgB;CACtI,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,iBAAiB,OAAO,CAAC,IAAI,EAAE,QAAQ,cAAc;EACzD,GAAI,iBAAiB,OAAO,CAAC,IAAI,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EAAE,UAAU,QAAQ,SAAS;EACjE,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;EAC3D,GAAI,QAAQ,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;CAC7D,CAAC,CAAC;AACJ;;;;;;;;;;;;;AChCA,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.2",
3
+ "version": "1.0.0-alpha.4",
4
4
  "description": "CLI tool to run project scripts from a shared configuration",
5
5
  "keywords": [
6
6
  "cli",
@@ -49,5 +49,6 @@
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"
52
- }
52
+ },
53
+ "gitHead": "d39c8e42e2e9cb34d05ea9e23c757383dd30795a"
53
54
  }
@@ -1,3 +1,5 @@
1
+ import path from 'node:path';
2
+
1
3
  import type { ManagedScriptCommand } from '../type.js';
2
4
 
3
5
  import { ConfigLoader } from '../internal/ConfigLoader.js';
@@ -16,7 +18,7 @@ const handlers = {
16
18
  } = command;
17
19
  const logger = Logger.create({ color, level: logLevel, stderr, stdout });
18
20
  const loaded = await ConfigLoader.load({ cwd });
19
- logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}.`);
21
+ logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}`);
20
22
  const resolved = resolveScripts(loaded);
21
23
  const { scripts } = resolved;
22
24
 
@@ -42,13 +44,14 @@ const handlers = {
42
44
  ...scriptArgs.map((argument) => `'${argument.replaceAll("'", String.raw`'\''`)}'`),
43
45
  ].join(' ');
44
46
 
47
+ // relative to cwd
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`);
45
51
  if (dryRun) {
46
- stdout.write(`${commandLine}\n`);
47
52
  return 0;
48
53
  }
49
54
 
50
- logger.info(`Running script "${name}": ${commandLine}`);
51
-
52
55
  // Prepare the environment variables for the script execution.
53
56
  const scriptEnv = {
54
57
  [ManagedScriptEnv.Color]: color,
@@ -58,7 +61,6 @@ const handlers = {
58
61
  [ManagedScriptEnv.LogLevel]: logLevel,
59
62
  [ManagedScriptEnv.Name]: name,
60
63
  };
61
-
62
64
  const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });
63
65
 
64
66
  if (exitCode !== 0) {
@@ -1,3 +1,5 @@
1
+ import { meta } from '../meta.js';
2
+
1
3
  export type ColorMode = 'always' | 'auto' | 'never';
2
4
  export type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';
3
5
 
@@ -15,8 +17,13 @@ const logLevelRank: Record<LogLevel, number> = {
15
17
  export interface CreateLoggerOptions {
16
18
  readonly color?: ColorMode;
17
19
  readonly level: LogLevel;
20
+
21
+ /**
22
+ * Program name used as message prefix (default: binary name)
23
+ */
24
+ readonly name?: string;
18
25
  readonly stderr: NodeJS.WritableStream;
19
- readonly stdout: NodeJS.WritableStream;
26
+ readonly stdout?: NodeJS.WritableStream | undefined;
20
27
  }
21
28
 
22
29
  export interface Logger {
@@ -30,22 +37,26 @@ export interface Logger {
30
37
  * Creates a logger writing to `stream`, filtering out messages above the configured `level`.
31
38
  */
32
39
  export const Logger = {
33
- create({ color = 'auto', level, stderr, stdout }: CreateLoggerOptions): Logger {
40
+ create({ color = 'auto', level, name = meta.binaryName, stderr }: CreateLoggerOptions): Logger {
34
41
  const write = (messageLevel: LogLevel, message: string) => {
35
42
  if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {
36
43
  return;
37
44
  }
38
- // write to stderr for warnings and errors
39
- const outputStream = logLevelRank[messageLevel] <= logLevelRank.warn ? stderr : stdout;
45
+ // Keep stdout free for command output that may be consumed by another process.
46
+ const outputStream = stderr;
40
47
  const shouldColor = color === 'always' || (color === 'auto' && 'isTTY' in outputStream && outputStream.isTTY === true);
41
48
  const colorCode = {
42
49
  debug: '\u{1B}[36m',
43
50
  error: '\u{1B}[31m',
44
- info: '\u{1B}[32m',
51
+ info: '',
45
52
  silent: '',
46
53
  warn: '\u{1B}[33m',
47
54
  }[messageLevel];
48
- outputStream.write(`${shouldColor ? `${colorCode}${message}\u{1B}[0m` : message}\n`);
55
+ // Unix convention: `program: [level: ]message`, info has no level label
56
+ const label = { debug: 'debug', error: 'error', info: '', silent: '', warn: 'warning' }[messageLevel];
57
+ const coloredLabel = shouldColor && colorCode !== '' ? `${colorCode}${label}\u{1B}[0m` : label;
58
+ const prefix = label === '' ? `${name}: ` : `${name}: ${coloredLabel}: `;
59
+ outputStream.write(`${prefix}${message}\n`);
49
60
  };
50
61
 
51
62
  return {
@@ -1,9 +1,9 @@
1
- import { log as zxLog } from 'zx';
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { chalk, log as zxLog } from 'zx';
2
3
 
3
4
  import type { LogLevel } from '../internal/Logger.js';
4
5
  import type { ZXOptions } from './ZXOptions.js';
5
6
 
6
- import { Logger } from '../internal/Logger.js';
7
7
  import { defaultContext } from '../ManagedScript/defaultContext.js';
8
8
 
9
9
  export function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogLevel | undefined; stderr?: NodeJS.WritableStream | undefined; stdout?: NodeJS.WritableStream | undefined }): Partial<ZXOptions> {
@@ -16,17 +16,30 @@ export function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogL
16
16
  ...(optionsStderr == null ? {} : { stderr: optionsStderr }),
17
17
  ...(optionsStdout == null ? {} : { stdout: optionsStdout }),
18
18
  });
19
- const logger = Logger.create({ color: context.color, level: context.logLevel, stderr: context.stderr, stdout: context.stdout });
20
19
 
21
20
  return {
22
21
  cwd: context.cwd,
23
22
  env: context.env,
24
23
  log: (entry) => {
25
- if (entry.kind === 'cmd') {
26
- logger.info(entry.cmd);
27
- return;
24
+ const target = (entry.kind === 'cmd' || entry.kind === 'stdout' ? context.stdout : context.stderr) as NodeJS.WriteStream;
25
+ const colorEnabled = context.color === 'always' || (context.color === 'auto' && autoColor(context.env, target));
26
+ const previousOutput = zxLog.output;
27
+ const previousLevel = chalk.level;
28
+ zxLog.output = colorEnabled
29
+ ? target
30
+ : ({ write: (chunk: string) => target.write(stripVTControlCharacters(chunk)) } as unknown as NodeJS.WriteStream);
31
+ if (colorEnabled && !chalk.level) {
32
+ chalk.level = 1;
33
+ } else if (!colorEnabled) {
34
+ chalk.level = 0;
35
+ }
36
+ try {
37
+ zxLog(entry.kind === 'cmd' && (context.logLevel === 'info' || context.logLevel === 'debug') ? { ...entry, verbose: true } : entry);
38
+ } finally {
39
+ // eslint-disable-next-line ts/no-non-null-assertion
40
+ zxLog.output = previousOutput!;
41
+ chalk.level = previousLevel;
28
42
  }
29
- zxLog(entry);
30
43
  },
31
44
  preferLocal: true,
32
45
  quiet: context.logLevel === 'silent',
@@ -35,3 +48,11 @@ export function defaultZXOptions(options: Partial<ZXOptions> & { logLevel?: LogL
35
48
  ...optionsRest,
36
49
  };
37
50
  }
51
+
52
+ function autoColor(env: NodeJS.ProcessEnv, stream: NodeJS.WriteStream): boolean {
53
+ if (env['NO_COLOR'] != null && env['NO_COLOR'] !== '') {
54
+ return false;
55
+ }
56
+ const force = env['FORCE_COLOR'];
57
+ return force == null ? stream.isTTY === true : force !== '0' && force !== 'false';
58
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"ManagedScript-DIacNHCc.js","names":[],"sources":["../src/meta.ts","../src/internal/ConfigLoader.ts","../src/internal/Executor.ts","../src/internal/ScriptNameResolver.ts","../src/ManagedScript/resolveScripts.ts","../src/ManagedScript/execute.ts","../src/ManagedScript/runScript.ts","../src/ManagedScript.ts"],"sourcesContent":["export const meta = Object.freeze({\n binaryLabel: 'W5S Managed Script',\n binaryName: 'managed-script',\n // @ts-ignore - these variables are injected at build time\n binaryVersion: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n // @ts-ignore - these variables are injected at build time\n buildNumber: 1, // (typeof __PACKAGE_BUILD_NUMBER__ === 'undefined' ? 0 : __PACKAGE_BUILD_NUMBER__) as number,\n // @ts-ignore - these variables are injected at build time\n name: (typeof __PACKAGE_NAME__ === 'undefined' ? '' : __PACKAGE_NAME__) as string,\n // @ts-ignore - these variables are injected at build time\n version: (typeof __PACKAGE_VERSION__ === 'undefined' ? '' : __PACKAGE_VERSION__) as string,\n});\n","import type { ConfigLayer } from 'c12';\n\nimport { loadConfig } from 'c12';\n\nimport type { UserConfig } from '../type/UserConfig.js';\n\nimport { meta } from '../meta.js';\n\nexport interface ConfigLoaderOptions {\n readonly cwd: string;\n}\n\nexport interface ConfigLoaderResult {\n readonly config: UserConfig;\n readonly configFile: string | undefined;\n readonly layers: Array<ConfigLayer<UserConfig>>;\n}\n\nexport const ConfigLoader = {\n async load(options: ConfigLoaderOptions): Promise<ConfigLoaderResult> {\n const result = await loadConfig<UserConfig>({\n cwd: options.cwd,\n name: meta.binaryName,\n packageJson: [meta.binaryName],\n });\n\n return {\n config: result.config,\n configFile: result.configFile ?? undefined,\n layers: result.layers ?? [],\n };\n },\n};\n","import { spawn } from 'node:child_process';\n\nexport interface ExecutorRunOptions {\n readonly cwd?: string | undefined;\n readonly env?: NodeJS.ProcessEnv | undefined;\n}\n\n/**\n * Executes a command via the system shell, inheriting stdio and forwarding its exit code.\n */\nexport const Executor = {\n async run(command: string, options: ExecutorRunOptions = {}): Promise<number> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, {\n cwd: options.cwd,\n env: options.env == null ? process.env : { ...process.env, ...options.env },\n shell: true,\n stdio: 'inherit',\n });\n\n child.on('error', reject);\n child.on('close', (code, signal) => {\n resolve(code ?? (signal == null ? 1 : 128));\n });\n });\n },\n};\n","import { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport interface ScriptNameResolverOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly scriptName: string | undefined;\n}\n\n/**\n * Resolves the script name to run.\n *\n * Priority: first positional CLI argument > `MANAGED_SCRIPT_NAME` env var > `npm_lifecycle_event` env var.\n */\nexport const ScriptNameResolver = {\n resolve({ env, scriptName }: ScriptNameResolverOptions): string | undefined {\n return scriptName ?? env[ManagedScriptEnv.Name] ?? env['npm_lifecycle_event'];\n },\n};\n","import path from 'node:path/win32';\n\nimport type { ConfigLoaderResult } from '../internal/ConfigLoader.js';\nimport type { ResolvedConfig } from '../type/ResolvedConfig.js';\n\nexport function resolveScripts(loaded: ConfigLoaderResult): ResolvedConfig {\n const scripts: ResolvedConfig['scripts'] = {};\n const layers = loaded.layers.length > 0 ? loaded.layers : [{ config: loaded.config }];\n\n for (const layer of layers) {\n for (const [name, command] of Object.entries(layer.config?.scripts ?? {})) {\n const configFile = layer.configFile ?? loaded.configFile;\n const configDir = configFile == null ? undefined : path.dirname(configFile);\n scripts[name] ??= {\n command,\n configDir,\n configFile,\n };\n }\n }\n\n return {\n scripts,\n };\n}\n","import type { ManagedScriptCommand } from '../type.js';\n\nimport { ConfigLoader } from '../internal/ConfigLoader.js';\nimport { Executor } from '../internal/Executor.js';\nimport { Logger } from '../internal/Logger.js';\nimport { ScriptNameResolver } from '../internal/ScriptNameResolver.js';\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\nimport { defaultContext } from './defaultContext.js';\nimport { resolveScripts } from './resolveScripts.js';\n\nconst handlers = {\n RunScript: async (command: ManagedScriptCommand.RunScript): Promise<number> => {\n const {\n context: { color, cwd, dryRun, env, logLevel, stderr, stdout },\n parameters: { scriptArgs = [], scriptName },\n } = command;\n const logger = Logger.create({ color, level: logLevel, stderr, stdout });\n const loaded = await ConfigLoader.load({ cwd });\n logger.debug(`Resolved configuration from ${loaded.configFile ?? 'defaults (no config file found)'}.`);\n const resolved = resolveScripts(loaded);\n const { scripts } = resolved;\n\n const name = ScriptNameResolver.resolve({ env, scriptName: scriptName });\n if (name == null) {\n throw new Error(\n 'Unable to resolve the script name. Pass it as the first argument, set the MANAGED_SCRIPT_NAME environment variable, or run through an npm/pnpm script (npm_lifecycle_event).',\n );\n }\n\n const script = scripts[name];\n if (script == null) {\n const available = Object.keys(scripts);\n throw new Error(\n `No script named \"${name}\" found in the configuration.${\n available.length > 0 ? ` Available scripts: ${available.join(', ')}.` : ' No scripts are configured.'\n }`,\n );\n }\n\n const commandLine = [\n script.command,\n ...scriptArgs.map((argument) => `'${argument.replaceAll(\"'\", String.raw`'\\''`)}'`),\n ].join(' ');\n\n if (dryRun) {\n stdout.write(`${commandLine}\\n`);\n return 0;\n }\n\n logger.info(`Running script \"${name}\": ${commandLine}`);\n\n // Prepare the environment variables for the script execution.\n const scriptEnv = {\n [ManagedScriptEnv.Color]: color,\n [ManagedScriptEnv.ConfigDir]: script.configDir,\n [ManagedScriptEnv.ConfigFile]: script.configFile,\n [ManagedScriptEnv.Cwd]: cwd,\n [ManagedScriptEnv.LogLevel]: logLevel,\n [ManagedScriptEnv.Name]: name,\n };\n\n const exitCode = await Executor.run(commandLine, { cwd, env: scriptEnv });\n\n if (exitCode !== 0) {\n throw new Error(`Script \"${name}\" exited with code ${exitCode}.`);\n }\n\n return exitCode;\n },\n} satisfies {\n [K in ManagedScriptCommand['_']]: (command: Extract<ManagedScriptCommand, { _: K }>) => Promise<any>;\n};\n\nexport type ExecuteCommand<T extends ManagedScriptCommand> = Omit<T, 'context'> & {\n /**\n * Context is optional\n */\n context?: Partial<ManagedScriptCommand['context']>;\n};\n\n/**\n * Extract command parameter from execute handler\n */\nexport type ExecuteCommandParameters<T extends ManagedScriptCommand> = Omit<Parameters<typeof execute<T>>[0], '_'>;\n\n/**\n * Dispatch the command to the appropriate handler based on its type.\n *\n * @param command\n */\nexport async function execute<T extends ManagedScriptCommand>(command: ExecuteCommand<T>): Promise<Awaited<ReturnType<typeof handlers[T['_']]>>> {\n const context = defaultContext(command.context);\n // @ts-ignore we know this works\n return handlers[command._]({\n ...command,\n context,\n });\n}\n","import { ManagedScriptCommand } from '../type.js';\nimport { execute, type ExecuteCommandParameters } from './execute.js';\n\nexport async function runScript(options: ExecuteCommandParameters<ManagedScriptCommand.RunScript>) {\n return execute({\n _: 'RunScript',\n ...options,\n });\n}\n","import { runScript } from './ManagedScript/runScript.js';\n\n/**\n * @namespace\n */\nexport const ManagedScript = Object.freeze({\n runScript,\n});\n"],"mappings":";;;;;AAAA,MAAa,OAAO,OAAO,OAAO;CAChC,aAAa;CACb,YAAY;CAEZ,eAAA;CAEA,aAAa;CAEb,MAAA;CAEA,SAAA;AACF,CAAC;;;ACOD,MAAa,eAAe,EAC1B,MAAM,KAAK,SAA2D;CACpE,MAAM,SAAS,MAAM,WAAuB;EAC1C,KAAK,QAAQ;EACb,MAAM,KAAK;EACX,aAAa,CAAC,KAAK,UAAU;CAC/B,CAAC;CAED,OAAO;EACL,QAAQ,OAAO;EACf,YAAY,OAAO,cAAc,KAAA;EACjC,QAAQ,OAAO,UAAU,CAAC;CAC5B;AACF,EACF;;;;;;ACtBA,MAAa,WAAW,EACtB,MAAM,IAAI,SAAiB,UAA8B,CAAC,GAAoB;CAC5E,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,QAAQ,MAAM,SAAS;GAC3B,KAAK,QAAQ;GACb,KAAK,QAAQ,OAAO,OAAO,QAAQ,MAAM;IAAE,GAAG,QAAQ;IAAK,GAAG,QAAQ;GAAI;GAC1E,OAAO;GACP,OAAO;EACT,CAAC;EAED,MAAM,GAAG,SAAS,MAAM;EACxB,MAAM,GAAG,UAAU,MAAM,WAAW;GAClC,QAAQ,SAAS,UAAU,OAAO,IAAI,IAAI;EAC5C,CAAC;CACH,CAAC;AACH,EACF;;;;;;;;ACdA,MAAa,qBAAqB,EAChC,QAAQ,EAAE,KAAK,cAA6D;CAC1E,OAAO,cAAc,IAAI,iBAAiB,SAAS,IAAI;AACzD,EACF;;;ACXA,SAAgB,eAAe,QAA4C;CACzE,MAAM,UAAqC,CAAC;CAC5C,MAAM,SAAS,OAAO,OAAO,SAAS,IAAI,OAAO,SAAS,CAAC,EAAE,QAAQ,OAAO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AAa;CAGtD,MAAM,YAAY;GACf,iBAAiB,QAAQ;GACzB,iBAAiB,YAAY,OAAO;GACpC,iBAAiB,aAAa,OAAO;GACrC,iBAAiB,MAAM;GACvB,iBAAiB,WAAW;GAC5B,iBAAiB,OAAO;CAC3B;CAEA,MAAM,WAAW,MAAM,SAAS,IAAI,aAAa;EAAE;EAAK,KAAK;CAAU,CAAC;CAExE,IAAI,aAAa,GACf,MAAM,IAAI,MAAM,WAAW,KAAK,qBAAqB,SAAS,EAAE;CAGlE,OAAO;AACT,EACF;;;;;;AAqBA,eAAsB,QAAwC,SAAmF;CAC/I,MAAM,UAAU,eAAe,QAAQ,OAAO;CAE9C,OAAO,SAAS,QAAQ,EAAE,CAAC;EACzB,GAAG;EACH;CACF,CAAC;AACH;;;AC9FA,eAAsB,UAAU,SAAmE;CACjG,OAAO,QAAQ;EACb,GAAG;EACH,GAAG;CACL,CAAC;AACH;;;;;;ACHA,MAAa,gBAAgB,OAAO,OAAO,EACzC,UACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultContext-D_QWP9aF.js","names":[],"sources":["../src/internal/Logger.ts","../src/ManagedScriptEnv.ts","../src/ManagedScript/defaultContext.ts"],"sourcesContent":["export type ColorMode = 'always' | 'auto' | 'never';\nexport type LogLevel = 'debug' | 'error' | 'info' | 'silent' | 'warn';\n\n/**\n * Rank order used to compare log levels, higher means more verbose.\n */\nconst logLevelRank: Record<LogLevel, number> = {\n debug: 4,\n error: 1,\n info: 3,\n silent: 0,\n warn: 2,\n};\n\nexport interface CreateLoggerOptions {\n readonly color?: ColorMode;\n readonly level: LogLevel;\n readonly stderr: NodeJS.WritableStream;\n readonly stdout: NodeJS.WritableStream;\n}\n\nexport interface Logger {\n debug(message: string): void;\n error(message: string): void;\n info(message: string): void;\n warn(message: string): void;\n}\n\n/**\n * Creates a logger writing to `stream`, filtering out messages above the configured `level`.\n */\nexport const Logger = {\n create({ color = 'auto', level, stderr, stdout }: CreateLoggerOptions): Logger {\n const write = (messageLevel: LogLevel, message: string) => {\n if (!(logLevelRank[messageLevel] <= logLevelRank[level])) {\n return;\n }\n // write to stderr for warnings and errors\n const outputStream = logLevelRank[messageLevel] <= logLevelRank.warn ? stderr : stdout;\n const shouldColor = color === 'always' || (color === 'auto' && 'isTTY' in outputStream && outputStream.isTTY === true);\n const colorCode = {\n debug: '\\u{1B}[36m',\n error: '\\u{1B}[31m',\n info: '\\u{1B}[32m',\n silent: '',\n warn: '\\u{1B}[33m',\n }[messageLevel];\n outputStream.write(`${shouldColor ? `${colorCode}${message}\\u{1B}[0m` : message}\\n`);\n };\n\n return {\n debug: (message) => write('debug', message),\n error: (message) => write('error', message),\n info: (message) => write('info', message),\n warn: (message) => write('warn', message),\n };\n },\n};\n","/**\n * Enum for managed script environment variables.\n *\n * @enum\n */\nexport const ManagedScriptEnv = Object.freeze({\n /**\n * The color mode used for messages.\n */\n Color: 'MANAGED_SCRIPT_COLOR',\n\n /**\n * The directory where the managed script configuration is located.\n */\n ConfigDir: 'MANAGED_SCRIPT_CONFIG_DIR',\n\n /**\n * The file where the managed script configuration is located.\n */\n ConfigFile: 'MANAGED_SCRIPT_CONFIG_FILE',\n\n /**\n * The invocation directory used to resolve configuration and spawn the script.\n */\n Cwd: 'MANAGED_SCRIPT_CWD',\n\n /**\n * The resolved log level.\n */\n LogLevel: 'MANAGED_SCRIPT_LOGLEVEL',\n\n /**\n * The name of the managed script.\n */\n Name: 'MANAGED_SCRIPT_NAME',\n});\nexport type ManagedScriptEnv = typeof ManagedScriptEnv[keyof typeof ManagedScriptEnv];\n","import type { LogLevel } from '../internal/Logger.js';\nimport type { CommandContext } from '../type.js';\n\nimport { ManagedScriptEnv } from '../ManagedScriptEnv.js';\n\nexport function defaultContext(context: Partial<CommandContext> | undefined): CommandContext {\n const {\n cli = {},\n color,\n cwd,\n dryRun,\n env = process.env,\n logLevel,\n stderr = process.stderr,\n stdout = process.stdout,\n } = context ?? {};\n const envLogLevel = env[ManagedScriptEnv.LogLevel];\n return {\n cli,\n color: color ?? cli.color ?? 'auto',\n cwd: cwd ?? cli.cwd ?? env[ManagedScriptEnv.Cwd] ?? process.cwd(),\n dryRun: dryRun ?? cli.dryRun ?? false,\n env,\n logLevel: logLevel ?? cli.logLevel ?? (isLogLevel(envLogLevel) ? envLogLevel : 'info'),\n stderr,\n stdout,\n };\n}\n\nconst knownLogLevels = new Set<LogLevel>(['debug', 'error', 'info', 'silent', 'warn']);\n\nfunction isLogLevel(value: string | undefined): value is LogLevel {\n return knownLogLevels.has(value as LogLevel);\n}\n"],"mappings":";;;;AAMA,MAAM,eAAyC;CAC7C,OAAO;CACP,OAAO;CACP,MAAM;CACN,QAAQ;CACR,MAAM;AACR;;;;AAmBA,MAAa,SAAS,EACpB,OAAO,EAAE,QAAQ,QAAQ,OAAO,QAAQ,UAAuC;CAC7E,MAAM,SAAS,cAAwB,YAAoB;EACzD,IAAI,EAAE,aAAa,iBAAiB,aAAa,SAC/C;EAGF,MAAM,eAAe,aAAa,iBAAiB,aAAa,OAAO,SAAS;EAChF,MAAM,cAAc,UAAU,YAAa,UAAU,UAAU,WAAW,gBAAgB,aAAa,UAAU;EACjH,MAAM,YAAY;GAChB,OAAO;GACP,OAAO;GACP,MAAM;GACN,QAAQ;GACR,MAAM;EACR,EAAE;EACF,aAAa,MAAM,GAAG,cAAc,GAAG,YAAY,QAAQ,aAAa,QAAQ,GAAG;CACrF;CAEA,OAAO;EACL,QAAQ,YAAY,MAAM,SAAS,OAAO;EAC1C,QAAQ,YAAY,MAAM,SAAS,OAAO;EAC1C,OAAO,YAAY,MAAM,QAAQ,OAAO;EACxC,OAAO,YAAY,MAAM,QAAQ,OAAO;CAC1C;AACF,EACF;;;;;;;;ACpDA,MAAa,mBAAmB,OAAO,OAAO;;;;CAI5C,OAAO;;;;CAKP,WAAW;;;;CAKX,YAAY;;;;CAKZ,KAAK;;;;CAKL,UAAU;;;;CAKV,MAAM;AACR,CAAC;;;AC9BD,SAAgB,eAAe,SAA8D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