CodeSampleX

Пример

source-map-js 1.2.1: SourceMapConsumer, SourceMapGenerator

Проверенный пример — npm source-map-js 1.2.1: SourceMapConsumer, SourceMapGenerator. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:c7e7bcb54e8c4164ce59f88e5510206cfc9f5a5d237b11eddc62cac1f5312980

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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 pkg:npm/source-map-js@1.2.1
Пакеты
Символы
  • SourceMapConsumer
  • SourceMapGenerator
Окружение
node 22.23.2
Создан
2026-08-27T15:43:39Z

Контракт

  1. assert SourceMapGenerator builds valid v3 source map JSON with mappings and metadata
  2. assert SourceMapConsumer resolves original position for generated position with symbol name
  3. assert SourceMapConsumer resolves generated position for given original position
  4. assert SourceMapConsumer retrieves embedded source content for source files
  5. assert SourceMapConsumer iterates all mappings sequentially via eachMapping

Файлы

  • 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 pkg:npm/source-map-js@1.2.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/source-map-js@1.2.1
Demonstrate these symbols/APIs:
  - SourceMapConsumer
  - SourceMapGenerator

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:4984ac22f8f7b7ddf6456178a7a63f1a89c101586ea82429e6afd7152eedb912","contract":["assert SourceMapGenerator builds valid v3 source map JSON with mappings and metadata","assert SourceMapConsumer resolves original position for generated position with symbol name","assert SourceMapConsumer resolves generated position for given original position","assert SourceMapConsumer retrieves embedded source content for source files","assert SourceMapConsumer iterates all mappings sequentially via eachMapping"],"goal":"verify pkg:npm/source-map-js@1.2.1","kind":"HOW","packages":["pkg:npm/source-map-js@1.2.1"],"schemaVersion":1,"symbols":["SourceMapConsumer","SourceMapGenerator"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","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/source-map-js@1.2.1"],"schemaVersion":1,"subject":"pkg:npm/source-map-js@1.2.1","symbols":["SourceMapConsumer","SourceMapGenerator"],"verifierAdapter":"node-typescript@1"}
index.js
const { SourceMapConsumer, SourceMapGenerator } = require('source-map-js');

/**
 * Creates a SourceMapGenerator instance with given options.
 *
 * @param {Object} [options] - Configuration for generator (file, sourceRoot, etc.)
 * @returns {SourceMapGenerator}
 */
function createSourceMap(options) {
  return new SourceMapGenerator(options);
}

/**
 * Creates a SourceMapConsumer instance from a raw source map object or string.
 *
 * @param {Object|string} rawSourceMap - Source map object or JSON string
 * @returns {SourceMapConsumer}
 */
function consumeSourceMap(rawSourceMap) {
  return new SourceMapConsumer(rawSourceMap);
}

