@substrat-run/contracts
The source of truth for every data shape that crosses a Substrat boundary. Schemas are written in Zod, so the reviewed artifact is the runtime validator — OpenAPI and JSON Schema documents are emitted from this package, never hand-maintained beside it.
pnpm add @substrat-run/contracts zodIDs (ids.ts)
Branded ULID types — opaque, sortable, no PII, and unmixable at compile time:
| Schema | Type | Notes |
|---|---|---|
tenantId | TenantId | |
scopeId | ScopeId | a ScopeId won't typecheck as a TenantId |
principalId | PrincipalId | a tenant subject |
platformActorId | PlatformActorId | a control-plane staff subject — branded apart from PrincipalId so the two can't be confused |
eventId | EventId | |
dataSubjectId | DataSubjectId | keys crypto-shredding erasure |
moduleId | ModuleId | npm-package-shaped: @substrat-run/engine-workorder |
instant | Instant | ISO 8601 with timezone, normalised to UTC; stamped kernel-side |
calendarDate | — | YYYY-MM-DD, a real month/day check, no time and no zone — a day, never an implicit midnight; never compared with or coerced into an instant |
permissionKey | PermissionKey | module-namespaced: workorder:create |
slug | — | URL-safe identifier |
import { tenantId, type TenantId } from '@substrat-run/contracts';
const t: TenantId = tenantId.parse(input); // validated + brandedIDs are deliberately meaning-free: they appear in logs and billing systems outside any jurisdiction, so they must never encode anything.
Tenancy (tenancy.ts)
tenant / Tenant, scope / Scope, plus tenantStatus, scopeStatus, storageShape ('A' | 'B') and jurisdiction ('eu' | 'us' | 'global', plus provisionableJurisdiction — the subset the control plane currently accepts), and createTenantInput. Also org / Org and createOrgInput — organizations inside a tenant, which membership tuples point at and grantToOrg targets. migrationFailure on a scope is non-null when its last migration attempt failed, which is what stops a scope that serves nothing from rendering as healthy. See Tenants & scopes.
Control plane (control-plane.ts)
adminAction (the enum of audited control-plane mutations) and adminLogEntry / AdminLogEntry — one append-only audit row: actor, action, target, before/after, timestamp. tenantId is nullable for platform-level actions that target no tenant; causedBy holds the id of the event that caused the action, when one did, which is what joins the two halves of the connector seam.
Identity lives here too: identityLink, resolvedIdentity, identityPool / poolTopology ('central' | 'tenant-bound' — whether the same external subject id in two tenants is one human or two), and orgMembership, whose revokedAt is a tombstone rather than a deletion. See The platform layer and Authentication & identity.
The owner seat of a hosted scope (#925) is here as well: ownerSeat / OwnerSeat — claimed | unclaimed | unknown, the bound owner, whether the plain first-sign-in path is still open and until when, and whether a claimLink is outstanding — and ownerClaimLink / OwnerClaimLink, the freshly minted claimUrl + expiresAt that rides one exchange from the vertical through the control plane to the dashboard and is persisted by nobody (the vertical keeps only its hash).
Errors (errors.ts)
The failure vocabulary, one closed taxonomy for every layer (D-22 / RFC 9457):
errorCode/ErrorCode—unauthenticated,permission_denied,forbidden,not_found,conflict,validation_failed,precondition_failed,rate_limited,unavailable,internal. A module never invents a code; it narrows one with areasonslug it owns (conflict+reason: 'already_exported').problem/Problem— the wire body: the RFC 9457 members pluscodeand the per-code extensions inPROBLEM_EXTENSIONS(permission_denied.permission/.entity,validation_failed.errorsasvalidationIssue[]— path, message, code —precondition_failed.entity,rate_limited.retryAfter).PROBLEM_CONTENT_TYPE,PROBLEM_TYPE_BASEandproblemTypeFor(code)name thetypeURIs;PROBLEM_CATALOGandDOCUMENTED_ERROR_CODESare what the OpenAPI emitter documents.substratError(code, message, extensions?)— the one way to throw: it types and parses the extensions at the throw site.SubstratError,isSubstratError,errorCodeOf.toProblem(err, instance?)— any thrown value to aProblem, an unknown one becominginternalwith nothing leaked;problemForStatusfor the transport-level cases.validationIssuesFrom(zodError)is what turns a failed input parse into thevalidation_failed.errorsmember.wireFailure/toWireFailure/fromWireFailure— the same error carried across a structured-clone or RPC boundary and rehydrated as the same class on the other side.
See Failures are data.
Engine seam (seam.ts)
"Parse, don't trust" in the other direction (#771): a value crossing an engine's published surface is parsed on the way out, not merely typed. The failure that catches is a vertical compiled against engine 0.3 and running against 0.4, whose row shape moved — the vertical reads a field that is now null and the first symptom is wrong data on a screen rather than a throw.
engineSeam(name) binds both halves to the name one engine answers under, in one line (#970 — four engines previously carried byte-identical copies that differed only in that name):
const { returns, columnsOf } = engineSeam('engine-workorder');returns(schema, surface, value)— parses a value against the schema the engine publishes, or refuses to publish it. Parse always, including bulk reads: dev-only validation is absent exactly where the version skew lives. Every read behind the helper is one row or one page, so the parsed set is bounded by construction.columnsOf(schema)— theSELECTlist derived from that schema, so a read asks for exactly the columns the seam promises.SELECT *pinned the published shape to whatever the physical table happened to hold.
A mismatch throws internal, deliberately, not validation_failed: the caller's input was already parsed and is not what went wrong, a 400 would blame the caller for a fault on the engine's side, and toProblem drops internal's detail from the body — so the drift is logged rather than handed to a client that can do nothing with it.
Pagination (pagination.ts)
The one list convention: keyset pages over the list's own sort key, { entries, nextCursor } out. ListPage (limit, cursor, order — the kernel-side params, unset limit meaning unbounded for an internal caller), listPageQuery / ListPageQuery (the HTTP query, which always defaults a page), Page<T> and CountedPage<T> (total, opt-in per operation because it is a second query), pageOf / countedPageOf / mapPage / isPage / pageSchema, listLimitOf (LIST_PAGE_DEFAULT 20, LIST_PAGE_MAX 200 — one resolution for the HTTP layer, ctx.page and handler-composed reads), the Link and X-Total-Count headers (PAGE_LINK_HEADER, PAGE_TOTAL_HEADER, PAGE_EXPOSED_HEADERS, nextPageLink), LIST_SORT_PARAM, pageVisible — the walk a per-row-filtered read owns, bounded by VISIBLE_SCAN_BUDGET and read in VISIBLE_BATCH-row batches; writable scope operations return a sealed continuation at a budget stop, including on an empty page, while read-only and copy walks return no budget-stop cursor (#2074); Page.rowCursors, each row's own cursor, which pageOf, mapPage and ctx.page return when asked (rowCursors: true) and withoutRowCursors strips at the wire — and pageOverFold, which cuts a page off a list the handler already folded in memory (the paged: { sortKey } half of #811, as a function).
The cursor key pageOf / pageOverFold reads must be unique and ordered the same way the query is, or the walk skips or repeats the tie. CURSOR_FIELD_SEPARATOR is what joins the halves of a composite cursor when the ordering column is not unique — U+0000, chosen because it cannot occur in an ISO instant, a ULID or a key. Name it rather than spelling the byte inline, so the two ends of one cursor cannot drift apart:
pageOverFold(entries, input, (e) => `${e.occurredAt}${CURSOR_FIELD_SEPARATOR}${e.id}`);See Lists are pages, not dumps and You compose it — sortKey.
Concurrency (concurrency.ts)
The wire half of optimistic concurrency (#129): ETAG_HEADER (ETag, always strong), IF_MATCH_HEADER, CONCURRENCY_EXPOSED_HEADERS, etagOf(version) and ifMatchAdmits(ifMatch, version). The version itself is the ULID of the entity's last event and lives in the kernel (entityVersionOf), because contracts sits below the spine and must not know which table answers. A stale tag is a precondition_failedProblem that deliberately does not carry the current version. See A read-modify-write says what it is writing over.
Idempotency (idempotency.ts)
The wire half of request idempotency (#116): IDEMPOTENCY_KEY_HEADER (Idempotency-Key), IDEMPOTENCY_REPLAYED_HEADER, IDEMPOTENCY_EXPOSED_HEADERS, isValidIdempotencyKey (IDEMPOTENCY_KEY_MAX_LENGTH), canonicalJson and requestFingerprint(operation, input) — what makes two requests the same request, so a second key use with a different fingerprint is a reuse (IDEMPOTENCY_REUSED, 409) rather than a replay — plus IDEMPOTENCY_RETENTION_MS (24 h), IDEMPOTENCY_RESULT_LIMIT and IDEMPOTENCY_REPLAY_UNAVAILABLE. The table that remembers the answer is the kernel's (_substrat_idempotency). See Writes are safe to retry.
Impersonation (impersonation.ts)
Acting as a principal with the real actor preserved (K-42): beginImpersonationInput (tenant, scope, principal, a reason of at least IMPERSONATION_MIN_REASON characters, mode, minutes), impersonationMode ('read-only' | 'write'), impersonationSession / ImpersonationSession and its impersonationSessionId, impersonationStamp (the { session, actor } pair every outbox row, denial and platform intent written under a session carries), impersonationFilter, and the bounds — IMPERSONATION_MAX_MINUTES (60, an over-ask is refused rather than clamped), IMPERSONATION_DEFAULT_MINUTES (15), DEFAULT_IMPERSONATION_LIMIT.
Denials (denial.ts)
The refused-check log's shapes (K-35): permissionDenial / PermissionDenial, denialFilter (actor, permission, operation, since/until), denialBucket and denialSummary (per actor and key, busiest first, with the window's own floor), and DEFAULT_DENIAL_LIMIT / DENIAL_LIMIT_MAX. Read through HostAdmin.listDenials / summarizeDenials. See Denials are recorded.
Refusals (refusal.ts)
The refusal log's read shapes (#1745), the denial log's sibling: refusalRecord / RefusalRecord (its kind, transition or guard; the record, fromState, attemptedState, operation, the guard predicate on a guard row, the actor and its actorKind, the problem code as reason, the invocationId), refusalFilter (kind, record, actor, operation, call, since/until), and DEFAULT_REFUSAL_LIMIT / REFUSAL_LIMIT_MAX. fromState is null on a guard row, and undeclared (UNDECLARED_STATE, from lifecycle.ts) when the record was in no declared state. A reason outside problemReason (in errors.ts, the grammar every problem code is written in) is kept as unrecognized (UNRECOGNIZED_REFUSAL_REASON). A record type that is not spelled as an entity type is kept as undeclared (refusalEntityType, UNDECLARED_ENTITY_TYPE). nameRefusedRecord(err, ref) / refusedRecordOf(err) let a guard predicate name the record its refusal is about. Read through HostAdmin.listRefusals. See A refusal is recorded.
Events (events.ts)
entityRef/EntityRef— the opaque(entityType, entityId)reference everything generic binds to.piiClass—'none' | 'pseudonymous' | 'direct', required on every event.domainEventInput— what module code passes toemit(); origin fields deliberately absent.domainEvent— the full kernel-stamped envelope.actor— aPrincipalIdor{ system: ModuleId }.
The schema enforces the crypto-shredding invariant: a PII-classed event without a subjectId fails validation. See Events & audit.
Permissions (permission.ts)
The authored surface: node, roleDefinition, roleAssignment, capabilityGrant. The evaluation representation: objectRef, relationTuple (internal to checkers). The results: decision / Decision (proof-carrying discriminated union) and effectivePermissions. See Permissions.
Module manifest (manifest.ts)
moduleManifest / ModuleManifest — the self-description every module ships: permissions, events (emits/consumes), migrations + skew window, attachment targets, entity relations, entitlement key, searchables ({ entityType, fields, tokenizer? } — the table and id column are filled in by manifestEntities from the entity registry, and the kernel derives a per-scope FTS5 index from the result), UI contributions, envSpec (envVarSpec[] — the declared environment that the Dashboard's Env form renders from; a non-secret setting may opt in to previewCarry, re-delivered to a preview on every push, and a secret or kind: 'model' setting may not), schedules (scheduleSpec[] — recurring work: { operation, cadence: { everyMinutes }, input?, permissions } the platform sweep runs on every live scope under a system actor), and freshness (freshnessSpec[] — freshness expectations: { eventType, within: { hours } }, hours by design; the eventType must be in the module's own events.emits ∪ consumes, or moduleManifest.parse refuses it, since an expectation on a type that can never arrive would read as permanently stale). Field-by-field walkthrough in Modules & the manifest.
checkSubject — who a permission check is about: { kind: 'principal' | 'connection' | 'system', id }. systemGrant grants a permission to a module's system principal ({ moduleId, permission, node, … }), the scheduler analogue of connectionGrant.
Vertical & version registry (registry.ts)
The registry shapes (#31): vertical / Vertical (slug, source, ownerTenant, declared envSpec, install spec — entitlements/grants/capabilities/surfaces), verticalVersion (digests + admission status — so push is not live), the channel records promotion moves a scope between, and verticalOwnerPeriod — one period of a slug's ownership (#2501), which is what bills a past period to the builder who owned it then. A vertical record also carries the connectors its latest push declared. This is what turns the scope's nullable vertical string into a pinnable record. See The platform layer.
Deploy manifest (deploy.ts)
deployManifest — the JSON a substrat push sends beside the module files (D-39), re-parsed at the control-plane trust boundary and run through the §4 sandbox contract. runtimeNeeds.tenantStores may say kind: 'relational' or kind: 'blob' (the older blobStores spelling is the same blob). The manifest a push sends does not: relational stores stay in tenantStores and blobs stay in blobStores. It also carries scopeStores, one platform-run object per scope, the permission registry, and RUNTIME_BASELINE. Optional modules carries each loaded module's { id, permissions: [{ key, description, holder? }], ownerGrants? } declarations. When present, the control plane recomputes the registry's key rows at publish and refuses a disagreement; absence keeps older CLI manifests readable and publishable. These declarations are builder-supplied. The next step of #2446 will verify known engine manifests; third-party modules remain author-asserted. One schema, two parses, no drift.
Connections (connections.ts)
The integrations hub's store (#101): connection / Connection and connectionStatus, keyed on (tenant, vertical, provider) so one vendor's host code never reaches another's credential. A provider is a lowercase slug, or <namespace>.<name> for a vertical-defined connector. A connection is tenant-owned unless ownerScopeId names the scope that made it through the connection relay (#2732): the owner is part of the live key, so two scopes can connect the same account and each hold its own, and only the owning scope binds it. connectionRevoke takes one key back from a connection on one scope while the connection stays live, and connectionSendTest / connectionSenders / connectionSendTestResult are the send test of a connection that sends mail. Everything here is metadata — the sealed credential never appears in these shapes. See The connector seam.
Vertical-defined connectors (vertical-connector.ts)
The vocabulary a vertical's own connector shares with the platform (D-64): the declaration (verticalConnectorDeclaration, a <namespace>.<name> provider), the call the platform makes into the vertical's worker (connectorCallRequest) and the vertical's answer (connectorCallResponse), each parsed on both ends. The platform keeps the sealed credential, the bindings and the connector state, and hands the vertical one connection's worth per call. connectorCallTarget (connector-call-target.ts) is where the router dispatches one such call.
Inbound mail (mail-in.ts)
What a vertical sees of a message mailed to one of its scopes (#2611) and what crosses the relay when a scope asks for, rotates or gives up its address: mailInAddress, mailInChange, mailInRelayRequest / mailInRelayResult. An address is a capability for one scope, backed by its own mail-in connection; a vertical opts in by declaring a mail-in landing.
Source builds (source-build.ts)
sourceSnapshot and sourceBuildRequest / sourceBuildResult: a release built from persisted source rather than client-built uploads (D-66, PLATFORM_FEATURE_SOURCE_BUILDS). Paths are repository-relative; credential and generated paths are excluded by excludedSourcePath, and a snapshot is bounded by SOURCE_BYTES_MAX and SOURCE_FILES_MAX.
Scope introspection (introspection.ts)
The read-only "Data" window into a scope's own database (kernel-design §5.4): scopeTable, scopeTablePage / readScopeTableInput, and the free-SQL queryScope shapes — table-shaped and bounded, no write path to forge the spine.
Routing (routing.ts)
The hostname map (K-26): RouteTarget (hostname → (tenant, scope, vertical, surface, region) — what the environment router resolves), hostnameBinding / HostnameStatus and its issuance/DNS records, plus declaredSurface and surfaceName (a scope fronts many surfaces — storefront + back office — from one database).
OpenAPI (openapi.ts)
ApiCatalog / ApiOperationDoc and the builder that renders a vertical's operation catalog — the same Zod schemas its handlers parse — as an OpenAPI 3.1 document, so the published contract cannot drift from the enforcement (D-22).
Money (money.ts)
money / Money (decimal-string amount + ISO 4217 currency, both branded) and the sanctioned arithmetic: addMoney, mulMoney, moneyOf, addDecimal, mulDecimal, compareDecimal — exact micro-unit (6 dp) bigint arithmetic, half-up rounding. See Money.
CSV (csv.ts)
csvTable(header, rows) writes a CSV file a spreadsheet opens as data: every cell through csvCell, comma-separated, CRLF after every record, as RFC 4180 has it. Excel, LibreOffice and Google Sheets run a cell starting with =, +, - or @ as a formula even when it is quoted, so csvCell writes such a string, and one starting with a tab, CR or LF, with a leading ', then quotes it if it holds a comma, a ", a CR or an LF. A string that is wholly a decimal number (-12.50) is left as it is, since money is a string here; a number is written as String(n); null and undefined are an empty cell. NaN, Infinity, anything that is not a string, number, boolean or null, and a row whose width is not the header's all throw. boundary-lint rule R13 refuses cells joined by hand in module code.
Model usage (model-usage.ts)
The one fact a platform-provided model call produces, and the meter built from it:
modelUsageLine/ModelUsageLine— token counts as the provider reported them (reported: falseand zeros when it reported none, never an estimate that becomes a bill),listUsdcomputed on our side from the generated rate card (nullfor a model the card does not know — unpriced, not $0),elapsedMs, andattribution.UNREPORTED_MESSAGEis what refuses a line that claims tokens it also says were unreported.modelAttribution/ModelAttribution— fixed at five keys:tenant,scope,vertical,version,operation. Five is the smallest per-request metadata limit among the providers we route through, so a sixth key would drop silently on the wire and break the reconciliation join for that provider only.MODEL_USAGE_KIND('model-usage') — the platform-intent kind a vertical raises to hand a line to the platform's ledger (ctx.requestPlatform({ kind: MODEL_USAGE_KIND, payload: line })). The drain refuses a line whose attribution names a different tenant or scope than the one being drained, and records it under the intent's own id, which is what makes a retried drain write nothing twice.modelUsageEntry/ModelUsageEntry— a line as the ledger holds it, plus the platform's two stamps (id,requestId).modelUsageSummary/modelUsageSummaryRow— meter 3, one row per (tenant, vertical, model). Money is folded withaddDecimal, never floated, andunpricedcounts the calls the rate card did not know: shown beside the money, never folded into it as $0.marginFactor(percent)— a whole-percent margin as the exact decimal factormulDecimaltakes (20→'1.2').billedUsdislistUsd × marginFactorapplied at read time, so a margin change re-prices history consistently instead of leaving two rates in one table.
The producer side is createModelHost in @substrat-run/vertical-host.
Attachments (attachments.ts)
visibility — 'internal' | 'customer', the mandatory classification on every attachment item that could reach a customer portal.
File sources (file-source.ts)
The vocabulary a vertical sees of a provider that holds files, whichever provider it is (#2499). The first provider is the Microsoft 365 channel-files connector, which re-exports these under its own names; a second lands on the same words.
fileSourceChange/FileSourceChange— the change a sync lands through the vertical's own operation, one per invoke:upsert(new or changed, withpreviousPathon a move and acontentstate saying whether bytes follow),content(the bytes landed as an attachment, with the attachment itreplaces) ordelete(deleted, ormoved-outwithout saying where). Every change is keyed byitemId, delivery is at least once, and a delete is only ever on that item's own answer — never cascaded from a folder.fileSourceWriteRequest/FileSourceWriteRequest— the payload of the event a vertical emits to write attachments into its bound folder.conflict(fileSourceConflict:replace,renameorfail) is required; it is never a default and the provider never picks.fileSourceUpsertAnswer— what the landing operation answers to anupsertwhosecontentisfollows: the{ entity }the bytes attach to.FILE_SOURCE_MAX_FILES_PER_WRITE(20),FILE_SOURCE_MAX_FILE_BYTES(50 MiB) andFILE_SOURCE_MAX_WRITE_BYTES(100 MiB).
The event type a write travels under stays the provider's, because it is what routes the delivery. See connections §6.3.
Client context (client-context.ts)
clientContext / ClientContext — who is on the other end of a request, as distinct from the principal: device (browser, OS and kind — desktop, mobile, tablet, bot — parsed out of the User-Agent by parseUserAgent), language (the head of Accept-Language), and geo (country, region, city, timezone, continent). Every collected value is nullable; device and geo are always present and device.kind is unknown when the parser could not tell. There is no IP address. A host builds one with clientContextOf(headers, geo?) and hands it to an operation as input; module code has no request to read. The Cloudflare read of request.cf is normalised once, in cloudflareClientContext — a vertical sees this shape on every runtime.
Subpaths that import nothing
The platform bundles an entry module in front of every deployed vertical (#1893), and this package's root would bring every schema, and zod, with it. So what that entry and the router need has subpaths of its own, each importing nothing at run time but one another:
| Subpath | Exports |
|---|---|
@substrat-run/contracts/wire-headers | the wire header names (PLATFORM_SECRET_HEADER, LIVE_MODE_HEADER, …), also exported from the root |
@substrat-run/contracts/invocation-record | the invocation record the router meters a request by, and invocationLevelOf, also exported from the root |
@substrat-run/contracts/wire-auth | assertPlatformCall, PlatformCallError and secretMatches: is the platform itself calling? It fails closed with no configuration at all — an unset secret is a refusal, never a bypass, because an open provisioning endpoint lets a stranger mint tenants inside a vertical. Its callers are verticals (through @substrat-run/vertical-host, which re-exports the first two), the control plane and the social relay. secretMatches is the constant-time compare behind it and behind readRoutedNode |
@substrat-run/contracts/wire-signing | The Ed25519 envelope the router and the control plane are to put on a call to a vertical, so that a deployment holds public keys only. Proposed in RFC wire-signing. The router and the control plane sign one beside the legacy headers once their own sign flag is on (wireSigningOn: exactly on); the platform's entry module verifies one, inert until a deployment is given key lists. signWireEnvelope and importWireSigningKey sign, wireSigningKeyOf imports a signer's key once per isolate, wireSignerOf is a signer's whole decision (null while its flag is off; on, sign or hand the request back whole with the reason), and signWireRequest puts a fresh envelope on a request about to be sent, every other header kept and a call's exact body bound; WIRE_UNSIGNED_HEADERS names the two router headers listed as carrying no authority, and wireUnsignedHeadersOf the ones a request of a kind hands on (one ULID each); verifyWireEnvelope checks in one fixed order and returns the one refusal WIRE_REFUSED for every failure the caller caused. wireVerificationKeys builds the only key set it accepts, and any other throws. Also canonicalWireEnvelope/parseWireEnvelope, wireRequestBinding, wireDigest, and the WireNonceCache interface behind a call's required replay policy ('none' or a cache). What a deployment is given and writes: the setting names (WIRE_ROUTER_KEYS_VAR, WIRE_PLATFORM_KEYS_VAR, WIRE_AUDIENCE_VAR, WIRE_STATE_VAR), wireUploadSettings (what one upload gives a deployment: both lists, judged as the entry loads them, its own name and WIRE_UPLOAD_STATE, which is dual, with each list's key ids), wireStateOf (no key lists is legacy-only, an unknown state with keys is dual), wireEndpoint (which kind of envelope, from which issuers, a path accepts), wireReplayOf with its WIRE_REPLAY_FREE_CALLS table (a call keeps nonces unless its method is safe or the table lists it), decodeWireEnvelope (the verifier's own decode, nothing verified), a call's body as a WireBodyReader (read only once the signature, audience, time, method and target have passed), and the per-request WireVerificationLine with its WIRE_OUTCOMES and WIRE_FAULTS. The key forms and key ids are the scope-store envelope's, through the ./scope-store-envelope subpath it imports |
@substrat-run/contracts/trace-sink | TraceSink, the slot a host reads it from (TRACE_SINK_KEY), the plain types of a trace's head and steps, and the shared time axis (markTraceStart, traceOffsetMs) every recorder stamps a step with. substrat dev installs a sink; a host with none records nothing. The matching schemas (requestTrace, traceStep) are in the root |
Versioning
The package is semver'd and every event and manifest carries explicit schema versions. Pre-1.0, shapes change without notice; from the first shipped vertical onward, breaking changes to emitted schemas are CI-diffed and linted.
The model
One TypeScript module declares a vertical's entities, operations and permissions; the compiler checks the joins between them. Full walkthrough in The model.
| export | what it does |
|---|---|
defineEntities | declares entities — table, fields, parents, key, erasable, outsideText, erasure. parents is checked against the map's own keys; key, erasable and outsideText against each entity's own fields, and neither of the last two may ride an event payload |
defineOperations(entities, permissions, engines?) | declares operations against those entities, a declared permission set, and any composed engine registries |
manifestOperations(ops, { permissions, checksDeclaredElsewhere?, consumes? }) | the operation half of the manifest — descriptions supplied, the permission key set and events.emits derived; a key checked but owned by a composed engine is listed under checksDeclaredElsewhere with its owner, and both an undescribed key and a stale exemption are load errors |
manifestEntities(entities, refs) | composes the entity-referencing manifest fragments; derives entityRelations from each entity's parents |
permissionsUsedBy · eventsEmittedBy | derive the manifest's permissions and events.emits from the operations |
operationInputsOf(ops) | the inputs map a registration's operations carries — every operation's declared input schema, which the host parses on every path in before the guards and the handler. A module gets it from operationsFor in the kernel rather than calling it |
operationConcurrencyOf(ops) · operationIdempotencyOptOutsOf(ops) · operationImpersonationRefusalsOf(ops) | the concurrency map (which entity's version each operation's If-Match is checked against), the operations that opted out of Idempotency-Key, and those no impersonation session may invoke — all derived, never written a second time |
emitModel | renders the registry to deterministic JSON — the artifact pnpm lint:model --check gates |
EntityRow<T, K> | a declared entity's row type, for ctx.sql.query<…> |
OperationImpl<Ops, Ctx> | the handler map an operation set requires; the kernel's operationsFor holds a module's map to it |
model.json is for consumers that must not execute your code, or that want diffability. A code generator reads the TypeScript: z.toJSONSchema drops .refine() and .brand(), so a generator reading the JSON would emit validators weaker than you declared.