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/dist/auth.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{defaultErrors as e}from"./errors.mjs";import{composeRules as t,createTenantRules as n,wrapDatabaseReader as r,wrapDatabaseWriter as i}from"./tenancy.mjs";import{zCustomAction as a,zCustomMutation as o,zCustomQuery as s}from"convex-helpers/server/zod4";function c(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function l(t){let n=t?.errors??e,r=t?.maxRows??100;function i(e,t){return{when:(n,r)=>t||n==null?i(e,t):i(e,r(e,n)),matching:(n,r,a=!0)=>t||!a?i(e,t):i(e,e.withIndex(n,r)),otherwise:n=>t??n(e),resolve:()=>t??e.fullTableScan(),execute:async(i,a)=>{if(!Number.isSafeInteger(i)||i<1||i>r)return n.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${r}`});let o=await(t??e.fullTableScan()).take(i);return a?a(o):o},paginate:async(i,a)=>{if(!Number.isSafeInteger(i.numItems)||i.numItems<1||i.numItems>r)return n.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${r}`});let o=await(t??e.fullTableScan()).paginate(i);return a?{...o,page:await a(o.page)}:o}}}return e=>i(e)}function u(c){let u=c.errors??e,d=c.triggers?e=>c.triggers.wrapDB(e):c.wrapDB??(e=>e),f=l({errors:u,maxRows:c.maxIncludedQueryRows});async function p(e){let t=await e.auth.getUserIdentity(),n=t?await c.getAuthUser(e):null;if(!t||!n)return u.throw({code:`UNAUTHENTICATED`});let r,i;if(c.resolveOrganization){let a=null;try{a=await c.resolveOrganization({ctx:e,identity:t,user:n})}catch{}if(!a)return u.throw({code:`FORBIDDEN`});r=a.organizationId,i=a.roleSlug}else{let e=t.organization,n=e&&typeof e==`object`&&`organizationId`in e&&typeof e.organizationId==`string`?e.organizationId:typeof t.org_id==`string`?t.org_id:null;if(!n)return u.throw({code:`UNAUTHENTICATED`});r=n,i=e&&typeof e==`object`&&`role`in e&&typeof e.role==`string`?e.role:typeof t.role==`string`?t.role:void 0}let a=c.mapRole(i);if(!a)return u.throw({code:`FORBIDDEN`});let o={identity:t,user:Object.freeze({id:n.id}),org:Object.freeze({organizationId:r,role:a}),role:a,actor:Object.freeze({userId:n.id,organizationId:r,role:a})};return Object.freeze({...o,tenant:c.security?.tenancy?.resolve?.(o)??r})}let m=c.security?{defaultPolicy:c.security.defaultPolicy??(c.security.tenancy?`deny`:`allow`)}:void 0;function h(e){let r=c.security;if(!r)return;let i=[];return r.tenancy&&i.push(n(e.tenant,r.tenancy.tables)),r.rules&&i.push(r.rules(e)),i.length===1?i[0]:t(...i)}function g(e,t){let n=h(t);return n?{...e,db:r({},e.db,n,m)}:e}function _(e,t){let n=h(t);return n?{...e,db:i({},e.db,n,m)}:e}async function v(e,t){if(!c.verifyMembership)return null;try{let n=await c.verifyMembership({userId:e,organizationId:t});if(n&&n.organizationId===t)return n}catch{}return u.throw({code:`FORBIDDEN`})}function y(e,t){if(!t.includes(e))return u.throw({code:`FORBIDDEN`})}async function b(e){let t=await p(e);return{ctx:{...g(e,t),include:f,...t},args:{}}}async function x(e){let t=await p(e);return{ctx:{..._(d(e),t),include:f,...t},args:{}}}async function S(e){let t=await p(e),n=await v(t.user.id,t.org.organizationId);if(!n)return{ctx:{...e,...t},args:{}};let r=c.mapRole(n.roleSlug);if(!r)return u.throw({code:`FORBIDDEN`});let i={identity:t.identity,user:t.user,org:Object.freeze({organizationId:n.organizationId,role:r}),role:r,actor:Object.freeze({userId:t.user.id,organizationId:n.organizationId,role:r})};return{ctx:{...e,...i,tenant:c.security?.tenancy?.resolve?.(i)??n.organizationId},args:{}}}function C(...e){return s(c.query,{args:{},input:async t=>{let n=await b(t);return y(n.ctx.actor.role,e),n}})}function w(...e){return o(c.mutation,{args:{},input:async t=>{let n=await x(t);return y(n.ctx.actor.role,e),n}})}function T(...e){return a(c.action,{args:{},input:async t=>{let n=await S(t);return y(n.ctx.actor.role,e),n}})}return{include:f,authenticatedUser:p,roleQuery:C,roleMutation:w,roleAction:T,authQuery:s(c.query,{args:{},input:b}),authMutation:o(c.mutation,{args:{},input:x}),authAction:a(c.action,{args:{},input:S}),adminQuery:C(...c.adminRoles),adminMutation:w(...c.adminRoles),adminAction:T(...c.adminRoles),systemQuery:s(c.internalQuery,{args:{},input:async e=>({ctx:{...e,include:f},args:{}})}),systemMutation:o(c.internalMutation,{args:{},input:async e=>({ctx:{...d(e),include:f},args:{}})}),systemAction:a(c.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})}}export{u as createAuthFunctions,l as createInclude,c as defaultRoleMap};
1
+ import{kCustomFunctions as e,rawFunctionArgs as t}from"./registration.mjs";import{k as n}from"./k/index.mjs";import{memoize as r}from"./modules/contracts/lazy.mjs";import{defaultErrors as i}from"./errors.mjs";import{registerQueryReader as a,suppliedPolicyRules as o}from"./querying/security.mjs";import{composeRules as s,createTenantRules as c,wrapDatabaseReader as l,wrapDatabaseWriter as u}from"./tenancy.mjs";function d(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function f(e){let t=e?.errors??i,n=e?.maxRows??100;function r(e,i){async function a(r,a){if(!Number.isSafeInteger(r)||r<1||r>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).take(r);return a?a(o):o}async function o(r,a){if(!Number.isSafeInteger(r.numItems)||r.numItems<1||r.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).paginate(r);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>i||t==null?r(e,i):r(e,n(e,t)),matching:(t,n,a=!0)=>i||!a?r(e,i):r(e,e.withIndex(t,n)),otherwise:t=>i??t(e),resolve:()=>i??e.fullTableScan(),execute:a,paginate:o}}return e=>r(e)}function p(e){let t=_(e),n=g(e,t),{kCustomMutation:r}=t.builders;function i(t){return r(e.internalMutation,{args:{},input:n.serviceMutationInput(t)})}function a(...t){return r(e.mutation,{args:{},input:n.roleMutationInput(t)})}return{...h(e,t),roleMutation:a,authMutation:r(e.mutation,{args:{},input:n.mutationInput}),adminMutation:a(...e.adminRoles),serviceMutation:i,systemMutation:r(e.internalMutation,{args:{},input:n.systemMutationInput})}}function m(e){return h(e,_(e))}function h(e,t){let{kCustomQuery:n,kCustomAction:r}=t.builders;function i(r){return n(e.internalQuery,{args:{},input:t.serviceQueryInput(r)})}function a(...r){return n(e.query,{args:{},input:t.roleQueryInput(r)})}function o(...n){return r(e.action,{args:{},input:t.roleActionInput(n)})}return{include:t.include,authenticatedUser:t.authenticatedUser,roleQuery:a,roleAction:o,authQuery:n(e.query,{args:{},input:t.queryInput}),authAction:r(e.action,{args:{},input:t.actionInput}),adminQuery:a(...e.adminRoles),adminAction:o(...e.adminRoles),serviceQuery:i,systemQuery:n(e.internalQuery,{args:{},input:t.systemQueryInput}),systemAction:r(e.internalAction,{args:{},input:t.systemActionInput})}}function g(e,t){let{include:n,secureWriter:r,servicePrincipal:i,requireRole:a}=t,o=e.triggers,s=o?e=>o.wrapDB(e):e.wrapDB??(e=>e);async function c(e){let i=await t.authenticatedUser(e);return{ctx:{...r(s(e),i),include:n,...i},args:{}}}return{mutationInput:c,serviceMutationInput:e=>async t=>{let a=await i(e,t);return{ctx:{...r(s(t),a),...a,include:n},args:{}}},roleMutationInput:e=>async t=>{let n=await c(t);return a(n.ctx.actor.role,e),n},systemMutationInput:async e=>({ctx:{...s(e),include:n},args:{}})}}function _(n){let r=n.errors??i,d=e({argumentFailure:n.argumentFailure}),p=f({errors:r,maxRows:n.maxIncludedQueryRows});async function m(e){let t=await e.auth.getUserIdentity(),i=t?await n.getAuthUser(e,t):null;if(!t||!i)return r.throw({code:`UNAUTHENTICATED`});let a,o;if(n.resolveOrganization){let s=null;try{s=await n.resolveOrganization({ctx:e,identity:t,user:i})}catch{}if(!s)return r.throw({code:`FORBIDDEN`});a=s.organizationId,o=s.roleSlug}else{let e=y(t);if(!e.organizationId)return r.throw({code:`UNAUTHENTICATED`});a=e.organizationId,o=e.role}let s=n.mapRole(o);if(!s)return r.throw({code:`FORBIDDEN`});let c={identity:t,user:Object.freeze({id:i.id}),org:Object.freeze({organizationId:a,role:s}),role:s,actor:Object.freeze({userId:i.id,organizationId:a,role:s})};return Object.freeze({...c,tenant:n.security?.tenancy?.resolve?.(c)??a})}let h=n.security?{defaultPolicy:n.security.defaultPolicy??(n.security.tenancy?`deny`:`allow`)}:void 0;function g(e){let t=n.security;if(!t)return;let r=[];return t.tenancy&&r.push(c(e.tenant,t.tenancy.tables)),t.rules&&r.push(t.rules(e)),r.length===1?r[0]:s(...r)}function _(e,t,n=`authenticated`){let r=g(t),i=h?.defaultPolicy??`allow`,s=r?l({db:e.db},e.db,o(e.db,r,i),h):e.db;return{...e,db:a(e.db,s,{scope:{mode:n,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:r??{},defaultPolicy:i})}}function b(e,t){let n=g(t);return n?{...e,db:u({db:e.db},e.db,o(e.db,n,h?.defaultPolicy??`allow`),h)}:e}async function x(e,t){if(!n.verifyMembership)return null;try{let r=await n.verifyMembership({userId:e,organizationId:t});if(r&&r.organizationId===t)return r}catch{}return r.throw({code:`FORBIDDEN`})}function S(e,t){if(!t.includes(e))return r.throw({code:`FORBIDDEN`})}async function C(e){let t=await m(e);return{ctx:{..._(e,t),include:p,...t},args:{}}}async function w(e){let t=await m(e),i=await x(t.user.id,t.org.organizationId);if(!i)return{ctx:{...e,...t},args:{}};let a=n.mapRole(i.roleSlug);if(!a)return r.throw({code:`FORBIDDEN`});let o={identity:t.identity,user:t.user,org:Object.freeze({organizationId:i.organizationId,role:a}),role:a,actor:Object.freeze({userId:t.user.id,organizationId:i.organizationId,role:a})};return{ctx:{...e,...o,tenant:n.security?.tenancy?.resolve?.(o)??i.organizationId},args:{}}}async function T(e,n){let r=await e(n,t(n));if(!v().safeParse(r).success)throw Error(`A service principal must be an AuthBundle with user.id and tenant`);let i=Object.keys(r).filter(e=>e in n);if(i.length>0)throw Error(`A service principal cannot override native context fields: ${i.join(`, `)}`);return r}return{builders:d,include:p,authenticatedUser:m,secureWriter:b,servicePrincipal:T,requireRole:S,queryInput:C,actionInput:w,serviceQueryInput:e=>async t=>{let n=await T(e,t);return{ctx:{..._(t,n,`trusted`),...n,include:p},args:{}}},roleQueryInput:e=>async t=>{let n=await C(t);return S(n.ctx.actor.role,e),n},roleActionInput:e=>async t=>{let n=await w(t);return S(n.ctx.actor.role,e),n},systemQueryInput:async e=>({ctx:{...e,include:p,db:a(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}}),systemActionInput:async e=>({ctx:e,args:{}})}}const v=r(()=>n.object({user:n.object({id:n.string()}).strip(),tenant:n.string()}).strip());function y(e){let t=x(e.organization);return{organizationId:b(t?.organizationId)??b(e.org_id),role:b(t?.role)??b(e.role)}}function b(e){return typeof e==`string`?e:void 0}function x(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}export{p as createAuthFunctions,m as createAuthReaders,f as createInclude,d as defaultRoleMap};
2
2
  //# sourceMappingURL=auth.mjs.map
package/dist/auth.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"auth.mjs","names":[],"sources":["../src/auth.ts"],"sourcesContent":["import {\n\tzCustomAction,\n\tzCustomMutation,\n\tzCustomQuery,\n} from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: AuthBundle<Role>) => Rules<unknown, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\nexport type AuthFunctionsConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\tmutation: MutationBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/** Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx). */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (\n\t\tctx: GenericMutationCtx<DataModel>,\n\t) => GenericMutationCtx<DataModel>\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*, and\n\t * admin* constructor. system* constructors stay unwrapped (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' ||\n\t\tnormalized === 'writer' ||\n\t\tnormalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<\n\t\t\t\tDocumentByInfo<Table>,\n\t\t\t\tNamedIndex<Table, IndexName>\n\t\t\t>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(\n\t\tselect: (query: QueryInitializer<Table>) => Query<Table>,\n\t): Query<Table>\n\tresolve(): Query<Table>\n\texecute<Result = Awaited<ReturnType<Query<Table>['take']>>>(\n\t\tlimit: number,\n\t\ttransform?: (\n\t\t\tdata: Awaited<ReturnType<Query<Table>['take']>>,\n\t\t) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/zod-table for the boundary schemas.\n\t */\n\tpaginate<Item = DocumentByInfo<Table>>(\n\t\topts: PaginationOptions,\n\t\ttransform?: (\n\t\t\tpage: DocumentByInfo<Table>[],\n\t\t) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: {\n\terrors?: ErrorFactory\n\tmaxRows?: number\n}): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute: async (limit, transform) => {\n\t\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\t\treturn errors.throw({\n\t\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\t\treturn transform ? transform(data) : (data as never)\n\t\t\t},\n\t\t\tpaginate: async (opts, transform) => {\n\t\t\t\tif (\n\t\t\t\t\t!Number.isSafeInteger(opts.numItems) ||\n\t\t\t\t\topts.numItems < 1 ||\n\t\t\t\t\topts.numItems > maxRows\n\t\t\t\t) {\n\t\t\t\t\treturn errors.throw({\n\t\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\t\tif (!transform) return result as never\n\t\t\t\treturn { ...result, page: await transform(result.page) } as never\n\t\t\t},\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst wrapDB = config.triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) =>\n\t\t\t\t(config.triggers as Triggers<DataModel>).wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(\n\t\tctx: AnyAuthContext<DataModel>,\n\t): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst organization = identity.organization\n\t\t\tconst claimedOrganizationId =\n\t\t\t\torganization &&\n\t\t\t\ttypeof organization === 'object' &&\n\t\t\t\t'organizationId' in organization &&\n\t\t\t\ttypeof organization.organizationId === 'string'\n\t\t\t\t\t? organization.organizationId\n\t\t\t\t\t: typeof identity.org_id === 'string'\n\t\t\t\t\t\t? identity.org_id\n\t\t\t\t\t\t: null\n\t\t\tif (!claimedOrganizationId) {\n\t\t\t\treturn errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\t}\n\t\t\torganizationId = claimedOrganizationId\n\t\t\torganizationRole =\n\t\t\t\torganization &&\n\t\t\t\ttypeof organization === 'object' &&\n\t\t\t\t'role' in organization &&\n\t\t\t\ttypeof organization.role === 'string'\n\t\t\t\t\t? organization.role\n\t\t\t\t\t: typeof identity.role === 'string'\n\t\t\t\t\t\t? identity.role\n\t\t\t\t\t\t: undefined\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ??\n\t\t\t\t\t(config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<unknown, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<unknown, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(\n\t\t\t\tcreateTenantRules<DataModel>(bundle.tenant, security.tenancy.tables),\n\t\t\t)\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseReader({}, ctx.db, rules as never, securityConfig),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter({}, ctx.db, rules as never, securityConfig),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant:\n\t\t\t\t\tconfig.security?.tenancy?.resolve?.(verified) ??\n\t\t\t\t\tmembership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn zCustomQuery(config.query, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\treturn {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleMutation,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tauthAction: zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: actionInput,\n\t\t}),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tsystemQuery: zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...ctx, include }, args: {} }),\n\t\t}),\n\t\tsystemMutation: zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...wrapDB(ctx), include }, args: {} }),\n\t\t}),\n\t\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n}\n"],"mappings":"mQA+JA,SAAgB,EAAe,EAAuC,CACrE,IAAM,EAAa,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADI,IAAe,SAAiB,SAC7B,IAAe,UACrB,IAAe,UACf,IAAe,QACb,EACA,IACJ,CA+CA,SAAgB,EAAc,EAGlB,CACX,IAAM,EAAS,GAAS,QAAU,EAC5B,EAAU,GAAS,SAAW,IAEpC,SAAS,EACR,EACA,EACuB,CACvB,MAAO,CACN,MAAO,EAAO,IACb,GAAY,GAAiC,KAC1C,EAAO,EAAO,CAAQ,EACtB,EAAO,EAAO,EAAO,EAAO,CAAK,CAAC,EACtC,UAAW,EAAW,EAAY,EAAc,KAC/C,GAAY,CAAC,EACV,EAAO,EAAO,CAAQ,EACtB,EAAO,EAAO,EAAM,UAAU,EAAW,CAAU,CAAC,EACxD,UAAY,GAAW,GAAY,EAAO,CAAK,EAC/C,YAAe,GAAY,EAAM,cAAc,EAC/C,QAAS,MAAO,EAAO,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AG,MAAO,CAAW,CAAC,EACrE,aAAc,EAAgB,EAAO,SAAU,CAC9C,KAAM,CAAC,EACP,MAAO,CACR,CAAC,EACD,WAAY,EAAc,EAAO,OAAQ,CACxC,KAAM,CAAC,EACP,MAAO,CACR,CAAC,EACD,WAAY,EAAU,GAAG,EAAO,UAAU,EAC1C,cAAe,EAAa,GAAG,EAAO,UAAU,EAChD,YAAa,EAAW,GAAG,EAAO,UAAU,EAC5C,YAAa,EAAa,EAAO,cAAe,CAC/C,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,IAAK,CAAE,GAAG,EAAK,SAAQ,EAAG,KAAM,CAAC,CAAE,EAC7D,CAAC,EACD,eAAgB,EAAgB,EAAO,iBAAkB,CACxD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,IAAK,CAAE,GAAG,EAAO,CAAG,EAAG,SAAQ,EAAG,KAAM,CAAC,CAAE,EACrE,CAAC,EACD,aAAc,EAAc,EAAO,eAAgB,CAClD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,MAAK,KAAM,CAAC,CAAE,EACxC,CAAC,CACF,CACD"}
1
+ {"version":3,"file":"auth.mjs","names":["defaultRoleMap","normalized","roleSlug","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","core","createAuthCore","config","inputs","createMutationInputs","serviceMutation","kCustomMutation","principal","roleMutation","allowed","readers","createAuthReaders","serviceQuery","kCustomQuery","roleQuery","roleAction","kCustomAction","triggers","wrapDB","ctx","mutationInput","bundle","secureWriter","servicePrincipal","authenticated","requireRole","builders","kCustomFunctions","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","role","base","securityConfig","securityRules","security","sets","createTenantRules","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","wrapDatabaseWriter","verifiedMembership","membership","queryInput","actionInput","verified","rawFunctionArgs","principalContract","reserved","key","memoize","k","organization","claimRecord","claimString"],"sources":["../src/auth.ts"],"sourcesContent":["import { kCustomFunctions, rawFunctionArgs, type KCustomBuilder } from './registration'\nimport type { ArgumentFailurePolicy } from './modules/contracts/errors'\nimport { k } from './k/index'\nimport { memoize } from './modules/contracts/lazy'\nimport type { JSONValue } from 'convex/values'\nimport type {\n\tActionBuilder,\n\tDefaultFunctionArgs,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * The bundle handed to security rules. Service principals (serviceQuery /\n * serviceMutation) may carry extra host-supplied fields beside the standard\n * bundle; rules read them as unknown and narrow as needed.\n */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras\n\n/** Extra fields a host factory attaches to a service principal. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type ServiceExtras = Readonly<Record<string, unknown>>\n\n/**\n * A trusted host factory producing the principal a service function runs as.\n * `args` are the raw (unparsed) arguments of the invocation, so the host can\n * derive the scope (e.g. a client id) from them. Never accept the principal\n * itself from the caller — only derive it.\n */\nexport type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (\n\tctx: Ctx,\n\targs: DefaultFunctionArgs,\n) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: SecurityBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\n/**\n * Configuration for createAuthReaders: everything createAuthFunctions takes\n * except the mutation builders and trigger wrapping, so a module built from\n * it never has to import the trigger registry.\n */\nexport type AuthReadersConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/**\n\t * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).\n\t * The already-resolved, non-null identity is supplied as a second argument.\n\t * Callbacks may ignore it; using it can avoid a redundant identity lookup.\n\t */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t\tidentity: UserIdentity,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * How argument validation failures are thrown by every constructor. `'validation'`\n\t * (default) throws `KValidationError` (`ConvexError({ code: 'VALIDATION', issues })`);\n\t * `'declared'` throws `argumentErrors` `INVALID_ARGUMENTS`; a function returns the value to throw.\n\t */\n\targumentFailure?: ArgumentFailurePolicy\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*,\n\t * admin*, and service* constructor. system* constructors stay unwrapped\n\t * (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** A reader config plus the mutation builders and trigger wrapping. */\nexport type AuthFunctionsConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = AuthReadersConfig<DataModel, Role> & {\n\tmutation: MutationBuilder<DataModel, 'public'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * The auth-aware constructors, registered through `k` schemas and native validators\n * (src/registration.ts). Keep native contexts symbolic in published declarations: inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: KCustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: KCustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: KCustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\t/**\n\t * Internal query running as a host-supplied service principal with the\n\t * app's security rules fully applied. No identity lookup; the trusted\n\t * host's factory is the only principal source.\n\t */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => ServiceQuery<DataModel, Role, Extra>\n\t/** Internal mutation running as a service principal: triggers first, then the secured writer. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => ServiceMutation<DataModel, Role, Extra>\n\tsystemQuery: KCustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: KCustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: KCustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** The read-only constructors: everything AuthFunctions has except mutations. */\nexport type AuthReaders<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>\n\nexport type ServiceQuery<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = KCustomBuilder<\n\t'query',\n\t{},\n\tGenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericQueryCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\nexport type ServiceMutation<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = KCustomBuilder<\n\t'mutation',\n\t{},\n\tGenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericMutationCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst core = createAuthCore(config)\n\tconst inputs = createMutationInputs(config, core)\n\tconst { kCustomMutation } = core.builders\n\n\t/** Internal mutation running as the host-derived service principal: triggers, then rules. */\n\tfunction serviceMutation<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t): ServiceMutation<DataModel, Role, Extra> {\n\t\treturn kCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: inputs.serviceMutationInput(principal),\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn kCustomMutation(config.mutation, { args: {}, input: inputs.roleMutationInput(allowed) })\n\t}\n\n\treturn {\n\t\t...readers(config, core),\n\t\troleMutation,\n\t\tauthMutation: kCustomMutation(config.mutation, { args: {}, input: inputs.mutationInput }),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tserviceMutation,\n\t\tsystemMutation: kCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: inputs.systemMutationInput,\n\t\t}),\n\t}\n}\n\n/**\n * Builds the read-only constructors (queries and actions) from the same\n * policy as createAuthFunctions, without mutation builders or triggers.\n * Identity, tenancy, rules, role gates, membership checks and errors are the\n * same implementation, so a module built from these never imports the\n * trigger registry or the domains it pulls in.\n */\nexport function createAuthReaders<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role> {\n\treturn readers(config, createAuthCore(config))\n}\n\ntype AuthCore<DataModel extends GenericDataModel, Role extends string> = ReturnType<\n\ttypeof createAuthCore<DataModel, Role>\n>\n\n/** Assembly of the read-only constructors. */\nfunction readers<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n\tcore: AuthCore<DataModel, Role>,\n): AuthReaders<DataModel, Role> {\n\tconst { kCustomQuery, kCustomAction } = core.builders\n\t/** Internal query running as the host-derived service principal, rules applied. */\n\tfunction serviceQuery<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t): ServiceQuery<DataModel, Role, Extra> {\n\t\treturn kCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: core.serviceQueryInput(principal),\n\t\t})\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn kCustomQuery(config.query, { args: {}, input: core.roleQueryInput(allowed) })\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn kCustomAction(config.action, { args: {}, input: core.roleActionInput(allowed) })\n\t}\n\n\treturn {\n\t\tinclude: core.include,\n\t\tauthenticatedUser: core.authenticatedUser,\n\t\troleQuery,\n\t\troleAction,\n\t\tauthQuery: kCustomQuery(config.query, { args: {}, input: core.queryInput }),\n\t\tauthAction: kCustomAction(config.action, { args: {}, input: core.actionInput }),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tserviceQuery,\n\t\tsystemQuery: kCustomQuery(config.internalQuery, { args: {}, input: core.systemQueryInput }),\n\t\tsystemAction: kCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: core.systemActionInput,\n\t\t}),\n\t}\n}\n\n/** The mutation customizations createAuthFunctions adds to the readers. */\nfunction createMutationInputs<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthFunctionsConfig<DataModel, Role>,\n\tcore: AuthCore<DataModel, Role>,\n) {\n\tconst { include, secureWriter, servicePrincipal, requireRole } = core\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await core.authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\treturn {\n\t\tmutationInput,\n\t\tserviceMutationInput:\n\t\t\t<Extra extends Record<string, unknown>>(\n\t\t\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t\t\t) =>\n\t\t\tasync (ctx: GenericMutationCtx<DataModel>) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\troleMutationInput: (allowed: readonly Role[]) => async (ctx: GenericMutationCtx<DataModel>) => {\n\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\tsystemMutationInput: async (ctx: GenericMutationCtx<DataModel>) => ({\n\t\t\tctx: { ...wrapDB(ctx), include },\n\t\t\targs: {},\n\t\t}),\n\t}\n}\n\n/** Shared implementation behind the constructors: everything but the registration builders. */\nfunction createAuthCore<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst builders = kCustomFunctions({ argumentFailure: config.argumentFailure })\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx, identity) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims(identity)\n\t\t\tif (!claims.organizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claims.organizationId\n\t\t\torganizationRole = claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t\tmode: 'authenticated' | 'trusted' = 'authenticated',\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode,\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function servicePrincipal<\n\t\tCtx extends GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n\t\tExtra extends Record<string, unknown>,\n\t>(principal: ServicePrincipal<Ctx, Role, Extra>, ctx: Ctx) {\n\t\tconst bundle = await principal(ctx, rawFunctionArgs(ctx))\n\t\tif (!principalContract().safeParse(bundle).success) {\n\t\t\tthrow new Error('A service principal must be an AuthBundle with user.id and tenant')\n\t\t}\n\t\t// Extras are spread onto the secured ctx; a host field named like a native\n\t\t// handle (db, auth, scheduler, ...) would silently replace the secured one.\n\t\tconst reserved = Object.keys(bundle).filter((key) => key in ctx)\n\t\tif (reserved.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`A service principal cannot override native context fields: ${reserved.join(', ')}`,\n\t\t\t)\n\t\t}\n\t\treturn bundle\n\t}\n\n\treturn {\n\t\tbuilders,\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\tsecureWriter,\n\t\tservicePrincipal,\n\t\trequireRole,\n\t\tqueryInput,\n\t\tactionInput,\n\t\tserviceQueryInput:\n\t\t\t<Extra extends Record<string, unknown>>(\n\t\t\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t\t\t) =>\n\t\t\tasync (ctx: GenericQueryCtx<DataModel>) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureReader(ctx, bundle, 'trusted'), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\troleQueryInput: (allowed: readonly Role[]) => async (ctx: GenericQueryCtx<DataModel>) => {\n\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\troleActionInput: (allowed: readonly Role[]) => async (ctx: GenericActionCtx<DataModel>) => {\n\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\tsystemQueryInput: async (ctx: GenericQueryCtx<DataModel>) => ({\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\tinclude,\n\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\tscope: {\n\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\trole: null,\n\t\t\t\t\t},\n\t\t\t\t\trules: {},\n\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t}),\n\t\t\t},\n\t\t\targs: {},\n\t\t}),\n\t\tsystemActionInput: async (ctx: GenericActionCtx<DataModel>) => ({ ctx, args: {} }),\n\t}\n}\n\n/** The minimum a host factory must return; unknown keys pass, the rest of the bundle is the host's contract. */\nconst principalContract = memoize(() =>\n\tk.object({ user: k.object({ id: k.string() }).strip(), tenant: k.string() }).strip(),\n)\n\n/** The organization authority an identity's claims carry; each claim is undefined when malformed. */\nfunction organizationClaims(identity: UserIdentity) {\n\tconst organization = claimRecord(identity.organization)\n\treturn {\n\t\torganizationId: claimString(organization?.organizationId) ?? claimString(identity.org_id),\n\t\trole: claimString(organization?.role) ?? claimString(identity.role),\n\t}\n}\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- Identity claims are undecoded JSON narrowed by representation. */\nfunction claimString(value: JSONValue | undefined): string | undefined {\n\treturn typeof value === 'string' ? value : undefined\n}\n\nfunction claimRecord(value: JSONValue | undefined): { [key: string]: JSONValue } | undefined {\n\treturn value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined\n}\n/* oxlint-enable anti-slop/no-runtime-typeof */\n"],"mappings":"A,4ZA6MA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD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KACd,OAAQ,KACR,KAAM,IACP,EACA,MAAO,CAAC,EACR,cAAe,OAChB,CAAC,CACF,EACA,KAAM,CAAC,CACR,GACA,kBAAmB,KAAO,KAAsC,CAAE,MAAK,KAAM,CAAC,CAAE,EACjF,CACD,CAGA,MAAMwC,EAAoBG,MACzBC,EAAE,OAAO,CAAE,KAAMA,EAAE,OAAO,CAAE,GAAIA,EAAE,OAAO,CAAE,CAAC,CAAC,CAAC,MAAM,EAAG,OAAQA,EAAE,OAAO,CAAE,CAAC,CAAC,CAAC,MAAM,CACpF,EAGA,SAAS3B,EAAmB,EAAwB,CACnD,IAAM4B,EAAeC,EAAYnC,EAAS,YAAY,EACtD,MAAO,CACN,eAAgBoC,EAAYF,GAAc,cAAc,GAAKE,EAAYpC,EAAS,MAAM,EACxF,KAAMoC,EAAYF,GAAc,IAAI,GAAKE,EAAYpC,EAAS,IAAI,CACnE,CACD,CAGA,SAASoC,EAAY,EAAkD,CACtE,OAAO,OAAOxE,GAAU,SAAWA,EAAQ,IAAA,EAC5C,CAEA,SAASuE,EAAY,EAAwE,CAC5F,OAAyB,OAAOvE,GAAU,UAAnCA,GAA+C,CAAC,MAAM,QAAQA,CAAK,EAAIA,EAAQ,IAAA,EACvF,C"}
@@ -1,15 +1,14 @@
1
1
  import { audit_d_exports } from "../audit.mjs";
2
- import { constants_d_exports } from "../constants.mjs";
3
- import { validators_d_exports } from "../validators.mjs";
4
- import { workflow_steps_d_exports } from "../workflow_steps.mjs";
5
2
  import { client_d_exports } from "../client.mjs";
3
+ import { constants_d_exports } from "../constants.mjs";
6
4
  import { decisions_d_exports } from "../decisions.mjs";
7
5
  import { functions_d_exports } from "../functions.mjs";
8
6
  import { health_d_exports } from "../health.mjs";
9
7
  import { requests_d_exports } from "../requests.mjs";
8
+ import { validators_d_exports } from "../validators.mjs";
10
9
  import { workflow_d_exports } from "../workflow.mjs";
10
+ import { workflow_steps_d_exports } from "../workflow_steps.mjs";
11
11
  import { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
12
- //#region src/components/approvals/_generated/api.d.ts
13
12
  declare const fullApi: ApiFromModules<{
14
13
  audit: typeof audit_d_exports;
15
14
  client: typeof client_d_exports;
@@ -30,7 +29,7 @@ declare const fullApi: ApiFromModules<{
30
29
  * const myFunctionReference = api.myModule.myFunction;
31
30
  * ```
32
31
  */
33
- declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
32
+ export declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
34
33
  /**
35
34
  * A utility for referencing Convex functions in your app's internal API.
36
35
  *
@@ -39,11 +38,10 @@ declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
39
38
  * const myFunctionReference = internal.myModule.myFunction;
40
39
  * ```
41
40
  */
42
- declare const internal: FilterApi<typeof fullApi, FunctionReference<any, "internal">>;
43
- declare const components: {
41
+ export declare const internal: FilterApi<typeof fullApi, FunctionReference<any, "internal">>;
42
+ export declare const components: {
44
43
  workflow: import("@convex-dev/workflow/_generated/component.js").ComponentApi<"workflow">;
45
44
  auditLog: import("convex-audit-log/_generated/component.js").ComponentApi<"auditLog">;
46
45
  };
47
- //#endregion
48
- export { api, components, internal };
46
+ export {};
49
47
  //# sourceMappingURL=api.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.mjs","names":[],"sources":["../../../../src/components/approvals/_generated/api.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated `api` utility.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type * as audit from \"../audit.js\";\nimport type * as client from \"../client.js\";\nimport type * as constants from \"../constants.js\";\nimport type * as decisions from \"../decisions.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as health from \"../health.js\";\nimport type * as requests from \"../requests.js\";\nimport type * as validators from \"../validators.js\";\nimport type * as workflow from \"../workflow.js\";\nimport type * as workflow_steps from \"../workflow_steps.js\";\n\nimport type {\n ApiFromModules,\n FilterApi,\n FunctionReference,\n} from \"convex/server\";\nimport { anyApi, componentsGeneric } from \"convex/server\";\n\nconst fullApi: ApiFromModules<{\n audit: typeof audit;\n client: typeof client;\n constants: typeof constants;\n decisions: typeof decisions;\n functions: typeof functions;\n health: typeof health;\n requests: typeof requests;\n validators: typeof validators;\n workflow: typeof workflow;\n workflow_steps: typeof workflow_steps;\n}> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's public API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = api.myModule.myFunction;\n * ```\n */\nexport const api: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"public\">\n> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's internal API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = internal.myModule.myFunction;\n * ```\n */\nexport const internal: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"internal\">\n> = anyApi as any;\n\nexport const components = componentsGeneric() as unknown as {\n workflow: import(\"@convex-dev/workflow/_generated/component.js\").ComponentApi<\"workflow\">;\n auditLog: import(\"convex-audit-log/_generated/component.js\").ComponentApi<\"auditLog\">;\n};\n"],"mappings":"8DAiDA,MAAa,EAGT,EAUS,EAGT,EAES,EAAa,EAAkB"}
1
+ {"version":3,"file":"api.mjs","names":["api","anyApi","internal","components","componentsGeneric"],"sources":["../../../../src/components/approvals/_generated/api.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated `api` utility.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type * as audit from \"../audit.js\";\nimport type * as client from \"../client.js\";\nimport type * as constants from \"../constants.js\";\nimport type * as decisions from \"../decisions.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as health from \"../health.js\";\nimport type * as requests from \"../requests.js\";\nimport type * as validators from \"../validators.js\";\nimport type * as workflow from \"../workflow.js\";\nimport type * as workflow_steps from \"../workflow_steps.js\";\n\nimport type {\n ApiFromModules,\n FilterApi,\n FunctionReference,\n} from \"convex/server\";\nimport { anyApi, componentsGeneric } from \"convex/server\";\n\nconst fullApi: ApiFromModules<{\n audit: typeof audit;\n client: typeof client;\n constants: typeof constants;\n decisions: typeof decisions;\n functions: typeof functions;\n health: typeof health;\n requests: typeof requests;\n validators: typeof validators;\n workflow: typeof workflow;\n workflow_steps: typeof workflow_steps;\n}> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's public API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = api.myModule.myFunction;\n * ```\n */\nexport const api: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"public\">\n> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's internal API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = internal.myModule.myFunction;\n * ```\n */\nexport const internal: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"internal\">\n> = anyApi as any;\n\nexport const components = componentsGeneric() as unknown as {\n workflow: import(\"@convex-dev/workflow/_generated/component.js\").ComponentApi<\"workflow\">;\n auditLog: import(\"convex-audit-log/_generated/component.js\").ComponentApi<\"auditLog\">;\n};\n"],"mappings":"A,8DAiDA,MAAaA,EAGTC,EAUSC,EAGTD,EAESE,EAAaC,EAAkB,E"}
@@ -1,5 +1,4 @@
1
1
  import { FunctionReference } from "convex/server";
2
- //#region src/components/approvals/_generated/component.d.ts
3
2
  /**
4
3
  * A utility for referencing a Convex component's exposed API.
5
4
  *
@@ -11,7 +10,7 @@ import { FunctionReference } from "convex/server";
11
10
  * }
12
11
  * ```
13
12
  */
14
- type ComponentApi<Name extends string | undefined = string | undefined> = {
13
+ export type ComponentApi<Name extends string | undefined = string | undefined> = {
15
14
  audit: {
16
15
  cleanup: FunctionReference<"mutation", "internal", {
17
16
  batchSize: number;
@@ -299,6 +298,4 @@ type ComponentApi<Name extends string | undefined = string | undefined> = {
299
298
  }, Name>;
300
299
  };
301
300
  };
302
- //#endregion
303
- export { ComponentApi };
304
301
  //# sourceMappingURL=component.d.mts.map
@@ -1,17 +1,16 @@
1
1
  import _default from "../schema.js";
2
- import { DataModelFromSchemaDefinition, DocumentByName, SystemTableNames, TableNamesInDataModel } from "convex/server";
3
2
  import { GenericId } from "convex/values";
4
- //#region src/components/approvals/_generated/dataModel.d.ts
3
+ import { DataModelFromSchemaDefinition, DocumentByName, SystemTableNames, TableNamesInDataModel } from "convex/server";
5
4
  /**
6
5
  * The names of all of your Convex tables.
7
6
  */
8
- type TableNames = TableNamesInDataModel<DataModel>;
7
+ export type TableNames = TableNamesInDataModel<DataModel>;
9
8
  /**
10
9
  * The type of a document stored in Convex.
11
10
  *
12
11
  * @typeParam TableName - A string literal type of the table name (like "users").
13
12
  */
14
- type Doc<TableName extends TableNames> = DocumentByName<DataModel, TableName>;
13
+ export type Doc<TableName extends TableNames> = DocumentByName<DataModel, TableName>;
15
14
  /**
16
15
  * An identifier for a document in Convex.
17
16
  *
@@ -25,7 +24,7 @@ type Doc<TableName extends TableNames> = DocumentByName<DataModel, TableName>;
25
24
  *
26
25
  * @typeParam TableName - A string literal type of the table name (like "users").
27
26
  */
28
- type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
27
+ export type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
29
28
  /**
30
29
  * A type describing your Convex data model.
31
30
  *
@@ -35,7 +34,5 @@ type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
35
34
  * This type is used to parameterize methods like `queryGeneric` and
36
35
  * `mutationGeneric` to make them type-safe.
37
36
  */
38
- type DataModel = DataModelFromSchemaDefinition<typeof _default>;
39
- //#endregion
40
- export { DataModel, Doc, Id, TableNames };
37
+ export type DataModel = DataModelFromSchemaDefinition<typeof _default>;
41
38
  //# sourceMappingURL=dataModel.d.mts.map
@@ -1,6 +1,5 @@
1
1
  import { DataModel } from "./dataModel.mjs";
2
2
  import { ActionBuilder, GenericActionCtx, GenericDatabaseReader, GenericDatabaseWriter, GenericMutationCtx, GenericQueryCtx, HttpActionBuilder, MutationBuilder, QueryBuilder } from "convex/server";
3
- //#region src/components/approvals/_generated/server.d.ts
4
3
  /**
5
4
  * Define a query in this Convex app's public API.
6
5
  *
@@ -9,7 +8,7 @@ import { ActionBuilder, GenericActionCtx, GenericDatabaseReader, GenericDatabase
9
8
  * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
10
9
  * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
11
10
  */
12
- declare const query: QueryBuilder<DataModel, "public">;
11
+ export declare const query: QueryBuilder<DataModel, "public">;
13
12
  /**
14
13
  * Define a query that is only accessible from other Convex functions (but not from the client).
15
14
  *
@@ -18,7 +17,7 @@ declare const query: QueryBuilder<DataModel, "public">;
18
17
  * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
19
18
  * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
20
19
  */
21
- declare const internalQuery: QueryBuilder<DataModel, "internal">;
20
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
22
21
  /**
23
22
  * Define a mutation in this Convex app's public API.
24
23
  *
@@ -27,7 +26,7 @@ declare const internalQuery: QueryBuilder<DataModel, "internal">;
27
26
  * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
28
27
  * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
29
28
  */
30
- declare const mutation: MutationBuilder<DataModel, "public">;
29
+ export declare const mutation: MutationBuilder<DataModel, "public">;
31
30
  /**
32
31
  * Define a mutation that is only accessible from other Convex functions (but not from the client).
33
32
  *
@@ -36,7 +35,7 @@ declare const mutation: MutationBuilder<DataModel, "public">;
36
35
  * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
37
36
  * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
38
37
  */
39
- declare const internalMutation: MutationBuilder<DataModel, "internal">;
38
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
40
39
  /**
41
40
  * Define an action in this Convex app's public API.
42
41
  *
@@ -48,14 +47,14 @@ declare const internalMutation: MutationBuilder<DataModel, "internal">;
48
47
  * @param func - The action. It receives an {@link ActionCtx} as its first argument.
49
48
  * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
50
49
  */
51
- declare const action: ActionBuilder<DataModel, "public">;
50
+ export declare const action: ActionBuilder<DataModel, "public">;
52
51
  /**
53
52
  * Define an action that is only accessible from other Convex functions (but not from the client).
54
53
  *
55
54
  * @param func - The function. It receives an {@link ActionCtx} as its first argument.
56
55
  * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
57
56
  */
58
- declare const internalAction: ActionBuilder<DataModel, "internal">;
57
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
59
58
  /**
60
59
  * Define an HTTP action.
61
60
  *
@@ -67,7 +66,7 @@ declare const internalAction: ActionBuilder<DataModel, "internal">;
67
66
  * and a Fetch API `Request` object as its second.
68
67
  * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
69
68
  */
70
- declare const httpAction: HttpActionBuilder;
69
+ export declare const httpAction: HttpActionBuilder;
71
70
  /**
72
71
  * A set of services for use within Convex query functions.
73
72
  *
@@ -76,7 +75,7 @@ declare const httpAction: HttpActionBuilder;
76
75
  *
77
76
  * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
78
77
  */
79
- type QueryCtx = GenericQueryCtx<DataModel>;
78
+ export type QueryCtx = GenericQueryCtx<DataModel>;
80
79
  /**
81
80
  * A set of services for use within Convex mutation functions.
82
81
  *
@@ -85,14 +84,14 @@ type QueryCtx = GenericQueryCtx<DataModel>;
85
84
  *
86
85
  * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
87
86
  */
88
- type MutationCtx = GenericMutationCtx<DataModel>;
87
+ export type MutationCtx = GenericMutationCtx<DataModel>;
89
88
  /**
90
89
  * A set of services for use within Convex action functions.
91
90
  *
92
91
  * The action context is passed as the first argument to any Convex action
93
92
  * function run on the server.
94
93
  */
95
- type ActionCtx = GenericActionCtx<DataModel>;
94
+ export type ActionCtx = GenericActionCtx<DataModel>;
96
95
  /**
97
96
  * An interface to read from the database within Convex query functions.
98
97
  *
@@ -100,7 +99,7 @@ type ActionCtx = GenericActionCtx<DataModel>;
100
99
  * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
101
100
  * building a query.
102
101
  */
103
- type DatabaseReader = GenericDatabaseReader<DataModel>;
102
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
104
103
  /**
105
104
  * An interface to read from and write to the database within Convex mutation
106
105
  * functions.
@@ -110,7 +109,5 @@ type DatabaseReader = GenericDatabaseReader<DataModel>;
110
109
  * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
111
110
  * for the guarantees Convex provides your functions.
112
111
  */
113
- type DatabaseWriter = GenericDatabaseWriter<DataModel>;
114
- //#endregion
115
- export { ActionCtx, DatabaseReader, DatabaseWriter, MutationCtx, QueryCtx, action, httpAction, internalAction, internalMutation, internalQuery, mutation, query };
112
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
116
113
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../../../../src/components/approvals/_generated/server.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated utilities for implementing server-side Convex query and mutation functions.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type {\n ActionBuilder,\n HttpActionBuilder,\n MutationBuilder,\n QueryBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n GenericDatabaseReader,\n GenericDatabaseWriter,\n} from \"convex/server\";\nimport {\n actionGeneric,\n httpActionGeneric,\n queryGeneric,\n mutationGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"convex/server\";\nimport type { DataModel } from \"./dataModel.js\";\n\n/**\n * Define a query in this Convex app's public API.\n *\n * This function will be allowed to read your Convex database and will be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const query: QueryBuilder<DataModel, \"public\"> = queryGeneric;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to read from your Convex database. It will not be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const internalQuery: QueryBuilder<DataModel, \"internal\"> =\n internalQueryGeneric;\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * This function will be allowed to modify your Convex database and will be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const mutation: MutationBuilder<DataModel, \"public\"> = mutationGeneric;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to modify your Convex database. It will not be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const internalMutation: MutationBuilder<DataModel, \"internal\"> =\n internalMutationGeneric;\n\n/**\n * Define an action in this Convex app's public API.\n *\n * An action is a function which can execute any JavaScript code, including non-deterministic\n * code and code with side-effects, like calling third-party services.\n * They can be run in Convex's JavaScript environment or in Node.js using the \"use node\" directive.\n * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.\n *\n * @param func - The action. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped action. Include this as an `export` to name it and make it accessible.\n */\nexport const action: ActionBuilder<DataModel, \"public\"> = actionGeneric;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n */\nexport const internalAction: ActionBuilder<DataModel, \"internal\"> =\n internalActionGeneric;\n\n/**\n * Define an HTTP action.\n *\n * The wrapped function will be used to respond to HTTP requests received\n * by a Convex deployment if the requests matches the path and method where\n * this action is routed. Be sure to route your httpAction in `convex/http.js`.\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument\n * and a Fetch API `Request` object as its second.\n * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.\n */\nexport const httpAction: HttpActionBuilder = httpActionGeneric;\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type QueryCtx = GenericQueryCtx<DataModel>;\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type MutationCtx = GenericMutationCtx<DataModel>;\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * function run on the server.\n */\nexport type ActionCtx = GenericActionCtx<DataModel>;\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * The two entry points are {@link DatabaseReader.get}, which fetches a single\n * document by its {@link Id}, or {@link DatabaseReader.query}, which starts\n * building a query.\n */\nexport type DatabaseReader = GenericDatabaseReader<DataModel>;\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n */\nexport type DatabaseWriter = GenericDatabaseWriter<DataModel>;\n"],"mappings":"8LAwCA,MAAa,EAA2C,EAU3C,EACX,EAUW,EAAiD,EAUjD,EACX,EAaW,EAA6C,EAQ7C,EACX,EAaW,EAAgC"}
1
+ {"version":3,"file":"server.mjs","names":["query","queryGeneric","internalQuery","internalQueryGeneric","mutation","mutationGeneric","internalMutation","internalMutationGeneric","action","actionGeneric","internalAction","internalActionGeneric","httpAction","httpActionGeneric"],"sources":["../../../../src/components/approvals/_generated/server.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated utilities for implementing server-side Convex query and mutation functions.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type {\n ActionBuilder,\n HttpActionBuilder,\n MutationBuilder,\n QueryBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n GenericDatabaseReader,\n GenericDatabaseWriter,\n} from \"convex/server\";\nimport {\n actionGeneric,\n httpActionGeneric,\n queryGeneric,\n mutationGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"convex/server\";\nimport type { DataModel } from \"./dataModel.js\";\n\n/**\n * Define a query in this Convex app's public API.\n *\n * This function will be allowed to read your Convex database and will be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const query: QueryBuilder<DataModel, \"public\"> = queryGeneric;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to read from your Convex database. It will not be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const internalQuery: QueryBuilder<DataModel, \"internal\"> =\n internalQueryGeneric;\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * This function will be allowed to modify your Convex database and will be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const mutation: MutationBuilder<DataModel, \"public\"> = mutationGeneric;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to modify your Convex database. It will not be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const internalMutation: MutationBuilder<DataModel, \"internal\"> =\n internalMutationGeneric;\n\n/**\n * Define an action in this Convex app's public API.\n *\n * An action is a function which can execute any JavaScript code, including non-deterministic\n * code and code with side-effects, like calling third-party services.\n * They can be run in Convex's JavaScript environment or in Node.js using the \"use node\" directive.\n * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.\n *\n * @param func - The action. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped action. Include this as an `export` to name it and make it accessible.\n */\nexport const action: ActionBuilder<DataModel, \"public\"> = actionGeneric;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n */\nexport const internalAction: ActionBuilder<DataModel, \"internal\"> =\n internalActionGeneric;\n\n/**\n * Define an HTTP action.\n *\n * The wrapped function will be used to respond to HTTP requests received\n * by a Convex deployment if the requests matches the path and method where\n * this action is routed. Be sure to route your httpAction in `convex/http.js`.\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument\n * and a Fetch API `Request` object as its second.\n * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.\n */\nexport const httpAction: HttpActionBuilder = httpActionGeneric;\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type QueryCtx = GenericQueryCtx<DataModel>;\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type MutationCtx = GenericMutationCtx<DataModel>;\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * function run on the server.\n */\nexport type ActionCtx = GenericActionCtx<DataModel>;\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * The two entry points are {@link DatabaseReader.get}, which fetches a single\n * document by its {@link Id}, or {@link DatabaseReader.query}, which starts\n * building a query.\n */\nexport type DatabaseReader = GenericDatabaseReader<DataModel>;\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n */\nexport type DatabaseWriter = GenericDatabaseWriter<DataModel>;\n"],"mappings":"A,8LAwCA,MAAaA,EAA2CC,EAU3CC,EACXC,EAUWC,EAAiDC,EAUjDC,EACXC,EAaWC,EAA6CC,EAQ7CC,EACXC,EAaWC,EAAgCC,E"}
@@ -3,7 +3,7 @@ import { AuditEventInput, AuditLog } from "convex-audit-log";
3
3
  declare namespace audit_d_exports {
4
4
  export { ApprovalAuditProjection, ApprovalAuditTransition, approvalAudit, approvalAuditEvent, cleanup, history, logApprovalTransition };
5
5
  }
6
- type ApprovalAuditTransition = Readonly<{
6
+ export type ApprovalAuditTransition = Readonly<{
7
7
  action: string;
8
8
  actorRef?: string;
9
9
  runId: string;
@@ -12,14 +12,14 @@ type ApprovalAuditTransition = Readonly<{
12
12
  transition: string;
13
13
  severity?: AuditEventInput['severity'];
14
14
  }>;
15
- type ApprovalAuditProjection = Readonly<{
15
+ export type ApprovalAuditProjection = Readonly<{
16
16
  action: string;
17
17
  actorRef?: string;
18
18
  correlationKey: string;
19
19
  transition: string;
20
20
  }>;
21
- declare const approvalAudit: AuditLog;
22
- declare const history: import("convex/server").RegisteredQuery<"public", {
21
+ export declare const approvalAudit: AuditLog;
22
+ export declare const history: import("convex/server").RegisteredQuery<"public", {
23
23
  limit?: number | undefined;
24
24
  resourceRef: string;
25
25
  resourceType: string;
@@ -29,12 +29,11 @@ declare const history: import("convex/server").RegisteredQuery<"public", {
29
29
  correlationKey: string;
30
30
  transition: string;
31
31
  }>[]>>;
32
- declare const cleanup: import("convex/server").RegisteredMutation<"public", {
32
+ export declare const cleanup: import("convex/server").RegisteredMutation<"public", {
33
33
  batchSize: number;
34
34
  olderThanDays: number;
35
35
  }, Promise<number>>;
36
- declare function approvalAuditEvent(input: ApprovalAuditTransition): AuditEventInput;
37
- declare function logApprovalTransition(ctx: MutationCtx, input: ApprovalAuditTransition): Promise<void>;
38
- //#endregion
39
- export { ApprovalAuditProjection, ApprovalAuditTransition, approvalAudit, approvalAuditEvent, audit_d_exports, cleanup, history, logApprovalTransition };
36
+ export declare function approvalAuditEvent(input: ApprovalAuditTransition): AuditEventInput;
37
+ export declare function logApprovalTransition(ctx: MutationCtx, input: ApprovalAuditTransition): Promise<void>;
38
+ export { audit_d_exports };
40
39
  //# sourceMappingURL=audit.d.mts.map
@@ -1,2 +1,2 @@
1
- import{components as e}from"./_generated/api.mjs";import{mutation as t,query as n}from"./_generated/server.mjs";import{APPROVAL_AUDIT_RETENTION_CATEGORY as r,MAX_APPROVAL_AUDIT_RETENTION_DAYS as i}from"./constants.mjs";import{v as a}from"convex/values";import{AuditLog as o}from"convex-audit-log";const s=new o(e.auditLog,{samplingEnabled:!1}),c=n({args:{resourceType:a.string(),resourceRef:a.string(),limit:a.optional(a.number())},returns:a.array(a.object({action:a.string(),actorRef:a.optional(a.string()),correlationKey:a.string(),transition:a.string()})),handler:async(e,t)=>{let n=Math.max(1,Math.min(Math.trunc(t.limit??100),100)),r=await s.queryByResource(e,{resourceType:t.resourceType,resourceId:t.resourceRef,limit:n}),i=new Map;for(let e of r){let t=p(e);t&&i.set(t.correlationKey,t)}return[...i.values()]}}),l=t({args:{olderThanDays:a.number(),batchSize:a.number()},returns:a.number(),handler:(e,t)=>{let n=f(t.olderThanDays,1,i,`olderThanDays`),a=f(t.batchSize,1,100,`batchSize`);return s.cleanup(e,{olderThanDays:n,batchSize:a,retentionCategory:r})}});function u(e){return{action:e.action,...e.actorRef===void 0?{}:{actorId:e.actorRef},resourceType:e.resourceType,resourceId:e.resourceRef,severity:e.severity??`info`,tags:[`approvals`],retentionCategory:r,metadata:{correlationKey:`${e.runId}:${e.transition}`,runId:e.runId,transition:e.transition}}}async function d(e,t){await s.log(e,u(t))}function f(e,t,n,r){if(!Number.isInteger(e)||e<t||e>n)throw Error(`${r} must be an integer between ${t} and ${n}`);return e}function p(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.metadata;if(!n||typeof n!=`object`)return null;let r=n;return typeof t.action!=`string`||typeof r.correlationKey!=`string`||typeof r.transition!=`string`?null:{action:t.action,...typeof t.actorId==`string`?{actorRef:t.actorId}:{},correlationKey:r.correlationKey,transition:r.transition}}export{s as approvalAudit,u as approvalAuditEvent,l as cleanup,c as history,d as logApprovalTransition};
1
+ import{components as e}from"./_generated/api.mjs";import{mutation as t,query as n}from"./_generated/server.mjs";import{APPROVAL_AUDIT_RETENTION_CATEGORY as r,MAX_APPROVAL_AUDIT_RETENTION_DAYS as i}from"./constants.mjs";import{approvalAuditEventProjection as a,approvalOptionalString as o}from"./validators.mjs";import{v as s}from"convex/values";import{AuditLog as c}from"convex-audit-log";const l=new c(e.auditLog,{samplingEnabled:!1}),u=n({args:{resourceType:s.string(),resourceRef:s.string(),limit:s.optional(s.number())},returns:s.array(s.object({action:s.string(),actorRef:s.optional(s.string()),correlationKey:s.string(),transition:s.string()})),handler:async(e,t)=>{let n=Math.max(1,Math.min(Math.trunc(t.limit??100),100)),r=await l.queryByResource(e,{resourceType:t.resourceType,resourceId:t.resourceRef,limit:n}),i=/* @__PURE__ */ new Map;for(let e of r){let t=h(e);t&&i.set(t.correlationKey,t)}return[...i.values()]}}),d=t({args:{olderThanDays:s.number(),batchSize:s.number()},returns:s.number(),handler:(e,t)=>{let n=m(t.olderThanDays,1,i,`olderThanDays`),a=m(t.batchSize,1,100,`batchSize`);return l.cleanup(e,{olderThanDays:n,batchSize:a,retentionCategory:r})}});function f(e){return{action:e.action,actorId:e.actorRef,resourceType:e.resourceType,resourceId:e.resourceRef,severity:e.severity??`info`,tags:[`approvals`],retentionCategory:r,metadata:{correlationKey:`${e.runId}:${e.transition}`,runId:e.runId,transition:e.transition}}}async function p(e,t){await l.log(e,f(t))}function m(e,t,n,r){if(!Number.isInteger(e)||e<t||e>n)throw Error(`${r} must be an integer between ${t} and ${n}`);return e}function h(e){let t=a.safeParse(e);if(!t.success)return null;let{action:n,actorId:r,metadata:i}=t.data,s=o.safeParse(r);return{action:n,actorRef:s.success?s.data:void 0,...i}}export{l as approvalAudit,f as approvalAuditEvent,d as cleanup,u as history,p as logApprovalTransition};
2
2
  //# sourceMappingURL=audit.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"audit.mjs","names":[],"sources":["../../../src/components/approvals/audit.ts"],"sourcesContent":["import { AuditLog, type AuditEventInput } from 'convex-audit-log'\nimport { v } from 'convex/values'\n\nimport { components } from './_generated/api'\nimport { mutation, query, type MutationCtx } from './_generated/server'\nimport {\n\tAPPROVAL_AUDIT_RETENTION_CATEGORY,\n\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n} from './constants'\n\nexport type ApprovalAuditTransition = Readonly<{\n\taction: string\n\tactorRef?: string\n\trunId: string\n\tresourceType: string\n\tresourceRef: string\n\ttransition: string\n\tseverity?: AuditEventInput['severity']\n}>\n\nexport type ApprovalAuditProjection = Readonly<{\n\taction: string\n\tactorRef?: string\n\tcorrelationKey: string\n\ttransition: string\n}>\n\nexport const approvalAudit = new AuditLog(components.auditLog, {\n\tsamplingEnabled: false,\n})\n\nexport const history = query({\n\targs: {\n\t\tresourceType: v.string(),\n\t\tresourceRef: v.string(),\n\t\tlimit: v.optional(v.number()),\n\t},\n\treturns: v.array(\n\t\tv.object({\n\t\t\taction: v.string(),\n\t\t\tactorRef: v.optional(v.string()),\n\t\t\tcorrelationKey: v.string(),\n\t\t\ttransition: v.string(),\n\t\t}),\n\t),\n\thandler: async (ctx, input) => {\n\t\tconst limit = Math.max(1, Math.min(Math.trunc(input.limit ?? 100), 100))\n\t\tconst events = await approvalAudit.queryByResource(ctx, {\n\t\t\tresourceType: input.resourceType,\n\t\t\tresourceId: input.resourceRef,\n\t\t\tlimit,\n\t\t})\n\t\tconst unique = new Map<string, ApprovalAuditProjection>()\n\t\tfor (const event of events) {\n\t\t\tconst projection = auditProjection(event)\n\t\t\tif (projection) unique.set(projection.correlationKey, projection)\n\t\t}\n\t\treturn [...unique.values()]\n\t},\n})\n\nexport const cleanup = mutation({\n\targs: {\n\t\tolderThanDays: v.number(),\n\t\tbatchSize: v.number(),\n\t},\n\treturns: v.number(),\n\thandler: (ctx, input) => {\n\t\tconst olderThanDays = boundedInteger(\n\t\t\tinput.olderThanDays,\n\t\t\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\t'olderThanDays',\n\t\t)\n\t\tconst batchSize = boundedInteger(\n\t\t\tinput.batchSize,\n\t\t\t1,\n\t\t\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\t\t\t'batchSize',\n\t\t)\n\t\treturn approvalAudit.cleanup(ctx, {\n\t\t\tolderThanDays,\n\t\t\tbatchSize,\n\t\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\t})\n\t},\n})\n\nexport function approvalAuditEvent(\n\tinput: ApprovalAuditTransition,\n): AuditEventInput {\n\treturn {\n\t\taction: input.action,\n\t\t...(input.actorRef === undefined ? {} : { actorId: input.actorRef }),\n\t\tresourceType: input.resourceType,\n\t\tresourceId: input.resourceRef,\n\t\tseverity: input.severity ?? 'info',\n\t\ttags: ['approvals'],\n\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\tmetadata: {\n\t\t\tcorrelationKey: `${input.runId}:${input.transition}`,\n\t\t\trunId: input.runId,\n\t\t\ttransition: input.transition,\n\t\t},\n\t}\n}\n\nexport async function logApprovalTransition(\n\tctx: MutationCtx,\n\tinput: ApprovalAuditTransition,\n): Promise<void> {\n\tawait approvalAudit.log(ctx, approvalAuditEvent(input))\n}\n\nfunction boundedInteger(\n\tvalue: number,\n\tminimum: number,\n\tmaximum: number,\n\tname: string,\n): number {\n\tif (!Number.isInteger(value) || value < minimum || value > maximum)\n\t\tthrow new Error(\n\t\t\t`${name} must be an integer between ${minimum} and ${maximum}`,\n\t\t)\n\treturn value\n}\n\nfunction auditProjection(event: unknown): ApprovalAuditProjection | null {\n\tif (!event || typeof event !== 'object') return null\n\tconst value = event as Record<string, unknown>\n\tconst metadata = value.metadata\n\tif (!metadata || typeof metadata !== 'object') return null\n\tconst details = metadata as Record<string, unknown>\n\tif (\n\t\ttypeof value.action !== 'string' ||\n\t\ttypeof details.correlationKey !== 'string' ||\n\t\ttypeof details.transition !== 'string'\n\t)\n\t\treturn null\n\treturn {\n\t\taction: value.action,\n\t\t...(typeof value.actorId === 'string' ? { actorRef: value.actorId } : {}),\n\t\tcorrelationKey: details.correlationKey,\n\t\ttransition: details.transition,\n\t}\n}\n"],"mappings":"ySA6BA,MAAa,EAAgB,IAAI,EAAS,EAAW,SAAU,CAC9D,gBAAiB,EAClB,CAAC,EAEY,EAAU,EAAM,CAC5B,KAAM,CACL,aAAc,EAAE,OAAO,EACvB,YAAa,EAAE,OAAO,EACtB,MAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAC7B,EACA,QAAS,EAAE,MACV,EAAE,OAAO,CACR,OAAQ,EAAE,OAAO,EACjB,SAAU,EAAE,SAAS,EAAE,OAAO,CAAC,EAC/B,eAAgB,EAAE,OAAO,EACzB,WAAY,EAAE,OAAO,CACtB,CAAC,CACF,EACA,QAAS,MAAO,EAAK,IAAU,CAC9B,IAAM,EAAQ,KAAK,IAAI,EAAG,KAAK,IAAI,KAAK,MAAM,EAAM,OAAS,GA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AAI,CAAC,GAAS,OAAO,GAAU,SAAU,OAAO,KAChD,IAAM,EAAQ,EACR,EAAW,EAAM,SACvB,GAAI,CAAC,GAAY,OAAO,GAAa,SAAU,OAAO,KACtD,IAAM,EAAU,EAOhB,OALC,OAAO,EAAM,QAAW,UACxB,OAAO,EAAQ,gBAAmB,UAClC,OAAO,EAAQ,YAAe,SAEvB,KACD,CACN,OAAQ,EAAM,OACd,GAAI,OAAO,EAAM,SAAY,SAAW,CAAE,SAAU,EAAM,OAAQ,EAAI,CAAC,EACvE,eAAgB,EAAQ,eACxB,WAAY,EAAQ,UACrB,CACD"}
1
+ {"version":3,"file":"audit.mjs","names":["approvalAudit","AuditLog","components","history","query","v","limit","input","events","ctx","unique","event","projection","auditProjection","cleanup","mutation","olderThanDays","boundedInteger","MAX_APPROVAL_AUDIT_RETENTION_DAYS","batchSize","APPROVAL_AUDIT_RETENTION_CATEGORY","approvalAuditEvent","logApprovalTransition","value","minimum","maximum","name","parsed","approvalAuditEventProjection","actorRef","approvalOptionalString","actorId","metadata"],"sources":["../../../src/components/approvals/audit.ts"],"sourcesContent":["import { AuditLog, type AuditEventInput } from 'convex-audit-log'\nimport { v } from 'convex/values'\n\nimport { components } from './_generated/api'\nimport { mutation, query, type MutationCtx } from './_generated/server'\nimport {\n\tAPPROVAL_AUDIT_RETENTION_CATEGORY,\n\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n} from './constants'\nimport { approvalAuditEventProjection, approvalOptionalString } from './validators'\n\nexport type ApprovalAuditTransition = Readonly<{\n\taction: string\n\tactorRef?: string\n\trunId: string\n\tresourceType: string\n\tresourceRef: string\n\ttransition: string\n\tseverity?: AuditEventInput['severity']\n}>\n\nexport type ApprovalAuditProjection = Readonly<{\n\taction: string\n\tactorRef?: string\n\tcorrelationKey: string\n\ttransition: string\n}>\n\nexport const approvalAudit = new AuditLog(components.auditLog, {\n\tsamplingEnabled: false,\n})\n\nexport const history = query({\n\targs: {\n\t\tresourceType: v.string(),\n\t\tresourceRef: v.string(),\n\t\tlimit: v.optional(v.number()),\n\t},\n\treturns: v.array(\n\t\tv.object({\n\t\t\taction: v.string(),\n\t\t\tactorRef: v.optional(v.string()),\n\t\t\tcorrelationKey: v.string(),\n\t\t\ttransition: v.string(),\n\t\t}),\n\t),\n\thandler: async (ctx, input) => {\n\t\tconst limit = Math.max(1, Math.min(Math.trunc(input.limit ?? 100), 100))\n\t\tconst events = await approvalAudit.queryByResource(ctx, {\n\t\t\tresourceType: input.resourceType,\n\t\t\tresourceId: input.resourceRef,\n\t\t\tlimit,\n\t\t})\n\t\tconst unique = new Map<string, ApprovalAuditProjection>()\n\t\tfor (const event of events) {\n\t\t\tconst projection = auditProjection(event)\n\t\t\tif (projection) unique.set(projection.correlationKey, projection)\n\t\t}\n\t\treturn [...unique.values()]\n\t},\n})\n\nexport const cleanup = mutation({\n\targs: {\n\t\tolderThanDays: v.number(),\n\t\tbatchSize: v.number(),\n\t},\n\treturns: v.number(),\n\thandler: (ctx, input) => {\n\t\tconst olderThanDays = boundedInteger(\n\t\t\tinput.olderThanDays,\n\t\t\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\t'olderThanDays',\n\t\t)\n\t\tconst batchSize = boundedInteger(\n\t\t\tinput.batchSize,\n\t\t\t1,\n\t\t\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\t\t\t'batchSize',\n\t\t)\n\t\treturn approvalAudit.cleanup(ctx, {\n\t\t\tolderThanDays,\n\t\t\tbatchSize,\n\t\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\t})\n\t},\n})\n\nexport function approvalAuditEvent(input: ApprovalAuditTransition): AuditEventInput {\n\treturn {\n\t\taction: input.action,\n\t\tactorId: input.actorRef,\n\t\tresourceType: input.resourceType,\n\t\tresourceId: input.resourceRef,\n\t\tseverity: input.severity ?? 'info',\n\t\ttags: ['approvals'],\n\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\tmetadata: {\n\t\t\tcorrelationKey: `${input.runId}:${input.transition}`,\n\t\t\trunId: input.runId,\n\t\t\ttransition: input.transition,\n\t\t},\n\t}\n}\n\nexport async function logApprovalTransition(\n\tctx: MutationCtx,\n\tinput: ApprovalAuditTransition,\n): Promise<void> {\n\tawait approvalAudit.log(ctx, approvalAuditEvent(input))\n}\n\nfunction boundedInteger(value: number, minimum: number, maximum: number, name: string): number {\n\tif (!Number.isInteger(value) || value < minimum || value > maximum)\n\t\tthrow new Error(`${name} must be an integer between ${minimum} and ${maximum}`)\n\treturn value\n}\n\nfunction auditProjection(\n\tevent: Awaited<ReturnType<typeof approvalAudit.queryByResource>>[number],\n): ApprovalAuditProjection | null {\n\tconst parsed = approvalAuditEventProjection.safeParse(event)\n\tif (!parsed.success) return null\n\tconst { action, actorId, metadata } = parsed.data\n\tconst actorRef = approvalOptionalString.safeParse(actorId)\n\treturn { action, actorRef: actorRef.success ? actorRef.data : undefined, ...metadata }\n}\n"],"mappings":"A,qYA8BA,MAAaA,EAAgB,IAAIC,EAASC,EAAW,SAAU,CAC9D,gBAAiB,EAClB,CAAC,EAEYC,EAAUC,EAAM,CAC5B,KAAM,CACL,aAAcC,EAAE,OAAO,EACvB,YAAaA,EAAE,OAAO,EACtB,MAAOA,EAAE,SAASA,EAAE,OAAO,CAAC,CAC7B,EACA,QAASA,EAAE,MACVA,EAAE,OAAO,CACR,OAAQA,EAAE,OAAO,EACjB,SAAUA,EAAE,SAASA,EAAE,OAAO,CAAC,EAC/B,eAAgBA,EAAE,OAAO,EACzB,WAAYA,EAAE,OAAO,CACtB,CAAC,CACF,EACA,QAAS,MAAO,EAAK,IAAU,CAC9B,IAAMC,EAAQ,KAAK,IAAI,EAAG,KAAK,IAAI,KAAK,MAAMC,EAAM,OAA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