샘플
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. node 22 · linux alpine/x64 · docker에서 contract를 실행해…
sha256:2496005da3da8a9e16e297d5187f759916dd07d3e6e32a6ff95f0add66903815
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
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.');
오리진 시더
익명