Skip to content

Releases

v0.8.1

Choose a tag to compare

@github-actions github-actions released this 04 Dec 19:32
2bdf330

Fixes for tabs whose local data is gone, and the CLI's deploy advice. No breaking changes.

Fixes

  • A tab whose local data is gone loads again without waiting for another tab.
    • A tab with no stored data downloads its own and is ready once that download is complete. That covers a first visit and IndexedDB deleted or cleared.
    • Before, a tab that wasn't the leader counted itself ready only once the leader reported a successful sync. A leader in a background tab, which browsers throttle or freeze, could keep it loading indefinitely.
    • That download retries with backoff when it fails, and a follower's own download leaves its status as it was rather than "bootstrapping".
  • A bootstrap or pull whose response ends before the server's end marker fails and is retried. That covers a dropped connection or a proxy cutting the stream. Before, what had arrived was taken as complete.
  • A tab taking over as the leader starts syncing even when writing its data to storage fails. It then runs without storage instead of never connecting.
  • clientdb --help matches the deploy docs. It says to run migrate and setup once the new release serves, never in a build while the old release serves.
  • The docs, READMEs and landing page match 0.8.0, and every TypeScript snippet in them is type-checked against the packages in CI.

Published to npm

v0.8.0

Choose a tag to compare

@github-actions github-actions released this 04 Dec 17:45
bf2c31d

Claims are declared values. Breaking for code that uses claims; everything else is unchanged from 0.7.0, and the protocol's session claims map keeps its shape (a value is never a list).

Breaking changes

  • Declare each claim once, in a file the server and the client both import:
    • declareClaim("staff") is yes or no;
    • declareClaim("currentTeam").uuid() holds a UUID;
    • .string() holds any text.
  • Sessions set values by calling the claim: claims: [staffClaim(isStaff), currentTeamClaim(teamId)]. Each call is typed by the claim's kind, and a UUID claim refuses a value that isn't one. A claim left out is false or null.
  • Rules read claims with $.claim(…):
    • $.claim(staffClaim) is a condition;
    • tag.teamId.is($.claim(currentTeamClaim)) compares a column (or a membership row inside some()) with the claim's value;
    • enforce: ($) => ({ teamId: $.claim(currentTeamClaim) }) works too.
  • The engine learns claims from the rules that read them. Two claims of one name with different kinds are refused, and so is a session setting a claim whose kind differs from the one the rules read.
  • Clients read db.$session.claim(currentTeamClaim), typed by its kind. Swift: Claim("currentTeam").uuid() and db.session.claim(_:).
  • Migrating from 0.7.0:
    • drop the schema's claims option, from both createSchema and fromPrisma;
    • replace claim.* builders with declareClaim, $.claims.<name> with $.claim(claim), claims: { name: value } with claims: [claim(value)], and db.$session.claims.<name> with db.$session.claim(claim);
    • claim.idOf, idsOf, strings and list values are gone: use .uuid() or .string();
    • Swift's isGranted, value(of:) and values(of:) are replaced by db.session.claim(_:).

Fixes

  • sequenceNow() drains everything committed before the call, also when another process holds the drain. Change ids are drawn at insert, so a change can commit after one with a later id. A caller that waited for another process's drain could find nothing past the last drained id and return with its own change still queued; it went into the log only with the next drain. The leader's idle check had the same blind spot. Nothing was lost.

Published to npm

v0.7.0

Choose a tag to compare

@github-actions github-actions released this 04 Dec 17:20
6da4ea8

Claims with values, server logic in the client's transaction, refusals in the app's words, open tabs that survive deploys, and connections no slow download can hold. Two breaking changes, in the claims API and the client; the session's claims changed shape in the protocol, so update clients and server together.

