CodeSampleX

Ejemplo

minipass-flush 1.0.5

Muestra verificada para npm minipass-flush 1.0.5. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: Flush constructor throws TypeError…

sha256:98620bce00a632b7abfb91560a220ad934776371047e1c10e33bdea64ffe85eb

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 debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-19

Caso

HOW
Objetivo
verify pkg:npm/minipass-flush@1.0.5
Paquetes
Entorno
node 22.23.2
Creado
2026-09-18T19:47:45Z

Contrato

  1. Flush constructor throws TypeError when no flush function is provided
  2. Flush accepts a function argument or options object with flush method
  3. Flush can be subclassed with a flush method on the prototype
  4. Flush delays end event until callback-based flush function completes
  5. Flush delays end event until promise-returning async flush resolves
  6. Flush emits error if callback-based flush returns an error
  7. Flush emits error if promise-returning flush rejects
  8. Flush passes data through while holding end event until flush completes

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: verify pkg:npm/minipass-flush@1.0.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/minipass-flush@1.0.5

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:9e24103579c41b69e2302cb0272d0136496cbc771ec2a22edd447442c836c3b9","constraints":{"executionContext":"node"},"contract":["Flush constructor throws TypeError when no flush function is provided","Flush accepts a function argument or options object with flush method","Flush can be subclassed with a flush method on the prototype","Flush delays end event until callback-based flush function completes","Flush delays end event until promise-returning async flush resolves","Flush emits error if callback-based flush returns an error","Flush emits error if promise-returning flush rejects","Flush passes data through while holding end event until flush completes"],"goal":"verify pkg:npm/minipass-flush@1.0.5","kind":"HOW","packages":["pkg:npm/minipass-flush@1.0.5"],"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/minipass-flush@1.0.5"],"schemaVersion":1,"subject":"pkg:npm/minipass-flush@1.0.5","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-minipass-flush",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-minipass-flush",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "minipass-flush": "1.0.5"
      }
    },
    "node_modules/minipass": {
      "version": "3.3.6",
      "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
      "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
      "license": "ISC",
      "dependencies": {
        "yallist": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/minipass-flush": {
      "version": "1.0.5",
      "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.5.tgz",
      "integrity": "sha512-JmQSYYpPUqX5Jyn1mXaRwOda1uQ8HP5KAT/oDSLCzt1BYRhQU0/hDtsB1ufZfEEzMZ9aAVmsBw8+FWsIXlClWw==",
      "license": "ISC",
      "dependencies": {
        "minipass": "^3.0.0"
      },
      "engines": {
        "node": ">= 8"
      }
    },
    "node_modules/yallist": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
      "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-minipass-flush",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for minipass-flush@1.0.5",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "minipass-flush": "1.0.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/minipass-flush@1.0.5",
  "kind": "HOW",
  "packages": [
    "pkg:npm/minipass-flush@1.0.5"
  ]
}
src/index.js
'use strict';

const Flush = require('minipass-flush');

/**
 * Creates a new Flush stream instance with the provided flush function and options.
 *
 * @param {Function} flushFn - The flush handler function (callback-style or async).
 * @param {object} [options={}] - Additional Minipass stream options.
 * @returns {Flush} A Minipass-flush stream instance.
 */
function createFlushStream(flushFn, options = {}) {
  return new Flush({
    ...options,
    flush: flushFn
  });
}

/**
 * A Flush subclass that executes an asynchronous cleanup or notification before end.
 */
class CleanupFlushStream extends Flush {
  constructor(cleanupFn, options = {}) {
    super(options);
    this.cleanupFn = cleanupFn;
  }

  flush(cb) {
    if (typeof this.cleanupFn === 'function') {
      const res = this.cleanupFn();
      if (res && typeof res.then === 'function') {
        return res.then(() => cb(), (err) => cb(err));
      }
    }
    cb();
  }
}

/**
 * Consumes a Minipass stream and collects all emitted chunks into an array.
 *
 * @param {Flush} stream - The stream to consume.
 * @returns {Promise<any[]>} Resolves with array of collected chunks.
 */
function collectChunks(stream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    stream.on('data', (chunk) => chunks.push(chunk));
    stream.on('end', () => resolve(chunks));
    stream.on('error', (err) => reject(err));
  });
}

