CodeSampleX

Пример

chalk 5.4.1: Conditionally suppress output when colors are disabled via chalk.visible rather than expecting ANSI visibility escapes or fallback text

Проверенный пример — npm chalk 5.4.1: Conditionally suppress output when colors are disabled via chalk.visible rather than expecting ANSI visibility escapes…

sha256:0240563ac9001349696844ed8d9dd11b6a0a7c2ee4407250abdd3570838147f1

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда node linux x64 node node npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Кейс

HOW
Цель
Conditionally suppress output when colors are disabled via chalk.visible rather than expecting ANSI visibility escapes or fallback text
Пакеты
Символы
  • chalk.visible
  • Chalk.prototype.visible
  • chalk.hidden
Окружение
node
Создан
2026-08-16T16:09:14Z

Контракт

  1. chalk.visible returns an empty string when chalk.level is 0, suppressing the text entirely rather than returning the plain unstyled string or adding ANSI visibility escape sequences.
  2. chalk.visible at level 1 returns the exact unstyled text without adding any ANSI open or close escape sequences
  3. chained styles containing visible return an empty string at level 0 and formatted text at level 1
  4. chalk.hidden emits ANSI hidden escape codes at level 1 and preserves the unstyled string at level 0, contrasting with chalk.visible

Файлы

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Chalk `visible` Modifier Behavior and Fallback Suppression

### What `search_known_solution` answered
- `search_known_solution` returned existing sample `sha256:525f14e9ff41964b2cf8700329f042389c75335c2b13dc4d12796c1cbb8e0f28` ("Configure runtime color formatting and disable ANSI codes in Chalk v5 via chalk.level instead of deprecated chalk.enabled or missing chalk.supportsColor").
- This sample proves a distinct modifier trap: `chalk.visible` does not emit ANSI visibility escape codes, but instead functions as a conditional visibility gate that discards text (returning `""`) when `level === 0`.

### What a model would have written instead
- A model assumes `chalk.visible(text)` either wraps `text` in ANSI visibility escape sequences or returns the unstyled input string when colors are disabled (`level: 0`), matching the fallback behavior of all other modifiers like `chalk.bold`, `chalk.hidden`, and `chalk.dim`.

### How the wrong version fails
- Silently with a green build: in non-color environments or redirected pipelines (`level: 0`), `chalk.visible` silently produces empty strings (`""`), causing expected status strings or logs to be completely erased from output rather than rendered as plain text.
csx.json
{"case":{"believed":"chalk.visible wraps text in ANSI visibility escape codes when enabled and returns the unstyled input string when colors are disabled (level: 0), matching the fallback behavior of all other chalk modifiers.","caseId":"case:sha256:9960b572d301299f067c2be2eebe065095490e0c60c9b40542a2c51c2fc62847","contract":["chalk.visible returns an empty string when chalk.level is 0, suppressing the text entirely rather than returning the plain unstyled string or adding ANSI visibility escape sequences.","chalk.visible at level 1 returns the exact unstyled text without adding any ANSI open or close escape sequences","chained styles containing visible return an empty string at level 0 and formatted text at level 1","chalk.hidden emits ANSI hidden escape codes at level 1 and preserves the unstyled string at level 0, contrasting with chalk.visible"],"goal":"Conditionally suppress output when colors are disabled via chalk.visible rather than expecting ANSI visibility escapes or fallback text","kind":"HOW","packages":["pkg:npm/chalk@5.4.1"],"schemaVersion":1,"symbols":["chalk.visible","Chalk.prototype.visible","chalk.hidden"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/chalk@5.4.1"],"schemaVersion":1,"symbols":["chalk.visible","Chalk.prototype.visible","chalk.hidden"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-chalk-visible",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-chalk-visible",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "chalk": "5.4.1"
      }
    },
    "node_modules/chalk": {
      "version": "5.4.1",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
      "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
      "license": "MIT",
      "engines": {
        "node": "^12.17.0 || ^14.13 || >=16.0.0"
      },
      "funding": {
        "url": "https://github.com/chalk/chalk?sponsor=1"
      }
    }
  }
}
package.json
{
  "name": "sample-chalk-visible",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "chalk": "5.4.1"
  }
}
src/index.mjs
import chalk, { Chalk } from 'chalk';

/**
 * Format text using chalk.visible.
 *
 * When color is disabled (level: 0), chalk.visible discards the text and returns an empty string.
 * When color is enabled (level >= 1), chalk.visible passes through the text without adding ANSI codes.
 *
 * @param {import('chalk').ChalkInstance} styler
 * @param {...unknown} args
 * @returns {string}
 */