module.exports = {
  createSourceMap,
  consumeSourceMap,
  SourceMapConsumer,
  SourceMapGenerator,
};
package-lock.json
{
  "name": "sample-source-map-js",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-source-map-js",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "source-map-js": "1.2.1"
      }
    },
    "node_modules/source-map-js": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-source-map-js",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pkg:npm/source-map-js@1.2.1 functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "source-map-js": "1.2.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/source-map-js@1.2.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/source-map-js@1.2.1"
  ],
  "symbols": [
    "SourceMapConsumer",
    "SourceMapGenerator"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import sourceMapJs from 'source-map-js';
const { SourceMapConsumer, SourceMapGenerator } = sourceMapJs;
import { createSourceMap, consumeSourceMap } from '../index.js';

// 1. SourceMapGenerator builds valid v3 source map JSON with mappings and metadata
const generator = createSourceMap({
  file: 'min.js',
  sourceRoot: 'http://example.com/src/'
});

generator.addMapping({
  generated: { line: 1, column: 0 },
  original: { line: 1, column: 0 },
  source: 'app.js',
  name: 'calculateTotal'
});

generator.addMapping({
  generated: { line: 1, column: 15 },
  original: { line: 2, column: 4 },
  source: 'app.js'
});

const sourceCode = 'function calculateTotal() {\n  return 42;\n}';
generator.setSourceContent('app.js', sourceCode);

const mapJson = generator.toJSON();
assert.strictEqual(mapJson.version, 3, 'SourceMapGenerator produces version 3 source map');
assert.strictEqual(mapJson.file, 'min.js', 'SourceMapGenerator preserves generated file name');
assert.strictEqual(mapJson.sourceRoot, 'http://example.com/src/', 'SourceMapGenerator preserves sourceRoot');
assert.deepStrictEqual(mapJson.sources, ['app.js'], 'SourceMapGenerator registers source files');
assert.deepStrictEqual(mapJson.names, ['calculateTotal'], 'SourceMapGenerator registers identifier names');
assert.strictEqual(typeof mapJson.mappings, 'string', 'SourceMapGenerator encodes mappings string');

const mapString = generator.toString();
assert.strictEqual(typeof mapString, 'string', 'SourceMapGenerator.toString returns string');
assert.strictEqual(JSON.parse(mapString).version, 3, 'SourceMapGenerator.toString produces parseable JSON');

// 2. SourceMapConsumer resolves original position for generated position with symbol name
const consumer = consumeSourceMap(mapJson);

const origPos1 = consumer.originalPositionFor({ line: 1, column: 0 });
assert.strictEqual(origPos1.source, 'http://example.com/src/app.js', 'SourceMapConsumer resolves full source URL with sourceRoot');
assert.strictEqual(origPos1.line, 1, 'SourceMapConsumer resolves correct original line');
assert.strictEqual(origPos1.column, 0, 'SourceMapConsumer resolves correct original column');
assert.strictEqual(origPos1.name, 'calculateTotal', 'SourceMapConsumer resolves mapped symbol name');

const origPos2 = consumer.originalPositionFor({ line: 1, column: 15 });
assert.strictEqual(origPos2.source, 'http://example.com/src/app.js', 'SourceMapConsumer resolves source URL for second mapping');
assert.strictEqual(origPos2.line, 2, 'SourceMapConsumer resolves original line 2');
assert.strictEqual(origPos2.column, 4, 'SourceMapConsumer resolves original column 4');
assert.strictEqual(origPos2.name, null, 'SourceMapConsumer returns null for unnamed mapping');

// 3. SourceMapConsumer resolves generated position for given original position
const genPos = consumer.generatedPositionFor({
  source: 'http://example.com/src/app.js',
  line: 2,
  column: 4
});
assert.strictEqual(genPos.line, 1, 'SourceMapConsumer resolves generated line');
assert.strictEqual(genPos.column, 15, 'SourceMapConsumer resolves generated column');

// 4. SourceMapConsumer retrieves embedded source content for source files
assert.strictEqual(
  consumer.hasContentsOfAllSources(),
  true,
  'SourceMapConsumer indicates all sources have embedded content'
);
assert.strictEqual(
  consumer.sourceContentFor('app.js'),
  sourceCode,
  'SourceMapConsumer retrieves content by source filename'
);
assert.strictEqual(
  consumer.sourceContentFor('http://example.com/src/app.js'),
  sourceCode,
  'SourceMapConsumer retrieves content by full source URL'
);

// 5. SourceMapConsumer iterates all mappings sequentially via eachMapping
const collectedMappings = [];
consumer.eachMapping((m) => {
  collectedMappings.push({
    genLine: m.generatedLine,
    genCol: m.generatedColumn,
    origLine: m.originalLine,
    origCol: m.originalColumn,
    name: m.name
  });
});

assert.strictEqual(collectedMappings.length, 2, 'SourceMapConsumer iterates exactly 2 mappings');
assert.deepStrictEqual(
  collectedMappings[0],
  { genLine: 1, genCol: 0, origLine: 1, origCol: 0, name: 'calculateTotal' },
  'First mapping matches expected coordinates and symbol'
);
assert.deepStrictEqual(
  collectedMappings[1],
  { genLine: 1, genCol: 15, origLine: 2, origCol: 4, name: null },
  'Second mapping matches expected coordinates'
);

console.log('All contract assertions passed.');

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

аноним