@crud-api/core
v0.7.0
Published
CRUD API reference implementation: data model, engine, provider contract, field lists, projection, sorting, pagination, patch engines, negotiation
Maintainers
Readme
@crud-api/core
Core of the CRUD API reference implementation: the data model, the createCrudServer engine, the provider contract, field lists, projection, sorting, pagination, patch engines, negotiation, Warnings and the strict policy, and the conformance declaration. It knows no data source and does no I/O; providers (such as @crud-api/memory) and protocol adapters plug into it.
ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.
Usage
import { createCrudServer } from "@crud-api/core";
import { createMemoryProvider } from "@crud-api/memory";
const server = createCrudServer({ provider: createMemoryProvider({ implicitCollections: true }) });
const created = await server.execute({ operation: "create", collection: "orders", resources: [{ total: 10 }, { total: 25 }] });
const page = await server.execute({
operation: "list",
collection: "orders",
query: { format: "text/vnd.unquery.sql", text: "total > 15" },
params: { sort: "-total", limit: 20 },
});
if (page.ok) console.log(page.resources, page.meta.matchedCount);
else console.log(page.error.code, page.error.message);execute never throws for an operation that fails: it returns { ok: false, error, meta }, where error is a CrudError (Base error codes, toProblemDetails for RFC 9457) and meta still carries the negotiated specification versions, representation, Correlation ID, Warnings and, for writes, the Modified Count. createCrudServer throws when the configuration is invalid (an extension enabled twice or missing a required extension, a reused Base code, an extension that needs system storage without one, an extension whose attach refuses the configuration).
The engine
An OperationRequest is protocol-neutral: operation (one of the ten Base operations, or an operation of the list verb an enabled extension adds, such as listByView), collection, the Subject (id, resources, resource, patch, newId, query, and view and viewParams for listByView), params (fields, sort, page, offset, cursor, limit, expectMatch, denyUpsert, custom) and meta (accept, returnPreference, strict, require, correlationId, principal, input, and for asynchronous operations async, asyncContext, waitUntil and onSettled), plus the adapter's warnings. Values are host values of the ECSON model; the core converts nothing and never serializes.
Each operation goes through the steps of the design, and the first failure stops it:
- specification versions (
META_CRUD_RANGE_MATCH); - Output representation (
META_RES_PREFERENCE,META_RES_FALLBACK), then, with an execution hook, the execution mode (ASYNC_SERVER_MATRIX, below), then the Search Query format; - the
authorizehook (ACCESS_DENIED); - the Collection (
COLLECTION_SLUG,COLLECTION_NOT_FOUND,COLLECTION_CREATE_IMPLICIT); - the operation;
- Parameters: field lists (indexes only in the Sorting Parameter,
SORTING_ARRAY_PATH), sorting (SORTING_NULLS), pagination with the smaller maximum of server and provider, unknown Parameters reported asPARAM_IGNORED; - the Subject: Resource IDs, Field names, reserved Fields (
_metawithout Metadata is dropped withFIELD_IGNORED), Client IDs (RES_NO_IDS), patch well-formedness; - the Search Query, parsed with UnQuery and checked against the provider's operators;
- extension hooks (
beforeWrite,afterRead); - the write policy (
WRITE_ATOMIC_STRICT,WRITE_STRICT_LATE_WARNINGS); prepareof every primitive, with the depth check of each Resource to write (a Resource the Server could not answer back inside a list, deeper than 999 levels with the ECSON defaultDEPTH_LIMITof 1000, isINVALID_INPUTwithecsonCode: "DEPTH_LIMIT"; D108), then the strict policy on every Warning collected so far.
Only then does anything get written. When the operation runs asynchronously (below), steps 1 to 8 still run before the answer, so their failures stay synchronous (S87), and steps 9 to 11 run later in the extension's runner. Reads and writes are composed from provider primitives (find, findByIds, insert, replace, remove): writes by query read the exact matched set once and write each Resource by ID, never re-running the filter. Writes on several Resources run in provider.transaction() when the provider has one (all or nothing); without it they are partial in lenient mode (each failure becomes WRITE_FAILED) and fail with UNSUPPORTED before writing under the strict preference, unless it allows WRITE_FAILED.
Options
provider: the data provider.system: the system storage of extensions such as Schema, Views and Async; by default the data provider when it declaressystemCollections, otherwise none.extensions: extension objects (name,spec,versions,requires,before,needsSystemStorage,reservedFields,reservedCollections,errorCodes,warningCodes,parameters,operationsand the hooks below).specs: specifications and versions declared (default{ base: ["0.2.0"] }, plus each extension's).representations: Output representations (default["ecson", "json"]).limits:maxLimit,defaultLimitand UnQueryquerylimits.clock,random: injected time and random source (defaultsDate.nowandcrypto.getRandomValues), used for UUIDv7 Resource IDs and Correlation IDs.generateId: replaces the UUIDv7 generator for new Resource IDs.authorize: returns false to refuse an operation.customParams: Custom Parameters the server recognizes.onError: receives the original of everyINTERNALerror, which never reaches the Client; a throwingonErroris ignored.codec: the ECSON codec (@ecson/corecreateCodec) with the types of the enabled extensions; used for sorting, composite keys and Search Queries, and passed to the provider asctx.codec. Default:createCodec(), the core, References ($rel,Rel) and Error ($error) type sets of@ecson/core0.2.0 (D111). Exposed asserver.codec.
Extension hooks
Extensions (such as @crud-api/metadata, @crud-api/relationships, @crud-api/schema, @crud-api/views and @crud-api/async) plug into the steps above through generic hooks; the decisions that introduced them are D116, D129, D137, D138, D155 and D167.
parameters: extra Parameters ({ name, operations, check?, appliesTo? }), recognized by the listed operations (and, withappliesTo, only on the Collections it accepts), checked in step 6 and given to the extension's hooks inparams.beforeWrite(input, ctx): each Resource about to be written, with its previous state (nullon create, clone, upsert and a write over a placeholder), the extension's Parameters, the clone source and the Client's patch; returns the Resource to write.precondition(input, ctx): the current state of each Resource a write by ID or by query targets, before anything changes; throwing fails the operation.afterRead(input, ctx): the Resources read bygetandlist, with the Parameters and the Client's Projection.ownedValues(input, ctx): a predicate over Field paths whose values the extension reads itself, so FIELDS_NAMES and FIELDS_NO_PREFIXES skip them (Schema owns theschemaField of@schemaand the values underestype).reservedCollectionsandreservedProvider(collection): a provider that serves a reserved Collection (@schema); the whole operation runs with it, its capabilities and its transactions. A claimed name without one isUNSUPPORTED.attach(env): called once when the Server is built, with the data provider, the system storage, the codec, the clock and the enabled extensions (env.extension(name)gives an enabled extension's instance); throwing stops the Server.operations: operations of thelistverb the extension adds ({ name, resolve(input, ctx) }, such aslistByView).resolveturns the Subject into a plan (ListPlan: a filter or a rendered native query, sort keys and a Projection), and the core runs it as alistcombined with the Client's Search Query (and-ed), sort keys (after the plan's) and Projection (intersected,intersectProjections); pagination and the Matched Count count the combined items. Such an operation runs only on data Collections (a reserved name isNOT_FOUND, targetcollection) and recognizes every Parameter oflist. The Client's filter and sort keys may use only Fields the plan's Projection keeps: a hidden path isUNSUPPORTED, rule VIEW_COMBO_UNSUPPORTED, before reading (S85). Declaring a Base operation, a name other thanlistByView(the only extra member ofOperationName), or one name in two extensions, throws when the Server is built.before: extensions that must come after this one inextensions.execution(D167): one enabled extension may declare how operations run asynchronously (two are a constructionError),{ support(operation, collection), accept(input), get(id, meta), watch(id, listener) }.supportanswers"sync","async"or"both", and the core applies the matrix of ASYNC_SERVER_MATRIX tometa.async("prefer","require"or absent; another value isINVALID_INPUT):requireon a sync-only operation and nothing on an async-only one areNEGOTIATION, rule ASYNC_SERVER_MATRIX,data.supported. The hook is asked only about Base and extension list operations with a string Collection; without a hookmeta.asyncis ignored. For an asynchronous run the core validates the request through step 8, then callsaccept({ request, operation, collection, run }), whererun(progress)executes steps 9 to 11 once and resolves with the resultexecutewould have returned (never rejecting), and answers{ ok: true, resources: null, accepted: OperationState, meta }with the Warnings found so far. Under the strict preference, those Warnings fail the final state withSTRICT_WARNINGS, as the synchronous run fails; Warnings an adapter passes in fail at once. A failingacceptisINTERNAL.ExtensionEnv.newUuid()gives the Server's UUIDv7 generator to the extension.@crud-api/asyncimplements it.CollectionInfo.isPlaceholder(resource): a Resource the Collection shows but does not store, which is not a conflict forcreateandclone.HookCtx:warn,warnOnce,clock,principal,codec,stored(the stored form of a Resource),read(collection, ids)(Resources of a data Collection, authorized as agetof the Client),annotate(name, value)(setsmeta.annotations[name]of a successful result, for the Protocols),local(aMapshared by the hooks of one operation) andinput(the Representation the Subject was read in, frommeta.input).
For Protocol adapters
queryis text in a negotiated format ({ format, text }), the same text combined with conditions read elsewhere ({ format, text, and }, whereandis an UnQuery model, such as the query string of an HTTPQUERYrequest), or a model the adapter already built ({ filter }). Limits and the provider's operators apply to the final model; a native format cannot be combined withand(UNSUPPORTED).warningscarries the Warnings the adapter found while reading the request (an unknown control parameter, a condition on a single-Resource endpoint). They come first inmeta.warnings, and under the strict preference the operation fails withSTRICT_WARNINGSbefore any provider call.- Every Warning, whoever reports it (the adapter, an extension, the provider), keeps only the members whose names follow WARN_MEMBER_NAMES (lowercase ASCII letters, digits,
_and-, starting with a letter):docUrlor1xare left out,doc_urlstays, so every Protocol sends a member under the same name (D114).isWarningMemberName(name)tells which names a Client must ignore. server.registerProtocol({ name, warningCodes, errorCodes })registers the codes a Protocol specification defines (CONDITION_IGNOREDfor HTTP). It is idempotent, and throws (registering nothing) on a Base code or a code another extension or Protocol owns.server.descriptionlists the specifications, extensions,customParams,queryFormats(UnQuery JSON, UnQuery SQL, then the provider's) andrepresentations.meta.limitis the page size alistused (the requestedlimit, the maximum it was reduced to, the default limit, ornullfor a page without limit; D97), so an adapter can build the links of the next page (Linkheader fields).meta.inputsays how the Subject was read:"ecson"(the default) or"json"for a plain JSON body (REPR_PLAIN_JSON); Schema validates what the Client sent in that form.meta.annotations(absent when none) carries what extensions annotate on a successful result, for the Protocol to describe it:schema({ collection, version }),compiled(the compiled schemas of a read on@schemawithparams.compiled),view({ collection, name }, alistByViewof a View with aschema) andcompiledViews(the compiledparamsandschemaof a read on<slug>/@viewswithparams.compiledViews).server.operations(Operations, null without an execution hook, D167):get(id, { principal?, correlationId? })resolves{ ok: true, state }or{ ok: false, error }(never rejects) after the host'sauthorize({ operation: "get", collection: "@operations", id, meta }), a refusal beingACCESS_DENIED; an unknown, foreign or expired Operation ID isNOT_FOUND, targetoperation.watch(id, listener)listens to every stored change of a state (progress, completion) and returns the unsubscribe function.support(operation, collection)tells a Protocol what the Server supports for an operation before running it ("sync"for an unknown operation, or when the hook throws, whose error goes toonError, or answers another value).OperationStateis{ id, status: "pending" | "succeeded" | "failed", operation, collection, progress?, createdAt, updatedAt, completedAt?, expiresAt?, pollInterval?, result?, context? }(Unix ms),resultbeing exactly the synchronous result andcontextthe adapter'smeta.asyncContext(JSON it needs to render the result again).meta.waitUntilis the host's (design 7.3), andmeta.onSettled(state)runs after the final state is stored, inside the same task (HTTP callbacks).negotiateExecution(support, declared)is the matrix alone.meta.idslists the canonical IDs written bycreate,clone,patchById,replaceByIdanddeleteById, in Subject order, also withreturnPreference: "minimal"(forLocationheader fields).exceedsDepth(tree, max),DEPTH_LIMITandRESOURCE_MAX_DEPTHbound the bodies and arguments an adapter reads with the same iterative walk the engine uses, so hostile nesting cannot overflow the stack (D108).
Providers
A provider implements Provider (capabilities, collection, listCollections, createCollection, dropEmptyCollection, prepare, execute, transaction, schema, testing; testing.inspectNative optionally tells how a stored value is kept, for the conformance kit). prepare is pure and synchronous: it translates a primitive and reports the Warnings that depend only on the input, so that the core can fail before writing. Both prepare and execute receive the Server's ECSON codec as ctx.codec. A find that sorts reads values with getPath (or sorts natively by the same rules) and reports from execute the SORT_ARRAY_PATH Warnings of sortArrayPathWarnings over every matched Resource (SORTING_ARRAY_PATH). An implicit Collection is created inside the transaction when the transaction object has createCollection; otherwise it is created before the writes and removed again with dropEmptyCollection when the create writes nothing. A provider whose Data source enforces a schema of its own implements schema (ProviderSchemaHooks: ownSchema, acceptsDbType, inferDbType, convertValue, optional deriveSchema) and the applySchema primitive, whose prepare is a dry run and whose execute changes the Data source's schema or fails with SCHEMA_INCOMPATIBLE changing nothing (D138). A provider with a native query language may receive a rendered View query in find (view: { format, query }, RenderedQuery: text segments with the values to bind apart, or a JSON value), whose items the filter, sort keys, projection and page then apply to; nativeCombination: { filter, sort } declares whether it can apply the Client's filter and sort keys to those items (D155). While an operation runs asynchronously, ExecCtx.progress?.(done, total?) is set and the provider may report progress (non-negative integers, total >= done; other values are ignored, ASYNC_PROGRESS); it is absent in synchronous runs. Capabilities declare what the provider can do exactly (operators, pagination, sorting, counts, transactions, ID kinds, native types, implicit and system Collections, lateWarnings); the core rejects anything outside them.
Conformance
conformance declares the CRUD Base specification 0.2.0 with its ten operations and no extension.
