CodeSampleX

Пример

json-parse-even-better-errors 2.3.1

Проверенный пример — npm json-parse-even-better-errors 2.3.1. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:13cc647301f0b6bab852b369100118cb2495893133679118130becc034786755

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-23
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-07

Кейс

HOW
Цель
verify pkg:npm/json-parse-even-better-errors@2.3.1
Пакеты
Создан
2026-08-23T15:24:46Z

Контракт

  1. parseJson parses valid JSON and strips leading byte order mark
  2. parseJson attaches detected newline and indentation symbols to parsed objects
  3. parseJson applies optional reviver function to transform parsed values
  4. parseJson throws JSONParseError with code EJSONPARSE and context on invalid JSON
  5. parseJson throws TypeError with code EJSONPARSE when non-string input fails parsing
  6. parseJson.noExceptions returns undefined without throwing when JSON is invalid

Файлы

  • PROMPT.md
  • csx.json
  • 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 pkg:npm/json-parse-even-better-errors@2.3.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/json-parse-even-better-errors@2.3.1

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:413d8266ad8f057f5a626269c4e335218ba7263bad47d7d23912bf931e67f2c5","contract":["parseJson parses valid JSON and strips leading byte order mark","parseJson attaches detected newline and indentation symbols to parsed objects","parseJson applies optional reviver function to transform parsed values","parseJson throws JSONParseError with code EJSONPARSE and context on invalid JSON","parseJson throws TypeError with code EJSONPARSE when non-string input fails parsing","parseJson.noExceptions returns undefined without throwing when JSON is invalid"],"goal":"verify pkg:npm/json-parse-even-better-errors@2.3.1","kind":"HOW","packages":["pkg:npm/json-parse-even-better-errors@2.3.1"],"schemaVersion":1},"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/json-parse-even-better-errors@2.3.1"],"schemaVersion":1,"subject":"pkg:npm/json-parse-even-better-errors@2.3.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-json-parse-even-better-errors",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-json-parse-even-better-errors",
      "version": "1.0.0",
      "dependencies": {
        "json-parse-even-better-errors": "2.3.1"
      }
    },
    "node_modules/json-parse-even-better-errors": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
      "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-json-parse-even-better-errors",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "json-parse-even-better-errors": "2.3.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/json-parse-even-better-errors@2.3.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/json-parse-even-better-errors@2.3.1"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import parseJson from 'json-parse-even-better-errors';

const kNewline = Symbol.for('newline');
const kIndent = Symbol.for('indent');

// 1. parseJson parses valid JSON and strips leading byte order mark
{
  const result = parseJson('\uFEFF{"hello":"world"}');
  assert.equal(result.hello, 'world');
  assert.equal(parseJson('"simple string"'), 'simple string');
  assert.equal(parseJson('123'), 123);
  assert.equal(parseJson('true'), true);
  assert.equal(parseJson('null'), null);
}

// 2. parseJson attaches detected newline and indentation symbols to parsed objects
{
  const jsonWithIndent = '{\r\n    "name": "csx",\r\n    "count": 1\r\n}';
  const parsed = parseJson(jsonWithIndent);
  assert.equal(parsed.name, 'csx');
  assert.equal(parsed.count, 1);
  assert.equal(parsed[kNewline], '\r\n');
  assert.equal(parsed[kIndent], '    ');

  const emptyObj = parseJson('{}');
  assert.equal(emptyObj[kNewline], '\n');
  assert.equal(emptyObj[kIndent], '  ');
}

// 3. parseJson applies optional reviver function to transform parsed values
{
  const input = '{"a": 1, "b": 2}';
  const reviver = (key, value) => {
    if (typeof value === 'number') {
      return value * 10;
    }
    return value;
  };
  const result = parseJson(input, reviver);
  assert.equal(result.a, 10);
  assert.equal(result.b, 20);
}

// 4. parseJson throws JSONParseError with code EJSONPARSE and context on invalid JSON
{
  assert.throws(
    () => parseJson('{"bad": json}'),
    (err) => {
      assert.ok(err instanceof SyntaxError);
      assert.equal(err.name, 'JSONParseError');
      assert.equal(err.code, 'EJSONPARSE');
      assert.ok(typeof err.position === 'number');
      assert.ok(err.message.includes('while parsing'));
      return true;
    }
  );
}

// 5. parseJson throws TypeError with code EJSONPARSE when non-string input fails parsing
{
  assert.throws(
    () => parseJson([]),
    (err) => {
      assert.ok(err instanceof TypeError);
      assert.equal(err.code, 'EJSONPARSE');
      assert.ok(err.message.includes('Cannot parse an empty array'));
      return true;
    }
  );

  assert.throws(
    () => parseJson({}),
    (err) => {
      assert.ok(err instanceof TypeError);
      assert.equal(err.code, 'EJSONPARSE');
      assert.ok(err.message.includes('Cannot parse [object Object]'));
      return true;
    }
  );
}

// 6. parseJson.noExceptions returns undefined without throwing when JSON is invalid
{
  const invalidResult = parseJson.noExceptions('{"invalid": json}');
  assert.equal(invalidResult, undefined);

  const validResult = parseJson.noExceptions('{"valid": true}');
  assert.equal(validResult.valid, true);
}

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

аноним