CodeSampleX

Пример

eventsource 3.0.7: ErrorEvent

Проверенный пример — npm eventsource 3.0.7: ErrorEvent. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: ErrorEvent extends Event and…

sha256:8dc4f2c2cfe274f161b8f4140584de3c2d95f9732b5b13c0349acfddca0bbade

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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.ErrorEvent in pkg:npm/eventsource@3.0.7
Пакеты
Символы
  • eventsource.ErrorEvent
Создан
2026-09-17T01:48:28Z

Контракт

  1. ErrorEvent extends Event and initializes type, message, and code properties from constructor options
  2. ErrorEvent defaults code and message to undefined when initialized without options
  3. ErrorEvent custom inspection formats properties including type, message, and code
  4. EventSource dispatches ErrorEvent instance to onerror callback with HTTP error code on HTTP failure
  5. EventSource dispatches ErrorEvent via addEventListener on connection failure

Файлы

  • 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.ErrorEvent in pkg:npm/eventsource@3.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/eventsource@3.0.7
Demonstrate these symbols/APIs:
  - eventsource.ErrorEvent

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:0bd3c5da7b877f0de637d0f7fe7b260f3b9307854c3dddfdd26737230d0df88f","contract":["ErrorEvent extends Event and initializes type, message, and code properties from constructor options","ErrorEvent defaults code and message to undefined when initialized without options","ErrorEvent custom inspection formats properties including type, message, and code","EventSource dispatches ErrorEvent instance to onerror callback with HTTP error code on HTTP failure","EventSource dispatches ErrorEvent via addEventListener on connection failure"],"goal":"verify eventsource.ErrorEvent in pkg:npm/eventsource@3.0.7","kind":"HOW","packages":["pkg:npm/eventsource@3.0.7"],"schemaVersion":1,"symbols":["eventsource.ErrorEvent"]},"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@3.0.7"],"schemaVersion":1,"subject":"pkg:npm/eventsource@3.0.7","symbols":["eventsource.ErrorEvent"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { EventSource, ErrorEvent } from 'eventsource';

/**
 * Creates an ErrorEvent instance with given type and error details.
 *
 * @param {string} type - Event type name (e.g. 'error').
 * @param {{ message?: string, code?: number }} [initDict] - Optional error attributes.
 * @returns {ErrorEvent}
 */
export function createErrorEvent(type = 'error', initDict) {
  return new ErrorEvent(type, initDict);
}

/**
 * Creates an EventSource instance configured for the specified SSE endpoint.
 *
 * @param {string | URL} url - Target URL.
 * @param {import('eventsource').EventSourceInit} [options] - Configuration options.
 * @returns {EventSource}
 */
export function createEventSource(url, options = {}) {
  return new EventSource(url, options);
}

export { EventSource, ErrorEvent };
package-lock.json
{
  "name": "sample-eventsource-errorevent",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-eventsource-errorevent",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "eventsource": "3.0.7"
      }
    },
    "node_modules/eventsource": {
      "version": "3.0.7",
      "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
      "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
      "license": "MIT",
      "dependencies": {
        "eventsource-parser": "^3.0.1"
      },
      "engines": {
        "node": ">=18.0.0"
      }
    },
    "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-errorevent",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "eventsource": "3.0.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify eventsource.ErrorEvent in pkg:npm/eventsource@3.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/eventsource@3.0.7"
  ],
  "symbols": [
    "eventsource.ErrorEvent"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import util from 'node:util';
import { EventSource, ErrorEvent, createErrorEvent, createEventSource } from '../index.mjs';

// Contract 1: ErrorEvent extends Event and initializes type, message, and code properties from constructor options
const ev1 = createErrorEvent('error', { message: 'Failed to connect', code: 500 });
assert.ok(ev1 instanceof Event);
assert.ok(ev1 instanceof ErrorEvent);
assert.equal(ev1.type, 'error');
assert.equal(ev1.message, 'Failed to connect');
assert.equal(ev1.code, 500);
assert.equal(typeof ev1.timeStamp, 'number');

// Contract 2: ErrorEvent defaults code and message to undefined when initialized without options
const ev2 = createErrorEvent('error');
assert.ok(ev2 instanceof Event);
assert.ok(ev2 instanceof ErrorEvent);
assert.equal(ev2.type, 'error');
assert.equal(ev2.message, undefined);
assert.equal(ev2.code, undefined);

// Contract 3: ErrorEvent custom inspection formats properties including type, message, and code
const ev3 = createErrorEvent('error', { message: 'Custom inspect test', code: 404 });
const inspected = util.inspect(ev3);
assert.ok(inspected.includes('Custom inspect test'));
assert.ok(inspected.includes('404'));
assert.ok(inspected.includes('error'));

// Contract 4: EventSource dispatches ErrorEvent instance to onerror callback with HTTP error code on HTTP failure
await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    res.writeHead(503, { 'Content-Type': 'text/plain' });
    res.end('Service Unavailable');
  });

  server.listen(0, '127.0.0.1', () => {
    const port = server.address().port;
    const es = createEventSource(`http://127.0.0.1:${port}/sse`);

    es.onerror = (ev) => {
      try {
        assert.ok(ev instanceof ErrorEvent, 'Event should be instance of ErrorEvent');
        assert.equal(ev.type, 'error');
        assert.equal(ev.code, 503);
        es.close();
        server.close(() => resolve());
      } catch (err) {
        es.close();
        server.close(() => reject(err));
      }
    };
  });
});

// Contract 5: EventSource dispatches ErrorEvent via addEventListener on connection failure
await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    res.destroy();
  });

  server.listen(0, '127.0.0.1', () => {
    const port = server.address().port;
    const es = createEventSource(`http://127.0.0.1:${port}/sse`);

    es.addEventListener('error', (ev) => {
      try {
        assert.ok(ev instanceof ErrorEvent, 'Event should be instance of ErrorEvent');
        assert.equal(ev.type, 'error');
        es.close();
        server.close(() => resolve());
      } catch (err) {
        es.close();
        server.close(() => reject(err));
      }
    });
  });
});

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

Исходный сидер

аноним