cvx-kit 0.2.0 → 2.0.0-beta.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 (372) hide show
  1. package/README.md +556 -99
  2. package/dist/agent-tools.d.mts +39 -26
  3. package/dist/agent-tools.mjs +1 -1
  4. package/dist/agent-tools.mjs.map +1 -1
  5. package/dist/auth.d.mts +120 -308
  6. package/dist/auth.mjs +1 -1
  7. package/dist/auth.mjs.map +1 -1
  8. package/dist/components/approvals/_generated/api.d.mts +7 -9
  9. package/dist/components/approvals/_generated/api.mjs.map +1 -1
  10. package/dist/components/approvals/_generated/component.d.mts +1 -4
  11. package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
  12. package/dist/components/approvals/_generated/server.d.mts +12 -15
  13. package/dist/components/approvals/_generated/server.mjs.map +1 -1
  14. package/dist/components/approvals/audit.d.mts +8 -9
  15. package/dist/components/approvals/audit.mjs +1 -1
  16. package/dist/components/approvals/audit.mjs.map +1 -1
  17. package/dist/components/approvals/client.d.mts +11 -12
  18. package/dist/components/approvals/client.mjs +1 -1
  19. package/dist/components/approvals/client.mjs.map +1 -1
  20. package/dist/components/approvals/constants.d.mts +30 -31
  21. package/dist/components/approvals/constants.mjs.map +1 -1
  22. package/dist/components/approvals/convex.config.d.mts +0 -2
  23. package/dist/components/approvals/convex.config.mjs.map +1 -1
  24. package/dist/components/approvals/decisions.d.mts +13 -17
  25. package/dist/components/approvals/decisions.mjs +1 -1
  26. package/dist/components/approvals/decisions.mjs.map +1 -1
  27. package/dist/components/approvals/functions.d.mts +3 -4
  28. package/dist/components/approvals/functions.mjs +1 -1
  29. package/dist/components/approvals/functions.mjs.map +1 -1
  30. package/dist/components/approvals/health.d.mts +2 -3
  31. package/dist/components/approvals/health.mjs.map +1 -1
  32. package/dist/components/approvals/requests.d.mts +114 -131
  33. package/dist/components/approvals/requests.mjs +1 -1
  34. package/dist/components/approvals/requests.mjs.map +1 -1
  35. package/dist/components/approvals/schema.d.ts +106 -315
  36. package/dist/components/approvals/schema.js +1 -1
  37. package/dist/components/approvals/validators.d.mts +323 -395
  38. package/dist/components/approvals/validators.mjs +1 -1
  39. package/dist/components/approvals/validators.mjs.map +1 -1
  40. package/dist/components/approvals/workflow.d.mts +4 -5
  41. package/dist/components/approvals/workflow.mjs +1 -1
  42. package/dist/components/approvals/workflow.mjs.map +1 -1
  43. package/dist/components/approvals/workflow_steps.d.mts +16 -17
  44. package/dist/components/approvals/workflow_steps.mjs +1 -1
  45. package/dist/components/approvals/workflow_steps.mjs.map +1 -1
  46. package/dist/components/foundation/_generated/api.d.mts +6 -8
  47. package/dist/components/foundation/_generated/api.mjs.map +1 -1
  48. package/dist/components/foundation/_generated/component.d.mts +1 -4
  49. package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
  50. package/dist/components/foundation/_generated/server.d.mts +12 -15
  51. package/dist/components/foundation/_generated/server.mjs.map +1 -1
  52. package/dist/components/foundation/client.d.mts +45 -38
  53. package/dist/components/foundation/client.mjs +1 -1
  54. package/dist/components/foundation/client.mjs.map +1 -1
  55. package/dist/components/foundation/convex.config.d.mts +0 -2
  56. package/dist/components/foundation/convex.config.mjs.map +1 -1
  57. package/dist/components/foundation/functions.d.mts +2 -3
  58. package/dist/components/foundation/functions.mjs.map +1 -1
  59. package/dist/components/foundation/modules/command/command.d.mts +65 -17
  60. package/dist/components/foundation/modules/command/command.mjs +1 -1
  61. package/dist/components/foundation/modules/command/command.mjs.map +1 -1
  62. package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
  63. package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
  64. package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
  65. package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
  66. package/dist/components/foundation/modules/observability/observability.mjs +1 -1
  67. package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
  68. package/dist/components/foundation/modules/query/query.d.mts +11 -12
  69. package/dist/components/foundation/modules/query/query.mjs +1 -1
  70. package/dist/components/foundation/modules/query/query.mjs.map +1 -1
  71. package/dist/components/foundation/operation.d.mts +72 -0
  72. package/dist/components/foundation/operation.mjs +2 -0
  73. package/dist/components/foundation/operation.mjs.map +1 -0
  74. package/dist/components/foundation/result.d.mts +7 -8
  75. package/dist/components/foundation/result.mjs.map +1 -1
  76. package/dist/components/foundation/schema.d.ts +0 -2
  77. package/dist/components/foundation/telemetry.d.mts +2 -3
  78. package/dist/components/foundation/telemetry.mjs +1 -1
  79. package/dist/components/foundation/telemetry.mjs.map +1 -1
  80. package/dist/contracts.d.mts +5 -0
  81. package/dist/contracts.mjs +1 -0
  82. package/dist/crud.d.mts +185 -27
  83. package/dist/crud.mjs +1 -1
  84. package/dist/crud.mjs.map +1 -1
  85. package/dist/effect.d.mts +16 -0
  86. package/dist/effect.mjs +1 -0
  87. package/dist/errors.d.mts +6 -6
  88. package/dist/errors.mjs +1 -1
  89. package/dist/errors.mjs.map +1 -1
  90. package/dist/filters.d.mts +4 -0
  91. package/dist/filters.mjs +1 -0
  92. package/dist/idempotency.d.mts +2 -0
  93. package/dist/idempotency.mjs +1 -0
  94. package/dist/index.d.mts +14 -7
  95. package/dist/index.mjs +1 -1
  96. package/dist/json-schema.d.mts +40 -0
  97. package/dist/json-schema.mjs +2 -0
  98. package/dist/json-schema.mjs.map +1 -0
  99. package/dist/k/compile.d.mts +17 -0
  100. package/dist/k/compile.mjs +2 -0
  101. package/dist/k/compile.mjs.map +1 -0
  102. package/dist/k/dates.d.mts +23 -0
  103. package/dist/k/dates.mjs +2 -0
  104. package/dist/k/dates.mjs.map +1 -0
  105. package/dist/k/formats.d.mts +24 -0
  106. package/dist/k/formats.mjs +2 -0
  107. package/dist/k/formats.mjs.map +1 -0
  108. package/dist/k/index.d.mts +32 -0
  109. package/dist/k/index.mjs +2 -0
  110. package/dist/k/index.mjs.map +1 -0
  111. package/dist/k/issues.d.mts +31 -0
  112. package/dist/k/issues.mjs +2 -0
  113. package/dist/k/issues.mjs.map +1 -0
  114. package/dist/k/kinds.d.mts +81 -0
  115. package/dist/k/kinds.mjs +2 -0
  116. package/dist/k/kinds.mjs.map +1 -0
  117. package/dist/k/object.d.mts +43 -0
  118. package/dist/k/object.mjs +2 -0
  119. package/dist/k/object.mjs.map +1 -0
  120. package/dist/k/parse.d.mts +29 -0
  121. package/dist/k/parse.mjs +2 -0
  122. package/dist/k/parse.mjs.map +1 -0
  123. package/dist/k/schema.d.mts +100 -0
  124. package/dist/k/schema.mjs +2 -0
  125. package/dist/k/schema.mjs.map +1 -0
  126. package/dist/k/standard.d.mts +8 -0
  127. package/dist/k/standard.mjs +2 -0
  128. package/dist/k/standard.mjs.map +1 -0
  129. package/dist/k/types.d.mts +64 -0
  130. package/dist/k/types.mjs +1 -0
  131. package/dist/k.d.mts +8 -0
  132. package/dist/k.mjs +1 -0
  133. package/dist/middleware.d.mts +8 -11
  134. package/dist/middleware.mjs +1 -1
  135. package/dist/middleware.mjs.map +1 -1
  136. package/dist/modules/contracts/binding.d.mts +23 -0
  137. package/dist/modules/contracts/binding.mjs +2 -0
  138. package/dist/modules/contracts/binding.mjs.map +1 -0
  139. package/dist/modules/contracts/contract.d.mts +67 -0
  140. package/dist/modules/contracts/contract.mjs +2 -0
  141. package/dist/modules/contracts/contract.mjs.map +1 -0
  142. package/dist/modules/contracts/convex.d.mts +18 -0
  143. package/dist/modules/contracts/convex.mjs +2 -0
  144. package/dist/modules/contracts/convex.mjs.map +1 -0
  145. package/dist/modules/contracts/domain.d.mts +62 -0
  146. package/dist/modules/contracts/domain.mjs +2 -0
  147. package/dist/modules/contracts/domain.mjs.map +1 -0
  148. package/dist/modules/contracts/errors.d.mts +737 -0
  149. package/dist/modules/contracts/errors.mjs +2 -0
  150. package/dist/modules/contracts/errors.mjs.map +1 -0
  151. package/dist/modules/contracts/exposure.d.mts +103 -0
  152. package/dist/modules/contracts/exposure.mjs +2 -0
  153. package/dist/modules/contracts/exposure.mjs.map +1 -0
  154. package/dist/modules/contracts/idempotency.d.mts +85 -0
  155. package/dist/modules/contracts/idempotency.mjs +2 -0
  156. package/dist/modules/contracts/idempotency.mjs.map +1 -0
  157. package/dist/modules/contracts/lazy.d.mts +6 -0
  158. package/dist/modules/contracts/lazy.mjs +2 -0
  159. package/dist/modules/contracts/lazy.mjs.map +1 -0
  160. package/dist/modules/contracts/standard.d.mts +17 -0
  161. package/dist/modules/contracts/standard.mjs +2 -0
  162. package/dist/modules/contracts/standard.mjs.map +1 -0
  163. package/dist/modules/contracts/workflow.d.mts +165 -0
  164. package/dist/modules/contracts/workflow.mjs +2 -0
  165. package/dist/modules/contracts/workflow.mjs.map +1 -0
  166. package/dist/modules/effect/action.d.mts +63 -0
  167. package/dist/modules/effect/action.mjs +2 -0
  168. package/dist/modules/effect/action.mjs.map +1 -0
  169. package/dist/modules/effect/agent-tools.d.mts +2 -0
  170. package/dist/modules/effect/agent-tools.mjs +1 -0
  171. package/dist/modules/effect/api-runtime.d.mts +36 -0
  172. package/dist/modules/effect/api-runtime.mjs +2 -0
  173. package/dist/modules/effect/api-runtime.mjs.map +1 -0
  174. package/dist/modules/effect/api.d.mts +46 -0
  175. package/dist/modules/effect/api.mjs +2 -0
  176. package/dist/modules/effect/api.mjs.map +1 -0
  177. package/dist/modules/effect/auth.d.mts +46 -0
  178. package/dist/modules/effect/auth.mjs +2 -0
  179. package/dist/modules/effect/auth.mjs.map +1 -0
  180. package/dist/modules/effect/client.d.mts +15 -0
  181. package/dist/modules/effect/client.mjs +1 -0
  182. package/dist/modules/effect/command.d.mts +108 -0
  183. package/dist/modules/effect/command.mjs +2 -0
  184. package/dist/modules/effect/command.mjs.map +1 -0
  185. package/dist/modules/effect/crud.d.mts +885 -0
  186. package/dist/modules/effect/crud.mjs +2 -0
  187. package/dist/modules/effect/crud.mjs.map +1 -0
  188. package/dist/modules/effect/domain.d.mts +82 -0
  189. package/dist/modules/effect/domain.mjs +2 -0
  190. package/dist/modules/effect/domain.mjs.map +1 -0
  191. package/dist/modules/effect/errors.d.mts +13 -0
  192. package/dist/modules/effect/errors.mjs +2 -0
  193. package/dist/modules/effect/errors.mjs.map +1 -0
  194. package/dist/modules/effect/failure-audit.d.mts +48 -0
  195. package/dist/modules/effect/failure-audit.mjs +2 -0
  196. package/dist/modules/effect/failure-audit.mjs.map +1 -0
  197. package/dist/modules/effect/failures.d.mts +21 -0
  198. package/dist/modules/effect/failures.mjs +2 -0
  199. package/dist/modules/effect/failures.mjs.map +1 -0
  200. package/dist/modules/effect/foundation.d.mts +23 -0
  201. package/dist/modules/effect/foundation.mjs +2 -0
  202. package/dist/modules/effect/foundation.mjs.map +1 -0
  203. package/dist/modules/effect/idempotency.d.mts +29 -0
  204. package/dist/modules/effect/idempotency.mjs +2 -0
  205. package/dist/modules/effect/idempotency.mjs.map +1 -0
  206. package/dist/modules/effect/input.d.mts +10 -0
  207. package/dist/modules/effect/input.mjs +2 -0
  208. package/dist/modules/effect/input.mjs.map +1 -0
  209. package/dist/modules/effect/normalize.d.mts +7 -0
  210. package/dist/modules/effect/normalize.mjs +2 -0
  211. package/dist/modules/effect/normalize.mjs.map +1 -0
  212. package/dist/modules/effect/operation.d.mts +148 -0
  213. package/dist/modules/effect/operation.mjs +2 -0
  214. package/dist/modules/effect/operation.mjs.map +1 -0
  215. package/dist/modules/effect/query.d.mts +90 -0
  216. package/dist/modules/effect/query.mjs +2 -0
  217. package/dist/modules/effect/query.mjs.map +1 -0
  218. package/dist/modules/effect/schema.d.mts +30 -0
  219. package/dist/modules/effect/schema.mjs +2 -0
  220. package/dist/modules/effect/schema.mjs.map +1 -0
  221. package/dist/modules/effect/scope.d.mts +25 -0
  222. package/dist/modules/effect/scope.mjs +2 -0
  223. package/dist/modules/effect/scope.mjs.map +1 -0
  224. package/dist/modules/effect/workflow.d.mts +75 -0
  225. package/dist/modules/effect/workflow.mjs +2 -0
  226. package/dist/modules/effect/workflow.mjs.map +1 -0
  227. package/dist/modules/foundation/foundation.d.mts +108 -0
  228. package/dist/modules/foundation/foundation.mjs +2 -0
  229. package/dist/modules/foundation/foundation.mjs.map +1 -0
  230. package/dist/modules/foundation/operation.d.mts +139 -0
  231. package/dist/modules/foundation/operation.mjs +2 -0
  232. package/dist/modules/foundation/operation.mjs.map +1 -0
  233. package/dist/namespace.d.mts +104 -0
  234. package/dist/namespace.mjs +2 -0
  235. package/dist/namespace.mjs.map +1 -0
  236. package/dist/oxlint/architecture.d.mts +23 -0
  237. package/dist/oxlint/architecture.mjs +2 -0
  238. package/dist/oxlint/architecture.mjs.map +1 -0
  239. package/dist/oxlint/ast.d.mts +51 -0
  240. package/dist/oxlint/ast.mjs +2 -0
  241. package/dist/oxlint/ast.mjs.map +1 -0
  242. package/dist/oxlint/components.d.mts +4 -0
  243. package/dist/oxlint/components.mjs +2 -0
  244. package/dist/oxlint/components.mjs.map +1 -0
  245. package/dist/oxlint/ownership.d.mts +59 -0
  246. package/dist/oxlint/ownership.mjs +2 -0
  247. package/dist/oxlint/ownership.mjs.map +1 -0
  248. package/dist/oxlint/reserved-files.d.mts +4 -0
  249. package/dist/oxlint/reserved-files.mjs +2 -0
  250. package/dist/oxlint/reserved-files.mjs.map +1 -0
  251. package/dist/oxlint.d.mts +9 -0
  252. package/dist/oxlint.mjs +2 -0
  253. package/dist/oxlint.mjs.map +1 -0
  254. package/dist/querying/cursors.d.mts +94 -0
  255. package/dist/querying/cursors.mjs +2 -0
  256. package/dist/querying/cursors.mjs.map +1 -0
  257. package/dist/querying/execution.d.mts +40 -0
  258. package/dist/querying/execution.mjs +2 -0
  259. package/dist/querying/execution.mjs.map +1 -0
  260. package/dist/querying/failures.d.mts +11 -0
  261. package/dist/querying/failures.mjs +2 -0
  262. package/dist/querying/failures.mjs.map +1 -0
  263. package/dist/querying/filter-boundary.d.mts +25 -0
  264. package/dist/querying/filter-boundary.mjs +2 -0
  265. package/dist/querying/filter-boundary.mjs.map +1 -0
  266. package/dist/querying/filters.d.mts +180 -0
  267. package/dist/querying/filters.mjs +2 -0
  268. package/dist/querying/filters.mjs.map +1 -0
  269. package/dist/querying/planner.d.mts +61 -0
  270. package/dist/querying/planner.mjs +2 -0
  271. package/dist/querying/planner.mjs.map +1 -0
  272. package/dist/querying/relationships.d.mts +58 -0
  273. package/dist/querying/relationships.mjs +2 -0
  274. package/dist/querying/relationships.mjs.map +1 -0
  275. package/dist/querying/search.d.mts +69 -0
  276. package/dist/querying/search.mjs +2 -0
  277. package/dist/querying/search.mjs.map +1 -0
  278. package/dist/querying/security.d.mts +123 -0
  279. package/dist/querying/security.mjs +2 -0
  280. package/dist/querying/security.mjs.map +1 -0
  281. package/dist/querying/shared/ast.d.mts +26 -0
  282. package/dist/querying/shared/ast.mjs +2 -0
  283. package/dist/querying/shared/ast.mjs.map +1 -0
  284. package/dist/querying/shared/contract.d.mts +98 -0
  285. package/dist/querying/shared/contract.mjs +2 -0
  286. package/dist/querying/shared/contract.mjs.map +1 -0
  287. package/dist/querying/shared/evaluate.d.mts +5 -0
  288. package/dist/querying/shared/evaluate.mjs +2 -0
  289. package/dist/querying/shared/evaluate.mjs.map +1 -0
  290. package/dist/querying/shared/filters.d.mts +65 -0
  291. package/dist/querying/shared/filters.mjs +2 -0
  292. package/dist/querying/shared/filters.mjs.map +1 -0
  293. package/dist/querying/shared/native-json.d.mts +7 -0
  294. package/dist/querying/shared/native-json.mjs +2 -0
  295. package/dist/querying/shared/native-json.mjs.map +1 -0
  296. package/dist/querying/shared/page.d.mts +20 -0
  297. package/dist/querying/shared/page.mjs +2 -0
  298. package/dist/querying/shared/page.mjs.map +1 -0
  299. package/dist/querying.d.mts +82 -0
  300. package/dist/querying.mjs +2 -0
  301. package/dist/querying.mjs.map +1 -0
  302. package/dist/react/failures.d.mts +24 -0
  303. package/dist/react/failures.mjs +2 -0
  304. package/dist/react/failures.mjs.map +1 -0
  305. package/dist/react/optimistic.d.mts +46 -0
  306. package/dist/react/optimistic.mjs +2 -0
  307. package/dist/react/optimistic.mjs.map +1 -0
  308. package/dist/react/pagination-state.d.mts +39 -0
  309. package/dist/react/pagination-state.mjs +2 -0
  310. package/dist/react/pagination-state.mjs.map +1 -0
  311. package/dist/react/use-command.d.mts +22 -0
  312. package/dist/react/use-command.mjs +2 -0
  313. package/dist/react/use-command.mjs.map +1 -0
  314. package/dist/react/use-paginated-list.d.mts +34 -0
  315. package/dist/react/use-paginated-list.mjs +2 -0
  316. package/dist/react/use-paginated-list.mjs.map +1 -0
  317. package/dist/react.d.mts +6 -0
  318. package/dist/react.mjs +1 -0
  319. package/dist/registration.d.mts +65 -0
  320. package/dist/registration.mjs +2 -0
  321. package/dist/registration.mjs.map +1 -0
  322. package/dist/relations-public.d.mts +2 -0
  323. package/dist/relations-public.mjs +1 -0
  324. package/dist/relations.d.mts +274 -0
  325. package/dist/relations.mjs +2 -0
  326. package/dist/relations.mjs.map +1 -0
  327. package/dist/state-machine.d.mts +1 -4
  328. package/dist/state-machine.mjs.map +1 -1
  329. package/dist/table.d.mts +222 -0
  330. package/dist/table.mjs +2 -0
  331. package/dist/table.mjs.map +1 -0
  332. package/dist/tenancy.d.mts +6 -8
  333. package/dist/tenancy.mjs +1 -1
  334. package/dist/tenancy.mjs.map +1 -1
  335. package/dist/triggers.d.mts +12 -10
  336. package/dist/triggers.mjs +1 -1
  337. package/dist/triggers.mjs.map +1 -1
  338. package/dist/webhooks.d.mts +22 -112
  339. package/dist/webhooks.mjs +1 -1
  340. package/dist/webhooks.mjs.map +1 -1
  341. package/dist/workflow.d.mts +2 -0
  342. package/dist/workflow.mjs +1 -0
  343. package/dist/zod.d.mts +30 -0
  344. package/dist/zod.mjs +2 -0
  345. package/dist/zod.mjs.map +1 -0
  346. package/package.json +145 -33
  347. package/src/test.ts +9 -17
  348. package/CHANGELOG.md +0 -145
  349. package/ROADMAP.md +0 -126
  350. package/dist/zod-table.d.mts +0 -175
  351. package/dist/zod-table.mjs +0 -2
  352. package/dist/zod-table.mjs.map +0 -1
  353. package/docs/agent-tools.md +0 -41
  354. package/docs/approvals.md +0 -200
  355. package/docs/architecture.md +0 -124
  356. package/docs/auth.md +0 -218
  357. package/docs/commands.md +0 -278
  358. package/docs/conventions.md +0 -291
  359. package/docs/crud.md +0 -62
  360. package/docs/llms.md +0 -220
  361. package/docs/maintainability.md +0 -124
  362. package/docs/migration.md +0 -351
  363. package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
  364. package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
  365. package/docs/tenancy.md +0 -179
  366. package/docs/triggers.md +0 -75
  367. package/docs/upgrading.md +0 -175
  368. package/docs/webhooks.md +0 -58
  369. package/docs/zod-table.md +0 -173
  370. package/scripts/convex-config-bridge.mjs +0 -55
  371. package/scripts/extract-changelog.mjs +0 -29
  372. package/scripts/smoke-packed-components.mjs +0 -374
