@goodbyenjn/utils 26.1.2 → 26.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![npm version](https://badge.fury.io/js/@goodbyenjn%2Futils.svg)](https://badge.fury.io/js/@goodbyenjn%2Futils)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- A modern TypeScript/JavaScript utility library providing a comprehensive collection of type-safe utility functions, functional error handling with the Result pattern, and filesystem operations.
6
+ A modern TypeScript/JavaScript utility library providing a comprehensive collection of type-safe utility functions, functional error handling with the Result pattern, filesystem operations, and shell command execution.
7
7
 
8
8
  ## Features
9
9
 
@@ -12,7 +12,8 @@ A modern TypeScript/JavaScript utility library providing a comprehensive collect
12
12
  - 📦 **Modular**: Import only what you need with tree-shakable exports and multiple entry points
13
13
  - 🛡️ **Result Pattern**: Functional error handling without exceptions, based on Rust-style Result types
14
14
  - 📁 **Safe File System**: Type-safe file system operations with Result-based error handling
15
- - 🧰 **Common Utilities**: String manipulation, math operations, promise utilities, shell commands, and error handling
15
+ - 🐚 **Shell Execution**: Powerful and flexible shell command execution with piping support
16
+ - 🧰 **Common Utilities**: String manipulation, math operations, promise utilities, and error handling
16
17
  - 📊 **Remeda Extensions**: Extended utilities built on top of [Remeda](https://remedajs.com/)
17
18
 
18
19
  ## Installation
@@ -31,7 +32,8 @@ yarn add @goodbyenjn/utils
31
32
 
32
33
  ```typescript
33
34
  // Import what you need from the main module
34
- import { sleep, template, $ } from "@goodbyenjn/utils";
35
+ import { sleep, template } from "@goodbyenjn/utils";
36
+ import { $ } from "@goodbyenjn/utils/shell";
35
37
  import { safeReadFile } from "@goodbyenjn/utils/fs";
36
38
  import { ok, Result } from "@goodbyenjn/utils/result";
37
39
  ```
@@ -151,30 +153,32 @@ const result = await promise;
151
153
  #### Shell Command Execution
152
154
 
153
155
  ```typescript
154
- import { $ } from "@goodbyenjn/utils";
155
-
156
- // Execute shell commands safely using template literals
157
- const result = await $`ls -la`;
158
- if (result.isOk()) {
159
- console.log("Command succeeded:");
160
- console.log("stdout:", result.unwrap().stdout);
161
- console.log("stderr:", result.unwrap().stderr);
162
- } else if (result.isErr()) {
163
- console.error("Command failed:", result.unwrapErr().message);
164
- }
156
+ import { $ } from "@goodbyenjn/utils/shell";
157
+
158
+ // Execute shell commands with template literals
159
+ const result = await $`npm install`;
160
+ console.log(result.stdout);
161
+ console.log(result.stderr);
162
+
163
+ // String command with args
164
+ const output = await $("ls", ["-la"]);
165
+ console.log(output.stdout);
165
166
 
166
- // Complex command with options
167
- const { $ } = await import("@goodbyenjn/utils");
168
- const deployResult = await $`docker build -t myapp .`;
169
- if (deployResult.isOk()) {
170
- const { stdout, stderr } = deployResult.unwrap();
171
- console.log("Build output:", stdout);
167
+ // Pipe commands
168
+ const piped = await $`echo "hello"`.pipe`cat`;
169
+ console.log(piped.stdout);
170
+
171
+ // Iterate output line by line
172
+ for await (const line of $`cat large-file.txt`) {
173
+ console.log(line);
172
174
  }
173
175
 
174
- // Using quoteShellArg for safe argument escaping
175
- import { quoteShellArg } from "@goodbyenjn/utils";
176
- const userInput = "'; rm -rf /;";
177
- const safeArg = quoteShellArg(userInput); // Properly escaped for shell
176
+ // Using options
177
+ const result2 = await $("npm", ["install"], { cwd: "/path/to/project" });
178
+
179
+ // Factory function with options
180
+ const withCwd = $({ cwd: "/path/to/project" });
181
+ const result3 = await withCwd`npm install`;
178
182
  ```
179
183
 
180
184
  #### Math Utilities
@@ -1001,7 +1001,7 @@ const unindent = (...params) => {
1001
1001
  return unindentImpl;
1002
1002
  }
1003
1003
  if (e$1(params[0]) || e$6(params[0])) return unindentImpl(...params);
1004
- throw new TypeError("Invalid arguments.");
1004
+ throw new TypeError(`First parameter has an invalid type: "${typeof params[0]}"`);
1005
1005
  };
1006
1006
  /**
1007
1007
  * @example
@@ -1051,7 +1051,7 @@ const indent = (...params) => {
1051
1051
  indentString = params[0];
1052
1052
  return indentImpl;
1053
1053
  }
1054
- throw new TypeError("Invalid arguments.");
1054
+ throw new TypeError(`First parameter has an invalid type: "${typeof params[0]}"`);
1055
1055
  };
1056
1056
  function template(str, ...args) {
1057
1057
  const [firstArg, fallback] = args;
@@ -1065,74 +1065,6 @@ function template(str, ...args) {
1065
1065
  });
1066
1066
  }
1067
1067
 
1068
- //#endregion
1069
- //#region src/common/shell.ts
1070
- const REGEXP_NULL_CHAR = /\x00+/g;
1071
- const REGEXP_SAFE_CHARS = /^[A-Za-z0-9,:=_./-]+$/;
1072
- const REGEXP_SINGLE_QUOTES = /'+/g;
1073
- const noop = () => {};
1074
- const pipeToStdout = (chunk) => process.stdout.write(chunk);
1075
- const pipeToStderr = (chunk) => process.stderr.write(chunk);
1076
- async function $(cmd, ...values) {
1077
- const { spawn } = await import("node:child_process");
1078
- const [command, options] = e$1(cmd) ? [cmd, values[0] || {}] : [concatTemplateStrings(cmd, values), {}];
1079
- const stdio = [
1080
- "inherit",
1081
- "pipe",
1082
- "pipe"
1083
- ];
1084
- let onStdin = noop;
1085
- if (options.onStdin !== void 0) {
1086
- stdio[0] = "pipe";
1087
- if (isFunction(options.onStdin)) onStdin = options.onStdin;
1088
- else {
1089
- const chunk = options.onStdin;
1090
- onStdin = (stdin) => stdin.write(chunk);
1091
- }
1092
- }
1093
- const onStdout = options.onStdout === "ignore" ? noop : options.onStdout === "print" ? pipeToStdout : options.onStdout || noop;
1094
- const onStderr = options.onStderr === "ignore" ? noop : options.onStderr === "print" ? pipeToStderr : options.onStderr || noop;
1095
- const fn = async () => {
1096
- const { promise, reject, resolve } = createPromiseWithResolvers();
1097
- const child = spawn(command, {
1098
- shell: true,
1099
- stdio
1100
- });
1101
- if (stdio[0] === "pipe" && child.stdin) {
1102
- await onStdin(child.stdin);
1103
- child.stdin?.end();
1104
- }
1105
- let stdout = "";
1106
- let stderr = "";
1107
- child.stdout?.on("data", (data) => {
1108
- const chunk = data.toString();
1109
- stdout += chunk;
1110
- onStdout(chunk);
1111
- });
1112
- child.stderr?.on("data", (data) => {
1113
- const chunk = data.toString();
1114
- stderr += chunk;
1115
- onStderr(chunk);
1116
- });
1117
- child.on("error", reject);
1118
- child.on("close", (code) => {
1119
- if (code === 0) resolve({
1120
- stdout: stdout.trim(),
1121
- stderr: stderr.trim()
1122
- });
1123
- else reject(/* @__PURE__ */ new Error(`Command exited with code ${code}`));
1124
- });
1125
- return await promise;
1126
- };
1127
- return (await Result.fromCallable(fn, Error)).context(`Failed to execute command: ${cmd}`);
1128
- }
1129
- const quoteShellArg = (arg) => {
1130
- if (!arg) return "''";
1131
- const cleaned = String(arg).replace(REGEXP_NULL_CHAR, "");
1132
- if (REGEXP_SAFE_CHARS.exec(cleaned)?.[0].length === cleaned.length) return cleaned;
1133
- return `'${cleaned.replace(REGEXP_SINGLE_QUOTES, (matched) => matched.length === 1 ? `'\\''` : `'"${matched}"'`)}'`.replace(/^''/, "").replace(/''$/, "");
1134
- };
1135
-
1136
1068
  //#endregion
1137
1069
  //#region src/common/throttle.ts
1138
1070
  const wrap = (fn, wait, options) => {
@@ -1168,4 +1100,4 @@ const throttle = (fn, wait = 0, options = {}) => {
1168
1100
  };
1169
1101
 
1170
1102
  //#endregion
1171
- export { stringify as A, parseKeyValuePairs as C, getErrorMessage as D, scale as E, safeTry as F, ResultError as I, __commonJSMin as L, Result as M, err as N, normalizeError as O, ok as P, __toESM as R, sleep as S, linear as T, toForwardSlash as _, addPrefix as a, createPromiseWithResolvers as b, indent as c, removePrefix as d, removeSuffix as f, template as g, splitWithSlash as h, quoteShellArg as i, unsafeParse as j, safeParse as k, join as l, splitByLineBreak as m, throttle as n, addSuffix as o, split as p, $ as r, concatTemplateStrings as s, debounce as t, joinWithSlash as u, unindent as v, parseValueToBoolean as w, createSingleton as x, createLock as y };
1103
+ export { Result as A, linear as C, safeParse as D, normalizeError as E, __commonJSMin as F, __toESM as I, ok as M, safeTry as N, stringify as O, ResultError as P, parseValueToBoolean as S, getErrorMessage as T, createLock as _, concatTemplateStrings as a, sleep as b, joinWithSlash as c, split as d, splitByLineBreak as f, unindent as g, toForwardSlash as h, addSuffix as i, err as j, unsafeParse as k, removePrefix as l, template as m, throttle as n, indent as o, splitWithSlash as p, addPrefix as r, join as s, debounce as t, removeSuffix as u, createPromiseWithResolvers as v, scale as w, parseKeyValuePairs as x, createSingleton as y };
package/dist/common.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { i as Result } from "./chunks/chunk-4b76d1c4.js";
2
- import { ai as Fn, on as Promisable, ri as AsyncFn } from "./chunks/chunk-a07ed28f.js";
2
+ import { ai as Fn, ri as AsyncFn } from "./chunks/chunk-a07ed28f.js";
3
3
 
4
4
  //#region src/common/error.d.ts
5
5
  declare const normalizeError: (error: unknown, caller?: Function) => Error;
@@ -82,20 +82,6 @@ declare const createSingleton: <T>(fn: AsyncFn<T>) => Singleton<T>;
82
82
  declare const createLock: () => Lock;
83
83
  declare const createPromiseWithResolvers: <T>() => PromiseWithResolvers<T>;
84
84
  //#endregion
85
- //#region src/common/shell.d.ts
86
- interface ShellExecOptions {
87
- onStdin?: string | Buffer | ((stdin: NodeJS.WritableStream) => Promisable<any>);
88
- onStdout?: "ignore" | "print" | ((chunk: string) => Promisable<any>);
89
- onStderr?: "ignore" | "print" | ((chunk: string) => Promisable<any>);
90
- }
91
- interface ShellExecResult {
92
- stdout: string;
93
- stderr: string;
94
- }
95
- declare function $(cmd: string, options?: ShellExecOptions): Promise<Result<ShellExecResult, Error>>;
96
- declare function $(cmd: TemplateStringsArray, ...values: any[]): Promise<Result<ShellExecResult, Error>>;
97
- declare const quoteShellArg: (arg: string) => string;
98
- //#endregion
99
85
  //#region src/common/string.d.ts
100
86
  declare const addPrefix: (prefix: string, str: string) => string;
101
87
  declare const addSuffix: (suffix: string, str: string) => string;
@@ -206,4 +192,4 @@ type ThrottleOptions = Options;
206
192
  declare const debounce: <T extends Fn>(fn: T, wait?: number, options?: DebounceOptions) => DebouncedFn<T>;
207
193
  declare const throttle: <T extends Fn>(fn: T, wait?: number, options?: ThrottleOptions) => ThrottledFn<T>;
208
194
  //#endregion
209
- export { $, type DebounceOptions, type DebouncedFn, type Lock, type PromiseWithResolvers, type ShellExecOptions, type ShellExecResult, type Singleton, type Stringify, type ThrottleOptions, type ThrottledFn, addPrefix, addSuffix, concatTemplateStrings, createLock, createPromiseWithResolvers, createSingleton, debounce, getErrorMessage, indent, join, joinWithSlash, linear, normalizeError, unsafeParse as parse, parseKeyValuePairs, parseValueToBoolean, quoteShellArg, removePrefix, removeSuffix, safeParse, scale, sleep, split, splitByLineBreak, splitWithSlash, stringify, template, throttle, toForwardSlash, unindent };
195
+ export { type DebounceOptions, type DebouncedFn, type Lock, type PromiseWithResolvers, type Singleton, type Stringify, type ThrottleOptions, type ThrottledFn, addPrefix, addSuffix, concatTemplateStrings, createLock, createPromiseWithResolvers, createSingleton, debounce, getErrorMessage, indent, join, joinWithSlash, linear, normalizeError, unsafeParse as parse, parseKeyValuePairs, parseValueToBoolean, removePrefix, removeSuffix, safeParse, scale, sleep, split, splitByLineBreak, splitWithSlash, stringify, template, throttle, toForwardSlash, unindent };
package/dist/common.js CHANGED
@@ -1,3 +1,3 @@
1
- import { A as stringify, C as parseKeyValuePairs, D as getErrorMessage, E as scale, O as normalizeError, S as sleep, T as linear, _ as toForwardSlash, a as addPrefix, b as createPromiseWithResolvers, c as indent, d as removePrefix, f as removeSuffix, g as template, h as splitWithSlash, i as quoteShellArg, j as unsafeParse, k as safeParse, l as join, m as splitByLineBreak, n as throttle, o as addSuffix, p as split, r as $, s as concatTemplateStrings, t as debounce, u as joinWithSlash, v as unindent, w as parseValueToBoolean, x as createSingleton, y as createLock } from "./chunks/chunk-f4c5d38b.js";
1
+ import { C as linear, D as safeParse, E as normalizeError, O as stringify, S as parseValueToBoolean, T as getErrorMessage, _ as createLock, a as concatTemplateStrings, b as sleep, c as joinWithSlash, d as split, f as splitByLineBreak, g as unindent, h as toForwardSlash, i as addSuffix, k as unsafeParse, l as removePrefix, m as template, n as throttle, o as indent, p as splitWithSlash, r as addPrefix, s as join, t as debounce, u as removeSuffix, v as createPromiseWithResolvers, w as scale, x as parseKeyValuePairs, y as createSingleton } from "./chunks/chunk-fda806f4.js";
2
2
 
3
- export { $, addPrefix, addSuffix, concatTemplateStrings, createLock, createPromiseWithResolvers, createSingleton, debounce, getErrorMessage, indent, join, joinWithSlash, linear, normalizeError, unsafeParse as parse, parseKeyValuePairs, parseValueToBoolean, quoteShellArg, removePrefix, removeSuffix, safeParse, scale, sleep, split, splitByLineBreak, splitWithSlash, stringify, template, throttle, toForwardSlash, unindent };
3
+ export { addPrefix, addSuffix, concatTemplateStrings, createLock, createPromiseWithResolvers, createSingleton, debounce, getErrorMessage, indent, join, joinWithSlash, linear, normalizeError, unsafeParse as parse, parseKeyValuePairs, parseValueToBoolean, removePrefix, removeSuffix, safeParse, scale, sleep, split, splitByLineBreak, splitWithSlash, stringify, template, throttle, toForwardSlash, unindent };
package/dist/fs.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as stringify, F as safeTry, L as __commonJSMin, M as Result, N as err, P as ok, R as __toESM, d as removePrefix, k as safeParse } from "./chunks/chunk-f4c5d38b.js";
1
+ import { A as Result, D as safeParse, F as __commonJSMin, I as __toESM, M as ok, N as safeTry, O as stringify, j as err, l as removePrefix } from "./chunks/chunk-fda806f4.js";
2
2
  import { Fn as e$1, Jt as n, Sn as e$2, gn as e } from "./chunks/chunk-267b337b.js";
3
3
  import * as nativeFs$1 from "fs";
4
4
  import nativeFs from "fs";
package/dist/result.js CHANGED
@@ -1,3 +1,3 @@
1
- import { F as safeTry, I as ResultError, M as Result, N as err, P as ok } from "./chunks/chunk-f4c5d38b.js";
1
+ import { A as Result, M as ok, N as safeTry, P as ResultError, j as err } from "./chunks/chunk-fda806f4.js";
2
2
 
3
3
  export { Result, ResultError, err, ok, safeTry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodbyenjn/utils",
3
- "version": "26.1.2",
3
+ "version": "26.1.3",
4
4
  "description": "GoodbyeNJN's utils for typescript and javascript",
5
5
  "keywords": [
6
6
  "utils",
@@ -60,6 +60,7 @@
60
60
  "@goodbyenjn/configs": "^6.1.4",
61
61
  "@goodbyenjn/utils": "file:",
62
62
  "@types/node": "^25.0.3",
63
+ "args-tokenizer": "^0.3.0",
63
64
  "eslint": "^9.39.2",
64
65
  "prettier": "^3.7.4",
65
66
  "remeda": "^2.33.1",
@@ -67,6 +68,7 @@
67
68
  "rolldown-plugin-dts": "^0.20.0",
68
69
  "rotery": "^0.7.0",
69
70
  "safe-stable-stringify": "^2.5.0",
71
+ "tinyexec": "^1.0.2",
70
72
  "tinyglobby": "^0.2.15",
71
73
  "type-fest": "^5.3.1",
72
74
  "typescript": "^5.9.3",