wcz-layout 9.7.0 → 10.1.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 (93) hide show
  1. package/dist/AggregatedCell-C7nAQyMO.mjs +510 -0
  2. package/dist/AggregatedCell-C7nAQyMO.mjs.map +1 -0
  3. package/dist/Approval-C-hF4jbT.mjs.map +1 -1
  4. package/dist/DialogsContext-DLqA8RJ_.mjs.map +1 -1
  5. package/dist/Email-BzQQkbe9.mjs.map +1 -1
  6. package/dist/FileMeta-DDqUju1Y.mjs.map +1 -1
  7. package/dist/LayoutTable-BkrjgpW_.d.mts +758 -0
  8. package/dist/{QueryClientParam-Cbb0MIKg.d.mts → QueryClientParam-JcH0mJWl.d.mts} +2 -2
  9. package/dist/RouterListItemButton-ULMlaQh6.mjs.map +1 -1
  10. package/dist/{User-1gKoYJvW.d.mts → User-D4__w1I1.d.mts} +4 -2
  11. package/dist/approval-BYryxFOW.mjs +84 -0
  12. package/dist/approval-BYryxFOW.mjs.map +1 -0
  13. package/dist/auth.d.mts +21 -11
  14. package/dist/auth.mjs +43 -26
  15. package/dist/auth.mjs.map +1 -1
  16. package/dist/components.d.mts +22 -30
  17. package/dist/components.mjs +813 -140
  18. package/dist/components.mjs.map +1 -1
  19. package/dist/createApi-DGJJ4I_R.mjs +27 -0
  20. package/dist/createApi-DGJJ4I_R.mjs.map +1 -0
  21. package/dist/data/client.d.mts +690 -1176
  22. package/dist/data/client.mjs +4 -3
  23. package/dist/data/client.mjs.map +1 -1
  24. package/dist/data/server.d.mts +3 -3
  25. package/dist/data/server.mjs +4 -2
  26. package/dist/data/server.mjs.map +1 -1
  27. package/dist/{file-DimNsRly.mjs → file-C14fhUeg.mjs} +6 -7
  28. package/dist/file-C14fhUeg.mjs.map +1 -0
  29. package/dist/{file-BWcNzq55.mjs → file-C5BOj1q8.mjs} +5 -24
  30. package/dist/file-C5BOj1q8.mjs.map +1 -0
  31. package/dist/hooks.d.mts +7 -46
  32. package/dist/hooks.mjs +2587 -239
  33. package/dist/hooks.mjs.map +1 -1
  34. package/dist/index.d.mts +28 -9
  35. package/dist/index.mjs +1248 -500
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/middleware.d.mts +20 -19
  38. package/dist/middleware.mjs +47 -2
  39. package/dist/middleware.mjs.map +1 -1
  40. package/dist/models.d.mts +17 -10
  41. package/dist/models.mjs.map +1 -1
  42. package/dist/{peoplesoft-CskGsqd6.d.mts → peoplesoft-BY_75WTS.d.mts} +2 -2
  43. package/dist/{peoplesoft-DTPGpN2h.mjs → peoplesoft-BkJMCcHb.mjs} +24 -81
  44. package/dist/peoplesoft-BkJMCcHb.mjs.map +1 -0
  45. package/dist/providers-DrairEO2.mjs +74 -0
  46. package/dist/providers-DrairEO2.mjs.map +1 -0
  47. package/dist/tokens-BLRreL1j.mjs +143 -0
  48. package/dist/tokens-BLRreL1j.mjs.map +1 -0
  49. package/dist/{utils-DjdexspV.mjs → utils-BUpDoqme.mjs} +73 -51
  50. package/dist/utils-BUpDoqme.mjs.map +1 -0
  51. package/dist/{utils-5x4uNxsX.d.mts → utils-Bhi0KiBx.d.mts} +18 -6
  52. package/dist/utils.d.mts +2 -2
  53. package/dist/utils.mjs +2 -2
  54. package/dist/vite.d.mts +1 -2
  55. package/dist/vite.mjs +3 -3
  56. package/dist/vite.mjs.map +1 -1
  57. package/package.json +130 -128
  58. package/skills/client-db/SKILL.md +104 -96
  59. package/skills/db-schema/SKILL.md +46 -33
  60. package/skills/dialogs/SKILL.md +21 -27
  61. package/skills/forms/SKILL.md +60 -39
  62. package/skills/general/SKILL.md +122 -94
  63. package/skills/general/references/exports.md +106 -0
  64. package/skills/migrations/SKILL.md +53 -2
  65. package/skills/migrations/versions/migrate-v9-to-v10.md +582 -0
  66. package/skills/routing/SKILL.md +50 -60
  67. package/skills/server-functions/SKILL.md +36 -56
  68. package/skills/services/SKILL.md +7 -4
  69. package/skills/services/docs/approval.md +2 -2
  70. package/skills/services/docs/peoplesoft.md +114 -110
  71. package/skills/start/SKILL.md +9 -5
  72. package/skills/start/steps/05-database-setup.md +52 -52
  73. package/skills/start/steps/06-entra-setup.md +1 -1
  74. package/skills/start/steps/07-vault-setup.md +5 -12
  75. package/skills/table/SKILL.md +263 -0
  76. package/skills/unslop/SKILL.md +80 -0
  77. package/dist/NotificationContext-CgwUOeW0.mjs +0 -7
  78. package/dist/NotificationContext-CgwUOeW0.mjs.map +0 -1
  79. package/dist/authMiddleware-DPly0b_T.mjs +0 -48
  80. package/dist/authMiddleware-DPly0b_T.mjs.map +0 -1
  81. package/dist/entra-CJSyeQsx.mjs +0 -109
  82. package/dist/entra-CJSyeQsx.mjs.map +0 -1
  83. package/dist/file-BWcNzq55.mjs.map +0 -1
  84. package/dist/file-DimNsRly.mjs.map +0 -1
  85. package/dist/msalServer-DLwA7_ta.mjs +0 -30
  86. package/dist/msalServer-DLwA7_ta.mjs.map +0 -1
  87. package/dist/peoplesoft-DTPGpN2h.mjs.map +0 -1
  88. package/dist/useDialogs-BUzVrTSP.mjs +0 -248
  89. package/dist/useDialogs-BUzVrTSP.mjs.map +0 -1
  90. package/dist/user-Dzv0N9fj.d.mts +0 -16
  91. package/dist/utils-DjdexspV.mjs.map +0 -1
  92. package/skills/data-grid/SKILL.md +0 -142
  93. package/skills/migrations/versions/migrate-v9-to-v10.tsx +0 -9
