CodeSampleX

Пример

source-map-support 0.5.21: sourceMapSupport.mapSourcePosition

Проверенный пример — npm source-map-support 0.5.21: sourceMapSupport.mapSourcePosition. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:ea144d8532241f410c77f861be3ef7fc89e54c8be4a2fd8ba4e0cfc810d86444

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-01

Кейс

HOW
Цель
verify sourceMapSupport.mapSourcePosition in pkg:npm/source-map-support@0.5.21
Пакеты
Символы
  • sourceMapSupport.mapSourcePosition
Создан
2026-09-01T11:55:14Z

Контракт

  1. sourceMapSupport.mapSourcePosition maps compiled file positions to original source files, lines, and columns using registered source maps
  2. sourceMapSupport.mapSourcePosition extracts original identifier name when mapped in source map names
  3. sourceMapSupport.mapSourcePosition returns null name when the mapped position has no identifier name
  4. sourceMapSupport.mapSourcePosition preserves unmapped position when no source map is registered for the source
  5. sourceMapSupport.mapSourcePosition supports source map objects passed as JSON strings from retrieveSourceMap

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 sourceMapSupport.mapSourcePosition in pkg:npm/source-map-support@0.5.21
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/source-map-support@0.5.21
Demonstrate these symbols/APIs:
  - sourceMapSupport.mapSourcePosition

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:fe713f931cdee2891962c7a8935080ebba652a2732873fdcd2b8bddd326399a4","contract":["sourceMapSupport.mapSourcePosition maps compiled file positions to original source files, lines, and columns using registered source maps","sourceMapSupport.mapSourcePosition extracts original identifier name when mapped in source map names","sourceMapSupport.mapSourcePosition returns null name when the mapped position has no identifier name","sourceMapSupport.mapSourcePosition preserves unmapped position when no source map is registered for the source","sourceMapSupport.mapSourcePosition supports source map objects passed as JSON strings from retrieveSourceMap"],"goal":"verify sourceMapSupport.mapSourcePosition in pkg:npm/source-map-support@0.5.21","kind":"HOW","packages":["pkg:npm/source-map-support@0.5.21"],"schemaVersion":1,"symbols":["sourceMapSupport.mapSourcePosition"]},"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/source-map-support@0.5.21"],"schemaVersion":1,"subject":"pkg:npm/source-map-support@0.5.21","symbols":["sourceMapSupport.mapSourcePosition"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-source-map-support-map-source-position",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-source-map-support-map-source-position",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "source-map-support": "0.5.21"
      }
    },
    "node_modules/buffer-from": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
      "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
      "license": "MIT"
    },
    "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"
      }
    },
    "node_modules/source-map-support": {
      "version": "0.5.21",
      "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
      "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
      "license": "MIT",
      "dependencies": {
        "buffer-from": "^1.0.0",
        "source-map": "^0.6.0"
      }
    }
  }
}
package.json
{
  "name": "sample-source-map-support-map-source-position",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of sourceMapSupport.mapSourcePosition",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "source-map-support": "0.5.21"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sourceMapSupport.mapSourcePosition in pkg:npm/source-map-support@0.5.21",
  "kind": "HOW",
  "packages": [
    "pkg:npm/source-map-support@0.5.21"
  ],
  "symbols": [
    "sourceMapSupport.mapSourcePosition"
  ]
}
src/index.js
const sourceMapSupport = require('source-map-support');

/**
 * Installs source map support into Node.js stack trace handling with custom configuration.
 * @param {object} [options]
 * @returns {void}
 */
function installSupport(options) {
  return sourceMapSupport.install(options);
}

/**
 * Maps a position in compiled code to the corresponding location in original source.
 * @param {string} source - Path or identifier of the compiled file
 * @param {number} line - 1-based line number in compiled code
 * @param {number} column - 0-based column number in compiled code
 * @returns {{ source: string, line: number, column: number, name?: string | null }}
 */
function mapSourcePosition(source, line, column) {
  return sourceMapSupport.mapSourcePosition({
    source,
    line,
    column,
  });
}