Breaking changes

  • Claims hold values and are declared in the schema. createSchema(models, { claims: { staff: claim.boolean(), currentTeam: claim.idOf("team") } }) (also fromPrisma(datamodel, { claims })); the session callback sets claims: { staff, currentTeam }; rules read $.claims.staff and compare columns with $.claims.currentTeam. declareClaim, $staff(…) grants and db.$session.hasClaim are removed; read db.$session.claims.<name>. The protocol's session claims is now a map. Swift: db.session.isGranted(_:), value(of:), values(of:).
  • db.$viewerId replaces db.$session.viewerId.

Features

  • Server logic in the same transaction:
    • createEngine({ transaction }), with prismaTransaction(prisma, …) from @clientdb/prisma (Prisma 5, 6 and 7), writes a device's change in a transaction you open;
    • beforeCommit(writes, $) sees every row it wrote and can write more, or refuse;
    • $.afterCommit(work) runs after the commit.
  • Refusals in your words:
    • createEngine({ messages: defineMessages(schema, { conflict, forbidden, fallback }) }) words what devices are told;
    • duplicates are matched by unique key through Postgres's catalog;
    • TransactionRejected(code, message) refuses from beforeCommit with your message;
    • composite unique keys come from the unique model option or Prisma's @@unique.
  • Deploys and open tabs:
    • clients and server exchange per-model hashes, and the server sends each client only the models it knows;
    • db.$version is "current", "updateAvailable" (the server only added models; the client keeps working) or "reloadRequired" (a model it uses changed: writes throw and onReloadRequired asks to reload);
    • Swift: db.version and SyncOptions(onReloadRequired:);
    • the deploy docs now run setup when the new release starts serving, not in the build.
  • fromPrisma:
    • sync: [...] lists the models that sync, and syncAuthModels replaces include;
    • models.<Model>.unique declares keys schema.prisma can't;
    • the types now refuse everything startup refuses, including fields of schema.prisma that can't sync and calls without options.
  • validate is typed by model.
  • onError on the fetch and Next.js handlers and on createSyncServer.
  • The permission helpers on $ can be destructured without lint errors.

Fixes

  • Slow or abandoned downloads hold no database connection:
    • a bootstrap reads each page in its own short transaction;
    • a pull commits before it sends;
    • a stream whose device takes nothing for 60 s is ended (downloadIdleTimeoutMs);
    • the Node server no longer leaks close listeners.
  • indexedDb() storage can't hang:
    • opening, loading and writing time out after 10 s;
    • a load that can't read what is stored downloads afresh;
    • other tabs' upgrades and deletes never block.
  • The capture trigger ignores updates that change only columns that don't sync.
  • npx clientdb setup explains a missing generated module, the usual monorepo mistake.

Published to npm

v0.6.3

Choose a tag to compare

@github-actions github-actions released this 04 Dec 10:53
e46b5bd

Prisma 5 and 6 support. No breaking changes.

Features

  • @clientdb/prisma works with Prisma 5, 6 and 7, with no workaround.
    • The generator speaks Prisma's generator protocol itself, and the package depends on none of Prisma's packages. prisma is an optional peer (5 or later), so a Prisma 5 app gets nothing of Prisma 7 installed.
    • Prisma 5's DMMF is converted in its own module: @db.* native types are read from the schema source (every file of a multi-file schema), and uuid(4)-style default names read as uuid().
    • Without the generator, datamodelSubset(dmmf, { schema }) takes the schema source for a Prisma 5 DMMF.
  • The generator stops with a clear error for a datasource that isn't PostgreSQL and for Prisma older than 5.

Fixes

  • npx clientdb setup and migrate read .env.local and .env from the working directory, as the Prisma CLI does. Variables already set win.

Published to npm

v0.6.2

Choose a tag to compare

@github-actions github-actions released this 04 Dec 10:28
10075de

Fixes for sessions that change while a client is connected. No breaking changes, and no new options; 0.6.x clients and servers talk to each other.

