@sayknow-cli/utils 0.2.2

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.
Files changed (65) hide show
  1. package/dist/types/abortable.d.ts +27 -0
  2. package/dist/types/async.d.ts +6 -0
  3. package/dist/types/cli.d.ts +118 -0
  4. package/dist/types/color.d.ts +82 -0
  5. package/dist/types/dirs.d.ts +163 -0
  6. package/dist/types/env.d.ts +68 -0
  7. package/dist/types/fetch-retry.d.ts +80 -0
  8. package/dist/types/format.d.ts +37 -0
  9. package/dist/types/frontmatter.d.ts +25 -0
  10. package/dist/types/fs-error.d.ts +31 -0
  11. package/dist/types/glob.d.ts +28 -0
  12. package/dist/types/hook-fetch.d.ts +16 -0
  13. package/dist/types/index.d.ts +30 -0
  14. package/dist/types/json.d.ts +4 -0
  15. package/dist/types/logger.d.ts +66 -0
  16. package/dist/types/mermaid-ascii.d.ts +11 -0
  17. package/dist/types/mime.d.ts +29 -0
  18. package/dist/types/peek-file.d.ts +9 -0
  19. package/dist/types/postmortem.d.ts +29 -0
  20. package/dist/types/procmgr.d.ts +35 -0
  21. package/dist/types/prompt.d.ts +18 -0
  22. package/dist/types/ptree.d.ts +108 -0
  23. package/dist/types/ring.d.ts +93 -0
  24. package/dist/types/safe-stderr.d.ts +1 -0
  25. package/dist/types/sanitize-text.d.ts +14 -0
  26. package/dist/types/snowflake.d.ts +25 -0
  27. package/dist/types/spawn-env.d.ts +4 -0
  28. package/dist/types/stream.d.ts +68 -0
  29. package/dist/types/tab-spacing.d.ts +9 -0
  30. package/dist/types/temp.d.ts +14 -0
  31. package/dist/types/type-guards.d.ts +3 -0
  32. package/dist/types/which.d.ts +37 -0
  33. package/package.json +61 -0
  34. package/src/abortable.ts +73 -0
  35. package/src/async.ts +50 -0
  36. package/src/cli.ts +439 -0
  37. package/src/color.ts +204 -0
  38. package/src/dirs.ts +539 -0
  39. package/src/env.ts +278 -0
  40. package/src/fetch-retry.ts +298 -0
  41. package/src/format.ts +112 -0
  42. package/src/frontmatter.ts +154 -0
  43. package/src/fs-error.ts +56 -0
  44. package/src/glob.ts +189 -0
  45. package/src/hook-fetch.ts +30 -0
  46. package/src/index.ts +50 -0
  47. package/src/json.ts +10 -0
  48. package/src/logger.ts +392 -0
  49. package/src/mermaid-ascii.ts +31 -0
  50. package/src/mime.ts +159 -0
  51. package/src/peek-file.ts +114 -0
  52. package/src/postmortem.ts +197 -0
  53. package/src/procmgr.ts +209 -0
  54. package/src/prompt.ts +471 -0
  55. package/src/ptree.ts +390 -0
  56. package/src/ring.ts +169 -0
  57. package/src/safe-stderr.ts +15 -0
  58. package/src/sanitize-text.ts +38 -0
  59. package/src/snowflake.ts +136 -0
  60. package/src/spawn-env.ts +23 -0
  61. package/src/stream.ts +403 -0
  62. package/src/tab-spacing.ts +312 -0
  63. package/src/temp.ts +77 -0
  64. package/src/type-guards.ts +11 -0
  65. package/src/which.ts +232 -0
