CodeSampleX

Пример

estree-walker 2.0.2: asyncWalk

Проверенный пример — npm estree-walker 2.0.2: asyncWalk. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: asyncWalk exports an async…

sha256:9232cb8a58d41c5af9ab876e2320611af031c33ee2a1f75fba35d6a82c2e7902

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node linux 24 · ubuntu · glibc 2.39 x64 node node 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-07

Кейс

HOW
Цель
verify estree-walker.asyncWalk in pkg:npm/estree-walker@2.0.2
Пакеты
Символы
  • estree-walker.asyncWalk
Окружение
node
Создан
2026-09-07T01:43:05Z

Контракт

  1. asyncWalk exports an async function that traverses an ESTree AST asynchronously
  2. asyncWalk visits AST nodes in enter and leave order asynchronously
  3. asyncWalk passes node, parent, prop, and index to visitor handlers
  4. asyncWalk this.skip skips descending into child nodes of current AST node
  5. asyncWalk this.replace substitutes matched AST node in parent structure asynchronously
  6. asyncWalk this.remove deletes matched AST node from parent array asynchronously
  7. filterNodesAsync and transformNodesAsync helper utilities query and mutate AST nodes using asyncWalk

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 estree-walker.asyncWalk in pkg:npm/estree-walker@2.0.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/estree-walker@2.0.2
Demonstrate these symbols/APIs:
  - estree-walker.asyncWalk

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:65b410545ce9acb95dc38eb081dbcefa5a49a6713cc67df0e55aeb226ed1323e","contract":["asyncWalk exports an async function that traverses an ESTree AST asynchronously","asyncWalk visits AST nodes in enter and leave order asynchronously","asyncWalk passes node, parent, prop, and index to visitor handlers","asyncWalk this.skip skips descending into child nodes of current AST node","asyncWalk this.replace substitutes matched AST node in parent structure asynchronously","asyncWalk this.remove deletes matched AST node from parent array asynchronously","filterNodesAsync and transformNodesAsync helper utilities query and mutate AST nodes using asyncWalk"],"goal":"verify estree-walker.asyncWalk in pkg:npm/estree-walker@2.0.2","kind":"HOW","packages":["pkg:npm/estree-walker@2.0.2"],"schemaVersion":1,"symbols":["estree-walker.asyncWalk"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"node","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/estree-walker@2.0.2"],"schemaVersion":1,"subject":"pkg:npm/estree-walker@2.0.2","symbols":["estree-walker.asyncWalk"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-estree-walker",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-estree-walker",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "estree-walker": "2.0.2"
      }
    },
    "node_modules/estree-walker": {
      "version": "2.0.2",
      "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
      "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "csx-sample-estree-walker",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "estree-walker": "2.0.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify estree-walker.asyncWalk in pkg:npm/estree-walker@2.0.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/estree-walker@2.0.2"
  ],
  "symbols": [
    "estree-walker.asyncWalk"
  ]
}
src/index.mjs
import { asyncWalk } from 'estree-walker';

export { asyncWalk };

/**
 * Traverses an ESTree AST asynchronously and collects nodes matching an async predicate.
 *
 * @param {object} ast - The AST root node.
 * @param {(node: object, parent: object | null) => Promise<boolean>} predicate - Async test function.
 * @returns {Promise<object[]>} Matching AST nodes.
 */
export async function filterNodesAsync(ast, predicate) {
  const matches = [];
  await asyncWalk(ast, {
    async enter(node, parent) {
      if (await predicate(node, parent)) {
        matches.push(node);
      }
    },
  });
  return matches;
}

/**
 * Transforms an ESTree AST asynchronously by applying an async replacer function.
 *
 * @param {object} ast - The AST root node.
 * @param {(node: object) => Promise<object | null | undefined>} transform - Async transformer returning replacement node, or null to remove.
 * @returns {Promise<object | null>} The transformed AST.
 */
