CodeSampleX

Sample

@types/esrecurse 4.3.1: traverse AST using esrecurse visit with custom visitor

Verified sample for npm @types/esrecurse 4.3.1: traverse AST using esrecurse visit with custom visitor. The contract ran on node 22 · linux alpine/x64 …

sha256:eddc9057c1000595375ae5f9a6df2c7b375e1c23034ab7b2f729e514d88bc39b

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
traverse AST using esrecurse visit with custom visitor
Packages
Symbols
  • Visitor
  • visit
Created
2026-08-27T17:30:20Z

Contract

  1. visit traverses standard ESTree AST and invokes node type callbacks on visitor object
  2. Visitor instance traverses child nodes recursively when this.visitChildren is invoked
  3. Visitor custom childVisitorKeys configuration enables traversal into custom AST node properties
  4. Visitor fallback iteration strategy traverses properties of unknown node types without throwing
  5. Visitor fallback function strategy extracts custom child property keys for unknown node types
  6. Visitor throws an error on unknown node types when no fallback strategy is provided
  7. visit handles null and undefined nodes gracefully without throwing errors

Files

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

Download the source artifact (tar.gz)

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: traverse AST using esrecurse visit with custom visitor
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40types/esrecurse@4.3.1
Demonstrate these symbols/APIs:
  - Visitor
  - visit

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:1f5aea46d4bd5112963944a29d1d46a8f84ea592659c5e6c1f538b0a803eaa23","contract":["visit traverses standard ESTree AST and invokes node type callbacks on visitor object","Visitor instance traverses child nodes recursively when this.visitChildren is invoked","Visitor custom childVisitorKeys configuration enables traversal into custom AST node properties","Visitor fallback iteration strategy traverses properties of unknown node types without throwing","Visitor fallback function strategy extracts custom child property keys for unknown node types","Visitor throws an error on unknown node types when no fallback strategy is provided","visit handles null and undefined nodes gracefully without throwing errors"],"goal":"traverse AST using esrecurse visit with custom visitor","kind":"HOW","packages":["pkg:npm/%40types/esrecurse@4.3.1"],"schemaVersion":1,"symbols":["Visitor","visit"]},"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/%40types/esrecurse@4.3.1"],"schemaVersion":1,"subject":"pkg:npm/%40types/esrecurse@4.3.1","symbols":["Visitor","visit"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-esrecurse",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-esrecurse",
      "version": "1.0.0",
      "dependencies": {
        "@types/esrecurse": "4.3.1",
        "esrecurse": "4.3.0"
      }
    },
    "node_modules/@types/esrecurse": {
      "version": "4.3.1",
      "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
      "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==",
      "license": "MIT"
    },
    "node_modules/esrecurse": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
      "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==",
      "license": "BSD-2-Clause",
      "dependencies": {
        "estraverse": "^5.2.0"
      },
      "engines": {
        "node": ">=4.0"
      }
    },
    "node_modules/estraverse": {
      "version": "5.3.0",
      "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
      "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=4.0"
      }
    }
  }
}
package.json
{
  "name": "sample-esrecurse",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@types/esrecurse": "4.3.1",
    "esrecurse": "4.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "traverse AST using esrecurse visit with custom visitor",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40types/esrecurse@4.3.1"
  ],
  "symbols": [
    "Visitor",
    "visit"
  ]
}
src/index.mjs
import { Visitor, visit } from "esrecurse";

/**
 * Traverses an AST with a visitor object and optional configuration.
 * @param {object} ast - The root AST node.
 * @param {object|Visitor} visitor - Visitor instance or object containing node type handlers.
 * @param {object} [options] - Visitor options (fallback, childVisitorKeys).
 */
export function traverseAST(ast, visitor, options) {
  visit(ast, visitor, options);
}

/**
 * Collects all identifier names from an AST.
 * @param {object} ast - The root AST node.
 * @returns {string[]} Array of identifier names.
 */
export function collectIdentifiers(ast) {
  const identifiers = [];
  visit(ast, {
    Identifier(node) {
      identifiers.push(node.name);
    },
  });
  return identifiers;
}

/**
 * Traverses an AST and records all visited node types in traversal order.
 * @param {object} ast - The root AST node.
 * @param {object} [options] - Visitor options.
 * @returns {string[]} Visited node types.
 */
export function collectNodeTypes(ast, options) {
  const visitedTypes = [];
  const visitor = new Visitor(
    {
      visit(node) {
        if (node && node.type) {
          visitedTypes.push(node.type);
        }
        this.visitChildren(node);
      },
    },
    options
  );
  visitor.visit(ast);
  return visitedTypes;
}

/**
 * Creates a custom AST visitor instance.
 * @param {object} [handlers] - Visitor handlers.
 * @param {object} [options] - Visitor configuration options.
 * @returns {Visitor} A new Visitor instance.
 */