/**
 * Resets custom source map retrieval handlers to default state.
 * @returns {void}
 */
function resetHandlers() {
  if (typeof sourceMapSupport.resetRetrieveHandlers === 'function') {
    sourceMapSupport.resetRetrieveHandlers();
  }
}

module.exports = {
  sourceMapSupport,
  installSupport,
  mapSourcePosition,
  resetHandlers,
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  sourceMapSupport,
  installSupport,
  mapSourcePosition,
  resetHandlers,
} = require('../src/index.js');

async function runContract() {
  // Sample source map payload for testing offline
  // Original source: src/math.ts
  // function add(a: number, b: number): number {
  //   return a + b;
  // }
  const sampleSourceMap = {
    version: 3,
    file: 'bundle.js',
    sources: ['src/math.ts'],
    sourcesContent: [
      'function add(a: number, b: number): number {\n  return a + b;\n}\n'
    ],
    names: ['add', 'a', 'b'],
    mappings: 'AAAA,SAASA,GAAG,CAACC,CAAS,EAAEC,CAAS;IAC/B,OAAOD,CAAC,GAAGC,CAAC;AACd,CAAC'
  };

  // Configure retrieval handler for bundle.js and string-map.js
  installSupport({
    emptyCacheBetweenOperations: true,
    handleUncaughtExceptions: false,
    environment: 'node',
    retrieveSourceMap(source) {
      if (source === 'bundle.js' || source.endsWith('/bundle.js')) {
        return {
          url: 'bundle.js',
          map: sampleSourceMap,
        };
      }
      if (source === 'string-map.js' || source.endsWith('/string-map.js')) {
        return {
          url: 'string-map.js',
          map: JSON.stringify(sampleSourceMap),
        };
      }
      return null;
    },
  });

  // 1. sourceMapSupport.mapSourcePosition maps compiled file positions to original source files, lines, and columns using registered source maps
  assert.strictEqual(typeof sourceMapSupport.mapSourcePosition, 'function');
  assert.strictEqual(typeof mapSourcePosition, 'function');

  const mapped = mapSourcePosition('bundle.js', 1, 9);
  assert.strictEqual(typeof mapped, 'object');
  assert.ok(mapped !== null);
  assert.ok(
    mapped.source.endsWith('src/math.ts'),
    `Expected mapped source to end with src/math.ts, got ${mapped.source}`
  );
  assert.strictEqual(mapped.line, 1);
  assert.strictEqual(typeof mapped.column, 'number');

  // 2. sourceMapSupport.mapSourcePosition extracts original identifier name when mapped in source map names
  assert.strictEqual(mapped.name, 'add');

  // 3. sourceMapSupport.mapSourcePosition returns null name when the mapped position has no identifier name
  const mappedNoName = mapSourcePosition('bundle.js', 1, 0);
  assert.strictEqual(typeof mappedNoName, 'object');
  assert.ok(mappedNoName.source.endsWith('src/math.ts'));
  assert.strictEqual(mappedNoName.line, 1);
  assert.strictEqual(mappedNoName.name, null);

  // 4. sourceMapSupport.mapSourcePosition preserves unmapped position when no source map is registered for the source
  const unmapped = mapSourcePosition('unmapped-module.js', 42, 15);
  assert.strictEqual(unmapped.source, 'unmapped-module.js');
  assert.strictEqual(unmapped.line, 42);
  assert.strictEqual(unmapped.column, 15);

  // 5. sourceMapSupport.mapSourcePosition supports source map objects passed as JSON strings from retrieveSourceMap
  const mappedFromString = mapSourcePosition('string-map.js', 1, 9);
  assert.strictEqual(typeof mappedFromString, 'object');
  assert.ok(mappedFromString.source.endsWith('src/math.ts'));
  assert.strictEqual(mappedFromString.line, 1);
  assert.strictEqual(mappedFromString.name, 'add');

  // Clean up
  resetHandlers();

  console.log('Contract assertions passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

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

аноним