@formancy/data-client
v0.3.0
Published
The browser's side of Formancy Data's runtime plane: a fetch-based client for a published form's records and lookups, and option sources both formancy renderers take. Framework-neutral, no Node.
Readme
@formancy/data-client
The browser's side of Formancy Data's runtime plane: one function per route for the forms a person may read, a published form's definition, records and lookups, option sources that both formancy renderers take, and a refusal's field problems in the shape a form engine applies them (0029).
Framework-neutral and fetch-based. It uses no Node API — the package's own
type check has no Node types, so a node: import does not compile — and runs
wherever fetch and AbortSignal exist.
Licence. Source-available under the Formancy Data licence in
LICENSE.md, like every package in this repository; see the
licence table in the repository README. It depends on the
Apache-2.0 @formancy/spec for types only.
What it exports
createDataClient({ token, base?, fetch? }) // → { forms, form, read, list, exportRecords, create, update, delete, reconcile, query, resolve }
isUnknownWrite(outcome) // → whether a create, update or delete's outcome is an UnknownWrite
lookupSources(client, formId, form, operation | () => operation) // → { [source]: { resolve, maxRows } }
sourceNames(form) // → every optionsSource the document names, once each, in document order
fieldProblems(refusal) // → { [field]: [sentence, …] }, for engine.applyServerErrorsEvery client function resolves to an Outcome: { ok: true, value } or a
Refusal — { ok: false, status, code, message, fieldErrors? }. It rejects
only for an abort the caller asked for, with the AbortError it raised.
create and update resolve to a WriteOutcome, which is that or an
UnknownWrite — see below; delete to a DeleteOutcome, the server's
{ record, deleted: true } or a refusal, or an UnknownWrite.
| Function | Route |
|---|---|
| forms(signal?) | GET /v1/forms → { forms: [{ id, title, operations, children }] } |
| form(formId) | GET /v1/forms/:id → { form, operations, readable, list, deleting } |
| read(formId, record) | POST /v1/forms/:id/records/read |
| list(formId, query?, signal?) | POST /v1/forms/:id/records/list → { rows, hasMore } |
| exportRecords(formId, query?, signal?) | POST /v1/forms/:id/records/export → { file, name }, a Blob of CSV and <form id>.csv |
| create(formId, answers) | POST /v1/forms/:id/records/create |
| update(formId, { record, version, answers }) | POST /v1/forms/:id/records/update |
| delete(formId, { record, version }) | POST /v1/forms/:id/records/delete → { record, deleted: true } |
| reconcile(formId, unknown) | POST /v1/forms/:id/records/read, or nothing when there is no token |
| query(formId, source, { operation, search, offset?, limit? }, signal?) | POST /v1/forms/:id/lookups/:source/query |
| resolve(formId, source, { operation, tokens }, signal?) | POST /v1/forms/:id/lookups/:source/resolve |
The reply types — FormMenu, FormMenuEntry, FormMenuChild,
PublishedForm, FormRecord, RecordList, RecordListQuery,
RecordExportQuery, ListSortTerm, ListColumns, LookupResult,
LookupRow, FieldError — and LIST_PAGE_SIZE, EXPORT_MAX_BYTES and
exportFileName are re-exported from
@formancy/data-core, where the server's handlers are checked against the
same declarations. A form's list
is null when the server would refuse this person a page, and otherwise
says which fields a page may be searched and sorted by
(0044);
a form reply without one is unexpected, as from a server older than
lists. list sends exactly search, sort, parent, offset and limit
in a POST body, each left out the server's default, so the search is in no
URL. A form's deleting says what a delete also does -- whether it
cascades, clears references, or may be refused while other rows refer to
the record -- for a page to word its confirmation by, and is null
exactly when operations holds no delete; a reply that breaks that is
unexpected, as is one without deleting from a server older than
deletes, so a host upgrades its server first
(0050).
delete sends exactly record and version, with a write id of its own,
and is done only on the server's { record, deleted: true }, whose token
is the row the statement deleted.
exportRecords is the file of every record list would page through for
the same search, sort and parent, the three keys it sends, in a POST
body
(0079).
It resolves to a RecordFile, { file, name }: the server's bytes as a
Blob, byte-order mark included, and <form id>.csv, taken from the form's
id and not from content-disposition, which a page on another origin cannot
read (0060); exportFileName(formId) is that name, for a page that says it
before the file arrives, as the host page's Download CSV does
(0080).
The server makes the file whole or refuses it with its own
code -- export-too-large past EXPORT_MAX_BYTES, export-timeout,
export-busy, moved, unencodable among them -- and the client adds two
of its own: a 200 that is not text/csv is unexpected, and a body that
did not arrive whole -- the connection cut, fewer bytes than the server
announced, which fetch refuses -- is incomplete, never a shorter file.
It asks for text/csv, application/json, an accept value CORS counts as
safelisted, so the preflight a cross-origin export sends anyway -- for its
authorization and its JSON content-type -- need not grant it, and the
server's allowed request headers are unchanged. An abort rejects with the
AbortError.
Saving the Blob is the host's: an object URL and an <a download>.
forms is the menu
(0045):
the forms the server says this person may read, each with its title, the
operations its policy grants them as published, and its children -- a
child form and the lookup field its rows name this form's records by, so a
host lists one record's children with
list(child.form, { parent: { field: child.field, record } }). The server
asks no database for it: form(formId) says what the database allows now,
and can still refuse a form the menu named. An answer whose entries lack
a title, operations or children is unexpected.
The rules it keeps for a host
- The token is the host's, per request.
token()is called once for every request and its answer goes inAuthorization: Bearer …and nowhere else — not a URL, not a body, not storage. A host whose session renews the token is never answered for the old one. - Same origin, or a listed one.
basedefaults to'', the page's own origin: served from the server's origin, or through a proxy on the page's own (0024). A page on another origin setsbaseto the server's, and is answered only when the server's operator lists the page's origin exactly inFORMANCY_DATA_CORS_ORIGINS(0060); otherwise every call is a refused preflight, a readunreachableand a write unknown though nothing was sent, and only the server's log says why. Across origins the client sends only headers the server grants --authorization,content-typeandformancy-write-id, andaccept, which a browser sends without asking -- and asks for no credentials: afetchthe host passes must not add a header or setcredentials: 'include', which the server never allows. - A name is one path segment. A form id or a source name is
encodeURIComponent'd into one segment under the form's routes. Empty,.and..cannot be one —fetchwould resolve them to another route — and are refused asinvalid-namebefore any request or token is made. A document decides which names exist, and never a URL, a header, a token, a tenant or an operation (formancy.ai 0077, 0012). - Refusals are the server's, verbatim. The client adds words only when
the server said none:
unreachable(status 0) when nothing answered,unexpectedwhen what answered was not the data server's shape — a proxy's HTML page, a redirect, a captive portal's200. A refusal with a sentence and no code ishttp-<status>. - An abort stops the lookup in the database. The signal a renderer
passes a source, or a host passes
queryandresolve, aborts the request; the server notices its client left and stops the statement it started, on both engines, and the call rejects with the AbortError (0061). A search that runs past the server's deadline is refused 503lookup-timeout, whose sentence says the same search will take as long again, whereunavailableinvites another try; a resolve past it isunavailable, since trying again helps a read by key. A source rejects with either, and a renderer shows "could not be loaded". The 499abandonedthe server answers an abandoned lookup reaches nobody: it is the audit trail's. - A search says whether its list goes on, never how long it is
(0085).
A source answers a search with one page,
{ options, more, withheld }:moreexactly when the server read a row past the page,withheldthe matching rows whose key does not fit a token, which the server counts asomittedand cannot offer (0012). A label request answers the rows it names, as a list. Each source'smaxRowsisDEFAULT_MAX_PAGE_SIZE, the largest page the runtime plane answers a lookup, so a renderer asks for and shows exactly that page. What a control says of it is the renderer's own (formancy.ai 0177): in an open typeahead "Showing the first 50; there are more — keep typing to narrow.", under a plain select "Showing the first 50; there are more than this list can show.", how many matches cannot be chosen here only when the list is complete, and nothing under a closed typeahead or a field a rule disables. formancy 0.6.0's Blueprint theme draws a typeahead's open list over the line its sentence is on, as the other three reference themes' stylesheets place it too, so a sighted person does not read the sentence while the list is open; a screen reader hears it from the line's live region (measured in Chromium and Firefox on 2026-10-18). - A write is known only when the data server says what happened
(0031).
A record, the server's 502
unknown-outcome, a 4xx with a sentence, or a 503unavailable. Anything else — a rejectedfetch, a body that cannot be read or is not JSON, a proxy's 502 or 504, a 500, a 2xx that is not a record — may have reached the database, so it is anUnknownWrite:{ ok: false, status, code: 'unknown-outcome', message, operation, record, version, origin },originbeingdatabase(the server's 502, whoserecordandversionit carries) ortransport(the update's or the delete's own, ornullfor a create).okis false, so a host that checks onlyokfails closed. Nothing is ever sent again.reconcile(formId, unknown)reads what it addressed and saysunchanged(an update's or a deletion's record still at the version sent: saving or deleting again with it is done at most once),changed,present,absent(the read's 404, through this person's read filter: not proof the row is not stored, but creating again is safe, because the key stops a second row; for a deletion, the record is gone, by it or another) orunverifiable(no token, and no request) — or passes on the read's own refusal. On a read, 0029's rules stand: a proxy's page isunexpected. - Every write carries a write id of its own, in the
formancy-write-idheader: 128 random bits fromcrypto.getRandomValues, new for everycreate,updateanddeletecall. Over HTTP/1.1, when a connection the browser reused closes after the server read a write and before any byte of an answer, Chromium and Firefox send it again on their own, below the page; one server process answers that copy with the first one's answer instead of applying it twice (0031). WebKit on Linux sends every write on a new connection and never sends one twice, so there the write is unknown (0058). The client itself still never sends anything again. - Field problems are sentences. The renderers print an error entry as
it is, beside the field and in the error summary, as observed at 0.3.0 on
2026-10-09, at 0.4.0 on 2026-10-10 and at 0.5.0 on 2026-10-11, and read
in 0.6.0's code on 2026-10-18, so
fieldProblemshands them the server's sentence, which never echoes a value. The code stays on the refusal for a program.
In React
import { createFormEngine } from '@formancy/core'
import { ErrorSummary, FormancyForm, FormancyProvider, OptionsSourcesProvider } from '@formancy/react'
import { createDataClient, fieldProblems, isUnknownWrite, lookupSources } from '@formancy/data-client'
const client = createDataClient({ token: () => session.token() })
const published = await client.form('order') // check .ok
const { form } = published.value
let held = { record: undefined as string | undefined, version: '', operation: 'create' as 'create' | 'update' }
const sources = lookupSources(client, 'order', form, () => held.operation)
const engine = createFormEngine({ schema: form, formId: 'order-react', capabilities })
async function save(outcome) {
if (!outcome.ok) return // the engine's own errors are showing
const saved = held.record === undefined
? await client.create('order', outcome.data)
: await client.update('order', { record: held.record, version: held.version, answers: outcome.data })
if (isUnknownWrite(saved)) return showUnknown(saved) // it may have been saved: client.reconcile, never a resend
if (!saved.ok) {
engine.applyServerErrors(fieldProblems(saved)) // {} when the refusal concerns no field
return show(saved.message) // 409 stale: keep the draft and say so
}
held = { record: saved.value.record ?? undefined, version: saved.value.version ?? '', operation: 'update' }
}
<OptionsSourcesProvider value={sources}>
<FormancyProvider engine={engine}>
<ErrorSummary />
<FormancyForm submitLabel="Save" onSubmit={save} />
</FormancyProvider>
</OptionsSourcesProvider>In Angular
import { provideFormancy, provideFormancyOptionsSources } from '@formancy/angular'
const app = await createApplication({
providers: [provideZonelessChangeDetection(), provideFormancy(engine), provideFormancyOptionsSources(sources)],
})The same sources object serves both renderers: each declares its own
OptionsSource on purpose, and a LookupSource is assignable to both, which
a host's type check proves. Angular's providers are fixed once its injector
exists, so the operation is passed as a getter: a form that moves from create
to update asks under update's filter without a new application.
What it does not do
- No cache and no retry. The server asks the policy on every request
(0022),
and a write whose outcome is unknown —
502 unknown-outcome, "may have been saved" — is the host's to reconcile, never the client's to send again (0015). What the browser sends again on its own is answered by the server once per write id, in its process only: a copy that reaches another replica is applied again. - No total. A search's page says that more rows match, never how
many: the server reads one row past the page rather than counting
(0012), and since formancy 0.6.0 a renderer refuses a page that names a
total, as a source that failed. Until 0.6.0 a renderer's option contract
was a list of
{ value, label }, so a list of exactly one page looked complete. Past the page a typeahead narrows as the person types; a plain select cannot, and says so. - Its types are
@formancy/spec0.6.0's.PublishedForm.formis theFormSchemaof the@formancy/specthis package pins exactly (0002), and therespecVersionmay be"4", so a host whose engine is@formancy/core0.3.0 does not compile the React snippet above: TS2322 atcreateFormEngine, measured with TypeScript 6.0.3 andskipLibCheckoff on 2026-10-10, and again against 0.5.0's types on 2026-10-11, when a host whose engine is at 0.4.0 compiled it; 0.6.0'sFormSchemadeclaration is byte-identical to 0.5.0's, compared on 2026-10-18. The document itself is spec 3 (0042), so such a host casts it to its own@formancy/spec'sFormSchema, or moves its renderer to 0.4.0 or later. Nothing here type-checks a 0.3.0 or a 0.4.0 host. - Records are addressed by token only. The definition does not name the
identity columns, so a host keeps the tokens that create, read and lookups
return, or encodes its own key with data-core's
encodeKeyToken. - Error sentences are the server's English. The codes stay on the refusal for a host that translates.
- A source answers for every name the document carries. A host with its own named lists merges maps; a name the server does not know fails closed, as "could not be loaded".
