CodeSampleX

Ejemplo

bare-buffer 3.7.0: Buffer.prototype.toString

Muestra verificada para npm bare-buffer 3.7.0: Buffer.prototype.toString. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:86de404fa7c11070be1c91f5e3d1a6e99a3fc5be6e3789fd4d06c32c8d66bc57

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 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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-27

Caso

HOW
Objetivo
verify Buffer.prototype.toString in pkg:npm/bare-buffer@3.7.0
Paquetes
Símbolos
  • Buffer.prototype.toString
Entorno
node 22.23.2
Creado
2026-08-27T05:42:10Z

Contrato

  1. Buffer.prototype.toString decodes buffer to UTF-8 string by default when called without arguments
  2. Buffer.prototype.toString encodes buffer to hex, base64, and base64url string formats accurately
  3. Buffer.prototype.toString supports ascii, latin1, binary, and utf16le string encodings
  4. Buffer.prototype.toString slices buffer range with start and end offsets clamping negative or out-of-bounds indices
  5. Buffer.prototype.toString returns empty string when start offset is beyond buffer length or end is less than start
  6. Buffer.prototype.toString returns empty string for zero-length buffer across all encodings
  7. Buffer.prototype.toString throws Error when an unknown encoding format is specified

Archivos

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 Buffer.prototype.toString in pkg:npm/bare-buffer@3.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-buffer@3.7.0
Demonstrate these symbols/APIs:
  - Buffer.prototype.toString

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:3fdee1c7f3db10dadeb4c33c1d59cc9e2aed55e3df1b68c14a00c784a9effd69","contract":["Buffer.prototype.toString decodes buffer to UTF-8 string by default when called without arguments","Buffer.prototype.toString encodes buffer to hex, base64, and base64url string formats accurately","Buffer.prototype.toString supports ascii, latin1, binary, and utf16le string encodings","Buffer.prototype.toString slices buffer range with start and end offsets clamping negative or out-of-bounds indices","Buffer.prototype.toString returns empty string when start offset is beyond buffer length or end is less than start","Buffer.prototype.toString returns empty string for zero-length buffer across all encodings","Buffer.prototype.toString throws Error when an unknown encoding format is specified"],"goal":"verify Buffer.prototype.toString in pkg:npm/bare-buffer@3.7.0","kind":"HOW","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"symbols":["Buffer.prototype.toString"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bare-buffer@3.7.0"],"schemaVersion":1,"subject":"pkg:npm/bare-buffer@3.7.0","symbols":["Buffer.prototype.toString"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module';
import path from 'node:path';

const require = createRequire(import.meta.url);

if (typeof Bare === 'undefined') {
  const nodeBuffer = globalThis.Buffer;
  const mockBinding = {
    constants: {
      MAX_LENGTH: 2147483647,
      MAX_STRING_LENGTH: 1073741799
    },
    alloc(size) {
      return new ArrayBuffer(size);
    },
    allocUnsafe(size) {
      return new ArrayBuffer(size);
    },
    compare(bufA, offA, lenA, bufB, offB, lenB) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.compare(b);
    },
    toStringHex(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('hex');
    },
    writeHex(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'hex');
    },
    toStringBase64(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64');
    },
    writeBase64(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64');
    },
    toStringBase64URL(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('base64url');
    },
    writeBase64URL(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'base64url');
    },
    toStringUTF8(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf8');
    },
    writeUTF8(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf8');
    },
    validateUTF8(buf, offset, len) {
      return nodeBuffer.isUtf8 ? nodeBuffer.isUtf8(nodeBuffer.from(buf, offset, len)) : true;
    },
    byteLengthUTF8(string) {
      return nodeBuffer.byteLength(string, 'utf8');
    },
    toStringUTF16LE(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('utf16le');
    },
    writeUTF16LE(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'utf16le');
    },
    toStringLatin1(buf, offset, len) {
      return nodeBuffer.from(buf, offset, len).toString('latin1');
    },
    writeLatin1(buf, offset, len, string) {
      return nodeBuffer.from(buf, offset, len).write(string, 0, len, 'latin1');
    },
    validateAscii(buf, offset, len) {
      const bytes = new Uint8Array(buf, offset, len);
      for (let i = 0; i < bytes.length; i++) {
        if (bytes[i] > 0x7f) return false;
      }
      return true;
    },
    indexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.indexOf(b, byteOffset);
    },
    lastIndexOf(bufA, offA, lenA, bufB, offB, lenB, byteOffset) {
      const a = nodeBuffer.from(bufA, offA, lenA);
      const b = nodeBuffer.from(bufB, offB, lenB);
      return a.lastIndexOf(b, byteOffset);
    },
    swap16(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap16();
    },
    swap32(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap32();
    },
    swap64(buf, offset, len) {
      nodeBuffer.from(buf, offset, len).swap64();
    }
  };

  const mainPath = require.resolve('bare-buffer');
  const bindingPath = path.join(path.dirname(mainPath), 'binding.js');
  require.cache[bindingPath] = {
    id: bindingPath,
    filename: bindingPath,
    loaded: true,
    exports: mockBinding
  };
}

const Buffer = require('bare-buffer');

export function bufferToString(buffer, encoding, start, end) {
  return buffer.toString(encoding, start, end);
}

