CodeSampleX

Exemple

jsesc 3.1.0: escape strings and objects with json formatting and compact representation

Échantillon vérifié pour npm jsesc 3.1.0: escape strings and objects with json formatting and compact representation. Le contrat s'est exécuté sur node 22 …

sha256:652b66b33a49e17c9b9b6811efff22beaa6dca8811e8332c224e74ab3fc8a7a5

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
2
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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-24
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-12

Cas

HOW
Objectif
escape strings and objects with json formatting and compact representation
Paquets
Symboles
  • jsesc
Environnement
node 22.23.2
Créé
2026-08-24T20:22:39Z

Contrat

  1. jsesc escapes characters and string literals with customizable quotes and wrapping options
  2. jsesc formats JavaScript objects into valid JSON strings with compact and multi-line indented output
  3. jsesc escapes closing script tags and HTML-sensitive characters when isScriptContext is true
  4. jsesc formats numbers in hexadecimal, binary, and octal representations

Fichiers

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

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: escape strings and objects with json formatting and compact representation
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jsesc@3.1.0
Demonstrate these symbols/APIs:
  - jsesc

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:3e25697e419340e43000ccd7e270d7104155518aea2abfcf65d618e330af101c","contract":["jsesc escapes characters and string literals with customizable quotes and wrapping options","jsesc formats JavaScript objects into valid JSON strings with compact and multi-line indented output","jsesc escapes closing script tags and HTML-sensitive characters when isScriptContext is true","jsesc formats numbers in hexadecimal, binary, and octal representations"],"goal":"escape strings and objects with json formatting and compact representation","kind":"HOW","packages":["pkg:npm/jsesc@3.1.0"],"schemaVersion":1,"symbols":["jsesc"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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/jsesc@3.1.0"],"schemaVersion":1,"subject":"pkg:npm/jsesc@3.1.0","symbols":["jsesc"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const jsesc = require('jsesc');

function escapeString(value, options = {}) {
  return jsesc(value, options);
}

function escapeJson(data, options = {}) {
  return jsesc(data, {
    json: true,
    compact: options.compact !== undefined ? options.compact : true,
    indent: options.indent !== undefined ? options.indent : '  ',
    ...options
  });
}

function escapeForScript(str, options = {}) {
  return jsesc(str, {
    isScriptContext: true,
    wrap: true,
    ...options
  });
}

module.exports = {
  escapeString,
  escapeJson,
  escapeForScript,
  jsesc
};
package-lock.json
{
  "name": "sample-jsesc-escape",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jsesc-escape",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jsesc": "3.1.0"
      }
    },
    "node_modules/jsesc": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
      "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
      "license": "MIT",
      "bin": {
        "jsesc": "bin/jsesc"
      },
      "engines": {
        "node": ">=6"
      }
    }
  }
}
package.json
{
  "name": "sample-jsesc-escape",
  "version": "1.0.0",
  "private": true,
  "description": "escape strings and objects with json formatting and compact representation using jsesc",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "jsesc": "3.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "escape strings and objects with json formatting and compact representation",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jsesc@3.1.0"
  ],
  "symbols": [
    "jsesc"
  ]
}
test/contract.cjs
'use strict';

const assert = require('assert');
const jsesc = require('jsesc');
const { escapeString, escapeJson, escapeForScript } = require('../index.js');

function testBasicEscaping() {
  const input = 'hello "world" and \'foo\' \n \t';
  const result = jsesc(input);
  assert.strictEqual(result, "hello \"world\" and \\'foo\\' \\n \\t", 'jsesc escapes quotes and whitespace control chars');

  const wrappedSingle = jsesc('hello "world"', { quotes: 'single', wrap: true });
  assert.strictEqual(wrappedSingle, '\'hello "world"\'', 'jsesc with quotes single wraps in single quotes');

  const wrappedDouble = jsesc("hello 'world'", { quotes: 'double', wrap: true });
  assert.strictEqual(wrappedDouble, '"hello \'world\'"', 'jsesc with quotes double wraps in double quotes');

  const wrappedBacktick = jsesc('hello `world` ${val}', { quotes: 'backtick', wrap: true });
  assert.strictEqual(wrappedBacktick, '`hello \\`world\\` \\${val}`', 'jsesc with backtick escapes template interpolation');
}

function testJsonFormatting() {
  const data = { title: 'sample', counts: [1, 2, 3], flags: { active: true } };
  const compactJson = jsesc(data, { json: true });
  assert.strictEqual(compactJson, '{"title":"sample","counts":[1,2,3],"flags":{"active":true}}', 'jsesc json: true produces compact JSON');
  assert.deepStrictEqual(JSON.parse(compactJson), data, 'Parsed compact JSON matches data');

  const prettyJson = jsesc(data, { json: true, compact: false, indent: '  ' });
  const expectedPretty = '{\n  "title": "sample",\n  "counts": [\n    1,\n    2,\n    3\n  ],\n  "flags": {\n    "active": true\n  }\n}';
  assert.strictEqual(prettyJson, expectedPretty, 'jsesc compact: false produces indented JSON');
  assert.deepStrictEqual(JSON.parse(prettyJson), data, 'Parsed pretty JSON matches data');
}

function testScriptContext() {
  const scriptContent = '<script>alert("test")</script>';
  const escapedScript = jsesc(scriptContent, { isScriptContext: true, wrap: true });
  assert.strictEqual(escapedScript, '\'<script>alert("test")<\\/script>\'', 'isScriptContext escapes forward slash in closing script tags');
}

function testNumberFormatting() {
  const hexNumber = jsesc(255, { numbers: 'hexadecimal' });
  assert.strictEqual(hexNumber, '0xFF', 'jsesc formats hexadecimal numbers');

  const binaryNumber = jsesc(5, { numbers: 'binary' });
  assert.strictEqual(binaryNumber, '0b101', 'jsesc formats binary numbers');

  const octalNumber = jsesc(63, { numbers: 'octal' });
  assert.strictEqual(octalNumber, '0o77', 'jsesc formats octal numbers');
}

function testHelperFunctions() {
  const str = escapeString('item\nline2');
  assert.strictEqual(str, 'item\\nline2', 'escapeString escapes newlines');

  const jsonCompact = escapeJson({ key: 'value' });
  assert.strictEqual(jsonCompact, '{"key":"value"}', 'escapeJson defaults to compact JSON');

  const jsonPretty = escapeJson({ key: 'value' }, { compact: false, indent: '  ' });
  assert.strictEqual(jsonPretty, '{\n  "key": "value"\n}', 'escapeJson formats indented JSON');

  const script = escapeForScript('</script>');
  assert.strictEqual(script, "'<\\/script>'", 'escapeForScript wraps and escapes script tags');
}

function runAll() {
  testBasicEscaping();
  testJsonFormatting();
  testScriptContext();
  testNumberFormatting();
  testHelperFunctions();
  console.log('Contract tests passed successfully.');
}

runAll();

Seeder d'origine

anonyme