package/src/env.ts ADDED
@@ -0,0 +1,278 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { getAgentDir, getConfigRootDir } from "./dirs";
5
+ import { isSafeEnvName, isSafeEnvValue } from "./spawn-env";
6
+
7
+ export { filterProcessEnv, isSafeEnvName, isSafeEnvValue } from "./spawn-env";
8
+
9
+ const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+
11
+ /**
12
+ * Strict shell-identifier shape. Used for dotenv keys we accept into
13
+ * `Bun.env` — those should be referenceable as `$NAME` from POSIX shells,
14
+ * so we reject anything outside `[A-Za-z_][A-Za-z0-9_]*`.
15
+ */
16
+ export function isValidEnvName(name: string): boolean {
17
+ return ENV_NAME_RE.test(name);
18
+ }
19
+
20
+ function stripInlineShellComment(value: string): string {
21
+ let quote: '"' | "'" | undefined;
22
+ for (let i = 0; i < value.length; i++) {
23
+ const char = value[i];
24
+ if (char === "\\") {
25
+ i++;
26
+ continue;
27
+ }
28
+ if ((char === '"' || char === "'") && (!quote || quote === char)) {
29
+ quote = quote ? undefined : char;
30
+ continue;
31
+ }
32
+ if (char === "#" && !quote && (i === 0 || /\s/.test(value[i - 1] ?? ""))) {
33
+ return value.slice(0, i).trimEnd();
34
+ }
35
+ }
36
+ return value.trimEnd();
37
+ }
38
+
39
+ /**
40
+ * Parses simple POSIX shell environment assignments from files such as
41
+ * ~/.zshrc without executing user shell code. Supports `export KEY=value` and
42
+ * `KEY=value`, including single/double quoted literal values. Dynamic shell
43
+ * expressions are intentionally ignored because evaluating startup files would
44
+ * run arbitrary code during CLI startup.
45
+ */
46
+ export function parseShellEnvFile(filePath: string): Record<string, string> {
47
+ const result: Record<string, string> = {};
48
+ try {
49
+ const content = fs.readFileSync(filePath, "utf-8");
50
+ for (const line of content.split("\n")) {
51
+ const trimmed = line.trim();
52
+ if (!trimmed || trimmed.startsWith("#")) continue;
53
+
54
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(trimmed);
55
+ if (!match) continue;
56
+
57
+ const key = match[1];
58
+ if (!isValidEnvName(key)) continue;
59
+
60
+ let value = stripInlineShellComment(match[2] ?? "").trim();
61
+ if (value.endsWith(";")) value = value.slice(0, -1).trimEnd();
62
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
63
+ value = value.slice(1, -1);
64
+ }
65
+ if (!isSafeEnvValue(value)) continue;
66
+ if (/[$`]/.test(value)) continue;
67
+
68
+ result[key] = value;
69
+ }
70
+ } catch {
71
+ // File doesn't exist or can't be read - return empty result
72
+ }
73
+
74
+ return result;
75
+ }
76
+
77
+ /**
78
+ * Parses a .env file synchronously and extracts key-value string pairs.
79
+ * Ignores lines that are empty or start with '#'. Trims whitespace.
80
+ * Allows values to be quoted with single or double quotes.
81
+ * Returns an object of key-value pairs.
82
+ */
83
+ export function parseEnvFile(filePath: string): Record<string, string> {
84
+ const result: Record<string, string> = {};
85
+ try {
86
+ const content = fs.readFileSync(filePath, "utf-8");
87
+ for (const line of content.split("\n")) {
88
+ const trimmed = line.trim();
89
+ // Skip comments and blank lines
90
+ if (!trimmed || trimmed.startsWith("#")) continue;
91
+
92
+ const eqIndex = trimmed.indexOf("=");
93
+ if (eqIndex === -1) continue;
94
+
95
+ const key = trimmed.slice(0, eqIndex).trim();
96
+ if (!isValidEnvName(key)) continue;
97
+
98
+ let value = trimmed.slice(eqIndex + 1).trim();
99
+
100
+ // Remove surrounding quotes (" or ')
101
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
102
+ value = value.slice(1, -1);
103
+ }
104
+ if (!isSafeEnvValue(value)) continue;
105
+
106
+ result[key] = value;
107
+ }
108
+ } catch {
109
+ // File doesn't exist or can't be read - return empty result
110
+ }
111
+
112
+ return result;
113
+ }
114
+
115
+ function resolveFileEnvValue(file: Record<string, string>, name: string): string | undefined {
116
+ if (!isSafeEnvName(name)) return undefined;
117
+ const value = file[name];
118
+ if (value === undefined || !isSafeEnvValue(value)) return undefined;
119
+ const trimmed = value.trim();
120
+ return trimmed.length > 0 ? trimmed : undefined;
121
+ }
122
+
123
+ function filterCredentialInheritedEnv(env: Record<string, string | undefined>): Record<string, string> {
124
+ const result: Record<string, string> = {};
125
+ for (const key in env) {
126
+ const value = env[key];
127
+ if (!isSafeEnvName(key) || value === undefined || !isSafeEnvValue(value)) continue;
128
+
129
+ // Bun may have already loaded cwd/.env before JS runs. It does not expose the
130
+ // source of each entry, so an exact match with projectEnv is ambiguous. Use
131
+ // the safer credential rule: ambiguous project matches are excluded from the
132
+ // credential-only inherited snapshot, while remaining available through $env.
133
+ const projectValue = resolveFileEnvValue(projectEnv, key);
134
+ if (projectValue !== undefined && projectValue === value) continue;
135
+
136
+ result[key] = value;
137
+ }
138
+ return result;
139
+ }
140
+
141
+ // Eagerly parse the user's $HOME/.env and the current project's .env (from cwd)
142
+ const homeShellEnv = {
143
+ ...parseShellEnvFile(path.join(os.homedir(), ".zshenv")),
144
+ ...parseShellEnvFile(path.join(os.homedir(), ".zprofile")),
145
+ ...parseShellEnvFile(path.join(os.homedir(), ".zshrc")),
146
+ ...parseShellEnvFile(path.join(os.homedir(), ".bash_profile")),
147
+ ...parseShellEnvFile(path.join(os.homedir(), ".bashrc")),
148
+ };
149
+ const homeEnv = parseEnvFile(path.join(os.homedir(), ".env"));
150
+ const piEnv = parseEnvFile(path.join(getConfigRootDir(), ".env"));
151
+ const agentEnv = parseEnvFile(path.join(getAgentDir(), ".env"));
152
+ const projectEnv = parseEnvFile(path.join(process.cwd(), ".env"));
153
+
154
+ const inheritedEnv = filterCredentialInheritedEnv(Bun.env);
155
+
156
+ export function $inheritedEnv(name: string): string | undefined {
157
+ return resolveFileEnvValue(inheritedEnv, name);
158
+ }
159
+
160
+ function resolveLiveCredentialEnvValue(name: string): string | undefined {
161
+ if (!isSafeEnvName(name)) return undefined;
162
+ const value = Bun.env[name];
163
+ if (value === undefined || !isSafeEnvValue(value)) return undefined;
164
+ const trimmed = value.trim();
165
+ if (trimmed.length === 0) return undefined;
166
+
167
+ const projectValue = resolveFileEnvValue(projectEnv, name);
168
+ if (
169
+ projectValue !== undefined &&
170
+ projectValue === trimmed &&
171
+ resolveFileEnvValue(inheritedEnv, name) === undefined
172
+ ) {
173
+ return undefined;
174
+ }
175
+
176
+ return trimmed;
177
+ }
178
+
179
+ for (const file of [projectEnv, agentEnv, piEnv, homeEnv, homeShellEnv]) {
180
+ for (const key in file) {
181
+ if (!Bun.env[key]) {
182
+ Bun.env[key] = file[key];
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Intentional re-export of Bun.env.
189
+ *
190
+ * All users should import this env module (import { $env } from "@sayknow-cli/utils")
191
+ * before using environment variables. This ensures that .env files have been loaded and
192
+ * overrides (project, home) have been applied, so $env always reflects the correct values.
193
+ *
194
+ * Provider credential resolution must not use this merged view because it includes the
195
+ * caller's cwd/.env. Use $credentialEnv/$pickCredentialEnv for model authentication.
196
+ */
197
+ export const $env: Record<string, string> = Bun.env as Record<string, string>;
198
+
199
+ /**
200
+ * Resolve the first environment variable value from the given keys.
201
+ * @param keys - The keys to resolve.
202
+ * @returns The first environment variable value, or undefined if no value is found.
203
+ */
204
+ export function $pickenv(...keys: string[]): string | undefined {
205
+ for (const key of keys) {
206
+ const value = Bun.env[key]?.trim();
207
+ if (value) {
208
+ return value;
209
+ }
210
+ }
211
+ return undefined;
212
+ }
213
+
214
+ /**
215
+ * Resolve credential-bearing environment variables without consulting the caller's project .env.
216
+ *
217
+ * SKC loads cwd/.env into $env for project-aware tools, but model-provider authentication should
218
+ * only use values explicitly inherited from the launching shell or SKC/user-owned config files.
219
+ */
220
+ export function $credentialEnv(name: string): string | undefined {
221
+ return (
222
+ $inheritedEnv(name) ??
223
+ resolveLiveCredentialEnvValue(name) ??
224
+ resolveFileEnvValue(agentEnv, name) ??
225
+ resolveFileEnvValue(piEnv, name) ??
226
+ resolveFileEnvValue(homeEnv, name) ??
227
+ resolveFileEnvValue(homeShellEnv, name)
228
+ );
229
+ }
230
+
231
+ /**
232
+ * Resolve the first credential env value from the given keys, excluding cwd/.env overlays.
233
+ */
234
+ export function $pickCredentialEnv(...keys: string[]): string | undefined {
235
+ for (const key of keys) {
236
+ const value = $credentialEnv(key);
237
+ if (value) return value;
238
+ }
239
+ return undefined;
240
+ }
241
+
242
+ /**
243
+ * Parses a positive decimal integer from `$env[name]`.
244
+ * Empty, invalid, NaN, zero, or negative values return `defaultValue`.
245
+ */
246
+ export function $envpos(name: string, defaultValue: number): number {
247
+ const raw = $env[name];
248
+ if (!raw) return defaultValue;
249
+ const parsed = Number.parseInt(raw, 10);
250
+ if (Number.isNaN(parsed) || parsed <= 0) return defaultValue;
251
+ return parsed;
252
+ }
253
+
254
+ /** True when `BUN_ENV` or `NODE_ENV` is the string `test`. */
255
+ export function isBunTestRuntime(): boolean {
256
+ return Bun.env.BUN_ENV === "test" || Bun.env.NODE_ENV === "test";
257
+ }
258
+
259
+ /**
260
+ * True when this code is running inside a `bun build --compile` standalone
261
+ * binary. Detects via the embedded virtual-filesystem path markers
262
+ * (`$bunfs`, `~BUN`, or its URL-encoded form `%7EBUN`) in `import.meta.url`,
263
+ * which Bun rewrites for every module bundled into the executable. The
264
+ * `PI_COMPILED` env var (set by the build script's `--define`) is checked
265
+ * first for cheap fast-path detection.
266
+ */
267
+ export function isCompiledBinary(): boolean {
268
+ if (Bun.env.PI_COMPILED) return true;
269
+ const url = import.meta.url;
270
+ return url.includes("$bunfs") || url.includes("~BUN") || url.includes("%7EBUN");
271
+ }
272
+
273
+ const TRUTHY: Dict<boolean> = { "1": true, Y: true, TRUE: true, YES: true, ON: true };
274
+ export function $flag(name: string, def: boolean = false): boolean {
275
+ const value = $env[name];
276
+ if (!value) return def;
277
+ return TRUTHY[value] === true;
278
+ }
@@ -0,0 +1,298 @@
1
+ import { scheduler } from "node:timers/promises";
2
+
3
+ // "reset after 1h2m3s" / "10m15s" / "39s"
4
+ const QUOTA_RESET_PATTERN = /reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i;
5
+ // "Please retry in 250ms" / "Please retry in 12s"
6
+ const PLEASE_RETRY_PATTERN = /Please retry in ([0-9.]+)(ms|s)/i;
7
+ // JSON field: "retryDelay": "34.074824224s"
8
+ const RETRY_DELAY_FIELD_PATTERN = /"retryDelay":\s*"([0-9.]+)(ms|s)"/i;
9
+ // "try again in 250ms" / "try again in 12s" / "try again in 12sec"
10
+ const TRY_AGAIN_PATTERN = /try again in\s+(\d+(?:\.\d+)?)\s*(ms|s)(?:ec)?/i;
11
+
12
+ /**
13
+ * Server-suggested retry delay extraction. Merges the patterns historically used
14
+ * by the OpenAI code provider and Google Gemini retry helpers.
15
+ *
16
+ * Header sources (checked in order):
17
+ * - `Retry-After` (numeric seconds, or HTTP date)
18
+ * - `x-ratelimit-reset` (Unix epoch seconds)
19
+ * - `x-ratelimit-reset-after` (seconds)
20
+ *
21
+ * Body patterns:
22
+ * - `Your quota will reset after 18h31m10s` / `10m15s` / `39s`
23
+ * - `Please retry in 250ms` / `Please retry in 12s`
24
+ * - `"retryDelay": "34.074824224s"` (JSON error detail field)
25
+ * - `try again in 250ms` / `try again in 12s` / `try again in 12sec`
26
+ *
27
+ * Returns `undefined` if no signal is found.
28
+ */
29
+ export function extractRetryHint(source: Response | Headers | null | undefined, body?: string): number | undefined {
30
+ const headers = source instanceof Headers ? source : (source?.headers ?? undefined);
31
+ if (headers) {
32
+ const retryAfter = headers.get("retry-after");
33
+ if (retryAfter) {
34
+ const seconds = Number(retryAfter);
35
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
36
+ const parsedDate = Date.parse(retryAfter);
37
+ if (!Number.isNaN(parsedDate)) return Math.max(0, parsedDate - Date.now());
38
+ }
39
+ const rateLimitReset = headers.get("x-ratelimit-reset");
40
+ if (rateLimitReset) {
41
+ const resetSeconds = Number.parseInt(rateLimitReset, 10);
42
+ if (!Number.isNaN(resetSeconds)) {
43
+ const delta = resetSeconds * 1000 - Date.now();
44
+ if (delta > 0) return delta;
45
+ }
46
+ }
47
+ const rateLimitResetAfter = headers.get("x-ratelimit-reset-after");
48
+ if (rateLimitResetAfter) {
49
+ const seconds = Number(rateLimitResetAfter);
50
+ if (Number.isFinite(seconds) && seconds > 0) return seconds * 1000;
51
+ }
52
+ }
53
+
54
+ if (!body) return undefined;
55
+
56
+ const quotaMatch = QUOTA_RESET_PATTERN.exec(body);
57
+ if (quotaMatch) {
58
+ const hours = quotaMatch[1] ? Number.parseInt(quotaMatch[1], 10) : 0;
59
+ const minutes = quotaMatch[2] ? Number.parseInt(quotaMatch[2], 10) : 0;
60
+ const seconds = Number.parseFloat(quotaMatch[3]!);
61
+ if (!Number.isNaN(seconds)) {
62
+ const totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1000;
63
+ if (totalMs > 0) return totalMs;
64
+ }
65
+ }
66
+ for (const pattern of [PLEASE_RETRY_PATTERN, RETRY_DELAY_FIELD_PATTERN, TRY_AGAIN_PATTERN]) {
67
+ const match = pattern.exec(body);
68
+ if (match?.[1]) {
69
+ const value = Number.parseFloat(match[1]);
70
+ if (Number.isFinite(value) && value > 0) {
71
+ return match[2]!.toLowerCase() === "ms" ? value : value * 1000;
72
+ }
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+
78
+ export interface FetchWithRetryOptions extends RequestInit {
79
+ /** Total fetch attempts (initial + retries). Default `5`. */
80
+ maxAttempts?: number;
81
+ /**
82
+ * Per-delay cap. Server-provided `Retry-After` hints exceeding this return
83
+ * the current response immediately — caller deals with the `!response.ok`.
84
+ * Default `60_000`.
85
+ */
86
+ maxDelayMs?: number;
87
+ /**
88
+ * Fallback delay schedule when no server hint is present. Number, array
89
+ * (indexed by attempt, clamped to last), or function. Default exponential
90
+ * `500ms * 2 ** attempt` capped at `maxDelayMs`.
91
+ */
92
+ defaultDelayMs?: number | readonly number[] | ((attempt: number) => number);
93
+ /**
94
+ * Optional per-attempt overlay merged into the base `RequestInit` each try.
95
+ * Headers from the overlay shallow-merge over the base. Useful for auth
96
+ * token refresh or user-agent rotation.
97
+ */
98
+ prepareInit?: (attempt: number) => RequestInit | Promise<RequestInit>;
99
+ /**
100
+ * Optional `fetch` implementation override. Defaults to `globalThis.fetch`.
101
+ * Useful for routing requests through a proxy, instrumented transport, or
102
+ * mock during tests.
103
+ */
104
+ fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
105
+ }
106
+
107
+ const DEFAULT_MAX_DELAY_MS = 60_000;
108
+ const DEFAULT_MAX_ATTEMPTS = 5;
109
+
110
+ /**
111
+ * Fetch with bounded retries and sensible defaults. Retries on any
112
+ * `isRetryableStatus` (5xx, 408, 429) and on transient network errors. Server
113
+ * `Retry-After`/quota hints are honoured up to `maxDelayMs`; a hint that exceeds
114
+ * the cap returns the current response so the caller can fail fast. Aborts on
115
+ * `init.signal` propagate as `"Request was aborted"`.
116
+ *
117
+ * The caller is responsible for inspecting `!response.ok` once the call returns.
118
+ */
119
+ export async function fetchWithRetry(
120
+ url: string | URL | ((attempt: number) => string | URL),
121
+ options: FetchWithRetryOptions = {},
122
+ ): Promise<Response> {
123
+ const {
124
+ maxAttempts = DEFAULT_MAX_ATTEMPTS,
125
+ maxDelayMs = DEFAULT_MAX_DELAY_MS,
126
+ defaultDelayMs,
127
+ prepareInit,
128
+ fetch: fetchImpl = fetch,
129
+ ...baseInit
130
+ } = options;
131
+ const signal = baseInit.signal as AbortSignal | undefined;
132
+
133
+ for (let attempt = 0; ; attempt++) {
134
+ if (signal?.aborted) throw new Error("Request was aborted");
135
+ const requestUrl = typeof url === "function" ? url(attempt) : url;
136
+ const init = prepareInit ? mergeInit(baseInit, await prepareInit(attempt)) : baseInit;
137
+
138
+ let response: Response;
139
+ try {
140
+ response = await fetchImpl(requestUrl, init);
141
+ } catch (error) {
142
+ if (signal?.aborted) throw new Error("Request was aborted");
143
+ const wrapped = wrapNetworkError(error);
144
+ if (attempt + 1 >= maxAttempts) throw wrapped;
145
+ await scheduler.wait(resolveDefaultDelay(defaultDelayMs, attempt, maxDelayMs), { signal });
146
+ continue;
147
+ }
148
+
149
+ if (!isRetryableStatus(response.status)) return response;
150
+ if (attempt + 1 >= maxAttempts) return response;
151
+
152
+ const hint = extractRetryHint(response, await response.clone().text());
153
+ if (hint !== undefined && hint > maxDelayMs) return response;
154
+
155
+ const delayMs = Math.min(hint ?? resolveDefaultDelay(defaultDelayMs, attempt, maxDelayMs), maxDelayMs);
156
+ await scheduler.wait(delayMs, { signal });
157
+ }
158
+ }
159
+
160
+ function mergeInit(base: RequestInit, overlay: RequestInit): RequestInit {
161
+ const merged: RequestInit = { ...base, ...overlay };
162
+ if (base.headers || overlay.headers) {
163
+ const baseHeaders = new Headers(base.headers ?? undefined);
164
+ const overlayHeaders = new Headers(overlay.headers ?? undefined);
165
+ overlayHeaders.forEach((value, key) => {
166
+ baseHeaders.set(key, value);
167
+ });
168
+ merged.headers = baseHeaders;
169
+ }
170
+ return merged;
171
+ }
172
+
173
+ function wrapNetworkError(error: unknown): Error {
174
+ if (error instanceof Error) {
175
+ if (error.name === "AbortError" || error.message === "Request was aborted") {
176
+ return new Error("Request was aborted");
177
+ }
178
+ if (error.message === "fetch failed" && error.cause instanceof Error) {
179
+ return new Error(`Network error: ${error.cause.message}`);
180
+ }
181
+ return error;
182
+ }
183
+ return new Error(String(error));
184
+ }
185
+
186
+ function resolveDefaultDelay(
187
+ option: FetchWithRetryOptions["defaultDelayMs"],
188
+ attempt: number,
189
+ maxDelayMs: number,
190
+ ): number {
191
+ if (option === undefined) return Math.min(500 * 2 ** attempt, maxDelayMs);
192
+ if (typeof option === "number") return Math.min(option, maxDelayMs);
193
+ if (typeof option === "function") return Math.min(option(attempt), maxDelayMs);
194
+ return Math.min(option[Math.min(attempt, option.length - 1)] ?? 0, maxDelayMs);
195
+ }
196
+
197
+ /**
198
+ * Inspect an arbitrary error value (or its `cause` chain, up to depth 2) for an
199
+ * HTTP status code. Reads `status`, `statusCode`, and `response.status` fields,
200
+ * coerces string values, and falls back to scanning the error message for
201
+ * common patterns like `Error: 401`, `error (429)`, or `HTTP 503`.
202
+ */
203
+ export function extractHttpStatusFromError(error: unknown): number | undefined {
204
+ return extractHttpStatusFromErrorInternal(error, 0);
205
+ }
206
+
207
+ type HttpErrorLike = {
208
+ message?: string;
209
+ name?: string;
210
+ status?: number | string;
211
+ statusCode?: number | string;
212
+ response?: { status?: number | string };
213
+ cause?: unknown;
214
+ };
215
+
216
+ function extractHttpStatusFromErrorInternal(error: unknown, depth: number): number | undefined {
217
+ if (!error || typeof error !== "object" || depth > 2) return undefined;
218
+ const info = error as HttpErrorLike;
219
+ const rawStatus = info.status ?? info.statusCode ?? info.response?.status;
220
+
221
+ let status: number | undefined;
222
+ if (typeof rawStatus === "number" && Number.isFinite(rawStatus)) {
223
+ status = rawStatus;
224
+ } else if (typeof rawStatus === "string") {
225
+ const parsed = Number(rawStatus);
226
+ if (Number.isFinite(parsed)) status = parsed;
227
+ }
228
+ if (status !== undefined && status >= 100 && status <= 599) return status;
229
+
230
+ if (info.message) {
231
+ const extracted = extractStatusFromMessage(info.message);
232
+ if (extracted !== undefined) return extracted;
233
+ }
234
+ if (info.cause) return extractHttpStatusFromErrorInternal(info.cause, depth + 1);
235
+ return undefined;
236
+ }
237
+
238
+ const STATUS_MESSAGE_PATTERNS = [
239
+ /\berror\s*[:=]\s*(\d{3})\b/i,
240
+ /error\s*\((\d{3})\)/i,
241
+ /status\s*[:=]?\s*(\d{3})/i,
242
+ /\bhttp\s*(\d{3})\b/i,
243
+ /\b(\d{3})\s*(?:status|error)\b/i,
244
+ ] as const;
245
+
246
+ function extractStatusFromMessage(message: string): number | undefined {
247
+ for (const pattern of STATUS_MESSAGE_PATTERNS) {
248
+ const match = pattern.exec(message);
249
+ if (!match) continue;
250
+ const value = Number(match[1]);
251
+ if (Number.isFinite(value) && value >= 100 && value <= 599) return value;
252
+ }
253
+ return undefined;
254
+ }
255
+
256
+ /**
257
+ * `true` if the given HTTP status code is one we treat as transient: 408
258
+ * (Request Timeout), 429 (Too Many Requests), or any 5xx (server error).
259
+ */
260
+ export function isRetryableStatus(status: number): boolean {
261
+ return status >= 500 || status === 408 || status === 429;
262
+ }
263
+
264
+ /**
265
+ * `true` if the message describes an unexpected socket closure — Bun and some
266
+ * proxies surface these for any HTTP/2 stream reset.
267
+ */
268
+ export function isUnexpectedSocketCloseMessage(message: string): boolean {
269
+ return /\b(?:the\s+)?socket connection (?:was )?closed unexpectedly\b/i.test(message);
270
+ }
271
+
272
+ const TRANSIENT_MESSAGE_PATTERN =
273
+ /overloaded|rate.?limit|too many requests|service.?unavailable|server error|internal error|connection.?error|unable to connect|fetch failed|network error|stream stall|other side closed/i;
274
+
275
+ const VALIDATION_MESSAGE_PATTERN =
276
+ /invalid|validation|bad request|unsupported|schema|missing required|not found|unauthorized|forbidden/i;
277
+
278
+ /**
279
+ * Identify errors that should be retried: aborts/timeouts in the error name or
280
+ * message, retryable HTTP statuses (see `isRetryableStatus`), unexpected socket
281
+ * closes, and the standard transient phrases. 4xx statuses other than 408/429
282
+ * and validation-shaped messages short-circuit to `false`.
283
+ */
284
+ export function isRetryableError(error: unknown): boolean {
285
+ const info = error as { message?: string; name?: string } | null;
286
+ const message = info?.message ?? "";
287
+ const name = info?.name ?? "";
288
+ if (name === "AbortError" || /timeout|timed out|aborted/i.test(message)) return true;
289
+
290
+ const status = extractHttpStatusFromError(error);
291
+ if (status !== undefined) {
292
+ if (isRetryableStatus(status)) return true;
293
+ if (status >= 400 && status < 500) return false;
294
+ }
295
+
296
+ if (VALIDATION_MESSAGE_PATTERN.test(message)) return false;
297
+ return isUnexpectedSocketCloseMessage(message) || TRANSIENT_MESSAGE_PATTERN.test(message);
298
+ }
package/src/format.ts ADDED
@@ -0,0 +1,112 @@
1
+ const SEC = 1_000;
2
+ const MIN = 60 * SEC;
3
+ const HOUR = 60 * MIN;
4
+ const DAY = 24 * HOUR;
5
+
6
+ /**
7
+ * Format a duration in milliseconds to a short human-readable string.
8
+ * Examples: "123ms", "1.5s", "30m15s", "2h30m", "3d2h"
9
+ */
10
+ export function formatDuration(ms: number): string {
11
+ if (ms < SEC) return `${ms}ms`;
12
+ if (ms < MIN) return `${(ms / SEC).toFixed(1)}s`;
13
+ if (ms < HOUR) {
14
+ const mins = Math.floor(ms / MIN);
15
+ const secs = Math.floor((ms % MIN) / SEC);
16
+ return secs > 0 ? `${mins}m${secs}s` : `${mins}m`;
17
+ }
18
+ if (ms < DAY) {
19
+ const hours = Math.floor(ms / HOUR);
20
+ const mins = Math.floor((ms % HOUR) / MIN);
21
+ return mins > 0 ? `${hours}h${mins}m` : `${hours}h`;
22
+ }
23
+ const days = Math.floor(ms / DAY);
24
+ const hours = Math.floor((ms % DAY) / HOUR);
25
+ return hours > 0 ? `${days}d${hours}h` : `${days}d`;
26
+ }
27
+
28
+ /**
29
+ * Format a number with K/M/B suffix for compact display.
30
+ * Uses 1 decimal for small leading digits when non-zero, rounded otherwise.
31
+ * Examples: "999", "1K", "1.5K", "25K", "1M", "1.5M", "25M", "1.5B"
32
+ */
33
+ export function formatNumber(n: number): string {
34
+ if (n < 1_000) return n.toString();
35
+ if (n < 10_000) return `${trim1(n / 1_000)}K`;
36
+ if (n < 1_000_000) return `${Math.round(n / 1_000)}K`;
37
+ if (n < 10_000_000) return `${trim1(n / 1_000_000)}M`;
38
+ if (n < 1_000_000_000) return `${Math.round(n / 1_000_000)}M`;
39
+ if (n < 10_000_000_000) return `${trim1(n / 1_000_000_000)}B`;
40
+ return `${Math.round(n / 1_000_000_000)}B`;
41
+ }
42
+
43
+ /** Format with up to 1 decimal place, dropping trailing `.0`. */
44
+ function trim1(n: number): string {
45
+ const s = n.toFixed(1);
46
+ return s.endsWith(".0") ? s.slice(0, -2) : s;
47
+ }
48
+
49
+ /**
50
+ * Format a byte count to a human-readable string.
51
+ * Examples: "512B", "1.5KB", "2.3MB", "1.2GB"
52
+ */
53
+ export function formatBytes(bytes: number): string {
54
+ if (bytes < 1024) return `${bytes}B`;
55
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
56
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
57
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
58
+ }
59
+
60
+ /**
61
+ * Truncate a string to maxLen characters, appending an ellipsis if truncated.
62
+ * For display-width-aware truncation (terminals), use truncateToWidth from @sayknow-cli/tui.
63
+ */
64
+ export function truncate(str: string, maxLen: number, ellipsis = "…"): string {
65
+ if (str.length <= maxLen) return str;
66
+ const sliceLen = Math.max(0, maxLen - ellipsis.length);
67
+ return `${str.slice(0, sliceLen)}${ellipsis}`;
68
+ }
69
+
70
+ /**
71
+ * Format count with pluralized label (e.g., "3 files", "1 error").
72
+ */
73
+ export function formatCount(label: string, count: number): string {
74
+ const safeCount = Number.isFinite(count) ? count : 0;
75
+ return `${safeCount} ${pluralize(label, safeCount)}`;
76
+ }
77
+
78
+ /**
79
+ * Format age from seconds to human-readable string.
80
+ */
81
+ export function formatAge(ageSeconds: number | null | undefined): string {
82
+ if (!ageSeconds) return "";
83
+ const mins = Math.floor(ageSeconds / 60);
84
+ const hours = Math.floor(mins / 60);
85
+ const days = Math.floor(hours / 24);
86
+ const weeks = Math.floor(days / 7);
87
+ const months = Math.floor(days / 30);
88
+
89
+ if (months > 0) return `${months}mo ago`;
90
+ if (weeks > 0) return `${weeks}w ago`;
91
+ if (days > 0) return `${days}d ago`;
92
+ if (hours > 0) return `${hours}h ago`;
93
+ if (mins > 0) return `${mins}m ago`;
94
+ return "just now";
95
+ }
96
+
97
+ /**
98
+ * Pluralize a label based on the count.
99
+ */
100
+ export function pluralize(label: string, count: number): string {
101
+ if (count === 1) return label;
102
+ if (/(?:ch|sh|s|x|z)$/i.test(label)) return `${label}es`;
103
+ if (/[^aeiou]y$/i.test(label)) return `${label.slice(0, -1)}ies`;
104
+ return `${label}s`;
105
+ }
106
+
107
+ /**
108
+ * Format a ratio as a percentage.
109
+ */
110
+ export function formatPercent(ratio: number): string {
111
+ return `${(ratio * 100).toFixed(1)}%`;
112
+ }