export { Buffer };
export default Buffer;
package-lock.json
{
  "name": "sample-bare-buffer-tostring",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-buffer-tostring",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bare-buffer": "3.7.0"
      }
    },
    "node_modules/bare-buffer": {
      "version": "3.7.0",
      "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.0.tgz",
      "integrity": "sha512-/xRTbBuLis7sE3Izii0A0yOm+WqH1/gh12UVqkpIAOLZ4gWluyK0THbGB+UysKI8ZBjcZ+MaEs9Auxcyiz2yLA==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.20.0"
      }
    }
  }
}
package.json
{
  "name": "sample-bare-buffer-tostring",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Verify Buffer.prototype.toString in bare-buffer",
  "license": "MIT-0",
  "dependencies": {
    "bare-buffer": "3.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Buffer.prototype.toString in pkg:npm/bare-buffer@3.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-buffer@3.7.0"
  ],
  "symbols": [
    "Buffer.prototype.toString"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Buffer, { bufferToString } from '../index.js';

// 1. Buffer.prototype.toString decodes buffer to UTF-8 string by default when called without arguments
const utf8Buf = Buffer.from('Hello, CodeSampleX!');
assert.strictEqual(utf8Buf.toString(), 'Hello, CodeSampleX!', 'Default toString() must decode as UTF-8');
assert.strictEqual(utf8Buf.toString('utf8'), 'Hello, CodeSampleX!', 'Explicit utf8 toString must match default');
assert.strictEqual(utf8Buf.toString('utf-8'), 'Hello, CodeSampleX!', 'Case and hyphen in utf-8 must be handled');
assert.strictEqual(bufferToString(utf8Buf), 'Hello, CodeSampleX!', 'bufferToString helper should produce identical UTF-8 output');

const emojiBuf = Buffer.from('🚀 Rocket');
assert.strictEqual(emojiBuf.toString(), '🚀 Rocket', 'Multi-byte UTF-8 emoji string must decode correctly');

// 2. Buffer.prototype.toString encodes buffer to hex, base64, and base64url string formats accurately
const textBuf = Buffer.from('CodeSampleX');
assert.strictEqual(textBuf.toString('hex'), '436f646553616d706c6558', 'hex toString must match expected hexadecimal representation');
assert.strictEqual(textBuf.toString('HEX'), '436f646553616d706c6558', 'HEX uppercase encoding name must be supported');
assert.strictEqual(textBuf.toString('base64'), 'Q29kZVNhbXBsZVg=', 'base64 toString must produce valid standard base64');
assert.strictEqual(textBuf.toString('base64url'), 'Q29kZVNhbXBsZVg', 'base64url toString must produce unpadded URL-safe base64');

// 3. Buffer.prototype.toString supports ascii, latin1, binary, and utf16le string encodings
const asciiBuf = Buffer.from('Testing 123');
assert.strictEqual(asciiBuf.toString('ascii'), 'Testing 123', 'ascii toString must match ascii input');

const latin1Buf = Buffer.from('café', 'latin1');
assert.strictEqual(latin1Buf.toString('latin1'), 'café', 'latin1 toString must decode latin1 characters');
assert.strictEqual(latin1Buf.toString('binary'), 'café', 'binary toString alias must decode latin1 characters');

const utf16leBuf = Buffer.from('Test', 'utf16le');
assert.strictEqual(utf16leBuf.toString('utf16le'), 'Test', 'utf16le toString must decode UTF-16LE characters');
assert.strictEqual(utf16leBuf.toString('ucs2'), 'Test', 'ucs2 alias must decode UTF-16LE characters');

// 4. Buffer.prototype.toString slices buffer range with start and end offsets clamping negative or out-of-bounds indices
const numBuf = Buffer.from('0123456789');
assert.strictEqual(numBuf.toString('utf8', 2, 7), '23456', 'Slice with start=2 and end=7 must return "23456"');
assert.strictEqual(numBuf.toString('utf8', 5), '56789', 'Slice with start=5 and omitted end must read to buffer end');
assert.strictEqual(numBuf.toString('utf8', -4, 5), '01234', 'Negative start offset must be clamped to 0');
assert.strictEqual(numBuf.toString('utf8', 6, 50), '6789', 'End offset beyond buffer length must be clamped to byteLength');

// 5. Buffer.prototype.toString returns empty string when start offset is beyond buffer length or end is less than start
assert.strictEqual(numBuf.toString('utf8', 10, 15), '', 'start >= byteLength must return empty string');
assert.strictEqual(numBuf.toString('utf8', 20, 30), '', 'start > byteLength must return empty string');
assert.strictEqual(numBuf.toString('utf8', 6, 3), '', 'end <= start must return empty string');
assert.strictEqual(numBuf.toString('utf8', 4, 4), '', 'end === start must return empty string');

// 6. Buffer.prototype.toString returns empty string for zero-length buffer across all encodings
const emptyBuf = Buffer.alloc(0);
assert.strictEqual(emptyBuf.toString(), '', 'Empty buffer toString() must return empty string');
assert.strictEqual(emptyBuf.toString('hex'), '', 'Empty buffer hex toString must return empty string');
assert.strictEqual(emptyBuf.toString('base64'), '', 'Empty buffer base64 toString must return empty string');
assert.strictEqual(emptyBuf.toString('base64url'), '', 'Empty buffer base64url toString must return empty string');
assert.strictEqual(emptyBuf.toString('ascii'), '', 'Empty buffer ascii toString must return empty string');

// 7. Buffer.prototype.toString throws Error when an unknown encoding format is specified
assert.throws(
  () => utf8Buf.toString('unsupported-format'),
  (err) => {
    assert(err instanceof Error, 'Thrown value must be an Error instance');
    assert.strictEqual(err.message, "Unknown encoding 'unsupported-format'");
    return true;
  },
  'Unknown encoding must throw Error with descriptive message'
);

console.log('All Buffer.prototype.toString contract assertions passed successfully.');

Seeder de origen

anónimo