CodeSampleX

Exemple

json-stringify-safe 5.0.1: safely serialize javascript objects containing circular references to JSON without throwing TypeError

Échantillon vérifié pour npm json-stringify-safe 5.0.1: safely serialize javascript objects containing circular references to JSON without throwing…

sha256:ab9386164fed43217ef072fa56e7931c3e84de2d42411cf3135dc020c4649141

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
safely serialize javascript objects containing circular references to JSON without throwing TypeError
Paquets
Symboles
  • json-stringify-safe
Créé
2026-08-28T03:21:04Z

Contrat

  1. stringify serializes objects without circular references to valid JSON string
  2. stringify serializes circular references using default [Circular ~] markers without throwing TypeError
  3. stringify formats output with custom indentation spaces
  4. stringify supports custom replacer functions and custom cycleReplacer handlers
  5. stringify.getSerialize provides a reusable replacer for standard JSON.stringify

Fichiers

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

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: 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.
csx.json
{"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"}
index.mjs
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;
package-lock.json
{
  "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"
    }
  }
}
package.json
{
  "name": "sample-json-stringify-safe",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "json-stringify-safe": "5.0.1"
  }
}
spec.json
{
  "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"
  ]
}
test/contract.mjs
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.');

Seeder d'origine

anonyme