Getting started

Generate from a contract

One API contract gives the typed parts of the Ember Workbench: the WarpDrive schemas, the Millwork shapes and values, the Real Enums, the Formwright validators and the Harnessed mocks. The contract can be OpenAPI 3.0 or 3.1, JSON:API (an OpenAPI document with JSON:API bodies) or GraphQL.

pnpm add @millwork-ts/core @millwork-ts/warp-drive @millwork-ts/contract @real-enums/core
pnpm add -D @millwork-ts/codegen @harnessed-ts/mock
# GraphQL contracts: the mocks run each query with graphql
pnpm add -D graphql

Put a config in the app root:

// millwork.config.ts
import { defineConfig } from '@millwork-ts/codegen'

export default defineConfig({
  source: { path: 'api/openapi.yaml' }, // or a .graphql file
  out: 'app/generated',
  dates: '@millwork-ts/temporal',
})

Ember apps: Ember compiles legacy decorators, so add decorators: 'legacy'. The classes then use @field declare city: string, and the mocks use http handlers in place of ApiHarness classes. The default, 'standard', writes @field accessor city!: string.

Then run the CLI:

npx millwork-codegen
# millwork-codegen: wrote 11 files to app/generated

Call registerContract() once, before the first read. It registers the codecs and the classes, and gives the store config.

import { useRecommendedStore } from '@warp-drive/core'
import { JSONAPICache } from '@warp-drive/json-api'
import { contractRequests, registerContract } from 'my-app/generated'

const Store = useRecommendedStore({
  cache: JSONAPICache,
  ...registerContract(), // schemas and transformations
  handlers: [contractRequests], // REST and GraphQL only
})

Getting started

What it writes

Each file starts with a "do not edit" line. Run the CLI again when the contract changes.

File What it holds
enums.ts A Real Enums class for each enum, and the codec map.
structures.ts A Millwork shape or value class for each object that is not an entity.
schemas.ts A WarpDrive resource schema and a record type for each entity.
requests.ts A request builder for each operation, for store.request.
normalizers.ts REST and GraphQL: the handler that turns a response into JSON:API.
validators.ts A Standard Schema validator for each type, for Formwright.
wire.ts The raw JSON type of each type.
mocks.ts Harnessed factories, mock state and API harnesses.
register.ts, index.ts registerContract, and one entry for all of it.

targets in the config picks the emitters. The default is all five: warp-drive, millwork, real-enums, formwright and harnessed.

Contracts

OpenAPI

The reader takes OpenAPI 3.0 and 3.1, in YAML or JSON. It reads each schema under components.schemas, and each path and method.

Contracts

JSON:API

JSON:API has no schema language of its own. Describe the API with an OpenAPI document whose bodies are JSON:API documents. The reader finds each resource object: an object with type (a const), id and attributes.

The reader finds JSON:API by itself. To make it required, set source: { kind: 'jsonapi', path }. WarpDrive reads JSON:API with no normalizer, so there is no normalizers.ts.

Contracts

GraphQL

The reader takes SDL (.graphql) or an introspection result (.json).

export default defineConfig({
  source: { path: 'schema.graphql' },
  dates: '@millwork-ts/temporal',
  scalars: {
    DateTime: 'datetime',
    Money: { name: 'money', options: { wire: 'decimal' } },
  },
})
import { requests } from 'my-app/generated'

const { content } = await store.request(requests.order({ id: '1' }))
content.data.state // OrderState.Shipped

Contracts

How types are classified

A contract does not say if an object is an entity, a shape or a value. Codegen decides with these rules, in this order. The first rule that applies wins.

  1. A mark: x-millwork: entity | shape | value in OpenAPI, the @millwork(kind: ...) directive in GraphQL, or the classify map in the config.
  2. Entity: a JSON:API resource object, a GraphQL type with id: ID!, or an OpenAPI object with an id that a response gives at the top level.
  3. Value: each property is readOnly.
  4. Shape: every other object. A form can edit a shape.

To see each decision and the rule that made it, run explain:

npx millwork-codegen explain
# Order: entity (entity: response id) at openapi.yaml#/components/schemas/Order
# Price: value (value: all readOnly) at openapi.yaml#/components/schemas/Price
# Address: shape (shape: default) at openapi.yaml#/components/schemas/Address

