CodeSampleX

Ejemplo

base64-js 1.5.1: byteLength

Muestra verificada para npm base64-js 1.5.1: byteLength. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:48dc3ef5ac007eb7cbe7fe38b20b5391bdada2e6816cbdbadf836b568cd800bd

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-26

Caso

HOW
Objetivo
verify byteLength in pkg:npm/base64-js@1.5.1
Paquetes
Símbolos
  • byteLength
Creado
2026-08-26T11:22:39Z

Contrato

  1. byteLength calculates correct decoded byte size for unpadded and padded base64 strings
  2. byteLength matches the exact length of toByteArray decoded Uint8Array
  3. byteLength handles empty base64 string returning zero length
  4. byteLength throws Error when base64 string length is not a multiple of 4
  5. byteLength accurately computes byte lengths for multi-chunk base64 payloads

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 byteLength 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:
  - byteLength

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:82a99b36f08b791e868c44c741013385b498e5e95ff13dda11b7a18f2a496871","contract":["byteLength calculates correct decoded byte size for unpadded and padded base64 strings","byteLength matches the exact length of toByteArray decoded Uint8Array","byteLength handles empty base64 string returning zero length","byteLength throws Error when base64 string length is not a multiple of 4","byteLength accurately computes byte lengths for multi-chunk base64 payloads"],"goal":"verify byteLength in pkg:npm/base64-js@1.5.1","kind":"HOW","packages":["pkg:npm/base64-js@1.5.1"],"schemaVersion":1,"symbols":["byteLength"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/base64-js@1.5.1"],"schemaVersion":1,"subject":"pkg:npm/base64-js@1.5.1","symbols":["byteLength"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "base64-js-byte-length-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "base64-js-byte-length-sample",
      "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": "base64-js-byte-length-sample",
  "version": "1.0.0",
  "description": "verify byteLength in pkg:npm/base64-js@1.5.1",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "base64-js": "1.5.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify byteLength in pkg:npm/base64-js@1.5.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/base64-js@1.5.1"
  ],
  "symbols": [
    "byteLength"
  ]
}
src/index.mjs
import base64 from 'base64-js';

const { byteLength, toByteArray, fromByteArray } = base64;

/**
 * Calculates the byte length of a base64 encoded string without decoding.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {number} Decoded length in bytes.
 */
export function getDecodedByteLength(b64) {
  return byteLength(b64);
}

/**
 * Validates if the base64 string length is valid (multiple of 4) and returns its decoded length.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {{ valid: boolean, length?: number, error?: string }}
 */
export function validateAndCalculateLength(b64) {
  try {
    const length = byteLength(b64);
    return { valid: true, length };
  } catch (err) {
    return { valid: false, error: err.message };
  }
}

/**
 * Verifies that byteLength matches the actual length of decoded Uint8Array from toByteArray.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {boolean} True if byteLength equals toByteArray(b64).length.
 */
export function matchesDecodedBufferLength(b64) {
  const calculatedLen = byteLength(b64);
  const decoded = toByteArray(b64);
  return calculatedLen === decoded.length;
}

/**
 * Allocates a Uint8Array with the exact byte size determined by byteLength and decodes into it.
 *
 * @param {string} b64 - Base64 encoded string.
 * @returns {Uint8Array} Decoded byte array.
 */
export function allocateAndDecode(b64) {
  const length = byteLength(b64);
  const buffer = new Uint8Array(length);
  const decoded = toByteArray(b64);
  buffer.set(decoded);
  return buffer;
}

/**
 * Calculates decoded byte lengths for a batch of base64 strings.
 *
 * @param {string[]} b64List - Array of base64 strings.
 * @returns {number[]} Array of calculated byte lengths.
 */
export function batchByteLengths(b64List) {
  return b64List.map((str) => byteLength(str));
}
test/contract.mjs
import assert from 'node:assert/strict';
import base64 from 'base64-js';
import {
  getDecodedByteLength,
  validateAndCalculateLength,
  matchesDecodedBufferLength,
  allocateAndDecode,
  batchByteLengths,
} from '../src/index.mjs';

const { byteLength, toByteArray, fromByteArray } = base64;

// Contract 1: byteLength calculates correct decoded byte size for unpadded and padded base64 strings
{
  // 'f' -> 'Zg==' (1 byte, 2 padding chars)
  assert.strictEqual(getDecodedByteLength('Zg=='), 1);
  assert.strictEqual(byteLength('Zg=='), 1);

  // 'fo' -> 'Zm8=' (2 bytes, 1 padding char)
  assert.strictEqual(getDecodedByteLength('Zm8='), 2);
  assert.strictEqual(byteLength('Zm8='), 2);

  // 'foo' -> 'Zm9v' (3 bytes, 0 padding chars)
  assert.strictEqual(getDecodedByteLength('Zm9v'), 3);
  assert.strictEqual(byteLength('Zm9v'), 3);

  // 'foobar' -> 'Zm9vYmFy' (6 bytes, 0 padding chars)
  assert.strictEqual(getDecodedByteLength('Zm9vYmFy'), 6);
  assert.strictEqual(byteLength('Zm9vYmFy'), 6);
}

// Contract 2: byteLength matches the exact length of toByteArray decoded Uint8Array
{
  const testStrings = [
    'Zg==',
    'Zm8=',
    'Zm9v',
    'Zm9vYmFy',
    'SGVsbG8gV29ybGQh', // "Hello World!" (12 bytes)
    'QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=', // A-Z (26 bytes)
  ];

  for (const str of testStrings) {
    assert.strictEqual(matchesDecodedBufferLength(str), true);
    const decoded = allocateAndDecode(str);
    assert.strictEqual(decoded.length, byteLength(str));
    assert.deepStrictEqual(decoded, toByteArray(str));
  }
}

// Contract 3: byteLength handles empty base64 string returning zero length
{
  assert.strictEqual(byteLength(''), 0);
  assert.strictEqual(getDecodedByteLength(''), 0);
  const result = validateAndCalculateLength('');
  assert.strictEqual(result.valid, true);
  assert.strictEqual(result.length, 0);
}

// Contract 4: byteLength throws Error when base64 string length is not a multiple of 4
{
  assert.throws(
    () => byteLength('abc'),
    {
      name: 'Error',
      message: 'Invalid string. Length must be a multiple of 4',
    }
  );

  const invalidResult = validateAndCalculateLength('abcde');
  assert.strictEqual(invalidResult.valid, false);
  assert.strictEqual(invalidResult.error, 'Invalid string. Length must be a multiple of 4');
}

// Contract 5: byteLength accurately computes byte lengths for multi-chunk base64 payloads
{
  const lengths = [10, 50, 100, 256, 1000, 5000];
  const b64List = [];

  for (const len of lengths) {
    const rawBytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      rawBytes[i] = (i * 31 + 7) % 256;
    }
    const b64 = fromByteArray(rawBytes);
    b64List.push(b64);
  }

  const calculated = batchByteLengths(b64List);
  assert.deepStrictEqual(calculated, lengths);
}

console.log('All contract tests passed successfully.');

Seeder de origen

anónimo