module.exports = {
  Flush,
  createFlushStream,
  CleanupFlushStream,
  collectChunks
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { Flush, createFlushStream, CleanupFlushStream, collectChunks } = require('../src/index.js');

async function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function testAll() {
  // 1. Export verification and instance checks
  assert.equal(typeof Flush, 'function', 'Flush must be a constructor function');
  assert.equal(typeof createFlushStream, 'function', 'createFlushStream helper must be a function');
  assert.equal(typeof CleanupFlushStream, 'function', 'CleanupFlushStream class must be a function');
  assert.equal(typeof collectChunks, 'function', 'collectChunks helper must be a function');

  // 2. Constructor argument validation
  assert.throws(
    () => new Flush(),
    {
      name: 'TypeError',
      message: 'must provide flush function in options'
    },
    'Flush should throw TypeError when called without arguments'
  );

  assert.throws(
    () => new Flush({}),
    {
      name: 'TypeError',
      message: 'must provide flush function in options'
    },
    'Flush should throw TypeError when called with empty options'
  );

  assert.throws(
    () => new Flush({ flush: 'not-a-function' }),
    {
      name: 'TypeError',
      message: 'must provide flush function in options'
    },
    'Flush should throw TypeError when flush option is not a function'
  );

  // 3. Accepts function directly or options object
  const fnStream = new Flush((cb) => cb());
  assert.ok(fnStream instanceof Flush, 'instance created with function argument');

  const optStream = new Flush({ flush: (cb) => cb(), encoding: 'utf8' });
  assert.ok(optStream instanceof Flush, 'instance created with options object');

  // 4. Subclass with prototype flush method
  let subclassFlushed = false;
  const subclassStream = new CleanupFlushStream(() => {
    subclassFlushed = true;
  }, { encoding: 'utf8' });
  assert.ok(subclassStream instanceof Flush, 'subclass instance is an instance of Flush');
  const subclassPromise = collectChunks(subclassStream);
  subclassStream.write('subclass-data');
  subclassStream.end();
  const subclassChunks = await subclassPromise;
  assert.equal(subclassFlushed, true, 'subclass flush hook executed');
  assert.deepEqual(subclassChunks, ['subclass-data'], 'data passed through');

  // 5. Callback-based flush execution delays end
  let callbackFlushed = false;
  let endEmitted = false;
  const cbStream = createFlushStream((cb) => {
    assert.equal(endEmitted, false, 'end must not be emitted before flush completes');
    setTimeout(() => {
      callbackFlushed = true;
      cb();
    }, 25);
  }, { encoding: 'utf8' });

  cbStream.on('end', () => {
    assert.equal(callbackFlushed, true, 'end event must only emit after callbackFlushed is true');
    endEmitted = true;
  });

  const cbCollect = collectChunks(cbStream);
  cbStream.write('initial-data');
  cbStream.end();

  const cbResults = await cbCollect;
  assert.equal(callbackFlushed, true, 'callback-based flush must be executed');
  assert.equal(endEmitted, true, 'end event must be emitted');
  assert.deepEqual(cbResults, ['initial-data'], 'stream data correctly passed through');

  // 6. Promise-returning async flush delays end
  let asyncFlushed = false;
  let asyncEndEmitted = false;
  const asyncStream = createFlushStream(async () => {
    assert.equal(asyncEndEmitted, false, 'end must not be emitted before async flush completes');
    await delay(25);
    asyncFlushed = true;
  }, { encoding: 'utf8' });

  asyncStream.on('end', () => {
    assert.equal(asyncFlushed, true, 'end event must only emit after asyncFlushed is true');
    asyncEndEmitted = true;
  });

  const asyncCollect = collectChunks(asyncStream);
  asyncStream.write('async-data');
  asyncStream.end();

  const asyncResults = await asyncCollect;
  assert.equal(asyncFlushed, true, 'async flush should complete');
  assert.equal(asyncEndEmitted, true, 'async stream end emitted');
  assert.deepEqual(asyncResults, ['async-data'], 'stream data collected');

  // 7. Error propagation from callback-based flush
  const errStream = createFlushStream((cb) => {
    cb(new Error('callback flush failure'));
  });

  let errStreamEndEmitted = false;
  errStream.on('end', () => {
    errStreamEndEmitted = true;
  });

  await assert.rejects(
    async () => {
      const errCollect = collectChunks(errStream);
      errStream.write('data');
      errStream.end();
      await errCollect;
    },
    {
      name: 'Error',
      message: 'callback flush failure'
    },
    'callback error should be emitted on error event'
  );
  assert.equal(errStreamEndEmitted, false, 'end event must NOT be emitted when synchronous flush fails');

  // 8. Error propagation from rejected async flush
  const rejectedStream = createFlushStream(async () => {
    await delay(10);
    throw new Error('promise flush failure');
  });

  let errorEventEmitted = false;
  rejectedStream.on('error', (err) => {
    assert.equal(err.message, 'promise flush failure');
    errorEventEmitted = true;
  });

  await assert.rejects(
    async () => {
      const rejCollect = collectChunks(rejectedStream);
      rejectedStream.write('data');
      rejectedStream.end();
      await rejCollect;
    },
    {
      name: 'Error',
      message: 'promise flush failure'
    },
    'promise rejection should be emitted on error event'
  );
  assert.equal(errorEventEmitted, true, 'error event must be emitted when async flush rejects');

  // 9. Data pass-through with multiple writes and flush
  const multiChunks = [];
  const passStream = createFlushStream(async () => {
    await delay(15);
  }, { encoding: 'utf8' });

  passStream.on('data', (c) => multiChunks.push(c));
  passStream.write('chunk-1');
  passStream.write('chunk-2');
  passStream.write('chunk-3');
  passStream.end();

  await new Promise((resolve) => passStream.on('end', resolve));
  assert.deepEqual(multiChunks, ['chunk-1', 'chunk-2', 'chunk-3'], 'all chunks streamed through');

  console.log('All minipass-flush contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

Seeder de origen

anónimo