CodeSampleX

Exemplo

typescript 5.9.3: Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3

Amostra verificada para npm typescript 5.9.3: Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3. O…

sha256:250f4f22e83d2d557c8444be328d462f4f7bbe1801321479b92b3a720c225353

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node linux 24 · ubuntu · glibc 2.39 x64 node node npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3
Pacotes
Símbolos
  • ts.createPrinter
  • ts.createSourceFile
  • ts.factory
  • ts.transform
  • ts.visitEachChild
Ambiente
node
Criado
2026-08-27T18:56:50Z

Contrato

  1. ts.createSourceFile parses TypeScript code into an AST SourceFile with statements and syntax kinds
  2. ts.transform applies custom TransformerFactory functions to rewrite AST nodes during compilation pipeline
  3. ts.visitEachChild recursively traverses AST child nodes and returns updated parent nodes when children are transformed
  4. ts.factory and TransformationContext.factory create and update AST nodes including identifiers, binary expressions, and call expressions
  5. ts.createPrinter formats transformed AST SourceFile and nodes back to valid TypeScript/JavaScript code
  6. TransformationResult.dispose releases transformation context and allocated AST resources after transformation

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# TypeScript AST Transformation with `ts.transform`, `ts.factory`, and `ts.createPrinter`

## Pinned Version
- `typescript`: `5.9.3`

## Symbols Demonstrated
- `ts.createSourceFile`
- `ts.transform`
- `ts.visitEachChild`
- `ts.factory`
- `ts.createPrinter`

## Overview & Architecture
In TypeScript 5.x, AST transformations are performed using `ts.transform` along with custom `TransformerFactory` instances. Nodes are traversed using `ts.visitEachChild`, and updated/synthesized nodes are constructed using `context.factory` (or `ts.factory`).

### Key Mechanics
1. **AST Parsing (`ts.createSourceFile`)**:
   Converts code strings into a structured AST SourceFile with statements and syntax tokens.

2. **AST Traversal (`ts.visitEachChild`)**:
   Recursively visits all child nodes of a given AST node. If any child is modified, a new parent node is returned automatically without mutating the original tree.

3. **Node Factory (`context.factory` / `ts.factory`)**:
   Provides methods to create new nodes (e.g. `factory.createIdentifier`, `factory.createToken`, `factory.createCallExpression`) and update existing nodes (`factory.updateBinaryExpression`).

4. **AST Printing (`ts.createPrinter`)**:
   Formats an AST SourceFile or individual node back to JavaScript/TypeScript text, handling comment preservation and indentation.

5. **Lifecycle Management (`TransformationResult.dispose`)**:
   Frees memory and cleans up internal compiler transformation caches.
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: Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@5.9.3
Demonstrate these symbols/APIs:
  - ts.createPrinter
  - ts.createSourceFile
  - ts.factory
  - ts.transform
  - ts.visitEachChild

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:4a4efa02a454be25a06f0f2150fb074f263fd6bcc22cbe530836ca2eec28f804","contract":["ts.createSourceFile parses TypeScript code into an AST SourceFile with statements and syntax kinds","ts.transform applies custom TransformerFactory functions to rewrite AST nodes during compilation pipeline","ts.visitEachChild recursively traverses AST child nodes and returns updated parent nodes when children are transformed","ts.factory and TransformationContext.factory create and update AST nodes including identifiers, binary expressions, and call expressions","ts.createPrinter formats transformed AST SourceFile and nodes back to valid TypeScript/JavaScript code","TransformationResult.dispose releases transformation context and allocated AST resources after transformation"],"goal":"Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3","kind":"HOW","packages":["pkg:npm/typescript@5.9.3"],"schemaVersion":1,"symbols":["ts.createPrinter","ts.createSourceFile","ts.factory","ts.transform","ts.visitEachChild"]},"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/typescript@5.9.3"],"schemaVersion":1,"subject":"pkg:npm/typescript@5.9.3","symbols":["ts.createPrinter","ts.createSourceFile","ts.factory","ts.transform","ts.visitEachChild"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-typescript-ast-transform-5-9-3",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-typescript-ast-transform-5-9-3",
      "version": "1.0.0",
      "dependencies": {
        "typescript": "5.9.3"
      }
    },
    "node_modules/typescript": {
      "version": "5.9.3",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc",
        "tsserver": "bin/tsserver"
      },
      "engines": {
        "node": ">=14.17"
      }
    }
  }
}
package.json
{
  "name": "npm-typescript-ast-transform-5-9-3",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "typescript": "5.9.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Transform TypeScript AST nodes using ts.transform, ts.factory, and ts.createPrinter in TypeScript 5.9.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@5.9.3"
  ],
  "symbols": [
    "ts.createPrinter",
    "ts.createSourceFile",
    "ts.factory",
    "ts.transform",
    "ts.visitEachChild"
  ]
}
src/index.mjs
import ts from 'typescript';

