示例
typescript 6.0.3: Parse TypeScript source code and traverse AST using createSourceFile
已验证示例 — npm typescript 6.0.3: Parse TypeScript source code and traverse AST using createSourceFile. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.
sha256:2496005da3da8a9e16e297d5187f759916dd07d3e6e32a6ff95f0add66903815
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 2
- 构建过它的签名密钥
- 2
声明的环境
linux 24 · ubuntu · glibc 2.39 x64 npm
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-20 |
| 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- 目标
- Parse TypeScript source code and traverse AST using createSourceFile
- 符号
-
- createSourceFile
- 创建时间
- 2026-08-20T04:01:00Z
契约
- parseSourceCode parses TypeScript source code into a SourceFile AST and extracts top-level statements
- collectIdentifiers traverses AST nodes recursively using ts.forEachChild and extracts all identifier names
- findFunctionsAndParameters parses function declarations and extracts parameter names and return types
- analyzeTsxElements parses TSX syntax when ScriptKind is set to TSX and identifies JSX nodes
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
源代码
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: Parse TypeScript source code and traverse AST using createSourceFile
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/typescript@6.0.3
Demonstrate these symbols/APIs:
- createSourceFile
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.
{"case":{"caseId":"case:sha256:7b7167b1f7493f5637153c3ab113a1f25b92ea649348ffba83b75d2862bd600b","contract":["parseSourceCode parses TypeScript source code into a SourceFile AST and extracts top-level statements","collectIdentifiers traverses AST nodes recursively using ts.forEachChild and extracts all identifier names","findFunctionsAndParameters parses function declarations and extracts parameter names and return types","analyzeTsxElements parses TSX syntax when ScriptKind is set to TSX and identifies JSX nodes"],"goal":"Parse TypeScript source code and traverse AST using createSourceFile","kind":"HOW","packages":["pkg:npm/typescript@6.0.3"],"schemaVersion":1,"symbols":["createSourceFile"]},"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/typescript@6.0.3"],"schemaVersion":1,"symbols":["createSourceFile"],"verifierAdapter":"node-typescript@1"}
{
"name": "typescript-createsourcefile-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "typescript-createsourcefile-sample",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"typescript": "6.0.3"
}
},
"node_modules/typescript": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
{
"name": "typescript-createsourcefile-sample",
"version": "1.0.0",
"description": "Demonstrates createSourceFile and AST traversal in TypeScript",
"type": "module",
"main": "src/index.mjs",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"typescript": "6.0.3"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "Parse TypeScript source code and traverse AST using createSourceFile",
"kind": "HOW",
"packages": [
"pkg:npm/typescript@6.0.3"
],
"symbols": [
"createSourceFile"
]
}
import ts from 'typescript';
/**
* Parses TypeScript source code into an AST SourceFile.
*
* @param {string} fileName - The file name for the source file.
* @param {string} sourceText - The TypeScript source code string.
* @param {ts.ScriptTarget} [target=ts.ScriptTarget.Latest] - Target ECMAScript version.
* @param {boolean} [setParentNodes=true] - Whether to set parent nodes on AST nodes.
* @param {ts.ScriptKind} [scriptKind=ts.ScriptKind.TS] - Script kind (TS, TSX, JS, etc.).
* @returns {ts.SourceFile} The parsed AST SourceFile.
*/
export function parseSourceCode(fileName, sourceText, target = ts.ScriptTarget.Latest, setParentNodes = true, scriptKind = ts.ScriptKind.TS) {
return ts.createSourceFile(fileName, sourceText, target, setParentNodes, scriptKind);
}
/**
* Recursively traverses an AST node and collects all identifier names.
*
* @param {ts.Node} node - The root AST node to traverse.
* @returns {string[]} An array of identifier names found in the AST.
*/
export function collectIdentifiers(node) {
const identifiers = [];
function visit(childNode) {
if (ts.isIdentifier(childNode)) {
identifiers.push(childNode.text);
}
ts.forEachChild(childNode, visit);
}
visit(node);
return identifiers;
}
/**
* Finds all function declarations in a source file and extracts their metadata.
*
* @param {ts.SourceFile} sourceFile - The parsed AST SourceFile.
* @returns {Array<{ name: string, parameters: string[], returnType: string | null }>} Array of function details.
*/
export function findFunctionsAndParameters(sourceFile) {
const functions = [];
function visit(node) {
if (ts.isFunctionDeclaration(node)) {
const name = node.name ? node.name.text : '<anonymous>';
const parameters = node.parameters.map((param) => param.name.getText(sourceFile));
const returnType = node.type ? node.type.getText(sourceFile) : null;
functions.push({
name,
parameters,
returnType,
});
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
return functions;
}
/**
* Analyzes TSX elements in source code when parsed with TSX support.
*
* @param {string} sourceText - The TSX source code.
* @returns {{ isTsx: boolean, jsxElementCount: number }} Analysis result.
*/
export function analyzeTsxElements(sourceText) {
const sourceFile = ts.createSourceFile('component.tsx', sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let count = 0;
function visit(node) {
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) {
count++;
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
return {
isTsx: sourceFile.scriptKind === ts.ScriptKind.TSX,
jsxElementCount: count,
};
}
export { ts };
import assert from 'node:assert/strict';
import { ts, parseSourceCode, collectIdentifiers, findFunctionsAndParameters, analyzeTsxElements } from '../src/index.mjs';
// Contract 1: parseSourceCode parses TypeScript source code into a SourceFile AST and extracts top-level statements
{
const code = `
const x: number = 42;
export interface User {
id: string;
name: string;
}
`;
const sourceFile = parseSourceCode('user.ts', code);
assert.strictEqual(sourceFile.kind, ts.SyntaxKind.SourceFile, 'Root node should be a SourceFile');
assert.strictEqual(sourceFile.fileName, 'user.ts', 'File name should match');
assert.ok(sourceFile.statements.length >= 2, 'Should contain statements');
assert.strictEqual(sourceFile.statements[0].kind, ts.SyntaxKind.VariableStatement, 'First statement should be variable statement');
assert.strictEqual(sourceFile.statements[1].kind, ts.SyntaxKind.InterfaceDeclaration, 'Second statement should be interface declaration');
}
// Contract 2: collectIdentifiers traverses AST nodes recursively using ts.forEachChild and extracts all identifier names
{
const code = `
function calculateTotal(subtotal: number, taxRate: number): number {
const tax = subtotal * taxRate;
return subtotal + tax;
}
`;
const sourceFile = parseSourceCode('calc.ts', code);
const identifiers = collectIdentifiers(sourceFile);
assert.ok(identifiers.includes('calculateTotal'), 'Should find function identifier');
assert.ok(identifiers.includes('subtotal'), 'Should find parameter identifier');
assert.ok(identifiers.includes('taxRate'), 'Should find parameter identifier');
assert.ok(identifiers.includes('tax'), 'Should find local variable identifier');
}
// Contract 3: findFunctionsAndParameters parses function declarations and extracts parameter names and return types
{
const code = `
function greet(name: string, age: number): string {
return "Hello " + name;
}
function noop(): void {}
`;
const sourceFile = parseSourceCode('functions.ts', code);
const funcs = findFunctionsAndParameters(sourceFile);
assert.strictEqual(funcs.length, 2, 'Should find two function declarations');
assert.strictEqual(funcs[0].name, 'greet', 'First function name should be greet');
assert.deepStrictEqual(funcs[0].parameters, ['name', 'age'], 'Parameters should match');
assert.strictEqual(funcs[0].returnType, 'string', 'Return type should be string');
assert.strictEqual(funcs[1].name, 'noop', 'Second function name should be noop');
assert.deepStrictEqual(funcs[1].parameters, [], 'Parameters should be empty');
assert.strictEqual(funcs[1].returnType, 'void', 'Return type should be void');
}
// Contract 4: analyzeTsxElements parses TSX syntax when ScriptKind is set to TSX and identifies JSX nodes
{
const tsxCode = `
export const Widget = () => (
<div className="container">
<img src="icon.png" />
<span>Content</span>
</div>
);
`;
const result = analyzeTsxElements(tsxCode);
assert.strictEqual(result.isTsx, true, 'ScriptKind should be TSX');
assert.strictEqual(result.jsxElementCount, 3, 'Should count div, img, and span JSX elements');
}
console.log('All pkg:npm/typescript@6.0.3 contracts passed successfully.');
原始种子者
匿名