Пример
chalk 6.0.0: Instantiate Chalk instances with custom color levels to downsample 24-bit hex and RGB colors across terminal depths and avoid default export constructor traps
Проверенный пример — npm chalk 6.0.0: Instantiate Chalk instances with custom color levels to downsample 24-bit hex and RGB colors across terminal depths and…
sha256:1d01640309b3b61194965429100ee64dc820854d9541aa68eaf18e0830575a8a
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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- Цель
- Instantiate Chalk instances with custom color levels to downsample 24-bit hex and RGB colors across terminal depths and avoid default export constructor traps
- Пакеты
- Символы
-
- Chalk
- Chalk.prototype.hex
- Chalk.prototype.rgb
- Chalk.prototype.bgHex
- Chalk.prototype.level
- Окружение
- node
- Создан
- 2026-08-16T07:28:31Z
Контракт
- import Chalk constructor as a named export rather than accessing undefined chalk.Chalk or chalk.Instance on default export
- assert level 3 (truecolor) emits 24-bit 38;2 foreground and 48;2 background ANSI codes
- assert level 2 (256-color) dynamically downsamples rgb and hex colors to 38;5 palette index escape codes
- assert level 1 (16-color) downsamples rgb and hex to standard 16-color ANSI codes (e.g. 91m, 104m)
- assert level 0 strips ANSI styling and returns plain strings
- assert mutating instance level property dynamically adjusts downsampling for subsequent calls
- assert nested styles re-open the enclosing style code immediately following the child closing code
Файлы
- NOTES.md
- csx.json
- package-lock.json
- package.json
- src/index.mjs
- test/contract.mjs
Исходный код
# Chalk API & Downsampling Contract Notes
## Search Results
`search_known_solution` returned existing sample `sha256:5ac46730b5bb5d118cfacbf37a585770c5984e5dd37bc9ffbde2f967ada3a06c` ("Make chalk emit colour codes when output is piped instead of silently producing plain text").
## What a Model Would Have Written Instead
A model creating custom stylers or asserting ANSI escape codes for 24-bit colors (`hex()`/`rgb()`) would write `new chalk.Instance({ level })` or `new chalk.Chalk({ level })` on the default export and assert that `hex('#FF0000')` unconditionally produces 24-bit Truecolor sequence `\u001b[38;2;255;0;0m`.
## How the Wrong Version Fails
1. **Loudly at runtime**: Accessing `chalk.Chalk` or `chalk.Instance` throws `TypeError: chalk.Chalk is not a constructor` because Chalk v5+ only provides `Chalk` as a named ESM export.
2. **Loudly in test assertions / silently in terminal rendering**: In Level 1 (16-color) or Level 2 (256-color) terminal environments, Chalk dynamically downsamples `hex('#FF0000')` to `\u001b[91m` (16-color) or `\u001b[38;5;196m` (256-color), causing Truecolor regex/exact match assertions to fail while terminal renderers degrade smoothly without errors.
{"case":{"caseId":"case:sha256:57ac4e54f3a1662b1bb8a36dcd81a7ada8acb5bc34022d0894c513c42d4b96c0","contract":["import Chalk constructor as a named export rather than accessing undefined chalk.Chalk or chalk.Instance on default export","assert level 3 (truecolor) emits 24-bit 38;2 foreground and 48;2 background ANSI codes","assert level 2 (256-color) dynamically downsamples rgb and hex colors to 38;5 palette index escape codes","assert level 1 (16-color) downsamples rgb and hex to standard 16-color ANSI codes (e.g. 91m, 104m)","assert level 0 strips ANSI styling and returns plain strings","assert mutating instance level property dynamically adjusts downsampling for subsequent calls","assert nested styles re-open the enclosing style code immediately following the child closing code"],"goal":"Instantiate Chalk instances with custom color levels to downsample 24-bit hex and RGB colors across terminal depths and avoid default export constructor traps","kind":"HOW","packages":["pkg:npm/chalk@6.0.0"],"schemaVersion":1,"symbols":["Chalk","Chalk.prototype.hex","Chalk.prototype.rgb","Chalk.prototype.bgHex","Chalk.prototype.level"]},"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@6.0.0"],"schemaVersion":1,"symbols":["Chalk","Chalk.prototype.hex","Chalk.prototype.rgb","Chalk.prototype.bgHex","Chalk.prototype.level"],"verifierAdapter":"node-typescript@1"}
{
"name": "csx-sample-chalk-api",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "csx-sample-chalk-api",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"chalk": "6.0.0"
}
},
"node_modules/chalk": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz",
"integrity": "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==",
"license": "MIT",
"engines": {
"node": ">=22"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
}
}
}
{
"name": "csx-sample-chalk-api",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"chalk": "6.0.0"
}
}
import chalk, { Chalk } from 'chalk';
// In Chalk v5+, Chalk is a named export; the default export does NOT attach
// chalk.Chalk or chalk.Instance (both are undefined).
export function createStyler(level) {
return new Chalk({ level });
}
// Default export checks for models attempting v4-style access
export function getDefaultExportProps() {
return {
hasChalkOnDefault: typeof chalk.Chalk !== 'undefined',
hasInstanceOnDefault: typeof chalk.Instance !== 'undefined',
hasSupportsColorOnDefault: typeof chalk.supportsColor !== 'undefined',
};
}
// Rgb / Hex styling downsamples dynamically based on instance level:
// level 3 -> 24-bit truecolor (\u001b[38;2;r;g;bm)
// level 2 -> 256-color palette (\u001b[38;5;idxm)
// level 1 -> 16-color basic (\u001b[91m / \u001b[31m)
// level 0 -> plain text
export function renderRgb(styler, text, r, g, b) {
return styler.rgb(r, g, b)(text);
}
export function renderHex(styler, text, hex) {
return styler.hex(hex)(text);
}
export function renderBgHex(styler, text, hex) {
return styler.bgHex(hex)(text);
}
// Multi-argument styling joins with spaces and wraps the entire string
export function renderMulti(styler, ...args) {
return styler.red(...args);
}
// Nested styles: Chalk re-opens parent style code after inner style closing code
export function renderNested(styler, outerPrefix, innerText, outerSuffix) {
return styler.red(`${outerPrefix} ${styler.blue(innerText)} ${outerSuffix}`);
}
import { strict as assert } from 'node:assert';
import {
createStyler,
getDefaultExportProps,
renderRgb,
renderHex,
renderBgHex,
renderMulti,
renderNested,
} from '../src/index.mjs';
// 1. In Chalk v5+, chalk default export does not expose Chalk, Instance, or supportsColor
const defaultProps = getDefaultExportProps();
assert.equal(defaultProps.hasChalkOnDefault, false, 'chalk.Chalk is undefined on default export');
assert.equal(defaultProps.hasInstanceOnDefault, false, 'chalk.Instance is undefined on default export');
assert.equal(defaultProps.hasSupportsColorOnDefault, false, 'chalk.supportsColor is undefined on default export');
// 2. Level 3 (Truecolor 24-bit) emits 38;2 and 48;2 sequences
const styler3 = createStyler(3);
assert.equal(
renderRgb(styler3, 'alert', 255, 0, 0),
'\u001b[38;2;255;0;0malert\u001b[39m',
'Level 3 rgb() emits 24-bit ANSI truecolor'
);
assert.equal(
renderHex(styler3, 'alert', '#FF0000'),
'\u001b[38;2;255;0;0malert\u001b[39m',
'Level 3 hex() emits 24-bit ANSI truecolor'
);
assert.equal(
renderBgHex(styler3, 'badge', '#0000FF'),
'\u001b[48;2;0;0;255mbadge\u001b[49m',
'Level 3 bgHex() emits 24-bit ANSI truecolor background'
);
// 3. Level 2 (256-color) downsamples rgb/hex to 256-color palette (38;5;idx)
const styler2 = createStyler(2);
assert.equal(
renderRgb(styler2, 'alert', 255, 0, 0),
'\u001b[38;5;196malert\u001b[39m',
'Level 2 rgb() downsamples to 256-color palette index 196'
);
assert.equal(
renderHex(styler2, 'alert', '#FF0000'),
'\u001b[38;5;196malert\u001b[39m',
'Level 2 hex() downsamples to 256-color palette index 196'
);
// 4. Level 1 (16-color basic) downsamples rgb/hex to basic ANSI escape codes
const styler1 = createStyler(1);
assert.equal(
renderRgb(styler1, 'alert', 255, 0, 0),
'\u001b[91malert\u001b[39m',
'Level 1 rgb() downsamples to basic ANSI 91 (bright red)'
);
assert.equal(
renderHex(styler1, 'alert', '#FF0000'),
'\u001b[91malert\u001b[39m',
'Level 1 hex() downsamples to basic ANSI 91 (bright red)'
);
assert.equal(
renderBgHex(styler1, 'badge', '#0000FF'),
'\u001b[104mbadge\u001b[49m',
'Level 1 bgHex() downsamples to basic ANSI 104 (bright blue bg)'
);
// 5. Level 0 (disabled) produces plain text without any escape sequences
const styler0 = createStyler(0);
assert.equal(renderHex(styler0, 'alert', '#FF0000'), 'alert', 'Level 0 hex() returns unstyled text');
assert.equal(renderRgb(styler0, 'alert', 255, 0, 0), 'alert', 'Level 0 rgb() returns unstyled text');
// 6. Dynamic mutation of styler.level recalculates downsampling on subsequent calls
const dynamicStyler = createStyler(3);
assert.equal(renderHex(dynamicStyler, 'msg', '#FF0000'), '\u001b[38;2;255;0;0mmsg\u001b[39m');
dynamicStyler.level = 1;
assert.equal(renderHex(dynamicStyler, 'msg', '#FF0000'), '\u001b[91mmsg\u001b[39m');
// 7. Nested styles automatically re-open the parent style after inner reset code
assert.equal(
renderNested(styler3, 'START', 'MID', 'END'),
'\u001b[31mSTART \u001b[34mMID\u001b[39m\u001b[31m END\u001b[39m',
'Chalk re-opens parent style (31m) immediately after child closing code (39m)'
);
// 8. Multi-argument calls join with spaces
assert.equal(
renderMulti(styler3, 'foo', 'bar', 42),
'\u001b[31mfoo bar 42\u001b[39m',
'Chalk joins multiple arguments with a space and wraps with style'
);
console.log('CONTRACT PASS: Chalk instance downsampling, nesting, and constructor behavior verified');