CodeSampleX

Exemplo

eventsource-parser 3.1.1: EventSourceParser

Amostra verificada para npm eventsource-parser 3.1.1: EventSourceParser. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:dd0b26712b53af27316a55bfee4a442656a61a558e3be0713da04774d8b98494

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-02

Caso

HOW
Objetivo
verify EventSourceParser in pkg:npm/eventsource-parser@3.1.1
Pacotes
Símbolos
  • EventSourceParser
Ambiente
node 22.23.2
Criado
2026-09-02T01:41:10Z

Contrato

  1. createParser returns an EventSourceParser instance with feed and reset methods
  2. EventSourceParser parses basic messages, multiline data, event types, and message IDs
  3. EventSourceParser streams partial chunks across line and message boundaries
  4. EventSourceParser emits comment and retry events to their respective callbacks
  5. EventSourceParser handles reset and reports invalid retry or unknown fields
  6. EventSourceParser enforces maxBufferSize and throws on subsequent feed until reset

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 EventSourceParser in pkg:npm/eventsource-parser@3.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/eventsource-parser@3.1.1
Demonstrate these symbols/APIs:
  - EventSourceParser
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:b987c91379c625a6c3d201d51faccb6bc1b6a1c8e4408b074ea64dd72fd4bc8e","constraints":{"executionContext":"node"},"contract":["createParser returns an EventSourceParser instance with feed and reset methods","EventSourceParser parses basic messages, multiline data, event types, and message IDs","EventSourceParser streams partial chunks across line and message boundaries","EventSourceParser emits comment and retry events to their respective callbacks","EventSourceParser handles reset and reports invalid retry or unknown fields","EventSourceParser enforces maxBufferSize and throws on subsequent feed until reset"],"goal":"verify EventSourceParser in pkg:npm/eventsource-parser@3.1.1","kind":"HOW","packages":["pkg:npm/eventsource-parser@3.1.1"],"schemaVersion":1,"symbols":["EventSourceParser"]},"contractCommand":["node","test/contract.js"],"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/eventsource-parser@3.1.1"],"schemaVersion":1,"subject":"pkg:npm/eventsource-parser@3.1.1","symbols":["EventSourceParser"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-eventsource-parser",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-eventsource-parser",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "eventsource-parser": "3.1.1"
      }
    },
    "node_modules/eventsource-parser": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
      "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
      "license": "MIT",
      "engines": {
        "node": ">=18.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-eventsource-parser",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for EventSourceParser in eventsource-parser",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "eventsource-parser": "3.1.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify EventSourceParser in pkg:npm/eventsource-parser@3.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/eventsource-parser@3.1.1"
  ],
  "symbols": [
    "EventSourceParser"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { createParser, ParseError } = require('eventsource-parser');

/**
 * Creates an EventSource parser instance with given callbacks and options.
 * @param {import('eventsource-parser').ParserConfig} config
 * @returns {import('eventsource-parser').EventSourceParser}
 */
function createEventParser(config) {
  return createParser(config);
}

/**
 * Feeds SSE chunked stream into a new parser and collects parsed events.
 * @param {string[]} chunks
 * @param {import('eventsource-parser').ParserConfig} [config]
 * @returns {Array<import('eventsource-parser').EventSourceMessage>}
 */
function parseChunks(chunks, config = {}) {
  const events = [];
  const parser = createParser({
    ...config,
    onEvent: (event) => {
      events.push(event);
      if (config.onEvent) config.onEvent(event);
    }
  });

  for (const chunk of chunks) {
    parser.feed(chunk);
  }

  return events;
}

module.exports = {
  createParser,
  createEventParser,
  parseChunks,
  ParseError
};
test/contract.js
const assert = require('node:assert/strict');
const { createParser, ParseError } = require('eventsource-parser');
const { createEventParser, parseChunks } = require('../src/index.js');

// 1. createParser returns an EventSourceParser instance with feed and reset methods
{
  const parser = createParser({ onEvent: () => {} });
  assert.equal(typeof parser.feed, 'function', 'parser.feed should be a function');
  assert.equal(typeof parser.reset, 'function', 'parser.reset should be a function');
  assert.throws(() => createParser(() => {}), TypeError);

  const wrappedParser = createEventParser({ onEvent: () => {} });
  assert.equal(typeof wrappedParser.feed, 'function');
  assert.equal(typeof wrappedParser.reset, 'function');
}

// 2. EventSourceParser parses basic messages, multiline data, event types, and message IDs
{
  const events = [];
  const parser = createParser({
    onEvent: (event) => events.push(event)
  });

  parser.feed('data: hello world\n\n');
  assert.deepEqual(events[0], {
    id: undefined,
    event: undefined,
    data: 'hello world'
  });

  parser.feed('id: 42\nevent: custom-event\ndata: line 1\ndata: line 2\n\n');
  assert.deepEqual(events[1], {
    id: '42',
    event: 'custom-event',
    data: 'line 1\nline 2'
  });

  assert.equal(events.length, 2);
}

// 3. EventSourceParser streams partial chunks across line and message boundaries
{
  const events = [];
  const parser = createParser({
    onEvent: (event) => events.push(event)
  });

  parser.feed('\xEF\xBB\xBFdata: hel');
  assert.equal(events.length, 0);

  parser.feed('lo\n');
  assert.equal(events.length, 0);

  parser.feed('\n');
  assert.equal(events.length, 1);
  assert.deepEqual(events[0], {
    id: undefined,
    event: undefined,
    data: 'hello'
  });

  const parsedFromHelper = parseChunks(['data: ch', 'unk1\n\n', 'data: chunk2\n\n']);
  assert.equal(parsedFromHelper.length, 2);
  assert.equal(parsedFromHelper[0].data, 'chunk1');
  assert.equal(parsedFromHelper[1].data, 'chunk2');
}

// 4. EventSourceParser emits comment and retry events to their respective callbacks
{
  const comments = [];
  const retries = [];
  const parser = createParser({
    onComment: (comment) => comments.push(comment),
    onRetry: (retry) => retries.push(retry)
  });

  parser.feed(': this is a comment\n\n');
  assert.deepEqual(comments, ['this is a comment']);

  parser.feed('retry: 5000\n\n');
  assert.deepEqual(retries, [5000]);
}

// 5. EventSourceParser handles reset and reports invalid retry or unknown fields
{
  const errors = [];
  const parser = createParser({
    onError: (err) => errors.push(err)
  });

  parser.feed('retry: not-a-number\n\n');
  assert.equal(errors.length, 1);
  assert.equal(errors[0].type, 'invalid-retry');
  assert(errors[0] instanceof ParseError);

  parser.feed('unknown-field: some-value\n\n');
  assert.equal(errors.length, 2);
  assert.equal(errors[1].type, 'unknown-field');

  // reset with consume parses trailing incomplete line
  parser.feed('trailing-invalid: foo');
  parser.reset({ consume: true });
  assert.equal(errors.length, 3);
  assert.equal(errors[2].type, 'unknown-field');
}

// 6. EventSourceParser enforces maxBufferSize and throws on subsequent feed until reset
{
  const errors = [];
  const parser = createParser({
    maxBufferSize: 10,
    onError: (err) => errors.push(err)
  });

  parser.feed('data: unclosed line exceeding buffer size');
  assert.equal(errors.length, 1);
  assert.equal(errors[0].type, 'max-buffer-size-exceeded');
  assert(errors[0] instanceof ParseError);

  // Feeding terminated parser throws
  assert.throws(() => parser.feed('data: test\n\n'), /Cannot feed parser/);

  // Calling reset allows feeding again
  parser.reset();
  parser.feed('data: ok\n\n');
}

console.log('Contract tests passed successfully.');

Seeder de origem

anônimo