Skip to content

@typeglot/compiler

The compiler package transforms JSON translation files into strongly-typed TypeScript functions.

Installation

bash
npm install @typeglot/compiler
# or
pnpm add @typeglot/compiler

Features

  • JSON to TypeScript compilation
  • Parameter type inference
  • Pluralization support
  • Watch mode for development
  • Incremental compilation

Basic Usage

typescript
import { TypeGlotCompiler } from '@typeglot/compiler';
import { loadConfig } from '@typeglot/core';

const config = await loadConfig(process.cwd());

const compiler = new TypeGlotCompiler({
  config,
  projectRoot: process.cwd(),
  verbose: true,
});

const results = await compiler.compile();

console.log(`Compiled ${results.length} files`);

Compiler API

TypeGlotCompiler

typescript
import { TypeGlotCompiler, CompilerOptions } from '@typeglot/compiler';

const options: CompilerOptions = {
  config: {
    sourceLocale: 'en',
    targetLocales: ['es', 'fr'],
    localesDir: './locales',
    outputDir: './src/generated/i18n',
  },
  projectRoot: '/path/to/project',
  verbose: false,
};

const compiler = new TypeGlotCompiler(options);

compile()

Compile all translation files:

typescript
const results = await compiler.compile();

for (const result of results) {
  console.log(`${result.outputPath}: ${result.keysCount} keys`);
  if (!result.success) {
    console.error(result.errors);
  }
}

compileSingle()

Compile a single locale file:

typescript
const result = await compiler.compileSingle('./locales/es.json');

Watch Mode

typescript
import { TranslationWatcher } from '@typeglot/compiler';

const watcher = new TranslationWatcher({
  config,
  projectRoot: process.cwd(),
  onCompile: (results) => {
    console.log(`Compiled ${results.length} files`);
  },
  onError: (error) => {
    console.error('Compilation error:', error);
  },
});

// Start watching
await watcher.start();

// Stop watching
await watcher.stop();

Parser

Parse Translation Files

typescript
import { parseTranslationFile, parseParameters } from '@typeglot/compiler';

// Parse a JSON file
const translations = await parseTranslationFile('./locales/en.json');
// { 'hello': 'Hello', 'welcome': 'Welcome, {name}!' }

// Parse parameters from a value
const params = parseParameters('Hello, {name}! You have {count} items.');
// ['name', 'count']

Nested Key Flattening

Nested objects are automatically flattened:

json
// Input: locales/en.json
{
  "common": {
    "save": "Save",
    "cancel": "Cancel"
  }
}
typescript
// Output
{
  'common.save': 'Save',
  'common.cancel': 'Cancel'
}

Code Generator

Generate Typed Functions

typescript
import { generateTypedFunctions } from '@typeglot/compiler';

const translations = {
  hello: 'Hello',
  welcome: 'Welcome, {name}!',
  items: '{count, plural, one {# item} other {# items}}',
};

const code = generateTypedFunctions(translations, 'en');

Generated Output

typescript
// Auto-generated by @typeglot/compiler

export function hello(): string {
  return messages['hello'] ?? 'Hello';
}

export function welcome(params: { name: string }): string {
  const template = messages['welcome'] ?? 'Welcome, {name}!';
  return formatMessage(template, params);
}

export function items(params: { count: number }): string {
  const template = messages['items'] ?? '{count, plural, one {# item} other {# items}}';
  return formatMessage(template, params);
}

export const m = { hello, welcome, items } as const;

Output Structure

The compiler generates the following file structure:

src/generated/i18n/
├── index.ts      # Main entry point, exports all
├── messages.ts   # Typed translation functions
├── en.ts         # English locale data
├── es.ts         # Spanish locale data
└── fr.ts         # French locale data

index.ts

typescript
export * from './messages.js';

export * as en from './en.js';
export * as es from './es.js';
export * as fr from './fr.js';

export const availableLocales = ['en', 'es', 'fr'] as const;
export type Locale = (typeof availableLocales)[number];

messages.ts

Contains the typed functions and locale switching utilities:

typescript
export function setLocale(locale: Locale): void;
export function getLocale(): Locale;
export function loadMessages(messages: Record<string, string>): void;

{locale}.ts

Contains the raw message data for each locale:

typescript
export const locale = 'es' as const;

export const messages = {
  hello: 'Hola',
  welcome: '¡Bienvenido, {name}!',
} as const;

export type MessageKey = keyof typeof messages;

Configuration Options

CompilerOptions

typescript
interface CompilerOptions {
  config: TypeGlotConfig; // TypeGlot configuration
  projectRoot: string; // Project root path
  verbose?: boolean; // Enable verbose logging
}

CompileResult

typescript
interface CompileResult {
  success: boolean; // Whether compilation succeeded
  outputPath: string; // Path to generated file
  keysCount: number; // Number of translation keys
  errors?: string[]; // Error messages if failed
}

Dependencies

  • @typeglot/core — Shared types and utilities
  • chokidar — File watching

Released under the MIT License.