@quickback-dev/cli 0.58.1 → 0.58.3
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/README.md +3 -1
- package/dist/commands/compile.d.ts +5 -0
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +34 -0
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/schema.d.ts +16 -0
- package/dist/commands/schema.d.ts.map +1 -0
- package/dist/commands/schema.js +122 -0
- package/dist/commands/schema.js.map +1 -0
- package/dist/commands/schema.test.d.ts +2 -0
- package/dist/commands/schema.test.d.ts.map +1 -0
- package/dist/commands/schema.test.js +57 -0
- package/dist/commands/schema.test.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +7 -2
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +14 -4
- package/dist/index.js.map +1 -1
- package/dist/lib/action-harvest.d.ts +9 -6
- package/dist/lib/action-harvest.d.ts.map +1 -1
- package/dist/lib/action-harvest.js +28 -15
- package/dist/lib/action-harvest.js.map +1 -1
- package/dist/lib/action-harvest.test.js +21 -0
- package/dist/lib/action-harvest.test.js.map +1 -1
- package/dist/lib/api-client.d.ts +53 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js +2 -0
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/api-client.test.js +18 -0
- package/dist/lib/api-client.test.js.map +1 -1
- package/dist/lib/migrations/command-runner.d.ts +10 -0
- package/dist/lib/migrations/command-runner.d.ts.map +1 -0
- package/dist/lib/migrations/command-runner.js +66 -0
- package/dist/lib/migrations/command-runner.js.map +1 -0
- package/dist/lib/migrations/drizzle.d.ts +12 -0
- package/dist/lib/migrations/drizzle.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle.js +60 -0
- package/dist/lib/migrations/drizzle.js.map +1 -0
- package/dist/lib/migrations/drizzle.test.d.ts +2 -0
- package/dist/lib/migrations/drizzle.test.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle.test.js +61 -0
- package/dist/lib/migrations/drizzle.test.js.map +1 -0
- package/dist/lib/migrations/errors.d.ts +6 -0
- package/dist/lib/migrations/errors.d.ts.map +1 -0
- package/dist/lib/migrations/errors.js +9 -0
- package/dist/lib/migrations/errors.js.map +1 -0
- package/dist/lib/migrations/executor.d.ts +52 -0
- package/dist/lib/migrations/executor.d.ts.map +1 -0
- package/dist/lib/migrations/executor.js +190 -0
- package/dist/lib/migrations/executor.js.map +1 -0
- package/dist/lib/migrations/executor.test.d.ts +2 -0
- package/dist/lib/migrations/executor.test.d.ts.map +1 -0
- package/dist/lib/migrations/executor.test.js +241 -0
- package/dist/lib/migrations/executor.test.js.map +1 -0
- package/dist/lib/migrations/index.d.ts +11 -0
- package/dist/lib/migrations/index.d.ts.map +1 -0
- package/dist/lib/migrations/index.js +11 -0
- package/dist/lib/migrations/index.js.map +1 -0
- package/dist/lib/migrations/inventory.d.ts +19 -0
- package/dist/lib/migrations/inventory.d.ts.map +1 -0
- package/dist/lib/migrations/inventory.js +135 -0
- package/dist/lib/migrations/inventory.js.map +1 -0
- package/dist/lib/migrations/inventory.test.d.ts +2 -0
- package/dist/lib/migrations/inventory.test.d.ts.map +1 -0
- package/dist/lib/migrations/inventory.test.js +81 -0
- package/dist/lib/migrations/inventory.test.js.map +1 -0
- package/dist/lib/migrations/lock.d.ts +6 -0
- package/dist/lib/migrations/lock.d.ts.map +1 -0
- package/dist/lib/migrations/lock.js +101 -0
- package/dist/lib/migrations/lock.js.map +1 -0
- package/dist/lib/migrations/lock.test.d.ts +2 -0
- package/dist/lib/migrations/lock.test.d.ts.map +1 -0
- package/dist/lib/migrations/lock.test.js +35 -0
- package/dist/lib/migrations/lock.test.js.map +1 -0
- package/dist/lib/migrations/paths.d.ts +12 -0
- package/dist/lib/migrations/paths.d.ts.map +1 -0
- package/dist/lib/migrations/paths.js +82 -0
- package/dist/lib/migrations/paths.js.map +1 -0
- package/dist/lib/migrations/paths.test.d.ts +2 -0
- package/dist/lib/migrations/paths.test.d.ts.map +1 -0
- package/dist/lib/migrations/paths.test.js +32 -0
- package/dist/lib/migrations/paths.test.js.map +1 -0
- package/dist/lib/migrations/plan.d.ts +7 -0
- package/dist/lib/migrations/plan.d.ts.map +1 -0
- package/dist/lib/migrations/plan.js +189 -0
- package/dist/lib/migrations/plan.js.map +1 -0
- package/dist/lib/migrations/plan.test.d.ts +2 -0
- package/dist/lib/migrations/plan.test.d.ts.map +1 -0
- package/dist/lib/migrations/plan.test.js +104 -0
- package/dist/lib/migrations/plan.test.js.map +1 -0
- package/dist/lib/migrations/staging.d.ts +18 -0
- package/dist/lib/migrations/staging.d.ts.map +1 -0
- package/dist/lib/migrations/staging.js +150 -0
- package/dist/lib/migrations/staging.js.map +1 -0
- package/dist/lib/migrations/staging.test.d.ts +2 -0
- package/dist/lib/migrations/staging.test.d.ts.map +1 -0
- package/dist/lib/migrations/staging.test.js +73 -0
- package/dist/lib/migrations/staging.test.js.map +1 -0
- package/dist/lib/migrations/types.d.ts +49 -0
- package/dist/lib/migrations/types.d.ts.map +1 -0
- package/dist/lib/migrations/types.js +18 -0
- package/dist/lib/migrations/types.js.map +1 -0
- package/dist/lib/schema-engine-loader.d.ts +8 -0
- package/dist/lib/schema-engine-loader.d.ts.map +1 -0
- package/dist/lib/schema-engine-loader.js +26 -0
- package/dist/lib/schema-engine-loader.js.map +1 -0
- package/dist/lib/schema-sync/index.d.ts +41 -0
- package/dist/lib/schema-sync/index.d.ts.map +1 -0
- package/dist/lib/schema-sync/index.js +246 -0
- package/dist/lib/schema-sync/index.js.map +1 -0
- package/dist/lib/schema-sync/index.test.d.ts +2 -0
- package/dist/lib/schema-sync/index.test.d.ts.map +1 -0
- package/dist/lib/schema-sync/index.test.js +128 -0
- package/dist/lib/schema-sync/index.test.js.map +1 -0
- package/dist/schema-engine/index.d.ts +3 -0
- package/dist/schema-engine/index.d.ts.map +1 -0
- package/dist/schema-engine/index.js +854 -0
- package/dist/schema-engine/index.js.map +7 -0
- package/dist/schema-engine/managed-columns.d.ts +82 -0
- package/dist/schema-engine/managed-columns.d.ts.map +1 -0
- package/dist/schema-engine/source-sync.d.ts +64 -0
- package/dist/schema-engine/source-sync.d.ts.map +1 -0
- package/dist/skill/docs/compiler/definitions/actions.md +14 -6
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +7 -4
- package/dist/skill/docs/compiler/targets/hono-api/using-the-api/typescript.md +141 -0
- package/package.json +4 -2
- package/src/skill/docs/compiler/definitions/actions.md +14 -6
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +7 -4
- package/src/skill/docs/compiler/targets/hono-api/using-the-api/typescript.md +141 -0
package/dist/docs/content.js
CHANGED
|
@@ -83,7 +83,7 @@ export const DOCS = {
|
|
|
83
83
|
},
|
|
84
84
|
"compiler/definitions/actions": {
|
|
85
85
|
"title": "Actions",
|
|
86
|
-
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment, and\nit must be a valid **camelCase identifier** — `sendMessage.ts`, not\n`send-message.ts` (hyphenated names are a compile error, since the name becomes\na generated identifier).\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { defineAction, applications } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and preserves the exact value\n> returned by `execute` without imposing an action-output schema. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n> **Your editor is typed too.** `quickback compile` writes the same typed\n> helpers into `quickback/features/<feature>/.quickback/` (plus a\n> `quickback/tsconfig.json`), so the import above resolves — and typechecks —\n> in the tree you actually edit, not just in the generated output. The helper\n> also **re-exports the feature's table** typed with the generated schema, so\n> compiler-managed columns (`createdAt`, `modifiedBy`, `deletedAt`,\n> `organizationId`) are visible on it without casts:\n>\n> ```typescript\n> import { defineAction, applications } from \"../.quickback/define-action\";\n> ```\n>\n> Prefer this single import over the older\n> `import { applications } from \"../applications\"` — that path resolves to\n> your authored file at edit time, which has no named export and none of the\n> injected columns. The helper files are regenerated on every compile; keep\n> `quickback/features/*/.quickback/` in `.gitignore` (new projects get this\n> automatically).\n\n### Local input-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` with Zod 4's `z.toJSONSchema`. It does\nnot call `execute`; the hosted compiler never evaluates project code. Under\ncontract v2, every action must produce a schema. A failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair. Lives on a record-based action, or on a standalone action paired with a `record:` binding. See [Transitions](/compiler/definitions/transitions) |\n| `record` | Standalone only | Feature-area transition adapter binding: `{ table, idFrom: \"path.<param>\", matchScope? }`. Binds + firewalls the record a `transition` operates on from a proven route param. See [Feature-area transition adapter](#feature-area-transition-adapter) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |\n| `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\nPaths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)\nwith a mounted prefix, two more forms apply:\n\n- **Relative** — `path: './tasks/add'` resolves against the area's prefix\n (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are\n rejected at compile time.\n- **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the\n area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected\n where it would be dead). The action is then gated solely by its own `access:` and listed in\n `quickback/authz-manifest.json`.\n\nAn action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —\nand never vocabulary of an area the feature is not inside (compile error).\n\n### Feature-area transition adapter\n\nA record [state transition](/compiler/definitions/transitions) normally lives on a\ntable-bound record action (`POST /:id/{action}`). When your clients call a nested\n**feature-area** route instead, you can attach the same compiler-owned transition to\nan explicit (`path:`) action by adding a `record:` binding. The binding is what lets a\n`transition` ride a standalone action — without it, `transition` on a `path:` action is\na compile error.\n\n```typescript\n// features/events/event_documents/actions/publishEventDocument.ts\nexport default defineAction({\n path: \"/events/:eventId/documents/:documentId/publish\",\n method: \"POST\",\n description: \"Publish one completed event document.\",\n input: z.object({ idempotencyKey: z.string().min(8) }),\n access: { roles: [\"member+\"] },\n // The compiler — not the action body — binds and firewalls the record.\n record: {\n table: \"event_documents\",\n idFrom: \"path.documentId\", // MUST be a route param, never a body field\n matchScope: \"event\", // row.eventId === ctx.event.id (area-proven)\n },\n transition: {\n field: \"status\",\n to: \"published\",\n fromTo: { draft: [\"published\"] },\n idempotent: \"noop\",\n stamp: { at: \"publishedAt\" },\n },\n async execute({ record, invalidate }) {\n // `record` is already bound, firewalled, area-matched, and transitioned.\n // Own the response projection + invalidations here.\n return { success: true as const, document: record };\n },\n});\n```\n\nSecurity semantics (all enforced by the compiler, fail-closed):\n\n- The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);\n a request-body source is rejected at compile time.\n- The row is loaded through the **scoped db**, so the table's full firewall\n (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.\n- `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`\n hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a\n different scope is a `404` (no cross-scope existence oracle).\n- The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated\n in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.\n- Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.\n- `idempotent: \"noop\"` short-circuits **before** `execute`, so a no-op never fires the\n action's invalidations. Existing record actions and table-level transitions are unchanged.\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\nBoth standalone and record-based actions support relationship roles directly in\n`access.roles`. Declare the relationship under `authz.relationships`, name it\nunder `authz.roles`, and use that name like any organization or pseudo-role.\n\nFor a standalone action, optional `loads` / `exposeAs` fields can hydrate the\nmatched resource onto `ctx`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe standalone action's surface (path params + input fields) must expose the\nrelationship's `resource.column`. A missing key is a compile error, so the\nresolver can never be skipped silently. See [Access — standalone\nactions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019)\nfor the full mechanism.\n\nFor a record-based action, Quickback already has the firewalled record in\nscope. It emits an inline relationship match against that record before\n`execute()` runs:\n\n```typescript\n// features/sessions/actions/comment.ts\nexport default defineAction({\n input: z.object({ text: z.string().max(2000) }),\n access: { roles: ['guest', 'admin'] },\n async execute({ db, record, input }) {\n // The route loaded `record` through its firewall, then verified guestOf\n // against record.eventId. Only domain logic remains here.\n return db.insert(comments).values({\n sessionId: record.id,\n text: input.text,\n });\n },\n});\n```\n\nSimple role arms are checked before the record lookup to preserve ID-probe\nresistance. Relationship arms run only after the record has been loaded through\nthe firewall, because the record supplies the relationship key. No manual\nlookup or firewall exception is required.\n\nSee [Access — relationship\nauthorization](/compiler/definitions/access#relationship-based-authorization)\nfor the full surface matrix, namespace hoisting, and tenant-context stamping.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete` with a\npurpose-built, SQL-pushable rule language: `principals`, `roles`, recursive\n`or`/`and`, and record `equals` against a DB-visible account or principal\ncontext value. Application-only values such as `userRole`, functions, and\nrequest/body fields stay at the action access layer; the compiler refuses them\ninside database RLS rather than pretending PostgreSQL can evaluate them.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\n\n### Scoped relational-query safety\n\nDrizzle's relational query API — `db.query.<table>.findFirst()` /\n`findMany()` (including nested `with:` relations) — builds its SQL from the\nrelations config and your `where` alone, so the scoped wrapper cannot inject\nthe org/owner/team firewall into it. The scoped `db` therefore exposes the\nDrizzle select builder—the path where Quickback can guarantee firewall\ninjection—and refuses `db.query.<table>` rather than returning unscoped rows:\n\n```typescript\nasync execute({ db, input }) {\n // ❌ Throws: relational queries aren't org-scoped\n const item = await db.query.media.findFirst({ where: eq(media.id, input.id) });\n\n // ✅ Scoped builder — firewall conditions injected automatically\n const [item] = await db.select().from(media).where(eq(media.id, input.id));\n}\n```\n\nFor nested reads, compose joins with the scoped select builder. If a\nPostgres-specific relational query is genuinely required, make the boundary\nexplicit with `unsafe: true` and query `unsafeDb.query` with the full scope\npredicate in the `WHERE` (for example,\n`eq(media.organizationId, ctx.activeOrgId)`).\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../../applications/applications\";\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise identical to D1. On Cloudflare, both HTTP\nand Hyperdrive are supported. Hyperdrive is the recommended lane when an unsafe\naction also needs an interactive transaction. The deprecated Node/Bun WebSocket\nmode is refused for unsafe actions because it cannot provide the same\nrequest-scoped service-role boundary.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\nimport { z } from \"zod\";\nimport { sql } from \"drizzle-orm\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\nimport { z } from \"zod\";\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { advanceInput } from \"../lib/inputs\";\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\nimport { eq, and } from \"drizzle-orm\";\n\n// Same feature — import from parent directory using the table's file name\nimport { applications } from \"../applications\";\nimport { interviewScores } from \"../interview-scores\";\n\n// Cross-feature — go up to the features directory, then into the other feature\nimport { candidates } from \"../../candidates/candidates\";\nimport { jobs } from \"../../jobs/jobs\";\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\nimport type { Auth } from \"better-auth\";\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { z } from \"zod\";\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()` —\nand on the conflict branch of an `onConflictDoUpdate({...})` upsert.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\nWho the stamped actor is depends on the verified principal, never on\nanything the handler passes:\n\n| Caller | `createdBy` / `modifiedBy` value |\n|---|---|\n| Signed-in user | the Better Auth `userId` |\n| Delegated principal (API key, service) | `actor:<type>:<id>` |\n| Scope-token principal (no account) | `scope:<kind>:<subjectId>` |\n| Cron schedule via `withInternalContext` | `system:cron-<name>` |\n| Queue handler via `withInternalContext` | `system:queue-<name>` |\n| No verified caller | the write **throws** (fail closed) — system-side code that must write outside a request uses the raw client and owns its own provenance |\n\nDon't hand-build audit timestamps as a \"just in case\" fallback: on the\nwrapped `db` they're dead code, and the idiom is a portability trap —\nPostgres audit columns take `Date` objects while SQLite takes ISO strings\n(the wrapper picks the right one per dialect).\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { ActionError } from \"@quickback/compiler\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { getOrgMemberRole } from \"../../../lib/org-access\";\nimport { projects } from \"../projects\";\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\nimport { ActionError } from \"@quickback/compiler\";\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { candidates } from \"../candidates\";\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
86
|
+
"content": "Actions are custom API endpoints for business logic beyond CRUD operations. They enable workflows, integrations, and complex operations.\n\n## Overview\n\nQuickback supports two types of actions:\n\n| Aspect | Record-Based | Standalone |\n|--------|--------------|------------|\n| Route | `{METHOD} /:id/{actionName}` | Custom `path` (required) |\n| Record fetching | Automatic | None (`record` is `undefined`) |\n| Firewall applied | Yes | No |\n| Preconditions | Supported via `access.record` | Not applicable |\n| Response types | JSON only | JSON, stream, file |\n| Use case | Advance application, reject candidate | AI chat, bulk import from job board, webhooks |\n\nStandalone actions are signalled by the presence of a `path:` field in the action config. Record-based actions omit `path` and bind to the feature's primary table.\n\n## Where do actions live?\n\n**One file per action.** Each action is its own module under the feature's\n`actions/` directory:\n\n```\nfeatures/applications/\n├── applications.ts ← defineTable (primary table)\n├── candidates.ts ← defineTable (sibling table)\n├── actions/\n│ ├── advance.ts ← defineAction, binds to applications\n│ ├── reject.ts ← defineAction, binds to applications\n│ ├── stats.ts ← defineAction, standalone (has `path:`)\n│ └── candidates/\n│ └── disqualify.ts ← defineAction, binds to candidates\n└── lib/\n └── inputs.ts ← shared schemas (optional, copied verbatim)\n```\n\n| Layout | Binds to |\n|--------|----------|\n| `actions/<name>.ts` | The feature's primary table (table file matching the feature name), or standalone if `path:` is set. |\n| `actions/<table>/<name>.ts` | The sibling table file `<table>.ts` at the feature root. Standalone actions inside a subdir ignore the binding. |\n\nThe action's filename (sans `.ts`) is the action name and the URL segment, and\nit must be a valid **camelCase identifier** — `sendMessage.ts`, not\n`send-message.ts` (hyphenated names are a compile error, since the name becomes\na generated identifier).\nUniqueness is enforced per `(bound table, name)` pair — sibling-bound\nactions on **different** tables may share a verb (`actions/episodes/publish.ts`\nand `actions/shows/publish.ts` mount at `/episodes/:id/publish` and\n`/shows/:id/publish` and compile cleanly). The compiler errors only when\ntwo action files would mount at the same URL — for example, a flat\n`actions/foo.ts` (binds to primary) plus `actions/<primary>/foo.ts`, or\ntwo standalones with the same `(method, path)`. Standalone actions are\nunique per `(method, path)`.\n\nTableless features have no top-level `*.ts` files; every action under\n`actions/` must be standalone (have `path:`). Use this for utility endpoints\nlike webhooks, reports, or integrations that don't operate on a specific\nrecord.\n\n### Retired layouts\n\nThese are rejected at load time with migration guidance:\n\n- **`actions.ts`** (bundled multi-action file)\n- **`_feature.ts`** (shared schemas + non-table-bound actions)\n- **`handlers/`** (separate handler-file directory)\n- **`defineActions(table, {...})`** (the multi-action factory)\n- **`defineActions(null, {...})`** (tableless variant)\n- **`*-actions.ts` / `*.actions.ts`** filename patterns\n\nFor shared Zod schemas or helpers, put them under `<feature>/lib/` and import\nfrom each action file. Files under `lib/` are copied verbatim into the\ngenerated output.\n\n## Defining Actions\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { defineAction, applications } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n }),\n output: z.object({\n id: z.string(),\n status: z.enum([\"screening\", \"interview\", \"offer\"]),\n }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereTransition!(applications))\n .returning();\n return updated;\n },\n});\n```\n\n> **`defineAction` import.** Import from `\"../.quickback/define-action\"` —\n> the `.quickback/` directory is generated alongside your feature with a\n> typed helper. It infers `record` and Zod `input`, exposes the generated\n> `Services`, types `c` as a Hono request context, binds `whereRecord` and\n> `whereTransition` to the feature table, and checks the value returned by\n> `execute` against `output` when you declare one. Scoped\n> `db` and interactive `tx` are schema-aware on D1 and Neon Hyperdrive;\n> HTTP/WebSocket Neon keeps its dynamic database escape hatch. `AppContext`\n> also retains its open index for namespace-hydrated fields. Audit fields\n> (`createdAt`, `createdBy`, `modifiedAt`,\n> `modifiedBy`) are hard-stamped by the audit DB wrapper on every\n> `db.insert().values()` and `db.update().set()` — handlers don't pass\n> them and can't override them.\n\n> **Your editor is typed too.** `quickback compile` writes the same typed\n> helpers into `quickback/features/<feature>/.quickback/` (plus a\n> `quickback/tsconfig.json`), so the import above resolves — and typechecks —\n> in the tree you actually edit, not just in the generated output. The helper\n> also **re-exports the feature's table** typed with the generated schema, so\n> compiler-managed columns (`createdAt`, `modifiedBy`, `deletedAt`,\n> `organizationId`) are visible on it without casts:\n>\n> ```typescript\n> import { defineAction, applications } from \"../.quickback/define-action\";\n> ```\n>\n> Prefer this single import over the older\n> `import { applications } from \"../applications\"` — that path resolves to\n> your authored file at edit time, which has no named export and none of the\n> injected columns. The helper files are regenerated on every compile; keep\n> `quickback/features/*/.quickback/` in `.gitignore` (new projects get this\n> automatically).\n\n### Local action-schema harvest\n\nBefore sending a compile request, the CLI loads each action in an isolated\nlocal bundle and converts `action.input` plus an optional `action.output` with\nZod 4's `z.toJSONSchema`. It does not call `execute`; the hosted compiler never\nevaluates project code. The output contract feeds OpenAPI and\n`Api.<feature>.actions.<action>.Output` in `quickback.gen.ts`. Under\ncontract v2, every action input must produce a schema; output remains optional.\nA failure names the exact\naction, whether bundling or evaluation failed, and the underlying local error.\nV1 can still fall back to the lower-fidelity static schema parser.\n\nBare imports are resolved from the generated runtime's configured\n`build.outputDir/node_modules` first. If definitions live in `quickback/` and\nthe generated Worker lives in `src/`, install runtime dependencies in `src/`\nas usual; no project-root dependency symlink is required. Shared schema or DTO\nmodules may also declare top-level Drizzle selection objects. Quickback\nreplaces authored table exports with inert proxies during this schema-only\nevaluation, so reading `records.id` to build a projection does not execute\napplication or database logic.\n\nParameterized standalone paths use Hono's `:param` syntax in authored source,\nfor example `path: \"/events/:eventId/check-in\"`. The harvest planner converts\nthose segments to the OpenAPI `{param}` form before applying the schema, so\ncontract-v2 completeness uses the same route key as the emitted OpenAPI and MCP\nsurfaces. The same normalization applies when a record resource path contains\nnamespace parameters.\n\n### Configuration Options\n\n| Option | Required | Description |\n|--------|----------|-------------|\n| `description` | Yes | Human-readable description of the action |\n| `input` | Yes | Zod schema for request validation |\n| `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |\n| `access` | Yes | Access control (roles, record conditions, or function) |\n| `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |\n| `path` | Standalone only | Custom route path. Presence of `path` makes the action standalone. |\n| `method` | No | HTTP method: GET, POST, PUT, PATCH, DELETE (default: POST). GET actions parse `input` from query params; all other methods parse from the JSON body. See [GET vs POST for input](#get-vs-post-for-input). |\n| `responseType` | No | Response format: json, stream, file (default: json) |\n| `sideEffects` | No | Hint for AI tools: `'sync'`, `'async'`, or `'fire-and-forget'` |\n| `allowRawSql` | No | Explicit compile-time opt-in for raw SQL in execute code |\n| `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |\n| `transition` | No | State-machine policy enforcing the from/to pair. Lives on a record-based action, or on a standalone action paired with a `record:` binding. See [Transitions](/compiler/definitions/transitions) |\n| `record` | Standalone only | Feature-area transition adapter binding: `{ table, idFrom: \"path.<param>\", matchScope? }`. Binds + firewalls the record a `transition` operates on from a proven route param. See [Feature-area transition adapter](#feature-area-transition-adapter) |\n| `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |\n| `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |\n| `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |\n| `cms` | No | Pass-through metadata blob for CMS surfaces |\n\n`execute` must be an `async (ctx) => { … }` arrow function. `async function`\ndeclarations and non-async forms are rejected at parse time.\n\n## Record-Based Actions\n\nRecord-based actions operate on an existing record. The record is automatically loaded and validated before your action executes.\n\n**Route pattern:** `{METHOD} /:id/{actionName}`\n\n```\nPOST /applications/:id/advance\nPOST /applications/:id/reject\nPOST /applications/:id/schedule-interview\n```\n\n### Runtime Flow\n\n1. **Authentication** - User token is validated\n2. **Input Validation** - Request body validated against Zod schema\n3. **Role Gate** - The access roles are checked *before* the record is\n fetched (v0.46+), so a wrong-role caller gets a uniform\n `403 ACCESS_ROLE_REQUIRED` whether or not the record exists — the\n response can't be used to probe for record ids\n4. **Record Loading** - The record is fetched by ID **through the firewall**\n (a cross-tenant or missing id is a standard firewall miss)\n5. **Access Check** - Record preconditions (`access.record`) and transition\n policy are validated against the loaded record\n6. **Execution** - Your action handler runs\n7. **Response** - Result is returned to client\n\n### Example: Advance Application Stage\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Move application to the next pipeline stage\",\n input: z.object({\n stage: z.enum([\"screening\", \"interview\", \"offer\", \"hired\"]),\n notes: z.string().optional(),\n }),\n access: {\n roles: [\"owner\", \"hiring-manager\"],\n record: { stage: { notEquals: \"rejected\" } },\n },\n async execute({ db, record, input }) {\n const [updated] = await db\n .update(applications)\n .set({\n stage: input.stage,\n notes: input.notes ?? record.notes,\n })\n .where(eq(applications.id, record.id))\n .returning();\n return updated;\n },\n});\n```\n\n### Request Example\n\n```\nPOST /applications/app_123/advance\nContent-Type: application/json\n\n{\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n}\n```\n\n### Response Example\n\n```json\n{\n \"data\": {\n \"id\": \"app_123\",\n \"stage\": \"interview\",\n \"notes\": \"Strong technical background, moving to interview\"\n }\n}\n```\n\n### Bulk variant\n\nSet `bulkVariant: true` to auto-generate a bulk version of the action at\n`POST /:resource/batch/{action}`. The compiler emits a second route alongside\nthe per-record one, looping the same access + transition + execute pipeline\nover an array of ids. This is the answer to \"I need to advance 50\napplications at once\" — you don't have to hand-roll a parallel standalone\naction that duplicates the per-record logic.\n\n```typescript\n// features/applications/actions/advance.ts\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n bulkVariant: true,\n transition: {\n field: \"status\",\n via: \"nextStatus\",\n fromTo: { applied: [\"screening\"], screening: [\"interview\"], interview: [\"offer\"] },\n },\n async execute({ db, record, input, whereTransition }) {\n const [updated] = await db\n .update(applications)\n .set({ status: input.nextStatus })\n .where(whereTransition!(applications))\n .returning();\n if (!updated) throw new TransitionLostError(\"status\", record.status, input.nextStatus);\n return updated;\n },\n});\n```\n\n**Request shape:**\n\n```http\nPOST /applications/batch/advance\nContent-Type: application/json\n\n{\n \"ids\": [\"app_001\", \"app_002\", \"app_003\"],\n \"input\": { \"nextStatus\": \"interview\" },\n \"failFast\": false\n}\n```\n\nThe `input` is shared across the batch — the action's Zod schema is\nvalidated once, not per id. For per-record input variation, use the\nsingle-record endpoint (`POST /:id/{action}`) or write a standalone action.\n\nThe generated OpenAPI document and MCP tools reuse that exact action schema\nin both places: as the single-record request body and as the bulk wrapper's\nnested `input` property. Under contract v2, Quickback considers the action's\nschema harvest complete only after both operations are patched. This also\nholds when the table filename and declared table name use different casing or\nseparators (for example, `event-guests.ts` exporting `event_guests`); the\noperations follow the table's declared resource path.\n\n**Response (207 Multi-Status when any record fails, 200 when clean):**\n\n```json\n{\n \"success\": [{ \"id\": \"app_001\", \"status\": \"interview\" }],\n \"errors\": [\n {\n \"index\": 1,\n \"id\": \"app_002\",\n \"error\": {\n \"error\": \"Action not allowed for current state\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": { \"field\": \"status\", \"currentValue\": \"rejected\" }\n }\n }\n ],\n \"meta\": {\n \"total\": 3,\n \"succeeded\": 2,\n \"failed\": 1,\n \"failFast\": false,\n \"transactional\": false\n }\n}\n```\n\n**Per-record pipeline** mirrors the single-record route exactly — the same\nfirewall fetch, access reason split (403 vs 409), transition pre-check,\n`whereTransition` factory, and `TransitionLostError` handling. Per-record\nfailures land in `errors[]` with their original index; successful records\nland in `success[]` masked the same way the single-record response is.\n\n**Transactional matrix** (same as `PATCH /batch`):\n\n| Provider | failFast | transactional | Behavior |\n|---|---|---|---|\n| tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the loop; any throw rolls back all writes |\n| (any) | `false` | `false` | Independent per-record outcomes, partial success |\n| cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — earlier records stay committed (the driver has no `db.transaction`; `drizzle-orm/neon-http` throws at runtime) |\n\n**Constraints:**\n\n- Record-based actions only. Standalone actions reject `bulkVariant: true`\n at compile time (no record context to loop over).\n- `unsafe` actions reject `bulkVariant: true` in v1 — the cross-tenant\n per-record audit story is not yet wired through.\n- Method is forced to POST regardless of the action's `method` setting. The\n semantic asymmetry (one row → many rows) makes inheriting GET/DELETE\n confusing.\n- Max batch size is 100 ids per request.\n\n## Standalone Actions\n\nStandalone actions are independent endpoints that don't require a record context. Set a `path:` to declare the action standalone.\n\n**Route pattern:** Custom `path`\n\n```\nPOST /chat\nGET /reports/summary\nPOST /webhooks/stripe\n```\n\nPaths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)\nwith a mounted prefix, two more forms apply:\n\n- **Relative** — `path: './tasks/add'` resolves against the area's prefix\n (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are\n rejected at compile time.\n- **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the\n area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected\n where it would be dead). The action is then gated solely by its own `access:` and listed in\n `quickback/authz-manifest.json`.\n\nAn action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —\nand never vocabulary of an area the feature is not inside (compile error).\n\n### Feature-area transition adapter\n\nA record [state transition](/compiler/definitions/transitions) normally lives on a\ntable-bound record action (`POST /:id/{action}`). When your clients call a nested\n**feature-area** route instead, you can attach the same compiler-owned transition to\nan explicit (`path:`) action by adding a `record:` binding. The binding is what lets a\n`transition` ride a standalone action — without it, `transition` on a `path:` action is\na compile error.\n\n```typescript\n// features/events/event_documents/actions/publishEventDocument.ts\nexport default defineAction({\n path: \"/events/:eventId/documents/:documentId/publish\",\n method: \"POST\",\n description: \"Publish one completed event document.\",\n input: z.object({ idempotencyKey: z.string().min(8) }),\n access: { roles: [\"member+\"] },\n // The compiler — not the action body — binds and firewalls the record.\n record: {\n table: \"event_documents\",\n idFrom: \"path.documentId\", // MUST be a route param, never a body field\n matchScope: \"event\", // row.eventId === ctx.event.id (area-proven)\n },\n transition: {\n field: \"status\",\n to: \"published\",\n fromTo: { draft: [\"published\"] },\n idempotent: \"noop\",\n stamp: { at: \"publishedAt\" },\n },\n async execute({ record, invalidate }) {\n // `record` is already bound, firewalled, area-matched, and transitioned.\n // Own the response projection + invalidations here.\n return { success: true as const, document: record };\n },\n});\n```\n\nSecurity semantics (all enforced by the compiler, fail-closed):\n\n- The record id is bound from the **proven route param** named in `idFrom` (`path.<param>`);\n a request-body source is rejected at compile time.\n- The row is loaded through the **scoped db**, so the table's full firewall\n (org / owner / team + soft-delete) applies — a cross-tenant id is a `404`, never a leak.\n- `matchScope` asserts the row belongs to the **area-proven** scope (e.g. `:eventId`\n hydrated onto `ctx.event`); an unhydrated scope fails closed (`500`), and a row under a\n different scope is a `404` (no cross-scope existence oracle).\n- The transition keeps its **TOCTOU-safe guarded UPDATE** — the from-state is re-validated\n in the `WHERE`, and a lost race returns `409` `ACCESS_TRANSITION_LOST`.\n- Area admission **and** the action's own `access:` still AND-compose; the adapter widens neither.\n- `idempotent: \"noop\"` short-circuits **before** `execute`, so a no-op never fires the\n action's invalidations. Existing record actions and table-level transitions are unchanged.\n\n### Example: AI Chat with Streaming\n\n```typescript\n// features/sessions/actions/chat.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Send a message to AI\",\n path: \"/chat\",\n method: \"POST\",\n responseType: \"stream\",\n input: z.object({\n message: z.string().min(1).max(2000),\n }),\n access: { roles: [\"recruiter\", \"hiring-manager\"] },\n async execute({ input, c }) {\n // Stream response back to client...\n return c.newResponse(/* ReadableStream */);\n },\n});\n```\n\n### Streaming Response Example\n\nFor actions with `responseType: 'stream'`:\n\n```\nContent-Type: text/event-stream\n\ndata: {\"type\": \"start\"}\ndata: {\"type\": \"chunk\", \"content\": \"Hello\"}\ndata: {\"type\": \"chunk\", \"content\": \"! I'm\"}\ndata: {\"type\": \"chunk\", \"content\": \" here to help.\"}\ndata: {\"type\": \"done\"}\n```\n\n### Tableless Features\n\nA feature directory with no top-level `*.ts` files is \"tableless\" — every\naction under `actions/` must be standalone. Use this for utility endpoints\nlike reports, integrations, or webhooks that don't map to a specific\nresource.\n\n```\nquickback/features/\n└── reports/\n └── actions/\n ├── trial-balance.ts ← standalone (has path:)\n └── profit-loss.ts ← standalone (has path:)\n```\n\n```typescript\n// features/reports/actions/trial-balance.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Generate trial balance report\",\n path: \"/reports/trial-balance\",\n method: \"GET\",\n input: z.object({\n startDate: z.string(),\n endDate: z.string(),\n }),\n access: { roles: [\"admin\", \"accountant\"] },\n async execute({ db, input }) {\n // ... build report\n return { rows: [] };\n },\n});\n```\n\n### GET vs POST for input\n\nGET actions read `input` from URL query parameters; every other method (POST,\nPUT, PATCH, DELETE) reads from the JSON body. The Zod schema is the same in\nboth cases — the compiler picks the right parser based on `method`.\n\n```typescript\n// GET — input populated from ?q=…&limit=…\ndefineAction({\n method: \"GET\",\n path: \"/search\",\n input: z.object({\n q: z.string(),\n limit: z.coerce.number().int().positive().max(100).default(20),\n }),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ input }) {\n // input is { q: string, limit: number } — fully typed.\n },\n});\n```\n\nRepeated query keys (`?tag=a&tag=b`) come through as arrays automatically;\nsingle values stay as strings. Use Zod's `.coerce.number()` /\n`.coerce.boolean()` when you want typed primitives from the parsed strings.\n\n**Use POST when input is structured.** GET requests cannot carry a JSON body\nin any of the surfaces Quickback APIs are commonly called from:\n\n- Browsers throw on `fetch(url, { method: 'GET', body })`.\n- CDNs and caches key on URL+method; a GET with a body either gets the body\n stripped at the edge or cache-collides with semantically different requests.\n- OpenAPI client generators (axios, openapi-fetch, openapi-typescript-codegen)\n refuse to emit GET-with-body, so the generated SDKs break.\n- The MCP agent surface treats GET as parameter-only — agents calling a GET\n action will only see what the URL exposes.\n\nIf your action takes nested objects, arrays of objects, or large inputs that\ndon't serialize cleanly to a query string, set `method: \"POST\"`. POST doesn't\nimply \"this writes data\" — it's the right method whenever the request body is\nload-bearing. Use the response shape (`responseType: \"json\"`, or just the data\nyour handler returns) to convey read semantics; HTTP method choice is about\ninput transport, not action intent.\n\n## Access Configuration\n\nAccess controls who can execute an action and under what conditions.\n\n### Role-Based Access\n\n```typescript\naccess: {\n roles: [\"hiring-manager\", \"recruiter\"] // OR logic: user needs any of these roles\n}\n```\n\nIf the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).\n\n[Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.\n\n**A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.\n\n### Public Access\n\nUse `roles: [\"PUBLIC\"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.\n\n```typescript\n// features/contact/actions/submit.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Public contact form submission\",\n path: \"/submit\",\n input: z.object({\n name: z.string().min(1),\n email: z.string().email(),\n message: z.string().min(10),\n }),\n access: { roles: [\"PUBLIC\"] },\n async execute({ db, input }) {\n // ... persist submission\n return { ok: true };\n },\n});\n```\n\nThe wildcard `\"*\"` is not supported and will throw a compile-time error. Use `\"PUBLIC\"` explicitly.\n\n### Record Conditions\n\nFor record-based actions, you can require the record to be in a specific state:\n\n```typescript\naccess: {\n roles: [\"hiring-manager\"],\n record: {\n stage: { equals: \"screening\" } // Precondition\n }\n}\n```\n\n**Supported operators:**\n\n| Operator | Description |\n|----------|-------------|\n| `equals` | Field must equal value |\n| `notEquals` | Field must not equal value |\n| `in` | Field must be one of the values |\n| `notIn` | Field must not be one of the values |\n\n### Context Substitution\n\nUse `$ctx` to reference the current user's context:\n\n```typescript\naccess: {\n record: {\n ownerId: { equals: \"$ctx.userId\" },\n organizationId: { equals: \"$ctx.activeOrgId\" }\n }\n}\n```\n\n### OR/AND Combinations\n\n```typescript\naccess: {\n or: [\n { roles: [\"hiring-manager\"] },\n {\n roles: [\"recruiter\"],\n record: { ownerId: { equals: \"$ctx.userId\" } }\n }\n ]\n}\n```\n\n### Function Access\n\nFor complex logic, use an access function:\n\n```typescript\naccess: async (ctx, record) => {\n return ctx.roles.includes('admin') || record.ownerId === ctx.userId;\n}\n```\n\n### Relationship-roles in actions\n\nBoth standalone and record-based actions support relationship roles directly in\n`access.roles`. Declare the relationship under `authz.relationships`, name it\nunder `authz.roles`, and use that name like any organization or pseudo-role.\n\nFor a standalone action, optional `loads` / `exposeAs` fields can hydrate the\nmatched resource onto `ctx`:\n\n```ts\n// quickback.config.ts\nauthz: {\n relationships: {\n attendeeOf: {\n from: 'guests',\n subject: { column: 'userId', equals: 'ctx.userId' },\n resource: { column: 'eventId' },\n where: { status: 'confirmed' },\n loads: 'events',\n exposeAs: 'event',\n },\n },\n roles: { attendee: { via: 'attendeeOf' } },\n}\n\n// features/chat/actions/getInbox.ts\nexport default defineAction({\n path: '/chat/get-inbox',\n input: z.object({ eventId: z.number().int().positive() }),\n access: { roles: ['admin', 'member', 'attendee'] },\n execute: async ({ db, ctx, input }) => {\n // The resolver already verified attendance and loaded ctx.event.\n // No hand-rolled `SELECT … FROM guests WHERE …` needed.\n },\n});\n```\n\nThe standalone action's surface (path params + input fields) must expose the\nrelationship's `resource.column`. A missing key is a compile error, so the\nresolver can never be skipped silently. See [Access — standalone\nactions](/compiler/definitions/access#standalone-actions-surface-keys-and-loads--exposeas-v019)\nfor the full mechanism.\n\nFor a record-based action, Quickback already has the firewalled record in\nscope. It emits an inline relationship match against that record before\n`execute()` runs:\n\n```typescript\n// features/sessions/actions/comment.ts\nexport default defineAction({\n input: z.object({ text: z.string().max(2000) }),\n access: { roles: ['guest', 'admin'] },\n async execute({ db, record, input }) {\n // The route loaded `record` through its firewall, then verified guestOf\n // against record.eventId. Only domain logic remains here.\n return db.insert(comments).values({\n sessionId: record.id,\n text: input.text,\n });\n },\n});\n```\n\nSimple role arms are checked before the record lookup to preserve ID-probe\nresistance. Relationship arms run only after the record has been loaded through\nthe firewall, because the record supplies the relationship key. No manual\nlookup or firewall exception is required.\n\nSee [Access — relationship\nauthorization](/compiler/definitions/access#relationship-based-authorization)\nfor the full surface matrix, namespace hoisting, and tenant-context stamping.\n\n## Scoped Database\n\nAll actions receive a **scoped `db`** instance that automatically enforces security:\n\n| Operation | Org Scoping | Owner Scoping | Soft Delete Filter | Auto-inject on INSERT |\n|-----------|-------------|---------------|--------------------|-----------------------|\n| `SELECT` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `INSERT` | n/a | n/a | n/a | `organizationId`, `ownerId` from ctx |\n| `UPDATE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n| `DELETE` | `WHERE organizationId = ?` | `WHERE ownerId = ?` | `WHERE deletedAt IS NULL` | n/a |\n\nScoping is duck-typed at runtime — tables with an `organizationId` column get org scoping, tables with `ownerId` get owner scoping, tables with `deletedAt` get soft delete filtering.\n\n```typescript\nasync execute({ db, ctx, input }) {\n // This query automatically includes WHERE organizationId = ? AND deletedAt IS NULL\n const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));\n\n // Inserts automatically include organizationId\n await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });\n\n return items;\n}\n```\n\n**Not enforced** in scoped DB (by design):\n- **Guards** — actions ARE the authorized way to modify guarded fields\n- **Masking** — actions are backend code that may need raw data\n- **Access** — already checked before action execution\n\n### Delegated principals and `databaseAccess`\n\nOn a contract-v2 Cloudflare + Neon Hyperdrive project, an action can admit a\nconfigured delegated principal with `access.principals`:\n\n```typescript\nexport default defineAction({\n description: \"Confirm attendance from an event session\",\n path: \"/attendance/confirm\",\n input: z.object({ response: z.enum([\"yes\", \"no\"]) }),\n access: { principals: [\"event_delegate\"] },\n async execute({ ctx, db, input }) {\n // ctx.principal is guaranteed and narrowed by the generated helper.\n const { eventId, personId } = ctx.principal.claims;\n return confirmAttendance(db, { eventId, personId, response: input.response });\n },\n});\n```\n\nThis is a separate authority lane, not an account impersonation. A delegated\naction context has no `userId`, active organization/team, or membership roles.\nIf access has a `PUBLIC` sibling arm, the generated type includes the anonymous\nlane and code must narrow `ctx.principal` before reading it.\n\nFor an organization- or team-scoped host feature, the standalone route does\nnot run the Better Auth `activeOrgId` / `activeTeamId` precondition before a\nprincipal access tree. Authentication and `evaluateAccessPreRecord` still run;\nthe declared `principals` arm is the authority decision. This avoids turning an\naccount-session field into an accidental prerequisite for delegated callers.\n\nThe generated standalone route reuses that action-specific `execute` context\nafter its runtime access gates. Account, `event_pass`, and `event_delegate`\nactions therefore keep distinct compile-time authority types all the way into\nthe handler. The route also reuses the action's schema-aware scoped `db` type,\nincluding when an unsafe/service-role client is wrapped before the call. If a\nrelationship uses `loads` / `exposeAs`, the loaded row type is\nintersected with the same authority context: a single or shared hydration\ntarget is required, while targets selected by distinct relationship lanes are\noptional and must be narrowed by the handler.\n\nFor tables queried by authored actions, `resource.databaseAccess` adds an\nindependent Postgres RLS policy without adding HTTP surface. It never mounts a\nread/CRUD route and never adds an OpenAPI operation. The action remains the API\nlayer where validation, state transitions, side effects, and business logic\nbelong; `databaseAccess` is only the database's row-level upper bound.\n\n```typescript\nexport default defineTable(attendanceEvidence, {\n // Ordinary account CRUD remains organization-scoped.\n firewall: [\n { field: \"organizationId\", equals: \"ctx.activeOrgId\" },\n ],\n\n // Authored actions can use their caller-scoped db under one of two exact\n // row lanes. Sibling arms OR; fields in each arm AND.\n databaseAccess: {\n select: {\n or: [\n {\n roles: [\"AUTHENTICATED\"],\n record: {\n organizationId: { equals: \"$ctx.activeOrgId\" },\n },\n },\n {\n principals: [\"event_delegate\"],\n record: {\n eventId: { equals: \"$ctx.principal.claims.eventId\" },\n personId: { equals: \"$ctx.principal.claims.personId\" },\n },\n },\n ],\n },\n },\n});\n```\n\n`databaseAccess` supports `select`, `insert`, `update`, and `delete` with a\npurpose-built, SQL-pushable rule language: `principals`, `roles`, recursive\n`or`/`and`, and record `equals` against a DB-visible account or principal\ncontext value. Application-only values such as `userRole`, functions, and\nrequest/body fields stay at the action access layer; the compiler refuses them\ninside database RLS rather than pretending PostgreSQL can evaluate them.\n\nEvery authorization path must contain at least one nonempty record equality.\nA principal-only or role-only leaf is rejected; every `or` arm must be bounded.\nAn `and` group is bounded when at least one child bounds every expansion (for\nexample, a principal child AND an event-id record child). A node cannot mix\nleaf fields with `or`/`and`, because the boolean node is the complete rule.\nThis mandatory shape prevents an action declaration from accidentally granting\nthe delegated principal an entire table.\n\nThe supported equality sources are `ctx.userId`, `ctx.activeOrgId`,\n`ctx.activeTeamId`, `ctx.principal.actor.id`, optional principal session/family\nids, and `ctx.principal.claims.<name>` (with or without a leading `$`). The\nrecord keys are Drizzle/JavaScript table field names; Quickback resolves them\nthrough the table metadata and quotes the exact physical PostgreSQL identifier,\nso a field such as `eventId: text(\"event-id\")` is safe. Unknown fields fail the\ncompile. `ADMIN` and the app-only `INTERNAL` marker are forbidden on this DB\nsurface, while `SYSADMIN` retains its explicit `cms.sysadmin` prerequisite. The\nfeature is rejected outside Cloudflare + Neon Hyperdrive because those targets\ncannot guarantee request-scoped Postgres claims.\n\n### Scoped relational-query safety\n\nDrizzle's relational query API — `db.query.<table>.findFirst()` /\n`findMany()` (including nested `with:` relations) — builds its SQL from the\nrelations config and your `where` alone, so the scoped wrapper cannot inject\nthe org/owner/team firewall into it. The scoped `db` therefore exposes the\nDrizzle select builder—the path where Quickback can guarantee firewall\ninjection—and refuses `db.query.<table>` rather than returning unscoped rows:\n\n```typescript\nasync execute({ db, input }) {\n // ❌ Throws: relational queries aren't org-scoped\n const item = await db.query.media.findFirst({ where: eq(media.id, input.id) });\n\n // ✅ Scoped builder — firewall conditions injected automatically\n const [item] = await db.select().from(media).where(eq(media.id, input.id));\n}\n```\n\nFor nested reads, compose joins with the scoped select builder. If a\nPostgres-specific relational query is genuinely required, make the boundary\nexplicit with `unsafe: true` and query `unsafeDb.query` with the full scope\npredicate in the `WHERE` (for example,\n`eq(media.organizationId, ctx.activeOrgId)`).\n\n### Unsafe Mode\n\nActions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.\n\nUse object form for explicit policy and mandatory audit metadata:\n\n```typescript\n// features/admin/actions/cross-tenant-report.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../../applications/applications\";\n\nexport default defineAction({\n description: \"Generate cross-org hiring report\",\n path: \"/admin/cross-tenant-report\",\n input: z.object({ startDate: z.string() }),\n access: { roles: [\"owner\"] },\n unsafe: {\n reason: \"Support investigation for enterprise customer\",\n adminOnly: true, // default true\n crossTenant: true, // default true\n targetScope: \"all\", // \"all\" | \"organization\"\n },\n async execute({ unsafeDb, input }) {\n // unsafeDb bypasses scoped filters\n const allOrgs = await unsafeDb.select().from(applications);\n return allOrgs;\n },\n});\n```\n\nUnsafe cross-tenant actions are generated with:\n\n- Better Auth authentication required (no unauthenticated path)\n- sysadmin gate (`ctx.userRole === \"sysadmin\"`)\n- mandatory audit logging on deny/success/error\n\n**Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query\nbypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An\nunsafe action with `crossTenant: false` receives a raw Drizzle handle backed by\nthe request database, so the caller's organization or delegated-principal\nclaims remain active—including inside `db.transaction()`. Its code must still\nprovide every intended scope predicate explicitly.\n\nOnly an action with `crossTenant: true` acquires the dedicated service-role\nhandle (`createServiceDb`). That handle sets the `quickback.service_role`\ntransaction marker instead of caller claims, and generated RLS grants it an\nexplicit per-table bypass policy. The sysadmin guard and mandatory audit log\ntherefore protect the same boundary that receives the RLS bypass. The\naudit-logging contract is otherwise identical to D1. On Cloudflare, both HTTP\nand Hyperdrive are supported. Hyperdrive is the recommended lane when an unsafe\naction also needs an interactive transaction. The deprecated Node/Bun WebSocket\nmode is refused for unsafe actions because it cannot provide the same\nrequest-scoped service-role boundary.\n\n`PUBLIC` actions also receive mandatory audit logging (same audit table), since unauthenticated endpoints are high-risk by nature.\n\nWithout unsafe mode, `unsafeDb` is `undefined` in the executor params.\n\n### Raw SQL Policy\n\nBy default, the compiler rejects raw SQL in action code. Use Drizzle query-builder syntax whenever possible.\n\nIf a specific action must use raw SQL, opt in explicitly:\n\n```typescript\n// features/ledgers/actions/reconcile.ts\nimport { z } from \"zod\";\nimport { sql } from \"drizzle-orm\";\nimport { defineAction } from \"../.quickback/define-action\";\n\nexport default defineAction({\n description: \"Run custom reconciliation query\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n allowRawSql: true,\n async execute({ db }) {\n return db.execute(sql`select 1`);\n },\n});\n```\n\nWithout `allowRawSql: true`, compilation fails with a loud error pointing to the action and snippet.\n\nThe detector checks for SQL keywords in string arguments, so non-SQL method calls like `headers.get(\"X-Forwarded-For\")` or `map.get(\"key\")` will not trigger false positives.\n\n## Sharing Code Between Actions\n\nFor Zod schemas, helpers, or constants used across multiple actions in a\nfeature, put them under `<feature>/lib/` and import from each action file.\nFiles under `lib/` are copied verbatim into the generated output.\n\n```\nfeatures/applications/\n├── applications.ts\n├── actions/\n│ ├── advance.ts\n│ └── reject.ts\n└── lib/\n ├── inputs.ts ← shared Zod schemas\n └── transitions.ts ← state-machine helpers\n```\n\n```typescript\n// features/applications/lib/inputs.ts\nimport { z } from \"zod\";\n\nexport const advanceInput = z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n notes: z.string().max(2000).optional(),\n});\n```\n\n```typescript\n// features/applications/actions/advance.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { advanceInput } from \"../lib/inputs\";\n\nexport default defineAction({\n description: \"Move forward\",\n input: advanceInput,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input }) { /* … */ },\n});\n```\n\n### Importing Tables\n\nAction files import tables from their own feature or other features. The compiler generates alias files for each table, so you import by the table's file name:\n\n```typescript\n// features/applications/actions/advance.ts\nimport { eq, and } from \"drizzle-orm\";\n\n// Same feature — import from parent directory using the table's file name\nimport { applications } from \"../applications\";\nimport { interviewScores } from \"../interview-scores\";\n\n// Cross-feature — go up to the features directory, then into the other feature\nimport { candidates } from \"../../candidates/candidates\";\nimport { jobs } from \"../../jobs/jobs\";\n```\n\n**Path pattern from `features/{name}/actions/`:**\n- Same feature table: `../{table-file-name}` (e.g., `../applications`)\n- Other feature table: `../../{other-feature}/{table-file-name}` (e.g., `../../candidates/candidates`)\n- Generated lib files: `../../../lib/{module}` (e.g., `../../../lib/realtime`, `../../../lib/webhooks`)\n\n### Executor Parameters\n\n```typescript\nimport type { Auth } from \"better-auth\";\n\ninterface ActionExecutorParams {\n db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)\n unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)\n ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)\n record?: TRecord; // The record (record-based only, undefined for standalone)\n input: TInput; // Validated input from Zod schema\n services: TServices; // Configured integrations (billing, notifications, etc.)\n c: HonoContext; // Raw Hono context for advanced use\n env: Env; // Runtime bindings (Cloudflare env / process env). Alias for c.env.\n auth: Auth; // Better Auth instance — call auth.api.getSession(...) etc. Lazy on Cloudflare.\n whereRecord?: (table) => SQL; // Pre-built WHERE: firewall + soft-delete + eq(table.id, record.id). Record-based actions only.\n whereTransition?: (table) => SQL; // whereRecord plus the transition's \"from\" precondition. Transition actions only.\n}\n```\n\n#### `auth` — Better Auth instance\n\n`auth` is the Better Auth instance, ready to call from inside an action\nhandler. Use it for things like minting an OAuth access token, fetching the\ncurrent session in a custom way, or invoking a Better Auth plugin method\nthat isn't already exposed by the generated middleware.\n\n```typescript\n// features/integrations/actions/connect-google-drive.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { z } from \"zod\";\n\nexport default defineAction({\n description: \"Get a fresh Google Drive access token for the signed-in user\",\n input: z.object({}),\n access: { roles: [\"AUTHENTICATED\"] },\n async execute({ auth, ctx, c }) {\n // genericOAuth plugin method — needs a cast since the default-generic\n // `Auth` type doesn't carry plugin-specific API surface.\n const token = await (auth.api as any).getAccessToken({\n headers: c.req.raw.headers,\n body: { providerId: \"google\", userId: ctx.userId },\n });\n return { accessToken: token.accessToken };\n },\n});\n```\n\n**Lazy on Cloudflare**: the generated handler emits a `Proxy` so\n`createAuth(c.env, c.req.raw.cf)` only runs the first time you read a\nproperty on `auth`. Actions that never touch `auth` pay zero construction\ncost. On Bun/Node `auth` is the imported singleton (an IIFE that lazy-loads\nthe database adapter) wrapped in the same proxy shape — call sites are\nidentical across runtimes.\n\n**Typing**: `auth` is typed as `Auth` from `better-auth`. The base API\n(`getSession`, `signOut`, `signInEmail`, etc.) is fully typed. Plugin-only\nmethods (`getAccessToken` from `genericOAuth`, admin-plugin methods, etc.)\nneed a cast at the call site — the default-generic `Auth` doesn't infer\nthe project's specific plugin set.\n\n#### `whereRecord` — explicit, scope-safe WHERE\n\nFor protected-field writes inside record-based actions, prefer\n`whereRecord(table)` over `eq(table.id, record.id)`. It returns a Drizzle\nexpression that AND-merges the resource's firewall and soft-delete predicates\nwith the record id, so the WHERE is explicit even if a future refactor swaps\n`db` back to an unscoped client:\n\n```typescript\n// features/applications/actions/advance.ts\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Advance\",\n input: /* … */,\n access: { roles: [\"owner\"] },\n async execute({ db, record, input, whereRecord }) {\n const [updated] = await db\n .update(applications)\n .set({\n status: input.nextStatus,\n notes: input.notes ?? record.notes,\n })\n .where(whereRecord!(applications)) // firewall + soft-delete + id, all in one\n .returning();\n return updated;\n },\n});\n```\n\nThe audit DB wrapper hard-stamps `modifiedAt`/`modifiedBy` on every\n`.set()` call, so handlers don't write them. The same wrapper hard-stamps\n`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy` on every `.values()` —\nand on the conflict branch of an `onConflictDoUpdate({...})` upsert.\nCaller-supplied audit fields are dropped on the floor — the audit log\nalways reflects the real actor and the real moment.\n\nWho the stamped actor is depends on the verified principal, never on\nanything the handler passes:\n\n| Caller | `createdBy` / `modifiedBy` value |\n|---|---|\n| Signed-in user | the Better Auth `userId` |\n| Delegated principal (API key, service) | `actor:<type>:<id>` |\n| Scope-token principal (no account) | `scope:<kind>:<subjectId>` |\n| Cron schedule via `withInternalContext` | `system:cron-<name>` |\n| Queue handler via `withInternalContext` | `system:queue-<name>` |\n| No verified caller | the write **throws** (fail closed) — system-side code that must write outside a request uses the raw client and owns its own provenance |\n\nDon't hand-build audit timestamps as a \"just in case\" fallback: on the\nwrapped `db` they're dead code, and the idiom is a portability trap —\nPostgres audit columns take `Date` objects while SQLite takes ISO strings\n(the wrapper picks the right one per dialect).\n\n`whereRecord` is undefined for standalone actions (they have no record), so\nthe parameter is typed as optional. `whereTransition` extends `whereRecord`\nwith the transition's \"from\" precondition for transition actions.\n\n#### Reaching Better Auth tables (`authDb`)\n\nThe scoped `db` only sees your feature tables. To read Better Auth tables —\nusers, organizations, members — use the auth database connection from the\nHono context plus the generated `lib/org-access.ts` helper:\n\n```typescript\n// features/projects/actions/assign.ts — validate a userId is an org member\nimport { z } from \"zod\";\nimport { eq } from \"drizzle-orm\";\nimport { ActionError } from \"@quickback/compiler\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { getOrgMemberRole } from \"../../../lib/org-access\";\nimport { projects } from \"../projects\";\n\nexport default defineAction({\n description: \"Assign a project to an org member\",\n input: z.object({ assigneeId: z.string() }),\n access: { roles: [\"member\", \"admin\"] },\n async execute({ db, record, input, ctx, c, whereRecord }) {\n // getOrgMemberRole(authDb, userId, organizationId) → role string | null\n const role = await getOrgMemberRole(c.get(\"authDb\"), input.assigneeId, ctx.activeOrgId!);\n if (!role) {\n throw new ActionError(\"Assignee is not a member of this organization\", \"NOT_A_MEMBER\", 400);\n }\n const [updated] = await db\n .update(projects)\n .set({ assigneeId: input.assigneeId })\n .where(whereRecord!(projects))\n .returning();\n return updated;\n },\n});\n```\n\n`c.get(\"authDb\")` is the Drizzle connection to the auth database (in dual-DB\nmode it's a separate D1 from your features). For richer queries, import the\nauth schema tables from `../../../auth/schema` and query `authDb` directly.\n\n## HTTP API Reference\n\n### Request Format\n\n| Method | Input Source | Use Case |\n|--------|--------------|----------|\n| `GET` | Query parameters | Read-only operations, fetching data |\n| `POST` | JSON body | Default, state-changing operations |\n| `PUT` | JSON body | Full replacement operations |\n| `PATCH` | JSON body | Partial updates |\n| `DELETE` | JSON body | Deletion with optional payload |\n\n### Response Formats\n\n| Type | Content-Type | Use Case |\n|------|--------------|----------|\n| `json` | `application/json` | Standard API responses (default) |\n| `stream` | `text/event-stream` | Real-time streaming (AI chat, live updates) |\n| `file` | Varies | File downloads (reports, exports) |\n\n### Error Codes\n\n| Status | Description |\n|--------|-------------|\n| `400` | Invalid input / validation error (also `GUARD_FIELD_PROTECTED` for direct protected-field writes) |\n| `401` | Not authenticated |\n| `403` | Access role check failed (`ACCESS_ROLE_REQUIRED`) |\n| `404` | Record not found (record-based actions) |\n| `409` | Record is in the wrong state for this action — `access.record` predicate or `transition` policy failed (`ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`) |\n| `500` | Handler execution error |\n\n### Validation Error Response\n\n```json\n{\n \"error\": \"Invalid request data\",\n \"layer\": \"validation\",\n \"code\": \"VALIDATION_FAILED\",\n \"details\": {\n \"fields\": {\n \"amount\": \"Expected positive number\"\n }\n },\n \"hint\": \"Check the input schema for this action\"\n}\n```\n\n### Error Handling\n\n**Option 1: Return a JSON error response** (recommended for most cases)\n\nSince action handlers receive the Hono context (`c`), you can return error responses directly:\n\n```typescript\nasync execute({ ctx, record, input, c }) {\n if (record.stage === 'hired') {\n return c.json({\n error: 'Cannot modify a hired application',\n code: 'ALREADY_HIRED',\n details: { currentStage: record.stage },\n }, 400);\n }\n // ... continue\n}\n```\n\n**Option 2: Throw an ActionError**\n\n```typescript\nimport { ActionError } from \"@quickback/compiler\";\n\nasync execute({ ctx, record, input }) {\n if (record.stage === 'hired') {\n throw new ActionError('Cannot modify a hired application', 'ALREADY_HIRED', 400, {\n currentStage: record.stage,\n });\n }\n // ... continue\n}\n```\n\nThe `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.\n\n## Protected Fields\n\nActions can modify fields that are protected from regular CRUD operations:\n\n```typescript\n// In the table file (defineTable config)\nguards: {\n protected: {\n status: [\"advance\", \"reject\", \"hire\", \"withdraw\"], // Only these actions can modify status\n }\n}\n```\n\nThis allows the `advance` action to set `status = \"interview\"` even though the field is protected from regular PATCH requests. Direct `PATCH /:id` attempts to set `status` are rejected by the guards layer with **400 GUARD_FIELD_PROTECTED**, and the field is omitted from the generated POST/PATCH body Zod schemas — clients cannot even send it past validation.\n\n## Transition (state-machine policy)\n\nFor protected fields that follow a state machine — application status, invoice\nlifecycle, order fulfilment — use `transition` on the action so the compiler\ngenerates a runtime guard that enforces the *from/to pair*, not just the\ncurrent state. Without it, an `advance` action whose input enum allows\n`[\"screening\", \"interview\", \"offer\"]` and whose `access.record` allows\n`status in [\"applied\", \"screening\", \"interview\"]` will happily run\n`applied → offer` (a skip) or `interview → screening` (a regression).\n\n```typescript\n// features/applications/actions/advance.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Move an application forward in the pipeline.\",\n input: z.object({ nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]) }),\n access: { roles: [\"owner\", \"admin\"] },\n transition: {\n field: \"status\",\n via: \"nextStatus\", // read target from input.nextStatus\n fromTo: {\n applied: [\"screening\"],\n screening: [\"interview\"],\n interview: [\"offer\"],\n },\n },\n async execute({ db, record, input, whereTransition }) { /* … */ },\n});\n```\n\n```typescript\n// features/applications/actions/hire.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { applications } from \"../applications\";\n\nexport default defineAction({\n description: \"Finalize an offer.\",\n input: z.object({}),\n access: { roles: [\"owner\"] },\n transition: {\n field: \"status\",\n to: \"hired\", // fixed target — same value every call\n fromTo: { offer: [\"hired\"] },\n },\n async execute({ db, record, whereTransition }) { /* … */ },\n});\n```\n\n| Field | Required | Description |\n|---|---|---|\n| `field` | Yes | Record column to validate (e.g. `\"status\"`) |\n| `fromTo` | Yes | Map of current value → permitted next values. Keys also enumerate the legal source states. |\n| `via` | Yes (or `to`) | Input key that carries the target value. Use for variable-target actions like `advance`. |\n| `to` | Yes (or `via`) | Literal target value the action always writes. Use for fixed-target actions like `hire`/`reject`. |\n\nExactly one of `via` or `to` must be provided. The compiler rejects both at\nvalidate time. When `to` is set, it must appear in some `fromTo[*]` array —\notherwise the action would be unreachable, which is almost certainly a bug.\n\n### Wire-level errors\n\nThe compiled guard returns **409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`** with\nthe field, the current value, the requested target, and the allowed set:\n\n```json\n{\n \"error\": \"Action not allowed for current record state\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ACTION_NOT_ALLOWED_FOR_STATE\",\n \"details\": {\n \"field\": \"status\",\n \"current\": \"interview\",\n \"target\": \"screening\",\n \"allowedTargets\": [\"offer\"]\n },\n \"hint\": \"From \\\"interview\\\", status can transition to: offer\"\n}\n```\n\nThis is distinct from a role failure: if the caller has the wrong role they\nget **403 `ACCESS_ROLE_REQUIRED`** as before. Splitting the two lets clients\ntell *\"you can't do this\"* from *\"you can't do this *yet*\"* — the latter is\nrecoverable by the user, the former isn't.\n\nThe same 409 code is used when an `access.record` predicate (without\n`transition`) fails — for example `record: { status: { equals: \"pending\" } }`\ncalled against a paid invoice now returns 409 `ACCESS_ACTION_NOT_ALLOWED_FOR_STATE`,\nnot a misleading 403.\n\nTransitions grew a v2 surface — guards, timestamp/actor stamps, idempotent\nno-ops, compiler-applied writes with optional `execute`, `undo` pairs, and\ntable-level generated transition actions. See **[Transitions](/compiler/definitions/transitions)**.\n\n## After-commit hooks\n\n> For typed realtime *\"this changed — refresh\"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.\n\nSecondary effects — activity feeds, notification nudges, cache warmers — must\nnever roll back or delay the primary write. Instead of hand-wrapping each leg\nin `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:\n\n```typescript\nexport default defineAction({\n // ...\n execute: async ({ db, record, ctx, now }) => {\n await db.update(guests).set({ checkedInAt: now }).where(/* … */);\n return { success: true, checkedInAt: now };\n },\n afterCommit: {\n // Named hooks run after execute returns successfully, in declared order.\n activityFeed: async ({ db, env, record, ctx }, result) => {\n await recordActivity(db, env, { verb: \"guest.checked_in\", /* … */ });\n },\n // blocking: true is awaited before the response (client depends on it).\n issueBadge: { blocking: true, run: async (actx, result) => { /* … */ } },\n },\n});\n```\n\nThe contract:\n\n- Hooks receive `(actx, result)` — the same context `execute` got, plus its\n return value.\n- Each hook is **independently wrapped**: a throw is logged as\n `[<action>] afterCommit:<hook> failed` and never affects the response or\n other hooks.\n- Non-blocking hooks (the default) ride `executionCtx.waitUntil`; blocking\n hooks are awaited before responding.\n- If `execute` throws, no hooks run. A result carrying `dryRun: true` also\n skips them (preview branches never fire side effects).\n- Bulk twins run hooks **once per invocation** with the bulk envelope as\n `result` — per-record fan-out is the hook author's job.\n\nFor effects that need mid-execute data, the context carries an imperative\nescape hatch with the same semantics:\n\n```typescript\nexecute: async ({ db, effects }) => {\n // …\n effects.enqueue(\"cohortRecalc\", () => recalculate(/* … */));\n return { success: true };\n}\n```\n\nEffects enqueued by an `execute` that later throws are dropped. The context\nalso carries `now` — one ISO timestamp per invocation; prefer it over\n`new Date().toISOString()`.\n\n## Realtime emit from actions\n\nTables that lock auto-CRUD but mutate through custom actions no longer need\nhand-written `realtime.insert/update/delete` blocks. Opt the table in:\n\n```typescript\nrealtime: {\n enabled: true,\n access: { roles: [\"member+\"] },\n scopeKeyFrom: \"events:{eventId}\", // sugar for scopeTable + scopeField\n emitFromActions: true, // scoped-db writes auto-emit after commit\n}\n```\n\nWrites to the table through the scoped `db` inside record-bound and bulk\nactions emit frames byte-compatible with auto-CRUD (same envelope, masking,\naudience), after commit, best-effort. For projections, standalone actions, or\ncross-feature targets, declare an action-level `emit:` to get a pre-bound\n`emitCrud(row, oldRow?)` helper. Full details and the capture caveats live in\nthe [realtime docs](/stack/realtime/durable-objects).\n\n## Refs (scoped foreign-key inputs)\n\nThe most common action preamble — load an input id, 404 if missing, assert it\nbelongs to the caller's event/org — becomes declarative:\n\n```typescript\nexport default defineAction({\n input: z.object({ agendaItemId: z.string(), guestId: z.string(), locationId: z.string().optional() }),\n refs: {\n agendaItemId: { table: \"agendaItems\", as: \"agendaItem\",\n matchScope: \"event\", // row.eventId === ctx.event.id\n notFound: { code: \"ITEM_NOT_FOUND\" } }, // status defaults to 404\n guestId: { table: \"guests\", as: \"guest\",\n matchWith: { ref: \"agendaItem\", on: \"eventId\" }, // cross-input parenthood\n mismatch: { code: \"EVENT_MISMATCH\", status: 400 } },\n locationId: { table: \"locations\", as: \"location\", optional: true, matchScope: \"event\" },\n },\n execute: async ({ input, agendaItem, guest, location }) => { /* … */ },\n});\n```\n\n- Loads run **through the scoped db** before `execute` — the org firewall and\n soft-delete filter apply by construction, so a cross-org id 404s with zero\n hand-written tenancy checks. All loads batch into one `Promise.all`.\n- `matchScope: \"<scope>\"` asserts `row.<scope>Id === ctx.<scope>.id` and\n fail-closes (500) if the scope object isn't hydrated. The explicit form\n `{ column, equals: \"ctx.activeOrgId\" }` is also accepted.\n- `matchWith` compares a column against an earlier-declared ref — declaration\n order defines resolution order; forward references are compile errors.\n- Ref keys must exist on the inline `z.object` input with agreeing\n optionality; `as` names can't shadow reserved context keys. Injected rows\n are the **unmasked** DB rows (masking remains a read-projection concern).\n\n## Examples\n\n### Bulk Import (Standalone, No Record)\n\n```typescript\n// features/candidates/actions/bulk-import.ts\nimport { z } from \"zod\";\nimport { defineAction } from \"../.quickback/define-action\";\nimport { candidates } from \"../candidates\";\n\nexport default defineAction({\n description: \"Import candidates from job board CSV\",\n path: \"/candidates/import\",\n input: z.object({\n data: z.array(z.object({\n email: z.string().email(),\n name: z.string(),\n })),\n }),\n access: { roles: [\"hiring-manager\", \"recruiter\"] },\n async execute({ db, input }) {\n const inserted = await db\n .insert(candidates)\n .values(input.data)\n .returning();\n return { imported: inserted.length };\n },\n});\n```"
|
|
87
87
|
},
|
|
88
88
|
"compiler/definitions/arrows": {
|
|
89
89
|
"title": "Arrows",
|
|
@@ -267,12 +267,16 @@ export const DOCS = {
|
|
|
267
267
|
},
|
|
268
268
|
"compiler/targets/hono-api/using-the-api/openapi": {
|
|
269
269
|
"title": "OpenAPI Spec",
|
|
270
|
-
"content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every
|
|
270
|
+
"content": "The compiler generates an [OpenAPI 3.1](https://spec.openapis.org/oas/v3.1.0) specification from your feature definitions. By default it's both written to `openapi.json` at your project root and served as a runtime route.\n\n## Endpoint\n\n```\nGET /openapi.json\n```\n\nReturns the full OpenAPI spec as JSON.\n\n```bash\ncurl https://your-api.example.com/openapi.json\n```\n\n## What's included\n\nThe generated spec documents every route the compiler produces:\n\n- CRUD endpoints (list, get, create, update, delete)\n- Batch operations\n- Views\n- Actions (including standalone actions)\n- Auth routes (`/api/auth/**`)\n- Storage, embeddings, and webhook routes (when configured)\n\nEach endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.\n\n### Schema fidelity\n\nThe generated component schemas carry enough type information that strict validators (zod, openapi-typescript, openapi-fetch) produce non-optional, narrowed types out of the box:\n\n- **`required[]` on response components** — every selected column is listed; nullable columns are present as `T | null`, not optional.\n- **Logical q types survive database lowering** — `q.bool()` remains `boolean`, `q.timestamp()` remains an ISO date-time string, and `q.url()` retains its URI format even when D1 stores the value as text or integer.\n- **Closed enums on `text(_, { enum: [...] })` columns** — emitted as `{ type: \"string\", enum: [...] }`, narrowing to a literal union in TS.\n- **`Error.code` is a closed enum** — every `code` value the API can emit (`AUTH_MISSING`, `DB_UNIQUE_VIOLATION`, `BATCH_SIZE_EXCEEDED`, …) is enumerated so consumers can `switch` exhaustively.\n- **ID `format`** — only emitted as `format: \"uuid\"` when your project's `generateId` actually produces UUIDs. cuid2 / prefixed / nanoid / serial generators get plain `{ type: \"string\" }`, keeping strict OpenAPI validators happy.\n\n### Action input and output schemas\n\nActions defined with [`defineAction({ input, output })`](/compiler/definitions/actions) get both Zod schemas lifted into the operation. `GET` inputs become typed query parameters; other methods use a JSON request body. A declared `output` becomes the success response schema and the generated helper requires `execute` to return a compatible value.\n\nThe CLI evaluates only the schema declarations in an isolated local bundle and converts them with Zod 4's `z.toJSONSchema()`. It never invokes `execute`, and the hosted compiler only receives plain JSON Schema data. Discriminated unions, refinements, recursive schemas, and shared schema references therefore flow to OpenAPI and generated TypeScript without relying on the compiler's static fallback parser.\n\n## Configuration\n\nBoth generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:\n\n```typescript\nexport default defineConfig({\n name: \"my-app\",\n // ...\n openapi: {\n generate: true, // write openapi.json to project root\n publish: true, // serve GET /openapi.json at runtime\n },\n});\n```\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `generate` | `true` | Write `openapi.json` to the project root during compilation |\n| `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |\n| `docs` | `false` | Mount an interactive API browser at `GET /docs` — `\"scalar\"`, `\"swagger\"`, or `false` |\n\nOmitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.\n\n### Generate only (no runtime route)\n\n```typescript\nopenapi: {\n generate: true,\n publish: false,\n}\n```\n\nThe file is still written so you can use it in CI or commit it to your repo, but no route is added to the app.\n\n### Disable entirely\n\n```typescript\nopenapi: {\n generate: false,\n}\n```\n\nNo file is written and no route is served.\n\n### Interactive API browser at `/docs`\n\nMount an in-browser API reference by setting `openapi.docs`:\n\n```typescript\nopenapi: {\n docs: 'scalar', // or 'swagger'\n}\n```\n\n| Value | UI | Notes |\n|---|---|---|\n| `\"scalar\"` | [Scalar API Reference](https://scalar.com/) — modern, lightweight | Recommended default |\n| `\"swagger\"` | [Swagger UI](https://swagger.io/tools/swagger-ui/) — the familiar standard | Good if your team expects it |\n| `false` / unset | No `/docs` route | Default |\n\nBoth UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.\n\nRequires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.\n\n## Usage with tools\n\n### Import into Postman\n\n1. Open Postman and click **Import**\n2. Paste the URL `https://your-api.example.com/openapi.json` or upload the file\n3. Postman creates a collection with every endpoint pre-configured\n\n### Generated TypeScript types (`api-types.gen.ts`)\n\nThe compiler emits `api-types.gen.ts` next to `openapi.json` by default — a fully typed view of every route, request body, and response, ready to import in client code:\n\n```typescript\nimport type { paths, components } from '../api-types.gen';\n\ntype Job = components['schemas']['Job'];\ntype ListJobsResponse = paths['/api/v1/jobs']['get']['responses']['200']['content']['application/json'];\n```\n\nPair it with [`openapi-fetch`](https://github.com/openapi-ts/openapi-typescript/tree/main/packages/openapi-fetch) for a fully typed client:\n\n```typescript\nimport createClient from 'openapi-fetch';\nimport type { paths } from '../api-types.gen';\n\nconst client = createClient<paths>({ baseUrl: 'https://your-api.example.com' });\nconst { data, error } = await client.GET('/api/v1/jobs', { params: { query: { limit: 25 } } });\n```\n\n#### Configuration\n\n| `openapi.types` | Behavior |\n|---|---|\n| `true` (default) | Write `api-types.gen.ts` to the project root |\n| `false` | Don't emit the types file |\n| `\"src/lib/api-types.ts\"` | Custom output path (relative to project root) |\n| `[\"api-types.gen.ts\", \"apps/web/src/lib/api-types.gen.ts\"]` | Write the same generated types to multiple paths in one compile |\n\n```typescript\n// quickback.config.ts\nexport default defineConfig({\n // ...\n openapi: {\n types: ['api-types.gen.ts', 'apps/web/src/lib/api-types.gen.ts'],\n },\n});\n```\n\nThe file is generated by piping the in-memory spec through [openapi-typescript](https://github.com/openapi-ts/openapi-typescript) — you can keep running it manually if you want a different output path or version, but for the typical case there's nothing to wire up. If your API project and SPA live in the same repo, prefer multiple `openapi.types` outputs over a second manual `codegen:api` step so one `quickback compile` keeps both copies in sync. Skipped automatically when `openapi.generate` is `false`.\n\nFor application code, prefer the compact first-party [`quickback.gen.ts` type tree](/compiler/targets/hono-api/using-the-api/typescript). Keep `api-types.gen.ts` for `openapi-fetch` and third-party OpenAPI tooling.\n\n### External viewer\n\nPoint any OpenAPI-compatible viewer at the endpoint:\n\n```\nhttps://petstore.swagger.io/?url=https://your-api.example.com/openapi.json\n```\n\nOr enable the in-project browser via the [`docs` config option](#interactive-api-browser-at-docs) above and visit `/docs` directly.\n\n## Example output (excerpt)\n\n```json\n{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"my-app API\",\n \"version\": \"1.0.0\"\n },\n \"paths\": {\n \"/api/v1/jobs\": {\n \"get\": {\n \"summary\": \"List jobs\",\n \"operationId\": \"listJobs\",\n \"parameters\": [\n { \"name\": \"limit\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } },\n { \"name\": \"offset\", \"in\": \"query\", \"schema\": { \"type\": \"integer\" } }\n ],\n \"responses\": {\n \"200\": {\n \"description\": \"Success\",\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"data\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/components/schemas/Job\" } }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n```\n\n## Operations manifest\n\nAlongside the spec, every compile writes `reports/operations.manifest.json` — a\nstable, machine-readable index of the full route surface (resource, action,\nview, and auth routes; since v0.47 also the realtime, storage, and FGA\nsurfaces):\n\n```json\n[\n { \"operationId\": \"listCustomers\", \"method\": \"GET\", \"path\": \"/api/v1/customers\", \"auth\": \"session\", \"feature\": \"customers\", \"kind\": \"crud\" }\n]\n```\n\nThe manifest is a public contract: entries are sorted by `operationId`, carry\nno timestamps, and the shape is extend-only — new fields may be added, existing\nones won't change meaning. `operationId`s are stable across compiles for the\nsame configuration, which makes the manifest the recommended integration point\nfor agent/MCP tooling, route inventories, and diff-based change review.\n\nA sibling artifact, `reports/conformance.manifest.json`, enumerates the\nexpected authorization outcome for every route × principal class (derived from\nthe same compiler model that emits the enforcement code). The compiler's own CI\nexecutes it against a running build on every change."
|
|
271
271
|
},
|
|
272
272
|
"compiler/targets/hono-api/using-the-api/query-params": {
|
|
273
273
|
"title": "Query Parameters",
|
|
274
274
|
"content": "The generated API supports filtering, pagination, sorting, field selection, search, and total count via query parameters on `GET` list endpoints.\n\n## Filter Operators\n\n| Operator | Query Param | SQL Equivalent |\n|----------|-------------|----------------|\n| Equals | `?field=value` | `WHERE field = value` |\n| Not equals | `?field.ne=value` | `WHERE field != value` |\n| Greater than | `?field.gt=value` | `WHERE field > value` |\n| Greater or equal | `?field.gte=value` | `WHERE field >= value` |\n| Less than | `?field.lt=value` | `WHERE field < value` |\n| Less or equal | `?field.lte=value` | `WHERE field <= value` |\n| Pattern match | `?field.like=value` | `WHERE field LIKE '%value%'` |\n| In list | `?field.in=a,b,c` | `WHERE field IN ('a','b','c')` |\n\n### Examples\n\n```bash\n# Filter by status\nGET /api/v1/jobs?status=open\n\n# Range query\nGET /api/v1/jobs?salaryMin.gte=100000&salaryMax.lte=200000\n\n# Pattern matching\nGET /api/v1/jobs?title.like=Engineer\n\n# Multiple values\nGET /api/v1/jobs?department.in=Engineering,Design,Product\n```\n\n## Pagination\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `limit` | `50` | Number of records to return (min: 1, max: 100) |\n| `offset` | `0` | Number of records to skip |\n\n```bash\nGET /api/v1/jobs?limit=25&offset=50\n```\n\nThe default `limit` can be configured per-resource in your `read` definition:\n\n```typescript\nread: {\n access: { roles: [\"recruiter\"] },\n pageSize: 25, // Default limit\n maxPageSize: 100, // Maximum allowed limit\n},\n```\n\n### Response Shape\n\n```json\n{\n \"data\": [ /* records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 50,\n \"count\": 12\n }\n}\n```\n\n- `count` — number of records returned on this page\n- `total` — total matching records across all pages (only when `?total=true`, see below)\n\n## Sorting\n\nSort by one or more fields. Use the `-` prefix for descending order.\n\n### Multi-Sort (Recommended)\n\n```bash\n# Sort by status ascending, then createdAt descending\nGET /api/v1/jobs?sort=status,-createdAt\n\n# Single field descending\nGET /api/v1/jobs?sort=-createdAt\n\n# Multiple fields\nGET /api/v1/jobs?sort=department,-salaryMax,title\n```\n\n| Prefix | Direction |\n|--------|-----------|\n| (none) | Ascending |\n| `-` | Descending |\n\n### Legacy Format\n\nThe original `sort` + `order` format is still supported for backwards compatibility:\n\n```bash\nGET /api/v1/jobs?sort=title&order=asc\n```\n\n| Parameter | Values | Default | Description |\n|-----------|--------|---------|-------------|\n| `sort` | Any column name | `createdAt` | Field to sort by |\n| `order` | `asc`, `desc` | `desc` | Sort direction |\n\nWhen the multi-sort format is detected (comma or `-` prefix), the `order` parameter is ignored.\n\n## Field Selection\n\nSelect which columns to return using `?fields=`. Available on LIST and GET routes (not Views — they define their own field set).\n\n```bash\n# Return only id, title, and status\nGET /api/v1/jobs?fields=id,title,status\n\n# Combine with other query params\nGET /api/v1/jobs?fields=id,title,status&status=open&sort=-createdAt\n\n# Single record\nGET /api/v1/jobs/job_123?fields=id,title,salaryMin,salaryMax\n```\n\nAll columns are available including system columns (`id`, `organizationId`, `createdAt`, `modifiedAt`, etc.). Invalid field names are silently ignored. If no valid fields are provided, all columns are returned.\n\n**Security**: Masking still applies to selected fields. Requesting `?fields=ssn` will return the masked value, not the raw data.\n\n## Total Count\n\nGet the total number of matching records across all pages by adding `?total=true`. Available on LIST and VIEW routes.\n\n```bash\nGET /api/v1/jobs?status=open&total=true\n```\n\n```json\n{\n \"data\": [ /* 25 records */ ],\n \"pagination\": {\n \"limit\": 25,\n \"offset\": 0,\n \"count\": 25,\n \"total\": 142\n }\n}\n```\n\nThis is opt-in because it runs an additional `COUNT(*)` query. Only use it when you need the total (e.g., for pagination UI).\n\n## Search\n\nFull-text search across all text columns using `?search=`. Available on LIST and VIEW routes.\n\n```bash\n# Search across all text fields\nGET /api/v1/jobs?search=engineer\n\n# Combine with filters\nGET /api/v1/jobs?search=engineer&status=open\n```\n\nThe search generates an OR'd `LIKE` condition across all `text()` columns in your schema:\n\n```sql\nWHERE (title LIKE '%engineer%' OR department LIKE '%engineer%')\n```\n\nOnly columns defined with `text()` in your Drizzle schema are searchable. Non-text columns (integers, timestamps, UUIDs, blobs) are automatically excluded.\n\n## Complete Example\n\nCombine all query parameters together:\n\n```bash\nGET /api/v1/jobs?fields=id,title,status,salaryMin&status=open&salaryMin.gte=100000&search=engineer&sort=salaryMin,-createdAt&limit=10&offset=20&total=true\n```\n\nThis request:\n1. **Selects** only `id`, `title`, `status`, `salaryMin` fields\n2. **Filters** to open jobs with salaryMin >= 100000\n3. **Searches** text columns for \"engineer\"\n4. **Sorts** by salaryMin ascending, then createdAt descending\n5. **Paginates** with 10 results starting at offset 20\n6. **Counts** total matching records\n\n## Parameter Summary\n\n| Parameter | Applies To | Description |\n|-----------|-----------|-------------|\n| `limit` | LIST, VIEW | Page size (default: 50, max: 100) |\n| `offset` | LIST, VIEW | Skip N records |\n| `sort` | LIST, VIEW | Sort fields (comma-separated, `-` prefix for desc) |\n| `order` | LIST, VIEW | Legacy sort direction (`asc` or `desc`) |\n| `fields` | LIST, GET | Comma-separated column names to return |\n| `total` | LIST, VIEW | Set to `true` to include total count |\n| `search` | LIST, VIEW | Search text across all text columns |\n| `field=value` | LIST, VIEW | Filter by exact match |\n| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |\n| `starting_after` | LIST, VIEW | Opaque keyset cursor — rows strictly after the boundary |\n| `ending_before` | LIST, VIEW | Opaque keyset cursor — rows strictly before the boundary |\n| `include` | LIST, VIEW, GET | FK-graph embedding (contract v2, allowlisted — see below) |\n| `fields[<fk>]` | LIST, VIEW, GET | Sparse fields for an embedded include target (contract v2) |\n\n## Include & Sparse Fields (contract v2)\n\nOn the v2 contract a resource can allowlist FK columns for **FK-graph\nembedding**, collapsing client-side N+1 fetches:\n\n```ts title=\"quickback/features/orders/order-items.ts\"\nexport default feature(\"orderItems\", {\n columns: {\n id: q.id(),\n orderId: q.text().required().references(() => orders.id),\n organizationId: q.scope(\"organization\"),\n },\n read: {\n access: { roles: [\"member\", \"admin\"] },\n include: [\"orderId\"], // FK columns eligible for ?include=\n },\n});\n```\n\n```bash\nGET /api/v2/order-items?include=orderId&fields[orderId]=id,total\n```\n\n```json\n{\n \"data\": [ { \"id\": \"oi_1\", \"orderId\": \"ord_9\" } ],\n \"included\": { \"orderId\": { \"ord_9\": { \"id\": \"ord_9\", \"total\": 129 } } }\n}\n```\n\nEmbedded rows land in a **top-level `included` map** keyed by FK column, then\nby target primary key — row objects are never mutated.\n\n**Security semantics (all enforced, fail-closed):**\n\n- An embedded read **is a read of the target resource**: the target's own\n `read.access` is checked before any fetch (403 on failure, never silent\n omission), the child query runs under the target's tenant firewall on the\n caller's own database handle, and embedded rows pass through the target's\n masking before attachment.\n- Targets whose `read.access` is **record-aware** (function access, `record:`\n conditions, `relationship` or `fga` arms) are refused **at compile time** —\n embedding them would skip their post-fetch record checks.\n- A tenant-scoped target with no resolvable firewall clause is a compile\n error; a global reference table must opt out explicitly with\n `firewall: { exception: true }`. Even then, the child fetch still calls\n the target's own firewall helper — for a soft-deleting reference table\n that helper is the soft-delete predicate, so an embed never serves rows\n the target's own routes refuse.\n- `?include=` on a resource (or view) without an allowlist is a **400**.\n Explicit views declare their own `include: [...]` — nothing is expandable\n undeclared. Depth is exactly 1. A view that declares `include` must keep\n each listed FK column in its `fields` projection (compile error\n otherwise — the embedded lookup pivots on that column).\n\n**Strict fields on v2:** unknown names in bare `?fields=` and in\n`fields[<fk>]=` are rejected with a 400 Problem. (Pinned v1 keeps its\nhistorical silent-drop for bare `?fields=`.) A `?fields=` projection that\ndrops the FK column of a requested `?include=` is also a **400** —\n`include=orderId requires \"orderId\" in ?fields=` — never a silently-empty\n`included` slot."
|
|
275
275
|
},
|
|
276
|
+
"compiler/targets/hono-api/using-the-api/typescript": {
|
|
277
|
+
"title": "TypeScript Type Tree",
|
|
278
|
+
"content": "Every compile emits `quickback.gen.ts`: a compact, type-only tree designed for application code. It is generated directly from the same compiler model that drives routes and OpenAPI, so there is no runtime package and no code to initialize.\n\n```typescript\nimport type { Api, Qb } from \"../quickback.gen\";\n\ntype Application = Api.applications.Row;\ntype NewApplication = Api.applications.Insert;\ntype ApplicationPatch = Api.applications.Update;\ntype ApplicationId = Api.applications.Id;\n\ntype AdvanceInput = Api.applications.actions.advance.Input;\ntype AdvanceOutput = Api.applications.actions.advance.Output;\ntype PipelineItem = Api.applications.views.pipeline.Item;\ntype PipelineResponse = Api.applications.views.pipeline.Response;\n\ntype Page = Qb.Page<Application>;\ntype ApiProblem = Qb.Problem;\n```\n\nFeature areas preserve their authored hierarchy:\n\n```typescript\ntype Booking = Api.events.travel.bookings.Row;\n```\n\n## Table types\n\nEach resource table exposes:\n\n| Member | Meaning |\n|---|---|\n| `Id` | Nominal table-specific primary-key type |\n| `Row` | Complete selected wire shape |\n| `Insert` | Createable fields, with defaults and nullable fields optional |\n| `Update` | Updatable fields, all optional |\n| `ListResponse` | `Qb.Page<Row>` |\n| `columns.<name>` | Type of one row column |\n| `views.<name>.Item` | A view's projected row |\n| `views.<name>.Response` | Page plus typed aggregations where declared |\n| `actions.<name>.Input` | The action's Zod input contract |\n| `actions.<name>.Output` | The declared Zod output contract, or `unknown` |\n\nPrimary 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.\n\n```typescript\nfunction loadJob(id: Api.jobs.Id) {}\n\ndeclare const candidateId: Api.candidates.Id;\nloadJob(candidateId); // TypeScript error\n```\n\nAt an untyped boundary, validate the value and cast it once:\n\n```typescript\nconst jobId = routeParams.id as Api.jobs.Id;\n```\n\n## Reading collections\n\nList and view responses share one envelope: rows under `data`, pagination\nmetadata under `pagination`, and `view` naming the projection behind the\nresponse (`null` for the default collection read).\n\n```typescript\ndeclare const res: Api.applications.ListResponse; // Qb.Page<Api.applications.Row>\n\nres.data; // Api.applications.Row[]\nres.view; // string | null\nres.pagination.count; // rows in this page\nres.pagination.hasMore;\nres.pagination.nextCursor; // pass back as ?starting_after=\nres.pagination.total; // number | undefined — only when ?total=true\n```\n\n`total` and `totalPages` are counted only when the request passes\n`?total=true`, so both are optional; every other member is always present. A\nview that declares aggregations intersects this shape with a typed\n`aggregations` object, and an aggregate-only view returns `{ view,\naggregations }` with no rows or pagination.\n\n## Declaring action outputs\n\nAdd an optional `output` Zod schema to make an action end-to-end typed:\n\n```typescript\nexport default defineAction({\n description: \"Advance an application\",\n input: z.object({\n nextStatus: z.enum([\"screening\", \"interview\", \"offer\"]),\n }),\n output: z.object({\n id: z.string(),\n status: z.enum([\"screening\", \"interview\", \"offer\"]),\n }),\n access: { roles: [\"recruiter+\"] },\n async execute({ record, input }) {\n return { id: record.id, status: input.nextStatus };\n },\n});\n```\n\nThe generated feature helper checks `execute` against the declared output. The CLI harvests both schemas locally without invoking `execute`; the resulting contract feeds `quickback.gen.ts`, OpenAPI, and `api-types.gen.ts`.\n\n## Configuration\n\nThe artifact is on by default:\n\n```typescript\nexport default defineConfig({\n // Default: quickback.gen.ts\n types: true,\n});\n```\n\nUse a custom path, fan out identical copies to colocated apps, disable branding, or turn the artifact off:\n\n```typescript\nexport default defineConfig({\n types: {\n output: [\n \"quickback.gen.ts\",\n \"apps/web/src/lib/quickback.gen.ts\",\n ],\n brandIds: true,\n },\n});\n```\n\n| `types` value | Behavior |\n|---|---|\n| `true` or omitted | Write `quickback.gen.ts` |\n| `false` | Do not emit the first-party type tree |\n| `\"src/lib/quickback.gen.ts\"` | Write to one custom path |\n| `[\"quickback.gen.ts\", \"apps/web/src/quickback.gen.ts\"]` | Fan out identical copies |\n| `{ output, brandIds: false }` | Configure paths and use structural IDs |\n\n`api-types.gen.ts` remains available through `openapi.types` for `openapi-fetch` and third-party OpenAPI tools. The two artifacts are independent: disabling OpenAPI types does not disable the first-party tree.\n\nThe compiler also emits `reports/types.parity.gen.ts` when both artifacts exist. Quickback's output-matrix CI compiles that proof separately to require mutual assignability between direct table/action types and the OpenAPI wire types; it is outside the generated application's `src/**/*` build."
|
|
279
|
+
},
|
|
276
280
|
"compiler/targets/hono-api/using-the-api/views-api": {
|
|
277
281
|
"title": "Views API",
|
|
278
282
|
"content": "Views provide named column projections that limit which fields are returned in API responses. Each view can have its own access control, and all security pillars (firewall, masking) still apply.\n\n## Endpoints\n\nNamed views are queried through a dedicated path endpoint:\n\n```\nGET /api/v1/{resource}/views/{view-name}\n```\n\nIf you set `read.defaultView`, bare `GET /api/v1/{resource}` can still resolve\nto that view. Named views themselves are addressed via `/views/{view-name}`.\n\n## Example\n\nGiven this definition (views live under [`read.views`](/compiler/definitions/read#views-under-read-views)):\n\n```typescript\nexport default defineTable(candidates, {\n read: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n },\n },\n },\n // ...\n});\n```\n\n### Request\n\n```bash\ncurl /api/v1/candidates/views/pipeline \\\n -H \"Authorization: Bearer <token>\"\n```\n\n### Response\n\n```json\n{\n \"data\": [\n { \"id\": \"cand_001\", \"name\": \"Alice Johnson\", \"source\": \"LinkedIn\" },\n { \"id\": \"cand_002\", \"name\": \"Bob Martinez\", \"source\": \"referral\" }\n ],\n \"view\": \"pipeline\",\n \"pagination\": {\n \"count\": 2,\n \"page\": 1,\n \"pageSize\": 50,\n \"hasMore\": false\n }\n}\n```\n\nOnly the fields specified in the view definition are returned. Requesting the `full` view with an `interviewer` role returns 403.\n\n## Query Parameters\n\nViews support the same query parameters as the list endpoint:\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `limit` | Number of records to return (1–100) | `50` |\n| `offset` | Number of records to skip | `0` |\n| `sort` | Field to sort by | `createdAt` |\n| `order` | Sort direction (`asc` or `desc`) | `desc` |\n| `{field}` | Filter by exact value | — |\n| `{field}.gt` | Greater than | — |\n| `{field}.gte` | Greater than or equal | — |\n| `{field}.lt` | Less than | — |\n| `{field}.lte` | Less than or equal | — |\n| `{field}.ne` | Not equal | — |\n| `{field}.like` | Pattern match (SQL LIKE) | — |\n| `{field}.in` | Match any value in comma-separated list | — |\n\n### Examples\n\n```bash\n# Paginated with sorting\nGET /api/v1/candidates/views/pipeline?limit=10&offset=0&sort=name&order=asc\n\n# With filters\nGET /api/v1/candidates/views/pipeline?source=referral&name.like=%25Johnson%25\n\n# Combined\nGET /api/v1/candidates/views/pipeline?source.in=LinkedIn,referral&sort=name&order=asc&limit=25\n```\n\n## Security\n\nAll security pillars apply to view endpoints:\n\n1. **Authentication** — Required (401 if missing)\n2. **Firewall** — Organization/user isolation applied to all results. Only records the user owns or has access to are returned.\n3. **Access** — Per-view role check. Each view can require different roles.\n4. **Masking** — Applied to all returned fields. If a masked field is in the view's field list, the masking rules still apply based on the user's role.\n\n### Access Control Per View\n\nDifferent views can require different permission levels:\n\n```typescript\nread: {\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n views: {\n // Available to all org members including interviewers\n pipeline: {\n fields: ['id', 'name', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter', 'interviewer'] },\n },\n // Restricted view with contact details\n full: {\n fields: ['id', 'name', 'email', 'phone', 'resumeUrl', 'source'],\n access: { roles: ['owner', 'hiring-manager', 'recruiter'] },\n },\n },\n}\n```\n\nAn `interviewer` requesting the `full` view receives:\n\n```json\n{\n \"error\": \"Insufficient permissions\",\n \"layer\": \"access\",\n \"code\": \"ACCESS_ROLE_REQUIRED\",\n \"details\": { \"required\": [\"hiring-manager\", \"recruiter\"], \"current\": [\"interviewer\"] }\n}\n```\n\n### Masking in Views\n\nMasking is applied after field projection. If your masking config hides `phone` from interviewers:\n\n```typescript\nmasking: {\n phone: { type: 'phone', show: { roles: ['hiring-manager', 'recruiter'] } },\n}\n```\n\nAn `interviewer` requesting a view that includes `phone` will see the masked value (e.g., `***-***-5678`), while a `recruiter` sees the full value.\n\n## See Also\n\n- [Defining Views](/compiler/definitions/views) — How to configure views in defineTable\n- [Query Parameters](/compiler/targets/hono-api/using-the-api/query-params) — Full query parameter reference\n- [Access Control](/compiler/definitions/access) — Role-based access configuration"
|
|
@@ -599,6 +603,7 @@ export const TOPIC_LIST = [
|
|
|
599
603
|
"compiler/targets/hono-api/using-the-api",
|
|
600
604
|
"compiler/targets/hono-api/using-the-api/openapi",
|
|
601
605
|
"compiler/targets/hono-api/using-the-api/query-params",
|
|
606
|
+
"compiler/targets/hono-api/using-the-api/typescript",
|
|
602
607
|
"compiler/targets/hono-api/using-the-api/views-api",
|
|
603
608
|
"compiler/targets",
|
|
604
609
|
"compiler/troubleshooting",
|
package/dist/docs/content.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/docs/content.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,0DAA0D;AAO1D,MAAM,CAAC,MAAM,IAAI,GAA6B;IAC5C,WAAW,EAAE;QACX,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,8s+RAA8s+R;KAC1t+R;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,oBAAoB;QAC7B,SAAS,EAAE,giRAAgiR;KAC5iR;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,kmEAAkmE;KAC9mE;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,gtXAAgtX;KAC5tX;IACD,gCAAgC,EAAE;QAChC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,2iKAA2iK;KACvjK;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,2jMAA2jM;KACvkM;IACD,yBAAyB,EAAE;QACzB,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,8tLAA8tL;KAC1uL;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,8xHAA8xH;KAC1yH;IACD,yCAAyC,EAAE;QACzC,OAAO,EAAE,iBAAiB;QAC1B,SAAS,EAAE,k/DAAk/D;KAC9/D;IACD,wBAAwB,EAAE;QACxB,OAAO,EAAE,oBAAoB;QAC7B,SAAS,EAAE,ggXAAggX;KAC5gX;IACD,sBAAsB,EAAE;QACtB,OAAO,EAAE,YAAY;QACrB,SAAS,EAAE,olWAAolW;KAChmW;IACD,0BAA0B,EAAE;QAC1B,OAAO,EAAE,iBAAiB;QAC1B,SAAS,EAAE,yvTAAyvT;KACrwT;IACD,yBAAyB,EAAE;QACzB,OAAO,EAAE,2BAA2B;QACpC,SAAS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IACxB,YAAY;IACZ,6BAA6B;IAC7B,+BAA+B;IAC/B,4BAA4B;IAC5B,4BAA4B;IAC5B,oBAAoB;IACpB,qBAAqB;IACrB,uBAAuB;IACvB,mBAAmB;IACnB,sBAAsB;IACtB,sBAAsB;IACtB,qBAAqB;IACrB,WAAW;IACX,0BAA0B;IAC1B,iBAAiB;IACjB,0BAA0B;IAC1B,yBAAyB;IACzB,2BAA2B;IAC3B,oBAAoB;IACpB,uBAAuB;IACvB,OAAO;IACP,YAAY;IACZ,uBAAuB;IACvB,cAAc;IACd,2BAA2B;IAC3B,gCAAgC;IAChC,gBAAgB;IAChB,2BAA2B;IAC3B,oCAAoC;IACpC,kCAAkC;IAClC,+BAA+B;IAC/B,iBAAiB;IACjB,eAAe;IACf,kBAAkB;IAClB,kBAAkB;IAClB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,+BAA+B;IAC/B,wBAAwB;IACxB,gBAAgB;IAChB,yBAAyB;CAC1B,CAAC"}
|
|
1
|
+
{"version":3,"file":"content.js","sourceRoot":"","sources":["../../src/docs/content.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,0DAA0D;AAO1D,MAAM,CAAC,MAAM,IAAI,GAA6B;IAC5C,WAAW,EAAE;QACX,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,8s+RAA8s+R;KAC1t+R;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,oBAAoB;QAC7B,SAAS,EAAE,giRAAgiR;KAC5iR;IACD,wCAAwC,EAAE;QACxC,OAAO,EAAE,gBAAgB;QACzB,SAAS,EAAE,kmEAAkmE;KAC9mE;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,eAAe;QACxB,SAAS,EAAE,gtXAAgtX;KAC5tX;IACD,gCAAgC,EAAE;QAChC,OAAO,EAAE,WAAW;QACpB,SAAS,EAAE,2iKAA2iK;KACvjK;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,WAAW;QACpB,SA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ACd,+BAA+B;IAC/B,wBAAwB;IACxB,gBAAgB;IAChB,yBAAyB;CAC1B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import pc from "picocolors";
|
|
12
12
|
// Version injected at build time by scripts/inject-version.ts
|
|
13
|
-
const CLI_VERSION = "0.58.
|
|
13
|
+
const CLI_VERSION = "0.58.3";
|
|
14
14
|
function getPackageVersion() {
|
|
15
15
|
return CLI_VERSION;
|
|
16
16
|
}
|
|
@@ -52,6 +52,7 @@ ${pc.bold("COMMANDS")}
|
|
|
52
52
|
${pc.cyan("compile")} Compile definitions via remote API
|
|
53
53
|
${pc.cyan("check")} [--watch] Typecheck the authored quickback/ tree (no compile; CI-friendly)
|
|
54
54
|
${pc.cyan("migrate")} <codemod> Authored-source codemods (visible-columns, helper-imports)
|
|
55
|
+
${pc.cyan("schema")} <subcommand> Check or synchronize managed schema columns
|
|
55
56
|
${pc.cyan("deploy")} Provision Cloudflare resources + deploy (D1/KV/R2, id sync, migrations)
|
|
56
57
|
${pc.cyan("dev")} Run wrangler dev (prints named-subdomain URLs)
|
|
57
58
|
${pc.cyan("migrations")} <subcommand> Inspect/repair drizzle migration state (try: doctor)
|
|
@@ -69,6 +70,7 @@ ${pc.bold("OPTIONS")}
|
|
|
69
70
|
${pc.cyan("-v, --version")} Show version number
|
|
70
71
|
${pc.cyan("-h, --help")} Show this help message
|
|
71
72
|
${pc.cyan("compile --verbose")} Show detailed remote compile failure output
|
|
73
|
+
${pc.cyan("compile --fix-schema")} Apply safe managed-column additions before compiling
|
|
72
74
|
|
|
73
75
|
${pc.bold("EXAMPLES")}
|
|
74
76
|
${pc.gray("# Brand new? One command in an empty folder.")}
|
|
@@ -166,7 +168,13 @@ else if (cmd === "example") {
|
|
|
166
168
|
else if (cmd === "compile") {
|
|
167
169
|
const noSyncConfig = args.includes("--no-sync-config");
|
|
168
170
|
const verbose = args.includes("--verbose") || args.includes("-v");
|
|
169
|
-
|
|
171
|
+
const fixSchema = args.includes("--fix-schema");
|
|
172
|
+
import("./commands/compile.js").then(({ compile }) => compile({ syncConfig: !noSyncConfig, verbose, fixSchema })).catch((err) => {
|
|
173
|
+
fatal(String(err?.message ?? err));
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
else if (cmd === "schema") {
|
|
177
|
+
import("./commands/schema.js").then(({ schema }) => schema(args)).catch((err) => {
|
|
170
178
|
fatal(String(err?.message ?? err));
|
|
171
179
|
});
|
|
172
180
|
}
|
|
@@ -240,8 +248,10 @@ else if (cmd === "mcp") {
|
|
|
240
248
|
fatal(String(err?.message ?? err));
|
|
241
249
|
});
|
|
242
250
|
}
|
|
243
|
-
else if (cmd === "db:generate" || cmd === "db:migrate" || cmd === "db:studio"
|
|
244
|
-
// Legacy database commands - now handled via drizzle-kit directly
|
|
251
|
+
else if (cmd === "db:generate" || cmd === "db:migrate" || cmd === "db:studio") {
|
|
252
|
+
// Legacy database commands - now handled via drizzle-kit directly.
|
|
253
|
+
// `migrate` is deliberately absent: v0.58.0 gave it a real handler
|
|
254
|
+
// (authored-source codemods) above, so listing it here was unreachable.
|
|
245
255
|
console.log(pc.yellow(`\nThe '${cmd}' command has been deprecated.`));
|
|
246
256
|
console.log(pc.gray("\nUse drizzle-kit directly in your project:\n"));
|
|
247
257
|
console.log(pc.cyan(" npx drizzle-kit generate # Generate migrations"));
|