npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

laravel2typescript

v1.2.0

Published

Convert Laravel models to TypeScript interfaces. Generate TypeScript types from Laravel PHP models.

Downloads

165

Readme

laravel2typescript 🚀

License: MIT Node.js Version PRs Welcome

Convert Laravel models ↔ TypeScript interfaces, bidirectionally 🔄

Generate TypeScript interfaces from Laravel models and Laravel DTOs, form requests, policies, factories, and API resources from TypeScript definitions. Keep your frontend and backend types in perfect harmony! 🤝


Table of Contents 📑


Features 🌟

  • 🔀 Bidirectional Sync — Convert Laravel PHP models → TypeScript interfaces AND TypeScript interfaces → Laravel PHP models, form requests, DTOs, policies, factories, API resources, and controllers
  • 📋 Full Laravel Model Parsing — Parses $fillable, $guarded, $hidden, $casts, $appends, traits, interfaces, parent classes, relationships (hasOne, hasMany, belongsTo, belongsToMany, morphTo, morphMany, morphToMany), accessors (getXxxAttribute), mutators (setXxxAttribute), scopes (scopeXxx), and inline enums
  • ✅ Smart Model Detection — Auto-detects Laravel models via @property/@method doc comments, extends Model/Authenticatable/Pivot, or trait usage (HasFactory, SoftDeletes, etc.)
  • 🔧 Generator Options — Generate models, form requests, DTOs, policies, factories, and API resources from TypeScript — each toggleable via config flags
  • 🧠 Field Type Inference — Infers TypeScript types from field names (idnumber, is_*boolean, *_atstring, price/amountnumber, json/metadataRecord<string, unknown>)
  • 📝 Smart Validation Rules — Auto-generates Laravel form request validation rules with field-aware heuristics (email → email rule, password → min:8, name → max:255, price → numeric:min:0)
  • 🏭 Smart Factory Faker — Generates context-aware fake() calls (emailfake()->email(), phonefake()->phoneNumber(), urlfake()->url(), booleanfake()->boolean())
  • 👀 Watch Mode — Automatically regenerate TypeScript interfaces when Laravel model files change using chokidar
  • ⚙️ Highly Configurable — Custom type mappings, field overrides, ignore lists, multiple config file formats (.js, .json, .ts, .rc files, package.json)
  • 🎨 Interface or Type — Choose between export interface or export type style for TypeScript output
  • 📁 Per-Model & Aggregated — Generate individual files per model OR a single aggregated models.ts file (or both!)
  • 🧪 Utility Types — Auto-generates CreateInput, UpdateInput, and Filter utility types for each model
  • 🏷️ Enum Support — Extracts PHP enums from Laravel models and generates TypeScript enums
  • 🔗 Relationship Types — Generates TypeScript types for Eloquent relationships with proper nullability and array handling + standalone relation type exports
  • 🧹 Dry Run Mode — Preview what files would be generated without writing anything to disk
  • ✅ Config Validation — Built-in validate command to verify your configuration
  • 🤖 AI-Powered Conversion — Convert between PHP and TypeScript/TSX using NVIDIA AI API (via both CLI ai-convert command and standalone npm run rasultest script)
  • 📂 Multiple Config Formats — Supports JavaScript, JSON, TypeScript, RC files, and package.json config — auto-searched and loaded

Architecture 🏗️

┌──────────────────────────────────────────────────────────────────┐
│                  laravel2typescript CLI v1.2.0 🖥️               │
│                    (Commander-based CLI)                         │
└──────────────────┬───────────────────────────┬──────────────────┘
                   │                           │
         ┌─────────▼──────────┐     ┌──────────▼─────────┐
         │  Laravel Parser 🐘  │     │ TypeScript Parser 📝│
         │  (php-parser AST)  │     │  (TS Compiler API) │
         └─────────┬──────────┘     └──────────┬─────────┘
                   │                           │
         ┌─────────▼──────────┐     ┌──────────▼─────────┐
         │TypeScript Generator│     │  Laravel Generator  │
         │ (.ts interfaces,   │     │  (.php models,      │
         │  types, enums,     │     │   form requests,    │
         │  utility types,    │     │   DTOs, policies,   │
         │  relation types)   │     │   factories,        │
         └────────────────────┘     │   API resources)    │
                                    └─────────────────────┘
                   │                           │
         ┌─────────▼───────────────────────────▼─────────┐
         │           AI Converter 🤖                      │
         │  (NVIDIA AI API — OpenAI-compatible)           │
         │  PHP ↔ TypeScript ↔ TSX bidirectional          │
         └─────────────────────────────────────────────────┘