export function createASTVisitor(handlers, options) {
  return new Visitor(handlers, options);
}

export { Visitor, visit };
test/contract.mjs
import assert from "node:assert/strict";
import {
  Visitor,
  visit,
  traverseAST,
  collectIdentifiers,
  collectNodeTypes,
  createASTVisitor,
} from "../src/index.mjs";

async function runContract() {
  const sampleAST = {
    type: "Program",
    body: [
      {
        type: "VariableDeclaration",
        kind: "const",
        declarations: [
          {
            type: "VariableDeclarator",
            id: { type: "Identifier", name: "sum" },
            init: {
              type: "BinaryExpression",
              operator: "+",
              left: { type: "Identifier", name: "a" },
              right: { type: "Literal", value: 10, raw: "10" },
            },
          },
        ],
      },
    ],
  };

  // 1. visit traverses standard ESTree AST and invokes node type callbacks on visitor object
  const visitedIdentifiers = [];
  const visitedLiterals = [];
  visit(sampleAST, {
    Identifier(node) {
      visitedIdentifiers.push(node.name);
    },
    Literal(node) {
      visitedLiterals.push(node.value);
    },
  });
  assert.deepEqual(visitedIdentifiers, ["sum", "a"]);
  assert.deepEqual(visitedLiterals, [10]);

  const collected = collectIdentifiers(sampleAST);
  assert.deepEqual(collected, ["sum", "a"]);

  // 2. Visitor instance traverses child nodes recursively when this.visitChildren is invoked
  const traversalLog = [];
  const customVisitor = new Visitor({
    VariableDeclaration(node) {
      traversalLog.push(`start:${node.kind}`);
      this.visitChildren(node);
      traversalLog.push(`end:${node.kind}`);
    },
    Identifier(node) {
      traversalLog.push(`id:${node.name}`);
    },
  });
  customVisitor.visit(sampleAST);
  assert.deepEqual(traversalLog, ["start:const", "id:sum", "id:a", "end:const"]);

  // 3. Visitor custom childVisitorKeys configuration enables traversal into custom AST node properties
  const customNodeAST = {
    type: "Program",
    body: [
      {
        type: "CustomJSXElement",
        openingElement: {
          type: "Identifier",
          name: "MyWidget",
        },
      },
    ],
  };
  const jsxIdentifiers = [];
  const jsxVisitor = createASTVisitor(
    {
      Identifier(node) {
        jsxIdentifiers.push(node.name);
      },
    },
    {
      childVisitorKeys: {
        CustomJSXElement: ["openingElement"],
      },
    }
  );
  jsxVisitor.visit(customNodeAST);
  assert.deepEqual(jsxIdentifiers, ["MyWidget"]);

  // 4. Visitor fallback iteration strategy traverses properties of unknown node types without throwing
  const unknownNodeAST = {
    type: "ExperimentalPipeline",
    pipelineInput: {
      type: "Identifier",
      name: "inputData",
    },
  };
  const fallbackIterationIdentifiers = [];
  visit(
    unknownNodeAST,
    {
      Identifier(node) {
        fallbackIterationIdentifiers.push(node.name);
      },
    },
    {
      fallback: "iteration",
    }
  );
  assert.deepEqual(fallbackIterationIdentifiers, ["inputData"]);

  // 5. Visitor fallback function strategy extracts custom child property keys for unknown node types
  const decoratedAST = {
    type: "CustomDecorator",
    targetIdentifier: {
      type: "Identifier",
      name: "authenticatedHandler",
    },
    ignoredProperty: {
      type: "Identifier",
      name: "ignoredData",
    },
  };
  const fallbackFunctionIdentifiers = [];
  visit(
    decoratedAST,
    {
      Identifier(node) {
        fallbackFunctionIdentifiers.push(node.name);
      },
    },
    {
      fallback: (node) => (node.type === "CustomDecorator" ? ["targetIdentifier"] : []),
    }
  );
  assert.deepEqual(fallbackFunctionIdentifiers, ["authenticatedHandler"]);

  // 6. Visitor throws an error on unknown node types when no fallback strategy is provided
  const unsupportedAST = {
    type: "UnsupportedUnknownNode",
    child: {
      type: "Identifier",
      name: "x",
    },
  };
  assert.throws(
    () => {
      visit(unsupportedAST, {
        Identifier(node) {
          // should not reach
        },
      });
    },
    {
      name: "Error",
      message: "Unknown node type UnsupportedUnknownNode.",
    }
  );

  // 7. visit handles null and undefined nodes gracefully without throwing errors
  assert.doesNotThrow(() => {
    visit(null);
    visit(undefined);
    traverseAST(null, {});
    const emptyVisitor = new Visitor();
    emptyVisitor.visit(null);
    emptyVisitor.visit(undefined);
  });

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

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

Origin Seeder

anonymous