CodeSampleX

Ejemplo

get-stream 6.0.1: read readable stream to string with encoding and maxBuffer options using get-stream

Muestra verificada para npm get-stream 6.0.1: read readable stream to string with encoding and maxBuffer options using get-stream. El contrato se ejecutó en…

sha256:3f3b9c9629f127dcfec0f6e7c79ceab74501b3901af68bec92befc267284bf9c

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

Caso

HOW
Objetivo
read readable stream to string with encoding and maxBuffer options using get-stream
Paquetes
Símbolos
  • getStream
Creado
2026-08-27T12:31:55Z

Contrato

  1. getStream reads a readable stream and resolves to its complete string content
  2. getStream decodes stream chunks using the specified encoding option
  3. getStream resolves to an empty string when given an empty readable stream
  4. getStream rejects with MaxBufferError when stream content length exceeds maxBuffer option
  5. getStream rejects with the emitted error when the stream encounters an error
  6. getStream rejects with an error when called without a stream argument

Archivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: read readable stream to string with encoding and maxBuffer options using get-stream
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/get-stream@6.0.1
Demonstrate these symbols/APIs:
  - getStream

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:a35daad4a29f81ab9ad9ee7d48976af3e2094124b745dc400415fff4fd36f0a3","contract":["getStream reads a readable stream and resolves to its complete string content","getStream decodes stream chunks using the specified encoding option","getStream resolves to an empty string when given an empty readable stream","getStream rejects with MaxBufferError when stream content length exceeds maxBuffer option","getStream rejects with the emitted error when the stream encounters an error","getStream rejects with an error when called without a stream argument"],"goal":"read readable stream to string with encoding and maxBuffer options using get-stream","kind":"HOW","packages":["pkg:npm/get-stream@6.0.1"],"schemaVersion":1,"symbols":["getStream"]},"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/get-stream@6.0.1"],"schemaVersion":1,"subject":"pkg:npm/get-stream@6.0.1","symbols":["getStream"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-get-stream",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-get-stream",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "get-stream": "6.0.1"
      }
    },
    "node_modules/get-stream": {
      "version": "6.0.1",
      "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
      "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "sample-get-stream",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "get-stream": "6.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "read readable stream to string with encoding and maxBuffer options using get-stream",
  "kind": "HOW",
  "packages": [
    "pkg:npm/get-stream@6.0.1"
  ],
  "symbols": [
    "getStream"
  ]
}
src/index.js
const getStream = require('get-stream');

/**
 * Reads a readable stream and resolves to its string content.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {object} [options] - Optional options passed to get-stream.
 * @returns {Promise<string>} The stream content as a string.
 */
async function readStreamToString(stream, options) {
  return getStream(stream, options);
}

/**
 * Reads a stream using a specific character encoding.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {string} encoding - The character encoding (e.g., 'utf8', 'hex', 'base64').
 * @returns {Promise<string>} The decoded string.
 */
async function readStreamWithEncoding(stream, encoding) {
  return getStream(stream, { encoding });
}

/**
 * Reads a stream with a maximum buffer size limit.
 *
 * @param {import('node:stream').Readable} stream - The stream to read.
 * @param {number} maxBuffer - Maximum allowed character length.
 * @returns {Promise<string>} The stream content as a string.
 */
async function readStreamWithLimit(stream, maxBuffer) {
  return getStream(stream, { maxBuffer });
}

module.exports = {
  getStream,
  readStreamToString,
  readStreamWithEncoding,
  readStreamWithLimit,
  MaxBufferError: getStream.MaxBufferError
};
test/contract.mjs
import assert from 'node:assert/strict';
import { Readable } from 'node:stream';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const getStream = require('get-stream');
const {
  readStreamToString,
  readStreamWithEncoding,
  readStreamWithLimit,
  MaxBufferError
} = require('../src/index.js');

async function testReadStreamToString() {
  const stream = Readable.from(['hello ', 'world', '!']);
  const result = await getStream(stream);
  assert.strictEqual(typeof result, 'string');
  assert.strictEqual(result, 'hello world!');

  const bufStream = Readable.from([Buffer.from('stream '), Buffer.from('data')]);
  const bufResult = await readStreamToString(bufStream);
  assert.strictEqual(bufResult, 'stream data');
}

async function testReadStreamWithEncoding() {
  const data = 'Hello, CodeSampleX!';
  const hexExpected = Buffer.from(data).toString('hex');
  const base64Expected = Buffer.from(data).toString('base64');

  const streamHex = Readable.from([Buffer.from(data)]);
  const hexResult = await getStream(streamHex, { encoding: 'hex' });
  assert.strictEqual(hexResult, hexExpected);

  const streamBase64 = Readable.from([Buffer.from(data)]);
  const base64Result = await readStreamWithEncoding(streamBase64, 'base64');
  assert.strictEqual(base64Result, base64Expected);
}

async function testEmptyStream() {
  const stream = Readable.from([]);
  const result = await getStream(stream);
  assert.strictEqual(typeof result, 'string');
  assert.strictEqual(result, '');

  const helperStream = Readable.from([]);
  const helperResult = await readStreamToString(helperStream);
  assert.strictEqual(helperResult, '');
}

async function testMaxBufferLimit() {
  const stream = Readable.from(['long content exceeding limit']);
  await assert.rejects(
    async () => {
      await getStream(stream, { maxBuffer: 5 });
    },
    (err) => {
      assert.ok(err instanceof MaxBufferError || err.name === 'MaxBufferError', 'should be MaxBufferError');
      assert.strictEqual(err.message, 'maxBuffer exceeded');
      return true;
    }
  );

  const helperStream = Readable.from(['another long content']);
  await assert.rejects(
    async () => {
      await readStreamWithLimit(helperStream, 4);
    },
    (err) => {
      assert.ok(err instanceof MaxBufferError || err.name === 'MaxBufferError', 'should be MaxBufferError');
      assert.strictEqual(err.message, 'maxBuffer exceeded');
      return true;
    }
  );
}

async function testStreamError() {
  const customError = new Error('simulated stream error');
  const stream = new Readable({
    read() {
      this.destroy(customError);
    }
  });

  await assert.rejects(
    async () => {
      await getStream(stream);
    },
    (err) => {
      assert.strictEqual(err, customError);
      return true;
    }
  );
}

async function testMissingStream() {
  await assert.rejects(
    async () => {
      await getStream(null);
    },
    {
      message: 'Expected a stream'
    }
  );

  await assert.rejects(
    async () => {
      await readStreamToString(undefined);
    },
    {
      message: 'Expected a stream'
    }
  );
}

async function runAll() {
  await testReadStreamToString();
  await testReadStreamWithEncoding();
  await testEmptyStream();
  await testMaxBufferLimit();
  await testStreamError();
  await testMissingStream();
  console.log('All getStream contract tests passed successfully.');
}

await runAll();

Seeder de origen

anónimo