Parsers 🧠

| Parser | Source | Technology | Output | |--------|--------|------------|--------| | LaravelParser 🐘 | PHP model files | php-parser v3 (AST) | LaravelModel[] — fields, casts, relations, traits, accessors, mutators, scopes, enums, observer | | TypeScriptParser 📝 | .ts / .tsx / .d.ts files | TypeScript Compiler API (ts.createSourceFile) | TypeScriptInterface[] + Map<string, string[]> enums |

Generators 🏭

| Generator | Input | Output | |-----------|-------|--------| | TypeScriptGenerator 💙 | LaravelModel[] | .ts interfaces/types, enums, utility types (CreateInput, UpdateInput, Filter), relation types | | LaravelGenerator 🟠 | TypeScriptInterface[] | .php models, form requests, DTOs, policies, factories, API resources |

AI Converter 🤖

| Component | Input | Output | API | |-----------|-------|--------|-----| | AiConverter (class) 🤖 | .ts / .tsx / .php | .php / .ts | OpenAI-compatible NVIDIA API (default: microsoft/phi-4-mini-instruct) | | convert.cjs (script) 📜 | .ts / .tsx / .php | .php / .tsx | Direct NVIDIA API (model: minimaxai/minimax-m3) |


Installation 📦

Global Installation 🌍

npm install -g laravel2typescript

Local Installation (recommended) 📁

npm install --save-dev laravel2typescript

Run with npx (no install) ⚡

npx laravel2typescript --help

Requirements ✅

  • Node.js >= 16.0.0
  • Laravel project (for Laravel → TypeScript direction)
  • TypeScript project (for TypeScript → Laravel direction)
  • NVIDIA API key (only for AI-powered conversion 🤖)

Quick Start 🚀

1️⃣ Initialize Configuration

npx laravel2typescript init

This creates a laravel2typescript.config.js file in your project root with sensible defaults. ✨

2️⃣ Generate TypeScript from Laravel

npx laravel2typescript laravel-to-ts

This parses your Laravel models in ./app/Models and generates TypeScript interfaces in ./generated/. 🐘 → 💙

3️⃣ Generate Laravel from TypeScript

npx laravel2typescript ts-to-laravel

This parses your TypeScript interfaces in ./src/types and generates Laravel PHP files in ./generated/. 💙 → 🐘


Configuration ⚙️

Edit laravel2typescript.config.js in your project root:

module.exports = {
  // 📁 Path to Laravel models directory
  laravelPath: './app/Models',

  // 📁 Path to TypeScript types directory
  typescriptPath: './src/types',

  // 📁 Output directory for generated files
  outputDir: './generated',

  // 📄 Generate one file per model
  generatePerModel: true,

  // 📄 Generate aggregated types file
  generateAggregated: true,

  // 📄 Aggregated file name
  aggregatedFileName: 'models.ts',

  // 🎨 Use 'interface' or 'type' for TypeScript output
  interfaceStyle: 'interface',

  // 🚫 Models to ignore (by name)
  ignoreModels: [],

  // 🚫 Fields to ignore globally (timestamps, etc.)
  ignoreFields: ['id', 'created_at', 'updated_at', 'deleted_at'],

  // 🔄 Custom type mappings (Laravel PHP type -> TS type)
  typeOverrides: {},

  // 🎨 Custom field name -> Laravel cast type mappings
  customMappings: {},

  // ✨ Use Prettier for formatting (requires prettier installed)
  usePrettier: false,

  // 👀 Enable watch mode
  watchMode: false,

  // 🧪 Dry run (no files written to disk)
  dryRun: false,

  // 📣 Verbose output
  verbose: false,

  // 🏷️ Generate TypeScript enums from PHP enums
  generateEnums: true,

  // 🔧 Generate Laravel accessors in model
  generateAccessors: false,

  // 🔧 Generate Laravel mutators in model
  generateMutators: false,

  // 🔍 Generate Laravel query scopes
  generateScopes: false,

  // 🛡️ Generate Laravel policies (ts-to-laravel)
  generatePolicies: false,

  // 🏭 Generate Laravel factories (ts-to-laravel)
  generateFactories: false,

  // 📡 Generate Laravel API resources (ts-to-laravel)
  generateApiResources: false,

  // 🎮 Generate Laravel controllers (ts-to-laravel)
  generateControllers: false,
};

Config File Formats 📄

