@quickback-dev/cli 0.10.2 → 0.10.4

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 (48) hide show
  1. package/dist/commands/compile.d.ts +9 -1
  2. package/dist/commands/compile.d.ts.map +1 -1
  3. package/dist/commands/compile.js +44 -13
  4. package/dist/commands/compile.js.map +1 -1
  5. package/dist/commands/init.d.ts.map +1 -1
  6. package/dist/commands/init.js +22 -0
  7. package/dist/commands/init.js.map +1 -1
  8. package/dist/cursor/quickback.mdc +24 -13
  9. package/dist/docs/content.js +11 -11
  10. package/dist/docs/content.js.map +1 -1
  11. package/dist/index.js +3 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/lib/api-client.d.ts +15 -0
  14. package/dist/lib/api-client.d.ts.map +1 -1
  15. package/dist/lib/api-client.js +31 -2
  16. package/dist/lib/api-client.js.map +1 -1
  17. package/dist/lib/api-client.test.js +58 -0
  18. package/dist/lib/api-client.test.js.map +1 -1
  19. package/dist/lib/config-sync.d.ts +55 -0
  20. package/dist/lib/config-sync.d.ts.map +1 -0
  21. package/dist/lib/config-sync.js +207 -0
  22. package/dist/lib/config-sync.js.map +1 -0
  23. package/dist/lib/config-sync.test.d.ts +2 -0
  24. package/dist/lib/config-sync.test.d.ts.map +1 -0
  25. package/dist/lib/config-sync.test.js +151 -0
  26. package/dist/lib/config-sync.test.js.map +1 -0
  27. package/dist/lib/prepare-output.d.ts +31 -0
  28. package/dist/lib/prepare-output.d.ts.map +1 -0
  29. package/dist/lib/prepare-output.js +95 -0
  30. package/dist/lib/prepare-output.js.map +1 -0
  31. package/dist/lib/prepare-output.test.d.ts +2 -0
  32. package/dist/lib/prepare-output.test.d.ts.map +1 -0
  33. package/dist/lib/prepare-output.test.js +105 -0
  34. package/dist/lib/prepare-output.test.js.map +1 -0
  35. package/dist/lib/sweep-stale.d.ts +25 -0
  36. package/dist/lib/sweep-stale.d.ts.map +1 -0
  37. package/dist/lib/sweep-stale.js +179 -0
  38. package/dist/lib/sweep-stale.js.map +1 -0
  39. package/dist/lib/sweep-stale.test.d.ts +2 -0
  40. package/dist/lib/sweep-stale.test.d.ts.map +1 -0
  41. package/dist/lib/sweep-stale.test.js +130 -0
  42. package/dist/lib/sweep-stale.test.js.map +1 -0
  43. package/dist/skill/SKILL.md +245 -52
  44. package/dist/skill/agents/quickback-specialist/AGENT.md +42 -36
  45. package/package.json +1 -1
  46. package/src/cursor/quickback.mdc +24 -13
  47. package/src/skill/SKILL.md +245 -52
  48. package/src/skill/agents/quickback-specialist/AGENT.md +42 -36
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=sweep-stale.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sweep-stale.test.d.ts","sourceRoot":"","sources":["../../src/lib/sweep-stale.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,130 @@
1
+ import { describe, expect, test, beforeEach, afterEach } from 'bun:test';
2
+ import { promises as fs } from 'fs';
3
+ import { join, sep } from 'path';
4
+ import { tmpdir } from 'os';
5
+ import { sweepStaleGeneratedFiles } from './sweep-stale.js';
6
+ const HEADER = '/**\n * Generated by quickback.dev\n */\n';
7
+ const PLAIN = '// hand-authored content\n';
8
+ let tmp;
9
+ beforeEach(async () => {
10
+ tmp = await fs.mkdtemp(join(tmpdir(), 'sweep-stale-'));
11
+ });
12
+ afterEach(async () => {
13
+ await fs.rm(tmp, { recursive: true, force: true }).catch(() => { });
14
+ });
15
+ async function writeFile(rel, content) {
16
+ const full = join(tmp, ...rel.split('/'));
17
+ await fs.mkdir(join(full, '..'), { recursive: true });
18
+ await fs.writeFile(full, content);
19
+ }
20
+ async function fileExists(rel) {
21
+ try {
22
+ await fs.access(join(tmp, ...rel.split('/')));
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ describe('sweepStaleGeneratedFiles', () => {
30
+ // User story: As a developer who renames a feature, I want stale generator
31
+ // output from the old name to disappear so my project tree reflects only
32
+ // what the current config produces — no ghost routes/types lingering.
33
+ test('deletes generated files not in the manifest', async () => {
34
+ await writeFile('src/features/old/schema.ts', HEADER);
35
+ await writeFile('src/features/new/schema.ts', HEADER);
36
+ const result = await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts']);
37
+ expect(result.deleted.sort()).toEqual(['src/features/old/schema.ts']);
38
+ expect(await fileExists('src/features/old/schema.ts')).toBe(false);
39
+ expect(await fileExists('src/features/new/schema.ts')).toBe(true);
40
+ });
41
+ // User story: As a developer who pasted a personal note into src/, I want
42
+ // the sweep to leave my hand-authored file alone — the header check is the
43
+ // line between "compiler owns this" and "the user owns this".
44
+ test('preserves files without the generated-header marker', async () => {
45
+ await writeFile('src/features/new/notes.md', PLAIN);
46
+ await writeFile('src/features/new/schema.ts', HEADER);
47
+ const result = await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts']);
48
+ expect(result.deleted).toEqual([]);
49
+ expect(result.preserved).toEqual(['src/features/new/notes.md']);
50
+ expect(await fileExists('src/features/new/notes.md')).toBe(true);
51
+ });
52
+ // User story: As a developer running quickback compile back-to-back with no
53
+ // changes, I want the sweep to be a fast no-op — no spurious archive dirs
54
+ // littering the repo every time I recompile.
55
+ test('does not archive when nothing is stale', async () => {
56
+ await writeFile('src/features/new/schema.ts', HEADER);
57
+ const archiveDir = join(tmp, 'quickback', '.archives');
58
+ const result = await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts'], {
59
+ archiveDir,
60
+ });
61
+ expect(result.deleted).toEqual([]);
62
+ expect(result.archivePath).toBeUndefined();
63
+ expect(await fileExists('quickback/.archives')).toBe(false);
64
+ });
65
+ // User story: As a developer about to lose 30 generator-emitted files in a
66
+ // sweep, I want a snapshot of src/ saved automatically so I can recover if
67
+ // the compiler stopped emitting something I was depending on.
68
+ test('archives src/ before deleting when orphans are present', async () => {
69
+ await writeFile('src/features/old/schema.ts', HEADER);
70
+ await writeFile('src/features/new/schema.ts', HEADER);
71
+ const archiveDir = join(tmp, 'quickback', '.archives');
72
+ const result = await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts'], {
73
+ archiveDir,
74
+ });
75
+ expect(result.deleted).toEqual(['src/features/old/schema.ts']);
76
+ expect(result.archivePath).toBeDefined();
77
+ // Archive should contain a copy of the pre-sweep tree.
78
+ const archived = await fs.readdir(result.archivePath, { recursive: true });
79
+ const flat = archived.map((p) => (sep === '/' ? p : p.split(sep).join('/')));
80
+ expect(flat).toContain('features/old/schema.ts');
81
+ expect(flat).toContain('features/new/schema.ts');
82
+ });
83
+ // User story: As a developer who refactors aggressively over a week, I want
84
+ // older snapshots pruned automatically so the .archives folder doesn't
85
+ // balloon — last 3 generations is enough to walk back from a regret.
86
+ test('prunes old archives, keeping most recent N', async () => {
87
+ const archiveDir = join(tmp, 'archives');
88
+ await fs.mkdir(archiveDir, { recursive: true });
89
+ // Pre-seed 5 fake archives with sortable names.
90
+ for (const stamp of ['src-0001', 'src-0002', 'src-0003', 'src-0004']) {
91
+ await fs.mkdir(join(archiveDir, stamp));
92
+ }
93
+ await writeFile('src/features/old/schema.ts', HEADER);
94
+ await writeFile('src/features/new/schema.ts', HEADER);
95
+ await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts'], {
96
+ archiveDir,
97
+ archiveKeep: 3,
98
+ });
99
+ const remaining = (await fs.readdir(archiveDir)).filter((d) => d.startsWith('src-'));
100
+ expect(remaining.length).toBe(3);
101
+ // Newest survives — pruning is alphabetical-descending.
102
+ expect(remaining).toContain('src-0004');
103
+ expect(remaining).not.toContain('src-0001');
104
+ });
105
+ // User story: As a developer with SPA bundles in src/apps/cms/assets/, I want
106
+ // the sweep to leave that subtree alone — the upstream code wipes it
107
+ // wholesale before each write, so the per-file header probe would be
108
+ // wasted work.
109
+ test('respects skipPrefixes (SPA asset dirs)', async () => {
110
+ await writeFile('src/apps/cms/assets/main-abc123.js', HEADER);
111
+ await writeFile('src/apps/cms/assets/main-def456.js', HEADER);
112
+ const result = await sweepStaleGeneratedFiles(tmp, 'src', ['src/apps/cms/assets/main-def456.js'], {
113
+ skipPrefixes: ['src/apps/cms/assets'],
114
+ });
115
+ expect(result.deleted).toEqual([]);
116
+ expect(await fileExists('src/apps/cms/assets/main-abc123.js')).toBe(true);
117
+ });
118
+ // User story: As a developer with a now-empty src/features/old/ after a
119
+ // sweep, I don't want the bare directory hanging around — the file tree
120
+ // should match the manifest, including its shape.
121
+ test('removes empty directories left after deletion', async () => {
122
+ await writeFile('src/features/old/schema.ts', HEADER);
123
+ await writeFile('src/features/old/routes.ts', HEADER);
124
+ await writeFile('src/features/new/schema.ts', HEADER);
125
+ await sweepStaleGeneratedFiles(tmp, 'src', ['src/features/new/schema.ts']);
126
+ expect(await fileExists('src/features/old')).toBe(false);
127
+ expect(await fileExists('src/features/new')).toBe(true);
128
+ });
129
+ });
130
+ //# sourceMappingURL=sweep-stale.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sweep-stale.test.js","sourceRoot":"","sources":["../../src/lib/sweep-stale.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACzE,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC5B,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAE5D,MAAM,MAAM,GAAG,2CAA2C,CAAC;AAC3D,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAE3C,IAAI,GAAW,CAAC;AAEhB,UAAU,CAAC,KAAK,IAAI,EAAE;IACpB,GAAG,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,cAAc,C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,CAAC"}
@@ -115,6 +115,38 @@ export default defineConfig({
115
115
 
116
116
  Minimal: `account: true` enables with all defaults. `account: { build: false }` skips rebuild on subsequent compiles.
117
117
 
118
+ ### Discoverable options block
119
+
120
+ After the first compile, the file gets a managed comment block bracketed by `// [quickback:options-start]` … `// [quickback:options-end]`. Every option Quickback supports is listed there as a commented-out line. To enable one, lift the line **above** the start sentinel and uncomment — Quickback notices and drops it from the managed block on the next compile to avoid duplicates. Anything outside the sentinels is yours and never touched. Skip with `quickback compile --no-sync-config`.
121
+
122
+ ### Custom bindings (`config.bindings`)
123
+
124
+ Declare additional Cloudflare bindings that flow into `wrangler.toml`. The compiler also auto-wires the `[[send_email]] EMAIL` binding, the `cloudflare-email.ts` helper, and Better Auth's `sendResetPassword` / `sendVerificationEmail` / `sendInvitationEmail` callbacks for any auth surface that needs mail (`emailAndPassword.enabled` OR the `emailOtp` / `magicLink` / `organization` plugins) — you don't need to add `bindings.sendEmail` by hand for the standard cases.
125
+
126
+ ```typescript
127
+ export default defineConfig({
128
+ // ...
129
+ bindings: {
130
+ kv: [{ binding: 'CACHE', id: '...' }],
131
+ r2: [{ binding: 'UPLOADS', bucketName: 'my-uploads' }],
132
+ queues: {
133
+ producers: [{ binding: 'JOBS', queue: 'jobs' }],
134
+ consumers: [{ queue: 'jobs', maxBatchSize: 10 }],
135
+ },
136
+ durableObjects: [{ binding: 'CHAT', className: 'ChatRoom' }],
137
+ vars: { FEATURE_X: 'true' },
138
+ },
139
+ });
140
+ ```
141
+
142
+ ### CMS access default
143
+
144
+ `cms: true` defaults to `access: 'admin'` — only users with `user.role === 'admin'` can enter the CMS. Non-admins are redirected to `/account/profile`. Override with `cms: { access: 'user' }` to open the CMS to all authenticated users.
145
+
146
+ ### Account fileUploads
147
+
148
+ `account.fileUploads: true` shows the avatar upload UI on the profile page. Defaults to `false`; enabling it requires R2 configured for storage.
149
+
118
150
  ## Compile Output and State Artifacts
119
151
 
120
152
  - Runtime code stays in `build.outputDir` (e.g. `src/`, `wrangler.toml`, `package.json`)
@@ -152,15 +184,17 @@ export default feature("todos", {
152
184
  columns: {
153
185
  id: q.id(),
154
186
  title: q.text().required(),
155
- description: q.text().optional(),
187
+ description: q.text({ maxLength: 1000 }).optional(),
156
188
  completed: q.bool().default(false),
157
- userId: q.text().required(),
158
- organizationId: q.text().required(),
189
+ ownerId: q.scope("owner"), // → ctx.userId, auto-firewalled, auto-populated
190
+ organizationId: q.scope("organization"), // → ctx.activeOrgId, same
159
191
  },
160
- firewall: { organization: {}, owner: {} },
192
+ // firewall block omitted — q.scope() auto-derives:
193
+ // [{ field: 'organizationId', equals: 'ctx.activeOrgId' },
194
+ // { field: 'ownerId', equals: 'ctx.userId' },
195
+ // { field: 'deletedAt', isNull: true }]
196
+ read: { access: { roles: ["member", "admin"] } },
161
197
  crud: {
162
- list: { access: { roles: ["member", "admin"] } },
163
- get: { access: { roles: ["member", "admin"] } },
164
198
  create: { access: { roles: ["member", "admin"] } },
165
199
  update: { access: { roles: ["admin"] } },
166
200
  delete: { access: { roles: ["admin"] }, mode: "soft" },
@@ -169,16 +203,53 @@ export default feature("todos", {
169
203
  createable: ["title", "description", "completed"],
170
204
  updatable: ["title", "description", "completed"],
171
205
  },
172
- masking: {
173
- userId: { type: "redact", show: { roles: ["admin"] } },
174
- },
175
206
  });
176
207
  ```
177
208
 
178
- **q DSL quick reference:** column names default to snake_case of the JS key (`organizationId` → `organization_id`). `q.id()` emits a cuid2 primary key. Chainable modifiers: `.required()` / `.optional()` / `.default(v)` / `.unique()` / `.index()` / `.references(() => other.id, { onDelete: 'cascade' })`.
179
-
180
209
  The `feature()` form is compile-time sugar — the compiler expands it to `q.table()` + `defineTable()` internally. Use whichever reads best for the file.
181
210
 
211
+ ### q DSL — column types
212
+
213
+ Column names default to snake_case of the JS key (`organizationId` → `organization_id`). Override with the positional name string or the `sqlName` option.
214
+
215
+ | Builder | SQL | Zod | Notes |
216
+ |---|---|---|---|
217
+ | `q.id()` | `text('id').primaryKey()` | `z.string()` | cuid2 by default; ID style follows `database.generateId` |
218
+ | `q.text(name?)` / `q.text({ sqlName?, maxLength? })` | `text(...)` | `z.string()` (`.max(n)` if `maxLength`) | options form adds zod max-length only — SQL stays unconstrained |
219
+ | `q.url({ sqlName?, maxLength? })` | `text(...)` | `z.string().url()` | rejects `javascript:` / `data:` / non-URL strings at the API edge |
220
+ | `q.int(name?)` | `integer(...)` | `z.number().int()` | |
221
+ | `q.bool(name?)` | `boolean(...)` (sqlite: integer mode) | `z.boolean()` | |
222
+ | `q.uuid(name?)` | `uuid(...)` (sqlite: text) | `z.string().uuid()` | |
223
+ | `q.timestamp(name?)` | `timestamp(...)` (sqlite: text ISO) | `z.coerce.date()` | |
224
+ | `q.json(zodType?)` | `jsonb(...)` (sqlite: text mode) | `z.unknown()` or your zod | pass a zod schema for typed JSON |
225
+ | `q.enum(['a','b'])` | `text(..., { enum })` | `z.enum([...])` | |
226
+ | `q.scope(kind)` | `text(...).notNull()` | `z.string()` | tenant-scope column — see Firewall |
227
+
228
+ **Chainable modifiers:** `.required()` / `.optional()` / `.default(v)` / `.unique()` / `.index()` / `.filterable(false)` / `.searchable(false)` / `.references(() => other.id, { onDelete: 'cascade' })`.
229
+
230
+ `.filterable(false)` and `.searchable(false)` are capability opt-outs — every text column is filter/search-eligible by default; chain `false` to remove a column from `?<col>=` filters or the `?search=` OR'd LIKE scan. Masked columns are always excluded from `?search` regardless (see Masking).
231
+
232
+ ### Composite indexes & uniques on `feature()`
233
+
234
+ Single-column indexes go on the column (`q.text().index()`). Composite ones go at the top level — the sugar forwards them into the same `q.table` opts:
235
+
236
+ ```typescript
237
+ export default feature("memberships", {
238
+ columns: { userId: q.scope("owner"), organizationId: q.scope("organization"), role: q.text() },
239
+ indexes: [{ name: "memberships_user_org_idx", columns: ["userId", "organizationId"] }],
240
+ unique: [{ columns: ["userId", "organizationId"] }],
241
+ // ... read / crud / guards
242
+ });
243
+ ```
244
+
245
+ **Auto-indexes:** the compiler emits the indexes you'd otherwise author by hand. Don't pre-declare these — they'll be deduped:
246
+
247
+ | Trigger | Index emitted |
248
+ |---|---|
249
+ | Tenant col (`organizationId` / `userId`) + `deletedAt` | composite `(<isolation>, deletedAt)` |
250
+ | Any FK (`.references(...)`) | single-col `(<fk>)` (D1/SQLite don't auto-index FKs) |
251
+ | Any column in a view's `read.query.sortable` | single-col `(<col>)` |
252
+
182
253
  ### Example: same todos using the two-export form
183
254
 
184
255
  ```typescript
@@ -188,14 +259,15 @@ export const todos = q.table("todos", {
188
259
  id: q.id(),
189
260
  title: q.text().required(),
190
261
  completed: q.bool().default(false),
191
- userId: q.text().required(),
192
- organizationId: q.text().required(),
262
+ ownerId: q.scope("owner"),
263
+ organizationId: q.scope("organization"),
193
264
  });
194
265
 
195
266
  export default defineTable(todos, {
196
- firewall: { organization: {}, owner: {} },
197
- crud: { /* same as above */ },
198
- guards: { /* same as above */ },
267
+ // firewall auto-derived from q.scope() — same as the feature() example
268
+ read: { /* same as above */ },
269
+ crud: { /* same as above */ },
270
+ guards: { /* same as above */ },
199
271
  });
200
272
 
201
273
  export type Todo = typeof todos.$infer;
@@ -203,6 +275,8 @@ export type Todo = typeof todos.$infer;
203
275
 
204
276
  ### Example: same todos with Drizzle (for interop)
205
277
 
278
+ When bringing forward existing Drizzle code, declare a regular column. Auto-detection by **name** (`organizationId`, `ownerId`, `teamId`, `userId`) still picks it up — `q.scope()` semantics (auto-firewall, systemManaged, auto-populate) apply because they key off the firewall predicate, not the column DSL.
279
+
206
280
  ```typescript
207
281
  import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
208
282
  import { defineTable } from "@quickback/compiler";
@@ -216,9 +290,10 @@ export const todos = sqliteTable("todos", {
216
290
  });
217
291
 
218
292
  export default defineTable(todos, {
219
- firewall: { organization: {}, owner: {} },
220
- crud: { /* same as above */ },
221
- guards: { /* same as above */ },
293
+ // firewall auto-derived from column names; declare explicitly only if names don't match
294
+ read: { /* same as above */ },
295
+ crud: { /* same as above */ },
296
+ guards: { /* same as above */ },
222
297
  });
223
298
  ```
224
299
 
@@ -328,45 +403,82 @@ Request → Firewall → Access → Guards → Database → Masking → Response
328
403
 
329
404
  ### 1. Firewall — Data Isolation
330
405
 
331
- Compiles WHERE clauses to isolate data by ownership. Auto-detects column names.
406
+ Compiles WHERE clauses to isolate data by ownership. Predicates are AND'd together.
407
+
408
+ ```typescript
409
+ firewall: [
410
+ { field: 'organizationId', equals: 'ctx.activeOrgId' }, // WHERE organizationId = ctx.activeOrgId
411
+ { field: 'ownerId', equals: 'ctx.userId' }, // AND ownerId = ctx.userId
412
+ { field: 'teamId', equals: 'ctx.activeTeamId' }, // AND teamId = ctx.activeTeamId
413
+ { field: 'deletedAt', isNull: true }, // AND deletedAt IS NULL (soft-delete filter)
414
+ ]
415
+
416
+ // Public/system resources opt out of tenant scoping (soft-delete still applied):
417
+ firewall: [{ exception: true }]
418
+ ```
419
+
420
+ **Recommended: declare scope columns with `q.scope()`** — auto-derives the firewall predicate AND marks the column `systemManaged` (rejected from client input) AND auto-populates from ctx on insert/upsert. Zero ambiguity in the source:
332
421
 
333
422
  ```typescript
334
- firewall: {
335
- organization: {}, // WHERE organizationId = ctx.activeOrgId
336
- owner: { mode: 'optional' }, // AND (ownerId = ctx.userId OR ownerId IS NULL)
337
- team: {}, // WHERE teamId = ctx.activeTeamId
338
- softDelete: {}, // AND deletedAt IS NULL
339
- exception: true, // No filtering (public resources)
423
+ columns: {
424
+ organizationId: q.scope("organization"), // → ctx.activeOrgId
425
+ ownerId: q.scope("owner"), // → ctx.userId
426
+ teamId: q.scope("team"), // → ctx.activeTeamId
340
427
  }
341
428
  ```
342
429
 
343
- Auto-detection:
344
- - `organization` → looks for `organizationId` or `organization_id`
345
- - `owner` → looks for `userId` or `user_id`
346
- - `team` → looks for `teamId` or `team_id`
430
+ **Auto-derivation by name** (Drizzle interop, when the `firewall:` block is omitted): the compiler scans column names and emits the same predicates.
431
+
432
+ | Column name in schema | Predicate emitted |
433
+ |---|---|
434
+ | `organizationId` / `organisationId` | `{ field: '...', equals: 'ctx.activeOrgId' }` |
435
+ | `userId` (or `ownerId`) | `{ field: '...', equals: 'ctx.userId' }` |
436
+ | `teamId` | `{ field: 'teamId', equals: 'ctx.activeTeamId' }` |
437
+ | `deletedAt` (always present via audit injection) | `{ field: 'deletedAt', isNull: true }` |
438
+
439
+ - Exactly one isolation column → auto-derived.
440
+ - Two or more → compile-time error; declare `firewall: [...]` explicitly OR use `q.scope()` to lock semantics in the source.
441
+ - Zero columns AND no PUBLIC route → compile-time error ("missing isolation column").
347
442
 
348
- Column overrides:
443
+ **Custom column / context source**: just write the predicate explicitly.
349
444
 
350
445
  ```typescript
351
- firewall: {
352
- organization: {
353
- column: 'tenant_id',
354
- source: 'ctx.tenant.id',
355
- },
356
- }
446
+ firewall: [
447
+ { field: 'tenantId', equals: 'ctx.activeOrgId' },
448
+ { field: 'status', in: ['active', 'pending'] }, // literal value, not ctx-derived
449
+ ]
357
450
  ```
358
451
 
359
- Owner modes: default = strict (only own records), `optional` = own + NULL owner (admin pattern).
452
+ **Predicate operators**: `equals` (column = ctx.* or literal), `isNull: true` (column IS NULL), `in: [...]` (column IN ...), `{ exception: true }` (opt out of tenant scoping).
360
453
 
361
454
  ### 2. Access — Permission Checks
362
455
 
363
456
  Role-based and record-based access control. Deny by default.
364
457
 
458
+ DSL v2 separates **reads** (collection + per-id GET) from **mutations**. The unified `read` block owns `GET /` AND `GET /:id` AND views; mutations live under `crud.create/update/delete`.
459
+
365
460
  ```typescript
461
+ read: {
462
+ access: { roles: ['member+'] }, // gates GET / and GET /:id
463
+ query: {
464
+ sortable: ['createdAt', 'status'], // ?sort= allowlist (defaults to all cols)
465
+ searchable: ['title', 'body'], // ?search= OR'd LIKE allowlist
466
+ filterable: ['status', 'priority'], // ?<col>= allowlist
467
+ },
468
+ views: {
469
+ summary: {
470
+ fields: ['id', 'title', 'status'],
471
+ access: { roles: ['member+'] },
472
+ query: { sortable: ['title'] }, // per-view overrides allowed
473
+ },
474
+ full: {
475
+ fields: ['id', 'title', 'status', 'body', 'internalNotes'],
476
+ access: { roles: ['admin+'] },
477
+ },
478
+ },
479
+ },
366
480
  crud: {
367
- list: { access: { roles: ['member+'] } }, // member, admin, owner
368
- get: { access: { roles: ['member+'] } },
369
- create: { access: { roles: ['admin+'] } }, // admin, owner
481
+ create: { access: { roles: ['admin+'] } },
370
482
  update: {
371
483
  access: {
372
484
  or: [
@@ -375,10 +487,18 @@ crud: {
375
487
  ],
376
488
  },
377
489
  },
378
- delete: { access: { roles: ['owner'] } }, // owner only
490
+ delete: { access: { roles: ['owner'] } },
379
491
  }
380
492
  ```
381
493
 
494
+ **Generated read endpoints:**
495
+ - `GET /api/v1/{resource}` — gated by `read.access`
496
+ - `GET /api/v1/{resource}/:id` — gated by `read.access` (single-record GET inherits)
497
+ - `GET /api/v1/{resource}?view=summary` — view dispatch under `?view=`
498
+ - `GET /api/v1/{resource}/views/summary` — explicit view path
499
+
500
+ > **DSL v2 migration:** `crud.list` and `crud.get` are rejected at compile time. Move them to `read.access`. A bare `crud: { list: {} }` becomes `read: {}`.
501
+
382
502
  **Role hierarchy**: Configure `auth.roleHierarchy` in your config (e.g., `['member', 'admin', 'owner']`) and use the `+` suffix to mean "this role and above". `"member+"` expands to `["member", "admin", "owner"]` at compile time. Roles without `+` are exact matches.
383
503
 
384
504
  Record condition operators: `equals`, `notEquals`, `in`, `notIn`, `greaterThan`, `lessThan`
@@ -415,6 +535,8 @@ Mask types: `email`, `phone`, `ssn`, `creditCard`, `name`, `redact`, `custom`
415
535
 
416
536
  Auto-detection warns on unmasked sensitive columns (`email`, `phone`, `ssn`, `password`, etc.).
417
537
 
538
+ **Search/filter gating.** Masked columns are dropped from `?search` by default — letting an unauthorized caller substring-search a masked SSN trivially leaks digit positions. To re-enable search on a masked column for callers who *can* see it unmasked, list it under a view's `read.query.searchable`. The compiler validates the intersection at compile time.
539
+
418
540
  ---
419
541
 
420
542
  ## Views — Column-Level Security
@@ -541,20 +663,24 @@ Docs: `quickback docs account-ui` | https://docs.quickback.dev/account-ui
541
663
 
542
664
  ## Actions — Custom Business Logic
543
665
 
544
- Defined in a separate `actions.ts` file using `defineActions()`.
666
+ Defined in a separate `actions.ts` file using `defineActions()`. Per-action permissions live under `access:` (same shape as resource-level access).
545
667
 
546
668
  ```typescript
547
- import { todos } from './todos';
669
+ import todos from './todos'; // default import: feature() exports
670
+ // import { todos } from './todos'; // named import: two-export form
548
671
  import { defineActions } from '@quickback/compiler';
672
+ import { q } from '../../lib/q'; // generated namespace; same as drizzle-orm
549
673
  import { z } from 'zod';
550
674
 
551
675
  export default defineActions(todos, {
552
676
  complete: {
553
677
  description: "Mark todo as complete",
554
678
  input: z.object({ completedAt: z.string().datetime().optional() }),
555
- guard: { roles: ["member", "admin"], record: { completed: { equals: false } } },
556
- execute: async ({ db, record, ctx, input }) => {
557
- await db.update(todos).set({ completed: true }).where(eq(todos.id, record.id));
679
+ access: { roles: ["member", "admin"], record: { completed: { equals: false } } },
680
+ execute: async ({ db, record, whereRecord, auditFields }) => {
681
+ await db.update(todos)
682
+ .set({ completed: true, modifiedAt: auditFields.modifiedAt })
683
+ .where(whereRecord!(todos)); // firewall + soft-delete + id, in one
558
684
  return { success: true };
559
685
  },
560
686
  sideEffects: "sync",
@@ -562,16 +688,83 @@ export default defineActions(todos, {
562
688
  archive: {
563
689
  description: "Archive a todo",
564
690
  input: z.object({}),
565
- guard: { roles: ["admin"] },
691
+ access: { roles: ["admin"] },
566
692
  handler: "./handlers/archive",
567
693
  },
568
694
  });
569
695
  ```
570
696
 
571
- **Record-based** (default): `POST /api/v1/{resource}/:id/{action}`
572
- **Standalone**: `standalone: true`, custom `path` and `method`
697
+ **Record-based** (default): `POST /api/v1/{resource}/:id/{action}` — record is loaded, firewall + access checks run, then `execute` is called with `record`, `whereRecord`, scoped `db`.
698
+ **Standalone**: `standalone: true`, custom `path` and `method`. No record context, no firewall preload.
699
+
700
+ Action options: `standalone`, `method` (GET/POST/PUT/PATCH/DELETE), `responseType` (json/stream/file), `sideEffects` (sync/async/fire-and-forget), `transition`, `unsafe`, `allowRawSql`.
701
+
702
+ ### `whereRecord(table)` — explicit, scope-safe WHERE
703
+
704
+ In record-based actions, `whereRecord(table)` returns a Drizzle expression that AND-merges the resource's firewall + soft-delete + `eq(table.id, record.id)`. Use it for protected-field writes — even if a future refactor swaps `db` for an unscoped client, the WHERE stays explicit. `whereRecord` is `undefined` for standalone actions.
705
+
706
+ ### `transition` — state-machine policy on protected fields
707
+
708
+ For protected fields that follow a state machine (status, lifecycle, fulfilment), enforce the *from/to pair*, not just the current state. Without `transition`, an `advance` action whose access allows `status in ['applied', 'screening']` will happily run `applied → offer` (a skip) or `screening → applied` (a regression).
709
+
710
+ ```typescript
711
+ advance: {
712
+ description: "Move application forward",
713
+ input: z.object({ nextStatus: z.enum(['screening', 'interview', 'offer']) }),
714
+ access: { roles: ['owner', 'admin'] },
715
+ transition: {
716
+ field: 'status',
717
+ via: 'nextStatus', // read target from input.nextStatus
718
+ fromTo: {
719
+ applied: ['screening'],
720
+ screening: ['interview'],
721
+ interview: ['offer'],
722
+ },
723
+ },
724
+ handler: './handlers/advance',
725
+ },
726
+ hire: {
727
+ input: z.object({}),
728
+ access: { roles: ['owner'] },
729
+ transition: {
730
+ field: 'status',
731
+ to: 'hired', // fixed target — same value every call
732
+ fromTo: { offer: ['hired'] },
733
+ },
734
+ handler: './handlers/hire',
735
+ },
736
+ ```
737
+
738
+ Exactly one of `via` or `to` must be provided. On a bad transition the runtime returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with `field`, `current`, `target`, `allowedTargets`. The same 409 fires when a plain `access.record` precondition fails (was 403 before — splitting it lets clients tell *"you can't do this"* from *"you can't do this **yet**"*).
739
+
740
+ ### `unsafe` — bypass scoped DB filters (object form, with mandatory audit)
741
+
742
+ For platform-level support / cross-tenant operations, opt out of the scoped DB. The object form is required for new code — it makes the policy explicit and forces an audit reason:
743
+
744
+ ```typescript
745
+ adminReport: {
746
+ description: "Cross-org hiring report",
747
+ unsafe: {
748
+ reason: "Support investigation for enterprise customer",
749
+ adminOnly: true, // default true — gates on ctx.userRole === 'admin'
750
+ crossTenant: true, // default true — bypasses firewall
751
+ targetScope: 'all', // 'all' | 'organization'
752
+ },
753
+ input: z.object({ startDate: z.string() }),
754
+ access: { roles: ['owner'] },
755
+ execute: async ({ db, unsafeDb, ctx, input }) => {
756
+ // db is still scoped (safety net for accidental writes)
757
+ // unsafeDb bypasses scoped filters
758
+ return await unsafeDb.select().from(applications);
759
+ },
760
+ },
761
+ ```
762
+
763
+ Generated runtime auto-injects: Better Auth required, platform admin gate, mandatory audit logging on deny/success/error. Without unsafe mode, `unsafeDb` is `undefined`. Legacy `unsafe: true` still works but object form is preferred.
764
+
765
+ ### Soft-delete cascade (cross-feature)
573
766
 
574
- Action options: `standalone`, `method` (GET/POST/PUT/PATCH/DELETE), `responseType` (json/stream/file), `sideEffects` (sync/async/fire-and-forget)
767
+ When a parent is soft-deleted, every child table that holds an FK to it — both **same-feature** and **cross-feature** children — receives the same `deletedAt` / `deletedBy` stamp. The cascade UPDATE always AND-merges the child's own firewall, so a delete in one tenant never reaches a child row in another tenant. FKs declared with `onDelete: 'cascade'` or `'set null'` participate; FKs without `onDelete` are cascaded for backwards compat.
575
768
 
576
769
  ### Actions-Only Features
577
770
 
@@ -589,7 +782,7 @@ export default defineActions(null, {
589
782
  method: "GET",
590
783
  description: "Health check endpoint",
591
784
  input: z.object({}),
592
- guard: { roles: ["member", "admin"] },
785
+ access: { roles: ["member", "admin"] },
593
786
  handler: "./handlers/health-check",
594
787
  },
595
788
  });