CodeSampleX

Пример

js-yaml 4.3.0: YAMLException

Проверенный пример — npm js-yaml 4.3.0: YAMLException. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: yaml.YAMLException is exported as…

sha256:a089e2c71d3b562df9474697d35d4e5228d28055906a30ba18259c04ee5fc283

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

Кейс

HOW
Цель
verify js-yaml.YAMLException in pkg:npm/js-yaml@4.3.0
Пакеты
Символы
  • js-yaml.YAMLException
Окружение
node 22.23.2
Создан
2026-09-05T01:44:52Z

Контракт

  1. yaml.YAMLException is exported as a constructor function inheriting from Error
  2. YAMLException instance exposes name, reason, mark, and message properties
  3. YAMLException formats position snippet and supports compact toString output
  4. yaml.load throws YAMLException with mark and reason on malformed YAML syntax
  5. yaml.load throws YAMLException on duplicate mapping keys by default
  6. yaml.load throws YAMLException when single-document parser encounters multiple documents
  7. safeParseYaml catches YAMLException on bad input and returns parsed value on valid input

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • 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 js-yaml.YAMLException in pkg:npm/js-yaml@4.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/js-yaml@4.3.0
Demonstrate these symbols/APIs:
  - js-yaml.YAMLException

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:132c59b700f55de43f1ba14ecaf5e0136a4ef2d88c3821343d4347569047b7c7","contract":["yaml.YAMLException is exported as a constructor function inheriting from Error","YAMLException instance exposes name, reason, mark, and message properties","YAMLException formats position snippet and supports compact toString output","yaml.load throws YAMLException with mark and reason on malformed YAML syntax","yaml.load throws YAMLException on duplicate mapping keys by default","yaml.load throws YAMLException when single-document parser encounters multiple documents","safeParseYaml catches YAMLException on bad input and returns parsed value on valid input"],"goal":"verify js-yaml.YAMLException in pkg:npm/js-yaml@4.3.0","kind":"HOW","packages":["pkg:npm/js-yaml@4.3.0"],"schemaVersion":1,"symbols":["js-yaml.YAMLException"]},"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/js-yaml@4.3.0"],"schemaVersion":1,"subject":"pkg:npm/js-yaml@4.3.0","symbols":["js-yaml.YAMLException"],"verifierAdapter":"node-typescript@1"}
index.js
const yaml = require('js-yaml');

/**
 * Creates a YAMLException with optional reason and mark.
 *
 * @param {string} [reason] - Description of parsing or syntax failure.
 * @param {object} [mark] - File position context with line, column, snippet.
 * @returns {yaml.YAMLException}
 */
function createYAMLException(reason, mark) {
  return new yaml.YAMLException(reason, mark);
}

/**
 * Attempts to parse YAML string; returns result or catches YAMLException.
 *
 * @param {string} input - YAML string to parse.
 * @param {object} [options] - Options passed to yaml.load.
 * @returns {[any, yaml.YAMLException|null]} Tuple of [result, error].
 */
function parseYamlCatching(input, options) {
  try {
    const res = yaml.load(input, options);
    return [res, null];
  } catch (err) {
    if (err instanceof yaml.YAMLException) {
      return [null, err];
    }
    throw err;
  }
}