/**
 * Parse TypeScript source code string into an AST SourceFile.
 * @param {string} code
 * @param {string} [fileName='source.ts']
 * @param {ts.ScriptTarget} [target=ts.ScriptTarget.ES2022]
 * @returns {ts.SourceFile}
 */
export function parseSource(code, fileName = 'source.ts', target = ts.ScriptTarget.ES2022) {
  return ts.createSourceFile(fileName, code, target, true, ts.ScriptKind.TS);
}

/**
 * Print an AST node or source file back to source code string.
 * @param {ts.SourceFile | ts.Node} nodeOrFile
 * @param {ts.PrinterOptions} [options={}]
 * @param {ts.SourceFile} [sourceFile]
 * @returns {string}
 */
export function printSource(nodeOrFile, options = {}, sourceFile = undefined) {
  const printer = ts.createPrinter({
    newLine: ts.NewLineKind.LineFeed,
    removeComments: false,
    ...options,
  });

  if (ts.isSourceFile(nodeOrFile)) {
    return printer.printFile(nodeOrFile);
  }

  return printer.printNode(
    ts.EmitHint.Unspecified,
    nodeOrFile,
    sourceFile || parseSource('', 'hint.ts')
  );
}

/**
 * Creates a transformer factory that renames identifiers according to a mapping.
 * @param {Record<string, string>} renameMap
 * @returns {ts.TransformerFactory<ts.SourceFile>}
 */
export function createIdentifierRenamerTransformer(renameMap) {
  return (context) => {
    const factory = context.factory;
    return (sourceFile) => {
      const visitor = (node) => {
        if (ts.isIdentifier(node) && Object.prototype.hasOwnProperty.call(renameMap, node.text)) {
          const newName = renameMap[node.text];
          return factory.createIdentifier(newName);
        }
        return ts.visitEachChild(node, visitor, context);
      };
      return ts.visitEachChild(sourceFile, visitor, context);
    };
  };
}

/**
 * Creates a transformer factory that replaces specified binary operator tokens.
 * @param {ts.SyntaxKind} fromKind
 * @param {ts.SyntaxKind} toKind
 * @returns {ts.TransformerFactory<ts.SourceFile>}
 */
export function createBinaryOperatorReplacerTransformer(fromKind, toKind) {
  return (context) => {
    const factory = context.factory;
    return (sourceFile) => {
      const visitor = (node) => {
        if (ts.isBinaryExpression(node) && node.operatorToken.kind === fromKind) {
          const updated = factory.updateBinaryExpression(
            node,
            node.left,
            factory.createToken(toKind),
            node.right
          );
          return ts.visitEachChild(updated, visitor, context);
        }
        return ts.visitEachChild(node, visitor, context);
      };
      return ts.visitEachChild(sourceFile, visitor, context);
    };
  };
}

/**
 * Creates a transformer factory that wraps numeric literals with a function call.
 * @param {string} wrapperName
 * @returns {ts.TransformerFactory<ts.SourceFile>}
 */
export function createNumericLiteralWrapperTransformer(wrapperName) {
  return (context) => {
    const factory = context.factory;
    return (sourceFile) => {
      const visitor = (node) => {
        if (ts.isNumericLiteral(node)) {
          return factory.createCallExpression(
            factory.createIdentifier(wrapperName),
            undefined,
            [factory.createNumericLiteral(node.text)]
          );
        }
        return ts.visitEachChild(node, visitor, context);
      };
      return ts.visitEachChild(sourceFile, visitor, context);
    };
  };
}

/**
 * Transform an AST SourceFile using ts.transform and return the result.
 * @param {ts.SourceFile} sourceFile
 * @param {ts.TransformerFactory<ts.SourceFile>[]} transformers
 * @param {ts.CompilerOptions} [compilerOptions={}]
 * @returns {{ transformedSourceFile: ts.SourceFile, diagnostics: readonly ts.Diagnostic[] | undefined, dispose: () => void }}
 */
export function transformSource(sourceFile, transformers, compilerOptions = {}) {
  const result = ts.transform(sourceFile, transformers, compilerOptions);
  return {
    transformedSourceFile: result.transformed[0],
    diagnostics: result.diagnostics,
    dispose: () => result.dispose(),
  };
}

export { ts };
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  ts,
  parseSource,
  printSource,
  createIdentifierRenamerTransformer,
  createBinaryOperatorReplacerTransformer,
  createNumericLiteralWrapperTransformer,
  transformSource,
} from '../src/index.mjs';

