printable-shell-command 0.1.0-pre1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # `printable-shell-command`
2
+
3
+ A helper class to construct shell commands in a way that allows printing them.
4
+
5
+ The goal is to make it easy to print commands that are being run by a program, in a way that makes it easy and safe for a user to copy-and-paste.
6
+
7
+ ## Goals
8
+
9
+ 1. Security — the printed commands should be possible to use in all shells without injection vulnerabilities.
10
+ 2. Fidelity — the printed command must match the arguments provided.
11
+ 3. Aesthetics — the command is pretty-printed to make it easy to read and to avoid escaping/quoting simple arguments where humans usually would not.
12
+
13
+ Point 1 is difficult, and maybe even impossible. This library will do its best, but what you don't know can hurt you.
14
+
15
+ ## Usage
16
+
17
+ Construct a command by providing a command string and a list of arguments. Each argument can either be an individual string, or a "pair" list containing two strings (usually a command flag and its argument). Pairs do not affect the semantics of the command, but they affect pretty-printing.
18
+
19
+ ```typescript
20
+ // example.ts
21
+ import { PrintableShellCommand } from "printable-shell-command";
22
+
23
+ export const command = new PrintableShellCommand("ffmpeg", [
24
+ ["-i", "./test/My video.mp4"],
25
+ ["-filter:v", "setpts=2.0*PTS"],
26
+ ["-filter:a", "atempo=0.5"],
27
+ "./test/My video (slow-mo).mov",
28
+ ]);
29
+
30
+ command.print();
31
+ ```
32
+
33
+ This prints:
34
+
35
+ ```shell
36
+ ffmpeg \
37
+ -i './test/My video.mp4' \
38
+ -filter:v 'setpts=2.0*PTS' \
39
+ -filter:a atempo=0.5 \
40
+ './test/My video (slow-mo).mov'
41
+ ```
42
+
43
+ ### Spawn a process in `node`
44
+
45
+ ```typescript
46
+ import { PrintableShellCommand } from "printable-shell-command";
47
+ import { spawn } from "node:child_process";
48
+
49
+ const command = new PrintableShellCommand(/* … */);
50
+ const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`
51
+
52
+ // or directly
53
+ await command.spawnNode().success;
54
+ await command.spawnNodeInherit().success;
55
+ ```
56
+
57
+ ### Spawn a process in `bun`
58
+
59
+ ```typescript
60
+ import { PrintableShellCommand } from "printable-shell-command";
61
+ import { spawn } from "bun";
62
+
63
+ const command = new PrintableShellCommand(/* … */);
64
+ await spawn(command.toFlatCommand()).exited;
65
+
66
+ // or directly
67
+ await command.spawnBun().success;
68
+ await command.spawnBunInherit().success;
69
+ ```
70
+
71
+ ## Protections
72
+
73
+ Any command or argument containing the following characters is quoted and escaped:
74
+
75
+ - <code> </code> (space character)
76
+ - `"` (double quote)
77
+ - `'` (single quote)
78
+ - <code>`</code> (backtick)
79
+ - `|`
80
+ - `$`
81
+ - `*`
82
+ - `?`
83
+ - `>`
84
+ - `<`
85
+ - `(`
86
+ - `)`
87
+ - `[`
88
+ - `]`
89
+ - `{`
90
+ - `}`
91
+ - `&`
92
+ - `\`
93
+ - `;`
94
+
95
+ Additionally, a command is escaped if it contains an `=`.
96
+
97
+ Escaping is done as follows:
98
+
99
+ - The command is single-quoted.
100
+ - Backslashes and single quotes are escaped.
@@ -0,0 +1,73 @@
1
+ import type { ChildProcess as NodeChildProcess, SpawnOptions as NodeSpawnOptions, SpawnOptionsWithStdioTuple as NodeSpawnOptionsWithStdioTuple, SpawnOptionsWithoutStdio as NodeSpawnOptionsWithoutStdio, StdioNull as NodeStdioNull, StdioPipe as NodeStdioPipe } from "node:child_process";
2
+ import type { SpawnOptions as BunSpawnOptions, Subprocess as BunSubprocess } from "bun";
3
+ type SingleArgument = string;
4
+ type FlagArgumentPair = [string, string];
5
+ type ArgsEntry = SingleArgument | FlagArgumentPair;
6
+ type Args = ArgsEntry[];
7
+ export interface PrintOptions {
8
+ mainIndentation?: string;
9
+ argIndentation?: string;
10
+ quoting?: "auto" | "extra-safe";
11
+ argumentLineWrapping?: "by-entry" | "nested-by-entry" | "by-argument" | "inline";
12
+ }
13
+ export declare class PrintableShellCommand {
14
+ #private;
15
+ private args;
16
+ constructor(commandName: string, args?: Args);
17
+ get commandName(): string;
18
+ toFlatCommand(): string[];
19
+ forBun(): string[];
20
+ toCommandWithFlatArgs(): [string, string[]];
21
+ forNode(): [string, string[]];
22
+ getPrintableCommand(options?: PrintOptions): string;
23
+ print(options?: PrintOptions): PrintableShellCommand;
24
+ /**
25
+ * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
26
+ */
27
+ spawnNode<Stdin extends NodeStdioNull | NodeStdioPipe, Stdout extends NodeStdioNull | NodeStdioPipe, Stderr extends NodeStdioNull | NodeStdioPipe>(options?: NodeSpawnOptions | NodeSpawnOptionsWithoutStdio | NodeSpawnOptionsWithStdioTuple<Stdin, Stdout, Stderr>): // TODO: figure out how to return `ChildProcessByStdio<…>` without duplicating fragile boilerplate.
28
+ NodeChildProcess & {
29
+ success: Promise<void>;
30
+ };
31
+ /** A wrapper for `.spawnNode(…)` that sets stdio to `"inherit"` (common for
32
+ * invoking commands from scripts whose output and interaction should be
33
+ * surfaced to the user). */
34
+ spawnNodeInherit(options?: Omit<NodeSpawnOptions, "stdio">): NodeChildProcess & {
35
+ success: Promise<void>;
36
+ };
37
+ /** Equivalent to:
38
+ *
39
+ * ```
40
+ * await this.print().spawnNodeInherit().success;
41
+ * ```
42
+ */
43
+ shellOutNode(options?: Omit<NodeSpawnOptions, "stdio">): Promise<void>;
44
+ /**
45
+ * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
46
+ */
47
+ spawnBun<const In extends BunSpawnOptions.Writable = "ignore", const Out extends BunSpawnOptions.Readable = "pipe", const Err extends BunSpawnOptions.Readable = "inherit">(options?: Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, "cmd">): BunSubprocess<In, Out, Err> & {
48
+ success: Promise<void>;
49
+ };
50
+ /**
51
+ * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
52
+ * for invoking commands from scripts whose output and interaction should be
53
+ * surfaced to the user).
54
+ */
55
+ spawnBunInherit(options?: Omit<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd">, "stdio">): BunSubprocess<"inherit", "inherit", "inherit"> & {
56
+ success: Promise<void>;
57
+ };
58
+ /** Equivalent to:
59
+ *
60
+ * ```
61
+ * new Response(this.spawnBun(options).stdout);
62
+ * ```
63
+ */
64
+ spawnBunStdout(options?: Omit<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd">, "stdio">): Response;
65
+ /** Equivalent to:
66
+ *
67
+ * ```
68
+ * await this.print().spawnBunInherit().success;
69
+ * ```
70
+ */
71
+ shellOutBun(options?: Omit<Omit<BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">, "cmd">, "stdio">): Promise<void>;
72
+ }
73
+ export {};
@@ -0,0 +1,305 @@
1
+ // src/index.ts
2
+ var DEFAULT_MAIN_INDENTATION = "";
3
+ var DEFAULT_ARG_INDENTATION = " ";
4
+ var DEFAULT_ARGUMENT_LINE_WRAPPING = "by-entry";
5
+ var INLINE_SEPARATOR = " ";
6
+ var LINE_WRAP_LINE_END = " \\\n";
7
+ function isString(s) {
8
+ return typeof s === "string";
9
+ }
10
+ var SPECIAL_SHELL_CHARACTERS = /* @__PURE__ */ new Set([
11
+ " ",
12
+ '"',
13
+ "'",
14
+ "`",
15
+ "|",
16
+ "$",
17
+ "*",
18
+ "?",
19
+ ">",
20
+ "<",
21
+ "(",
22
+ ")",
23
+ "[",
24
+ "]",
25
+ "{",
26
+ "}",
27
+ "&",
28
+ "\\",
29
+ ";"
30
+ ]);
31
+ var SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND = (
32
+ // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)
33
+ SPECIAL_SHELL_CHARACTERS.union(/* @__PURE__ */ new Set(["="]))
34
+ );
35
+ var PrintableShellCommand = class {
36
+ constructor(commandName, args = []) {
37
+ this.args = args;
38
+ if (!isString(commandName)) {
39
+ throw new Error("Command name is not a string:", commandName);
40
+ }
41
+ this.#commandName = commandName;
42
+ if (typeof args === "undefined") {
43
+ return;
44
+ }
45
+ if (!Array.isArray(args)) {
46
+ throw new Error("Command arguments are not an array");
47
+ }
48
+ for (let i = 0; i < args.length; i++) {
49
+ const argEntry = args[i];
50
+ if (typeof argEntry === "string") {
51
+ continue;
52
+ }
53
+ if (Array.isArray(argEntry) && argEntry.length === 2 && isString(argEntry[0]) && isString(argEntry[1])) {
54
+ continue;
55
+ }
56
+ throw new Error(`Invalid arg entry at index: ${i}`);
57
+ }
58
+ }
59
+ #commandName;
60
+ get commandName() {
61
+ return this.#commandName;
62
+ }
63
+ // For use with `bun`.
64
+ //
65
+ // Usage example:
66
+ //
67
+ // import { PrintableShellCommand } from "printable-shell-command";
68
+ // import { spawn } from "bun";
69
+ //
70
+ // const command = new PrintableShellCommand(/* … */);
71
+ // await spawn(command.toFlatCommand()).exited;
72
+ //
73
+ toFlatCommand() {
74
+ return [this.commandName, ...this.args.flat()];
75
+ }
76
+ // Convenient alias for `toFlatCommand()`.
77
+ //
78
+ // Usage example:
79
+ //
80
+ // import { PrintableShellCommand } from "printable-shell-command";
81
+ // import { spawn } from "bun";
82
+ //
83
+ // const command = new PrintableShellCommand(/* … */);
84
+ // await spawn(command.forBun()).exited;
85
+ //
86
+ forBun() {
87
+ return this.toFlatCommand();
88
+ }
89
+ // For use with `node:child_process`
90
+ //
91
+ // Usage example:
92
+ //
93
+ // import { PrintableShellCommand } from "printable-shell-command";
94
+ // import { spawn } from "node:child_process";
95
+ //
96
+ // const command = new PrintableShellCommand(/* … */);
97
+ // const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`
98
+ //
99
+ toCommandWithFlatArgs() {
100
+ return [this.commandName, this.args.flat()];
101
+ }
102
+ // For use with `node:child_process`
103
+ //
104
+ // Usage example:
105
+ //
106
+ // import { PrintableShellCommand } from "printable-shell-command";
107
+ // import { spawn } from "node:child_process";
108
+ //
109
+ // const command = new PrintableShellCommand(/* … */);
110
+ // const child_process = spawn(...command.forNode()); // Note the `...`
111
+ //
112
+ // Convenient alias for `toCommandWithFlatArgs()`.
113
+ forNode() {
114
+ return this.toCommandWithFlatArgs();
115
+ }
116
+ #escapeArg(arg, isMainCommand, options) {
117
+ const argCharacters = new Set(arg);
118
+ const specialShellCharacters = isMainCommand ? SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND : SPECIAL_SHELL_CHARACTERS;
119
+ if (options?.quoting === "extra-safe" || // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)
120
+ argCharacters.intersection(specialShellCharacters).size > 0) {
121
+ const escaped = arg.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
122
+ return `'${escaped}'`;
123
+ }
124
+ return arg;
125
+ }
126
+ #mainIndentation(options) {
127
+ return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;
128
+ }
129
+ #argIndentation(options) {
130
+ return this.#mainIndentation(options) + (options?.argIndentation ?? DEFAULT_ARG_INDENTATION);
131
+ }
132
+ #lineWrapSeparator(options) {
133
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
134
+ }
135
+ #argPairSeparator(options) {
136
+ switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
137
+ case "by-entry": {
138
+ return INLINE_SEPARATOR;
139
+ }
140
+ case "nested-by-entry": {
141
+ return this.#lineWrapSeparator(options) + this.#argIndentation(options);
142
+ }
143
+ case "by-argument": {
144
+ return this.#lineWrapSeparator(options);
145
+ }
146
+ case "inline": {
147
+ return INLINE_SEPARATOR;
148
+ }
149
+ default:
150
+ throw new Error("Invalid argument line wrapping argument.");
151
+ }
152
+ }
153
+ #entrySeparator(options) {
154
+ switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
155
+ case "by-entry": {
156
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
157
+ }
158
+ case "nested-by-entry": {
159
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
160
+ }
161
+ case "by-argument": {
162
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
163
+ }
164
+ case "inline": {
165
+ return INLINE_SEPARATOR;
166
+ }
167
+ default:
168
+ throw new Error("Invalid argument line wrapping argument.");
169
+ }
170
+ }
171
+ getPrintableCommand(options) {
172
+ options ??= {};
173
+ const serializedEntries = [];
174
+ serializedEntries.push(
175
+ this.#mainIndentation(options) + this.#escapeArg(this.commandName, true, options)
176
+ );
177
+ for (let i = 0; i < this.args.length; i++) {
178
+ const argsEntry = this.args[i];
179
+ if (isString(argsEntry)) {
180
+ serializedEntries.push(this.#escapeArg(argsEntry, false, options));
181
+ } else {
182
+ const [part1, part2] = argsEntry;
183
+ serializedEntries.push(
184
+ this.#escapeArg(part1, false, options) + this.#argPairSeparator(options) + this.#escapeArg(part2, false, options)
185
+ );
186
+ }
187
+ }
188
+ return serializedEntries.join(this.#entrySeparator(options));
189
+ }
190
+ print(options) {
191
+ console.log(this.getPrintableCommand(options));
192
+ return this;
193
+ }
194
+ /**
195
+ * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
196
+ */
197
+ spawnNode(options) {
198
+ const { spawn } = process.getBuiltinModule("node:child_process");
199
+ const subprocess = spawn(...this.forNode(), options);
200
+ Object.defineProperty(subprocess, "success", {
201
+ get() {
202
+ return new Promise(
203
+ (resolve, reject) => this.addListener(
204
+ "exit",
205
+ (exitCode) => {
206
+ if (exitCode === 0) {
207
+ resolve();
208
+ } else {
209
+ reject(`Command failed with non-zero exit code: ${exitCode}`);
210
+ }
211
+ }
212
+ )
213
+ );
214
+ },
215
+ enumerable: false
216
+ });
217
+ return subprocess;
218
+ }
219
+ /** A wrapper for `.spawnNode(…)` that sets stdio to `"inherit"` (common for
220
+ * invoking commands from scripts whose output and interaction should be
221
+ * surfaced to the user). */
222
+ spawnNodeInherit(options) {
223
+ if (options && "stdio" in options) {
224
+ throw new Error("Unexpected `stdio` field.");
225
+ }
226
+ return this.spawnNode({ ...options, stdio: "inherit" });
227
+ }
228
+ /** Equivalent to:
229
+ *
230
+ * ```
231
+ * await this.print().spawnNodeInherit().success;
232
+ * ```
233
+ */
234
+ async shellOutNode(options) {
235
+ await this.print().spawnNodeInherit(options).success;
236
+ }
237
+ /**
238
+ * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
239
+ */
240
+ spawnBun(options) {
241
+ if (options && "cmd" in options) {
242
+ throw new Error("Unexpected `cmd` field.");
243
+ }
244
+ const { spawn } = process.getBuiltinModule("bun");
245
+ const subprocess = spawn({
246
+ ...options,
247
+ cmd: this.forBun()
248
+ });
249
+ Object.defineProperty(subprocess, "success", {
250
+ get() {
251
+ return new Promise(
252
+ (resolve, reject) => this.exited.then((exitCode) => {
253
+ if (exitCode === 0) {
254
+ resolve();
255
+ } else {
256
+ reject(
257
+ new Error(
258
+ `Command failed with non-zero exit code: ${exitCode}`
259
+ )
260
+ );
261
+ }
262
+ }).catch(reject)
263
+ );
264
+ },
265
+ enumerable: false
266
+ });
267
+ return subprocess;
268
+ }
269
+ /**
270
+ * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
271
+ * for invoking commands from scripts whose output and interaction should be
272
+ * surfaced to the user).
273
+ */
274
+ spawnBunInherit(options) {
275
+ if (options && "stdio" in options) {
276
+ throw new Error("Unexpected `stdio` field.");
277
+ }
278
+ return this.spawnBun({
279
+ ...options,
280
+ stdio: ["inherit", "inherit", "inherit"]
281
+ });
282
+ }
283
+ /** Equivalent to:
284
+ *
285
+ * ```
286
+ * new Response(this.spawnBun(options).stdout);
287
+ * ```
288
+ */
289
+ spawnBunStdout(options) {
290
+ return new Response(this.spawnBun(options).stdout);
291
+ }
292
+ /** Equivalent to:
293
+ *
294
+ * ```
295
+ * await this.print().spawnBunInherit().success;
296
+ * ```
297
+ */
298
+ async shellOutBun(options) {
299
+ await this.print().spawnBunInherit(options).success;
300
+ }
301
+ };
302
+ export {
303
+ PrintableShellCommand
304
+ };
305
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/index.ts"],
4
+ "sourcesContent": ["import type {\n\tChildProcess as NodeChildProcess,\n\tSpawnOptions as NodeSpawnOptions,\n\tSpawnOptionsWithStdioTuple as NodeSpawnOptionsWithStdioTuple,\n\tSpawnOptionsWithoutStdio as NodeSpawnOptionsWithoutStdio,\n\tStdioNull as NodeStdioNull,\n\tStdioPipe as NodeStdioPipe,\n} from \"node:child_process\";\nimport type {\n\tSpawnOptions as BunSpawnOptions,\n\tSubprocess as BunSubprocess,\n} from \"bun\";\n\nconst DEFAULT_MAIN_INDENTATION = \"\";\nconst DEFAULT_ARG_INDENTATION = \" \";\nconst DEFAULT_ARGUMENT_LINE_WRAPPING = \"by-entry\";\n\nconst INLINE_SEPARATOR = \" \";\nconst LINE_WRAP_LINE_END = \" \\\\\\n\";\n\n// biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.\nfunction isString(s: any): s is string {\n\treturn typeof s === \"string\";\n}\n\n// TODO: allow `.toString()`ables?\ntype SingleArgument = string;\ntype FlagArgumentPair = [string, string];\ntype ArgsEntry = SingleArgument | FlagArgumentPair;\ntype Args = ArgsEntry[];\n\nexport interface PrintOptions {\n\tmainIndentation?: string; // Defaults to \"\"\n\targIndentation?: string; // Defaults to \" \"\n\t// - \"auto\": Quote only arguments that need it for safety. This tries to be\n\t// portable and safe across shells, but true safety and portability is hard\n\t// to guarantee.\n\t// - \"extra-safe\": Quote all arguments, even ones that don't need it. This is\n\t// more likely to be safe under all circumstances.\n\tquoting?: \"auto\" | \"extra-safe\";\n\t// Line wrapping to use between arguments. Defaults to `\"by-entry\"`.\n\targumentLineWrapping?:\n\t\t| \"by-entry\"\n\t\t| \"nested-by-entry\"\n\t\t| \"by-argument\"\n\t\t| \"inline\";\n}\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS = new Set([\n\t\" \",\n\t'\"',\n\t\"'\",\n\t\"`\",\n\t\"|\",\n\t\"$\",\n\t\"*\",\n\t\"?\",\n\t\">\",\n\t\"<\",\n\t\"(\",\n\t\")\",\n\t\"[\",\n\t\"]\",\n\t\"{\",\n\t\"}\",\n\t\"&\",\n\t\"\\\\\",\n\t\";\",\n]);\n\n// https://mywiki.wooledge.org/BashGuide/SpecialCharacters\nconst SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND =\n\t// biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n\t(SPECIAL_SHELL_CHARACTERS as unknown as any).union(new Set([\"=\"]));\n\nexport class PrintableShellCommand {\n\t#commandName: string;\n\tconstructor(\n\t\tcommandName: string,\n\t\tprivate args: Args = [],\n\t) {\n\t\tif (!isString(commandName)) {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: We want to print this, no matter what it is.\n\t\t\tthrow new Error(\"Command name is not a string:\", commandName as any);\n\t\t}\n\t\tthis.#commandName = commandName;\n\t\tif (typeof args === \"undefined\") {\n\t\t\treturn;\n\t\t}\n\t\tif (!Array.isArray(args)) {\n\t\t\tthrow new Error(\"Command arguments are not an array\");\n\t\t}\n\t\tfor (let i = 0; i < args.length; i++) {\n\t\t\tconst argEntry = args[i];\n\t\t\tif (typeof argEntry === \"string\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tArray.isArray(argEntry) &&\n\t\t\t\targEntry.length === 2 &&\n\t\t\t\tisString(argEntry[0]) &&\n\t\t\t\tisString(argEntry[1])\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthrow new Error(`Invalid arg entry at index: ${i}`);\n\t\t}\n\t}\n\n\tget commandName(): string {\n\t\treturn this.#commandName;\n\t}\n\n\t// For use with `bun`.\n\t//\n\t// Usage example:\n\t//\n\t// import { PrintableShellCommand } from \"printable-shell-command\";\n\t// import { spawn } from \"bun\";\n\t//\n\t// const command = new PrintableShellCommand(/* \u2026 */);\n\t// await spawn(command.toFlatCommand()).exited;\n\t//\n\tpublic toFlatCommand(): string[] {\n\t\treturn [this.commandName, ...this.args.flat()];\n\t}\n\n\t// Convenient alias for `toFlatCommand()`.\n\t//\n\t// Usage example:\n\t//\n\t// import { PrintableShellCommand } from \"printable-shell-command\";\n\t// import { spawn } from \"bun\";\n\t//\n\t// const command = new PrintableShellCommand(/* \u2026 */);\n\t// await spawn(command.forBun()).exited;\n\t//\n\tpublic forBun(): string[] {\n\t\treturn this.toFlatCommand();\n\t}\n\n\t// For use with `node:child_process`\n\t//\n\t// Usage example:\n\t//\n\t// import { PrintableShellCommand } from \"printable-shell-command\";\n\t// import { spawn } from \"node:child_process\";\n\t//\n\t// const command = new PrintableShellCommand(/* \u2026 */);\n\t// const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`\n\t//\n\tpublic toCommandWithFlatArgs(): [string, string[]] {\n\t\treturn [this.commandName, this.args.flat()];\n\t}\n\n\t// For use with `node:child_process`\n\t//\n\t// Usage example:\n\t//\n\t// import { PrintableShellCommand } from \"printable-shell-command\";\n\t// import { spawn } from \"node:child_process\";\n\t//\n\t// const command = new PrintableShellCommand(/* \u2026 */);\n\t// const child_process = spawn(...command.forNode()); // Note the `...`\n\t//\n\t// Convenient alias for `toCommandWithFlatArgs()`.\n\tpublic forNode(): [string, string[]] {\n\t\treturn this.toCommandWithFlatArgs();\n\t}\n\n\t#escapeArg(\n\t\targ: string,\n\t\tisMainCommand: boolean,\n\t\toptions: PrintOptions,\n\t): string {\n\t\tconst argCharacters = new Set(arg);\n\t\tconst specialShellCharacters = isMainCommand\n\t\t\t? SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND\n\t\t\t: SPECIAL_SHELL_CHARACTERS;\n\t\tif (\n\t\t\toptions?.quoting === \"extra-safe\" ||\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)\n\t\t\t(argCharacters as unknown as any).intersection(specialShellCharacters)\n\t\t\t\t.size > 0\n\t\t) {\n\t\t\t// Use single quote to reduce the need to escape (and therefore reduce the chance for bugs/security issues).\n\t\t\tconst escaped = arg.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"'\", \"\\\\'\");\n\t\t\treturn `'${escaped}'`;\n\t\t}\n\t\treturn arg;\n\t}\n\n\t#mainIndentation(options: PrintOptions): string {\n\t\treturn options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;\n\t}\n\n\t#argIndentation(options: PrintOptions): string {\n\t\treturn (\n\t\t\tthis.#mainIndentation(options) +\n\t\t\t(options?.argIndentation ?? DEFAULT_ARG_INDENTATION)\n\t\t);\n\t}\n\n\t#lineWrapSeparator(options: PrintOptions): string {\n\t\treturn LINE_WRAP_LINE_END + this.#argIndentation(options);\n\t}\n\n\t#argPairSeparator(options: PrintOptions): string {\n\t\tswitch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n\t\t\tcase \"by-entry\": {\n\t\t\t\treturn INLINE_SEPARATOR;\n\t\t\t}\n\t\t\tcase \"nested-by-entry\": {\n\t\t\t\treturn this.#lineWrapSeparator(options) + this.#argIndentation(options);\n\t\t\t}\n\t\t\tcase \"by-argument\": {\n\t\t\t\treturn this.#lineWrapSeparator(options);\n\t\t\t}\n\t\t\tcase \"inline\": {\n\t\t\t\treturn INLINE_SEPARATOR;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Invalid argument line wrapping argument.\");\n\t\t}\n\t}\n\n\t#entrySeparator(options: PrintOptions): string {\n\t\tswitch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {\n\t\t\tcase \"by-entry\": {\n\t\t\t\treturn LINE_WRAP_LINE_END + this.#argIndentation(options);\n\t\t\t}\n\t\t\tcase \"nested-by-entry\": {\n\t\t\t\treturn LINE_WRAP_LINE_END + this.#argIndentation(options);\n\t\t\t}\n\t\t\tcase \"by-argument\": {\n\t\t\t\treturn LINE_WRAP_LINE_END + this.#argIndentation(options);\n\t\t\t}\n\t\t\tcase \"inline\": {\n\t\t\t\treturn INLINE_SEPARATOR;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error(\"Invalid argument line wrapping argument.\");\n\t\t}\n\t}\n\n\tpublic getPrintableCommand(options?: PrintOptions): string {\n\t\t// TODO: Why in the world does TypeScript not give the `options` arg the type of `PrintOptions | undefined`???\n\t\t// biome-ignore lint/style/noParameterAssign: We want a default assignment without affecting the signature.\n\t\toptions ??= {};\n\t\tconst serializedEntries: string[] = [];\n\n\t\tserializedEntries.push(\n\t\t\tthis.#mainIndentation(options) +\n\t\t\t\tthis.#escapeArg(this.commandName, true, options),\n\t\t);\n\n\t\tfor (let i = 0; i < this.args.length; i++) {\n\t\t\tconst argsEntry = this.args[i];\n\n\t\t\tif (isString(argsEntry)) {\n\t\t\t\tserializedEntries.push(this.#escapeArg(argsEntry, false, options));\n\t\t\t} else {\n\t\t\t\tconst [part1, part2] = argsEntry;\n\t\t\t\tserializedEntries.push(\n\t\t\t\t\tthis.#escapeArg(part1, false, options) +\n\t\t\t\t\t\tthis.#argPairSeparator(options) +\n\t\t\t\t\t\tthis.#escapeArg(part2, false, options),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn serializedEntries.join(this.#entrySeparator(options));\n\t}\n\n\tpublic print(options?: PrintOptions): PrintableShellCommand {\n\t\tconsole.log(this.getPrintableCommand(options));\n\t\treturn this;\n\t}\n\n\t/**\n\t * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313\n\t */\n\tpublic spawnNode<\n\t\tStdin extends NodeStdioNull | NodeStdioPipe,\n\t\tStdout extends NodeStdioNull | NodeStdioPipe,\n\t\tStderr extends NodeStdioNull | NodeStdioPipe,\n\t>(\n\t\toptions?:\n\t\t\t| NodeSpawnOptions\n\t\t\t| NodeSpawnOptionsWithoutStdio\n\t\t\t| NodeSpawnOptionsWithStdioTuple<Stdin, Stdout, Stderr>,\n\t): // TODO: figure out how to return `ChildProcessByStdio<\u2026>` without duplicating fragile boilerplate.\n\tNodeChildProcess & { success: Promise<void> } {\n\t\tconst { spawn } = process.getBuiltinModule(\"node:child_process\");\n\t\t// @ts-ignore: The TypeScript checker has trouble reconciling the optional (i.e. potentially `undefined`) `options` with the third argument.\n\t\tconst subprocess = spawn(...this.forNode(), options) as NodeChildProcess & {\n\t\t\tsuccess: Promise<void>;\n\t\t};\n\t\tObject.defineProperty(subprocess, \"success\", {\n\t\t\tget() {\n\t\t\t\treturn new Promise<void>((resolve, reject) =>\n\t\t\t\t\tthis.addListener(\n\t\t\t\t\t\t\"exit\",\n\t\t\t\t\t\t(exitCode: number /* we only use the first arg */) => {\n\t\t\t\t\t\t\tif (exitCode === 0) {\n\t\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treject(`Command failed with non-zero exit code: ${exitCode}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t});\n\t\treturn subprocess;\n\t}\n\n\t/** A wrapper for `.spawnNode(\u2026)` that sets stdio to `\"inherit\"` (common for\n\t * invoking commands from scripts whose output and interaction should be\n\t * surfaced to the user). */\n\tpublic spawnNodeInherit(\n\t\toptions?: Omit<NodeSpawnOptions, \"stdio\">,\n\t): NodeChildProcess & { success: Promise<void> } {\n\t\tif (options && \"stdio\" in options) {\n\t\t\tthrow new Error(\"Unexpected `stdio` field.\");\n\t\t}\n\t\treturn this.spawnNode({ ...options, stdio: \"inherit\" });\n\t}\n\n\t/** Equivalent to:\n\t *\n\t * ```\n\t * await this.print().spawnNodeInherit().success;\n\t * ```\n\t */\n\tpublic async shellOutNode(\n\t\toptions?: Omit<NodeSpawnOptions, \"stdio\">,\n\t): Promise<void> {\n\t\tawait this.print().spawnNodeInherit(options).success;\n\t}\n\n\t/**\n\t * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313\n\t */\n\tpublic spawnBun<\n\t\tconst In extends BunSpawnOptions.Writable = \"ignore\",\n\t\tconst Out extends BunSpawnOptions.Readable = \"pipe\",\n\t\tconst Err extends BunSpawnOptions.Readable = \"inherit\",\n\t>(\n\t\toptions?: Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, \"cmd\">,\n\t): BunSubprocess<In, Out, Err> & { success: Promise<void> } {\n\t\tif (options && \"cmd\" in options) {\n\t\t\tthrow new Error(\"Unexpected `cmd` field.\");\n\t\t}\n\t\tconst { spawn } = process.getBuiltinModule(\"bun\") as typeof import(\"bun\");\n\t\tconst subprocess = spawn({\n\t\t\t...options,\n\t\t\tcmd: this.forBun(),\n\t\t}) as BunSubprocess<In, Out, Err> & { success: Promise<void> };\n\t\tObject.defineProperty(subprocess, \"success\", {\n\t\t\tget() {\n\t\t\t\treturn new Promise<void>((resolve, reject) =>\n\t\t\t\t\tthis.exited\n\t\t\t\t\t\t.then((exitCode: number) => {\n\t\t\t\t\t\t\tif (exitCode === 0) {\n\t\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\t`Command failed with non-zero exit code: ${exitCode}`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.catch(reject),\n\t\t\t\t);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t});\n\t\treturn subprocess;\n\t}\n\n\t/**\n\t * A wrapper for `.spawnBunInherit(\u2026)` that sets stdio to `\"inherit\"` (common\n\t * for invoking commands from scripts whose output and interaction should be\n\t * surfaced to the user).\n\t */\n\tpublic spawnBunInherit(\n\t\toptions?: Omit<\n\t\t\tOmit<\n\t\t\t\tBunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n\t\t\t\t\"cmd\"\n\t\t\t>,\n\t\t\t\"stdio\"\n\t\t>,\n\t): BunSubprocess<\"inherit\", \"inherit\", \"inherit\"> & {\n\t\tsuccess: Promise<void>;\n\t} {\n\t\tif (options && \"stdio\" in options) {\n\t\t\tthrow new Error(\"Unexpected `stdio` field.\");\n\t\t}\n\t\treturn this.spawnBun({\n\t\t\t...options,\n\t\t\tstdio: [\"inherit\", \"inherit\", \"inherit\"],\n\t\t});\n\t}\n\n\t/** Equivalent to:\n\t *\n\t * ```\n\t * new Response(this.spawnBun(options).stdout);\n\t * ```\n\t */\n\tpublic spawnBunStdout(\n\t\toptions?: Omit<\n\t\t\tOmit<\n\t\t\t\tBunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n\t\t\t\t\"cmd\"\n\t\t\t>,\n\t\t\t\"stdio\"\n\t\t>,\n\t): Response {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.\n\t\treturn new Response((this.spawnBun(options) as any).stdout);\n\t}\n\n\t/** Equivalent to:\n\t *\n\t * ```\n\t * await this.print().spawnBunInherit().success;\n\t * ```\n\t */\n\tpublic async shellOutBun(\n\t\toptions?: Omit<\n\t\t\tOmit<\n\t\t\t\tBunSpawnOptions.OptionsObject<\"inherit\", \"inherit\", \"inherit\">,\n\t\t\t\t\"cmd\"\n\t\t\t>,\n\t\t\t\"stdio\"\n\t\t>,\n\t): Promise<void> {\n\t\tawait this.print().spawnBunInherit(options).success;\n\t}\n}\n"],
5
+ "mappings": ";AAaA,IAAM,2BAA2B;AACjC,IAAM,0BAA0B;AAChC,IAAM,iCAAiC;AAEvC,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAG3B,SAAS,SAAS,GAAqB;AACtC,SAAO,OAAO,MAAM;AACrB;AA0BA,IAAM,2BAA2B,oBAAI,IAAI;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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QACf;AAAA,MACD;AAAA,MACA,YAAY;AAAA,IACb,CAAC;AACD,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,gBACN,SASC;AACD,QAAI,WAAW,WAAW,SAAS;AAClC,YAAM,IAAI,MAAM,2BAA2B;AAAA,IAC5C;AACA,WAAO,KAAK,SAAS;AAAA,MACpB,GAAG;AAAA,MACH,OAAO,CAAC,WAAW,WAAW,SAAS;AAAA,IACxC,CAAC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,eACN,SAOW;AAEX,WAAO,IAAI,SAAU,KAAK,SAAS,OAAO,EAAU,MAAM;AAAA,EAC3D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,YACZ,SAOgB;AAChB,UAAM,KAAK,MAAM,EAAE,gBAAgB,OAAO,EAAE;AAAA,EAC7C;AACD;",
6
+ "names": []
7
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "printable-shell-command",
3
+ "version": "0.1.0-pre1",
4
+ "main": "./src/index.ts",
5
+ "devDependencies": {
6
+ "@biomejs/biome": "^1.9.4",
7
+ "@cubing/dev-config": "^0.1.2",
8
+ "@types/bun": "^1.2.11",
9
+ "@types/node": "^22.15.3",
10
+ "esbuild": "^0.25.3"
11
+ },
12
+ "optionalDependencies": {
13
+ "@types/bun": "^1.2.11",
14
+ "@types/node": "^22.15.3"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/lib/printable-shell-command/index.js",
19
+ "import": "./dist/lib/printable-shell-command/index.d.ts"
20
+ }
21
+ },
22
+ "files": [
23
+ "./dist/",
24
+ "./src/"
25
+ ],
26
+ "type": "module"
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,446 @@
1
+ import type {
2
+ ChildProcess as NodeChildProcess,
3
+ SpawnOptions as NodeSpawnOptions,
4
+ SpawnOptionsWithStdioTuple as NodeSpawnOptionsWithStdioTuple,
5
+ SpawnOptionsWithoutStdio as NodeSpawnOptionsWithoutStdio,
6
+ StdioNull as NodeStdioNull,
7
+ StdioPipe as NodeStdioPipe,
8
+ } from "node:child_process";
9
+ import type {
10
+ SpawnOptions as BunSpawnOptions,
11
+ Subprocess as BunSubprocess,
12
+ } from "bun";
13
+
14
+ const DEFAULT_MAIN_INDENTATION = "";
15
+ const DEFAULT_ARG_INDENTATION = " ";
16
+ const DEFAULT_ARGUMENT_LINE_WRAPPING = "by-entry";
17
+
18
+ const INLINE_SEPARATOR = " ";
19
+ const LINE_WRAP_LINE_END = " \\\n";
20
+
21
+ // biome-ignore lint/suspicious/noExplicitAny: This is the correct type nere.
22
+ function isString(s: any): s is string {
23
+ return typeof s === "string";
24
+ }
25
+
26
+ // TODO: allow `.toString()`ables?
27
+ type SingleArgument = string;
28
+ type FlagArgumentPair = [string, string];
29
+ type ArgsEntry = SingleArgument | FlagArgumentPair;
30
+ type Args = ArgsEntry[];
31
+
32
+ export interface PrintOptions {
33
+ mainIndentation?: string; // Defaults to ""
34
+ argIndentation?: string; // Defaults to " "
35
+ // - "auto": Quote only arguments that need it for safety. This tries to be
36
+ // portable and safe across shells, but true safety and portability is hard
37
+ // to guarantee.
38
+ // - "extra-safe": Quote all arguments, even ones that don't need it. This is
39
+ // more likely to be safe under all circumstances.
40
+ quoting?: "auto" | "extra-safe";
41
+ // Line wrapping to use between arguments. Defaults to `"by-entry"`.
42
+ argumentLineWrapping?:
43
+ | "by-entry"
44
+ | "nested-by-entry"
45
+ | "by-argument"
46
+ | "inline";
47
+ }
48
+
49
+ // https://mywiki.wooledge.org/BashGuide/SpecialCharacters
50
+ const SPECIAL_SHELL_CHARACTERS = new Set([
51
+ " ",
52
+ '"',
53
+ "'",
54
+ "`",
55
+ "|",
56
+ "$",
57
+ "*",
58
+ "?",
59
+ ">",
60
+ "<",
61
+ "(",
62
+ ")",
63
+ "[",
64
+ "]",
65
+ "{",
66
+ "}",
67
+ "&",
68
+ "\\",
69
+ ";",
70
+ ]);
71
+
72
+ // https://mywiki.wooledge.org/BashGuide/SpecialCharacters
73
+ const SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND =
74
+ // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)
75
+ (SPECIAL_SHELL_CHARACTERS as unknown as any).union(new Set(["="]));
76
+
77
+ export class PrintableShellCommand {
78
+ #commandName: string;
79
+ constructor(
80
+ commandName: string,
81
+ private args: Args = [],
82
+ ) {
83
+ if (!isString(commandName)) {
84
+ // biome-ignore lint/suspicious/noExplicitAny: We want to print this, no matter what it is.
85
+ throw new Error("Command name is not a string:", commandName as any);
86
+ }
87
+ this.#commandName = commandName;
88
+ if (typeof args === "undefined") {
89
+ return;
90
+ }
91
+ if (!Array.isArray(args)) {
92
+ throw new Error("Command arguments are not an array");
93
+ }
94
+ for (let i = 0; i < args.length; i++) {
95
+ const argEntry = args[i];
96
+ if (typeof argEntry === "string") {
97
+ continue;
98
+ }
99
+ if (
100
+ Array.isArray(argEntry) &&
101
+ argEntry.length === 2 &&
102
+ isString(argEntry[0]) &&
103
+ isString(argEntry[1])
104
+ ) {
105
+ continue;
106
+ }
107
+ throw new Error(`Invalid arg entry at index: ${i}`);
108
+ }
109
+ }
110
+
111
+ get commandName(): string {
112
+ return this.#commandName;
113
+ }
114
+
115
+ // For use with `bun`.
116
+ //
117
+ // Usage example:
118
+ //
119
+ // import { PrintableShellCommand } from "printable-shell-command";
120
+ // import { spawn } from "bun";
121
+ //
122
+ // const command = new PrintableShellCommand(/* … */);
123
+ // await spawn(command.toFlatCommand()).exited;
124
+ //
125
+ public toFlatCommand(): string[] {
126
+ return [this.commandName, ...this.args.flat()];
127
+ }
128
+
129
+ // Convenient alias for `toFlatCommand()`.
130
+ //
131
+ // Usage example:
132
+ //
133
+ // import { PrintableShellCommand } from "printable-shell-command";
134
+ // import { spawn } from "bun";
135
+ //
136
+ // const command = new PrintableShellCommand(/* … */);
137
+ // await spawn(command.forBun()).exited;
138
+ //
139
+ public forBun(): string[] {
140
+ return this.toFlatCommand();
141
+ }
142
+
143
+ // For use with `node:child_process`
144
+ //
145
+ // Usage example:
146
+ //
147
+ // import { PrintableShellCommand } from "printable-shell-command";
148
+ // import { spawn } from "node:child_process";
149
+ //
150
+ // const command = new PrintableShellCommand(/* … */);
151
+ // const child_process = spawn(...command.toCommandWithFlatArgs()); // Note the `...`
152
+ //
153
+ public toCommandWithFlatArgs(): [string, string[]] {
154
+ return [this.commandName, this.args.flat()];
155
+ }
156
+
157
+ // For use with `node:child_process`
158
+ //
159
+ // Usage example:
160
+ //
161
+ // import { PrintableShellCommand } from "printable-shell-command";
162
+ // import { spawn } from "node:child_process";
163
+ //
164
+ // const command = new PrintableShellCommand(/* … */);
165
+ // const child_process = spawn(...command.forNode()); // Note the `...`
166
+ //
167
+ // Convenient alias for `toCommandWithFlatArgs()`.
168
+ public forNode(): [string, string[]] {
169
+ return this.toCommandWithFlatArgs();
170
+ }
171
+
172
+ #escapeArg(
173
+ arg: string,
174
+ isMainCommand: boolean,
175
+ options: PrintOptions,
176
+ ): string {
177
+ const argCharacters = new Set(arg);
178
+ const specialShellCharacters = isMainCommand
179
+ ? SPECIAL_SHELL_CHARACTERS_FOR_MAIN_COMMAND
180
+ : SPECIAL_SHELL_CHARACTERS;
181
+ if (
182
+ options?.quoting === "extra-safe" ||
183
+ // biome-ignore lint/suspicious/noExplicitAny: Workaround to make this package easier to use in a project that otherwise only uses ES2022.)
184
+ (argCharacters as unknown as any).intersection(specialShellCharacters)
185
+ .size > 0
186
+ ) {
187
+ // Use single quote to reduce the need to escape (and therefore reduce the chance for bugs/security issues).
188
+ const escaped = arg.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
189
+ return `'${escaped}'`;
190
+ }
191
+ return arg;
192
+ }
193
+
194
+ #mainIndentation(options: PrintOptions): string {
195
+ return options?.mainIndentation ?? DEFAULT_MAIN_INDENTATION;
196
+ }
197
+
198
+ #argIndentation(options: PrintOptions): string {
199
+ return (
200
+ this.#mainIndentation(options) +
201
+ (options?.argIndentation ?? DEFAULT_ARG_INDENTATION)
202
+ );
203
+ }
204
+
205
+ #lineWrapSeparator(options: PrintOptions): string {
206
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
207
+ }
208
+
209
+ #argPairSeparator(options: PrintOptions): string {
210
+ switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
211
+ case "by-entry": {
212
+ return INLINE_SEPARATOR;
213
+ }
214
+ case "nested-by-entry": {
215
+ return this.#lineWrapSeparator(options) + this.#argIndentation(options);
216
+ }
217
+ case "by-argument": {
218
+ return this.#lineWrapSeparator(options);
219
+ }
220
+ case "inline": {
221
+ return INLINE_SEPARATOR;
222
+ }
223
+ default:
224
+ throw new Error("Invalid argument line wrapping argument.");
225
+ }
226
+ }
227
+
228
+ #entrySeparator(options: PrintOptions): string {
229
+ switch (options?.argumentLineWrapping ?? DEFAULT_ARGUMENT_LINE_WRAPPING) {
230
+ case "by-entry": {
231
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
232
+ }
233
+ case "nested-by-entry": {
234
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
235
+ }
236
+ case "by-argument": {
237
+ return LINE_WRAP_LINE_END + this.#argIndentation(options);
238
+ }
239
+ case "inline": {
240
+ return INLINE_SEPARATOR;
241
+ }
242
+ default:
243
+ throw new Error("Invalid argument line wrapping argument.");
244
+ }
245
+ }
246
+
247
+ public getPrintableCommand(options?: PrintOptions): string {
248
+ // TODO: Why in the world does TypeScript not give the `options` arg the type of `PrintOptions | undefined`???
249
+ // biome-ignore lint/style/noParameterAssign: We want a default assignment without affecting the signature.
250
+ options ??= {};
251
+ const serializedEntries: string[] = [];
252
+
253
+ serializedEntries.push(
254
+ this.#mainIndentation(options) +
255
+ this.#escapeArg(this.commandName, true, options),
256
+ );
257
+
258
+ for (let i = 0; i < this.args.length; i++) {
259
+ const argsEntry = this.args[i];
260
+
261
+ if (isString(argsEntry)) {
262
+ serializedEntries.push(this.#escapeArg(argsEntry, false, options));
263
+ } else {
264
+ const [part1, part2] = argsEntry;
265
+ serializedEntries.push(
266
+ this.#escapeArg(part1, false, options) +
267
+ this.#argPairSeparator(options) +
268
+ this.#escapeArg(part2, false, options),
269
+ );
270
+ }
271
+ }
272
+
273
+ return serializedEntries.join(this.#entrySeparator(options));
274
+ }
275
+
276
+ public print(options?: PrintOptions): PrintableShellCommand {
277
+ console.log(this.getPrintableCommand(options));
278
+ return this;
279
+ }
280
+
281
+ /**
282
+ * The returned child process includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
283
+ */
284
+ public spawnNode<
285
+ Stdin extends NodeStdioNull | NodeStdioPipe,
286
+ Stdout extends NodeStdioNull | NodeStdioPipe,
287
+ Stderr extends NodeStdioNull | NodeStdioPipe,
288
+ >(
289
+ options?:
290
+ | NodeSpawnOptions
291
+ | NodeSpawnOptionsWithoutStdio
292
+ | NodeSpawnOptionsWithStdioTuple<Stdin, Stdout, Stderr>,
293
+ ): // TODO: figure out how to return `ChildProcessByStdio<…>` without duplicating fragile boilerplate.
294
+ NodeChildProcess & { success: Promise<void> } {
295
+ const { spawn } = process.getBuiltinModule("node:child_process");
296
+ // @ts-ignore: The TypeScript checker has trouble reconciling the optional (i.e. potentially `undefined`) `options` with the third argument.
297
+ const subprocess = spawn(...this.forNode(), options) as NodeChildProcess & {
298
+ success: Promise<void>;
299
+ };
300
+ Object.defineProperty(subprocess, "success", {
301
+ get() {
302
+ return new Promise<void>((resolve, reject) =>
303
+ this.addListener(
304
+ "exit",
305
+ (exitCode: number /* we only use the first arg */) => {
306
+ if (exitCode === 0) {
307
+ resolve();
308
+ } else {
309
+ reject(`Command failed with non-zero exit code: ${exitCode}`);
310
+ }
311
+ },
312
+ ),
313
+ );
314
+ },
315
+ enumerable: false,
316
+ });
317
+ return subprocess;
318
+ }
319
+
320
+ /** A wrapper for `.spawnNode(…)` that sets stdio to `"inherit"` (common for
321
+ * invoking commands from scripts whose output and interaction should be
322
+ * surfaced to the user). */
323
+ public spawnNodeInherit(
324
+ options?: Omit<NodeSpawnOptions, "stdio">,
325
+ ): NodeChildProcess & { success: Promise<void> } {
326
+ if (options && "stdio" in options) {
327
+ throw new Error("Unexpected `stdio` field.");
328
+ }
329
+ return this.spawnNode({ ...options, stdio: "inherit" });
330
+ }
331
+
332
+ /** Equivalent to:
333
+ *
334
+ * ```
335
+ * await this.print().spawnNodeInherit().success;
336
+ * ```
337
+ */
338
+ public async shellOutNode(
339
+ options?: Omit<NodeSpawnOptions, "stdio">,
340
+ ): Promise<void> {
341
+ await this.print().spawnNodeInherit(options).success;
342
+ }
343
+
344
+ /**
345
+ * The returned subprocess includes a `.success` `Promise` field, per https://github.com/oven-sh/bun/issues/8313
346
+ */
347
+ public spawnBun<
348
+ const In extends BunSpawnOptions.Writable = "ignore",
349
+ const Out extends BunSpawnOptions.Readable = "pipe",
350
+ const Err extends BunSpawnOptions.Readable = "inherit",
351
+ >(
352
+ options?: Omit<BunSpawnOptions.OptionsObject<In, Out, Err>, "cmd">,
353
+ ): BunSubprocess<In, Out, Err> & { success: Promise<void> } {
354
+ if (options && "cmd" in options) {
355
+ throw new Error("Unexpected `cmd` field.");
356
+ }
357
+ const { spawn } = process.getBuiltinModule("bun") as typeof import("bun");
358
+ const subprocess = spawn({
359
+ ...options,
360
+ cmd: this.forBun(),
361
+ }) as BunSubprocess<In, Out, Err> & { success: Promise<void> };
362
+ Object.defineProperty(subprocess, "success", {
363
+ get() {
364
+ return new Promise<void>((resolve, reject) =>
365
+ this.exited
366
+ .then((exitCode: number) => {
367
+ if (exitCode === 0) {
368
+ resolve();
369
+ } else {
370
+ reject(
371
+ new Error(
372
+ `Command failed with non-zero exit code: ${exitCode}`,
373
+ ),
374
+ );
375
+ }
376
+ })
377
+ .catch(reject),
378
+ );
379
+ },
380
+ enumerable: false,
381
+ });
382
+ return subprocess;
383
+ }
384
+
385
+ /**
386
+ * A wrapper for `.spawnBunInherit(…)` that sets stdio to `"inherit"` (common
387
+ * for invoking commands from scripts whose output and interaction should be
388
+ * surfaced to the user).
389
+ */
390
+ public spawnBunInherit(
391
+ options?: Omit<
392
+ Omit<
393
+ BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
394
+ "cmd"
395
+ >,
396
+ "stdio"
397
+ >,
398
+ ): BunSubprocess<"inherit", "inherit", "inherit"> & {
399
+ success: Promise<void>;
400
+ } {
401
+ if (options && "stdio" in options) {
402
+ throw new Error("Unexpected `stdio` field.");
403
+ }
404
+ return this.spawnBun({
405
+ ...options,
406
+ stdio: ["inherit", "inherit", "inherit"],
407
+ });
408
+ }
409
+
410
+ /** Equivalent to:
411
+ *
412
+ * ```
413
+ * new Response(this.spawnBun(options).stdout);
414
+ * ```
415
+ */
416
+ public spawnBunStdout(
417
+ options?: Omit<
418
+ Omit<
419
+ BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
420
+ "cmd"
421
+ >,
422
+ "stdio"
423
+ >,
424
+ ): Response {
425
+ // biome-ignore lint/suspicious/noExplicitAny: Avoid breaking the lib check when used without `@types/bun`.
426
+ return new Response((this.spawnBun(options) as any).stdout);
427
+ }
428
+
429
+ /** Equivalent to:
430
+ *
431
+ * ```
432
+ * await this.print().spawnBunInherit().success;
433
+ * ```
434
+ */
435
+ public async shellOutBun(
436
+ options?: Omit<
437
+ Omit<
438
+ BunSpawnOptions.OptionsObject<"inherit", "inherit", "inherit">,
439
+ "cmd"
440
+ >,
441
+ "stdio"
442
+ >,
443
+ ): Promise<void> {
444
+ await this.print().spawnBunInherit(options).success;
445
+ }
446
+ }