diff --git a/CODEBASE.md b/CODEBASE.md index 4895638..4b8ae93 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -56,14 +56,14 @@ that needs them (`commander`, `marked`, `marked-terminal-renderer`, Each subpath is an independent entry point so JSON-only consumers don't pay for markdown/OAuth transitive installs. -| Subpath | Provides | Optional peers needed | -| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- | -| `.` (root) | `CliError`, config I/O, data/state dirs, JSON/NDJSON + `emitView`, `printEmpty`, spinner, stdin reader, terminal detection, global-args parser, command-token scan, usage-tracking headers | — (chalk/yocto bundled) | -| `@todoist/cli-core/auth` | OAuth runtime, the `attach*Command` registrars, providers, keyring `TokenStore`, refresh, the `TokenStore`/`AuthProvider` contracts | `commander`, `oauth4webapi`, `open`, `@napi-rs/keyring` | -| `@todoist/cli-core/commands` | `registerChangelogCommand`, `registerUpdateCommand` + semver helpers | `commander` | -| `@todoist/cli-core/extensions` | `createExtensionManager`, `registerExtension*` registrars, `createExtension` scaffolding, doctor helpers | `commander`, `zod` | -| `@todoist/cli-core/markdown` | `preloadMarkdown`, `renderMarkdown` | `marked`, `marked-terminal-renderer` | -| `@todoist/cli-core/testing` | `describeEmptyMachineOutput`, `createTestProgram`, console captures, `mockStdin`, account fixtures, extension fixtures | `vitest`, `commander` | +| Subpath | Provides | Optional peers needed | +| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| `.` (root) | `CliError`, config I/O, data/state dirs, JSON/NDJSON + `emitView`, `printEmpty`, `--yes`/`--dry-run` confirmation, spinner, stdin reader, terminal detection, global-args parser, command-token scan, usage-tracking headers | — (chalk/yocto bundled) | +| `@todoist/cli-core/auth` | OAuth runtime, the `attach*Command` registrars, providers, keyring `TokenStore`, refresh, the `TokenStore`/`AuthProvider` contracts | `commander`, `oauth4webapi`, `open`, `@napi-rs/keyring` | +| `@todoist/cli-core/commands` | `registerChangelogCommand`, `registerUpdateCommand` + semver helpers | `commander` | +| `@todoist/cli-core/extensions` | `createExtensionManager`, `registerExtension*` registrars, `createExtension` scaffolding, doctor helpers | `commander`, `zod` | +| `@todoist/cli-core/markdown` | `preloadMarkdown`, `renderMarkdown` | `marked`, `marked-terminal-renderer` | +| `@todoist/cli-core/testing` | `describeEmptyMachineOutput`, `createTestProgram`, console captures, `mockStdin`, account fixtures, extension fixtures | `vitest`, `commander` | The public surface = every re-export through these entry barrels. `tsc --noEmit` validates the re-exports; there is no separate runtime pinning test (per AGENTS.md). @@ -75,6 +75,7 @@ src/ ├─ index.ts # Root barrel (the `.` export) ├─ errors.ts # CliError + CliErrorCode aggregator + getErrorMessage ├─ config.ts # XDG config I/O; CoreConfig / UpdateChannel / ConfigErrorCode +├─ confirmation.ts # requireConfirmation / previewUnlessConfirmed / printDryRun (--yes, --dry-run) ├─ paths.ts # getDataDir / getStateDir (XDG data + state, Windows LOCALAPPDATA) ├─ command-token.ts # findCommandToken / needsExtensionLookup (argv scan before commander) ├─ json.ts # formatJson / formatNdjson (throw on non-serializable) diff --git a/README.md b/README.md index f38933a..1faf20c 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Previously published as `@doist/cli-core`, which no longer receives updates. To | `command-token` | `findCommandToken`, `needsExtensionLookup`, `CommandToken` | Find which argv entry names the command without parsing the rest, stepping over value-taking root flags (`--user`, `--progress-jsonl` by default), and decide whether an invocation needs the installed extensions looked up at all. | | `commands` (subpath) | `registerChangelogCommand`, `registerUpdateCommand` (+ semver helpers) | Commander wiring for cli-core's standard commands (e.g. ` changelog`, ` update`, ` update switch`). **Requires** `commander` as an optional peer-dep. | | `config` | `getConfigPath`, `readConfig`, `readConfigStrict`, `writeConfig`, `updateConfig`, `CoreConfig`, `UpdateChannel` | Read / write a per-CLI JSON config file with typed error codes; `CoreConfig` is the shape of fields cli-core itself owns (extend it for per-CLI fields). | +| `confirmation` | `requireConfirmation`, `previewUnlessConfirmed`, `printDryRun`, `ConfirmationOptions`, `ConfirmationPreview`, `ConfirmationErrorCode` | | `empty` | `printEmpty` | Print an empty-state message gated on `--json` / `--ndjson` / `--ids-only` so machine consumers never see human strings on stdout. | | `errors` | `CliError` | Typed CLI error class with `code` and exit-code mapping. | | `extensions` (subpath) | `createExtensionManager`, `registerExtensionCommands`, `registerExtensionGroup`, `registerExtensionPassThrough`, `createExtension`, `listTemplates`, `defaultTemplatesDir`, `satisfiesRange`, `findManifestProblems`, `mapWithConcurrency`, `ExtensionManagerOptions` / `ExtensionManager` / `Extension` / `ExtensionListing` / `ExtensionCommands` / `ExtensionErrorCode` types | A `gh`-style extension system for any CLI: discover `-*` directories under the data dir, install from GitHub releases, git clones or local paths, upgrade, remove, scaffold from shipped templates, and dispatch ` …` to the executable with the `_*` environment contract. **Requires** `commander` and `zod` as optional peer-deps. | @@ -63,6 +64,35 @@ if (tasks.length === 0) { } ``` +### Confirming destructive commands + +A destructive command previews by default and runs with `--yes`. `requireConfirmation` refuses a script-mode run (`--json`, or the CLI's own `--quiet`) that has neither `--yes` nor `--dry-run`, with `CONFIRMATION_REQUIRED`, before any request is sent. Once the target is resolved, `previewUnlessConfirmed` prints the preview and returns `true` (a `{ status: "preview", command, messages }` object under `--dry-run --json`, the `printDryRun` rows under `--dry-run`, or the summary and `Use --yes to confirm.` without `--yes`), or returns `false` when the command should go ahead. + +```ts +import { previewUnlessConfirmed, requireConfirmation } from '@todoist/cli-core' + +const command = 'td project delete' +const notes = ['Its tasks are deleted with it.'] +const confirmation = { ...options, quiet: isQuiet() } + +requireConfirmation(confirmation, { command, hints: notes }) +const project = await resolveProjectRef(api, ref) + +if ( + previewUnlessConfirmed(confirmation, { + command, + action: 'delete project', + summary: `Would delete project: ${project.name} (id:${project.id})`, + notes, + details: { Project: project.name, ID: project.id }, + }) +) { + return +} + +await api.deleteProject(project.id) +``` + ### Reading piped stdin `readStdin` backs a command's `--stdin` flag. When nothing is piped in (stdin is a terminal) it throws `STDIN_IS_TTY` instead of waiting for an EOF that never comes. It returns the input untrimmed, so the command decides what empty input means. diff --git a/src/confirmation.test.ts b/src/confirmation.test.ts new file mode 100644 index 0000000..5ee0224 --- /dev/null +++ b/src/confirmation.test.ts @@ -0,0 +1,195 @@ +import chalk from 'chalk' +import { beforeEach, describe, expect, it } from 'vitest' +import { previewUnlessConfirmed, printDryRun, requireConfirmation } from './confirmation.js' +import { CliError } from './errors.js' +import { captureConsole } from './testing/index.js' + +const COMMAND = 'td project delete' +const WARNING = 'Its tasks are deleted with it.' + +beforeEach(() => { + chalk.level = 0 +}) + +function lines(spy: ReturnType): unknown[] { + return spy.mock.calls.map((call) => call[0]) +} + +describe('requireConfirmation', () => { + it.each([ + ['--json', { json: true }], + ['--quiet', { quiet: true }], + ])('throws CONFIRMATION_REQUIRED under %s without --yes or --dry-run', (_flag, options) => { + let thrown: unknown + try { + requireConfirmation(options, { command: COMMAND, hints: [WARNING] }) + } catch (error) { + thrown = error + } + + expect(thrown).toBeInstanceOf(CliError) + expect(thrown).toMatchObject({ + code: 'CONFIRMATION_REQUIRED', + message: 'Pass --yes to execute td project delete, or --dry-run to preview it.', + hints: [WARNING], + }) + }) + + it.each([ + ['--json --yes', { json: true, yes: true }], + ['--json --dry-run', { json: true, dryRun: true }], + ['--quiet --yes', { quiet: true, yes: true }], + ['--quiet --dry-run', { quiet: true, dryRun: true }], + ['human output without --yes', {}], + ])('lets %s through', (_flags, options) => { + expect(() => requireConfirmation(options, { command: COMMAND })).not.toThrow() + }) + + it('leaves hints unset when none are given', () => { + expect(() => requireConfirmation({ json: true }, { command: COMMAND })).toThrow( + expect.objectContaining({ code: 'CONFIRMATION_REQUIRED', hints: undefined }), + ) + }) +}) + +describe('previewUnlessConfirmed', () => { + const preview = { + command: COMMAND, + action: 'delete project', + summary: 'Would delete project: Inbox (id:6X7rM8997g3RQmvh)', + notes: [WARNING], + details: { Project: 'Inbox', ID: '6X7rM8997g3RQmvh', Parent: undefined }, + } + + it('with --yes prints nothing and lets the write go ahead', () => { + const spy = captureConsole() + + expect(previewUnlessConfirmed({ yes: true }, preview)).toBe(false) + expect(previewUnlessConfirmed({ yes: true, json: true }, preview)).toBe(false) + expect(spy).not.toHaveBeenCalled() + }) + + it('without --yes prints the summary, the notes and how to confirm', () => { + const spy = captureConsole() + + expect(previewUnlessConfirmed({}, preview)).toBe(true) + expect(lines(spy)).toEqual([ + 'Would delete project: Inbox (id:6X7rM8997g3RQmvh)', + 'Its tasks are deleted with it.', + 'Use --yes to confirm.', + ]) + }) + + it('without notes prints only the summary and how to confirm', () => { + const spy = captureConsole() + + previewUnlessConfirmed({}, { ...preview, notes: undefined }) + + expect(lines(spy)).toEqual([ + 'Would delete project: Inbox (id:6X7rM8997g3RQmvh)', + 'Use --yes to confirm.', + ]) + }) + + it('with --dry-run prints the dry-run preview, even with --yes', () => { + const spy = captureConsole() + + expect(previewUnlessConfirmed({ dryRun: true, yes: true }, preview)).toBe(true) + expect(lines(spy)).toEqual([ + '[dry-run] Would delete project:', + ' Project: Inbox', + ' ID: 6X7rM8997g3RQmvh', + 'Run without --dry-run to execute.', + ]) + }) + + it('with --quiet --dry-run prints the dry-run preview it was asked for', () => { + const spy = captureConsole() + + expect(previewUnlessConfirmed({ dryRun: true, quiet: true }, preview)).toBe(true) + expect(lines(spy)).toEqual([ + '[dry-run] Would delete project:', + ' Project: Inbox', + ' ID: 6X7rM8997g3RQmvh', + 'Run without --dry-run to execute.', + ]) + }) + + it('with --dry-run --json prints one JSON preview envelope', () => { + const spy = captureConsole() + + expect(previewUnlessConfirmed({ dryRun: true, json: true }, preview)).toBe(true) + expect(spy).toHaveBeenCalledTimes(1) + expect(JSON.parse(String(spy.mock.calls[0][0]))).toEqual({ + status: 'preview', + command: 'td project delete', + messages: [ + 'Would delete project: Inbox (id:6X7rM8997g3RQmvh)', + 'Its tasks are deleted with it.', + ], + }) + }) + + it.each([ + ['--json', { json: true }], + ['--quiet', { quiet: true }], + ])( + 'under %s without --yes throws CONFIRMATION_REQUIRED with the notes as hints', + (_flag, options) => { + const spy = captureConsole() + + expect(() => previewUnlessConfirmed(options, preview)).toThrow( + expect.objectContaining({ + code: 'CONFIRMATION_REQUIRED', + message: 'Pass --yes to execute td project delete, or --dry-run to preview it.', + hints: [WARNING], + }), + ) + expect(spy).not.toHaveBeenCalled() + }, + ) +}) + +describe('printDryRun', () => { + it('prints the action, one indented row per defined detail, and how to execute', () => { + const spy = captureConsole() + + printDryRun('archive section', { + Section: 'Later', + ID: '6Jf8VQXxpwv56VQ7', + Note: undefined, + }) + + expect(lines(spy)).toEqual([ + '[dry-run] Would archive section:', + ' Section: Later', + ' ID: 6Jf8VQXxpwv56VQ7', + 'Run without --dry-run to execute.', + ]) + }) + + it('indents the continuation lines of a multi-line value under its row', () => { + const spy = captureConsole() + + printDryRun('add comment', { Content: 'First line\nSecond line\nThird line' }) + + expect(lines(spy)).toEqual([ + '[dry-run] Would add comment:', + ' Content: First line', + ' Second line', + ' Third line', + 'Run without --dry-run to execute.', + ]) + }) + + it('prints only the action and the footer without details', () => { + const spy = captureConsole() + + printDryRun('clear status') + + expect(lines(spy)).toEqual([ + '[dry-run] Would clear status:', + 'Run without --dry-run to execute.', + ]) + }) +}) diff --git a/src/confirmation.ts b/src/confirmation.ts new file mode 100644 index 0000000..039355b --- /dev/null +++ b/src/confirmation.ts @@ -0,0 +1,118 @@ +import chalk from 'chalk' +import { CliError } from './errors.js' +import { formatJson } from './json.js' + +export type ConfirmationErrorCode = 'CONFIRMATION_REQUIRED' + +/** + * The flags that decide whether a destructive command runs, previews or + * refuses. `quiet` is the CLI's own `--quiet`, which the caller reads from + * its global args store. + */ +export type ConfirmationOptions = { + yes?: boolean + dryRun?: boolean + json?: boolean + quiet?: boolean +} + +export type ConfirmationPreview = { + /** The command as typed, such as `td project delete`. */ + command: string + /** Completes the dry-run header `[dry-run] Would :`. */ + action: string + /** One line saying what would happen, such as `Would delete project: Inbox (id:1)`. */ + summary: string + /** + * Lines shown after the summary, such as what breaks once the write goes + * through. They also become the JSON preview's extra messages and the + * hints on `CONFIRMATION_REQUIRED`. + */ + notes?: string[] + /** The rows of the dry-run preview. */ + details?: Record +} + +/** + * Refuse a destructive command that would print a preview where its result + * belongs. + * + * Under `--json` the output is parsed, and under `--quiet` it is only the + * bare result, so a preview printed in its place would be read as the + * result. A missing `--yes` there throws `CONFIRMATION_REQUIRED` instead. + * `--dry-run` asks for the preview, so it passes. Call this before any API + * request, so a refused run sends nothing. + */ +export function requireConfirmation( + options: ConfirmationOptions, + { command, hints }: { command: string; hints?: string[] }, +): void { + if ((options.json || options.quiet) && !options.yes && !options.dryRun) { + throw new CliError( + 'CONFIRMATION_REQUIRED', + `Pass --yes to execute ${command}, or --dry-run to preview it.`, + { hints }, + ) + } +} + +/** + * Print a preview instead of running a destructive command, unless `--yes` + * confirms it. Returns `true` when it printed a preview, so the caller + * returns without writing: + * + * - `--dry-run --json`: one `{ status: "preview", command, messages }` object + * - `--dry-run` (with or without `--yes` or `--quiet`): the + * {@link printDryRun} preview + * - no `--yes`: the summary, the notes and `Use --yes to confirm.` + * + * Under `--json` or `--quiet` without `--yes` it throws, as + * {@link requireConfirmation} does. Call that first, before any API request, + * and this once the entity is resolved and can be named. + */ +export function previewUnlessConfirmed( + options: ConfirmationOptions, + preview: ConfirmationPreview, +): boolean { + const { command, action, summary, notes, details } = preview + requireConfirmation(options, { command, hints: notes }) + + if (options.dryRun) { + if (options.json) { + console.log( + formatJson({ status: 'preview', command, messages: [summary, ...(notes ?? [])] }), + ) + } else { + printDryRun(action, details) + } + return true + } + + if (!options.yes) { + console.log(summary) + for (const note of notes ?? []) console.log(note) + console.log('Use --yes to confirm.') + return true + } + + return false +} + +/** + * Print the standard `--dry-run` preview: a `[dry-run] Would :` + * header, one ` Key: value` row per defined detail (continuation lines of a + * multi-line value indented under it), and how to run it for real. + */ +export function printDryRun( + action: string, + details: Record = {}, +): void { + console.log(chalk.yellow(`[dry-run] Would ${action}:`)) + for (const [key, value] of Object.entries(details)) { + if (value === undefined) continue + const [firstLine, ...rest] = value.split('\n') + console.log(` ${key}: ${firstLine}`) + for (const line of rest) console.log(` ${line}`) + } + console.log(chalk.dim('Run without --dry-run to execute.')) +} diff --git a/src/errors.ts b/src/errors.ts index 1ccf5d8..9498ef9 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,6 +1,7 @@ import type { AuthErrorCode } from './auth/errors.js' import type { CommandErrorCode } from './commands/errors.js' import type { ConfigErrorCode } from './config.js' +import type { ConfirmationErrorCode } from './confirmation.js' import type { ExtensionErrorCode } from './extensions/errors.js' import type { StdinErrorCode } from './stdin.js' @@ -26,6 +27,7 @@ export type CliErrorCode = | AuthErrorCode | CommandErrorCode | ConfigErrorCode + | ConfirmationErrorCode | ExtensionErrorCode | StdinErrorCode diff --git a/src/index.ts b/src/index.ts index bb950e3..a9e7816 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,6 +17,12 @@ export type { UpdateChannel, WriteConfigOptions, } from './config.js' +export { previewUnlessConfirmed, printDryRun, requireConfirmation } from './confirmation.js' +export type { + ConfirmationErrorCode, + ConfirmationOptions, + ConfirmationPreview, +} from './confirmation.js' export { printEmpty } from './empty.js' export { CliError, getErrorMessage } from './errors.js' export type { CliErrorCode, CliErrorOptions, ErrorType } from './errors.js'