Fixes

  • $sync() no longer loops after a claim is removed on an idle database. The pull that removed the claim ended at the position it started from, and the client waited for a later position before trusting any answer, so it asked /partial and /revalidate again forever. The token change now takes the position the pull ends at. The Swift client has the same fix.
  • An open socket follows the session the client's requests resolve. A socket keeps the credentials it opened with, for example the cookie from before a switch from an admin token to a plain one for the same user.
    • The server closes a client's socket with code 4409 and routes nothing more to it when a read, pull or push from that client resolves another session. Reads now carry clientId.
    • The client also reconnects its socket when an answer names other tokens than its stream gave it, at most once every 10 seconds. This covers a socket on another instance, and it fetches a new sync token first. The Swift client does the same.
  • A session revoked on the server (an allowlist change, a revoked session) while the client is idle is applied at the socket's next session check, every token lifetime (300 s by default). A demotion evicts the claim's rows; a null session closes the socket with 4401.

Published to npm

v0.6.1

Choose a tag to compare

@github-actions github-actions released this 04 Dec 09:33
4a315c8

Fixes and the 0.6.0 regressions. No breaking changes; 0.6.0 and 0.6.1 clients and servers talk to each other.

Fixes

  • $sync() no longer loops on POST /revalidate after a session claim is removed (for example claim:staff, when the session is re-resolved on a later request). Answers remove tokens the client no longer has; answers to requests sent before a token change are asked again; a pull ends with the session's token changes. A token gain's revalidation names the tokens the client held before it (heldBefore).
  • Setup no longer deadlocks with writes in progress. It locks the synced tables first and retries on deadlock, serialization failure or lock timeout.
  • fromPrisma accepts models.<Model>.relations.<relation>.mayBeUnreadable at runtime.
  • The readability proof accepts narrower memberships (a rule readable by members or admins, where admins are members), so it no longer warns falsely.
  • A child deleted just before its parent moved or was deleted reaches every client that read it through the parent.
  • @clientdb/prisma's BigInt notice goes to stderr.

Performance (one 4-core VM, local Postgres 16)

  • Promote / demote / move-out on a client: 108 / 54 / 14 ms → 51–57 / 20–27 / 3.9–4.9 ms (bench:access; 0.5.0: 52 / 19 / 3.9). Client access evaluation is incremental.
  • One process serves 20,000 WebSockets (p50 5.6–15.4 ms at 300 writes/s; 0.6.0 saturated at 323 ms), with about a third less memory per connection.
  • Polling server CPU at 5,000 / 10,000 clients: 72–76% / 98–102% → 56% / 77%.
  • Postgres CPU per write while the engine drains: 0.35 → 0.21 ms (0.5.0: 0.23); 10,500–10,766 concurrent upserts/s.
  • Serverless throughput with 8 instances: 650 → 920–1,050 pushes/s (0.5.0: 1,184).

Published to npm

v0.6.0

Choose a tag to compare

@github-actions github-actions released this 03 Dec 22:28
264545f

A new sync engine (wire protocol v3, see spec/protocol.md and spec/replica.md): no migrations, every write to a synced table syncs, access compiled into tokens and an access plan that clients evaluate, revalidation with digests instead of reloads, and lazy clients that receive only what they hold. 0.5 and 0.6 clients and servers don't talk to each other, and stored client data (IndexedDB, Swift SQLite) is fetched again once.

