Programmatic API for building URLSpec files
@urlspec/builder provides a fluent, programmatic API for generating .urlspec files in TypeScript. Instead of writing URLSpec syntax manually, you can build URLSpec documents using a chainable API, making it ideal for code generation tools, dynamic specification generation, and migration scripts.
- Fluent API: Chain method calls for readable code
- Type-Safe: Full TypeScript support with type checking
- AST Generation: Built on top of
@urlspec/language - File Output: Write directly to
.urlspecfiles - Dynamic Generation: Generate specifications programmatically (e.g., from loops, API schemas)
# npm
npm install @urlspec/builder
# yarn
yarn add @urlspec/builder
# pnpm
pnpm add @urlspec/builderimport { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
spec.addParamType('sortOrder', ['recent', 'popular', 'trending']);
spec.addParamType('jobStatus', ['active', 'closed', 'draft']);
spec.addGlobalParam({
name: 'utm_source',
type: 'string',
optional: true,
});
spec.addPage({
name: 'list',
path: '/jobs',
parameters: [
{ name: 'category', type: 'string', optional: true },
{ name: 'sort', type: 'sortOrder' },
],
});
spec.addPage({
name: 'detail',
path: '/jobs/:job_id',
parameters: [
{ name: 'job_id', type: 'string' },
{ name: 'preview', type: ['true', 'false'], optional: true },
{ name: 'status', type: 'jobStatus', optional: true },
],
});
// Output to string
console.log(spec.toString());
// Write to file
await spec.writeFile('./jobs.urlspec');Output:
param sortOrder = "recent" | "popular" | "trending";
param jobStatus = "active" | "closed" | "draft";
global {
utm_source?: string;
}
page list = /jobs {
category?: string;
sort: sortOrder;
}
page detail = /jobs/:job_id {
job_id: string;
preview?: "true" | "false";
status?: jobStatus;
}
Main builder class for constructing URLSpec documents.
const spec = new URLSpec();Add a reusable parameter type definition.
// Primitive type
spec.addParamType('status', 'string');
// String literal
spec.addParamType('role', 'admin');
// Union of string literals
spec.addParamType('sort', ['asc', 'desc']);
spec.addParamType('priority', ['low', 'medium', 'high']);
// Reference to another param type (define that type first)
spec.addParamType('userSort', 'sort');ParamType Definition:
type ParamType = 'string' | string | string[];Add a global parameter that applies to all pages.
spec.addGlobalParam({
name: 'utm_source',
type: 'string',
optional: true,
});
spec.addGlobalParam({
name: 'debug',
type: ['true', 'false'],
optional: true,
});Add a page definition.
spec.addPage({
name: 'userProfile',
path: '/users/:user_id',
parameters: [
{ name: 'user_id', type: 'string' },
{ name: 'tab', type: ['posts', 'likes', 'comments'], optional: true },
],
});PageDefinition Interface:
interface PageDefinition {
name: string;
path: string;
parameters?: ParameterDefinition[];
comment?: string; // Not yet implemented
}ParameterDefinition Interface:
interface ParameterDefinition {
name: string;
type: ParamType;
optional?: boolean;
}Build and return the Langium AST document.
const ast = spec.toAST();
console.log(ast.pages);Convert the spec to formatted .urlspec text.
const urlspecText = spec.toString();
console.log(urlspecText);Write the spec to a file.
await spec.writeFile('./output/api.urlspec');import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
spec.addPage({
name: 'home',
path: '/',
});
spec.addPage({
name: 'article',
path: '/articles/:article_id',
parameters: [
{ name: 'article_id', type: 'string' },
],
});
console.log(spec.toString());Generate multiple similar pages programmatically:
import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
// Define available statuses
const statuses = ['pending', 'approved', 'rejected', 'archived'];
// Generate a page for each status
for (const status of statuses) {
spec.addPage({
name: `${status}Jobs`,
path: `/jobs/${status}`,
parameters: [
{ name: 'page', type: 'string', optional: true },
{ name: 'limit', type: 'string', optional: true },
],
});
}
await spec.writeFile('./jobs.urlspec');import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
// Define reusable types
spec.addParamType('category', ['electronics', 'clothing', 'food', 'books']);
spec.addParamType('sortBy', ['price', 'popularity', 'newest']);
spec.addParamType('sortOrder', ['asc', 'desc']);
// Use type references in pages
spec.addPage({
name: 'products',
path: '/products',
parameters: [
{ name: 'cat', type: 'category', optional: true },
{ name: 'sort', type: 'sortBy', optional: true },
{ name: 'order', type: 'sortOrder', optional: true },
],
});
spec.addPage({
name: 'search',
path: '/search',
parameters: [
{ name: 'q', type: 'string' },
{ name: 'category', type: 'category', optional: true },
],
});
console.log(spec.toString());import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
// Add global tracking parameters
spec.addGlobalParam({
name: 'utm_source',
type: 'string',
optional: true,
});
spec.addGlobalParam({
name: 'utm_campaign',
type: 'string',
optional: true,
});
spec.addGlobalParam({
name: 'utm_medium',
type: ['email', 'social', 'cpc', 'banner'],
optional: true,
});
// These pages will inherit global parameters
spec.addPage({
name: 'landing',
path: '/landing',
});
spec.addPage({
name: 'signup',
path: '/signup',
parameters: [
{ name: 'plan', type: ['free', 'pro', 'enterprise'] },
],
});
await spec.writeFile('./analytics.urlspec');import { URLSpec } from '@urlspec/builder';
// Hypothetical OpenAPI schema
const openAPISchema = {
basePath: 'https://api.example.com',
paths: {
'/users': {
get: {
parameters: [
{ name: 'page', type: 'integer' },
{ name: 'limit', type: 'integer' },
],
},
},
'/users/{userId}': {
get: {
parameters: [
{ name: 'userId', in: 'path', type: 'string' },
],
},
},
},
};
// Convert to URLSpec
const spec = new URLSpec();
for (const [path, methods] of Object.entries(openAPISchema.paths)) {
const getMethod = methods.get;
if (getMethod) {
// Convert "/users/{userId}" to camelCase name like "users" or "usersById"
const segments = path.split('/').filter(Boolean);
const name = segments
.map((s, i) => s.startsWith('{') ? 'by' + s[1].toUpperCase() + s.slice(2, -1) : (i === 0 ? s : s[0].toUpperCase() + s.slice(1)))
.join('');
const urlspecPath = path.replace(/{(\w+)}/g, ':$1');
spec.addPage({
name,
path: urlspecPath,
parameters: getMethod.parameters.map(p => ({
name: p.name,
type: 'string', // All types are string in URLSpec
optional: p.in !== 'path',
})),
});
}
}
console.log(spec.toString());import { URLSpec } from '@urlspec/builder';
// Legacy route definitions
const legacyRoutes = [
{ name: 'home', path: '/' },
{ name: 'about', path: '/about' },
{ name: 'contact', path: '/contact' },
{ name: 'product', path: '/products/:id', params: ['id'] },
];
// Convert to URLSpec
const spec = new URLSpec();
for (const route of legacyRoutes) {
spec.addPage({
name: route.name,
path: route.path,
parameters: route.params?.map(param => ({
name: param,
type: 'string',
})),
});
}
await spec.writeFile('./website.urlspec');import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
spec.addPage({ name: 'home', path: '/' });
// Get the AST
const ast = spec.toAST();
// Access AST properties
console.log(ast.$type); // "URLSpecModel"
console.log(ast.pages.length); // 1
// Use with @urlspec/language functions
import { print } from '@urlspec/language';
const doc = {
parseResult: { value: ast },
} as any;
console.log(print(doc));For advanced use cases, you can use the exported AST builder functions directly:
import {
createURLSpecDocument,
createPageDeclaration,
createParameterDeclaration,
createStringType,
createStringLiteralType,
createUnionType,
} from '@urlspec/builder';
const ast = createURLSpecDocument({
pages: [
createPageDeclaration(
'users',
'/users',
[
createParameterDeclaration('sort', createStringLiteralType('name'), true),
]
),
],
});The package exports all necessary TypeScript types:
import type {
URLSpec,
ParamType,
ParameterDefinition,
PageDefinition,
// Langium AST types
URLSpecDocument,
PageDeclaration,
ParameterDeclaration,
Type,
// ... and more
} from '@urlspec/builder';import { URLSpec } from '@urlspec/builder';
const spec = new URLSpec();
// Add at least one page
spec.addPage({
name: 'home',
path: '/',
});
const ast = spec.toAST(); // Valid URLSpec document
console.log(ast.pages.length); // 1Generate URLSpec files from database schemas, GraphQL schemas, or API documentation.
Programmatically create URLSpec documents for testing parsers and validators.
Convert legacy routing configurations to URLSpec format.
Generate specs based on runtime configuration or environment variables.
Automatically generate URLSpec files from your API implementation.
yarn build# Run tests
yarn test
# Watch mode
yarn test:watch- @urlspec/language - Core language implementation (used internally)
- urlspec-vscode-extension - VS Code extension
Contributions are welcome! Please see the root repository README for contribution guidelines.
MIT License - see LICENSE for details