@theholocron/kyber 5.0.0-alpha.342 → 5.0.0-alpha.344

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
@@ -10,17 +10,17 @@ Published, so a second CLI can import it. `@theholocron/cli` is its first consum
10
10
 
11
11
  ## Subpaths
12
12
 
13
- | Subpath | What it gives a CLI |
14
- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15
- | `/ui` | Status glyphs and colours, padded status rows, a depth-limited JSON view, a spinner that only shows on a terminal (and `createRetryNotice(subscribe)`, which says on it when a request is retried, given the HTTP client's retry hook), wait-for-Enter, open-in-file-browser, the error for "a prompt was needed but there is no terminal", and the cleaning of error text before it reaches a terminal (`describeError`, `commandFailureMessage`, `logReason`, `sanitizeDetail`, `stripControl`). |
16
- | `/notifier` | A cached, best-effort "a newer version exists" notice for an npm package: `checkForUpdates({ name, currentVersion, cacheDir })` returns a function that prints a boxed notice to stderr, or `null`. Silent in CI and with `NO_UPDATE_NOTIFIER`. |
17
- | `/secrets` | Handling tokens safely, with no terminal UI: owner-only (`0600`) files, shredding a file that held tokens, "does git ignore this path", dotenv lines that survive quoting, reading a `.env` at the repo root, the clipboard, the OS keyring (`createKeyring({ service })`, best-effort, `@napi-rs/keyring` optional), an in-process store for credentials a provider returned, `--token` / `--token vendor=value` parsing, and resolving a token from the flag, the environment, that store and the keyring (`createResolveToken`, `createFeatureResolver`, `AuthError`). |
18
- | `/prompts` | A searchable menu (`pickMenuItem`), and prompting for the positionals and options a command left out (`promptForPositionals`, `promptForOptions`): required options always asked, the rest behind one checkbox, mutually exclusive `modes`, secret options masked, and a value that is asked last (`askLast`). They take small structural types (`PositionalCommand`, `OptionsCommand`), not the CLI's command registry. |
19
- | `/menu` | The interactive menu of a CLI, driven by data: `launchMenu(entries, argv, { bin, envPrefix })` shows a searchable, nested picker over a list of `MenuEntry`, asks for the positionals and options the command needs, then spawns the CLI again with the answers. A command that supports `--dry-run` is previewed first and then confirmed (`--skip-dry-run` opts out); a preview that reports `DRY_RUN_NOOP_EXIT_CODE` skips the question. Secret options never reach argv: they travel as `<envPrefix>_<OPTION>` env vars, and a preview child gets `dryRunPreviewEnvVar(envPrefix)`. `createMenu({ bin, envPrefix })` binds it once (returning `launchMenu(entries, argv, options?)` and `dryRunPreviewEnvVar`). Also `menuItems`, `buildChildArgv`, `forwardedFlags`, `secretEnv`, `shouldPreviewDryRun`. |
20
- | `/testing` | A test harness for a CLI: `createCliRunner` runs a built binary in a fresh directory with an environment built from nothing, `runCommand` runs one yargs command module through a real parse, `ensureBuilt` is a Vitest global setup that builds only when `dist` is missing or stale, and `hermeticCreateRequire` resolves modules only from one directory. |
21
- | `/observability` | The logging and telemetry wiring of a CLI: `createCliLogger({ envPrefix, resolveAxiom? })` returns a memoized root logger (`buildCliLogger`, `getLogger`, `reportError`, `getRunId`, `resolveLogLevel`) whose level comes from `--log` / `--verbose` / `--quiet`, then `<PREFIX>_LOG_LEVEL`, then the config file, and is quiet on a terminal unless asked; `createCliTelemetry({ envPrefix, dsn, posthogKey, posthogHost })` returns Sentry error reporting and PostHog analytics behind `<PREFIX>_TELEMETRY=false`. `@theholocron/observability` is an optional peer. |
22
- | `/config` | A `<name>.config.{ts,js,mjs,cjs,json}` for a new CLI: `createConfigSystem({ name, derive?, resolve, merge })` returns `defineConfig`, `loadConfig` (walks up to `.git`) and `compose()` (dedupe by `id`, all unmet `requires` in one `ConfigError`, per-key merge). Strategies: `lastWins`, `shallowMerge`, `union`, `mergeByKey`. `@theholocron/datapad` is an optional peer. |
23
- | `/flags` | The options every command of a tool takes: `addGlobalOptions(parser, { describe?, cwd? })` declares `--dry-run`, a repeatable `--token` and `--cwd` once on the root; `tokenContext(values, report)` parses the `--token` values and reports a bad one without a stack trace; `groupMenu(parent, open)` is the hidden default command that makes a bare group (`tool repo`) do something useful; `InferArgs` types a command's handler arguments from its builder. |
13
+ | Subpath | What it gives a CLI |
14
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15
+ | `/ui` | Status glyphs and colours, padded status rows, a check-rows renderer (`printCheckRows`, `printCheckSummary`, `summariseChecks`, `declaredVsActual`), a depth-limited JSON view, a spinner that only shows on a terminal (and `createRetryNotice(subscribe)`, which says on it when a request is retried, given the HTTP client's retry hook), wait-for-Enter, open-in-file-browser, the error for "a prompt was needed but there is no terminal", and the cleaning of error text before it reaches a terminal (`describeError`, `commandFailureMessage`, `logReason`, `sanitizeDetail`, `stripControl`). |
16
+ | `/notifier` | A cached, best-effort "a newer version exists" notice for an npm package: `checkForUpdates({ name, currentVersion, cacheDir })` returns a function that prints a boxed notice to stderr, or `null`. Silent in CI and with `NO_UPDATE_NOTIFIER`. |
17
+ | `/secrets` | Handling tokens safely, with no terminal UI: owner-only (`0600`) files, shredding a file that held tokens, the wait-for-the-import-then-delete step that follows (`finishCredentialsFile`: deletes the file on Enter, Ctrl-C or a closed terminal), "does git ignore this path", dotenv lines that survive quoting, reading a `.env` at the repo root, the clipboard, the OS keyring (`createKeyring({ service })`, best-effort, `@napi-rs/keyring` optional), an in-process store for credentials a provider returned, `--token` / `--token vendor=value` parsing, and resolving a token from the flag, the environment, that store and the keyring (`createResolveToken`, `createFeatureResolver`, `AuthError`). |
18
+ | `/prompts` | A searchable menu (`pickMenuItem`), and prompting for the positionals and options a command left out (`promptForPositionals`, `promptForOptions`): required options always asked, the rest behind one checkbox, mutually exclusive `modes`, secret options masked, and a value that is asked last (`askLast`). They take small structural types (`PositionalCommand`, `OptionsCommand`), not the CLI's command registry. |
19
+ | `/menu` | The interactive menu of a CLI, driven by data: `launchMenu(entries, argv, { bin, envPrefix })` shows a searchable, nested picker over a list of `MenuEntry`, asks for the positionals and options the command needs, then spawns the CLI again with the answers. A command that supports `--dry-run` is previewed first and then confirmed (`--skip-dry-run` opts out); a preview that reports `DRY_RUN_NOOP_EXIT_CODE` skips the question. Secret options never reach argv: they travel as `<envPrefix>_<OPTION>` env vars, and a preview child gets `dryRunPreviewEnvVar(envPrefix)`. `createMenu({ bin, envPrefix })` binds it once (returning `launchMenu(entries, argv, options?)` and `dryRunPreviewEnvVar`). `createCommandRegistry(entries, label?)` declares the commands once and returns `{ entries, getEntry(name) }` (a repeated name throws), and `numeric` is a ready `validate` for a number prompt. Also `menuItems`, `buildChildArgv`, `forwardedFlags`, `secretEnv`, `shouldPreviewDryRun`. |
20
+ | `/testing` | A test harness for a CLI: `createCliRunner` runs a built binary in a fresh directory with an environment built from nothing, `runCommand` runs one yargs command module through a real parse, `ensureBuilt` is a Vitest global setup that builds only when `dist` is missing or stale, and `hermeticCreateRequire` resolves modules only from one directory. |
21
+ | `/observability` | The logging and telemetry wiring of a CLI: `createCliLogger({ envPrefix, resolveAxiom? })` returns a memoized root logger (`buildCliLogger`, `getLogger`, `reportError`, `getRunId`, `resolveLogLevel`) whose level comes from `--log` / `--verbose` / `--quiet`, then `<PREFIX>_LOG_LEVEL`, then the config file, and is quiet on a terminal unless asked; `createCliTelemetry({ envPrefix, dsn, posthogKey, posthogHost })` returns Sentry error reporting and PostHog analytics behind `<PREFIX>_TELEMETRY=false`. `@theholocron/observability` is an optional peer. |
22
+ | `/config` | A `<name>.config.{ts,js,mjs,cjs,json}` for a new CLI: `createConfigSystem({ name, derive?, resolve, merge })` returns `defineConfig`, `loadConfig` (walks up to `.git`) and `compose()` (dedupe by `id`, all unmet `requires` in one `ConfigError`, per-key merge). Strategies: `lastWins`, `shallowMerge`, `union`, `mergeByKey`. `@theholocron/datapad` is an optional peer. |
23
+ | `/flags` | The options every command of a tool takes: `addGlobalOptions(parser, { describe?, cwd? })` declares `--dry-run`, a repeatable `--token` and `--cwd` once on the root; `tokenContext(values, report)` parses the `--token` values and reports a bad one without a stack trace; `groupMenu(parent, open)` is the hidden default command that makes a bare group (`tool repo`) do something useful; `InferArgs` types a command's handler arguments from its builder. |
24
24
 
25
25
  ## Usage
26
26
 
package/dist/menu.d.mts CHANGED
@@ -75,6 +75,26 @@ interface MenuEntry {
75
75
  * shape identically with no need to know which kind of command it came from.
76
76
  */
77
77
  export declare function buildChildArgv(entry: MenuEntry, positionals: string[], resolved: ResolvedOptions, parentArgv: Record<string, unknown>, dryRunOverride?: boolean): string[];
78
+ /** A CLI's command catalog: the entries in menu order, and a lookup by full name. See {@link createCommandRegistry}. */
79
+ interface CommandRegistry<E extends MenuEntry = MenuEntry> {
80
+ /** Every entry, in the order they were declared (the order the menu lists them in). */
81
+ entries: E[];
82
+ /** The entry for a full command name (`"auth set"`); throws when there is none. */
83
+ getEntry(name: string): E;
84
+ }
85
+ /**
86
+ * Declare a CLI's commands once, as a list of {@link MenuEntry}, and get the catalog the menu and the prompts
87
+ * read from: hand `entries` to {@link launchMenu}, and have a leaf command's handler call `getEntry(name)` to
88
+ * prompt for just its own missing positionals (`promptForPositionals`).
89
+ *
90
+ * The list is kept in the order given. A repeated name is a mistake (the menu would list it twice and
91
+ * `getEntry` could only reach the first), so it throws here, when the catalog is built, not at the prompt.
92
+ *
93
+ * @param entries - The commands, in menu order.
94
+ * @param label - Names the catalog in error messages (default `"menu"`).
95
+ * @throws When two entries share a name.
96
+ */
97
+ export declare function createCommandRegistry<E extends MenuEntry>(entries: E[], label?: string): CommandRegistry<E>;
78
98
  /** How {@link launchMenu} is bound to one particular CLI. */
79
99
  interface LaunchMenuConfig {
80
100
  /** The CLI's binary name, used in the default non-interactive hint (`Run \`<bin> --help\` …`). */
@@ -179,6 +199,11 @@ export declare const BACK = "back";
179
199
  * Registration order is kept.
180
200
  */
181
201
  export declare function menuItems(entries: MenuEntry[], path?: string[]): MenuItem[];
202
+ /**
203
+ * A `validate` function for an `input` positional or option (`PositionalPrompt.validate`) that accepts only
204
+ * digits; anything else returns the message `"enter a number"`.
205
+ */
206
+ export declare const numeric: (value: string) => boolean | string;
182
207
  /**
183
208
  * Secret option answers, keyed by the env var their handler reads instead
184
209
  * of argv (`ps` and shell history expose argv, never a child's own env) —
@@ -197,4 +222,4 @@ export declare function secretEnv(resolved: ResolvedOptions, envPrefix: string):
197
222
  * straight to the real run").
198
223
  */
199
224
  export declare function shouldPreviewDryRun(entry: MenuEntry, parentArgv: Record<string, unknown>): boolean;
200
- export type { LaunchMenuConfig, MenuEntry };
225
+ export type { CommandRegistry, LaunchMenuConfig, MenuEntry };
package/dist/menu.mjs CHANGED
@@ -75,6 +75,34 @@ function buildChildArgv(entry, positionals, resolved, parentArgv, dryRunOverride
75
75
  ...forwardedFlags(parentArgv, dryRunOverride)
76
76
  ];
77
77
  }
78
+ // src/menu/create-command-registry/create-command-registry.ts
79
+ /**
80
+ * Declare a CLI's commands once, as a list of {@link MenuEntry}, and get the catalog the menu and the prompts
81
+ * read from: hand `entries` to {@link launchMenu}, and have a leaf command's handler call `getEntry(name)` to
82
+ * prompt for just its own missing positionals (`promptForPositionals`).
83
+ *
84
+ * The list is kept in the order given. A repeated name is a mistake (the menu would list it twice and
85
+ * `getEntry` could only reach the first), so it throws here, when the catalog is built, not at the prompt.
86
+ *
87
+ * @param entries - The commands, in menu order.
88
+ * @param label - Names the catalog in error messages (default `"menu"`).
89
+ * @throws When two entries share a name.
90
+ */
91
+ function createCommandRegistry(entries, label = "menu") {
92
+ const seen = /* @__PURE__ */ new Set();
93
+ for (const { name } of entries) {
94
+ if (seen.has(name)) throw new Error(`${label}: duplicate command registry entry "${name}"`);
95
+ seen.add(name);
96
+ }
97
+ return {
98
+ entries,
99
+ getEntry(name) {
100
+ const entry = entries.find((e) => e.name === name);
101
+ if (!entry) throw new Error(`${label}: no command registry entry named "${name}"`);
102
+ return entry;
103
+ }
104
+ };
105
+ }
78
106
  // src/menu/dry-run-preview-env-var/dry-run-preview-env-var.ts
79
107
  /**
80
108
  * The env var {@link launchMenu} sets on a dry-run preview child (`<ENV_PREFIX>_DRY_RUN_PREVIEW`), so its
@@ -319,4 +347,10 @@ function createMenu({ bin, envPrefix }) {
319
347
  dryRunPreviewEnvVar: dryRunPreviewEnvVar(envPrefix)
320
348
  };
321
349
  }
322
- export { BACK, DRY_RUN_NOOP_EXIT_CODE, GROUP, buildChildArgv, createMenu, dryRunPreviewEnvVar, forwardedFlags, launchMenu, menuItems, secretEnv, shouldPreviewDryRun };
350
+ // src/menu/numeric/numeric.ts
351
+ /**
352
+ * A `validate` function for an `input` positional or option (`PositionalPrompt.validate`) that accepts only
353
+ * digits; anything else returns the message `"enter a number"`.
354
+ */
355
+ const numeric = (value) => /^\d+$/.test(value) ? true : "enter a number";
356
+ export { BACK, DRY_RUN_NOOP_EXIT_CODE, GROUP, buildChildArgv, createCommandRegistry, createMenu, dryRunPreviewEnvVar, forwardedFlags, launchMenu, menuItems, numeric, secretEnv, shouldPreviewDryRun };
package/dist/prompts.mjs CHANGED
@@ -36,7 +36,7 @@ function searchChoices(items, term) {
36
36
  // src/prompts/prompt-options/prompt-options.ts
37
37
  /**
38
38
  * A required option must not resolve to an empty answer — `optionArgv`/
39
- * `secretEnv` (child-argv.ts) both drop an empty-string value entirely,
39
+ * `secretEnv` (menu/option-argv, menu/secret-env) both drop an empty-string value entirely,
40
40
  * which would silently invoke the child without a flag the caller asked
41
41
  * for. Passed as `validate` so inquirer re-prompts instead of accepting it.
42
42
  */
@@ -170,6 +170,32 @@ type FeatureTokenResolver = (input?: ResolveTokenInput) => string;
170
170
  * replaces the credential store and the keyring together.
171
171
  */
172
172
  export declare function createFeatureResolver(config: FeatureResolverConfig): FeatureTokenResolver;
173
+ /** What {@link finishCredentialsFile} needs to know about the file it was handed and how to talk about it. */
174
+ interface FinishCredentialsFileInput {
175
+ /** The private file that was just written. */
176
+ path: string;
177
+ /** The identity of the file as written: the descriptor held for its cleanup, and the device and inode. */
178
+ identity: FileIdentity;
179
+ /** Where the lines go. Names and paths only, never a value. */
180
+ print: (line: string) => void;
181
+ /** What the file holds, for the warnings: `your tokens`, `the app's credentials`. */
182
+ holds: string;
183
+ /** The line that says how to import the file. */
184
+ importHint: string;
185
+ /** Leave the file in place instead of deleting it once the import is done. */
186
+ keep?: boolean | undefined;
187
+ /** Whether there is a terminal to ask on. Without one the file is left and the command says to delete it. */
188
+ interactive?: boolean | undefined;
189
+ /** Overwrites and removes the file it was written as. Defaults to `shredFile`. */
190
+ shred?: ((path: string, identity: FileIdentity) => ShredOutcome) | undefined;
191
+ /** Waits for the user to finish importing. Defaults to waiting for Enter on the terminal. */
192
+ waitForImport?: ((message: string) => Promise<unknown>) | undefined;
193
+ }
194
+ /**
195
+ * Once the lines are in the private file, says what to do with it and, on a terminal, deletes it when the import is
196
+ * done. Returns whether the file is gone (or was left on purpose): `false` means plaintext secrets are still on disk.
197
+ */
198
+ export declare function finishCredentialsFile(input: FinishCredentialsFileInput): Promise<boolean>;
173
199
  /**
174
200
  * What git says about a path: `ignored` when a rule ignores it, `tracked` when git would track it, `no-repo` when the
175
201
  * path is not in a git repository (or git is not installed, in which case nothing can commit it), and `unknown` when
@@ -268,4 +294,4 @@ export declare function createPrivateFile(path: string, text: string, write?: (f
268
294
  * `remove` is how the path is deleted; it is a parameter so a test can look at the file just before it goes.
269
295
  */
270
296
  export declare function shredFile(path: string, identity: FileIdentity, remove?: (path: string) => void): ShredOutcome;
271
- export type { FeatureResolverConfig, FeatureTokenResolver, FileIdentity, GitIgnoreState, Keyring, KeyringBinding, KeyringEntry, KeyringOptions, ParsedTokenArgs, ResolveTokenConfig, ResolveTokenInput, ShredOutcome, TokenResolver };
297
+ export type { FeatureResolverConfig, FeatureTokenResolver, FileIdentity, FinishCredentialsFileInput, GitIgnoreState, Keyring, KeyringBinding, KeyringEntry, KeyringOptions, ParsedTokenArgs, ResolveTokenConfig, ResolveTokenInput, ShredOutcome, TokenResolver };
package/dist/secrets.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { n as parseTokenArgs, t as TokenParseError } from "./token-args-BgrCq_kK.mjs";
2
+ import { n as describeError, t as waitForEnter } from "./wait-for-enter-Do0h9yET.mjs";
2
3
  import { createRequire } from "node:module";
3
4
  import { execFileSync } from "node:child_process";
4
5
  import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
@@ -250,6 +251,56 @@ function createFeatureResolver(config) {
250
251
  return token;
251
252
  };
252
253
  }
254
+ // src/secrets/finish-credentials-file/finish-credentials-file.ts
255
+ /** Signals that end the wait for the import, with the exit status each is conventionally reported as. */
256
+ const INTERRUPTS = [
257
+ ["SIGINT", 130],
258
+ ["SIGTERM", 143],
259
+ ["SIGHUP", 129]
260
+ ];
261
+ /**
262
+ * Once the lines are in the private file, says what to do with it and, on a terminal, deletes it when the import is
263
+ * done. Returns whether the file is gone (or was left on purpose): `false` means plaintext secrets are still on disk.
264
+ */
265
+ async function finishCredentialsFile(input) {
266
+ const { path, identity, print } = input;
267
+ print(`wrote ${path} (readable only by you)`);
268
+ print(input.importHint);
269
+ if (input.keep || !input.interactive) {
270
+ closeSync(identity.fd);
271
+ print(`it holds ${input.holds} in plain text: delete it when you are done: ${path}`);
272
+ return true;
273
+ }
274
+ const cleanup = () => {
275
+ try {
276
+ const outcome = (input.shred ?? shredFile)(path, identity);
277
+ if (outcome === "deleted") print(`deleted ${path}`);
278
+ else if (outcome === "missing") print(`${path} was already gone`);
279
+ else print(`left ${path} alone: it is no longer the file this command wrote`);
280
+ return true;
281
+ } catch (err) {
282
+ print(`could not delete ${path}: ${describeError(err)}`);
283
+ print(`it holds ${input.holds} in plain text: delete it yourself: ${path}`);
284
+ return false;
285
+ }
286
+ };
287
+ const handlers = INTERRUPTS.map(([signal, code]) => {
288
+ const handler = () => {
289
+ cleanup();
290
+ process.exit(code);
291
+ };
292
+ process.once(signal, handler);
293
+ return [signal, handler];
294
+ });
295
+ let cleaned;
296
+ try {
297
+ await (input.waitForImport ?? waitForEnter)("press Enter when the import is done and the file will be deleted: ");
298
+ } finally {
299
+ for (const [signal, handler] of handlers) process.off(signal, handler);
300
+ cleaned = cleanup();
301
+ }
302
+ return cleaned;
303
+ }
253
304
  // src/secrets/git-ignored/git-ignored.ts
254
305
  /**
255
306
  * Ask git whether it ignores `path` (see {@link GitIgnoreState}). A caller that must not leave a file where it could be
@@ -398,4 +449,4 @@ function createResolveToken(config) {
398
449
  return token;
399
450
  };
400
451
  }
401
- export { AuthError, DOTENV_FILE, TokenParseError, clearCredentials, copyToClipboard, createFeatureResolver, createKeyring, createPrivateFile, createResolveToken, dotenvLine, getCredential, hasCredentials, isGitIgnored, parseTokenArgs, readDotenvFile, setCredentials, shredFile, writeCredentialsFile };
452
+ export { AuthError, DOTENV_FILE, TokenParseError, clearCredentials, copyToClipboard, createFeatureResolver, createKeyring, createPrivateFile, createResolveToken, dotenvLine, finishCredentialsFile, getCredential, hasCredentials, isGitIgnored, parseTokenArgs, readDotenvFile, setCredentials, shredFile, writeCredentialsFile };
@@ -68,7 +68,7 @@ export declare function ensureBuilt(options: EnsureBuiltOptions): void;
68
68
  *
69
69
  * vi.mock("node:module", async (importOriginal) => {
70
70
  * const actual = await importOriginal<typeof import("node:module")>();
71
- * const { hermeticCreateRequire } = await import("../../testing/hermetic-require.js");
71
+ * const { hermeticCreateRequire } = await import("@theholocron/kyber/testing");
72
72
  * return { ...actual, createRequire: hermeticCreateRequire(actual) };
73
73
  * });
74
74
  */
package/dist/testing.mjs CHANGED
@@ -104,7 +104,7 @@ function ensureBuilt(options) {
104
104
  *
105
105
  * vi.mock("node:module", async (importOriginal) => {
106
106
  * const actual = await importOriginal<typeof import("node:module")>();
107
- * const { hermeticCreateRequire } = await import("../../testing/hermetic-require.js");
107
+ * const { hermeticCreateRequire } = await import("@theholocron/kyber/testing");
108
108
  * return { ...actual, createRequire: hermeticCreateRequire(actual) };
109
109
  * });
110
110
  */
package/dist/ui.d.mts CHANGED
@@ -1,9 +1,60 @@
1
+ /** How a row of a check or setup run came out: it passed, it failed, or it was skipped. */
2
+ type RowStatus = "ok" | "fail" | "skip";
3
+ /** Right-pads `s` to `width` with spaces — never truncates. */
4
+ export declare function pad(s: string, width: number): string;
5
+ /**
6
+ * One row of a status report: a 2-space indent, the status icon (✓ / ✗ / ·),
7
+ * then `columns` joined with a two-space gap (blank columns dropped, so a
8
+ * row that has nothing for its last column doesn't trail whitespace).
9
+ * Column padding (`pad`) is the caller's job — `doctor` pads capability and
10
+ * provider to a fixed width; `clone`'s repo names and paths don't, since
11
+ * they vary too widely for fixed-width alignment to read cleanly.
12
+ *
13
+ * Shared by `doctor` (capability / provider / message) and `clone` (repo /
14
+ * destination / reason) so every status table in the CLI reads the same way.
15
+ */
16
+ export declare function statusRow(status: RowStatus, columns: string[]): string;
17
+ /** How one step of a deep check ended: it held, it did not, or it could not be tried. */
18
+ type CheckStatus = RowStatus;
19
+ /** One step of a deep check, as a CLI's check commands print it. */
20
+ interface CheckRow {
21
+ id: string;
22
+ title: string;
23
+ status: CheckStatus;
24
+ /** One line: what was found, or why it failed or was skipped. */
25
+ detail: string;
26
+ /** For a failing row, one line per thing that is wrong. */
27
+ problems: string[];
28
+ }
29
+ /** The counts on the closing `N ok, N fail, N skipped` line. */
30
+ interface CheckSummary {
31
+ ok: number;
32
+ fail: number;
33
+ skip: number;
34
+ }
1
35
  /**
2
36
  * The line to print for an error that reached the top of a command: {@link describeError | describeError}'s text, and
3
37
  * never empty, so a failure always says something. An error with no message prints its class name; anything else with
4
38
  * no text prints "the command failed".
5
39
  */
6
40
  export declare function commandFailureMessage(err: unknown): string;
41
+ /** How `declaredVsActual` compares and words its problem lines. */
42
+ interface DeclaredVsActualOptions<T> {
43
+ /** What the things compared are called in the problem lines: `variable`, `secret`, `check`. */
44
+ noun: string;
45
+ /** Whether two values for the same key agree. Defaults to `===`. */
46
+ equal?: (declared: T, actual: T) => boolean;
47
+ /** How a value reads in a problem line. Defaults to `String`. */
48
+ show?: (value: T) => string;
49
+ /** Whether a key found but not declared is a problem. Defaults to `true`. */
50
+ flagExtra?: boolean;
51
+ }
52
+ /**
53
+ * Compares what the config declares with what exists, both as maps by key, and returns one problem line per
54
+ * difference: a declared key that is missing, a key found but not declared, a key whose values disagree.
55
+ * An empty list means they match. A deep check is then a list of these comparisons, not a renderer of its own.
56
+ */
57
+ export declare function declaredVsActual<T>(declared: ReadonlyMap<string, T>, actual: ReadonlyMap<string, T>, options: DeclaredVsActualOptions<T>): string[];
7
58
  /**
8
59
  * What to print for a caught value: its message with control characters stripped (a provider's text can carry them),
9
60
  * and, when the error has a non-empty `details` (the raw response body of an API error, say), that body after it,
@@ -93,6 +144,10 @@ export declare class NonInteractiveError extends Error {
93
144
  * on PATH (e.g. no `xdg-open` in a minimal container).
94
145
  */
95
146
  export declare function openPath(path: string): void;
147
+ /** One row per step, titles padded to the widest, each problem on its own indented line. */
148
+ export declare function printCheckRows(rows: readonly CheckRow[], print: (line: string) => void): void;
149
+ /** A blank line, then the closing `N ok, N fail, N skipped`. */
150
+ export declare function printCheckSummary(summary: CheckSummary, print: (line: string) => void): void;
96
151
  /** A spinner for one step at a time, which the step can print through without breaking it. */
97
152
  interface Progress {
98
153
  /** Run `fn` under a spinner named `label`. The spinner is cleared, not kept, so the step's own result line stands alone. */
@@ -154,22 +209,6 @@ export declare function createRetryNotice(subscribe: RetrySubscribe): ProgressLi
154
209
  * unknown size that lands in the terminal.
155
210
  */
156
211
  export declare function sanitizeDetail(text: string): string;
157
- /** How a row of a check or setup run came out: it passed, it failed, or it was skipped. */
158
- type RowStatus = "ok" | "fail" | "skip";
159
- /** Right-pads `s` to `width` with spaces — never truncates. */
160
- export declare function pad(s: string, width: number): string;
161
- /**
162
- * One row of a status report: a 2-space indent, the status icon (✓ / ✗ / ·),
163
- * then `columns` joined with a two-space gap (blank columns dropped, so a
164
- * row that has nothing for its last column doesn't trail whitespace).
165
- * Column padding (`pad`) is the caller's job — `doctor` pads capability and
166
- * provider to a fixed width; `clone`'s repo names and paths don't, since
167
- * they vary too widely for fixed-width alignment to read cleanly.
168
- *
169
- * Shared by `doctor` (capability / provider / message) and `clone` (repo /
170
- * destination / reason) so every status table in the CLI reads the same way.
171
- */
172
- export declare function statusRow(status: RowStatus, columns: string[]): string;
173
212
  /**
174
213
  * Control characters (newlines and the C1 range included, whose 0x9b is an 8-bit CSI) turned into spaces and whitespace
175
214
  * collapsed, with no length cap. For text from outside the process that is about to reach a terminal, where a crafted
@@ -195,6 +234,8 @@ export declare const style: {
195
234
  /** Bold text for a heading. */
196
235
  header: (msg: string) => string;
197
236
  };
237
+ /** How many rows ended each way. */
238
+ export declare function summariseChecks(rows: readonly CheckRow[]): CheckSummary;
198
239
  /**
199
240
  * Print `message` and wait until Enter is pressed, the input ends, or Ctrl-C is pressed, whichever comes first, and
200
241
  * return which: `enter`, or `closed` for the other two. It never hangs on a closed input. It reads from stdin and
@@ -202,4 +243,4 @@ export declare const style: {
202
243
  * streams are parameters so a test can answer for the user.
203
244
  */
204
245
  export declare function waitForEnter(message: string, input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream): Promise<"enter" | "closed">;
205
- export type { Container, Key, Line, Path, Progress, ProgressListener, RenderOptions, RetryNoticeEvent, RetrySubscribe, RowStatus, ViewJsonOptions, ViewState };
246
+ export type { CheckRow, CheckStatus, CheckSummary, Container, DeclaredVsActualOptions, Key, Line, Path, Progress, ProgressListener, RenderOptions, RetryNoticeEvent, RetrySubscribe, RowStatus, ViewJsonOptions, ViewState };
package/dist/ui.mjs CHANGED
@@ -1,44 +1,8 @@
1
1
  import { t as NonInteractiveError } from "./non-interactive-error-Mm_Mn79M.mjs";
2
+ import { i as stripControl, n as describeError, r as sanitizeDetail, t as waitForEnter } from "./wait-for-enter-Do0h9yET.mjs";
2
3
  import chalk from "chalk";
3
4
  import { spawn } from "node:child_process";
4
5
  import ora from "ora";
5
- import { createInterface } from "node:readline";
6
- // src/ui/strip-control/strip-control.ts
7
- /**
8
- * Control characters (newlines and the C1 range included, whose 0x9b is an 8-bit CSI) turned into spaces and whitespace
9
- * collapsed, with no length cap. For text from outside the process that is about to reach a terminal, where a crafted
10
- * value could otherwise forge extra lines or inject escape sequences.
11
- */
12
- function stripControl(text) {
13
- return text.replace(/[\x00-\x1f\x7f-\x9f]/g, " ").replace(/\s+/g, " ").trim();
14
- }
15
- // src/ui/sanitize-detail/sanitize-detail.ts
16
- /** The longest a detail is kept, so one oversized body cannot flood a report. */
17
- const MAX_DETAIL_LENGTH = 200;
18
- /**
19
- * {@link stripControl}, then cut to 200 characters with an ellipsis. For a vendor's response body or any other text of
20
- * unknown size that lands in the terminal.
21
- */
22
- function sanitizeDetail(text) {
23
- const stripped = stripControl(text);
24
- return stripped.length > MAX_DETAIL_LENGTH ? `${stripped.slice(0, MAX_DETAIL_LENGTH)}…` : stripped;
25
- }
26
- // src/ui/describe-error/describe-error.ts
27
- /**
28
- * What to print for a caught value: its message with control characters stripped (a provider's text can carry them),
29
- * and, when the error has a non-empty `details` (the raw response body of an API error, say), that body after it,
30
- * sanitized and length-capped. A bare "GET /x → 403" then says why, and the vendor's text cannot flood or manipulate the
31
- * terminal. Anything that is not an `Error` is printed with `String()`.
32
- */
33
- function describeError(err) {
34
- const base = stripControl(err instanceof Error ? err.message : String(err));
35
- const details = err instanceof Error ? err.details : void 0;
36
- if (details) {
37
- const detail = sanitizeDetail(String(details));
38
- if (detail) return `${base}: ${detail}`;
39
- }
40
- return base;
41
- }
42
6
  // src/ui/command-failure/command-failure.ts
43
7
  /**
44
8
  * The line to print for an error that reached the top of a command: {@link describeError | describeError}'s text, and
@@ -48,6 +12,29 @@ function describeError(err) {
48
12
  function commandFailureMessage(err) {
49
13
  return describeError(err) || (err instanceof Error ? err.name : "the command failed");
50
14
  }
15
+ // src/ui/declared-vs-actual/declared-vs-actual.ts
16
+ /**
17
+ * Compares what the config declares with what exists, both as maps by key, and returns one problem line per
18
+ * difference: a declared key that is missing, a key found but not declared, a key whose values disagree.
19
+ * An empty list means they match. A deep check is then a list of these comparisons, not a renderer of its own.
20
+ */
21
+ function declaredVsActual(declared, actual, options) {
22
+ const equal = options.equal ?? ((a, b) => a === b);
23
+ const show = options.show ?? ((value) => String(value));
24
+ const problems = [];
25
+ for (const [key, want] of declared) {
26
+ if (!actual.has(key)) {
27
+ problems.push(`missing ${options.noun} ${key}`);
28
+ continue;
29
+ }
30
+ const found = actual.get(key);
31
+ if (!equal(want, found)) problems.push(`${options.noun} ${key}: declared ${show(want)}, found ${show(found)}`);
32
+ }
33
+ if (options.flagExtra !== false) {
34
+ for (const key of actual.keys()) if (!declared.has(key)) problems.push(`unexpected ${options.noun} ${key}`);
35
+ }
36
+ return problems;
37
+ }
51
38
  // src/ui/json-view/json-view.ts
52
39
  function isContainer(value) {
53
40
  return typeof value === "object" && value !== null;
@@ -312,6 +299,61 @@ function openPath(path) {
312
299
  child.on("error", () => {});
313
300
  child.unref();
314
301
  }
302
+ // src/ui/style/style.ts
303
+ /** Formats a message with a status marker and colour: one helper per kind of line a command prints. */
304
+ const style = {
305
+ /** A green `✓` for something that worked. */
306
+ success: (msg) => `${chalk.green("✓")} ${msg}`,
307
+ /** A yellow `⚠` for something worth a second look. */
308
+ warn: (msg) => `${chalk.yellow("⚠")} ${msg}`,
309
+ /** A red `✗` for something that failed. */
310
+ fail: (msg) => `${chalk.red("✗")} ${msg}`,
311
+ /** A cyan `→` for a step being taken. */
312
+ step: (msg) => `${chalk.cyan("→")} ${msg}`,
313
+ /** A dim `·` marker for a row that's neither a pass nor a failure — loaded but inactive, or skipped. */
314
+ skip: (msg) => chalk.dim(`· ${msg}`),
315
+ /** Dimmed text for a suggestion or a next step. */
316
+ hint: (msg) => chalk.dim(msg),
317
+ /** Dimmed text for detail that should recede. */
318
+ dim: (msg) => chalk.dim(msg),
319
+ /** Bold text for a heading. */
320
+ header: (msg) => chalk.bold(msg)
321
+ };
322
+ // src/ui/status-row/status-row.ts
323
+ /** Right-pads `s` to `width` with spaces — never truncates. */
324
+ function pad(s, width) {
325
+ return s.length >= width ? s : s + " ".repeat(width - s.length);
326
+ }
327
+ /**
328
+ * One row of a status report: a 2-space indent, the status icon (✓ / ✗ / ·),
329
+ * then `columns` joined with a two-space gap (blank columns dropped, so a
330
+ * row that has nothing for its last column doesn't trail whitespace).
331
+ * Column padding (`pad`) is the caller's job — `doctor` pads capability and
332
+ * provider to a fixed width; `clone`'s repo names and paths don't, since
333
+ * they vary too widely for fixed-width alignment to read cleanly.
334
+ *
335
+ * Shared by `doctor` (capability / provider / message) and `clone` (repo /
336
+ * destination / reason) so every status table in the CLI reads the same way.
337
+ */
338
+ function statusRow(status, columns) {
339
+ const joined = columns.filter((c) => c.length > 0).join(" ");
340
+ return ` ${status === "ok" ? style.success(joined) : status === "fail" ? style.fail(joined) : style.skip(joined)}`;
341
+ }
342
+ // src/ui/print-check-rows/print-check-rows.ts
343
+ /** One row per step, titles padded to the widest, each problem on its own indented line. */
344
+ function printCheckRows(rows, print) {
345
+ const width = Math.max(0, ...rows.map((row) => row.title.length));
346
+ for (const row of rows) {
347
+ print(statusRow(row.status, [row.title.padEnd(width), row.detail]));
348
+ for (const problem of row.problems) print(` - ${problem}`);
349
+ }
350
+ }
351
+ // src/ui/print-check-summary/print-check-summary.ts
352
+ /** A blank line, then the closing `N ok, N fail, N skipped`. */
353
+ function printCheckSummary(summary, print) {
354
+ print("");
355
+ print(style.header(`${summary.ok} ok, ${summary.fail} fail, ${summary.skip} skipped`));
356
+ }
315
357
  // src/ui/progress/progress.ts
316
358
  /**
317
359
  * Runs `fn`, showing an ora spinner for its duration in TTY environments.
@@ -402,66 +444,13 @@ function createRetryNotice(subscribe) {
402
444
  setText(`${label} (retrying ${e.vendor ?? "the request"}, attempt ${e.attempt} of ${e.of})`);
403
445
  });
404
446
  }
405
- // src/ui/style/style.ts
406
- /** Formats a message with a status marker and colour: one helper per kind of line a command prints. */
407
- const style = {
408
- /** A green `✓` for something that worked. */
409
- success: (msg) => `${chalk.green("✓")} ${msg}`,
410
- /** A yellow `⚠` for something worth a second look. */
411
- warn: (msg) => `${chalk.yellow("⚠")} ${msg}`,
412
- /** A red `✗` for something that failed. */
413
- fail: (msg) => `${chalk.red("✗")} ${msg}`,
414
- /** A cyan `→` for a step being taken. */
415
- step: (msg) => `${chalk.cyan("→")} ${msg}`,
416
- /** A dim `·` marker for a row that's neither a pass nor a failure — loaded but inactive, or skipped. */
417
- skip: (msg) => chalk.dim(`· ${msg}`),
418
- /** Dimmed text for a suggestion or a next step. */
419
- hint: (msg) => chalk.dim(msg),
420
- /** Dimmed text for detail that should recede. */
421
- dim: (msg) => chalk.dim(msg),
422
- /** Bold text for a heading. */
423
- header: (msg) => chalk.bold(msg)
424
- };
425
- // src/ui/status-row/status-row.ts
426
- /** Right-pads `s` to `width` with spaces — never truncates. */
427
- function pad(s, width) {
428
- return s.length >= width ? s : s + " ".repeat(width - s.length);
429
- }
430
- /**
431
- * One row of a status report: a 2-space indent, the status icon (✓ / ✗ / ·),
432
- * then `columns` joined with a two-space gap (blank columns dropped, so a
433
- * row that has nothing for its last column doesn't trail whitespace).
434
- * Column padding (`pad`) is the caller's job — `doctor` pads capability and
435
- * provider to a fixed width; `clone`'s repo names and paths don't, since
436
- * they vary too widely for fixed-width alignment to read cleanly.
437
- *
438
- * Shared by `doctor` (capability / provider / message) and `clone` (repo /
439
- * destination / reason) so every status table in the CLI reads the same way.
440
- */
441
- function statusRow(status, columns) {
442
- const joined = columns.filter((c) => c.length > 0).join(" ");
443
- return ` ${status === "ok" ? style.success(joined) : status === "fail" ? style.fail(joined) : style.skip(joined)}`;
444
- }
445
- // src/ui/wait-for-enter/wait-for-enter.ts
446
- /**
447
- * Print `message` and wait until Enter is pressed, the input ends, or Ctrl-C is pressed, whichever comes first, and
448
- * return which: `enter`, or `closed` for the other two. It never hangs on a closed input. It reads from stdin and
449
- * writes to stderr, so a pipe on stdout is never touched; the caller checks there is a terminal to answer it. The
450
- * streams are parameters so a test can answer for the user.
451
- */
452
- function waitForEnter(message, input = process.stdin, output = process.stderr) {
453
- return new Promise((resolve) => {
454
- const rl = createInterface({
455
- input,
456
- output
457
- });
458
- let answered = false;
459
- rl.on("close", () => resolve(answered ? "enter" : "closed"));
460
- rl.on("SIGINT", () => rl.close());
461
- rl.question(message, () => {
462
- answered = true;
463
- rl.close();
464
- });
465
- });
447
+ // src/ui/summarise-checks/summarise-checks.ts
448
+ /** How many rows ended each way. */
449
+ function summariseChecks(rows) {
450
+ return {
451
+ ok: rows.filter((r) => r.status === "ok").length,
452
+ fail: rows.filter((r) => r.status === "fail").length,
453
+ skip: rows.filter((r) => r.status === "skip").length
454
+ };
466
455
  }
467
- export { NonInteractiveError, allowProgress, commandFailureMessage, createProgress, createRetryNotice, describeError, expandToDepth, logReason, openPath, pad, progressEnabled, reduceKey, renderTree, sanitizeDetail, setProgressListener, statusRow, stripControl, style, viewJson, waitForEnter, withProgress, withSpinner };
456
+ export { NonInteractiveError, allowProgress, commandFailureMessage, createProgress, createRetryNotice, declaredVsActual, describeError, expandToDepth, logReason, openPath, pad, printCheckRows, printCheckSummary, progressEnabled, reduceKey, renderTree, sanitizeDetail, setProgressListener, statusRow, stripControl, style, summariseChecks, viewJson, waitForEnter, withProgress, withSpinner };
@@ -0,0 +1,60 @@
1
+ import { createInterface } from "node:readline";
2
+ // src/ui/strip-control/strip-control.ts
3
+ /**
4
+ * Control characters (newlines and the C1 range included, whose 0x9b is an 8-bit CSI) turned into spaces and whitespace
5
+ * collapsed, with no length cap. For text from outside the process that is about to reach a terminal, where a crafted
6
+ * value could otherwise forge extra lines or inject escape sequences.
7
+ */
8
+ function stripControl(text) {
9
+ return text.replace(/[\x00-\x1f\x7f-\x9f]/g, " ").replace(/\s+/g, " ").trim();
10
+ }
11
+ // src/ui/sanitize-detail/sanitize-detail.ts
12
+ /** The longest a detail is kept, so one oversized body cannot flood a report. */
13
+ const MAX_DETAIL_LENGTH = 200;
14
+ /**
15
+ * {@link stripControl}, then cut to 200 characters with an ellipsis. For a vendor's response body or any other text of
16
+ * unknown size that lands in the terminal.
17
+ */
18
+ function sanitizeDetail(text) {
19
+ const stripped = stripControl(text);
20
+ return stripped.length > MAX_DETAIL_LENGTH ? `${stripped.slice(0, MAX_DETAIL_LENGTH)}…` : stripped;
21
+ }
22
+ // src/ui/describe-error/describe-error.ts
23
+ /**
24
+ * What to print for a caught value: its message with control characters stripped (a provider's text can carry them),
25
+ * and, when the error has a non-empty `details` (the raw response body of an API error, say), that body after it,
26
+ * sanitized and length-capped. A bare "GET /x → 403" then says why, and the vendor's text cannot flood or manipulate the
27
+ * terminal. Anything that is not an `Error` is printed with `String()`.
28
+ */
29
+ function describeError(err) {
30
+ const base = stripControl(err instanceof Error ? err.message : String(err));
31
+ const details = err instanceof Error ? err.details : void 0;
32
+ if (details) {
33
+ const detail = sanitizeDetail(String(details));
34
+ if (detail) return `${base}: ${detail}`;
35
+ }
36
+ return base;
37
+ }
38
+ // src/ui/wait-for-enter/wait-for-enter.ts
39
+ /**
40
+ * Print `message` and wait until Enter is pressed, the input ends, or Ctrl-C is pressed, whichever comes first, and
41
+ * return which: `enter`, or `closed` for the other two. It never hangs on a closed input. It reads from stdin and
42
+ * writes to stderr, so a pipe on stdout is never touched; the caller checks there is a terminal to answer it. The
43
+ * streams are parameters so a test can answer for the user.
44
+ */
45
+ function waitForEnter(message, input = process.stdin, output = process.stderr) {
46
+ return new Promise((resolve) => {
47
+ const rl = createInterface({
48
+ input,
49
+ output
50
+ });
51
+ let answered = false;
52
+ rl.on("close", () => resolve(answered ? "enter" : "closed"));
53
+ rl.on("SIGINT", () => rl.close());
54
+ rl.question(message, () => {
55
+ answered = true;
56
+ rl.close();
57
+ });
58
+ });
59
+ }
60
+ export { stripControl as i, describeError as n, sanitizeDetail as r, waitForEnter as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/kyber",
3
- "version": "5.0.0-alpha.342",
3
+ "version": "5.0.0-alpha.344",
4
4
  "description": "The reusable parts of a command-line tool: terminal output, prompts, the interactive menu, the update notifier, safe handling of tokens, a test harness and the global flags.",
5
5
  "keywords": [
6
6
  "cli",
@@ -90,12 +90,12 @@
90
90
  "typescript": "^5.9.3",
91
91
  "vitest": "^5.0.5",
92
92
  "yargs": "^18.1.0",
93
- "@theholocron/tsconfig": "^8.9.0-alpha.8",
94
- "@theholocron/eslint-config": "^8.9.0-alpha.8",
93
+ "@theholocron/datapad": "5.0.0-alpha.344",
95
94
  "@theholocron/observability": "0.7.0-alpha.1",
95
+ "@theholocron/eslint-config": "^8.9.0-alpha.8",
96
+ "@theholocron/tsconfig": "^8.9.0-alpha.8",
96
97
  "@theholocron/tsdown-config": "^8.9.0-alpha.8",
97
- "@theholocron/vitest-config": "^8.9.0-alpha.8",
98
- "@theholocron/datapad": "5.0.0-alpha.342"
98
+ "@theholocron/vitest-config": "^8.9.0-alpha.8"
99
99
  },
100
100
  "peerDependencies": {
101
101
  "@inquirer/prompts": "^8.0.0",
@@ -106,7 +106,7 @@
106
106
  "dotenv": "^17.0.0",
107
107
  "ora": "^9.0.0",
108
108
  "yargs": "^18.0.0",
109
- "@theholocron/datapad": "^5.0.0-alpha.342",
109
+ "@theholocron/datapad": "^5.0.0-alpha.344",
110
110
  "@theholocron/observability": "^0.7.0-alpha.1"
111
111
  },
112
112
  "peerDependenciesMeta": {