package/package.json CHANGED
@@ -1,128 +1,130 @@
1
- {
2
- "name": "wcz-layout",
3
- "version": "9.7.0",
4
- "private": false,
5
- "keywords": [
6
- "tanstack-intent"
7
- ],
8
- "repository": {
9
- "type": "git",
10
- "url": "https://gitlab.wistron.com/wcz/it-developers/layout/tanstack.git"
11
- },
12
- "files": [
13
- "dist",
14
- "skills",
15
- "!skills/_artifacts"
16
- ],
17
- "type": "module",
18
- "sideEffects": [
19
- "./dist/index.mjs"
20
- ],
21
- "exports": {
22
- "./package.json": "./package.json",
23
- ".": {
24
- "types": "./dist/index.d.mts",
25
- "import": "./dist/index.mjs"
26
- },
27
- "./components": {
28
- "types": "./dist/components.d.mts",
29
- "import": "./dist/components.mjs"
30
- },
31
- "./hooks": {
32
- "types": "./dist/hooks.d.mts",
33
- "import": "./dist/hooks.mjs"
34
- },
35
- "./middleware": {
36
- "types": "./dist/middleware.d.mts",
37
- "import": "./dist/middleware.mjs"
38
- },
39
- "./models": {
40
- "types": "./dist/models.d.mts",
41
- "import": "./dist/models.mjs"
42
- },
43
- "./data/client": {
44
- "types": "./dist/data/client.d.mts",
45
- "import": "./dist/data/client.mjs"
46
- },
47
- "./data/server": {
48
- "types": "./dist/data/server.d.mts",
49
- "import": "./dist/data/server.mjs"
50
- },
51
- "./utils": {
52
- "types": "./dist/utils.d.mts",
53
- "import": "./dist/utils.mjs"
54
- },
55
- "./auth": {
56
- "types": "./dist/auth.d.mts",
57
- "import": "./dist/auth.mjs"
58
- },
59
- "./vite": {
60
- "types": "./dist/vite.d.mts",
61
- "import": "./dist/vite.mjs"
62
- }
63
- },
64
- "scripts": {
65
- "dev": "vp dev",
66
- "check": "vp check",
67
- "typecheck": "tsc --noEmit --watch --preserveWatchOutput",
68
- "build": "vp pack",
69
- "prepublishOnly": "npm run build"
70
- },
71
- "dependencies": {
72
- "@azure/msal-node": "^5.5.0",
73
- "@t3-oss/env-core": "^0.13.11",
74
- "i18next": "^26.3.6",
75
- "i18next-browser-languagedetector": "^8.2.1",
76
- "jose": "^6.2.9",
77
- "react-dropzone": "^20.1.0",
78
- "react-i18next": "^17.0.11",
79
- "react-intersection-observer": "^11.0.0",
80
- "react-number-format": "^5.4.5",
81
- "tus-js-client": "^4.3.1",
82
- "uuidv7": "^1.2.1"
83
- },
84
- "devDependencies": {
85
- "@arethetypeswrong/core": "^0.18.5",
86
- "@rolldown/plugin-babel": "^0.2.3",
87
- "@tanstack/ai": "^0.44.1",
88
- "@tanstack/ai-client": "^0.23.2",
89
- "@tanstack/ai-openai": "^0.19.0",
90
- "@tanstack/highlight": "^0.0.10",
91
- "@tanstack/react-table": "^9.1.2",
92
- "@types/node": "^24.10.13",
93
- "@types/react": "^19.2.18",
94
- "@types/react-dom": "^19.2.4",
95
- "@vitejs/plugin-react": "^6.0.5",
96
- "babel-plugin-react-compiler": "^1.0.0",
97
- "nitro": "npm:nitro-nightly@latest",
98
- "publint": "^0.3.23",
99
- "typescript": "^7.0.2",
100
- "vite": "npm:@voidzero-dev/vite-plus-core@0.2.9",
101
- "vite-plus": "0.2.9"
102
- },
103
- "peerDependencies": {
104
- "@emotion/cache": "11.x",
105
- "@emotion/react": "11.x",
106
- "@emotion/styled": "11.x",
107
- "@mui/icons-material": "9.x",
108
- "@mui/material": "9.x",
109
- "@mui/x-data-grid-premium": "9.x",
110
- "@mui/x-date-pickers-pro": "9.x",
111
- "@tanstack/query-db-collection": "1.x",
112
- "@tanstack/react-db": "0.x",
113
- "@tanstack/react-form": "1.x",
114
- "@tanstack/react-query": "5.x",
115
- "@tanstack/react-router": "1.x",
116
- "@tanstack/react-router-ssr-query": "1.x",
117
- "@tanstack/react-start": "1.x",
118
- "axios": "1.x",
119
- "dayjs": "1.x",
120
- "react": "19.x",
121
- "react-dom": "19.x",
122
- "zod": "4.x"
123
- },
124
- "overrides": {
125
- "vite": "npm:@voidzero-dev/vite-plus-core@0.2.9"
126
- },
127
- "packageManager": "npm@12.0.2"
128
- }
1
+ {
2
+ "name": "wcz-layout",
3
+ "version": "10.1.0",
4
+ "private": false,
5
+ "keywords": [
6
+ "tanstack-intent"
7
+ ],
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://gitlab.wistron.com/wcz/it-developers/layout/tanstack.git"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "skills",
15
+ "!skills/_artifacts"
16
+ ],
17
+ "type": "module",
18
+ "sideEffects": [
19
+ "./dist/index.mjs"
20
+ ],
21
+ "exports": {
22
+ "./package.json": "./package.json",
23
+ ".": {
24
+ "types": "./dist/index.d.mts",
25
+ "import": "./dist/index.mjs"
26
+ },
27
+ "./components": {
28
+ "types": "./dist/components.d.mts",
29
+ "import": "./dist/components.mjs"
30
+ },
31
+ "./hooks": {
32
+ "types": "./dist/hooks.d.mts",
33
+ "import": "./dist/hooks.mjs"
34
+ },
35
+ "./middleware": {
36
+ "types": "./dist/middleware.d.mts",
37
+ "import": "./dist/middleware.mjs"
38
+ },
39
+ "./models": {
40
+ "types": "./dist/models.d.mts",
41
+ "import": "./dist/models.mjs"
42
+ },
43
+ "./data/client": {
44
+ "types": "./dist/data/client.d.mts",
45
+ "import": "./dist/data/client.mjs"
46
+ },
47
+ "./data/server": {
48
+ "types": "./dist/data/server.d.mts",
49
+ "import": "./dist/data/server.mjs"
50
+ },
51
+ "./utils": {
52
+ "types": "./dist/utils.d.mts",
53
+ "import": "./dist/utils.mjs"
54
+ },
55
+ "./auth": {
56
+ "types": "./dist/auth.d.mts",
57
+ "import": "./dist/auth.mjs"
58
+ },
59
+ "./vite": {
60
+ "types": "./dist/vite.d.mts",
61
+ "import": "./dist/vite.mjs"
62
+ }
63
+ },
64
+ "scripts": {
65
+ "dev": "vp dev",
66
+ "typecheck": "tsc --noEmit --watch --preserveWatchOutput",
67
+ "build": "vp pack",
68
+ "prepublishOnly": "npm run build"
69
+ },
70
+ "dependencies": {
71
+ "@t3-oss/env-core": "^0.13.11",
72
+ "i18next": "^26.4.2",
73
+ "i18next-browser-languagedetector": "^8.2.1",
74
+ "jose": "^6.2.12",
75
+ "react-dropzone": "^20.1.2",
76
+ "react-i18next": "^17.0.14",
77
+ "react-intersection-observer": "^11.0.1",
78
+ "react-number-format": "^5.4.5",
79
+ "tus-js-client": "^4.3.1",
80
+ "uuidv7": "^1.2.1"
81
+ },
82
+ "devDependencies": {
83
+ "@arethetypeswrong/core": "^0.18.5",
84
+ "@rolldown/plugin-babel": "^0.2.4",
85
+ "@tanstack/ai": "^0.55.0",
86
+ "@tanstack/ai-client": "^0.32.1",
87
+ "@tanstack/ai-openai": "^0.22.8",
88
+ "@tanstack/highlight": "^0.1.0",
89
+ "@tanstack/intent": "^0.4.0",
90
+ "@tanstack/react-pacer": "^0.23.0",
91
+ "@types/node": "^24.10.13",
92
+ "@types/react": "^19.3.0",
93
+ "@types/react-dom": "^19.3.0",
94
+ "@vitejs/plugin-react": "^6.1.1",
95
+ "babel-plugin-react-compiler": "^1.0.0",
96
+ "nitro": "npm:nitro-nightly@latest",
97
+ "publint": "^0.3.24",
98
+ "typescript": "^7.0.2",
99
+ "vite": "npm:@voidzero-dev/vite-plus-core@0.3.3",
100
+ "vite-plus": "0.3.3"
101
+ },
102
+ "peerDependencies": {
103
+ "@emotion/cache": "11.x",
104
+ "@emotion/react": "11.x",
105
+ "@emotion/styled": "11.x",
106
+ "@mui/icons-material": "9.x",
107
+ "@mui/material": "9.x",
108
+ "@mui/x-date-pickers": "9.x",
109
+ "@tanstack/query-db-collection": "1.x",
110
+ "@tanstack/react-db": "0.x",
111
+ "@tanstack/react-form": "1.x",
112
+ "@tanstack/react-hotkeys": "0.x",
113
+ "@tanstack/react-pacer": "0.x",
114
+ "@tanstack/react-query": "5.x",
115
+ "@tanstack/react-router": "1.x",
116
+ "@tanstack/react-router-ssr-query": "1.x",
117
+ "@tanstack/react-start": "1.x",
118
+ "@tanstack/react-table": "9.x",
119
+ "@tanstack/react-virtual": "3.x",
120
+ "axios": "1.x",
121
+ "dayjs": "1.x",
122
+ "react": "19.x",
123
+ "react-dom": "19.x",
124
+ "zod": "4.x"
125
+ },
126
+ "overrides": {
127
+ "vite": "npm:@voidzero-dev/vite-plus-core@0.3.3"
128
+ },
129
+ "packageManager": "npm@12.0.2"
130
+ }
@@ -1,124 +1,132 @@
1
1
  ---
