CodeSampleX

Ejemplo

source-map 0.6.1: SourceNode

Muestra verificada para npm source-map 0.6.1: SourceNode. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:37b956378f645a8faaa9bf7aa566e0037de3975ee51f3fdfd78000829e293b84

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-23
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-07

Caso

HOW
Objetivo
verify source-map.SourceNode in pkg:npm/source-map@0.6.1
Paquetes
Símbolos
  • source-map.SourceNode
Creado
2026-08-23T13:42:52Z

Contrato

  1. SourceNode instantiates code chunks with line, column, source file, and optional identifier name
  2. SourceNode.add and SourceNode.prepend append and prepend string chunks or child SourceNodes
  3. SourceNode.walk traverses chunk nodes yielding code snippets and mapped source locations
  4. SourceNode.join combines chunks with a separator and SourceNode.replaceRight updates matching text
  5. SourceNode.toStringWithSourceMap generates merged code and a SourceMapGenerator with line and column mappings
  6. SourceNode.fromStringWithSourceMap reconstructs SourceNodes from generated code and a SourceMapConsumer
  7. SourceNode.setSourceContent and walkSourceContents manage original file source content

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 source-map.SourceNode in pkg:npm/source-map@0.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/source-map@0.6.1
Demonstrate these symbols/APIs:
  - source-map.SourceNode

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:0ab2eb95142514f98b253f8b8f5980840259bc9432263fd626a8817ca3890dd8","contract":["SourceNode instantiates code chunks with line, column, source file, and optional identifier name","SourceNode.add and SourceNode.prepend append and prepend string chunks or child SourceNodes","SourceNode.walk traverses chunk nodes yielding code snippets and mapped source locations","SourceNode.join combines chunks with a separator and SourceNode.replaceRight updates matching text","SourceNode.toStringWithSourceMap generates merged code and a SourceMapGenerator with line and column mappings","SourceNode.fromStringWithSourceMap reconstructs SourceNodes from generated code and a SourceMapConsumer","SourceNode.setSourceContent and walkSourceContents manage original file source content"],"goal":"verify source-map.SourceNode in pkg:npm/source-map@0.6.1","kind":"HOW","packages":["pkg:npm/source-map@0.6.1"],"schemaVersion":1,"symbols":["source-map.SourceNode"]},"contractCommand":["node","test/contract.js"],"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/source-map@0.6.1"],"schemaVersion":1,"subject":"pkg:npm/source-map@0.6.1","symbols":["source-map.SourceNode"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { SourceNode, SourceMapConsumer, SourceMapGenerator } = require('source-map');

/**
 * Creates a new SourceNode instance.
 * @param {number|null} line - 1-based line number in source file
 * @param {number|null} column - 0-based column number in source file
 * @param {string|null} source - Source filename
 * @param {string|SourceNode|Array<string|SourceNode>} [chunks] - Optional initial chunks
 * @param {string} [name] - Optional identifier name
 * @returns {SourceNode}
 */
function createSourceNode(line, column, source, chunks, name) {
  return new SourceNode(line, column, source, chunks, name);
}

/**
 * Combines multiple chunks or nodes with an optional separator.
 * @param {Array<string|SourceNode>} nodes - Nodes or string chunks to combine
 * @param {string} [separator] - Delimiter to join chunks with
 * @returns {SourceNode}
 */
function buildJoinedNode(nodes, separator) {
  const root = new SourceNode(null, null, null, nodes);
  if (separator !== undefined) {
    return root.join(separator);
  }
  return root;
}

/**
 * Generates output code along with its SourceMapGenerator.
 * @param {SourceNode} node - The root SourceNode
 * @param {object} [options] - Options like { file: string }
 * @returns {{ code: string, map: SourceMapGenerator }}
 */
function generateCodeAndMap(node, options) {
  return node.toStringWithSourceMap(options);
}

/**
 * Reconstructs a SourceNode tree from generated code and a SourceMapConsumer.
 * @param {string} code - Generated code string
 * @param {SourceMapConsumer} consumer - The source map consumer
 * @param {string} [relativePath] - Optional relative path
 * @returns {SourceNode}
 */
function parseSourceNodeFromMap(code, consumer, relativePath) {
  return SourceNode.fromStringWithSourceMap(code, consumer, relativePath);
}

module.exports = {
  SourceNode,
  SourceMapConsumer,
  SourceMapGenerator,
  createSourceNode,
  buildJoinedNode,
  generateCodeAndMap,
  parseSourceNodeFromMap
};
package-lock.json
{
  "name": "sample-source-map-sourcenode",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-source-map-sourcenode",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "source-map": "0.6.1"
      }
    },
    "node_modules/source-map": {
      "version": "0.6.1",
      "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
      "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-source-map-sourcenode",
  "version": "1.0.0",
  "private": true,
  "description": "verify source-map.SourceNode in pkg:npm/source-map@0.6.1",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "source-map": "0.6.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify source-map.SourceNode in pkg:npm/source-map@0.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/source-map@0.6.1"
  ],
  "symbols": [
    "source-map.SourceNode"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  SourceNode,
  SourceMapConsumer,
  createSourceNode,
  buildJoinedNode,
  generateCodeAndMap,
  parseSourceNodeFromMap
} = require('../index.js');

