@gallopsystems/agent-skills 1.32.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +11 -0
  2. package/package.json +1 -1
  3. package/plugins/kysely-postgres/skills/kysely-postgres/SKILL.md +17 -3
  4. package/plugins/kysely-postgres/skills/kysely-postgres/references/common-pitfalls.md +91 -0
  5. package/plugins/kysely-postgres/skills/kysely-postgres/references/concurrency-and-transactions.md +155 -0
  6. package/plugins/kysely-postgres/skills/kysely-postgres/references/full-text-and-grouping.md +13 -0
  7. package/plugins/kysely-postgres/skills/kysely-postgres/references/migrations-and-codegen.md +50 -0
  8. package/plugins/kysely-postgres/skills/kysely-postgres/references/query-patterns.md +65 -0
  9. package/plugins/kysely-postgres/skills/kysely-postgres/references/set-lateral-locking.md +2 -0
  10. package/plugins/nitro-testing/skills/nitro-testing/SKILL.md +10 -0
  11. package/plugins/nitro-testing/skills/nitro-testing/proving-the-claim.md +240 -0
  12. package/plugins/nitro-testing/skills/nitro-testing/transaction-rollback.md +1 -0
  13. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/SKILL.md +23 -12
  14. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/auth-patterns.md +50 -0
  15. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/error-handling.md +34 -3
  16. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/examples/validation-endpoint.ts +2 -2
  17. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/fetch-patterns.md +57 -0
  18. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/nitro-tasks.md +2 -0
  19. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/server-services.md +100 -1
  20. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/sse.md +1 -1
  21. package/plugins/nuxt-nitro-api/skills/nuxt-nitro-api/validation.md +120 -14
  22. package/plugins/pr-review/.claude-plugin/plugin.json +8 -0
  23. package/plugins/pr-review/skills/pr-review/SKILL.md +68 -0
  24. package/plugins/pr-review/skills/pr-review/brief-prompt.md +33 -0
  25. package/plugins/pr-review/skills/pr-review/focus-areas.md +63 -0
  26. package/plugins/pr-review/skills/pr-review/judge.md +29 -0
  27. package/plugins/vue-nuxt/skills/vue-nuxt/SKILL.md +29 -0
  28. package/plugins/vue-nuxt/skills/vue-nuxt/async-state.md +229 -0
  29. package/plugins/vue-nuxt/skills/vue-nuxt/component-authoring.md +45 -0
  30. package/plugins/vue-nuxt/skills/vue-nuxt/editing-forms.md +137 -0
  31. package/plugins/vue-nuxt/skills/vue-nuxt/formatters.md +8 -0
  32. package/plugins/vue-nuxt/skills/vue-nuxt/slots.md +16 -0
  33. package/plugins/vue-nuxt/skills/vue-nuxt/template-idioms.md +52 -0
  34. package/plugins/vue-nuxt/skills/vue-nuxt/v-model.md +2 -1
  35. package/plugins/vue-nuxt/skills/vue-nuxt/watch.md +5 -1