2
2
  name: client-db
3
- description: "Use when: creating or modifying TanStack DB collections, live queries, optimistic collection writes, subset loading, collection preloading."
3
+ description: "Use when reading or writing client data with TanStack DB: collections, live queries, route preloading, optimistic writes, eager/on-demand sync, or browser SQLite persistence."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
4
7
  ---
5
8
 
6
- > Mechanics (`createCollection`, `queryCollectionOptions`, the live-query builder, `createOptimisticAction`) are covered by TanStack's own skills — load `@tanstack/db#db-core/live-queries`, `#db-core/mutations-optimistic`, and `@tanstack/react-db` for the API details. This skill adds only the wcz-layout conventions on top.
9
+ > Mechanics (the live-query builder, `createOptimisticAction`, collection adapters,
10
+ > browser persistence) are covered by TanStack's own skills. List the skills shipped by
11
+ > `@tanstack/db` and `@tanstack/react-db` and load whichever cover the task at hand.
12
+ > This skill adds the wcz-layout conventions on top, and overrides upstream where noted.
7
13
 
8
14
  ## Rules
9
15
 
10
- - Use `eager` syncMode for top-level collections, `on-demand` for child/relational data and for any collection expected to exceed ~10k rows.
11
- - Always preload every `eager` collection used by a route, including collections used only by components rendered under that route. Do not preload `on-demand` collections.
12
- - On detail routes keyed by a param, guard the loader with `queryOnce` (from `@tanstack/react-db`) — the route's `where` plus `.findOne()` — and `throw notFound()` (from `@tanstack/react-router`) when it resolves to `undefined`. It works for both sync modes, and for `on-demand` it warms the subset's query-cache entry. It is one-shot, so the component still needs `useLiveQuery`.
13
- - Use `useLiveQuery` for list/grid pages and `useLiveSuspenseQuery` for detail components wrapped in suspense.
14
- - Shape data in the collection query whenever possible: filter, order, group and aggregate only the fields the consumer needs. Do not load broad results and further filter or transform them in component code.
15
- - For mutations use `createOptimisticAction` — mirror the server mutation in `onMutate`, then call the server function in `mutationFn` and await `utils.refetch()` on every collection the server function writes.
16
- - For on-demand subset loading, convert `meta.loadSubsetOptions` with `fromTanDb()` (from `agnostic-query/tanstack-db`) before passing it to the server fn, and set `syncMode: "on-demand"`, `autoIndex: "eager"` and `defaultIndexType: BasicIndex` (from `@tanstack/react-db`).
17
-
18
- ## File Placement
19
-
20
- ```
21
- src/db-collections/ — DB collections
22
- src/server/actions/ — server functions (select/update/insert/delete)
23
- src/lib/schemas/ — Zod schemas (shared between client and server)
24
- src/lib/auth/scopes.ts — API scope keys
25
- ```
16
+ - One `DbClient` per request, built in `src/router.tsx` and put on the router context
17
+ next to `queryClient`. Components reach it with `useDbClient()`, loaders with
18
+ `context.dbClient`.
19
+ - Declare collections as descriptors: `collectionOptions(id, (client) => ...)`. Take the
20
+ query client from the factory with `client.requireDependency<QueryClient>("queryClient")`,
21
+ never a module-scope one — it is built per request and a singleton leaks across SSR.
22
+ - Export a `use<Table>Collection` hook next to each collection. It is the only way components
23
+ get a live collection to write to.
24
+ - Define every live query once in `src/db/queries/<table>.ts` as
25
+ `{ query: (q: InitialQueryBuilder) => ... }`. Reuse that definition in loaders and
26
+ components.
27
+ - Preload in the route loader and return the promise:
28
+ `loader: ({ context }) => context.dbClient.preloadLiveQuery(<x>QueryOptions)`.
29
+ This transports the query result. Explicit collection preload transports source rows
30
+ and is a no-op for on-demand collections.
31
+ - `useLiveQuery` for list pages, `useLiveSuspenseQuery` for detail components under
32
+ suspense. Suspense data is initialized, but `.findOne()` still returns `T | undefined`;
33
+ handle not-found explicitly.
34
+ - Shape data in the query: filter, order, group and aggregate only the fields the
35
+ consumer needs. Do not load broad results and transform them in component code.
36
+ - Mutations go through `createOptimisticAction`: mirror the server write in `onMutate`,
37
+ call the server function in `mutationFn`, then
38
+ `await utils.refetch({ throwOnError: true })` on every collection that function writes.
39
+ Await `transaction.isPersisted.promise` at the call site and surface failures with
40
+ `alert()`.
41
+ - `syncMode: "eager"` for top-level collections, `"on-demand"` for child data and anything expected past ~10k rows.
42
+ - Increment persisted `schemaVersion` whenever the row shape changes.
26
43
 