Breaking changes

  • No clientdb tables or models in your schema. The engine keeps its bookkeeping in its own Postgres schema, clientdb, and installs one capture trigger per synced table when it first starts (createEngine({ setup: "auto" }), the default). npx clientdb setup <module> does it from a deploy step; --print-sql prints the SQL for a migration of your own (then use setup: "verify", which answers 503 NotMigrated until the database matches). npx clientdb-prisma models / triggers, the Clientdb* Prisma models, the clientdb_* tables and adopting existing rows are gone.

    Migrating: delete the Clientdb* models and the clientdb trigger migrations, and drop the adoption step from your deploy. Keep setup: "auto", or add a migration from clientdb setup --print-sql and use setup: "verify".

  • Every write syncs. Prisma, raw SQL, other services and cascades all sync; a statement over bulkRows rows (default 1,000) or a TRUNCATE is logged as one invalidation. engine.changed(), engine.reconcile(), engine.resync(), engine.uncaptured(), the warnUntracked handler option and resyncInvalidateThreshold are removed.

  • Tokens instead of groups. Viewers hold tokens (user|<id>, team.member|<teamId>, claim:staff|*). db.$groups is db.$tokens, and the onAccessRemoved hook receives tokens. Rows readable through a parent ($.canRead(row.parent)) leave the client with the parent, and answers ship the parents their rows need. $.canRead(row, { except }) is removed.

  • Required relations a viewer may not read. The engine warns at startup when the rules don't prove a required relation's target readable wherever its row is. Mark such relations t.belongsTo(…).mayBeUnreadable() (fromPrisma: models.<Model>.relations.<relation>.mayBeUnreadable: true) to type them nullable on clients.

  • Force sync resolves with { missing } and applies its answer as a revalidation.

  • Protocol v3: stamps on every answer, tokens, plan and invalidate actions, POST /revalidate, chunked /partial, interest by hash (interestHash, interestChange, interestUnknown) and replays. QueryRequest.where is a list of clauses ({ or } alternatives).

  • Swift implements protocol v3 (ClientDBCore passes every conformance vector). The per-model LoadMode is ModelLoad; the client's LoadMode is lazy, schema or all. SQLite layout v3 drops older stored data.

