@contember/cli-common 2.2.0-alpha.17 → 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.
- package/dist/development/index.cjs +7 -0
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +7 -0
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/application/Application.cjs +7 -7
- package/dist/development/src/application/Application.cjs.map +1 -1
- package/dist/development/src/application/Application.js +7 -7
- package/dist/development/src/application/Application.js.map +1 -1
- package/dist/development/src/application/ErrorRenderer.cjs +3 -3
- package/dist/development/src/application/ErrorRenderer.cjs.map +1 -1
- package/dist/development/src/application/ErrorRenderer.js +3 -3
- package/dist/development/src/application/ErrorRenderer.js.map +1 -1
- package/dist/development/src/application/Output.cjs +72 -39
- package/dist/development/src/application/Output.cjs.map +1 -1
- package/dist/development/src/application/Output.js +72 -39
- package/dist/development/src/application/Output.js.map +1 -1
- package/dist/development/src/application/colors.cjs +29 -0
- package/dist/development/src/application/colors.cjs.map +1 -0
- package/dist/development/src/application/colors.js +29 -0
- package/dist/development/src/application/colors.js.map +1 -0
- package/dist/development/src/application/table.cjs +23 -0
- package/dist/development/src/application/table.cjs.map +1 -0
- package/dist/development/src/application/table.js +23 -0
- package/dist/development/src/application/table.js.map +1 -0
- package/dist/production/index.cjs +7 -0
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +7 -0
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/application/Application.cjs +7 -7
- package/dist/production/src/application/Application.cjs.map +1 -1
- package/dist/production/src/application/Application.js +7 -7
- package/dist/production/src/application/Application.js.map +1 -1
- package/dist/production/src/application/ErrorRenderer.cjs +3 -3
- package/dist/production/src/application/ErrorRenderer.cjs.map +1 -1
- package/dist/production/src/application/ErrorRenderer.js +3 -3
- package/dist/production/src/application/ErrorRenderer.js.map +1 -1
- package/dist/production/src/application/Output.cjs +72 -39
- package/dist/production/src/application/Output.cjs.map +1 -1
- package/dist/production/src/application/Output.js +72 -39
- package/dist/production/src/application/Output.js.map +1 -1
- package/dist/production/src/application/colors.cjs +29 -0
- package/dist/production/src/application/colors.cjs.map +1 -0
- package/dist/production/src/application/colors.js +29 -0
- package/dist/production/src/application/colors.js.map +1 -0
- package/dist/production/src/application/table.cjs +23 -0
- package/dist/production/src/application/table.cjs.map +1 -0
- package/dist/production/src/application/table.js +23 -0
- package/dist/production/src/application/table.js.map +1 -0
- package/dist/types/application/Output.d.ts +23 -8
- package/dist/types/application/Output.d.ts.map +1 -1
- package/dist/types/application/colors.d.ts +10 -0
- package/dist/types/application/colors.d.ts.map +1 -0
- package/dist/types/application/index.d.ts +2 -0
- package/dist/types/application/index.d.ts.map +1 -1
- package/dist/types/application/table.d.ts +7 -0
- package/dist/types/application/table.d.ts.map +1 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -7
- package/src/application/Application.ts +7 -7
- package/src/application/ErrorRenderer.ts +3 -3
- package/src/application/Output.ts +85 -49
- package/src/application/colors.ts +36 -0
- package/src/application/index.ts +2 -0
- package/src/application/table.ts +31 -0
- package/src/index.ts +8 -1
- package/tests/cases/unit/application.test.ts +2 -2
- package/tests/cases/unit/cliError.test.ts +2 -2
- package/tests/cases/unit/colors.test.ts +49 -0
- package/tests/cases/unit/output.test.ts +63 -22
- package/tests/lib/testOutput.ts +10 -2
- package/types/chalk-table/index.d.ts +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Output.cjs","sources":["../../../../../packages/cli-common/src/application/Output.ts"],"sourcesContent":["/// <reference path=\"../../types/chalk-table/index.d.ts\" />\n\nimport chalk from 'chalk'\nimport chalkTable from 'chalk-table'\nimport { Writable } from 'node:stream'\nimport type { GlobalOptionValues } from './GlobalOptions.js'\n\nexport type OutputMode = 'human' | 'json' | 'quiet'\n\nlet supportedChalkLevel = chalk.level\n\nexport interface OutputStream {\n\twrite(text: string): void\n\treadonly isTty: boolean\n\treadonly columns?: number\n\tonError?(listener: (error: unknown) => void): void\n}\n\nexport interface OutputOptions {\n\tstdout?: OutputStream\n\tstderr?: OutputStream\n\tisStdinTty?: () => boolean\n}\n\nexport interface PromptOutputStream extends Writable {\n\treadonly isTTY: boolean\n\treadonly columns: number\n}\n\nexport type OutputScalar = string | number | boolean | bigint | null | undefined\n\nexport interface OutputDataOptions<T> {\n\thuman?: (value: T) => string\n\tquiet?: (value: T) => OutputScalar | readonly OutputScalar[]\n}\n\n/**\n * Per field column specs, so that each `format` sees the exact type of its own field. Indexed by the\n * field name only to let {@link Output.table} render a cell without widening the union.\n */\nexport type OutputTableColumns<T> = {\n\t[K in keyof T & string]: {\n\t\tfield: K\n\t\tname: string\n\t\t/** Human mode only — `--json` still emits the raw row and `--quiet` the raw value. */\n\t\tformat?: (value: T[K], row: T) => string\n\t}\n}\n\nexport type OutputTableColumn<T> = OutputTableColumns<T>[keyof T & string]\n\nexport const resolveOutputMode = (globals: GlobalOptionValues): OutputMode => {\n\tif (globals.json) {\n\t\treturn 'json'\n\t}\n\tif (globals.quiet) {\n\t\treturn 'quiet'\n\t}\n\treturn 'human'\n}\n\n/**\n * The single output channel of the CLI: stdout carries data, stderr carries everything a human reads.\n *\n * The instance is created before argv is parsed, so the mode is mutable and set by `Application` once\n * the global options are known. Every consumer holds the same instance.\n */\nexport class Output {\n\tprivate currentMode: OutputMode = 'human'\n\tprivate progressVisible = false\n\tprivate readonly stdout: OutputStream\n\tprivate readonly stderr: OutputStream\n\tprivate readonly stdinIsTty: () => boolean\n\tprivate readonly promptStderr: PromptOutputStream\n\n\tconstructor(options: OutputOptions = {}) {\n\t\tthis.stdout = options.stdout ?? createProcessStream(process.stdout)\n\t\tthis.stderr = options.stderr ?? createProcessStream(process.stderr)\n\t\tthis.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true)\n\t\tthis.promptStderr = options.stderr === undefined ? process.stderr : createPromptStream(this.stderr)\n\t\tthis.stdout.onError?.(handleStreamError)\n\t\tthis.stderr.onError?.(handleStreamError)\n\t}\n\n\tpublic get mode(): OutputMode {\n\t\treturn this.currentMode\n\t}\n\n\tpublic get isJson(): boolean {\n\t\treturn this.currentMode === 'json'\n\t}\n\n\tpublic get isQuiet(): boolean {\n\t\treturn this.currentMode === 'quiet'\n\t}\n\n\t/** Set by `Application` once the global options are parsed. */\n\tpublic setMode(mode: OutputMode): void {\n\t\tthis.currentMode = mode\n\t}\n\n\tpublic applyGlobalOptions(globals: GlobalOptionValues): void {\n\t\tthis.setMode(resolveOutputMode(globals))\n\t\tif (globals.color && this.currentMode === 'human') {\n\t\t\tif (chalk.level === 0) {\n\t\t\t\tchalk.level = supportedChalkLevel\n\t\t\t} else {\n\t\t\t\tsupportedChalkLevel = chalk.level\n\t\t\t}\n\t\t} else {\n\t\t\tif (chalk.level !== 0) {\n\t\t\t\tsupportedChalkLevel = chalk.level\n\t\t\t}\n\t\t\tchalk.level = 0\n\t\t}\n\t}\n\n\t// DATA → stdout\n\n\t/** Prints command data with optional mode-specific projections. JSON always receives the raw value. */\n\tpublic data<T>(value: T, human?: (value: T) => string): void\n\tpublic data<T>(value: T, options?: OutputDataOptions<T>): void\n\tpublic data<T>(value: T, rendering?: ((value: T) => string) | OutputDataOptions<T>): void {\n\t\tconst human = typeof rendering === 'function' ? rendering : rendering?.human\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(value ?? null, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst quietValue = typeof rendering === 'object' && rendering.quiet ? rendering.quiet(value) : value\n\t\t\tfor (const line of toScalarLines(quietValue)) {\n\t\t\t\tthis.writeStdout(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.writeStdout(human ? human(value) : JSON.stringify(value ?? null, null, 2))\n\t}\n\n\tpublic table<T>(columns: OutputTableColumn<T>[], rows: T[], quietField?: keyof T & string): void {\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(rows, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst field = quietField ?? columns[0]?.field\n\t\t\tif (field === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const row of rows) {\n\t\t\t\tthis.writeStdout(formatCell(row[field]))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (rows.length === 0) {\n\t\t\treturn\n\t\t}\n\t\tconst data: Record<string, string>[] = rows.map(row => {\n\t\t\tconst cells: Record<string, string> = {}\n\t\t\tfor (const column of columns) {\n\t\t\t\tcells[column.field] = renderTableCell(column, row)\n\t\t\t}\n\t\t\treturn cells\n\t\t})\n\t\tthis.writeStdout(chalkTable<string>({ columns: columns.map(it => ({ field: it.field, name: it.name })) }, data))\n\t}\n\n\t// DIAGNOSTICS → stderr\n\n\tpublic info(message: string): void {\n\t\tthis.writeDiagnostic(message)\n\t}\n\n\tpublic warn(message: string): void {\n\t\tthis.writeDiagnostic(message, text => chalk.yellow(text))\n\t}\n\n\tpublic error(message: string): void {\n\t\tthis.writeDiagnostic(message, text => chalk.red(text))\n\t}\n\n\t// PROGRESS → stderr\n\n\tpublic progress(message: string): void {\n\t\tif (this.currentMode !== 'human' || !this.stderr.isTty) {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, escapeTerminalText(message))\n\t\tthis.progressVisible = true\n\t}\n\n\tpublic clearProgress(): void {\n\t\tif (!this.progressVisible) {\n\t\t\treturn\n\t\t}\n\t\tthis.progressVisible = false\n\t\twriteStream(this.stderr, '\\r\\u001b[K')\n\t}\n\n\t/** False unless both sides of an interactive prompt are TTYs in human mode. */\n\tpublic canPrompt(): boolean {\n\t\treturn this.currentMode === 'human' && this.stdinIsTty() && this.stderr.isTty\n\t}\n\n\t/** A real Writable suitable for the `stdout` option of interactive prompt libraries. */\n\tpublic get promptOutput(): PromptOutputStream {\n\t\treturn this.promptStderr\n\t}\n\n\t/**\n\t * Writes a line to stderr regardless of the mode. Reserved for content the user explicitly asked for\n\t * (help) or must always see (a fatal error) — everything else belongs to the methods above.\n\t */\n\tpublic writeStderr(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, text + '\\n')\n\t}\n\n\tprivate writeStdout(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stdout, text + '\\n')\n\t}\n\n\tprivate writeDiagnostic(message: string, format: (text: string) => string = text => text): void {\n\t\tif (this.currentMode !== 'human') {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, format(escapeTerminalText(message)) + '\\n')\n\t}\n}\n\nconst createProcessStream = (stream: NodeJS.WriteStream): OutputStream => ({\n\twrite: text => {\n\t\tstream.write(text)\n\t},\n\tget isTty() {\n\t\treturn stream.isTTY === true\n\t},\n\tget columns() {\n\t\treturn stream.columns\n\t},\n\tonError: listener => {\n\t\tstream.on('error', error => listener(error))\n\t},\n})\n\nclass PromptWritable extends Writable {\n\tpublic readonly isTTY: boolean\n\n\tconstructor(private readonly stream: OutputStream) {\n\t\tsuper({ decodeStrings: false })\n\t\tthis.isTTY = stream.isTty\n\t}\n\n\tpublic get columns(): number {\n\t\treturn this.stream.columns ?? 80\n\t}\n\n\tpublic override _write(chunk: string | Uint8Array, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n\t\ttry {\n\t\t\twriteStream(this.stream, typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(encoding))\n\t\t\tcallback()\n\t\t} catch (error) {\n\t\t\tcallback(error instanceof Error ? error : new Error(String(error)))\n\t\t}\n\t}\n}\n\nconst createPromptStream = (stream: OutputStream): PromptOutputStream => new PromptWritable(stream)\n\nconst writeStream = (stream: OutputStream, text: string): void => {\n\ttry {\n\t\tstream.write(text)\n\t} catch (error) {\n\t\thandleStreamError(error)\n\t}\n}\n\nconst handleStreamError = (error: unknown): void => {\n\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EPIPE') {\n\t\treturn\n\t}\n\tthrow error\n}\n\n/** Removes terminal control characters from untrusted human-readable text. */\nexport const escapeTerminalText = (value: string): string => {\n\tlet escaped = ''\n\tfor (const character of value) {\n\t\tif (!isTerminalControl(character)) {\n\t\t\tescaped += character\n\t\t}\n\t}\n\treturn escaped\n}\n\nconst isTerminalControl = (character: string): boolean => {\n\tconst codePoint = character.codePointAt(0)\n\treturn codePoint !== undefined && (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n}\n\n// generic in the field so that `format` is a single signature here, not a union of them\nconst renderTableCell = <T, K extends keyof T & string>(column: OutputTableColumns<T>[K], row: T): string =>\n\tcolumn.format ? column.format(row[column.field], row) : formatCell(row[column.field])\n\nconst formatCell = (value: unknown): string => {\n\tif (value === undefined || value === null) {\n\t\treturn ''\n\t}\n\tif (typeof value === 'string') {\n\t\treturn escapeTerminalText(value)\n\t}\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn JSON.stringify(value) ?? ''\n}\n\nconst toScalarLines = (value: unknown): string[] => {\n\tconst values: unknown[] = Array.isArray(value) ? value : [value]\n\tif (!values.every(isOutputScalar)) {\n\t\tthrow new TypeError('Quiet output requires a scalar value or an array of scalar values. Pass an explicit quiet projection for structured data.')\n\t}\n\treturn values.filter(it => it !== undefined && it !== null).map(formatCell)\n}\n\nconst isOutputScalar = (value: unknown): value is OutputScalar =>\n\tvalue === null || value === undefined || ['string', 'number', 'boolean', 'bigint'].includes(typeof value)\n"],"names":["Writable"],"mappings":";;;;;;;;AASA,IAAI,sBAAsB,MAAM;AA0CzB,MAAM,oBAAoB,CAAC,YAA4C;AAC7E,MAAI,QAAQ,MAAM;AACjB,WAAO;AAAA,EACR;AACA,MAAI,QAAQ,OAAO;AAClB,WAAO;AAAA,EACR;AACA,SAAO;AACR;AAQO,MAAM,OAAO;AAAA,EAQnB,YAAY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AAQ,aAAa;AAC5F;AAGA,MAAM,kBAAkB,CAAgC,QAAkC,QACzF,OAAO,SAAS,OAAO,OAAO,IAAI,OAAO,KAAK,GAAG,GAAG,IAAI,WAAW,IAAI,OAAO,KAAK,CAAC;AAErF,MAAM,aAAa,CAAC,UAA2B;AAC9C,MAAI,UAAU,UAAa,UAAU,MAAM;AAC1C,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,UAAU;AAC9B,WAAO,mBAAmB,KAAK;AAAA,EAChC;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACzF,WAAO,OAAO,KAAK;AAAA,EACpB;AACA,SAAO,KAAK,UAAU,KAAK,KAAK;AACjC;AAEA,MAAM,gBAAgB,CAAC,UAA6B;AACnD,QAAM,SAAoB,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC/D,MAAI,CAAC,OAAO,MAAM,cAAc,GAAG;AAClC,UAAM,IAAI,UAAU,2HAA2H;AAAA,EAChJ;AACA,SAAO,OAAO,OAAO,CAAA,OAAM,OAAO,UAAa,OAAO,IAAI,EAAE,IAAI,UAAU;AAC3E;AAEA,MAAM,iBAAiB,CAAC,UACvB,UAAU,QAAQ,UAAU,UAAa,CAAC,UAAU,UAAU,WAAW,QAAQ,EAAE,SAAS,OAAO,KAAK;;;;"}
|
|
1
|
+
{"version":3,"file":"Output.cjs","sources":["../../../../../packages/cli-common/src/application/Output.ts"],"sourcesContent":["import { createInterface, type Interface } from 'node:readline'\nimport type { Readable } from 'node:stream'\nimport { CliError, ExitCode } from './CliError.js'\nimport { setColorsEnabled, style, terminalSupportsColor } from './colors.js'\nimport type { GlobalOptionValues } from './GlobalOptions.js'\nimport { formatTable } from './table.js'\n\nexport type OutputMode = 'human' | 'json' | 'quiet'\n\nexport interface OutputStream {\n\twrite(text: string): void\n\treadonly isTty: boolean\n\treadonly columns?: number\n\tonError?(listener: (error: unknown) => void): void\n}\n\n/** Reads one line of the user's answer, or `undefined` when the input is closed. */\nexport type PromptLineReader = () => Promise<string | undefined>\n\nexport interface OutputOptions {\n\tstdout?: OutputStream\n\tstderr?: OutputStream\n\tisStdinTty?: () => boolean\n\treadPromptLine?: PromptLineReader\n}\n\nexport type OutputScalar = string | number | boolean | bigint | null | undefined\n\nexport interface OutputDataOptions<T> {\n\thuman?: (value: T) => string\n\tquiet?: (value: T) => OutputScalar | readonly OutputScalar[]\n}\n\n/**\n * Per field column specs, so that each `format` sees the exact type of its own field. Indexed by the\n * field name only to let {@link Output.table} render a cell without widening the union.\n */\nexport type OutputTableColumns<T> = {\n\t[K in keyof T & string]: {\n\t\tfield: K\n\t\tname: string\n\t\t/** Human mode only — `--json` still emits the raw row and `--quiet` the raw value. */\n\t\tformat?: (value: T[K], row: T) => string\n\t}\n}\n\nexport type OutputTableColumn<T> = OutputTableColumns<T>[keyof T & string]\n\nexport const resolveOutputMode = (globals: GlobalOptionValues): OutputMode => {\n\tif (globals.json) {\n\t\treturn 'json'\n\t}\n\tif (globals.quiet) {\n\t\treturn 'quiet'\n\t}\n\treturn 'human'\n}\n\n/**\n * The single output channel of the CLI: stdout carries data, stderr carries everything a human reads.\n *\n * The instance is created before argv is parsed, so the mode is mutable and set by `Application` once\n * the global options are known. Every consumer holds the same instance.\n */\nexport class Output {\n\tprivate currentMode: OutputMode = 'human'\n\tprivate progressVisible = false\n\tprivate readonly stdout: OutputStream\n\tprivate readonly stderr: OutputStream\n\tprivate readonly stdinIsTty: () => boolean\n\tprivate readonly readPromptLine: PromptLineReader\n\n\tconstructor(options: OutputOptions = {}) {\n\t\tthis.stdout = options.stdout ?? createProcessStream(process.stdout)\n\t\tthis.stderr = options.stderr ?? createProcessStream(process.stderr)\n\t\tthis.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true)\n\t\tthis.readPromptLine = options.readPromptLine ?? readStdinLine\n\t\tthis.stdout.onError?.(handleStreamError)\n\t\tthis.stderr.onError?.(handleStreamError)\n\t}\n\n\tpublic get mode(): OutputMode {\n\t\treturn this.currentMode\n\t}\n\n\tpublic get isJson(): boolean {\n\t\treturn this.currentMode === 'json'\n\t}\n\n\tpublic get isQuiet(): boolean {\n\t\treturn this.currentMode === 'quiet'\n\t}\n\n\t/** Set by `Application` once the global options are parsed. */\n\tpublic setMode(mode: OutputMode): void {\n\t\tthis.currentMode = mode\n\t}\n\n\tpublic applyGlobalOptions(globals: GlobalOptionValues): void {\n\t\tthis.setMode(resolveOutputMode(globals))\n\t\tsetColorsEnabled(globals.color && this.currentMode === 'human' && terminalSupportsColor)\n\t}\n\n\t// DATA → stdout\n\n\t/** Prints command data with optional mode-specific projections. JSON always receives the raw value. */\n\tpublic data<T>(value: T, human?: (value: T) => string): void\n\tpublic data<T>(value: T, options?: OutputDataOptions<T>): void\n\tpublic data<T>(value: T, rendering?: ((value: T) => string) | OutputDataOptions<T>): void {\n\t\tconst human = typeof rendering === 'function' ? rendering : rendering?.human\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(value ?? null, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst quietValue = typeof rendering === 'object' && rendering.quiet ? rendering.quiet(value) : value\n\t\t\tfor (const line of toScalarLines(quietValue)) {\n\t\t\t\tthis.writeStdout(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.writeStdout(human ? human(value) : JSON.stringify(value ?? null, null, 2))\n\t}\n\n\tpublic table<T>(columns: OutputTableColumn<T>[], rows: T[], quietField?: keyof T & string): void {\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(rows, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst field = quietField ?? columns[0]?.field\n\t\t\tif (field === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const row of rows) {\n\t\t\t\tthis.writeStdout(formatCell(row[field]))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (rows.length === 0) {\n\t\t\treturn\n\t\t}\n\t\tconst data = rows.map(row => {\n\t\t\tconst cells: Partial<Record<keyof T & string, string>> = {}\n\t\t\tfor (const column of columns) {\n\t\t\t\tcells[column.field] = renderTableCell(column, row)\n\t\t\t}\n\t\t\treturn cells\n\t\t})\n\t\tthis.writeStdout(formatTable(columns.map(it => ({ field: it.field, name: it.name })), data))\n\t}\n\n\t// DIAGNOSTICS → stderr\n\n\tpublic info(message: string): void {\n\t\tthis.writeDiagnostic(message)\n\t}\n\n\tpublic warn(message: string): void {\n\t\tthis.writeDiagnostic(message, text => style('yellow', text))\n\t}\n\n\tpublic error(message: string): void {\n\t\tthis.writeDiagnostic(message, text => style('red', text))\n\t}\n\n\t// PROGRESS → stderr\n\n\tpublic progress(message: string): void {\n\t\tif (this.currentMode !== 'human' || !this.stderr.isTty) {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, escapeTerminalText(message))\n\t\tthis.progressVisible = true\n\t}\n\n\tpublic clearProgress(): void {\n\t\tif (!this.progressVisible) {\n\t\t\treturn\n\t\t}\n\t\tthis.progressVisible = false\n\t\twriteStream(this.stderr, '\\r\\u001b[K')\n\t}\n\n\t/** False unless both sides of an interactive prompt are TTYs in human mode. */\n\tpublic canPrompt(): boolean {\n\t\treturn this.currentMode === 'human' && this.stdinIsTty() && this.stderr.isTty\n\t}\n\n\t/** Writes `question` to stderr and reads one answer line. */\n\tpublic prompt(question: string): Promise<string | undefined> {\n\t\tif (!this.canPrompt()) {\n\t\t\tthrow new CliError('TTY not available. Pass --yes to confirm.', { code: 'TTY_UNAVAILABLE', exitCode: ExitCode.InputError })\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, question)\n\t\treturn this.readPromptLine()\n\t}\n\n\t/**\n\t * Writes a line to stderr regardless of the mode. Reserved for content the user explicitly asked for\n\t * (help) or must always see (a fatal error) — everything else belongs to the methods above.\n\t */\n\tpublic writeStderr(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, text + '\\n')\n\t}\n\n\tprivate writeStdout(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stdout, text + '\\n')\n\t}\n\n\tprivate writeDiagnostic(message: string, format: (text: string) => string = text => text): void {\n\t\tif (this.currentMode !== 'human') {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, format(escapeTerminalText(message)) + '\\n')\n\t}\n}\n\nconst createProcessStream = (stream: NodeJS.WriteStream): OutputStream => ({\n\twrite: text => {\n\t\tstream.write(text)\n\t},\n\tget isTty() {\n\t\treturn stream.isTTY === true\n\t},\n\tget columns() {\n\t\treturn stream.columns\n\t},\n\tonError: listener => {\n\t\tstream.on('error', error => listener(error))\n\t},\n})\n\nlet stdinReader: LineReader | undefined\nconst readStdinLine: PromptLineReader = () => {\n\tstdinReader ??= new LineReader(process.stdin)\n\treturn stdinReader.read()\n}\n\n/**\n * Reads answer lines from one input for all prompts, so that a line typed or pasted ahead of the next prompt is kept\n * and an input that already ended reads as closed. Not in readline's terminal mode: the TTY handles line editing and\n * echo, and Ctrl+C stays a plain SIGINT.\n */\nexport class LineReader {\n\tprivate reader: Interface | undefined\n\tprivate readonly lines: string[] = []\n\tprivate waiting: ((line: string | undefined) => void) | undefined\n\tprivate closed = false\n\n\tconstructor(private readonly input: Readable) {}\n\n\tpublic read(): Promise<string | undefined> {\n\t\tif (this.waiting) {\n\t\t\tthrow new Error('LineReader: a read is already pending')\n\t\t}\n\t\tconst line = this.lines.shift()\n\t\tif (line !== undefined) {\n\t\t\treturn Promise.resolve(line)\n\t\t}\n\t\t// readline never reports `close` for an input that ended before it was attached (Bun does not set readableEnded)\n\t\tif (this.closed || this.input.readableEnded) {\n\t\t\tthis.closed = true\n\t\t\treturn Promise.resolve(undefined)\n\t\t}\n\t\treturn new Promise(resolve => {\n\t\t\tthis.waiting = resolve\n\t\t\tthis.open().resume()\n\t\t})\n\t}\n\n\tprivate open(): Interface {\n\t\tif (this.reader) {\n\t\t\treturn this.reader\n\t\t}\n\t\tconst reader = createInterface({ input: this.input, terminal: false })\n\t\treader.on('line', line => this.settle(line))\n\t\treader.on('close', () => {\n\t\t\tthis.closed = true\n\t\t\tthis.settle(undefined)\n\t\t})\n\t\tthis.reader = reader\n\t\treturn reader\n\t}\n\n\tprivate settle(line: string | undefined): void {\n\t\tconst waiting = this.waiting\n\t\tif (!waiting) {\n\t\t\tif (line !== undefined) {\n\t\t\t\tthis.lines.push(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.waiting = undefined\n\t\tif (!this.closed) {\n\t\t\t// a paused TTY does not keep the process alive between prompts; Node throws when pausing a closed interface\n\t\t\tthis.reader?.pause()\n\t\t}\n\t\twaiting(line)\n\t}\n}\n\nconst writeStream = (stream: OutputStream, text: string): void => {\n\ttry {\n\t\tstream.write(text)\n\t} catch (error) {\n\t\thandleStreamError(error)\n\t}\n}\n\nconst handleStreamError = (error: unknown): void => {\n\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EPIPE') {\n\t\treturn\n\t}\n\tthrow error\n}\n\n/** Removes terminal control characters from untrusted human-readable text. */\nexport const escapeTerminalText = (value: string): string => {\n\tlet escaped = ''\n\tfor (const character of value) {\n\t\tif (!isTerminalControl(character)) {\n\t\t\tescaped += character\n\t\t}\n\t}\n\treturn escaped\n}\n\nconst isTerminalControl = (character: string): boolean => {\n\tconst codePoint = character.codePointAt(0)\n\treturn codePoint !== undefined && (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n}\n\n// generic in the field so that `format` is a single signature here, not a union of them\nconst renderTableCell = <T, K extends keyof T & string>(column: OutputTableColumns<T>[K], row: T): string =>\n\tcolumn.format ? column.format(row[column.field], row) : formatCell(row[column.field])\n\nconst formatCell = (value: unknown): string => {\n\tif (value === undefined || value === null) {\n\t\treturn ''\n\t}\n\tif (typeof value === 'string') {\n\t\treturn escapeTerminalText(value)\n\t}\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn JSON.stringify(value) ?? ''\n}\n\nconst toScalarLines = (value: unknown): string[] => {\n\tconst values: unknown[] = Array.isArray(value) ? value : [value]\n\tif (!values.every(isOutputScalar)) {\n\t\tthrow new TypeError('Quiet output requires a scalar value or an array of scalar values. Pass an explicit quiet projection for structured data.')\n\t}\n\treturn values.filter(it => it !== undefined && it !== null).map(formatCell)\n}\n\nconst isOutputScalar = (value: unknown): value is OutputScalar =>\n\tvalue === null || value === undefined || ['string', 'number', 'boolean', 'bigint'].includes(typeof value)\n"],"names":["setColorsEnabled","terminalSupportsColor","formatTable","style","CliError","ExitCode","createInterface"],"mappings":";;;;;;;;;AAgDO,MAAM,oBAAoB,CAAC,YAA4C;AAC7E,MAAI,QAAQ,MAAM;AACjB,WAAO;AAAA,EACR;AACA,MAAI,QAAQ,OAAO;AAClB,WAAO;AAAA,EACR;AACA,SAAO;AACR;AAQO,MAAM,OAAO;AAAA,EAQnB,YAAY,UAAyB,IAAI;AAPzC,kBAAA,MAAQ,eAA0B,OAAA;AAClC,kBAAA,MAAQ,mBAAkB,KAAA;AAC1B,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,YAAA;AACjB,kBAAA,MAAiB,gBAAA;AAGhB,SAAK,SAAS,QAAQ,UAAU,oBAAoB,QAAQ,MAAM;AAClE,SAAK,SAAS,QAAQ,UAAU,oBAAoB,QAAQ,MAAM;AAClE,SAAK,aAAa,QAAQ,eAAe,MAAM,QAAQ,MAAM,UAAU;AACvE,SAAK,iBAAiB,QAAQ,kBAAkB;AAChD,SAAK,OAAO,UAAU,iBAAiB;AACvC,SAAK,OAAO,UAAU,iBAAiB;AAAA,EACxC;AAAA,EAEA,IAAW,OAAmB;AAC7B,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,IAAW,SAAkB;AAC5B,WAAO,KAAK,gBAA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,EACD;AACA,SAAO;AACR;AAEA,MAAM,oBAAoB,CAAC,cAA+B;AACzD,QAAM,YAAY,UAAU,YAAY,CAAC;AACzC,SAAO,cAAc,WAAc,aAAa,MAAS,aAAa,OAAQ,aAAa;AAC5F;AAGA,MAAM,kBAAkB,CAAgC,QAAkC,QACzF,OAAO,SAAS,OAAO,OAAO,IAAI,OAAO,KAAK,GAAG,GAAG,IAAI,WAAW,IAAI,OAAO,KAAK,CAAC;AAErF,MAAM,aAAa,CAAC,UAA2B;AAC9C,MAAI,UAAU,UAAa,UAAU,MAAM;AAC1C,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,UAAU;AAC9B,WAAO,mBAAmB,KAAK;AAAA,EAChC;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AACzF,WAAO,OAAO,KAAK;AAAA,EACpB;AACA,SAAO,KAAK,UAAU,KAAK,KAAK;AACjC;AAEA,MAAM,gBAAgB,CAAC,UAA6B;AACnD,QAAM,SAAoB,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC/D,MAAI,CAAC,OAAO,MAAM,cAAc,GAAG;AAClC,UAAM,IAAI,UAAU,2HAA2H;AAAA,EAChJ;AACA,SAAO,OAAO,OAAO,CAAA,OAAM,OAAO,UAAa,OAAO,IAAI,EAAE,IAAI,UAAU;AAC3E;AAEA,MAAM,iBAAiB,CAAC,UACvB,UAAU,QAAQ,UAAU,UAAa,CAAC,UAAU,UAAU,WAAW,QAAQ,EAAE,SAAS,OAAO,KAAK;;;;;"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { CliError, ExitCode } from "./CliError.js";
|
|
3
|
+
import { setColorsEnabled, terminalSupportsColor, style } from "./colors.js";
|
|
4
|
+
import { formatTable } from "./table.js";
|
|
4
5
|
var __defProp = Object.defineProperty;
|
|
5
6
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
7
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
-
let supportedChalkLevel = chalk.level;
|
|
8
8
|
const resolveOutputMode = (globals) => {
|
|
9
9
|
if (globals.json) {
|
|
10
10
|
return "json";
|
|
@@ -21,11 +21,11 @@ class Output {
|
|
|
21
21
|
__publicField(this, "stdout");
|
|
22
22
|
__publicField(this, "stderr");
|
|
23
23
|
__publicField(this, "stdinIsTty");
|
|
24
|
-
__publicField(this, "
|
|
24
|
+
__publicField(this, "readPromptLine");
|
|
25
25
|
this.stdout = options.stdout ?? createProcessStream(process.stdout);
|
|
26
26
|
this.stderr = options.stderr ?? createProcessStream(process.stderr);
|
|
27
27
|
this.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true);
|
|
28
|
-
this.
|
|
28
|
+
this.readPromptLine = options.readPromptLine ?? readStdinLine;
|
|
29
29
|
this.stdout.onError?.(handleStreamError);
|
|
30
30
|
this.stderr.onError?.(handleStreamError);
|
|
31
31
|
}
|
|
@@ -44,18 +44,7 @@ class Output {
|
|
|
44
44
|
}
|
|
45
45
|
applyGlobalOptions(globals) {
|
|
46
46
|
this.setMode(resolveOutputMode(globals));
|
|
47
|
-
|
|
48
|
-
if (chalk.level === 0) {
|
|
49
|
-
chalk.level = supportedChalkLevel;
|
|
50
|
-
} else {
|
|
51
|
-
supportedChalkLevel = chalk.level;
|
|
52
|
-
}
|
|
53
|
-
} else {
|
|
54
|
-
if (chalk.level !== 0) {
|
|
55
|
-
supportedChalkLevel = chalk.level;
|
|
56
|
-
}
|
|
57
|
-
chalk.level = 0;
|
|
58
|
-
}
|
|
47
|
+
setColorsEnabled(globals.color && this.currentMode === "human" && terminalSupportsColor);
|
|
59
48
|
}
|
|
60
49
|
data(value, rendering) {
|
|
61
50
|
const human = typeof rendering === "function" ? rendering : rendering?.human;
|
|
@@ -97,17 +86,17 @@ class Output {
|
|
|
97
86
|
}
|
|
98
87
|
return cells;
|
|
99
88
|
});
|
|
100
|
-
this.writeStdout(
|
|
89
|
+
this.writeStdout(formatTable(columns.map((it) => ({ field: it.field, name: it.name })), data));
|
|
101
90
|
}
|
|
102
91
|
// DIAGNOSTICS → stderr
|
|
103
92
|
info(message) {
|
|
104
93
|
this.writeDiagnostic(message);
|
|
105
94
|
}
|
|
106
95
|
warn(message) {
|
|
107
|
-
this.writeDiagnostic(message, (text) =>
|
|
96
|
+
this.writeDiagnostic(message, (text) => style("yellow", text));
|
|
108
97
|
}
|
|
109
98
|
error(message) {
|
|
110
|
-
this.writeDiagnostic(message, (text) =>
|
|
99
|
+
this.writeDiagnostic(message, (text) => style("red", text));
|
|
111
100
|
}
|
|
112
101
|
// PROGRESS → stderr
|
|
113
102
|
progress(message) {
|
|
@@ -129,9 +118,14 @@ class Output {
|
|
|
129
118
|
canPrompt() {
|
|
130
119
|
return this.currentMode === "human" && this.stdinIsTty() && this.stderr.isTty;
|
|
131
120
|
}
|
|
132
|
-
/**
|
|
133
|
-
|
|
134
|
-
|
|
121
|
+
/** Writes `question` to stderr and reads one answer line. */
|
|
122
|
+
prompt(question) {
|
|
123
|
+
if (!this.canPrompt()) {
|
|
124
|
+
throw new CliError("TTY not available. Pass --yes to confirm.", { code: "TTY_UNAVAILABLE", exitCode: ExitCode.InputError });
|
|
125
|
+
}
|
|
126
|
+
this.clearProgress();
|
|
127
|
+
writeStream(this.stderr, question);
|
|
128
|
+
return this.readPromptLine();
|
|
135
129
|
}
|
|
136
130
|
/**
|
|
137
131
|
* Writes a line to stderr regardless of the mode. Reserved for content the user explicitly asked for
|
|
@@ -167,26 +161,64 @@ const createProcessStream = (stream) => ({
|
|
|
167
161
|
stream.on("error", (error) => listener(error));
|
|
168
162
|
}
|
|
169
163
|
});
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
164
|
+
let stdinReader;
|
|
165
|
+
const readStdinLine = () => {
|
|
166
|
+
stdinReader ?? (stdinReader = new LineReader(process.stdin));
|
|
167
|
+
return stdinReader.read();
|
|
168
|
+
};
|
|
169
|
+
class LineReader {
|
|
170
|
+
constructor(input) {
|
|
171
|
+
this.input = input;
|
|
172
|
+
__publicField(this, "reader");
|
|
173
|
+
__publicField(this, "lines", []);
|
|
174
|
+
__publicField(this, "waiting");
|
|
175
|
+
__publicField(this, "closed", false);
|
|
176
176
|
}
|
|
177
|
-
|
|
178
|
-
|
|
177
|
+
read() {
|
|
178
|
+
if (this.waiting) {
|
|
179
|
+
throw new Error("LineReader: a read is already pending");
|
|
180
|
+
}
|
|
181
|
+
const line = this.lines.shift();
|
|
182
|
+
if (line !== void 0) {
|
|
183
|
+
return Promise.resolve(line);
|
|
184
|
+
}
|
|
185
|
+
if (this.closed || this.input.readableEnded) {
|
|
186
|
+
this.closed = true;
|
|
187
|
+
return Promise.resolve(void 0);
|
|
188
|
+
}
|
|
189
|
+
return new Promise((resolve) => {
|
|
190
|
+
this.waiting = resolve;
|
|
191
|
+
this.open().resume();
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
open() {
|
|
195
|
+
if (this.reader) {
|
|
196
|
+
return this.reader;
|
|
197
|
+
}
|
|
198
|
+
const reader = createInterface({ input: this.input, terminal: false });
|
|
199
|
+
reader.on("line", (line) => this.settle(line));
|
|
200
|
+
reader.on("close", () => {
|
|
201
|
+
this.closed = true;
|
|
202
|
+
this.settle(void 0);
|
|
203
|
+
});
|
|
204
|
+
this.reader = reader;
|
|
205
|
+
return reader;
|
|
179
206
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
207
|
+
settle(line) {
|
|
208
|
+
const waiting = this.waiting;
|
|
209
|
+
if (!waiting) {
|
|
210
|
+
if (line !== void 0) {
|
|
211
|
+
this.lines.push(line);
|
|
212
|
+
}
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.waiting = void 0;
|
|
216
|
+
if (!this.closed) {
|
|
217
|
+
this.reader?.pause();
|
|
186
218
|
}
|
|
219
|
+
waiting(line);
|
|
187
220
|
}
|
|
188
221
|
}
|
|
189
|
-
const createPromptStream = (stream) => new PromptWritable(stream);
|
|
190
222
|
const writeStream = (stream, text) => {
|
|
191
223
|
try {
|
|
192
224
|
stream.write(text);
|
|
@@ -235,6 +267,7 @@ const toScalarLines = (value) => {
|
|
|
235
267
|
};
|
|
236
268
|
const isOutputScalar = (value) => value === null || value === void 0 || ["string", "number", "boolean", "bigint"].includes(typeof value);
|
|
237
269
|
export {
|
|
270
|
+
LineReader,
|
|
238
271
|
Output,
|
|
239
272
|
escapeTerminalText,
|
|
240
273
|
resolveOutputMode
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Output.js","sources":["../../../../../packages/cli-common/src/application/Output.ts"],"sourcesContent":["/// <reference path=\"../../types/chalk-table/index.d.ts\" />\n\nimport chalk from 'chalk'\nimport chalkTable from 'chalk-table'\nimport { Writable } from 'node:stream'\nimport type { GlobalOptionValues } from './GlobalOptions.js'\n\nexport type OutputMode = 'human' | 'json' | 'quiet'\n\nlet supportedChalkLevel = chalk.level\n\nexport interface OutputStream {\n\twrite(text: string): void\n\treadonly isTty: boolean\n\treadonly columns?: number\n\tonError?(listener: (error: unknown) => void): void\n}\n\nexport interface OutputOptions {\n\tstdout?: OutputStream\n\tstderr?: OutputStream\n\tisStdinTty?: () => boolean\n}\n\nexport interface PromptOutputStream extends Writable {\n\treadonly isTTY: boolean\n\treadonly columns: number\n}\n\nexport type OutputScalar = string | number | boolean | bigint | null | undefined\n\nexport interface OutputDataOptions<T> {\n\thuman?: (value: T) => string\n\tquiet?: (value: T) => OutputScalar | readonly OutputScalar[]\n}\n\n/**\n * Per field column specs, so that each `format` sees the exact type of its own field. Indexed by the\n * field name only to let {@link Output.table} render a cell without widening the union.\n */\nexport type OutputTableColumns<T> = {\n\t[K in keyof T & string]: {\n\t\tfield: K\n\t\tname: string\n\t\t/** Human mode only — `--json` still emits the raw row and `--quiet` the raw value. */\n\t\tformat?: (value: T[K], row: T) => string\n\t}\n}\n\nexport type OutputTableColumn<T> = OutputTableColumns<T>[keyof T & string]\n\nexport const resolveOutputMode = (globals: GlobalOptionValues): OutputMode => {\n\tif (globals.json) {\n\t\treturn 'json'\n\t}\n\tif (globals.quiet) {\n\t\treturn 'quiet'\n\t}\n\treturn 'human'\n}\n\n/**\n * The single output channel of the CLI: stdout carries data, stderr carries everything a human reads.\n *\n * The instance is created before argv is parsed, so the mode is mutable and set by `Application` once\n * the global options are known. Every consumer holds the same instance.\n */\nexport class Output {\n\tprivate currentMode: OutputMode = 'human'\n\tprivate progressVisible = false\n\tprivate readonly stdout: OutputStream\n\tprivate readonly stderr: OutputStream\n\tprivate readonly stdinIsTty: () => boolean\n\tprivate readonly promptStderr: PromptOutputStream\n\n\tconstructor(options: OutputOptions = {}) {\n\t\tthis.stdout = options.stdout ?? createProcessStream(process.stdout)\n\t\tthis.stderr = options.stderr ?? createProcessStream(process.stderr)\n\t\tthis.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true)\n\t\tthis.promptStderr = options.stderr === undefined ? process.stderr : createPromptStream(this.stderr)\n\t\tthis.stdout.onError?.(handleStreamError)\n\t\tthis.stderr.onError?.(handleStreamError)\n\t}\n\n\tpublic get mode(): OutputMode {\n\t\treturn this.currentMode\n\t}\n\n\tpublic get isJson(): boolean {\n\t\treturn this.currentMode === 'json'\n\t}\n\n\tpublic get isQuiet(): boolean {\n\t\treturn this.currentMode === 'quiet'\n\t}\n\n\t/** Set by `Application` once the global options are parsed. */\n\tpublic setMode(mode: OutputMode): void {\n\t\tthis.currentMode = mode\n\t}\n\n\tpublic applyGlobalOptions(globals: GlobalOptionValues): void {\n\t\tthis.setMode(resolveOutputMode(globals))\n\t\tif (globals.color && this.currentMode === 'human') {\n\t\t\tif (chalk.level === 0) {\n\t\t\t\tchalk.level = supportedChalkLevel\n\t\t\t} else {\n\t\t\t\tsupportedChalkLevel = chalk.level\n\t\t\t}\n\t\t} else {\n\t\t\tif (chalk.level !== 0) {\n\t\t\t\tsupportedChalkLevel = chalk.level\n\t\t\t}\n\t\t\tchalk.level = 0\n\t\t}\n\t}\n\n\t// DATA → stdout\n\n\t/** Prints command data with optional mode-specific projections. JSON always receives the raw value. */\n\tpublic data<T>(value: T, human?: (value: T) => string): void\n\tpublic data<T>(value: T, options?: OutputDataOptions<T>): void\n\tpublic data<T>(value: T, rendering?: ((value: T) => string) | OutputDataOptions<T>): void {\n\t\tconst human = typeof rendering === 'function' ? rendering : rendering?.human\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(value ?? null, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst quietValue = typeof rendering === 'object' && rendering.quiet ? rendering.quiet(value) : value\n\t\t\tfor (const line of toScalarLines(quietValue)) {\n\t\t\t\tthis.writeStdout(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.writeStdout(human ? human(value) : JSON.stringify(value ?? null, null, 2))\n\t}\n\n\tpublic table<T>(columns: OutputTableColumn<T>[], rows: T[], quietField?: keyof T & string): void {\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(rows, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst field = quietField ?? columns[0]?.field\n\t\t\tif (field === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const row of rows) {\n\t\t\t\tthis.writeStdout(formatCell(row[field]))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (rows.length === 0) {\n\t\t\treturn\n\t\t}\n\t\tconst data: Record<string, string>[] = rows.map(row => {\n\t\t\tconst cells: Record<string, string> = {}\n\t\t\tfor (const column of columns) {\n\t\t\t\tcells[column.field] = renderTableCell(column, row)\n\t\t\t}\n\t\t\treturn cells\n\t\t})\n\t\tthis.writeStdout(chalkTable<string>({ columns: columns.map(it => ({ field: it.field, name: it.name })) }, data))\n\t}\n\n\t// DIAGNOSTICS → stderr\n\n\tpublic info(message: string): void {\n\t\tthis.writeDiagnostic(message)\n\t}\n\n\tpublic warn(message: string): void {\n\t\tthis.writeDiagnostic(message, text => chalk.yellow(text))\n\t}\n\n\tpublic error(message: string): void {\n\t\tthis.writeDiagnostic(message, text => chalk.red(text))\n\t}\n\n\t// PROGRESS → stderr\n\n\tpublic progress(message: string): void {\n\t\tif (this.currentMode !== 'human' || !this.stderr.isTty) {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, escapeTerminalText(message))\n\t\tthis.progressVisible = true\n\t}\n\n\tpublic clearProgress(): void {\n\t\tif (!this.progressVisible) {\n\t\t\treturn\n\t\t}\n\t\tthis.progressVisible = false\n\t\twriteStream(this.stderr, '\\r\\u001b[K')\n\t}\n\n\t/** False unless both sides of an interactive prompt are TTYs in human mode. */\n\tpublic canPrompt(): boolean {\n\t\treturn this.currentMode === 'human' && this.stdinIsTty() && this.stderr.isTty\n\t}\n\n\t/** A real Writable suitable for the `stdout` option of interactive prompt libraries. */\n\tpublic get promptOutput(): PromptOutputStream {\n\t\treturn this.promptStderr\n\t}\n\n\t/**\n\t * Writes a line to stderr regardless of the mode. Reserved for content the user explicitly asked for\n\t * (help) or must always see (a fatal error) — everything else belongs to the methods above.\n\t */\n\tpublic writeStderr(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, text + '\\n')\n\t}\n\n\tprivate writeStdout(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stdout, text + '\\n')\n\t}\n\n\tprivate writeDiagnostic(message: string, format: (text: string) => string = text => text): void {\n\t\tif (this.currentMode !== 'human') {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, format(escapeTerminalText(message)) + '\\n')\n\t}\n}\n\nconst createProcessStream = (stream: NodeJS.WriteStream): OutputStream => ({\n\twrite: text => {\n\t\tstream.write(text)\n\t},\n\tget isTty() {\n\t\treturn stream.isTTY === true\n\t},\n\tget columns() {\n\t\treturn stream.columns\n\t},\n\tonError: listener => {\n\t\tstream.on('error', error => listener(error))\n\t},\n})\n\nclass PromptWritable extends Writable {\n\tpublic readonly isTTY: boolean\n\n\tconstructor(private readonly stream: OutputStream) {\n\t\tsuper({ decodeStrings: false })\n\t\tthis.isTTY = stream.isTty\n\t}\n\n\tpublic get columns(): number {\n\t\treturn this.stream.columns ?? 80\n\t}\n\n\tpublic override _write(chunk: string | Uint8Array, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {\n\t\ttry {\n\t\t\twriteStream(this.stream, typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(encoding))\n\t\t\tcallback()\n\t\t} catch (error) {\n\t\t\tcallback(error instanceof Error ? error : new Error(String(error)))\n\t\t}\n\t}\n}\n\nconst createPromptStream = (stream: OutputStream): PromptOutputStream => new PromptWritable(stream)\n\nconst writeStream = (stream: OutputStream, text: string): void => {\n\ttry {\n\t\tstream.write(text)\n\t} catch (error) {\n\t\thandleStreamError(error)\n\t}\n}\n\nconst handleStreamError = (error: unknown): void => {\n\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EPIPE') {\n\t\treturn\n\t}\n\tthrow error\n}\n\n/** Removes terminal control characters from untrusted human-readable text. */\nexport const escapeTerminalText = (value: string): string => {\n\tlet escaped = ''\n\tfor (const character of value) {\n\t\tif (!isTerminalControl(character)) {\n\t\t\tescaped += character\n\t\t}\n\t}\n\treturn escaped\n}\n\nconst isTerminalControl = (character: string): boolean => {\n\tconst codePoint = character.codePointAt(0)\n\treturn codePoint !== undefined && (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n}\n\n// generic in the field so that `format` is a single signature here, not a union of them\nconst renderTableCell = <T, K extends keyof T & string>(column: OutputTableColumns<T>[K], row: T): string =>\n\tcolumn.format ? column.format(row[column.field], row) : formatCell(row[column.field])\n\nconst formatCell = (value: unknown): string => {\n\tif (value === undefined || value === null) {\n\t\treturn ''\n\t}\n\tif (typeof value === 'string') {\n\t\treturn escapeTerminalText(value)\n\t}\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn JSON.stringify(value) ?? ''\n}\n\nconst toScalarLines = (value: unknown): string[] => {\n\tconst values: unknown[] = Array.isArray(value) ? value : [value]\n\tif (!values.every(isOutputScalar)) {\n\t\tthrow new TypeError('Quiet output requires a scalar value or an array of scalar values. Pass an explicit quiet projection for structured data.')\n\t}\n\treturn values.filter(it => it !== undefined && it !== null).map(formatCell)\n}\n\nconst isOutputScalar = (value: unknown): value is OutputScalar =>\n\tvalue === null || value === undefined || ['string', 'number', 'boolean', 'bigint'].includes(typeof value)\n"],"names":[],"mappings":";;;;;;AASA,IAAI,sBAAsB,MAAM;AA0CzB,MAAM,oBAAoB,CAAC,YAA4C;AAC7E,MAAI,QAAQ,MAAM;AACjB,WAAO;AAAA,EACR;AACA,MAAI,QAAQ,OAAO;AAClB,WAAO;AAAA,EACR;AACA,SAAO;AACR;AAQO,MAAM,OAAO;AAAA,EAQnB,YAAY,UAAyB,IAAI;AAPzC,kBAAA,MAAQ,eAA0B,OAAA;AAClC,kBAAA,MAAQ,mBAAkB,KAAA;AAC1B,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,YAAA;AACjB,kBAAA,MAAiB,cAAA;AAGhB,SAAK,SAAS,QAAQ,UAAU,oBAAoB,QAAQ,MAAM;AAClE,SAAK,SAAS,QAAQ,UAAU,oBAAoB,QAAQ,MAAM;AAClE,SAAK,aAAa,QAAQ,eAAe,MAAM,QAAQ,MAAM,UAAU;AACvE,SAAK,eAAe,QAAQ,WAAW,SAAY,QAAQ,SAAS,mBAAmB,KA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AAK,UAAU,KAAK,KAAK;AACjC;AAEA,MAAM,gBAAgB,CAAC,UAA6B;AACnD,QAAM,SAAoB,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC/D,MAAI,CAAC,OAAO,MAAM,cAAc,GAAG;AAClC,UAAM,IAAI,UAAU,2HAA2H;AAAA,EAChJ;AACA,SAAO,OAAO,OAAO,CAAA,OAAM,OAAO,UAAa,OAAO,IAAI,EAAE,IAAI,UAAU;AAC3E;AAEA,MAAM,iBAAiB,CAAC,UACvB,UAAU,QAAQ,UAAU,UAAa,CAAC,UAAU,UAAU,WAAW,QAAQ,EAAE,SAAS,OAAO,KAAK;"}
|
|
1
|
+
{"version":3,"file":"Output.js","sources":["../../../../../packages/cli-common/src/application/Output.ts"],"sourcesContent":["import { createInterface, type Interface } from 'node:readline'\nimport type { Readable } from 'node:stream'\nimport { CliError, ExitCode } from './CliError.js'\nimport { setColorsEnabled, style, terminalSupportsColor } from './colors.js'\nimport type { GlobalOptionValues } from './GlobalOptions.js'\nimport { formatTable } from './table.js'\n\nexport type OutputMode = 'human' | 'json' | 'quiet'\n\nexport interface OutputStream {\n\twrite(text: string): void\n\treadonly isTty: boolean\n\treadonly columns?: number\n\tonError?(listener: (error: unknown) => void): void\n}\n\n/** Reads one line of the user's answer, or `undefined` when the input is closed. */\nexport type PromptLineReader = () => Promise<string | undefined>\n\nexport interface OutputOptions {\n\tstdout?: OutputStream\n\tstderr?: OutputStream\n\tisStdinTty?: () => boolean\n\treadPromptLine?: PromptLineReader\n}\n\nexport type OutputScalar = string | number | boolean | bigint | null | undefined\n\nexport interface OutputDataOptions<T> {\n\thuman?: (value: T) => string\n\tquiet?: (value: T) => OutputScalar | readonly OutputScalar[]\n}\n\n/**\n * Per field column specs, so that each `format` sees the exact type of its own field. Indexed by the\n * field name only to let {@link Output.table} render a cell without widening the union.\n */\nexport type OutputTableColumns<T> = {\n\t[K in keyof T & string]: {\n\t\tfield: K\n\t\tname: string\n\t\t/** Human mode only — `--json` still emits the raw row and `--quiet` the raw value. */\n\t\tformat?: (value: T[K], row: T) => string\n\t}\n}\n\nexport type OutputTableColumn<T> = OutputTableColumns<T>[keyof T & string]\n\nexport const resolveOutputMode = (globals: GlobalOptionValues): OutputMode => {\n\tif (globals.json) {\n\t\treturn 'json'\n\t}\n\tif (globals.quiet) {\n\t\treturn 'quiet'\n\t}\n\treturn 'human'\n}\n\n/**\n * The single output channel of the CLI: stdout carries data, stderr carries everything a human reads.\n *\n * The instance is created before argv is parsed, so the mode is mutable and set by `Application` once\n * the global options are known. Every consumer holds the same instance.\n */\nexport class Output {\n\tprivate currentMode: OutputMode = 'human'\n\tprivate progressVisible = false\n\tprivate readonly stdout: OutputStream\n\tprivate readonly stderr: OutputStream\n\tprivate readonly stdinIsTty: () => boolean\n\tprivate readonly readPromptLine: PromptLineReader\n\n\tconstructor(options: OutputOptions = {}) {\n\t\tthis.stdout = options.stdout ?? createProcessStream(process.stdout)\n\t\tthis.stderr = options.stderr ?? createProcessStream(process.stderr)\n\t\tthis.stdinIsTty = options.isStdinTty ?? (() => process.stdin.isTTY === true)\n\t\tthis.readPromptLine = options.readPromptLine ?? readStdinLine\n\t\tthis.stdout.onError?.(handleStreamError)\n\t\tthis.stderr.onError?.(handleStreamError)\n\t}\n\n\tpublic get mode(): OutputMode {\n\t\treturn this.currentMode\n\t}\n\n\tpublic get isJson(): boolean {\n\t\treturn this.currentMode === 'json'\n\t}\n\n\tpublic get isQuiet(): boolean {\n\t\treturn this.currentMode === 'quiet'\n\t}\n\n\t/** Set by `Application` once the global options are parsed. */\n\tpublic setMode(mode: OutputMode): void {\n\t\tthis.currentMode = mode\n\t}\n\n\tpublic applyGlobalOptions(globals: GlobalOptionValues): void {\n\t\tthis.setMode(resolveOutputMode(globals))\n\t\tsetColorsEnabled(globals.color && this.currentMode === 'human' && terminalSupportsColor)\n\t}\n\n\t// DATA → stdout\n\n\t/** Prints command data with optional mode-specific projections. JSON always receives the raw value. */\n\tpublic data<T>(value: T, human?: (value: T) => string): void\n\tpublic data<T>(value: T, options?: OutputDataOptions<T>): void\n\tpublic data<T>(value: T, rendering?: ((value: T) => string) | OutputDataOptions<T>): void {\n\t\tconst human = typeof rendering === 'function' ? rendering : rendering?.human\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(value ?? null, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst quietValue = typeof rendering === 'object' && rendering.quiet ? rendering.quiet(value) : value\n\t\t\tfor (const line of toScalarLines(quietValue)) {\n\t\t\t\tthis.writeStdout(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.writeStdout(human ? human(value) : JSON.stringify(value ?? null, null, 2))\n\t}\n\n\tpublic table<T>(columns: OutputTableColumn<T>[], rows: T[], quietField?: keyof T & string): void {\n\t\tif (this.currentMode === 'json') {\n\t\t\tthis.writeStdout(JSON.stringify(rows, null, 2))\n\t\t\treturn\n\t\t}\n\t\tif (this.currentMode === 'quiet') {\n\t\t\tconst field = quietField ?? columns[0]?.field\n\t\t\tif (field === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const row of rows) {\n\t\t\t\tthis.writeStdout(formatCell(row[field]))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (rows.length === 0) {\n\t\t\treturn\n\t\t}\n\t\tconst data = rows.map(row => {\n\t\t\tconst cells: Partial<Record<keyof T & string, string>> = {}\n\t\t\tfor (const column of columns) {\n\t\t\t\tcells[column.field] = renderTableCell(column, row)\n\t\t\t}\n\t\t\treturn cells\n\t\t})\n\t\tthis.writeStdout(formatTable(columns.map(it => ({ field: it.field, name: it.name })), data))\n\t}\n\n\t// DIAGNOSTICS → stderr\n\n\tpublic info(message: string): void {\n\t\tthis.writeDiagnostic(message)\n\t}\n\n\tpublic warn(message: string): void {\n\t\tthis.writeDiagnostic(message, text => style('yellow', text))\n\t}\n\n\tpublic error(message: string): void {\n\t\tthis.writeDiagnostic(message, text => style('red', text))\n\t}\n\n\t// PROGRESS → stderr\n\n\tpublic progress(message: string): void {\n\t\tif (this.currentMode !== 'human' || !this.stderr.isTty) {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, escapeTerminalText(message))\n\t\tthis.progressVisible = true\n\t}\n\n\tpublic clearProgress(): void {\n\t\tif (!this.progressVisible) {\n\t\t\treturn\n\t\t}\n\t\tthis.progressVisible = false\n\t\twriteStream(this.stderr, '\\r\\u001b[K')\n\t}\n\n\t/** False unless both sides of an interactive prompt are TTYs in human mode. */\n\tpublic canPrompt(): boolean {\n\t\treturn this.currentMode === 'human' && this.stdinIsTty() && this.stderr.isTty\n\t}\n\n\t/** Writes `question` to stderr and reads one answer line. */\n\tpublic prompt(question: string): Promise<string | undefined> {\n\t\tif (!this.canPrompt()) {\n\t\t\tthrow new CliError('TTY not available. Pass --yes to confirm.', { code: 'TTY_UNAVAILABLE', exitCode: ExitCode.InputError })\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, question)\n\t\treturn this.readPromptLine()\n\t}\n\n\t/**\n\t * Writes a line to stderr regardless of the mode. Reserved for content the user explicitly asked for\n\t * (help) or must always see (a fatal error) — everything else belongs to the methods above.\n\t */\n\tpublic writeStderr(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, text + '\\n')\n\t}\n\n\tprivate writeStdout(text: string): void {\n\t\tthis.clearProgress()\n\t\twriteStream(this.stdout, text + '\\n')\n\t}\n\n\tprivate writeDiagnostic(message: string, format: (text: string) => string = text => text): void {\n\t\tif (this.currentMode !== 'human') {\n\t\t\treturn\n\t\t}\n\t\tthis.clearProgress()\n\t\twriteStream(this.stderr, format(escapeTerminalText(message)) + '\\n')\n\t}\n}\n\nconst createProcessStream = (stream: NodeJS.WriteStream): OutputStream => ({\n\twrite: text => {\n\t\tstream.write(text)\n\t},\n\tget isTty() {\n\t\treturn stream.isTTY === true\n\t},\n\tget columns() {\n\t\treturn stream.columns\n\t},\n\tonError: listener => {\n\t\tstream.on('error', error => listener(error))\n\t},\n})\n\nlet stdinReader: LineReader | undefined\nconst readStdinLine: PromptLineReader = () => {\n\tstdinReader ??= new LineReader(process.stdin)\n\treturn stdinReader.read()\n}\n\n/**\n * Reads answer lines from one input for all prompts, so that a line typed or pasted ahead of the next prompt is kept\n * and an input that already ended reads as closed. Not in readline's terminal mode: the TTY handles line editing and\n * echo, and Ctrl+C stays a plain SIGINT.\n */\nexport class LineReader {\n\tprivate reader: Interface | undefined\n\tprivate readonly lines: string[] = []\n\tprivate waiting: ((line: string | undefined) => void) | undefined\n\tprivate closed = false\n\n\tconstructor(private readonly input: Readable) {}\n\n\tpublic read(): Promise<string | undefined> {\n\t\tif (this.waiting) {\n\t\t\tthrow new Error('LineReader: a read is already pending')\n\t\t}\n\t\tconst line = this.lines.shift()\n\t\tif (line !== undefined) {\n\t\t\treturn Promise.resolve(line)\n\t\t}\n\t\t// readline never reports `close` for an input that ended before it was attached (Bun does not set readableEnded)\n\t\tif (this.closed || this.input.readableEnded) {\n\t\t\tthis.closed = true\n\t\t\treturn Promise.resolve(undefined)\n\t\t}\n\t\treturn new Promise(resolve => {\n\t\t\tthis.waiting = resolve\n\t\t\tthis.open().resume()\n\t\t})\n\t}\n\n\tprivate open(): Interface {\n\t\tif (this.reader) {\n\t\t\treturn this.reader\n\t\t}\n\t\tconst reader = createInterface({ input: this.input, terminal: false })\n\t\treader.on('line', line => this.settle(line))\n\t\treader.on('close', () => {\n\t\t\tthis.closed = true\n\t\t\tthis.settle(undefined)\n\t\t})\n\t\tthis.reader = reader\n\t\treturn reader\n\t}\n\n\tprivate settle(line: string | undefined): void {\n\t\tconst waiting = this.waiting\n\t\tif (!waiting) {\n\t\t\tif (line !== undefined) {\n\t\t\t\tthis.lines.push(line)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthis.waiting = undefined\n\t\tif (!this.closed) {\n\t\t\t// a paused TTY does not keep the process alive between prompts; Node throws when pausing a closed interface\n\t\t\tthis.reader?.pause()\n\t\t}\n\t\twaiting(line)\n\t}\n}\n\nconst writeStream = (stream: OutputStream, text: string): void => {\n\ttry {\n\t\tstream.write(text)\n\t} catch (error) {\n\t\thandleStreamError(error)\n\t}\n}\n\nconst handleStreamError = (error: unknown): void => {\n\tif (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EPIPE') {\n\t\treturn\n\t}\n\tthrow error\n}\n\n/** Removes terminal control characters from untrusted human-readable text. */\nexport const escapeTerminalText = (value: string): string => {\n\tlet escaped = ''\n\tfor (const character of value) {\n\t\tif (!isTerminalControl(character)) {\n\t\t\tescaped += character\n\t\t}\n\t}\n\treturn escaped\n}\n\nconst isTerminalControl = (character: string): boolean => {\n\tconst codePoint = character.codePointAt(0)\n\treturn codePoint !== undefined && (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f))\n}\n\n// generic in the field so that `format` is a single signature here, not a union of them\nconst renderTableCell = <T, K extends keyof T & string>(column: OutputTableColumns<T>[K], row: T): string =>\n\tcolumn.format ? column.format(row[column.field], row) : formatCell(row[column.field])\n\nconst formatCell = (value: unknown): string => {\n\tif (value === undefined || value === null) {\n\t\treturn ''\n\t}\n\tif (typeof value === 'string') {\n\t\treturn escapeTerminalText(value)\n\t}\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn JSON.stringify(value) ?? ''\n}\n\nconst toScalarLines = (value: unknown): string[] => {\n\tconst values: unknown[] = Array.isArray(value) ? value : [value]\n\tif (!values.every(isOutputScalar)) {\n\t\tthrow new TypeError('Quiet output requires a scalar value or an array of scalar values. Pass an explicit quiet projection for structured data.')\n\t}\n\treturn values.filter(it => it !== undefined && it !== null).map(formatCell)\n}\n\nconst isOutputScalar = (value: unknown): value is OutputScalar =>\n\tvalue === null || value === undefined || ['string', 'number', 'boolean', 'bigint'].includes(typeof value)\n"],"names":[],"mappings":";;;;;;;AAgDO,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AAO,OAAO,KAAK;AAAA,EACpB;AACA,SAAO,KAAK,UAAU,KAAK,KAAK;AACjC;AAEA,MAAM,gBAAgB,CAAC,UAA6B;AACnD,QAAM,SAAoB,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC/D,MAAI,CAAC,OAAO,MAAM,cAAc,GAAG;AAClC,UAAM,IAAI,UAAU,2HAA2H;AAAA,EAChJ;AACA,SAAO,OAAO,OAAO,CAAA,OAAM,OAAO,UAAa,OAAO,IAAI,EAAE,IAAI,UAAU;AAC3E;AAEA,MAAM,iBAAiB,CAAC,UACvB,UAAU,QAAQ,UAAU,UAAa,CAAC,UAAU,UAAU,WAAW,QAAQ,EAAE,SAAS,OAAO,KAAK;"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const node_util = require("node:util");
|
|
4
|
+
const detectColorSupport = () => {
|
|
5
|
+
const forceColor = process.env.FORCE_COLOR;
|
|
6
|
+
if (forceColor !== void 0) {
|
|
7
|
+
return forceColor !== "0" && forceColor !== "false";
|
|
8
|
+
}
|
|
9
|
+
const stdout = process.stdout;
|
|
10
|
+
return stdout.isTTY === true && (typeof stdout.hasColors !== "function" || stdout.hasColors());
|
|
11
|
+
};
|
|
12
|
+
const terminalSupportsColor = detectColorSupport();
|
|
13
|
+
let colorsEnabled = terminalSupportsColor;
|
|
14
|
+
const setColorsEnabled = (enabled) => {
|
|
15
|
+
colorsEnabled = enabled;
|
|
16
|
+
};
|
|
17
|
+
const areColorsEnabled = () => colorsEnabled;
|
|
18
|
+
const style = (styles, text) => {
|
|
19
|
+
if (!colorsEnabled) {
|
|
20
|
+
return text;
|
|
21
|
+
}
|
|
22
|
+
const list = typeof styles === "string" ? [styles] : styles;
|
|
23
|
+
return list.reduceRight((result, current) => node_util.styleText(current, result, { validateStream: false }), text);
|
|
24
|
+
};
|
|
25
|
+
exports.areColorsEnabled = areColorsEnabled;
|
|
26
|
+
exports.setColorsEnabled = setColorsEnabled;
|
|
27
|
+
exports.style = style;
|
|
28
|
+
exports.terminalSupportsColor = terminalSupportsColor;
|
|
29
|
+
//# sourceMappingURL=colors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"colors.cjs","sources":["../../../../../packages/cli-common/src/application/colors.ts"],"sourcesContent":["import { styleText } from 'node:util'\n\nexport type TextStyle = Exclude<Parameters<typeof styleText>[0], readonly unknown[]>\n\n// Same detection as in @contember/logger's PrettyPrintLoggerHandler (which cannot depend on cli-common); keep them in sync.\nconst detectColorSupport = (): boolean => {\n\tconst forceColor = process.env.FORCE_COLOR\n\tif (forceColor !== undefined) {\n\t\treturn forceColor !== '0' && forceColor !== 'false'\n\t}\n\t// hasColors() honours NO_COLOR, NODE_DISABLE_COLORS and TERM=dumb; Bun's non-TTY stdout has no hasColors.\n\tconst stdout = process.stdout\n\treturn stdout.isTTY === true && (typeof stdout.hasColors !== 'function' || stdout.hasColors())\n}\n\n/** Whether stdout can show colors, detected once at startup. */\nexport const terminalSupportsColor: boolean = detectColorSupport()\n\nlet colorsEnabled = terminalSupportsColor\n\n/** Turns colored output on or off for the whole process (`--no-color`, machine-readable modes). */\nexport const setColorsEnabled = (enabled: boolean): void => {\n\tcolorsEnabled = enabled\n}\n\nexport const areColorsEnabled = (): boolean => colorsEnabled\n\n/** Styles `text` with the given styles (outermost first), or returns it unchanged when colors are off. */\nexport const style = (styles: TextStyle | readonly TextStyle[], text: string): string => {\n\tif (!colorsEnabled) {\n\t\treturn text\n\t}\n\tconst list: readonly TextStyle[] = typeof styles === 'string' ? [styles] : styles\n\t// validateStream is off because the decision above is ours; Bun ignores the option and Node < 22.13 lacks it.\n\treturn list.reduceRight((result, current) => styleText(current, result, { validateStream: false }), text)\n}\n"],"names":["styleText"],"mappings":";;;AAKA,MAAM,qBAAqB,MAAe;AACzC,QAAM,aAAa,QAAQ,IAAI;AAC/B,MAAI,eAAe,QAAW;AAC7B,WAAO,eAAe,OAAO,eAAe;AAAA,EAC7C;AAEA,QAAM,SAAS,QAAQ;AACvB,SAAO,OAAO,UAAU,SAAS,OAAO,OAAO,cAAc,cAAc,OAAO;AACnF;AAGO,MAAM,wBAAiC,mBAAA;AAE9C,IAAI,gBAAgB;AAGb,MAAM,mBAAmB,CAAC,YAA2B;AAC3D,kBAAgB;AACjB;AAEO,MAAM,mBAAmB,MAAe;AAGxC,MAAM,QAAQ,CAAC,QAA0C,SAAyB;AACxF,MAAI,CAAC,eAAe;AACnB,WAAO;AAAA,EACR;AACA,QAAM,OAA6B,OAAO,WAAW,WAAW,CAAC,MAAM,IAAI;AAE3E,SAAO,KAAK,YAAY,CAAC,QAAQ,YAAYA,UAAAA,UAAU,SAAS,QAAQ,EAAE,gBAAgB,MAAA,CAAO,GAAG,IAAI;AACzG;;;;;"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
const detectColorSupport = () => {
|
|
3
|
+
const forceColor = process.env.FORCE_COLOR;
|
|
4
|
+
if (forceColor !== void 0) {
|
|
5
|
+
return forceColor !== "0" && forceColor !== "false";
|
|
6
|
+
}
|
|
7
|
+
const stdout = process.stdout;
|
|
8
|
+
return stdout.isTTY === true && (typeof stdout.hasColors !== "function" || stdout.hasColors());
|
|
9
|
+
};
|
|
10
|
+
const terminalSupportsColor = detectColorSupport();
|
|
11
|
+
let colorsEnabled = terminalSupportsColor;
|
|
12
|
+
const setColorsEnabled = (enabled) => {
|
|
13
|
+
colorsEnabled = enabled;
|
|
14
|
+
};
|
|
15
|
+
const areColorsEnabled = () => colorsEnabled;
|
|
16
|
+
const style = (styles, text) => {
|
|
17
|
+
if (!colorsEnabled) {
|
|
18
|
+
return text;
|
|
19
|
+
}
|
|
20
|
+
const list = typeof styles === "string" ? [styles] : styles;
|
|
21
|
+
return list.reduceRight((result, current) => styleText(current, result, { validateStream: false }), text);
|
|
22
|
+
};
|
|
23
|
+
export {
|
|
24
|
+
areColorsEnabled,
|
|
25
|
+
setColorsEnabled,
|
|
26
|
+
style,
|
|
27
|
+
terminalSupportsColor
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=colors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"colors.js","sources":["../../../../../packages/cli-common/src/application/colors.ts"],"sourcesContent":["import { styleText } from 'node:util'\n\nexport type TextStyle = Exclude<Parameters<typeof styleText>[0], readonly unknown[]>\n\n// Same detection as in @contember/logger's PrettyPrintLoggerHandler (which cannot depend on cli-common); keep them in sync.\nconst detectColorSupport = (): boolean => {\n\tconst forceColor = process.env.FORCE_COLOR\n\tif (forceColor !== undefined) {\n\t\treturn forceColor !== '0' && forceColor !== 'false'\n\t}\n\t// hasColors() honours NO_COLOR, NODE_DISABLE_COLORS and TERM=dumb; Bun's non-TTY stdout has no hasColors.\n\tconst stdout = process.stdout\n\treturn stdout.isTTY === true && (typeof stdout.hasColors !== 'function' || stdout.hasColors())\n}\n\n/** Whether stdout can show colors, detected once at startup. */\nexport const terminalSupportsColor: boolean = detectColorSupport()\n\nlet colorsEnabled = terminalSupportsColor\n\n/** Turns colored output on or off for the whole process (`--no-color`, machine-readable modes). */\nexport const setColorsEnabled = (enabled: boolean): void => {\n\tcolorsEnabled = enabled\n}\n\nexport const areColorsEnabled = (): boolean => colorsEnabled\n\n/** Styles `text` with the given styles (outermost first), or returns it unchanged when colors are off. */\nexport const style = (styles: TextStyle | readonly TextStyle[], text: string): string => {\n\tif (!colorsEnabled) {\n\t\treturn text\n\t}\n\tconst list: readonly TextStyle[] = typeof styles === 'string' ? [styles] : styles\n\t// validateStream is off because the decision above is ours; Bun ignores the option and Node < 22.13 lacks it.\n\treturn list.reduceRight((result, current) => styleText(current, result, { validateStream: false }), text)\n}\n"],"names":[],"mappings":";AAKA,MAAM,qBAAqB,MAAe;AACzC,QAAM,aAAa,QAAQ,IAAI;AAC/B,MAAI,eAAe,QAAW;AAC7B,WAAO,eAAe,OAAO,eAAe;AAAA,EAC7C;AAEA,QAAM,SAAS,QAAQ;AACvB,SAAO,OAAO,UAAU,SAAS,OAAO,OAAO,cAAc,cAAc,OAAO;AACnF;AAGO,MAAM,wBAAiC,mBAAA;AAE9C,IAAI,gBAAgB;AAGb,MAAM,mBAAmB,CAAC,YAA2B;AAC3D,kBAAgB;AACjB;AAEO,MAAM,mBAAmB,MAAe;AAGxC,MAAM,QAAQ,CAAC,QAA0C,SAAyB;AACxF,MAAI,CAAC,eAAe;AACnB,WAAO;AAAA,EACR;AACA,QAAM,OAA6B,OAAO,WAAW,WAAW,CAAC,MAAM,IAAI;AAE3E,SAAO,KAAK,YAAY,CAAC,QAAQ,YAAY,UAAU,SAAS,QAAQ,EAAE,gBAAgB,MAAA,CAAO,GAAG,IAAI;AACzG;"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const node_util = require("node:util");
|
|
4
|
+
const colors = require("./colors.cjs");
|
|
5
|
+
const visibleLength = (text) => node_util.stripVTControlCharacters(text).length;
|
|
6
|
+
const pad = (text, width) => text + " ".repeat(Math.max(width - visibleLength(text), 0));
|
|
7
|
+
const formatTable = (columns, rows) => {
|
|
8
|
+
const headers = columns.map((column) => colors.style("bold", column.name));
|
|
9
|
+
const widths = columns.map(
|
|
10
|
+
(column, index) => rows.reduce((width, row) => Math.max(width, visibleLength(row[column.field] ?? "")), visibleLength(headers[index]))
|
|
11
|
+
);
|
|
12
|
+
const separator = `+${widths.map((width) => "-".repeat(width + 2)).join("+")}+`;
|
|
13
|
+
const line = (cells) => `| ${cells.map((cell, index) => pad(cell, widths[index])).join(" | ")} |`;
|
|
14
|
+
return [
|
|
15
|
+
separator,
|
|
16
|
+
line(headers),
|
|
17
|
+
separator,
|
|
18
|
+
...rows.map((row) => line(columns.map((column) => row[column.field] ?? ""))),
|
|
19
|
+
separator
|
|
20
|
+
].join("\n");
|
|
21
|
+
};
|
|
22
|
+
exports.formatTable = formatTable;
|
|
23
|
+
//# sourceMappingURL=table.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"table.cjs","sources":["../../../../../packages/cli-common/src/application/table.ts"],"sourcesContent":["import { stripVTControlCharacters } from 'node:util'\nimport { style } from './colors.js'\n\nexport interface TableColumn<Field extends string> {\n\treadonly field: Field\n\treadonly name: string\n}\n\nconst visibleLength = (text: string): number => stripVTControlCharacters(text).length\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(width - visibleLength(text), 0))\n\n/** Renders an ASCII table with bold headers; widths ignore ANSI styling in the cells. */\nexport const formatTable = <Field extends string>(\n\tcolumns: readonly TableColumn<Field>[],\n\trows: readonly Partial<Record<Field, string>>[],\n): string => {\n\tconst headers = columns.map(column => style('bold', column.name))\n\tconst widths = columns.map((column, index) =>\n\t\trows.reduce((width, row) => Math.max(width, visibleLength(row[column.field] ?? '')), visibleLength(headers[index]))\n\t)\n\tconst separator = `+${widths.map(width => '-'.repeat(width + 2)).join('+')}+`\n\tconst line = (cells: readonly string[]): string => `| ${cells.map((cell, index) => pad(cell, widths[index])).join(' | ')} |`\n\treturn [\n\t\tseparator,\n\t\tline(headers),\n\t\tseparator,\n\t\t...rows.map(row => line(columns.map(column => row[column.field] ?? ''))),\n\t\tseparator,\n\t].join('\\n')\n}\n"],"names":["stripVTControlCharacters","style"],"mappings":";;;;AAQA,MAAM,gBAAgB,CAAC,SAAyBA,mCAAyB,IAAI,EAAE;AAE/E,MAAM,MAAM,CAAC,MAAc,UAA0B,OAAO,IAAI,OAAO,KAAK,IAAI,QAAQ,cAAc,IAAI,GAAG,CAAC,CAAC;AAGxG,MAAM,cAAc,CAC1B,SACA,SACY;AACZ,QAAM,UAAU,QAAQ,IAAI,CAAA,WAAUC,OAAAA,MAAM,QAAQ,OAAO,IAAI,CAAC;AAChE,QAAM,SAAS,QAAQ;AAAA,IAAI,CAAC,QAAQ,UACnC,KAAK,OAAO,CAAC,OAAO,QAAQ,KAAK,IAAI,OAAO,cAAc,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC,GAAG,cAAc,QAAQ,KAAK,CAAC,CAAC;AAAA,EAAA;AAEnH,QAAM,YAAY,IAAI,OAAO,IAAI,CAAA,UAAS,IAAI,OAAO,QAAQ,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC;AAC1E,QAAM,OAAO,CAAC,UAAqC,KAAK,MAAM,IAAI,CAAC,MAAM,UAAU,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC;AACxH,SAAO;AAAA,IACN;AAAA,IACA,KAAK,OAAO;AAAA,IACZ;AAAA,IACA,GAAG,KAAK,IAAI,CAAA,QAAO,KAAK,QAAQ,IAAI,CAAA,WAAU,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC,CAAC;AAAA,IACvE;AAAA,EAAA,EACC,KAAK,IAAI;AACZ;;"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
import { style } from "./colors.js";
|
|
3
|
+
const visibleLength = (text) => stripVTControlCharacters(text).length;
|
|
4
|
+
const pad = (text, width) => text + " ".repeat(Math.max(width - visibleLength(text), 0));
|
|
5
|
+
const formatTable = (columns, rows) => {
|
|
6
|
+
const headers = columns.map((column) => style("bold", column.name));
|
|
7
|
+
const widths = columns.map(
|
|
8
|
+
(column, index) => rows.reduce((width, row) => Math.max(width, visibleLength(row[column.field] ?? "")), visibleLength(headers[index]))
|
|
9
|
+
);
|
|
10
|
+
const separator = `+${widths.map((width) => "-".repeat(width + 2)).join("+")}+`;
|
|
11
|
+
const line = (cells) => `| ${cells.map((cell, index) => pad(cell, widths[index])).join(" | ")} |`;
|
|
12
|
+
return [
|
|
13
|
+
separator,
|
|
14
|
+
line(headers),
|
|
15
|
+
separator,
|
|
16
|
+
...rows.map((row) => line(columns.map((column) => row[column.field] ?? ""))),
|
|
17
|
+
separator
|
|
18
|
+
].join("\n");
|
|
19
|
+
};
|
|
20
|
+
export {
|
|
21
|
+
formatTable
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=table.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"table.js","sources":["../../../../../packages/cli-common/src/application/table.ts"],"sourcesContent":["import { stripVTControlCharacters } from 'node:util'\nimport { style } from './colors.js'\n\nexport interface TableColumn<Field extends string> {\n\treadonly field: Field\n\treadonly name: string\n}\n\nconst visibleLength = (text: string): number => stripVTControlCharacters(text).length\n\nconst pad = (text: string, width: number): string => text + ' '.repeat(Math.max(width - visibleLength(text), 0))\n\n/** Renders an ASCII table with bold headers; widths ignore ANSI styling in the cells. */\nexport const formatTable = <Field extends string>(\n\tcolumns: readonly TableColumn<Field>[],\n\trows: readonly Partial<Record<Field, string>>[],\n): string => {\n\tconst headers = columns.map(column => style('bold', column.name))\n\tconst widths = columns.map((column, index) =>\n\t\trows.reduce((width, row) => Math.max(width, visibleLength(row[column.field] ?? '')), visibleLength(headers[index]))\n\t)\n\tconst separator = `+${widths.map(width => '-'.repeat(width + 2)).join('+')}+`\n\tconst line = (cells: readonly string[]): string => `| ${cells.map((cell, index) => pad(cell, widths[index])).join(' | ')} |`\n\treturn [\n\t\tseparator,\n\t\tline(headers),\n\t\tseparator,\n\t\t...rows.map(row => line(columns.map(column => row[column.field] ?? ''))),\n\t\tseparator,\n\t].join('\\n')\n}\n"],"names":[],"mappings":";;AAQA,MAAM,gBAAgB,CAAC,SAAyB,yBAAyB,IAAI,EAAE;AAE/E,MAAM,MAAM,CAAC,MAAc,UAA0B,OAAO,IAAI,OAAO,KAAK,IAAI,QAAQ,cAAc,IAAI,GAAG,CAAC,CAAC;AAGxG,MAAM,cAAc,CAC1B,SACA,SACY;AACZ,QAAM,UAAU,QAAQ,IAAI,CAAA,WAAU,MAAM,QAAQ,OAAO,IAAI,CAAC;AAChE,QAAM,SAAS,QAAQ;AAAA,IAAI,CAAC,QAAQ,UACnC,KAAK,OAAO,CAAC,OAAO,QAAQ,KAAK,IAAI,OAAO,cAAc,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC,GAAG,cAAc,QAAQ,KAAK,CAAC,CAAC;AAAA,EAAA;AAEnH,QAAM,YAAY,IAAI,OAAO,IAAI,CAAA,UAAS,IAAI,OAAO,QAAQ,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC;AAC1E,QAAM,OAAO,CAAC,UAAqC,KAAK,MAAM,IAAI,CAAC,MAAM,UAAU,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC;AACxH,SAAO;AAAA,IACN;AAAA,IACA,KAAK,OAAO;AAAA,IACZ;AAAA,IACA,GAAG,KAAK,IAAI,CAAA,QAAO,KAAK,QAAQ,IAAI,CAAA,WAAU,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC,CAAC;AAAA,IACvE;AAAA,EAAA,EACC,KAAK,IAAI;AACZ;"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const Application = require("./src/application/Application.cjs");
|
|
4
4
|
const CliError = require("./src/application/CliError.cjs");
|
|
5
|
+
const colors = require("./src/application/colors.cjs");
|
|
5
6
|
const Command = require("./src/application/Command.cjs");
|
|
6
7
|
const CommandManager = require("./src/application/CommandManager.cjs");
|
|
7
8
|
const CommandConfiguration = require("./src/application/CommandConfiguration.cjs");
|
|
@@ -12,6 +13,7 @@ const Input = require("./src/application/Input.cjs");
|
|
|
12
13
|
const InputParser = require("./src/application/InputParser.cjs");
|
|
13
14
|
const Option = require("./src/application/Option.cjs");
|
|
14
15
|
const Output = require("./src/application/Output.cjs");
|
|
16
|
+
const table = require("./src/application/table.cjs");
|
|
15
17
|
const CommandRunner = require("./src/npm/CommandRunner.cjs");
|
|
16
18
|
const PackageWorkspace = require("./src/npm/PackageWorkspace.cjs");
|
|
17
19
|
const Bun = require("./src/npm/packageManagers/Bun.cjs");
|
|
@@ -25,6 +27,10 @@ exports.Application = Application.Application;
|
|
|
25
27
|
exports.CliError = CliError.CliError;
|
|
26
28
|
exports.ExitCode = CliError.ExitCode;
|
|
27
29
|
exports.toCliError = CliError.toCliError;
|
|
30
|
+
exports.areColorsEnabled = colors.areColorsEnabled;
|
|
31
|
+
exports.setColorsEnabled = colors.setColorsEnabled;
|
|
32
|
+
exports.style = colors.style;
|
|
33
|
+
exports.terminalSupportsColor = colors.terminalSupportsColor;
|
|
28
34
|
exports.Command = Command.Command;
|
|
29
35
|
exports.CommandManager = CommandManager.CommandManager;
|
|
30
36
|
exports.CommandConfiguration = CommandConfiguration.CommandConfiguration;
|
|
@@ -39,6 +45,7 @@ exports.OptionMode = Option.OptionMode;
|
|
|
39
45
|
exports.mergeOptions = Option.mergeOptions;
|
|
40
46
|
exports.Output = Output.Output;
|
|
41
47
|
exports.escapeTerminalText = Output.escapeTerminalText;
|
|
48
|
+
exports.formatTable = table.formatTable;
|
|
42
49
|
exports.ChildProcessError = CommandRunner.ChildProcessError;
|
|
43
50
|
exports.CommandRunner = CommandRunner.CommandRunner;
|
|
44
51
|
exports.PackageWorkspace = PackageWorkspace.PackageWorkspace;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/production/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Application } from "./src/application/Application.js";
|
|
2
2
|
import { CliError, ExitCode, toCliError } from "./src/application/CliError.js";
|
|
3
|
+
import { areColorsEnabled, setColorsEnabled, style, terminalSupportsColor } from "./src/application/colors.js";
|
|
3
4
|
import { Command } from "./src/application/Command.js";
|
|
4
5
|
import { CommandManager } from "./src/application/CommandManager.js";
|
|
5
6
|
import { CommandConfiguration, InvalidConfigurationError } from "./src/application/CommandConfiguration.js";
|
|
@@ -10,6 +11,7 @@ import { Input } from "./src/application/Input.js";
|
|
|
10
11
|
import { InvalidInputError } from "./src/application/InputParser.js";
|
|
11
12
|
import { OptionMode, mergeOptions } from "./src/application/Option.js";
|
|
12
13
|
import { Output, escapeTerminalText } from "./src/application/Output.js";
|
|
14
|
+
import { formatTable } from "./src/application/table.js";
|
|
13
15
|
import { ChildProcessError, CommandRunner } from "./src/npm/CommandRunner.js";
|
|
14
16
|
import { PackageWorkspace } from "./src/npm/PackageWorkspace.js";
|
|
15
17
|
import { Bun } from "./src/npm/packageManagers/Bun.js";
|
|
@@ -40,13 +42,18 @@ export {
|
|
|
40
42
|
Pnpm,
|
|
41
43
|
Yarn,
|
|
42
44
|
YarnClassic,
|
|
45
|
+
areColorsEnabled,
|
|
43
46
|
escapeTerminalText,
|
|
44
47
|
exitProcess,
|
|
45
48
|
findPackageRoot,
|
|
49
|
+
formatTable,
|
|
46
50
|
globalOptions,
|
|
47
51
|
mergeOptions,
|
|
48
52
|
readGlobalOptionsFromArgs,
|
|
49
53
|
renderCliError,
|
|
54
|
+
setColorsEnabled,
|
|
55
|
+
style,
|
|
56
|
+
terminalSupportsColor,
|
|
50
57
|
toCliError
|
|
51
58
|
};
|
|
52
59
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
-
const
|
|
3
|
+
const colors = require("./colors.cjs");
|
|
4
4
|
const Command = require("./Command.cjs");
|
|
5
5
|
const InputParser = require("./InputParser.cjs");
|
|
6
6
|
const Output = require("./Output.cjs");
|
|
@@ -82,7 +82,7 @@ class Application {
|
|
|
82
82
|
const exitCode = ErrorRenderer.renderCliError(e, this.output);
|
|
83
83
|
if (e instanceof InputParser.InvalidInputError && command !== void 0 && this.output.mode === "human") {
|
|
84
84
|
const usage = command.getConfiguration().getUsage({ format: "line" });
|
|
85
|
-
this.output.writeStderr(`${showCommandName && entry ?
|
|
85
|
+
this.output.writeStderr(`${showCommandName && entry ? colors.style("greenBright", entry.name) + " " : ""}${colors.style("green", usage)}`);
|
|
86
86
|
}
|
|
87
87
|
return exitCode;
|
|
88
88
|
}
|
|
@@ -98,11 +98,11 @@ class Application {
|
|
|
98
98
|
const indent = " ";
|
|
99
99
|
for (const entry of commands) {
|
|
100
100
|
const configuration = entry.create().getConfiguration();
|
|
101
|
-
this.output.writeStderr(`${indent}${
|
|
101
|
+
this.output.writeStderr(`${indent}${colors.style("greenBright", entry.name.padEnd(maxCommandNameLength))}${indent}${configuration.getDescription()}`);
|
|
102
102
|
if (verbose) {
|
|
103
103
|
const helpIndent = `${indent}${" ".repeat(maxCommandNameLength)}${indent}`;
|
|
104
104
|
const usage = configuration.getUsage({ format: "multiline", indent: helpIndent });
|
|
105
|
-
this.output.writeStderr(usage ?
|
|
105
|
+
this.output.writeStderr(usage ? colors.style("green", usage) : `${helpIndent}${colors.style("gray", "No options")}`);
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
}
|
|
@@ -112,12 +112,12 @@ class Application {
|
|
|
112
112
|
const indent = " ";
|
|
113
113
|
for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
114
114
|
const configuration = entry.create().getConfiguration();
|
|
115
|
-
this.output.writeStderr(`${indent}${
|
|
115
|
+
this.output.writeStderr(`${indent}${colors.style("greenBright", entry.name.padEnd(maxCommandNameLength))}${indent}${configuration.getDescription()}`);
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
printCommandHelp(name, command, showCommandName) {
|
|
119
119
|
if (showCommandName) {
|
|
120
|
-
this.output.writeStderr(
|
|
120
|
+
this.output.writeStderr(colors.style("greenBright", name));
|
|
121
121
|
}
|
|
122
122
|
const configuration = command.getConfiguration();
|
|
123
123
|
const commandDescription = configuration.getDescription();
|
|
@@ -127,7 +127,7 @@ class Application {
|
|
|
127
127
|
const shortUsage = configuration.getUsage({ format: "short" });
|
|
128
128
|
if (shortUsage) {
|
|
129
129
|
this.output.writeStderr("\nUsage:");
|
|
130
|
-
this.output.writeStderr(
|
|
130
|
+
this.output.writeStderr(colors.style("green", shortUsage));
|
|
131
131
|
this.output.writeStderr("\nArguments and options:");
|
|
132
132
|
this.output.writeStderr(configuration.getUsage({ format: "multiline" }));
|
|
133
133
|
}
|