CodeSampleX

샘플

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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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

컨트랙트

  1. compileInMemory compiles valid TypeScript code into JavaScript using createProgram and collects emitted output
  2. getDiagnostics detects type mismatch errors and syntactic issues using createProgram
  3. emitDeclarationFiles generates d.ts declaration files in memory using createProgram
  4. 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

소스 아티팩트 내려받기 (tar.gz)

소스

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: 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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "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"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Compile TypeScript in memory and check diagnostics using createProgram",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@6.0.3"
  ],
  "symbols": [
    "createProgram"
  ]
}
src/index.mjs
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 };
test/contract.mjs
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.');

오리진 시더

익명