Features

  • Revalidation instead of reloads: after an invalidation, a gained token, a deploy with new rules or a pruned log, clients re-read what they hold with per-item digests; unchanged items answer same.
  • Lazy clients send their interest and receive changes only for rows and collections they hold; an idle pull stays about 300 bytes at any held-row count.
  • entity.forceSync() / db.<model>.forceSync(ids), load: "all", and session-level load and forceSync permissions (NotAllowed, 403).
  • where takes or alternatives, locally and in server queries.
  • Named rules that reach the viewer several ways get one token kind per way (name#1, name#2).

Fixes

  • where({ id }) on a lazy model loads that row, not the whole model.
  • fromPrisma refuses implicit many-to-many relations with guidance.
  • clientdb migrate / setup load app modules with tsconfig path aliases and extensionless imports.

Known regressions (fixes planned for 0.6.x)

  • Postgres spends about 50% more CPU per write while the engine drains (0.35 vs 0.23 ms per write in bench:triggers).
  • One process serves about 10,000 WebSocket clients comfortably; 20,000 saturate it. Polling costs more server CPU than in 0.5.
  • Promoting, demoting or hiding a row from a client re-evaluates its whole held set (promote 132 vs 52 ms in bench:server).
  • Serverless throughput with many instances draining inline is lower (667 vs 1,184 tx/s with 8 instances).

Published to npm

v0.5.0

Choose a tag to compare

@github-actions github-actions released this 03 Dec 05:30
85a3971

The public API settles: models named by their createSchema key with relations as fields, $ as a rule argument, sessions with claims and read-only access, restricted fields, server queries, lazy clients with eviction, writes that apply at most once across long offline periods, retention, a round of security fixes and a faster sequencer. Old APIs are removed, not deprecated. Wire protocol v2 and schema IR v2: 0.4 and 0.5 clients and servers don't talk to each other, and open tabs reload once when you deploy. Breaking changes are listed first, each with what to change; the Swift client follows every change.

Breaking changes

  • Schema. model(fields, options) takes no name, and createSchema({ user, todo }, { viewer: "user" }) names models by their key. Relations are fields: project: t.belongsTo("project", { inverse: "todos", foreignKey, onDelete, eager }) replaces schema(models, (relations) => …) and relations.belongsTo.

    Migrating: move each model into the createSchema object under its name, and each relations.belongsTo(…) onto the child as a t.belongsTo field.

  • owned is removed; cascades come from onDelete. t.belongsTo("todo", { inverse: "comments", onDelete: "cascade" }) is the one way to cascade (default "setNull" for nullable relations, "restrict" otherwise). With fromPrisma, the relation's onDelete in schema.prisma decides: Cascade cascades, SetNull clears the key, anything else restricts. Client deletes, undo, ensureUndoable and archive inheritance follow every cascading relation, and a model may cascade from several parents (archived while any of them is). Schema metadata has cascadingParents / cascadingChildren instead of owner / ownedChildren; the schema IR drops owned.

    Migrating: replace owned: true with onDelete: "cascade", or give the Prisma relation onDelete: Cascade.

  • Load modes are "eager" and "lazy". "eager:critical" and "partial" are gone: a lazy model loads by its id, unique fields and foreign keys, and eager: true on a relation loads children with their parent. db.$ready() takes no level, and <DatabaseProvider ready> is a boolean.

    Migrating: "eager:critical" becomes "eager", "partial" becomes "lazy", ready="critical" becomes ready.

  • fromPrisma options per model. models: { Todo: { load, id: { prefix }, restricted, archivable, relations: { project: { eager } } } } replaces the top-level load and owned lists; eager is the only relation option. Mistakes are type errors on the offending key, including misspelled model names in models, omit and notSecret.

  • Permissions take $ as an argument. defineModelRules(schema, "todo", { read: (todo, $) => { … } }), defineRule(schema, "project", (project, $) => …, { name }) and definePermissions(schema, [rules…], { strict, groups }) replace createRules, rules(…) and rules.fn; explicit groups move to definePermissions' groups.

  • $.canRead(row.relation), and nothing is readable implicitly. $.canRead(comment.todo) (or $.canRead(comment.todo, { except })), in read and write rules, replaces comment.todo.canRead(). Children no longer inherit their parent's read rule: every synced model needs a read rule, and outside production (strict) definePermissions fails without one. read: (comment, $) => { return $.canRead(comment.todo); } reads exactly like the parent and is re-tagged in bulk when the parent's access changes.

    Migrating: add that rule to each formerly owned child.

  • update rules are field groups: { when, fields } or a list of them. Each changed field must belong to a group whose when holds before and after the write.

  • Sessions replace viewers. The handlers' viewer(request) option is now session(request), returning { viewer, claims?, readOnly?, tenant? } or null, and verifyJwt({ viewer }) is verifyJwt({ session }). Sync tokens carry the whole session. On the client, db.$viewerId is db.$session.viewerId. Engine methods (bootstrap, pull, push, partial, connect) take a Session from createSession(viewer, { claims, readOnly, tenant }) instead of tenant and viewer ids, engine.viewerGroups is engine.sessionGroups(session), and sync ids are opaque strings.

    Migrating: rename viewer: to session: and return { viewer: id }.

  • Server mutators are removed, with createEngine({ mutators }), db.$call and the call operation. Keep server logic in your own server actions or routes and call them through db.$action(fn).

  • EntitiesOf<Schema> (DB["Todo"]) replaces the public EntityOf<Schema, "todo">.

  • db.$sync() resolves only after a pull that started after the call (a barrier on live sockets), not after one already in flight.

  • Stricter security defaults, each refusing something 0.4 accepted:

    • Sync token secrets (tokens.secret, mintSyncToken) and verifyJwt({ secret }) need at least 32 characters (openssl rand -base64 32).
    • POST bodies must be application/json; other media types get 415.
    • ?token= is read only on WebSocket upgrades, never on plain HTTP requests.
    • Without cors, a WebSocket from another origin needs a sync token: cookies alone get 403. Pass cors if pages on other origins call the server.
  • Custom Reactivity implementations need a reaction(onInvalidate) method; signals and mobxReactivity() have it.

  • Engine: sequenceOnce() is removed. sequenceNow() takes no arguments and drainChanges() resolves once the backlog is empty; both return nothing.

  • Upgrading the database. Run npx clientdb migrate <engine module> when you deploy (--dry-run first prints the plan). On engine-owned tables it adds the new columns itself. Prisma apps first re-run npx clientdb-prisma models and migrate, for the new clientdb_row.field_readers, clientdb_log.created_at and nonce, clientdb_head.transactions_horizon and clientdb_transactions.head columns (clientdb migrate names any that are missing), and regenerate the capture triggers with npx clientdb-prisma triggers src/sync/schema.ts: they now cover serverOnly models, key changes, TRUNCATE and cascaded rows, and wake the sequencer.

Features

  • Restricted fields: .restricted() (or models.X.restricted with Prisma) and per-field read rules, read: { when, fields: { inviteCode: (project, $) => { … } } }. Hidden fields are undefined on the client and routed in their own field_readers column.

  • Claims and read-only sessions: declareClaim("staff"), granted by the session callback, used as a condition in rules and checked on the client with db.$session.hasClaim($staff). readOnly: true on a session or route refuses writes with ReadOnly (ReadOnlyError on the client), and createDatabaseClient({ readOnly: true }) types a client without writes. Live sockets check their session again every token lifetime and renew sync tokens, and changed claims move rows on and off the device.

  • Writes apply at most once, also after long offline periods. Applied transaction ids are kept for retention.transactions (default the longer of retention.log and 90 days). A pull from a client behind the pruned log is answered with reset before anything it sent is applied, and a resend the server may have applied after its id was pruned is refused with the new Stale code instead of applied twice. The client stamps each transaction with the sync position it is first sent from.

  • Server queries: db.todo.query({ where, orderBy, limit }) over POST /query, with keyset pages and per-model query: { fields, maxLimit } rules. where gains text operators (contains, startsWith, endsWith).

  • Lazy clients and eviction: createDatabaseClient({ load: "lazy" }) starts with no rows, and eviction: { maxRows } drops the loads used longest ago that nothing observes.

  • Fields: t.uuid({ prefix }), t.decimal(), .unique() and .generated() (Prisma autoincrement and dbgenerated() columns).

  • db.$action(fn, { optimistic }) previews a server action's outcome on the device until the server answers.

  • Engine: retention: { log, transactions, archived } applied by engine.prune() (hourly in start(), and by clientdb migrate); clients behind the pruned log start over. hooks: { onWriteRejected, onAccessRemoved } (no row data, safe to log), bootstrapRowWarning, cascadeRowLimit and recentLogActions. clientdb migrate --dry-run and engine.migrationPlan() show what a migration would do.

  • Prisma archives: models.X.archivable with archivedAt/archivedBy columns, so Prisma tables support archive(), unarchive() and retention.archived.

  • Transient database failures (a lost connection, shutdown, statement timeout or deadlock) throw Unavailable: HTTP answers 503, a live socket closes with 1011, and the client keeps the transaction and resends it, instead of dropping a write that was never wrong.

Fixes

  • Security:

    • Cross-site WebSockets authenticated by cookies are refused (browsers attach cookies to any site's upgrade), and an opaque null Origin no longer crashes the server.
    • Non-JSON POST bodies get 415, so another site can't push transactions with the viewer's cookies through a form or a no-cors fetch.
    • Tokens are no longer read from URLs of plain HTTP requests, and the Swift client sends its token as a header on the WebSocket too.
    • Secrets under 32 characters are refused. Malformed JWTs and JWKS keys that don't fit the token's algorithm answer 401 instead of 500.
    • Written values are checked against their field (type, enum, nullability) before rules run, so a rule can't be passed with "0" that Postgres then stores as 0.
    • Client archives, and creates or restores of archived rows, are stamped with the server's clock and the viewer and need the archive rule, so a back-dated archive can't make retention delete a row.
    • Writes to r...
Read more

v0.4.0

Choose a tag to compare

@github-actions github-actions released this 02 Dec 17:53
da8f0f4

load: "partial" with load keys inferred from relations, a round of API fixes so each thing has one name and one shape, and helpers for plain Node.js servers (Express, Fastify, Hono). Breaking changes are listed first, each with what to change.

Breaking changes

  • load: { partial: [...] } is now load: "partial", and every relation's foreign key is a load key. Before, a reference left out of the list was treated as fully loaded, so user.comments reported "complete" while showing only the comments already on the device; now each parent's collection loads (and reports "partial") on its own.

    Migrating: replace load: { partial: ["todoId"] } with load: "partial" (in model() options or fromPrisma's load). The old shape throws with a pointer to the new one, and a partial model without a relation to a parent is rejected (use "lazy"). On your own tables (Prisma), index every foreign key of a partial model, such as @@index([authorId]).

    engine.partial / partialMany only load a partial model by one of its load keys (or as a whole, for reloads after invalidate); loads by other fields return nothing.

    Model and schema hashes now cover load and each relation's onDelete, so a client running an older bundle gets SchemaOutdated after a load-strategy change instead of showing a now-partial model as complete. Every schema hash changes once with this release, so open tabs reload when you deploy it. Migrations compare the new shapeHash (the previous formula), so stored snapshots stay valid and changing only load or onDelete needs no migration.

  • One way to keep a model on the server: model("auditLog", { … }, { serverOnly: true }), or fromPrisma(models, { serverOnly: ["AuditLog"] }). A server-only model needs no rules, clients can't write it, and it and its relations are left out of client types, accessors and generated Swift code; rules can still read it.

    Removed, with errors that name the replacement:

    • load: "local". It was documented as "never synced", but the server accepted and fanned out its writes, required rules for it, and its collections reported complete without loading the server's rows.
    • sync: false on models (now serverOnly: true).
    • rules("model", "server-only") (mark the model serverOnly in the schema; rules for a server-only model now throw).

    The schema IR writes serverOnly instead of sync; the Swift client still reads "sync": false.

  • sync no longer means three things. fromPrisma's sync (the secret-looking columns that may go to clients) is now notSecret, and createDatabaseClient({ sync: false }) (no network) is now network: false; the model option became serverOnly earlier. The old spellings throw with the new name.

  • updatedAt fields now change on every update, as documented. Declare them with the field modifier updatedAt: t.timestamp().updatedAt() (the updatedAt model option is removed and throws; fromPrisma maps @updatedAt to it). The client stamps the field at once on every update that changes another field (optimistically, and the operation carries the value), the server stamps it on updates made on the server (system writes, mutators) on engine-owned tables too, and field permissions (update.fields) never need to list it. Previously the field was only set on insert, except on Prisma tables, where clients didn't receive the new value until a reconcile. dirtyFields doesn't list stamped fields. New: completeUpdate in @clientdb/core (spec/replica.md §4.1), mirrored by the Swift client.

  • One name for each thing: the permission helpers $.all and $.any are removed in favour of $.and and $.or (they were documented as "same as"), and Collection.findById(id) (which returned null) is now get(id) returning undefined, the same name and convention as db.issue.get(id).

  • Owned children now inherit their parent's read access, as documented: an owned: true child without a read rule is readable exactly when its parent is (parent.canRead()), and strict mode no longer asks for a rule for it. Its writes still need rules; an explicit read rule still wins.

    owned: { inheritAccess: false } is removed (it only switched off a set-based re-tagging optimization; give the child its own read rule instead), and so is inheritAccess on relation metadata and in the schema IR. The engine's bulkInherit option is now internal.

  • owned no longer silently overrides onDelete. belongsTo(…, { owned: true, onDelete }) is a type error and throws (owned relations always cascade), and fromPrisma's owned refuses a relation whose schema.prisma onDelete isn't Cascade, so deleting a parent with Prisma Client and with clientdb does the same thing.

  • archivable is now a boolean: model("issue", { … }, { archivable: true }). The retain setting is gone: it was required but nothing read it (there is no purge job), so a value like "30d" silently kept archived rows forever. An object value now throws. The schema IR writes "archivable": true | false; the Swift client still reads the old object form. ArchivableOptions is no longer exported.

  • load: "onDemand" is removed: it behaved exactly like load: "lazy", which stays. The load strategies are now "eager:critical", "eager" (default), "lazy" and "partial". Using "onDemand" throws with the replacement; the Swift client reads it as lazy in older schema files.

  • createSyncServer serves under /api/sync by default, the client's default url, instead of /sync, so an unconfigured server and client meet. Pass basePath: "/sync" to keep the old path. It also accepts warnUntracked, like the fetch and Next.js handlers.

  • Safer token and error defaults:

    • Sync tokens carry aud: "clientdb-sync", and the handlers accept a bearer token as a sync token only with that audience, so another HS256 token signed with the same secret (another app's, or staging's) isn't one. New exports: verifySyncToken, SYNC_TOKEN_AUDIENCE.
    • verifyJwt and verifyJwtToken refuse tokens without an expiry (exp), which would otherwise never expire.
    • verifyJwt({ jwks }) warns in development when no audience is set: without one, tokens your auth provider issued for your other apps are accepted.
    • In production, a failed request answers { error: "internal error" } instead of the error message (database errors name tables and constraints); the details are still logged.

Features

  • Plain Node.js servers: createSyncServer now plugs into Express and Connect (syncServer.middleware), Fastify (app.register(syncServer.fastify)) and Hono or Bun (syncServer.fetch), and syncServer.attachWebSocket(server) adds the realtime socket to a server you created. New cors and bodyLimit options (default 16 MiB) on createSyncServer, createFetchHandler and the Next.js handler. syncServer.close() now returns a promise: it closes sockets with code 1001, refuses new ones and stops the sequencer it started. A throwing viewer now answers 500 instead of hanging the request (and crashing the process with an unhandled rejection), attach leaves other listeners' WebSocket upgrades alone, and malformed JSON bodies answer 400. The viewer callback of createSyncServer also gets the Node request as raw.

  • The schema names its viewer model: schema(models, relations, { viewer: "member" }) or fromPrisma(models, { viewer: "Member" }), defaulting to the user model. db.$viewer is now typed as that model's entity (it was a union of every model, so db.$viewer?.name didn't type-check), and createRules(schema) takes the viewer from the schema; an explicit createRules(schema, { viewer }) must match it. New exports: ViewerModel, SchemaOptions; Schema has a third type parameter and a viewer property.

  • Less to restate in a TypeScript schema: every model gets id: t.id() without declaring it (declaring it still works), and belongsTo names the relation after a foreign key named …Id when as is left out (belongsTo(issue, "teamId", team, { inverse: "issues" }) is issue.team). Other foreign keys still need as, as a type error and at runtime.

  • createEngine({ permissions }) takes its schema from the permissions (createRules(schema) already names it), so schema is optional. When it's passed and isn't the permissions' schema, createEngine throws instead of compiling access for one schema and storing rows for another. EngineOptions.permissions is now typed Permissions<S>. Docs drop the redundant schema and, where DATABASE_URL is the default anyway, database.

  • db.$computed(fn) and db.$effect(fn) derive values and run effects with whichever reactivity the client uses (built-in signals or MobX), so there is no computed to pick from the right package. mobxReactivity() no longer needs the mobx module passed in: it uses the app's mobx (a peer dependency); passing one still works.

  • createDatabaseClient (and createTestClient) report a type error when the classes in Register["models"] and in the models option differ. Relations return Register's classes while db.<model> returns the option's, so a class listed in only one of them used to type-check and then fail at runtime (a relation typed as Todo returning a plain entity without todo.toggle()). New export: RegisterCheck.

  • In development, the sync handlers warn once when anonymous and the rules disagree: read rules use $.public but signed-out requests get 401, or anonymous: true is set but no rule uses $.public.

Fixes

  • fromPrisma rough edges:

    • Creating a row of a model whose omitted column is required without a database default is refused with a Validation error naming the column, instead of failing in Postgres with a 500 (ExternalModelStorage.requiredOmitted).
    • On the server in development, fromPrisma notes once which columns change shape on clients: BigInt columns (numbers, ex...
Read more

v0.3.0

Choose a tag to compare

@github-actions github-actions released this 02 Dec 16:46
eae96aa