import { storageTenant } from './request-scope.ts'; import { isWorldAccountName } from './world-account-name.ts'; import { parseExactJson, compareExactNumbers, exactInteger, isExactIntegerValue } from './exact-json.ts'; // THE DERIVED CORE — what a derived pack does for an operation it declares no handler for // (docs/contributing/architecture.md, "Protocol 3"). The generated surface says what the // vendor's operations are; the pack's manifest says the vendor facts no spec carries (how ids look, // how lists page, how errors read, which fields are state and how they move). From those two this // serves CRUD generically and applies declared transitions, over the kernel's tree and write path. // Nothing here knows a vendor: every vendor difference is a manifest value. import { applyTwinWrite, applyTwinWriteAtomic, applyTwinWrites, noteTwinRequest, twinResources, type TwinResource } from './serve.ts'; import { copyResource, foldLocalWrite, heldSubject, ownFields, parentStamp, readTreeAsOf, subjectHistory, treeChangesSince, treeResources, treeStamp, type Subject } from './log.ts'; import { performsAtHeadNow } from './head.ts'; import { getActiveWorldStore, worldStateFile, type WorldStore } from './world-store.ts'; import { getActiveBlobStore } from './blob-store.ts'; import { worldPaths } from './storage.ts'; import { GitObjectStore } from './git/objects.ts'; import { GitRefs } from './git/refs.ts'; import { worldNow } from './world-clock.ts'; import { worldEnvValue } from './world-env.ts'; import { openSessions, socketWrite, type SocketDecl, type SocketSession } from './sockets.ts'; import { liveAccess } from './live/access.ts'; import type { LiveAccess, LiveDecl } from './live/types.ts'; import { awaitWrite, awaitCondition, heldReadsWrite } from './held-reads.ts'; import { MACHINE_POOL, poolFor, guardedMachinePool, type MachinePool, type MachineHttpReply } from './machines.ts'; import { askApplication, deliverEvents, type ApplicationAnswer, type ApplicationStandIn, type EventRender, type EventScheme, type EventsDecl, type EventValues } from './events.ts'; import type { RateBudgetDeclaration } from './rateBudget.ts'; import { handlerCrypto, hmac, keyFrom, ksuidFrom, lettersFrom, sha256, uuidFrom, type HandlerCrypto, type KeyFormat } from './signing.ts'; import { seededKeyPair } from './seeded-keys.ts'; import { hashFieldValue } from './hash.ts'; import { readResourceBlob, readResourceBlobRange, removeResourceBlob, resourceBlobSize, writeResourceBlob, writeResourceBlobStream } from './resource-blob.ts'; import { managedDatabase, unboundDatabase, type ManagedDatabase } from './managed-database.ts'; import { redisServiceTimes } from './redis/service-times.ts'; import { execRedisRun, type RedisDialect, type RunItem } from './redis/engine.ts'; import { sendMail, type Mail, type MailReply } from './smtp.ts'; import { ownField, parseBracketForm } from './form.ts'; export { ownField, parseBracketForm } from './form.ts'; import { multipartBoundary, multipartParts, type MultipartPart } from './multipart.ts'; import type { CorsDecl } from './cors.ts'; import { listActions, projectOwnerResources, resolveSubjectId, subjectAliases, type TwinAction } from './actions.ts'; import { vendorFetch } from './vendor-call.ts'; import { packReferences } from './references.ts'; import type { SubjectFields } from './hash.ts'; import { twinPublicBase, withRequestScopes } from './twin-fetch.ts'; import { inVendorMove, isReadOnlyRequest, runAsVendorMove, writesRefused } from './request-scope.ts'; import type { DerivedCall, DerivedCoreOutcome, DerivedHandler, DerivedOperation, DerivedSurface } from './derived.ts'; import { getPack, type PackDescriptor } from './packRegistry.ts'; import type { ScenarioDecision, ScenarioHandler, ScenarioStatusFault } from './scenario.ts'; import { decide, faultAt, listLag, recordFault, serviceLedger, type ScenarioLedger } from './scenario-consume.ts'; import { kernelFault } from './scenario-serve.ts'; import { durationMs, factAt, placedFaults, placedOn, type PlacedFault } from './placements.ts'; import { bodyTextOf, checkJsonBody, takeParsedBody } from './derived.ts'; // ── the manifest ───────────────────────────────────────────────────────────────────────────── /** How a stored field gets its value when the server assigns it. `now` is the world clock in the * manifest's time format; `id` the subject's id; a `value` is stored as given. */ /** A field the server assigns: the World clock's now, the subject's id, a fixed value, or a template over the stored * fields (and `{id}`), base64-encoded when `encode` says (GitHub's `node_id`: `05:Label{id}` in base64). */ export type FieldRule = { now: true } | { id: true } | { value: unknown } | { template: string; encode?: 'base64' }; /** A move of one state field, as data. `operation` is the operationId that causes it (an update * that requests `to` when absent); `from` the values it leaves; `effects` the other fields it writes; * `refusal` what the vendor answers when `from` does not hold. */ /** Who moves a state: a caller of the API (the default), the person on a vendor's hosted page or * another outside party (`external`), the vendor on its own (`vendor`), or time (`time`). A move * that is not the API's never answers an API call's legality. */ export type Actor = 'api' | 'external' | 'vendor' | 'time'; export type Transition = { operation?: string; actor?: Actor; from: string[] | '*'; /** the value it moves to; absent, the value stays (a guard that moves nothing), and absent with a `refusal`, the * operation is refused in the `from` states (a move another transition allows from there is taken first) */ to?: string; effects?: Record; /** placeholders `{from}`, `{to}`, `{field}`, `{id}` */ refusal?: { status: number; code?: string | number; message: string }; /** a refusal of its own for a particular current value (an invoice already `paid`) */ refusals?: Record; /** where the rule comes from: a docs URL, the SDK's types, or a recording */ source: string; }; /** A state field's machine. Values compare as strings, so a boolean field reads `'true'`/`'false'`, and * a field that is absent reads as `initial`. `derive` names states a stored value only implies (a * timestamp that is 0 until something happens), tried in order. `vendorInitial` is where the vendor * starts a subject when the twin starts it elsewhere. */ export type StateField = { initial: string | boolean; transitions: Transition[]; /** Plain updates may repeat the current representation without another state move. */ unchanged?: 'allow'; derive?: Array<{ state: string; when: { equals?: unknown; gt?: number; truthy?: boolean; absent?: boolean } }>; vendorInitial?: string; }; /** What a move to `to` stores in the field: a boolean field's value is a boolean, and a derived field's * value is written by the move's effects (a state name is not a timestamp), so it stores nothing itself. */ export function storedState(decl: StateField, to: string | undefined): unknown { if (to === undefined || decl.derive?.length) return undefined; return typeof decl.initial === 'boolean' ? to === 'true' : to; } /** The state a stored value is in, by the field's machine. */ export function stateOf(decl: StateField, value: unknown): string { for (const d of decl.derive ?? []) { const w = d.when; if (w.absent !== undefined && (value === undefined || value === null) === w.absent) return d.state; if (w.equals !== undefined && value === w.equals) return d.state; if (w.gt !== undefined && (typeof value === 'number' || isExactIntegerValue(value)) && compareExactNumbers(value, w.gt) > 0) return d.state; if (w.truthy !== undefined && Boolean(value) === w.truthy) return d.state; } return value === undefined || value === null ? String(decl.initial) : String(value); } export type ResourceDecl = { /** the tree's subject type, when it differs from the resource name */ storedAs?: string; idPrefix: string; /** a setting held once per parent at a path of its own (`/v1/projects/{ref}/config/auth`, GET and PATCH, which the * surface names by the schema its GET answers): keyed by the path's parameter, it answers `defaults` under what was * written until first written, and an update merges into it, making it on first write */ setting?: { defaults: Record }; /** this resource's id template, when it is not the manifest's (`ids.template`): `{uuid}`, `{ksuid}` (Clerk's), `{letters:20}` (twenty * lowercase letters, a Supabase project ref), `{digits:16}` (fixed-width decimal), `{snowflake:}` (Discord's ids), or a `{prefix}`/`{n}` * template */ ids?: string; /** fields the server assigns on create */ assigned?: Record; state?: Record; /** state candidates the manifest rules are not state */ notState?: string[]; /** id-holding fields a caller may ask to receive embedded, and the resource each holds */ embeds?: Record; /** `embeds` fields the vendor answers embedded on every answer, asked or not (its schema gives the object with no id * alternative: Stripe's issuing card's `cardholder`): still stored as the id, hydrated from the current object */ alwaysEmbedded?: string[]; /** the vendor's own fields whose names begin with `_` (GitHub's `_links`, a HAL object's), which the vendor answers: * answered like any field, where every other `_` field is the pack's bookkeeping and never answered */ vendorUnderscored?: string[]; /** Stored fields omitted from vendor views, without renaming them in retained state. Raw rows and * ctx.own retain them for parent scope and semantics; get, rows, render and core answers omit them. */ viewOmit?: readonly string[]; /** fields the vendor answers as a list of the current children of another resource (Stripe's subscription `items`: * its subscription_items), built on every answer from the child rows whose `by` field holds this id, in the order * they were made, each through the child's own view and its embedding; never a stored copy. `list` is the list's own * fields around `data`, where `{id}` is this resource's id and `"{count}"` the children's number */ collections?: Record }>; /** this resource's deletion answer, when it is not the manifest's (`vector_store.deleted`) */ deleted?: unknown; /** a child addressed under its parent: the path parameter naming the parent, the stored field that * holds it, and the parent resource, whose not-found answers a missing parent */ /** `param` is the path parameter naming the parent, or `params` several with `value` the template * that joins them into what `field` stores (`{owner}/{repo}`). `where` finds the parent by its stored * fields when its stored id is not what the path names (a repository stored as `repo:7` with `owner` * and `name`, addressed as `{owner}/{repo}`): each stored field against a template over the path. */ parent?: { param?: string; params?: string[]; value?: string; field: string; resource: string; allowDeleted?: boolean; where?: Record; /** Global subject paths omit the collection's parent labels; tenancy still applies. */ whenNamed?: true; /** private fields a child observed under its parent keeps from the parent's parameters (`_jurisdiction: * '{jurisdiction}'`), where the child's own read names none and a later read under it needs one ("Refresh") */ keep?: Record }; /** a number the resource counts per parent (a repository's issue numbers, a thread's messages): * the stored field, set on create to one past the highest among its siblings */ number?: { field: string }; /** the field the vendor's answer names a subject's id by, when it is not `id` (Daily's webhook `uuid`, Twilio's `sid`, * Asana's `gid`): the subject's id is answered under it, and no `id` */ idAs?: string; /** an update replaces the fields it names (`replace`), merges a nested object one level into them with `''` removing * a key (`merge`, the default: Stripe's metadata), or merges nested objects at every level with `null` removing a key * (`deep`: Clerk's metadata, "a deep merge … remove metadata keys at any level by setting their value to null") */ update?: 'merge' | 'replace' | 'deep'; /** the stored subject id when it is not the path's last parameter: a template over the path * parameters (`{vector_store_id}::{file_id}`) */ key?: string; /** a resource every tenant shares (a catalogue the vendor keeps for all, its countries or currencies): the manifest's * `tenant` does not scope it */ shared?: boolean; /** only subjects whose stored fields match are readable (a resource stored for every call but * answered only when asked to be kept) */ readableWhen?: Record; /** fields the vendor answers pending until its own work fills them, `for` (a duration of World time) after the subject * was made or after a write that set any of `on` (default: the field itself): a read before then answers `value`, one * after answers what is stored (a merge state computed in the background, a deployment's readiness) */ pending?: Record; /** this resource's not-found answer when it is not the manifest's: a message (`{id}`), or an * error code (an RPC vendor's `channel_not_found`) */ notFound?: string | { code: string; message?: string }; /** query parameters of the list operation that filter on the same-named field */ filters?: string[]; order?: { field: string; direction: 'asc' | 'desc' }; /** the list's ordering parameter (`order_by=-created_at`): `[+-]` over `fields`, `default` when absent; any * other field is refused with `invalid` (`{fields}` in its message names them), never ignored */ orderBy?: { param: string; fields: string[]; default: string; invalid: ErrorSpec }; /** fields no two live subjects share (a permission's `key`; a membership's `organization_id` and `user_id` together): * a create or update that would make a second one is refused with `refusal`, by the core and by `ctx.conflict` */ unique?: Array<{ fields: string[]; refusal: ErrorSpec }>; /** the subjects a delete takes with it (an organization's memberships and invitations): each resource whose `field` * holds the deleted subject's id, deleted first, each through the write path as its own delete (its events sent). * The field may be a dot path; exact field names take precedence. */ cascade?: Array<{ resource: string; field: string }>; /** fields that name a subject as its id does (an organization by its id or its slug): a path's id and `ctx.find` * match either */ alternateKeys?: string[]; /** fields that pair a subject a deploy settled with no vendor id with the vendor's copy a refresh observes (Slack's * `channel_join` message, made by `conversations.join` and answered by no id: its `subtype` and `user`), where the * `alternateKeys` do not; a subject missing one is never paired by them ("Refresh", adoption) */ adoptBy?: string[]; /** the list's search parameter (`query`): a row matches on an `exact` field's whole value or a `partial` field's * substring, case-insensitively */ search?: { param: string; exact?: string[]; partial?: string[] }; /** fields that count this subject's children (an App's `installations_count`): the live subjects of `of` whose `by` * holds this one's id (or vendor `parentKey`), only those with `present` set or `absent` unset when named and without * any matching `unless` field, plus `plus` (a customer's * `next_invoice_sequence` is one past its numbered invoices). `by` may be a dot path; exact field names take * precedence. The kernel keeps each whenever a child is written, the parent it left too when the write moves it; `of` * may name a bookkeeping type no resource declares, written with `ctx.record`. A count is kept by the lane that * declares it: a child another lane writes is not counted there. */ counts?: Record; plus?: number }>; /** how the vendor's state of this type is read back into a root (the real-system adapters, "Refresh"): the list that * enumerates it (once per parent, under `parent`; `complete: false` when it is not the whole type; `items`, the answer's * path to them, when the spec does not name the list it answers), the one read of a singleton, or `none` with why the * vendor offers no read-back. Every stored resource the vendor holds declares one. `{ get, known: true }`: the vendor * lists no whole type, so the World's own subjects of it are each read again by `get` (a 404 is one gone), and what * those reads observe anchors its children's lists; completeness is those subjects alone. */ /** `next`: where an answer names the next page's cursor (AWS's `NextToken`), sent back as `cursor` (the same name * unless said) in the query, or in the body of a list asked by POST (an RPC list: AWS JSON's `x-amz-target`); a * map of parameter to answer path where a page names several (S3's `key-marker` and `upload-id-marker`); `more`, the * answer's flag that another page follows (S3's `IsTruncated`). `headers`: fixed headers of the list, `{name}` filled * from the parent's parameters; `variants`: header sets each listed in turn, one type whole across them (R2's * jurisdictions). A blob read by an `operation` (a GET of the unit's surface, filled from the subject's fields and * its parent's parameters) keeps the bytes in the World's blobs, their key in `field`, and in `headersField` the * answer's headers `keepHeaders` names (a name ending `*` a prefix: `x-amz-meta-*`), both fields private. */ refresh?: ({ list: string; unpaginated?: true; keyed?: true; detail?: string; detailMerge?: string; detailWith?: Record; detailParams?: Record; complete?: false; items?: string; shape?: RefreshShape; next?: string | Record; nextLink?: { header: string; rel: string; query: string; when?: Record }; cursor?: string; more?: string } | { get: string; known?: true; gone?: { status: number; says: string } }) & { params?: Record; headers?: Record; variants?: ReadonlyArray<{ headers: Record }>; blobs?: ReadonlyArray<{ path: string; key: string; resource?: string; fields?: Record } | { operation: string; field: string; headers?: Record; headersField?: string; keepHeaders?: string[] }>; query?: Record; idAs?: string; graphql?: { query: string; variables?: Record; items: string; pageInfo?: string; cursor?: string } } | { none: string }; /** the reads a root scoped to one of the vendor's things makes instead of `refresh` */ scopedRefresh?: ReadonlyArray; /** the other resources one create of this one makes, and where its answer names each's id (a JSON path) */ companions?: Record; /** the field telling a newer copy of a subject from an older (an `updated_at`): an ingested event older than the * root's copy folds nothing */ version?: string; }; /** How a vendor's signed webhooks are folded into a root (the real-system adapters, "Ingest"). */ export type IngestDecl = { scheme: EventScheme | ReadonlyArray; /** where the event names its type: a header, a body path, and a sub-action path joined to it with `.` */ type: { header?: string; body?: string; action?: string }; /** the JSON path of the event's object */ object: string; /** event type → the resource it carries, where `events.types` read backwards and `.created|updated|deleted` * do not say it */ types?: Record; }>; /** an event answered instead of folded (Slack's url_verification): the body fields it matches, and the answer, a * `$body.` read from the event or a literal */ handshake?: { when: Record; answer: string }; }; /** Which lane a request is the vendor's gateway's to send ("Other wires: lanes"), each condition it names holding: a * path under `path` (Supabase's `/rest/v1`), a path matching `pathPattern` (a regular expression, where a front routes * by one: Sentry's sends a project's numbered `/api//` to Relay), a host matching `host` (a regular expression: * `^secretsmanager\.`), a header starting with `header.prefix` (AWS's `x-amz-target: secretsmanager.`), and a host not in `exceptHosts`. */ export type LaneRoute = { lane: string; path?: string; host?: string; exceptHosts?: ReadonlyArray; pathPattern?: string; /** a header starting with `prefix`, or, with `absent`, a request whose header does not (Clerk's Frontend API is asked * without a Backend API secret key) */ header?: { name: string; prefix: string; absent?: true }; /** where two of the vendor's APIs share one address: the route passes a path only the root's API serves (the lane's * surface does not), which is the root's */ unlessOnlyRoot?: true; }; /** A vendor's lanes: its routes, first match first, the lane that takes what no route names (`default`), and the * gateway's CORS. A `/_twin/` door goes to the lane whose manifest declares it. */ export type LanesDecl = { cors?: CorsDecl; routes: ReadonlyArray; default?: string }; /** The manifest of a vendor whose every API is a lane (Cloudflare's API v4 and R2, AWS's services): no API of its own, * only what the vendor's front says — its discovery facts, its lanes and its descriptor. */ export type VendorManifest = { vendor: string; discovery?: DerivedManifest['discovery']; lanes: LanesDecl; descriptor: Omit; ingest?: IngestDecl; rateBudget?: RateBudgetDeclaration; /** the vendor has no vendor-backed half (architecture, "The descriptor"): packOf copies it, and derives no state system */ vendorBacked?: DerivedManifest['vendorBacked']; /** what of the vendor's records identifies a person, for every lane's records (architecture, "A real account's data"): * a pack with units declares it here, on the manifest its entry exports */ privacy?: PrivacyDecl }; /** `code` as the vendor writes it: a string, or a number (Discord's JSON error codes are integers) */ export type ErrorSpec = { status: number; message: string; code?: string | number; param?: string; kind?: string }; /** Where the vendor reads a request's idempotency key: a request header; a body field at a dotted path (`when`: only * while another body field, at its dotted path, holds `equals`); or the request's content itself (its path, query and * body, hashed: a repeat of the same content is the same request). A request with no key is not deduplicated. */ export type IdempotencyKeySource = | { header: string } | { body: string; when?: { body: string; equals: unknown } } | { content: true }; /** The vendor's idempotency layer, as its pack declares it. A failure the World's scenario places lands inside it, so a * repeat with the same key replays the failure as the vendor keeps it. */ export type IdempotencyDecl = { /** the key's request header: the same as `key: { header }` */ header?: string; /** where the key comes from, when it is not `header` */ key?: IdempotencyKeySource; /** the bookkeeping type a key's record is kept under (starts with `_`) */ storedAs: string; /** whose keys share one space: the account's (default) or each credential's (the one the request presents) */ scope?: 'account' | 'credential'; /** how long a key is kept, a duration of World time (`24h`, `5m`); a request with a key kept longer is a new request. * Absent: kept for ever */ keptFor?: string; /** what a repeat with a kept key answers: the first answer as it was (`answer`, default); the subject the first * request made, as it stands now (`subject`: the first answer's `id`, or the value at `subjectId`'s dotted path, a * subject of the operation's resource, else the first answer as it was); or a declared error */ replay?: 'answer' | 'subject' | { error: ErrorSpec }; subjectId?: string; /** the answer to a kept key sent with other parameters; absent, the key replays whatever the parameters */ conflict?: ErrorSpec; /** the answer to a request whose key is held by a request still in progress in this twin; absent, each goes on */ inProgress?: ErrorSpec; /** `methods` defaults to POST; `onlySuccess` (keep only 2xx answers) to false */ methods?: string[]; onlySuccess?: boolean; }; /** How a form value outside its spec's list is refused (DerivedOperation.enums): the error, its message filled with * `{param}` (the bracket name) and `{values}` (the values it takes); `documented`, values the vendor documents outside * its spec, by operation and path; `version`, the header naming the API version a request is made at and the version * the spec is, so a request pinned to another version, whose lists the pack does not hold, is not checked. */ export type EnumRefusal = ErrorSpec & { documented?: Record>; version?: { header: string; served: string } }; /** A vendor screen a World serves (docs/contributing/architecture.md, "Screens"). A `flow` is a hosted * page an application sends its user through, held to its documented round trip; a `workspace` is a * screen people work in. `demand` says who reaches it; `controls` names what a person acts on, the * vendor's way, each a (screen, control) cell. */ export type ScreenDecl = { id: string; /** a hosted flow a person is sent through, a workspace they work in, or a content host serving what the vendor stores * (its CDN: an uploaded image, a video, a default avatar) */ kind: 'flow' | 'workspace' | 'content'; host: string; /** every other host the screen answers on (a sandbox's dashboard and production's, one page) */ hosts?: string[]; path: string; demand: string; status: 'done' | 'todo'; controls?: string[]; /** wherever this screen would answer (its host, a World's place, its path alone), a request the pack's API names for * its method is the operation's, not this screen's: a site whose pages draw while its forms and links act on * operations the spec writes at the same paths (Hacker News's /login page posts to POST /login; its front page at `/` * would otherwise take GET /vote) (architecture, "Screens") */ yieldsToApi?: true; /** a content screen that takes a form at a World's place (`/@/…`), beside GET and HEAD: the methods it * takes, with its demand (an upload bucket a page posts a lease's form to: Reddit's S3 hosts) (architecture, "A page * at a World's place") */ takes?: ReadonlyArray<'POST'>; /** a workspace page that shows one record: the stored type and the path parameter its id fills (a pull request's * page, `{number}`); `?show=:` asked of the pack's workspaces opens it (architecture, "Workspace") */ shows?: { type: string; param: string }; /** the stored types a workspace page lists, where `?show=` lands for a record no page shows by itself */ lists?: ReadonlyArray; /** the vendor's documentation of the round trip or the screen */ source: string; }; /** A protocol hook's arguments: the root's executor (it applies the sealed credential; `issued` carries one the vendor * issued instead), the group and its first entry's recorded input, the perform's context, the derived perform of an * input (`send`: the recorded request, or one the hook changed), the stored id the World's id of a type resolves to, * the surface's base path, and the World's blobs of this twin. */ export type PerformHookArgs = { execute: import('./remote-execute.ts').RemoteExecute; group: import('./actions.ts').TwinAction[]; /** Recorded local effects before root reference translation, for local blob ownership. */ localGroup: import('./actions.ts').TwinAction[]; input: Record; ctx: import('./head.ts').PerformContext; send: (input: Record) => Promise; resolve: (type: string, localId: string) => string; basePath: string; blob: (key: string) => Promise; }; export type PerformHook = (args: PerformHookArgs) => Promise; export type GitRepositoryDecl = { resource: string; name: string; remote: string }; export type GitPushDecl = { resource: string; repository: string; remote: string; ref: string; before: string; after: string }; /** A template over a row's fields (`{field}`, a dotted path read through objects), every name filled or refused. */ export function fillTemplate(template: string, row: Record): string { return template.replace(/\{([^}]+)\}/g, (_, name: string) => { const value = name.split('.').reduce((at, k) => (at !== null && typeof at === 'object' ? (at as Record)[k] : undefined), row); if (value === undefined || value === null || typeof value === 'object') throw new Error(`template ${template}: no value for ${name}`); return String(value); }); } /** A pack's git repository `name` in a World (the store and refs `ctx.git(name)` answers), under the twin's state and, * for a namespaced account, that account's. */ export function gitRepositoryOf(m: DerivedManifest, name: string, root?: string): { store: GitObjectStore; refs: GitRefs } { if (!/^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/.test(name) || name.split('/').some((seg) => seg === '.' || seg === '..')) throw new Error(`semantics: ${name} is not a git repository name`); const account = accountScope(m); const plane = `${worldPaths(m.service, root).dir}/git${account && account !== 'default' ? `/accounts/${encodeURIComponent(account)}` : ''}`; return { store: new GitObjectStore(getActiveBlobStore(), `${plane}/repos/${name}`), refs: new GitRefs(getActiveWorldStore(), `${plane}/repos/${name}`) }; } /** The name a repository row's code is kept under: the manifest's `git.repository.name` (a template over `{id}` alone) * filled with the row's first World id, the one an adoption rebound to the vendor's (walked back through the aliases), * so the screen, a refresh, a deploy and a waiting push's protection name one repository before and after adoption. */ export function gitNameOf(m: DerivedManifest, id: string, root?: string): string { const decl = m.git?.repository; if (!decl) throw new Error(`${m.vendor}: the manifest declares no git repositories`); if (decl.name.replace(/\{id\}/g, '').includes('{')) throw new Error(`${m.vendor}: git.repository.name is a template over {id} alone`); const type = `${storedType(m, decl.resource)}:`; const aliases = aliasesNow(m.service, root); let first = id; for (let hops = 0; hops < 8; hops++) { const from = [...aliases].find(([local, vendor]) => vendor === first && local.startsWith(type))?.[0]; if (from === undefined) break; first = from.slice(type.length); } return decl.name.replace(/\{id\}/g, first); } /** A kind of identifying value (ADR 0036, "A real account's data"): a person's `name`, `email`, `phone`, `ip`, an account * `id` (a user id, a distinct id), a `place`; replaced by one keyed pseudonym of the same form wherever it occurs. A * person's act `time`, a user `agent` and a `url`'s query are quasi-identifiers, changed only where declared: a time * moves by the key's one offset, an agent keeps its products' major versions, a URL's query values take * pseudonyms. */ export type IdentifierKind = 'name' | 'email' | 'phone' | 'ip' | 'id' | 'place' | 'time' | 'agent' | 'url' /** an email at a mailbox provider whose subaddress rule is the separator (Gmail's `+`): `local+tag@d` is the mailbox * `local@d` labelled, pseudonymized as P(`local@d`)'s local part with its tag (ADR 0036, "A real account's data") */ | 'email+' | 'email-'; export type PrivacyDecl = { identifiers: Record>; }; export type DerivedManifest = { /** Vendor data-plane hosts mapped to an already-running customer guest. */ machineRoutes?: ReadonlyArray<{ host: string; resource: string; where: Record; name: string; port: number | string }>; /** The pack's descriptor, as data (docs/contributing/architecture.md, "The descriptor"), every field but `vendor`, which * is the manifest's: the pack registers `packOf(manifest)`, so its index is a fixed file. A lane has none. */ descriptor?: Omit; vendor: string; /** the kernel service the pack writes */ service: string; /** `json: 'always'` reads a body as JSON whatever its content type (GitHub does) */ /** `strict`: a vendor that refuses a body field its operation does not declare, a value of another type, or a number * outside the spec's bounds (a NestJS validation pipe: Supabase's "property x should not exist"), with its messages; * `{name}`, `{type}` (`a string`, `an integer`), `{min}` and `{max}` are filled. `ctx.fields` checks a body so. */ body: { form?: { coerce: boolean; enumRefusal?: EnumRefusal }; json?: 'always'; validation?: { operations?: ReadonlyArray; status: number; missing: unknown; type: unknown; range: unknown }; strict?: { status: number; code?: string; unknown: string; type: string; range: string; arrays?: Record } }; /** `acceptProvided`: a create that names its own `id` keeps it (a vendor that seeds by id). The template counts * (`{prefix}_{n}`), or is `{uuid}` for a vendor whose ids are UUIDs: the next is derived from the resource and its * count, so a World mints the same ids every run */ ids: { template: string; acceptProvided?: boolean }; /** operations the derived core must not claim though their resource is declared: a gap until someone models them */ unmodeled?: string[]; /** documented variants of a served operation that no demand asks for, by operation: each a parameter present * (`pause_collection`), present on any item of a list (`items[].price_data`), or with a value * (`payment_method_data.type=sepa_debit`, `payment_method_types[]=sepa_debit`), or holding one entry of a comma-separated * value (`tweet.fields~=geo`; a parameter whose name holds a dot is read by that name). A request asking one is answered the * manifest's gap before its handler runs, as an operation no handler serves is (architecture, "Creating a pack", * step 7), so no pack line answers it */ variants?: Record; /** operations that only read though nothing in the spec says so (a POST that returns data): * a read-only twin answers them */ reads?: string[]; /** operations of the vendor's API that set an account up rather than use it: an operator registering an OAuth client * on the vendor's own admin routes, as a person makes settings on the vendor's site. Each is recorded as a door's * write is (the World's own), so a deploy never offers it to the vendor and the vendor-backed acceptance holds it as * what the account already has; `why` says who performs it and where */ accountSetup?: Array<{ operation: string; why: string }>; /** how the vendor writes an instant: Unix seconds, Unix milliseconds (Clerk's `created_at`), or ISO 8601 */ time: 'unix' | 'unix-ms' | 'iso'; /** the vendor's CORS, as its gateway answers a browser (cors.ts): the pack's fetch is served behind `withCors` */ cors?: CorsDecl; /** the HTTP status a vendor answers every error below `below` with, when its body names the error's own status * (storage-api: 400 for every error but a 500, the body's `statusCode` the error's: `{ status: 400, below: 500 }`) */ errorsAnsweredAs?: { status: number; below: number }; /** the texts the vendor reads as a boolean in a parameter, compared without case (Supabase: `true`, `1`, `yes`, `on`, * `y`, `enabled` and their opposites); absent, `true` and `false`. `ctx.flag` reads with them. */ booleans?: { truthy: string[]; falsy: string[] }; /** the vendor's error body, with `{message}`, `{code}`, `{param}`, `{kind}` placeholders; a * placeholder with no value is left out when `errorOmitsAbsent` */ error: unknown; errorOmitsAbsent?: boolean; /** the `{kind}` an error takes when it names none */ defaultKind?: string; /** what a write to a read-only twin answers */ readOnly: ErrorSpec; /** what a body labelled JSON that does not parse answers; absent, a 400 in the vendor's error body */ malformedBody?: ErrorSpec; /** the vendor's front merges repeated slashes in a path before it routes (nginx's default `merge_slashes`): a request * to `//r/x//about` is `/r/x/about`, merged on arrival before a door, a screen or an operation is matched */ mergeSlashes?: boolean; /** a request header that selects the vendor's API version, and the answer to a malformed one * (`{value}` in its message is the header's value) */ version?: { header: string; pattern: string; error: ErrorSpec }; /** request headers that carry meaning to the vendor (a tenant header such as `Stripe-Account`): recorded with a write * so its perform sends them again (the real-system adapters, "What a pack declares"); `version.header` is too. A name * ending `*` is a prefix: every header it begins (S3's `x-amz-meta-*`, an object's own metadata). */ headers?: string[]; /** the vendor's signed webhooks, folded into a root */ ingest?: IngestDecl; /** the vendor's documented limits, charged by the executor on every live call (D8), and the one its server keeps * (`served`), which a World's scenario switches on */ rateBudget?: RateBudgetDeclaration; /** the operations the vendor documents as eventually consistent (a search index that finds a new object after a * short delay; a configuration in force a while after it is set): where a World's scenario `lag` answers from the * World as it stood its `by` ago, and nowhere else. `reads`, by operation: the resources it reads as of then (absent: * every resource it reads, the kernel's own bookkeeping apart) */ eventuallyConsistent?: { operations: string[]; reads?: Record }; /** cursors the vendor keeps for a time, by operation: the request's `param` (a path parameter, else the query's, else * the body's) names a subject of `resource` by `field` (default its id); a subject made more than `keptFor` (a * duration of World time) before the request is past the vendor's retention, and the request is answered `error` */ cursors?: Record; /** where the vendor's repositories' code lives, as templates over a row's fields (`{field}`) (architecture, "The * real-system adapters"; ADR 0031): the resource whose rows are the vendor's repositories, the name each is kept under * (over `{id}` alone: the row's first World id, `gitNameOf`) and its remote (the vendor's absolute git URL), which a * refresh fetches; and the resource a push to a World repository records, one row per ref, with the World id of the * repository row it pushed to, which a deploy pushes */ git?: { repository: GitRepositoryDecl; push: GitPushDecl }; /** a pack whose wire has no derived perform (a socket, a line protocol, a managed database): binding a root is refused * with this reason */ vendorBacked?: { none: string }; /** the resource the vendor's paths name the account by (Cloudflare's `accounts/{account_id}`): with a root, the * World's account is the one account the root's credential reaches, which refresh observes ("The account a root * is", architecture) */ account?: string; /** a vendor protocol one recorded request cannot express, by the operation that ends it: a session whose answer * issues the credential its next calls carry (Cloudflare's assets upload), performed by the hook in place of the * derived request, which it composes (`send`) ("Protocols a request cannot express", architecture) */ performs?: Record; /** what of the vendor's records identifies a person (ADR 0036, "A real account's data"; architecture, "A real account's * data"): by resource type, each field (a dot path into the record's fields; `*` any one key, a list stepped into) * whose value is an identifier or a quasi-identifier, with its kind, which a root's pseudonymizing refresh replaces */ privacy?: PrivacyDecl; /** `withParam`: the error names the path parameter that held the unknown id */ notFound: { status: number; message: string; code?: string | number; kind?: string; withParam?: boolean }; /** the list envelope (placeholders `{data}`, `{has_more}`, `{url}`, `{first_id}`, `{last_id}`), * its page size, its cursors, and where an unknown cursor starts: the first page or past the end. * Absent when the unit serves no stored list; the core does not own lists without this declaration. */ list?: { style: 'envelope'; envelope: unknown; limit: { param: string; default: number; max: number }; after?: string; before?: string; unknownCursor?: 'start' | 'end'; /** an opaque cursor over positions (`{next_cursor}` in the envelope; empty on the last page), * in place of id cursors: `base64-offset` is base64 of `{"o":}` */ cursor?: { param: string; encoding: 'base64-offset' } | { param: string; encoding: 'offset-template'; template: string; link: { previous: string; next: string; results: string; cursor: string } }; /** numbered pages (1-based, the size in `limit.param`), with the vendor's `Link` header * naming the first, previous, next and last pages (`link`); the envelope may name `{total_count}` and `{max_page}` */ page?: { param: string; link: boolean }; /** offset paging: `param` names how many items to skip; the page sits under the operation's envelope key beside the * envelope, whose `{total_count}` is the count before paging (Tremendous's `{ orders: [...], total_count }`) */ offset?: { param: string }; /** page sizes by operationId, where a vendor's lists differ from `limit` (Tremendous: orders 10/500, invoices 10/10) */ limits?: Record; /** envelopes by operationId, where a vendor's lists differ from `envelope` (Tremendous gives `total_count` on orders, * rewards and invoices, and none on campaigns, funding sources or webhooks) */ envelopes?: Record; }; /** an RPC vendor's success envelope, merged into every answer, with the resource under the * operation's envelope key (`{ ok: true, channel: {...} }`) */ success?: Record; /** who is calling, from the request's credential (and the tree, where the vendor keeps tokens) */ identity?: (authorization: string | null, root?: string) => string; deleted: unknown; expandParam?: string; /** server-sent events: `data` lines, optionally `event:` lines named by each event, and the * sentinel a finished stream ends with */ sse?: { named: boolean; done?: string }; /** an operation whose stream is framed otherwise (named events, no sentinel) */ streamFor?: Record; /** the vendor's idempotency layer (IdempotencyDecl): a write repeated with the same key answers as the vendor * replays it; the same key with other parameters answers `conflict` */ idempotency?: IdempotencyDecl; /** how the vendor reads its credential, and what it answers without one or with a key the twin * reserves as invalid, or one of a shape the vendor never issues (`keyFormat`, a pattern every key it issues * matches: Resend's begin `re_`); a request that presents no such header at all is a trusted in-process call. * `held`: the key must be one the account holds, kept by its SHA-256 in a stored type's field (a token a Tokens page * made: `{ storedAs: '_access_token', hashField: 'sha256' }`), the live key of an `issued` purpose (`ctx.issueKey`), or * one of the World's `standing` keys (the one its seeds and init hand the app); any other is `invalid`. */ /** how the vendor reads its credential: the `header`, after its `scheme` (`''`: the header's whole value, an * `x-api-key`), or any of `also` (ElevenLabs' `xi-api-key` beside `Authorization`, Google's `?key=`); `paths` (a * regular expression) the paths it gates, every other passing ungated; a key the World issued is `held` by its hash */ auth?: { header: string; scheme: string; also?: Array<{ header?: string; scheme?: string; query?: string }>; paths?: string; missing: ErrorSpec; invalidKeys: string[]; keyFormat?: string; invalid: ErrorSpec; gateWhenAbsent: boolean; held?: ({ storedAs: string; hashField: string } | { storedAs?: never; hashField?: never }) & { /** purposes whose live key `ctx.issueKey` issued is held, the kernel's record its own (the application's `api-key`) */ issued?: string[]; standing?: string[]; /** a field set true on a key no longer held (OpenRouter's `disabled`) */ unless?: string }; /** operations that check a credential of their own, not the account's (Cloudflare's asset upload reads its upload * session's JWT from the same header): the gate leaves them to their handler */ exempt?: string[]; /** ordered API-skin error wires, selected before scenario matching and ordinary routing */ wires?: Array<{ paths: string; error: DerivedManifest['error']; missing?: ErrorSpec; invalid?: ErrorSpec }>; /** the vendor checks the key before it routes: a path it does not have is refused a missing or invalid key first */ beforeRouting?: boolean }; /** headers every answer carries (a request id); a value's `{hex:N}` is filled per answer, from the World's count of * answers (so a second World answers the same ids in the same order), unless the handler set the header itself */ answerHeaders?: Record; /** an origin the pack writes into URLs it mints, rewritten in every JSON answer to where this * twin is reached for the request (twinPublicBase) */ origin?: { placeholder: string }; /** Disclosed local connection fields, separate from vendor response schemas. */ worldFields?: Record>; resources: Record; /** Read-only cross-pack credential subjects of the same vendor (architecture A3); no root is exposed to handlers. */ ownerReads?: ReadonlyArray<{ owner: string; resource: string }>; /** the vendor's screens this pack serves or owes (demand decides which exist) */ screens?: ScreenDecl[]; /** The discovery door's facts (`GET /twin`): what the twin is of, what it stores, and how it is authenticated. */ discovery?: { twinOf: string; stores: string; identity?: string; notes?: string; /** a model vendor's: what its scenario scripts (the `on` keys and the `respond` shape), and a handler as an example */ behavior?: string; exampleHandler?: ScenarioHandler; }; /** The World's doors (architecture, "Doors, screens and the gap"): each a method and a path under `/_twin/` (with * `{param}` segments), answered by the export of `semantics/doors.ts` its id names, over the contract's context. */ doors?: Array<{ id: string; method: string; path: string; note?: string; redactBody?: string[] }>; /** REST refresh binds observed tenant metadata through the root account identity endpoint. */ refreshIdentity?: { operation: string; field: string }; /** The vendor's GraphQL API beside its REST one (`semantics/graphql.ts` over `generated/graphql-sdl.gen.json`): the * paths it is POSTed to, and the answer to a query selecting a field nothing models (`{field}`, `{type}`). */ graphql?: { paths: ReadonlyArray; unmodeled: { message: string; type?: string; status?: number } }; /** The vendor's answer for a path nothing serves and an operation nothing models, `{method}` and `{path}` filled * (OpenAI's `Unknown request URL: {method} {path}`); the manifest's `notFound` when it names none. */ gap?: ErrorSpec; /** The vendor's answer for a path its API serves under other methods than the request's (`405 Method not allowed: * {method} {path}`), `{method}` and `{path}` filled; the gap when it names none. */ wrongMethod?: ErrorSpec; /** The content codings the vendor reads a request's body in (its Content-Encoding: Tinybird's "Gzip or Zstandard" * events) and answers in when the request accepts one (Accept-Encoding), and its answer for a body that does not * decode as its Content-Encoding says. The kernel decodes before routing and encodes the API's answer. */ encodings?: { request?: ReadonlyArray<'gzip' | 'zstd' | 'deflate' | 'br'>; response?: ReadonlyArray<'gzip'>; undecodable?: ErrorSpec }; /** The content type the vendor labels a JSON answer with, when it is not the runtime's (Clerk's exact * `application/json`, which @clerk/backend reads a body as JSON only on): every JSON answer relabelled. */ jsonContentType?: string; /** The vendor's tenancy (architecture, "The derived core"): each stored subject belongs to the tenant it was made in — * an organization, a team, an account — and a caller reaches only its own tenant's, as a parent's children are * reached under it. `field` holds it on each subject; `semantics/tenant.ts` names the caller's. The core scopes every * read, list, update and delete by it and stamps it on every create, for each resource not `shared`. */ tenant?: { field: string; storage?: 'namespaced' }; /** The vendor's own lanes behind this manifest's API ("Other wires: lanes"), dispatched by the kernel before the * vendor's own doors, clock and API (LanesDecl). */ lanes?: LanesDecl; /** A host whose first label is part of the path, as a regular expression over the request's vendor host whose first * capture is put in front of the path before routing (S3's virtual-hosted addressing: `./` is * `//`); the host itself is left as it came. */ pathFromHost?: string; /** A prefix the vendor's hosts may put before a path (turbopuffer's region, `/aws-us-east-1`), as a regular expression * matched at the path's start: stripped before routing, so the operation it names is the one served. Its named groups * (Jira's `/ex/jira/(?[^/]+)`) are the operation's parameters as well. */ pathPrefix?: string; /** A prefix the vendor serves as its own base path (Discord answers `/api` and `/api/v9` as `/api/v10`, the spec's), as * a regular expression matched at the path's start: put in place of the surface's base path before routing, so an * operation compiled under the spec's base answers each. Perform and refresh send the spec's base, as the SDK does. */ basePathAlias?: string; /** A pattern over the request's vendor host whose named groups are the operation's parameters (E2B's envd answers each * sandbox at `49983-.e2b.app`: `^\\d+-(?[a-z0-9]+)\\.`). */ hostParams?: string; /** The vendor host a lane's calls go to when it carries the call's parameters (R2's `.r2.cloudflarestorage.com`): * `{name}` filled from the call's parameters, `values` a parameter's literal in the host (the real-system adapters, * "Lanes"). Perform and refresh send to `https://`. */ remoteHost?: { template: string; values?: Record> }; /** Named operation parameters from vendor routing headers (shared-host compute services). */ headerParams?: Record; /** The persistent wires the vendor's clients hold open (sockets.ts: Discord's Gateway): each served at its path by * the pack's `semantics/sockets.ts`, which the kernel offers every write after its webhooks. */ sockets?: ReadonlyArray; /** The broadcasts the vendor takes over RTMP (architecture, "Other wires": live media): each ingest's id, which names * its engine in the pack's `semantics/live.ts`, and the RTMP app it answers. The pack's fetch carries the ingest * (`fetch.ingest`), which its server serves on a side port. */ live?: ReadonlyArray; /** The vendor speaks gRPC (architecture, "Other wires": gRPC): its server answers HTTP/2 and HTTP/1 on one port, each * rpc (by its proto unit's schema, `src/generated/proto.gen.json`) through the pack's own fetch. */ grpc?: true; /** The vendor runs its customers' images (machines.ts: Fly's Machines): the kernel serves `POST /_twin/machine-pool` * and hands handlers the World's pool as `ctx.machines`. */ machines?: boolean; /** A lane routed by host ("Other wires: lanes"): the hosts it serves, each exact or a suffix. The vendor's server sends * them here, and SHAPE judges the lane on them alone, never on a page or door of the vendor on another host. */ hosts?: ReadonlyArray<{ host?: string; suffix?: string }>; /** The path parameters whose values span segments where the spec cannot say so (an OpenAPI path has no greedy label: * GitHub's `{ref}`, QStash's `{destination}`); a Smithy model's greedy labels are the surface's own `spanning`. */ spanning?: ReadonlyArray; /** The webhooks the vendor sends for its writes, as data the kernel renders, signs, delivers and records (events.ts); * `render` is the pack's `semantics/events.ts`, how the vendor renders an event's `data` when it is not the written * object. */ events?: EventsDecl & { render?: EventRender; values?: EventValues }; /** called after every stored write with the rendered resource, its stored type and the kernel operation name */ onWrite?: (write: { operation: string; storedType: string; body: Record; root?: string; occurredAt: string; request: Request; /** the writing call's context, narrow as a handler's, at the write's moment: what the hook reads to render the event * it sends (until `declared-semantics` makes events data the kernel renders) */ context(): Promise; }) => Promise; }; // ── request parsing ────────────────────────────────────────────────────────────────────────── /** A body's fields as a strict vendor checks them (`ctx.fields`, the manifest's `body.strict`). Without `strict`, every * field passes. An object or array field is not typed here: its own shape is the handler's. */ export function strictFields(m: DerivedManifest, operation: DerivedOperation, body: Record): { fields: Record } | { refused: Response } { const strict = m.body.strict; if (!strict) return { fields: { ...body } }; const declared = new Map((operation.body ?? []).map((f) => [f.name, f])); const refuse = (template: string, values: Record): { refused: Response } => ({ refused: vendorError(m, { status: strict.status, ...(strict.code ? { code: strict.code } : {}), message: String(fill(template, values)) }) }); const fields: Record = {}; for (const [name, value] of Object.entries(body)) { const field = declared.get(name); if (!field) return refuse(strict.unknown, { name }); const { type } = field; const fits = (value === null && !(type === 'array' && strict.arrays?.[name])) || (type === 'boolean' && typeof value === 'boolean') || (type === 'integer' && isExactIntegerValue(value)) || (type === 'number' && (typeof value === 'number' || isExactIntegerValue(value))) || (type === 'string' && typeof value === 'string') || (type === 'array' && Array.isArray(value) && (!strict.arrays?.[name] || value.every(item => typeof item === strict.arrays![name]))) || !['boolean', 'integer', 'number', 'string', 'array'].includes(type); if (!fits) return refuse(strict.type, { name, type: type === 'integer' ? 'an integer' : `a ${type}` }); if ((typeof value === 'number' || isExactIntegerValue(value)) && ((field.minimum !== undefined && compareExactNumbers(value, field.minimum) < 0) || (field.maximum !== undefined && compareExactNumbers(value, field.maximum) > 0))) { return refuse(strict.range, { name, min: field.minimum ?? null, max: field.maximum ?? null }); } fields[name] = value; } return { fields }; } /** Top-level schema checks with vendor-supplied response templates; unknown fields pass to semantics. */ function validateBody(m: DerivedManifest, operation: DerivedOperation, body: unknown): Response | undefined { const rule = m.body.validation; if (!rule || (rule.operations && !rule.operations.includes(operation.id))) return undefined; const refuse = (template: unknown, values: Record): Response => Response.json(fill(template, values), { status: rule.status }); if (!body || typeof body !== 'object' || Array.isArray(body)) return refuse(rule.type, { name: '$body', type: 'object', input: body ?? null }); const values = body as Record; for (const field of operation.body ?? []) { const value = values[field.name]; if (value === undefined) { if (field.required) return refuse(rule.missing, { name: field.name, input: values }); continue; } const types = field.type.split('|'); const fits = types.some((type) => type === 'null' ? value === null : type === 'integer' ? isExactIntegerValue(value) : type === 'array' ? Array.isArray(value) : type === 'object' ? value !== null && typeof value === 'object' && !Array.isArray(value) : type === 'string' ? typeof value === 'string' : type === 'number' ? typeof value === 'number' || isExactIntegerValue(value) : type === 'boolean' ? typeof value === 'boolean' : true); if (!fits) return refuse(rule.type, { name: field.name, type: field.type, input: value }); if ((typeof value === 'number' || isExactIntegerValue(value)) && ((field.minimum !== undefined && compareExactNumbers(value, field.minimum) < 0) || (field.maximum !== undefined && compareExactNumbers(value, field.maximum) > 0))) return refuse(rule.range, { name: field.name, min: field.minimum ?? null, max: field.maximum ?? null, input: value }); } return undefined; } /** A value as the vendor reads a boolean (`ctx.flag`, the manifest's `booleans`). */ export function flagOf(m: Pick, value: unknown): boolean | undefined { if (typeof value === 'boolean') return value; if (value === undefined || value === null) return undefined; const text = String(value).toLowerCase(); const { truthy, falsy } = m.booleans ?? { truthy: ['true'], falsy: ['false'] }; if (truthy.some((t) => t.toLowerCase() === text)) return true; if (falsy.some((f) => f.toLowerCase() === text)) return false; return undefined; } /** A request's parameters, its query's and its body's. With the manifest's `body.form.coerce`, a form's fields the * operation's spec types as numbers or booleans are read as them (parseBracketForm); without an operation (a twin door) * every form value is its text. */ export async function readParams(manifest: DerivedManifest, request: Request, operation?: DerivedOperation): Promise> { const url = new URL(request.url); const scalars = manifest.body.form?.coerce ? (operation?.scalars ?? {}) : undefined; const query = parseBracketForm(url.search.replace(/^\?/, ''), scalars); if (request.method === 'GET' || request.method === 'HEAD' || (operation && bytesPayload(operation))) return query; const type = request.headers.get('content-type') ?? ''; if (type.includes('multipart/form-data')) { // an upload: text fields as given, each file as its name, media type, size and content (its text), with its raw // `bytes` beside them for a pack that must tell an image or audio file from anything else; the bytes are not // enumerated, so a write's record of the request keeps the text alone // read from its bytes (multipart.ts): a runtime's form parser drops a part with an empty field name const boundary = multipartBoundary(type); const parts = boundary === null ? [] : multipartParts(new Uint8Array(await request.arrayBuffer()), boundary); const out: Record = { ...query }; for (const part of parts) { // each part a field of its own name, whatever the name (`__proto__` included: ownField) if (part.filename === null) { ownField(out, part.name, new TextDecoder().decode(part.body)); continue; } const bytes = part.body; const parsed = { name: part.filename, type: part.type ?? '', size: bytes.byteLength, content: new TextDecoder().decode(bytes) }; ownField(out, part.name, Object.defineProperty(parsed, 'bytes', { value: bytes, enumerable: false })); } return out; } // NDJSON (`application/x-ndjson`) is lines of JSON, not a JSON document: the handler reads its text const media = (type.split(';')[0] ?? '').trim().toLowerCase(); const isJson = media.includes('json') && !media.includes('ndjson') && !media.includes('connect+'); // a form is a body labelled one (application/x-www-form-urlencoded); a body of any other type (an image, a video, an // octet-stream PUT to an upload URL, a text/plain SQL statement, an NDJSON batch) is no form: its parameters are the // query's, and the handler reads its text or bytes itself const isForm = media === 'application/x-www-form-urlencoded'; const asJson = isJson || manifest.body.json === 'always'; if (!isForm && !asJson) return query; const text = await bodyTextOf(request); if (!text) return query; // `json: 'always'` reads a body labelled otherwise as JSON (GitHub reads curl -d's); a body that is not JSON is read // as a form only when it is labelled one (a sign-in page's own form, posted to the vendor's page), never a crash let body: unknown; if (asJson) { try { body = parseExactJson(text); } catch { if (isJson) throw new SyntaxError('malformed JSON body'); if (!isForm) return query; body = parseBracketForm(text, scalars); } } else body = parseBracketForm(text, scalars); // a body that is not an object (GitHub's set-labels takes a bare array) is the body, not fields return body && typeof body === 'object' && !Array.isArray(body) ? { ...query, ...(body as Record) } : { ...query }; } // ── answers ────────────────────────────────────────────────────────────────────────────────── const ABSENT = Symbol('absent'); function fill(template: unknown, values: Record, omitAbsent = false): unknown { if (typeof template === 'string') { const whole = /^\{(\w+)\}$/.exec(template); if (whole) return values[whole[1]!] ?? (omitAbsent ? ABSENT : null); return template.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? '')); } if (Array.isArray(template)) return template.map((t) => fill(t, values, omitAbsent)).filter((v) => v !== ABSENT); if (template && typeof template === 'object') { const entries = Object.entries(template).map(([k, v]) => [k, fill(v, values, omitAbsent)] as const).filter(([, v]) => v !== ABSENT); // an object every one of whose placeholders was absent is absent itself (Clerk's `meta` with no parameter to name) if (omitAbsent && entries.length === 0 && Object.keys(template).length > 0) return ABSENT; return Object.fromEntries(entries); } return template; } export function vendorError(manifest: DerivedManifest, e: ErrorSpec): Response { // the status as the answer's number, and as text for a vendor whose body spells it as a string (GitHub's "404") const values = { message: e.message, code: e.code ?? null, param: e.param ?? null, kind: e.kind ?? manifest.defaultKind ?? null, status: e.status, statusText: String(e.status) }; // the HTTP status, which a vendor may keep apart from the one its body names (errorsAnsweredAs) const answered = manifest.errorsAnsweredAs && e.status < manifest.errorsAnsweredAs.below ? manifest.errorsAnsweredAs.status : e.status; // a vendor that answers its errors as a document, not JSON (S3's XML `…`): the template is that text, // each value escaped into it if (typeof manifest.error === 'string') { const escape = (v: unknown): string => String(v ?? '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); const body = manifest.error.replace(/\{(\w+)\}/g, (_, k: string) => escape(values[k as keyof typeof values])); return new Response(body, { status: answered, headers: { 'content-type': body.trimStart().startsWith('<') ? 'application/xml' : 'text/plain; charset=utf-8' } }); } return Response.json(fill(manifest.error, values, manifest.errorOmitsAbsent ?? false), { status: answered }); } function notFound(manifest: DerivedManifest, object: string, id: string, param?: string): Response { const nf = manifest.notFound; if (!nf.withParam) param = undefined; const own = manifest.resources[object]?.notFound; const message = typeof own === 'string' ? own : (own?.message ?? nf.message); const code = typeof own === 'object' ? own.code : nf.code; return vendorError(manifest, { status: nf.status, message: String(fill(message, { object, id })), ...(code ? { code } : {}), ...(nf.kind ? { kind: nf.kind } : {}), ...(param ? { param } : {}) }); } // ── the tree ───────────────────────────────────────────────────────────────────────────────── const TENANT_TYPE = '::account:'; /** The accounts a namespaced pack holds rows of (each stored type's `::account:` suffix), and the unsuffixed default: whose * catch-up a twin's due work runs (ADR 0036 §4). */ export function storedTenants(m: DerivedManifest, root?: string): Array { if (m.tenant?.storage !== 'namespaced') return [undefined]; const accounts = new Set(); for (const r of twinResources(m.service, root)) { const encoded = r.type.split(TENANT_TYPE)[1]; if (encoded) accounts.add(decodeURIComponent(encoded)); } return [undefined, ...[...accounts].sort()]; } const accountScope = (m: DerivedManifest): string | undefined => m.tenant?.storage === 'namespaced' ? storageTenant(m.service) : undefined; /** The kernel's record of what `ctx.issueKey` issued: one subject per account and purpose, holding the value's SHA-256. */ const ISSUED_KEY = '_world_issued_key'; /** The generation of a purpose the next `issueKey` answers: the one recorded, or the one after it once it is revoked. */ const liveGeneration = (row: Record | undefined): number => (typeof row?.generation === 'number' ? row.generation : 1) + (row?.revoked === true ? 1 : 0); /** The issuance `value` was issued by in this World, when it is its purpose's live generation: its account and purpose. */ function issuedKeyOf(m: DerivedManifest, value: string, root: string | undefined): { account: string; purpose: string } | undefined { const hash = sha256(value); const row = resourcesOfType(m.service, storedType(m, ISSUED_KEY), root).find((r) => (r as Record)._sha256 === hash && (r as Record).revoked !== true) as Record | undefined; return row ? { account: String(row.account), purpose: String(row.purpose) } : undefined; } /** Revoke the live generation of `purpose` issued for `account`. */ async function revokeIssued(m: DerivedManifest, call: DerivedCall, account: string, purpose: string, root: string | undefined, at: string): Promise { const id = `${account}/${purpose}`, type = storedType(m, ISSUED_KEY); await applyTwinWriteAtomic(m.service, (snapshot) => { const row = snapshot.find((r) => r.type === type && r.id === id); return row?.revoked === true ? { kind: 'skip', value: id } : { kind: 'write', value: id, write: { operation: 'world_issued_key.revoke', subjectType: type, subjectId: id, fields: { account, purpose, generation: liveGeneration(row), ...(row ? {} : { _sha256: null }), revoked: true, revokedAt: at }, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' } } }; }, root); } const scopeLabel = (m: DerivedManifest, label: string): string => { const account = accountScope(m); return account && account !== 'default' ? `account:${account}:${label}` : label; }; export const storedType = (m: DerivedManifest, resource: string): string => { const base = m.resources[resource]?.storedAs ?? resource, account = accountScope(m); return account && account !== 'default' && !m.resources[resource]?.shared ? `${base}${TENANT_TYPE}${encodeURIComponent(account)}` : base; }; // A service's resources by type, folded once per World state (the tree's stamp; any write moves it), not on every read: // a read of one resource type projected the service's whole tree, so a pack whose tree also holds many subjects of // other types (PlanetScale's SQL rows beside its management records) paid for all of them on each read. A read gets its // own copy of each resource, as twinResources hands out, with the vendor's own id/type/updatedAt a spread would drop. const typeIndexes = new WeakMap>; typeByKey: Map }>>(); /** A service's resources of one type, each the reader's own copy: `twinResources` filtered by type, from an index * that follows each write rather than projecting the whole tree per call. */ export function resourcesOfType(service: string, type: string, root?: string): TwinResource[] { const store = getActiveWorldStore(); const indexes = typeIndexes.get(store) ?? typeIndexes.set(store, new Map()).get(store)!; const key = `${service}\u0000${root ?? ''}`; let held = indexes.get(key); // a write moves the stamp; the index follows it by the subjects the write touched, and refolds only when // the kernel cannot say which (a projection of the whole tree after every write grew with the World) const delta = held ? treeChangesSince(service, root, held.stamp) : undefined; if (held && delta) { // the index keeps the tree's order: a subject updated where it stands stays there, one new to the tree (or made // again after a delete) goes to the end in the order the tree holds it for (const k of [...delta.removed, ...delta.appended]) { const type = held.typeByKey.get(k); if (type !== undefined) held.byType.get(type)?.delete(k); held.typeByKey.delete(k); } const byKey = new Map(delta.changed.map((r) => [`${r.type}:${r.id}`, r])); for (const [k, r] of byKey) held.typeByKey.set(k, r.type); for (const [k, r] of byKey) if (!delta.appended.includes(k)) (held.byType.get(r.type) ?? held.byType.set(r.type, new Map()).get(r.type)!).set(k, r); for (const k of delta.appended) { const r = byKey.get(k)!; (held.byType.get(r.type) ?? held.byType.set(r.type, new Map()).get(r.type)!).set(k, r); } held.stamp = delta.stamp; } else { // the stamp is read once, before the fold, so a write between them can only leave a newer fold under an older stamp const stamp = treeStamp(service, root); if (!held || held.stamp !== stamp) { const byType = new Map>(); for (const r of twinResources(service, root)) (byType.get(r.type) ?? byType.set(r.type, new Map()).get(r.type)!).set(`${r.type}:${r.id}`, r); held = { stamp, byType, typeByKey: new Map([...byType].flatMap(([type, rows]) => [...rows.keys()].map(key => [key, type] as const))) }; indexes.set(key, held); } } return [...(held.byType.get(type)?.values() ?? [])].map(copyResource); } /** A resource's readable rows: of the World as it stands, or of `from` (the World as it stood at an instant, readTreeAsOf). */ function stored(m: DerivedManifest, resource: string, root?: string, opts: { withDeleted?: boolean; from?: TwinResource[] } = {}): TwinResource[] { const type = storedType(m, resource); const when = Object.entries(m.resources[resource]?.readableWhen ?? {}); const rows = m.tenant?.storage === 'namespaced' && accountScope(m) === undefined && !m.resources[resource]?.shared ? (opts.from ?? twinResources(m.service, root)).filter(row => row.type === type || row.type.startsWith(`${type}${TENANT_TYPE}`)) : opts.from ? opts.from.filter((row) => row.type === type) : resourcesOfType(m.service, type, root); return rows.filter((r) => (opts.withDeleted || r.deleted !== true) && when.every(([k, v]) => (r as Record)[k] === v)); } /** The subject an item operation names: the manifest's key over the path parameters, or the last one. */ function subjectOf(m: DerivedManifest, resource: string, call: DerivedCall): string | undefined { const key = m.resources[resource]?.key; return key ? String(fill(key, call.params)) : Object.values(call.params).at(-1); } /** A missing parent's not-found, when the resource lives under one. */ /** The parent value a call names: one path parameter, or several joined by the parent's template. */ function parentValue(parent: NonNullable, params: Record): string | undefined { if (parent.params) return String(fill(parent.value ?? parent.params.map((p) => `{${p}}`).join('/'), params)); return parent.param !== undefined ? params[parent.param] : undefined; } function parentField(row: unknown, path: string): unknown { if (row && typeof row === 'object' && Object.hasOwn(row, path)) return (row as Record)[path]; let value = row; for (const key of path.split('.')) value = value && typeof value === 'object' ? (value as Record)[key] : undefined; return value; } function parentOfCall(decl: ResourceDecl | undefined, call: DerivedCall): ResourceDecl['parent'] { const parent = decl?.parent; const names = parent?.params ?? (parent?.param === undefined ? [] : [parent.param]); return parent?.whenNamed && names.length && !names.some((name) => Object.hasOwn(call.params, name)) ? undefined : parent; } function missingParent(m: DerivedManifest, resource: string, call: DerivedCall, root?: string, tenant?: string): Response | undefined { const parent = parentOfCall(m.resources[resource], call); if (!parent) return undefined; const id = parentValue(parent, call.params); const where = Object.entries(parent.where ?? {}).map(([field, template]) => [field, String(fill(template, call.params))] as const); const found = (r: TwinResource): boolean => (where.length ? where.every(([field, v]) => String(parentField(r, field)) === v) : r.id === id) && (!m.tenant || m.tenant.storage === 'namespaced' || m.resources[parent.resource]?.shared || (r as Record)[m.tenant.field] === tenant); return id !== undefined && stored(m, parent.resource, root, { withDeleted: parent.allowDeleted === true }).some(found) ? undefined : notFound(m, parent.resource, String(id), parent.param ?? parent.params?.at(-1)); } /** The vendor's view of a stored subject: its own fields, bookkeeping (`_`) left out. */ /** A stored subject as the vendor's object: its id first (the subject's, unless the pack kept an id of its own), then * the fields the pack wrote, bookkeeping (`_`) and the kernel's updatedAt left out. */ export function render(r: TwinResource, vendorUnderscored: readonly string[] = []): Record { return renderOwn({ id: r.id, ...ownFields(r) }, vendorUnderscored); } /** Filter an own-field view through the same declared vendor fields as a stored row. */ function renderOwn(own: Record, vendorUnderscored: readonly string[] = []): Record { return Object.fromEntries(Object.entries(own).filter(([k]) => !k.startsWith('_') || vendorUnderscored.includes(k))); } type ViewOmissions = { fields: Map>; affected: Set; embeds: Map> }; const viewOmissions = new WeakMap(); // Precompute once at manifest binding: omitted fields, whether any exist, and their transitive containers through embeds. function prepareViewOmissions(m: DerivedManifest): ViewOmissions { const held = viewOmissions.get(m); if (held) return held; const fields = new Map>(); for (const [resource, decl] of Object.entries(m.resources)) { if (decl.viewOmit?.length) fields.set(resource, new Set(decl.viewOmit)); } const affected = new Set(fields.keys()); const embeds = new Map>(); if (fields.size) { let changed = true; while (changed) { changed = false; for (const [resource, decl] of Object.entries(m.resources)) { if (!affected.has(resource) && Object.values(decl.embeds ?? {}).some((target) => affected.has(target))) { affected.add(resource); changed = true; } } } for (const resource of affected) { embeds.set(resource, Object.entries(m.resources[resource]?.embeds ?? {}).filter(([, target]) => affected.has(target))); } } const plan = { fields, affected, embeds }; viewOmissions.set(m, plan); return plan; } /** The one response-omission mechanism, shared by stored, constructed and expanded resource views. */ function omitView(m: DerivedManifest, resource: string | undefined, body: Record, seen?: Map>>): Record { const plan = viewOmissions.get(m) ?? prepareViewOmissions(m); if (!resource || !plan.affected.has(resource)) return body; const held = seen?.get(resource)?.get(body); if (held) return held; const out = { ...body }; seen ??= new Map(); let visited = seen.get(resource); if (!visited) { visited = new WeakMap(); seen.set(resource, visited); } visited.set(body, out); for (const field of plan.fields.get(resource) ?? []) delete out[field]; for (const [field, target] of plan.embeds.get(resource) ?? []) { const present = out[field]; if (Array.isArray(present)) { out[field] = present.map((child) => child && typeof child === 'object' && !Array.isArray(child) ? omitView(m, target, child, seen) : child); } else if (present && typeof present === 'object') { out[field] = omitView(m, target, present as Record, seen); } } return out; } /** A stored subject as the vendor answers it: its own fields, its id under the name the vendor gives it. */ function view(m: DerivedManifest, resource: string, r: TwinResource): Record { const idAs = m.resources[resource]?.idAs; const keep = m.resources[resource]?.vendorUnderscored ?? []; const shown = omitView(m, resource, render(r, keep)); if (!idAs) return shown; const { id, ...rest } = shown; return { [idAs]: id, ...rest }; } /** Where the core runs: the World root it reads and writes, and its clock (the World's by default; * a caller that pins an instant passes its own). */ /** One call of a protocol-3 pack's default data (`src/semantics/seed.ts` exports `seed: SeedCall[]`): a request to the * vendor's own operation (or the pack's door), made in order against the twin by the runner `volter world init` writes * beside the copied data. An ordinary path is relative to the twin base. A call naming a browser uses the * vendor's absolute URL and is exported separately as `browserSeed`, after the ordinary `seed` calls. */ /** How a refresh list's answer items become subjects' fields where each is not one subject's object (architecture, * "Refresh"): `scalar`, a bare item is that field; `value` (with `keyed`), a scalar map value is that field and, with * `keyAs`, the map key is that field rather than the id; `spread`, an item expands into the array at `path`, each * element an object or a scalar named `as`, beside the item's fields `carry` names (field: path in the item). */ export type RefreshShape = { scalar?: string; value?: string; keyAs?: string; spread?: { path: string; as?: string; carry?: Record }; /** each item with every item nested under it at this field, however deep (a tree of spans) */ recurse?: string }; /** A read a root scoped to one of the vendor's own things makes instead of the resource's `refresh` (architecture, * "What the descriptor adds": `scopedRefresh`): `scope`'s `{name}`s capture the root scope's segments, and `each` makes * one read per distinct value at `path` among `from`'s observations of the same refresh, bound to `{as}`. The read itself * is a `refresh` list or get; its `idAs` reads the bindings too. */ export type ScopedRefresh = { scope: string; each?: { from: string; path: string; as: string } } & Exclude, { none: string }> & { graphql?: never }; export type SeedCall = { browser?: string; method: string; path: string; body?: unknown; headers?: Record; /** the instant the account made it, before the World's time: the call is made with the World clock frozen there */ at?: string }; /** Where a call is answered: the World's root, its clock, and the managed Postgres the runtime binds to the pack * (`database`, the descriptor's `managedDatabase`), which a handler reaches as `ctx.engine` — READ ONLY in every * transaction when the twin is (`readOnly`) or the request is (x-volter-read-only). */ export type CoreScope = { root?: string; clock?: () => string; database?: string; readOnly?: boolean; resources?: DerivedSurface['resources']; /** `semantics/tenant.ts`: the tenant the caller acts in (the manifest's `tenant`), or undefined for none */ tenant?: (ctx: HandlerContext) => string | undefined | Promise; /** the application a walk stands in for: vendor requests and declared events are answered by it (events.ts) */ application?: ApplicationStandIn; }; function now(m: DerivedManifest, at: string): unknown { return m.time === 'unix' ? Math.floor(Date.parse(at) / 1000) : m.time === 'unix-ms' ? Date.parse(at) : at; } function applyRule(m: DerivedManifest, rule: FieldRule, id: string, values: Record, at: string): unknown { if ('now' in rule) return now(m, at); if ('id' in rule) return id; if ('value' in rule) return rule.value; const text = fill(rule.template, { ...values, id }); return rule.encode === 'base64' ? btoa(String.fromCharCode(...new TextEncoder().encode(String(text)))) : text; } const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); /** The next id the manifest's template gives this resource: one past the highest it already minted. */ /** The World's seed for a service's secrets and keys (ctx.secret, ctx.signingKey): made once, then read. Where the host * names the World's seed identity (worldStateFile('seed'): a file of the active World's own, made at random when the World is first * made and kept by a reset, a resume and a branch), the seed is HMAC-SHA256(identity, `world-seed:`), so a * World returned to its seed issues every key and secret it issued before (ADR 0029, "Keys and generated secrets are * retained World state"); where none is named (a walk, a hosted World), it is drawn from the platform's random source. * The making is one per service store in the process: two first calls at once share it, so no secret handed out under * one seed is lost to another written after it (a service's store is one process's). */ const SEED = '_world_seed'; const seeding = new Map>(); function seedIdentity(file: string | undefined): string | undefined { if (!file) return undefined; const held = getActiveWorldStore().read(file)?.trim(); if (!held || !/^[0-9a-f]{64}$/.test(held)) throw new Error(`The World's seed identity at ${file} is ${held ? 'unreadable' : 'missing'}: a World's keys are drawn from it; restore it, or purge the World`); return held; } function worldSeed(service: string, root: string | undefined, at: string, seedFile = worldStateFile('seed')): Promise { const held = resourcesOfType(service, SEED, root).find((r) => r.id === 'seed') as Record | undefined; if (typeof held?.value === 'string') return Promise.resolve(held.value); const key = `${root ?? ''}\u0000${service}`; const pending = seeding.get(key); if (pending) return pending; const made = (async () => { // The action lock also joins first asks from several renderers/processes to the same seed. const { value } = await runAsVendorMove(() => applyTwinWriteAtomic(service, snapshot => { const existing = snapshot.find(row => row.type === SEED && row.id === 'seed'); if (typeof existing?.value === 'string') return { kind: 'skip', value: existing.value }; const identity = seedIdentity(seedFile); const value = identity ? hmac(identity, `world-seed:${service}`) : Buffer.from(globalThis.crypto.getRandomValues(new Uint8Array(32))).toString('hex'); return { kind: 'write', value, write: { operation: 'world_seed.record', subjectType: SEED, subjectId: 'seed', fields: { value }, occurredAt: at, actor: { kind: 'system' } } }; }, root)); return value; })().finally(() => seeding.delete(key)); seeding.set(key, made); return made; } /** World-owned generated values use the same private seed and log as pack secrets. */ export async function worldSecret(service: string, root: string, label: string, at = new Date().toISOString(), seedFile?: string): Promise { return hmac(await worldSeed(service, root, at, seedFile), label, 'base64url'); } /** The same retained account primitive for pack doors and private native twin fronts. */ export async function worldAccount(service: string, root: string | undefined, id: unknown = 'default', at = worldNow(), provisioning = false): Promise { if (!isWorldAccountName(id)) throw new Error('Credential account must be a name of at most 128 letters, digits, dots, underscores or hyphens'); await applyTwinWriteAtomic(service, (snapshot) => { const held = snapshot.find(row => row.type === '_world_account' && row.id === id); return held ? { kind: 'skip', value: id } : { kind: 'write', value: id, write: { operation: 'world_account.create', subjectType: '_world_account', subjectId: id, fields: { name: id }, ...(provisioning ? { input: { activity: 'provisioning' } } : {}), occurredAt: at, actor: { kind: 'system' } } }; }, root); return id; } type WorldOrganization = { id: string; label: string; members: string[] }; type VendorNameRule = { max: number; lower?: boolean; allowed: RegExp; separator?: string; first?: RegExp }; type NativeAccountLink = { resource: string; id: string }; function nativeAccountLink(row: TwinResource | undefined, field?: string): NativeAccountLink | undefined { if (!row || row.deleted === true) return undefined; const fields = ownFields(row); const value = field === undefined ? fields : fields[field]; if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; const link = value as Record; return typeof link.resource === 'string' && typeof link.id === 'string' ? { resource: link.resource, id: link.id } : undefined; } const sameAccountLink = (a: NativeAccountLink | undefined, b: NativeAccountLink | undefined): boolean => a?.resource === b?.resource && a?.id === b?.id; /** Native creation and reconstruction run outside the action lock; only the retained link is compared and written. */ async function retainNativeAccountLink( service: string, root: string | undefined, at: string, call: DerivedCall, type: string, id: string, field: string | undefined, resource: string, make: () => Promise, read: (link: NativeAccountLink) => Promise, ): Promise { for (;;) { const before = nativeAccountLink(resourcesOfType(service, type, root).find((row) => row.id === id), field); const held = before && await read(before); if (held !== undefined) return held; const made = { resource, id: await make() }; if (await read(made) === undefined) throw new Error(`Credential ${type}/${id}: native ${resource}/${made.id} is unavailable after creation`); const { value } = await applyTwinWriteAtomic(service, (snapshot) => { const current = nativeAccountLink(snapshot.find((row) => row.type === type && row.id === id), field); if (!sameAccountLink(current, before)) return { kind: 'skip', value: current }; return { kind: 'write', value: made, write: { operation: `${type.slice(1)}.link`, subjectType: type, subjectId: id, fields: field === undefined ? made : { name: id, [field]: made }, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' }, }, }; }, root); const linked = value && await read(value); if (linked !== undefined) return linked; } } function vendorName(label: string, rule: VendorNameRule, { suffixed = false, identity = label }: { suffixed?: boolean; identity?: string } = {}): string { const allowed = new RegExp(rule.allowed.source, rule.allowed.flags.replace(/[gy]/g, '')); const separator = rule.separator ?? '-'; if ([...separator].length !== 1 || !allowed.test(separator)) throw new Error('Credential name separator must be one allowed character'); const first = rule.first && new RegExp(rule.first.source, rule.first.flags.replace(/[gy]/g, '')); let name = [...(rule.lower ? label.toLowerCase() : label)].map((letter) => allowed.test(letter) ? letter : separator).join(''); name = name.replace(new RegExp(`${escapeRe(separator)}+`, 'g'), separator); if (first && !first.test(name[0] ?? '')) name = `w${separator}${name}`; return name !== label || name.length > rule.max || suffixed ? `${name.slice(0, Math.max(0, rule.max - 9))}${separator}${sha256(identity).slice(0, 8)}` : name; } /** A World's signing key for a label (ctx.signingKey): drawn once from the World's seed (seeded-keys.ts), so the same * seed and label give the same pair, then read; the making is one per service store and label in the process, as the * seed's is. */ const SIGNING_KEY = '_world_signing_key'; const keying = new Map>(); function heldWorldSigningKey(service: string, root: string | undefined, label: string, alg: 'RS256' | 'Ed25519'): { privatePem: string; publicPem: string } | undefined { const id = alg === 'RS256' ? label : `${label}#${alg}`; const held = resourcesOfType(service, SIGNING_KEY, root).find((r) => r.id === id) as Record | undefined; return typeof held?.privatePem === 'string' && typeof held.publicPem === 'string' ? { privatePem: held.privatePem, publicPem: held.publicPem } : undefined; } function worldSigningKey(service: string, root: string | undefined, at: string, label: string, alg: 'RS256' | 'Ed25519'): Promise<{ privatePem: string; publicPem: string }> { // an RSA key keeps its label; another algorithm's is kept under the label and the algorithm, so one label never names two const id = alg === 'RS256' ? label : `${label}#${alg}`; const held = resourcesOfType(service, SIGNING_KEY, root).find((r) => r.id === id) as Record | undefined; if (typeof held?.privatePem === 'string' && typeof held.publicPem === 'string') return Promise.resolve({ privatePem: held.privatePem, publicPem: held.publicPem }); const key = `${root ?? ''}\u0000${service}\u0000${id}`; const pending = keying.get(key); if (pending) return pending; const made = (async () => { const fields = await seededKeyPair(await worldSeed(service, root, at), label, alg); await runAsVendorMove(() => applyTwinWrite(service, { operation: 'world_signing_key.record', subjectType: SIGNING_KEY, subjectId: id, fields, occurredAt: at, actor: { kind: 'system' } }, root)); return fields; })().finally(() => keying.delete(key)); keying.set(key, made); return made; } /** Vendor ids remain unique across its accounts, including public links that carry an id instead of a key. */ function mintRows(m: DerivedManifest, resource: string, root?: string, snapshot?: readonly TwinResource[]): readonly TwinResource[] { const base = m.resources[resource]?.storedAs ?? resource; if (m.tenant?.storage === 'namespaced') return (snapshot ?? twinResources(m.service, root)).filter(row => row.type === base || row.type.startsWith(`${base}${TENANT_TYPE}`)); return snapshot ? snapshot.filter(row => row.type === base) : resourcesOfType(m.service, base, root); } function mintId(m: DerivedManifest, resource: string, root: string | undefined, at: string, snapshot?: readonly TwinResource[]): string { if (!m.resources[resource]) throw new Error(`mint: ${resource} is not a resource ${m.vendor}'s manifest declares`); const prefix = m.resources[resource]!.idPrefix; const template = m.resources[resource]!.ids ?? m.ids.template; if (template === '{uuid}') return mintUuid(m, resource, root, snapshot); const snowflake = /^\{snowflake:(\d+)\}$/.exec(template); if (snowflake) return mintSnowflake(m, BigInt(snowflake[1]!), root, at, snapshot); // `{letters:N}` and `{hex:N}`, alone, after the resource's prefix (`{prefix}{letters:16}`: Fly's `vol_…`), or after it // and a separator (`{prefix}_{hex:48}`: OpenAI's `resp_67cc…`) const letters = /^(?:\{prefix\}([_-]?))?\{letters:(\d+)\}$/.exec(template); if (letters) return mintLetters(m, resource, Number(letters[2]), root, letters[1] !== undefined ? `${prefix}${letters[1]}` : '', snapshot); const hex = /^(?:\{prefix\}([_-]?))?\{hex:(\d+)\}$/.exec(template); if (hex) return mintHex(m, resource, Number(hex[2]), root, hex[1] !== undefined ? `${prefix}${hex[1]}` : '', snapshot); const digits = /^\{digits:(\d+)\}$/.exec(template); if (digits) { const width = Number(digits[1]); if (!Number.isInteger(width) || width < 1 || width > 77) throw new Error('mint: decimal width must be between 1 and 77'); const held = new Set(mintRows(m, resource, root, snapshot).map((r) => r.id)); const floor = 10n ** BigInt(width - 1); for (let n = held.size + 1; ; n++) { const id = String(floor + BigInt('0x' + sha256(`${m.service}:${resource}:${n}`)) % (9n * floor)); if (!held.has(id)) return id; if (n - held.size > 9 * Number(floor)) throw new Error('mint: decimal id space exhausted'); } } // `{ksuid}` alone, after the prefix, or after it and a separator (`{prefix}_{ksuid}`: Clerk's `user_2…`) // `{ksuid:N}` gives the id N characters (a vendor's own length: OpenAI's `proj_` 24, `chatcmpl-` 29), its order kept const ksuid = /^(?:\{prefix\}([_-]?))?\{ksuid(?::(\d+))?\}$/.exec(template); // narrower than 11 characters a KSUID no longer holds its instant and mint count, so neither order nor uniqueness // within a second: such an id is minted otherwise ({letters:N}, {hex:N}) if (ksuid && ksuid[2] && Number(ksuid[2]) < 11) throw new Error(`${m.service}: ${resource}'s id template ${template} is narrower than a KSUID's 11 ordered characters`); if (ksuid) return mintKsuid(m, resource, at, root, ksuid[1] !== undefined ? `${prefix}${ksuid[1]}` : '', snapshot, ksuid[2] ? Number(ksuid[2]) : 27); const [head, tail = ''] = template.split('{n}'); const pattern = new RegExp(`^${escapeRe(String(fill(head!, { prefix })))}(\\d+)${escapeRe(String(fill(tail, { prefix })))}$`); let max = 0n; // the one type, from the index that follows writes (a scan of the whole World per create grew with it) for (const r of mintRows(m, resource, root, snapshot)) { const hit = pattern.exec(r.id); if (hit && BigInt(hit[1]!) > max) max = BigInt(hit[1]!); } return String(fill(template, { prefix, n: String(max + 1n) })); } /** The next snowflake (Discord's, X's): the milliseconds since the vendor's epoch shifted left 22 bits, the low bits an * increment. One space over every snowflake resource of the vendor, as its one generator's: the instant's first, or one * past the greatest the World holds when that is later (a frozen clock, or several ids in one millisecond), so ids * rise with time and never repeat. */ /** The last snowflake minted per store, vendor and World: two mints before the first is written (a message * and its attachment) must not meet. */ const lastSnowflake = new WeakMap>(); function mintSnowflake(m: DerivedManifest, epoch: bigint, root: string | undefined, at: string, snapshot?: readonly TwinResource[]): string { const ms = BigInt(Date.parse(at) || 0); const base = ms > epoch ? (ms - epoch) << 22n : 0n; let max = -1n; for (const [name, decl] of Object.entries(m.resources)) { if (!/^\{snowflake:\d+\}$/.test(decl.ids ?? m.ids.template)) continue; for (const r of mintRows(m, name, root, snapshot)) if (/^\d+$/.test(r.id)) { const v = BigInt(r.id); if (v > max) max = v; } } const store = getActiveWorldStore(); const reservations = lastSnowflake.get(store) ?? lastSnowflake.set(store, new Map()).get(store)!; const key = `${m.service}\0${root ?? ''}`; const last = reservations.get(key) ?? -1n; const floor = max > last ? max : last; const id = base > floor ? base : floor + 1n; reservations.set(key, id); return String(id); } /** The next KSUID for a resource (Clerk's and Svix's ids, `ksuidFrom`): the World's instant, then the type's mint * count, so a frozen clock still lists them as made; past any the World already holds. */ function mintKsuid(m: DerivedManifest, resource: string, at: string, root: string | undefined, prefix: string, snapshot: readonly TwinResource[] | undefined, width: number): string { const held = new Set(mintRows(m, resource, root, snapshot).map((r) => r.id)); const seconds = Math.floor((Date.parse(at) || 0) / 1000); for (let n = held.size + 1; ; n++) { const id = `${prefix}${ksuidFrom(seconds, n, `${m.service}:${resource}:${n}`, width)}`; if (!held.has(id)) return id; } } /** The next id of `count` lowercase letters for a resource, derived from the resource and the count before it, past * any the World already holds. */ function mintLetters(m: DerivedManifest, resource: string, count: number, root: string | undefined, prefix: string, snapshot?: readonly TwinResource[]): string { const held = new Set(mintRows(m, resource, root, snapshot).map((r) => r.id)); for (let n = held.size + 1; ; n++) { const id = `${prefix}${lettersFrom(`${m.service}:${resource}:${n}`, count)}`; if (!held.has(id)) return id; } } /** The next hex id for a resource: N hex digits derived from the resource and the count before it, past any the World * already holds (a Cloudflare id, 32). */ function mintHex(m: DerivedManifest, resource: string, count: number, root: string | undefined, prefix: string, snapshot?: readonly TwinResource[]): string { const held = new Set(mintRows(m, resource, root, snapshot).map((r) => r.id)); for (let n = held.size + 1; ; n++) { const id = `${prefix}${sha256(`${m.service}:${resource}:${n}`).slice(0, count)}`; if (!held.has(id)) return id; } } /** The next UUID for a resource: a version-4-shaped UUID derived from the resource and the count before it, past any * the World already holds. */ function mintUuid(m: DerivedManifest, resource: string, root?: string, snapshot?: readonly TwinResource[]): string { const held = new Set(mintRows(m, resource, root, snapshot).map((r) => r.id)); for (let n = held.size + 1; ; n++) { const id = uuidFrom(`${m.service}:${resource}:${n}`); if (!held.has(id)) return id; } } function expand(m: DerivedManifest, resource: string, body: Record, paths: string[], root?: string, within: ReadonlySet = new Set()): Record { body = omitView(m, resource, body); const embeds = m.resources[resource]?.embeds ?? {}; // the fields the vendor always embeds join the caller's paths; a resource already being embedded above is not embedded // again inside itself (a cycle answers the id) const always = within.has(resource) ? [] : (m.resources[resource]?.alwaysEmbedded ?? []); const inner = new Set([...within, resource]); const out = { ...body }; const idKey = m.resources[resource]?.idAs ?? 'id'; const ownId = typeof body[idKey] === 'string' ? body[idKey] as string : undefined; for (const [field, c] of within.has(resource) ? [] : Object.entries(m.resources[resource]?.collections ?? {})) { if (!ownId) continue; const childPaths = paths.filter((p) => p.startsWith(`${field}.data.`)).map((p) => p.slice(field.length + 6)); const data = stored(m, c.resource, root).filter((r) => (r as Record)[c.by] === ownId) .map((r) => expand(m, c.resource, view(m, c.resource, r), childPaths, root, inner)); const fill = (v: unknown): unknown => v === '{count}' ? data.length : typeof v === 'string' ? v.replaceAll('{id}', ownId) : v; out[field] = { ...Object.fromEntries(Object.entries(c.list ?? {}).map(([k, v]) => [k, fill(v)])), data }; } for (const path of [...new Set([...always, ...paths])]) { const [head, ...rest] = path.split('.'); const target = embeds[head!]; const id = out[head!]; if (!target) continue; // an object already embedded (an earlier path's) is walked further, not fetched again if (id && typeof id === 'object' && !Array.isArray(id)) { out[head!] = expand(m, target, id as Record, rest.length ? [rest.join('.')] : [], root, inner); continue; } if (typeof id !== 'string') continue; const hit = stored(m, target, root).find((r) => r.id === id); if (hit) out[head!] = expand(m, target, view(m, target, hit), rest.length ? [rest.join('.')] : [], root, inner); } return out; } function expandPaths(m: DerivedManifest, params: Record): string[] { const raw = m.expandParam ? params[m.expandParam] : undefined; return Array.isArray(raw) ? raw.map(String) : typeof raw === 'string' ? [raw] : []; } async function write(m: DerivedManifest, call: DerivedCall, resource: string, id: string, fields: Record, operation: string, params: Record, root: string | undefined, occurredAt: string, checks?: StateChecks): Promise> { return (await writeDetailed(m, call, resource, id, fields, operation, params, root, occurredAt, checks)).body; } /** The request a context was opened for, as it came (contextFor): its path parameters, the query names the operation * declares (a repeated name as its values), its body before the core's merge and alias adoption with only the fields * the operation declares (a credential the caller put in the query or the body, Slack's `token`, is not the request's: * a perform carries the root's), the headers the manifest names, and the caller's own request id as provenance. */ type SentRequest = { path: Record; query: Record; body: unknown; headers: Record; lane?: string; requestId?: string; parts?: MultipartPart[]; type?: string }; const sentOf = new WeakMap(); /** The lane a vendor's router sent a request to (pack-fetch's laneRouter sets it). */ export const LANE_HEADER = 'x-volter-lane'; function sentRequest(m: DerivedManifest, call: DerivedCall, body: unknown): SentRequest { const url = new URL(call.request.url); const named = [...(m.headers ?? []), ...(m.version ? [m.version.header] : [])].map((h) => h.toLowerCase()); const recorded = (h: string): boolean => named.some((n) => (n.endsWith('*') ? h.startsWith(n.slice(0, -1)) : h === n)); const headers = Object.fromEntries([...call.request.headers].filter(([h]) => recorded(h.toLowerCase())).map(([h, v]) => [h.toLowerCase(), v])); const lane = call.request.headers.get(LANE_HEADER) ?? undefined; const requestId = call.request.headers.get('x-twins-request-id') ?? undefined; const declared = new Set((call.operation.query ?? []).map((q) => q.name)); const query: Record = {}; for (const name of new Set(url.searchParams.keys())) { if (!declared.has(name)) continue; const values = url.searchParams.getAll(name); query[name] = values.length > 1 ? values : values[0]!; } const fields = new Set((call.operation.body ?? []).map((f) => f.name)); const asCame = body !== null && typeof body === 'object' && ('$text' in body || '$base64' in body); const sentBody = fields.size && !asCame && body !== null && typeof body === 'object' && !Array.isArray(body) ? Object.fromEntries(Object.entries(body as Record).filter(([k]) => fields.has(k))) : body; return { path: { ...call.params }, query, body: sentBody, headers, ...(lane ? { lane } : {}), ...(requestId ? { requestId } : {}) }; } /** What a write records of the call that made it: the surface operation and the request as it came, or which of the * World's own doors made it (a door or a screen, the gap, the clock), which a perform never sends. */ /** An operation whose body is its payload's bytes, one `blob` field: recorded as it came and never read as JSON * ("What the derived core records with a write"). */ const bytesPayload = (op: DerivedCall['operation']): boolean => op.body?.length === 1 && op.body[0]!.type === 'blob'; /** A body as it came: `{ $text }` when its bytes are UTF-8, else `{ $base64 }`. */ async function rawBody(request: Request): Promise<{ $text: string } | { $base64: string }> { const bytes = new Uint8Array(await request.clone().arrayBuffer()); try { return { $text: new TextDecoder('utf-8', { fatal: true }).decode(bytes) }; } catch { return { $base64: Buffer.from(bytes).toString('base64') }; } } /** A multipart request's file parts, kept in the World's blob store by their bytes' digest (`files/`): what a * write records of them (`input.files`), so a perform sends them again. */ async function keptFiles(m: DerivedManifest, call: DerivedCall, root: string | undefined): Promise | undefined> { const files = sentOf.get(call)?.parts?.filter((p) => p.filename !== null); if (!files?.length) return undefined; const out: Array<{ field: string; name: string; type: string | null; blob: string }> = []; for (const f of files) { const blob = `files/${hashFieldValue({ bytes: Buffer.from(f.body).toString('base64') })}`; await writeResourceBlob(m.service, blob, f.body, root); out.push({ field: f.name, name: f.filename!, type: f.type, blob }); } return out; } /** Presentation tag only: keep provisioning in history without copying credential request data. */ function provisioningInput(call: DerivedCall): { input?: { activity: 'provisioning' } } { return call.request.headers.get('x-volter-world-activity') === 'provisioning' ? { input: { activity: 'provisioning' } } : {}; } /** Whether a field names a credential: a password under any name the packs' doors and screens give it (`password`, * `passwd`, `pw`, `pass`, `session_password`, `user[password]`…; a screen names its own field, world-ui's SignIn * `password.name`, so the rule reads the name, not a list), or a secret, an API key, an access, refresh or id token, a * PKCE verifier or a private key, alone or as the name's last part. ADR 0025. */ const credentialKey = (key: string): boolean => { const k = key.toLowerCase(); return k.includes('password') || k.includes('passwd') || /(^|[[_.-])(pw|pass|secret|client_secret|api_?key|apikey|access_token|refresh_token|id_token|code_verifier|private_key)\]?$/.test(k); }; /** A request header that carries a credential: never recorded, whatever a manifest names (the executor sends the real * system's own from custody). */ const credentialHeader = (header: string): boolean => { const h = header.toLowerCase(); return h === 'authorization' || h === 'proxy-authorization' || h === 'cookie' || /(^|-)api-?key$/.test(h) || /token|secret|password|passwd/.test(h); }; /** A form's text as a `
` sends it (`a=1&password=…`), told apart from other text. */ /** A posted form's fields without its credentials, or the text unchanged, byte for byte, when it carries none. */ function formWithoutCredentials(text: string, removed: Set): string { const form = new URLSearchParams(text); const credentials = [...new Set(form.keys())].filter(credentialKey); if (!credentials.length) return text; for (const key of credentials) { removed.add(key); form.delete(key); } return form.toString(); } /** A multipart form's parts without one named for a credential, or the text unchanged when none is. */ function multipartWithoutCredentials(text: string, boundary: string, removed: Set): string { const parts = text.split(`--${boundary}`); const kept = parts.filter((part) => { const name = /name="([^"]*)"/.exec(part)?.[1] ?? ''; if (!credentialKey(name)) return true; removed.add(name); return false; }); return kept.length === parts.length ? text : kept.join(`--${boundary}`); } /** A recorded request's body or query without its credentials, named in `removed`: fields named for one are taken out of * a JSON value at any depth. A body that is a posted form (its content type says so) is read as one: its text, as it * came or kept as `{ $text }`, loses its credential fields (re-encoded with URLSearchParams, the others in order), and a * multipart form loses a part named for one. Any other string, at any depth, is left as it was: a URL with a query in * a JSON body (a checkout's success_url) is a value, not a form. */ function withoutCredentials(value: unknown, contentType = '', removed = new Set()): unknown { const form = /application\/x-www-form-urlencoded/i.test(contentType); const boundary = /multipart\/form-data;.*boundary="?([^";]+)"?/i.exec(contentType)?.[1]; if (typeof value === 'string') return form ? formWithoutCredentials(value, removed) : boundary ? multipartWithoutCredentials(value, boundary, removed) : value; // (a body that came as text is kept as { $text }: the form is in it) if (form && value && typeof value === 'object' && typeof (value as { $text?: unknown }).$text === 'string') { return { ...(value as object), $text: formWithoutCredentials((value as { $text: string }).$text, removed) }; } return withoutCredentialFields(value, removed); } /** A JSON value without the fields named for a credential, at any depth; every other value is kept as it was. */ function withoutCredentialFields(value: unknown, removed: Set): unknown { if (Array.isArray(value)) return value.map((v) => withoutCredentialFields(v, removed)); if (!value || typeof value !== 'object') return value; const proto = Object.getPrototypeOf(value); if (proto !== Object.prototype && proto !== null) return value; return Object.fromEntries(Object.entries(value).filter(([key]) => { if (!credentialKey(key)) return true; removed.add(key); return false; }).map(([key, v]) => [key, withoutCredentialFields(v, removed)])); } /** What a write records of its request, with no credential in it on any branch (ADR 0025): the body (JSON, form text, * multipart), the declared query and the GraphQL variables lose their credential fields, and a header that carries one * is not recorded. A write whose body, query or a header lost a field names it in `withheld`, so a deploy, which * sends the recorded request again, refuses it rather than sending it without (derived-real.ts performOf). */ function recordedInput(m: DerivedManifest, call: DerivedCall, merged: Record): Record { const id = call.operation.id; const sent = sentOf.get(call); const activity = call.request.headers.get('x-volter-world-activity') === 'provisioning' ? { activity: 'provisioning' } : {}; const door = m.doors?.find(d => d.id === id); const body = sent?.body ?? merged; const safeBody = door?.redactBody?.length && body && typeof body === 'object' && !Array.isArray(body) ? Object.fromEntries(Object.entries(body).filter(([key]) => !door.redactBody!.includes(key))) : body; const withheld = new Set(); // (a header a manifest names that carries a credential is named too: a deploy would otherwise send the write without it) const headers = (sentHeaders: Record): Record => Object.fromEntries(Object.entries(sentHeaders).filter(([h]) => { if (!credentialHeader(h)) return true; withheld.add(`header:${h.toLowerCase()}`); return false; })); const asSent = sent ? { ...activity, path: sent.path, query: withoutCredentials(sent.query, '', withheld) as Record, body: withoutCredentials(safeBody, sent.type ?? '', withheld), headers: headers(sent.headers), ...(sent.lane ? { lane: sent.lane } : {}), ...(sent.requestId ? { requestId: sent.requestId } : {}), ...(sent.type ? { contentType: sent.type } : {}) } : { ...activity, path: call.params, body: withoutCredentials(safeBody, '', withheld) }; const named = (): { withheld?: string[] } => (withheld.size ? { withheld: [...withheld].sort() } : {}); if (id === 'graphql') { const b = (sent?.body ?? {}) as { query?: unknown; variables?: unknown; operationName?: unknown }; const variables = withoutCredentials(b.variables ?? {}, '', withheld); return { ...activity, graphql: { query: b.query, variables, ...(b.operationName ? { operationName: b.operationName } : {}) }, ...(sent?.lane ? { lane: sent.lane } : {}), headers: headers(sent?.headers ?? {}), ...named() }; } if (id === 'clock') return { clock: true }; if (id === 'unmatched') return { gap: true, ...asSent, ...named() }; if ((m.doors ?? []).some((d) => d.id === id) || (m.screens ?? []).some((sc) => sc.id === id) || (m.accountSetup ?? []).some((a) => a.operation === id) || id === 'machine-pool' || id.startsWith('socket:')) return { door: id, ...asSent, ...named() }; return { operationId: id, ...asSent, ...named() }; } /** The scope each call is served in (serveCore, contextFor), for the contexts a write opens for its hooks. */ const scopeOfCall = new WeakMap(); /** The intact copy contextFor already keeps for core(), before a handler can consume its request. */ const requestOfCall = new WeakMap(); /** A row of the manifest's `git.push.resource` a screen writes (a client's push to a World repository) records the push * it is, which a deploy sends to the vendor as a git push (head.ts settlingEntries offers it; derived-real.ts performs * it). One an operation of the surface writes (an API commit, a ref the API creates) is that operation's, which a * deploy sends again. */ function pushedInput(m: DerivedManifest, resource: string, fields: Record, input: Record, root: string | undefined): Record { const push = m.git?.push; if (!push || push.resource !== resource || typeof input.door !== 'string') return input; const fill = (template: string): string => fillTemplate(template, fields); return { ...input, git: { name: gitNameOf(m, fill(push.repository), root), remote: fill(push.remote), ref: fill(push.ref), before: fill(push.before), after: fill(push.after) } }; } async function writeDetailed(m: DerivedManifest, call: DerivedCall, resource: string, id: string, fields: Record, operation: string, params: Record, root: string | undefined, occurredAt: string, checks?: StateChecks): Promise<{ body: Record; id: string; vendorData?: unknown }> { const before = stateBeforeWrite(m, resource, id, root); const prior = counted(m, resource) ? stored(m, resource, root).find((r) => r.id === id) as Record | undefined : undefined; const withFiles = async (input: Record): Promise> => { const files = input.operationId ? await keptFiles(m, call, root) : undefined; return files ? { ...input, files } : input; }; const { resource: row, result } = await applyTwinWrite( m.service, // a vendor's own move (ctx.asVendor, the clock) is the World's, as the clock's writes are: no API call a head performs inVendorMove() ? { operation, subjectType: storedType(m, resource), subjectId: id, fields, input: { clock: true }, occurredAt, actor: { kind: 'system' } } : { operation, subjectType: storedType(m, resource), subjectId: id, fields, input: pushedInput(m, resource, fields, await withFiles(recordedInput(m, call, params)), root), occurredAt, actor: { kind: 'agent' } }, root, ); observeStateWrite(m, result, before, root, checks); return finishWrite(m, call, resource, row, result, operation, params, root, occurredAt, prior && { ...prior }); } async function atomicWrite(m: DerivedManifest, call: DerivedCall, resource: string, decide: (snapshot: readonly TwinResource[]) => { id: string; fields: Record } | undefined, operation: string, params: Record, root: string | undefined, occurredAt: string, unchangedId?: string, checks?: StateChecks, omitInput = false, ): Promise | undefined> { const input = omitInput ? undefined : recordedInput(m, call, params); const files = input?.operationId ? await keptFiles(m, call, root) : undefined; let before: TwinResource | undefined; const committed = await applyTwinWriteAtomic(m.service, (snapshot) => { const selected = decide(snapshot); if (selected && (transitionObserver || counted(m, resource))) before = snapshot.find((r) => r.type === storedType(m, resource) && r.id === selected.id); return selected ? { kind: 'write', value: selected.id, write: { operation, subjectType: storedType(m, resource), subjectId: selected.id, fields: selected.fields, ...(input ? { input: files ? { ...input, files } : input } : {}), occurredAt, actor: { kind: 'agent' as const, ...(m.identity ? { id: m.identity(call.request.headers.get('authorization'), root) } : {}) }, } } : { kind: 'skip', value: undefined }; }, root); if (!committed.result || !committed.value) { const row = unchangedId ? stored(m, resource, root).find((r) => r.id === unchangedId) : undefined; return row ? view(m, resource, row) : undefined; } observeStateWrite(m, committed.result, before, root, checks); const row = resourcesOfType(m.service, storedType(m, resource), root).find((r) => r.id === resolveSubjectId(m.service, storedType(m, resource), committed.value!, root))!; return (await finishWrite(m, call, resource, row, committed.result, operation, params, root, occurredAt, before as unknown as Record | undefined)).body; } async function finishWrite(m: DerivedManifest, call: DerivedCall, resource: string, row: TwinResource, result: { externalId?: string; vendorData?: unknown }, operation: string, params: Record, root: string | undefined, occurredAt: string, prior?: Record, ): Promise<{ body: Record; id: string; vendorData?: unknown }> { await keepCounts(m, call, resource, row as unknown as Record, params, root, occurredAt, prior); const body = view(m, resource, row); // the write's own context for its hooks, in the scope the call was served in (a walk's application answers, a tenant, // the managed database), at the write's moment const request = requestOfCall.get(call) ?? call.request; const context = (): Promise => contextFor(m, { ...call, request: request.clone() }, { ...(scopeOfCall.get(call) ?? {}), ...(root !== undefined ? { root } : {}), clock: () => occurredAt }); if (m.onWrite) await m.onWrite({ operation, storedType: m.resources[resource]?.storedAs ?? resource, body, ...(root !== undefined ? { root } : {}), occurredAt, request: request.clone(), context }); if (m.events) { const endpoint = (kind: import('./events.ts').EndpointsDecl): import('./events.ts').EndpointsDecl => ({ ...kind, storedAs: storedType(m, kind.storedAs), ...(kind.joins ? { joins: Object.fromEntries(Object.entries(kind.joins).map(([name, join]) => [name, { ...join, storedAs: storedType(m, join.storedAs) }])) } : {}) }); const events = { ...m.events, ...(m.events.store ? { store: storedType(m, m.events.store) } : {}), endpoints: 'storedAs' in m.events.endpoints ? endpoint(m.events.endpoints) : m.events.endpoints.map(endpoint) }; const write = { operation, storedType: m.resources[resource]?.storedAs ?? resource, body, ...(root !== undefined ? { root } : {}), occurredAt, request: request.clone() }; await deliverEvents(m.service, events, write, async (type) => (events.render ? events.render(await context(), write, type) : body), undefined, events.values ? async (type) => events.values!(await context(), write, type) : undefined, scopeOfCall.get(call)?.application, m.vendor); } if (m.sockets?.length) socketWrite(m.service, root, { operation, storedType: m.resources[resource]?.storedAs ?? resource, body, ...(root !== undefined ? { root } : {}), occurredAt, request: request.clone() }); // a read held until the World writes (held-reads.ts) hears it heldReadsWrite(m.service, root, storedType(m, resource)); // the subject's id as it stands after the write: the vendor's, when a live head minted one return { body, id: result.externalId ?? row.id, ...(result.vendorData !== undefined ? { vendorData: result.vendorData } : {}) }; } /** The declared counts a written subject is a child in (a resource's `counts`), each kept on its parent: written when * the count moved, through the write path, so the parent's history says when. */ async function keepCounts(m: DerivedManifest, call: DerivedCall, resource: string, row: Record, params: Record, root: string | undefined, occurredAt: string, prior?: Record): Promise { for (const [parent, decl] of Object.entries(m.resources)) { for (const [field, c] of Object.entries(decl.counts ?? {})) { if (storedType(m, c.of) !== storedType(m, resource)) continue; // the parent the subject is under now, and the one it left when the write moved it: both counts changed const pids = new Set([parentField(row, c.by), prior === undefined ? undefined : parentField(prior, c.by)].filter((v) => v !== undefined && v !== null).map(String)); for (const pid of pids) { const held = stored(m, parent, root).find((r) => String(c.parentKey ? ownFields(r)[c.parentKey] : r.id) === pid) as Record | undefined; if (!held) continue; const n = stored(m, c.of, root).filter((r) => { const x = r as Record; return String(parentField(x, c.by)) === pid && (c.present === undefined || (x[c.present] !== undefined && x[c.present] !== null)) && (c.absent === undefined || parentField(ownFields(r), c.absent) === undefined || parentField(ownFields(r), c.absent) === null) && Object.entries(c.unless ?? {}).every(([key, value]) => ownFields(r)[key] !== value); }).length + (c.plus ?? 0); if (held[field] !== n) await writeDetailed(m, call, parent, String(held.id), { [field]: n }, `${storedType(m, parent)}.counted`, params, root, occurredAt); } } } } /** Whether any resource counts this one (`counts`): only then does a write read the subject as it stood, for the parent * it may leave. */ const counted = (m: DerivedManifest, resource: string): boolean => Object.values(m.resources).some((d) => Object.values(d.counts ?? {}).some((c) => storedType(m, c.of) === storedType(m, resource))); /** An answer in the vendor's success envelope, under the operation's key, when the vendor has one. */ function envelope(m: DerivedManifest, op: DerivedOperation, body: Record): Record { return m.success && op.answers?.key ? { ...m.success, [op.answers.key]: body } : body; } const encodeOffset = (o: number): string => btoa(JSON.stringify({ o })); function decodeOffset(cursor: unknown): number { if (typeof cursor !== 'string' || !cursor) return 0; try { const o = (parseExactJson(atob(cursor)) as { o?: unknown }).o; return typeof o === 'number' && o >= 0 ? o : 0; } catch { return 0; } } // ── state ──────────────────────────────────────────────────────────────────────────────────── /** What a coverage measurement sees of a pack's declared state logic: each move a request made and each refusal a * guard gave, by the transition that decided it. Nothing is observed unless a measurement installs an observer * (`twin-standard coverage`); serving never depends on it. */ export type TransitionEntry = { action: TwinAction; field: string; actor: Actor }; export type TransitionObserver = (decl: StateField, transition: Transition, outcome: 'moved' | 'refused', from: string, entry?: TransitionEntry) => void; let transitionObserver: TransitionObserver | undefined; export function observeTransitions(observer: TransitionObserver | undefined): void { transitionObserver = observer; } type StateCheck = { transition: Transition; operation: string; from: string; to: string; actor: Actor }; type StateChecks = Map; const stateCheckKey = (type: string, field: string): string => JSON.stringify([type, field]); const stateValue = (row: Record, field: string): unknown => field.split('.').reduce((value, part) => value && typeof value === 'object' ? (value as Record)[part] : undefined, row); function stateBeforeWrite(m: DerivedManifest, resource: string, id: string, root?: string): TwinResource | undefined { if (!transitionObserver) return undefined; const type = storedType(m, resource); const key = resolveSubjectId(m.service, type, id, root); return resourcesOfType(m.service, type, root).find((row) => row.id === key); } /** Observe the committed entry, not a legality probe's display id. Only a move the machine checks * for this entry's actual states, operation and actor is reported; no serving depends on measurement. */ function observeStateWrite(m: DerivedManifest, result: { actionId: string; status: 'performed' | 'replayed' }, before: TwinResource | undefined, root?: string, checks?: StateChecks): void { if (!transitionObserver) return; const action = listActions(m.service, root).find((a) => a.id === result.actionId); if (!action?.fields) return; const prior = before ? ownFields(before) : undefined; const next = { ...prior, ...action.fields }; const decisions = new Map(); for (const [resource, decl] of Object.entries(m.resources)) { if ((decl.storedAs ?? resource) !== action.subject.type) continue; for (const [field, machine] of Object.entries(decl.state ?? {})) { if (!(field.split('.')[0]! in action.fields)) continue; const key = stateCheckKey(action.subject.type, field); // Aliases of one stored field use the same consumed evidence on this one entry. if (!decisions.has(key)) { decisions.set(key, checks?.get(key) ?? []); checks?.delete(key); } if (result.status === 'replayed') continue; const current = prior ? stateValue(prior, field) : undefined, target = stateOf(machine, stateValue(next, field)); const from = stateOf(machine, current); const proof = decisions.get(key)!.find((c) => machine.transitions.includes(c.transition) && c.from === from && c.to === target); // Initial-state and same-state moves still need an explicit check and a committed field write. if ((!prior || from === target) && !proof) continue; const actor = proof?.actor ?? (action.actor?.kind === 'system' || action.input?.clock === true ? 'vendor' : 'api'); const operation = typeof action.input?.operationId === 'string' ? action.input.operationId : proof?.operation ?? (action.input?.clock === true ? 'clock' : action.operation ?? ''); transitionFor(field, machine, operation, current, target, action.subject.id, actor, { action, field, actor }); } } } /** The transition a request asks for on one state field, or the vendor's refusal when none applies. */ /** What a declared machine says to one move: the transition that allows it, or the refusal it gives (and * nothing when it declares neither). The derived core and `legal` ask it; so does an engine that is not * HTTP-shaped (a line protocol's session), so one machine rules every wire. */ export function transitionFor(field: string, decl: StateField, operationId: string, current: unknown, requested: unknown, id?: string, actor: Actor = 'api', entry?: TransitionEntry): { move?: Transition; refusal?: ErrorSpec } { const now = stateOf(decl, current); const candidates = decl.transitions.filter((t) => (t.actor ?? 'api') === actor && (t.operation ? t.operation === operationId : true) && (requested === undefined || (t.to ?? now) === String(requested) || (t.to === undefined && t.refusal !== undefined))); const move = candidates.find((t) => !(t.to === undefined && t.refusal !== undefined) && (t.from === '*' || t.from.includes(now))); if (move) { transitionObserver?.(decl, move, 'moved', now, entry); return { move }; } const refused = candidates.find((t) => t.refusals?.[now]) ?? candidates.find((t) => t.refusal && (t.to !== undefined || t.from === '*' || t.from.includes(now))); const r = refused?.refusals?.[now] ?? refused?.refusal; if (refused && r) transitionObserver?.(decl, refused, 'refused', now, entry); if (r) return { refusal: { status: r.status, message: String(fill(r.message, { from: current, to: refused!.to ?? now, field, id: id ?? '' })), ...(r.code ? { code: r.code } : {}) } }; return {}; } // ── the core ───────────────────────────────────────────────────────────────────────────────── export type CoreOutcome = { served: Response } | { unmodeled: string }; // ALIAS-AWARE LOOKUP AT THE REQUEST BOUNDARY (architecture.md): after an adoption a caller may still name a subject by // its local id; a declared reference in the call's params is resolved through the alias map once, here, where the // params are parsed, so a handler's lookup (`ctx.row`) and the write both see the adopted id. The map is read only // for a pack that declares references, and once per state of the parent side. An idempotency key's request hash is // taken over the bytes as sent, so the same key sent once with the local id and once with the adopted one is two // requests. const aliasMemos = new WeakMap }>>(); function aliasesNow(service: string, root?: string): Map { const store = getActiveWorldStore(); const memos = aliasMemos.get(store) ?? aliasMemos.set(store, new Map()).get(store)!; const key = `${service}\u0000${root ?? ''}`; // aliases come from the parent side alone: a local write (the branch log) leaves them as they were const stamp = parentStamp(service, root); let held = memos.get(key); if (!held || held.stamp !== stamp) { held = { stamp, aliases: subjectAliases(service, root) }; memos.set(key, held); } return held.aliases; } /** The call with a path parameter naming the operation's subject, or its parent, by a local id moved to the adopted * id (`GET /segments/` after the segment was adopted). Only the operation's own type and its parent's are * tried, so no other parameter is touched. A vendor naming its subject in the body (Slack's `ts`) declares it as a * reference, which adoptedInCall resolves. */ function adoptedPath(m: DerivedManifest, call: DerivedCall, root?: string): DerivedCall { const resource = call.operation.resource; const decl = resource ? m.resources[resource] : undefined; if (!decl || Object.keys(call.params).length === 0) return call; const aliases = aliasesNow(m.service, root); if (aliases.size === 0) return call; const types = [storedType(m, resource!), ...(decl.parent ? [storedType(m, decl.parent.resource)] : [])]; let params = call.params; for (const [name, value] of Object.entries(call.params)) { const adopted = types.map((type) => aliases.get(`${type}:${value}`)).find((id) => id !== undefined); if (adopted !== undefined && adopted !== value) params = { ...params, [name]: adopted }; } return params === call.params ? call : { ...call, params }; } /** A call's fields with each declared reference that names an adopted subject by its local id moved to the adopted * id. A call (a handler's operation) need not say which subject type it writes, so every reference the pack declares * is tried: a field is rewritten only when its value is a local id the alias map holds for the reference's target. */ function adoptedInCall(m: DerivedManifest, fields: Record, root?: string): Record { const service = m.service, refs = packReferences(service); if (refs.length === 0) return fields; const aliases = aliasesNow(service, root); if (aliases.size === 0) return fields; let out = fields; for (const ref of refs) { const local = ref.key(out as SubjectFields); const adopted = local === undefined ? undefined : aliases.get(`${storedType(m, ref.to)}:${local}`); if (adopted !== undefined && adopted !== local) out = { ...out, ...ref.adopt(out as SubjectFields, adopted) }; } return out; } async function boundaryParams(m: DerivedManifest, call: DerivedCall, root?: string): Promise> { return adoptedInCall(m, await readParams(m, call.request, call.operation), root); } /** The refusal a subject's fields would draw from its resource's `unique` rules: another live subject (not `except`) * already holds every field of a rule, each field given. */ function conflictOf(m: DerivedManifest, resource: string, fields: Record, except: string | undefined, root: string | undefined): ErrorSpec | undefined { for (const rule of m.resources[resource]?.unique ?? []) { if (rule.fields.some((f) => fields[f] === undefined || fields[f] === null)) continue; const held = stored(m, resource, root).some((r) => r.id !== except && rule.fields.every((f) => (r as Record)[f] === fields[f])); if (held) return rule.refusal; } return undefined; } /** A subject deleted through the write path, after every subject its resource's `cascade` takes with it (depth first). */ async function removeSubject(m: DerivedManifest, call: DerivedCall, resource: string, id: string, params: Record, root: string | undefined, at: string, operation?: string): Promise { for (const child of m.resources[resource]?.cascade ?? []) { for (const row of stored(m, child.resource, root).filter((r) => parentField(r, child.field) === id)) { await removeSubject(m, call, child.resource, String(row.id), params, root, at); } } await write(m, call, resource, id, { deleted: true }, operation ?? `${storedType(m, resource)}.delete`, params, root, at); } /** Whether a key names a stored subject: its id, or one of the resource's alternate keys. */ const namedBy = (decl: ResourceDecl | undefined, row: object, key: unknown): boolean => (row as { id?: unknown }).id === key || (decl?.alternateKeys ?? []).some((f) => key !== undefined && key !== null && (row as Record)[f] === key); const isBag = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); /** One field of an update, as the resource's `update` rule merges it into what is stored. */ /** A bag with every `null` key removed, at every level (a deep merge's new branch: null removes a key "at any level"). */ const withoutNulls = (bag: Record): Record => Object.fromEntries(Object.entries(bag).filter(([, v]) => v !== null).map(([k, v]) => [k, isBag(v) ? withoutNulls(v) : v])); export function mergeField(rule: ResourceDecl['update'], prior: unknown, next: unknown): unknown { if (rule === 'deep' && isBag(next) && !isBag(prior)) return withoutNulls(next); if (rule === 'replace' || !isBag(next) || !isBag(prior)) return next; if (rule === 'deep') { const out: Record = { ...prior }; for (const [k, v] of Object.entries(next)) { if (v === null) delete out[k]; else out[k] = isBag(v) && isBag(out[k]) ? mergeField('deep', out[k], v) : v; } return out; } return Object.fromEntries(Object.entries({ ...prior, ...next }).filter(([, value]) => value !== '')); } /** A list's rows as the resource declares them arranged for this call: its field filters, its search, its order (the * `orderBy` parameter's, else `order`, else newest first); a refusal when the call orders by a field it does not take. */ function arrangeRows(m: DerivedManifest, resource: string, params: Record, input: Array>): Array> | ErrorSpec { const decl = m.resources[resource]; let rows = input; for (const f of decl?.filters ?? []) if (params[f] !== undefined) rows = rows.filter((r) => String(r[f]) === String(params[f])); const needle = decl?.search ? params[decl.search.param] : undefined; if (decl?.search && typeof needle === 'string' && needle !== '') { const q = needle.toLowerCase(); rows = rows.filter((r) => (decl.search!.exact ?? []).some((f) => String(r[f] ?? '').toLowerCase() === q) || (decl.search!.partial ?? []).some((f) => String(r[f] ?? '').toLowerCase().includes(q))); } let order: { field: string; direction: 'asc' | 'desc' } = decl?.order ?? { field: 'created', direction: 'desc' }; // a declared ordering parameter orders text by its text; without one, the order is numeric, as it always was let byText = false; if (decl?.orderBy) { const asked = params[decl.orderBy.param]; const spec = typeof asked === 'string' && asked !== '' ? asked : decl.orderBy.default; const field = spec.replace(/^[+-]/, ''); if (!decl.orderBy.fields.includes(field)) return { ...decl.orderBy.invalid, message: decl.orderBy.invalid.message.replace('{fields}', decl.orderBy.fields.join(', ')) }; order = { field, direction: spec.startsWith('-') ? 'desc' : 'asc' }; byText = true; } const indexed = rows.map((row, i) => ({ row, i })); indexed.sort((a, b) => { const x = a.row[order.field]; const y = b.row[order.field]; const byValue = !byText || typeof x === 'number' || typeof y === 'number' ? compareExactNumbers(x ?? 0, y ?? 0) : String(x ?? '').localeCompare(String(y ?? '')); // ties (two made in one instant) by the order they were written: the rows come in the tree's order, which keeps each // subject where it was first written, so this is the creation order whatever the id template (an ordered KSUID or // count, or a hash-derived uuid, hex or letters id whose text says nothing of when it was made) const d = byValue || a.i - b.i; return order.direction === 'desc' ? -d : d; }); return indexed.map((x) => x.row); } /** A page of arranged rows, answered in the manifest's list envelope with its paging (cursors, pages, offsets). */ function pageRows(m: DerivedManifest, op: DerivedOperation, call: DerivedCall, params: Record, rows: Array>, resource: string, root: string | undefined, paths: string[]): Response { const list = m.list; if (!list) return vendorError(m, m.gap ?? m.notFound); const size = list.limits?.[op.id] ?? list.limit; const asked = params[list.limit.param]; const n = asked === undefined || asked === '' ? size.default : Number(asked); const limit = Number.isFinite(n) ? Math.min(size.max, Math.max(1, Math.trunc(n))) : size.default; const after = list.after ? params[list.after] : undefined; const before = list.before ? params[list.before] : undefined; let from = 0; let to: number; if (typeof before === 'string') { const at = rows.findIndex((r) => r.id === before); to = at === -1 ? (list.unknownCursor === 'end' ? 0 : rows.length) : at; from = Math.max(0, to - limit); } else { if (typeof after === 'string') { const at = rows.findIndex((r) => r.id === after); from = at === -1 ? (list.unknownCursor === 'end' ? rows.length : 0) : at + 1; } to = from + limit; } const page = rows.slice(from, to).map((r) => expand(m, resource, r, paths.filter((p) => p.startsWith('data.')).map((p) => p.slice(5)), root)); const hasMore = typeof before === 'string' ? from > 0 : to < rows.length; const url = op.path.replace(/\{[^}]+\}/g, (p) => call.params[p.slice(1, -1)] ?? p); if (list.page) { const n = Math.max(1, Math.floor(Number(params[list.page.param]) || 1)); const slice = rows.slice((n - 1) * limit, n * limit).map((r) => expand(m, resource, r, paths.filter((p) => p.startsWith('data.')).map((p) => p.slice(5)), root)); const last = Math.max(1, Math.ceil(rows.length / limit)); const headers = new Headers(); if (list.page.link && rows.length > limit) { const at = (k: number): string => { const u = new URL(call.request.url); u.searchParams.set(list.page!.param, String(k)); return u.toString(); }; const rels = [...(n > 1 ? [`<${at(n - 1)}>; rel="prev"`] : []), ...(n < last ? [`<${at(n + 1)}>; rel="next"`, `<${at(last)}>; rel="last"`] : []), ...(n > 1 ? [`<${at(1)}>; rel="first"`] : [])]; if (rels.length) headers.set('link', rels.join(', ')); } // `{total_count}` the count before paging, `{max_page}` the number of pages (none for an empty list: Polar's pagination) return Response.json(fill(list.envelope, { data: slice, next_cursor: null, key: op.answers?.key ?? 'data', total_count: rows.length, max_page: Math.ceil(rows.length / limit) }), { headers }); } if (list.offset) { const skip = Math.max(0, Math.trunc(Number(params[list.offset.param]) || 0)); const slice = rows.slice(skip, skip + limit); const key = op.answers?.key ?? 'data'; return Response.json({ ...(m.success ?? {}), [key]: slice, ...(fill(list.envelopes?.[op.id] ?? list.envelope, { data: slice, total_count: rows.length, key }) as object) }); } if (list.cursor) { if (list.cursor.encoding === 'offset-template') { const cursor = list.cursor; const names: string[] = []; const pattern = '^' + cursor.template.split(/(\{offset\}|\{reverse\})/).map((part) => { if (part === '{offset}' || part === '{reverse}') { names.push(part.slice(1, -1)); return '(\\d+)'; } return escapeRe(part); }).join('') + '$'; if (names.filter((name) => name === 'offset').length !== 1 || names.filter((name) => name === 'reverse').length !== 1) throw new Error('list: offset-template must name offset and reverse once'); const value = params[cursor.param]; const hit = typeof value === 'string' ? new RegExp(pattern).exec(value) : undefined; if (value !== undefined && !hit) return vendorError(m, { status: 400, message: 'Invalid cursor' }); const decoded = Object.fromEntries(names.map((name, i) => [name, Number(hit?.[i + 1] ?? 0)])); if (!Number.isSafeInteger(decoded.offset) || ![0, 1].includes(decoded.reverse!)) return vendorError(m, { status: 400, message: 'Invalid cursor' }); const start = decoded.reverse ? Math.max(0, decoded.offset! - limit) : decoded.offset!; const slice = rows.slice(start, start + limit); const link = (offset: number, reverse: number, rel: string, available: boolean): string => { const marker = cursor.template.replace('{offset}', String(offset)).replace('{reverse}', String(reverse)); const target = new URL(call.request.url); target.searchParams.set(cursor.param, marker); return `<${target.href}>; rel="${rel}"; ${cursor.link.results}="${available}"; ${cursor.link.cursor}="${marker}"`; }; return Response.json(fill(list.envelope, { data: slice, key: op.answers?.key ?? 'data' }), { headers: { link: [link(start, 1, cursor.link.previous, start > 0), link(start + limit, 0, cursor.link.next, start + limit < rows.length)].join(', '), } }); } const start = decodeOffset(params[list.cursor.param]); const slice = rows.slice(start, start + limit); const next = start + limit < rows.length ? encodeOffset(start + limit) : ''; return Response.json({ ...(m.success ?? {}), ...(fill(list.envelope, { data: slice, next_cursor: next, key: op.answers?.key ?? 'data' }) as object), ...(op.answers?.key ? { [op.answers.key]: slice } : {}) }); } return Response.json(fill(list.envelope, { data: page, has_more: hasMore, url, first_id: page[0]?.id ?? null, last_id: page.at(-1)?.id ?? null })); } /** Serve one operation from the manifest, or say why the core cannot. */ /** A setting's fields as the vendor answers them: its own, without the kernel's bookkeeping (a `_` field the resource * does not declare the vendor's own, as view() and render() keep it) or the parent it is kept under (a setting answers * its values, not an identity). */ function settingFields(own: Record, parentField?: string, vendorUnderscored: readonly string[] = []): Record { return Object.fromEntries(Object.entries(own).filter(([k]) => (!k.startsWith('_') || vendorUnderscored.includes(k)) && k !== 'deleted' && k !== parentField)); } function settingView(m: DerivedManifest, resource: string, hit: TwinResource): Record { // ownFields: the kernel's id, type and updatedAt gone, a vendor's own of those names restored return settingFields(ownFields(hit), m.resources[resource]?.parent?.field, m.resources[resource]?.vendorUnderscored); } /** How a request reads a resource's rows: `(resource, opts)`, the rows `stored` gives. */ type RowReader = (resource: string, opts?: { withDeleted?: boolean }) => TwinResource[]; /** An operation's rows as the vendor answers them at `at`. Where the operation is one the vendor documents as eventually * consistent and the World's scenario places a `lag` on it, each resource it reads (`eventuallyConsistent.reads`, else * all but the kernel's bookkeeping) is read from the World as it stood the lag's `by` before `at` (readTreeAsOf, the fold * a branch cut at that instant holds): a subject made since is not yet there, one changed since answers its older * fields, one removed since is still there, a configuration set since is not yet in force. Nothing is written; what the * lag hid is noted on the request's journal line, once per resource. Every other read is the World as it stands. */ function lagged(m: DerivedManifest, op: DerivedOperation, root: string | undefined, at: string, recording: boolean): RowReader { const current: RowReader = (resource, opts) => stored(m, resource, root, opts); const lag = m.eventuallyConsistent?.operations.includes(op.id) ? listLag({ vendor: m.vendor, service: m.service, root, at }, op.id) : undefined; if (!lag) return current; const reads = m.eventuallyConsistent!.reads?.[op.id]; const asOf = new Date(Date.parse(at) - durationMs(lag.by!)).toISOString(); let then: TwinResource[] | undefined; const noted = new Set(); const own = (r: TwinResource): string => JSON.stringify(ownFields(r)); return (resource, opts) => { if (resource.startsWith('_') || (reads !== undefined && !reads.includes(resource))) return current(resource, opts); then ??= readTreeAsOf(m.service, asOf, root); const rows = stored(m, resource, root, { ...opts, from: then }); if (recording && !noted.has(resource)) { noted.add(resource); const was = new Map(stored(m, resource, root, { from: then }).map((r) => [r.id, r])); const is = new Map(current(resource).map((r) => [r.id, r])); const unseen = [...is.keys()].filter((id) => !was.has(id)); const older = [...is].filter(([id, r]) => was.has(id) && own(was.get(id)!) !== own(r)).map(([id]) => id); const removed = [...was.keys()].filter((id) => !is.has(id)); if (unseen.length || older.length || removed.length) noteTwinRequest({ layer: lag.layer, kind: lag.kind, entry: lag.index, operation: op.id, resource, asOf, ...(unseen.length ? { unseen } : {}), ...(older.length ? { older } : {}), ...(removed.length ? { removed } : {}) }); } return rows; }; } /** A resource's rows as the vendor answers them at `at`: each field it declares `pending` answered as its pending value * until its `for` has passed since the subject was made or since a write set one of its `on` fields (the subject's * entries in the log). The stored value is never changed: World time alone fills the field. */ function pendingAt(m: DerivedManifest, resource: string, root: string | undefined, at: string): (r: TwinResource) => TwinResource { const pending = Object.entries(m.resources[resource]?.pending ?? {}); if (!pending.length) return (r) => r; const now = Date.parse(at); // the subject's entries, read once per stored type (a handler's raw row names its type without the account it is kept under) const byType = new Map>>(); const historyOf = (r: TwinResource): Array<{ at: number; fields: string[] }> => { const type = r.type.includes(TENANT_TYPE) ? r.type : storedType(m, resource); let entries = byType.get(type); if (!entries) { entries = new Map(); for (const e of subjectHistory(m.service, { type }, root)) { const id = e.aliasOf ?? e.subject.id; const list = entries.get(id) ?? []; list.push({ at: Date.parse(e.occurredAt), fields: Object.keys(e.fields ?? {}) }); entries.set(id, list); if (e.aliasOf !== undefined && e.subject.id !== e.aliasOf) entries.set(e.subject.id, list); } byType.set(type, entries); } return entries.get(r.id) ?? []; }; return (r) => { let shown: TwinResource | undefined; for (const [field, decl] of pending) { const history = historyOf(r); const on = decl.on ?? [field]; const since = history.reduce((latest, e, i) => (i === 0 || e.fields.some((f) => on.includes(f)) ? Math.max(latest, e.at) : latest), -Infinity); if (!(now < since + durationMs(decl.for))) continue; shown ??= copyResource(r); (shown as Record)[field] = decl.value; } return shown ?? r; }; } export async function serveCore(m: DerivedManifest, call: DerivedCall, scope: CoreScope = {}): Promise { const root = scope.root; const at = (scope.clock ?? worldNow)(); const op: DerivedOperation = call.operation; const resource = op.resource; const decl = resource ? m.resources[resource] : undefined; if (!resource || !decl) return { unmodeled: `no manifest entry for resource ${resource ?? '(none)'}` }; call = adoptedPath(m, call, root); scopeOfCall.set(call, scope); // the body is read from a copy, so the call's own request is still unread for the write hook's context const params = await boundaryParams(m, { ...call, request: call.request.clone() }, root); const idParam = subjectOf(m, resource, call); const parent = parentOfCall(decl, call); const parentId = parent ? parentValue(parent, call.params) : undefined; // the caller's tenant, when the vendor has tenancy and the resource is not shared by every tenant const tenantField = m.tenant?.storage !== 'namespaced' && m.tenant && !decl.shared ? m.tenant.field : undefined; const tenant = tenantField && scope.tenant ? await scope.tenant(await contextFor(m, { ...call, request: call.request.clone() }, scope)) : undefined; if (tenantField && tenant === undefined) return { unmodeled: `the caller names no tenant (semantics/tenant.ts) for ${resource}` }; const orphan = missingParent(m, resource, call, root, tenant); if (orphan) return { served: orphan }; const underParent = (r: TwinResource): boolean => (!parent || (r as Record)[parent.field] === parentId) && (!tenantField || (r as Record)[tenantField] === tenant); const paths = expandPaths(m, params); // the vendor's success status from its spec: 201 for most creates, 204 with no body where it answers nothing const status = op.successStatus ?? 200; const answer = (body: Record) => ({ served: status === 204 ? new Response(null, { status }) : Response.json(envelope(m, op, expand(m, resource, body, paths, root)), { status }), }); const control = new Set([m.expandParam, m.list?.limit.param, m.list?.after, m.list?.before, m.list?.offset?.param, m.list?.page?.param, m.list?.cursor?.param].filter(Boolean) as string[]); const data = Object.fromEntries(Object.entries(params).filter(([k]) => !control.has(k) && k !== 'id')); // a strict vendor refuses a body it does not declare before the core writes it (body.strict, as ctx.fields) if (m.body.strict && (op.class === 'create' || op.class === 'update')) { const queried = new Set((op.query ?? []).map((q) => q.name)); const checked = strictFields(m, op, Object.fromEntries(Object.entries(data).filter(([k]) => !queried.has(k) && !(k in call.params)))); if ('refused' in checked) return { served: checked.refused }; } switch (op.class) { case 'create': { for (const field of Object.keys(decl.state ?? {})) if (field in data) return { unmodeled: `create sets state field ${field}` }; if (decl.key) return { unmodeled: 'a create under a composite key is a handler' }; const provided = m.ids.acceptProvided && typeof params.id === 'string' && params.id ? params.id : undefined; const id = provided ?? mintId(m, resource, root, at); const assigned = Object.fromEntries(Object.entries(decl.assigned ?? {}).map(([k, rule]) => [k, applyRule(m, rule, id, data, at)])); const initial = Object.fromEntries(Object.entries(decl.state ?? {}).map(([k, s]) => [k, s.initial])); const under: Record = { ...(parent ? { [parent.field]: parentId } : {}), ...(tenantField ? { [tenantField]: tenant } : {}) }; if (decl.number) { const siblings = stored(m, resource, root, { withDeleted: true }).filter(underParent); const next = siblings.reduce((n, r) => { const value = String((r as Record)[decl.number!.field] ?? '0'); const held = /^-?\d+$/.test(value) ? BigInt(value) : 0n; return held > n ? held : n; }, 0n) + 1n; (under as Record)[decl.number.field] = exactInteger(String(next)); } const made = { ...assigned, ...initial, ...under, ...data }; const clash = conflictOf(m, resource, made, undefined, root); if (clash) return { served: vendorError(m, clash) }; return answer(await write(m, call, resource, id, made, `${storedType(m, resource)}.create`, params, root, at)); } case 'retrieve': { const settled = lagged(m, op, root, at, !(scope.readOnly === true || isReadOnlyRequest(call.request))); const found = idParam ? settled(resource).find((r) => namedBy(decl, r, idParam) && underParent(r)) : undefined; const hit = found && pendingAt(m, resource, root, at)(found); // a setting never written answers its defaults; one written answers them under what was written if (decl.setting) return answer({ ...decl.setting.defaults, ...(hit ? settingView(m, resource, hit) : {}) }); return hit ? answer(view(m, resource, hit)) : { served: notFound(m, resource, String(idParam), Object.keys(call.params).at(-1)) }; } case 'list': { if (!m.list) return { unmodeled: 'no manifest list configuration' }; const settled = lagged(m, op, root, at, !(scope.readOnly === true || isReadOnlyRequest(call.request))); const rows = settled(resource).filter(underParent).map(pendingAt(m, resource, root, at)).map((r) => view(m, resource, r)); const arranged = arrangeRows(m, resource, params, rows); if (!Array.isArray(arranged)) return { served: vendorError(m, arranged) }; return { served: pageRows(m, op, call, params, arranged, resource, root, paths) }; } case 'update': case 'action': { const hit = idParam ? stored(m, resource, root).find((r) => namedBy(decl, r, idParam) && underParent(r)) : undefined; // a setting's update merges what is given over what it holds (its defaults until first written), making it if (decl.setting && op.class === 'update' && idParam) { const current = { ...decl.setting.defaults, ...(hit ? settingView(m, resource, hit) : {}) }; const merged: Record = {}; for (const [k, v] of Object.entries(data)) merged[k] = mergeField(decl.update, current[k], v); const under = { ...(parent ? { [parent.field]: parentId } : {}), ...(tenantField ? { [tenantField]: tenant } : {}) }; await write(m, call, resource, hit?.id ?? String(idParam), { ...under, ...merged }, `${storedType(m, resource)}.update`, params, root, at); // a setting whose update the spec documents with no content answers none (a specification that omits a body // elsewhere is not trusted this far: only a setting's update reads it) if (op.emptySuccess) return { served: new Response(null, { status }) }; return answer({ ...current, ...merged }); } if (!hit) return { served: notFound(m, resource, String(idParam), Object.keys(call.params).at(-1)) }; const current = view(m, resource, hit); const changes: Record = { ...(op.class === 'update' ? data : {}) }; let moved = false; const stateChecks: StateChecks = new Map(); for (const [field, sdecl] of Object.entries(decl.state ?? {})) { const requested = op.class === 'update' ? data[field] : undefined; if (op.class === 'update' && requested === undefined) continue; if (op.class === 'update' && sdecl.unchanged === 'allow' && stateOf(sdecl, current[field]) === stateOf(sdecl, requested)) { changes[field] = requested; continue; } const { move, refusal } = transitionFor(field, sdecl, op.id, current[field], requested, hit.id); if (refusal) return { served: vendorError(m, refusal) }; if (!move) { if (op.class === 'update') return { unmodeled: `no declared transition of ${field} to ${String(requested)} by ${op.id}` }; continue; } if (transitionObserver) stateChecks.set(stateCheckKey(storedType(m, resource), field), [{ transition: move, operation: op.id, from: stateOf(sdecl, current[field]), to: move.to ?? stateOf(sdecl, current[field]), actor: 'api' }]); const stored = storedState(sdecl, move.to); if (stored !== undefined) changes[field] = stored; for (const [k, rule] of Object.entries(move.effects ?? {})) changes[k] = applyRule(m, rule, hit.id, { ...current, ...changes }, at); moved = true; } if (op.class === 'action' && !moved) return { unmodeled: `action ${op.id} declares no transition` }; const merged: Record = {}; for (const [k, v] of Object.entries(changes)) merged[k] = mergeField(decl.update, current[k], v); const clash = conflictOf(m, resource, { ...current, ...merged }, hit.id, root); if (clash) return { served: vendorError(m, clash) }; return answer(await write(m, call, resource, hit.id, merged, `${storedType(m, resource)}.${op.class === 'update' ? 'update' : op.id}`, params, root, at, stateChecks)); } case 'delete': { const hit = idParam ? stored(m, resource, root).find((r) => namedBy(decl, r, idParam) && underParent(r)) : undefined; if (!hit) return { served: notFound(m, resource, String(idParam), Object.keys(call.params).at(-1)) }; await removeSubject(m, call, resource, hit.id, params, root, at); const shape = decl.deleted !== undefined ? decl.deleted : m.deleted; return { served: status === 204 || shape === null ? new Response(null, { status: 204 }) : Response.json(fill(shape, { id: hit.id, object: current(hit) }), { status }) }; } default: return { unmodeled: `class ${op.class} is not served by the core` }; } } function current(r: TwinResource): unknown { return render(r).object ?? r.type; } /** Server-sent events in the manifest's framing. The events are known when the answer starts: the * twin decides deterministically, so the stream carries a decided answer, never a model's. */ export function sse(m: DerivedManifest, events: Array<{ event?: string; data: unknown }>, operationId?: string): Response { const enc = new TextEncoder(); const framing = (operationId && m.streamFor?.[operationId]) || m.sse; const frame = (e: { event?: string; data: unknown }): string => `${framing?.named && e.event ? `event: ${e.event}\n` : ''}data: ${JSON.stringify(e.data)}\n\n`; const body = new ReadableStream({ start(controller) { for (const e of events) controller.enqueue(enc.encode(frame(e))); if (framing?.done) controller.enqueue(enc.encode(`data: ${framing.done}\n\n`)); controller.close(); }, }); return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache' } }); } // ── semantics ──────────────────────────────────────────────────────────────────────────────── /** What a semantics handler works with: the request's parameters, the tree through the pack's view, * the write path (which runs the manifest's write hook), and the declared machine. A handler never * imports the kernel; this is its whole interface. */ export type SemanticsContext = { call: DerivedCall; params: Record; /** This unit's generated discriminator requirements; an unknown resource is a derivation defect. */ variants(resource: string): NonNullable[number]['variants']; /** the last path parameter: the subject an item operation names */ id: string | undefined; /** the request body as the vendor reads it (an array, where the vendor takes one), and its text */ body: unknown; text: string; root: string | undefined; occurredAt: string; /** The twin's own base URL as this request reached it (its links and redirects to its own pages carry it). */ publicBase: string; /** What the World's scenario decided for this turn (a model vendor's answer: the handler matched, or the miss), on an * operation the pack's `semantics/scenario.ts` names; undefined elsewhere, or when the World carries no scenario. */ scenario: ScenarioDecision | undefined; /** The vendor's judgement at one of its decision points (a fraud score, an identity check, deliverability), for the * subject it is keyed to: what the World's scenario decided, else `byDefault`, the vendor's normal outcome; recorded in * the twin's log either way (architecture, "Scenarios"). The handler follows it with what the vendor does next. */ decide(point: string, subject: string, byDefault: T): Promise; /** A fault the World's scenario placed at a point of the pack's own (one item of a batch) for `subject`, recorded as * landed; undefined when none is placed. */ fault(point: string, subject: string): Promise<{ kind: string; status?: number; message?: string; errorType?: string } | undefined>; /** A World fact (an exchange rate, a holiday, a place) as it stands at this request's World time, which the twin answers * with in its own shape; undefined when the World holds none. A read of the World's facts, as any read is: it writes * nothing, and the World's facts and clock give it again. */ fact(kind: string, key: string): Promise; /** A message the vendor sends the application's server and decides by its answer, waited on for at most `within` * milliseconds (a real-time authorization request): its status and body, or why there was none. */ ask(url: string, init: RequestInit, within: number): Promise; /** A git repository of the World, by the pack's name for it (the git plane, world-core git/): its objects in the * World's repository-scoped content-addressed object store, its refs in the World's store. Served over smart HTTP * (`git.serveSmartHttp`), read and written through the library's codecs. */ git(name: string): { store: GitObjectStore; refs: GitRefs }; /** The git repository of a row of the manifest's `git.repository.resource`, under the one name it keeps through * adoption (`gitNameOf`). */ gitRepository(row: Record): { store: GitObjectStore; refs: GitRefs }; /** A value the World set for its application (world-env.ts): what the app was given and the vendor must agree with (a * webhook signing secret the app verifies with), never the caller's own shell; undefined when the World sets none. */ worldEnv(name: string): string | undefined; /** Runs `fn` as the vendor's own move, not the caller's: what time makes due (a renewal a read catches up) is * recorded with no caller, wherever a handler reaches it. */ asVendor(fn: () => Promise): Promise; /** A mail the vendor hands on, over SMTP to the World's twin that receives each recipient's domain (smtp.ts, ADR 0032 * §3): each recipient's reply, `250` delivered and `5xx` refused; a domain no twin receives is refused by the kernel. */ mail(mail: Mail): Promise; now(): unknown; /** Render a stored row or vendor view using its resource declaration, retaining the stored subject id fallback. */ render(row: Record, resource?: string): Record; get(resource: string, id: string): Record | undefined; /** One credential subject in a manifest-declared owner's World store. Ambiguous stores refuse the read. */ ownerRow(owner: string, resource: string, id: string): Record | undefined; rows(resource: string): Array>; mint(resource: string): string; /** An id the vendor issues for what it does not keep (a completion's, a request's): minted, and its subject recorded, * so the next is another; a read-only request mints without recording. The resource is a declared bookkeeping type. */ issue(resource: string): Promise; /** The vendor's open sessions of one of its sockets in this World (a request answered by a session: sockets.ts). */ sockets(id: string): SocketSession[]; /** The World's recordings of what was broadcast to this twin (live media, live/access.ts): a recording's facts, and its * playlists, init and segments answered as the vendor's media host answers them. */ live: LiveAccess; /** Hold this read until the World writes (held-reads.ts: HTTP long polling): true when a write of one of the named * resources lands in this World, false when `ms` pass or the client hangs up; at once false in a read-only World. */ awaitWrite(resources: ReadonlyArray, ms: number): Promise; /** Observe a condition until it holds or the caller's timeout/cancellation, waking on writes and pollMs. */ awaitCondition(resources: ReadonlyArray, ms: number, pollMs: number, condition: () => Promise): Promise; /** A secret for `label` (an app's client secret, a store's read token): an HMAC under a seed the World makes once, at * random, and keeps as bookkeeping no door answers. The same label gives the same secret for the World's whole life, * and no one can compute it from ids the World shows, as they can a value derived from them alone. */ secret(label: string): Promise; /** The one door a key or a generated secret is issued through (ADR 0029, "Keys and generated secrets are retained World * state"): an API key, a webhook signing secret, a bot token, each its own `purpose`, for `account` (default: the * account the credential door selects, `ctx.account()`), in the vendor's `format`. Its value is a pure function of the * World's seed identity, the account and the purpose, nothing else (no minted id, no time, no request), so a reset, at * whatever instant, issues the same value and an application holding it stays accepted. The issuance is recorded * (`_world_issued_key`, at `/`, holding only the value's SHA-256), so `issuedKey` accepts it and * nothing else; a read-only request issues without recording. It answers the purpose's live generation: once * `revokeKey` revoked one, the next is issued (its value drawn under `#`), so a rotation is a * revocation and the same call again, and the revoked value stays refused. */ issueKey(purpose: string, format: KeyFormat, account?: string): Promise; /** An id that names an issued key or appears in it or beside it (a dashboard's key id, a DSN's ids, Slack's * `xapp-`, Telegram's `:`, a snowflake, a project id), in the vendor's id `format`: drawn from the same * three inputs as `issueKey` under its own label, of the purpose's live generation, as stable, and revealing nothing * of the key. Not recorded. */ issueKeyId(purpose: string, format: KeyFormat, account?: string): Promise; /** The issuance `value` was issued by in this World, when it is its purpose's live generation: its account and purpose. */ issuedKey(value: string): { account: string; purpose: string } | undefined; /** Revoke the live generation of `purpose` for `account` (a key deleted, disabled or expired): `issuedKey` refuses its * value, and the next `issueKey` of the purpose issues its next generation. */ revokeKey(purpose: string, account?: string): Promise; /** Select an account at a pack's credential door. Packs retain their own vendor account/key semantics. */ account(field?: string): Promise; /** The selected organization's label and people from the World's organization registry. */ organization(): Promise; /** The selected deployment, or an empty string for the organization's own level. */ deployment(): string; /** A vendor-safe label; retained links keep identity independent of names. */ vendorName(label: string, rule: VendorNameRule, options?: { suffixed?: boolean; identity?: string }): string; /** Retain the native customer tenant for the selected organization. */ tenant(resource: string, make: (organization: WorldOrganization) => Promise): Promise>; /** Retain one native resource of this kind for the selected organization and deployment. */ deploymentObject(kind: string, resource: string, make: (deployment: string) => Promise): Promise>; /** Reconstruct a live native key, replacing its link when the vendor's reader refuses it. */ accountKey(purpose: string, resource: string, key: { make: () => Promise; read: (row: Record) => Promise }): Promise<{ id: string; secret: string }>; /** The World's machine pool (machines.ts), as the pack's `machine-pool` door enrolled it; `none` when none was. */ machines: MachinePool; /** A signing key pair for `label` (an issuer's ID tokens, a provider's JWTs, a CA's or a log's key), PEM: RSA 2048 * (the default) or Ed25519, made once, at random, when the label is first asked for, and kept as bookkeeping no door * answers, so what it signs verifies against the World's published key (ctx.crypto.jwks of the public half) and no * one can forge it from anything the pack or the World shows, as they can with a key written in the pack. */ signingKey(label: string, alg?: 'RS256' | 'Ed25519'): Promise<{ privatePem: string; publicPem: string }>; /** The signing key for `label` when the World has made it (`signingKey`), else undefined: for code that signs where it * cannot wait (a cookie's token, read everywhere), after a front made the key before anything is answered. */ heldSigningKey(label: string, alg?: 'RS256' | 'Ed25519'): { privatePem: string; publicPem: string } | undefined; /** Allocate a stored occurrence and append its fields under one action lock. The optional field factory is pure. */ create(resource: string, fields: Record | ((id: string) => Record), operation: string): Promise>; /** Create under declared unique keys and the action lock; a collision returns the existing own-field view without a write. */ createUnique(resource: string, fields: Record | ((id: string) => Record), operation: string, options?: { input?: 'omit'; id?: string }): Promise<{ created: boolean; row: Record }>; /** Decide an update from the current live stored row under the action lock; undefined leaves it unchanged. */ change(resource: string, id: string, decide: (row: Record) => Record | undefined, operation: string, options?: { input: 'omit' }): Promise | undefined>; write(resource: string, id: string, fields: Record, operation: string): Promise>; /** * One command's writes as one group (docs/contributing/architecture.md, "A command's writes as one group"). * Inside `fn`, `write` stages its write and answers the row as it will stand; `row` and `rowsRaw` read the tree with * the staged writes folded over it, as it will be once they land. When `fn` returns or throws, every staged write * lands, in order, as one append; then its value is answered or its error thrown. Every other way to write, or to * wait on a write, lands the staged writes first; any other read of the tree (`get`, `rows`, `tree`, `history`, ...) * while writes are staged is refused, never answered without them. Each write keeps its own action, id, ordinal, * moment and recorded request. Where the pack has write hooks, events, sockets or counts, a state observer is on, * a head performs, or ids are aliased, `fn` simply runs, each write landing as it is made. */ batch(fn: () => Promise): Promise; /** Add numeric deltas to an existing bookkeeping row under the kernel's atomic write seam. */ accumulate(resource: string, id: string, deltas: Record, operation: string): Promise; /** `write`, with what a live vendor answered when the head performed it */ writeDetailed(resource: string, id: string, fields: Record, operation: string): Promise<{ body: Record; id: string; vendorData?: unknown }>; /** The id a subject has now, for an id a caller may still use from before the vendor minted its own * (a branch naming a message by the ts it minted locally). */ /** The tree's type a resource's rows are kept under (the manifest's `storedAs`, else its name): what an operation on * it is named by (`issuing_card.create`), as the vendor names the events it sends. */ storedType(resource: string): string; resolve(resource: string, id: string): string; /** Answer the vendor's success envelope around several fields (`{ ok: true, ts, channel, message }`). */ ok(fields: Record): Response; /** A stored row as it is kept, bookkeeping (`_`) fields and tombstones included. */ row(resource: string, id: string, opts?: { withDeleted?: boolean }): Record | undefined; rowsRaw(resource: string, opts?: { withDeleted?: boolean }): Array>; /** Every stored subject of the pack, of every type, in the tree's order (a projection folding many types at once). */ tree(): Array>; /** The writes that touched a subject, in order: its history. */ history(resource: string, id: string): Array<{ operation?: string; fields?: Record; occurredAt?: string }>; /** Write bookkeeping without the incoming request; an explicit operation observes its checked state move. Mint an id when none is given. */ record(type: string, fields: Record, id?: string, operation?: string): Promise; /** Decide a write from the tree as it stands and make it, with nothing written between the read * and the write (a minted number, a first poll that moves a subject). `decide` returns the write, * or nothing to write; the answer is its `value`. */ atomically(decide: (rows: (resource: string) => Array>) => { value: T; write?: { resource: string; id: string; fields: Record; operation: string } }): Promise; /** Answer bytes or text as they are (a file's content), with the vendor's headers. */ raw(body: BodyInit | null, init?: { status?: number; headers?: Record }): Response; /** Whether the machine lets `operationId` move `field` from `current` (to `to`): nothing when it * does, the vendor's refusal when it does not. A move the machine does not declare throws. */ legal(resource: string, field: string, operationId: string, current: unknown, to?: string, id?: string, actor?: Actor): ErrorSpec | undefined; /** Validate the request body's top-level derived schema under body.validation, before a write. */ validate(): Response | undefined; refuse(e: ErrorSpec): Response; /** Answer the manifest's declared unserved capability gap. */ gap(): Response; notFound(resource: string, id: string, param?: string): Response; reply(body: unknown, status?: number): Response; /** Answer in the vendor's success envelope under this operation's key (`{ ok: true, channel }`). */ wrap(body: Record, extra?: Record): Response; /** Answer as a server-sent event stream, framed as the manifest says. */ sse(events: Array<{ event?: string; data: unknown }>): Response; expand(resource: string, body: Record, paths?: string[]): Record; /** This context at another moment of the World clock (ISO): a move time makes is written at the moment it fell due. */ at(when: string): Promise; /** This call's context over another manifest of the same service, at the same moment: a lane over its vendor's * state reads and writes the vendor's resources through the vendor's manifest ("Pack layout"). */ over(other: DerivedManifest): Promise; /** The generic core's answer to this call, or undefined where the core does not serve it. */ core(): Promise; /** A stored row's own fields, as the vendor's object carries them (an `id`, `type` or `updatedAt` of its own restored). */ own(row: Record): Record; /** A handler's own rows (views) answered as the call's list: the resource's filters, search and order, then the * manifest's paging and envelope; the vendor's refusal when the call orders by a field the resource does not take. */ list(resource: string, rows: Array>): Response; /** The vendor's refusal when these fields would make a second live subject where the resource's `unique` rules allow * one (`except`: the subject being updated), or nothing. */ conflict(resource: string, fields: Record, except?: string): Response | undefined; /** A subject deleted as the vendor deletes it: every subject its resource's `cascade` names deleted first, then it, * each through the write path (`operation` names the subject's own delete when it is not `.delete`). */ remove(resource: string, id: string, operation?: string): Promise; /** The subject a key names, by its id (an alias the caller may still use resolved) or one of the resource's * `alternateKeys` (an organization by its slug), as the vendor serves it. */ find(resource: string, key: string): Record | undefined; /** A field's new value as the resource's `update` rule merges it into the stored one (`deep`: Clerk's metadata). */ merge(resource: string, prior: unknown, next: unknown): unknown; /** What a handler signs and hashes with (signing.ts): JWTs with a pack's key, their verification, a JWKS, an HMAC and * a SHA-256, deterministic, so no pack reaches `node:crypto` itself. */ crypto: HandlerCrypto; /** The World's managed Postgres (managed-database.ts): one transaction per batch, as a role with its settings, or a * script. A World that binds none refuses every use with the reason (EngineUnavailableError). */ engine: ManagedDatabase; /** A vendor's Redis (the kernel's Redis library, redis/engine.ts): a request's commands run in order over this call's * tree and clock, in the pack's own service, under its wire's dialect, in one of its databases (`database`: its keys * and scripts apart from the others'); each answered `{result}` or `{error}`, and whether any wrote. A read-only * World raises ReadOnlyError at the first write. `transaction` distinguishes a wire's queued transaction from * a pipeline for script restrictions. The wire around it (Upstash's REST envelope) is the pack's. */ redis(commands: string[][], options: { dialect: RedisDialect; database?: string; transaction?: boolean }): Promise<{ items: RunItem[]; wrote: boolean }>; /** Another vendor's own URL answered by the World's twin of it (vendor-call.ts): a vendor's call to another as part of * its behaviour (Clerk exchanging a Google sign-in's code). A vendor the World runs no twin of is refused * (VendorUnreachableError); nothing leaves the World. */ vendorFetch(url: string | URL, init?: RequestInit): Promise; /** A multipart/form-data body's parts in order (multipart.ts: field name, filename, media type, bytes), a part with an * empty field name included; none for any other body. */ parts(): Promise; /** The pack's resource blobs (an object's bytes), by key, on the World's branch: they branch with the World, and a * read falls back to an ancestor's. The row that names a blob is the pack's; the bytes are here. */ blobs: { put(key: string, bytes: Uint8Array): Promise; get(key: string): Promise; remove(key: string): Promise; /** a body written as it arrives (a request's own stream), kept only when `accept` holds for its size and SHA-256: * an upload of a large object never held whole. True when kept */ putStream(key: string, body: ReadableStream | AsyncIterable, accept: (written: { size: number; sha256: string }) => boolean): Promise; /** a blob's length, or null when there is none: a large object is answered without loading it */ size(key: string): Promise; /** the bytes `start`..`endInclusive` of a blob (a ranged read where the store has one), or null when there is none */ range(key: string, start: number, endInclusive: number): Promise; }; /** A body's fields checked against the operation's declared ones under the manifest's `body.strict`: the fields, or * the vendor's refusal of the first that is unknown, of another type or out of its bounds. */ fields(body: Record): { fields: Record } | { refused: Response }; /** A parameter as the vendor reads a boolean (the manifest's `booleans`): true, false, or undefined for a value that * is neither (absent, or text the vendor does not read as one). A boolean passes as itself. */ flag(value: unknown): boolean | undefined; }; export type Semantics = (ctx: SemanticsContext) => Promise; /** The context a derived pack's handler is given ("What an author writes, and how"): the kernel's own members * (`now`, `core`, `atomically`, `tree`, `writeDetailed`) and the tree's location (`root`) are not on it, so a handler * typed `Handler` cannot reach them. Its reads are those the contract lists (`row`, `rowsRaw`, `rows`, `get`, * `history`, `resolve`, `expand`); `at` and `over` give the same narrow context at another moment or over the * vendor's manifest. */ export type HandlerContext = Omit & { /** This context at another moment of the World clock (ISO): a move time makes is written at the moment it fell due. */ at(when: string): Promise; /** This call's context over the manifest of the vendor whose state a lane shares, at the same moment. */ over(other: DerivedManifest): Promise; }; /** What a write hook reads: the writing call's context without its ways to write, so a hook that renders an event * cannot write again (and run itself again). */ export type WriteHookContext = Omit; /** A derived pack's handler: one operation, by its operationId, over the contract's context. */ export type Handler = (ctx: HandlerContext) => Promise; /** The context the kernel opens for a call (a handler's, a door's, a screen's). Kernel-internal: packs are given it. */ /** A media type whose body the core reads for a context (and records with a write): JSON, a form, multipart, text, * or none named. */ const coreReadsBody = (type: string | null): boolean => { const media = (type ?? '').split(';')[0]!.trim().toLowerCase(); return media === '' || media === 'application/json' || media.endsWith('+json') || media === 'application/x-www-form-urlencoded' || media.startsWith('multipart/') || media.startsWith('text/'); }; const ledgers = new WeakMap ScenarioLedger>(); /** What a context consumes the World's scenario through (scenario-consume.ts): its twin's bookkeeping, at its time. */ export function scenarioLedgerOf(ctx: object): ScenarioLedger { const ledger = ledgers.get(ctx); if (!ledger) throw new Error('a scenario ledger is a context the kernel opened'); return ledger(); } /** `GET /twin/scenario`: what the World's scenario placed on this vendor, and what the twin consumed of it. */ export function scenarioRecords(m: DerivedManifest, root?: string): { vendor: string; placed: unknown[]; consumed: { decisions: unknown[]; faults: unknown[] } } { const placed = placedOn(m.vendor); const kept = (type: string) => resourcesOfType(m.service, storedType(m, type), root).map((r) => ownFields(r)); return { vendor: m.vendor, placed, consumed: { decisions: kept('_decision'), faults: kept('_fault') } }; } export async function contextFor(m: DerivedManifest, call: DerivedCall, scope: CoreScope): Promise { const root = scope.root; const asAsked = call; call = adoptedPath(m, call, root); scopeOfCall.set(call, scope); const at = (scope.clock ?? worldNow)(); // the guard's parse when it made one (taken once), else this context's own // a body that is its payload's bytes (S3's PutObject) is never read as JSON, whatever its label const payload = bytesPayload(call.operation); // a screen's body the core does not read (an upload's bytes) is left to its handler, unread (DerivedCall.streamed) const opaque = call.streamed === true && !coreReadsBody(call.request.headers.get('content-type')); const parsed = payload || opaque ? undefined : takeParsedBody(call.request); const text = opaque ? '' : await bodyTextOf(call.request.clone()).catch(() => ''); let body: unknown = parsed?.value; if (!parsed) { if (payload) body = text || undefined; else { try { body = text ? parseExactJson(text) : undefined; } catch { body = text; } } } // the request as it came, before the core's parameter merge and alias adoption: what a write records, so a perform // can send it again (the real-system adapters, "What the derived core records with a write") const boundary = payload ? null : multipartBoundary(call.request.headers.get('content-type')); const parts = boundary === null ? undefined : multipartParts(new Uint8Array(await call.request.clone().arrayBuffer()), boundary); // a body that is not JSON is recorded as it came, its type with it: text as text, bytes (a gzip the vendor's client // compressed itself, PostHog's `compression=gzip-js`) as base64 const raw = !parts && typeof body === 'string' && body !== '' ? await rawBody(call.request) : undefined; sentOf.set(call, { ...sentRequest(m, asAsked, parts ? Object.fromEntries(parts.filter((p) => p.filename === null).map((p) => [p.name, new TextDecoder().decode(p.body)])) : raw ?? body), ...(parts ? { parts } : {}), ...(raw ? { type: call.request.headers.get('content-type') ?? undefined } : {}) }); // a handler reading the body itself sees the adopted id too (the boundary's one resolution, below) if (body && typeof body === 'object' && !Array.isArray(body)) body = adoptedInCall(m, body as Record, root); // every read of the body is of a copy, so the handler's own `call.request` and the core's answer (`core()`) each // still find it unread, whichever of them reads it first const pristine = call.request.clone(); requestOfCall.set(call, pristine); const params = await boundaryParams(m, { ...call, request: call.request.clone() }, root).catch((error) => { // An around context opens before the credential/JSON guard. Keep non-body parameters available to it without // turning the guard's declared malformed-body refusal into a context-construction exception. if (!(error instanceof SyntaxError) || error.message !== 'malformed JSON body') throw error; return boundaryParams(m, { ...call, request: new Request(call.request.url, { headers: call.request.headers }) }, root); }); const paths = expandPaths(m, params); const stateChecks: StateChecks = new Map(); const credentialDoor = m.descriptor?.credentialDoor ?? getPack(m.vendor)?.credentialDoor; const credentialFields = body && typeof body === 'object' && !Array.isArray(body) ? body as Record : {}; const rawResources = new WeakMap, string>(); const rawRow = (resource: string, row: TwinResource): Record => { const name = m.resources[resource] ? resource : Object.keys(m.resources).find((name) => storedType(m, name) === row.type); if (m.tenant?.storage === 'namespaced') { const [base, encoded] = row.type.split(TENANT_TYPE); const owner = m.resources[name ?? resource]?.shared && row[m.tenant.field] !== undefined ? row[m.tenant.field] : encoded ? decodeURIComponent(encoded) : 'default'; row = copyResource(row); row.type = base!; row[m.tenant.field] = owner; } rawResources.set(row as Record, name ?? resource); return row as Record; }; const liveNativeRow = (link: NativeAccountLink): Record | undefined => { const row = context.row(link.resource, link.id); return row && row.deleted !== true ? row : undefined; }; const recording = !(scope.readOnly === true || isReadOnlyRequest(call.request)); // an operation that writes nothing consumes the scenario off the log (scenario-consume.ts) const reads = ['retrieve', 'list', 'computed'].includes(call.operation.class) || m.reads?.includes(call.operation.id) === true; const ledger = (): ScenarioLedger => ({ vendor: m.vendor, service: m.service, root, at, recording, reads, rows: (type) => context.rowsRaw(type), record: (type, fields, id) => context.record(type, fields, id) }); // the vendor's rows as an eventually consistent operation reads them (its own bookkeeping is no index's), and as the // vendor answers them (a pending field before its work fills it) const settled = lagged(m, call.operation, root, at, recording); const answered = (resource: string, rows: TwinResource[]): TwinResource[] => rows.map(pendingAt(m, resource, root, at)); const context: SemanticsContext = { call, params, variants: (name) => { const resource = scope.resources?.find((resource) => resource.name === name); if (!resource) throw new Error(`semantics: no generated resource ${name} in this unit`); return resource.variants; }, id: Object.values(call.params).at(-1), body, text, root, publicBase: twinPublicBase(call.request), scenario: scenarioDecisionOf(call.request), decide: (point, subject, byDefault) => decide(ledger(), point, subject, byDefault), fault: (point, subject) => faultAt(ledger(), point, subject), fact: async (kind, key) => factAt(kind, key, at), ask: (url, init, within) => askApplication(url, init, within, scope.application), worldEnv: (name) => worldEnvValue(name), asVendor: (fn) => runAsVendorMove(fn), git: (name) => gitRepositoryOf(m, name, root), gitRepository: (row) => gitRepositoryOf(m, gitNameOf(m, String(row.id), root), root), mail: (mail) => sendMail(mail), now: () => now(m, at), render: (row, resource) => { const raw = rawResources.has(row); const name = resource ?? rawResources.get(row); const declared = name && (m.resources[name] ? name : Object.keys(m.resources).find((r) => storedType(m, r) === name)); const keep = declared ? m.resources[declared]?.vendorUnderscored ?? [] : []; const shown = raw ? render(declared ? pendingAt(m, declared, root, at)(row as TwinResource) : row as TwinResource, keep) : renderOwn(row, keep); return omitView(m, declared || undefined, shown); }, get: (resource, id) => { const hit = settled(resource).find((r) => r.id === id); return hit ? view(m, resource, answered(resource, [hit])[0]!) : undefined; }, ownerRow: (owner, resource, id) => { if (!m.ownerReads?.some((r) => r.owner === owner && r.resource === resource)) throw new Error(`semantics: undeclared owner read ${owner}/${resource}`); const row = projectOwnerResources(owner, root, { type: resource, id }).find((r) => r.type === resource && r.id === id); return row ? { ...ownFields(row), ...(row.deleted === true ? { deleted: true } : {}) } : undefined; }, rows: (resource) => answered(resource, settled(resource)).map((r) => view(m, resource, r)), mint: (resource) => mintId(m, resource, root, at), sockets: (id) => openSessions(m.service, root, id), awaitWrite: (resources, ms) => (scope.readOnly === true || isReadOnlyRequest(call.request) ? Promise.resolve(false) : awaitWrite(m.service, root, resources.map((r) => storedType(m, r)), ms, call.request.signal)), awaitCondition: (resources, ms, pollMs, condition) => awaitCondition(m.service, root, resources.map((r) => storedType(m, r)), scope.readOnly === true || isReadOnlyRequest(call.request) ? 0 : ms, pollMs, condition, call.request.signal), issue: async (resource) => { if (!resource.startsWith('_')) throw new Error(`semantics: ${resource} is not a bookkeeping type (an issued id's type starts with _)`); if (scope.readOnly === true || isReadOnlyRequest(call.request)) return mintId(m, resource, root, at); const { value } = await applyTwinWriteAtomic(m.service, (snapshot) => { const id = mintId(m, resource, root, at, snapshot); return { kind: 'write', value: id, write: { operation: `${resource.slice(1)}.issue`, subjectType: storedType(m, resource), subjectId: id, fields: { issuedAt: at }, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' } } }; }, root); return value; }, occurredAt: at, secret: async (label) => hmac(await worldSeed(m.service, root, at), scopeLabel(m, label), 'base64url'), issueKey: async (purpose, format, account) => { const who = account ?? await context.account(); const seed = await worldSeed(m.service, root, at), id = `${who}/${purpose}`, type = storedType(m, ISSUED_KEY); const issue = (row: Record | undefined): { generation: number; value: string } => { const generation = liveGeneration(row); return { generation, value: keyFrom(seed, scopeLabel(m, `issued-key:${who}:${generation === 1 ? purpose : `${purpose}#${generation}`}`), format) }; }; const held = resourcesOfType(m.service, type, root).find((r) => r.id === id) as Record | undefined; const now = issue(held); if ((held?._sha256 === sha256(now.value) && held.revoked !== true) || scope.readOnly === true || isReadOnlyRequest(call.request)) return now.value; return (await applyTwinWriteAtomic(m.service, (snapshot) => { const row = snapshot.find((r) => r.type === type && r.id === id) as Record | undefined; const { generation, value } = issue(row), hash = sha256(value); // a branch whose own seed issued another value before the identity reached it is issued the identity's value return row?._sha256 === hash && row.revoked !== true ? { kind: 'skip', value } : { kind: 'write', value, write: { operation: 'world_issued_key.issue', subjectType: type, subjectId: id, fields: { account: who, purpose, generation, _sha256: hash, issuedAt: at, revoked: false }, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' } } }; }, root)).value; }, issueKeyId: async (purpose, format, account) => { const who = account ?? await context.account(); const generation = liveGeneration(resourcesOfType(m.service, storedType(m, ISSUED_KEY), root).find((r) => r.id === `${who}/${purpose}`) as Record | undefined); return keyFrom(await worldSeed(m.service, root, at), scopeLabel(m, `issued-key-id:${who}:${generation === 1 ? purpose : `${purpose}#${generation}`}`), format); }, issuedKey: (value) => issuedKeyOf(m, value, root), revokeKey: async (purpose, account) => revokeIssued(m, call, account ?? await context.account(), purpose, root, at), account: async (field = credentialDoor?.account?.field ?? 'account') => { return worldAccount(m.service, root, credentialFields[field] ?? 'default', at, call.request.headers.get('x-volter-world-activity') === 'provisioning'); }, organization: async () => { const id = await context.account(); const row = projectOwnerResources('_world', root, { type: '_world_organization', id }).find((row) => row.type === '_world_organization' && row.id === id && row.deleted !== true); return row ? { id, label: row.label as string, members: [...(row.members as string[])] } : { id, label: id, members: ['owner@world.test'] }; }, deployment: () => { const id = credentialFields[credentialDoor?.deployment?.field ?? 'deployment'] ?? ''; if (id !== '' && !isWorldAccountName(id)) throw new Error('Credential deployment must be a name of at most 128 letters, digits, dots, underscores or hyphens'); return id; }, vendorName, tenant: async (resource, make) => { const id = await context.account(); return retainNativeAccountLink(m.service, root, at, call, '_world_account', id, 'tenant', resource, async () => make(await context.organization()), async (link) => liveNativeRow(link)); }, deploymentObject: async (kind, resource, make) => { const organization = await context.account(), deployment = context.deployment(); return retainNativeAccountLink(m.service, root, at, call, '_world_deployment_object', `${organization}/${deployment}/${kind}`, undefined, resource, () => make(deployment), async (link) => liveNativeRow(link)); }, accountKey: async (purpose, resource, key) => { const organization = await context.account(), deployment = context.deployment(); return retainNativeAccountLink(m.service, root, at, call, '_world_account_key', `${organization}/${deployment}/${purpose}`, undefined, resource, () => key.make(), async (link) => { const row = liveNativeRow(link); if (!row) return undefined; const secret = await key.read(row); return secret === undefined ? undefined : { id: link.id, secret }; }); }, record: async (type, fields, id, operation) => { if (!type.startsWith('_')) throw new Error(`semantics: ${type} is not a bookkeeping type (bookkeeping types start with _)`); // a bookkeeping subject a resource counts (`counts` naming it: sentry's issue users) keeps that count as any // child does, the parent it left recounted too const keeps = counted(m, type), physicalType = storedType(m, type); if (id !== undefined) { const before = operation ? stateBeforeWrite(m, type, id, root) : undefined; const prior = keeps ? resourcesOfType(m.service, physicalType, root).find((r) => r.id === id) : undefined; const { resource: row, result } = await applyTwinWrite(m.service, { operation: operation ?? `${type.slice(1)}.record`, subjectType: physicalType, subjectId: id, fields, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' } }, root); if (operation) observeStateWrite(m, result, before, root, stateChecks); if (keeps) await keepCounts(m, call, type, row as unknown as Record, params, root, at, prior && { ...prior } as Record); return id; } const { value, result } = await applyTwinWriteAtomic(m.service, (resources) => { // Allocate and append under the same state lock: concurrent sign-ins must never share an issue id. const subject = (() => { const prefix = `${type.slice(1)}_`; let max = 0n; for (const r of resources) { if (r.type !== physicalType) continue; const digits = r.id.startsWith(prefix) ? r.id.slice(prefix.length) : ''; if (/^\d+$/.test(digits) && BigInt(digits) > max) max = BigInt(digits); } return `${prefix}${max + 1n}`; })(); return { kind: 'write', value: subject, write: { operation: operation ?? `${type.slice(1)}.record`, subjectType: physicalType, subjectId: subject, fields, ...provisioningInput(call), occurredAt: at, actor: { kind: 'system' } } }; }, root, () => resourcesOfType(m.service, physicalType, root)); if (operation && result) observeStateWrite(m, result, undefined, root, stateChecks); const made = keeps && value !== undefined ? resourcesOfType(m.service, physicalType, root).find((r) => r.id === value) : undefined; if (made) await keepCounts(m, call, type, made as unknown as Record, params, root, at); return value; }, get machines() { const enrolled = resourcesOfType(m.service, MACHINE_POOL, root).find((r) => r.id === 'pool') as unknown as { kind?: MachinePool['kind']; httpReplies?: MachineHttpReply[] } | undefined; return guardedMachinePool(poolFor(m.service, root, enrolled?.kind ?? 'none', enrolled?.httpReplies), m.service, ['retrieve', 'list'].includes(call.operation.class) || (m.reads?.includes(call.operation.id) ?? false)); }, signingKey: (label, alg) => worldSigningKey(m.service, root, at, scopeLabel(m, label), alg ?? 'RS256'), heldSigningKey: (label, alg) => heldWorldSigningKey(m.service, root, scopeLabel(m, label), alg ?? 'RS256'), create: (resource, fields, operation) => atomicWrite(m, call, resource, (snapshot) => { const id = mintId(m, resource, root, at, snapshot); return { id, fields: typeof fields === 'function' ? fields(id) : fields }; }, operation, params, root, at, undefined, stateChecks).then((row) => row!), createUnique: async (resource, fields, operation, options) => { if (options?.input === 'omit' && !resource.startsWith('_')) throw new Error('only bookkeeping writes may omit request input'); const rules = m.resources[resource]?.unique; if (!rules?.length) throw new Error('createUnique requires declared unique keys'); let existing: Record | undefined; const row = await atomicWrite(m, call, resource, (snapshot) => { const id = options?.id ?? mintId(m, resource, root, at, snapshot); const selected = typeof fields === 'function' ? fields(id) : fields; const hit = snapshot.find((r) => { if (r.type !== storedType(m, resource) || r.deleted === true) return false; const fields = { [m.resources[resource]?.idAs ?? 'id']: r.id, ...ownFields(r) }; return rules.some((rule) => rule.fields.every((field) => selected[field] !== undefined && fields[field] === selected[field])); }); if (hit) { existing = view(m, resource, hit); return undefined; } return { id, fields: selected }; }, operation, params, root, at, undefined, stateChecks, options?.input === 'omit'); return existing ? { created: false, row: existing } : { created: true, row: row! }; }, change: (resource, id, decide, operation, options) => { if (options?.input === 'omit' && !resource.startsWith('_')) throw new Error('only bookkeeping writes may omit request input'); return atomicWrite(m, call, resource, (snapshot) => { const row = snapshot.find((r) => r.type === storedType(m, resource) && r.id === id && r.deleted !== true); if (!row) return undefined; const fields = decide(row as Record); return fields === undefined ? undefined : { id, fields }; }, operation, params, root, at, id, stateChecks, options?.input === 'omit'); }, write: (resource, id, fields, operation) => write(m, call, resource, id, fields, operation, params, root, at, stateChecks), accumulate: async (resource, id, deltas, operation) => { if (!resource.startsWith('_') || !m.resources[resource]) throw new Error('accumulate requires a declared bookkeeping resource'); await applyTwinWriteAtomic(m.service, (resources) => { const prior = resources.find((row) => row.type === storedType(m, resource) && row.id === id && row.deleted !== true); if (!prior) throw new Error('accumulate requires an existing bookkeeping row'); const fields: Record = {}; for (const [field, delta] of Object.entries(deltas)) { const value = prior[field]; if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(delta) || !Number.isFinite(value + delta)) throw new Error('accumulate requires finite numeric fields and deltas'); fields[field] = value + delta; } return { kind: 'write', value: undefined, write: { operation, subjectType: storedType(m, resource), subjectId: id, fields, occurredAt: at, actor: { kind: 'agent' } } }; }, root); }, writeDetailed: (resource, id, fields, operation) => writeDetailed(m, call, resource, id, fields, operation, params, root, at, stateChecks), resolve: (resource, id) => resolveSubjectId(m.service, storedType(m, resource), id, root), storedType: (resource) => m.resources[resource]?.storedAs ?? resource, ok: (fields) => Response.json({ ...(m.success ?? {}), ...fields }), row: (resource, id, opts) => { const row = settled(resource, opts).find((r) => r.id === id); return row ? rawRow(resource, row) : undefined; }, rowsRaw: (resource, opts) => settled(resource, opts).map((row) => rawRow(resource, row)), tree: () => { const rows = twinResources(m.service, root); if (m.tenant?.storage !== 'namespaced') return rows as Array>; const account = accountScope(m); return rows.filter(row => { const [base, encoded] = row.type.split(TENANT_TYPE); const name = Object.keys(m.resources).find(name => (m.resources[name]?.storedAs ?? name) === base) ?? base!; return account === undefined || m.resources[name]?.shared || (encoded ? decodeURIComponent(encoded) : 'default') === account; }).map(row => rawRow(row.type.split(TENANT_TYPE)[0]!, row)); }, history: (resource, id) => subjectHistory(m.service, { type: storedType(m, resource), id }, root).map((e) => ({ ...(e.operation ? { operation: e.operation } : {}), ...(e.fields ? { fields: e.fields as Record } : {}), ...(e.occurredAt ? { occurredAt: e.occurredAt } : {}) })), raw: (body, init = {}) => new Response(body, { status: init.status ?? 200, headers: init.headers ?? {} }), atomically: async (decide) => { let before: TwinResource | undefined; const { value, result } = await applyTwinWriteAtomic( m.service, (resources) => { const rows = (resource: string): Array> => resources.filter((r) => r.type === storedType(m, resource) && r.deleted !== true) as Array>; const d = decide(rows); if (!d.write) return { kind: 'skip', value: d.value }; const w = d.write; if (transitionObserver) before = resources.find((r) => r.type === storedType(m, w.resource) && r.id === w.id); return { kind: 'write', value: d.value, write: { operation: w.operation, subjectType: storedType(m, w.resource), subjectId: w.id, fields: w.fields, ...provisioningInput(call), occurredAt: at, actor: { kind: 'agent' } } }; }, root, ); if (result) observeStateWrite(m, result, before, root, stateChecks); return value; }, legal: (resource, field, operationId, current, to, id, actor) => { const decl = m.resources[resource]?.state?.[field]; if (!decl) throw new Error(`semantics: ${resource}.${field} is not a declared state field`); const { move, refusal } = transitionFor(field, decl, operationId, current, to, id ?? Object.values(call.params).at(-1), actor ?? 'api'); if (move) { if (transitionObserver) { const key = stateCheckKey(storedType(m, resource), field); stateChecks.set(key, [...(stateChecks.get(key) ?? []), { transition: move, operation: operationId, from: stateOf(decl, current), to: move.to ?? stateOf(decl, current), actor: actor ?? 'api' }]); } return undefined; } if (refusal) return refusal; throw new Error(`semantics: ${operationId} moves ${resource}.${field} from ${String(current)}${to ? ` to ${to}` : ''}, which the machine does not declare`); }, refuse: (e) => vendorError(m, e), gap: () => vendorError(m, m.gap ?? m.notFound), notFound: (resource, id, param) => notFound(m, resource, id, param), validate: () => validateBody(m, call.operation, body), reply: (body, status = 200) => Response.json(body, { status }), wrap: (body, extra = {}) => Response.json({ ...envelope(m, call.operation, body), ...extra }), sse: (events) => sse(m, events, call.operation.id), expand: (resource, body, given) => expand(m, resource, body, given ?? paths, root), at: (when) => contextFor(m, { ...call, request: new Request(call.request.url) }, { ...scope, clock: () => when }), crypto: handlerCrypto, flag: (value) => flagOf(m, value), fields: (body) => strictFields(m, call.operation, body), vendorFetch: (url, init) => vendorFetch(url, init, scope.application), parts: async () => { const boundary = multipartBoundary(call.request.headers.get('content-type')); return boundary === null ? [] : multipartParts(new Uint8Array(await call.request.clone().arrayBuffer()), boundary); }, engine: scope.database === undefined ? unboundDatabase(m.service) : managedDatabase(scope.database, { readOnly: scope.readOnly === true || isReadOnlyRequest(call.request) }), redis: (commands, options) => execRedisRun(commands, { root, occurredAt: at, service: m.service, readOnly: scope.readOnly === true || isReadOnlyRequest(call.request), dialect: options.dialect, ...(accountScope(m) && accountScope(m) !== 'default' ? { database: scopeLabel(m, options.database ?? 'default') } : options.database === undefined ? {} : { database: options.database }), ...(options.transaction === undefined ? {} : { transaction: options.transaction }), }), live: liveAccess({ rows: (type) => stored(m, type, root).map(row => rawRow(type, row)), blob: (key) => readResourceBlob(m.service, scopeLabel(m, key), root) }, call.request), blobs: { put: (key, bytes) => writeResourceBlob(m.service, scopeLabel(m, key), bytes, root), putStream: (key, body, accept) => writeResourceBlobStream(m.service, scopeLabel(m, key), body, accept, root), get: (key) => readResourceBlob(m.service, scopeLabel(m, key), root), remove: (key) => removeResourceBlob(m.service, scopeLabel(m, key), root), size: (key) => resourceBlobSize(m.service, scopeLabel(m, key), root), range: (key, start, endInclusive) => readResourceBlobRange(m.service, scopeLabel(m, key), start, endInclusive, root), }, merge: (resource, prior, next) => mergeField(m.resources[resource]?.update, prior, next), conflict: (resource, fields, except) => { const clash = conflictOf(m, resource, fields, except, root); return clash ? vendorError(m, clash) : undefined; }, remove: (resource, id, operation) => removeSubject(m, call, resource, id, params, root, at, operation), find: (resource, key) => { const id = resolveSubjectId(m.service, storedType(m, resource), key, root); const hit = stored(m, resource, root).find((r) => r.id === id || namedBy(m.resources[resource], r, key)); return hit ? view(m, resource, hit) : undefined; }, list: (resource, rows) => { const arranged = arrangeRows(m, resource, params, rows); return Array.isArray(arranged) ? pageRows(m, call.operation, call, params, arranged, resource, root, paths) : vendorError(m, arranged); }, over: (other) => contextFor(other, { ...asAsked, request: asAsked.request.clone() }, { ...scope, clock: () => at }), core: async () => { const out = await serveCore(m, { ...call, request: pristine.clone() }, { ...scope, clock: () => at }); return 'served' in out ? out.served : undefined; }, own: (row) => ownFields(row as unknown as TwinResource), batch: (fn) => fn(), }; if (batchable(m, root)) bindBatch(m, call, context, params, root, at, rawRow); ledgers.set(context, ledger); return context; } /** * Whether a call's writes may be grouped (`ctx.batch`) with nothing about them changing: every effect a write has * besides its action and the tree (write hooks, events, sockets, a parent's counts, a state observer, a head that * performs it, an alias a read resolves through) is one the grouped path would move, so where any is present the * writes land one at a time, as they always have. */ function batchable(m: DerivedManifest, root: string | undefined): boolean { return !m.onWrite && !m.events && !m.sockets?.length && !transitionObserver && !Object.values(m.resources).some((decl) => decl.counts && Object.keys(decl.counts).length > 0) && !performsAtHeadNow(m.service, root) && subjectAliases(m.service, root).size === 0; } /** A staged write of `ctx.batch`, as `write` was asked it. */ type StagedWrite = { resource: string; id: string; fields: Record; operation: string }; /** The members of a context that read the tree other than `row`/`rowsRaw`: refused while writes are staged. */ const BATCH_REFUSED_READS = ['get', 'rows', 'tree', 'history', 'find', 'list', 'expand', 'mint', 'conflict', 'ownerRow', 'render'] as const; /** The members that write, or wait on writes, or answer as another context: each lands the staged writes first. */ const BATCH_LANDING_MEMBERS = ['create', 'createUnique', 'change', 'accumulate', 'writeDetailed', 'record', 'atomically', 'remove', 'issue', 'at', 'over', 'core', 'awaitWrite', 'awaitCondition', // a World's seed and signing keys are written when first asked (worldSeed, worldSigningKey, as a vendor's move) 'secret', 'signingKey', 'account', 'organization', 'tenant', 'deploymentObject', 'accountKey'] as const; /** `ctx.batch` over a context whose writes may be grouped (see `batchable`). */ function bindBatch(m: DerivedManifest, call: DerivedCall, context: SemanticsContext, params: Record, root: string | undefined, at: string, rawRow: (resource: string, row: TwinResource) => Record): void { let staged: StagedWrite[] | undefined; // A callback's native object must land before the helper writes its retained link. let nativeAccountWrites = 0; // each staged subject as it will stand, by `type:id`, in the order first written const subjects = new Map(); const land = async (): Promise => { if (!staged?.length) return; const writes = staged; staged = []; subjects.clear(); await writeGroup(m, call, writes, params, root, at); }; const ctx = context as unknown as Record; for (const name of BATCH_LANDING_MEMBERS) { const plain = ctx[name]; if (typeof plain !== 'function') continue; ctx[name] = async (...args: unknown[]) => { await land(); const native = name === 'tenant' || name === 'deploymentObject' || name === 'accountKey'; if (native) nativeAccountWrites++; try { return await (plain as (...a: unknown[]) => unknown)(...args); } finally { if (native) nativeAccountWrites--; } }; } for (const name of BATCH_REFUSED_READS) { const plain = ctx[name]; if (typeof plain !== 'function') continue; ctx[name] = (...args: unknown[]) => { if (staged?.length) throw new Error(`ctx.${name} reads the tree while ctx.batch holds staged writes: only row and rowsRaw see them`); return (plain as (...a: unknown[]) => unknown)(...args); }; } const plainWrite = context.write, plainRow = context.row, plainRowsRaw = context.rowsRaw; context.write = async (resource, id, fields, operation) => { // a vendor's own move (ctx.asVendor) is the clock's write, recorded as the system's: it lands alone, in its place if (!staged || nativeAccountWrites > 0 || inVendorMove()) { await land(); return plainWrite(resource, id, fields, operation); } const type = storedType(m, resource), key = `${type}:${id}`; // the one subject, as the memoized tree holds it (readTreeMap would copy the whole tree on every staged write) const subject = foldLocalWrite(subjects.get(key) ?? heldSubject(m.service, type, id, root), type, id, fields as SubjectFields, at); subjects.set(key, subject); staged.push({ resource, id, fields, operation }); return view(m, resource, treeResources(new Map([[key, subject]]))[0]!); }; // the stored rows of a resource's type with the staged subjects folded over them, filtered as `stored` filters const overlaid = (resource: string, opts?: { withDeleted?: boolean }): TwinResource[] | undefined => { if (!staged?.length) return undefined; const type = storedType(m, resource), prefix = `${type}:`; const mine = [...subjects].filter(([key]) => key.startsWith(prefix)); if (!mine.length) return undefined; const replaced = new Map(mine.map(([key, subject]) => [key, treeResources(new Map([[key, subject]]))[0]!])); const base = resourcesOfType(m.service, type, root); // a subject the tree holds stays where it stands; one new to it goes to the end, in the order first written const rows = base.map((row) => replaced.get(`${prefix}${row.id}`) ?? row); const held = new Set(base.map((row) => `${prefix}${row.id}`)); for (const [key, row] of replaced) if (!held.has(key)) rows.push(row); const when = Object.entries(m.resources[resource]?.readableWhen ?? {}); return rows.filter((r) => (opts?.withDeleted || r.deleted !== true) && when.every(([k, v]) => (r as Record)[k] === v)); }; context.row = (resource, id, opts) => { const rows = overlaid(resource, opts); if (!rows) return plainRow(resource, id, opts); const row = rows.find((r) => r.id === id); return row ? rawRow(resource, row) : undefined; }; context.rowsRaw = (resource, opts) => { const rows = overlaid(resource, opts); return rows ? rows.map((row) => rawRow(resource, row)) : plainRowsRaw(resource, opts); }; context.batch = async (fn) => { // a batch inside a batch is the outer one's if (staged !== undefined) return fn(); staged = []; try { return await fn(); } finally { // every write `write` answered lands, whether fn returned or threw: an ordered insert's prefix stays written try { await land(); } finally { staged = undefined; subjects.clear(); } } }; } /** * A command's staged writes landed as one group: each recorded with the request as `writeDetailed` records it (one * recordedInput, the same for every write of the call), the call's moment and actor, in order, under one lock and one * append (serve.ts applyTwinWrites); then a held read on each written type is told, as each write tells it. */ async function writeGroup(m: DerivedManifest, call: DerivedCall, writes: readonly StagedWrite[], params: Record, root: string | undefined, occurredAt: string): Promise { const input = recordedInput(m, call, params); const files = input.operationId ? await keptFiles(m, call, root) : undefined; const recorded = files ? { ...input, files } : input; const actor = { kind: 'agent' as const, ...(m.identity ? { id: m.identity(call.request.headers.get('authorization'), root) } : {}) }; await applyTwinWrites(m.service, writes.map((write) => ({ operation: write.operation, subjectType: storedType(m, write.resource), subjectId: write.id, fields: write.fields, input: recorded, occurredAt, actor })), root); for (const type of new Set(writes.map((write) => storedType(m, write.resource)))) heldReadsWrite(m.service, root, type); } /** A pack's semantics handlers as the dispatch's handlers. */ export function bindSemantics(m: DerivedManifest, handlers: Record, scope: CoreScope = {}): Record { prepareViewOmissions(m); return Object.fromEntries(Object.entries(handlers).map(([id, h]) => [id, async (call: DerivedCall) => { const ctx = await contextFor(m, call, scope); redisServiceTimes.lap('6c the handler\'s own context opened'); // an operation's own variants, else the ones every operation shares (`'*'`) const variants = m.variants?.[id] ?? m.variants?.['*']; if (variants && variantAsked(ctx.params as Record, variants, call.request.headers)) return variantGap(m, call.request); const outside = enumRefused(m, call, ctx.params as Record); return outside ?? h(ctx); }])); } /** The first of a request's form parameters whose value is not one its spec lists (DerivedOperation.enums), with the * bracket name a form gives it (`spending_controls[spending_limits][0][interval]`) and the values it takes. */ export function valueOutside(params: Record, enums: Readonly>>): { param: string; values: ReadonlyArray } | undefined { const at = (value: unknown, path: string[], name: string, values: ReadonlyArray): { param: string; values: ReadonlyArray } | undefined => { if (value === undefined || value === null) return undefined; if (!path.length) return typeof value === 'object' || values.includes(String(value)) ? undefined : { param: name, values }; const [head, ...rest] = path; if (head === '[]') { const items = Array.isArray(value) ? value.map((v, i) => [String(i), v] as const) : value && typeof value === 'object' ? Object.entries(value) : []; for (const [i, v] of items) { const found = at(v, rest, `${name}[${i}]`, values); if (found) return found; } return undefined; } return value && typeof value === 'object' && !Array.isArray(value) ? at((value as Record)[head!], rest, `${name}[${head}]`, values) : undefined; }; for (const [path, values] of Object.entries(enums)) { const [first, ...rest] = path.split('.'); const found = at(params[first!], rest, first!, values); if (found) return found; } return undefined; } /** The manifest's refusal of a form value outside the operation's spec lists (and the values documented beside * them), unless the request names an API version other than the one the spec is. */ function enumRefused(m: DerivedManifest, call: DerivedCall, params: Record): Response | undefined { const refusal = m.body.form?.enumRefusal; if (!refusal || !call.operation.enums) return undefined; const pinned = refusal.version ? call.request.headers.get(refusal.version.header) : null; if (pinned && pinned !== refusal.version!.served) return undefined; const documented = refusal.documented?.[call.operation.id] ?? {}; const enums = Object.fromEntries(Object.entries(call.operation.enums).map(([path, values]) => [path, [...values, ...(documented[path] ?? [])]])); const outside = valueOutside(params, enums); if (!outside) return undefined; const { documented: _d, version: _v, ...error } = refusal; return vendorError(m, { ...error, param: outside.param, message: error.message.replace(/\{param\}/g, outside.param).replace(/\{values\}/g, oneOfList(outside.values)) }); } /** A list of values as a sentence names them: `a, b, or c`. */ const oneOfList = (values: ReadonlyArray): string => (values.length < 2 ? values.join('') : `${values.slice(0, -1).join(', ')}, or ${values[values.length - 1]}`); /** Whether a request's parameters ask one of the operation's undemanded variants (DerivedManifest.variants). */ export function variantAsked(params: Record, variants: readonly string[], headers?: Headers): boolean { const valuesAt = (value: unknown, path: string[]): unknown[] => { if (!path.length) return value === undefined ? [] : [value]; const [head, ...rest] = path; // `!name` is the field left out: the value itself where it has none (`items[].!id`, an item naming no id) if (head!.startsWith('!')) return value && typeof value === 'object' && (value as Record)[head!.slice(1)] === undefined ? [value] : []; const list = head!.endsWith('[]'); const key = list ? head!.slice(0, -2) : head!; const next = value && typeof value === 'object' ? (value as Record)[key] : undefined; if (!list) return valuesAt(next, rest); const items = Array.isArray(next) ? next : next && typeof next === 'object' ? Object.values(next) : []; return items.flatMap((item) => valuesAt(item, rest)); }; // a variant joined with `&` is its parts asked together (`trial_end=now&items`): the combination, not either alone; // a part led by `!` is a parameter left out (`items[].price&!items[].id`, an item added rather than changed) return variants.some((variant) => variant.split('&').every((part) => { const absent = part.startsWith('!'); // `name~=value` is one entry of a comma-separated value (`tweet.fields~=geo`, X's fields lists); `name=value` the whole const body = absent ? part.slice(1) : part; const listed = body.includes('~='); const [path, wanted] = listed ? body.split('~=') : body.split('='); // a part led by `@` names a request header (`@stripe-account&application_fee_amount`, a charge made on a connected // account with the platform's fee) const header = path!.startsWith('@') ? headers?.get(path!.slice(1)) : undefined; // a parameter whose own name holds a dot (X's `tweet.fields`) is read by that name before the path is walked const found = path!.startsWith('@') ? (header === null || header === undefined ? [] : [header]) : Object.hasOwn(params, path!) ? (params[path!] === undefined ? [] : [params[path!]]) : valuesAt(params, path!.split('.')); const asked = wanted === undefined ? found.length > 0 : found.some((value) => (listed ? String(value).split(',').map((entry) => entry.trim()).includes(wanted) : String(value) === wanted)); return absent ? !asked : asked; })); } /** The manifest's gap, as a variant is answered: the unknown-request refusal (else its not-found). */ function variantGap(m: DerivedManifest, request: Request): Response { const nf = m.notFound; const gap: ErrorSpec = m.gap ?? { status: nf.status, message: nf.message, ...(nf.code !== undefined ? { code: nf.code } : {}), ...(nf.kind !== undefined ? { kind: nf.kind } : {}) }; return vendorError(m, { ...gap, message: gap.message.replace(/\{method\}/g, request.method).replace(/\{path\}/g, new URL(request.url).pathname) }); } /** The derived core as the dispatch's core: it owns every operation on a resource the manifest declares. */ export function coreFor(m: DerivedManifest, scope: CoreScope = {}): { owns: (o: DerivedOperation) => boolean; serve: (call: DerivedCall) => Promise } { prepareViewOmissions(m); const crud = new Set(['create', 'retrieve', 'list', 'update', 'delete']); const owns = (o: DerivedOperation): boolean => { const decl = o.resource !== undefined ? m.resources[o.resource] : undefined; if (!decl || m.unmodeled?.includes(o.id) || (o.class === 'list' && !m.list)) return false; if (crud.has(o.class)) return true; return o.class === 'action' && Object.values(decl.state ?? {}).some((f) => f.transitions.some((t) => t.operation === o.id)); }; return { owns, serve: (call) => serveCore(m, call, scope) }; } // ── what every moved operation gets ────────────────────────────────────────────────────────── const hex = (s: string): string => Array.from(new TextEncoder().encode(s), (b) => b.toString(16).padStart(2, '0')).join(''); /** Read-only refusal, API-version validation and idempotent replay, applied once around every * operation a handler or the core serves. */ /** The vendor's refusal of a request's credential under the manifest's `auth`, or undefined when it passes: what the * cross-cutting gate answers for an operation, and what a pack whose vendor checks the credential before routing (an * unknown path answers 401, as Supabase's recording shows) calls in front of its dispatch. */ /** The header the kernel names a scenario's decision in, set by createPackFetch alone (it strips it from every request it * is sent). */ export const SCENARIO_DECISION_HEADER = 'x-volter-scenario-decision'; /** HTTP field values are bytes; JSON escapes retain Unicode without putting it directly in a header. */ export function scenarioDecisionHeader(decision: ScenarioDecision): string { return JSON.stringify(decision).replace(/[\u007f-\uffff]/g, (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, '0')}`); } /** The header createPackFetch alone names a placed `failed` fault in (its timeline entry), so it lands where the vendor * fails: inside its idempotency layer (crossCutting). Stripped from every request the twin is sent. */ export const SCENARIO_FAULT_HEADER = 'x-volter-scenario-fault'; /** A request fault's status answer, in the vendor's own error envelope. */ export function faultError(m: DerivedManifest, fault: PlacedFault): Response { const placed = kernelFault(fault) as ScenarioStatusFault; const refused = vendorError(m, { status: placed.status, code: placed.errorType ?? 'twin_fault', message: placed.message! }); if (placed.retryAfterSeconds !== undefined) refused.headers.set('retry-after', String(placed.retryAfterSeconds)); return refused; } function scenarioDecisionOf(request: Request): ScenarioDecision | undefined { const raw = request.headers.get(SCENARIO_DECISION_HEADER); if (!raw) return undefined; try { return parseExactJson(raw) as ScenarioDecision; } catch { return undefined; } } /** Where the manifest's `auth` reads a credential: its header and scheme, then each `also`. */ const credentialSources = (m: DerivedManifest) => (m.auth ? [{ header: m.auth.header, scheme: m.auth.scheme } as { header?: string; scheme?: string; query?: string }, ...(m.auth.also ?? [])] : []); /** The credential a request presents where the manifest's `auth` reads it (the first source that holds one), else, for a * manifest that declares none, its Authorization header; '' when it presents none. */ export function presentedCredential(m: DerivedManifest, request: Request): string { if (!m.auth) return (request.headers.get('authorization') ?? '').trim(); const url = new URL(request.url); const keyOf = (s: ReturnType[number]): string => { if (s.query !== undefined) return (url.searchParams.get(s.query) ?? '').trim(); const raw = s.header ? request.headers.get(s.header) : null; if (raw === null) return ''; if (!s.scheme) return raw.trim(); const scheme = `${s.scheme.toLowerCase()} `; return raw.toLowerCase().startsWith(scheme) ? raw.slice(scheme.length).trim() : ''; }; return credentialSources(m).map(keyOf).find((k) => k !== '') ?? ''; } export function authRefusal(m: DerivedManifest, request: Request, root?: string): Response | undefined { if (!m.auth) return undefined; const url = new URL(request.url); if (m.auth.paths !== undefined && !new RegExp(m.auth.paths).test(url.pathname)) return undefined; const wire = m.auth.wires?.find((w) => new RegExp(w.paths).test(url.pathname)); const errorManifest = wire ? { ...m, error: wire.error } : m; const invalid = wire?.invalid ?? m.auth.invalid; const missing = wire?.missing ?? m.auth.missing; const sources = credentialSources(m); const given = sources.map((s) => (s.query !== undefined ? url.searchParams.get(s.query) : s.header ? request.headers.get(s.header) : null)).some((v) => v !== null); if (!given && !m.auth.gateWhenAbsent) return undefined; const key = presentedCredential(m, request); // no credential sent is `missing`; one sent in a form the vendor does not read is a key it does not know if (!key) return vendorError(errorManifest, given ? invalid : missing); if (m.auth.invalidKeys.includes(key) || (m.auth.keyFormat && !new RegExp(m.auth.keyFormat).test(key))) return vendorError(errorManifest, invalid); const held = m.auth.held; if (held && !held.standing?.includes(key)) { const hash = sha256(key); const holds = (held.storedAs !== undefined && stored(m, held.storedAs, root).some((r) => r.deleted !== true && (r as Record)[held.hashField] === hash && (held.unless === undefined || (r as Record)[held.unless] !== true))) || (held.issued?.includes(issuedKeyOf(m, key, root)?.purpose ?? '') ?? false); if (!holds) return vendorError(errorManifest, invalid); } return undefined; } /** The number of answers a World has given that carried a filled answer header (`answerHeaders`'s `{hex:N}`), kept in * the World's own directory beside its rate-budget ledger (bookkeeping, never a log entry): a fresh World counts from 1, * so two Worlds made alike answer the same values in the same order, and a resumed World counts on, never answering a * value the count holds again. A World with no root (an in-memory walk) counts in this process. */ const answeredInMemory = new Map(); function nextAnswer(service: string, root: string | undefined): number { const key = `${service}:${root ?? ''}`; if (root === undefined) { const n = (answeredInMemory.get(key) ?? 0) + 1; answeredInMemory.set(key, n); return n; } const store = getActiveWorldStore(); const path = `${worldPaths(service, root).dir}/answer-count`; // a read-only request writes nothing, bookkeeping and its lock included, and reads the count without the lock: it // counts on in this process past the kept count, so after a restart, or from another process serving the same World, // the answers given to read-only requests since the last write may be given again if (writesRefused()) { const kept = Number(store.read(path) ?? '0') || 0; const extra = (answeredInMemory.get(key) ?? 0) + 1; answeredInMemory.set(key, extra); return kept + extra; } // read and written under the count's lock, as the rate-budget ledger is: two writes from processes serving one World never // take one number return store.withLock(`${path}.lock`, () => { const n = (Number(store.read(path) ?? '0') || 0) + (answeredInMemory.get(key) ?? 0) + 1; answeredInMemory.delete(key); store.writeAtomic(path, String(n)); return n; }); } export function crossCutting(m: DerivedManifest, opts: CoreScope & { readOnly?: boolean } = {}): (call: DerivedCall, next: () => Promise) => Promise { const finish = async (r: Response, request: Request): Promise => { if (!m.origin || !(r.headers.get('content-type') ?? '').includes('json')) return withHeaders(r); const text = (await r.text()).replaceAll(m.origin.placeholder, twinPublicBase(request)); return withHeaders(new Response(text, { status: r.status, statusText: r.statusText, headers: r.headers })); }; const withHeaders = (r: Response): Response => { if (!m.answerHeaders) return r; const headers = new Headers(r.headers); const world = `${m.service}:${opts.root ?? ''}`; let seed: string | undefined; const filled = (v: string): string => v.replace(/\{hex:(\d+)\}/g, (_, w: string) => { seed ??= `${world}:answer:${nextAnswer(m.service, opts.root)}`; let hex = ''; for (let i = 0; hex.length < Number(w); i++) hex += sha256(`${seed}:${i}`); return hex.slice(0, Number(w)); }); for (const [k, v] of Object.entries(m.answerHeaders)) if (!headers.has(k)) headers.set(k, filled(v)); return new Response(r.body, { status: r.status, statusText: r.statusText, headers }); }; const idempotent = idempotencyLayer(m, opts); return async (call, next) => finish(await guarded(call, next), call.request); async function guarded(call: DerivedCall, next: () => Promise): Promise { const { request } = call; const refused = m.auth?.exempt?.includes(call.operation.id) ? undefined : authRefusal(m, request, opts.root); if (refused) return refused; // a read-only twin refuses writes: what the operation does, not the HTTP verb it came by (an RPC // wire POSTs its reads). A read-only REQUEST (x-volter-read-only, request-scope.ts) is refused the // same way, up front, on a writable twin. const readOnly = opts.readOnly || isReadOnlyRequest(request); if (readOnly && !['retrieve', 'list', 'computed'].includes(call.operation.class) && !m.reads?.includes(call.operation.id)) return vendorError(m, m.readOnly); // a body labelled JSON that does not parse is the vendor's refusal, never a crash of the twin // (`json: 'always'` reads the vendor's JSON bodies whatever their label, never an operation its spec declares // multipart or form: Cloudflare's asset and script uploads) const declared = call.operation.bodyEncoding; const labelled = request.headers.get('content-type') ?? ''; if (!bytesPayload(call.operation) && ((labelled.includes('json') && !labelled.includes('ndjson') && !labelled.includes('connect+')) || (m.body.json === 'always' && declared !== 'multipart' && declared !== 'form'))) { const ok = request.method === 'GET' || request.method === 'HEAD' ? true : await checkJsonBody(request.clone()).catch(() => true); if (!ok) return vendorError(m, m.malformedBody ?? { status: 400, message: 'The request body could not be parsed as JSON.' }); } if (m.version) { const value = request.headers.get(m.version.header); if (value && !new RegExp(m.version.pattern).test(value)) return vendorError(m, { ...m.version.error, message: String(fill(m.version.error.message, { value })) }); } // a cursor past the vendor's retention is refused before the operation reads it const expired = await cursorExpired(m, call, opts.root, (opts.clock ?? worldNow)()); if (expired) return vendorError(m, expired); return idempotent(call.request, next, { operation: call.operation, readOnly }); } } type IdempotencyWhere = { operation?: DerivedOperation; readOnly: boolean; graphql?: boolean }; /** The vendor's idempotency layer around one request (`next` answers it). A `failed` the World's scenario placed * (SCENARIO_FAULT_HEADER) lands in the operation's place inside it: kept under the request's key with its answer, and * replayed to a repeat with that key as the vendor keeps a failure; its record is the log's where a key keeps it, * else the request journal's (nothing else of the request is written). `graphql`: the request is a GraphQL document, * whose mutations alone are keyed. */ function idempotencyLayer(m: DerivedManifest, opts: CoreScope = {}): (request: Request, next: () => Promise, where: IdempotencyWhere) => Promise { return async function idempotent(request, next, where) { const { readOnly, operation } = where; const operationId = operation?.id ?? 'graphql'; const at = (opts.clock ?? worldNow)(); const entry = Number(request.headers.get(SCENARIO_FAULT_HEADER)); const failure = entry ? placedFaults(m.vendor, 'request', at).find((f) => f.index === entry && f.kind === 'failed') : undefined; const served = async (kept: boolean): Promise => { if (!failure) return next(); await recordFault(serviceLedger({ vendor: m.vendor, service: m.service, root: opts.root, at, recording: !readOnly, reads: !kept }), failure, { operation: operationId }); return faultError(m, failure); }; const decl = m.idempotency; if (!decl || !(decl.methods ?? ['POST']).includes(request.method.toUpperCase())) return served(false); // a header key the request does not send is no key: its body is not read const header = decl.key ? ('header' in decl.key ? decl.key.header : undefined) : decl.header; if (header !== undefined && !request.headers.get(header)) return served(false); const url = new URL(request.url); const text = await bodyTextOf(request.clone()); if (where.graphql && !graphqlMutation(text)) return served(false); const signature = hashFieldValue({ path: url.pathname + url.search, body: text }); const key = idempotencyKeyOf(decl, request, text, signature); if (key === undefined) return served(false); const credential = decl.scope === 'credential' ? presentedCredential(m, request) : undefined; const id = credential === undefined ? `idem_${hex(key)}` : `idem_${sha256(`${credential}\u0000${key}`)}`; const type = storedType(m, decl.storedAs); const held = twinResources(m.service, opts.root).find((r) => r.type === type && r.id === id) as Record | undefined; // a key kept past the vendor's retention is gone: the request is a new one const keptAt = held ? Date.parse(String(held.recordedAt ?? held.updatedAt)) : NaN; const prior = held && !(decl.keptFor !== undefined && Date.parse(at) - keptAt >= durationMs(decl.keptFor)) ? held : undefined; if (prior) { if (decl.conflict && prior.requestHash !== undefined && prior.requestHash !== signature) return vendorError(m, decl.conflict); const answer = prior.response as { status: number; body?: unknown; text?: string; contentType?: string }; if (typeof decl.replay === 'object') return vendorError(m, decl.replay.error); const made = prior.subject as { resource: string; id: string } | undefined; if (decl.replay === 'subject' && made && operation) { const row = stored(m, made.resource, opts.root).find((r) => r.id === made.id); if (row) return Response.json(envelope(m, operation, view(m, made.resource, pendingAt(m, made.resource, opts.root, at)(row))), { status: answer.status }); } // a streamed answer replays as the stream it was; a record kept before text was kept replays its JSON return answer.text !== undefined ? new Response(answer.text, { status: answer.status, headers: { 'content-type': answer.contentType ?? 'application/json' } }) : Response.json(answer.body, { status: answer.status }); } // a read-only request replays a stored answer but records none: recording is a write if (readOnly) return served(false); // a repeat while the first with its key is in progress is answered as the vendor answers it, where it declares one const flight = `${m.service}\u0000${opts.root ?? ''}\u0000${type}\u0000${id}`; if (decl.inProgress) { if (keysInProgress.has(flight)) return vendorError(m, decl.inProgress); keysInProgress.add(flight); } try { const response = await served(!decl.onlySuccess); if (decl.onlySuccess && (response.status < 200 || response.status >= 300)) return response; const contentType = response.headers.get('content-type') ?? 'application/json'; const answered = await response.clone().text(); const subject = decl.replay === 'subject' && operation?.resource ? subjectOfAnswer(answered, decl.subjectId ?? 'id') : undefined; await applyTwinWrite(m.service, { operation: 'idempotency.record', subjectType: type, subjectId: id, fields: { response: { status: response.status, text: answered, contentType }, requestHash: signature, recordedAt: at, ...(decl.replay === 'subject' ? { subject: subject === undefined ? null : { resource: operation!.resource!, id: subject } } : {}) }, occurredAt: (opts.clock ?? worldNow)(), actor: { kind: 'system' } }, opts.root); return response; } finally { if (decl.inProgress) keysInProgress.delete(flight); } }; } /** The keys a request holds while it is in progress in this process, for an idempotency layer that answers a * concurrent duplicate (IdempotencyDecl.inProgress). */ const keysInProgress = new Set(); /** A request's idempotency key where its vendor reads it, or undefined for a request that sends none. */ function idempotencyKeyOf(decl: IdempotencyDecl, request: Request, text: string, signature: string): string | undefined { const source: IdempotencyKeySource = decl.key ?? { header: decl.header! }; if ('header' in source) return request.headers.get(source.header) || undefined; if ('content' in source) return signature; const body = parsedBody(text, request.headers.get('content-type') ?? ''); if (source.when && !sameValue(parentField(body, source.when.body), source.when.equals)) return undefined; const value = parentField(body, source.body); if (value === undefined || value === null || value === '') return undefined; return typeof value === 'string' ? value : JSON.stringify(value); } const sameValue = (a: unknown, b: unknown): boolean => a === b || JSON.stringify(a) === JSON.stringify(b); /** A request body as fields: JSON, else a form's fields (bracket names kept as sent), else none. */ function parsedBody(text: string, contentType: string): Record { if (!text) return {}; if (contentType.includes('x-www-form-urlencoded')) return Object.fromEntries(new URLSearchParams(text)); try { const parsed = parseExactJson(text); return parsed && typeof parsed === 'object' ? parsed as Record : {}; } catch { return {}; } } /** Whether a GraphQL request's document runs a mutation: its named operation's, else its first operation's keyword. */ function graphqlMutation(text: string): boolean { const body = parsedBody(text, 'application/json') as { query?: unknown; operationName?: unknown }; if (typeof body.query !== 'string') return false; const document = body.query.replace(/#[^\n]*/g, ''); if (typeof body.operationName === 'string' && body.operationName) return new RegExp(`\\bmutation\\s+${body.operationName.replace(/[^_A-Za-z0-9]/g, '')}\\b`).test(document); return /^\s*mutation\b/.test(document); } /** The id an answer names at a dotted path (its envelope's key included, `data.id`). */ function subjectOfAnswer(text: string, path: string): string | undefined { const value = parentField(parsedBody(text, 'application/json'), path); return typeof value === 'string' || typeof value === 'number' ? String(value) : undefined; } /** The vendor's error for a request whose cursor (manifest `cursors`) names a subject made longer ago than the vendor * keeps it, else undefined. */ async function cursorExpired(m: DerivedManifest, call: DerivedCall, root: string | undefined, at: string): Promise { const decl = m.cursors?.[call.operation.id]; if (!decl) return undefined; const url = new URL(call.request.url); const bodyValue = async (): Promise => (call.request.method === 'GET' || call.request.method === 'HEAD' ? undefined : parentField(parsedBody(await bodyTextOf(call.request.clone()), call.request.headers.get('content-type') ?? ''), decl.param)); const value = call.params[decl.param] ?? url.searchParams.get(decl.param) ?? await bodyValue(); if (value === undefined || value === null || value === '') return undefined; const field = decl.field ?? 'id'; const hit = stored(m, decl.resource, root, { withDeleted: true }).find((r) => String((r as Record)[field]) === String(value)); if (!hit) return undefined; const made = subjectHistory(m.service, { type: hit.type, id: hit.id }, root)[0]; if (!made) return undefined; return Date.parse(at) - Date.parse(made.occurredAt) > durationMs(decl.keptFor) ? decl.error : undefined; } /** The vendor's idempotency layer (crossCutting's) around a request no surface operation names: a GraphQL wire's, whose * mutations it keys as the manifest declares. */ export function graphqlIdempotency(m: DerivedManifest, opts: CoreScope & { readOnly?: boolean } = {}): (request: Request, next: () => Promise) => Promise { const layer = idempotencyLayer(m, opts); return (request, next) => layer(request, next, { readOnly: opts.readOnly === true || isReadOnlyRequest(request), graphql: true }); } /** A derived pack's whole fetch behind the kernel's read scope (twin-fetch.ts withRequestScopes): a * read-only request's writes are refused at the write seam — the ones `crossCutting` cannot see * coming (another wire's mutation, a door, a screen) — and answered with the vendor's own read-only * error; `GET /twin` advertises `requestScopes`. The pack's catch-up runs under `runAsVendorMove` * (request-scope.ts), so time's moves still land when a read-only request is what arrives. */ export function derivedRequestScopes Promise>(m: DerivedManifest, fetch: F, readOnly = false): F { return withRequestScopes(fetch, { readOnly, refuse: () => vendorError(m, m.readOnly) }); } /** A semantics context for a request no surface operation names: another wire's (GraphQL) resolvers * get the same interface as a handler, named by the operation id the wire gives. */ export function semanticsContext(m: DerivedManifest, request: Request, operation: DerivedOperation, scope: CoreScope = {}): Promise { return contextFor(m, { request, operation, params: {} }, scope); }