The config loader auto-searches in order:

| # | Format | File Name | |---|--------|-----------| | 1️⃣ | JavaScript | laravel2typescript.config.js | | 2️⃣ | JSON | laravel2typescript.config.json | | 3️⃣ | TypeScript | laravel2typescript.config.ts | | 4️⃣ | RC (JSON5) | .laravel2typescriptrc | | 5️⃣ | RC (JSON) | .laravel2typescriptrc.json | | 6️⃣ | RC (JS) | .laravel2typescriptrc.js | | 7️⃣ | Package.json | laravel2typescript key in package.json |


CLI Commands 🖥️

laravel2typescript generate 📝 (default command)

Generate files based on direction:

# Laravel to TypeScript 🔀
npx laravel2typescript generate --direction laravel-to-ts

# TypeScript to Laravel 🔀
npx laravel2typescript generate --direction ts-to-laravel

laravel2typescript laravel-to-ts 💙 (alias: l2ts)

Generate TypeScript interfaces from Laravel models:

npx laravel2typescript laravel-to-ts

# With options
npx laravel2typescript laravel-to-ts --output ./src/types --verbose --dry-run

# Ignore specific models
npx laravel2typescript laravel-to-ts --ignore User,OldModel

laravel2typescript ts-to-laravel 🟠 (alias: ts2l)

Generate Laravel files from TypeScript interfaces:

npx laravel2typescript ts-to-laravel

# With options
npx laravel2typescript ts-to-laravel --output ./app/Models --dry-run --verbose

laravel2typescript init 🏁

Create a configuration file:

npx laravel2typescript init

laravel2typescript watch 👀

Watch for file changes and auto-regenerate:

npx laravel2typescript watch

# With custom config
npx laravel2typescript watch --config ./config/laravel2typescript.config.js

# With verbose output
npx laravel2typescript watch --verbose

laravel2typescript validate

Validate your configuration file:

npx laravel2typescript validate

# Validate a specific config
npx laravel2typescript validate --config ./custom-config.js

laravel2typescript ai-convert 🤖

Convert a single file using NVIDIA AI API:

npx laravel2typescript ai-convert User.php
npx laravel2typescript ai-convert models.ts
npx laravel2typescript ai-convert components.tsx

# With custom model and output
npx laravel2typescript ai-convert User.php --model microsoft/phi-4-mini-instruct --output ./ai-output

CLI Options 🎛️

| Option | Alias | Description | |--------|-------|-------------| | --config <path> | -c | Path to config file | | --output <path> | -o | Output directory | | --direction <direction> | -d | Generation direction: laravel-to-ts or ts-to-laravel | | --dry-run | | Run without writing files | | --verbose | -v | Enable verbose output | | --ignore <models> | | Models to ignore (comma-separated, e.g. User,Post) | | --api-key <key> | -k | NVIDIA API key (ai-convert only) | | --model <model> | -m | AI model to use (ai-convert only, default: microsoft/phi-4-mini-instruct) | | --help | -h | Display help information | | --version | -V | Display version number |


Type Mapping 🔄

Laravel to TypeScript 🐘 → 💙

| Laravel PHP Type | TypeScript Type | Notes | |-----------------|----------------|-------| | int / integer | number | | | bigint | number | | | float / double / decimal | number | | | string / varchar / char | string | | | text / longtext / mediumtext / tinytext | string | | | boolean / bool | boolean | | | date / datetime / timestamp | string | ⚠️ Serialized dates | | time | string | | | json / object | Record<string, unknown> | | | array / collection | unknown[] | | | binary | Buffer | | | uuid | string | | | enum | string | ⚠️ Use generateEnums: true for typed enums | | file | File | |

TypeScript to Laravel 💙 → 🐘

| TypeScript Type | Laravel PHP Type | Notes | |----------------|-----------------|-------| | number | integer | | | string | string | | | boolean | boolean | | | Date | datetime | | | Buffer | binary | | | Record<string, unknown> | json | | | unknown[] | json | | | File | file | |

Relationship Type Mapping 🔗

| Laravel Relation | TypeScript Type | Nullable | Exported Type | |-----------------|----------------|----------|---------------| | hasOne | RelatedModel \| null | ✅ | UserProfileRelation | | hasMany | RelatedModel[] | ❌ | UserPostsRelation | | belongsTo | RelatedModel \| null | ✅ | UserCompanyRelation | | belongsToMany | RelatedModel[] | ❌ | UserRolesRelation | | morphTo | RelatedModel \| null | ✅ | — | | morphMany | RelatedModel[] | ❌ | — | | morphToMany | RelatedModel[] | ❌ | — |


