CodeSampleX

Exemple

estree-walker 3.0.3: asyncWalk, walk

Échantillon vérifié pour npm estree-walker 3.0.3: asyncWalk, walk. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi.

sha256:131b1afee517902956631a0af938399939c41065efeacd6144545322f16cd137

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node linux 24 · ubuntu · glibc 2.39 x64 node node npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-26

Cas

HOW
Objectif
verify pkg:npm/estree-walker@3.0.3
Paquets
Symboles
  • asyncWalk
  • walk
Environnement
node
Créé
2026-08-26T08:29:13Z

Contrat

  1. walk exports a function that traverses an ESTree AST synchronously visiting nodes in enter and leave order
  2. walk this.skip skips descending into child nodes of the current AST node during enter traversal
  3. walk this.replace substitutes the matched AST node in the parent tree
  4. walk this.remove deletes the matched AST node from parent array
  5. asyncWalk exports a function that traverses an ESTree AST asynchronously supporting async visitor handlers
  6. asyncWalk this.replace and this.remove work asynchronously during traversal
  7. collectIdentifiers and findNodesAsync helper utilities traverse and query AST nodes using walk and asyncWalk

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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/estree-walker@3.0.3
Kind: HOW

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

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:be2f4e04eb17536aec4e1d8d76f389156d23de24a1a0f16ed14251e0d3178f27","contract":["walk exports a function that traverses an ESTree AST synchronously visiting nodes in enter and leave order","walk this.skip skips descending into child nodes of the current AST node during enter traversal","walk this.replace substitutes the matched AST node in the parent tree","walk this.remove deletes the matched AST node from parent array","asyncWalk exports a function that traverses an ESTree AST asynchronously supporting async visitor handlers","asyncWalk this.replace and this.remove work asynchronously during traversal","collectIdentifiers and findNodesAsync helper utilities traverse and query AST nodes using walk and asyncWalk"],"goal":"verify pkg:npm/estree-walker@3.0.3","kind":"HOW","packages":["pkg:npm/estree-walker@3.0.3"],"schemaVersion":1,"symbols":["asyncWalk","walk"]},"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@3.0.3"],"schemaVersion":1,"subject":"pkg:npm/estree-walker@3.0.3","symbols":["asyncWalk","walk"],"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": "3.0.3"
      }
    },
    "node_modules/@types/estree": {
      "version": "1.0.9",
      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
      "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
      "license": "MIT"
    },
    "node_modules/estree-walker": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
      "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "^1.0.0"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-estree-walker",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "estree-walker": "3.0.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/estree-walker@3.0.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/estree-walker@3.0.3"
  ],
  "symbols": [
    "asyncWalk",
    "walk"
  ]
}
src/index.mjs
import { walk, asyncWalk } from 'estree-walker';

export { walk, asyncWalk };

/**
 * Traverses an AST synchronously and collects all identifiers.
 *
 * @param {object} ast - The ESTree AST root node.
 * @returns {string[]} - Array of identifier names.
 */
export function collectIdentifiers(ast) {
  const names = [];
  walk(ast, {
    enter(node) {
      if (node.type === 'Identifier' && typeof node.name === 'string') {
        names.push(node.name);
      }
    },
  });
  return names;
}

/**
 * Traverses an AST and renames identifiers based on a lookup map.
 *
 * @param {object} ast - The ESTree AST root node.
 * @param {Record<string, string>} mapping - Mapping of old names to new names.
 * @returns {object} - The modified AST.
 */
export function renameIdentifiers(ast, mapping) {
  return walk(ast, {
    enter(node) {
      if (node.type === 'Identifier' && mapping[node.name]) {
        this.replace({
          ...node,
          name: mapping[node.name],
        });
      }
    },
  });
}

/**
 * Asynchronously traverses an AST and resolves metadata for specific nodes.
 *
 * @param {object} ast - The ESTree AST root node.
 * @param {(node: object) => Promise<boolean>} filter - Async filter predicate.
 * @returns {Promise<object[]>} - Matching nodes.
 */
export async function findNodesAsync(ast, filter) {
  const matches = [];
  await asyncWalk(ast, {
    async enter(node) {
      if (await filter(node)) {
        matches.push(node);
      }
    },
  });
  return matches;
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  walk,
  asyncWalk,
  collectIdentifiers,
  renameIdentifiers,
  findNodesAsync,
} from '../src/index.mjs';