export async function transformNodesAsync(ast, transform) {
  return await asyncWalk(ast, {
    async enter(node) {
      const result = await transform(node);
      if (result === null) {
        this.remove();
      } else if (result !== undefined && result !== node) {
        this.replace(result);
      }
    },
  });
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { asyncWalk, filterNodesAsync, transformNodesAsync } from '../src/index.mjs';

// 1. Verify asyncWalk is exported as a function
assert.equal(typeof asyncWalk, 'function');

// 2. Verify asyncWalk visits AST nodes in enter and leave order asynchronously
const sampleAst = {
  type: 'Program',
  body: [
    {
      type: 'VariableDeclaration',
      declarations: [
        {
          type: 'VariableDeclarator',
          id: { type: 'Identifier', name: 'count' },
          init: { type: 'Literal', value: 10 },
        },
      ],
      kind: 'const',
    },
  ],
};

const enterSequence = [];
const leaveSequence = [];
await asyncWalk(sampleAst, {
  async enter(node) {
    await new Promise((resolve) => setTimeout(resolve, 1));
    enterSequence.push(node.type);
  },
  async leave(node) {
    await new Promise((resolve) => setTimeout(resolve, 1));
    leaveSequence.push(node.type);
  },
});

assert.deepEqual(enterSequence, [
  'Program',
  'VariableDeclaration',
  'VariableDeclarator',
  'Identifier',
  'Literal',
]);
assert.deepEqual(leaveSequence, [
  'Identifier',
  'Literal',
  'VariableDeclarator',
  'VariableDeclaration',
  'Program',
]);

// 3. Verify enter handler receives node, parent, prop, and index
let identifierParentType = null;
let identifierProp = null;
let identifierIndex = null;

await asyncWalk(sampleAst, {
  async enter(node, parent, prop, index) {
    if (node.type === 'Identifier') {
      identifierParentType = parent?.type;
      identifierProp = prop;
      identifierIndex = index;
    }
  },
});

assert.equal(identifierParentType, 'VariableDeclarator');
assert.equal(identifierProp, 'id');
assert.equal(identifierIndex, null);

// 4. Verify this.skip skips descending into child nodes during asyncWalk
const skipAst = {
  type: 'Program',
  body: [
    {
      type: 'FunctionDeclaration',
      id: { type: 'Identifier', name: 'calculate' },
      body: {
        type: 'BlockStatement',
        body: [
          { type: 'ReturnStatement', argument: { type: 'Literal', value: 1 } },
        ],
      },
    },
  ],
};

const visitedInSkip = [];
await asyncWalk(skipAst, {
  async enter(node) {
    visitedInSkip.push(node.type);
    if (node.type === 'BlockStatement') {
      this.skip();
    }
  },
});

assert.deepEqual(visitedInSkip, [
  'Program',
  'FunctionDeclaration',
  'Identifier',
  'BlockStatement',
]);

// 5. Verify this.replace substitutes matched node asynchronously
const replaceAst = {
  type: 'Program',
  body: [
    {
      type: 'ExpressionStatement',
      expression: { type: 'Identifier', name: 'beforeReplace' },
    },
  ],
};

await asyncWalk(replaceAst, {
  async enter(node) {
    if (node.type === 'Identifier' && node.name === 'beforeReplace') {
      await new Promise((resolve) => setTimeout(resolve, 1));
      this.replace({ type: 'Identifier', name: 'afterReplace' });
    }
  },
});

assert.equal(replaceAst.body[0].expression.name, 'afterReplace');

// 6. Verify this.remove deletes matched node from parent array asynchronously
const removeAst = {
  type: 'Program',
  body: [
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'a' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'b' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'c' } },
  ],
};

await asyncWalk(removeAst, {
  async enter(node) {
    if (node.type === 'ExpressionStatement' && node.expression?.name === 'b') {
      await new Promise((resolve) => setTimeout(resolve, 1));
      this.remove();
    }
  },
});

assert.equal(removeAst.body.length, 2);
assert.equal(removeAst.body[0].expression.name, 'a');
assert.equal(removeAst.body[1].expression.name, 'c');

// 7. Verify helper functions filterNodesAsync and transformNodesAsync
const foundIdentifiers = await filterNodesAsync(sampleAst, async (n) => n.type === 'Identifier');
assert.equal(foundIdentifiers.length, 1);
assert.equal(foundIdentifiers[0].name, 'count');

const astToTransform = {
  type: 'Program',
  body: [
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'target' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'obsolete' } },
  ],
};

await transformNodesAsync(astToTransform, async (node) => {
  if (node.type === 'Identifier' && node.name === 'target') {
    return { type: 'Identifier', name: 'transformed' };
  }
  if (node.type === 'ExpressionStatement' && node.expression?.name === 'obsolete') {
    return null;
  }
});

assert.equal(astToTransform.body.length, 1);
assert.equal(astToTransform.body[0].expression.name, 'transformed');

console.log('CONTRACT PASS: estree-walker.asyncWalk verified');

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

аноним