Getting started
Install
Core holds the codec contract, shapes, values and every codec that needs no peer library. The WarpDrive adapter wires them into a store. Add other packages only for the libraries you use.
pnpm add @millwork-ts/core @millwork-ts/warp-drive
# a date library, if you read dates
pnpm add @millwork-ts/temporal temporal-polyfill
WarpDrive and ember-data 5.8 or later. Core and every codec package import nothing from Ember or WarpDrive, so you can use the codecs anywhere.
Getting started
Shapes and values
A record is an entity: it has an id, and the store tracks it. The parts inside a record have no id. Millwork has two kinds of part, after the entity vs value object split.
-
A value is immutable.
Money, a date and aLatLngare values. To change one, set a new one. Two values are equal when their codecequalssays so. - A shape is a nested object that you edit in place, such as an address in a form. It tracks each change by path and rolls back by path.
A codec turns one raw wire value into a value and back. Shapes are made of fields, and each field can name a codec.
Codecs
The codec contract
A codec is a frozen object with a name and four functions. Every codec in Millwork comes
from defineCodec, which adds the rules for null, errors and
freezing.
| Member | What it does |
|---|---|
name |
The name a field uses in a schema, such as 'money'. |
hydrate(raw, options) |
Raw wire value to value. Forgiving: bad data gives undefined. It
never throws.
|
serialize(value, options) |
Value back to the wire form. Strict: a value of the wrong type throws a
TypeError.
|
equals(a, b) |
Compares two values. Dirty checks use it. |
isValue(input) |
A type guard for the value type. |
Bad data is undefined
When a codec cannot read a raw value, the field reads undefined and Millwork
sends a report. One bad field does not fail the whole response. By default the report is
one console.warn for each codec and raw value. Send it somewhere else with
onInvalid:
import { onInvalid } from '@millwork-ts/core'
onInvalid(({ codec, raw, error }) => {
myErrorTracker.capture(error, { extra: { codec, raw } })
})
onInvalid(undefined) // back to the default warning
null and a missing value read as undefined with no report. To
keep null as null, wrap the codec: nullable(money).
Equality
Each codec decides what "the same" means. money compares the currency and the
amount at a common scale, so 19.99 USD equals 19.990 USD. luxon
datetime compares the instant. A record field that is set to an equal value
is not dirty.
Codecs
Core codecs
These need no peer library. Each one is a named export of @millwork-ts/core,
and the store knows each one by its name.
| Name | Value | Wire | Options |
|---|---|---|---|
money |
Money |
See money | wire, currency |
decimal |
Decimal |
"123.4500" |
scale |
bigint |
bigint |
"9007199254740993" |
|
number-string |
number |
"42", "NaN", "Infinity" |
|
percent |
Percent |
0.15, 15 or 1500 |
unit: 'fraction', 'percent',
'bps'; as: 'number',
'string'
|
ratio |
frozen { num, den } |
"16:9", { num, den } |
wire: 'string', 'object' |
boolean-ish |
boolean |
"true", "1", "Y", 1 |
true, false: the raw to write |
url |
frozen URL |
a URL string; only http:, https:,
mailto: and tel: by default
|
base, protocols (a list, or '*' for all)
|
email |
string |
domain in lower case | |
uuid, ulid |
string |
lower case; ulidTime(id) gives the time |
|
snowflake |
bigint |
a 64-bit id string; snowflakeTime(id, epoch) |
|
country, currency-code, language,
locale, time-zone
|
string |
ISO codes, BCP 47 tags, IANA zone ids | |
latlng |
frozen { lat, lng } |
{ lat, lng }, { latitude, longitude },
[a, b], "a,b"
|
order: 'latlng', 'lnglat';
wire
|
geojson |
frozen GeoJSON | RFC 7946 | |
bytes |
Uint8Array |
base64, base64url, hex | encoding |
byte-size |
number |
1048576, "1 MiB" |
|
bitflags |
ReadonlySet<string> |
an integer | flags: the names, bit 0 first |
mime-type |
frozen { type, subtype, parameters } |
"text/html; charset=utf-8" |
|
i18n-text |
I18nText, with .for(locale, fallbacks) |
{ "en": "…", "fr": "…" } |
Codecs from codecs
arrayOf, nullable, setOf, mapOf and
rangeOf wrap another codec. Their options go under of.
rangeOf reads { start, end }, [a, b], ISO
"a/b" and Postgres "[a,b)". Pass the codec object to a field,
because the store knows these by the object, not by a name.
import { decimal, rangeOf } from '@millwork-ts/core'
import { valueField } from '@millwork-ts/warp-drive'
valueField('priceBand', rangeOf(decimal), { wire: 'postgres', of: { scale: 2 } })
Codecs
Dates and times
Core has no date type. Pick one date package. Each one gives the same codec names, with
the type of its library. Each codecs record has every codec two times: by
kind (date) and with a prefix (luxon:date). Use the prefix if
you register two date packages.
| Name | Wire | temporal | luxon | date-fns | dayjs |
|---|---|---|---|---|---|
date |
"2026-12-01" |
PlainDate |
DateTime |
FrozenDate |
Dayjs |
time |
"14:30", "14:30:00.000" |
PlainTime |
DateTime |
no | Dayjs |
local-datetime |
"2026-12-01T14:30:00" |
PlainDateTime |
DateTime |
no | Dayjs |
datetime |
RFC 3339, with an offset or Z |
Instant |
DateTime |
FrozenDate |
Dayjs |
zoned-datetime |
"…-05:00[America/Toronto]", { at, zone } |
ZonedDateTime |
DateTime |
FrozenTZDate, from /tz |
Dayjs |
epoch |
a number, or a string for large values | Instant |
DateTime |
FrozenDate |
Dayjs |
year-month |
"2026-12" |
PlainYearMonth |
DateTime |
no | Dayjs |
duration |
ISO 8601 "PT1H30M", or a number |
Duration |
Duration |
frozen Duration |
dayjs duration |
interval |
"a/b", "a/PT1H", { start, end } |
frozen { start, end } |
Interval |
frozen Interval |
no |
| Option | Codecs | Use |
|---|---|---|
keepOffset |
datetime |
luxon and dayjs write the offset of the wire. Temporal Instant and
Date have no offset, so they always write Z.
|
unit |
epoch |
's', 'ms' (default), 'us',
'ns'
|
unit |
duration |
'iso' (default), 's', 'ms'. Months and
years never become a number.
|
wire: 'object' |
zoned-datetime, interval |
Write { at, zone } or { start, end }. Both forms are
read.
|
A date-only string is never read with new Date("2026-12-01"). That gives UTC
midnight, which is the day before in western time zones. Temporal needs
temporal-polyfill in browsers that do not ship it: import
'temporal-polyfill/global' once.
Codecs
Money and decimals
The core money codec gives a Money: a bigint
amount, an ISO 4217 currency and a scale. It reads a float amount, but it never writes
one.
wire |
Raw |
|---|---|
'minor' (default) |
{ "amount": 1999, "currency": "USD" } |
'decimal' |
{ "amount": "19.99", "currency": "USD" } |
'snapshot' |
a dinero.js v2 snapshot |
'minor-scaled' |
{ "amount": 19990, "currency": "USD", "scale": 3 } |
'amount' |
1999, with the currency in the currency option |
import { Money } from '@millwork-ts/core'
const price = Money.fromDecimal('19.99', 'USD')
price.toDecimalString() // "19.99"
String(price) // "19.99 USD"
price.equals(Money.fromMinor(1999, 'USD')) // true
Core Money holds the amount. For arithmetic and allocation, use
@millwork-ts/dinero: the dinero codec reads the same five wire
forms into a dinero.js object. @millwork-ts/decimal makes a codec for
decimal.js, big.js or bignumber.js:
import Decimal from 'decimal.js'
import { decimalCodec } from '@millwork-ts/decimal'
import { registerCodecs } from '@millwork-ts/core'
// The default name is 'big-decimal', so it does not clash with the core 'decimal'.
registerCodecs({ 'big-decimal': decimalCodec(Decimal) })
Codecs
Contact, geo and more
Each of these packages wraps one library. The full options are in each README.
| Package | Name | Wire | Options |
|---|---|---|---|
@millwork-ts/phone |
phone |
E.164 "+14165551234"; national with a country |
defaultCountry, metadata |
@millwork-ts/color |
color |
hex, rgb(), hsl(), oklch(), an rgb object
|
format: the form to write |
@millwork-ts/quantity |
quantity |
{ "value": 12.5, "unit": "kg" }, "12.5 kg" |
wire: 'object', 'string' |
@millwork-ts/semver |
semver |
"1.2.3-beta.1" |
loose |
@millwork-ts/ip |
ip, cidr |
"192.168.0.1", "::1", "10.0.0.0/8" |
unmapIPv4 |
@millwork-ts/rrule |
rrule |
"FREQ=WEEKLY;BYDAY=MO,WE" |
|
@millwork-ts/cron |
cron |
"0 9 * * 1-5" |
dialect: 'unix', 'seconds' |
@millwork-ts/geo |
wkt, geohash |
WKT "POINT(-79.38 43.65)", "dpz83d" |
precision (geohash) |
Register a package codec before the store asks for its Transformations:
registerCodecs(codecs), with the codecs record of the package.
See SchemaRecord.
Shapes and values
Declare a shape
A shape class extends Shape and has a static type. The
type is its name in schemas, because minifiers rename classes. Each
type must be unique: a second class with the same type throws.
import { Shape, field, type LatLng, type Money, type ShapeArray } from '@millwork-ts/core'
export class Address extends Shape {
static override type = 'address'
@field declare city: string // plain JSON
@field declare zip: string
@field('latlng', { optional: true }) declare location?: LatLng // a codec
}
export class LineItem extends Shape {
static override type = 'line-item'
@field declare sku: string
@field declare qty: number
@field('money', { wire: 'decimal' }) declare price: Money
}
export class Order extends Shape {
static override type = 'order-draft'
@field(Address) declare shipTo: Address // a nested shape
@field(LineItem, { array: true, key: 'sku' }) declare items: ShapeArray<LineItem>
}
Ember compiles legacy decorators, so the fields use declare. With standard
decorators, write @field accessor city!: string.
The JSON form
shape({ type, fields }) and value({ type, fields }) make a class
with the same power, for example from a schema that the server sends.
import { shape } from '@millwork-ts/core'
export const Contact = shape({
type: 'contact',
fields: [
{ name: 'name' },
{ name: 'email', codec: 'email' },
{ name: 'home', shape: Address, optional: true },
],
})
Polymorphic fields
Give a map of discriminator values to classes. The key is $type by default.
It stays in the raw value, so it goes back to the server.
export class Card extends Shape {
static override type = 'card'
@field declare last4: string
}
export class Bank extends Shape {
static override type = 'bank'
@field declare iban: string
}
export class Checkout extends Shape {
static override type = 'checkout'
// { "$type": "card", "last4": "4242" } reads as a Card
@field({ card: Card, bank: Bank }) declare payment: Card | Bank | undefined
// { "kind": "bank", "iban": "…" } reads as a Bank
@field({ card: Card, bank: Bank }, { discriminator: 'kind' }) declare refund?: Card | Bank
}
An unknown discriminator, or no raw value, reads as undefined.
Shapes and values
Change tracking
Shapes and shape arrays have the Tracked API. A shape keeps no change log: it
compares the local raw value with the remote raw value at each path, with each codec
equals. So the record API and a server push never get out of step with it.
order.shipTo.city = 'Montreal'
order.shipTo.zip = 'H2X'
order.shipTo.isDirty // true
order.shipTo.changes()
// [{ kind: 'set', path: ['city'], from: 'Toronto', to: 'Montreal' },
// { kind: 'set', path: ['zip'], from: 'M5V', to: 'H2X' }]
order.shipTo.rollback(['city']) // undo one field
order.shipTo.rollback() // undo everything
Set a field back to its remote value and the change is gone: no flag stays on.
Shape arrays
A shape array is a frozen array. Change it with add, remove and
move, so each change is tracked. A member is named by its key,
or by its index when the field has no key.
order.items.add({ sku: 'c', qty: 3 }) // at the end
order.items.add({ sku: 'z', qty: 1 }, 0) // at an index
order.items.remove('a') // by key, by index, or the shape itself
order.items.move(0, 2)
order.items.changes()
// [{ kind: 'remove', path: ['a'], … }, { kind: 'add', path: ['c'], … }, …]
order.items.rollback(['a']) // puts 'a' back at its remote index
kind |
from and to |
|---|---|
set |
A leaf gives its hydrated values. A whole shape gives raw JSON. |
add, remove |
The raw JSON of the member. |
move |
The lists of member keys. |
Do not change the key of a member while you edit it. The key is how a change finds its member.
Shapes and values
Value classes
A Value class is an immutable value made of fields. A write throws a
TypeError. To change one, make a copy with with().
import { Money, Value, field } from '@millwork-ts/core'
export class Price extends Value {
static override type = 'price'
@field('money', { wire: 'decimal' }) declare amount: Money
@field declare label: string
}
const full = new Price({ amount: Money.fromDecimal('19.99', 'USD'), label: 'Full' })
const sale = full.with({ label: 'Sale' })
full.label = 'Sale' // TypeError
full.equals(sale) // false: field by field, with each codec equals
A value class is also a codec, Price.codec. So a record field and a legacy
transform take the class with no extra code: valueField('price', Price).
WarpDrive
SchemaRecord
Every Millwork field is a kind: 'field' with a Millwork Transformation. The
cache keeps the raw JSON, and the record gives the value or the shape. Give the store
every Transformation with one call:
// app/services/store.ts
import { codecs as temporal } from '@millwork-ts/temporal'
import { registerCodecs, transformations } from '@millwork-ts/warp-drive'
import { useLegacyStore } from '@warp-drive/legacy'
import { JSONAPICache } from '@warp-drive/json-api'
import { InvoiceSchema, OrderSchema } from './schemas'
// Core codecs are in the registry already. Add package codecs first:
// transformations() reads the registry when you call it.
registerCodecs(temporal)
export default useLegacyStore({
linksMode: true,
cache: JSONAPICache,
schemas: [OrderSchema, InvoiceSchema],
transformations: transformations(),
})
| Helper | Field |
|---|---|
valueField(name, codec?, options?) |
A value. The codec is a name, a codec object or a Value class. With
no codec, a plain field.
|
valueArrayField(name, codec, options?) |
A list of values. The codec runs on each element. |
shapeField(name, Class, options?) |
A shape, or a map of classes for a polymorphic shape. |
shapeArrayField(name, Class, { key }) |
A ShapeArray. key names the member identity. |
// app/schemas.ts
import { withDefaults } from '@warp-drive/core/reactive'
import { shapeArrayField, shapeField, valueField } from '@millwork-ts/warp-drive'
export const InvoiceSchema = withDefaults({
type: 'invoice',
fields: [
valueField('total', 'money', { wire: 'decimal' }),
valueField('issuedOn', 'date'),
valueField('price', Price),
shapeField('billTo', Address),
shapeArrayField('items', LineItem, { key: 'sku' }),
shapeField('payment', { card: Card, bank: Bank }, { discriminator: '$type' }),
],
})
A field read is memoized: invoice.total === invoice.total. A new raw value
from the server gives a new value.
Polaris records: checkout
A Polaris record is immutable. Edit a copy from checkout, and import it from
@millwork-ts/warp-drive: the Millwork version records the store, so the copy
can read its remote values for dirty state and rollback.
import { checkout } from '@millwork-ts/warp-drive'
const draft = await checkout(invoice)
draft.billTo.city = 'Montreal'
draft.billTo.isDirty // true
A record from a withDefaults schema on a legacy-mode store is editable with
no checkout.
WarpDrive
Legacy Model
The @millwork-ts/warp-drive/legacy entry loads no WarpDrive code at run time.
It gives @attr transforms for values, and a class form for records with
shapes.
Values on a Model: @attr transforms
Each core codec is an app transform already, so @attr('money') needs no file
in your app. The @attr options go to the codec.
import Model, { attr } from '@ember-data/model'
import type { Money } from '@millwork-ts/core'
import type { MoneyTransform } from '@millwork-ts/warp-drive/legacy'
export default class Order extends Model {
@attr<MoneyTransform>('money', { wire: 'decimal' }) declare total: Money
}
A codec from another package needs registerTransforms in an instance
initializer. It adds the codecs to the registry and to the app as
transform:<name>.
// app/instance-initializers/millwork.ts
import type ApplicationInstance from '@ember/application/instance'
import { datetime, duration } from '@millwork-ts/luxon'
import { registerTransforms } from '@millwork-ts/warp-drive/legacy'
export function initialize(owner: ApplicationInstance) {
registerTransforms(owner, { datetime, duration })
}
export default { initialize }
ember-data runs an @attr transform only in a serializer.
store.push does not run it, so a pushed Model record shows the
raw value. For pushed data, use a schema field (valueField).
Shapes: the class form
A Model attribute cannot hold a shape. Put the fields on a plain class with
@value, @shape and @shapeArray, and make a
legacy-mode schema from it. The record stays editable with no checkout, and
rollbackAttributes() works for the whole record.
import type { Money, ShapeArray } from '@millwork-ts/core'
import { modelSchema, shape, shapeArray, value } from '@millwork-ts/warp-drive/legacy'
import { withDefaults } from '@warp-drive/legacy/model/migration-support'
class OrderFields {
@value() declare customer: string // plain
@value('money', { wire: 'decimal' }) declare total: Money
@shape(Address) declare shipTo: Address
@shapeArray(LineItem, { key: 'sku' }) declare items: ShapeArray<LineItem>
@shape({ card: Card, bank: Bank }) declare payment: Card | Bank | undefined
}
export const OrderSchema = withDefaults(modelSchema('order', OrderFields))
Give OrderSchema to the store with useLegacyStore, as in
SchemaRecord.
WarpDrive
Known limits
WarpDrive has some sharp edges under nested data. Millwork works around them. Each decision has a record on GitHub.
- Shapes write the whole top-level value. The nested write path of the JSON:API cache loses sibling edits, and throws on a field with no remote value. So a shape write copies one top-level value. This costs more for a large shape. ADR 0005
-
Codecs use
kind: 'field', never'object'.kind: 'object'removes the prototype, so aMoneywould arrive as a plain object. Raw values in the cache are always JSON. ADR 0001 -
Shapes are not
schema-objectfields. WarpDrive tools do not see the nested fields of a shape. The Millwork class holds them. ADR 0007 -
Use the Millwork
checkout. WarpDrive has no public link from a copy to its store. The WarpDrivecheckoutworks only if the app read the immutable record first. ADR 0009 -
A
Modelattribute cannot hold a shape, andstore.pushdoes not run@attrtransforms. ADR 0003, ADR 0012 - A push gives a new value, also when the JSON is equal. Code that compares by reference sees new data. ADR 0008
-
No
subscribe. Signals give reactivity in Ember. A template that reads a shape renders again after a write, a rollback or a push. ADR 0011 -
Temporal in Safari needs
temporal-polyfill. ADR 0006
The WarpDrive floor is 5.8.0 (ADR 0004). All decisions are in docs/adr.
Going further
Validation
No validation runs when a record reads a field. When you want a strict check, for a form or for input from outside, ask for a Standard Schema. It works for a codec and for a shape or value class.
import { money, toStandardSchema } from '@millwork-ts/core'
const total = toStandardSchema(money, { wire: 'decimal' })
total['~standard'].validate({ amount: 'x', currency: 'USD' })
// { issues: [{ message: '[millwork] money: not a decimal: "x"' }] }
const address = toStandardSchema(Address)
address['~standard'].validate({ city: 'Toronto' })
// { issues: [{ message: '[millwork] zip: required', path: ['zip'] }] }
The schema reads the raw wire form. A valid input gives the value, or a new standalone
shape. A bad input gives issues and sends no onInvalid report.
Going further
Write a codec
Use defineCodec. Write parse and format;
defineCodec gives hydrate and serialize with the
rules: null in gives undefined, a throw in
parse gives undefined and a report, and plain objects are
frozen.
import { defineCodec, registerCodecs } from '@millwork-ts/core'
export interface Temperature {
readonly celsius: number
}
export const temperature = defineCodec<number, Temperature, { unit?: 'c' | 'f' } | undefined>({
name: 'temperature',
parse(raw, options) {
if (!Number.isFinite(raw)) throw new TypeError(`not a number: ${raw}`)
return { celsius: options?.unit === 'f' ? ((raw - 32) * 5) / 9 : raw }
},
format: (value, options) =>
options?.unit === 'f' ? (value.celsius * 9) / 5 + 32 : value.celsius,
isValue: (input): input is Temperature =>
typeof input === 'object' && input !== null && 'celsius' in input,
equals: (a, b) => Math.abs(a.celsius - b.celsius) < 1e-9,
})
registerCodecs({ temperature })
// valueField('outside', 'temperature', { unit: 'f' })
- The value must be immutable: a frozen plain object, or an immutable class.
- The raw value must be JSON. Never put a
bigintor a class in it. -
equalsdefaults toObject.is. Give one for any object value.
Going further
For AI agents
llms.txt has the rules for AI coding agents that write Millwork code. llms-full.txt adds the full API reference.