CodeSampleX

Пример

base64-js 1.5.1: toByteArray

Проверенный пример — npm base64-js 1.5.1: toByteArray. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: assert empty string decodes to…

sha256:384a73b9a8e8762538c0900b1f8d9a5eae78ca94bdd84e3712a262621ae0826a

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-05

Кейс

HOW
Цель
verify base64-js.toByteArray in pkg:npm/base64-js@1.5.1
Пакеты
Символы
  • base64-js.toByteArray
Окружение
node 22.23.2
Создан
2026-09-05T18:18:37Z

Контракт

  1. assert empty string decodes to empty Uint8Array
  2. assert single byte base64 string with double equals padding decodes to single byte
  3. assert two bytes base64 string with single equals padding decodes to two bytes
  4. assert three bytes base64 string without padding decodes to three bytes
  5. assert standard ASCII text base64 string decodes to matching UTF-8 byte array
  6. assert binary byte sequence with zero and max byte values decodes correctly
  7. assert url-safe base64 strings with minus and underscore characters decode correctly
  8. assert invalid base64 string with length not divisible by four throws an error
  9. assert round-trip decoding of byte buffer with fromByteArray preserves binary fidelity

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 base64-js.toByteArray in pkg:npm/base64-js@1.5.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/base64-js@1.5.1
Demonstrate these symbols/APIs:
  - base64-js.toByteArray
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:3e439724f41b64e5a13ab012a3fb8b45136f2582bcf9847ff0411ce5341ad789","constraints":{"executionContext":"node"},"contract":["assert empty string decodes to empty Uint8Array","assert single byte base64 string with double equals padding decodes to single byte","assert two bytes base64 string with single equals padding decodes to two bytes","assert three bytes base64 string without padding decodes to three bytes","assert standard ASCII text base64 string decodes to matching UTF-8 byte array","assert binary byte sequence with zero and max byte values decodes correctly","assert url-safe base64 strings with minus and underscore characters decode correctly","assert invalid base64 string with length not divisible by four throws an error","assert round-trip decoding of byte buffer with fromByteArray preserves binary fidelity"],"goal":"verify base64-js.toByteArray in pkg:npm/base64-js@1.5.1","kind":"HOW","packages":["pkg:npm/base64-js@1.5.1"],"schemaVersion":1,"symbols":["base64-js.toByteArray"]},"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/base64-js@1.5.1"],"schemaVersion":1,"subject":"pkg:npm/base64-js@1.5.1","symbols":["base64-js.toByteArray"],"verifierAdapter":"node-typescript@1"}
index.js
const { toByteArray, fromByteArray, byteLength } = require('base64-js');

function decodeBase64(base64Str) {
  return toByteArray(base64Str);
}

function decodeToUtf8(base64Str) {
  const bytes = toByteArray(base64Str);
  return new TextDecoder().decode(bytes);
}

function encodeBytes(bytes) {
  return fromByteArray(bytes);
}

function getByteLength(base64Str) {
  return byteLength(base64Str);
}

