@quickback-dev/cli 0.66.19 → 0.66.20
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.
- package/dist/index.js +1 -1
- package/dist/skill/SKILL.md +18 -0
- package/dist/skill/docs/api/actions.md +1 -1
- package/dist/skill/docs/api/typescript.md +2 -1
- package/dist/skill/docs/define/actions/defining.md +1 -0
- package/dist/skill/docs/define/actions/index.md +17 -2
- package/dist/skill/docs/define/actions/record-and-standalone.md +43 -0
- package/dist/skill/docs/define/actions/scoped-db.md +6 -0
- package/dist/skill/docs/define/changesets.md +24 -4
- package/dist/skill/docs/define/schema.md +33 -1
- package/dist/skill/docs/platform/webhooks/inbound.md +20 -7
- package/package.json +1 -1
- package/src/skill/SKILL.md +18 -0
- package/src/skill/docs/api/actions.md +1 -1
- package/src/skill/docs/api/typescript.md +2 -1
- package/src/skill/docs/define/actions/defining.md +1 -0
- package/src/skill/docs/define/actions/index.md +17 -2
- package/src/skill/docs/define/actions/record-and-standalone.md +43 -0
- package/src/skill/docs/define/actions/scoped-db.md +6 -0
- package/src/skill/docs/define/changesets.md +24 -4
- package/src/skill/docs/define/schema.md +33 -1
- package/src/skill/docs/platform/webhooks/inbound.md +20 -7
package/dist/index.js
CHANGED
package/dist/skill/SKILL.md
CHANGED
|
@@ -264,9 +264,27 @@ The action context's `db` is a Drizzle wrapper that:
|
|
|
264
264
|
- **Does** route soft-delete `delete()` calls to a `deletedAt` / `deletedBy` UPDATE.
|
|
265
265
|
- **Does** auto-populate scope columns on `insert`: any `q.scope()` column (and firewall-declared org/owner/team columns) is filled from ctx — `organizationId` ← `ctx.activeOrgId`, `ownerId` ← `ctx.userId`, etc. Audit fields (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`) are hard-stamped by the audit wrapper; caller-supplied values for them are dropped.
|
|
266
266
|
- **Does NOT** fill ordinary business columns — anything that isn't a scope or audit column is exactly what you pass to `.values({...})`.
|
|
267
|
+
- **Refuses** Drizzle's relational API (`db.query.<table>.findFirst/findMany`, `with:`) — it can't be firewalled, so it's a compile error. Use `db.select()` joins.
|
|
267
268
|
|
|
268
269
|
For unscoped writes (cross-tenant support, platform admin), use the `unsafe:` object form on the action — it forces an audit reason and gates on platform admin role.
|
|
269
270
|
|
|
271
|
+
## Relationships between tables
|
|
272
|
+
|
|
273
|
+
There is no Drizzle `relations()` in feature code — never author or generate it. Relationships are:
|
|
274
|
+
|
|
275
|
+
| Shape | Declare |
|
|
276
|
+
|---|---|
|
|
277
|
+
| Belongs-to (post → author) | `authorId: q.text().required().references(() => users.id)` — DB constraint, `Id` type brand, CMS typeahead + labels. Cross-feature target: `import users from "../users/users"`. |
|
|
278
|
+
| Embed the parent on reads | `read: { include: ["authorId"] }` → `GET /posts?include=authorId` (top-level `included` map, depth 1, target's access/firewall/masking apply) |
|
|
279
|
+
| Owned children (order → line items) | `owns: { lineItems: { table: "orderLineItems", fk: "orderId" } }` — atomic nested writes via changesets |
|
|
280
|
+
| Embed owned children on reads | `read: { include: ["lineItems"] }` → `GET /orders/:id?include=lineItems` |
|
|
281
|
+
| Non-owned has-many (user → posts) | FK on the child only; clients call `GET /posts?userId=…` (or `defineBundle` for many lists in one trip). No inline embed. |
|
|
282
|
+
| Value object with no identity (address) | `q.json()` |
|
|
283
|
+
|
|
284
|
+
Never `.references()` a Better Auth id (`userId`, `organizationId`, `memberId`) — auth rows live in `AUTH_DB`. `include` targets must have role-only `read.access` (record-aware targets are a compile error), so don't add every FK by reflex.
|
|
285
|
+
|
|
286
|
+
Details: `quickback docs define/schema` (References), `quickback docs define/read` (Aggregate Reads), `quickback docs define/changesets`.
|
|
287
|
+
|
|
270
288
|
## Error handling in actions
|
|
271
289
|
|
|
272
290
|
To return a clean 4xx from an action, throw `ActionError` — the route handler catches it by name and returns `{ error, code, details }` with your status:
|
|
@@ -243,7 +243,7 @@ export default defineAction({
|
|
|
243
243
|
access: { roles: ['PUBLIC'] },
|
|
244
244
|
unsafe: {
|
|
245
245
|
reason: 'Inbound mail webhook — tenant derived from mailbox record',
|
|
246
|
-
|
|
246
|
+
crossTenant: false, // the default (true) requires a sysadmin session — an anonymous webhook would 403
|
|
247
247
|
},
|
|
248
248
|
input: z.object({ mailboxId: z.string(), body: z.string() }),
|
|
249
249
|
async execute({ unsafeDb, input }) {
|
|
@@ -44,7 +44,8 @@ Each resource table exposes:
|
|
|
44
44
|
|
|
45
45
|
Column types follow the wire, not the storage: `q.bool()` and
|
|
46
46
|
`integer(..., { mode: "boolean" })` are `boolean`, `integer(..., { mode: "timestamp" })`
|
|
47
|
-
and `q.timestamp()` are ISO `string`, `q.json()` is `unknown
|
|
47
|
+
and `q.timestamp()` are ISO `string`, `q.json()` is `unknown` unless it is given a
|
|
48
|
+
[value schema](/define/schema#typed-json-columns), enum columns
|
|
48
49
|
are literal unions, and nullable columns add `| null`.
|
|
49
50
|
|
|
50
51
|
Primary and foreign keys are branded by default. That makes accidentally passing a candidate ID where a job ID is required a TypeScript error, while both values remain ordinary strings or numbers at runtime.
|
|
@@ -220,6 +220,7 @@ namespace parameters.
|
|
|
220
220
|
|--------|----------|-------------|
|
|
221
221
|
| `description` | Yes | Human-readable description of the action |
|
|
222
222
|
| `input` | Yes | Zod schema for request validation |
|
|
223
|
+
| `query` | No | Non-GET only. An inline `z.object({...})` of query-string parameters, validated apart from the JSON body and passed to `execute` as `query`. See [Query parameters on non-GET actions](/define/actions/record-and-standalone#query-parameters-on-non-get-actions) |
|
|
223
224
|
| `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |
|
|
224
225
|
| `access` | Yes | Access control (roles, record conditions, or function) |
|
|
225
226
|
| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
|
|
@@ -166,10 +166,25 @@ Fail-closed, one rule:
|
|
|
166
166
|
The compile fails if the named action is missing, bound to a different table,
|
|
167
167
|
the wrong shape (create needs a standalone `path:` equal to the collection URL;
|
|
168
168
|
update/delete need a record-based action with no `path:`), declares a
|
|
169
|
-
conflicting `method`, is already mapped to another verb
|
|
170
|
-
declares `owns` (changeset dispatch lives on the stock handler). `read.action`
|
|
169
|
+
conflicting `method`, or is already mapped to another verb. `read.action`
|
|
171
170
|
is not supported.
|
|
172
171
|
|
|
172
|
+
### Mapping a verb on an `owns` root
|
|
173
|
+
|
|
174
|
+
A table that declares [`owns`](/define/changesets) can map `create` or `update`
|
|
175
|
+
too. The action is then the only write path for that verb:
|
|
176
|
+
|
|
177
|
+
- A request to that verb with `Content-Type: application/vnd.quickback.changeset+json`
|
|
178
|
+
gets a `415`. It doesn't bypass the action, and the action's `input` doesn't
|
|
179
|
+
silently drop the child ops.
|
|
180
|
+
- OpenAPI documents only `application/json` for that operation. The unmapped
|
|
181
|
+
verb keeps its changeset lane.
|
|
182
|
+
- The changeset engine is still generated, so the action can take child
|
|
183
|
+
changes in its own `input` and delegate the aggregate write to
|
|
184
|
+
[`apply<Singular>Changeset`](/define/changesets#calling-it-from-authored-code)
|
|
185
|
+
(set `singular:` on the root if the default name reads wrong).
|
|
186
|
+
The root's crud access, guards and firewall still run inside it.
|
|
187
|
+
|
|
173
188
|
## The rest of this section
|
|
174
189
|
|
|
175
190
|
- **[Defining actions](/define/actions/defining)** — the action file, its configuration options, protected fields, and refs
|
|
@@ -420,3 +420,46 @@ imply "this writes data" — it's the right method whenever the request body is
|
|
|
420
420
|
load-bearing. Use the response shape (`responseType: "json"`, or just the data
|
|
421
421
|
your handler returns) to convey read semantics; HTTP method choice is about
|
|
422
422
|
input transport, not action intent.
|
|
423
|
+
|
|
424
|
+
### Query parameters on non-GET actions
|
|
425
|
+
|
|
426
|
+
A POST, PUT, PATCH or DELETE action can take query-string parameters as well as
|
|
427
|
+
its JSON body. Declare them with `query:`. They are validated apart from
|
|
428
|
+
`input` and passed to `execute` as `query`. This also works when the body is a
|
|
429
|
+
bare array:
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
// features/journal-entries/actions/bulkCreate.ts — POST /bulk/journal-entries?expand=lines
|
|
433
|
+
import { z } from "zod";
|
|
434
|
+
import { defineAction } from "../.quickback/define-action";
|
|
435
|
+
|
|
436
|
+
export default defineAction({
|
|
437
|
+
description: "Create journal entries in bulk; ?expand=lines includes their lines.",
|
|
438
|
+
method: "POST",
|
|
439
|
+
path: "/bulk/journal-entries",
|
|
440
|
+
input: z.array(z.object({ memo: z.string().optional() })),
|
|
441
|
+
query: z.object({
|
|
442
|
+
expand: z.enum(["lines"]).optional(),
|
|
443
|
+
limit: z.coerce.number().int().max(100).optional(),
|
|
444
|
+
}),
|
|
445
|
+
access: { roles: ["admin"] },
|
|
446
|
+
async execute({ input, query }) {
|
|
447
|
+
// query is { expand?: "lines", limit?: number } — fully typed.
|
|
448
|
+
return { count: input.length, expand: query.expand ?? null };
|
|
449
|
+
},
|
|
450
|
+
});
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
Each property is documented as an `in: query` parameter in `openapi.json`, so
|
|
454
|
+
it also shows up in `api-types.gen.ts`, in `quickback.gen.ts` as
|
|
455
|
+
`actions.<name>.Query`, and on the MCP tool. A bad value is a `400`, the same
|
|
456
|
+
as a bad body.
|
|
457
|
+
|
|
458
|
+
Rules, all checked at compile time:
|
|
459
|
+
|
|
460
|
+
- `query` must be an inline `z.object({...})` built from `z` and literals. The compiler converts it to JSON Schema itself.
|
|
461
|
+
- Not on GET actions. Their `input` already comes from the query string.
|
|
462
|
+
- Not together with `bulkVariant`.
|
|
463
|
+
|
|
464
|
+
Query values arrive as strings, and repeated keys become arrays. Use
|
|
465
|
+
`z.coerce.number()` / `z.coerce.boolean()` for typed primitives.
|
|
@@ -10,6 +10,12 @@ the same generated `WHERE` clause the table's CRUD routes use:
|
|
|
10
10
|
| `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
|
|
11
11
|
| `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
|
|
12
12
|
| `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
|
|
13
|
+
| `INSERT … onConflictDoUpdate` | the firewall AND-merged into `setWhere` — a conflict with a row the caller can't update (another tenant's id) is a no-op, never an overwrite |
|
|
14
|
+
|
|
15
|
+
The firewall is set on the builder when you call `.from()` / `.set()` /
|
|
16
|
+
`.delete()`, so every executor gets it: `await`, `.all()`, `.get()`,
|
|
17
|
+
`.values()`, `.run()`, `.execute()`, `.prepare()`, and the builder embedded as
|
|
18
|
+
a subquery (`inArray(col, db.select(...).from(t))`).
|
|
13
19
|
|
|
14
20
|
It is not a guess from column names. `any:` groups, `optional` arms, scope
|
|
15
21
|
(`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
|
|
@@ -121,9 +121,9 @@ to `"v2"` only if you also want the `/api/v2` prefix.
|
|
|
121
121
|
id — an unresolvable parent lid is a pointer-carrying **400**, never a
|
|
122
122
|
silent re-parent onto the root.
|
|
123
123
|
- `Prefer: return=minimal` omits `root` from the response. v1 representation
|
|
124
|
-
is **root-row-only** (re-read through the root's masking) —
|
|
125
|
-
|
|
126
|
-
|
|
124
|
+
is **root-row-only** (re-read through the root's masking) — read the
|
|
125
|
+
aggregate back with `?include=<ownsRelation>` (see [read → Aggregate
|
|
126
|
+
Reads](/define/read#aggregate-reads)).
|
|
127
127
|
|
|
128
128
|
### Headers
|
|
129
129
|
|
|
@@ -430,7 +430,22 @@ it; `meta.transactional` reports the actual guarantee (same contract as
|
|
|
430
430
|
The engine is exported per root as `apply<Singular>Changeset` — the seam
|
|
431
431
|
authored actions delegate through when they still need residue logic
|
|
432
432
|
(preconditions, server-side transforms, notifications) around the aggregate
|
|
433
|
-
write
|
|
433
|
+
write.
|
|
434
|
+
|
|
435
|
+
`<Singular>` comes from the table name with a trailing `s` dropped, so
|
|
436
|
+
`projects` gives `applyProjectChangeset`. For a name that rule gets wrong,
|
|
437
|
+
declare `singular:` on the root to add a correctly named export:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
// journalEntries would otherwise only export applyJournalEntrieChangeset
|
|
441
|
+
singular: "journalEntry", // adds applyJournalEntryChangeset
|
|
442
|
+
owns: { /* ... */ },
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
The default name is still exported, so existing imports keep working.
|
|
446
|
+
`singular` must be camelCase, and it's a compile error on a table that doesn't
|
|
447
|
+
declare `owns`.
|
|
448
|
+
|
|
434
449
|
|
|
435
450
|
{/* doc-compile: skip — the fence imports `../projects.changeset`, a module the compiler only generates for a root that declares `owns`, which this fence does not carry, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose — the point is the delegation seam. */}
|
|
436
451
|
```ts title="quickback/features/projects/actions/importBoard.ts"
|
|
@@ -450,6 +465,11 @@ export default defineAction({
|
|
|
450
465
|
});
|
|
451
466
|
```
|
|
452
467
|
|
|
468
|
+
This is also how a root that maps `create.action` or `update.action` writes its
|
|
469
|
+
children: the mapped verb has no changeset media type of its own (it answers
|
|
470
|
+
`415`), so its action delegates here. See
|
|
471
|
+
[Mapping a verb on an `owns` root](/define/actions#mapping-a-verb-on-an-owns-root).
|
|
472
|
+
|
|
453
473
|
**There is no trusted mode.** The auth assertion, cross-tenant guard, and the
|
|
454
474
|
root's own pre-record access gate are the helper's first statements — an
|
|
455
475
|
authored action whose action-level access is looser than the root's crud
|
|
@@ -119,7 +119,7 @@ A few mechanics to know:
|
|
|
119
119
|
| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
|
|
120
120
|
| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
|
|
121
121
|
| `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
|
|
122
|
-
| `q.json()` | `jsonb(...)` | `z.unknown()
|
|
122
|
+
| `q.json()` / `q.json(z.object({...}))` | `jsonb(...)` | `z.unknown()`, or the value schema you pass in — see [Typed JSON columns](#typed-json-columns) |
|
|
123
123
|
| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
|
|
124
124
|
| `q.id()` | `text('id').primaryKey()` | `z.string()` |
|
|
125
125
|
| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
|
|
@@ -136,6 +136,38 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
|
|
|
136
136
|
|
|
137
137
|
`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.
|
|
138
138
|
|
|
139
|
+
#### Typed JSON columns
|
|
140
|
+
|
|
141
|
+
Pass `q.json()` a Zod schema to give the column's value a shape. A table file may import `{ z }` from `zod` for this:
|
|
142
|
+
|
|
143
|
+
```typescript title="quickback/features/journal-entries/journal-entries.ts"
|
|
144
|
+
import { feature, q } from "@quickback/compiler";
|
|
145
|
+
import { z } from "zod";
|
|
146
|
+
|
|
147
|
+
export default feature("journalEntries", {
|
|
148
|
+
columns: {
|
|
149
|
+
id: q.id(),
|
|
150
|
+
organizationId: q.scope("organization"),
|
|
151
|
+
autocatResult: q.json(z.object({ method: z.string(), confidence: z.number().min(0).max(1) })).optional(),
|
|
152
|
+
applications: q.json(z.array(z.object({ invoiceId: z.string(), amount: z.string() }))).optional(),
|
|
153
|
+
raw: q.json().optional(),
|
|
154
|
+
...q.audit(),
|
|
155
|
+
...q.softDelete(),
|
|
156
|
+
},
|
|
157
|
+
read: { access: { roles: ["member"] } },
|
|
158
|
+
create: { access: { roles: ["admin"] } },
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The schema validates create and update bodies (and changeset ops), and its JSON Schema types the column in `openapi.json`, `api-types.gen.ts`, `quickback.gen.ts` and the MCP tools. A bare `q.json()` stays `unknown` there. Storage doesn't change: the column is `jsonb` on Postgres and JSON text on SQLite/D1.
|
|
163
|
+
|
|
164
|
+
The schema must be written inline from `z` and literals, because the compiler copies it into the generated routes and converts it to JSON Schema itself. These are compile errors:
|
|
165
|
+
|
|
166
|
+
- a reference to another binding: `q.json(Shape)`, or `z.object({ a: Shape })`
|
|
167
|
+
- a callback such as `.refine(...)` or `.transform(...)`
|
|
168
|
+
- using `z` anywhere else in the table file
|
|
169
|
+
- importing anything from `zod` other than `{ z }`
|
|
170
|
+
|
|
139
171
|
For `generateId: "cuid"`, there is one important nuance: import-capable runtime
|
|
140
172
|
paths can emit real `createId()` usage, but compiler-managed schema
|
|
141
173
|
auto-injection may keep the same `createId()` call site and back it with a
|
|
@@ -352,23 +352,36 @@ provider signed, never over re-serialised JSON.
|
|
|
352
352
|
{/* doc-compile: skip — excerpt: `decryptValue` and the `connections` table live in the generated project; the fence shows the shape only. */}
|
|
353
353
|
```ts title="quickback/features/comms/actions/resendEvents.ts"
|
|
354
354
|
import { z } from "zod";
|
|
355
|
-
import {
|
|
355
|
+
import { eq } from "drizzle-orm";
|
|
356
|
+
import { defineAction, ActionError } from "../.quickback/define-action";
|
|
356
357
|
import { decryptValue } from "../../../../src/lib/encryption";
|
|
358
|
+
import { connections } from "../connections";
|
|
357
359
|
|
|
358
360
|
export default defineAction({
|
|
359
361
|
description: "Per-org Resend events — secret lives on the connection row",
|
|
360
|
-
path: "/resend/events/:
|
|
362
|
+
path: "/resend/events/:connectionId",
|
|
361
363
|
method: "POST",
|
|
362
364
|
access: { roles: ["PUBLIC"] },
|
|
365
|
+
// A webhook carries no session, so no org claim: the scoped `db` reads
|
|
366
|
+
// nothing from an org-scoped table. Look the org up with `unsafeDb`, then
|
|
367
|
+
// pin every later query to it with `scopeTo`. `crossTenant: false` — the
|
|
368
|
+
// default (true) requires a sysadmin session and would 403 every delivery.
|
|
369
|
+
unsafe: { reason: "Resend webhook — tenant resolved from the connection row", crossTenant: false },
|
|
363
370
|
rawBody: true,
|
|
364
371
|
input: z.object({ type: z.string(), data: z.record(z.unknown()) }),
|
|
365
|
-
execute: async ({ c, env,
|
|
366
|
-
const
|
|
367
|
-
|
|
372
|
+
execute: async ({ c, env, unsafeDb, rawBody, input }) => {
|
|
373
|
+
const [conn] = await unsafeDb.select().from(connections)
|
|
374
|
+
.where(eq(connections.id, c.req.param("connectionId")));
|
|
375
|
+
if (!conn) throw new ActionError("Unknown connection", "NOT_FOUND", 404);
|
|
376
|
+
|
|
368
377
|
// ctx.crypto is hydrated for authenticated requests only — a PUBLIC
|
|
369
378
|
// action reads an .encrypted() column through decryptValue directly.
|
|
370
|
-
const secret = await decryptValue(env,
|
|
371
|
-
// verify `rawBody` + the provider's signature headers with `secret`;
|
|
379
|
+
const secret = await decryptValue(env, unsafeDb, conn.organizationId, conn.signingSecret);
|
|
380
|
+
// verify `rawBody` + the provider's signature headers with `secret`;
|
|
381
|
+
// throw a 401 ActionError on failure — BEFORE touching any tenant data.
|
|
382
|
+
|
|
383
|
+
const db = unsafeDb.scopeTo({ organizationId: conn.organizationId });
|
|
384
|
+
// every query on `db` now carries that org's firewall; inserts are stamped with it
|
|
372
385
|
return { ok: true, type: input.type };
|
|
373
386
|
},
|
|
374
387
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quickback-dev/cli",
|
|
3
|
-
"version": "0.66.
|
|
3
|
+
"version": "0.66.20",
|
|
4
4
|
"description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
|
|
5
5
|
"author": "Kardoe Incorporated <paul@kardoe.com>",
|
|
6
6
|
"license": "MIT",
|
package/src/skill/SKILL.md
CHANGED
|
@@ -264,9 +264,27 @@ The action context's `db` is a Drizzle wrapper that:
|
|
|
264
264
|
- **Does** route soft-delete `delete()` calls to a `deletedAt` / `deletedBy` UPDATE.
|
|
265
265
|
- **Does** auto-populate scope columns on `insert`: any `q.scope()` column (and firewall-declared org/owner/team columns) is filled from ctx — `organizationId` ← `ctx.activeOrgId`, `ownerId` ← `ctx.userId`, etc. Audit fields (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`) are hard-stamped by the audit wrapper; caller-supplied values for them are dropped.
|
|
266
266
|
- **Does NOT** fill ordinary business columns — anything that isn't a scope or audit column is exactly what you pass to `.values({...})`.
|
|
267
|
+
- **Refuses** Drizzle's relational API (`db.query.<table>.findFirst/findMany`, `with:`) — it can't be firewalled, so it's a compile error. Use `db.select()` joins.
|
|
267
268
|
|
|
268
269
|
For unscoped writes (cross-tenant support, platform admin), use the `unsafe:` object form on the action — it forces an audit reason and gates on platform admin role.
|
|
269
270
|
|
|
271
|
+
## Relationships between tables
|
|
272
|
+
|
|
273
|
+
There is no Drizzle `relations()` in feature code — never author or generate it. Relationships are:
|
|
274
|
+
|
|
275
|
+
| Shape | Declare |
|
|
276
|
+
|---|---|
|
|
277
|
+
| Belongs-to (post → author) | `authorId: q.text().required().references(() => users.id)` — DB constraint, `Id` type brand, CMS typeahead + labels. Cross-feature target: `import users from "../users/users"`. |
|
|
278
|
+
| Embed the parent on reads | `read: { include: ["authorId"] }` → `GET /posts?include=authorId` (top-level `included` map, depth 1, target's access/firewall/masking apply) |
|
|
279
|
+
| Owned children (order → line items) | `owns: { lineItems: { table: "orderLineItems", fk: "orderId" } }` — atomic nested writes via changesets |
|
|
280
|
+
| Embed owned children on reads | `read: { include: ["lineItems"] }` → `GET /orders/:id?include=lineItems` |
|
|
281
|
+
| Non-owned has-many (user → posts) | FK on the child only; clients call `GET /posts?userId=…` (or `defineBundle` for many lists in one trip). No inline embed. |
|
|
282
|
+
| Value object with no identity (address) | `q.json()` |
|
|
283
|
+
|
|
284
|
+
Never `.references()` a Better Auth id (`userId`, `organizationId`, `memberId`) — auth rows live in `AUTH_DB`. `include` targets must have role-only `read.access` (record-aware targets are a compile error), so don't add every FK by reflex.
|
|
285
|
+
|
|
286
|
+
Details: `quickback docs define/schema` (References), `quickback docs define/read` (Aggregate Reads), `quickback docs define/changesets`.
|
|
287
|
+
|
|
270
288
|
## Error handling in actions
|
|
271
289
|
|
|
272
290
|
To return a clean 4xx from an action, throw `ActionError` — the route handler catches it by name and returns `{ error, code, details }` with your status:
|
|
@@ -243,7 +243,7 @@ export default defineAction({
|
|
|
243
243
|
access: { roles: ['PUBLIC'] },
|
|
244
244
|
unsafe: {
|
|
245
245
|
reason: 'Inbound mail webhook — tenant derived from mailbox record',
|
|
246
|
-
|
|
246
|
+
crossTenant: false, // the default (true) requires a sysadmin session — an anonymous webhook would 403
|
|
247
247
|
},
|
|
248
248
|
input: z.object({ mailboxId: z.string(), body: z.string() }),
|
|
249
249
|
async execute({ unsafeDb, input }) {
|
|
@@ -44,7 +44,8 @@ Each resource table exposes:
|
|
|
44
44
|
|
|
45
45
|
Column types follow the wire, not the storage: `q.bool()` and
|
|
46
46
|
`integer(..., { mode: "boolean" })` are `boolean`, `integer(..., { mode: "timestamp" })`
|
|
47
|
-
and `q.timestamp()` are ISO `string`, `q.json()` is `unknown
|
|
47
|
+
and `q.timestamp()` are ISO `string`, `q.json()` is `unknown` unless it is given a
|
|
48
|
+
[value schema](/define/schema#typed-json-columns), enum columns
|
|
48
49
|
are literal unions, and nullable columns add `| null`.
|
|
49
50
|
|
|
50
51
|
Primary and foreign keys are branded by default. That makes accidentally passing a candidate ID where a job ID is required a TypeScript error, while both values remain ordinary strings or numbers at runtime.
|
|
@@ -220,6 +220,7 @@ namespace parameters.
|
|
|
220
220
|
|--------|----------|-------------|
|
|
221
221
|
| `description` | Yes | Human-readable description of the action |
|
|
222
222
|
| `input` | Yes | Zod schema for request validation |
|
|
223
|
+
| `query` | No | Non-GET only. An inline `z.object({...})` of query-string parameters, validated apart from the JSON body and passed to `execute` as `query`. See [Query parameters on non-GET actions](/define/actions/record-and-standalone#query-parameters-on-non-get-actions) |
|
|
223
224
|
| `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |
|
|
224
225
|
| `access` | Yes | Access control (roles, record conditions, or function) |
|
|
225
226
|
| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
|
|
@@ -166,10 +166,25 @@ Fail-closed, one rule:
|
|
|
166
166
|
The compile fails if the named action is missing, bound to a different table,
|
|
167
167
|
the wrong shape (create needs a standalone `path:` equal to the collection URL;
|
|
168
168
|
update/delete need a record-based action with no `path:`), declares a
|
|
169
|
-
conflicting `method`, is already mapped to another verb
|
|
170
|
-
declares `owns` (changeset dispatch lives on the stock handler). `read.action`
|
|
169
|
+
conflicting `method`, or is already mapped to another verb. `read.action`
|
|
171
170
|
is not supported.
|
|
172
171
|
|
|
172
|
+
### Mapping a verb on an `owns` root
|
|
173
|
+
|
|
174
|
+
A table that declares [`owns`](/define/changesets) can map `create` or `update`
|
|
175
|
+
too. The action is then the only write path for that verb:
|
|
176
|
+
|
|
177
|
+
- A request to that verb with `Content-Type: application/vnd.quickback.changeset+json`
|
|
178
|
+
gets a `415`. It doesn't bypass the action, and the action's `input` doesn't
|
|
179
|
+
silently drop the child ops.
|
|
180
|
+
- OpenAPI documents only `application/json` for that operation. The unmapped
|
|
181
|
+
verb keeps its changeset lane.
|
|
182
|
+
- The changeset engine is still generated, so the action can take child
|
|
183
|
+
changes in its own `input` and delegate the aggregate write to
|
|
184
|
+
[`apply<Singular>Changeset`](/define/changesets#calling-it-from-authored-code)
|
|
185
|
+
(set `singular:` on the root if the default name reads wrong).
|
|
186
|
+
The root's crud access, guards and firewall still run inside it.
|
|
187
|
+
|
|
173
188
|
## The rest of this section
|
|
174
189
|
|
|
175
190
|
- **[Defining actions](/define/actions/defining)** — the action file, its configuration options, protected fields, and refs
|
|
@@ -420,3 +420,46 @@ imply "this writes data" — it's the right method whenever the request body is
|
|
|
420
420
|
load-bearing. Use the response shape (`responseType: "json"`, or just the data
|
|
421
421
|
your handler returns) to convey read semantics; HTTP method choice is about
|
|
422
422
|
input transport, not action intent.
|
|
423
|
+
|
|
424
|
+
### Query parameters on non-GET actions
|
|
425
|
+
|
|
426
|
+
A POST, PUT, PATCH or DELETE action can take query-string parameters as well as
|
|
427
|
+
its JSON body. Declare them with `query:`. They are validated apart from
|
|
428
|
+
`input` and passed to `execute` as `query`. This also works when the body is a
|
|
429
|
+
bare array:
|
|
430
|
+
|
|
431
|
+
```typescript
|
|
432
|
+
// features/journal-entries/actions/bulkCreate.ts — POST /bulk/journal-entries?expand=lines
|
|
433
|
+
import { z } from "zod";
|
|
434
|
+
import { defineAction } from "../.quickback/define-action";
|
|
435
|
+
|
|
436
|
+
export default defineAction({
|
|
437
|
+
description: "Create journal entries in bulk; ?expand=lines includes their lines.",
|
|
438
|
+
method: "POST",
|
|
439
|
+
path: "/bulk/journal-entries",
|
|
440
|
+
input: z.array(z.object({ memo: z.string().optional() })),
|
|
441
|
+
query: z.object({
|
|
442
|
+
expand: z.enum(["lines"]).optional(),
|
|
443
|
+
limit: z.coerce.number().int().max(100).optional(),
|
|
444
|
+
}),
|
|
445
|
+
access: { roles: ["admin"] },
|
|
446
|
+
async execute({ input, query }) {
|
|
447
|
+
// query is { expand?: "lines", limit?: number } — fully typed.
|
|
448
|
+
return { count: input.length, expand: query.expand ?? null };
|
|
449
|
+
},
|
|
450
|
+
});
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
Each property is documented as an `in: query` parameter in `openapi.json`, so
|
|
454
|
+
it also shows up in `api-types.gen.ts`, in `quickback.gen.ts` as
|
|
455
|
+
`actions.<name>.Query`, and on the MCP tool. A bad value is a `400`, the same
|
|
456
|
+
as a bad body.
|
|
457
|
+
|
|
458
|
+
Rules, all checked at compile time:
|
|
459
|
+
|
|
460
|
+
- `query` must be an inline `z.object({...})` built from `z` and literals. The compiler converts it to JSON Schema itself.
|
|
461
|
+
- Not on GET actions. Their `input` already comes from the query string.
|
|
462
|
+
- Not together with `bulkVariant`.
|
|
463
|
+
|
|
464
|
+
Query values arrive as strings, and repeated keys become arrays. Use
|
|
465
|
+
`z.coerce.number()` / `z.coerce.boolean()` for typed primitives.
|
|
@@ -10,6 +10,12 @@ the same generated `WHERE` clause the table's CRUD routes use:
|
|
|
10
10
|
| `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
|
|
11
11
|
| `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
|
|
12
12
|
| `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
|
|
13
|
+
| `INSERT … onConflictDoUpdate` | the firewall AND-merged into `setWhere` — a conflict with a row the caller can't update (another tenant's id) is a no-op, never an overwrite |
|
|
14
|
+
|
|
15
|
+
The firewall is set on the builder when you call `.from()` / `.set()` /
|
|
16
|
+
`.delete()`, so every executor gets it: `await`, `.all()`, `.get()`,
|
|
17
|
+
`.values()`, `.run()`, `.execute()`, `.prepare()`, and the builder embedded as
|
|
18
|
+
a subquery (`inArray(col, db.select(...).from(t))`).
|
|
13
19
|
|
|
14
20
|
It is not a guess from column names. `any:` groups, `optional` arms, scope
|
|
15
21
|
(`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
|
|
@@ -121,9 +121,9 @@ to `"v2"` only if you also want the `/api/v2` prefix.
|
|
|
121
121
|
id — an unresolvable parent lid is a pointer-carrying **400**, never a
|
|
122
122
|
silent re-parent onto the root.
|
|
123
123
|
- `Prefer: return=minimal` omits `root` from the response. v1 representation
|
|
124
|
-
is **root-row-only** (re-read through the root's masking) —
|
|
125
|
-
|
|
126
|
-
|
|
124
|
+
is **root-row-only** (re-read through the root's masking) — read the
|
|
125
|
+
aggregate back with `?include=<ownsRelation>` (see [read → Aggregate
|
|
126
|
+
Reads](/define/read#aggregate-reads)).
|
|
127
127
|
|
|
128
128
|
### Headers
|
|
129
129
|
|
|
@@ -430,7 +430,22 @@ it; `meta.transactional` reports the actual guarantee (same contract as
|
|
|
430
430
|
The engine is exported per root as `apply<Singular>Changeset` — the seam
|
|
431
431
|
authored actions delegate through when they still need residue logic
|
|
432
432
|
(preconditions, server-side transforms, notifications) around the aggregate
|
|
433
|
-
write
|
|
433
|
+
write.
|
|
434
|
+
|
|
435
|
+
`<Singular>` comes from the table name with a trailing `s` dropped, so
|
|
436
|
+
`projects` gives `applyProjectChangeset`. For a name that rule gets wrong,
|
|
437
|
+
declare `singular:` on the root to add a correctly named export:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
// journalEntries would otherwise only export applyJournalEntrieChangeset
|
|
441
|
+
singular: "journalEntry", // adds applyJournalEntryChangeset
|
|
442
|
+
owns: { /* ... */ },
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
The default name is still exported, so existing imports keep working.
|
|
446
|
+
`singular` must be camelCase, and it's a compile error on a table that doesn't
|
|
447
|
+
declare `owns`.
|
|
448
|
+
|
|
434
449
|
|
|
435
450
|
{/* doc-compile: skip — the fence imports `../projects.changeset`, a module the compiler only generates for a root that declares `owns`, which this fence does not carry, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose — the point is the delegation seam. */}
|
|
436
451
|
```ts title="quickback/features/projects/actions/importBoard.ts"
|
|
@@ -450,6 +465,11 @@ export default defineAction({
|
|
|
450
465
|
});
|
|
451
466
|
```
|
|
452
467
|
|
|
468
|
+
This is also how a root that maps `create.action` or `update.action` writes its
|
|
469
|
+
children: the mapped verb has no changeset media type of its own (it answers
|
|
470
|
+
`415`), so its action delegates here. See
|
|
471
|
+
[Mapping a verb on an `owns` root](/define/actions#mapping-a-verb-on-an-owns-root).
|
|
472
|
+
|
|
453
473
|
**There is no trusted mode.** The auth assertion, cross-tenant guard, and the
|
|
454
474
|
root's own pre-record access gate are the helper's first statements — an
|
|
455
475
|
authored action whose action-level access is looser than the root's crud
|
|
@@ -119,7 +119,7 @@ A few mechanics to know:
|
|
|
119
119
|
| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
|
|
120
120
|
| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
|
|
121
121
|
| `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
|
|
122
|
-
| `q.json()` | `jsonb(...)` | `z.unknown()
|
|
122
|
+
| `q.json()` / `q.json(z.object({...}))` | `jsonb(...)` | `z.unknown()`, or the value schema you pass in — see [Typed JSON columns](#typed-json-columns) |
|
|
123
123
|
| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
|
|
124
124
|
| `q.id()` | `text('id').primaryKey()` | `z.string()` |
|
|
125
125
|
| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
|
|
@@ -136,6 +136,38 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
|
|
|
136
136
|
|
|
137
137
|
`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.
|
|
138
138
|
|
|
139
|
+
#### Typed JSON columns
|
|
140
|
+
|
|
141
|
+
Pass `q.json()` a Zod schema to give the column's value a shape. A table file may import `{ z }` from `zod` for this:
|
|
142
|
+
|
|
143
|
+
```typescript title="quickback/features/journal-entries/journal-entries.ts"
|
|
144
|
+
import { feature, q } from "@quickback/compiler";
|
|
145
|
+
import { z } from "zod";
|
|
146
|
+
|
|
147
|
+
export default feature("journalEntries", {
|
|
148
|
+
columns: {
|
|
149
|
+
id: q.id(),
|
|
150
|
+
organizationId: q.scope("organization"),
|
|
151
|
+
autocatResult: q.json(z.object({ method: z.string(), confidence: z.number().min(0).max(1) })).optional(),
|
|
152
|
+
applications: q.json(z.array(z.object({ invoiceId: z.string(), amount: z.string() }))).optional(),
|
|
153
|
+
raw: q.json().optional(),
|
|
154
|
+
...q.audit(),
|
|
155
|
+
...q.softDelete(),
|
|
156
|
+
},
|
|
157
|
+
read: { access: { roles: ["member"] } },
|
|
158
|
+
create: { access: { roles: ["admin"] } },
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The schema validates create and update bodies (and changeset ops), and its JSON Schema types the column in `openapi.json`, `api-types.gen.ts`, `quickback.gen.ts` and the MCP tools. A bare `q.json()` stays `unknown` there. Storage doesn't change: the column is `jsonb` on Postgres and JSON text on SQLite/D1.
|
|
163
|
+
|
|
164
|
+
The schema must be written inline from `z` and literals, because the compiler copies it into the generated routes and converts it to JSON Schema itself. These are compile errors:
|
|
165
|
+
|
|
166
|
+
- a reference to another binding: `q.json(Shape)`, or `z.object({ a: Shape })`
|
|
167
|
+
- a callback such as `.refine(...)` or `.transform(...)`
|
|
168
|
+
- using `z` anywhere else in the table file
|
|
169
|
+
- importing anything from `zod` other than `{ z }`
|
|
170
|
+
|
|
139
171
|
For `generateId: "cuid"`, there is one important nuance: import-capable runtime
|
|
140
172
|
paths can emit real `createId()` usage, but compiler-managed schema
|
|
141
173
|
auto-injection may keep the same `createId()` call site and back it with a
|
|
@@ -352,23 +352,36 @@ provider signed, never over re-serialised JSON.
|
|
|
352
352
|
{/* doc-compile: skip — excerpt: `decryptValue` and the `connections` table live in the generated project; the fence shows the shape only. */}
|
|
353
353
|
```ts title="quickback/features/comms/actions/resendEvents.ts"
|
|
354
354
|
import { z } from "zod";
|
|
355
|
-
import {
|
|
355
|
+
import { eq } from "drizzle-orm";
|
|
356
|
+
import { defineAction, ActionError } from "../.quickback/define-action";
|
|
356
357
|
import { decryptValue } from "../../../../src/lib/encryption";
|
|
358
|
+
import { connections } from "../connections";
|
|
357
359
|
|
|
358
360
|
export default defineAction({
|
|
359
361
|
description: "Per-org Resend events — secret lives on the connection row",
|
|
360
|
-
path: "/resend/events/:
|
|
362
|
+
path: "/resend/events/:connectionId",
|
|
361
363
|
method: "POST",
|
|
362
364
|
access: { roles: ["PUBLIC"] },
|
|
365
|
+
// A webhook carries no session, so no org claim: the scoped `db` reads
|
|
366
|
+
// nothing from an org-scoped table. Look the org up with `unsafeDb`, then
|
|
367
|
+
// pin every later query to it with `scopeTo`. `crossTenant: false` — the
|
|
368
|
+
// default (true) requires a sysadmin session and would 403 every delivery.
|
|
369
|
+
unsafe: { reason: "Resend webhook — tenant resolved from the connection row", crossTenant: false },
|
|
363
370
|
rawBody: true,
|
|
364
371
|
input: z.object({ type: z.string(), data: z.record(z.unknown()) }),
|
|
365
|
-
execute: async ({ c, env,
|
|
366
|
-
const
|
|
367
|
-
|
|
372
|
+
execute: async ({ c, env, unsafeDb, rawBody, input }) => {
|
|
373
|
+
const [conn] = await unsafeDb.select().from(connections)
|
|
374
|
+
.where(eq(connections.id, c.req.param("connectionId")));
|
|
375
|
+
if (!conn) throw new ActionError("Unknown connection", "NOT_FOUND", 404);
|
|
376
|
+
|
|
368
377
|
// ctx.crypto is hydrated for authenticated requests only — a PUBLIC
|
|
369
378
|
// action reads an .encrypted() column through decryptValue directly.
|
|
370
|
-
const secret = await decryptValue(env,
|
|
371
|
-
// verify `rawBody` + the provider's signature headers with `secret`;
|
|
379
|
+
const secret = await decryptValue(env, unsafeDb, conn.organizationId, conn.signingSecret);
|
|
380
|
+
// verify `rawBody` + the provider's signature headers with `secret`;
|
|
381
|
+
// throw a 401 ActionError on failure — BEFORE touching any tenant data.
|
|
382
|
+
|
|
383
|
+
const db = unsafeDb.scopeTo({ organizationId: conn.organizationId });
|
|
384
|
+
// every query on `db` now carries that org's firewall; inserts are stamped with it
|
|
372
385
|
return { ok: true, type: input.type };
|
|
373
386
|
},
|
|
374
387
|
});
|