サンプル
typescript 6.0.3: Compile TypeScript in memory and check diagnostics using createProgram
検証済みサンプル — npm typescript 6.0.3: Compile TypeScript in memory and check diagnostics using createProgram. node 22 · linux alpine/x64 · docker で contract…
sha256:8e30d3f151fc8fbd72a2e8bae0cc8d65468f41232c42b9d4a23e47aa6f078114
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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- ゴール
- Compile TypeScript in memory and check diagnostics using createProgram
- パッケージ
- シンボル
-
- createProgram
- 作成日
- 2026-08-20T04:06:38Z
コントラクト
- compileInMemory compiles valid TypeScript code into JavaScript using createProgram and collects emitted output
- getDiagnostics detects type mismatch errors and syntactic issues using createProgram
- emitDeclarationFiles generates d.ts declaration files in memory using createProgram
- createInMemoryCompilerHost resolves multi-file module imports in memory for createProgram
ファイル
- 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: Compile TypeScript in memory and check diagnostics using createProgram
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/typescript@6.0.3
Demonstrate these symbols/APIs:
- createProgram
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:a8c5ee4a7aabe48d64076884d631db0eb131ff470e35fc6c5dc15f4435d2888f","contract":["compileInMemory compiles valid TypeScript code into JavaScript using createProgram and collects emitted output","getDiagnostics detects type mismatch errors and syntactic issues using createProgram","emitDeclarationFiles generates d.ts declaration files in memory using createProgram","createInMemoryCompilerHost resolves multi-file module imports in memory for createProgram"],"goal":"Compile TypeScript in memory and check diagnostics using createProgram","kind":"HOW","packages":["pkg:npm/typescript@6.0.3"],"schemaVersion":1,"symbols":["createProgram"]},"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":["createProgram"],"verifierAdapter":"node-typescript@1"}
{
"name": "typescript-createprogram-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "typescript-createprogram-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-createprogram-sample",
"version": "1.0.0",
"description": "Compile TypeScript in memory and check diagnostics using createProgram",
"type": "module",
"main": "src/index.mjs",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"typescript": "6.0.3"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "Compile TypeScript in memory and check diagnostics using createProgram",
"kind": "HOW",
"packages": [
"pkg:npm/typescript@6.0.3"
],
"symbols": [
"createProgram"
]
}
import ts from 'typescript';
/**
* Normalizes file path lookup across virtual paths (e.g. /file.ts, ./file.ts, file.ts).
*
* @param {Record<string, string>} sourceFiles - Virtual file map.
* @param {string} filePath - Path to resolve.
* @returns {string | undefined} File content or undefined if not found.
*/
function resolveVirtualFile(sourceFiles, filePath) {
if (!filePath) return undefined;
if (sourceFiles[filePath] !== undefined) {
return sourceFiles[filePath];
}
const clean = filePath.replace(/^\.\//, '');
if (sourceFiles[clean] !== undefined) {
return sourceFiles[clean];
}
const withSlash = clean.startsWith('/') ? clean : `/${clean}`;
if (sourceFiles[withSlash] !== undefined) {
return sourceFiles[withSlash];
}
const withoutSlash = clean.replace(/^\//, '');
if (sourceFiles[withoutSlash] !== undefined) {
return sourceFiles[withoutSlash];
}
return undefined;
}
/**
* Creates an in-memory TypeScript CompilerHost backed by a virtual file dictionary
* with fallback to the standard compiler host for standard library definitions.
*
* @param {Record<string, string>} sourceFiles - Map of file paths to source text.
* @param {Record<string, string>} [outputs={}] - Mutable map to collect emitted files.
* @param {ts.CompilerOptions} [options={}] - Compiler options.
* @returns {ts.CompilerHost} Virtual compiler host.
*/
export function createInMemoryCompilerHost(sourceFiles, outputs = {}, options = {}) {
const baseHost = ts.createCompilerHost(options);
return {
...baseHost,
getSourceFile: (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
const content = resolveVirtualFile(sourceFiles, fileName);
if (content !== undefined) {
return ts.createSourceFile(fileName, content, languageVersion, true);
}
return baseHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
},
getDefaultLibFileName: (opts) => baseHost.getDefaultLibFileName(opts),
writeFile: (fileName, content) => {
outputs[fileName] = content;
},
getCurrentDirectory: () => '/',
getDirectories: (path) => (baseHost.getDirectories ? baseHost.getDirectories(path) : []),
getCanonicalFileName: (fileName) => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => '\n',
fileExists: (fileName) => resolveVirtualFile(sourceFiles, fileName) !== undefined || baseHost.fileExists(fileName),
readFile: (fileName) => {
const content = resolveVirtualFile(sourceFiles, fileName);
if (content !== undefined) {
return content;
}
return baseHost.readFile(fileName);
},
};
}
/**
* Compiles virtual TypeScript source files in memory using ts.createProgram.
*
* @param {Record<string, string>} sourceFiles - Map of virtual file names to source code.
* @param {ts.CompilerOptions} [options={}] - Custom compiler options.
* @returns {{
* success: boolean,
* diagnostics: Array<{ message: string, code: number, category: number, fileName?: string }>,
* outputs: Record<string, string>,
* emitSkipped: boolean
* }}
*/
export function compileInMemory(sourceFiles, options = {}) {
const compilerOptions = {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
...options,
};
const outputs = {};
const host = createInMemoryCompilerHost(sourceFiles, outputs, compilerOptions);
const rootNames = Object.keys(sourceFiles);
const program = ts.createProgram(rootNames, compilerOptions, host);
const emitResult = program.emit();
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
const formattedDiagnostics = allDiagnostics.map((d) => ({
message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
code: d.code,
category: d.category,
fileName: d.file ? d.file.fileName : undefined,
}));
const hasErrors = allDiagnostics.some((d) => d.category === ts.DiagnosticCategory.Error);
return {
success: !hasErrors && !emitResult.emitSkipped,
diagnostics: formattedDiagnostics,
outputs,
emitSkipped: emitResult.emitSkipped,
};
}
/**
* Collects pre-emit diagnostics (syntax and type-check errors) for given TypeScript files.
*
* @param {Record<string, string>} sourceFiles - Map of file names to source code.
* @param {ts.CompilerOptions} [options={}] - Compiler options.
* @returns {Array<{ message: string, code: number, category: number, fileName?: string }>}
*/
export function getDiagnostics(sourceFiles, options = {}) {
const compilerOptions = {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
...options,
};
const host = createInMemoryCompilerHost(sourceFiles, {}, compilerOptions);
const program = ts.createProgram(Object.keys(sourceFiles), compilerOptions, host);
const preEmitDiagnostics = ts.getPreEmitDiagnostics(program);
return preEmitDiagnostics.map((d) => ({
message: ts.flattenDiagnosticMessageText(d.messageText, '\n'),
code: d.code,
category: d.category,
fileName: d.file ? d.file.fileName : undefined,
}));
}
/**
* Emits TypeScript declaration files (.d.ts) in memory using createProgram.
*
* @param {Record<string, string>} sourceFiles - Map of file names to source code.
* @param {ts.CompilerOptions} [options={}] - Compiler options.
* @returns {Record<string, string>} Map of emitted declaration filenames to their content.
*/
export function emitDeclarationFiles(sourceFiles, options = {}) {
const compilerOptions = {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
declaration: true,
emitDeclarationOnly: true,
moduleResolution: ts.ModuleResolutionKind.Bundler,
...options,
};
const outputs = {};
const host = createInMemoryCompilerHost(sourceFiles, outputs, compilerOptions);
const program = ts.createProgram(Object.keys(sourceFiles), compilerOptions, host);
program.emit();
return outputs;
}
export { ts };
import assert from 'node:assert/strict';
import {
ts,
createInMemoryCompilerHost,
compileInMemory,
getDiagnostics,
emitDeclarationFiles,
} from '../src/index.mjs';
// Contract 1: compileInMemory compiles valid TypeScript code into JavaScript using createProgram and collects emitted output
{
const files = {
'/main.ts': `
export interface User {
id: number;
name: string;
}
export function formatUser(user: User): string {
return user.name + ' (#' + user.id + ')';
}
`,
};
const result = compileInMemory(files);
assert.strictEqual(result.success, true, 'Compilation should succeed for valid TypeScript code');
assert.strictEqual(result.emitSkipped, false, 'Emit should not be skipped');
assert.strictEqual(result.diagnostics.length, 0, 'There should be no diagnostics errors');
const jsOutput = result.outputs['/main.js'];
assert.ok(jsOutput, 'JavaScript output file /main.js should be emitted');
assert.ok(jsOutput.includes('function formatUser'), 'Emitted JS should contain the formatUser function');
assert.ok(!jsOutput.includes('interface User'), 'Emitted JS should not contain interface definition');
}
// Contract 2: getDiagnostics detects type mismatch errors and syntactic issues using createProgram
{
const filesWithTypeError = {
'/broken.ts': `
const num: number = "not-a-number";
`,
};
const diagnostics = getDiagnostics(filesWithTypeError);
assert.ok(diagnostics.length > 0, 'Should return diagnostics for type error');
assert.ok(
diagnostics.some((d) => d.code === 2322 || d.message.includes('not assignable to type')),
'Diagnostic should report type mismatch (error code 2322)'
);
const filesWithSyntaxError = {
'/syntax.ts': `
const x: = 123;
`,
};
const syntaxDiagnostics = getDiagnostics(filesWithSyntaxError);
assert.ok(syntaxDiagnostics.length > 0, 'Should return diagnostics for syntax error');
}
// Contract 3: emitDeclarationFiles generates d.ts declaration files in memory using createProgram
{
const files = {
'/math.ts': `
export function multiply(a: number, b: number): number {
return a * b;
}
export const PI: number = 3.14159;
`,
};
const declarations = emitDeclarationFiles(files);
const dtsOutput = declarations['/math.d.ts'];
assert.ok(dtsOutput, 'Should emit /math.d.ts declaration file');
assert.ok(dtsOutput.includes('declare function multiply(a: number, b: number): number;'), 'd.ts should declare multiply function signature');
assert.ok(dtsOutput.includes('declare const PI: number;'), 'd.ts should declare PI constant');
assert.ok(!dtsOutput.includes('return a * b'), 'd.ts should not contain implementation body');
}
// Contract 4: createInMemoryCompilerHost resolves multi-file module imports in memory for createProgram
{
const files = {
'/util.ts': `
export function double(n: number): number {
return n * 2;
}
`,
'/app.ts': `
import { double } from './util';
export const quadrupled = double(double(2));
`,
};
const result = compileInMemory(files);
assert.strictEqual(result.success, true, 'Multi-file project compilation should succeed');
assert.ok(result.outputs['/util.js'], 'util.js should be emitted');
assert.ok(result.outputs['/app.js'], 'app.js should be emitted');
assert.ok(result.outputs['/app.js'].includes('double'), 'app.js should reference double function');
}
console.log('All pkg:npm/typescript@6.0.3 contracts passed successfully.');
オリジンシーダー
匿名