export function formatVisible(styler, ...args) {
  return styler.visible(...args);
}

/**
 * Format text combining chalk.visible with foreground color and modifier styling.
 *
 * @param {import('chalk').ChalkInstance} styler
 * @param {...unknown} args
 * @returns {string}
 */
export function formatVisibleStyled(styler, ...args) {
  return styler.visible.cyan.bold(...args);
}

/**
 * Format text using chalk.hidden.
 *
 * Unlike visible, hidden emits ANSI escape codes (\u001b[8m...\u001b[28m) when level >= 1,
 * and preserves the unstyled text when level is 0.
 *
 * @param {import('chalk').ChalkInstance} styler
 * @param {...unknown} args
 * @returns {string}
 */
export function formatHidden(styler, ...args) {
  return styler.hidden(...args);
}

/**
 * Format text using chalk.bold.
 *
 * @param {import('chalk').ChalkInstance} styler
 * @param {...unknown} args
 * @returns {string}
 */
export function formatBold(styler, ...args) {
  return styler.bold(...args);
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import chalk, { Chalk } from 'chalk';
import {
  formatVisible,
  formatVisibleStyled,
  formatHidden,
  formatBold,
} from '../src/index.mjs';

// 1. Contract assertion 1: When chalk.level is 0, chalk.visible returns an empty string "",
// suppressing output entirely rather than returning the plain unstyled string.
const level0 = new Chalk({ level: 0 });
assert.strictEqual(
  formatVisible(level0, 'important status'),
  '',
  'chalk.visible must return an empty string when level is 0'
);
assert.strictEqual(
  formatVisible(level0, 'part1', 'part2', 100),
  '',
  'chalk.visible with multiple arguments must return an empty string when level is 0'
);

// Verify that the default export behaves identically when chalk.level = 0
chalk.level = 0;
assert.strictEqual(
  chalk.visible('color-only text'),
  '',
  'default chalk.visible must return empty string when chalk.level is 0'
);

// 2. Contract assertion 2: At level >= 1, chalk.visible returns the unstyled input string
// without introducing ANY ANSI escape sequences (open or close).
const level1 = new Chalk({ level: 1 });
const visibleOutput = formatVisible(level1, 'important status');
assert.strictEqual(
  visibleOutput,
  'important status',
  'chalk.visible must return unstyled text at level 1'
);
assert.strictEqual(
  visibleOutput.includes('\u001b'),
  false,
  'chalk.visible must not introduce any ANSI escape codes'
);
assert.strictEqual(
  formatVisible(level1, 'part1', 'part2', 100),
  'part1 part2 100',
  'chalk.visible must join multiple arguments with space at level 1'
);

// 3. Contract assertion 3: Chained styles with visible return "" at level 0 and styled text at level 1.
assert.strictEqual(
  formatVisibleStyled(level0, 'critical alert'),
  '',
  'Chained visible styles must discard output completely when level is 0'
);
assert.strictEqual(
  level0.red.visible('alert'),
  '',
  'Chaining visible after color must also discard output when level is 0'
);
assert.strictEqual(
  formatVisibleStyled(level1, 'critical alert'),
  '\u001b[36m\u001b[1mcritical alert\u001b[22m\u001b[39m',
  'Chained visible styles must emit ANSI codes at level 1'
);
assert.strictEqual(
  level1.red.visible('alert'),
  '\u001b[31malert\u001b[39m',
  'Chaining visible after color must emit red ANSI codes at level 1'
);

// 4. Contract assertion 4: Contrast with chalk.hidden and chalk.bold fallback behavior.
// Unlike chalk.visible which returns "", standard modifiers preserve the unstyled string at level 0.
assert.strictEqual(
  formatHidden(level0, 'secret key'),
  'secret key',
  'chalk.hidden must return plain string when level is 0'
);
assert.strictEqual(
  formatBold(level0, 'heading'),
  'heading',
  'chalk.bold must return plain string when level is 0'
);

// At level 1, chalk.hidden introduces ANSI hidden escape code 8m / 28m.
assert.strictEqual(
  formatHidden(level1, 'secret key'),
  '\u001b[8msecret key\u001b[28m',
  'chalk.hidden must emit ANSI hidden escapes at level 1'
);

console.log('CONTRACT PASS: chalk.visible conditional suppression behavior verified');

Исходный сидер

csx-seed