@@ -0,0 +1,240 @@
1
+ # Writing Tests That Prove Their Claim
2
+
3
+ The most common review finding on test files is not a broken test. It is a green test
4
+ that would **stay green if the code were wrong**: the name promises one behaviour and the
5
+ body never checks it. Each section below is one way that happens, with the rule that
6
+ prevents it. Run the [self-check](#self-check-before-you-finish) on every test you write.
7
+
8
+ ## 1. The fixture cannot tell right from wrong
9
+
10
+ **Trap:** the data makes the broken implementation produce the correct answer. A sort test
11
+ whose rows are already in order passes with no sort. A filter test where every row matches
12
+ passes with no filter. A "returns a live view" test passes for a copy if nothing changes.
13
+
14
+ **Rule:** design the fixture so the wrong implementation gives a different answer. Insert
15
+ the row the filter must exclude, insert rows in an order the sort must change, and mutate the
16
+ source after reading when the claim is "view, not copy". Fixtures must also match the real
17
+ input's shape (an already-normalised value, a masked string) or the test runs a path
18
+ production never sees. A stubbed lookup that answers for any input cannot produce the
19
+ "not found" case the test is about.
20
+
21
+ ```typescript
22
+ // ❌ Passes without the filter: every project belongs to the requested owner
23
+ test("lists only the owner's projects", async ({ factories }) => {
24
+ const owner = await factories.user();
25
+ await factories.project({ ownerId: owner.id });
26
+ const result = await handler(mockGet({ ownerId: owner.id }));
27
+ expect(result).toHaveLength(1);
28
+ });
29
+
30
+ // ✅ A project that must be filtered out, and identities, not just a count
31
+ test("lists only the owner's projects", async ({ factories }) => {
32
+ const owner = await factories.user();
33
+ const mine = await factories.project({ ownerId: owner.id });
34
+ await factories.project(); // another owner: must not appear
35
+ const result = await handler(mockGet({ ownerId: owner.id }));
36
+ expect(result.map((p) => p.id)).toEqual([mine.id]);
37
+ });
38
+
39
+ // ✅ Sort: insert in the reverse of the expected order
40
+ const b = await factories.task({ name: "B", dueOn: "2025-03-02" });
41
+ const a = await factories.task({ name: "A", dueOn: "2025-03-01" });
42
+ expect((await handler(mockGet({}))).map((t) => t.id)).toEqual([a.id, b.id]);
43
+ ```
44
+
45
+ ## 2. The test never reaches the branch it names
46
+
47
+ **Trap:** "pads short rows" builds only full rows; "falls back to the query when the cache
48
+ misses" tests only the pure builder; "persists on update" calls the create path; a stub
49
+ returns early so the code under test never runs and the assertions inside a callback never
50
+ execute.
51
+
52
+ **Rule:** build the exact input the name describes and call the exact entry point. Drive a
53
+ component through its real model (`v-model` / emitted events), not by setting internal
54
+ state. When assertions live in a callback or a loop that might run zero times, pin the count:
55
+
56
+ ```typescript
57
+ test("notifies each assignee", async ({ factories }) => {
58
+ expect.assertions(3); // fails unless the callback ran exactly twice
59
+ const [u1, u2] = [await factories.user(), await factories.user()];
60
+ const task = await factories.task({ assigneeIds: [u1.id, u2.id] });
61
+ const notified: number[] = [];
62
+ await notifyAssignees(task.id, (msg) => {
63
+ expect(msg.taskId).toBe(task.id);
64
+ notified.push(msg.userId);
65
+ });
66
+ expect(notified.sort()).toEqual([u1.id, u2.id].sort()); // each assignee, not one twice
67
+ });
68
+ ```
69
+
70
+ `expect.hasAssertions()` is the weaker form (at least one).
71
+
72
+ ## 3. The assertion is narrower than the name
73
+
74
+ **Trap:** the title says "totals every column", the body checks two; the case names three
75
+ controls, the body checks one; "keeps the count" asserts the card renders but not the
76
+ number; "shows a separate Retry button" asserts the old button is gone, not that the new one
77
+ exists; "signs in as the user" asserts `ok: true` but not *which* user.
78
+
79
+ **Rule:** every noun in the test name maps to an assertion. Assert concrete values (the
80
+ number, the id, the visible error text), **presence and absence** both, and the identity
81
+ fields in anything auth-related. If the body cannot cover the name, split the test or rename
82
+ it. A whole-object `toEqual` / `toMatchObject` is often the cheapest way to cover "every
83
+ field".
84
+
85
+ ```typescript
86
+ // ❌ Passes if the button is missing entirely
87
+ expect(wrapper.find("[data-test=submit]").exists()).toBe(false);
88
+
89
+ // ✅ The claim is "replaced by Retry": both halves
90
+ expect(wrapper.find("[data-test=submit]").exists()).toBe(false);
91
+ expect(wrapper.get("[data-test=retry]").text()).toBe("Retry");
92
+ ```
93
+
94
+ ## 4. The assertion passes for the wrong reason
95
+
96
+ **Trap:** `rejects.toThrow()` passes for a crash, a typo, or a 500; a broad selector matches
97
+ a stray element; the test asserts on the object it built *before* the action, so a handler
98
+ that never wrote anything still passes.
99
+
100
+ **Rule:**
101
+ - In rejection tests, assert the status (and message where it is the contract):
102
+ `await expectHttpError(handler(event), { statusCode: 400 })`. In a loop over bad inputs,
103
+ every iteration asserts the status.
104
+ - Select by the exact attribute the claim concerns and assert the **count**
105
+ (`findAll(...)` then `toHaveLength(n)`), not "some element matched".
106
+ - After a write, **re-read from the `db` fixture**. Status codes and return values are not
107
+ persisted state.
108
+
109
+ ```typescript
110
+ // ❌ `task` is the pre-action object: this can never fail
111
+ await handler(mockPatch({ id: task.id }, { status: "done" }));
112
+ expect(task.status).toBeDefined();
113
+
114
+ // ✅ Re-read what the handler persisted
115
+ const saved = await db.selectFrom("task").where("id", "=", task.id)
116
+ .select("status").executeTakeFirstOrThrow();
117
+ expect(saved.status).toBe("done");
118
+ ```
119
+
120
+ PostgreSQL trap of the same kind: `has_table_privilege(role, table, 'SELECT, INSERT')` is
121
+ true if **any** listed privilege is held. Check each required privilege separately.
122
+
123
+ ## 5. The fake ignores what it is given
124
+
125
+ **Trap:** a fake HTTP API that answers without looking at the `authorization` header; a
126
+ mocked query layer that returns the same rows whatever the filter; a mock router that sends
127
+ an outer query to the subquery's fixture; a stub child component that renders no element, so
128
+ selector assertions never match anything.
129
+
130
+ **Rule:** a fake must **reject** the input the real thing would reject, or the test must
131
+ assert what the fake received (`expect(fetchMock).toHaveBeenCalledWith(...)`, the bound
132
+ query parameters). Route mock fixtures by the outer/most specific match first. Stubs that
133
+ the test queries must render a real element (see frontend gotcha
134
+ [Reading or driving a stubbed child](./frontend-testing.md#7-reading-or-driving-a-stubbed-child-needs-an-explicit-stub)).
135
+ Prefer the real database over a mocked query layer: that is what the harness is for.
136
+
137
+ ## 6. Several expected failures in one transaction
138
+
139
+ **Trap:** the test asserts "INSERT is refused, UPDATE is refused, DELETE is refused" in one
140
+ body. In PostgreSQL, the first error aborts the transaction; every later statement fails with
141
+ `current transaction is aborted, commands ignored until end of transaction block` (SQLSTATE
142
+ `25P02`). The later checks "pass" for that reason, not for the reason claimed. In this
143
+ harness the whole test is one transaction, and nested `db.transaction()` calls reuse it (see
144
+ [transaction-rollback.md](./transaction-rollback.md#handling-nested-transactions)), so they
145
+ do not isolate anything either.
146
+
147
+ **Rule:** one expected database failure per test, so each gets its own transaction.
148
+ `test.for` keeps it short and, unlike `test.each`, passes the test context (and so the
149
+ fixtures) as its second argument:
150
+
151
+ ```typescript
152
+ test.for([
153
+ ["a negative quantity", { quantity: -1 }, "23514"], // check_violation
154
+ ["a missing product", { productId: null }, "23502"], // not_null_violation
155
+ ] as const)("refuses %s", async ([, override, code], { factories }) => {
156
+ await expect(factories.orderItem(override)).rejects.toMatchObject({ code });
157
+ });
158
+ ```
159
+
160
+ Assert the SQLSTATE `code` (or the constraint name), not just "it threw" (section 4).
161
+
162
+ ## 7. Other rows, other tests, other mounts
163
+
164
+ **Trap:** a "returns the newest" test with `limit 1` that a seeded or earlier row in the same
165
+ transaction can win; an audit assertion that matches a row written by setup, not by the
166
+ action; teleported dialog content (or an `attachTo: document.body` mount) from one test still
167
+ in `document.body` when the next test queries it.
168
+
169
+ **Rule:**
170
+ - Scope every query in an assertion to the records this test created (by id, or by a
171
+ parent id the test owns). Do not assume the table is empty: seeds and setup rows exist.
172
+ When the query has a time window, make the fixture sit clearly inside or outside it.
173
+ - Unmount in `afterEach`, so a failing assertion cannot leak nodes into later tests, and
174
+ query teleported content through a scoped root, not the whole `document.body`:
175
+
176
+ ```typescript
177
+ let wrapper: VueWrapper | undefined; // from @vue/test-utils
178
+ afterEach(() => wrapper?.unmount());
179
+
180
+ it("opens the filter panel", async () => {
181
+ wrapper = await mountSuspended(ProjectFilters);
182
+ // ...
183
+ });
184
+ ```
185
+
186
+ ## 8. Time and concurrency
187
+
188
+ **Trap:** hard-coded "future" dates that become past dates next year; a lock test that
189
+ "proves" a wait by checking the second query is still pending after 200 ms, which passes on a
190
+ slow host without any lock.
191
+
192
+ **Rule:** pin the clock for anything that compares with today. Fake only `Date` in tests that
193
+ touch the database, so driver timeouts keep working:
194
+
195
+ ```typescript
196
+ beforeEach(() => {
197
+ vi.useFakeTimers({ toFake: ["Date"], now: new Date("2025-06-15T12:00:00Z") });
198
+ });
199
+ afterEach(() => vi.useRealTimers());
200
+ ```
201
+
202
+ The JS clock does not move PostgreSQL: `now()` comes from the server and, inside this
203
+ harness, is fixed at the start of the test's transaction. When SQL compares with `now()`,
204
+ build fixture dates relative to it, or pass the date in as a parameter.
205
+
206
+ For waits and locks, observe the state directly (from another connection, the blocked
207
+ backend shows `wait_event_type = 'Lock'` in `pg_stat_activity`) instead of inferring it
208
+ from a timeout.
209
+
210
+ ## 9. The test never runs, or never compiles
211
+
212
+ **Trap:** a new test file that no declared test command includes, or that reads an env var
213
+ the command does not set, so CI skips it silently; a module-level `db` connection that fails
214
+ (or forces the env var) when the suite is meant to be skipped; fixtures that pass a value
215
+ the factory's type union no longer allows, or a column a migration dropped.
216
+
217
+ **Rule:** check that the file matches an `include` glob of a command CI runs, with the env
218
+ var that command sets. Open connections in `beforeAll`, not at module top level (top-level
219
+ code runs when the file is collected, even if every test is skipped). Run `typecheck` on test
220
+ files, and update tests in the same change as the migration or type they depend on.
221
+
222
+ Test helpers that catch errors (cleanup, an expected exit code) must catch only the expected
223
+ one and rethrow the rest, and clean up in `finally` when the state lives outside the test
224
+ transaction.
225
+
226
+ ## Self-check before you finish
227
+
228
+ For each test, answer these. A "no" means the test does not yet prove its name.
229
+
230
+ 1. **Would it fail if I deleted the line under test** (the filter, the sort, the write, the
231
+ permission check)? If you are unsure, revert it and run the test once.
232
+ 2. Does the fixture contain the case that the wrong implementation gets wrong (the excluded
233
+ row, the out-of-order row, the missing row)?
234
+ 3. Does every noun in the test name have an assertion, including both presence and absence?
235
+ 4. After a write, did I re-read the database rather than trust the response or the
236
+ pre-action object?
237
+ 5. Do rejection tests assert the status or error code, and does each expected database
238
+ failure have its own test?
239
+ 6. Can another row, test, or mount satisfy the assertion? Is it time- or speed-dependent?
240
+ 7. Does a command CI actually runs include this file, and does it typecheck?
@@ -163,6 +163,7 @@ describe("POST /api/orders", () => {
163
163
  3. **Nested transactions work** - Thanks to prototype patching
164
164
  4. **No cleanup needed** - Rollback happens automatically
165
165
  5. **Tests are isolated** - Can't affect each other
166
+ 6. **One expected DB error per test** - The first error aborts the whole test transaction, and the nested-transaction patch adds no savepoint, so later statements fail for that reason. See [proving-the-claim.md](./proving-the-claim.md#6-several-expected-failures-in-one-transaction)
166
167
 
167
168
  ## Gotcha: Unused Factories
168
169
 
@@ -26,10 +26,10 @@ Use this skill when:
26
26
 
27
27
  For detailed patterns, see these topic-focused reference files:
28
28
 
29
- - [validation.md](./validation.md) - Zod validation with h3, Standard Schema, error handling
30
- - [fetch-patterns.md](./fetch-patterns.md) - useFetch vs $fetch vs useAsyncData, refreshNuxtData
31
- - [auth-patterns.md](./auth-patterns.md) - nuxt-auth-utils, OAuth, WebAuthn, middleware
32
- - [error-handling.md](./error-handling.md) - createError (fatal), error.vue, clearError, NuxtErrorBoundary
29
+ - [validation.md](./validation.md) - Zod validation with h3 (`schema.parse`), blank strings, dates, strict objects, PATCH semantics
30
+ - [fetch-patterns.md](./fetch-patterns.md) - useFetch vs $fetch vs useAsyncData, refreshNuxtData, error/status semantics
31
+ - [auth-patterns.md](./auth-patterns.md) - nuxt-auth-utils, OAuth, WebAuthn, middleware, per-resource authorization
32
+ - [error-handling.md](./error-handling.md) - createError (fatal, server fields), error.vue, clearError, NuxtErrorBoundary
33
33
  - [state-management.md](./state-management.md) - useState (never a module-scope ref), clearNuxtState, callOnce
34
34
  - [composables-utils.md](./composables-utils.md) - composables vs utils, runtimeConfig public/private, runWithContext
35
35
  - [ssr-client.md](./ssr-client.md) - SSR + localStorage, hydration, useRequestURL/Headers, useCookie, VueUse
@@ -41,7 +41,7 @@ For detailed patterns, see these topic-focused reference files:
41
41
  - [layers.md](./layers.md) - sharing components/composables/config across repos via extends
42
42
  - [nitro-tasks.md](./nitro-tasks.md) - Background jobs, scheduled tasks, job queues
43
43
  - [sse.md](./sse.md) - Server-Sent Events for real-time streaming
44
- - [server-services.md](./server-services.md) - Third-party service integration patterns
44
+ - [server-services.md](./server-services.md) - Third-party services: failure classification, timeouts, side-effect ordering
45
45
 
46
46
  ## Example Files
47
47
 
@@ -57,7 +57,7 @@ Working examples from a Nuxt project:
57
57
  ## Core Principles
58
58
 
59
59
  1. **Let Nitro infer types** - Never add manual type params to `$fetch<Type>()` or `useFetch<Type>()`
60
- 2. **Use h3 validation** - `getValidatedQuery()`, `readValidatedBody()` with Zod schemas
60
+ 2. **Use h3 validation** - `getValidatedQuery(event, schema.parse)`, `readValidatedBody(event, schema.parse)`; never raw `readBody` + destructure
61
61
  3. **Composables for context, utils for pure functions** - Composables access Nuxt context, utils are pure
62
62
  4. **SSR-safe code** - Guard browser APIs with `import.meta.client` or `onMounted`
63
63
  5. **Keep pages thin** - Pages = layout + route params + components. Components own data fetching and logic. (Page composition + display formatting now live in the `vue-nuxt` skill.)
@@ -94,21 +94,24 @@ Code auto-imported on both client AND server. Use for:
94
94
 
95
95
  ## Quick Patterns
96
96
 
97
- ### Validation (h3 v2+ with Standard Schema)
97
+ ### Validation (h3 v1: pass `schema.parse`)
98
98
 
99
99
  ```typescript
100
- // Pass Zod schema directly (h3 v2+)
100
+ // Nuxt 4 ships h3 v1: the validator is a FUNCTION. A throw becomes a 400.
101
101
  const query = await getValidatedQuery(event, z.object({
102
102
  search: z.string().optional(),
103
- page: z.coerce.number().default(1),
104
- }));
103
+ page: z.coerce.number().int().positive().default(1),
104
+ }).parse);
105
105
 
106
106
  const body = await readValidatedBody(event, z.object({
107
107
  email: z.email(), // Zod 4: top-level, not z.string().email()
108
- name: z.string().min(1),
109
- }));
108
+ name: z.string().trim().min(1).max(200),
109
+ }).parse);
110
110
  ```
111
111
 
112
+ Passing the schema object itself is h3 v2 syntax (a type error here); passing
113
+ `schema.safeParse` returns the `{ success, ... }` wrapper as your data.
114
+
112
115
  ### $fetch Type Inference
113
116
 
114
117
  ```typescript
@@ -223,6 +226,14 @@ Needs Nuxt/Vue context (useRuntimeConfig, useRoute, refs)?
223
226
  11. **Never export a module-scope `ref` for shared state** - Leaks across SSR requests; use `useState`. See [state-management.md](./state-management.md).
224
227
  12. **Internal server `$fetch` doesn't forward cookies** - Pass `headers` explicitly or the callee sees no session. See [server-runtime.md](./server-runtime.md).
225
228
 
229
+ ### Traps reviewers keep finding
230
+
231
+ 13. **Validate every input, ids and route params included** - `""` coerces to `0`, a shape regex accepts `2025-02-30` (use `z.iso.date()`), `z.object` silently drops unknown keys, and unbounded strings on public routes are a DoS. See [validation.md](./validation.md#validation-traps-that-keep-shipping).
232
+ 14. **Authorize the resource, on every route and every branch** - Logged-in isn't allowed. Load the record scoped to the caller in each handler for that resource (read *and* write, every branch of an update), and check that ids in the body belong to the parent. See [auth-patterns.md](./auth-patterns.md#per-resource-authorization).
233
+ 15. **`useFetch` and `refresh()` never throw** - A failure sets `error`, resets `data` to its default and resolves. Check `error`/`status` after `await refresh()`, and never render a failed load as the empty state or a failed permission check as "denied". See [fetch-patterns.md](./fetch-patterns.md#errors-status-and-stale-data).
234
+ 16. **Don't turn a third-party failure into "empty" or "done"** - Only a not-found means absent; a per-resource 401/403 is local; a 2xx missing the expected object is a failure; give every outbound call a real timeout. See [server-services.md](./server-services.md#failures-from-third-party-calls).
235
+ 17. **Validate everything before the first side effect** - A multi-step handler that writes externally (or to the DB) and then hits a validation error leaves partial changes. See [server-services.md](./server-services.md#multi-step-operations-with-side-effects).
236
+
226
237
  ### Ambiguous Route Type Inference
227
238
 
228
239
  Nuxt generates types in `.nuxt/types/nitro-routes.d.ts` with an `InternalApi` object keyed by route paths. When routes overlap, Nuxt can't infer types from template literals:
@@ -185,6 +185,56 @@ export async function requireAdmin(event: H3Event) {
185
185
  }
186
186
  ```
187
187
 
188
+ ## Per-resource authorization
189
+
190
+ Middleware and `requireRole` answer "who is this?" and "what role?". They do not
191
+ answer "may this caller touch **this** record?". Reviewers keep finding handlers
192
+ that check it on one route and not its sibling, on read but not write, or on the
193
+ obvious branch of an update but not the others.
194
+
195
+ Put the check in one helper that loads the record **scoped to the caller** and
196
+ throws, and call it first in every handler under the resource:
197
+
198
+ ```typescript
199
+ // server/utils/access.ts
200
+ export async function requireProjectAccess(event: H3Event, projectId: number) {
201
+ const user = await getAuthenticatedUser(event); // your session user must carry its tenant (here `accountId`)
202
+ const project = await useDatabase()
203
+ .selectFrom("project")
204
+ .selectAll()
205
+ .where("id", "=", projectId)
206
+ .where("account_id", "=", user.accountId) // the scope IS the check
207
+ .executeTakeFirst();
208
+ // 404, not 403, so ids of other accounts' records aren't confirmed to exist
209
+ if (!project) throw createError({ statusCode: 404, statusMessage: "Not Found" });
210
+ return { user, project };
211
+ }
212
+
213
+ // server/api/projects/[id]/archive.post.ts, and [id].get.ts, [id].patch.ts, [id]/files/*...
214
+ const { id } = await getValidatedRouterParams(event, z.object({ id: z.coerce.number().int().positive() }).parse);
215
+ const { project } = await requireProjectAccess(event, id);
216
+ ```
217
+
218
+ Rules:
219
+
220
+ - **Every endpoint on the resource**, including nested ones (`/[id]/files`,
221
+ `/[id]/export`), list endpoints (filter by the same scope) and any generic
222
+ "raw read" helper you point restricted users at.
223
+ - **Every branch of a write.** If an update can also reactivate, reassign or change
224
+ status, each branch needs the permission that action requires, not just the one
225
+ for the common edit.
226
+ - **Ids in the body belong to the parent.** `{ documentIds: [...] }` or
227
+ `{ contactId }` sent to `/api/cases/12` must be checked to belong to case 12 (or
228
+ to the caller), not merely to exist. Otherwise a caller links or edits another
229
+ tenant's rows. Re-check on every transition that makes an old reference matter.
230
+ - **Scope mutations to the kind of record they're for.** A `contacts` update must
231
+ `where` on the contact type too, so it can't change another kind of row that
232
+ shares the table.
233
+ - **Sessions outlive account changes.** A session cookie stays valid after the user
234
+ is deactivated or their role is lowered. For sensitive actions, have the shared
235
+ guard re-read the user's status/role from the database instead of trusting the
236
+ session copy.
237
+
188
238
  ## Type Extension
189
239
 
190
240
  ```typescript
@@ -1,7 +1,7 @@
1
1
  # Error Handling (client + server)
2
2
 
3
- The skill covers throwing `createError` in API handlers (see `auth-patterns.md`).
4
- This file is the **client/page** surface: triggering the error page, the
3
+ What each `createError` field does on the server is in its own section below. The
4
+ rest of this file is the **client/page** surface: triggering the error page, the
5
5
  `error.vue` root, recovering, and containing a failure to a subtree.
6
6
 
7
7
  ## `createError` — fatal vs non-fatal
@@ -13,7 +13,11 @@ handle locally:
13
13
 
14
14
  ```typescript
15
15
  // page setup — show the full-screen error page for a missing resource
16
- const { data } = await useFetch(`/api/invoices/${id}`);
16
+ const { data, error } = await useFetch(`/api/invoices/${id}`);
17
+ if (error.value) {
18
+ // keep the real status: a 500 or 403 is not "not found"
19
+ throw createError({ statusCode: error.value.statusCode ?? 500, statusMessage: error.value.statusMessage, fatal: true });
20
+ }
17
21
  if (!data.value) {
18
22
  throw createError({ statusCode: 404, statusMessage: "Invoice not found", fatal: true });
19
23
  }
@@ -22,6 +26,33 @@ if (!data.value) {
22
26
  `showError(...)` is the imperative equivalent (call it from a handler instead of
23
27
  throwing). Pass `data` on the error to carry structured detail to `error.vue`.
24
28
 
29
+ ## Server: what each `createError` field does
30
+
31
+ | Field | Goes to | Notes |
32
+ |---|---|---|
33
+ | `statusCode` | HTTP status | The client branches on it (`err.statusCode` / `err.status`). |
34
+ | `statusMessage` | the HTTP status line | h3 **strips anything outside printable ASCII**, so accents, curly quotes, dashes and emoji vanish. Keep it a short ASCII phrase. |
35
+ | `message` | JSON body `message` | Human-readable text, any characters. Read client-side as `err.data?.message`. |
36
+ | `data` | JSON body `data` | Structured detail (field errors, conflicting ranges). |
37
+
38
+ ```typescript
39
+ throw createError({
40
+ statusCode: 409,
41
+ statusMessage: "Conflict",
42
+ message: "Overlaps the booking for 3–5 March", // non-ASCII is fine here
43
+ data: { conflictingId: other.id },
44
+ });
45
+ ```
46
+
47
+ In a production build Nitro sends `message` and `data` only for handled, non-fatal
48
+ errors: a server `createError` with `fatal: true` is redacted like an unhandled one.
49
+
50
+ A plain `throw new Error(...)` (or any non-`createError` throw) is **unhandled**: the
51
+ client gets a 500 and, in a production build, `message: "Server Error"` with no `data` (the real message shows only in dev). Expected failures
52
+ (bad input, missing record, conflict, an upstream rejection) must be a
53
+ `createError` with the right status. Don't catch them and return a success-shaped
54
+ body (`{ ok: true }`, `[]`, `null`) either: the client can't tell it failed.
55
+
25
56
  ## `error.vue` — the app-root error page
26
57
 
27
58
  A single `error.vue` at the project root renders for any fatal error (and SSR
@@ -10,8 +10,8 @@ const querySchema = z.object({
10
10
  });
11
11
 
12
12
  export default defineEventHandler(async (event) => {
13
- // h3 v2+ - pass schema directly (Standard Schema)
14
- const query = await getValidatedQuery(event, querySchema);
13
+ // h3 v1 (Nuxt 4): pass the schema's parse function; a throw becomes a 400
14
+ const query = await getValidatedQuery(event, querySchema.parse);
15
15
 
16
16
  // query is fully typed: { search?: string, page: number, limit: number, status: "active" | "inactive" | "all" }
17
17
 
@@ -139,6 +139,61 @@ For this to target precisely, give the fetches explicit keys
139
139
  `clearNuxtData(keys?)` drops cached payload + error state without refetching (e.g.
140
140
  reset a wizard's loaded data on cancel).
141
141
 
142
+ ## Errors, status and stale data
143
+
144
+ These are the `useFetch`/`useAsyncData` semantics (read from the Nuxt 4 runtime)
145
+ that generated code gets wrong most often. How to *render* them (loading, error
146
+ with Retry, empty, data; double submit; stale responses) is in the `vue-nuxt`
147
+ skill's `async-state.md`.
148
+
149
+ - **Nothing throws.** A failed request sets `error`, resets `data` to its
150
+ `default()` (`undefined` unless you passed one) and sets `status` to `'error'`.
151
+ `await useFetch(...)`, `await refresh()` and `await execute()` all **resolve**. A
152
+ `try/catch` around them catches nothing, so check afterwards:
153
+
154
+ ```typescript
155
+ await refresh();
156
+ // also check status: a refresh superseded by a newer one resolves with no error
157
+ if (error.value || status.value !== "success") {
158
+ reportError("Couldn't reload the invoice"); // your app's toast/alert
159
+ return; // don't send, advance "as of", or redirect on stale data
160
+ }
161
+ ```
162
+
163
+ - **`data` being empty is not an answer.** `data` is `undefined` while loading,
164
+ after a failure and when the server returned nothing, so `!data.value` can't mean
165
+ "no rows" or "no access". Branch on `status`/`error` first. A failed permission or
166
+ integration check is **unknown** (show an error and Retry), never "denied", and
167
+ don't pick a view from `data` until `status === 'success'`.
168
+ - **`status` can start at `'idle'`.** With `server: false` the whole server render
169
+ and the first client render are `'idle'`, not `'pending'`, and with
170
+ `immediate: false` it stays `'idle'` until `execute()` runs. A skeleton gated on
171
+ `status === 'pending'` alone doesn't appear. Treat `'idle'` as loading when the
172
+ fetch is going to start by itself.
173
+ - **A new key keeps the old data.** When a reactive URL/key changes, the new entry
174
+ starts with the **previous key's `data`** while `status` is `'pending'` (a plain
175
+ `refresh()` likewise keeps `data` until replaced). So the screen shows last month's
176
+ report under this month's heading, and buttons act on it. Hide the data and disable
177
+ actions until `status === 'success'` for the current key.
178
+ - **Start every fetch before awaiting any.** In a custom composable, code after an
179
+ `await` can run without the Nuxt instance ("Nuxt instance unavailable"), and
180
+ sequential awaits are slower anyway. Start both, then await together:
181
+
182
+ ```typescript
183
+ const invoices = useFetch("/api/invoices");
184
+ const totals = useFetch("/api/invoices/totals");
185
+ await Promise.all([invoices, totals]);
186
+ ```
187
+
188
+ In a page, give `useHead`/`useSeoMeta` a getter (`title: () => data.value?.name ?? 'Project'`)
189
+ so the title follows the data; a plain value read once at setup goes stale.
190
+ - **Polling:** a 401 from a background poll means the session ended; clear the
191
+ state, don't restore the old value. Tolerate a transient failure or two, but cap
192
+ the loop and then report "unknown", not "failed".
193
+ - **Capped lists:** a picker or "upcoming vs past" split built from one `limit`-ed
194
+ page silently omits rows. Search server-side (with a stable order) or fetch every
195
+ page before splitting.
196
+
142
197
  ## Type Inference
143
198
 
144
199
  Template literals preserve type inference (fixed late 2024):
@@ -194,3 +249,5 @@ const result = await $fetch("/api/users/123");
194
249
  3. **Adding type params** - Types are inferred from Nitro
195
250
  4. **Using `watch` option for dynamic URLs** - Use getter function
196
251
  5. **Passing null/undefined in query** - Filter them out first
252
+ 6. **`try/catch` around `refresh()`** - It never throws; check `error.value` after it (see above)
253
+ 7. **Rendering `!data` as "nothing here"** - A failed load is an error state, not an empty one
@@ -241,3 +241,5 @@ export async function markJobFailed(jobId: number, error: Error) {
241
241
  4. **Dev API only in dev** - `/_nitro/tasks/*` not in production
242
242
  5. **Cron needs specific runtimes** - node-server, bun, deno-server, cloudflare
243
243
  6. **Fire-and-forget errors** - Must add `.catch()` or errors are swallowed
244
+ 7. **`runTask` returns `run()`'s value as-is** - No wrapper is added. If `run` returns `{ result: { queued: 3 } }`, the caller reads `res.result.queued`; don't guess a shape.
245
+ 8. **A run whose items failed is a failed run** - If `run` catches per-item errors and returns normally, Nitro's scheduler sees success: it only reports a run that **throws**. Record the counts (a run table, a log line), then throw when any item failed if the scheduler or caller must see the failure; a returned `{ ok: false }` is visible only to code that reads it.
@@ -41,8 +41,13 @@ export function useStripe() {
41
41
 
42
42
  ```typescript
43
43
  // server/api/checkout/create.post.ts
44
+ import { z } from "zod";
45
+
44
46
  export default defineEventHandler(async (event) => {
45
- const { amount, currency } = await readBody(event);
47
+ const { amount, currency } = await readValidatedBody(event, z.object({
48
+ amount: z.number().int().positive(),
49
+ currency: z.enum(["usd", "eur"]),
50
+ }).parse); // never raw readBody + destructure: see validation.md
46
51
 
47
52
  const { createPaymentIntent } = useStripe();
48
53
 
@@ -169,6 +174,98 @@ async function callExternalApi() {
169
174
  }
170
175
  ```
171
176
 
177
+ ## Failures from third-party calls
178
+
179
+ The shape reviewers flag most in service code: a catch or a status check that turns
180
+ a **failure** into a normal-looking result ("not found", "empty", "disconnected",
181
+ "done"), which the caller then acts on.
182
+
183
+ ```typescript
184
+ // ❌ every error becomes "no such folder", so the caller creates a duplicate
185
+ async function findFolder(name: string) {
186
+ try { return await drive.find(name); } catch { return null; }
187
+ }
188
+
189
+ // ✅ only a real not-found means absent; everything else propagates
190
+ async function findFolder(name: string) {
191
+ try {
192
+ return await drive.find(name);
193
+ } catch (error: any) {
194
+ if (error?.status === 404) return null;
195
+ throw error;
196
+ }
197
+ }
198
+ ```
199
+
200
+ - **Only not-found is absence.** Timeouts, 5xx, 429 and auth errors on a lookup are
201
+ failures. Never create, delete, or report "no access" on the strength of a
202
+ lookup that failed.
203
+ - **A 2xx without the expected object is a failure**, not a completed read (an
204
+ empty body, a missing `items` key, a wrapper with `error` inside).
205
+ - **A 401/403 for one resource is local.** One mailbox, calendar or user the
206
+ integration can't reach doesn't mean the whole connection is down: mark that item,
207
+ keep going, and only flip "disconnected" on an auth failure of the connection itself.
208
+ - **Batches: isolate items.** One bad item (or one chunk's unreadable response body)
209
+ must not fail the whole batch. Collect per-item results, retry the failing chunk
210
+ item by item if the API is all-or-nothing, and report partial success as partial.
211
+ - **Map known upstream rejections to the right status** (a provider's "too large" to
212
+ 413, "not found" to 404) instead of a generic 502/500, so the client can say why.
213
+ - **Third-party contracts:** handle every status representation the provider
214
+ documents (string *and* numeric codes, new enum values), detect state changes by
215
+ the documented field rather than an inferred one (a zero total is not "voided"),
216
+ and re-validate a stored remote id before reusing it, since the remote side can
217
+ delete or move it.
218
+ - **Log allowlisted fields, never the whole error.** SDK errors carry request
219
+ headers, tokens and payloads; logs are not the place for emails or other personal
220
+ identifiers. Log `{ service, status, code, requestId }`.
221
+
222
+ ### Timeouts and best-effort work
223
+
224
+ An outbound call without a timeout can hang the request (or a job's claim) for
225
+ minutes. `Promise.race` against a timer **does not cancel** the call; it keeps
226
+ running and holding whatever it holds. Put the timeout on the call itself:
227
+
228
+ ```typescript
229
+ await $fetch(url, { timeout: 5_000 }); // ofetch; ignored if you also pass `signal`, and it stops
230
+ // at the response headers: a stalled body is not covered
231
+ await $fetch(url, { signal: AbortSignal.timeout(5_000) }); // covers the body read too
232
+ await fetch(url, { signal: AbortSignal.timeout(5_000) }); // native fetch
233
+ // SDKs: use the client's own timeout option
234
+ ```
235
+
236
+ Don't block a response on best-effort work (a chat notification, an analytics ping,
237
+ a "last seen" refresh). Hand it to Nitro and return:
238
+
239
+ ```typescript
240
+ event.waitUntil(notifyChannel(payment).catch((e) => console.error("notify failed", e.message)));
241
+ return { ok: true };
242
+ ```
243
+
244
+ (`event.waitUntil` is Nitro v2's; on serverless runtimes it extends the invocation,
245
+ on Node it just tracks the promise. Always `.catch`: nobody awaits it.)
246
+
247
+ ## Multi-step operations with side effects
248
+
249
+ When one handler or job does several writes, some of them external (create a folder,
250
+ send an email, post to an API), order matters because external writes can't be
251
+ rolled back with the DB transaction:
252
+
253
+ 1. **Validate everything first.** Every input, every referenced record, every
254
+ refusal check, before the first mutation. Cleanup or "prep" steps go after the
255
+ checks, so a refused request changes nothing.
256
+ 2. **DB work in one transaction** (see Transaction Pattern below), external calls
257
+ outside it, so a slow API doesn't hold row locks.
258
+ 3. **Record intent before delivery** (an outbox/guard row inserted first, delivery
259
+ marked done after). The guard that stops re-runs must not also stop a **retry** of a
260
+ delivery that failed: track delivery state separately from "already processed".
261
+ A retry after "sent but not yet marked done" sends twice, so pass the provider a
262
+ stable idempotency key (the outbox row's id) where it accepts one.
263
+ 4. **Idempotency keys cover the whole payload.** When a replay is detected by key,
264
+ compare every field that affects the result and reject a replay whose payload
265
+ differs, instead of returning the first result for a different request.
266
+ 5. **Conditional external writes.** If you validated against a remote version/etag,
267
+ send it on the write (`If-Match`) so a concurrent edit isn't overwritten.
268
+
172
269
  ## Transaction Pattern
173
270
 
174
271
  ```typescript
@@ -236,3 +333,5 @@ export function useService() {
236
333
  3. **Composition order** - Call use*() inside functions, not module level
237
334
  4. **Error transformation** - Convert SDK errors to HTTP errors
238
335
  5. **Transaction scope** - Pass `trx` when in transaction
336
+ 6. **Failure is not absence** - Only a not-found means "none"; see Failures from third-party calls
337
+ 7. **Every outbound call gets a timeout** - On the call itself, not a `Promise.race`
@@ -191,7 +191,7 @@ const reconnect = () => {
191
191
 
192
192
  ```typescript
193
193
  // Server reads position
194
- const { position } = await getValidatedQuery(event, schema);
194
+ const { position } = await getValidatedQuery(event, schema.parse);
195
195
  const chunks = await getChunksFromPosition(id, position);
196
196
  ```
197
197