@apollo-deploy/tesseract
v4.0.0
Published
Manifest and OpenAPI SDK generator for TypeScript, Python, Ruby, Rails, Go, PHP, Laravel, Java, Kotlin, .NET, Rust, Elixir, Swift, Zig, and CLI packages
Maintainers
Readme
Tesseract
SDK generator for sdk-manifold/v1 manifests and OpenAPI 3.0/3.1 JSON/YAML documents. Both source formats normalize into Tesseract’s language-neutral contract, so they use the same typed generators for TypeScript, Python, Ruby, Rails, Go, PHP, Laravel, Java, Kotlin, .NET, Rust, Elixir, Swift, Zig, and generated CLI packages.
OpenAPI files are parsed with @apidevtools/swagger-parser; OpenAPI 3.0 inputs also receive its full specification validation. Tesseract supports local #/components/schemas references and local component references for parameters, request bodies, responses, and security schemes. External $refs, cookie parameters, callbacks, links, and webhooks are rejected with actionable errors rather than silently degraded.
Install
npm install -g @apollo-deploy/[email protected]
# or
bun add -g @apollo-deploy/[email protected]Quick Start
# sdk-manifold/v1 JSON
tesseract generate -i manifest.json -o ./sdk
# OpenAPI 3.0/3.1 JSON or YAML
tesseract generate -i openapi.yaml -o ./sdkBoth commands produce a complete SDK in ./sdk/.
CLI
tesseract generate
Generate an SDK from a static sdk-manifold/v1 JSON manifest or an OpenAPI 3.0/3.1 JSON/YAML document.
| Flag | Required | Description |
| ----------------------------- | -------- | -------------------------------------------------------------------------------------------------- |
| -i, --input <path> | Yes | Path to the sdk-manifold/v1 JSON manifest or OpenAPI 3.0/3.1 JSON/YAML document |
| -o, --output <dir> | Yes | Output directory for the generated SDK |
| -l, --language <lang> | No | Target selector from Target Languages; defaults to typescript |
| -n, --name <name> | No | Override the npm package name |
| --package-version <version> | No | Override the generated package version |
| --version-bump <type> | No | Automatic bump type: patch (default), minor, or major |
| --client-name <name> | No | Override the generated client class name |
| --base-url <url> | No | Override the default base URL |
| --sdk-style <style> | No | functional (default) or class (Resend-style new MySDK('key')) |
| --client-type <type> | No | internal (full options, default) or public (auth key only, baseUrl baked in) |
| --dry-run | No | Preview changes without writing files |
| --check | No | Exit non-zero if generated output is out of date |
| --go-module-path <path> | For Go | Canonical installable module path, such as github.com/acme/widget-sdk |
--dry-run and --check are mutually exclusive.
OpenAPI extensions
Standard OpenAPI fields map directly to generated SDK operations: tags group domains, operationId supplies the method name, parameters become path/query/header arguments, request-body media types select transport, and text/event-stream responses generate SSE methods. For manifest-only controls that have no OpenAPI equivalent, use the x-tesseract extension:
Active apiKey, bearer HTTP, OAuth 2, and OpenID Connect security schemes become generated client credentials. Because generated transports use one global credential profile, every operation must resolve to the same effective OpenAPI security requirements. Tesseract rejects mixed profiles, including a mixture of public and protected operations, instead of sending credentials to the wrong routes.
info.x-tesseract.versionBumptags[].x-tesseract:prefix,domain,fileName, andstabilitypaths.*.*.x-tesseract: the existing route options such astimeout,internal,transport,returnType, andsseReturnType
These extensions let an OpenAPI document reproduce the same output as a purpose-built manifest.
Versioning
When packageVersion is omitted, Tesseract applies versionBump to the current package version. TypeScript checks npm first and falls back to info.version; other adapters use info.version. The default bump is patch.
Patch and minor components use decimal carry instead of double digits:
0.0.9+ patch →0.1.00.9.9+ patch →1.0.02.9.4+ minor →3.0.02.8.7+ major →3.0.0
Set the policy with --version-bump, versionBump in generator/collector config, or info.versionBump in a static manifest. An explicit packageVersion always wins.
tesseract run
Boot an instrumented Fastify app with TESSERACT_GENERATE=1 to collect annotated routes at runtime and generate an SDK without a static manifest file.
tesseract run dist/app.jsThe app must register tesseractPlugin from @apollo-deploy/tesseract/fastify. See Fastify Integration below.
Target Languages
Tesseract ships adapters for multiple target languages. Pass -l <lang> to tesseract generate, set language in CollectorOptions, or use additionalTargets to emit multiple languages in a single run.
| Language / integration | Value | Output |
| ---------------------- | ------------ | --------------------------------------------------- |
| TypeScript | typescript | npm package with Axios transport |
| Python | python | pip package |
| Ruby | ruby | standalone gem |
| Rails | rails | Ruby gem with a Railtie and Rails configuration |
| Go | go | Go module |
| PHP | php | standalone Composer package |
| Laravel | laravel | Composer package with provider discovery and config |
| Java | java | Gradle project using Java HttpClient and Jackson |
| Kotlin | kotlin | Gradle project with Ktor and kotlinx.serialization |
| .NET | dotnet | NuGet package |
| C# compatibility alias | csharp | Byte-identical alias of dotnet |
| Rust | rust | Cargo crate |
| Elixir | elixir | Mix package using Req |
| Swift | swift | Swift Package using Foundation and URLSession |
| Zig | zig | Zig package using std.http.Client |
| CLI | cli | npm package with a generated executable dispatcher |
The rails and laravel selectors are framework-native packages layered on
the Ruby and PHP emitters. The cli selector generates a static Node.js command
dispatcher over the TypeScript client and rejects request body encodings it
cannot safely represent, including multipart bodies.
Go output requires an installable module path. Set go.modulePath in the API or
--go-module-path on the CLI when packageName is not already a path such as
github.com/acme/widget-sdk.
Multiple targets in one run
Use additionalTargets on any collector or the Fastify plugin to emit multiple languages simultaneously without running the generator twice:
const collector = new SDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './sdk/typescript', // primary — TypeScript
additionalTargets: [
{ language: 'kotlin', output: './sdk/java' },
{ language: 'python', output: './sdk/python', packageName: 'my-api' },
],
});Each additional target inherits clientType, packageName, packageVersion, and sdkStyle from the primary options unless overridden per-target.
Targets without TypeScript schema-package support automatically expand registered Zod / $defs types into local models. The typescript and cli targets inherit schemaPackage and re-export those types instead of regenerating them.
Generated SDK structure
Every adapter emits a compact package overview and a separate reference tree:
README.md
docs/
├── README.md # documentation index
├── types.md # generated models, enums, unions, and aliases
└── domains/
├── users.md # operations for one API domain
└── billing.mdThe root README contains installation, quick start, reliability configuration, error handling, and links into the reference. Domain pages document HTTP paths, parameters by location, request bodies, response types, deprecations, streaming behavior, and links to generated source.
Generated transport reliability
Generated transports share the same baseline behavior across all target languages:
- Bounded request timeouts and cancellation where the language supports it
- Structured errors with status, code, message, and request ID
- Retries for transient network failures and HTTP
408,425,429,500,502,503, and504 - Exponential backoff with jitter and
Retry-Aftersupport - Automatic retries for idempotent methods only
POSTandPATCHretries only when explicitly enabled or anX-Idempotency-Keyis supplied- Default headers and a generated SDK user agent where the runtime permits it
- Explicit client cleanup for transports that own sockets or connection pools
The exact option names follow each target language's conventions and are shown in the generated README.
Input: The Manifest
Tesseract consumes a BackendManifest JSON file with $schema: "sdk-manifold/v1":
{
"$schema": "sdk-manifold/v1",
"info": {
"title": "My API",
"version": "1.0.0",
"versionBump": "patch",
"description": "An example API",
"baseUrl": "https://api.example.com"
},
"domains": [
{
"domain": "users",
"prefix": "/users",
"stability": "stable",
"routes": [
{
"method": "GET",
"url": "/:id",
"schema": {
"params": { "id": { "type": "string" } },
"response": { "200": { "$ref": "#/definitions/User" } }
},
"sdk": { "methodName": "get" }
}
]
}
],
"definitions": {
"User": {
"type": "object",
"properties": {
"id": { "type": "string" },
"name": { "type": "string" }
}
}
}
}Key Manifest Fields
info— Title, version, optionalversionBump, description, and base URL for the APIdomains— Groups of routes organized by domain, each with a prefix, stability level (stable/experimental/internal), and route definitions.internal-stability domains are excluded from public SDK builds.definitions— JSON Schema definitions for shared typesschemaPackage(optional) — An external npm package to import types from instead of generating them
Route Configuration
Each route in a domain can specify:
method/url— HTTP method and Fastify-style URL pattern (:param)schema— JSON Schemas forparams,querystring,body,headers, andresponsesdk— SDK-specific config:methodName,transport(json|multipart|binary|stream),exclude,deprecated,internal,timeout,requiredHeaderssse: true— Marks the route as a Server-Sent Events stream
Framework Integration
Tesseract ships adapters for every major Node.js API framework. Each adapter is a separate subpath export so you only pull in what you use.
| Framework | Import |
| --------------------------- | --------------------------------------------------------- |
| Fastify | @apollo-deploy/tesseract/fastify |
| Express | @apollo-deploy/tesseract/express |
| Hono | @apollo-deploy/tesseract/hono |
| Koa | @apollo-deploy/tesseract/koa |
| Elysia | @apollo-deploy/tesseract/elysia |
| NestJS | @apollo-deploy/tesseract/nestjs |
| Generic / any framework | import { SDKCollector } from '@apollo-deploy/tesseract' |
All adapters share the same CollectorOptions interface, which means language and additionalTargets work identically across every framework.
Fastify
The Fastify adapter hooks into onRoute to collect routes automatically at boot time — no manual registration needed. Internally it delegates to SDKCollector, so all CollectorOptions including language and additionalTargets are supported.
// app.ts
import { tesseractPlugin } from '@apollo-deploy/tesseract/fastify';
app.register(tesseractPlugin, {
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
// Generate a Kotlin SDK alongside the primary TypeScript one:
additionalTargets: [{ language: 'kotlin', output: './sdk/java' }],
// Optional: import types from a shared package instead of regenerating them
schemaPackage: { name: '@my-org/schemas', version: '^2.0.0' },
sdkStyle: 'functional', // or 'class'
clientType: 'internal', // or 'public'
});The plugin is a complete no-op unless TESSERACT_GENERATE=1 is set, so it is safe to register unconditionally.
Add sdk as a top-level option on each route (sibling to schema):
fastify.get(
'/:id',
{
schema: { response: { 200: UserSchema } },
sdk: { methodName: 'getUser' },
},
handler,
);Use sdkDomain() to name the domain and set a description:
import fp from 'fastify-plugin';
import { sdkDomain } from '@apollo-deploy/tesseract/fastify';
export default fp(async (fastify) => {
sdkDomain(fastify, { domain: 'users', description: 'User management' });
fastify.get(
'/:id',
{
schema: { response: { 200: UserSchema } },
sdk: { methodName: 'getUser' },
},
handler,
);
});Or use the @SDKModule() class decorator:
import { SDKModule } from '@apollo-deploy/tesseract';
@SDKModule({ prefix: '/users', domain: 'users', description: 'User management' })
export class UsersPlugin {
register(app: FastifyInstance) {
app.get('/:id', { schema: { ... }, sdk: { methodName: 'getUser' } }, handler);
}
}Trigger:
tesseract run dist/app.js
# or
TESSERACT_GENERATE=1 node dist/app.jsExpress
import express from 'express';
import { ExpressSDKCollector } from '@apollo-deploy/tesseract/express';
const app = express();
const collector = new ExpressSDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
additionalTargets: [{ language: 'kotlin', output: './sdk/java' }],
});
collector.domain('/users', { domain: 'users', description: 'User management' });
app.get(
'/users/:id',
collector.expressRoute('/users/:id', 'GET', {
sdk: { methodName: 'getUser' },
}),
getUserHandler,
);
app.post(
'/users',
collector.expressRoute('/users', 'POST', {
sdk: { methodName: 'createUser' },
}),
createUserHandler,
);
// After all routes are registered:
if (await collector.tryGenerate()) process.exit(0);
app.listen(3000);Trigger: TESSERACT_GENERATE=1 node dist/app.js
Hono
import { Hono } from 'hono';
import { HonoSDKCollector } from '@apollo-deploy/tesseract/hono';
const app = new Hono();
const collector = new HonoSDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
});
collector.domain('/users', { domain: 'users', description: 'User management' });
app.get(
'/users/:id',
collector.honoMiddleware('/users/:id', 'GET', {
sdk: { methodName: 'getUser' },
}),
(c) => c.json(getUser(c.req.param('id'))),
);
if (await collector.tryGenerate()) process.exit(0);
export default app;Trigger: TESSERACT_GENERATE=1 node dist/app.js
Koa
import Koa from 'koa';
import Router from '@koa/router';
import { KoaSDKCollector } from '@apollo-deploy/tesseract/koa';
const app = new Koa();
const router = new Router();
const collector = new KoaSDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
});
collector.domain('/users', { domain: 'users', description: 'User management' });
router.get(
'/users/:id',
collector.koaMiddleware('/users/:id', 'GET', {
sdk: { methodName: 'getUser' },
}),
getUserHandler,
);
app.use(router.routes());
if (await collector.tryGenerate()) process.exit(0);
app.listen(3000);Trigger: TESSERACT_GENERATE=1 node dist/app.js
Elysia
import { Elysia } from 'elysia';
import { tesseractPlugin } from '@apollo-deploy/tesseract/elysia';
const { plugin, collector } = tesseractPlugin({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
});
collector.domain('/users', { domain: 'users', description: 'User management' });
collector.route('/users/:id', 'GET', { sdk: { methodName: 'getUser' } });
collector.route('/users', 'POST', { sdk: { methodName: 'createUser' } });
const app = new Elysia()
.use(plugin)
.get('/users/:id', ({ params }) => getUser(params.id))
.post('/users', ({ body }) => createUser(body))
.listen(3000);The plugin triggers generation automatically in its onStart hook when TESSERACT_GENERATE=1 is set.
Trigger: TESSERACT_GENERATE=1 bun run dist/app.js
NestJS
Decorate controllers and methods, then call collectFromNestControllers() at bootstrap:
// users.controller.ts
import { Controller, Get, Post, Param, Body } from '@nestjs/common';
import { SDKMethod, SDKDomain } from '@apollo-deploy/tesseract/nestjs';
@Controller('users')
@SDKDomain({ domain: 'users', description: 'User management' })
export class UsersController {
@Get(':id')
@SDKMethod({ methodName: 'getUser', schema: { response: { 200: { $ref: 'User' } } } })
getUser(@Param('id') id: string) { ... }
@Post()
@SDKMethod({ methodName: 'createUser' })
createUser(@Body() body: CreateUserDto) { ... }
}// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import {
SDKCollector,
collectFromNestControllers,
} from '@apollo-deploy/tesseract/nestjs';
import { UsersController } from './users/users.controller';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.init();
if (process.env.TESSERACT_GENERATE) {
const collector = new SDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
additionalTargets: [{ language: 'kotlin', output: './sdk/java' }],
});
collectFromNestControllers([UsersController], collector);
await collector.generate();
await app.close();
process.exit(0);
}
await app.listen(3000);
}
bootstrap();Requires reflect-metadata (standard NestJS dep) and "emitDecoratorMetadata": true in tsconfig.json.
Trigger: TESSERACT_GENERATE=1 node dist/main.js
Generic / any framework
Use SDKCollector directly from the main package with any HTTP framework:
import { SDKCollector } from '@apollo-deploy/tesseract';
const collector = new SDKCollector({
info: {
title: 'My API',
version: '1.0.0',
baseUrl: 'https://api.example.com',
},
output: './packages/api-sdk',
additionalTargets: [
{ language: 'kotlin', output: './sdk/java' },
{ language: 'python', output: './sdk/python', packageName: 'my-api' },
],
});
collector.domain('/users', { domain: 'users', description: 'User management' });
collector.route('/users/:id', 'GET', { sdk: { methodName: 'getUser' } });
collector.route('/users', 'POST', { sdk: { methodName: 'createUser' } });
// After all routes are declared:
if (await collector.tryGenerate()) process.exit(0);Output
Tesseract generates a complete, publishable package. Structure varies by sdkStyle and target language.
TypeScript (default)
Functional style (default — createMyClient(config)):
sdk/
├── package.json
├── tsconfig.json
├── README.md
├── index.ts
└── src/
├── client.ts
├── transport/
│ ├── axios.ts
│ └── sse.ts
├── domain/
│ └── users.ts
├── types/
│ ├── models.ts
│ ├── common.ts
│ ├── errors.ts
│ └── index.ts
├── utils/
│ └── query.ts
└── webhooks/
└── handler.tsClass style (--sdk-style class — new MySDK('api_key', options?)): generates client-class.ts, domain-class/ files, and a matching index.ts.
Kotlin
Generates a Gradle project using Ktor HTTP client, kotlinx.serialization, and coroutines:
sdk/java/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle.properties
├── gradle/wrapper/gradle-wrapper.properties
├── .gitignore
├── README.md
└── src/main/kotlin/<package>/
├── Client.kt
├── internal/Transport.kt
├── exceptions/SdkException.kt
├── models/Types.kt
└── api/
└── UsersAPI.ktOther languages
Python, Ruby/Rails, PHP/Laravel, Go, Java, Rust, Elixir, Swift, Zig, .NET, and CLI targets each generate native project scaffolding with the appropriate package-manager metadata and typed client code.
Generated TypeScript SDK Features
- Typed client with grouped domain methods
- Automatic retries with exponential backoff, jitter, and customizable retry logic
- Configurable timeouts at both transport and per-request level
- Security scheme support — API key, Bearer, OAuth2, OpenID Connect
- Plugin system —
SDKPluginhooks for request/response/error interception - Telemetry hooks —
onRequest,onResponse,onErrorwith timing data - Idempotency keys on mutating requests
- SSE streaming — Typed
AsyncIterable<SSEEvent<T>>with automatic reconnection, heartbeat detection, and buffer overflow protection - Webhook handlers — Typed event registry with HMAC verification, replay protection, handler timeouts, and one-time handlers
- AbortSignal support for request cancellation
- Per-request overrides — timeout, headers, retry config
Example Usage of Generated TypeScript SDK
import { createMyApiClient } from './sdk';
const client = createMyApiClient({
baseUrl: 'https://api.example.com',
apiKey: 'sk_...',
timeoutMs: 10000,
retries: { attempts: 3, backoffMs: 500, jitter: true },
plugins: [
{
name: 'logger',
beforeRequest(config) {
console.log('→', config.method, config.url);
},
},
],
onError({ method, url, error, attempt, willRetry }) {
console.error(
`${method} ${url} failed (attempt ${attempt}, retry: ${willRetry})`,
);
},
});
// Typed domain methods
const user = await client.users.get('user_123');
// Per-request overrides
const result = await client.orders.list(
{ page: 1, limit: 20 },
{ timeoutMs: 30000, retries: { attempts: 5 } },
);
// SSE streaming
for await (const event of client.events.stream({ signal: controller.signal })) {
console.log(event.type, event.data);
}
// Webhooks
client.webhooks.on('orderCreated', async (payload, meta) => {
console.log('New order:', payload.id);
});Pipeline
Tesseract processes manifests through three stages:
Intake — Reads and validates the manifest, converts it to an intermediate representation (SDKIR). Handles JSON Schema → TypeScript type conversion, parameter extraction, and domain grouping. Internal-stability domains are filtered out.
Enrich — Augments the SDKIR with a symbol table, import graph, topologically sorted schemas (with cycle detection), render decisions (interface / type alias / enum / union), method signatures, and doc blocks.
Write — Diff-aware file writer. Only overwrites files whose content has actually changed, making it safe for CI/CD regeneration.
Code Generation Approach
Tesseract uses a dual strategy:
- ts-morph (AST-based) for type definitions — interfaces, enums, type aliases
- Handlebars templates for everything else — client, transport, domain methods, utilities
TypeScript output is formatted with Prettier.
Programmatic API
import { generate } from '@apollo-deploy/tesseract';
await generate({
input: './manifest.json',
output: './sdk',
language: 'kotlin',
packageName: '@my-org/api-sdk',
versionBump: 'minor',
});You can also pass a pre-parsed manifest object:
import { generate } from '@apollo-deploy/tesseract';
import type { BackendManifest } from '@apollo-deploy/tesseract';
const manifest: BackendManifest = {
/* ... */
};
await generate({ manifest, output: './sdk', language: 'kotlin' });Configuration
Either input or manifest must be provided.
| Option | Type | Description |
| ---------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| input | string? | Path to the manifest file. Required if manifest is not provided. |
| manifest | BackendManifest? | Pre-parsed manifest object. Alternative to input. |
| output | string | Output directory |
| language | TargetLanguage? | Target selector from Target Languages; defaults to typescript |
| packageName | string? | Override npm/package name |
| packageVersion | string? | Exact generated package version override |
| versionBump | 'patch' \| 'minor' \| 'major'? | Automatic bump when packageVersion is omitted; defaults to patch |
| clientName | string? | Override client class name |
| baseUrl | string? | Override default base URL |
| sdkStyle | 'functional' \| 'class'? | functional (default) generates a createMyClient(config) factory; class generates a Resend-style new MySDK('api_key', options?) class |
| clientType | 'internal' \| 'public'? | internal (default) exposes full config options; public accepts only an auth key with baseUrl baked in |
| environments | { name: string; baseUrl: string }[]? | Named environment presets |
| dryRun | boolean? | Transform only, no file I/O |
| check | boolean? | Compare output without writing |
| prettier | boolean? | Toggle formatting (default: true) |
CollectorOptions
Shared by all framework adapters and SDKCollector. Extends the programmatic API config with additionalTargets.
| Option | Type | Description |
| ------------------- | -------------------------------- | ------------------------------------------------------------ |
| info | object | API metadata: title, version, baseUrl?, description? |
| output | string | Primary output directory |
| language | TargetLanguage? | Primary target language (default: typescript) |
| additionalTargets | AdditionalTarget[]? | Extra languages to emit alongside the primary output |
| schemaPackage | object? | External type package: name, version?, importPath? |
| sdkStyle | 'functional' \| 'class'? | SDK style |
| clientType | 'internal' \| 'public'? | Client type |
| packageName | string? | Override package name |
| packageVersion | string? | Exact package version override |
| versionBump | 'patch' \| 'minor' \| 'major'? | Automatic bump policy; defaults to patch |
Each AdditionalTarget entry:
| Field | Type | Description |
| ---------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| language | TargetLanguage | Required. Target language for this output |
| output | string | Required. Output directory |
| packageName | string? | Overrides primary packageName for this target |
| packageVersion | string? | Overrides primary packageVersion for this target |
| versionBump | 'patch' \| 'minor' \| 'major'? | Overrides primary versionBump for this target |
| clientType | 'internal' \| 'public'? | Overrides primary clientType for this target |
| sdkStyle | 'functional' \| 'class'? | Overrides primary sdkStyle for this target |
| schemaPackage | object \| null? | Override schema ownership. Targets other than typescript and cli default to local expansion; pass null explicitly to force it. |
Requirements
- Node.js ≥ 18 or Bun ≥ 1.0
License
MIT
