CodeSampleX

샘플

thread-stream 4.2.0: ThreadStream, ThreadStream.prototype.end, ThreadStream.prototype.flushSync

검증된 샘플 — npm thread-stream 4.2.0: ThreadStream, ThreadStream.prototype.end, ThreadStream.prototype.flushSync. node 22 · linux debian/x64 · docker에서 contract를…

sha256:178a6277c75742b8d3166de3780a33fe5928cc75dc6f3a974e5995ea00c88e7a

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-19

케이스

HOW
목표
verify pkg:npm/thread-stream@4.2.0
패키지
심벌
  • ThreadStream
  • ThreadStream.prototype.end
  • ThreadStream.prototype.flushSync
  • ThreadStream.prototype.write
환경
node 22.23.2
생성일
2026-09-18T14:20:53Z

컨트랙트

  1. ThreadStream constructor creates an active stream instance to a worker thread
  2. ThreadStream.prototype.write writes data to the worker stream buffer
  3. ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination
  4. ThreadStream.prototype.end closes the stream and flushes remaining data before exit
  5. ThreadStream supports synchronous streaming mode with sync option enabled
  6. ThreadStream.prototype.write emits an error event when called after end

파일

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

소스 아티팩트 내려받기 (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 pkg:npm/thread-stream@4.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/thread-stream@4.2.0
Demonstrate these symbols/APIs:
  - ThreadStream
  - ThreadStream.prototype.end
  - ThreadStream.prototype.flushSync
  - ThreadStream.prototype.write

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:b156cce445fd570f467968202c5990b074e033bbe48d01cb7015aebc37909f8a","contract":["ThreadStream constructor creates an active stream instance to a worker thread","ThreadStream.prototype.write writes data to the worker stream buffer","ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination","ThreadStream.prototype.end closes the stream and flushes remaining data before exit","ThreadStream supports synchronous streaming mode with sync option enabled","ThreadStream.prototype.write emits an error event when called after end"],"goal":"verify pkg:npm/thread-stream@4.2.0","kind":"HOW","packages":["pkg:npm/thread-stream@4.2.0"],"schemaVersion":1,"symbols":["ThreadStream","ThreadStream.prototype.end","ThreadStream.prototype.flushSync","ThreadStream.prototype.write"]},"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/thread-stream@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/thread-stream@4.2.0","symbols":["ThreadStream","ThreadStream.prototype.end","ThreadStream.prototype.flushSync","ThreadStream.prototype.write"],"verifierAdapter":"node-typescript@1"}
index.js
const path = require('node:path');
const ThreadStream = require('thread-stream');

/**
 * Creates a ThreadStream configured to stream data to a worker file destination.
 * @param {string} dest Destination file path.
 * @param {object} [options={}] Additional ThreadStream options.
 * @returns {ThreadStream}
 */
function createWorkerStream(dest, options = {}) {
  const workerFile = path.join(__dirname, 'worker.js');
  return new ThreadStream({
    filename: workerFile,
    workerData: { dest },
    sync: false,
    ...options
  });
}

module.exports = {
  createWorkerStream,
  ThreadStream
};
package-lock.json
{
  "name": "sample-thread-stream",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-thread-stream",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "thread-stream": "4.2.0"
      }
    },
    "node_modules/real-require": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
      "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
      "license": "MIT"
    },
    "node_modules/thread-stream": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
      "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",
      "license": "MIT",
      "dependencies": {
        "real-require": "^1.0.0"
      },
      "engines": {
        "node": ">=20"
      }
    }
  }
}
package.json
{
  "name": "sample-thread-stream",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pkg:npm/thread-stream@4.2.0 functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "thread-stream": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/thread-stream@4.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/thread-stream@4.2.0"
  ],
  "symbols": [
    "ThreadStream",
    "ThreadStream.prototype.end",
    "ThreadStream.prototype.flushSync",
    "ThreadStream.prototype.write"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import pkg from '../index.js';

const { ThreadStream, createWorkerStream } = pkg;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workerPath = path.join(__dirname, '../worker.js');
const tmpDir = path.join(os.tmpdir(), `thread-stream-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(tmpDir, { recursive: true });

try {
  // 1. ThreadStream constructor creates an active stream instance to a worker thread
  {
    const dest = path.join(tmpDir, 'test-constructor.log');
    const stream = new ThreadStream({
      filename: workerPath,
      workerData: { dest }
    });
    assert.ok(stream instanceof ThreadStream);
    assert.strictEqual(typeof stream.write, 'function');
    assert.strictEqual(typeof stream.flushSync, 'function');
    assert.strictEqual(typeof stream.end, 'function');
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
  }

  // 2. ThreadStream.prototype.write writes data to the worker stream buffer
  {
    const dest = path.join(tmpDir, 'test-write.log');
    const stream = createWorkerStream(dest);
    const accepted1 = stream.write('message line 1\n');
    const accepted2 = stream.write('message line 2\n');
    assert.strictEqual(accepted1, true);
    assert.strictEqual(accepted2, true);
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'message line 1\nmessage line 2\n');
  }

  // 3. ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination
  {
    const dest = path.join(tmpDir, 'test-flush.log');
    const stream = createWorkerStream(dest);
    stream.write('chunk-alpha\n');
    stream.flushSync();
    stream.write('chunk-beta\n');
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'chunk-alpha\nchunk-beta\n');
  }

  // 4. ThreadStream.prototype.end closes the stream and flushes remaining data before exit
  {
    const dest = path.join(tmpDir, 'test-end.log');
    const stream = createWorkerStream(dest);
    stream.write('final-line\n');
    stream.end();
    let finishFired = false;
    stream.on('finish', () => {
      finishFired = true;
    });
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    assert.strictEqual(finishFired, true);
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'final-line\n');
  }

  // 5. ThreadStream supports synchronous streaming mode with sync option enabled
  {
    const dest = path.join(tmpDir, 'test-sync-mode.log');
    const stream = new ThreadStream({
      filename: workerPath,
      workerData: { dest },
      sync: true
    });
    const writeResult = stream.write('sync-entry\n');
    assert.strictEqual(writeResult, true);
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'sync-entry\n');
  }

  // 6. ThreadStream.prototype.write emits an error event when called after end
  {
    const dest = path.join(tmpDir, 'test-write-after-end.log');
    const stream = createWorkerStream(dest);
    stream.write('before-end\n');
    stream.end();

    let errorReceived = false;
    stream.on('error', (err) => {
      if (err) errorReceived = true;
    });

    stream.write('after-end\n');
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    assert.strictEqual(errorReceived, true);
  }
} finally {
  fs.rmSync(tmpDir, { recursive: true, force: true });
}

console.log('Contract tests passed successfully.');
worker.js
const fs = require('node:fs');
const { once } = require('node:events');

/**
 * Worker thread destination entrypoint.
 * @param {object} opts Worker options containing destination file path.
 * @returns {Promise<fs.WriteStream>} Writable stream for worker thread data.
 */
module.exports = async function run(opts) {
  const stream = fs.createWriteStream(opts.dest);
  await once(stream, 'open');
  return stream;
};

오리진 시더

익명