Custom Mappings 🎨

Add custom mappings in your config to handle project-specific types:

module.exports = {
  // 🎨 Custom field name -> Laravel cast type mappings
  customMappings: {
    'Money': 'decimal:10,2',
    'Status': 'enum:active,inactive',
    'UUID': 'uuid',
    'SocialLinks': 'json',
    'Coordinates': 'object',
  },

  // 🔄 Override specific field types (name -> TS type)
  typeOverrides: {
    'amount': 'number',
    'currency': 'string',
    'metadata': 'Record<string, unknown>',
    'tags': 'string[]',
  },

  // 🚫 Ignore specific fields globally
  ignoreFields: [
    'id',
    'created_at',
    'updated_at',
    'deleted_at',
    'laravel_through_key',
    'remember_token',
  ],
};

Generated Files 📄

TypeScript Output 💙

When running laravel-to-ts, each model generates:

Main Interface

// models/user.ts
export interface User {
  id: number;
  name: string;
  email: string;
  password?: string;
  is_active: boolean;
  role: 'admin' | 'user' | 'guest';
  avatar_url?: string;
  bio?: string | null;
  date_of_birth?: string;
  email_verified_at?: string;
  created_at: string;
  updated_at: string;
}

Utility Types (auto-generated) 🛠️

// 📝 Create input — all fillable fields required
export type UserCreateInput = {
  name: string;
  email: string;
  password: string;
  role?: string;
  is_active?: boolean;
  avatar_url?: string;
  bio?: string | null;
};

// ✏️ Update input — all fields optional
export type UserUpdateInput = {
  name?: string;
  email?: string;
  password?: string;
  role?: string;
  is_active?: boolean;
  avatar_url?: string;
  bio?: string | null;
  date_of_birth?: string;
};

// 🔍 Filter type — all fields optional for query filtering
export type UserFilter = {
  id?: number;
  name?: string;
  email?: string;
  role?: string;
  is_active?: boolean;
  created_at?: string;
  updated_at?: string;
};

Generated Enums 🏷️

// Enums for User
export enum UserRole {
  ADMIN = 'admin',
  USER = 'user',
  GUEST = 'guest',
}

Relation Types 🔗

import type { Post } from './post';
import type { Profile } from './profile';

export interface User {
  // ...fields...
  posts?: Post[];
  profile?: Profile | null;
}

// Standalone relation types
export type UserPostsRelation = Post;
export type UserProfileRelation = Profile;

Laravel Output 🟠

When running ts-to-laravel, each interface generates:

Eloquent Model 🐘

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    protected $table = 'users';

    protected $fillable = [
        'name', 'email', 'password', 'role',
        'is_active', 'avatar_url', 'bio', 'date_of_birth'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'email_verified_at' => 'datetime',
        'date_of_birth' => 'datetime',
        'settings' => 'array',
    ];

    protected $hidden = ['password'];
}

Form Request ✅

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255'],
            'password' => ['required', 'string', 'min:8'],
            'role' => ['nullable', 'string'],
            'is_active' => ['nullable', 'boolean'],
            'avatar_url' => ['nullable', 'string', 'url'],
            'bio' => ['nullable', 'string', 'max:1000'],
            'date_of_birth' => ['nullable', 'date'],
        ];
    }

    public function messages(): array
    {
        return [
            // Add custom validation messages here
        ];
    }
}

DTO 📦

<?php

namespace App\Dtos;

class UserDto
{
    private string $name;
    private string $email;
    // ...

    public function __construct(
        string $name,
        string $email,
        // ...
    ) { /* ... */ }

    // Getters...
    public function getName(): string { return $this->name; }

    // toArray()...
    public function toArray(): array { /* ... */ }

    // fromArray()...
    public static function fromArray(array $data): self { /* ... */ }
}

Policy 🛡️

Generated when generatePolicies: true

<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user): bool { return true; }
    public function view(User $user, User $model): bool { return true; }
    public function create(User $user): bool { return true; }
    public function update(User $user, User $model): bool { return $user->id === $model->id; }
    public function delete(User $user, User $model): bool { return $user->id === $model->id; }
    public function restore(User $user, User $model): bool { return true; }
    public function forceDelete(User $user, User $model): bool { return true; }
}

Factory 🏭

