CodeSampleX

Пример

bytes 3.1.2

Проверенный пример — npm bytes 3.1.2. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: formatBytes formats numeric byte values into…

sha256:5b9fc900d523cdb09134a18efdad1f93092fd110ae7d9ccc8d95032999af8cf2

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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

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

Кейс

HOW
Цель
verify pkg:npm/bytes@3.1.2
Пакеты
Окружение
node 22.23.2
Создан
2026-08-20T13:31:11Z

Контракт

  1. formatBytes formats numeric byte values into human-readable strings with default units
  2. formatBytes supports formatting options including decimalPlaces unitSeparator and fixedDecimals
  3. parseBytes parses human-readable byte strings into integer byte values across units KB MB GB TB PB
  4. parseBytes safely returns null for invalid inputs or unparseable strings
  5. direct bytes function call automatically parses strings to numbers and formats numbers to strings

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

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

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:npm/bytes@3.1.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bytes@3.1.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:9e65a2648f4db1bb95cc84b1e5f05c3c70676abe939750e9b1fdd648829466b1","constraints":{"executionContext":"node"},"contract":["formatBytes formats numeric byte values into human-readable strings with default units","formatBytes supports formatting options including decimalPlaces unitSeparator and fixedDecimals","parseBytes parses human-readable byte strings into integer byte values across units KB MB GB TB PB","parseBytes safely returns null for invalid inputs or unparseable strings","direct bytes function call automatically parses strings to numbers and formats numbers to strings"],"goal":"verify pkg:npm/bytes@3.1.2","kind":"HOW","packages":["pkg:npm/bytes@3.1.2"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bytes@3.1.2"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-bytes",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bytes",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bytes": "3.1.2"
      }
    },
    "node_modules/bytes": {
      "version": "3.1.2",
      "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
      "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8"
      }
    }
  }
}
package.json
{
  "name": "sample-bytes",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of bytes string formatting and byte parsing",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "bytes": "3.1.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/bytes@3.1.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bytes@3.1.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const bytes = require('bytes');

/**
 * Format a byte count into a human-readable string.
 * @param {number} value - The number of bytes to format.
 * @param {object} [options] - Formatting options.
 * @returns {string|null} Formatted byte string or null if invalid.
 */
function formatBytes(value, options) {
  return bytes.format(value, options);
}

/**
 * Parse a human-readable byte string into a numeric byte count.
 * @param {string|number} value - The byte string or number to parse.
 * @returns {number|null} Byte count in integer, or null if invalid.
 */
function parseBytes(value) {
  return bytes.parse(value);
}

module.exports = {
  bytes,
  formatBytes,
  parseBytes
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { bytes, formatBytes, parseBytes } = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof bytes, 'function', 'bytes should be exported as a function');
assert.strictEqual(typeof bytes.format, 'function', 'bytes.format should be a function');
assert.strictEqual(typeof bytes.parse, 'function', 'bytes.parse should be a function');
assert.strictEqual(typeof formatBytes, 'function', 'formatBytes helper should be a function');
assert.strictEqual(typeof parseBytes, 'function', 'parseBytes helper should be a function');

// 2. Format byte numbers to human-readable strings
assert.strictEqual(formatBytes(0), '0B', 'formatBytes(0) should return 0B');
assert.strictEqual(formatBytes(1024), '1KB', 'formatBytes(1024) should return 1KB');
assert.strictEqual(formatBytes(1024 * 1024), '1MB', 'formatBytes(1048576) should return 1MB');
assert.strictEqual(formatBytes(1024 * 1024 * 1024), '1GB', 'formatBytes(1GB in bytes) should return 1GB');

// 3. Formatting with options (decimalPlaces, unitSeparator, thousandsSeparator, fixedDecimals)
assert.strictEqual(
  formatBytes(1024 * 1.5, { decimalPlaces: 1 }),
  '1.5KB',
  'formatBytes should respect decimalPlaces'
);
assert.strictEqual(
  formatBytes(1024, { unitSeparator: ' ' }),
  '1 KB',
  'formatBytes should respect unitSeparator'
);
assert.strictEqual(
  formatBytes(1000, { thousandsSeparator: ',' }),
  '1,000B',
  'formatBytes should respect thousandsSeparator'
);
assert.strictEqual(
  formatBytes(1024, { fixedDecimals: true, decimalPlaces: 2 }),
  '1.00KB',
  'formatBytes should respect fixedDecimals'
);

// 4. Parse human-readable byte strings to numbers
assert.strictEqual(parseBytes('1KB'), 1024, 'parseBytes("1KB") should equal 1024');
assert.strictEqual(parseBytes('1.5MB'), 1572864, 'parseBytes("1.5MB") should equal 1572864');
assert.strictEqual(parseBytes('1GB'), 1073741824, 'parseBytes("1GB") should equal 1073741824');
assert.strictEqual(parseBytes('1 TB'), 1099511627776, 'parseBytes("1 TB") should equal 1099511627776');
assert.strictEqual(parseBytes('1 PB'), 1125899906842624, 'parseBytes("1 PB") should equal 1125899906842624');

// 5. Parse edge cases and invalid inputs
assert.strictEqual(parseBytes(1024), 1024, 'parseBytes with number should return the number');
assert.strictEqual(parseBytes('invalid'), null, 'parseBytes with invalid string should return null');
assert.strictEqual(parseBytes(null), null, 'parseBytes with null should return null');

// 6. Direct wrapper function call
assert.strictEqual(bytes('1KB'), 1024, 'bytes("1KB") should parse string');
assert.strictEqual(bytes(1024), '1KB', 'bytes(1024) should format number');

console.log('Contract tests passed successfully.');

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

аноним