CodeSampleX

Пример

@babel/types 7.29.8: cloneNode

Проверенный пример — npm @babel/types 7.29.8: cloneNode. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: types.cloneNode produces an…

sha256:adb78833022763ebc8c5198be4c2cefd5009b092bea28bb94005d24f4a733e10

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

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

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

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

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

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

Кейс

HOW
Цель
verify @babel/types.cloneNode in pkg:npm/%40babel/types@7.29.8
Пакеты
Символы
  • @babel/types.cloneNode
Создан
2026-08-23T04:31:24Z

Контракт

  1. types.cloneNode produces an independent deep copy of an AST node with structural equivalence
  2. types.cloneNode deeply clones nested children such that mutating a clone does not mutate the original AST
  3. types.cloneNode supports shallow cloning when deep is false, preserving references to child nodes
  4. types.cloneNode strips location metadata (loc, start, end) when withoutLoc is true
  5. types.cloneNode safely handles null and undefined inputs by returning them unchanged
  6. types.cloneNode duplicates complex AST nodes including function declarations, binary expressions, and variable declarations

Файлы

  • 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 @babel/types.cloneNode in pkg:npm/%40babel/types@7.29.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40babel/types@7.29.8
Demonstrate these symbols/APIs:
  - @babel/types.cloneNode

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:21b3c32f3f03466b1efa93a631fb7110f05436f22bdfc55ab34d3f676d7df60c","contract":["types.cloneNode produces an independent deep copy of an AST node with structural equivalence","types.cloneNode deeply clones nested children such that mutating a clone does not mutate the original AST","types.cloneNode supports shallow cloning when deep is false, preserving references to child nodes","types.cloneNode strips location metadata (loc, start, end) when withoutLoc is true","types.cloneNode safely handles null and undefined inputs by returning them unchanged","types.cloneNode duplicates complex AST nodes including function declarations, binary expressions, and variable declarations"],"goal":"verify @babel/types.cloneNode in pkg:npm/%40babel/types@7.29.8","kind":"HOW","packages":["pkg:npm/%40babel/types@7.29.8"],"schemaVersion":1,"symbols":["@babel/types.cloneNode"]},"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/%40babel/types@7.29.8"],"schemaVersion":1,"subject":"pkg:npm/%40babel/types@7.29.8","symbols":["@babel/types.cloneNode"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-babel-types-clonenode",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-babel-types-clonenode",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@babel/types": "7.29.8"
      }
    },
    "node_modules/@babel/helper-string-parser": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
      "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/types": {
      "version": "7.29.8",
      "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
      "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-string-parser": "^7.29.7",
        "@babel/helper-validator-identifier": "^7.29.7"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-babel-types-clonenode",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @babel/types.cloneNode",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@babel/types": "7.29.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @babel/types.cloneNode in pkg:npm/%40babel/types@7.29.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40babel/types@7.29.8"
  ],
  "symbols": [
    "@babel/types.cloneNode"
  ]
}
src/index.js
const t = require('@babel/types');

/**
 * Deeply clones an AST node.
 * @param {object} node
 * @returns {object}
 */
function cloneNodeDeep(node) {
  return t.cloneNode(node, true);
}

/**
 * Shallowly clones an AST node without recursively cloning child nodes.
 * @param {object} node
 * @returns {object}
 */
function cloneNodeShallow(node) {
  return t.cloneNode(node, false);
}

/**
 * Clones an AST node while stripping location information (loc, start, end).
 * @param {object} node
 * @param {boolean} [deep=true]
 * @returns {object}
 */
function cloneNodeWithoutLoc(node, deep = true) {
  return t.cloneNode(node, deep, true);
}

/**
 * Creates a binary expression AST node.
 * @param {string} operator
 * @param {object} left
 * @param {object} right
 * @returns {object}
 */
function createBinaryExpression(operator, left, right) {
  return t.binaryExpression(operator, left, right);
}

/**
 * Creates a function declaration AST node with a body and parameters.
 * @param {string} name
 * @param {string[]} paramNames
 * @param {object[]} bodyStatements
 * @returns {object}
 */
function createFunctionDeclaration(name, paramNames, bodyStatements) {
  const id = t.identifier(name);
  const params = paramNames.map((p) => t.identifier(p));
  const body = t.blockStatement(bodyStatements);
  return t.functionDeclaration(id, params, body);
}

/**
 * Checks if two AST nodes are structurally equivalent.
 * @param {object} a
 * @param {object} b
 * @returns {boolean}
 */
function areNodesEquivalent(a, b) {
  return t.isNodesEquivalent(a, b);
}

module.exports = {
  t,
  cloneNodeDeep,
  cloneNodeShallow,
  cloneNodeWithoutLoc,
  createBinaryExpression,
  createFunctionDeclaration,
  areNodesEquivalent,
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  t,
  cloneNodeDeep,
  cloneNodeShallow,
  cloneNodeWithoutLoc,
  createBinaryExpression,
  createFunctionDeclaration,
  areNodesEquivalent,
} = require('../src/index.js');