module.exports = {
  yaml,
  YAMLException: yaml.YAMLException,
  createYAMLException,
  parseYamlCatching,
};
package-lock.json
{
  "name": "sample-js-yaml-yamlexception",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-js-yaml-yamlexception",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "js-yaml": "4.3.0"
      }
    },
    "node_modules/argparse": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
      "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
      "license": "Python-2.0"
    },
    "node_modules/js-yaml": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
      "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/puzrin"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/nodeca"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "argparse": "^2.0.1"
      },
      "bin": {
        "js-yaml": "bin/js-yaml.js"
      }
    }
  }
}
package.json
{
  "name": "sample-js-yaml-yamlexception",
  "version": "1.0.0",
  "description": "Clean-room sample verifying js-yaml.YAMLException functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "js-yaml": "4.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify js-yaml.YAMLException in pkg:npm/js-yaml@4.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/js-yaml@4.3.0"
  ],
  "symbols": [
    "js-yaml.YAMLException"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import yaml from 'js-yaml';
import samplePkg from '../index.js';

const {
  YAMLException: CjsYAMLException,
  createYAMLException,
  parseYamlCatching,
} = samplePkg;

// 1. yaml.YAMLException is exported as a constructor function inheriting from Error
assert.strictEqual(typeof yaml.YAMLException, 'function', 'yaml.YAMLException must be a function/constructor');
assert.strictEqual(typeof CjsYAMLException, 'function', 'CommonJS exported YAMLException must be a constructor');

const defaultErr = new yaml.YAMLException();
assert.strictEqual(defaultErr instanceof Error, true, 'YAMLException instance must inherit from Error');
assert.strictEqual(defaultErr instanceof yaml.YAMLException, true, 'YAMLException instance must match instanceof YAMLException');

// 2. YAMLException instance exposes name, reason, mark, and message properties
const reasonText = 'invalid scalar syntax';
const basicErr = createYAMLException(reasonText);
assert.strictEqual(basicErr.name, 'YAMLException', 'Error name must be YAMLException');
assert.strictEqual(basicErr.reason, reasonText, 'Error reason must match constructor argument');
assert.strictEqual(basicErr.mark, undefined, 'Error mark must default to undefined when omitted');
assert.strictEqual(basicErr.message, reasonText, 'Error message must equal reason when mark is omitted');

// 3. YAMLException formats position snippet and supports compact toString output
const customMark = {
  name: 'config.yaml',
  line: 4,
  column: 10,
  snippet: '  key: : value\n          ^',
};
const markedErr = new yaml.YAMLException('bad mapping value', customMark);
assert.strictEqual(markedErr.mark, customMark, 'Error mark must store mark object');
assert.ok(markedErr.message.includes('bad mapping value'), 'Message must contain reason');
assert.ok(markedErr.message.includes('in "config.yaml" (5:11)'), 'Message must format 1-based line:column');
assert.ok(markedErr.message.includes('key: : value'), 'Message must contain snippet when compact is false');
assert.ok(markedErr.toString().startsWith('YAMLException: bad mapping value'), 'toString() must format name and reason');
assert.strictEqual(
  markedErr.toString(true),
  'YAMLException: bad mapping value in "config.yaml" (5:11)',
  'toString(true) must return compact representation without snippet'
);

// 4. yaml.load throws YAMLException with mark and reason on malformed YAML syntax
assert.throws(
  () => {
    yaml.load('foo: : bar');
  },
  (err) => {
    return (
      err instanceof yaml.YAMLException &&
      err.name === 'YAMLException' &&
      typeof err.reason === 'string' &&
      Boolean(err.mark) &&
      typeof err.mark.line === 'number' &&
      typeof err.mark.column === 'number'
    );
  },
  'Malformed syntax must throw YAMLException with mark and reason'
);

// 5. yaml.load throws YAMLException on duplicate mapping keys by default
assert.throws(
  () => {
    yaml.load('duplicated_key: 1\nduplicated_key: 2');
  },
  (err) => {
    return (
      err instanceof yaml.YAMLException &&
      err.name === 'YAMLException' &&
      err.reason.includes('duplicated mapping key')
    );
  },
  'Duplicated mapping keys must throw YAMLException by default'
);

// 6. yaml.load throws YAMLException when single-document parser encounters multiple documents
assert.throws(
  () => {
    yaml.load('---\nfirst: 1\n---\nsecond: 2\n');
  },
  (err) => {
    return (
      err instanceof yaml.YAMLException &&
      err.name === 'YAMLException' &&
      err.reason.includes('expected a single document in the stream')
    );
  },
  'Multi-document stream passed to load() must throw YAMLException'
);

// 7. safeParseYaml catches YAMLException on bad input and returns parsed value on valid input
const [validDoc, validErr] = parseYamlCatching('key: value\ncount: 10');
assert.strictEqual(validErr, null, 'Valid YAML should produce no error');
assert.deepStrictEqual(validDoc, { key: 'value', count: 10 }, 'Valid YAML must parse correctly');

const [invalidDoc, invalidErr] = parseYamlCatching('unclosed: [item1, item2');
assert.strictEqual(invalidDoc, null, 'Invalid YAML must return null document');
assert.strictEqual(invalidErr instanceof CjsYAMLException, true, 'Invalid YAML must return YAMLException');
assert.strictEqual(invalidErr.name, 'YAMLException');

console.log('All contract assertions for js-yaml.YAMLException passed successfully.');

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

аноним