Generated when generateFactories: true

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'password' => bcrypt('password'),
            'role' => fake()->randomElement(['admin', 'user', 'guest']),
            'is_active' => fake()->boolean(),
            'bio' => fake()->optional()->text(200),
        ];
    }
}

API Resource 📡

Generated when generateApiResources: true

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'role' => $this->role,
            'is_active' => $this->is_active,
            'avatar_url' => $this->avatar_url,
            'bio' => $this->bio,
            'date_of_birth' => $this->date_of_birth,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Watch Mode 👀

Enable automatic regeneration on file changes:

npx laravel2typescript watch

This watches the laravelPath directory and regenerates TypeScript interfaces whenever a model file is created, modified, or deleted. 🪄

# With verbose output
npx laravel2typescript watch --verbose

# With custom config
npx laravel2typescript watch --config ./my-config.js

The watcher uses chokidar with these defaults:

  • Ignores dotfiles
  • Watches all .php files in the configured laravelPath directory
  • Auto-debounces rapid successive changes
  • Prevents concurrent regeneration (queues changes during active generation)
  • Press Ctrl+C to stop watching 🛑

Programmatic API 🧩

You can use laravel2typescript programmatically in your own scripts:

import {
  LaravelParser,
  TypeScriptParser,
  TypeScriptGenerator,
  LaravelGenerator,
  AiConverter,
  loadConfig,
  resolvePaths,
  validateConfig,
  createDefaultConfig,
  mergeConfigs,
} from 'laravel2typescript';

async function generate() {
  // 1️⃣ Load configuration
  const config = loadConfig('./laravel2typescript.config.js');
  const paths = resolvePaths(config);

  // 2️⃣ Parse Laravel models
  const parser = new LaravelParser(config);
  const models = await parser.parseDirectory(paths.laravelPath);

  // 3️⃣ Generate TypeScript interfaces
  const generator = new TypeScriptGenerator(config);
  const result = await generator.generateFromModels(models, paths.outputDir);

  console.log(`✅ Generated ${result.filesGenerated.length} files`);
  console.log(`⏱️  Duration: ${result.duration}ms`);
}

async function convertWithAI() {
  // 4️⃣ AI-powered conversion 🤖
  const converter = new AiConverter({
    apiKey: process.env.NVIDIA_API_KEY,
    model: 'microsoft/phi-4-mini-instruct',
    outputDir: './generated/ai-converted',
  });

  const result = await converter.convertFile('./User.php');
  console.log(`✅ Converted: ${result.outputFile}`);
}

Available Classes 📚

| Class | Import | Description | |-------|--------|-------------| | LaravelParser 🐘 | laravel2typescript | Parses PHP Laravel model files (AST via php-parser) into LaravelModel[] | | TypeScriptParser 📝 | laravel2typescript | Parses .ts/.tsx files (TS Compiler API) into TypeScriptInterface[] | | TypeScriptGenerator 💙 | laravel2typescript | Generates .ts files (interfaces, types, enums, utilities) from LaravelModel[] | | LaravelGenerator 🟠 | laravel2typescript | Generates .php files (models, requests, DTOs, policies, factories, resources) from TypeScriptInterface[] | | AiConverter 🤖 | laravel2typescript | Converts files between PHP and TypeScript/TSX using NVIDIA AI API |

Available Utilities 🔧

| Function | Description | |----------|-------------| | loadConfig(path?) | Load and merge config from file with defaults (auto-searches 7 file formats) | | saveConfig(config) | Save config to default laravel2typescript.config.js | | validateConfig(config) | Validate config, returns string[] of errors | | resolvePaths(config) | Resolve relative paths to absolute from CWD | | createDefaultConfig() | Create config with all default values | | mergeConfigs(base, override) | Deep merge two configs (properly merges arrays and nested objects) |


AI-Powered Conversion 🤖

This package includes two AI conversion approaches using NVIDIA's API (OpenAI-compatible):

Approach 1: Standalone Script 📜 (npm run rasultest)

Quick one-off conversion using Axios + minimaxai/minimax-m3 model:

npm run rasultest models.ts     # TypeScript (.ts) → Laravel PHP
npm run rasultest components.tsx # TypeScript React (.tsx) → Laravel PHP
npm run rasultest User.php      # Laravel PHP → TypeScript (.tsx)

Outputs to generated/{ts-to-php|tsx-to-php|php-to-ts}/.

Approach 2: CLI Command 🖥️ (npx laravel2typescript ai-convert)

Full feature conversion using the OpenAI library + microsoft/phi-4-mini-instruct model:

