@quickback-dev/cli 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +34 -19
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.d.ts.map +1 -1
  5. package/dist/docs/content.js +31 -21
  6. package/dist/docs/content.js.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/action-harvest.d.ts +35 -4
  9. package/dist/lib/action-harvest.d.ts.map +1 -1
  10. package/dist/lib/action-harvest.js +233 -50
  11. package/dist/lib/action-harvest.js.map +1 -1
  12. package/dist/lib/action-harvest.test.js +130 -2
  13. package/dist/lib/action-harvest.test.js.map +1 -1
  14. package/dist/lib/auth.d.ts +6 -0
  15. package/dist/lib/auth.d.ts.map +1 -1
  16. package/dist/lib/auth.js +18 -1
  17. package/dist/lib/auth.js.map +1 -1
  18. package/dist/lib/auth.test.d.ts +2 -0
  19. package/dist/lib/auth.test.d.ts.map +1 -0
  20. package/dist/lib/auth.test.js +19 -0
  21. package/dist/lib/auth.test.js.map +1 -0
  22. package/dist/lib/compile-next-steps.d.ts +4 -0
  23. package/dist/lib/compile-next-steps.d.ts.map +1 -0
  24. package/dist/lib/compile-next-steps.js +69 -0
  25. package/dist/lib/compile-next-steps.js.map +1 -0
  26. package/dist/lib/compile-next-steps.test.d.ts +2 -0
  27. package/dist/lib/compile-next-steps.test.d.ts.map +1 -0
  28. package/dist/lib/compile-next-steps.test.js +76 -0
  29. package/dist/lib/compile-next-steps.test.js.map +1 -0
  30. package/dist/lib/file-loader.d.ts.map +1 -1
  31. package/dist/lib/file-loader.js +1 -0
  32. package/dist/lib/file-loader.js.map +1 -1
  33. package/dist/lib/file-writer.d.ts +1 -1
  34. package/dist/lib/file-writer.d.ts.map +1 -1
  35. package/dist/lib/file-writer.js +20 -5
  36. package/dist/lib/file-writer.js.map +1 -1
  37. package/dist/lib/file-writer.test.d.ts +2 -0
  38. package/dist/lib/file-writer.test.d.ts.map +1 -0
  39. package/dist/lib/file-writer.test.js +90 -0
  40. package/dist/lib/file-writer.test.js.map +1 -0
  41. package/dist/lib/shell.test.d.ts +2 -0
  42. package/dist/lib/shell.test.d.ts.map +1 -0
  43. package/dist/lib/shell.test.js +39 -0
  44. package/dist/lib/shell.test.js.map +1 -0
  45. package/dist/skill/docs/changelog.md +476 -2
  46. package/dist/skill/docs/compiler/cloud-compiler/cli.md +16 -0
  47. package/dist/skill/docs/compiler/cloud-compiler/endpoints.md +4 -2
  48. package/dist/skill/docs/compiler/cloud-compiler/local-compiler.md +17 -5
  49. package/dist/skill/docs/compiler/config/auth.md +17 -2
  50. package/dist/skill/docs/compiler/config/index.md +271 -12
  51. package/dist/skill/docs/compiler/config/output.md +49 -3
  52. package/dist/skill/docs/compiler/config/providers.md +12 -1
  53. package/dist/skill/docs/compiler/config/variables.md +5 -0
  54. package/dist/skill/docs/compiler/definitions/access.md +7 -0
  55. package/dist/skill/docs/compiler/definitions/actions.md +267 -9
  56. package/dist/skill/docs/compiler/definitions/bundles.md +69 -0
  57. package/dist/skill/docs/compiler/definitions/firewall.md +6 -1
  58. package/dist/skill/docs/compiler/definitions/masking.md +2 -2
  59. package/dist/skill/docs/compiler/definitions/schema.md +12 -0
  60. package/dist/skill/docs/compiler/definitions/transitions.md +149 -0
  61. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +353 -20
  62. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/index.md +7 -1
  63. package/dist/skill/docs/stack/account-ui/hooks.md +104 -1
  64. package/dist/skill/docs/stack/auth/plugins/aws-sns.md +20 -3
  65. package/dist/skill/docs/stack/cms/schema-format.md +4 -2
  66. package/dist/skill/docs/stack/cms/schema-registry.md +4 -2
  67. package/dist/skill/docs/stack/realtime/durable-objects.md +17 -4
  68. package/package.json +1 -1
  69. package/src/skill/docs/changelog.md +476 -2
  70. package/src/skill/docs/compiler/cloud-compiler/cli.md +16 -0
  71. package/src/skill/docs/compiler/cloud-compiler/endpoints.md +4 -2
  72. package/src/skill/docs/compiler/cloud-compiler/local-compiler.md +17 -5
  73. package/src/skill/docs/compiler/config/auth.md +17 -2
  74. package/src/skill/docs/compiler/config/index.md +271 -12
  75. package/src/skill/docs/compiler/config/output.md +49 -3
  76. package/src/skill/docs/compiler/config/providers.md +12 -1
  77. package/src/skill/docs/compiler/config/variables.md +5 -0
  78. package/src/skill/docs/compiler/definitions/access.md +7 -0
  79. package/src/skill/docs/compiler/definitions/actions.md +267 -9
  80. package/src/skill/docs/compiler/definitions/bundles.md +69 -0
  81. package/src/skill/docs/compiler/definitions/firewall.md +6 -1
  82. package/src/skill/docs/compiler/definitions/masking.md +2 -2
  83. package/src/skill/docs/compiler/definitions/schema.md +12 -0
  84. package/src/skill/docs/compiler/definitions/transitions.md +149 -0
  85. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +353 -20
  86. package/src/skill/docs/compiler/targets/hono-api/using-the-api/index.md +7 -1
  87. package/src/skill/docs/stack/account-ui/hooks.md +104 -1
  88. package/src/skill/docs/stack/auth/plugins/aws-sns.md +20 -3
  89. package/src/skill/docs/stack/cms/schema-format.md +4 -2
  90. package/src/skill/docs/stack/cms/schema-registry.md +4 -2
  91. package/src/skill/docs/stack/realtime/durable-objects.md +17 -4
