CodeSampleX

Пример

flatted 3.4.4: stringify

Проверенный пример — npm flatted 3.4.4: stringify. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: flatted.stringify serializes circular…

sha256:7bed7cdebb5dbf4f7efcb0868ace2abf90abca38e93f42fe3821b7b158e0121f

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

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

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

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

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

Окружение Контракт Этапы Запуск
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-27

Кейс

HOW
Цель
verify flatted.stringify in pkg:npm/flatted@3.4.4
Пакеты
Символы
  • flatted.stringify
Окружение
node 22.23.2
Создан
2026-08-27T13:59:01Z

Контракт

  1. flatted.stringify serializes circular object references without throwing TypeError
  2. flatted.stringify serializes circular array references into indexed flatted structure
  3. flatted.stringify preserves shared references across object properties
  4. flatted.stringify serializes primitive values into flatted array representation
  5. flatted.stringify supports replacer function to transform serialized values
  6. flatted.stringify supports replacer array to filter object properties
  7. flatted.stringify supports space parameter for formatted indentation
  8. flatted.stringify roundtrips through flatted.parse recovering exact circular structure and identity

Файлы

  • 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 flatted.stringify in pkg:npm/flatted@3.4.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/flatted@3.4.4
Demonstrate these symbols/APIs:
  - flatted.stringify

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:232c6e2feaf49ea1176f2764823f814384767a944e23fb4b0553374d49bad2c5","contract":["flatted.stringify serializes circular object references without throwing TypeError","flatted.stringify serializes circular array references into indexed flatted structure","flatted.stringify preserves shared references across object properties","flatted.stringify serializes primitive values into flatted array representation","flatted.stringify supports replacer function to transform serialized values","flatted.stringify supports replacer array to filter object properties","flatted.stringify supports space parameter for formatted indentation","flatted.stringify roundtrips through flatted.parse recovering exact circular structure and identity"],"goal":"verify flatted.stringify in pkg:npm/flatted@3.4.4","kind":"HOW","packages":["pkg:npm/flatted@3.4.4"],"schemaVersion":1,"symbols":["flatted.stringify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/flatted@3.4.4"],"schemaVersion":1,"subject":"pkg:npm/flatted@3.4.4","symbols":["flatted.stringify"],"verifierAdapter":"node-typescript@1"}
index.js
import { stringify, parse } from 'flatted';

export function stringifyCircular(value, replacer, space) {
  return stringify(value, replacer, space);
}

export function stringifyWithReplacer(value, replacer) {
  return stringify(value, replacer);
}

export function stringifyWithIndent(value, space) {
  return stringify(value, null, space);
}

export { stringify, parse };
export default stringify;
package-lock.json
{
  "name": "sample-flatted-stringify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-flatted-stringify",
      "version": "1.0.0",
      "dependencies": {
        "flatted": "3.4.4"
      }
    },
    "node_modules/flatted": {
      "version": "3.4.4",
      "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz",
      "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-flatted-stringify",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "flatted": "3.4.4"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify flatted.stringify in pkg:npm/flatted@3.4.4",
  "kind": "HOW",
  "packages": [
    "pkg:npm/flatted@3.4.4"
  ],
  "symbols": [
    "flatted.stringify"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { parse } from 'flatted';
import { stringify, stringifyCircular, stringifyWithReplacer, stringifyWithIndent } from '../index.js';

// 1. flatted.stringify serializes circular object references without throwing TypeError
{
  const circularObj = { name: 'root' };
  circularObj.self = circularObj;
  circularObj.child = { parent: circularObj };

  // Standard JSON.stringify throws TypeError on circular structures
  assert.throws(() => JSON.stringify(circularObj), TypeError);

  const serialized = stringify(circularObj);
  assert.strictEqual(typeof serialized, 'string', 'serialized output must be a string');
  assert.strictEqual(stringifyCircular(circularObj), serialized);

  const raw = JSON.parse(serialized);
  assert.strictEqual(Array.isArray(raw), true, 'flatted serialized payload must be a JSON array');
  assert.strictEqual(raw[0].name, '1');
  assert.strictEqual(raw[0].self, '0', 'self reference points back to index 0');
}

// 2. flatted.stringify serializes circular array references into indexed flatted structure
{
  const circularArr = [10, 20];
  circularArr.push(circularArr);

  const serialized = stringify(circularArr);
  const raw = JSON.parse(serialized);
  assert.strictEqual(Array.isArray(raw), true, 'flatted serialized payload must be a JSON array');
  assert.strictEqual(raw[0][0], 10);
  assert.strictEqual(raw[0][1], 20);
  assert.strictEqual(raw[0][2], '0', 'self reference points back to root array index 0');
}

// 3. flatted.stringify preserves shared references across object properties
{
  const shared = { id: 'shared-node', count: 100 };
  const container = { first: shared, second: shared };

  const serialized = stringify(container);
  const raw = JSON.parse(serialized);
  assert.strictEqual(raw[0].first, raw[0].second, 'both properties must point to identical flatted index');
}

// 4. flatted.stringify serializes primitive values into flatted array representation
{
  assert.strictEqual(stringify('hello world'), '["hello world"]');
  assert.strictEqual(stringify(12345), '[12345]');
  assert.strictEqual(stringify(true), '[true]');
  assert.strictEqual(stringify(false), '[false]');
  assert.strictEqual(stringify(null), '[null]');
  assert.strictEqual(stringify(undefined), '[]');
}

// 5. flatted.stringify supports replacer function to transform serialized values
{
  const data = { x: 10, y: 20, tag: 'keep' };
  const serialized = stringifyWithReplacer(data, (key, value) => {
    if (typeof value === 'number') {
      return value * 2;
    }
    return value;
  });
  const parsed = parse(serialized);
  assert.strictEqual(parsed.x, 20, 'replacer should double numeric value x');
  assert.strictEqual(parsed.y, 40, 'replacer should double numeric value y');
  assert.strictEqual(parsed.tag, 'keep', 'replacer should preserve tag');
}

// 6. flatted.stringify supports replacer array to filter object properties
{
  const data = { a: 1, b: 2, c: 3 };
  const serialized = stringify(data, ['a', 'c']);
  const parsed = parse(serialized);
  assert.strictEqual(parsed.a, 1);
  assert.strictEqual(parsed.b, undefined, 'property b must be omitted');
  assert.strictEqual(parsed.c, 3);
}

// 7. flatted.stringify supports space parameter for formatted indentation
{
  const data = { a: 1, b: 'text' };
  const formatted = stringifyWithIndent(data, 2);
  assert.strictEqual(typeof formatted, 'string');
  assert.strictEqual(formatted.includes('\n'), true, 'formatted output should include newlines');
  assert.strictEqual(formatted.includes('  "a": 1'), true, 'formatted output should include indented properties');
}

// 8. flatted.stringify roundtrips through flatted.parse recovering exact circular structure and identity
{
  const nodeA = { name: 'NodeA' };
  const nodeB = { name: 'NodeB' };
  nodeA.neighbor = nodeB;
  nodeB.neighbor = nodeA;

  const serialized = stringify(nodeA);
  const recovered = parse(serialized);

  assert.strictEqual(recovered.name, 'NodeA');
  assert.strictEqual(recovered.neighbor.name, 'NodeB');
  assert.strictEqual(recovered.neighbor.neighbor, recovered, 'circular graph identity must be preserved across roundtrip');
}

console.log('Contract verification finished successfully.');

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

аноним