function testInstantiationAndAddPrepend() {
  const node = createSourceNode(1, 0, 'source-a.js', 'function compute(');
  node.add('x, y) {\n');
  node.prepend('/* generated header */\n');

  const result = node.toString();
  assert.strictEqual(
    result,
    '/* generated header */\nfunction compute(x, y) {\n',
    'SourceNode must correctly prepend and append chunks'
  );
}

function testWalk() {
  const node = createSourceNode(10, 4, 'helper.js', 'return x * y;', 'computeMul');
  const visited = [];

  node.walk((chunk, loc) => {
    visited.push({ chunk, loc });
  });

  assert.strictEqual(visited.length, 1, 'SourceNode.walk should visit one chunk');
  assert.strictEqual(visited[0].chunk, 'return x * y;');
  assert.strictEqual(visited[0].loc.line, 10);
  assert.strictEqual(visited[0].loc.column, 4);
  assert.strictEqual(visited[0].loc.source, 'helper.js');
  assert.strictEqual(visited[0].loc.name, 'computeMul');
}

function testJoinAndReplaceRight() {
  const nodeA = createSourceNode(1, 0, 'a.js', 'alpha');
  const nodeB = createSourceNode(2, 0, 'b.js', 'beta');
  const nodeC = createSourceNode(3, 0, 'c.js', 'gamma_old');

  const joined = buildJoinedNode([nodeA, nodeB, nodeC], ' + ');
  assert.strictEqual(joined.toString(), 'alpha + beta + gamma_old');

  joined.replaceRight(/gamma_old/, 'gamma_new');
  assert.strictEqual(
    joined.toString(),
    'alpha + beta + gamma_new',
    'SourceNode.replaceRight must update the rightmost matching chunk'
  );
}

function testToStringWithSourceMapAndConsumer() {
  const root = new SourceNode(null, null, null, [
    createSourceNode(1, 0, 'math.js', 'const factor = 2;\n'),
    createSourceNode(2, 0, 'math.js', 'const total = factor * 5;\n', 'totalCalc'),
    createSourceNode(3, 0, 'math.js', 'console.log(total);\n')
  ]);

  const { code, map } = generateCodeAndMap(root, { file: 'output.js' });
  const expectedCode = 'const factor = 2;\nconst total = factor * 5;\nconsole.log(total);\n';

  assert.strictEqual(code, expectedCode, 'Generated code must match combined chunks');

  const rawMap = map.toJSON();
  assert.strictEqual(rawMap.file, 'output.js');
  assert.deepStrictEqual(rawMap.sources, ['math.js']);

  const consumer = new SourceMapConsumer(rawMap);

  const pos1 = consumer.originalPositionFor({ line: 1, column: 0 });
  assert.strictEqual(pos1.source, 'math.js');
  assert.strictEqual(pos1.line, 1);
  assert.strictEqual(pos1.column, 0);

  const pos2 = consumer.originalPositionFor({ line: 2, column: 0 });
  assert.strictEqual(pos2.source, 'math.js');
  assert.strictEqual(pos2.line, 2);
  assert.strictEqual(pos2.column, 0);
  assert.strictEqual(pos2.name, 'totalCalc');

  // Test static fromStringWithSourceMap reconstruction
  const reconstructed = parseSourceNodeFromMap(code, consumer);
  assert.strictEqual(
    reconstructed.toString(),
    code,
    'SourceNode.fromStringWithSourceMap must recreate equivalent output'
  );
}

function testSourceContentManagement() {
  const node = createSourceNode(1, 0, 'module.js', 'const value = 42;\n');
  const sourceCode = '// module source file\nconst value = 42;\n';
  node.setSourceContent('module.js', sourceCode);

  let retrievedContent = null;
  node.walkSourceContents((source, content) => {
    if (source === 'module.js') {
      retrievedContent = content;
    }
  });

  assert.strictEqual(retrievedContent, sourceCode, 'Source content must be retrieved correctly');

  const { map } = generateCodeAndMap(node);
  const rawMap = map.toJSON();
  assert.strictEqual(
    rawMap.sourcesContent[0],
    sourceCode,
    'Source map must include embedded sourcesContent'
  );
}

function run() {
  testInstantiationAndAddPrepend();
  testWalk();
  testJoinAndReplaceRight();
  testToStringWithSourceMapAndConsumer();
  testSourceContentManagement();
  console.log('Contract tests passed successfully.');
  process.exit(0);
}

run();

Seeder de origen

anónimo