package/docs/tenancy.md DELETED
@@ -1,179 +0,0 @@
1
- # `cvx-kit/tenancy` — row-level security, with tenancy as an opt-in layer
2
-
3
- Row-level security and tenancy are **separate, composable features** of the
4
- same `security` config on `createAuthFunctions`:
5
-
6
- - **`security.rules` alone** — role-level / module-level RLS with no tenancy
7
- at all: gate writes by role, freeze evidence tables, ownership-gate reads.
8
- `defaultPolicy` stays `'allow'`; unlisted tables behave normally.
9
- - **`security.tenancy` alone** — pure tenant isolation from a table registry.
10
- - **Both** — rules are AND-composed with tenant isolation.
11
-
12
- A single-org app that only wants role-gated writes configures `rules` and
13
- never touches tenancy. Nothing below is required unless you opt into it.
14
-
15
- Multi-tenancy itself is a structural machine, not a per-handler
16
- convention. The model: **tenant = the identity provider's organization id**,
17
- stamped as a server-owned `tenant` string field on every tenant-scoped row,
18
- always derived from the verified identity — never accepted as an argument.
19
- Isolation is defense-in-depth; each layer covers a hole in the previous one:
20
-
21
- 1. **Schema** — `tenantTable` injects the field and strips it from every
22
- write boundary.
23
- 2. **Row-level security** — deny-default rules generated mechanically from
24
- one table registry, wrapped into the auth constructors.
25
- 3. **Triggers** — a post-image invariant forbids tenant reassignment (RLS
26
- authorizes against the pre-image only).
27
- 4. **Reference guards** — client-supplied ids re-verify ownership without
28
- disclosing existence.
29
-
30
- Single-org apps skip all of this: every piece is opt-in, and
31
- `createAuthFunctions` without a `security` config behaves exactly as before.
32
-
33
- ## The registry is the design
34
-
35
- One list of table names drives everything. Adding a table to the registry is
36
- the entire onboarding — there is no second per-table step to forget:
37
-
38
- ```ts
39
- // convex/tenancy.ts (or alongside triggers.ts)
40
- export const TENANT_TABLES = ['<entities>', '<others>'] as const
41
- ```
42
-
43
- - `security.tenancy.tables: TENANT_TABLES` → RLS rules generated per table
44
- - `tenantOwnership(triggers, ...TENANT_TABLES)` → reassignment guard per table
45
- - each listed table is declared with `tenantTable(...)` in its module
46
-
47
- Recommended architecture test: assert every `tenantTable` in the codebase
48
- appears in `TENANT_TABLES`, and vice versa.
49
-
50
- ## Wiring
51
-
52
- ```ts
53
- // domain/<module>/schema.ts — tenant injected at the schema boundary
54
- export const <entities> = tenantTable('<entities>', (id) => ({
55
- name: z.string(), ownerId: id('users'),
56
- }), { publicFields: ['name'] })
57
- // tenant: excluded from insertSchema/updateSchema/commandInput,
58
- // in publicDto only if explicitly allowlisted
59
-
60
- // domain/<module>/table.ts — every index tenant-prefixed
61
- <entities>: <entities>.table.index('by_tenant', ['tenant'])
62
- .index('by_tenant_owner', ['tenant', 'ownerId'])
63
-
64
- // convex/triggers.ts
65
- tenantOwnership(triggers, ...TENANT_TABLES)
66
-
67
- // convex/functions.ts
68
- createAuthFunctions<DataModel>({
69
- ...,
70
- security: {
71
- tenancy: {
72
- tables: TENANT_TABLES,
73
- // optional; defaults to bundle.org.organizationId
74
- resolve: (bundle) => bundle.org.organizationId,
75
- },
76
- // role-level security, AND-composed with tenant isolation
77
- rules: (bundle) => ({
78
- '<entities>': { modify: async () => bundle.role === '<privileged>' },
79
- }),
80
- // defaults to 'deny' when tenancy is configured
81
- defaultPolicy: 'deny',
82
- },
83
- })
84
- ```
85
-
86
- ## What the constructors do with it
87
-
88
- - Every authenticated ctx gains **`ctx.tenant`** (also on the frozen bundle) —
89
- resolved via `security.tenancy.resolve`, defaulting to the organization id.
90
- Actions re-derive it from the live-verified membership.
91
- - **Queries** get a wrapped reader: rows failing `read` are invisible —
92
- filtered from every `get`/`query`, even a full table scan.
93
- - **Mutations** wrap triggers first, then the RLS writer — `insert`/`modify`
94
- failing a rule throws. Order matters and is handled for you.
95
- - **`system*` constructors stay unwrapped** — trusted internal paths reach
96
- every table. This is deliberate: schedulers and callbacks receive the
97
- server-derived tenant as data, never as authority.
98
- - With tenancy configured, `defaultPolicy` defaults to **deny**: tables
99
- outside the registry are unreachable from `auth*`/`role*`/`admin*`
100
- functions. Global/platform tables are reached from `system*` paths, or by
101
- explicitly granting rules for them.
102
-
103
- Handlers stamp inserts from the ctx — the schema forbids clients supplying
104
- it, RLS rejects a wrong value, and the trigger forbids changing it later:
105
-
106
- ```ts
107
- await ctx.db.insert('<entities>', { ...args, tenant: ctx.tenant })
108
- ```
109
-
110
- ## Role-level security — with or without tenancy
111
-
112
- `security.rules` receives the full auth bundle and returns convex-helpers
113
- `Rules`. It works standalone (no tenancy configured) or AND-composed with
114
- tenant isolation (`composeRules`) — a row must pass **every** rule set that
115
- defines the operation. Use it for role-gated writes, ownership-gated reads,
116
- or state-machine write locks:
117
-
118
- ```ts
119
- // rules-only, single-org app: no tenancy anywhere
120
- security: {
121
- rules: (bundle) => ({
122
- '<entities>': { modify: async () => bundle.role !== '<readonly-role>' },
123
- }),
124
- }
125
- ```
126
-
127
- ```ts
128
- rules: (bundle) => ({
129
- '<entities>': {
130
- modify: async (_ctx, doc) =>
131
- bundle.role === 'admin' || doc.ownerId === bundle.actor.userId,
132
- },
133
- '<evidence>': { modify: async () => false }, // frozen via RLS as well as trigger
134
- })
135
- ```
136
-
137
- ## Client-supplied ids
138
-
139
- RLS makes foreign rows invisible to reads, but any id a client sends should
140
- still be re-verified — and without disclosing existence:
141
-
142
- ```ts
143
- import { requireTenantReference } from 'cvx-kit/tenancy'
144
-
145
- const row = await requireTenantReference(ctx.tenant, () => ctx.db.get(args.id))
146
- // missing row and foreign row fail identically: REFERENCE_NOT_FOUND
147
- ```
148
-
149
- `assertTenantOwned(tenant, doc)` is the internal-path variant
150
- (CROSS_TENANT_REFERENCE, for rows you already loaded on trusted paths).
151
-
152
- ## Footguns
153
-
154
- 1. **Actions have no db** — an action passing work to internal functions must
155
- pass `ctx.tenant` (server-derived) as data; internal functions must never
156
- accept a caller-chosen tenant on a public path.
157
- 2. **Provider ids are global** (memberships, invitations in WorkOS-style
158
- providers): org-scoped mutations against the provider must re-check the
159
- id belongs to the active org, or you ship a cross-tenant IDOR.
160
- 3. **Tables outside the registry get none of this.** Keep the global-table
161
- list short and named; every one is a per-handler-discipline zone.
162
- 4. **`t.run(...)` in convex-test bypasses RLS and triggers** — same rule as
163
- always: seeding only.
164
- 5. **Return "not found", never "forbidden"** for cross-tenant references —
165
- existence is also tenant data.
166
-
167
- ## Module maps
168
-
169
- `createModule` (from `cvx-kit/zod-table`) merges per-module table maps into
170
- the schema and rejects a table declared by two modules:
171
-
172
- ```ts
173
- // convex/domain/table.ts
174
- export const domainTables = createModule(
175
- <moduleA>Tables, <moduleB>Tables, <moduleC>Tables,
176
- )
177
- // convex/schema.ts
178
- export default defineSchema(domainTables)
179
- ```
package/docs/triggers.md DELETED
@@ -1,75 +0,0 @@
1
- # `cvx-kit/triggers` — one application-wide mutation interceptor registry
2
-
3
- A single `Triggers` registry (from convex-helpers) is created once per app and
4
- handed to `createAuthFunctions`. From then on, every `authMutation`,
5
- `roleMutation`, and `systemMutation` runs its writes through
6
- `triggers.wrapDB(ctx)` — trigger enforcement is **structural, not a
7
- convention**. A handler cannot skip a trigger because it never sees an
8
- unwrapped `ctx.db`.
9
-
10
- ## Setup
11
-
12
- ```ts
13
- // convex/triggers.ts — the single registry
14
- import { appendOnly, createTriggers, noDelete, timestamps } from 'cvx-kit/triggers'
15
- import type { DataModel } from './_generated/dataModel'
16
-
17
- export const triggers = createTriggers<DataModel>()
18
-
19
- // Server-owned lifecycle timestamps (see zod-table.md)
20
- timestamps(triggers, 'documents', 'projects', 'members')
21
-
22
- // Evidence tables: inserts only — updates/deletes throw and roll back
23
- appendOnly(triggers, 'votes', 'history')
24
-
25
- // Soft-delete discipline: hard deletes throw
26
- noDelete(triggers, 'documents')
27
-
28
- // Domain triggers register on the same instance
29
- triggers.register('documents', async (ctx, change) => {
30
- if (change.operation === 'insert') { /* denormalize, validate, cascade */ }
31
- })
32
- ```
33
-
34
- ```ts
35
- // convex/functions.ts
36
- createAuthFunctions<DataModel>({ ..., triggers })
37
- ```
38
-
39
- ## The built-in helpers
40
-
41
- - **`timestamps(triggers, ...tables)`** — maintains zod-table's opinionated
42
- fields: sets `createdAt` + `updatedAt` on insert, moves `updatedAt` on every
43
- update. `archivedAt` stays under application control. Contains its own
44
- recursion guard (a write that already moved `updatedAt` — including the
45
- trigger's own patch — is left alone). Register once per table.
46
- - **`appendOnly(triggers, ...tables)`** — inserts pass; any update or delete
47
- throws, which **rolls back the whole transaction**. The pattern for
48
- votes/history/audit-style evidence tables.
49
- - **`noDelete(triggers, ...tables)`** — forbids hard deletes only; updates
50
- pass. Pair with `archivedAt` for soft deletion.
51
- - **`tenantOwnership(triggers, ...tables)`** — the tenancy post-image
52
- invariant: inserts must carry a non-empty `tenant`, updates may never
53
- reassign it. Register for every table in the tenancy registry (row-level
54
- security checks the pre-image only — this closes that hole). See
55
- `tenancy.md`.
56
-
57
- `Triggers`, `Change`, and `Trigger` are re-exported for custom registrations.
58
-
59
- ## Footguns
60
-
61
- 1. **Anything outside the kit constructors bypasses every trigger.** Raw
62
- `mutation`/`internalMutation` from `_generated/server`, and `ctx.db` inside
63
- `convex-test`'s `t.run(...)`, are unwrapped. Never build a mutation outside
64
- your `functions.ts`, and expect test-side `t.run` writes to be trigger-free
65
- (useful for seeding, dangerous for assertions about trigger behavior).
66
- 2. **Wrapper spread order matters** if you compose ctx manually:
67
- `{ ...wrapDB(ctx), ...otherStuff }` — `wrapDB` returns a full ctx, so
68
- spreading it *after* anything that carries `db` restores the raw database.
69
- The kit's constructors already order this correctly
70
- (`{ ...wrapDB(ctx), include, ...authBundle }`).
71
- 3. **A throwing trigger aborts the transaction.** That is the point for
72
- `appendOnly`/`noDelete`, but remember it when writing custom triggers —
73
- validation triggers should throw; best-effort denormalization should not.
74
- 4. **Triggers run per write, in registration order.** Keep them small; heavy
75
- work belongs in a scheduled function, not in a trigger.
package/docs/upgrading.md DELETED
@@ -1,175 +0,0 @@
1
- # Upgrading to 0.1.0 — the new way of things
2
-
3
- ## Approvals packaging repair (0.1.x patch)
4
-
5
- `cvx-kit@0.1.0` published component schemas as `schema.mjs`, which Convex does
6
- not discover for packaged components. Upgrade to the patch containing this
7
- repair, remove any `patchedDependencies` entry that copied or renamed the
8
- approvals schema, reinstall from a clean lockfile state, and run one normal
9
- deployment:
10
-
11
- ```bash
12
- bun install
13
- bunx convex dev --once
14
- ```
15
-
16
- The repaired package publishes only `schema.js` and `schema.d.ts` for each
17
- component. Do not retain both `.mjs` and `.js`; Convex canonicalizes them to the
18
- same module and rejects the deployment with `CanonicalizationConflict`.
19
-
20
- This upgrade does not change table fields or index definitions, so a second
21
- deployment is not required for staged index backfills. Existing deployments
22
- that never received the component schema will create the tables and indexes on
23
- the first repaired deployment. Confirm readiness through
24
- `components.approvals.health.check` before resuming approval traffic.
25
-
26
- The migration file for consumers on 0.0.x. Each section: the old way you were
27
- hand-writing, the 0.1.0 way, and what stays unchanged. Nothing existing
28
- breaks in this release except one boundary-mask improvement (see the last
29
- section).
30
-
31
- **Semver contract from 0.1.0:** breaking changes land only on minor bumps;
32
- patches are additive or fixes. One caveat, stated honestly: the breaking
33
- window formally closes at the follow-up consolidation release (package-name
34
- decision + full export-name API audit) — until then the six new helper
35
- surfaces may still be renamed in a minor. Every tag now gets a GitHub
36
- Release with CHANGELOG notes.
37
-
38
- ## Pagination — was: `.take()` loops or hand-bridged validators
39
-
40
- Old way:
41
-
42
- ```ts
43
- // hand-rolled: convexToZod(paginationOptsValidator) in every project,
44
- // or worse, .execute(100) and client-side slicing.
45
- ```
46
-
47
- New way:
48
-
49
- ```ts
50
- import { paginated } from 'cvx-kit/zod-table'
51
-
52
- const page = paginated(<entities>.publicDto)
53
- export const list = authQuery({
54
- args: { paginationOpts: page.args.paginationOpts },
55
- returns: page.result,
56
- handler: (ctx, args) =>
57
- ctx.include(ctx.db.query('<entities>'))
58
- .matching('by_tenant', (ix) => ix.eq('tenant', ctx.tenant))
59
- .paginate(args.paginationOpts, (rows) => rows.map(<entities>.toPublicDto)),
60
- })
61
- ```
62
-
63
- Unchanged: `execute(limit)` for non-cursor reads; the maxRows bound applies
64
- to `numItems` too. Under RLS, pages may be SHORTER than `numItems` when
65
- rules reject rows mid-page — cursors remain correct, keep paging until
66
- `isDone`.
67
-
68
- ## CRUD — was: hand-written create/update/archive per entity
69
-
70
- New way:
71
-
72
- ```ts
73
- import { createCrudCommands } from 'cvx-kit/crud'
74
-
75
- const crud = createCrudCommands({
76
- Command, // destructured from your Foundation
77
- table: <entities>,
78
- aggregateType: '<entity>',
79
- actor: (ctx) => ctx.actor.userId,
80
- enrich: (ctx) => ({ tenant: ctx.tenant }), // REQUIRED for tenantTables
81
- })
82
- // crud.executeCreate / executeUpdate / executeArchive — audited commands
83
- ```
84
-
85
- Unchanged: your api/ adapters stay thin; bespoke operations keep using
86
- `Command.operation` directly. Archive is soft-delete only, by doctrine.
87
-
88
- ## Transition guards — was: hand-written `if` chains
89
-
90
- New way:
91
-
92
- ```ts
93
- import { createStateMachine } from 'cvx-kit/state-machine'
94
-
95
- const machine = createStateMachine(<ENTITY>_STATES, {
96
- draft: ['published', 'archived'],
97
- published: ['archived'],
98
- })
99
- // in a command guard:
100
- guard: async (ctx, command) => machine.assert(row.state, command.to)
101
- ```
102
-
103
- ## Rate limiting — was: hand-rolled counters or none
104
-
105
- New way (host mounts `@convex-dev/rate-limiter`; the kit stays
106
- dependency-free — it receives the instance):
107
-
108
- ```ts
109
- import { rateLimit } from 'cvx-kit/middleware'
110
-
111
- const commands = new Command(operations, {
112
- middleware: [rateLimit({ limiter, name: '<entities>.write' })],
113
- })
114
- ```
115
-
116
- Keyed by `ctx.tenant` by default. No tenant and no `key` fn →
117
- `RATE_LIMIT_KEY_MISSING` (configuration error, never a shared bucket).
118
-
119
- ## Webhooks — was: ad-hoc verification and dedup in the action
120
-
121
- New way:
122
-
123
- ```ts
124
- import { createWebhookBoundary, recordWebhookEvent, webhookEventsTable } from 'cvx-kit/webhooks'
125
-
126
- // schema: webhookEvents: webhookEventsTable().table.index('by_eventKey', ['eventKey'])
127
- const boundary = createWebhookBoundary({
128
- verify: async (raw, request) => timingSafeHmacVerify(raw, request), // RAW body, constant-time, secret from env
129
- eventKey: (raw) => { const e = JSON.parse(raw); return `${e.event}:${e.id}:${e.updatedAt}` },
130
- })
131
- // http.ts routes to boundary.handle(ctx, request, internal.<module>.functions.applyEvent)
132
- // applyEvent (systemMutation) calls recordWebhookEvent FIRST — transactional dedup.
133
- ```
134
-
135
- Dedup rows are host-owned: prune on a retention window longer than the
136
- provider's redelivery horizon (cleanup cron over `receivedAt`).
137
-
138
- ## Agent tools — was: hand-written tool definitions with raw db access
139
-
140
- New way:
141
-
142
- ```ts
143
- import { createAgentTools } from 'cvx-kit/agent-tools'
144
-
145
- const tools = createAgentTools(<entities>, {
146
- create: (ctx, input) => crud.executeCreate(ctx, input), // audited command
147
- get: (ctx, { id }) => loadDto(ctx, id), // reads: query handlers
148
- list: (ctx, { paginationOpts }) => listPage(ctx, paginationOpts),
149
- })
150
- // host: spread each record into @convex-dev/agent's createTool (or ai-sdk tool())
151
- ```
152
-
153
- Shape-compatible, dependency-free; checked against `@convex-dev/agent@0.6.x`
154
- — re-verify at install.
155
-
156
- ## Typed middleware context — was: loose `next({ context })`
157
-
158
- New way:
159
-
160
- ```ts
161
- const withVendor = Command.middleware<Ctx, { vendor: Vendor }>(
162
- async ({ context, next }) => next({ context: { vendor: await load(context) } }),
163
- )
164
- // registries/operations accept typed middleware without casts
165
- ```
166
-
167
- Unchanged: untyped middleware keeps compiling.
168
-
169
- ## The one behavior change: tool masks use jsonSafeZid
170
-
171
- `<table>.tools.update` and `<table>.tools.id` now type ids with
172
- `jsonSafeZid` instead of `zid`, so generated JSON schemas present ids as
173
- plain strings (compile-time `Id<...>` preserved). If you relied on the masks
174
- producing `zid` runtime metadata, re-check; for LLM tool schemas this is the
175
- fix you wanted.
package/docs/webhooks.md DELETED
@@ -1,58 +0,0 @@
1
- # `cvx-kit/webhooks` — the sanctioned webhook boundary
2
-
3
- Webhooks are the one boundary that genuinely needs deduplication (Convex's
4
- client gives exactly-once for its own mutations; external providers redeliver).
5
- The helper encodes the pattern: **verify over the raw body (fail closed) →
6
- derive the natural key → delegate to an internal mutation whose first act is
7
- transactional dedup**.
8
-
9
- ## Wiring
10
-
11
- ```ts
12
- // schema — host-owned dedup table (the kit gains no tables):
13
- webhookEvents: webhookEventsTable().table.index('by_eventKey', ['eventKey'])
14
-
15
- // boundary — used inside the host's httpAction:
16
- const boundary = createWebhookBoundary({
17
- // RAW body, BEFORE parsing. Constant-time comparison (crypto.subtle HMAC
18
- // verify), secret from a Convex environment variable — never in code.
19
- verify: async (raw, request) => verifyVendorSignature(raw, request.headers),
20
- // The natural-key pattern:
21
- eventKey: (raw) => {
22
- const event = JSON.parse(raw)
23
- return `${event.type}:${event.id}:${event.updatedAt}`
24
- },
25
- source: 'vendor',
26
- })
27
-
28
- // http.ts — routing only:
29
- http.route({ path: '/webhooks/vendor', method: 'POST',
30
- handler: httpAction((ctx, request) =>
31
- boundary.handle(ctx, request, internal.<module>.functions.applyVendorEvent)) })
32
-
33
- // the target — a systemMutation; dedup FIRST, transactionally:
34
- export const applyVendorEvent = systemMutation({
35
- args: { eventKey: z.string(), payload: z.string(), source: z.string() },
36
- handler: async (ctx, args) => {
37
- const { duplicate } = await recordWebhookEvent(ctx, { key: args.eventKey, source: args.source })
38
- if (duplicate) return null
39
- const payload = JSON.parse(args.payload) // parse INSIDE the trusted path
40
- // ...apply, via domain executors
41
- return null
42
- },
43
- })
44
- ```
45
-
46
- ## Rules
47
-
48
- 1. **Dedup lives in the mutation, never the action.** The action can race;
49
- the mutation's insert-if-absent is transactional.
50
- 2. **Verification is over raw bytes.** Re-serialized/parsed bodies break or
51
- weaken HMACs; the helper hands `verify` the raw `request.text()`.
52
- 3. **Fail closed.** `verify` returning false OR throwing both reject with
53
- `WEBHOOK_SIGNATURE_INVALID`, before any delegation.
54
- 4. **Retention is yours.** Dedup rows grow forever unless pruned — run a
55
- cleanup cron over `receivedAt` with a window comfortably longer than the
56
- provider's redelivery horizon (days, not hours).
57
- 5. Providers with signed timestamps (Stripe-style): also enforce a tolerance
58
- window inside `verify`.
package/docs/zod-table.md DELETED
@@ -1,173 +0,0 @@
1
- # `cvx-kit/zod-table` — one zod shape per entity, masked into every boundary
2
-
3
- The core idea: an entity's shape is declared **once** as a zod object, and every
4
- boundary that shape crosses — storage, insert, update, command input, public
5
- DTO, LLM tool input — is a *derived mask* of that single declaration. There is
6
- no second source of truth to drift.
7
-
8
- ```ts
9
- import { z } from 'zod'
10
- import { zodTable } from 'cvx-kit/zod-table'
11
-
12
- export const documents = zodTable(
13
- 'documents',
14
- (id) => ({
15
- title: z.string(),
16
- ownerId: id('users'), // `id` is convex-helpers' zid — typed Id<'users'>
17
- secretNote: z.string(),
18
- reviewState: z.enum(['draft', 'published']),
19
- }),
20
- {
21
- serverFields: ['reviewState'], // excluded from inserts — server assigns it
22
- commandFields: ['title'], // the ONLY fields a command may carry
23
- publicFields: ['title', 'ownerId'], // the DTO allowlist — everything else is redacted
24
- },
25
- )
26
- ```
27
-
28
- ## What you get back
29
-
30
- | Property | What it is | Where you use it |
31
- |---|---|---|
32
- | `table` | `defineTable(...)` from the storage shape | `convex/schema.ts` |
33
- | `storage` | zod object of the raw row (no `_id`/`_creationTime`) | validating rows |
34
- | `schema` | `storage` + `_id` + `_creationTime` | full-document validation |
35
- | `insertSchema` | storage minus timestamps minus `serverFields` | mutation args |
36
- | `updateSchema` | `insertSchema.partial()` | patch mutation args |
37
- | `commandInput` | strict pick of `commandFields` | command protocol inputs |
38
- | `publicDto` | strict pick of `publicFields` | query return validators |
39
- | `toPublicDto(row)` | projects **and re-parses** a row into the DTO | query handlers |
40
- | `insert(omit?)` / `update(omit?)` | schema with per-callsite field omission | specialized mutations |
41
- | `tools.insert` / `tools.update` / `tools.id` | ready-made LLM tool input schemas | agent tool definitions |
42
- | `tableName` | the literal table name | indexes, triggers registration |
43
-
44
- ## Redaction is runtime, not just types
45
-
46
- `toPublicDto` does not merely `pick` at the type level — it re-parses the
47
- projected object through the strict `publicDto` schema. A field that leaks into
48
- the projection throws instead of shipping to the client. Use it on **every**
49
- row a public query returns:
50
-
51
- ```ts
52
- export const get = authQuery({
53
- args: { id: zid('documents') },
54
- returns: documents.publicDto,
55
- handler: async (ctx, { id }) => {
56
- const row = await ctx.db.get(id)
57
- if (!row) throw new KitError({ code: 'NOT_FOUND' })
58
- return documents.toPublicDto(row) // secretNote can never leak
59
- },
60
- })
61
- ```
62
-
63
- ## Opinionated timestamps
64
-
65
- Every `zodTable` bakes in three optional, **server-owned** fields:
66
-
67
- - `createdAt` — set once on insert
68
- - `updatedAt` — moved on every update
69
- - `archivedAt` — soft-delete marker, under application control
70
-
71
- They are always excluded from `insertSchema`, `updateSchema`, and
72
- `commandInput` — a client or command can never write them. They are *not* in
73
- `publicFields` by default; list them explicitly when a DTO needs them
74
- (`publicFields: ['title', 'createdAt']`).
75
-
76
- They maintain themselves only if you register the `timestamps` trigger once
77
- per table (see `triggers.md`). Without the trigger they stay `undefined`.
78
-
79
- Prefer `createdAt` over `_creationTime` in DTOs so the whole lifecycle
80
- vocabulary is yours; `_creationTime` remains available for index ordering.
81
-
82
- ## Field masks — who sees what
83
-
84
- Think of the options as three independent allowlists over the same shape:
85
-
86
- - `serverFields` — *the server assigns these.* Excluded from `insertSchema`
87
- and `updateSchema`. Example: `reviewState`, denormalized counters.
88
- - `commandFields` — *a command may say these.* The command protocol's input
89
- is exactly this pick, strict. Everything else must be derived by the handler.
90
- - `publicFields` — *a client may see these.* The DTO is exactly this pick;
91
- may include timestamp fields.
92
-
93
- All derived objects are `.strict()` — unknown keys are rejected, in both
94
- directions.
95
-
96
- ## `tenantTable` — tenant-owned rows
97
-
98
- `tenantTable` is `zodTable` plus a server-owned `tenant` string field —
99
- injected exactly like timestamps: present in storage, excluded from
100
- `insertSchema`/`updateSchema`/`commandInput`, in `publicDto` only by explicit
101
- allowlist. Handlers stamp it from `ctx.tenant`; row-level security matches on
102
- it; the `tenantOwnership` trigger forbids reassigning it. See `tenancy.md`.
103
-
104
- ```ts
105
- export const <entities> = tenantTable('<entities>', (id) => ({ ... }), {
106
- commandFields: [...], publicFields: [...],
107
- })
108
- ```
109
-
110
- ## `createModule` — module table maps
111
-
112
- Merges per-module table maps into the application schema, throwing when two
113
- modules declare the same table — the combinator for `domain/table.ts`:
114
-
115
- ```ts
116
- export default defineSchema(createModule(<moduleA>Tables, <moduleB>Tables))
117
- ```
118
-
119
- ## `zodVariantTable` — discriminated unions
120
-
121
- For tables whose rows are a discriminated union (events, polymorphic
122
- resources), `zodTable`'s object-shape model doesn't apply. `zodVariantTable`
123
- keeps the same "one owner per table" convention while accepting any zod type
124
- as storage:
125
-
126
- ```ts
127
- const events = zodVariantTable('events', z.discriminatedUnion('kind', [
128
- z.object({ kind: z.literal('created'), by: zid('users') }),
129
- z.object({ kind: z.literal('archived'), reason: z.string() }),
130
- ]))
131
- // events.table → defineTable, events.insertSchema → the union itself
132
- ```
133
-
134
- Note: variant tables do not get the timestamp fields or boundary masks — the
135
- union is the boundary.
136
-
137
- ## `jsonSafeZid` — Ids in LLM tool schemas
138
-
139
- JSON-schema generators turn `zid('users')` into an opaque custom type that
140
- confuses LLM tool calling. `jsonSafeZid('users')` presents as a plain
141
- described string in the generated JSON schema while keeping `Id<'users'>` at
142
- the type level:
143
-
144
- ```ts
145
- const assignInput = z.object({
146
- documentId: jsonSafeZid('documents'), // LLM sees: string, "Convex document id for table \"documents\""
147
- })
148
- ```
149
-
150
- ## Wiring into `schema.ts`
151
-
152
- ```ts
153
- // convex/schema.ts
154
- import { defineSchema } from 'convex/server'
155
- import { documents } from './tables/documents'
156
-
157
- export default defineSchema({
158
- documents: documents.table
159
- .index('by_owner', ['ownerId'])
160
- .index('by_owner_archived', ['ownerId', 'archivedAt']),
161
- })
162
- ```
163
-
164
- Indexes are chained on `.table` exactly like a hand-written `defineTable`.
165
-
166
- ## Rules of thumb
167
-
168
- 1. One `zodTable` per entity, in its own module, exported by name.
169
- 2. Never define an inline `defineTable` or a second zod object for the same
170
- entity — masks only.
171
- 3. Every public query returns `publicDto`-shaped data via `toPublicDto`.
172
- 4. Every command input is `commandInput` (or a documented composition of it).
173
- 5. Timestamps are trigger-maintained; handlers never write them.