// 1. Verify walk export and synchronous AST traversal in enter and leave order
assert.equal(typeof walk, 'function');
assert.equal(typeof asyncWalk, 'function');

const sampleAst = {
  type: 'Program',
  body: [
    {
      type: 'VariableDeclaration',
      declarations: [
        {
          type: 'VariableDeclarator',
          id: { type: 'Identifier', name: 'x' },
          init: { type: 'Literal', value: 42 },
        },
      ],
      kind: 'const',
    },
  ],
};

const entered = [];
const left = [];
walk(sampleAst, {
  enter(node) {
    entered.push(node.type);
  },
  leave(node) {
    left.push(node.type);
  },
});

assert.deepEqual(entered, ['Program', 'VariableDeclaration', 'VariableDeclarator', 'Identifier', 'Literal']);
assert.deepEqual(left, ['Identifier', 'Literal', 'VariableDeclarator', 'VariableDeclaration', 'Program']);

// 2. Verify walk this.skip skips descending into child nodes of current AST node
const astSkip = {
  type: 'Program',
  body: [
    {
      type: 'FunctionDeclaration',
      id: { type: 'Identifier', name: 'foo' },
      body: {
        type: 'BlockStatement',
        body: [
          { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'bar' } },
        ],
      },
    },
  ],
};

const visitedTypes = [];
walk(astSkip, {
  enter(node) {
    visitedTypes.push(node.type);
    if (node.type === 'BlockStatement') {
      this.skip();
    }
  },
});

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

// 3. Verify walk this.replace substitutes the matched AST node in parent tree
const astReplace = {
  type: 'Program',
  body: [
    {
      type: 'ExpressionStatement',
      expression: { type: 'Identifier', name: 'oldVar' },
    },
  ],
};

renameIdentifiers(astReplace, { oldVar: 'newVar' });
assert.equal(astReplace.body[0].expression.name, 'newVar');

// 4. Verify walk this.remove deletes the matched AST node from parent array
const astRemove = {
  type: 'Program',
  body: [
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'keepFirst' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'removeMe' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'keepLast' } },
  ],
};

walk(astRemove, {
  enter(node) {
    if (node.type === 'ExpressionStatement' && node.expression.name === 'removeMe') {
      this.remove();
    }
  },
});

assert.equal(astRemove.body.length, 2);
assert.equal(astRemove.body[0].expression.name, 'keepFirst');
assert.equal(astRemove.body[1].expression.name, 'keepLast');

// 5. Verify asyncWalk traverses an ESTree AST asynchronously supporting async visitor handlers
const astAsync = {
  type: 'Program',
  body: [
    {
      type: 'VariableDeclaration',
      declarations: [
        {
          type: 'VariableDeclarator',
          id: { type: 'Identifier', name: 'alpha' },
          init: { type: 'Literal', value: 100 },
        },
      ],
      kind: 'let',
    },
  ],
};

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

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

// 6. Verify asyncWalk this.replace and this.remove work asynchronously during traversal
const astAsyncMod = {
  type: 'Program',
  body: [
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'targetAsync' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'dropAsync' } },
  ],
};

await asyncWalk(astAsyncMod, {
  async enter(node) {
    await new Promise((resolve) => setTimeout(resolve, 1));
    if (node.type === 'Identifier' && node.name === 'targetAsync') {
      this.replace({ type: 'Identifier', name: 'updatedAsync' });
    }
    if (node.type === 'ExpressionStatement' && node.expression && node.expression.name === 'dropAsync') {
      this.remove();
    }
  },
});

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

// 7. Verify helper functions work as expected
const idAst = {
  type: 'Program',
  body: [
    {
      type: 'VariableDeclaration',
      declarations: [
        {
          type: 'VariableDeclarator',
          id: { type: 'Identifier', name: 'first' },
          init: { type: 'Identifier', name: 'second' },
        },
      ],
      kind: 'const',
    },
  ],
};
const identifiers = collectIdentifiers(idAst);
assert.deepEqual(identifiers, ['first', 'second']);

const asyncNodes = await findNodesAsync(idAst, async (n) => n.type === 'Identifier');
assert.equal(asyncNodes.length, 2);

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

Seeder d'origine

anonyme