@contember/cli-common 2.2.0-alpha.18 → 2.2.0-alpha.19

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 (73) hide show
  1. package/dist/development/index.cjs +7 -0
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +7 -0
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/application/Application.cjs +7 -7
  6. package/dist/development/src/application/Application.cjs.map +1 -1
  7. package/dist/development/src/application/Application.js +7 -7
  8. package/dist/development/src/application/Application.js.map +1 -1
  9. package/dist/development/src/application/ErrorRenderer.cjs +3 -3
  10. package/dist/development/src/application/ErrorRenderer.cjs.map +1 -1
  11. package/dist/development/src/application/ErrorRenderer.js +3 -3
  12. package/dist/development/src/application/ErrorRenderer.js.map +1 -1
  13. package/dist/development/src/application/Output.cjs +72 -39
  14. package/dist/development/src/application/Output.cjs.map +1 -1
  15. package/dist/development/src/application/Output.js +72 -39
  16. package/dist/development/src/application/Output.js.map +1 -1
  17. package/dist/development/src/application/colors.cjs +29 -0
  18. package/dist/development/src/application/colors.cjs.map +1 -0
  19. package/dist/development/src/application/colors.js +29 -0
  20. package/dist/development/src/application/colors.js.map +1 -0
  21. package/dist/development/src/application/table.cjs +23 -0
  22. package/dist/development/src/application/table.cjs.map +1 -0
  23. package/dist/development/src/application/table.js +23 -0
  24. package/dist/development/src/application/table.js.map +1 -0
  25. package/dist/production/index.cjs +7 -0
  26. package/dist/production/index.cjs.map +1 -1
  27. package/dist/production/index.js +7 -0
  28. package/dist/production/index.js.map +1 -1
  29. package/dist/production/src/application/Application.cjs +7 -7
  30. package/dist/production/src/application/Application.cjs.map +1 -1
  31. package/dist/production/src/application/Application.js +7 -7
  32. package/dist/production/src/application/Application.js.map +1 -1
  33. package/dist/production/src/application/ErrorRenderer.cjs +3 -3
  34. package/dist/production/src/application/ErrorRenderer.cjs.map +1 -1
  35. package/dist/production/src/application/ErrorRenderer.js +3 -3
  36. package/dist/production/src/application/ErrorRenderer.js.map +1 -1
  37. package/dist/production/src/application/Output.cjs +72 -39
  38. package/dist/production/src/application/Output.cjs.map +1 -1
  39. package/dist/production/src/application/Output.js +72 -39
  40. package/dist/production/src/application/Output.js.map +1 -1
  41. package/dist/production/src/application/colors.cjs +29 -0
  42. package/dist/production/src/application/colors.cjs.map +1 -0
  43. package/dist/production/src/application/colors.js +29 -0
  44. package/dist/production/src/application/colors.js.map +1 -0
  45. package/dist/production/src/application/table.cjs +23 -0
  46. package/dist/production/src/application/table.cjs.map +1 -0
  47. package/dist/production/src/application/table.js +23 -0
  48. package/dist/production/src/application/table.js.map +1 -0
  49. package/dist/types/application/Output.d.ts +23 -8
  50. package/dist/types/application/Output.d.ts.map +1 -1
  51. package/dist/types/application/colors.d.ts +10 -0
  52. package/dist/types/application/colors.d.ts.map +1 -0
  53. package/dist/types/application/index.d.ts +2 -0
  54. package/dist/types/application/index.d.ts.map +1 -1
  55. package/dist/types/application/table.d.ts +7 -0
  56. package/dist/types/application/table.d.ts.map +1 -0
  57. package/dist/types/index.d.ts +2 -2
  58. package/dist/types/index.d.ts.map +1 -1
  59. package/dist/types/tsconfig.tsbuildinfo +1 -1
  60. package/package.json +2 -7
  61. package/src/application/Application.ts +7 -7
  62. package/src/application/ErrorRenderer.ts +3 -3
  63. package/src/application/Output.ts +85 -49
  64. package/src/application/colors.ts +36 -0
  65. package/src/application/index.ts +2 -0
  66. package/src/application/table.ts +31 -0
  67. package/src/index.ts +8 -1
  68. package/tests/cases/unit/application.test.ts +2 -2
  69. package/tests/cases/unit/cliError.test.ts +2 -2
  70. package/tests/cases/unit/colors.test.ts +49 -0
  71. package/tests/cases/unit/output.test.ts +63 -22
  72. package/tests/lib/testOutput.ts +10 -2
  73. package/types/chalk-table/index.d.ts +0 -9