async function runContract() {
  // 1. types.cloneNode produces an independent deep copy of an AST node with structural equivalence
  const idNode = t.identifier('counter');
  const clonedId = cloneNodeDeep(idNode);
  assert.notStrictEqual(clonedId, idNode, 'Cloned node must have distinct object identity');
  assert.strictEqual(clonedId.type, 'Identifier');
  assert.strictEqual(clonedId.name, 'counter');
  assert.strictEqual(areNodesEquivalent(clonedId, idNode), true);

  const numNode = t.numericLiteral(100);
  const clonedNum = t.cloneNode(numNode);
  assert.notStrictEqual(clonedNum, numNode);
  assert.strictEqual(clonedNum.type, 'NumericLiteral');
  assert.strictEqual(clonedNum.value, 100);
  assert.strictEqual(areNodesEquivalent(clonedNum, numNode), true);

  // 2. types.cloneNode deeply clones nested children such that mutating a clone does not mutate the original AST
  const originalBinary = createBinaryExpression('+', t.identifier('a'), t.numericLiteral(5));
  const deepClonedBinary = cloneNodeDeep(originalBinary);

  assert.notStrictEqual(deepClonedBinary, originalBinary);
  assert.notStrictEqual(deepClonedBinary.left, originalBinary.left, 'Deep clone child node must have distinct reference');
  assert.notStrictEqual(deepClonedBinary.right, originalBinary.right, 'Deep clone child node must have distinct reference');
  assert.strictEqual(areNodesEquivalent(deepClonedBinary, originalBinary), true);

  // Mutate clone child and ensure original is unaffected
  deepClonedBinary.left.name = 'modifiedVar';
  assert.strictEqual(originalBinary.left.name, 'a', 'Original node child must not be affected by clone modification');
  assert.strictEqual(deepClonedBinary.left.name, 'modifiedVar');

  // 3. types.cloneNode supports shallow cloning when deep is false, preserving references to child nodes
  const leftNode = t.identifier('b');
  const rightNode = t.numericLiteral(10);
  const binaryForShallow = createBinaryExpression('*', leftNode, rightNode);
  const shallowClonedBinary = cloneNodeShallow(binaryForShallow);

  assert.notStrictEqual(shallowClonedBinary, binaryForShallow, 'Shallow clone root must have distinct reference');
  assert.strictEqual(shallowClonedBinary.left, binaryForShallow.left, 'Shallow clone must share child node references');
  assert.strictEqual(shallowClonedBinary.right, binaryForShallow.right, 'Shallow clone must share child node references');

  // Mutating child via shallow clone affects original child reference
  shallowClonedBinary.left.name = 'mutatedB';
  assert.strictEqual(binaryForShallow.left.name, 'mutatedB');

  // 4. types.cloneNode strips location metadata (loc, start, end) when withoutLoc is true
  const nodeWithLoc = t.identifier('myVariable');
  nodeWithLoc.loc = {
    start: { line: 1, column: 0 },
    end: { line: 1, column: 10 },
  };
  nodeWithLoc.start = 0;
  nodeWithLoc.end = 10;
  nodeWithLoc.leadingComments = [{ type: 'CommentLine', value: ' banner comment' }];

  const strippedNode = cloneNodeWithoutLoc(nodeWithLoc, true);
  assert.notStrictEqual(strippedNode, nodeWithLoc);
  assert.strictEqual(strippedNode.name, 'myVariable');
  assert.strictEqual(strippedNode.loc, null, 'Location object must be reset to null');
  assert.strictEqual(strippedNode.start, undefined, 'Start offset must be stripped');
  assert.strictEqual(strippedNode.end, undefined, 'End offset must be stripped');

  // Verify original node preserved its location metadata
  assert.strictEqual(nodeWithLoc.start, 0);
  assert.strictEqual(nodeWithLoc.loc.start.line, 1);

  // 5. types.cloneNode safely handles null and undefined inputs by returning them unchanged
  assert.strictEqual(t.cloneNode(null), null);
  assert.strictEqual(t.cloneNode(undefined), undefined);
  assert.strictEqual(cloneNodeDeep(null), null);
  assert.strictEqual(cloneNodeWithoutLoc(undefined), undefined);

  // 6. types.cloneNode duplicates complex AST nodes including function declarations, binary expressions, and variable declarations
  const returnExpr = createBinaryExpression('+', t.identifier('x'), t.identifier('y'));
  const fnDecl = createFunctionDeclaration('sum', ['x', 'y'], [t.returnStatement(returnExpr)]);

  const clonedFn = t.cloneNode(fnDecl);
  assert.notStrictEqual(clonedFn, fnDecl);
  assert.notStrictEqual(clonedFn.id, fnDecl.id);
  assert.notStrictEqual(clonedFn.params[0], fnDecl.params[0]);
  assert.notStrictEqual(clonedFn.params[1], fnDecl.params[1]);
  assert.notStrictEqual(clonedFn.body, fnDecl.body);
  assert.strictEqual(clonedFn.id.name, 'sum');
  assert.strictEqual(clonedFn.params.length, 2);
  assert.strictEqual(areNodesEquivalent(clonedFn, fnDecl), true);

  const varDecl = t.variableDeclaration('const', [
    t.variableDeclarator(t.identifier('total'), clonedFn.id),
  ]);
  const clonedVarDecl = t.cloneNode(varDecl);
  assert.notStrictEqual(clonedVarDecl, varDecl);
  assert.strictEqual(clonedVarDecl.kind, 'const');
  assert.strictEqual(areNodesEquivalent(clonedVarDecl, varDecl), true);

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

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

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

аноним