When an entity field holds an entity, it is a relation. The inverse is set when exactly one field on each side links the two.

Contracts

Codec map

Contract Codec
string + date-time, date, time, duration The date package in dates. There is no default.
string + uuid, email, uri uuid, email, url
string + decimal decimal
string + int64 bigint
An object with only amount and currency money: wire: 'minor' for an integer amount, else 'decimal'
An enum of strings The generated Real Enums codec
Anything else A plain field

To change one field, use the codecs map with the key Type.field. To change a whole schema, mark it x-millwork: codec:<name>.

codecs: { 'Order.total': { name: 'money', options: { wire: 'minor' } } }

The output

WarpDrive

Each entity gets a resource schema and a record type. The default door is SchemaRecord. Set door: 'legacy' for legacy-mode schemas.

export const OrderSchema = withDefaults({
  type: 'order',
  fields: [
    valueField('state', 'order-state'),
    valueField('total', 'money', { wire: 'decimal' }),
    valueField('placedAt', 'datetime'),
    shapeField('shipTo', Address),
    shapeArrayField('items', LineItem),
    shapeField('payment', { card: Card, bank: Bank }, { discriminator: '$type' }),
    { kind: 'belongsTo', name: 'customer', type: 'customer', options: { async: false, inverse: null, linksMode: true } },
  ],
})

REST and GraphQL responses

WarpDrive's cache reads JSON:API. For a REST or GraphQL contract, codegen writes the entity map and the contractRequests handler. A request with options.contract gets its response as a JSON:API document. An embedded entity becomes a relationship and an included member. The generated requests set the option for you:

const { content } = await store.request(requests.getOrder('1'))
content.data.customer.name

The output

Shapes and values

Each object that is not an entity becomes a class in the class form, with its rules.

export class Address extends Shape {
  static override type = 'address'
  @field(undefined, { rules: { minLength: 1, maxLength: 80 } }) accessor line1!: string
  @field(undefined, { rules: { pattern: '^[0-9]{5}$' } }) accessor zip!: string
}

The rules are the Millwork field rules. shapeSchema checks them. Hydrate does not. See Validation.

The output

Real Enums

export class OrderState extends Enum {
  static Pending = OrderState.of('pending')
  static Shipped = OrderState.of('shipped')

  @is() accessor isPending!: boolean
  @is() accessor isShipped!: boolean
}

A member name comes from the value in PascalCase. x-enum-varnames in OpenAPI replaces it. enumAccessors: false in the config removes the @is() accessors. enumClasses is the map for enumTransformations from @real-enums/warp-drive, if you prefer it to the Millwork codecs.

The output

Formwright validators

validators has a Standard Schema for each type. Each one checks raw JSON, a shape or value, or a record with the same fields. Pass it to the Formwright @validator argument.

import { validators } from 'my-app/generated'

<template>
  <Form @model={{this.address}} @validator={{validators.Address}} as |f|>
    <f.Field @name="zip" />
  </Form>
</template>

An issue has the path of the field, such as ['items', 0, 'sku']. A field value of the wrong type is an issue at its path. The validator does not throw.

The output

Harnessed mocks

mocks.ts calls @harnessed-ts/mock. It adds no mock logic of its own.

import { mock } from '@harnessed-ts/mock'
import { harnesses, openapi, orderFactory, type MockState } from 'my-app/generated'

const api = mock<MockState>(env, {
  state: { orders: [orderFactory.with('shipped').build()], customers: [] },
  openapi,
})
await api.use(...harnesses)

A factory value comes from the example, then the default, then the codec and the rules. When it cannot make a value for a pattern, the CLI gives a warning: add an example to the contract.

Going further

Custom behaviour

Do not edit the generated files. To add behaviour to a shape or value, write the class in your own file and name it in extend. The generated code then imports your class.

extend: { Address: '../models/address.js' }

Going further

In CI

npx millwork-codegen --check   # fails when a file differs from the contract
npx millwork-codegen --watch   # writes the files again when the contract changes

The output goes through the app's Prettier config when the app has Prettier (an optional peer). Two runs give the same bytes.

Going further

Known limits