Пример
json-stringify-safe 5.0.1: safely serialize javascript objects containing circular references to JSON without throwing TypeError
Проверенный пример — npm json-stringify-safe 5.0.1: safely serialize javascript objects containing circular references to JSON without throwing TypeError.…
sha256:ab9386164fed43217ef072fa56e7931c3e84de2d42411cf3135dc020c4649141
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 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-28 |
Кейс
HOW- Цель
- safely serialize javascript objects containing circular references to JSON without throwing TypeError
- Пакеты
- Символы
-
- json-stringify-safe
- Создан
- 2026-08-28T03:21:04Z
Контракт
- stringify serializes objects without circular references to valid JSON string
- stringify serializes circular references using default [Circular ~] markers without throwing TypeError
- stringify formats output with custom indentation spaces
- stringify supports custom replacer functions and custom cycleReplacer handlers
- stringify.getSerialize provides a reusable replacer for standard JSON.stringify
Файлы
- PROMPT.md
- csx.json
- index.mjs
- package-lock.json
- package.json
- spec.json
- test/contract.mjs
Исходный код
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: safely serialize javascript objects containing circular references to JSON without throwing TypeError
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/json-stringify-safe@5.0.1
Demonstrate these symbols/APIs:
- json-stringify-safe
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.
{"case":{"caseId":"case:sha256:847127d8d46a69e86ffa51f7a38f6212f2fca777bf4e72d4b141461d0f02e786","contract":["stringify serializes objects without circular references to valid JSON string","stringify serializes circular references using default [Circular ~] markers without throwing TypeError","stringify formats output with custom indentation spaces","stringify supports custom replacer functions and custom cycleReplacer handlers","stringify.getSerialize provides a reusable replacer for standard JSON.stringify"],"goal":"safely serialize javascript objects containing circular references to JSON without throwing TypeError","kind":"HOW","packages":["pkg:npm/json-stringify-safe@5.0.1"],"schemaVersion":1,"symbols":["json-stringify-safe"]},"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-stringify-safe@5.0.1"],"schemaVersion":1,"subject":"pkg:npm/json-stringify-safe@5.0.1","symbols":["json-stringify-safe"],"verifierAdapter":"node-typescript@1"}
import stringifySafe from 'json-stringify-safe';
/**
* Safely serialize any JavaScript value (including objects with circular references) to a JSON string.
*
* @param {*} value - The value to convert to a JSON string
* @param {Function|Array<string|number>|null} [replacer] - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as an allowlist
* @param {string|number|null} [space] - A String or Number object that is used to insert white space into the output JSON string for readability purposes
* @param {Function|null} [cycleReplacer] - Custom handler function for circular references
* @returns {string} Safe JSON string representation
*/
export function safeStringify(value, replacer, space, cycleReplacer) {
return stringifySafe(value, replacer, space, cycleReplacer);
}
/**
* Create a serializer function that handles circular references for use with standard JSON.stringify.
*
* @param {Function|null} [replacer] - Optional standard replacer function
* @param {Function|null} [cycleReplacer] - Optional handler for circular references
* @returns {Function} Serializer function compatible with JSON.stringify
*/
export function createSafeSerializer(replacer, cycleReplacer) {
return stringifySafe.getSerialize(replacer, cycleReplacer);
}
export { stringifySafe };
export default safeStringify;
{
"name": "sample-json-stringify-safe",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-json-stringify-safe",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"json-stringify-safe": "5.0.1"
}
},
"node_modules/json-stringify-safe": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
"integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",
"license": "ISC"
}
}
}
{
"name": "sample-json-stringify-safe",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"dependencies": {
"json-stringify-safe": "5.0.1"
}
}
{
"schemaVersion": 1,
"goal": "safely serialize javascript objects containing circular references to JSON without throwing TypeError",
"kind": "HOW",
"packages": [
"pkg:npm/json-stringify-safe@5.0.1"
],
"symbols": [
"json-stringify-safe"
]
}
import assert from 'node:assert/strict';
import stringifySafe from 'json-stringify-safe';
import { safeStringify, createSafeSerializer } from '../index.mjs';
// 1. Basic serialization without circular references
const plainObj = { name: 'sample', count: 42, active: true, items: [1, 2, 3] };
const standardJson = JSON.stringify(plainObj);
assert.equal(safeStringify(plainObj), standardJson, 'safeStringify should match JSON.stringify for plain objects');
assert.equal(stringifySafe(plainObj), standardJson, 'stringifySafe should match JSON.stringify for plain objects');
// 2. Circular reference handling without throwing TypeError
const circularRoot = { name: 'root' };
circularRoot.self = circularRoot;
// Standard JSON.stringify throws TypeError on circular structures
assert.throws(
() => JSON.stringify(circularRoot),
{ name: 'TypeError' },
'JSON.stringify must throw TypeError on circular reference'
);
// safeStringify serializes circular references using default [Circular ~] markers
const circularRootResult = safeStringify(circularRoot);
assert.equal(
circularRootResult,
'{"name":"root","self":"[Circular ~]"}',
'safeStringify must replace direct self-reference with [Circular ~]'
);
// Nested circular references
const parent = { id: 1, name: 'parent' };
const child = { id: 2, parent: parent };
parent.child = child;
const nestedResult = safeStringify(parent);
const parsedNested = JSON.parse(nestedResult);
assert.equal(parsedNested.id, 1);
assert.equal(parsedNested.child.id, 2);
assert.equal(parsedNested.child.parent, '[Circular ~]');
// Array with circular reference
const circularArray = ['item1'];
circularArray.push(circularArray);
const arrayResult = safeStringify(circularArray);
assert.equal(arrayResult, '["item1","[Circular ~]"]');
// 3. Formatting with indentation spaces
const formattedResult = safeStringify({ a: 1, b: 2 }, null, 2);
assert.equal(formattedResult, '{\n "a": 1,\n "b": 2\n}', 'safeStringify must support indentation spaces');
// 4. Custom replacer and custom cycleReplacer
const customCycleResult = safeStringify(
circularRoot,
null,
null,
(key, value) => `[CycleRef:${key}]`
);
assert.equal(
customCycleResult,
'{"name":"root","self":"[CycleRef:self]"}',
'safeStringify must respect custom cycleReplacer'
);
// Cycle replacer returning undefined removes circular property
const prunedCycleResult = safeStringify(
circularRoot,
null,
null,
() => undefined
);
assert.equal(
prunedCycleResult,
'{"name":"root"}',
'cycleReplacer returning undefined should omit circular property'
);
// Custom property replacer
const replacerResult = safeStringify(
{ count: 10, secret: 'hidden' },
(key, value) => (key === 'secret' ? undefined : value)
);
assert.equal(replacerResult, '{"count":10}', 'safeStringify must apply custom property replacer');
// 5. stringify.getSerialize / createSafeSerializer with standard JSON.stringify
const serializer = createSafeSerializer();
const jsonWithSerializer = JSON.stringify(circularRoot, serializer);
assert.equal(
jsonWithSerializer,
'{"name":"root","self":"[Circular ~]"}',
'createSafeSerializer must work seamlessly with standard JSON.stringify'
);
const directSerializer = stringifySafe.getSerialize();
assert.equal(
JSON.stringify(circularRoot, directSerializer),
'{"name":"root","self":"[Circular ~]"}',
'stringifySafe.getSerialize must work directly with JSON.stringify'
);
console.log('json-stringify-safe contract tests passed successfully.');
Исходный сидер
аноним