CodeSampleX

샘플

eventsource-parser 3.1.0: EventSourceParserStream

검증된 샘플 — npm eventsource-parser 3.1.0: EventSourceParserStream. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: assert EventSourceParserStream…

sha256:c0110ad5b23cd3f2b34a0f232186bc37f76fbd806a6a6d70d0d415abc90ac37e

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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-17

케이스

HOW
목표
verify eventsource-parser.EventSourceParserStream in pkg:npm/eventsource-parser@3.1.0
패키지
심벌
  • eventsource-parser.EventSourceParserStream
생성일
2026-09-17T01:45:36Z

컨트랙트

  1. assert EventSourceParserStream transforms chunked string streams into EventSourceMessage objects
  2. assert EventSourceParserStream extracts event types and message ids from streamed events
  3. assert EventSourceParserStream triggers onRetry and onComment callbacks during streaming
  4. assert EventSourceParserStream emits ParseError to onError callback or terminates when configured
  5. assert EventSourceParserStream errors the stream when maxBufferSize is exceeded

파일

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

소스 아티팩트 내려받기 (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 eventsource-parser.EventSourceParserStream in pkg:npm/eventsource-parser@3.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/eventsource-parser@3.1.0
Demonstrate these symbols/APIs:
  - eventsource-parser.EventSourceParserStream

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:9956da406ed8e903f481f472534f0a2142c292931ee43e33333a395aa677995a","contract":["assert EventSourceParserStream transforms chunked string streams into EventSourceMessage objects","assert EventSourceParserStream extracts event types and message ids from streamed events","assert EventSourceParserStream triggers onRetry and onComment callbacks during streaming","assert EventSourceParserStream emits ParseError to onError callback or terminates when configured","assert EventSourceParserStream errors the stream when maxBufferSize is exceeded"],"goal":"verify eventsource-parser.EventSourceParserStream in pkg:npm/eventsource-parser@3.1.0","kind":"HOW","packages":["pkg:npm/eventsource-parser@3.1.0"],"schemaVersion":1,"symbols":["eventsource-parser.EventSourceParserStream"]},"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/eventsource-parser@3.1.0"],"schemaVersion":1,"subject":"pkg:npm/eventsource-parser@3.1.0","symbols":["eventsource-parser.EventSourceParserStream"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { EventSourceParserStream, ParseError } from 'eventsource-parser/stream';

/**
 * Creates an EventSourceParserStream transform stream.
 * @param {import('eventsource-parser/stream').StreamOptions} [options]
 * @returns {EventSourceParserStream}
 */
export function createEventSourceStream(options) {
  return new EventSourceParserStream(options);
}

export { EventSourceParserStream, ParseError };
export default EventSourceParserStream;
package-lock.json
{
  "name": "sample-eventsource-parser-stream-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-eventsource-parser-stream-verify",
      "version": "1.0.0",
      "dependencies": {
        "eventsource-parser": "3.1.0"
      }
    },
    "node_modules/eventsource-parser": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz",
      "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==",
      "license": "MIT",
      "engines": {
        "node": ">=18.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-eventsource-parser-stream-verify",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "eventsource-parser": "3.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify eventsource-parser.EventSourceParserStream in pkg:npm/eventsource-parser@3.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/eventsource-parser@3.1.0"
  ],
  "symbols": [
    "eventsource-parser.EventSourceParserStream"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { EventSourceParserStream, ParseError, createEventSourceStream } from '../index.mjs';

async function collectStreamEvents(readable) {
  const reader = readable.getReader();
  const events = [];
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    events.push(value);
  }
  return events;
}

// 1. assert EventSourceParserStream transforms chunked string streams into EventSourceMessage objects
{
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue('data: chunk');
      controller.enqueue('ed message\n\n');
      controller.close();
    },
  });

  const parsedEvents = await collectStreamEvents(stream.pipeThrough(new EventSourceParserStream()));
  assert.strictEqual(parsedEvents.length, 1);
  assert.deepStrictEqual(parsedEvents[0], {
    id: undefined,
    event: undefined,
    data: 'chunked message',
  });
}

// 2. assert EventSourceParserStream extracts event types and message ids from streamed events
{
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue('id: 101\nevent: update\ndata: first event\n\n');
      controller.enqueue('id: 102\nevent: completion\ndata: second event\n\n');
      controller.close();
    },
  });

  const parsedEvents = await collectStreamEvents(stream.pipeThrough(createEventSourceStream()));
  assert.strictEqual(parsedEvents.length, 2);
  assert.strictEqual(parsedEvents[0].id, '101');
  assert.strictEqual(parsedEvents[0].event, 'update');
  assert.strictEqual(parsedEvents[0].data, 'first event');

  assert.strictEqual(parsedEvents[1].id, '102');
  assert.strictEqual(parsedEvents[1].event, 'completion');
  assert.strictEqual(parsedEvents[1].data, 'second event');
}

// 3. assert EventSourceParserStream triggers onRetry and onComment callbacks during streaming
{
  const retries = [];
  const comments = [];
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue(': connection keep-alive\nretry: 2500\ndata: payload\n\n');
      controller.close();
    },
  });

  const parsedEvents = await collectStreamEvents(
    stream.pipeThrough(
      new EventSourceParserStream({
        onRetry: (interval) => retries.push(interval),
        onComment: (comment) => comments.push(comment),
      })
    )
  );

  assert.strictEqual(parsedEvents.length, 1);
  assert.strictEqual(parsedEvents[0].data, 'payload');
  assert.deepStrictEqual(retries, [2500]);
  assert.deepStrictEqual(comments, ['connection keep-alive']);
}

// 4. assert EventSourceParserStream emits ParseError to onError callback or terminates when configured
{
  const errors = [];
  const streamWithCallback = new ReadableStream({
    start(controller) {
      controller.enqueue('bad_field: test\ndata: still parsed\n\n');
      controller.close();
    },
  });

  const parsedEvents = await collectStreamEvents(
    streamWithCallback.pipeThrough(
      new EventSourceParserStream({
        onError: (err) => errors.push(err),
      })
    )
  );

  assert.strictEqual(parsedEvents.length, 1);
  assert.strictEqual(errors.length, 1);
  assert.ok(errors[0] instanceof ParseError);
  assert.strictEqual(errors[0].type, 'unknown-field');

  const streamWithTerminate = new ReadableStream({
    start(controller) {
      controller.enqueue('bad_field: test\n\n');
      controller.close();
    },
  });

  let terminated = false;
  try {
    await collectStreamEvents(
      streamWithTerminate.pipeThrough(new EventSourceParserStream({ onError: 'terminate' }))
    );
  } catch (err) {
    terminated = true;
    assert.ok(err instanceof ParseError);
    assert.strictEqual(err.type, 'unknown-field');
  }
  assert.strictEqual(terminated, true);
}

// 5. assert EventSourceParserStream errors the stream when maxBufferSize is exceeded
{
  const stream = new ReadableStream({
    start(controller) {
      controller.enqueue('data: ' + 'x'.repeat(100));
      controller.close();
    },
  });

  let bufferErrorThrown = false;
  try {
    await collectStreamEvents(
      stream.pipeThrough(new EventSourceParserStream({ maxBufferSize: 20 }))
    );
  } catch (err) {
    bufferErrorThrown = true;
    assert.ok(err instanceof ParseError);
    assert.strictEqual(err.type, 'max-buffer-size-exceeded');
  }
  assert.strictEqual(bufferErrorThrown, true);
}

console.log('All EventSourceParserStream contract assertions passed.');

오리진 시더

익명