# All directions supported
npx laravel2typescript ai-convert User.php
npx laravel2typescript ai-convert models.ts
npx laravel2typescript ai-convert components.tsx

# Custom model and output
npx laravel2typescript ai-convert User.php --model microsoft/phi-4-mini-instruct --output ./ai-output

Outputs to generated/ai-converted/{php-to-ts|ts-to-php|tsx-to-php}/.

Approach 3: Programmatic API 🧩

import { AiConverter } from 'laravel2typescript';

const converter = new AiConverter({
  apiKey: 'nvapi-...',           // or set NVIDIA_API_KEY env
  model: 'microsoft/phi-4-mini-instruct',
  temperature: 0.1,
  topP: 0.7,
  maxTokens: 4096,
  outputDir: './generated/ai-converted',
});

const result = await converter.convertFile('User.php');
console.log(`${result.direction} → ${result.outputFile}`);

API Key 🔑

Create a .env file in the project root:

NVIDIA_API_KEY="your-nvidia-api-key"

The scripts auto-load .env automatically. You can also set it manually:

# Linux / Mac 🐧
export NVIDIA_API_KEY="your-nvidia-api-key"

# Windows (Command Prompt) 🪟
set NVIDIA_API_KEY=your-nvidia-api-key

# Windows (PowerShell)
$env:NVIDIA_API_KEY="your-nvidia-api-key"

Examples 📚

The examples/ directory contains realistic Laravel and TypeScript model examples:

examples/
├── laravel/
│   └── Models/
│       ├── User.php     — User model with HasFactory, 4 relations, casts, fillable, hidden
│       └── Post.php     — Post model with SoftDeletes, 4 relations, custom methods
└── angular/
    └── types/
        ├── user.interface.ts  — Generated TS interface + CreateInput + UpdateInput + Filter
        └── post.interface.ts  — Generated TS interface with union types + utility types

These serve as reference for how models are parsed and what the generated output looks like. 📖


Testing 🧪

# Run all tests 🏃
npm test

# Run tests in watch mode 👀
npm run test:watch

# Run tests with coverage 📊
npm run test:coverage

# AI conversion test (PHP → .tsx) 🤖
npm run rasultest tests/index.php

# Lint source code 🔍
npm run lint

# TypeScript type checking ✅
npm run typecheck

# Clean build output 🧹
npm run clean

Test Coverage ✅

The test suite (tests/index.tsx) covers:

| Module | Tests | |--------|-------| | LaravelParser 🐘 | parseContent: model name, namespace, fillable, hidden, casts, properties, relationships, doc comments | | TypeScriptParser 📝 | parseContent: interfaces, optional properties, arrays, type aliases, readonly properties | | TypeScriptGenerator 💙 | generateInterfaceFromModel: basic output, utility types | | LaravelGenerator 🟠 | Model generation, form requests, DTOs, policies, factories, API resources, full pipeline | | CLI 🖥️ | Program name and description |


Contributing 🤝

We welcome contributions! Here's how you can help:

  1. 🍴 Fork the repository
  2. 🌿 Create your feature branch (git checkout -b feature/amazing-feature)
  3. 💻 Commit your changes (git commit -m 'Add some amazing feature')
  4. 📤 Push to the branch (git push origin feature/amazing-feature)
  5. 🔁 Open a Pull Request

Development Setup 🛠️

# Clone the repository
git clone https://github.com/yourusername/laravel2typescript.git

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

Project Structure 📁

laravel2typescript/
├── src/
│   ├── cli/           # Commander-based CLI commands 🖥️
│   ├── parsers/       # LaravelParser + TypeScriptParser 🧠
│   ├── generators/    # TypeScriptGenerator + LaravelGenerator 🏭
│   ├── types/         # All TypeScript interfaces & constants 📐
│   ├── utils/         # Config loader, path utils, validators 🔧
│   ├── ai-converter/  # AI-powered conversion (NVIDIA API) 🤖
│   ├── index.ts       # Public API exports 📦
│   └── cli.ts         # CLI binary entry point 🚪
├── tests/             # Vitest test suite 🧪
├── scripts/           # Standalone helper scripts 📜
├── examples/          # Example Laravel + Angular models 📚
└── generated/         # Generated output (gitignored) 📄

Code Style Guidelines 📐

  • Follow the existing code style and conventions
  • Write tests for new features
  • Update documentation as needed
  • Use meaningful commit messages
  • Keep pull requests focused on a single change

License 📄

This project is licensed under the MIT License — see the LICENSE file for details.


Support 💬