27
44
  ## Examples
28
45
 
29
46
  ```ts
30
- // src/db-collections/<feature>.ts
31
- export const librariesCollection = createCollection(
32
- queryCollectionOptions({
33
- queryKey: ["libraries"],
34
- queryFn: () => selectLibraries(),
47
+ // src/db/collections/<table>.ts
48
+ import { persistedCollectionOptions } from "@tanstack/browser-db-sqlite-persistence";
49
+ import { queryCollectionOptions } from "@tanstack/query-db-collection";
50
+ import { collectionOptions, useDbClient } from "@tanstack/react-db";
51
+ import type { QueryClient } from "@tanstack/react-query";
52
+ import { browserPersistence } from "../persistence";
53
+ import { TodoSchema } from "~/lib/schemas/todo";
54
+ import { selectTodos } from "~/server/actions/todo";
55
+
56
+ const TODOS_ID = "todos";
57
+
58
+ export const todoCollection = collectionOptions(TODOS_ID, (client) => {
59
+ const options = queryCollectionOptions({
60
+ id: TODOS_ID,
61
+ queryKey: [TODOS_ID],
62
+ queryFn: () => selectTodos(),
35
63
  getKey: ({ id }) => id,
36
- schema: LibrarySchema,
37
- queryClient: queryClient,
64
+ schema: TodoSchema,
65
+ queryClient: client.requireDependency<QueryClient>("queryClient"),
38
66
  syncMode: "eager",
39
- }),
40
- );
67
+ });
41
68
 
42
- // src/db-collections/<feature>.ts — child/relational or >10k rows (on-demand)
43
- import { BasicIndex } from "@tanstack/react-db";
44
- import { fromTanDb } from "agnostic-query/tanstack-db";
69
+ const persistence = browserPersistence();
70
+ if (!persistence) return options;
45
71
 
46
- export const bookCollection = createCollection(
47
- queryCollectionOptions({
48
- queryKey: ["books"],
49
- queryFn: ({ meta }) => selectBooks({ data: fromTanDb(meta?.loadSubsetOptions) }),
50
- getKey: ({ id }) => id,
51
- schema: BookSchema,
52
- queryClient: queryClient,
53
- syncMode: "on-demand",
54
- autoIndex: "eager",
55
- defaultIndexType: BasicIndex,
56
- }),
57
- );
58
-
59
- // Preload
60
- export const Route = createFileRoute("/")({
61
- loader: () => {
62
- void librariesCollection.preload();
63
- },
72
+ return persistedCollectionOptions({
73
+ ...options,
74
+ persistence,
75
+ schemaVersion: 1, // Increment when the persisted row shape changes.
76
+ }) as typeof options;
64
77
  });
65
78
 
66
- // Detail route — not-found guard
67
- export const Route = createFileRoute("/libraries/$libraryId")({
68
- loader: async ({ params }) => {
69
- const library = await queryOnce((q) =>
70
- q
71
- .from({ library: libraryCollection })
72
- .where(({ library }) => eq(library.id, params.libraryId))
73
- .findOne(),
74
- );
75
-
76
- if (!library) throw notFound();
77
- },
79
+ export const useTodoCollection = () => useDbClient().collection(todoCollection);
80
+ ```
81
+
82
+ ```ts
83
+ // src/db/queries/<table>.ts
84
+ import type { InitialQueryBuilder } from "@tanstack/react-db";
85
+ import { eq } from "@tanstack/react-db";
86
+ import { todoCollection } from "../collections/todo";
87
+
88
+ export const todosQueryOptions = {
89
+ query: (q: InitialQueryBuilder) =>
90
+ q.from({ todo: todoCollection }).orderBy(({ todo }) => todo.id, "desc"),
91
+ };
92
+
93
+ export const todoByIdQueryOptions = (id: string) => ({
94
+ query: (q: InitialQueryBuilder) =>
95
+ q
96
+ .from({ todo: todoCollection })
97
+ .where(({ todo }) => eq(todo.id, id))
98
+ .findOne(),
78
99
  });
100
+ ```
79
101
 