@@ -115,12 +115,43 @@ export default defineAction({
115
115
 
116
116
  > **`defineAction` import.** Import from `"../.quickback/define-action"` —
117
117
  > the `.quickback/` directory is generated alongside your feature with a
118
- > typed helper that infers `record` and `input` types from the rest of the
119
- > action config. Audit fields (`createdAt`, `createdBy`, `modifiedAt`,
118
+ > typed helper. It infers `record` and Zod `input`, exposes the generated
119
+ > `Services`, types `c` as a Hono request context, binds `whereRecord` and
120
+ > `whereTransition` to the feature table, and preserves the exact value
121
+ > returned by `execute` without imposing an action-output schema. Scoped
122
+ > `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;
123
+ > HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`
124
+ > also retains its open index for namespace-hydrated fields. Audit fields
125
+ > (`createdAt`, `createdBy`, `modifiedAt`,
120
126
  > `modifiedBy`) are hard-stamped by the audit DB wrapper on every
121
127
  > `db.insert().values()` and `db.update().set()` — handlers don't pass
122
128
  > them and can't override them.
123
129
 
130
+ ### Local input-schema harvest
131
+
132
+ Before sending a compile request, the CLI loads each action in an isolated
133
+ local bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does
134
+ not call `execute`; the hosted compiler never evaluates project code. Under
135
+ contract v2, every action must produce a schema. A failure names the exact
136
+ action, whether bundling or evaluation failed, and the underlying local error.
137
+ V1 can still fall back to the lower-fidelity static schema parser.
138
+
139
+ Bare imports are resolved from the generated runtime's configured
140
+ `build.outputDir/node_modules` first. If definitions live in `quickback/` and
141
+ the generated Worker lives in `src/`, install runtime dependencies in `src/`
142
+ as usual; no project-root dependency symlink is required. Shared schema or DTO
143
+ modules may also declare top-level Drizzle selection objects. Quickback
144
+ replaces authored table exports with inert proxies during this schema-only
145
+ evaluation, so reading `records.id` to build a projection does not execute
146
+ application or database logic.
147
+
148
+ Parameterized standalone paths use Hono's `:param` syntax in authored source,
149
+ for example `path: "/events/:eventId/check-in"`. The harvest planner converts
150
+ those segments to the OpenAPI `{param}` form before applying the schema, so
151
+ contract-v2 completeness uses the same route key as the emitted OpenAPI and MCP
152
+ surfaces. The same normalization applies when a record resource path contains
153
+ namespace parameters.
154
+
124
155
  ### Configuration Options
125
156
 
126
157
  | Option | Required | Description |
@@ -276,6 +307,14 @@ The `input` is shared across the batch — the action's Zod schema is
276
307
  validated once, not per id. For per-record input variation, use the
277
308
  single-record endpoint (`POST /:id/{action}`) or write a standalone action.
278
309
 
310
+ The generated OpenAPI document and MCP tools reuse that exact action schema
311
+ in both places: as the single-record request body and as the bulk wrapper's
312
+ nested `input` property. Under contract v2, Quickback considers the action's
313
+ schema harvest complete only after both operations are patched. This also
314
+ holds when the table filename and declared table name use different casing or
315
+ separators (for example, `event-guests.ts` exporting `event_guests`); the
316
+ operations follow the table's declared resource path.
317
+
279
318
  **Response (207 Multi-Status when any record fails, 200 when clean):**
280
319
 
281
320
  ```json
@@ -660,6 +699,108 @@ async execute({ db, ctx, input }) {
660
699
  - **Masking** — actions are backend code that may need raw data
661
700
  - **Access** — already checked before action execution
662
701
 
702
+ ### Delegated principals and `databaseAccess`
703
+
704
+ On a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a
705
+ configured delegated principal with `access.principals`:
706
+
707
+ ```typescript
708
+ export default defineAction({
709
+ description: "Confirm attendance from an event session",
710
+ path: "/attendance/confirm",
711
+ input: z.object({ response: z.enum(["yes", "no"]) }),
712
+ access: { principals: ["event_delegate"] },
713
+ async execute({ ctx, db, input }) {
714
+ // ctx.principal is guaranteed and narrowed by the generated helper.
715
+ const { eventId, personId } = ctx.principal.claims;
716
+ return confirmAttendance(db, { eventId, personId, response: input.response });
717
+ },
718
+ });
719
+ ```
720
+
721
+ This is a separate authority lane, not an account impersonation. A delegated
722
+ action context has no `userId`, active organization/team, or membership roles.
723
+ If access has a `PUBLIC` sibling arm, the generated type includes the anonymous
724
+ lane and code must narrow `ctx.principal` before reading it.
725
+
726
+ For an organization- or team-scoped host feature, the standalone route does
727
+ not run the Better Auth `activeOrgId` / `activeTeamId` precondition before a
728
+ principal access tree. Authentication and `evaluateAccessPreRecord` still run;
729
+ the declared `principals` arm is the authority decision. This avoids turning an
730
+ account-session field into an accidental prerequisite for delegated callers.
731
+
732
+ The generated standalone route reuses that action-specific `execute` context
733
+ after its runtime access gates. Account, `event_pass`, and `event_delegate`
734
+ actions therefore keep distinct compile-time authority types all the way into
735
+ the handler. The route also reuses the action's schema-aware scoped `db` type,
736
+ including when an unsafe/service-role client is wrapped before the call. If a
737
+ relationship uses `loads` / `exposeAs`, the loaded row type is
738
+ intersected with the same authority context: a single or shared hydration
739
+ target is required, while targets selected by distinct relationship lanes are
740
+ optional and must be narrowed by the handler.
741
+
742
+ For tables queried by authored actions, `resource.databaseAccess` adds an
743
+ independent Postgres RLS policy without adding HTTP surface. It never mounts a
744
+ read/CRUD route and never adds an OpenAPI operation. The action remains the API
745
+ layer where validation, state transitions, side effects, and business logic
746
+ belong; `databaseAccess` is only the database's row-level upper bound.
747
+
748
+ ```typescript
749
+ export default defineTable(attendanceEvidence, {
750
+ // Ordinary account CRUD remains organization-scoped.
751
+ firewall: [
752
+ { field: "organizationId", equals: "ctx.activeOrgId" },
753
+ ],
754
+
755
+ // Authored actions can use their caller-scoped db under one of two exact
756
+ // row lanes. Sibling arms OR; fields in each arm AND.
757
+ databaseAccess: {
758
+ select: {
759
+ or: [
760
+ {
761
+ roles: ["AUTHENTICATED"],
762
+ record: {
763
+ organizationId: { equals: "$ctx.activeOrgId" },
764
+ },
765
+ },
766
+ {
767
+ principals: ["event_delegate"],
768
+ record: {
769
+ eventId: { equals: "$ctx.principal.claims.eventId" },
770
+ personId: { equals: "$ctx.principal.claims.personId" },
771
+ },
772
+ },
773
+ ],
774
+ },
775
+ },
776
+ });
777
+ ```
778
+
779
+ `databaseAccess` supports `select`, `insert`, `update`, and `delete`. Its rule
780
+ language is intentionally smaller than application access: `principals`,
781
+ `roles`, recursive `or`/`and`, and record `equals` against a DB-visible account
782
+ or principal context value. `userRole`, functions, request/body values, and
783
+ other predicate operators are compile errors.
784
+
785
+ Every authorization path must contain at least one nonempty record equality.
786
+ A principal-only or role-only leaf is rejected; every `or` arm must be bounded.
787
+ An `and` group is bounded when at least one child bounds every expansion (for
788
+ example, a principal child AND an event-id record child). A node cannot mix
789
+ leaf fields with `or`/`and`, because the boolean node is the complete rule.
790
+ This mandatory shape prevents an action declaration from accidentally granting
791
+ the delegated principal an entire table.
792
+
793
+ The supported equality sources are `ctx.userId`, `ctx.activeOrgId`,
794
+ `ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family
795
+ ids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The
796
+ record keys are Drizzle/JavaScript table field names; Quickback resolves them
797
+ through the table metadata and quotes the exact physical PostgreSQL identifier,
798
+ so a field such as `eventId: text("event-id")` is safe. Unknown fields fail the
799
+ compile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB
800
+ surface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The
801
+ feature is rejected outside Cloudflare + Neon Hyperdrive because those targets
802
+ cannot guarantee request-scoped Postgres claims.
803
+
663
804
  ### Relational queries are blocked (fail-closed)
664
805
 
665
806
  Drizzle's relational query API — `db.query.<table>.findFirst()` /
@@ -720,13 +861,19 @@ Unsafe cross-tenant actions are generated with:
720
861
  - sysadmin gate (`ctx.userRole === "sysadmin"`)
721
862
  - mandatory audit logging on deny/success/error
722
863
 
723
- **Provider note (Neon):** on Neon the request-scoped db enforces Row Level
724
- Security with the *caller's* org claims, which would filter out exactly the
725
- cross-tenant rows unsafe actions exist to reach. Unsafe handlers therefore
726
- acquire a dedicated service-role handle (`createServiceDb`) that sets the
727
- `quickback.service_role` transaction marker instead of caller claims; the
728
- generated RLS grants that context an explicit per-table bypass policy. The
729
- audit-logging contract is identical to D1. Neon with
864
+ **Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query
865
+ bypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An
866
+ unsafe action with `crossTenant: false` receives a raw Drizzle handle backed by
867
+ the request database, so the caller's organization or delegated-principal
868
+ claims remain active—including inside `db.transaction()`. Its code must still
869
+ provide every intended scope predicate explicitly.
870
+
871
+ Only an action with `crossTenant: true` acquires the dedicated service-role
872
+ handle (`createServiceDb`). That handle sets the `quickback.service_role`
873
+ transaction marker instead of caller claims, and generated RLS grants it an
874
+ explicit per-table bypass policy. The sysadmin guard and mandatory audit log
875
+ therefore protect the same boundary that receives the RLS bypass. The
876
+ audit-logging contract is otherwise identical to D1. Neon with
730
877
  `connectionMode: 'websocket'` does not support unsafe actions yet and fails
731
878
  the compile with a descriptive error.
732
879
 
@@ -1158,6 +1305,117 @@ The same 409 code is used when an `access.record` predicate (without
1158
1305
  called against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,
1159
1306
  not a misleading 403.
1160
1307
 
1308
+ Transitions grew a v2 surface — guards, timestamp/actor stamps, idempotent
1309
+ no-ops, compiler-applied writes with optional `execute`, `undo` pairs, and
1310
+ table-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.
1311
+
1312
+ ## After-commit hooks
1313
+
1314
+ Secondary effects — activity feeds, notification nudges, cache warmers — must
1315
+ never roll back or delay the primary write. Instead of hand-wrapping each leg
1316
+ in `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:
1317
+
1318
+ ```typescript
1319
+ export default defineAction({
1320
+ // ...
1321
+ execute: async ({ db, record, ctx, now }) => {
1322
+ await db.update(guests).set({ checkedInAt: now }).where(/* … */);
1323
+ return { success: true, checkedInAt: now };
1324
+ },
1325
+ afterCommit: {
1326
+ // Named hooks run after execute returns successfully, in declared order.
1327
+ activityFeed: async ({ db, env, record, ctx }, result) => {
1328
+ await recordActivity(db, env, { verb: "guest.checked_in", /* … */ });
1329
+ },
1330
+ // blocking: true is awaited before the response (client depends on it).
1331
+ issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },
1332
+ },
1333
+ });
1334
+ ```
1335
+
1336
+ The contract:
1337
+
1338
+ - Hooks receive `(actx, result)` — the same context `execute` got, plus its
1339
+ return value.
1340
+ - Each hook is **independently wrapped**: a throw is logged as
1341
+ `[<action>] afterCommit:<hook> failed` and never affects the response or
1342
+ other hooks.
1343
+ - Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking
1344
+ hooks are awaited before responding.
1345
+ - If `execute` throws, no hooks run. A result carrying `dryRun: true` also
1346
+ skips them (preview branches never fire side effects).
1347
+ - Bulk twins run hooks **once per invocation** with the bulk envelope as
1348
+ `result` — per-record fan-out is the hook author's job.
1349
+
1350
+ For effects that need mid-execute data, the context carries an imperative
1351
+ escape hatch with the same semantics:
1352
+
1353
+ ```typescript
1354
+ execute: async ({ db, effects }) => {
1355
+ // …
1356
+ effects.enqueue("cohortRecalc", () => recalculate(/* … */));
1357
+ return { success: true };
1358
+ }
1359
+ ```
1360
+
1361
+ Effects enqueued by an `execute` that later throws are dropped. The context
1362
+ also carries `now` — one ISO timestamp per invocation; prefer it over
1363
+ `new Date().toISOString()`.
1364
+
1365
+ ## Realtime emit from actions
1366
+
1367
+ Tables that lock auto-CRUD but mutate through custom actions no longer need
1368
+ hand-written `realtime.insert/update/delete` blocks. Opt the table in:
1369
+
1370
+ ```typescript
1371
+ realtime: {
1372
+ enabled: true,
1373
+ access: { roles: ["member+"] },
1374
+ scopeKeyFrom: "events:{eventId}", // sugar for scopeTable + scopeField
1375
+ emitFromActions: true, // scoped-db writes auto-emit after commit
1376
+ }
1377
+ ```
1378
+
1379
+ Writes to the table through the scoped `db` inside record-bound and bulk
1380
+ actions emit frames byte-compatible with auto-CRUD (same envelope, masking,
1381
+ audience), after commit, best-effort. For projections, standalone actions, or
1382
+ cross-feature targets, declare an action-level `emit:` to get a pre-bound
1383
+ `emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in
1384
+ the [realtime docs](/stack/realtime/durable-objects).
1385
+
1386
+ ## Refs (scoped foreign-key inputs)
1387
+
1388
+ The most common action preamble — load an input id, 404 if missing, assert it
1389
+ belongs to the caller's event/org — becomes declarative:
1390
+
1391
+ ```typescript
1392
+ export default defineAction({
1393
+ input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),
1394
+ refs: {
1395
+ agendaItemId: { table: "agendaItems", as: "agendaItem",
1396
+ matchScope: "event", // row.eventId === ctx.event.id
1397
+ notFound: { code: "ITEM_NOT_FOUND" } }, // status defaults to 404
1398
+ guestId: { table: "guests", as: "guest",
1399
+ matchWith: { ref: "agendaItem", on: "eventId" }, // cross-input parenthood
1400
+ mismatch: { code: "EVENT_MISMATCH", status: 400 } },
1401
+ locationId: { table: "locations", as: "location", optional: true, matchScope: "event" },
1402
+ },
1403
+ execute: async ({ input, agendaItem, guest, location }) => { /* … */ },
1404
+ });
1405
+ ```
1406
+
1407
+ - Loads run **through the scoped db** before `execute` — the org firewall and
1408
+ soft-delete filter apply by construction, so a cross-org id 404s with zero
1409
+ hand-written tenancy checks. All loads batch into one `Promise.all`.
1410
+ - `matchScope: "<scope>"` asserts `row.<scope>Id === ctx.<scope>.id` and
1411
+ fail-closes (500) if the scope object isn't hydrated. The explicit form
1412
+ `{ column, equals: "ctx.activeOrgId" }` is also accepted.
1413
+ - `matchWith` compares a column against an earlier-declared ref — declaration
1414
+ order defines resolution order; forward references are compile errors.
1415
+ - Ref keys must exist on the inline `z.object` input with agreeing
1416
+ optionality; `as` names can't shadow reserved context keys. Injected rows
1417
+ are the **unmasked** DB rows (masking remains a read-projection concern).
1418
+
1161
1419
  ## Examples
1162
1420
 
1163
1421
  ### Bulk Import (Standalone, No Record)
@@ -0,0 +1,69 @@
1
+ # Bundles
2
+
3
+ ## Overview
4
+
5
+ Client bootstrap screens want many small lists in one request. Hand-written
6
+ "bundle" endpoints all repeat the same 150 lines: a `Promise.all` of selects
7
+ shaped byte-identically to the CRUD list endpoints they replace, a
8
+ `sections: string[]` subset filter, a copy-pasted SHA-1 ETag +
9
+ `ifNoneMatch → notModified` short-circuit, a `Server-Timing` header, and
10
+ hand-re-derived per-slice masking. `defineBundle` generates all of it.
11
+
12
+ ```typescript
13
+ // features/events/actions/getOverviewBundle.ts
14
+ import { defineBundle, list, custom } from "../.quickback/define-bundle";
15
+
16
+ export default defineBundle({
17
+ path: "/event/:eventId/overview-bundle",
18
+ description: "Console Overview bootstrap",
19
+ access: { roles: ["member", "admin"] },
20
+ etag: true, // default true
21
+ serverTiming: "overview", // optional
22
+ sections: {
23
+ guests: list("guests", {
24
+ columns: ["id", "status", "modifiedAt", "createdAt", "displayName"],
25
+ where: { eventId: "$ctx.event.id" },
26
+ orderBy: [{ createdAt: "desc" }],
27
+ limit: 500,
28
+ }),
29
+ tickets: list("supportTickets", { where: { eventId: "$ctx.event.id" }, orderBy: [{ modifiedAt: "desc" }], limit: 100 }),
30
+ counts: custom(async ({ db, ctx }) => ({ open: 0 })), // computed slice — author owns masking
31
+ },
32
+ });
33
+ ```
34
+
35
+ ## Semantics
36
+
37
+ - **Generated POST action** with input `{ sections?: string[], ifNoneMatch?: string }`,
38
+ mounted through the standard standalone pipeline — auth, access, org/team
39
+ preconditions, rate limits, OpenAPI, MCP tools, security contracts all
40
+ apply.
41
+ - **`list()` sections run through the scoped db** — the org firewall and
42
+ soft-delete filter apply by construction — and the target table's REAL
43
+ mask function is applied (the same read projection the CRUD list endpoint
44
+ runs), so masked columns are safe to include. Every list slice lands as
45
+ `{ data: rows }` (the per-resource cache-seed contract).
46
+ - **`sections` filter**: omitted/empty = all. An un-wanted list section
47
+ returns `{ data: [] }` (drop-in compatible with existing clients);
48
+ un-wanted `custom` sections are absent.
49
+ - **All sections run in one `Promise.all`.**
50
+ - **ETag**: SHA-1 hex over `{ scopeSeed: <path params>, userId, payload }`.
51
+ An `ifNoneMatch` match returns `{ success: true, etag, notModified: true }`
52
+ with **no sections**. The digest is also exported as `sha1Hex` from
53
+ `lib/etag` so remaining hand-written reads can delete their copies.
54
+ - **`custom()` sections** receive the full action context and are embedded
55
+ verbatim under the section name — the author owns masking there.
56
+
57
+ ## Compile-time validation (fail-closed)
58
+
59
+ - Unknown section tables error, listing candidates.
60
+ - `columns` / `where` / `orderBy` must name declared columns
61
+ (compiler-injected audit columns like `createdAt`/`modifiedAt` are allowed).
62
+ - `where` values are literals or the strict substitution allowlist
63
+ (`$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id`) — always
64
+ parameterized. Anything richer belongs in a `custom()` section.
65
+ - Section names may not shadow the response envelope
66
+ (`success`, `etag`, `notModified`, `sections`).
67
+ - **A bundle must never widen read access**: its `access.roles` must be a
68
+ subset of every list section table's `read.access` roles — a violation is
69
+ a compile error, not a warning.
@@ -61,7 +61,7 @@ When you omit the `firewall:` block entirely, the compiler scans the schema for
61
61
 
62
62
  ```typescript
63
63
  type FirewallPredicate =
64
- | { field: string; equals: string; optional?: boolean } // column = ctx.* (or literal)
64
+ | { field: string; equals: string; optional?: boolean; nullable?: true } // column = ctx.* (or literal)
65
65
  | { field: string; isNull: true } // column IS NULL
66
66
  | { field: string; in: string[] | string; optional?: boolean } // column IN (...)
67
67
  | { field: string; via: string } // column IN (relationship subquery)
@@ -97,6 +97,11 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
97
97
  - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).
98
98
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
99
99
 
100
+ `nullable: true` is a separate database-schema opt-in, supported only on an
101
+ owner predicate whose source is exactly `ctx.userId`. It allows the persisted
102
+ owner column to be NULL; NULL rows still do not match the owner arm because SQL
103
+ equality never matches NULL. It does not make the request claim optional.
104
+
100
105
  ```typescript
101
106
  // (org OR event) AND owner AND not-deleted
102
107
  firewall: {
@@ -204,7 +204,7 @@ read: {
204
204
  Masking redacts a column on the **read paths** (`GET /:id`, list, views, realtime) per role. It does **not** automatically follow the value if you copy it into a *derived* artifact that bypasses those read paths — a different record, an html/text string, or an outbound payload. Quickback guards those egress points so a masked token/PII can't quietly ship in the clear:
205
205
 
206
206
  - **Compile-time block (declarative).** A masked column is rejected at build time if it appears in `embeddings.fields` / `embeddings.metadata` (the value would be embedded and stored beside the vector, and returned in search hits) or is used as the table's `displayColumn` (it would render as the FK label inside every referencing record).
207
- - **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (`sql\`…\${record.col}\``) are fine — only the storage/payload sinks are flagged.
207
+ - **Compile-time scan (actions).** A record-based action that copies `record.<maskedColumn>` into another record's column, an html/text template that gets stored, or a payload object fails compilation. Plain reads, comparisons, logging, and tagged templates (``sql`…${record.col}` ``) are fine — only the storage/payload sinks are flagged.
208
208
  - **Realtime → webhook.** Rows pushed to a realtime webhook sink are masked (an external sink carries no role, so masked columns are redacted), matching what WebSocket subscribers see.
209
209
 
210
210
  ### Revealing a value on purpose: `unmask()`
@@ -229,7 +229,7 @@ masking: {
229
229
  }
230
230
  ```
231
231
 
232
- `egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/docs/compiler/definitions/encryption).
232
+ `egress` defaults to `'block'` (fail-closed). Note the action scan is a heuristic — it catches the obvious accidental copy (`record.col` straight into a sink) but not values first aliased into another variable, the whole row returned/spread, or a re-fetch via `db.select()`. Treat it as a guardrail against accidents, not a cryptographic boundary; for true secrecy use the [encryption pillar](/compiler/definitions/encryption).
233
233
 
234
234
  ## Complete Example
235
235
 
@@ -642,6 +642,18 @@ export const jobsRelations = relations(jobs, ({ one, many }) => ({
642
642
  }));
643
643
  ```
644
644
 
645
+ Drizzle `relations(...)` describe application-side joins; they do not always
646
+ create a database foreign-key constraint. On Neon, use
647
+ [`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations)
648
+ for fully qualified cross-schema or composite constraints that cannot be
649
+ declared alongside a table. The ordered source and target column tuples must
650
+ have equal arity, and the referenced target tuple must have a matching unique
651
+ or primary-key constraint before the foreign key migration runs.
652
+
653
+ Use these constraints for relational integrity only. Authorization, pass
654
+ consumption, state transitions, and other business logic belong in the API
655
+ action layer.
656
+
645
657
  ## Database Configuration
646
658
 
647
659
  Configure database options in your Quickback config:
@@ -0,0 +1,149 @@
1
+ # Transitions
2
+
3
+ ## Overview
4
+
5
+ Most state changes follow the same shape: check the row is in a legal state,
6
+ flip a column, stamp who/when, maybe cascade. Before transitions v2 every one
7
+ of those was a hand-written action file — a podcast app had **ten files that
8
+ were byte-identical except the table name** (`publish.ts` / `revertToDraft.ts`
9
+ across five entities), and an events app had eight near-identical
10
+ check-in/check-out files.
11
+
12
+ Transitions v2 collapses both patterns:
13
+
14
+ - **Action-level extensions** on `defineAction({ transition })` — guards,
15
+ stamps, idempotency, compiler-applied writes.
16
+ - **Table-level `transitions`** on `defineTable` — the compiler *generates*
17
+ the action files, including `undo` inverses and `onEnter` cascades.
18
+
19
+ ## The marquee example: 10 files → 2 lines each
20
+
21
+ Before (×10 files across episodes/shows/seasons/collections/profiles):
22
+
23
+ ```typescript
24
+ // actions/episodes/publish.ts — and nine siblings like it
25
+ export default defineAction({
26
+ description: "Publish an episode",
27
+ input: z.object({}),
28
+ access: { roles: ["admin+"] },
29
+ async execute({ db, record }) {
30
+ const [updated] = await db.update(episodes)
31
+ .set({ isPublished: true })
32
+ .where(eq(episodes.id, record.id)).returning();
33
+ return updated;
34
+ },
35
+ });
36
+ ```
37
+
38
+ After — on each entity's `defineTable`:
39
+
40
+ ```typescript
41
+ export default defineTable(episodes, {
42
+ // ...
43
+ transitions: {
44
+ publish: { field: "isPublished", from: false, to: true, access: { roles: ["admin+"] } },
45
+ revertToDraft: { field: "isPublished", from: true, to: false, access: { roles: ["admin+"] } },
46
+ },
47
+ });
48
+ ```
49
+
50
+ The generated actions mount exactly where the hand-written files did
51
+ (`POST /episodes/:id/publish`, operationId `episodesPublish`, same MCP tool
52
+ name), ride the same OpenAPI/security-contract pipeline, and delete cleanly:
53
+ **an explicit `actions/<name>.ts` file always wins** (the compiler warns about
54
+ the shadowed transitions entry).
55
+
56
+ ## Action-level extensions
57
+
58
+ All new keys are optional — a plain `{ field, fromTo, to|via }` transition
59
+ behaves exactly as before.
60
+
61
+ ```typescript
62
+ transition: {
63
+ field: "status",
64
+ to: "confirmed",
65
+ fromTo: { pending: ["confirmed"] },
66
+ // v2:
67
+ guard: { // extra row preconditions
68
+ status: "confirmed", // equality
69
+ checkedInAt: { null: true }, // or { notNull: true }
70
+ custom: (record) => record.eventId !== null, // escape hatch; may throw ActionError
71
+ },
72
+ onIllegal: { code: "GUEST_NOT_CONFIRMED", status: 409, message: "Only confirmed guests can be checked in" },
73
+ idempotent: "noop", // already-in-target → { success: true, unchanged: true }
74
+ stamp: { at: "checkedInAt", by: "checkedInById" }, // now-ISO / ctx.userId
75
+ clears: ["checkedOutAt", "checkedOutById"], // nulled on transition
76
+ }
77
+ ```
78
+
79
+ Semantics:
80
+
81
+ - **Guards** run against the fetched record *and* fold into the UPDATE's
82
+ WHERE, so preconditions re-validate atomically at the SQL layer (an empty
83
+ `RETURNING` maps to 409 `ACCESS_TRANSITION_LOST`). Guard failures return
84
+ `onIllegal` (default 409 `TRANSITION_GUARD_FAILED`); on bulk twins they
85
+ report per-id in the batch envelope.
86
+ - **Compiler-applied writes**: declaring `stamp`/`clears` (or
87
+ `applyBefore: true`) makes the compiler execute the UPDATE itself before
88
+ `execute` — and `execute` becomes optional. An omitted `execute` returns
89
+ `{ success: true, <field>: <to>, <stamp.at>: <now> }`. Set
90
+ `applyBefore: false` to keep the write in your own `execute` (today's
91
+ behavior).
92
+ - **`field: null`** declares a pure stamp transition (check-in/check-out
93
+ style) — guards + stamps with no state column.
94
+ - **`actx.now`**: every action's execute context now carries `now` — one ISO
95
+ timestamp per invocation. Prefer it over `new Date().toISOString()`.
96
+
97
+ ## Table-level generation
98
+
99
+ ```typescript
100
+ export default defineTable(guests, {
101
+ // ...
102
+ transitions: {
103
+ checkIn: {
104
+ field: null, // pure stamp transition
105
+ guard: { status: "confirmed", checkedInAt: { null: true } },
106
+ stamp: { at: "checkedInAt", by: "checkedInById" },
107
+ undo: "cancelCheckIn", // generates the inverse
108
+ access: { roles: ["member+"] },
109
+ bulkVariant: true,
110
+ },
111
+ cancel: {
112
+ field: "status",
113
+ fromTo: { published: ["cancelled"] },
114
+ to: "cancelled",
115
+ stamp: { at: "cancelledAt" },
116
+ access: { roles: ["admin+"] },
117
+ onEnter: [
118
+ { update: "eventGuests",
119
+ set: { status: "rescinded" },
120
+ where: { eventId: "$record.id", status: { in: ["invited", "confirmed"] } } },
121
+ { enqueue: { queue: "COMMS_QUEUE",
122
+ message: { kind: "eventCancelled", eventId: "$record.id", actorId: "$ctx.userId" } } },
123
+ ],
124
+ },
125
+ },
126
+ });
127
+ ```
128
+
129
+ - **`undo: "<name>"`** generates the inverse action: the guard flips to
130
+ `{ notNull: true }` on the stamp column, the SET nulls the stamp columns,
131
+ and `from`/`to` reverse for field transitions.
132
+ - **`onEnter` steps** run in the generated `execute`, *after* the
133
+ compiler-applied primary write (parent row first). `update` steps go
134
+ through the scoped db — cross-feature targets resolve automatically and
135
+ inherit the firewall. `enqueue` steps ride the after-commit effects queue.
136
+ Substitution values are a strict allowlist — `$record.<col>`,
137
+ `$ctx.userId`, `$ctx.activeOrgId`, `$ctx.<scope>.id` — always
138
+ parameterized, never interpolated into SQL.
139
+ - **`access` is required** on every transition (fail-closed, like
140
+ `defineAction`).
141
+ - Boolean `from` values match integer-boolean columns too (`from: false`
142
+ matches both `false` and `0`).
143
+
144
+ ### Not yet supported (fail loudly)
145
+
146
+ `guard.custom` at table level, `onEnter.enqueue` with `perRowOf` or function
147
+ messages, and via-style (input-driven) targets all error with a pointer to a
148
+ hand-written action. For manual fan-out enqueues, `sendQueueBatched` in
149
+ `lib/effects` chunks at the Cloudflare Queues 100-message cap.