module.exports = {
  toByteArray,
  fromByteArray,
  byteLength,
  decodeBase64,
  decodeToUtf8,
  encodeBytes,
  getByteLength,
};
package-lock.json
{
  "name": "sample-base64-js",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-base64-js",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "base64-js": "1.5.1"
      }
    },
    "node_modules/base64-js": {
      "version": "1.5.1",
      "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
      "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/feross"
        },
        {
          "type": "patreon",
          "url": "https://www.patreon.com/feross"
        },
        {
          "type": "consulting",
          "url": "https://feross.org/support"
        }
      ],
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-base64-js",
  "version": "1.0.0",
  "description": "Minimal clean-room sample verifying toByteArray in base64-js",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "base64-js": "1.5.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify base64-js.toByteArray in pkg:npm/base64-js@1.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/base64-js@1.5.1"
  ],
  "symbols": [
    "base64-js.toByteArray"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert';
import { toByteArray, fromByteArray, byteLength } from 'base64-js';
import {
  decodeBase64,
  decodeToUtf8,
  encodeBytes,
  getByteLength,
} from '../index.js';

// 1. assert empty string decodes to empty Uint8Array
const emptyResult = decodeBase64('');
assert.ok(emptyResult instanceof Uint8Array, 'Empty string must return a Uint8Array');
assert.strictEqual(emptyResult.length, 0, 'Empty string must decode to 0 bytes');

// 2. assert single byte base64 string with double equals padding decodes to single byte
const singleByte = decodeBase64('SA==');
assert.ok(singleByte instanceof Uint8Array, 'Must return Uint8Array');
assert.strictEqual(singleByte.length, 1, 'Single byte base64 must decode to length 1');
assert.strictEqual(singleByte[0], 72, 'SA== must decode to ASCII 72 (H)');

// 3. assert two bytes base64 string with single equals padding decodes to two bytes
const twoBytes = decodeBase64('SGU=');
assert.strictEqual(twoBytes.length, 2, 'Two bytes base64 must decode to length 2');
assert.strictEqual(twoBytes[0], 72, 'First byte must match');
assert.strictEqual(twoBytes[1], 101, 'Second byte must match');

// 4. assert three bytes base64 string without padding decodes to three bytes
const threeBytes = decodeBase64('SGVs');
assert.strictEqual(threeBytes.length, 3, 'Three bytes base64 must decode to length 3');
assert.strictEqual(threeBytes[0], 72);
assert.strictEqual(threeBytes[1], 101);
assert.strictEqual(threeBytes[2], 108);

// 5. assert standard ASCII text base64 string decodes to matching UTF-8 byte array
const textDecoded = decodeToUtf8('SGVsbG8sIFdvcmxkIQ==');
assert.strictEqual(textDecoded, 'Hello, World!', 'Base64 string must decode to Hello, World!');

// 6. assert binary byte sequence with zero and max byte values decodes correctly
const binaryBytes = decodeBase64('AAEC/v8=');
assert.deepStrictEqual(
  Array.from(binaryBytes),
  [0x00, 0x01, 0x02, 0xFE, 0xFF],
  'Binary byte sequence with 0x00 and 0xFF must decode accurately'
);

// 7. assert url-safe base64 strings with minus and underscore characters decode correctly
const urlSafeBytes = decodeBase64('AAEC_v8=');
assert.deepStrictEqual(
  Array.from(urlSafeBytes),
  [0x00, 0x01, 0x02, 0xFE, 0xFF],
  'URL-safe base64 string with _ must decode identically'
);
const standardUrlMatch1 = decodeBase64('+w==');
const standardUrlMatch2 = decodeBase64('-w==');
assert.deepStrictEqual(
  Array.from(standardUrlMatch1),
  Array.from(standardUrlMatch2),
  'URL-safe - must decode identically to +'
);

// 8. assert invalid base64 string with length not divisible by four throws an error
assert.throws(
  () => toByteArray('abc'),
  /Invalid string\. Length must be a multiple of 4/,
  'toByteArray must reject strings with length not divisible by 4'
);
assert.throws(
  () => toByteArray('a'),
  /Invalid string\. Length must be a multiple of 4/,
  'toByteArray must reject strings with length 1'
);

// 9. assert round-trip decoding of byte buffer with fromByteArray preserves binary fidelity
const size = 512;
const originalBytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
  originalBytes[i] = (i * 7 + 13) & 0xff;
}
const encoded = encodeBytes(originalBytes);
const roundTripDecoded = decodeBase64(encoded);
assert.strictEqual(roundTripDecoded.length, size, 'Round-trip length must match');
assert.deepStrictEqual(
  Array.from(roundTripDecoded),
  Array.from(originalBytes),
  'Round-trip decoding must match original bytes exactly'
);

console.log('All toByteArray contract assertions passed.');

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

аноним