80
- // simple query
81
- const { data, isLoading } = useLiveQuery((q) =>
82
- q.from({ library: libraryCollection }).orderBy(({ library }) => library.name, "asc"),
83
- );
84
-
85
- // advanced query with relational data
86
- const { data } = useLiveQuery((q) =>
87
- q
88
- .from({ library: libraryCollection })
89
- .where(({ library }) => eq(library.id, id))
90
- .findOne()
91
- .select(({ library }) => ({
92
- ...library,
93
- books: toArray(
94
- q
95
- .from({ book: bookCollection })
96
- .where(({ book }) => eq(book.libraryId, library.id))
97
- .orderBy(({ book }) => book.title, "asc")
98
- .select(({ book }) => ({
99
- id: book.id,
100
- title: book.title,
101
- })),
102
- ),
103
- })),
104
- );
105
-
106
- // form submission handler
107
- const handleOnSubmit = createOptimisticAction<Library>({
108
- onMutate: (formValues) => {
109
- libraryCollection.update(id, (prev) => Object.assign(prev, formValues));
102
+ ```tsx
103
+ // route + component
104
+ export const Route = createFileRoute("/todos/$id")({
105
+ beforeLoad: requireAuth("admin"),
106
+ loader: ({ context, params }) =>
107
+ context.dbClient.preloadLiveQuery(todoByIdQueryOptions(params.id)),
108
+ });
109
+
110
+ const { id } = Route.useParams();
111
+ const todos = useTodoCollection();
112
+ const { data } = useLiveSuspenseQuery(todoByIdQueryOptions(id));
113
+
114
+ const handleOnDelete = createOptimisticAction<string>({
115
+ onMutate: (id) => {
116
+ todos.delete(id);
110
117
  },
111
- mutationFn: async (formValues) => {
112
- await updateLibrary({ data: formValues });
113
- await libraryCollection.utils.refetch();
118
+ mutationFn: async (id) => {
119
+ await deleteTodo({ data: { id } });
120
+ await todos.utils.refetch({ throwOnError: true });
114
121
  },
115
122
  });
116
123
 
117
- // calling the handler
118
124
  try {
119
- const transaction = handleOnSubmit(formValues);
125
+ const transaction = handleOnDelete(id);
120
126
  await transaction.isPersisted.promise;
121
127
  } catch (error) {
122
- if (error instanceof Error) alert(error.message);
128
+ if (error instanceof Error) await alert(error.message);
123
129
  }
130
+
131
+ if (!data) return null;
124
132
  ```
@@ -1,55 +1,64 @@
1
1
  ---
2
2
  name: db-schema
3
- description: "Use when: defining or updating Drizzle ORM table schemas, relations, enums, migrations, or Zod schemas derived from database models."
3
+ description: "Use when changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys, relations, migrations, or Drizzle-derived Zod schemas in a wcz-layout app."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
4
7
  ---
5
8
 
6
- # Database Schema Patterns
9
+ # Database schema patterns
7
10
 
8
11
  ## Rules
9
12
 
10
13
  - One table per file, named after the table (e.g. `bookTable` lives in `book.ts`). Never put multiple tables in one file, even when they are related — a parent and its children each get their own file.
11
- - Always use `uuid` for primary keys, and `snakeCase` for generating tables.
12
- - For `uuid` columns, do not generate random values in the schema. Client should generate UUIDs when creating new records.
14
+ - Use `uuid` for application-table primary keys and `snakeCase` for generating tables.
15
+ - For `uuid` columns, do not generate random values in the schema. The client generates the id with `uuidv7()` from `wcz-layout/utils` when creating the record.
13
16
  - Always add `withTimezone: true` to timestamp columns.
14
- - Always add `onDelete: "cascade"` on foreign keys for child/dependent tables.
17
+ - Always declare `onDelete` explicitly on every foreign key — never rely on the default. Pick the behavior from the business rule: `"cascade"` when the child is meaningless without its parent, `"restrict"` when the parent must not be deleted while children exist, `"set null"` for optional references.
18
+ - Index every foreign key column. Postgres does not create one for you.
15
19
  - Define relations in a central `relations.ts` file.
16
- - Generate Zod schemas with `createSelectSchema`; override fields with stricter rules (trim, min/max) where needed.
17
- - Use `.transform()` on all Zod schemas that include related data to assign parent IDs.
20
+ - Declare enums with `pgEnum` in the table's own file, export them, and reference `enumValues` everywhere else — never re-declare the values.
21
+ - Generate the full client record schema with `createSelectSchema` from `drizzle-orm/zod`. Use `createInsertSchema`; override fields with stricter rules (trim, min/max) where needed.
22
+ - The second argument of `createSelectSchema` refines **existing columns only**. Adding a key
23
+ that is not a column is a type error. Attach related data with `.extend()` after it.
18
24
  - Do not auto-generate migrations unless the user explicitly asks. When asked, run `npm run db:generate`; migrations apply automatically at app startup while `DATABASE_AUTO_MIGRATE=true`.
19
- - Export enums from the schema file and reference enumValues everywhere else — never re-declare the values.
20
-
21
- ## File Placement
22
-
23
- ```
24
- drizzle-orm - defineRelations utility
25
- drizzle-orm/pg-core - snakeCase table builder and column types
26
- drizzle-orm/zod - createSelectSchema
27
- zod - Zod
28
- src/server/db/schemas/ - Drizzle table schemas, one table per file + relations.ts
29
- src/server/db/migrations/ - Drizzle migration files
30
- src/lib/schemas/ - Zod schemas (shared between client and server)
31
- wcz-layout/utils - `t` translation function
32
- ```
33
25
 
34
26
  ## Examples
35
27
 
36
28
  ```ts
37
29
  // src/server/db/schemas/library.ts
30
+ import { snakeCase, text, uuid } from "drizzle-orm/pg-core";
31
+
38
32
  export const libraryTable = snakeCase.table("libraries", {
39
33
  id: uuid().primaryKey(),
40
34
  name: text().notNull(),
41
35
  });
42
36
 
43
37
  // src/server/db/schemas/book.ts
44
- export const bookTable = snakeCase.table("books", {
45
- id: uuid().primaryKey(),
46
- title: text().notNull(),
47
- libraryId: uuid()
48
- .notNull()
49
- .references(() => libraryTable.id, { onDelete: "cascade" }),
50
- });
38
+ import { index, pgEnum, snakeCase, text, timestamp, uuid } from "drizzle-orm/pg-core";
39
+ import { libraryTable } from "./library";
40
+
41
+ export const bookStatusEnum = pgEnum("book_status", ["draft", "published"]);
42
+
43
+ export const bookTable = snakeCase.table(
44
+ "books",
45
+ {
46
+ id: uuid().primaryKey(),
47
+ title: text().notNull(),
48
+ status: bookStatusEnum().notNull().default("draft"),
49
+ libraryId: uuid()
50
+ .notNull()
51
+ .references(() => libraryTable.id, { onDelete: "cascade" }),
52
+ createdAt: timestamp({ withTimezone: true }).defaultNow().notNull(),
53
+ },
54
+ (table) => [index().on(table.libraryId)],
55
+ );
51
56
 
52
57
  // src/server/db/schemas/relations.ts
58
+ import { defineRelations } from "drizzle-orm";
59
+ import { bookTable } from "./book";
60
+ import { libraryTable } from "./library";
61
+
53
62
  export const relations = defineRelations(
54
63
  { libraryTable, bookTable },
55
64
  ({ one, many, libraryTable: library, bookTable: book }) => ({
@@ -62,18 +71,22 @@ export const relations = defineRelations(
62
71
  }),
63
72
  );
64
73
 
65
- // src/lib/schemas/<feature>.ts
74
+ // src/lib/schemas/<table>.ts
75
+ import { createSelectSchema } from "drizzle-orm/zod";
76
+ import { t } from "wcz-layout/utils";
77
+ import type { z } from "zod";
78
+ import { bookTable } from "~/server/db/schemas/book";
79
+ import { PageSchema } from "./page";
80
+
66
81
  export const BookSchema = createSelectSchema(bookTable, {
67
82
  title: (schema) =>
68
83
  schema
69
84
  .trim()
70
85
  .min(1, t("Validation.Required"))
71
86
  .max(255, t("Validation.MaxLength", { length: 255 })),
87
+ }).extend({
72
88
  pages: PageSchema.array().min(1, t("Validation.Required")),
73
- }).transform((data) => ({
74
- ...data,
75
- pages: data.pages.map((page) => ({ ...page, bookId: data.id })),
76
- }));
89
+ });
77
90
 
78
91
  export type Book = z.infer<typeof BookSchema>;
79
92
  ```