// 1. Verify requested symbol availability on TypeScript 5.9.3
assert.strictEqual(typeof ts.createPrinter, 'function', 'ts.createPrinter must be a function');
assert.strictEqual(typeof ts.createSourceFile, 'function', 'ts.createSourceFile must be a function');
assert.strictEqual(typeof ts.factory, 'object', 'ts.factory must be an object');
assert.strictEqual(typeof ts.transform, 'function', 'ts.transform must be a function');
assert.strictEqual(typeof ts.visitEachChild, 'function', 'ts.visitEachChild must be a function');

// 2. Verify AST parsing with ts.createSourceFile
const sampleCode = `
const initialValue: number = 42;
const isThreshold: boolean = initialValue === 42;
function compute(delta: number): number {
  return initialValue + delta;
}
`;

const sourceFile = parseSource(sampleCode, 'test.ts', ts.ScriptTarget.ES2022);
assert.strictEqual(sourceFile.kind, ts.SyntaxKind.SourceFile, 'Parsed node must be a SourceFile');
assert.strictEqual(sourceFile.fileName, 'test.ts', 'SourceFile must retain specified fileName');
assert.strictEqual(sourceFile.statements.length, 3, 'SourceFile must parse exactly 3 top-level statements');

// 3. Verify identifier renaming transformation using ts.transform and ts.visitEachChild
const renameMap = {
  initialValue: 'baseValue',
  isThreshold: 'hasReachedLimit',
};

const renameResult = transformSource(sourceFile, [createIdentifierRenamerTransformer(renameMap)]);
assert.ok(renameResult.transformedSourceFile, 'Transform result must contain transformed SourceFile');

const renamedOutput = printSource(renameResult.transformedSourceFile);
assert.ok(renamedOutput.includes('const baseValue: number = 42;'), 'Transformed code must contain renamed variable');
assert.ok(renamedOutput.includes('const hasReachedLimit: boolean = baseValue === 42;'), 'Variable references must be renamed');
assert.ok(renamedOutput.includes('return baseValue + delta;'), 'Function body references must be renamed');
assert.ok(!renamedOutput.includes('initialValue'), 'Original identifier name must not remain in output');
renameResult.dispose();

// 4. Verify binary expression modification using factory.updateBinaryExpression
const equalitySource = parseSource('const check = a === b;', 'equal.ts');
const operatorResult = transformSource(equalitySource, [
  createBinaryOperatorReplacerTransformer(
    ts.SyntaxKind.EqualsEqualsEqualsToken,
    ts.SyntaxKind.ExclamationEqualsEqualsToken
  ),
]);

const operatorOutput = printSource(operatorResult.transformedSourceFile);
assert.strictEqual(operatorOutput.trim(), 'const check = a !== b;', '=== must be transformed to !==');
operatorResult.dispose();

// 5. Verify call expression wrapping using factory.createCallExpression
const literalSource = parseSource('const num = 100;', 'literal.ts');
const wrapperResult = transformSource(literalSource, [
  createNumericLiteralWrapperTransformer('customWrap'),
]);

const wrapperOutput = printSource(wrapperResult.transformedSourceFile);
assert.strictEqual(wrapperOutput.trim(), 'const num = customWrap(100);', 'Numeric literal must be wrapped in customWrap');
wrapperResult.dispose();

// 6. Verify chained transformations in a single pipeline
const pipelineSource = parseSource('const initialValue: number = 42; const flag = initialValue === 42;', 'chain.ts');
const chainedResult = transformSource(pipelineSource, [
  createIdentifierRenamerTransformer({ initialValue: 'totalCount', flag: 'isMatch' }),
  createBinaryOperatorReplacerTransformer(
    ts.SyntaxKind.EqualsEqualsEqualsToken,
    ts.SyntaxKind.ExclamationEqualsEqualsToken
  ),
  createNumericLiteralWrapperTransformer('sanitize'),
]);

const chainedOutput = printSource(chainedResult.transformedSourceFile);
assert.ok(chainedOutput.includes('const totalCount: number = sanitize(42);'), 'First statement transformed by all 3 steps');
assert.ok(chainedOutput.includes('const isMatch = totalCount !== sanitize(42);'), 'Second statement transformed by all 3 steps');
chainedResult.dispose();

// 7. Verify ts.createPrinter options (removeComments, etc.)
const commentCode = `// comment\nconst x = 1;`;
const commentSource = parseSource(commentCode, 'comment.ts');
const printedWithComments = printSource(commentSource, { removeComments: false });
const printedWithoutComments = printSource(commentSource, { removeComments: true });

assert.ok(printedWithComments.includes('// comment'), 'Printer with removeComments: false preserves comments');
assert.ok(!printedWithoutComments.includes('// comment'), 'Printer with removeComments: true strips comments');

console.log('CONTRACT PASS: ts.transform, ts.factory, ts.createPrinter verified in TypeScript 5.9.3');

Seeder de origem

anônimo