@@ -1,14 +1,12 @@
1
- /// <reference path="../../types/chalk-table/index.d.ts" />
2
-
3
- import chalk from 'chalk'
4
- import chalkTable from 'chalk-table'
5
- import { Writable } from 'node:stream'
1
+ import { createInterface, type Interface } from 'node:readline'
2
+ import type { Readable } from 'node:stream'
3
+ import { CliError, ExitCode } from './CliError.js'
4
+ import { setColorsEnabled, style, terminalSupportsColor } from './colors.js'
6
5
  import type { GlobalOptionValues } from './GlobalOptions.js'
6
+ import { formatTable } from './table.js'
7
7
 
8
8
  export type OutputMode = 'human' | 'json' | 'quiet'
9
9
 
10
- let supportedChalkLevel = chalk.level
11
-
12
10
  export interface OutputStream {
13
11
  write(text: string): void
14
12
  readonly isTty: boolean
@@ -16,15 +14,14 @@ export interface OutputStream {
16
14
  onError?(listener: (error: unknown) => void): void
17
15
  }
18
16
 
17
+ /** Reads one line of the user's answer, or `undefined` when the input is closed. */
18
+ export type PromptLineReader = () => Promise<string | undefined>
19
+
19
20
  export interface OutputOptions {
20
21
  stdout?: OutputStream
21
22
  stderr?: OutputStream
22
23
  isStdinTty?: () => boolean
23
- }
24
-
25
- export interface PromptOutputStream extends Writable {
26
- readonly isTTY: boolean
27
- readonly columns: number
24
+ readPromptLine?: PromptLineReader
28
25
  }
29
26
 
30
27
  export type OutputScalar = string | number | boolean | bigint | null | undefined
@@ -71,13 +68,13 @@ export class Output {
71
68
  private readonly stdout: OutputStream
72
69
  private readonly stderr: OutputStream
73
70
  private readonly stdinIsTty: () => boolean
74
- private readonly promptStderr: PromptOutputStream
71
+ private readonly readPromptLine: PromptLineReader
75
72
 
76
73
  constructor(options: OutputOptions = {}) {
77
74
  this.stdout = options.stdout ?? createProcessStream(process.stdout)
78
75
  this.stderr = options.stderr ?? createProcessStream(process.stderr)
79
76
  this.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true)
80
- this.promptStderr = options.stderr === undefined ? process.stderr : createPromptStream(this.stderr)
77
+ this.readPromptLine = options.readPromptLine ?? readStdinLine
81
78
  this.stdout.onError?.(handleStreamError)
82
79
  this.stderr.onError?.(handleStreamError)
83
80
  }
@@ -101,18 +98,7 @@ export class Output {
101
98
 
102
99
  public applyGlobalOptions(globals: GlobalOptionValues): void {
103
100
  this.setMode(resolveOutputMode(globals))
104
- if (globals.color && this.currentMode === 'human') {
105
- if (chalk.level === 0) {
106
- chalk.level = supportedChalkLevel
107
- } else {
108
- supportedChalkLevel = chalk.level
109
- }
110
- } else {
111
- if (chalk.level !== 0) {
112
- supportedChalkLevel = chalk.level
113
- }
114
- chalk.level = 0
115
- }
101
+ setColorsEnabled(globals.color && this.currentMode === 'human' && terminalSupportsColor)
116
102
  }
117
103
 
118
104
  // DATA → stdout
@@ -154,14 +140,14 @@ export class Output {
154
140
  if (rows.length === 0) {
155
141
  return
156
142
  }
157
- const data: Record<string, string>[] = rows.map(row => {
158
- const cells: Record<string, string> = {}
143
+ const data = rows.map(row => {
144
+ const cells: Partial<Record<keyof T & string, string>> = {}
159
145
  for (const column of columns) {
160
146
  cells[column.field] = renderTableCell(column, row)
161
147
  }
162
148
  return cells
163
149
  })
164
- this.writeStdout(chalkTable<string>({ columns: columns.map(it => ({ field: it.field, name: it.name })) }, data))
150
+ this.writeStdout(formatTable(columns.map(it => ({ field: it.field, name: it.name })), data))
165
151
  }
166
152
 
167
153
  // DIAGNOSTICS → stderr
@@ -171,11 +157,11 @@ export class Output {
171
157
  }
172
158
 
173
159
  public warn(message: string): void {
174
- this.writeDiagnostic(message, text => chalk.yellow(text))
160
+ this.writeDiagnostic(message, text => style('yellow', text))
175
161
  }
176
162
 
177
163
  public error(message: string): void {
178
- this.writeDiagnostic(message, text => chalk.red(text))
164
+ this.writeDiagnostic(message, text => style('red', text))
179
165
  }
180
166
 
181
167
  // PROGRESS → stderr
@@ -202,9 +188,14 @@ export class Output {
202
188
  return this.currentMode === 'human' && this.stdinIsTty() && this.stderr.isTty
203
189
  }
204
190
 
205
- /** A real Writable suitable for the `stdout` option of interactive prompt libraries. */
206
- public get promptOutput(): PromptOutputStream {
207
- return this.promptStderr
191
+ /** Writes `question` to stderr and reads one answer line. */
192
+ public prompt(question: string): Promise<string | undefined> {
193
+ if (!this.canPrompt()) {
194
+ throw new CliError('TTY not available. Pass --yes to confirm.', { code: 'TTY_UNAVAILABLE', exitCode: ExitCode.InputError })
195
+ }
196
+ this.clearProgress()
197
+ writeStream(this.stderr, question)
198
+ return this.readPromptLine()
208
199
  }
209
200
 
210
201
  /**
@@ -245,30 +236,75 @@ const createProcessStream = (stream: NodeJS.WriteStream): OutputStream => ({
245
236
  },
246
237
  })
247
238
 
248
- class PromptWritable extends Writable {
249
- public readonly isTTY: boolean
239
+ let stdinReader: LineReader | undefined
240
+ const readStdinLine: PromptLineReader = () => {
241
+ stdinReader ??= new LineReader(process.stdin)
242
+ return stdinReader.read()
243
+ }
250
244
 
251
- constructor(private readonly stream: OutputStream) {
252
- super({ decodeStrings: false })
253
- this.isTTY = stream.isTty
245
+ /**
246
+ * Reads answer lines from one input for all prompts, so that a line typed or pasted ahead of the next prompt is kept
247
+ * and an input that already ended reads as closed. Not in readline's terminal mode: the TTY handles line editing and
248
+ * echo, and Ctrl+C stays a plain SIGINT.
249
+ */
250
+ export class LineReader {
251
+ private reader: Interface | undefined
252
+ private readonly lines: string[] = []
253
+ private waiting: ((line: string | undefined) => void) | undefined
254
+ private closed = false
255
+
256
+ constructor(private readonly input: Readable) {}
257
+
258
+ public read(): Promise<string | undefined> {
259
+ if (this.waiting) {
260
+ throw new Error('LineReader: a read is already pending')
261
+ }
262
+ const line = this.lines.shift()
263
+ if (line !== undefined) {
264
+ return Promise.resolve(line)
265
+ }
266
+ // readline never reports `close` for an input that ended before it was attached (Bun does not set readableEnded)
267
+ if (this.closed || this.input.readableEnded) {
268
+ this.closed = true
269
+ return Promise.resolve(undefined)
270
+ }
271
+ return new Promise(resolve => {
272
+ this.waiting = resolve
273
+ this.open().resume()
274
+ })
254
275
  }
255
276
 
256
- public get columns(): number {
257
- return this.stream.columns ?? 80
277
+ private open(): Interface {
278
+ if (this.reader) {
279
+ return this.reader
280
+ }
281
+ const reader = createInterface({ input: this.input, terminal: false })
282
+ reader.on('line', line => this.settle(line))
283
+ reader.on('close', () => {
284
+ this.closed = true
285
+ this.settle(undefined)
286
+ })
287
+ this.reader = reader
288
+ return reader
258
289
  }
259
290
 
260
- public override _write(chunk: string | Uint8Array, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
261
- try {
262
- writeStream(this.stream, typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(encoding))
263
- callback()
264
- } catch (error) {
265
- callback(error instanceof Error ? error : new Error(String(error)))
291
+ private settle(line: string | undefined): void {
292
+ const waiting = this.waiting
293
+ if (!waiting) {
294
+ if (line !== undefined) {
295
+ this.lines.push(line)
296
+ }
297
+ return
298
+ }
299
+ this.waiting = undefined
300
+ if (!this.closed) {
301
+ // a paused TTY does not keep the process alive between prompts; Node throws when pausing a closed interface
302
+ this.reader?.pause()
266
303
  }
304
+ waiting(line)
267
305
  }
268
306
  }
269
307
 
270
- const createPromptStream = (stream: OutputStream): PromptOutputStream => new PromptWritable(stream)
271
-
272
308
  const writeStream = (stream: OutputStream, text: string): void => {
273
309
  try {
274
310
  stream.write(text)
@@ -0,0 +1,36 @@
1
+ import { styleText } from 'node:util'
2
+
3
+ export type TextStyle = Exclude<Parameters<typeof styleText>[0], readonly unknown[]>
4
+
5
+ // Same detection as in @contember/logger's PrettyPrintLoggerHandler (which cannot depend on cli-common); keep them in sync.
6
+ const detectColorSupport = (): boolean => {
7
+ const forceColor = process.env.FORCE_COLOR
8
+ if (forceColor !== undefined) {
9
+ return forceColor !== '0' && forceColor !== 'false'
10
+ }
11
+ // hasColors() honours NO_COLOR, NODE_DISABLE_COLORS and TERM=dumb; Bun's non-TTY stdout has no hasColors.
12
+ const stdout = process.stdout
13
+ return stdout.isTTY === true && (typeof stdout.hasColors !== 'function' || stdout.hasColors())
14
+ }
15
+
16
+ /** Whether stdout can show colors, detected once at startup. */
17
+ export const terminalSupportsColor: boolean = detectColorSupport()
18
+
19
+ let colorsEnabled = terminalSupportsColor
20
+
21
+ /** Turns colored output on or off for the whole process (`--no-color`, machine-readable modes). */
22
+ export const setColorsEnabled = (enabled: boolean): void => {
23
+ colorsEnabled = enabled
24
+ }
25
+
26
+ export const areColorsEnabled = (): boolean => colorsEnabled
27
+
28
+ /** Styles `text` with the given styles (outermost first), or returns it unchanged when colors are off. */
29
+ export const style = (styles: TextStyle | readonly TextStyle[], text: string): string => {
30
+ if (!colorsEnabled) {
31
+ return text
32
+ }
33
+ const list: readonly TextStyle[] = typeof styles === 'string' ? [styles] : styles
34
+ // validateStream is off because the decision above is ours; Bun ignores the option and Node < 22.13 lacks it.
35
+ return list.reduceRight((result, current) => styleText(current, result, { validateStream: false }), text)
36
+ }
@@ -2,6 +2,7 @@ export * from './Application.js'
2
2
  export * from './Argument.js'
3
3
  export * from './assertNever.js'
4
4
  export * from './CliError.js'
5
+ export * from './colors.js'
5
6
  export * from './Command.js'
6
7
  export * from './CommandManager.js'
7
8
  export * from './CommandConfiguration.js'
@@ -12,4 +13,5 @@ export * from './Input.js'
12
13
  export * from './InputParser.js'
13
14
  export * from './Option.js'
14
15
  export * from './Output.js'
16
+ export * from './table.js'
15
17
  export * from './UsageFormatter.js'
@@ -0,0 +1,31 @@
1
+ import { stripVTControlCharacters } from 'node:util'
2
+ import { style } from './colors.js'
3
+
4
+ export interface TableColumn<Field extends string> {
5
+ readonly field: Field
6
+ readonly name: string
7
+ }
8
+
9
+ const visibleLength = (text: string): number => stripVTControlCharacters(text).length
10
+
11
+ const pad = (text: string, width: number): string => text + ' '.repeat(Math.max(width - visibleLength(text), 0))
12
+
13
+ /** Renders an ASCII table with bold headers; widths ignore ANSI styling in the cells. */
14
+ export const formatTable = <Field extends string>(
15
+ columns: readonly TableColumn<Field>[],
16
+ rows: readonly Partial<Record<Field, string>>[],
17
+ ): string => {
18
+ const headers = columns.map(column => style('bold', column.name))
19
+ const widths = columns.map((column, index) =>
20
+ rows.reduce((width, row) => Math.max(width, visibleLength(row[column.field] ?? '')), visibleLength(headers[index]))
21
+ )
22
+ const separator = `+${widths.map(width => '-'.repeat(width + 2)).join('+')}+`
23
+ const line = (cells: readonly string[]): string => `| ${cells.map((cell, index) => pad(cell, widths[index])).join(' | ')} |`
24
+ return [
25
+ separator,
26
+ line(headers),
27
+ separator,
28
+ ...rows.map(row => line(columns.map(column => row[column.field] ?? ''))),
29
+ separator,
30
+ ].join('\n')
31
+ }
package/src/index.ts CHANGED
@@ -16,10 +16,13 @@ export type {
16
16
  OutputTableColumn,
17
17
  OutputTableColumns,
18
18
  ParsedCommandInput,
19
- PromptOutputStream,
19
+ PromptLineReader,
20
+ TableColumn,
21
+ TextStyle,
20
22
  } from './application/index.js'
21
23
  export {
22
24
  Application,
25
+ areColorsEnabled,
23
26
  CliError,
24
27
  Command,
25
28
  CommandConfiguration,
@@ -27,6 +30,7 @@ export {
27
30
  escapeTerminalText,
28
31
  ExitCode,
29
32
  exitProcess,
33
+ formatTable,
30
34
  globalOptions,
31
35
  Input,
32
36
  InvalidConfigurationError,
@@ -36,6 +40,9 @@ export {
36
40
  Output,
37
41
  readGlobalOptionsFromArgs,
38
42
  renderCliError,
43
+ setColorsEnabled,
44
+ style,
45
+ terminalSupportsColor,
39
46
  toCliError,
40
47
  } from './application/index.js'
41
48
  export * from './npm/index.js'
@@ -1,5 +1,5 @@
1
1
  import { beforeAll, describe, expect, spyOn, test } from 'bun:test'
2
- import chalk from 'chalk'
2
+ import { setColorsEnabled } from '../../../src/index.js'
3
3
  import {
4
4
  Application,
5
5
  CliError,
@@ -18,7 +18,7 @@ import {
18
18
  import { createTestOutput, TestOutput } from '../../lib/testOutput.js'
19
19
 
20
20
  beforeAll(() => {
21
- chalk.level = 0
21
+ setColorsEnabled(false)
22
22
  })
23
23
 
24
24
  type PrintSchemaOptions = {
@@ -1,10 +1,10 @@
1
1
  import { beforeAll, describe, expect, test } from 'bun:test'
2
- import chalk from 'chalk'
2
+ import { setColorsEnabled } from '../../../src/index.js'
3
3
  import { CliError, ExitCode, InvalidInputError, renderCliError, toCliError } from '../../../src/index.js'
4
4
  import { createTestOutput } from '../../lib/testOutput.js'
5
5
 
6
6
  beforeAll(() => {
7
- chalk.level = 0
7
+ setColorsEnabled(false)
8
8
  })
9
9
 
10
10
  describe('toCliError', () => {
@@ -0,0 +1,49 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test'
2
+ import { formatTable, setColorsEnabled, style, terminalSupportsColor } from '../../../src/index.js'
3
+
4
+ afterEach(() => setColorsEnabled(false))
5
+
6
+ describe('style', () => {
7
+ test('returns the text unchanged when colors are off', () => {
8
+ setColorsEnabled(false)
9
+ expect(style('red', 'x')).toBe('x')
10
+ expect(style(['bgRedBright', 'white'], 'x')).toBe('x')
11
+ })
12
+
13
+ test('wraps the text in the styles, outermost first', () => {
14
+ setColorsEnabled(true)
15
+ expect(style('red', 'x')).toBe('\u001b[31mx\u001b[39m')
16
+ expect(style(['bgRedBright', 'white'], 'x')).toBe('\u001b[101m\u001b[37mx\u001b[39m\u001b[49m')
17
+ })
18
+
19
+ test.skipIf(process.stdout.isTTY === true || process.env.FORCE_COLOR !== undefined)(
20
+ 'a non-TTY stdout without FORCE_COLOR has no color support',
21
+ () => {
22
+ expect(terminalSupportsColor).toBe(false)
23
+ },
24
+ )
25
+ })
26
+
27
+ describe('formatTable', () => {
28
+ const columns = [{ field: 'status', name: 'Status' }, { field: 'name', name: 'Migration' }] as const
29
+
30
+ test('pads cells to the widest value and frames the table', () => {
31
+ setColorsEnabled(false)
32
+ expect(formatTable(columns, [{ status: 'Executed', name: '2024-01-01-a' }, { status: 'Skip', name: 'b' }])).toBe([
33
+ '+----------+--------------+',
34
+ '| Status | Migration |',
35
+ '+----------+--------------+',
36
+ '| Executed | 2024-01-01-a |',
37
+ '| Skip | b |',
38
+ '+----------+--------------+',
39
+ ].join('\n'))
40
+ })
41
+
42
+ test('ignores ANSI styling when measuring and renders missing cells empty', () => {
43
+ setColorsEnabled(true)
44
+ const lines = formatTable(columns, [{ status: style('red', 'ERROR') }]).split('\n')
45
+ expect(lines[0]).toBe('+--------+-----------+')
46
+ expect(lines[1]).toBe('| \u001b[1mStatus\u001b[22m | \u001b[1mMigration\u001b[22m |')
47
+ expect(lines[3]).toBe('| \u001b[31mERROR\u001b[39m | |')
48
+ })
49
+ })
@@ -1,11 +1,13 @@
1
1
  import { beforeAll, describe, expect, test } from 'bun:test'
2
- import chalk from 'chalk'
2
+ import { PassThrough } from 'node:stream'
3
+ import { areColorsEnabled, setColorsEnabled, terminalSupportsColor } from '../../../src/index.js'
3
4
  import { escapeTerminalText, Output, OutputStream, OutputTableColumn } from '../../../src/index.js'
5
+ import { LineReader } from '../../../src/application/Output.js'
4
6
  import { CapturingStream, createTestOutput } from '../../lib/testOutput.js'
5
7
 
6
8
  beforeAll(() => {
7
9
  // deterministic assertions regardless of the terminal the suite runs in
8
- chalk.level = 0
10
+ setColorsEnabled(false)
9
11
  })
10
12
 
11
13
  describe('Output.data', () => {
@@ -333,24 +335,63 @@ describe('Output.canPrompt', () => {
333
335
  })
334
336
  })
335
337
 
336
- describe('Output.promptOutput', () => {
337
- test('uses the real process stderr by default', () => {
338
- const output = new Output()
339
- expect(output.promptOutput).toBe(process.stderr)
338
+ describe('Output.prompt', () => {
339
+ test('writes the question to stderr, clears progress and returns the answer', async () => {
340
+ const { output, stderr } = createTestOutput({ stdinTty: true, stderrTty: true, answers: ['yes'] })
341
+ output.progress('working')
342
+
343
+ expect(await output.prompt('Continue? ')).toBe('yes')
344
+ expect(stderr.text).toBe('working\r\u001b[KContinue? ')
340
345
  })
341
346
 
342
- test('adapts an injected diagnostic stream to a Writable with TTY metadata', async () => {
343
- const stderr = new CapturingStream(true, 132)
344
- const output = new Output({ stderr })
347
+ test('refuses to prompt without a TTY or outside human mode', () => {
348
+ const { output, stderr } = createTestOutput({ stdinTty: false, stderrTty: true, answers: ['yes'] })
349
+ expect(() => output.prompt('Continue? ')).toThrow(expect.objectContaining({ code: 'TTY_UNAVAILABLE' }))
350
+ const json = createTestOutput({ stdinTty: true, stderrTty: true, answers: ['yes'] })
351
+ json.output.setMode('json')
352
+ expect(() => json.output.prompt('Continue? ')).toThrow(expect.objectContaining({ code: 'TTY_UNAVAILABLE' }))
353
+ expect(stderr.text).toBe('')
354
+ })
345
355
 
346
- expect(output.promptOutput.writable).toBe(true)
347
- expect(output.promptOutput.isTTY).toBe(true)
348
- expect(output.promptOutput.columns).toBe(132)
356
+ test('returns undefined when no answer is left', async () => {
357
+ const { output } = createTestOutput({ stdinTty: true, stderrTty: true, answers: [] })
358
+ expect(await output.prompt('Continue? ')).toBeUndefined()
359
+ })
360
+ })
349
361
 
350
- await new Promise<void>((resolve, reject) => {
351
- output.promptOutput.write('prompt text', error => error ? reject(error) : resolve())
352
- })
353
- expect(stderr.text).toBe('prompt text')
362
+ describe('LineReader', () => {
363
+ test('reads one line per call and keeps lines that arrived ahead of the next call', async () => {
364
+ const input = new PassThrough()
365
+ const reader = new LineReader(input)
366
+ const first = reader.read()
367
+ input.write('yes\nno\n')
368
+ expect(await first).toBe('yes')
369
+ expect(await reader.read()).toBe('no')
370
+ })
371
+
372
+ test('reads as closed once the input ended, also on later calls', async () => {
373
+ const input = new PassThrough()
374
+ const reader = new LineReader(input)
375
+ const first = reader.read()
376
+ input.write('last\n')
377
+ expect(await first).toBe('last')
378
+ input.end()
379
+ expect(await reader.read()).toBeUndefined()
380
+ expect(await reader.read()).toBeUndefined()
381
+ })
382
+
383
+ test('reads as closed when the input ended before the first read', async () => {
384
+ const input = new PassThrough()
385
+ input.resume()
386
+ input.end()
387
+ await new Promise(resolve => input.once('end', resolve))
388
+ expect(await new LineReader(input).read()).toBeUndefined()
389
+ })
390
+
391
+ test('refuses a second read while one is pending', () => {
392
+ const reader = new LineReader(new PassThrough())
393
+ void reader.read()
394
+ expect(() => reader.read()).toThrow('already pending')
354
395
  })
355
396
  })
356
397
 
@@ -375,19 +416,19 @@ describe('Output.applyGlobalOptions', () => {
375
416
  expect(output.mode).toBe('human')
376
417
  })
377
418
 
378
- test('--no-color turns chalk off', () => {
419
+ test('--no-color turns colors off', () => {
379
420
  const { output } = createTestOutput()
380
- chalk.level = 3
421
+ setColorsEnabled(true)
381
422
  output.applyGlobalOptions({ json: false, quiet: false, color: false, help: false })
382
- expect(chalk.level).toBe(0)
423
+ expect(areColorsEnabled()).toBe(false)
383
424
  })
384
425
 
385
426
  test('restores supported color after a machine execution', () => {
386
427
  const { output } = createTestOutput()
387
- chalk.level = 2
428
+ setColorsEnabled(true)
388
429
  output.applyGlobalOptions({ json: true, quiet: false, color: true, help: false })
389
- expect(chalk.level).toBe(0)
430
+ expect(areColorsEnabled()).toBe(false)
390
431
  output.applyGlobalOptions({ json: false, quiet: false, color: true, help: false })
391
- expect(chalk.level).toBe(2)
432
+ expect(areColorsEnabled()).toBe(terminalSupportsColor)
392
433
  })
393
434
  })
@@ -24,12 +24,20 @@ export interface TestOutput {
24
24
  stderr: CapturingStream
25
25
  }
26
26
 
27
- export const createTestOutput = ({ stderrTty = false, stdinTty = false }: { stderrTty?: boolean; stdinTty?: boolean } = {}): TestOutput => {
27
+ export interface TestOutputOptions {
28
+ stderrTty?: boolean
29
+ stdinTty?: boolean
30
+ /** Lines answered to prompts, in order; once they run out, the input reads as closed. */
31
+ answers?: readonly string[]
32
+ }
33
+
34
+ export const createTestOutput = ({ stderrTty = false, stdinTty = false, answers = [] }: TestOutputOptions = {}): TestOutput => {
28
35
  const stdout = new CapturingStream()
29
36
  const stderr = new CapturingStream(stderrTty)
37
+ const pending = [...answers]
30
38
  return {
31
39
  stdout,
32
40
  stderr,
33
- output: new Output({ stdout, stderr, isStdinTty: () => stdinTty }),
41
+ output: new Output({ stdout, stderr, isStdinTty: () => stdinTty, readPromptLine: async () => pending.shift() }),
34
42
  }
35
43
  }
@@ -1,9 +0,0 @@
1
- declare module 'chalk-table' {
2
- export default function chalkTable<Keys extends string>(
3
- options: {
4
- intersectionCharacter?: string
5
- columns?: (Keys | { field: Keys; name: string })[]
6
- },
7
- data: Record<Keys, string>[],
8
- ): string
9
- }