better-supabase 0.43.0 → 0.45.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 (472) hide show
  1. package/dist/{access-sql-Dao1C0fz.js → access-sql-BHat-brX.js} +1 -0
  2. package/dist/{adapter-ddQ9Hzka.js → adapter-C0C4jIwI.js} +153 -4
  3. package/dist/{agents-BAiLeoR-.d.ts → agents-DxhGxwDS.d.ts} +4 -4
  4. package/dist/{ai-cache-B94R1da7.d.ts → ai-cache-OkvpE7L-.d.ts} +4 -4
  5. package/dist/{ai-chat-rQ7Ftq9W.d.ts → ai-chat-LHWztFya.d.ts} +4 -4
  6. package/dist/{ai-schedules-DIiPmFgn.d.ts → ai-schedules-BP0PBKhY.d.ts} +5 -5
  7. package/dist/ai-sdk/agents/index.d.ts +6 -6
  8. package/dist/ai-sdk/batches/index.d.ts +3 -3
  9. package/dist/ai-sdk/cache/index.d.ts +1 -1
  10. package/dist/ai-sdk/chat/index.d.ts +2 -2
  11. package/dist/ai-sdk/embeddings/index.d.ts +2 -2
  12. package/dist/ai-sdk/files/index.d.ts +1 -1
  13. package/dist/ai-sdk/index.d.ts +5 -5
  14. package/dist/ai-sdk/mcp/index.d.ts +3 -3
  15. package/dist/ai-sdk/memory/index.d.ts +3 -3
  16. package/dist/ai-sdk/memory/index.js +1 -1
  17. package/dist/ai-sdk/workflow/index.d.ts +3 -3
  18. package/dist/{api-CbY2qdzT.d.ts → api-CgO8Gin7.d.ts} +6 -6
  19. package/dist/{api-wwix_K5c.js → api-DXCaMM2S.js} +1 -1
  20. package/dist/{api-keys-U3JQ8IlM.d.ts → api-keys-DINjcAaY.d.ts} +4 -4
  21. package/dist/{app-tables-CVMn4c4b.d.ts → app-tables-Dg9lERHb.d.ts} +1 -1
  22. package/dist/{approvals-CYbTzQ7v.d.ts → approvals-CoBe9E2b.d.ts} +6 -6
  23. package/dist/{assistant-B1p5mYaM.d.ts → assistant-DMaZZFps.d.ts} +2 -2
  24. package/dist/astro/index.d.ts +7 -7
  25. package/dist/astro/index.js +4 -5
  26. package/dist/{authorization-hGBtxrnQ.d.ts → authorization-CcWVJSsN.d.ts} +82 -22
  27. package/dist/{authorization-hooks-CR8TVvqo.d.ts → authorization-hooks-u2Z18CAM.d.ts} +2 -2
  28. package/dist/authz-refresh-C_zK-BdX.js +115 -0
  29. package/dist/authz-refresh-DIqPTJZe.d.ts +79 -0
  30. package/dist/{auth-link-BmJsQG4a.js → authz-refresh-DQ0Q_1_V.js} +87 -1
  31. package/dist/authz-refresh-Nc-38Xeh.d.ts +38 -0
  32. package/dist/authz-topic-C7n3kIm_.d.ts +21 -0
  33. package/dist/{automations-K0O3En6E.js → automations-Bk-_P7Zp.js} +2 -1
  34. package/dist/better-result/index.d.ts +3 -3
  35. package/dist/{bind-DWAIKYvJ.d.ts → bind-BieIoT6r.d.ts} +7 -7
  36. package/dist/{block-env-C6OEu9Xk.d.ts → block-env-YzSHv579.d.ts} +4 -4
  37. package/dist/{block-helpers-Sj-efEhC.d.ts → block-helpers-DzIR3Ob8.d.ts} +1 -1
  38. package/dist/{block-hooks-VW4knarE.d.ts → block-hooks-D9NKzUqW.d.ts} +2 -2
  39. package/dist/{block-subjects-B1zfhFWC.js → block-subjects-CTIsFATg.js} +1 -1
  40. package/dist/{block-subjects-Bkieh2Xk.d.ts → block-subjects-hcIVjfyD.d.ts} +1 -1
  41. package/dist/{block-tables-BIExrL2J.d.ts → block-tables-D-UjSTXa.d.ts} +1 -1
  42. package/dist/{block-transport-CDmOUuLZ.d.ts → block-transport-Do7J4MsA.d.ts} +2 -2
  43. package/dist/blocks/access-requests/index.d.ts +5 -5
  44. package/dist/blocks/activities/index.d.ts +10 -10
  45. package/dist/blocks/activities/index.js +1 -1
  46. package/dist/blocks/agents/index.d.ts +4 -4
  47. package/dist/blocks/ai-cache/index.d.ts +3 -3
  48. package/dist/blocks/ai-chat/index.d.ts +8 -8
  49. package/dist/blocks/ai-files/index.d.ts +3 -3
  50. package/dist/blocks/ai-keys/index.d.ts +4 -4
  51. package/dist/blocks/ai-schedules/index.d.ts +3 -3
  52. package/dist/blocks/announcements/index.d.ts +8 -8
  53. package/dist/blocks/api-keys/index.d.ts +3 -3
  54. package/dist/blocks/approvals/index.d.ts +4 -4
  55. package/dist/blocks/assets/index.d.ts +6 -6
  56. package/dist/blocks/assignment/index.d.ts +7 -7
  57. package/dist/blocks/attachments/index.d.ts +4 -4
  58. package/dist/blocks/audit/index.d.ts +13 -13
  59. package/dist/blocks/audit/index.js +1 -1
  60. package/dist/blocks/automations/index.d.ts +12 -12
  61. package/dist/blocks/billable-time/index.d.ts +6 -6
  62. package/dist/blocks/billing/index.d.ts +9 -9
  63. package/dist/blocks/bookings/index.d.ts +4 -4
  64. package/dist/blocks/bulk/index.d.ts +4 -4
  65. package/dist/blocks/calendar/index.d.ts +5 -5
  66. package/dist/blocks/catalog/index.d.ts +6 -6
  67. package/dist/blocks/channels/index.d.ts +7 -7
  68. package/dist/blocks/collections/index.d.ts +6 -6
  69. package/dist/blocks/comments/index.d.ts +10 -10
  70. package/dist/blocks/compliance/index.d.ts +26 -10
  71. package/dist/blocks/compliance/index.js +38 -4
  72. package/dist/blocks/connectors/index.d.ts +4 -4
  73. package/dist/blocks/contacts/index.d.ts +52 -9
  74. package/dist/blocks/contacts/index.js +48 -5
  75. package/dist/blocks/content/index.d.ts +5 -5
  76. package/dist/blocks/contracts/index.d.ts +6 -6
  77. package/dist/blocks/courses/index.d.ts +22 -7
  78. package/dist/blocks/courses/index.js +11 -0
  79. package/dist/blocks/created-by/index.d.ts +2 -2
  80. package/dist/blocks/custom-fields/index.d.ts +7 -7
  81. package/dist/blocks/custom-fields/index.js +1 -1
  82. package/dist/blocks/data-lifecycle/index.d.ts +8 -8
  83. package/dist/blocks/deals/index.d.ts +6 -6
  84. package/dist/blocks/dispatch/index.d.ts +6 -6
  85. package/dist/blocks/documents/index.d.ts +4 -4
  86. package/dist/blocks/domains/index.d.ts +6 -6
  87. package/dist/blocks/donations/index.d.ts +6 -6
  88. package/dist/blocks/drive/index.d.ts +6 -6
  89. package/dist/blocks/employees/index.d.ts +8 -8
  90. package/dist/blocks/enrichment/index.d.ts +6 -6
  91. package/dist/blocks/enrollments/index.d.ts +6 -6
  92. package/dist/blocks/entitlements/index.d.ts +6 -6
  93. package/dist/blocks/expenses/index.d.ts +5 -5
  94. package/dist/blocks/field-history/index.d.ts +4 -4
  95. package/dist/blocks/flags/index.d.ts +5 -5
  96. package/dist/blocks/forecasts/index.d.ts +6 -6
  97. package/dist/blocks/forms/index.d.ts +6 -6
  98. package/dist/blocks/goals/index.d.ts +5 -5
  99. package/dist/blocks/goals/index.js +1 -1
  100. package/dist/blocks/guests/index.d.ts +6 -6
  101. package/dist/blocks/guests/index.js +2 -2
  102. package/dist/blocks/hiring/index.d.ts +6 -6
  103. package/dist/blocks/identities/index.d.ts +5 -5
  104. package/dist/blocks/imports/index.d.ts +5 -5
  105. package/dist/blocks/inbox/index.d.ts +10 -10
  106. package/dist/blocks/incidents/index.d.ts +5 -5
  107. package/dist/blocks/index.d.ts +9 -9
  108. package/dist/blocks/inventory/index.d.ts +6 -6
  109. package/dist/blocks/invoices/index.d.ts +13 -8
  110. package/dist/blocks/invoices/index.js +2 -1
  111. package/dist/blocks/knowledge/index.d.ts +3 -3
  112. package/dist/blocks/lead-scoring/index.d.ts +7 -7
  113. package/dist/blocks/leases/index.d.ts +6 -6
  114. package/dist/blocks/leave/index.d.ts +5 -5
  115. package/dist/blocks/ledger/index.d.ts +6 -6
  116. package/dist/blocks/mail-sync/index.d.ts +5 -5
  117. package/dist/blocks/memberships/index.d.ts +2 -2
  118. package/dist/blocks/memory/index.d.ts +4 -4
  119. package/dist/blocks/messaging/index.d.ts +11 -11
  120. package/dist/blocks/metrics/index.d.ts +6 -6
  121. package/dist/blocks/mfa/index.d.ts +2 -2
  122. package/dist/blocks/moderation/index.d.ts +6 -6
  123. package/dist/blocks/notifications/index.d.ts +11 -11
  124. package/dist/blocks/numbering/index.d.ts +4 -4
  125. package/dist/blocks/oauth-server/index.d.ts +64 -38
  126. package/dist/blocks/oauth-server/index.js +6 -3
  127. package/dist/blocks/onboarding/index.d.ts +5 -5
  128. package/dist/blocks/orders/index.d.ts +7 -7
  129. package/dist/blocks/organizations/index.d.ts +8 -8
  130. package/dist/blocks/outbox/index.d.ts +4 -4
  131. package/dist/blocks/passes/index.d.ts +8 -8
  132. package/dist/blocks/permissions/index.d.ts +7 -7
  133. package/dist/blocks/pipelines/index.d.ts +6 -6
  134. package/dist/blocks/posts/index.d.ts +5 -5
  135. package/dist/blocks/profiles/index.d.ts +4 -4
  136. package/dist/blocks/promotions/index.d.ts +5 -5
  137. package/dist/blocks/push/index.d.ts +7 -7
  138. package/dist/blocks/queue/index.d.ts +7 -7
  139. package/dist/blocks/queue/index.js +4 -4
  140. package/dist/blocks/quotes/index.d.ts +20 -13
  141. package/dist/blocks/quotes/index.js +3 -2
  142. package/dist/blocks/rank/index.d.ts +4 -4
  143. package/dist/blocks/reactions/index.d.ts +9 -9
  144. package/dist/blocks/relations/index.d.ts +7 -7
  145. package/dist/blocks/reminders/index.d.ts +8 -8
  146. package/dist/blocks/reviews/index.d.ts +5 -5
  147. package/dist/blocks/saved-views/index.d.ts +6 -6
  148. package/dist/blocks/scores/index.d.ts +5 -5
  149. package/dist/blocks/search/index.d.ts +7 -7
  150. package/dist/blocks/security-events/index.d.ts +7 -7
  151. package/dist/blocks/segments/index.d.ts +7 -7
  152. package/dist/blocks/sequences/index.d.ts +6 -6
  153. package/dist/blocks/service-accounts/index.d.ts +5 -5
  154. package/dist/blocks/service-accounts/index.js +1 -1
  155. package/dist/blocks/sessions/index.d.ts +2 -2
  156. package/dist/blocks/settings/index.d.ts +6 -6
  157. package/dist/blocks/share-links/index.d.ts +5 -5
  158. package/dist/blocks/shipments/index.d.ts +6 -6
  159. package/dist/blocks/signatures/index.d.ts +14 -6
  160. package/dist/blocks/signatures/index.js +3 -1
  161. package/dist/blocks/signing-keys/index.d.ts +4 -4
  162. package/dist/blocks/sla/index.d.ts +7 -7
  163. package/dist/blocks/sso/index.d.ts +6 -6
  164. package/dist/blocks/state-machine/index.d.ts +5 -5
  165. package/dist/blocks/subjects/index.d.ts +6 -6
  166. package/dist/blocks/tags/index.d.ts +6 -6
  167. package/dist/blocks/tasks/index.d.ts +9 -9
  168. package/dist/blocks/teams/index.d.ts +4 -4
  169. package/dist/blocks/templates/index.d.ts +8 -8
  170. package/dist/blocks/time-tracking/index.d.ts +7 -7
  171. package/dist/blocks/timeline/index.d.ts +9 -9
  172. package/dist/blocks/timeline/index.js +1 -1
  173. package/dist/blocks/trash/index.d.ts +6 -6
  174. package/dist/blocks/undo/index.d.ts +4 -4
  175. package/dist/blocks/updated-at/index.d.ts +2 -2
  176. package/dist/blocks/usage/index.d.ts +4 -4
  177. package/dist/blocks/vercel-marketplace/index.d.ts +5 -5
  178. package/dist/blocks/versions/index.d.ts +6 -6
  179. package/dist/blocks/waitlist/index.d.ts +5 -5
  180. package/dist/blocks/webhooks/index.d.ts +13 -13
  181. package/dist/blocks/workflow-editor/index.d.ts +9 -9
  182. package/dist/blocks/workflows/index.d.ts +7 -7
  183. package/dist/{bookings-CHUzFwOI.d.ts → bookings-Du1lvUg1.d.ts} +3 -3
  184. package/dist/{bucket-CrsJNHzi.d.ts → bucket-CjIhrluq.d.ts} +1 -1
  185. package/dist/cache-tags-C5Oivuxo.js +27 -0
  186. package/dist/{sign-in-D5Bg7R47.d.ts → cache-tags-DrywUP3I.d.ts} +16 -2
  187. package/dist/chat-sdk/index.d.ts +6 -6
  188. package/dist/claims/index.d.ts +6 -6
  189. package/dist/claims/index.js +1 -1
  190. package/dist/cli/{add-fdZAY8C_.js → add-B5Gq34wX.js} +12 -12
  191. package/dist/cli/add-D_JV6V6k.js +1 -0
  192. package/dist/cli/{add-uwUI80aZ.js → add-DcLNy2oN.js} +2 -2
  193. package/dist/cli/{app-table-files-BR_7lT4u.js → app-table-files-CcGWy0qX.js} +14 -6
  194. package/dist/cli/{app-tables-DoxrhJb1.js → app-tables-RbPMD2M3.js} +2 -2
  195. package/dist/cli/{backfill-BTMgDL6X.js → backfill-BJterqcQ.js} +3 -3
  196. package/dist/cli/bin.js +1 -1
  197. package/dist/cli/{blocks-Bj0LS3rF.js → blocks-BBALfFv-.js} +1 -1
  198. package/dist/cli/{blocks-BgPbXNhB.js → blocks-DsAwI_4v.js} +1 -1
  199. package/dist/cli/{cache-CEGpAmXJ.js → cache-DRb1xVPh.js} +1 -1
  200. package/dist/cli/{codemod-CaXGpQ10.js → codemod-Cpd4DnrL.js} +1 -1
  201. package/dist/cli/{config-CrwCec-B.js → config-CGVmcEZa.js} +1 -1
  202. package/dist/cli/{config-DrrkMihk.js → config-Dy-BAGel.js} +34 -5
  203. package/dist/cli/{content-mapper-BJRfCnFX.js → content-mapper-D0riSMnP.js} +2 -2
  204. package/dist/cli/{db-bK5eCLaE.js → db-BCVXzXDA.js} +2 -2
  205. package/dist/cli/{doctor-CHQDLcwL.js → doctor-CHmX2gau.js} +273 -230
  206. package/dist/cli/{gen-DSK152A3.js → gen-DB0svRc8.js} +14 -14
  207. package/dist/cli/index.d.ts +1 -1
  208. package/dist/cli/index.js +7 -7
  209. package/dist/cli/{init-CPC1ceqC.js → init-B4fQNe4C.js} +9 -9
  210. package/dist/cli/{live-BFXisTDf.js → live-Bft5EE70.js} +2 -2
  211. package/dist/cli/{mcp-CrulrTBs.js → mcp-BKcS-LZw.js} +2 -2
  212. package/dist/cli/{metadata-yePOltZY.js → metadata-CgKNmMsc.js} +3 -3
  213. package/dist/cli/{migrate-kjYx7du-.js → migrate-ehxT23Gg.js} +1 -1
  214. package/dist/cli/{migration-safety-DnvCYRsw.js → migration-safety-D2gG-dDs.js} +2 -2
  215. package/dist/cli/{migrations-ZYHA0gks.js → migrations-CQ1Sgz_X.js} +2 -2
  216. package/dist/cli/{module-migration-Du7UHsO9.js → module-migration-BOPJUkIX.js} +2 -2
  217. package/dist/cli/powersync-B8GWjT_L.js +1 -0
  218. package/dist/cli/{powersync-BOxy1_xW.js → powersync-BTari5WF.js} +20 -4
  219. package/dist/cli/{print-B4OqfSML.js → print-BMJnlJ8k.js} +2 -2
  220. package/dist/cli/{providers-KYOKi_jp.js → providers-BNZ-OqMI.js} +1 -1
  221. package/dist/cli/{prune-workflows-7JISyAI7.js → prune-workflows-BG55npqs.js} +3 -3
  222. package/dist/cli/{remove-DvncDSRp.js → remove-BIqGDE0A.js} +5 -5
  223. package/dist/cli/{render-C6dQ0C0Y.js → render-BIC4Wctz.js} +4 -4
  224. package/dist/cli/{run-BYiApqFR.js → run-BJ4_rmHy.js} +9 -9
  225. package/dist/cli/{run-DWDRg4vp.js → run-C_slJx8m.js} +32 -32
  226. package/dist/cli/{seed-DSC6f0oh.js → seed-0r_0aD8_.js} +2 -2
  227. package/dist/cli/seed-DX1NTTOK.js +1 -0
  228. package/dist/cli/{shared-DC86fQYk.js → shared-DhpBDjRa.js} +1 -1
  229. package/dist/cli/{snapshot-CwCG_YX2.js → snapshot-CMJksw-t.js} +3 -3
  230. package/dist/cli/{source-DDxRHVzk.js → source-CJilfcq-.js} +1 -1
  231. package/dist/cli/{source-args-Bz5QQne2.js → source-args-CgCX8KUJ.js} +1 -1
  232. package/dist/cli/{spec-Cnxqc7kC.js → spec-Br9cWMbU.js} +2 -2
  233. package/dist/cli/{spec-CvKJ6GpI.js → spec-CnjHA0br.js} +1 -1
  234. package/dist/cli/{sql-layout-BwbfVSR8.js → sql-layout-BCiEl_G5.js} +32 -13
  235. package/dist/cli/{sync-lpbLqJly.js → sync-Bulv1zyy.js} +4 -4
  236. package/dist/cli/{table-BIQA9Hdt.js → table-BAR0cLmU.js} +1 -1
  237. package/dist/cli/{upgrade-34ZODJZj.js → upgrade-C8fiTE3r.js} +2 -2
  238. package/dist/cli/{upgrade-Cq4EFBH7.js → upgrade-DTBvTAAV.js} +5 -5
  239. package/dist/cli/{version-BGN5319Z.js → version-hhuwVLKj.js} +1 -1
  240. package/dist/client/index.d.ts +6 -6
  241. package/dist/client/native/index.d.ts +7 -31
  242. package/dist/client/native/index.js +2 -2
  243. package/dist/{cloud-event-BjgxkfJJ.d.ts → cloud-event-LTUGgt6D.d.ts} +1 -1
  244. package/dist/{compiler-BOW4yPcW.d.ts → compiler-CJorTlU7.d.ts} +2 -2
  245. package/dist/{composite-DPN4SFud.d.ts → composite-BCUNxZCd.d.ts} +7 -7
  246. package/dist/{composite-BidYZWZY.js → composite-C3lLpMys.js} +2 -2
  247. package/dist/config/index.d.ts +5 -5
  248. package/dist/config/index.js +5 -5
  249. package/dist/{config-C-eXOuhp.js → config-DA_R9O_y.js} +3 -3
  250. package/dist/{config-BN17nVp1.js → config-HOXkrND2.js} +1 -1
  251. package/dist/{connectors-OMJkoAP6.d.ts → connectors-DTxDzUzD.d.ts} +4 -4
  252. package/dist/{context-Dga2sgyx.d.ts → context-BJK9_ppk.d.ts} +38 -4
  253. package/dist/contract/index.d.ts +11 -10
  254. package/dist/{controller-BFOCK5AG.d.ts → controller-TplPQG5m.d.ts} +1 -1
  255. package/dist/{conversion-BShzA-u-.d.ts → conversion-DwDBNeWT.d.ts} +1 -1
  256. package/dist/create/index.d.ts +3 -3
  257. package/dist/create/index.js +18 -3
  258. package/dist/create/lite/index.d.ts +4 -4
  259. package/dist/create/lite/index.js +3 -3
  260. package/dist/credentials/index.d.ts +4 -4
  261. package/dist/{data-engine-CX1oYDZl.d.ts → data-engine-ZcGeVz1i.d.ts} +7 -1
  262. package/dist/{define-C_He1bQO.d.ts → define-DXQHQ2Qy.d.ts} +5 -5
  263. package/dist/{define-block-DBD7yhQg.d.ts → define-block-tFQZ8936.d.ts} +12 -12
  264. package/dist/{documents-CNVPrE_0.d.ts → documents-Ciijx56T.d.ts} +3 -3
  265. package/dist/edge/index.d.ts +9 -9
  266. package/dist/edge/index.js +6 -7
  267. package/dist/elysia/index.d.ts +1 -1
  268. package/dist/elysia/index.js +1 -1
  269. package/dist/{embeddings-C2PBJ2Lx.d.ts → embeddings-LhxY3bUD.d.ts} +1 -1
  270. package/dist/{ended-BwpmNC5k.d.ts → ended-CpyW7_0h.d.ts} +2 -2
  271. package/dist/{entitlements-C5k_9hHt.d.ts → entitlements-SqfT4gk_.d.ts} +2 -2
  272. package/dist/eve/index.d.ts +9 -9
  273. package/dist/eve/index.js +1 -1
  274. package/dist/{eve-CtQd4iaO.d.ts → eve-DmbLji3M.d.ts} +2 -2
  275. package/dist/events/index.d.ts +3 -3
  276. package/dist/{events-DddDlibJ.d.ts → events-BrgD2StJ.d.ts} +3 -1
  277. package/dist/{executor-CxMHiDp_.d.ts → executor-DlAtlYxY.d.ts} +4 -4
  278. package/dist/{executor-DL7cZ-3T.d.ts → executor-kfUaLlQr.d.ts} +1 -1
  279. package/dist/{executor-DoSNec_H.d.ts → executor-rs231gO_.d.ts} +1 -1
  280. package/dist/expo/index.d.ts +51 -8
  281. package/dist/expo/index.js +89 -4
  282. package/dist/{field-errors-LVBXokQN.d.ts → field-errors-DyWpuH1q.d.ts} +10 -10
  283. package/dist/{field-formats-DVukMbRa.d.ts → field-formats-BJeg-rv8.d.ts} +13 -3
  284. package/dist/{field-formats-Cap-V7UP.js → field-formats-sLYMh1ZK.js} +52 -4
  285. package/dist/{fields-CP46SPNE.d.ts → fields-OVgN0HOy.d.ts} +1 -1
  286. package/dist/{filter-evaluate-Bkbb0nuQ.d.ts → filter-evaluate-BzyMp2LO.d.ts} +1 -1
  287. package/dist/{filter-query-Xj40B5KT.d.ts → filter-query-BcheQ5zK.d.ts} +1 -1
  288. package/dist/{flags-BrXfCmGB.d.ts → flags-D71LTDHR.d.ts} +2 -2
  289. package/dist/flags-sdk/index.d.ts +2 -2
  290. package/dist/{framework-B6JAPr1i.d.ts → framework-C8HFM1bX.d.ts} +8 -8
  291. package/dist/{framework-z3KTPRjk.js → framework-DydnLrMk.js} +1 -1
  292. package/dist/{gateway-DJX-XUWl.d.ts → gateway-DQirTFOg.d.ts} +3 -3
  293. package/dist/guest-actions-Du1ph4dE.js +11 -0
  294. package/dist/h3/index.d.ts +1 -1
  295. package/dist/h3/index.js +1 -1
  296. package/dist/h3/v1/index.d.ts +1 -1
  297. package/dist/h3/v1/index.js +1 -1
  298. package/dist/hono/index.d.ts +9 -9
  299. package/dist/hono/index.js +5 -6
  300. package/dist/{inbox-DiQ8KhG8.d.ts → inbox-nk8pqL8V.d.ts} +5 -5
  301. package/dist/{index-1_-lg9Gc.d.ts → index-0erPlzHd.d.ts} +5 -5
  302. package/dist/{index-1uV69AZq.d.ts → index-BKDvrKDl.d.ts} +1 -1
  303. package/dist/{index-CjN6kzvL.d.ts → index-BjN_IQQd.d.ts} +5 -5
  304. package/dist/{index-DjJUamhw.d.ts → index-Brzh6XAW.d.ts} +5 -4
  305. package/dist/{index-CvLTqmdq.d.ts → index-CwDdMCdH.d.ts} +1 -1
  306. package/dist/{index-BA8sPQ49.d.ts → index-DCyNdhEC.d.ts} +5 -5
  307. package/dist/{index-DBbdaYAH.d.ts → index-DcmDWojr.d.ts} +1 -1
  308. package/dist/{index-DUmsXPdh.d.ts → index-Ddjcn6i7.d.ts} +5 -5
  309. package/dist/{index-DwP65vFk.d.ts → index-DkmorC1b.d.ts} +5 -5
  310. package/dist/{index-D-SIdOiL.d.ts → index-vGZZjCW7.d.ts} +14 -14
  311. package/dist/{index-BhmjjkMu.d.ts → index-x2YRPbXr.d.ts} +6 -6
  312. package/dist/index.d.ts +7 -7
  313. package/dist/index.js +1 -1
  314. package/dist/{instances-Bx94JGSW.js → instances-DGtu3S0m.js} +111 -15
  315. package/dist/{kit-lHFpu2_1.d.ts → kit-C1GVbhtg.d.ts} +4 -4
  316. package/dist/{kit-D5rRAKWJ.js → kit-CB3AfM9W.js} +106 -4
  317. package/dist/{knowledge-DtECa_QW.d.ts → knowledge-CCOSNGJp.d.ts} +5 -5
  318. package/dist/lint/index.d.ts +1 -1
  319. package/dist/list/index.d.ts +3 -3
  320. package/dist/{list-query-BkbLV-Yc.d.ts → list-query-CF-5EUVX.d.ts} +3 -3
  321. package/dist/mapper/bin.js +7 -6
  322. package/dist/mcp/index.d.ts +3 -3
  323. package/dist/mcp/index.js +4 -5
  324. package/dist/mcp/sdk/index.d.ts +6 -6
  325. package/dist/mcp/sdk/index.js +2 -2
  326. package/dist/{messaging-CpQIhkFi.d.ts → messaging-2-SIPAp-.d.ts} +4 -4
  327. package/dist/nestjs/index.d.ts +2 -2
  328. package/dist/nestjs/index.js +1 -1
  329. package/dist/next/client/index.d.ts +1 -1
  330. package/dist/next/index.d.ts +29 -76
  331. package/dist/next/index.js +29 -117
  332. package/dist/node/index.d.ts +2 -2
  333. package/dist/node/index.js +1 -1
  334. package/dist/{operations-J0PkKTaF.d.ts → operations-CkgwsViz.d.ts} +1 -1
  335. package/dist/options-Cdr6Ac4-.d.ts +12 -0
  336. package/dist/{options-DUNUGuhM.js → options-CpSqyI8k.js} +4 -1
  337. package/dist/orpc/index.d.ts +8 -8
  338. package/dist/orpc/index.js +3 -4
  339. package/dist/otel/index.d.ts +3 -3
  340. package/dist/otel/index.js +5 -5
  341. package/dist/{outbox-Cpxpzcue.d.ts → outbox-DL2737I0.d.ts} +4 -4
  342. package/dist/{permissions-Cp2qvVJo.d.ts → permissions-vbtGrV26.d.ts} +1 -1
  343. package/dist/{pool-BJAjQcrJ.d.ts → pool-DfDolmmm.d.ts} +3 -3
  344. package/dist/{ports-C61eesjD.d.ts → ports-ClyPs0q6.d.ts} +1 -1
  345. package/dist/postgres/index.d.ts +4 -4
  346. package/dist/{postgrest-Bjain6nf.d.ts → postgrest-CF0ekbC-.d.ts} +1 -1
  347. package/dist/powersync/index.d.ts +44 -10
  348. package/dist/powersync/index.js +52 -5
  349. package/dist/preset/index.d.ts +3 -3
  350. package/dist/preset/index.js +3 -3
  351. package/dist/{preset-yRJgGbn9.js → preset-His18bto.js} +3 -3
  352. package/dist/{project-ps9mOsLx.js → project-D81NwLP6.js} +13 -7
  353. package/dist/{provider-CVlXXbda.d.ts → provider-DxJWo8yD.d.ts} +1 -1
  354. package/dist/{push-token-2LRdwl_8.d.ts → push-token-DMOeO8cU.d.ts} +1 -1
  355. package/dist/query/index.d.ts +1 -1
  356. package/dist/react/index.d.ts +9 -10
  357. package/dist/react/index.js +3 -3
  358. package/dist/react/native/index.d.ts +38 -1
  359. package/dist/react/native/index.js +47 -3
  360. package/dist/react/server.d.ts +9 -10
  361. package/dist/react/server.js +2 -2
  362. package/dist/react/session.d.ts +64 -2
  363. package/dist/react/session.js +1 -1
  364. package/dist/{react-DZ7AW2yf.js → react-DkGGh9FE.js} +2 -2
  365. package/dist/react-router/index.d.ts +6 -6
  366. package/dist/react-router/index.js +4 -5
  367. package/dist/realtime/index.d.ts +6 -6
  368. package/dist/realtime/index.js +1 -1
  369. package/dist/{record-form-C-1TPtMG.d.ts → record-form-BRtDkhLZ.d.ts} +1 -1
  370. package/dist/{recordings-BVuri85k.d.ts → recordings-fWDldPuP.d.ts} +1 -1
  371. package/dist/records/index.d.ts +9 -9
  372. package/dist/records/index.js +1 -1
  373. package/dist/{refusal-rnbr6RZD.js → refusal-B9w5Bapa.js} +1 -2
  374. package/dist/{refusal-CjUUBfhY.d.ts → refusal-DjCQCcCj.d.ts} +3 -3
  375. package/dist/representatives-DRNDAf0i.js +22 -0
  376. package/dist/{resolve-XlMQRUeG.d.ts → resolve-CKJMUYRc.d.ts} +8 -1
  377. package/dist/{resolve-CZV31iCm.js → resolve-nj0eZ44A.js} +38 -1
  378. package/dist/{resource-CaYpB07K.d.ts → resource-C_rLLwNU.d.ts} +1 -1
  379. package/dist/{resource-COaS9_i8.js → resource-CrmhNagD.js} +1 -1
  380. package/dist/{resource-execute-B7-QaS6R.d.ts → resource-execute-DZeWkyIU.d.ts} +2 -2
  381. package/dist/{resource-types-CF3Uc6OW.d.ts → resource-types-D3gmBOeY.d.ts} +4 -4
  382. package/dist/{resources-DhiK3yLO.js → resources-B2i_nIgJ.js} +1 -1
  383. package/dist/{resources-DnHSmJIM.d.ts → resources-CSjwmcFs.d.ts} +2 -2
  384. package/dist/{respond-D7kUatjc.d.ts → respond-DxS_8bzC.d.ts} +1 -1
  385. package/dist/{sales-lines-wQHuL-pa.d.ts → sales-lines-DFQ9oIO-.d.ts} +1 -1
  386. package/dist/{sandboxes-DKgJZYUZ.d.ts → sandboxes-Xh_uNXU4.d.ts} +1 -1
  387. package/dist/{scores-BXuSVczw.d.ts → scores-DaGD79BY.d.ts} +5 -5
  388. package/dist/server/index.d.ts +29 -38
  389. package/dist/server/index.js +9 -9
  390. package/dist/{server-types-DpI82uNq.d.ts → server-types-DCC-dWKF.d.ts} +91 -17
  391. package/dist/{session-s-mUZ8RQ.d.ts → session-Ca4clB30.d.ts} +6 -6
  392. package/dist/{session-BjPYE4dT.js → session-CaoAgv8e.js} +58 -51
  393. package/dist/{session-status-CJjTuFtA.d.ts → session-status-CYtwZBi5.d.ts} +2 -2
  394. package/dist/{sign-in-k2lXELeC.js → sign-in-BUiy6unD.js} +1 -1
  395. package/dist/{sign-in-djgvab1X.js → sign-in-Dhd16x_j.js} +1 -1
  396. package/dist/{signers-UANxMfH-.d.ts → signers-CtrTcr3i.d.ts} +4 -4
  397. package/dist/{signing-keys-DhBSWFy_.d.ts → signing-keys-BAyNlJE4.d.ts} +2 -2
  398. package/dist/solid/index.d.ts +10 -10
  399. package/dist/solid-start/index.d.ts +6 -6
  400. package/dist/solid-start/index.js +4 -5
  401. package/dist/spec/index.d.ts +3 -3
  402. package/dist/spec/index.js +2 -2
  403. package/dist/{spec-pins-CuQ2anBw.d.ts → spec-pins-CRJEZYBW.d.ts} +5 -0
  404. package/dist/{spec-pins-FKUzgF6K.js → spec-pins-Dd1Qj3Sj.js} +1 -0
  405. package/dist/sql/index.d.ts +5 -5
  406. package/dist/sql/index.js +3 -3
  407. package/dist/{sql-CWzlxS6f.js → sql-D3ihagTr.js} +1048 -305
  408. package/dist/sqlite/index.d.ts +3 -3
  409. package/dist/{sso-Frh3sbJ1.d.ts → sso-BVYSNVmk.d.ts} +3 -3
  410. package/dist/ssr/index.d.ts +4 -4
  411. package/dist/ssr/index.js +1 -1
  412. package/dist/storage/index.d.ts +3 -3
  413. package/dist/storage/index.js +1 -1
  414. package/dist/streams/index.d.ts +1 -1
  415. package/dist/{subject-readers-D1Km_Q42.d.ts → subject-readers-nnYmRpv8.d.ts} +2 -2
  416. package/dist/{subjects-DNFE2rMl.d.ts → subjects-DgP5x73R.d.ts} +3 -3
  417. package/dist/{support-Dj5V2WTs.d.ts → support-BzXcdRLG.d.ts} +4 -4
  418. package/dist/{support-view-DKZkZeM5.d.ts → support-view-DNZh8-wA.d.ts} +1 -1
  419. package/dist/svelte/index.d.ts +9 -9
  420. package/dist/sveltekit/index.d.ts +7 -7
  421. package/dist/sveltekit/index.js +4 -5
  422. package/dist/{tags-BihwKkTT.d.ts → tags-CpFIpRw8.d.ts} +1 -1
  423. package/dist/tanstack-db/index.d.ts +3 -3
  424. package/dist/tanstack-start/index.d.ts +6 -6
  425. package/dist/tanstack-start/index.js +4 -5
  426. package/dist/{tenant-P7mo0ulH.d.ts → tenant-DyZZDYmm.d.ts} +1 -1
  427. package/dist/testing/index.d.ts +56 -30
  428. package/dist/testing/index.js +58 -7
  429. package/dist/{timeline-BB9fKT_r.d.ts → timeline-Df8GMPkZ.d.ts} +5 -5
  430. package/dist/{topic-CjKlzHD-.d.ts → topic-B4fSui6P.d.ts} +5 -5
  431. package/dist/{topic-k17VvXRj.js → topic-BtoL1fKf.js} +1 -1
  432. package/dist/{types-VwM7DBvC.d.ts → types-BeXhugiI.d.ts} +2 -2
  433. package/dist/{types-DU_nNO7U.d.ts → types-BgvKQUuy.d.ts} +3 -3
  434. package/dist/{types-LLCyr-xs.d.ts → types-ByApBdXv.d.ts} +5 -5
  435. package/dist/{types-BzIYSSWK.d.ts → types-CF5j7kOm.d.ts} +4 -2
  436. package/dist/{types-kq8S5HVE.d.ts → types-CeV22tnf.d.ts} +1 -1
  437. package/dist/{types-DCzgSAlU.d.ts → types-D6GlpLD9.d.ts} +4 -4
  438. package/dist/{types-z31g0-5T.d.ts → types-DJfGy-40.d.ts} +5 -5
  439. package/dist/{types-D--4dv5K.d.ts → types-mYxPduXR.d.ts} +7 -7
  440. package/dist/{undo-BCQMqIQN.d.ts → undo-CbLZkEny.d.ts} +2 -2
  441. package/dist/{usage-CJDj5j15.d.ts → usage-BcD0X7qJ.d.ts} +4 -4
  442. package/dist/{vault-CbhvnoVC.d.ts → vault-nYFV6WUD.d.ts} +2 -2
  443. package/dist/vercel-connect/index.d.ts +1 -1
  444. package/dist/vercel-sandbox/index.d.ts +2 -2
  445. package/dist/{verify-Cpc1upDA.d.ts → verify-DxTccsBh.d.ts} +2 -2
  446. package/dist/{view-eHgOOyRS.d.ts → view-DwXy8N6Y.d.ts} +27 -3
  447. package/dist/vue/index.d.ts +10 -10
  448. package/dist/{watch-topic-jqBMNMs3.d.ts → watch-topic-DShzD8ul.d.ts} +1 -1
  449. package/dist/workflow-sdk/builder/index.d.ts +3 -3
  450. package/dist/workflow-sdk/index.d.ts +1 -1
  451. package/dist/workflow-sdk/world/index.d.ts +1 -1
  452. package/dist/{workflow-sdk-DzKQo265.d.ts → workflow-sdk-ClwzLwNe.d.ts} +3 -3
  453. package/dist/{workflows-D7HvWeNu.d.ts → workflows-ZGDa9twb.d.ts} +3 -3
  454. package/dist/yjs/index.d.ts +2 -2
  455. package/dist/yjs/index.js +1 -1
  456. package/package.json +1 -1
  457. package/schemas/config-v1.json +24 -1
  458. package/schemas/design-v1.json +7 -1
  459. package/schemas/doctor-report-v1.json +1 -0
  460. package/skills/better-supabase/SKILL.md +1 -0
  461. package/skills/better-supabase/references/ui-recipes.md +13 -15
  462. package/skills/better-supabase-auth/SKILL.md +26 -2
  463. package/skills/better-supabase-auth/references/native.md +115 -0
  464. package/dist/cli/add-CjSPssgL.js +0 -1
  465. package/dist/cli/powersync-BurpZLJB.js +0 -1
  466. package/dist/cli/seed-CLlvrV8I.js +0 -1
  467. package/dist/guest-actions-CEwttioE.js +0 -8
  468. package/dist/impersonation-BOCJcsmS.d.ts +0 -26
  469. package/dist/options-B7Pl708M.js +0 -8
  470. package/dist/options-B9w_Y08G.d.ts +0 -6
  471. package/dist/respond-8A3EOo61.js +0 -106
  472. package/dist/session-JV1z0kxa.d.ts +0 -77
@@ -3,14 +3,14 @@ import { d as temporalText } from "./temporal-DKTdGK9i.js";
3
3
  import { r as NEGATIVE, t as FILTER_OPERATORS } from "./filter-query-Ds7Z6lgZ.js";
4
4
  import { a as ok } from "./result-8xza7w5W.js";
5
5
  import { a as hasPlaceholder, l as splitPlaceholders, s as placeholderOf } from "./read-set-DEDoIHMM.js";
6
- import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-B1zfhFWC.js";
6
+ import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-CTIsFATg.js";
7
7
  import { t as DEFAULT_CLAIMS } from "./claims-CqTr_N1n.js";
8
8
  import { o as tenantNames, r as composeNames } from "./entity-naming-BES3pkQI.js";
9
- import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-Bx94JGSW.js";
10
- import { a as RATING_BOUNDS, n as CUSTOM_FIELD_TYPES, r as FIELD_FORMATS, t as CUSTOM_FIELD_FORM_TYPES } from "./field-formats-Cap-V7UP.js";
9
+ import { C as columnsWithAccess, E as hiddenColumns, L as resolveBlock, P as BLOCK_SCOPES, R as tenantNameOf, S as hasComputed, T as hasColumnAccess, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as encryptedColumns, y as lookupColumn } from "./instances-DGtu3S0m.js";
10
+ import { i as FIELD_FORMATS, n as CUSTOM_FIELD_FORM_TYPES, o as FIELD_FORMAT_VALIDATORS, r as CUSTOM_FIELD_TYPES, s as RATING_BOUNDS, t as CUSTOM_FIELD_CHECKED_FORMATS } from "./field-formats-sLYMh1ZK.js";
11
11
  import { t as isSqlType } from "./sql-type-XWMeZRAl.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-CNq9xcfx.js";
13
- import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-Dao1C0fz.js";
13
+ import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-BHat-brX.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DqQ3d6op.js";
15
15
  import { $ as pageSize, A as addNotNullCheck, B as extraFieldsArg, C as SCHEMA$5, D as addCheck, E as activeMembership, F as defaultPartitionName, G as jwtClaim, H as fail$1, I as disabledHelpers, J as membershipDisabledAt, K as lockTable, L as disabledHelpersNeedLaterTables, M as columnRef, N as columnsObject, O as addExtraColumns, P as defaultPartition, Q as ownRowPolicies, R as dropExpiredPartitions, S as PARTITION_VARIABLES, T as accessDefinesDisabledHelpers, U as insertExtraColumns, V as extraFieldsJson, W as jsonSchemaChecks, X as notNullCheckName, Y as membershipSuspended, Z as organizationMissing, _ as rolesOf, _t as updatedAt, at as replaceColumnCheck, b as MONTHLY_PARTITIONS, bt as writeExtraColumns, c as accessModel, ct as serviceGrant, d as moduleOperations, dt as shortHash, et as quotedTable$1, f as modulePermission, ft as splitTable$1, g as roleScopeIs, gt as updateExtraColumns, h as roleNames, ht as triggerGrant, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as transitionReasonSql, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as transitionActorSql, q as memberAddedRecord, rt as registerPartitions, s as OPERATIONS, st as schemaPreamble, tt as raise$1, u as isOperationModule$1, ut as sha256Hex$1, v as tenantScope, vt as userGrant, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, yt as withExtraFields, z as ensureCheck } from "./workflow-sdk-Bps7tpOv.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-Z-bd_H1E.js";
@@ -38,7 +38,7 @@ import { t as collectionsSqlOptions } from "./options-DFSHZFLN.js";
38
38
  import { t as commentsSqlOptions } from "./options-C1kZ3qLd.js";
39
39
  import { t as complianceSqlOptions } from "./options-BDF60ouf.js";
40
40
  import { t as connectorsSqlOptions } from "./options-DvgKdZ2K.js";
41
- import { t as contactsSqlOptions } from "./options-B7Pl708M.js";
41
+ import { n as REPRESENTATIVE_ROLES, r as contactsSqlOptions, t as REPRESENTATIVE_AUTHORITIES } from "./representatives-DRNDAf0i.js";
42
42
  import { t as contentSqlOptions } from "./options-mypVYaqR.js";
43
43
  import { t as contractsSqlOptions } from "./options-Bn3NjXfn.js";
44
44
  import { t as coursesSqlOptions } from "./options--rohtkkC.js";
@@ -57,6 +57,7 @@ import { t as expensesSqlOptions } from "./options-BXiUftgG.js";
57
57
  import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
58
58
  import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
59
59
  import { t as goalsSqlOptions } from "./options-BNRvoEkj.js";
60
+ import { n as guestsSqlOptions, t as GUEST_ACTIONS } from "./guest-actions-Du1ph4dE.js";
60
61
  import { r as hiringSqlOptions, t as APPLICATION_TO_EMPLOYEE } from "./automations-BfH8GJqv.js";
61
62
  import { t as identitiesSqlOptions } from "./options-D5a9CHgP.js";
62
63
  import { r as inboxSqlOptions, t as CONVERSATION_TO_TASK } from "./automations-CCc5RUw-.js";
@@ -88,7 +89,7 @@ import { t as profilesSqlOptions } from "./options-BxdqA2Ex.js";
88
89
  import { t as promotionsSqlOptions } from "./options-BvttpM1M.js";
89
90
  import { t as pushSqlOptions } from "./options-jg0FMHA5.js";
90
91
  import { n as rateLimitSqlOptions, r as webhookInboxSqlOptions, t as queueSqlOptions } from "./options-BTRH26MJ.js";
91
- import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-K0O3En6E.js";
92
+ import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-Bk-_P7Zp.js";
92
93
  import { t as reactionsSqlOptions } from "./options-BcBdiPSZ.js";
93
94
  import { t as relationsSqlOptions } from "./options-Lg76d-cV.js";
94
95
  import { t as remindersSqlOptions } from "./options-PTLBl6QT.js";
@@ -104,7 +105,7 @@ import { t as sessionsSqlOptions } from "./options-D-jiqb0l.js";
104
105
  import { t as settingsSqlOptions } from "./options-DWgpi5ns.js";
105
106
  import { t as shareLinksSqlOptions } from "./options-CsLUAt04.js";
106
107
  import { t as shipmentsSqlOptions } from "./options-Bkx8vwip.js";
107
- import { t as signaturesSqlOptions } from "./options-DUNUGuhM.js";
108
+ import { t as signaturesSqlOptions } from "./options-CpSqyI8k.js";
108
109
  import { t as signingKeysSqlOptions } from "./options-DToWdVqW.js";
109
110
  import { t as slaSqlOptions } from "./options-BmwDdKwE.js";
110
111
  import { t as ssoSqlOptions } from "./options-CzWjw2HY.js";
@@ -122,7 +123,6 @@ import { t as versionsSqlOptions } from "./options-C5MfwOAO.js";
122
123
  import { t as waitlistSqlOptions } from "./options-DFgHHwzD.js";
123
124
  import { n as webhooksOutSqlOptions, t as webhooksInSqlOptions } from "./options-BfY4pyQE.js";
124
125
  import { t as workflowEditorSqlOptions } from "./options-SlC_jZ7y.js";
125
- import { t as GUEST_ACTIONS } from "./guest-actions-CEwttioE.js";
126
126
  import { n as SUBJECT_TYPE_SQL_PATTERN, r as subjectTypeIdent, t as SUBJECT_TYPE_PATTERN } from "./subject-type-BarjdHZV.js";
127
127
  import { t as AI_MESSAGE_PART_TYPES } from "./ai-message-cnroprVB.js";
128
128
  import { t as FINAL_RUN_STATES$1 } from "./run-state-DGiyDQxH.js";
@@ -1044,7 +1044,7 @@ const DROP_POLICY$1 = /* @__PURE__ */ new RegExp(String.raw`\bdrop\s+policy\s+(?
1044
1044
  const TABLE_NAME$4 = String.raw`${NAME$9}(?:\s*\.\s*${NAME$9})?`;
1045
1045
  const DROP_TABLE = /* @__PURE__ */ new RegExp(String.raw`\bdrop\s+table\s+(?:if\s+exists\s+)?(${TABLE_NAME$4}(?:\s*,\s*${TABLE_NAME$4})*)`, "gi");
1046
1046
  function droppedTables(list) {
1047
- return (list.match(new RegExp(TABLE_NAME$4, "g")) ?? []).map(qualified$8);
1047
+ return (list.match(new RegExp(TABLE_NAME$4, "g")) ?? []).map(qualified$9);
1048
1048
  }
1049
1049
  function inOrder(statements) {
1050
1050
  for (const statement of statements.flat().toSorted((a, b) => a.index - b.index)) statement.apply();
@@ -1056,7 +1056,7 @@ const COMMANDS$2 = [
1056
1056
  "delete"
1057
1057
  ];
1058
1058
  const unquote$5 = (name) => name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name.toLowerCase();
1059
- function qualified$8(target) {
1059
+ function qualified$9(target) {
1060
1060
  const parts = (target.match(new RegExp(NAME$9, "g")) ?? []).map(unquote$5);
1061
1061
  return parts.length === 1 ? `public.${parts[0]}` : parts.join(".");
1062
1062
  }
@@ -1076,7 +1076,7 @@ function declaredTables(files, schemas) {
1076
1076
  inOrder([[...text.matchAll(TABLE$2)].map((match) => ({
1077
1077
  index: match.index,
1078
1078
  apply: () => {
1079
- const table = qualified$8(match[1]);
1079
+ const table = qualified$9(match[1]);
1080
1080
  if (schemas.includes(table.slice(0, table.indexOf(".")))) found.add(table);
1081
1081
  }
1082
1082
  })), [...text.matchAll(DROP_TABLE)].map((match) => ({
@@ -1150,11 +1150,11 @@ function declaredViews(files, schemas) {
1150
1150
  const insteadOf = /* @__PURE__ */ new Set();
1151
1151
  for (const file of files) {
1152
1152
  const text = withoutComments(file.text);
1153
- for (const match of text.matchAll(INSTEAD_OF_TRIGGER)) insteadOf.add(qualified$8(match[1]));
1153
+ for (const match of text.matchAll(INSTEAD_OF_TRIGGER)) insteadOf.add(qualified$9(match[1]));
1154
1154
  inOrder([[...text.matchAll(VIEW)].map((match) => ({
1155
1155
  index: match.index,
1156
1156
  apply: () => {
1157
- const view = qualified$8(match[2]);
1157
+ const view = qualified$9(match[2]);
1158
1158
  if (!schemas.includes(view.slice(0, view.indexOf(".")))) return;
1159
1159
  let at = match.index + match[0].length;
1160
1160
  let listed;
@@ -1203,7 +1203,7 @@ function rlsTables(files, schemas) {
1203
1203
  inOrder([[...text.matchAll(RLS_TOGGLE)].map((match) => ({
1204
1204
  index: match.index,
1205
1205
  apply: () => {
1206
- const table = qualified$8(match[1]);
1206
+ const table = qualified$9(match[1]);
1207
1207
  if (!schemas.includes(table.slice(0, table.indexOf(".")))) return;
1208
1208
  if (match[2].toLowerCase() === "enable") found.add(table);
1209
1209
  else found.delete(table);
@@ -1238,7 +1238,7 @@ function declaredColumnTypes(files, schemas) {
1238
1238
  for (const file of files) {
1239
1239
  const text = withoutComments(file.text);
1240
1240
  for (const match of text.matchAll(TABLE$2)) {
1241
- const table = qualified$8(match[1]);
1241
+ const table = qualified$9(match[1]);
1242
1242
  if (!schemas.includes(table.slice(0, table.indexOf(".")))) continue;
1243
1243
  const open = match.index + match[0].length - 1;
1244
1244
  const close = closingParen(text, open);
@@ -1263,7 +1263,7 @@ function typeName(text) {
1263
1263
  const ENUM = /* @__PURE__ */ new RegExp(String.raw`\bcreate\s+type\s+(${NAME$9}(?:\s*\.\s*${NAME$9})?)\s+as\s+enum\b`, "gi");
1264
1264
  /** The enum types `files` create (`create type ... as enum`), as `schema.type`. */
1265
1265
  function declaredEnums(files) {
1266
- return new Set(files.flatMap((file) => [...withoutComments(file.text).matchAll(ENUM)].map((match) => qualified$8(match[1]))));
1266
+ return new Set(files.flatMap((file) => [...withoutComments(file.text).matchAll(ENUM)].map((match) => qualified$9(match[1]))));
1267
1267
  }
1268
1268
  function closingParen(text, open) {
1269
1269
  let depth = 0;
@@ -1316,7 +1316,7 @@ function policyGrants(files, schemas) {
1316
1316
  [...text.matchAll(POLICY$1)].map((match) => ({
1317
1317
  index: match.index,
1318
1318
  apply: () => {
1319
- const table = qualified$8(match[2]);
1319
+ const table = qualified$9(match[2]);
1320
1320
  if (!schemas.includes(table.slice(0, table.indexOf(".")))) return;
1321
1321
  const clauses = match[3];
1322
1322
  if (/\bas\s+restrictive\b/i.test(clauses)) return;
@@ -1334,7 +1334,7 @@ function policyGrants(files, schemas) {
1334
1334
  [...text.matchAll(DROP_POLICY$1)].map((match) => ({
1335
1335
  index: match.index,
1336
1336
  apply: () => {
1337
- policies.get(qualified$8(match[2]))?.delete(unquote$5(match[1]));
1337
+ policies.get(qualified$9(match[2]))?.delete(unquote$5(match[1]));
1338
1338
  }
1339
1339
  })),
1340
1340
  [...text.matchAll(DROP_TABLE)].map((match) => ({
@@ -1387,12 +1387,12 @@ const SETS_UPDATED_AT$1 = /\bnew\s*\.\s*"?updated_at"?\s*:?=/i;
1387
1387
  function declaredUpdatedAtTriggers(files, schemas) {
1388
1388
  const texts = files.map((file) => withoutComments(file.text));
1389
1389
  const setters = /* @__PURE__ */ new Set();
1390
- for (const text of texts) for (const match of text.matchAll(FUNCTION_DEF)) if (SETS_UPDATED_AT$1.test(match[3])) setters.add(qualified$8(match[1]));
1390
+ for (const text of texts) for (const match of text.matchAll(FUNCTION_DEF)) if (SETS_UPDATED_AT$1.test(match[3])) setters.add(qualified$9(match[1]));
1391
1391
  const found = {};
1392
1392
  for (const text of texts) for (const match of text.matchAll(TRIGGER_DEF)) {
1393
1393
  const name = unquote$5(match[1]);
1394
- const table = qualified$8(match[2]);
1395
- const fn = qualified$8(match[3]);
1394
+ const table = qualified$9(match[2]);
1395
+ const fn = qualified$9(match[3]);
1396
1396
  if (!name.startsWith("bsb_") && schemas.includes(table.slice(0, table.indexOf("."))) && (UPDATED_AT_FUNCTION.test(fn.slice(fn.indexOf(".") + 1)) || setters.has(fn))) found[table] ??= name;
1397
1397
  }
1398
1398
  return found;
@@ -1425,7 +1425,7 @@ function indexStatements(text) {
1425
1425
  const rest = text.slice(close + 1, end === -1 ? text.length : end);
1426
1426
  return [{
1427
1427
  name: match[2] === void 0 ? void 0 : unquote$5(match[2]),
1428
- table: qualified$8(match[3]),
1428
+ table: qualified$9(match[3]),
1429
1429
  unique: match[1] !== void 0,
1430
1430
  method: (match[4] ?? "btree").toLowerCase(),
1431
1431
  partial: /\bwhere\b/i.test(rest),
@@ -1453,7 +1453,7 @@ function declaredIndexes(files, schemas) {
1453
1453
  const text = withoutComments(file.text);
1454
1454
  for (const index of indexStatements(text)) if (!index.partial && index.method === "btree") add(index.table, index.columns, index.name);
1455
1455
  for (const match of text.matchAll(TABLE$2)) {
1456
- const table = qualified$8(match[1]);
1456
+ const table = qualified$9(match[1]);
1457
1457
  const open = match.index + match[0].length - 1;
1458
1458
  const close = closingParen(text, open);
1459
1459
  if (close === -1) continue;
@@ -1570,7 +1570,7 @@ const ENSURE_CHECK = /^do \$\$\nbegin\n {2}if coalesce\(obj_description\(\(\n\s+
1570
1570
  */
1571
1571
  function withoutAppTableEdits(sql, appTables) {
1572
1572
  if (appTables.size === 0) return sql;
1573
- const drop = (statement, table) => appTables.has(qualified$8(table)) ? "" : statement;
1573
+ const drop = (statement, table) => appTables.has(qualified$9(table)) ? "" : statement;
1574
1574
  return sql.replaceAll(ALTER_CONSTRAINT, drop).replaceAll(REVOKE, drop).replaceAll(ENSURE_CHECK, drop);
1575
1575
  }
1576
1576
  /**
@@ -1601,7 +1601,7 @@ function overAppViews(sql, views) {
1601
1601
  const statement = sql.slice(from, to);
1602
1602
  const masked = maskComments(statement);
1603
1603
  const target = DDL_TARGETS.map((pattern) => pattern.exec(masked)?.[1]).find((match) => match !== void 0);
1604
- const view = target === void 0 ? void 0 : qualified$8(target);
1604
+ const view = target === void 0 ? void 0 : qualified$9(target);
1605
1605
  if (view === void 0 || !views.has(view)) return statement;
1606
1606
  const lead = /^\s*/.exec(statement)[0];
1607
1607
  if (said.has(view)) return "";
@@ -1634,7 +1634,7 @@ function overAppTables(sql, appTables, appColumns = {}) {
1634
1634
  let out = "";
1635
1635
  let at = 0;
1636
1636
  for (const match of masked.matchAll(TABLE$2)) {
1637
- const table = qualified$8(match[1]);
1637
+ const table = qualified$9(match[1]);
1638
1638
  if (!appTables.has(table) || match.index < at) continue;
1639
1639
  const open = match.index + match[0].length - 1;
1640
1640
  const close = closingParen(masked, open);
@@ -1780,7 +1780,7 @@ function policiesOn(statements, appTables) {
1780
1780
  for (const { masked } of statements) {
1781
1781
  const match = CREATE_POLICY.exec(masked);
1782
1782
  if (match === null || isBlockName(match[2])) continue;
1783
- const table = qualified$8(match[4]);
1783
+ const table = qualified$9(match[4]);
1784
1784
  if (!appTables.has(table)) continue;
1785
1785
  const command = COMMAND.exec(masked)?.[1]?.toLowerCase() ?? "all";
1786
1786
  const list = found.get(table) ?? [];
@@ -1810,27 +1810,27 @@ function blockNamesOnAppTables(sql, appTables, updatedAtTriggers = {}) {
1810
1810
  return statements.map(({ text, masked: statement }) => {
1811
1811
  const create = CREATE_POLICY.exec(statement);
1812
1812
  if (create !== null) {
1813
- const name = policies.get(qualified$8(create[4]))?.get(unquote$5(create[2]));
1813
+ const name = policies.get(qualified$9(create[4]))?.get(unquote$5(create[2]));
1814
1814
  return name === void 0 || isBlockName(create[2]) ? text : renamed(text, create, 2, name);
1815
1815
  }
1816
1816
  const policy = POLICY_REFERENCE.exec(statement);
1817
1817
  if (policy !== null && !isBlockName(policy[2])) {
1818
- const table = qualified$8(policy[4]);
1818
+ const table = qualified$9(policy[4]);
1819
1819
  if (!appTables.has(table)) return text;
1820
1820
  const name = policies.get(table)?.get(unquote$5(policy[2]));
1821
1821
  return name === void 0 ? leading(text, policy) : renamed(text, policy, 2, name);
1822
1822
  }
1823
1823
  const trigger = CREATE_TRIGGER.exec(statement);
1824
- if (trigger !== null && appTables.has(qualified$8(trigger[4]))) {
1825
- const kept = updatedAtTriggers[qualified$8(trigger[4])];
1824
+ if (trigger !== null && appTables.has(qualified$9(trigger[4]))) {
1825
+ const kept = updatedAtTriggers[qualified$9(trigger[4])];
1826
1826
  if (kept !== void 0 && SETS_UPDATED_AT.test(statement)) return `${leading(text, trigger)}
1827
- -- ${qualified$8(trigger[4])} keeps updated_at current with its own trigger ${kept}.`;
1827
+ -- ${qualified$9(trigger[4])} keeps updated_at current with its own trigger ${kept}.`;
1828
1828
  return isBlockName(trigger[2]) ? text : renamed(text, trigger, 2, blockTriggerName(unquote$5(trigger[2])));
1829
1829
  }
1830
1830
  const reference = TRIGGER_REFERENCE.exec(statement);
1831
- if (reference !== null && appTables.has(qualified$8(reference[4])) && !isBlockName(reference[2])) return renamed(text, reference, 2, blockTriggerName(unquote$5(reference[2])));
1831
+ if (reference !== null && appTables.has(qualified$9(reference[4])) && !isBlockName(reference[2])) return renamed(text, reference, 2, blockTriggerName(unquote$5(reference[2])));
1832
1832
  const toggle = TABLE_TRIGGER.exec(statement);
1833
- if (toggle !== null && appTables.has(qualified$8(toggle[2])) && !isBlockName(toggle[4])) return renamed(text, toggle, 4, blockTriggerName(unquote$5(toggle[4])));
1833
+ if (toggle !== null && appTables.has(qualified$9(toggle[2])) && !isBlockName(toggle[4])) return renamed(text, toggle, 4, blockTriggerName(unquote$5(toggle[4])));
1834
1834
  return text;
1835
1835
  }).join("");
1836
1836
  }
@@ -2194,7 +2194,7 @@ const BLOCK_OPTION_SCHEMAS = {
2194
2194
  forecasts: NO_OPTIONS,
2195
2195
  forms: formsSqlOptions,
2196
2196
  goals: goalsSqlOptions,
2197
- guests: NO_OPTIONS,
2197
+ guests: guestsSqlOptions,
2198
2198
  hiring: hiringSqlOptions,
2199
2199
  idempotency: NO_OPTIONS,
2200
2200
  impersonation: impersonationSqlOptions,
@@ -8557,7 +8557,7 @@ function managerOf(ctx, requester, tenant, employee) {
8557
8557
  return `(select mgr.${e("user")} from ${table} me
8558
8558
  join ${table} mgr on mgr.${e("id")} = me.${e("manager")}
8559
8559
  where me.${e("tenant")} = ${tenant} and ${who}
8560
- and mgr.${e("user")} is not null and mgr.${e("status")}::text <> 'offboarded'
8560
+ and mgr.${e("user")} is not null and ${employees.is("employees", "status", `mgr.${e("status")}`, ["offboarded"], true)}
8561
8561
  limit 1)`;
8562
8562
  }
8563
8563
  /** Whether `user` is the requester's manager and still a member. */
@@ -8684,6 +8684,13 @@ $$;
8684
8684
  revoke execute on function ${signature} from public, anon, authenticated;${payload ? approvalConditionSql(ctx) : ""}`;
8685
8685
  }
8686
8686
  /**
8687
+ * `steps` with `required: "all"` on a step that only lists users replaced by
8688
+ * their count, as the config parser does.
8689
+ */
8690
+ const allUsersCounted = (steps) => `(select coalesce(jsonb_agg(case when s -> 'required' = '"all"'::jsonb and (s -> 'approvers') ? 'users'
8691
+ then jsonb_set(s, '{required}', to_jsonb(jsonb_array_length(s -> 'approvers' -> 'users'))) else s end order by o), '[]'::jsonb)
8692
+ from jsonb_array_elements(${steps}) with ordinality e(s, o))`;
8693
+ /**
8687
8694
  * PL/pgSQL that raises `invalid` unless every step of `steps` (a jsonb array
8688
8695
  * expression) names approvers and a valid required count and escalation. It
8689
8696
  * reads and writes `v_step` and `v_who`.
@@ -8704,7 +8711,10 @@ const stepsCheck$1 = (steps, invalid, manager) => ` for v_step in select * from
8704
8711
  end loop;
8705
8712
  if (v_step ? 'required' and v_step -> 'required' <> '"all"'::jsonb and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
8706
8713
  or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric)))
8707
- or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb)
8714
+ or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb
8715
+ and ((v_step -> 'approvers') - 'users' <> '{}'::jsonb or jsonb_array_length(v_step -> 'approvers' -> 'users') = 0))
8716
+ or (jsonb_typeof(v_step -> 'required') = 'number' and (v_step -> 'approvers') - 'users' = '{}'::jsonb
8717
+ and (v_step ->> 'required')::numeric > jsonb_array_length(v_step -> 'approvers' -> 'users'))
8708
8718
  or ((v_step ? 'escalateAfter') <> (v_step ? 'escalateTo'))
8709
8719
  or (v_step ? 'escalateAfter' and (jsonb_typeof(v_step -> 'escalateAfter') <> 'string' or (v_step ->> 'escalateAfter')::interval <= interval '0')) then
8710
8720
  ${invalid}
@@ -8835,6 +8845,7 @@ begin
8835
8845
  ${stepsInvalid}
8836
8846
  end if;
8837
8847
  ${stepsCheck$1("v_steps", stepsInvalid, manager)}
8848
+ v_steps := ${allUsersCounted("v_steps")};
8838
8849
  if coalesce(save_approval_policy.policy ->> 'mode', v_old.${p("mode")}::text, 'authorize') not in ('confirm', 'authorize') then
8839
8850
  ${fail$1("APPROVAL_POLICY_INVALID", "mode must be confirm or authorize", "22023")}
8840
8851
  end if;
@@ -9006,6 +9017,7 @@ begin
9006
9017
  ${ownInvalid}
9007
9018
  end if;
9008
9019
  ${stepsCheck$1("v_steps", ownInvalid, manager)}
9020
+ v_steps := ${allUsersCounted("v_steps")};
9009
9021
  v_expires := (approval_policy_tighten.own ->> 'expiresIn')::interval;
9010
9022
  if approval_policy_tighten.base is null then
9011
9023
  return jsonb_build_object(
@@ -9638,6 +9650,7 @@ function approverCheck(ctx, layout, request) {
9638
9650
  subject: request.subject,
9639
9651
  tenant: request.tenant,
9640
9652
  requester: request.requester,
9653
+ approvers: request.approvers ?? "null::jsonb",
9641
9654
  scope: provider.scope
9642
9655
  }),
9643
9656
  template: "isApprover",
@@ -10377,7 +10390,7 @@ const TRASH = {
10377
10390
  build: build$114
10378
10391
  };
10379
10392
  // src/sql/modules/drive-kit.ts
10380
- const SUBJECT_TYPE$1 = /^[a-z][a-z0-9_]{0,62}$/;
10393
+ const SUBJECT_TYPE$2 = /^[a-z][a-z0-9_]{0,62}$/;
10381
10394
  const ROLE$1 = /^[a-z][a-z0-9_]{0,30}$/;
10382
10395
  const SOURCE = /^[a-z][a-z0-9-]{0,30}$/;
10383
10396
  const CONFLICTS = [
@@ -10745,7 +10758,7 @@ function driveSubjectGuard(ctx) {
10745
10758
  /** `options.subjectType`: the subject type of a node, `drive_node` by default. */
10746
10759
  function driveSubjectType(ctx) {
10747
10760
  const type = ctx.text("subjectType", "drive_node");
10748
- if (!SUBJECT_TYPE$1.test(type)) throw new TypeError("blocks.drive.options.subjectType must be lowercase letters, digits and underscores");
10761
+ if (!SUBJECT_TYPE$2.test(type)) throw new TypeError("blocks.drive.options.subjectType must be lowercase letters, digits and underscores");
10749
10762
  return type;
10750
10763
  }
10751
10764
  function conflictDefault(ctx) {
@@ -11717,7 +11730,8 @@ function build$112(ctx, layout) {
11717
11730
  kind: { sql: `v_req.${c("subjectType")} || '.' || v_req.${c("action")}` },
11718
11731
  subject: `v_req.${c("subjectId")}::text`,
11719
11732
  tenant: `v_req.${c("tenant")}`,
11720
- requester: `v_req.${c("requestedBy")}`
11733
+ requester: `v_req.${c("requestedBy")}`,
11734
+ approvers: "(coalesce(v_approvers, '{}'::jsonb) || jsonb_build_object('required', coalesce(v_step -> 'required', '1'::jsonb)))"
11721
11735
  });
11722
11736
  const subjects = subjectsOption(ctx);
11723
11737
  const fn = (name) => ctx.fn(name);
@@ -26172,7 +26186,7 @@ ${forgetDropped(ctx)}`,
26172
26186
  tests: (ctx, layout) => auditTests(ctx, layout.auditedTables ?? [], restrictedOn(ctx))
26173
26187
  };
26174
26188
  // src/sql/modules/automations-tables.ts
26175
- const SUBJECT_TYPE = SUBJECT_TYPE_SQL_PATTERN;
26189
+ const SUBJECT_TYPE$1 = SUBJECT_TYPE_SQL_PATTERN;
26176
26190
  const TRIGGER$1 = "^[a-z][a-z0-9_]*([.:][a-z0-9_]+)*$";
26177
26191
  const ACTION_KIND = "^[a-z][a-z0-9_]*([.][a-z0-9_]+)*$";
26178
26192
  const FIELD_ID = "^[A-Za-z_][A-Za-z0-9_]*([.][A-Za-z_][A-Za-z0-9_]*)*$";
@@ -26213,7 +26227,7 @@ create unique index if not exists ${ctx.naming.rename("rules_default_key_idx")}
26213
26227
  ${createTable(ctx, "rules", [
26214
26228
  ["id", "uuid primary key default gen_random_uuid()"],
26215
26229
  ["tenant", `${id} not null`],
26216
- ["subjectType", `text not null check (${r("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
26230
+ ["subjectType", `text not null check (${r("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
26217
26231
  ["trigger", `text not null check (length(${r("trigger")}) <= 128 and ${r("trigger")} ~ ${sqlString(TRIGGER$1)})`],
26218
26232
  ["name", `text not null check (length(${r("name")}) between 1 and 200)`],
26219
26233
  ["description", `text check (length(${r("description")}) <= 2000)`],
@@ -26237,7 +26251,7 @@ ${lockTable(t)}
26237
26251
  ${createTable(ctx, "defaults", [
26238
26252
  ["key", `text primary key check (length(${rd("key")}) <= 128 and ${rd("key")} ~ ${sqlString(ACTION_KIND)})`],
26239
26253
  ["block", "text not null"],
26240
- ["subjectType", `text not null check (${rd("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
26254
+ ["subjectType", `text not null check (${rd("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
26241
26255
  ["trigger", `text not null check (length(${rd("trigger")}) <= 128 and ${rd("trigger")} ~ ${sqlString(TRIGGER$1)})`],
26242
26256
  ["name", `text not null check (length(${rd("name")}) between 1 and 200)`],
26243
26257
  ["description", `text check (length(${rd("description")}) <= 2000)`],
@@ -26286,7 +26300,7 @@ ${lockTable(e)}
26286
26300
  -- The fields rules may test, per subject type. The app declares them in code
26287
26301
  -- (defineRuleFields) and syncs them with the service role.
26288
26302
  ${createTable(ctx, "fields", [
26289
- ["subjectType", `text not null check (${rf("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
26303
+ ["subjectType", `text not null check (${rf("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
26290
26304
  ["id", `text not null check (length(${rf("id")}) <= 128 and ${rf("id")} ~ ${sqlString(FIELD_ID)})`],
26291
26305
  ["label", "text not null"],
26292
26306
  ["description", "text"],
@@ -27329,7 +27343,7 @@ begin
27329
27343
  if not ${canKey("save_rule.tenant", `(v_enabled or coalesce(v_old.${r("enabled")}, false))`)} then
27330
27344
  ${raise$1("You need % to save this rule", "42501", "RULE_FORBIDDEN", keyFor(`(v_enabled or coalesce(v_old.${r("enabled")}, false))`))}
27331
27345
  end if;
27332
- if v_subject_type is null or v_subject_type !~ ${sqlString(SUBJECT_TYPE)} then
27346
+ if v_subject_type is null or v_subject_type !~ ${sqlString(SUBJECT_TYPE$1)} then
27333
27347
  ${fail$1("RULE_INVALID", "A rule needs a subject type", "22023")}
27334
27348
  end if;
27335
27349
  if v_trigger is null or length(v_trigger) > 128 or v_trigger !~ ${sqlString(TRIGGER$1)} then
@@ -29049,9 +29063,9 @@ function plansOf(ctx) {
29049
29063
  ...variant === void 0 ? {} : { variant }
29050
29064
  };
29051
29065
  }
29052
- const qualified$7 = (table) => quotedTable$1(table);
29066
+ const qualified$8 = (table) => quotedTable$1(table);
29053
29067
  const platformPlans = (plans) => plans && {
29054
- table: qualified$7(plans.table),
29068
+ table: qualified$8(plans.table),
29055
29069
  key: plans.key,
29056
29070
  price: plans.price
29057
29071
  };
@@ -29069,7 +29083,7 @@ stable
29069
29083
  security definer
29070
29084
  set search_path = ''
29071
29085
  as $$
29072
- ${plans ? `select p.${sqlIdent(plans.price)}::text from ${qualified$7(plans.table)} p
29086
+ ${plans ? `select p.${sqlIdent(plans.price)}::text from ${qualified$8(plans.table)} p
29073
29087
  where p.${sqlIdent(plans.key)}::text = billing_plan_price.plan${plans.interval ? `
29074
29088
  and (billing_plan_price.billing_interval is null or p.${sqlIdent(plans.interval)}::text = billing_plan_price.billing_interval)` : ""}${plans.variant ? `
29075
29089
  and (billing_plan_price.variant is null or p.${sqlIdent(plans.variant)}::text = billing_plan_price.variant)` : ""}${plans.active ? `
@@ -32446,7 +32460,7 @@ const ALARM_ACTIONS = [
32446
32460
  const TRIGGER_BOUND = 525600;
32447
32461
  /** At most this many alarms per event. */
32448
32462
  const ALARM_LIMIT = 20;
32449
- const list$9 = (values) => `(${values.map((value) => `'${value}'`).join(", ")})`;
32463
+ const list$10 = (values) => `(${values.map((value) => `'${value}'`).join(", ")})`;
32450
32464
  /**
32451
32465
  * The `calendar_event_alarms` table: one row per `VALARM` of an event, with an
32452
32466
  * offset in minutes before the start or end (`offset_minutes`, the reminders
@@ -32480,7 +32494,7 @@ function alarmsTable(ctx) {
32480
32494
  ...ctx.has("alarms", "method") ? [addCheck({
32481
32495
  table: alarms,
32482
32496
  name: `${name}_method_check`,
32483
- expression: `${l("method")} in ${list$9(ALARM_ACTIONS)}`
32497
+ expression: `${l("method")} in ${list$10(ALARM_ACTIONS)}`
32484
32498
  })] : [],
32485
32499
  addCheck({
32486
32500
  table: alarms,
@@ -32568,7 +32582,7 @@ function alarmWrites(ctx) {
32568
32582
  if exists (
32569
32583
  select 1 from jsonb_array_elements(v_item -> 'alarms') x
32570
32584
  where jsonb_typeof(x) <> 'object'
32571
- or coalesce(x ->> 'method', 'display') not in ${list$9(ALARM_ACTIONS)}
32585
+ or coalesce(x ->> 'method', 'display') not in ${list$10(ALARM_ACTIONS)}
32572
32586
  or coalesce(x ->> 'related', 'start') not in ('start', 'end')
32573
32587
  or (x ->> 'offsetMinutes' is null) = (x ->> 'at' is null)
32574
32588
  or abs(coalesce((x ->> 'offsetMinutes')::integer, 0)) > ${TRIGGER_BOUND}
@@ -43513,6 +43527,13 @@ drop function if exists ${fn("comments_after_write")}();`;
43513
43527
  // src/sql/modules/compliance-shared.ts
43514
43528
  /** The keys the control reads return next to the extra columns. */
43515
43529
  const CONTROL_RESERVED = ["fields", "status"];
43530
+ /** What a framework is: a standard, a law, the organization's own or a contract. */
43531
+ const FRAMEWORK_KINDS = [
43532
+ "standard",
43533
+ "legal",
43534
+ "internal",
43535
+ "contract"
43536
+ ];
43516
43537
  /** The attachments module, when its table is there to reference. */
43517
43538
  function evidenceAttachments(ctx) {
43518
43539
  return ctx.installed("attachments") && ctx.of("attachments").manages ? ctx.of("attachments") : void 0;
@@ -43520,8 +43541,10 @@ function evidenceAttachments(ctx) {
43520
43541
  /** `row.column`, or null when the app's table lacks the optional column. */
43521
43542
  const optionalField$1 = (ctx, table, row, column) => ctx.has(table, column) ? `${row}.${ctx.col(table, column)}` : "null";
43522
43543
  // src/sql/modules/compliance-functions.ts
43544
+ /** The arguments of save_control before it took a source and a jurisdiction. */
43545
+ const PREVIOUS_CONTROL_ARGS = "uuid, text, text, text, uuid, boolean, uuid";
43523
43546
  /** The framework, control, evidence and evidence task functions. */
43524
- function controlsFunctions(ctx) {
43547
+ function complianceFunctions(ctx) {
43525
43548
  const frameworks = ctx.table("frameworks");
43526
43549
  const controls = ctx.table("controls");
43527
43550
  const evidence = ctx.table("evidence");
@@ -43545,9 +43568,12 @@ function controlsFunctions(ctx) {
43545
43568
  const insertCol = (table, column) => has(table, column) ? `, ${ctx.col(table, column)}` : "";
43546
43569
  const insertVal = (table, column, value) => has(table, column) ? `, ${value}` : "";
43547
43570
  const touch = (table) => has(table, "updatedAt") ? `, ${ctx.col(table, "updatedAt")} = now()` : "";
43571
+ const labels = ["source", "jurisdiction"].filter((column) => has("controls", column));
43572
+ const labelSets = (row) => labels.map((column) => `, ${k(column)} = ${row}.${k(column)}`).join("");
43573
+ const labelUpdates = labels.map((column) => `${k(column)} = nullif(trim(save_control.${column}), ''), `).join("");
43548
43574
  const assignee = has("tasks", "assignee");
43549
43575
  const owner = has("controls", "owner");
43550
- const frameworkSets = [`${f("name")} = excluded.${f("name")}${has("frameworks", "version") ? `, ${f("version")} = excluded.${f("version")}` : ""}`, [has("frameworks", "description") ? `${f("description")} = excluded.${f("description")}` : "", has("frameworks", "updatedAt") ? `${f("updatedAt")} = now()` : ""].filter((set) => set !== "").join(", ")].filter((line) => line !== "").join(",\n ");
43576
+ const frameworkSets = [`${f("name")} = excluded.${f("name")}${has("frameworks", "kind") ? `, ${f("kind")} = excluded.${f("kind")}` : ""}${has("frameworks", "version") ? `, ${f("version")} = excluded.${f("version")}` : ""}`, [has("frameworks", "description") ? `${f("description")} = excluded.${f("description")}` : "", has("frameworks", "updatedAt") ? `${f("updatedAt")} = now()` : ""].filter((set) => set !== "").join(", ")].filter((line) => line !== "").join(",\n ");
43551
43577
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
43552
43578
  const forbidden = (message) => fail$1("CONTROLS_FORBIDDEN", message);
43553
43579
  const invalid = (message) => fail$1("CONTROLS_INVALID", message, "22023");
@@ -43562,8 +43588,8 @@ function controlsFunctions(ctx) {
43562
43588
  when exists (select 1 from ${evidence} se where se.${e("control")} = ${row}.${k("id")}) then 'failing'
43563
43589
  else 'not_started'
43564
43590
  end`;
43565
- const controlJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'frameworkId', ${row}.${k("framework")}, 'code', ${row}.${k("code")}, 'title', ${row}.${k("title")}, 'description', ${field("controls", row, "description")}, 'ownerId', ${field("controls", row, "owner")}, 'applicable', ${row}.${k("applicable")}, 'status', ${status(row)}, 'createdAt', ${field("controls", row, "createdAt")}, 'updatedAt', ${field("controls", row, "updatedAt")}${extraFieldsJson(row, extras)})`;
43566
- const frameworkJson = (row) => `jsonb_build_object('id', ${row}.${f("id")}, 'organizationId', ${row}.${f("tenant")}, 'key', ${row}.${f("key")}, 'name', ${row}.${f("name")}, 'version', ${field("frameworks", row, "version")}, 'description', ${field("frameworks", row, "description")}, 'createdAt', ${field("frameworks", row, "createdAt")}, 'updatedAt', ${field("frameworks", row, "updatedAt")})`;
43591
+ const controlJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'frameworkId', ${row}.${k("framework")}, 'code', ${row}.${k("code")}, 'title', ${row}.${k("title")}, 'description', ${field("controls", row, "description")}, 'ownerId', ${field("controls", row, "owner")}, 'applicable', ${row}.${k("applicable")}, 'source', ${field("controls", row, "source")}, 'jurisdiction', ${field("controls", row, "jurisdiction")}, 'status', ${status(row)}, 'createdAt', ${field("controls", row, "createdAt")}, 'updatedAt', ${field("controls", row, "updatedAt")}${extraFieldsJson(row, extras)})`;
43592
+ const frameworkJson = (row) => `jsonb_build_object('id', ${row}.${f("id")}, 'organizationId', ${row}.${f("tenant")}, 'key', ${row}.${f("key")}, 'name', ${row}.${f("name")}, 'kind', ${has("frameworks", "kind") ? `${row}.${f("kind")}` : "'standard'"}, 'version', ${field("frameworks", row, "version")}, 'description', ${field("frameworks", row, "description")}, 'createdAt', ${field("frameworks", row, "createdAt")}, 'updatedAt', ${field("frameworks", row, "updatedAt")})`;
43567
43593
  const evidenceJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'organizationId', ${row}.${e("tenant")}, 'controlId', ${row}.${e("control")}, 'evidenceTaskId', ${row}.${e("task")}, 'attachmentId', ${row}.${e("attachment")}, 'note', ${field("evidence", row, "note")}, 'collectedBy', ${row}.${e("collectedBy")}, 'collectedAt', ${row}.${e("collectedAt")}, 'validUntil', ${row}.${e("validUntil")}, 'valid', ${valid(row)})`;
43568
43594
  const taskJson = (row) => `jsonb_build_object('id', ${row}.${t("id")}, 'organizationId', ${row}.${t("tenant")}, 'controlId', ${row}.${t("control")}, 'title', ${row}.${t("title")}, 'assigneeId', ${field("tasks", row, "assignee")}, 'intervalDays', ${row}.${t("intervalDays")}, 'dueOn', ${row}.${t("dueOn")}, 'lastCollectedAt', ${field("tasks", row, "lastCollectedAt")}, 'active', ${row}.${t("active")}, 'overdue', ${overdue(row)}, 'createdAt', ${field("tasks", row, "createdAt")}, 'updatedAt', ${field("tasks", row, "updatedAt")})`;
43569
43595
  const attachmentCheck = attachments === void 0 ? `if add_control_evidence.attachment_id is not null then
@@ -43591,7 +43617,10 @@ function controlsFunctions(ctx) {
43591
43617
  end if;` : "";
43592
43618
  return `
43593
43619
  -- Creates or updates a framework (SOC 2, ISO 27001, an internal one) by key.
43594
- create or replace function ${fn("save_control_framework")}(tenant ${idType}, key text, name text, version text default null, description text default null)
43620
+ -- kind is standard, legal (a register of legal obligations), internal or
43621
+ -- contract.
43622
+ drop function if exists ${fn("save_control_framework")}(${idType}, text, text, text, text);
43623
+ create or replace function ${fn("save_control_framework")}(tenant ${idType}, key text, name text, version text default null, description text default null, kind text default 'standard')
43595
43624
  returns jsonb
43596
43625
  language plpgsql
43597
43626
  security definer
@@ -43604,15 +43633,18 @@ begin
43604
43633
  if not ${allowed("save_control_framework.tenant", manage)} then
43605
43634
  ${forbidden("not allowed to manage controls")}
43606
43635
  end if;
43607
- insert into ${frameworks} (${f("tenant")}, ${f("key")}, ${f("name")}${insertCol("frameworks", "version")}${insertCol("frameworks", "description")})
43608
- values (save_control_framework.tenant, save_control_framework.key, trim(save_control_framework.name)${insertVal("frameworks", "version", "nullif(trim(save_control_framework.version), '')")}${insertVal("frameworks", "description", "nullif(trim(save_control_framework.description), '')")})
43636
+ if save_control_framework.kind is null or save_control_framework.kind not in (${FRAMEWORK_KINDS.map((item) => `'${item}'`).join(", ")}) then
43637
+ ${invalid(`kind must be one of ${FRAMEWORK_KINDS.join(", ")}`)}
43638
+ end if;
43639
+ insert into ${frameworks} (${f("tenant")}, ${f("key")}, ${f("name")}${insertCol("frameworks", "kind")}${insertCol("frameworks", "version")}${insertCol("frameworks", "description")})
43640
+ values (save_control_framework.tenant, save_control_framework.key, trim(save_control_framework.name)${insertVal("frameworks", "kind", "save_control_framework.kind")}${insertVal("frameworks", "version", "nullif(trim(save_control_framework.version), '')")}${insertVal("frameworks", "description", "nullif(trim(save_control_framework.description), '')")})
43609
43641
  on conflict (${f("tenant")}, ${f("key")}) do update
43610
43642
  set ${frameworkSets}
43611
43643
  returning * into v_row;
43612
43644
  return ${frameworkJson("v_row")};
43613
43645
  end;
43614
43646
  $$;
43615
- ${userGrant(`${fn("save_control_framework")}(${idType}, text, text, text, text)`)}
43647
+ ${userGrant(`${fn("save_control_framework")}(${idType}, text, text, text, text, text)`)}
43616
43648
 
43617
43649
  create or replace function ${fn("list_control_frameworks")}(tenant ${idType})
43618
43650
  returns jsonb
@@ -43629,8 +43661,12 @@ ${userGrant(`${fn("list_control_frameworks")}(${idType})`)}
43629
43661
 
43630
43662
  -- Creates a control in a framework, or changes one (control_id). Without
43631
43663
  -- control_id, a control with the same code in the framework is updated.
43632
- ${extra.drop(fn("save_control"), "uuid, text, text, text, uuid, boolean, uuid")}
43633
- create or replace function ${fn("save_control")}(framework_id uuid, code text, title text, description text default null, owner_id uuid default null, applicable boolean default true, control_id uuid default null${extra.param})
43664
+ -- source names where an obligation comes from (a law or a clause) and
43665
+ -- jurisdiction where it applies.
43666
+ drop function if exists ${fn("save_control")}(${PREVIOUS_CONTROL_ARGS});
43667
+ drop function if exists ${fn("save_control")}(${PREVIOUS_CONTROL_ARGS}, jsonb);
43668
+ ${extra.drop(fn("save_control"), `${PREVIOUS_CONTROL_ARGS}, text, text`)}
43669
+ create or replace function ${fn("save_control")}(framework_id uuid, code text, title text, description text default null, owner_id uuid default null, applicable boolean default true, control_id uuid default null, source text default null, jurisdiction text default null${extra.param})
43634
43670
  returns jsonb
43635
43671
  language plpgsql
43636
43672
  security definer
@@ -43656,15 +43692,15 @@ ${owner ? ` if save_control.owner_id is not null and not ${isMember(`v_framewor
43656
43692
  ${invalid("the owner must be a member of the organization")}
43657
43693
  end if;
43658
43694
  ` : ""} if save_control.control_id is null then
43659
- insert into ${controls} (${k("tenant")}, ${k("framework")}, ${k("code")}, ${k("title")}${insertCol("controls", "description")}${insertCol("controls", "owner")}, ${k("applicable")})
43660
- values (v_framework.${f("tenant")}, v_framework.${f("id")}, trim(save_control.code), trim(save_control.title)${insertVal("controls", "description", "nullif(trim(save_control.description), '')")}${insertVal("controls", "owner", "save_control.owner_id")}, coalesce(save_control.applicable, true))
43695
+ insert into ${controls} (${k("tenant")}, ${k("framework")}, ${k("code")}, ${k("title")}${insertCol("controls", "description")}${insertCol("controls", "owner")}${insertCol("controls", "source")}${insertCol("controls", "jurisdiction")}, ${k("applicable")})
43696
+ values (v_framework.${f("tenant")}, v_framework.${f("id")}, trim(save_control.code), trim(save_control.title)${insertVal("controls", "description", "nullif(trim(save_control.description), '')")}${insertVal("controls", "owner", "save_control.owner_id")}${insertVal("controls", "source", "nullif(trim(save_control.source), '')")}${insertVal("controls", "jurisdiction", "nullif(trim(save_control.jurisdiction), '')")}, coalesce(save_control.applicable, true))
43661
43697
  on conflict (${k("framework")}, ${k("code")}) do update
43662
- set ${k("title")} = excluded.${k("title")}${has("controls", "description") ? `, ${k("description")} = excluded.${k("description")}` : ""},
43698
+ set ${k("title")} = excluded.${k("title")}${has("controls", "description") ? `, ${k("description")} = excluded.${k("description")}` : ""}${labelSets("excluded")},
43663
43699
  ${owner ? `${k("owner")} = excluded.${k("owner")}, ` : ""}${k("applicable")} = excluded.${k("applicable")}${touch("controls")}
43664
43700
  returning * into v_row;
43665
43701
  else
43666
43702
  update ${controls} x set ${k("code")} = trim(save_control.code), ${k("title")} = trim(save_control.title),
43667
- ${has("controls", "description") ? `${k("description")} = nullif(trim(save_control.description), ''), ` : ""}${owner ? `${k("owner")} = save_control.owner_id,\n ` : ""}${k("applicable")} = coalesce(save_control.applicable, true)${touch("controls")}
43703
+ ${has("controls", "description") ? `${k("description")} = nullif(trim(save_control.description), ''), ` : ""}${labelUpdates}${owner ? `${k("owner")} = save_control.owner_id,\n ` : ""}${k("applicable")} = coalesce(save_control.applicable, true)${touch("controls")}
43668
43704
  where x.${k("id")} = save_control.control_id and x.${k("framework")} = v_framework.${f("id")}
43669
43705
  returning * into v_row;
43670
43706
  if not found then
@@ -43686,7 +43722,7 @@ ${owner ? ` if save_control.owner_id is not null and not ${isMember(`v_framewor
43686
43722
  return ${controlJson("v_row")};
43687
43723
  end;
43688
43724
  $$;
43689
- ${userGrant(`${fn("save_control")}(uuid, text, text, text, uuid, boolean, uuid${extra.type})`)}
43725
+ ${userGrant(`${fn("save_control")}(${PREVIOUS_CONTROL_ARGS}, text, text${extra.type})`)}
43690
43726
 
43691
43727
  -- A control with its evidence (the newest first) and its evidence tasks.
43692
43728
  create or replace function ${fn("get_control")}(control_id uuid)
@@ -43962,7 +43998,7 @@ ${serviceGrant(`${fn("notify_overdue_evidence_tasks")}()`)}
43962
43998
  `;
43963
43999
  }
43964
44000
  // src/sql/modules/compliance-policies.ts
43965
- /** The policy and acknowledgement functions of the `controls` module. */
44001
+ /** The policy and acknowledgement functions of the `compliance` module. */
43966
44002
  function policyFunctions(ctx) {
43967
44003
  const policies = ctx.table("policies");
43968
44004
  const acks = ctx.table("acknowledgements");
@@ -44301,12 +44337,14 @@ const NAMES$89 = {
44301
44337
  tenant: "tenant_id",
44302
44338
  key: "key",
44303
44339
  name: "name",
44340
+ kind: "kind",
44304
44341
  version: "version",
44305
44342
  description: "description",
44306
44343
  createdAt: "created_at",
44307
44344
  updatedAt: "updated_at"
44308
44345
  },
44309
44346
  optional: [
44347
+ "kind",
44310
44348
  "version",
44311
44349
  "description",
44312
44350
  "createdAt",
@@ -44329,12 +44367,16 @@ const NAMES$89 = {
44329
44367
  description: "description",
44330
44368
  owner: "owner_id",
44331
44369
  applicable: "applicable",
44370
+ source: "source",
44371
+ jurisdiction: "jurisdiction",
44332
44372
  createdAt: "created_at",
44333
44373
  updatedAt: "updated_at"
44334
44374
  },
44335
44375
  optional: [
44336
44376
  "description",
44337
44377
  "owner",
44378
+ "source",
44379
+ "jurisdiction",
44338
44380
  "createdAt",
44339
44381
  "updatedAt"
44340
44382
  ]
@@ -44455,6 +44497,9 @@ function tables$28(ctx) {
44455
44497
  const extras = ctx.extraColumns("controls", CONTROL_RESERVED);
44456
44498
  const name = (logical, suffix) => sqlIdent(`${ctx.tableName(logical).name}_${suffix}`);
44457
44499
  const opt = (logical, column, line) => ctx.has(logical, column) ? `\n ${line()},` : "";
44500
+ const added = (logical, column, line) => ctx.has(logical, column) ? `\nalter table ${ctx.table(logical)} add column if not exists ${line()};` : "";
44501
+ const kind = () => `${f("kind")} text not null default 'standard' check (${f("kind")} in (${FRAMEWORK_KINDS.map((item) => `'${item}'`).join(", ")}))`;
44502
+ const label = (column) => () => `${k(column)} text check (${k(column)} is null or length(${k(column)}) between 1 and 200)`;
44458
44503
  const readPolicy = (logical, using) => {
44459
44504
  const policy = ctx.owns(logical) ? name(logical, "read") : sqlIdent(`bsb_${ctx.tableName(logical).name}_read`);
44460
44505
  return renderPolicy(policy$1({
@@ -44475,10 +44520,10 @@ create table if not exists ${frameworks} (
44475
44520
  ${f("id")} uuid primary key default gen_random_uuid(),
44476
44521
  ${f("tenant")} ${ctx.idType} not null,
44477
44522
  ${f("key")} text not null check (${f("key")} ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'),
44478
- ${f("name")} text not null check (length(${f("name")}) between 1 and 200),${opt("frameworks", "version", () => `${f("version")} text check (${f("version")} is null or length(${f("version")}) <= 50)`)}${opt("frameworks", "description", () => `${f("description")} text check (${f("description")} is null or length(${f("description")}) <= 4000)`)}${opt("frameworks", "createdAt", () => `${f("createdAt")} timestamptz not null default now()`)}${opt("frameworks", "updatedAt", () => `${f("updatedAt")} timestamptz not null default now()`)}
44523
+ ${f("name")} text not null check (length(${f("name")}) between 1 and 200),${opt("frameworks", "kind", kind)}${opt("frameworks", "version", () => `${f("version")} text check (${f("version")} is null or length(${f("version")}) <= 50)`)}${opt("frameworks", "description", () => `${f("description")} text check (${f("description")} is null or length(${f("description")}) <= 4000)`)}${opt("frameworks", "createdAt", () => `${f("createdAt")} timestamptz not null default now()`)}${opt("frameworks", "updatedAt", () => `${f("updatedAt")} timestamptz not null default now()`)}
44479
44524
  unique (${f("tenant")}, ${f("key")}),
44480
44525
  unique (${f("tenant")}, ${f("id")})
44481
- );${appKey("frameworks", "tenant_key", `${f("tenant")}, ${f("key")}`)}${appKey("frameworks", "tenant_id", `${f("tenant")}, ${f("id")}`)}
44526
+ );${added("frameworks", "kind", kind)}${appKey("frameworks", "tenant_key", `${f("tenant")}, ${f("key")}`)}${appKey("frameworks", "tenant_id", `${f("tenant")}, ${f("id")}`)}
44482
44527
  ${lockTable(frameworks, { read: true })}
44483
44528
  ${readPolicy("frameworks", ctx.scope.check(f("tenant"), read))}
44484
44529
 
@@ -44489,11 +44534,11 @@ create table if not exists ${controls} (
44489
44534
  ${k("code")} text not null check (length(${k("code")}) between 1 and 50),
44490
44535
  ${k("title")} text not null check (length(${k("title")}) between 1 and 200),${opt("controls", "description", () => `${k("description")} text check (${k("description")} is null or length(${k("description")}) <= 10000)`)}${opt("controls", "owner", () => `${k("owner")} uuid`)}
44491
44536
  -- A control out of scope (excluded in the statement of applicability).
44492
- ${k("applicable")} boolean not null default true,${opt("controls", "createdAt", () => `${k("createdAt")} timestamptz not null default now()`)}${opt("controls", "updatedAt", () => `${k("updatedAt")} timestamptz not null default now()`)}
44537
+ ${k("applicable")} boolean not null default true,${opt("controls", "source", label("source"))}${opt("controls", "jurisdiction", label("jurisdiction"))}${opt("controls", "createdAt", () => `${k("createdAt")} timestamptz not null default now()`)}${opt("controls", "updatedAt", () => `${k("updatedAt")} timestamptz not null default now()`)}
44493
44538
  unique (${k("framework")}, ${k("code")}),
44494
44539
  unique (${k("tenant")}, ${k("id")}),
44495
44540
  foreign key (${k("tenant")}, ${k("framework")}) references ${frameworks} (${f("tenant")}, ${f("id")}) on delete cascade
44496
- );${addExtraColumns(controls, extras)}${appKey("controls", "framework_code", `${k("framework")}, ${k("code")}`)}${appKey("controls", "tenant_id", `${k("tenant")}, ${k("id")}`)}
44541
+ );${added("controls", "source", label("source"))}${added("controls", "jurisdiction", label("jurisdiction"))}${addExtraColumns(controls, extras)}${appKey("controls", "framework_code", `${k("framework")}, ${k("code")}`)}${appKey("controls", "tenant_id", `${k("tenant")}, ${k("id")}`)}
44497
44542
  create index if not exists ${name("controls", "tenant_idx")} on ${controls} (${k("tenant")}, ${k("framework")});${ctx.has("controls", "owner") ? `
44498
44543
  create index if not exists ${name("controls", "owner_idx")} on ${controls} (${k("tenant")}, ${k("owner")}) where ${k("owner")} is not null;` : ""}
44499
44544
  ${lockTable(controls, { read: true })}
@@ -44578,7 +44623,7 @@ function build$89(ctx) {
44578
44623
  return `${schemaPreamble(ctx)}
44579
44624
  -- Compliance controls: frameworks of controls, evidence linked to them,
44580
44625
  -- recurring evidence tasks, and versioned policies members acknowledge.
44581
- ${tables$28(ctx)}${controlsFunctions(ctx)}${policyFunctions(ctx)}`;
44626
+ ${tables$28(ctx)}${complianceFunctions(ctx)}${policyFunctions(ctx)}`;
44582
44627
  }
44583
44628
  function contract$80(ctx) {
44584
44629
  return [
@@ -44589,6 +44634,7 @@ function contract$80(ctx) {
44589
44634
  "text",
44590
44635
  "text",
44591
44636
  "text",
44637
+ "text",
44592
44638
  "text"
44593
44639
  ],
44594
44640
  returns: "jsonb"
@@ -44608,6 +44654,8 @@ function contract$80(ctx) {
44608
44654
  "uuid",
44609
44655
  "boolean",
44610
44656
  "uuid",
44657
+ "text",
44658
+ "text",
44611
44659
  ...extraFieldsArg(ctx.extraColumns("controls", CONTROL_RESERVED)).contract
44612
44660
  ],
44613
44661
  returns: "jsonb"
@@ -44724,7 +44772,7 @@ function contract$80(ctx) {
44724
44772
  }
44725
44773
  ];
44726
44774
  }
44727
- const CONTROLS = {
44775
+ const COMPLIANCE = {
44728
44776
  name: "compliance",
44729
44777
  scopes: ["tenant"],
44730
44778
  title: "Compliance controls",
@@ -46015,6 +46063,117 @@ $$;
46015
46063
  ${userGrant(`${fn("person_for_inbox_contact")}(uuid, boolean)`)}
46016
46064
  `;
46017
46065
  }
46066
+ // src/sql/modules/contacts-representatives.ts
46067
+ /** The relation kind a representative's link has. */
46068
+ const REPRESENTS = "represents";
46069
+ const list$9 = (values) => values.map((value) => sqlString(value)).join(", ");
46070
+ /** Whether `key` of `data` (a jsonb expression) is missing or a date string. */
46071
+ const dateOrMissing = (data, key) => `(${data} -> '${key}' is null or (jsonb_typeof(${data} -> '${key}') = 'string' and pg_input_is_valid(${data} ->> '${key}', 'date')))`;
46072
+ /**
46073
+ * The check `link` runs on a `represents` link's data: a role, an authority,
46074
+ * and `valid_from` and `valid_until` dates in order when set.
46075
+ */
46076
+ function representationData(data) {
46077
+ const from = `${data} ->> 'valid_from'`;
46078
+ const until = `${data} ->> 'valid_until'`;
46079
+ return `(jsonb_typeof(${data}) = 'object'
46080
+ and (${data} ->> 'role') in (${list$9(REPRESENTATIVE_ROLES)})
46081
+ and (${data} ->> 'authority') in (${list$9(REPRESENTATIVE_AUTHORITIES)})
46082
+ and ${dateOrMissing(data, "valid_from")}
46083
+ and ${dateOrMissing(data, "valid_until")}
46084
+ and case when pg_input_is_valid(${from}, 'date') and pg_input_is_valid(${until}, 'date')
46085
+ then (${from})::date <= (${until})::date else true end)`;
46086
+ }
46087
+ /**
46088
+ * Whether a `represents` link with `data` holds today: `valid_from` is past or
46089
+ * unset and `valid_until` is today or later or unset. A date Postgres can't
46090
+ * read ends the link, so an app kind without the check never throws here.
46091
+ */
46092
+ function representationActive(data) {
46093
+ const bound = (key, compare) => `case when ${data} ->> '${key}' is null then true
46094
+ when pg_input_is_valid(${data} ->> '${key}', 'date') then (${data} ->> '${key}')::date ${compare} current_date
46095
+ else false end`;
46096
+ return `(${bound("valid_from", "<=")}) and (${bound("valid_until", ">=")})`;
46097
+ }
46098
+ /**
46099
+ * The `represents` kind contacts adds to relations: a person represents a
46100
+ * record.
46101
+ */
46102
+ function representsKind(own) {
46103
+ return {
46104
+ kind: REPRESENTS,
46105
+ inverse: "represented_by",
46106
+ types: { source: [own.naming.rename("person")] },
46107
+ data: representationData
46108
+ };
46109
+ }
46110
+ /**
46111
+ * `list_representatives` and `represented_by_me` over the relations block's
46112
+ * links, with a leading newline. Empty without relations.
46113
+ */
46114
+ function representativeFunctions(ctx, names) {
46115
+ if (!ctx.installed("relations")) return "";
46116
+ const relations = ctx.of("relations");
46117
+ const links = relations.table("relations");
46118
+ const r = (column) => `r.${relations.col("relations", column)}`;
46119
+ const p = (column) => `p.${names.c("people", column)}`;
46120
+ const person = sqlString(ctx.naming.rename("person"));
46121
+ const active = representationActive(r("data"));
46122
+ const kind = sqlString(REPRESENTS);
46123
+ const terms = `'role', ${r("data")} ->> 'role', 'authority', ${r("data")} ->> 'authority',
46124
+ 'validFrom', ${r("data")} ->> 'valid_from', 'validUntil', ${r("data")} ->> 'valid_until'`;
46125
+ return `
46126
+ -- The people who represent a record (a client's guardian, a legal
46127
+ -- representative), with their role and authority. Runs as the caller, so the
46128
+ -- relations and people policies decide what they see. Ended links come last.
46129
+ create or replace function ${names.fn("list_representatives")}(subject_type text, subject_id text)
46130
+ returns jsonb
46131
+ language sql
46132
+ stable
46133
+ security invoker
46134
+ set search_path = ''
46135
+ as $$
46136
+ select coalesce(jsonb_agg(jsonb_build_object(
46137
+ 'id', ${r("id")}, 'organizationId', ${r("tenant")}::text,
46138
+ 'personId', ${p("id")}, 'name', ${p("name")}, 'email', ${p("email")}, 'phone', ${p("phone")},
46139
+ ${terms},
46140
+ 'active', ${active}, 'createdAt', ${r("createdAt")}
46141
+ ) order by ${active} desc, ${p("name")}, ${r("id")}), '[]'::jsonb)
46142
+ from ${links} r
46143
+ join ${names.t("people")} p on ${p("id")}::text = ${r("sourceId")} and ${p("tenant")} = ${r("tenant")}
46144
+ where ${r("kind")} = ${kind} and ${r("sourceType")} = ${person}
46145
+ and ${r("targetType")} = list_representatives.subject_type
46146
+ and ${r("targetId")} = list_representatives.subject_id
46147
+ $$;
46148
+ ${userGrant(`${names.fn("list_representatives")}(text, text)`)}
46149
+
46150
+ -- The records the caller represents in tenant, as a guest whose party is the
46151
+ -- representative, while the link holds.
46152
+ create or replace function ${names.fn("represented_by_me")}(tenant ${ctx.idType})
46153
+ returns jsonb
46154
+ language plpgsql
46155
+ stable
46156
+ security definer
46157
+ set search_path = ''
46158
+ as $$
46159
+ begin
46160
+ return (
46161
+ select coalesce(jsonb_agg(jsonb_build_object(
46162
+ 'id', ${r("id")}, 'organizationId', ${r("tenant")}::text, 'personId', ${r("sourceId")},
46163
+ 'subjectType', ${r("targetType")}, 'subjectId', ${r("targetId")},
46164
+ ${terms}
46165
+ ) order by ${r("createdAt")}, ${r("id")}), '[]'::jsonb)
46166
+ from ${links} r
46167
+ where ${r("tenant")} = represented_by_me.tenant
46168
+ and ${r("kind")} = ${kind} and ${r("sourceType")} = ${person}
46169
+ and ${active}
46170
+ and ${names.scope.guestParty("represented_by_me.tenant", person, r("sourceId"))}
46171
+ );
46172
+ end;
46173
+ $$;
46174
+ ${userGrant(`${names.fn("represented_by_me")}(${ctx.idType})`)}
46175
+ `;
46176
+ }
46018
46177
  // src/sql/modules/contacts.ts
46019
46178
  /** The lifecycle stages `options.companyLifecycles` falls back to. */
46020
46179
  const COMPANY_LIFECYCLES = [
@@ -46326,8 +46485,9 @@ function build$87(ctx) {
46326
46485
  };
46327
46486
  return `${schemaPreamble(ctx)}
46328
46487
  -- Companies and people an organization works with, and who works where.
46329
- ${tables$27(ctx, names)}${partyFunctions(ctx, names)}${partiesInboxSql(ctx, names)}`;
46488
+ ${tables$27(ctx, names)}${partyFunctions(ctx, names)}${partiesInboxSql(ctx, names)}${representativeFunctions(ctx, names)}`;
46330
46489
  }
46490
+ const CONTRIBUTES$12 = { relations: (own) => [representsKind(own)] };
46331
46491
  function contract$79(ctx) {
46332
46492
  return [
46333
46493
  {
@@ -46430,10 +46590,20 @@ function contract$79(ctx) {
46430
46590
  args: ["uuid", "boolean"],
46431
46591
  returns: "jsonb"
46432
46592
  }
46433
- ] : []
46593
+ ] : [],
46594
+ ...ctx.installed("relations") ? [{
46595
+ name: "list_representatives",
46596
+ args: ["text", "text"],
46597
+ returns: "jsonb"
46598
+ }, {
46599
+ name: "represented_by_me",
46600
+ args: ["{id}"],
46601
+ returns: "jsonb"
46602
+ }] : []
46434
46603
  ];
46435
46604
  }
46436
46605
  const PARTIES = {
46606
+ contributes: CONTRIBUTES$12,
46437
46607
  name: "contacts",
46438
46608
  scopes: ["tenant"],
46439
46609
  title: "Parties",
@@ -46443,7 +46613,8 @@ const PARTIES = {
46443
46613
  "outbox",
46444
46614
  "audit",
46445
46615
  "notifications",
46446
- "inbox"
46616
+ "inbox",
46617
+ "relations"
46447
46618
  ],
46448
46619
  target: "schema",
46449
46620
  modes: ["managed", "custom"],
@@ -48478,6 +48649,7 @@ const COURSE_KEYS = [
48478
48649
  "summary",
48479
48650
  "status",
48480
48651
  "certificate",
48652
+ "validForMonths",
48481
48653
  "createdBy",
48482
48654
  "createdAt",
48483
48655
  "updatedAt",
@@ -48523,7 +48695,7 @@ function courseSql(ctx) {
48523
48695
  forbidden: (message) => fail$1("COURSE_FORBIDDEN", message),
48524
48696
  courseMissing: fail$1("COURSE_NOT_FOUND", "course not found", "P0002"),
48525
48697
  lessonMissing: fail$1("COURSE_LESSON_NOT_FOUND", "course lesson not found", "P0002"),
48526
- courseJson: (row) => withExtraFields(`jsonb_build_object('id', ${row}.${c("id")}, 'organizationId', ${row}.${c("tenant")}, 'key', ${row}.${c("key")}, 'title', ${row}.${c("title")}, 'summary', ${field("courses", row, "summary")}, 'status', ${row}.${c("status")}, 'certificate', ${field("courses", row, "certificate", "true")}, 'createdBy', ${field("courses", row, "createdBy")}, 'createdAt', ${field("courses", row, "createdAt")}, 'updatedAt', ${field("courses", row, "updatedAt")})`, row, extras),
48698
+ courseJson: (row) => withExtraFields(`jsonb_build_object('id', ${row}.${c("id")}, 'organizationId', ${row}.${c("tenant")}, 'key', ${row}.${c("key")}, 'title', ${row}.${c("title")}, 'summary', ${field("courses", row, "summary")}, 'status', ${row}.${c("status")}, 'certificate', ${field("courses", row, "certificate", "true")}, 'validForMonths', ${field("courses", row, "validForMonths")}, 'createdBy', ${field("courses", row, "createdBy")}, 'createdAt', ${field("courses", row, "createdAt")}, 'updatedAt', ${field("courses", row, "updatedAt")})`, row, extras),
48527
48699
  program: (course) => `('course:' || ${course}::text)`,
48528
48700
  learnerRecord: (type, summary) => ctx.record({
48529
48701
  type,
@@ -48568,9 +48740,9 @@ function courseAuthoringFunctions(ctx) {
48568
48740
  summary: `'${summary}'`
48569
48741
  }
48570
48742
  });
48571
- const certificateRecord = (type, row, summary) => ctx.record({
48743
+ const certificateRecord = (type, row, summary, extra = "") => ctx.record({
48572
48744
  type,
48573
- payload: `jsonb_build_object('organizationId', ${row}.${q.k("tenant")}, 'id', ${row}.${q.k("id")}, 'courseId', ${row}.${q.k("course")}, 'userId', ${row}.${q.k("user")}, 'enrollmentId', ${row}.${q.k("enrollment")})`,
48745
+ payload: `jsonb_build_object('organizationId', ${row}.${q.k("tenant")}, 'id', ${row}.${q.k("id")}, 'courseId', ${row}.${q.k("course")}, 'userId', ${row}.${q.k("user")}, 'enrollmentId', ${row}.${q.k("enrollment")}${extra})`,
48574
48746
  subject: `'course-certificates/' || ${row}.${q.k("id")}::text`,
48575
48747
  tenant: `${row}.${q.k("tenant")}`,
48576
48748
  audit: {
@@ -48585,6 +48757,7 @@ function courseAuthoringFunctions(ctx) {
48585
48757
  const lessonJson = (row) => `jsonb_build_object('id', ${row}.${l("id")}, 'courseId', ${row}.${l("course")}, 'moduleId', ${row}.${l("module")}, 'title', ${row}.${l("title")}, 'kind', ${row}.${l("kind")}, 'body', ${field("lessons", row, "body")}, 'mediaUrl', ${field("lessons", row, "mediaUrl")}, 'formId', ${row}.${l("form")}, 'required', ${row}.${l("required")}, 'minutes', ${field("lessons", row, "minutes")}, 'rank', ${row}.${l("rank")}, 'createdAt', ${field("lessons", row, "createdAt")}, 'updatedAt', ${field("lessons", row, "updatedAt")})`;
48586
48758
  /** `, <column> = now()` when `table` has its updatedAt column. */
48587
48759
  const touched = (table) => ctx.has(table, "updatedAt") ? `, ${ctx.col(table, "updatedAt")} = now()` : "";
48760
+ const expires = ctx.has("certificates", "expiresAt");
48588
48761
  const touchCourse = ctx.has("courses", "updatedAt") ? `\n update ${q.courses} x set ${c("updatedAt")} = now() where x.${c("id")} = v_course.${c("id")};` : "";
48589
48762
  const courseInsert = [
48590
48763
  ["tenant", "save_course.tenant"],
@@ -48593,6 +48766,7 @@ function courseAuthoringFunctions(ctx) {
48593
48766
  ["summary", "v_summary"],
48594
48767
  ["status", ctx.cast("courses", "status", "v_status")],
48595
48768
  ["certificate", "v_certificate"],
48769
+ ["validForMonths", "v_valid_for"],
48596
48770
  ["createdBy", "auth.uid()"]
48597
48771
  ].filter(([column]) => ctx.has("courses", column));
48598
48772
  const lessonWrite = [
@@ -48652,7 +48826,7 @@ declare
48652
48826
  v_enrollment record;
48653
48827
  v_certificate ${q.certificates};
48654
48828
  begin
48655
- select x.${e("id")} as id, x.${e("tenant")} as tenant, x.${e("status")} as status, x.${e("user")} as learner, y.${c("id")} as course, ${field("courses", "y", "certificate", "true")} as certifies
48829
+ select x.${e("id")} as id, x.${e("tenant")} as tenant, x.${e("status")} as status, x.${e("user")} as learner, y.${c("id")} as course, ${field("courses", "y", "certificate", "true")} as certifies, ${field("courses", "y", "validForMonths")}::integer as valid_for
48656
48830
  into v_enrollment
48657
48831
  from ${q.enrollments} x join ${q.courses} y on ${q.program(`y.${c("id")}`)} = x.${e("program")}
48658
48832
  where x.${e("id")} = course_finish.enrollment_id;
@@ -48663,12 +48837,12 @@ begin
48663
48837
  ${q.learnerRecord("course.completed", "completed a course")}
48664
48838
  end if;
48665
48839
  if v_enrollment.certifies then
48666
- insert into ${q.certificates} (${q.k("tenant")}, ${q.k("course")}, ${q.k("enrollment")}, ${q.k("user")}, ${q.k("code")})
48667
- values (v_enrollment.tenant, v_enrollment.course, v_enrollment.id, v_enrollment.learner, encode(extensions.gen_random_bytes(16), 'hex'))
48840
+ insert into ${q.certificates} (${q.k("tenant")}, ${q.k("course")}, ${q.k("enrollment")}, ${q.k("user")}, ${q.k("code")}${expires ? `, ${q.k("expiresAt")}` : ""})
48841
+ values (v_enrollment.tenant, v_enrollment.course, v_enrollment.id, v_enrollment.learner, encode(extensions.gen_random_bytes(16), 'hex')${expires ? ", now() + make_interval(months => v_enrollment.valid_for)" : ""})
48668
48842
  on conflict ${q.certificateTarget} do nothing
48669
48843
  returning * into v_certificate;
48670
48844
  if v_certificate.${q.k("id")} is not null then
48671
- ${certificateRecord("course_certificate.issued", "v_certificate", "issued a course certificate")}
48845
+ ${certificateRecord("course_certificate.issued", "v_certificate", "issued a course certificate", `, 'expiresAt', ${field("certificates", "v_certificate", "expiresAt")}`)}
48672
48846
  end if;
48673
48847
  end if;
48674
48848
  end;
@@ -48707,7 +48881,8 @@ $$;
48707
48881
  revoke execute on function ${fn("course_sync")}(uuid) from public, anon, authenticated;
48708
48882
 
48709
48883
  -- Creates or changes a course. course is { id?, key, title, summary, status,
48710
- -- certificate, fields }; keys left out keep their value.
48884
+ -- certificate, validForMonths, fields }; keys left out keep their value.
48885
+ -- validForMonths is how long a certificate stays valid; null never expires.
48711
48886
  create or replace function ${fn("save_course")}(tenant ${idType}, course jsonb)
48712
48887
  returns jsonb
48713
48888
  language plpgsql
@@ -48724,6 +48899,7 @@ declare
48724
48899
  v_summary text;
48725
48900
  v_status text;
48726
48901
  v_certificate boolean;
48902
+ v_valid_for integer;
48727
48903
  begin
48728
48904
  if not ${q.allowed("save_course.tenant", q.manage)} then
48729
48905
  ${q.forbidden("not allowed to manage courses")}
@@ -48743,6 +48919,18 @@ begin
48743
48919
  v_summary := case when save_course.course ? 'summary' then nullif(trim(save_course.course ->> 'summary'), '') else ${field("courses", "v_old", "summary")} end;
48744
48920
  v_status := coalesce(save_course.course ->> 'status', v_old.${c("status")}, 'draft');
48745
48921
  v_certificate := case when save_course.course ? 'certificate' then (save_course.course ->> 'certificate')::boolean else coalesce(${field("courses", "v_old", "certificate")}, true) end;
48922
+ v_valid_for := ${field("courses", "v_old", "validForMonths")};
48923
+ if save_course.course ? 'validForMonths' then
48924
+ if jsonb_typeof(save_course.course -> 'validForMonths') = 'null' then
48925
+ v_valid_for := null;
48926
+ elsif jsonb_typeof(save_course.course -> 'validForMonths') <> 'number'
48927
+ or (save_course.course ->> 'validForMonths')::numeric % 1 <> 0
48928
+ or (save_course.course ->> 'validForMonths')::numeric not between 1 and 240 then
48929
+ ${q.invalid("validForMonths must be a whole number of months from 1 to 240, or null")}
48930
+ else
48931
+ v_valid_for := (save_course.course ->> 'validForMonths')::integer;
48932
+ end if;
48933
+ end if;
48746
48934
  if v_key is null or v_key !~ '^[a-z][a-z0-9-]{0,62}$' then
48747
48935
  ${q.invalid("key: use lowercase letters, digits or \"-\", starting with a letter")}
48748
48936
  end if;
@@ -48766,7 +48954,7 @@ begin
48766
48954
  else
48767
48955
  begin
48768
48956
  update ${q.courses} x
48769
- set ${c("key")} = v_key, ${c("title")} = v_title,${ctx.has("courses", "summary") ? ` ${c("summary")} = v_summary,` : ""} ${c("status")} = ${ctx.cast("courses", "status", "v_status")}${ctx.has("courses", "certificate") ? `,\n ${c("certificate")} = v_certificate` : ""}${touched("courses")}
48957
+ set ${c("key")} = v_key, ${c("title")} = v_title,${ctx.has("courses", "summary") ? ` ${c("summary")} = v_summary,` : ""} ${c("status")} = ${ctx.cast("courses", "status", "v_status")}${ctx.has("courses", "certificate") ? `,\n ${c("certificate")} = v_certificate` : ""}${ctx.has("courses", "validForMonths") ? `,\n ${c("validForMonths")} = v_valid_for` : ""}${touched("courses")}
48770
48958
  where x.${c("id")} = v_old.${c("id")}
48771
48959
  returning * into v_row;
48772
48960
  exception when unique_violation then
@@ -49156,7 +49344,9 @@ function courseLearningFunctions(ctx) {
49156
49344
  or exists (select 1 from ${q.enrollments} y where y.${e("tenant")} = ${course}.${c("tenant")} and y.${e("program")} = ${q.program(`${course}.${c("id")}`)}
49157
49345
  and y.${e("subjectType")} = 'user' and y.${e("subjectId")} = auth.uid()::text and y.${e("status")} <> 'cancelled'))`;
49158
49346
  const entryJson = (row) => `jsonb_build_object('lessonId', ${row}.${p("lesson")}, 'startedAt', ${field("progress", row, "startedAt")}, 'completedAt', ${row}.${p("completedAt")}, 'attempts', ${row}.${p("attempts")}, 'submissionId', ${field("progress", row, "submission")}, 'score', ${field("progress", row, "score")}, 'maxScore', ${field("progress", row, "maxScore")}, 'passed', ${field("progress", row, "passed")})`;
49159
- const certificateJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'courseId', ${row}.${k("course")}, 'userId', ${row}.${k("user")}, 'code', ${row}.${k("code")}, 'issuedAt', ${field("certificates", row, "issuedAt")}, 'revokedAt', ${row}.${k("revokedAt")})`;
49347
+ const certificateJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'courseId', ${row}.${k("course")}, 'userId', ${row}.${k("user")}, 'code', ${row}.${k("code")}, 'issuedAt', ${field("certificates", row, "issuedAt")}, 'expiresAt', ${field("certificates", row, "expiresAt")}, 'revokedAt', ${row}.${k("revokedAt")})`;
49348
+ const expiresAt = field("certificates", "z", "expiresAt");
49349
+ const expired = ctx.has("certificates", "expiresAt") ? `coalesce(${expiresAt} <= now(), false)` : "false";
49160
49350
  const enrollmentOf = (course, user) => `select * into v_row from ${q.enrollments} x
49161
49351
  where x.${e("tenant")} = ${course}.${c("tenant")} and x.${e("program")} = ${q.program(`${course}.${c("id")}`)}
49162
49352
  and x.${e("subjectType")} = 'user' and x.${e("subjectId")} = ${user}::text`;
@@ -49537,8 +49727,8 @@ $$;
49537
49727
  ${userGrant(`${fn("list_course_learners")}(uuid, text, integer, timestamptz)`)}
49538
49728
 
49539
49729
  -- Checks a certificate by the code its link carries. Anyone with the code
49540
- -- learns the course, when it was issued and whether it was revoked; null for
49541
- -- an unknown code.
49730
+ -- learns the course, when it was issued, when it expires and whether it was
49731
+ -- revoked; null for an unknown code. An expired certificate is not valid.
49542
49732
  create or replace function ${fn("verify_course_certificate")}(code text)
49543
49733
  returns jsonb
49544
49734
  language sql
@@ -49547,7 +49737,8 @@ security definer
49547
49737
  set search_path = ''
49548
49738
  as $$
49549
49739
  select jsonb_build_object('id', z.${k("id")}, 'courseId', z.${k("course")}, 'courseTitle', y.${c("title")}, 'organizationId', z.${k("tenant")},
49550
- 'issuedAt', ${field("certificates", "z", "issuedAt")}, 'revokedAt', z.${k("revokedAt")}, 'valid', z.${k("revokedAt")} is null)
49740
+ 'issuedAt', ${field("certificates", "z", "issuedAt")}, 'expiresAt', ${expiresAt}, 'revokedAt', z.${k("revokedAt")},
49741
+ 'expired', ${expired}, 'valid', z.${k("revokedAt")} is null and not ${expired})
49551
49742
  from ${q.certificates} z join ${q.courses} y on y.${c("id")} = z.${k("course")}
49552
49743
  where z.${k("code")} = lower(verify_course_certificate.code)
49553
49744
  $$;
@@ -49633,7 +49824,7 @@ const NAMES$84 = {
49633
49824
  },
49634
49825
  "course_certificate.issued": {
49635
49826
  subject: "course-certificates",
49636
- payload: COURSE_ITEM_PAYLOAD
49827
+ payload: [...COURSE_ITEM_PAYLOAD, "expiresAt"]
49637
49828
  },
49638
49829
  "course_certificate.revoked": {
49639
49830
  subject: "course-certificates",
@@ -49653,6 +49844,7 @@ const NAMES$84 = {
49653
49844
  optional: [
49654
49845
  "summary",
49655
49846
  "certificate",
49847
+ "validForMonths",
49656
49848
  "createdBy",
49657
49849
  "createdAt",
49658
49850
  "updatedAt"
@@ -49666,6 +49858,7 @@ const NAMES$84 = {
49666
49858
  summary: "summary",
49667
49859
  status: "status",
49668
49860
  certificate: "issues_certificate",
49861
+ validForMonths: "valid_for_months",
49669
49862
  createdBy: "created_by",
49670
49863
  createdAt: "created_at",
49671
49864
  updatedAt: "updated_at"
@@ -49761,7 +49954,7 @@ const NAMES$84 = {
49761
49954
  user: "user",
49762
49955
  export: true
49763
49956
  },
49764
- optional: ["issuedAt"],
49957
+ optional: ["issuedAt", "expiresAt"],
49765
49958
  columns: {
49766
49959
  id: "id",
49767
49960
  tenant: "tenant_id",
@@ -49770,6 +49963,7 @@ const NAMES$84 = {
49770
49963
  user: "user_id",
49771
49964
  code: "code",
49772
49965
  issuedAt: "issued_at",
49966
+ expiresAt: "expires_at",
49773
49967
  revokedAt: "revoked_at"
49774
49968
  }
49775
49969
  }
@@ -49796,6 +49990,9 @@ function courseTables(ctx) {
49796
49990
  const extras = ctx.extraColumns("courses", COURSE_KEYS);
49797
49991
  const name = (logical, suffix) => sqlIdent(`${ctx.tableName(logical).name}_${suffix}`);
49798
49992
  const optional = (table, column, definition) => ctx.has(table, column) ? `\n ${definition(ctx.col(table, column))},` : "";
49993
+ const added = (table, column, definition) => ctx.has(table, column) ? `\nalter table ${ctx.table(table)} add column if not exists ${definition(ctx.col(table, column))};` : "";
49994
+ const validFor = (x) => `${x} integer check (${x} is null or ${x} between 1 and 240)`;
49995
+ const expires = (x) => `${x} timestamptz`;
49799
49996
  const stamps = (table) => ["createdAt", "updatedAt"].filter((column) => ctx.has(table, column)).map((column) => `,\n ${ctx.col(table, column)} timestamptz not null default now()`).join("");
49800
49997
  const key = (logical, suffix, columns) => ctx.owns(logical) ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${ctx.tableName(logical).name}_${suffix}`)} on ${ctx.table(logical)} (${columns});`;
49801
49998
  return `create table if not exists ${courses} (
@@ -49803,9 +50000,9 @@ function courseTables(ctx) {
49803
50000
  ${c("tenant")} ${ctx.idType} not null,
49804
50001
  ${c("key")} text not null check (${c("key")} ~ '^[a-z][a-z0-9-]{0,62}$'),
49805
50002
  ${c("title")} text not null check (length(${c("title")}) between 1 and 200),${optional("courses", "summary", (x) => `${x} text check (${x} is null or length(${x}) <= 2000)`)}
49806
- ${c("status")} text not null default 'draft' check (${c("status")} in ('draft', 'published', 'archived')),${optional("courses", "certificate", (x) => `${x} boolean not null default true`)}${optional("courses", "createdBy", (x) => `${x} uuid`)}${optional("courses", "createdAt", (x) => `${x} timestamptz not null default now()`)}${optional("courses", "updatedAt", (x) => `${x} timestamptz not null default now()`)}
50003
+ ${c("status")} text not null default 'draft' check (${c("status")} in ('draft', 'published', 'archived')),${optional("courses", "certificate", (x) => `${x} boolean not null default true`)}${optional("courses", "validForMonths", validFor)}${optional("courses", "createdBy", (x) => `${x} uuid`)}${optional("courses", "createdAt", (x) => `${x} timestamptz not null default now()`)}${optional("courses", "updatedAt", (x) => `${x} timestamptz not null default now()`)}
49807
50004
  unique (${c("tenant")}, ${c("key")})
49808
- );${key("courses", "key_key", `${c("tenant")}, ${c("key")}`)}${addExtraColumns(courses, extras)}
50005
+ );${key("courses", "key_key", `${c("tenant")}, ${c("key")}`)}${added("courses", "validForMonths", validFor)}${addExtraColumns(courses, extras)}
49809
50006
 
49810
50007
  create table if not exists ${modules} (
49811
50008
  ${m("id")} uuid primary key default gen_random_uuid(),
@@ -49863,10 +50060,10 @@ create table if not exists ${certificates} (
49863
50060
  ${k("course")} uuid not null references ${courses} (${c("id")}) on delete cascade,
49864
50061
  ${k("enrollment")} uuid not null references ${enrollments} (${enrollmentId}) on delete cascade,
49865
50062
  ${k("user")} uuid not null references auth.users (id) on delete cascade,
49866
- ${k("code")} text not null unique check (${k("code")} ~ '^[0-9a-f]{32}$'),${optional("certificates", "issuedAt", (x) => `${x} timestamptz not null default now()`)}
50063
+ ${k("code")} text not null unique check (${k("code")} ~ '^[0-9a-f]{32}$'),${optional("certificates", "issuedAt", (x) => `${x} timestamptz not null default now()`)}${optional("certificates", "expiresAt", expires)}
49867
50064
  ${k("revokedAt")} timestamptz,
49868
50065
  constraint ${name("certificates", "enrollment_key")} unique (${k("enrollment")})
49869
- );${key("certificates", "enrollment_key", k("enrollment"))}
50066
+ );${key("certificates", "enrollment_key", k("enrollment"))}${added("certificates", "expiresAt", expires)}
49870
50067
  create index if not exists ${name("certificates", "parent_idx")} on ${certificates} (${k("course")});
49871
50068
  create index if not exists ${name("certificates", "user_idx")} on ${certificates} (${k("user")});
49872
50069
 
@@ -50114,6 +50311,79 @@ $$;
50114
50311
  revoke execute on function better_supabase.token_scope_allows(text) from public;
50115
50312
  grant execute on function better_supabase.token_scope_allows(text) to anon, authenticated, service_role;`
50116
50313
  };
50314
+ // src/sql/format-checks.ts
50315
+ /** `<schema>.bsb_valid_<name>`, quoted. */
50316
+ function validatorFunction(schema, validator) {
50317
+ return `${sqlIdent(schema)}.${sqlIdent(`bsb_valid_${validator}`)}`;
50318
+ }
50319
+ /** The validators the formats in `formats` need, in a fixed order. */
50320
+ function validatorsOf(formats) {
50321
+ const used = /* @__PURE__ */ new Set();
50322
+ for (const format of formats) {
50323
+ const validator = format === void 0 ? void 0 : FIELD_FORMATS[format].validator;
50324
+ if (validator !== void 0) used.add(validator);
50325
+ }
50326
+ return FIELD_FORMAT_VALIDATORS.filter((validator) => used.has(validator));
50327
+ }
50328
+ /**
50329
+ * The SQL conditions a `format` puts on the text expression `ident`: its
50330
+ * pattern and its validator in `schema`. Bounds are the caller's.
50331
+ */
50332
+ function formatConditions(format, ident, schema) {
50333
+ const spec = FIELD_FORMATS[format];
50334
+ return [...spec.pattern === void 0 ? [] : [`${ident} ~* ${sqlString(spec.pattern)}`], ...spec.validator === void 0 ? [] : [`${validatorFunction(schema, spec.validator)}(${ident})`]];
50335
+ }
50336
+ /**
50337
+ * Whether the text `value` passes the format the custom field type `type`
50338
+ * checks (`CUSTOM_FIELD_CHECKED_FORMATS`); `true` for the other types, and not
50339
+ * false for a `null` value.
50340
+ */
50341
+ function customFieldValueCheck(type, value, schema) {
50342
+ return `case ${type} ${Object.entries(CUSTOM_FIELD_CHECKED_FORMATS).map(([field, format]) => `when ${sqlString(field)} then ${formatConditions(format, value, schema).join(" and ")}`).join(" ")} else true end`;
50343
+ }
50344
+ /** The validators the checked custom field types call. */
50345
+ const CUSTOM_FIELD_VALIDATORS = validatorsOf(Object.values(CUSTOM_FIELD_CHECKED_FORMATS));
50346
+ function bodyOf(validator) {
50347
+ switch (validator) {
50348
+ case "bsn": return ` select case
50349
+ when value !~ '^[0-9]{9}$' or value = '000000000' then false
50350
+ else (
50351
+ select sum(substr(value, i, 1)::integer * case when i = 9 then -1 else 10 - i end)
50352
+ from generate_series(1, 9) as i
50353
+ ) % 11 = 0
50354
+ end`;
50355
+ case "iban": return ` select case
50356
+ when value !~ '^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$' then false
50357
+ else (
50358
+ select string_agg(case when ascii(c.ch) between 65 and 90 then (ascii(c.ch) - 55)::text else c.ch end, '' order by c.n)
50359
+ from regexp_split_to_table(substr(value, 5) || substr(value, 1, 4), '') with ordinality as c(ch, n)
50360
+ )::numeric % 97 = 1
50361
+ end`;
50362
+ default: throw new TypeError(`Unknown format validator "${String(validator)}"`);
50363
+ }
50364
+ }
50365
+ /**
50366
+ * The `bsb_valid_<name>(value text)` functions of `validators` in `schema`:
50367
+ * immutable, `null` for `null`, callable by signed-in users and the service
50368
+ * role so a check constraint that calls one runs for them.
50369
+ */
50370
+ function formatValidatorSql(schema, validators) {
50371
+ return validators.map((validator) => {
50372
+ const fn = validatorFunction(schema, validator);
50373
+ return `create or replace function ${fn}(value text)
50374
+ returns boolean
50375
+ language sql
50376
+ immutable
50377
+ strict
50378
+ parallel safe
50379
+ set search_path = ''
50380
+ as $$
50381
+ ${bodyOf(validator)}
50382
+ $$;
50383
+ revoke execute on function ${fn}(text) from public, anon;
50384
+ grant execute on function ${fn}(text) to authenticated, service_role;`;
50385
+ }).join("\n");
50386
+ }
50117
50387
  // src/sql/modules/custom-fields-keyed.ts
50118
50388
  /** The value column each field type is stored in, when the table maps it. */
50119
50389
  const VALUE_COLUMNS = {
@@ -50328,6 +50598,9 @@ begin
50328
50598
  if coalesce(trim(${s("key")}), '') = '' or coalesce(trim(${s("label")}), '') = '' or v_type is null or v_type not in (${CUSTOM_FIELD_TYPES.map((type) => sqlString(type)).join(", ")}) then
50329
50599
  ${fail$1("FIELD_INVALID", "a field needs a key, a label and a known type", "22023")}
50330
50600
  end if;
50601
+ if not (${customFieldValueCheck("v_type", `${s("value")} #>> '{}'`, ctx.schemaName)}) then
50602
+ ${fail$1("FIELD_VALUE_INVALID", "the value doesn't match the field's format", "22023")}
50603
+ end if;
50331
50604
  if not (${check(s("subject_type"), s("subject_id"), s("tenant"))}) then
50332
50605
  ${fail$1("FIELD_SUBJECT_FORBIDDEN", "not allowed to set fields on this record")}
50333
50606
  end if;
@@ -50459,6 +50732,8 @@ const NAMES$83 = {
50459
50732
  const FIELD_CIPHER_PREFIX = "bsf1:";
50460
50733
  /** The Vault secret name prefix of a data key; the owner follows it. */
50461
50734
  const FIELD_KEY_PREFIX = "bs:field-key:";
50735
+ /** The Vault secret name prefix of a lookup key; the owner follows it. */
50736
+ const FIELD_LOOKUP_KEY_PREFIX = "bs:field-lookup-key:";
50462
50737
  /** The pgcrypto options: AES-256, and one S2K pass since the key is random. */
50463
50738
  const CIPHER_OPTIONS = "cipher-algo=aes256, s2k-mode=1";
50464
50739
  /** SQL that revokes a function from every API role, the service role too. */
@@ -50474,15 +50749,10 @@ function fieldKeyOwner(kind, column) {
50474
50749
  }
50475
50750
  function build$83(ctx) {
50476
50751
  const fn = (name) => ctx.fn(name);
50477
- const secret = (owner) => `'${FIELD_KEY_PREFIX}' || ${owner}`;
50478
- return `${schemaPreamble(ctx)}
50479
- create extension if not exists pgcrypto with schema extensions;
50480
-
50481
- -- Field data keys live only in Vault, one per owner (tenant:<id>, user:<id>
50482
- -- or app), as bs:field-key:<owner>. No API role calls field_key, field_seal
50483
- -- or field_open; security definer functions of app tables and custom fields
50484
- -- do, after they check the caller's scope.
50485
- create or replace function ${fn("field_key")}(owner text, make boolean default true)
50752
+ const secret = (owner, prefix = FIELD_KEY_PREFIX) => `'${prefix}' || ${owner}`;
50753
+ const keyFunction = (name, prefix, label) => {
50754
+ const owner = `${name}.owner`;
50755
+ return `create or replace function ${fn(name)}(owner text, make boolean default true)
50486
50756
  returns text
50487
50757
  language plpgsql
50488
50758
  security definer
@@ -50491,25 +50761,37 @@ as $$
50491
50761
  declare
50492
50762
  v_key text;
50493
50763
  begin
50494
- if field_key.owner is null or length(field_key.owner) = 0 then
50764
+ if ${owner} is null or length(${owner}) = 0 then
50495
50765
  ${fail$1("FIELD_KEY_OWNER", "a field key needs an owner", "22023")}
50496
50766
  end if;
50497
50767
  select ds.decrypted_secret into v_key from vault.decrypted_secrets ds
50498
- where ds.name = ${secret("field_key.owner")};
50499
- if v_key is not null or not field_key.make then
50768
+ where ds.name = ${secret(owner, prefix)};
50769
+ if v_key is not null or not ${name}.make then
50500
50770
  return v_key;
50501
50771
  end if;
50502
- perform pg_advisory_xact_lock(hashtextextended(${secret("field_key.owner")}, 0));
50772
+ perform pg_advisory_xact_lock(hashtextextended(${secret(owner, prefix)}, 0));
50503
50773
  select ds.decrypted_secret into v_key from vault.decrypted_secrets ds
50504
- where ds.name = ${secret("field_key.owner")};
50774
+ where ds.name = ${secret(owner, prefix)};
50505
50775
  if v_key is null then
50506
50776
  v_key := encode(extensions.gen_random_bytes(32), 'base64');
50507
- perform vault.create_secret(v_key, ${secret("field_key.owner")}, 'better-supabase field encryption key');
50777
+ perform vault.create_secret(v_key, ${secret(owner, prefix)}, '${label}');
50508
50778
  end if;
50509
50779
  return v_key;
50510
50780
  end;
50511
50781
  $$;
50512
- ${privateGrant(`${fn("field_key")}(text, boolean)`)}
50782
+ ${privateGrant(`${fn(name)}(text, boolean)`)}`;
50783
+ };
50784
+ return `${schemaPreamble(ctx)}
50785
+ create extension if not exists pgcrypto with schema extensions;
50786
+
50787
+ -- Field data keys live only in Vault, one per owner (tenant:<id>, user:<id>
50788
+ -- or app), as bs:field-key:<owner>, and the lookup keys next to them as
50789
+ -- bs:field-lookup-key:<owner>. No API role calls field_key, field_lookup_key,
50790
+ -- field_seal, field_open or field_hash; security definer functions of app
50791
+ -- tables and custom fields do, after they check the caller's scope.
50792
+ ${keyFunction("field_key", FIELD_KEY_PREFIX, "better-supabase field encryption key")}
50793
+
50794
+ ${keyFunction("field_lookup_key", FIELD_LOOKUP_KEY_PREFIX, "better-supabase field lookup key")}
50513
50795
 
50514
50796
  -- Encrypts a value with a data key: ${FIELD_CIPHER_PREFIX} then base64 of an OpenPGP message.
50515
50797
  create or replace function ${fn("field_seal")}(key text, value text)
@@ -50541,6 +50823,20 @@ as $$
50541
50823
  $$;
50542
50824
  ${privateGrant(`${fn("field_open")}(text, text)`)}
50543
50825
 
50826
+ -- The lookup hash of a value: HMAC-SHA256 of the value, lowercased and
50827
+ -- without whitespace, under a lookup key. null without a key or a value.
50828
+ create or replace function ${fn("field_hash")}(key text, value text)
50829
+ returns bytea
50830
+ language sql
50831
+ immutable
50832
+ set search_path = ''
50833
+ as $$
50834
+ select case when field_hash.key is null or field_hash.value is null then null
50835
+ else extensions.hmac(convert_to(lower(regexp_replace(field_hash.value, '\\s', '', 'g')), 'UTF8'), decode(field_hash.key, 'base64'), 'sha256')
50836
+ end
50837
+ $$;
50838
+ ${privateGrant(`${fn("field_hash")}(text, text)`)}
50839
+
50544
50840
  -- Encrypts a value with the owner's key, creating the key on first use.
50545
50841
  create or replace function ${fn("field_encrypt")}(owner text, value text)
50546
50842
  returns text
@@ -50573,8 +50869,27 @@ end;
50573
50869
  $$;
50574
50870
  ${serviceGrant(`${fn("field_decrypt")}(text, text)`)}
50575
50871
 
50576
- -- Deletes an owner's key, so every value encrypted with it reads as null
50577
- -- (crypto-shredding, for example after a tenant is erased).
50872
+ -- The lookup hash of a value under the owner's lookup key, to compare with a
50873
+ -- <column>_lookup column; null when the owner has no lookup key.
50874
+ create or replace function ${fn("field_lookup")}(owner text, value text)
50875
+ returns bytea
50876
+ language plpgsql
50877
+ stable
50878
+ security definer
50879
+ set search_path = ''
50880
+ as $$
50881
+ begin
50882
+ if field_lookup.value is null then
50883
+ return null;
50884
+ end if;
50885
+ return ${fn("field_hash")}(${fn("field_lookup_key")}(field_lookup.owner, false), field_lookup.value);
50886
+ end;
50887
+ $$;
50888
+ ${serviceGrant(`${fn("field_lookup")}(text, text)`)}
50889
+
50890
+ -- Deletes an owner's data key and lookup key, so every value encrypted with
50891
+ -- them reads as null and no lookup finds it (crypto-shredding, for example
50892
+ -- after a tenant is erased).
50578
50893
  create or replace function ${fn("drop_field_key")}(owner text)
50579
50894
  returns boolean
50580
50895
  language plpgsql
@@ -50585,7 +50900,7 @@ begin
50585
50900
  if not (${SERVICE_CALLER$1}) then
50586
50901
  ${fail$1("FIELD_KEY_FORBIDDEN", "only the service role drops field keys")}
50587
50902
  end if;
50588
- delete from vault.secrets s where s.name = ${secret("drop_field_key.owner")};
50903
+ delete from vault.secrets s where s.name in (${secret("drop_field_key.owner")}, ${secret("drop_field_key.owner", FIELD_LOOKUP_KEY_PREFIX)});
50589
50904
  if not found then
50590
50905
  return false;
50591
50906
  end if;
@@ -50616,6 +50931,11 @@ function contract$75() {
50616
50931
  args: ["text", "text"],
50617
50932
  returns: "text"
50618
50933
  },
50934
+ {
50935
+ name: "field_lookup",
50936
+ args: ["text", "text"],
50937
+ returns: "bytea"
50938
+ },
50619
50939
  {
50620
50940
  name: "drop_field_key",
50621
50941
  args: ["text"],
@@ -50626,7 +50946,7 @@ function contract$75() {
50626
50946
  const FIELD_ENCRYPTION = {
50627
50947
  name: "field-encryption",
50628
50948
  title: "Field encryption",
50629
- description: "Encrypts app table columns and custom field values at rest with a data key per tenant, user or app, kept in Supabase Vault as bs:field-key:<owner>. Only security definer read paths that check the caller's scope decrypt; drop_field_key deletes a key so its values can no longer be read.",
50949
+ description: "Encrypts app table columns and custom field values at rest with a data key per tenant, user or app, kept in Supabase Vault as bs:field-key:<owner>. Only security definer read paths that check the caller's scope decrypt; a lookup column keeps an HMAC of the value under the owner's lookup key for equality searches; drop_field_key deletes both keys so the values can no longer be read or found.",
50630
50950
  requires: [],
50631
50951
  target: "schema",
50632
50952
  modes: ["managed"],
@@ -50640,7 +50960,10 @@ const FIELD_ENCRYPTION = {
50640
50960
  const ENCRYPTABLE_TYPES = [
50641
50961
  "text",
50642
50962
  "email",
50643
- "url"
50963
+ "url",
50964
+ "bsn",
50965
+ "iban",
50966
+ "phone_e164"
50644
50967
  ];
50645
50968
  const NAMES$82 = {
50646
50969
  entities: { field: {
@@ -50787,6 +51110,7 @@ function build$82(ctx) {
50787
51110
  const manageKey = ctx.permission("manage", OPERATIONS["custom-fields.manage"]);
50788
51111
  const { rankType, readAccess } = keyedOptions(ctx);
50789
51112
  if (layout === "keyed") return `${schemaPreamble(ctx)}
51113
+ ${formatValidatorSql(ctx.schemaName, CUSTOM_FIELD_VALIDATORS)}
50790
51114
  ${keyedFields(ctx, {
50791
51115
  manage: manageKey,
50792
51116
  read: ctx.permission("read", OPERATIONS["custom-fields.read"])
@@ -50846,7 +51170,7 @@ ${inline || !ctx.has("values", "definition") ? "" : `create index if not exists
50846
51170
  const visible = inline ? "true" : `not coalesce(d.${ctx.col("definitions", "sensitive")}, false)
50847
51171
  or ${ctx.scope.can(`v.${ctx.col("values", "tenant")}`, `coalesce(d.${ctx.col("definitions", "permission")}, ${sensitive})`)}`;
50848
51172
  return `${schemaPreamble(ctx)}
50849
- -- A sensitive value is returned only when the caller holds the field's
51173
+ ${inline ? "" : `${formatValidatorSql(ctx.schemaName, CUSTOM_FIELD_VALIDATORS)}\n`}-- A sensitive value is returned only when the caller holds the field's
50850
51174
  -- permission, or custom_fields.sensitive.read when the field names none.
50851
51175
  ${tables}
50852
51176
  create or replace function ${ctx.fn("save_field_definition")}(tenant ${ctx.idType}, entity text, key text, label text, type text, sensitive boolean)
@@ -50937,6 +51261,9 @@ begin
50937
51261
  end if;${subjectWrite === void 0 ? "" : `
50938
51262
  if not ${subjectWrite} then
50939
51263
  ${fail$1("FIELD_SUBJECT_FORBIDDEN", "not allowed to set fields on this record")}
51264
+ end if;`}${inline ? "" : `
51265
+ if exists (select 1 from ${definitions} d where d.${ctx.col("definitions", "id")} = set_field_value.definition and not (${customFieldValueCheck(`d.${ctx.col("definitions", "type")}`, "set_field_value.value", ctx.schemaName)})) then
51266
+ ${fail$1("FIELD_VALUE_INVALID", "the value doesn't match the field's format", "22023")}
50940
51267
  end if;`}
50941
51268
  insert into ${values} (${ctx.col("values", "tenant")}, ${ctx.has("values", "definition") && !inline ? `${ctx.col("values", "definition")}, ` : ""}${ctx.col("values", "subjectType")}, ${ctx.col("values", "subjectId")}, ${ctx.col("values", "valueText")})
50942
51269
  values (set_field_value.tenant, ${ctx.has("values", "definition") && !inline ? "set_field_value.definition, " : ""}set_field_value.subject_type, set_field_value.subject_id, ${encrypted === "" ? "set_field_value.value" : `case when exists (select 1 from ${definitions} d where d.${ctx.col("definitions", "id")} = set_field_value.definition and d.${ctx.col("definitions", "encrypted")}) then ${encryption?.fn("field_encrypt")}('tenant:' || set_field_value.tenant::text, set_field_value.value) else set_field_value.value end`})
@@ -53106,7 +53433,7 @@ function lineItemsSql(ctx, items, options) {
53106
53433
  ["selected", "coalesce((x.value ->> 'selected')::boolean, not coalesce((x.value ->> 'optional')::boolean, false))"],
53107
53434
  ["periods", "coalesce((x.value ->> 'periods')::integer, 1)"],
53108
53435
  ["position", "x.ordinality::integer"]
53109
- ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
53436
+ ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : column === "productId" && !replaces ? asColumnType(t, ctx.colName(items.lines, column), value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
53110
53437
  const extras = items.extras ?? [];
53111
53438
  const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
53112
53439
  const manages = ctx.manages ? `create table if not exists ${t} (
@@ -62372,9 +62699,22 @@ function hiringCandidate(hiring, row) {
62372
62699
  };
62373
62700
  }
62374
62701
  // src/sql/modules/quotes-kit.ts
62375
- /** Whether the quotes table has both columns of a company or contact link. */
62702
+ /**
62703
+ * How the quotes table holds a company or contact: a type and an id column
62704
+ * (`pair`), only an id column of the fixed type `options.company` or `contact`,
62705
+ * such as a foreign key to the app's customers (`fixed`), or not at all.
62706
+ */
62376
62707
  function quoteParty(ctx, party) {
62377
- return ctx.has("quotes", `${party}Type`) && ctx.has("quotes", `${party}Id`);
62708
+ if (!ctx.has("quotes", `${party}Id`)) return;
62709
+ return ctx.has("quotes", `${party}Type`) ? "pair" : "fixed";
62710
+ }
62711
+ /**
62712
+ * SQL for the type of a quote's company or contact under `prefix`: its type
62713
+ * column, or the fixed type when the id is set.
62714
+ */
62715
+ function quotePartyType(ctx, party, prefix) {
62716
+ const at = (logical) => `${prefix}${ctx.col("quotes", logical)}`;
62717
+ return quoteParty(ctx, party) === "pair" ? at(`${party}Type`) : `(case when ${at(`${party}Id`)} is null then null else ${sqlString(ctx.text(party, party === "company" ? "company" : "person"))} end)`;
62378
62718
  }
62379
62719
  /** Whether the quotes table has both columns of the record it was made from. */
62380
62720
  function quoteOrigin(ctx) {
@@ -62405,7 +62745,7 @@ function workingCopyOn(ctx) {
62405
62745
  */
62406
62746
  function quoteGuest(ctx, n, prefix) {
62407
62747
  const q = (column) => `${prefix}${n.c("quotes", column)}`;
62408
- const checks = [ctx.scope.guest(q("tenant"), "'quote'", `${q("id")}::text`, "read"), ...["company", "contact"].filter((party) => quoteParty(ctx, party)).map((party) => ctx.scope.guestParty(q("tenant"), q(`${party}Type`), q(`${party}Id`)))].filter((check) => check !== "false");
62748
+ const checks = [ctx.scope.guest(q("tenant"), "'quote'", `${q("id")}::text`, "read"), ...["company", "contact"].filter((party) => quoteParty(ctx, party) !== void 0).map((party) => ctx.scope.guestParty(q("tenant"), quotePartyType(ctx, party, prefix), q(`${party}Id`)))].filter((check) => check !== "false");
62409
62749
  return checks.length === 0 ? "false" : `(${ctx.is("quotes", "status", q("status"), ["draft"], true)} and (${checks.join(" or ")}))`;
62410
62750
  }
62411
62751
  function quoteKit(ctx, n) {
@@ -62463,7 +62803,8 @@ function quoteKit(ctx, n) {
62463
62803
  "selected",
62464
62804
  "periods"
62465
62805
  ].filter(lineHas).map((column) => `, ${sqlString(column)}, ql.${l(column)}`).join("");
62466
- const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('position', ql.${l("position")}, 'description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineValue("discountBps")}, 'taxRateBps', ${lineValue("taxRateBps")}, 'taxCode', ${lineValue("taxCode")}${documentLine}, 'product', case when ${lineValue("productType")} is null then null else jsonb_build_object('type', ${lineValue("productType")}, 'id', ${lineValue("productId")}) end${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
62806
+ const product = !lineHas("productType") && lineHas("productId") ? `case when ql.${l("productId")} is null then null else jsonb_build_object('type', null, 'id', ql.${l("productId")}) end` : `case when ${lineValue("productType")} is null then null else jsonb_build_object('type', ${lineValue("productType")}, 'id', ${lineValue("productId")}) end`;
62807
+ const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('position', ql.${l("position")}, 'description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineValue("discountBps")}, 'taxRateBps', ${lineValue("taxRateBps")}, 'taxCode', ${lineValue("taxCode")}${documentLine}, 'product', ${product}${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
62467
62808
  const tl = (column) => c("taxLines", column);
62468
62809
  const taxLines = (alias) => ctx.hasTable("taxLines") ? `coalesce((select jsonb_agg(jsonb_build_object('taxRateBps', tl.${tl("taxRateBps")}, 'taxCode', ${ctx.has("taxLines", "taxCode") ? `tl.${tl("taxCode")}` : "null"}, 'net', tl.${tl("net")}::text, 'tax', tl.${tl("tax")}::text, 'gross', tl.${tl("gross")}::text, 'discount', ${ctx.has("taxLines", "discount") ? `tl.${tl("discount")}::text` : "'0'"}) order by tl.${tl("taxRateBps")}, ${ctx.has("taxLines", "taxCode") ? `tl.${tl("taxCode")}` : "1"} nulls first) from ${t("taxLines")} tl where tl.${tl("parent")} = ${alias}.${q("id")}), '[]'::jsonb)` : "'[]'::jsonb";
62469
62810
  const int8Columns = [
@@ -62474,7 +62815,8 @@ function quoteKit(ctx, n) {
62474
62815
  ].filter(has);
62475
62816
  const int8 = int8Columns.map(q);
62476
62817
  const int8As = Object.fromEntries(int8Columns.map((logical) => [logical, (value) => `${value}::text`]));
62477
- const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}, 'taxLines', ${taxLines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
62818
+ const missingKeys = (alias) => `${["company", "contact"].filter((party) => quoteParty(ctx, party) === "fixed").map((party) => `, ${sqlString(`${party}_type`)}, ${quotePartyType(ctx, party, `${alias}.`)}`).join("")}${has("listTotal") ? "" : `, 'list_total', ${alias}.${q("subtotal")}::text`}${has("discountTotal") ? "" : ", 'discount_total', '0'"}`;
62819
+ const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}, 'taxLines', ${taxLines(alias)}${missingKeys(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
62478
62820
  const text = (alias, logical, otherwise) => has(logical) ? `${alias}.${q(logical)}::text` : otherwise;
62479
62821
  const v = (column) => c("versions", column);
62480
62822
  const vl = (column) => c("versionLines", column);
@@ -62493,17 +62835,37 @@ function quoteKit(ctx, n) {
62493
62835
  'taxTotal', ${alias}.${q("taxTotal")}::text, 'total', ${alias}.${q("total")}::text,
62494
62836
  'lines', ${version === void 0 ? withVersionLineIds(lines(alias), latestVersion(alias)) : withVersionLineIds(`coalesce(${version} -> 'lines', '[]'::jsonb)`, latestVersion(alias))},
62495
62837
  'taxLines', ${version === void 0 ? taxLines(alias) : `coalesce(${version} -> 'taxLines', '[]'::jsonb)`})`;
62496
- const checkParty = (kind, type, id, tenant) => (kind === "COMPANY" ? company : contact) ? `
62838
+ const checkParty = (kind, type, id, tenant) => {
62839
+ const party = kind === "COMPANY" ? "company" : "contact";
62840
+ const mode = kind === "COMPANY" ? company : contact;
62841
+ const fixed = party === "company" ? n.company : n.contact;
62842
+ if (mode === void 0) return refuse(false, id, kind, `${party} columns`);
62843
+ return `${mode === "fixed" ? `
62844
+ if ${id} is not null and ${type} is distinct from ${sqlString(fixed)} then
62845
+ ${fail$1(`QUOTE_${kind}_UNSUPPORTED`, `this quotes table takes only a ${fixed} as the ${party}`, "22023")}
62846
+ end if;` : ""}
62497
62847
  if ${id} is not null and not ${subjectInTenant(ctx, type, id, tenant)} then
62498
- ${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${kind.toLowerCase()} is unknown or not readable in this organization`, "42501")}
62499
- end if;` : refuse(false, id, kind, `${kind.toLowerCase()} columns`);
62500
- const notifyOwner = (event) => ctx.installed("notifications") ? `
62848
+ ${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${party} is unknown or not readable in this organization`, "42501")}
62849
+ end if;`;
62850
+ };
62851
+ const partyFields = (party) => {
62852
+ const mode = quoteParty(ctx, party);
62853
+ if (mode === void 0) return [];
62854
+ return mode === "pair" ? [`${party}Type`, `${party}Id`] : [`${party}Id`];
62855
+ };
62856
+ const partyValues = (party, type, id) => {
62857
+ const mode = quoteParty(ctx, party);
62858
+ if (mode === "pair") return [`case when ${id} is null then null else ${type} end`, id];
62859
+ return mode === "fixed" ? [asColumnType(t("quotes"), ctx.colName("quotes", `${party}Id`), id)] : [];
62860
+ };
62861
+ const notifyOwner = (event) => ctx.installed("notifications") && ctx.flag("notifications", true) ? `
62501
62862
  if v_row.${q("owner")} is not null then
62502
62863
  ${ctx.notify(`jsonb_build_object(
62503
62864
  'type', ${sqlString(event)},
62504
62865
  'tenant', v_row.${q("tenant")},
62505
62866
  'subject_type', 'quote',
62506
62867
  'subject_id', v_row.${q("id")}::text,
62868
+ 'subject_label', v_row.${q("identifier")} || ' ' || v_row.${q("title")},
62507
62869
  'summary', v_row.${q("identifier")} || ' ' || v_row.${q("title")},
62508
62870
  'recipients', jsonb_build_array(v_row.${q("owner")}),
62509
62871
  'key', ${sqlString(`${event}:`)} || v_row.${q("id")}::text,
@@ -62542,6 +62904,8 @@ function quoteKit(ctx, n) {
62542
62904
  workingCopy,
62543
62905
  record,
62544
62906
  checkParty,
62907
+ partyFields,
62908
+ partyValues,
62545
62909
  notifyOwner,
62546
62910
  markViewed,
62547
62911
  depositDue: !n.appTotals && has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
@@ -62666,10 +63030,10 @@ function quoteDecisions(ctx, n, k) {
62666
63030
  end if;` : ""}${selection(a.name)}
62667
63031
  ${ctx.hook("before_quote_accept", [["uuid", `v_row.${q("id")}`]])}
62668
63032
  end if;
62669
- update ${t("quotes")} x set ${q("status")} = ${ctx.cast("quotes", "status", `${a.name}.decision`)}, ${q("decidedAt")} = now(), ${q("decidedBy")} = nullif(trim(${a.by}), ''),
63033
+ ${a.customer ? "" : `${transitionReasonSql(`${a.name}.note`)}\n `}update ${t("quotes")} x set ${q("status")} = ${ctx.cast("quotes", "status", `${a.name}.decision`)}, ${q("decidedAt")} = now(), ${q("decidedBy")} = nullif(trim(${a.by}), ''),
62670
63034
  ${has("decisionNote") ? `${q("decisionNote")} = nullif(trim(${a.name}.note), ''), ` : ""}${client("decidedUser", a.actor === void 0 ? "auth.uid()" : `coalesce(nullif(${a.actor} ->> 'id', '')::uuid, auth.uid())`)}${client("decidedIp", a.customer || a.actor !== void 0 ? actorIp(a) : "null")}${client("decidedUserAgent", a.customer || a.actor !== void 0 ? actorAgent(a) : "null")}${k.workingCopy ? `${q("unpublishedChanges")} = case when ${a.name}.decision = 'accepted' then false else x.${q("unpublishedChanges")} end, ` : ""}${q("updatedAt")} = now()
62671
63035
  where x.${q("id")} = v_row.${q("id")}
62672
- returning * into v_row;
63036
+ returning * into v_row;${a.customer ? "" : `\n ${transitionReasonSql()}`}
62673
63037
  case ${a.name}.decision
62674
63038
  when 'accepted' then
62675
63039
  ${record("quote.accepted", "v_row", `, 'total', v_row.${q("total")}::text, 'currency', v_row.${q("currency")}, 'byName', v_row.${q("decidedBy")}, 'revision', v_row.${q("revision")}, 'depositDue', ${has("depositDue") ? `v_row.${q("depositDue")}::text` : "'0'"}`)}
@@ -62708,7 +63072,9 @@ function quoteDecisions(ctx, n, k) {
62708
63072
  const readable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.read)})`;
62709
63073
  return `
62710
63074
  -- Records the customer's answer taken another way (by phone, by email):
62711
- -- decision is accepted, rejected or changes_requested; by is their name.
63075
+ -- decision is accepted, rejected or changes_requested; by is their name,
63076
+ -- and without it or an actor the answer names no one. The note is also the
63077
+ -- reason in the state machine's history.
62712
63078
  -- selected lists the positions of the optional lines they took. actor is
62713
63079
  -- the customer when the app takes the answer in its own portal: id, name,
62714
63080
  -- email, ip and userAgent, kept with the answer and in the state machine's
@@ -62730,7 +63096,7 @@ begin
62730
63096
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
62731
63097
  end if;${answer({
62732
63098
  name: "decide_quote",
62733
- by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email', auth.uid()::text)",
63099
+ by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email')",
62734
63100
  customer: false,
62735
63101
  expires: "decide_quote.actor is not null",
62736
63102
  actor: "decide_quote.actor",
@@ -62941,6 +63307,13 @@ function quoteFunctions(ctx, n) {
62941
63307
  if v_row.${q("depositBps")} is not null and v_row.${q("depositAmount")} is not null then
62942
63308
  ${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
62943
63309
  end if;` : "";
63310
+ const partyAssign = (party) => {
63311
+ const given = `update_quote.attrs ? ${sqlString(party)}`;
63312
+ const id = `update_quote.attrs -> ${sqlString(party)} ->> 'id'`;
63313
+ const type = `coalesce(update_quote.attrs -> ${sqlString(party)} ->> 'type', ${sqlString(party === "company" ? n.company : n.contact)})`;
63314
+ const values = k.partyValues(party, type, id);
63315
+ return k.partyFields(party).map((field, index) => assign(field, (col) => `case when ${given} then ${values[index] ?? "null"} else x.${col} end`)).join("");
63316
+ };
62944
63317
  const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
62945
63318
  const resent = k.declined.length === 0 ? "" : `${q("validUntil")} = case when ${st(`x.${q("status")}`, k.declined)} then greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}) else x.${q("validUntil")} end, ${has("viewedAt") && !k.workingCopy ? `${q("viewedAt")} = case when ${st(`x.${q("status")}`, k.declined)} then null else x.${q("viewedAt")} end, ` : ""}`;
62946
63319
  const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
@@ -63061,14 +63434,14 @@ begin
63061
63434
  prefix: n.prefix
63062
63435
  })}
63063
63436
  begin
63064
- insert into ${t("quotes")} (${q("tenant")}, ${q("number")}, ${q("identifier")}, ${q("title")}${also("companyType")}${also("companyId")}${also("contactType")}${also("contactId")},
63437
+ insert into ${t("quotes")} (${q("tenant")}, ${q("number")}, ${q("identifier")}, ${q("title")}${[...k.partyFields("company"), ...k.partyFields("contact")].map((field) => `, ${q(field)}`).join("")},
63065
63438
  ${q("owner")}, ${q("currency")}, ${q("validUntil")}${also("terms")}${also("note")}${also("originType")}${also("originId")}${also("pricesIncludeTax")}${also("discountBps")}${also("discountAmount")}${also("depositBps")}${also("depositAmount")}${also("depositRequired")}${also("createdBy")}${insertExtraColumns(t("quotes"), n.extras, "coalesce(create_quote.attrs -> 'fields', '{}'::jsonb)").columns})
63066
63439
  values (${valueLines(" ", [
63067
63440
  "create_quote.tenant",
63068
63441
  "v_seq",
63069
63442
  "v_identifier",
63070
63443
  "trim(create_quote.attrs ->> 'title')"
63071
- ], company ? ["case when v_company_id is null then null else v_company_type end", "v_company_id"] : [], contact ? ["case when v_contact_id is null then null else v_contact_type end", "v_contact_id"] : [], ["coalesce((create_quote.attrs ->> 'ownerId')::uuid, auth.uid())", "upper(coalesce(create_quote.attrs ->> 'currency', 'EUR'))"], [`coalesce((create_quote.attrs ->> 'validUntil')::date, current_date + ${String(n.validDays)})`], [present("terms", "create_quote.attrs ->> 'terms'"), present("note", "create_quote.attrs ->> 'note'")], [present("originType", "create_quote.attrs -> 'origin' ->> 'type'"), present("originId", "create_quote.attrs -> 'origin' ->> 'id'")], [
63444
+ ], k.partyValues("company", "v_company_type", "v_company_id"), k.partyValues("contact", "v_contact_type", "v_contact_id"), ["coalesce((create_quote.attrs ->> 'ownerId')::uuid, auth.uid())", "upper(coalesce(create_quote.attrs ->> 'currency', 'EUR'))"], [`coalesce((create_quote.attrs ->> 'validUntil')::date, current_date + ${String(n.validDays)})`], [present("terms", "create_quote.attrs ->> 'terms'"), present("note", "create_quote.attrs ->> 'note'")], [present("originType", "create_quote.attrs -> 'origin' ->> 'type'"), present("originId", "create_quote.attrs -> 'origin' ->> 'id'")], [
63072
63445
  present("pricesIncludeTax", "coalesce((create_quote.attrs ->> 'pricesIncludeTax')::boolean, false)"),
63073
63446
  present("discountBps", "coalesce((create_quote.attrs ->> 'discountBps')::integer, 0)"),
63074
63447
  present("discountAmount", "coalesce((create_quote.attrs ->> 'discountAmount')::bigint, 0)"),
@@ -63124,7 +63497,7 @@ begin
63124
63497
  ${q("title")} = coalesce(nullif(trim(update_quote.attrs ->> 'title'), ''), x.${q("title")}),
63125
63498
  ${q("currency")} = coalesce(upper(update_quote.attrs ->> 'currency'), x.${q("currency")}),
63126
63499
  ${q("owner")} = case when update_quote.attrs ? 'ownerId' then (update_quote.attrs ->> 'ownerId')::uuid else x.${q("owner")} end,
63127
- ${q("validUntil")} = case when update_quote.attrs ? 'validUntil' then (update_quote.attrs ->> 'validUntil')::date else x.${q("validUntil")} end,${assign("terms", (col) => `case when update_quote.attrs ? 'terms' then update_quote.attrs ->> 'terms' else x.${col} end`)}${assign("note", (col) => `case when update_quote.attrs ? 'note' then update_quote.attrs ->> 'note' else x.${col} end`)}${assign("pricesIncludeTax", (col) => `case when update_quote.attrs ? 'pricesIncludeTax' then coalesce((update_quote.attrs ->> 'pricesIncludeTax')::boolean, false) else x.${col} end`)}${assign("discountBps", (col) => `case when update_quote.attrs ? 'discountBps' then coalesce((update_quote.attrs ->> 'discountBps')::integer, 0) else x.${col} end`)}${assign("discountAmount", (col) => `case when update_quote.attrs ? 'discountAmount' then coalesce((update_quote.attrs ->> 'discountAmount')::bigint, 0) else x.${col} end`)}${assign("depositBps", (col) => `case when update_quote.attrs ? 'depositBps' then (update_quote.attrs ->> 'depositBps')::integer else x.${col} end`)}${assign("depositAmount", (col) => `case when update_quote.attrs ? 'depositAmount' then (update_quote.attrs ->> 'depositAmount')::bigint else x.${col} end`)}${assign("depositRequired", (col) => `case when update_quote.attrs ? 'depositRequired' then coalesce((update_quote.attrs ->> 'depositRequired')::boolean, false) else x.${col} end`)}${k.workingCopy ? assign("unpublishedChanges", () => "true") : ""}${company ? assign("companyType", (col) => `case when update_quote.attrs ? 'company' then case when update_quote.attrs -> 'company' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'company' ->> 'type', ${sqlString(n.company)}) end else x.${col} end`) + assign("companyId", (col) => `case when update_quote.attrs ? 'company' then update_quote.attrs -> 'company' ->> 'id' else x.${col} end`) : ""}${contact ? assign("contactType", (col) => `case when update_quote.attrs ? 'contact' then case when update_quote.attrs -> 'contact' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'contact' ->> 'type', ${sqlString(n.contact)}) end else x.${col} end`) + assign("contactId", (col) => `case when update_quote.attrs ? 'contact' then update_quote.attrs -> 'contact' ->> 'id' else x.${col} end`) : ""}
63500
+ ${q("validUntil")} = case when update_quote.attrs ? 'validUntil' then (update_quote.attrs ->> 'validUntil')::date else x.${q("validUntil")} end,${assign("terms", (col) => `case when update_quote.attrs ? 'terms' then update_quote.attrs ->> 'terms' else x.${col} end`)}${assign("note", (col) => `case when update_quote.attrs ? 'note' then update_quote.attrs ->> 'note' else x.${col} end`)}${assign("pricesIncludeTax", (col) => `case when update_quote.attrs ? 'pricesIncludeTax' then coalesce((update_quote.attrs ->> 'pricesIncludeTax')::boolean, false) else x.${col} end`)}${assign("discountBps", (col) => `case when update_quote.attrs ? 'discountBps' then coalesce((update_quote.attrs ->> 'discountBps')::integer, 0) else x.${col} end`)}${assign("discountAmount", (col) => `case when update_quote.attrs ? 'discountAmount' then coalesce((update_quote.attrs ->> 'discountAmount')::bigint, 0) else x.${col} end`)}${assign("depositBps", (col) => `case when update_quote.attrs ? 'depositBps' then (update_quote.attrs ->> 'depositBps')::integer else x.${col} end`)}${assign("depositAmount", (col) => `case when update_quote.attrs ? 'depositAmount' then (update_quote.attrs ->> 'depositAmount')::bigint else x.${col} end`)}${assign("depositRequired", (col) => `case when update_quote.attrs ? 'depositRequired' then coalesce((update_quote.attrs ->> 'depositRequired')::boolean, false) else x.${col} end`)}${k.workingCopy ? assign("unpublishedChanges", () => "true") : ""}${partyAssign("company")}${partyAssign("contact")}
63128
63501
  ${q("updatedAt")} = now()
63129
63502
  where x.${q("id")} = v_row.${q("id")}
63130
63503
  returning * into v_row;${n.extras.length === 0 ? "" : `${writeExtraColumns(t("quotes"), n.extras, "(update_quote.attrs -> 'fields')", `x.${q("id")} = v_row.${q("id")}`)}
@@ -63238,8 +63611,10 @@ $$;
63238
63611
  ${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
63239
63612
 
63240
63613
  -- Takes back a sent or expired quote the customer hasn't accepted: it can't
63241
- -- be answered any more until it is revised and sent again.
63242
- create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null)
63614
+ -- be answered any more until it is revised and sent again. The actor and
63615
+ -- reason go to the state machine's history.
63616
+ drop function if exists ${fn("withdraw_quote")}(uuid, jsonb);
63617
+ create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null, reason text default null)
63243
63618
  returns jsonb
63244
63619
  language plpgsql
63245
63620
  security definer
@@ -63260,14 +63635,16 @@ begin
63260
63635
  ], true)} then
63261
63636
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
63262
63637
  end if;${actor("withdraw_quote")}
63638
+ ${transitionReasonSql("withdraw_quote.reason")}
63263
63639
  update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("updatedAt")} = now()
63264
63640
  where x.${q("id")} = v_row.${q("id")}
63265
63641
  returning * into v_row;
63642
+ ${transitionReasonSql()}
63266
63643
  ${record("quote.withdrawn", "v_row", `, 'revision', v_row.${q("revision")}`)}
63267
63644
  return ${row("v_row")};
63268
63645
  end;
63269
63646
  $$;
63270
- ${userGrant(`${fn("withdraw_quote")}(uuid, jsonb)`)}
63647
+ ${userGrant(`${fn("withdraw_quote")}(uuid, jsonb, text)`)}
63271
63648
  ${quoteDecisions(ctx, n, k)}
63272
63649
  -- Expires sent quotes past their valid date. Run it daily from a job.
63273
63650
  create or replace function ${fn("expire_quotes")}()
@@ -63416,7 +63793,7 @@ function employeeFunctions(ctx, n) {
63416
63793
  select u.${e("id")}, u.${e("manager")} from ${table} u join up on u.${e("id")} = up.manager
63417
63794
  )
63418
63795
  select 1 from up join ${table} me on me.${e("id")} = up.id where me.${e("user")} = auth.uid())`;
63419
- const payload = (alias, extra) => `jsonb_build_object('organizationId', ${alias}.${e("tenant")}, 'employeeId', ${alias}.${e("id")}, 'subjectType', 'employee', 'subjectId', ${alias}.${e("id")}::text, 'name', ${n.name(alias)}${extra})`;
63796
+ const payload = (alias, extra) => `jsonb_build_object('organizationId', ${alias}.${e("tenant")}, 'employeeId', ${alias}.${e("id")}, 'subjectType', 'employee', 'subjectId', ${alias}.${e("id")}::text, 'name', ${n.name(alias)}, 'userId', ${alias}.${e("user")}${extra})`;
63420
63797
  const record = (type, alias, extra = "") => ctx.record({
63421
63798
  type,
63422
63799
  payload: payload(alias, extra),
@@ -63542,7 +63919,7 @@ begin
63542
63919
  when check_violation or not_null_violation or invalid_text_representation or invalid_datetime_format or datetime_field_overflow then
63543
63920
  ${fail$1("EMPLOYEE_ATTRS_INVALID", "an employee field has an invalid value", "22023")}
63544
63921
  end;${typeCheck("v_row")}${member(`v_row.${e("tenant")}`, `v_row.${e("user")}`)}${link}
63545
- ${record("employee.created", "v_row", `, 'userId', v_row.${e("user")}, 'managerId', v_row.${e("manager")}, 'status', v_row.${e("status")}`)}
63922
+ ${record("employee.created", "v_row", `, 'managerId', v_row.${e("manager")}, 'status', v_row.${e("status")}`)}
63546
63923
  ${ctx.hook("after_employee_create", [["uuid", `v_row.${e("id")}`]])}
63547
63924
  return ${n.json("v_row")};
63548
63925
  end;
@@ -64018,7 +64395,7 @@ function contractsSql(ctx, n, reader, load) {
64018
64395
  end if;` : insertWith(void 0);
64019
64396
  const updated = ctx.record({
64020
64397
  type: "employee.updated",
64021
- payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'fields', jsonb_build_array('contract'))`,
64398
+ payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'userId', v_employee.${e("user")}, 'fields', jsonb_build_array('contract'))`,
64022
64399
  subject: `'employees/' || v_employee.${e("id")}::text`,
64023
64400
  tenant: `v_employee.${e("tenant")}::text`,
64024
64401
  audit: false
@@ -64170,14 +64547,14 @@ const EMPLOYEE = [
64170
64547
  "employeeId",
64171
64548
  "subjectType",
64172
64549
  "subjectId",
64173
- "name"
64550
+ "name",
64551
+ "userId"
64174
64552
  ];
64175
64553
  const EVENTS$12 = {
64176
64554
  "employee.created": {
64177
64555
  subject: "employees",
64178
64556
  payload: [
64179
64557
  ...EMPLOYEE,
64180
- "userId",
64181
64558
  "managerId",
64182
64559
  "status"
64183
64560
  ]
@@ -66607,7 +66984,7 @@ ${layout.entitlementsProvider ? providerEntitlementChecks(claims, layout.entitle
66607
66984
  revoke execute on function better_supabase.feature_claims(uuid) from public, anon, authenticated;
66608
66985
  grant execute on function better_supabase.feature_claims(uuid) to service_role, supabase_auth_admin;`;
66609
66986
  };
66610
- const qualified$6 = (table) => quotedTable$1(table);
66987
+ const qualified$7 = (table) => quotedTable$1(table);
66611
66988
  /**
66612
66989
  * `tenant_entitlements` over a plan catalog: the active subscription's plan
66613
66990
  * features.
@@ -66629,8 +67006,8 @@ security definer
66629
67006
  set search_path = ''
66630
67007
  as $$
66631
67008
  select coalesce(array_agg(distinct f.${sqlIdent(features.feature)}::text order by f.${sqlIdent(features.feature)}::text), '{}')
66632
- from ${qualified$6(subs.table)} s
66633
- join ${qualified$6(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
67009
+ from ${qualified$7(subs.table)} s
67010
+ join ${qualified$7(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
66634
67011
  where s.${sqlIdent(subs.tenant)} = tenant_entitlements.tenant${status}${included}
66635
67012
  and f.${sqlIdent(features.feature)} is not null
66636
67013
  $$;
@@ -66649,7 +67026,7 @@ security definer
66649
67026
  set search_path = ''
66650
67027
  as $$
66651
67028
  select coalesce(array_agg(distinct s.${sqlIdent(subs.plan)}::text order by s.${sqlIdent(subs.plan)}::text), '{}')
66652
- from ${qualified$6(subs.table)} s
67029
+ from ${qualified$7(subs.table)} s
66653
67030
  where s.${sqlIdent(subs.tenant)} = tenant_plans.tenant${status}
66654
67031
  and s.${sqlIdent(subs.plan)} is not null
66655
67032
  $$;
@@ -66678,8 +67055,8 @@ security definer
66678
67055
  set search_path = ''
66679
67056
  as $$
66680
67057
  select coalesce(${value}, 'true'::jsonb)
66681
- from ${qualified$6(subs.table)} s
66682
- join ${qualified$6(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
67058
+ from ${qualified$7(subs.table)} s
67059
+ join ${qualified$7(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
66683
67060
  where s.${sqlIdent(subs.tenant)} = tenant_entitlement_value.tenant${status}${included}
66684
67061
  and f.${sqlIdent(features.feature)}::text = tenant_entitlement_value.key
66685
67062
  order by case when jsonb_typeof(${value}) = 'number' then (${value} #>> '{}')::numeric end desc nulls last,
@@ -73213,6 +73590,7 @@ const NAMES$65 = {
73213
73590
  payload: ACCESS_PAYLOAD
73214
73591
  }
73215
73592
  },
73593
+ options: ["representation"],
73216
73594
  tables: {
73217
73595
  guests: {
73218
73596
  name: "guests",
@@ -73296,6 +73674,44 @@ function grantSubjectTenant(ctx, type, id) {
73296
73674
  const registered = subjectTenant(ctx, type, id);
73297
73675
  return owned.length === 0 ? registered : `(case ${type}\n ${owned.join("\n ")}\n else ${registered}\n end)`;
73298
73676
  }
73677
+ const SUBJECT_TYPE = /^[a-z][a-z0-9_-]{0,62}$/;
73678
+ /** `options.representation.subjects`, checked; undefined without the option. */
73679
+ function representedTypes(ctx) {
73680
+ const where = "blocks.guests.options.representation";
73681
+ const raw = ctx.option("representation");
73682
+ if (raw === void 0) return;
73683
+ const subjects = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? new Map(Object.entries(raw)).get("subjects") : void 0;
73684
+ const list = Array.isArray(subjects) ? subjects : [];
73685
+ const types = list.filter((type) => typeof type === "string" && SUBJECT_TYPE.test(type));
73686
+ if (types.length === 0 || types.length !== list.length) throw new TypeError(`${where} must be { subjects: [...] }, a non-empty list of subject types`);
73687
+ if (!ctx.installed("relations") || !ctx.installed("contacts")) throw new TypeError(`${where} needs the relations and contacts blocks`);
73688
+ if (!(ctx.has("guests", "partyType") && ctx.has("guests", "partyId"))) throw new TypeError(`${where} needs the guests table's party_type and party_id columns`);
73689
+ return types;
73690
+ }
73691
+ /**
73692
+ * The records a guest reaches as a representative: their party is a contacts
73693
+ * person with a `represents` link to a record of a listed type that holds
73694
+ * today. `read` always, `comment` and `upload` with `authority: "act"`. Read
73695
+ * live from the links, so ending or dating a link takes effect at once.
73696
+ */
73697
+ function representation(ctx, live) {
73698
+ const types = representedTypes(ctx);
73699
+ if (types === void 0) return {};
73700
+ const relations = ctx.of("relations");
73701
+ const r = (column) => `r.${relations.col("relations", column)}`;
73702
+ const g = (column) => `x.${ctx.col("guests", column)}`;
73703
+ const person = sqlString(ctx.of("contacts").naming.rename("person"));
73704
+ return { subjects: `select ${g("tenant")}::text, ${r("targetType")}, ${r("targetId")}
73705
+ from ${relations.table("relations")} r
73706
+ join ${ctx.table("guests")} x on ${g("tenant")} = ${r("tenant")}
73707
+ and ${g("partyType")} = ${person} and ${g("partyId")} = ${r("sourceId")}
73708
+ where ${live("x")}
73709
+ and ${r("kind")} = ${sqlString(REPRESENTS)} and ${r("sourceType")} = ${person}
73710
+ and ${r("targetType")} in (${types.map((type) => sqlString(type)).join(", ")})
73711
+ and ${representationActive(r("data"))}
73712
+ and (portal_subjects.action = 'read'
73713
+ or (${r("data")} ->> 'authority' = 'act' and portal_subjects.action in ('comment', 'upload')))` };
73714
+ }
73299
73715
  function tables$19(ctx) {
73300
73716
  if (!ctx.manages) return "";
73301
73717
  const guests = ctx.table("guests");
@@ -73478,7 +73894,11 @@ function functions$7(ctx, layout) {
73478
73894
  end if;`;
73479
73895
  const token = "encode(extensions.gen_random_bytes(32), 'hex')";
73480
73896
  const hash = (value) => sha256Hex$1(`convert_to(${value}, 'utf8')`);
73481
- return `${guestFunctions([own, providerGuestSource(layout)])}
73897
+ return `${guestFunctions([
73898
+ own,
73899
+ representation(ctx, live),
73900
+ providerGuestSource(layout)
73901
+ ])}
73482
73902
  -- Whether the caller reaches subject_type/subject_id as a guest for action.
73483
73903
  create or replace function ${fn("guest_can")}(subject_type text, subject_id text, action text default 'read')
73484
73904
  returns boolean
@@ -73868,7 +74288,8 @@ const GUESTS = {
73868
74288
  "audit",
73869
74289
  "invoices",
73870
74290
  "bookings",
73871
- "contacts"
74291
+ "contacts",
74292
+ "relations"
73872
74293
  ],
73873
74294
  before: "comments",
73874
74295
  target: "schema",
@@ -86656,7 +87077,7 @@ function invoiceFromQuote(ctx, n, k) {
86656
87077
  v_header := jsonb_build_object(${quoteDiscounts.map((column) => `${sqlString(column)}, v_quote.${q(column)}${column === "discountAmount" ? "::text" : ""}`).join(", ")});
86657
87078
  else${discountLines === "" ? "\n null;" : discountLines.replaceAll("\n", "\n ")}
86658
87079
  end if;` : discountLines;
86659
- const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
87080
+ const party = (kind) => (kind === "company" ? company : contact) && quoteParty(quotes, kind) !== void 0 ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', ${quotePartyType(quotes, kind, "v_quote.")}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
86660
87081
  const create = `${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
86661
87082
  'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', ${has("depositBps") ? "invoice_from_quote.deposit_bps" : "null"},${has("depositAmount") ? " 'depositAmount', invoice_from_quote.deposit_amount::text," : ""}${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
86662
87083
  'company', ${party("company")},
@@ -87236,11 +87657,13 @@ ${userGrant(`${fn("issue_invoice")}(uuid, date, date, jsonb)`)}
87236
87657
  -- currency as a ledger transaction from the invoice's receivable account to
87237
87658
  -- cash. A reference, such as a bank or payment provider id, is unique per
87238
87659
  -- organization, so recording the same payment twice adds it once. actor:
87239
- -- who recorded it, for the state machine's history.
87660
+ -- who recorded it, and reason: why the status changes, for the state
87661
+ -- machine's history.
87240
87662
  drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, timestamptz, text, text);
87241
87663
  drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text);
87242
87664
  drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text);
87243
- create or replace function ${fn("record_invoice_payment")}(invoice uuid, amount bigint, currency text, paid_at timestamptz, method text, reference text, note text default null, actor jsonb default null)
87665
+ drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb);
87666
+ create or replace function ${fn("record_invoice_payment")}(invoice uuid, amount bigint, currency text, paid_at timestamptz, method text, reference text, note text default null, actor jsonb default null, reason text default null)
87244
87667
  returns jsonb
87245
87668
  language plpgsql
87246
87669
  security definer
@@ -87288,7 +87711,9 @@ begin
87288
87711
  end if;
87289
87712
  ${ctx.hook("before_invoice_payment", [["uuid", `v_row.${i("id")}`], ["bigint", "record_invoice_payment.amount"]])}
87290
87713
  v_was := v_row.${i("status")};
87714
+ ${transitionReasonSql("record_invoice_payment.reason")}
87291
87715
  v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference", "nullif(trim(record_invoice_payment.note), '')")};${settle("v_row", afterWriteOff)}
87716
+ ${transitionReasonSql()}
87292
87717
  ${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
87293
87718
  if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
87294
87719
  ${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
@@ -87297,7 +87722,7 @@ begin
87297
87722
  return ${row("v_row")};
87298
87723
  end;
87299
87724
  $$;
87300
- ${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb)`)}
87725
+ ${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb, text)`)}
87301
87726
 
87302
87727
  create or replace function ${fn("list_invoice_payments")}(invoice uuid)
87303
87728
  returns jsonb
@@ -87946,7 +88371,8 @@ function contract$48(ctx) {
87946
88371
  "text",
87947
88372
  "text",
87948
88373
  "text",
87949
- "jsonb"
88374
+ "jsonb",
88375
+ "text"
87950
88376
  ],
87951
88377
  returns: "jsonb"
87952
88378
  },
@@ -96396,7 +96822,7 @@ function windowOf(ctx) {
96396
96822
  if (!WINDOW.test(window)) throw new TypeError("blocks.metrics.options.window must be an interval such as \"3 days\" or \"12 hours\"");
96397
96823
  return window;
96398
96824
  }
96399
- const qualified$5 = (table) => table.includes(".") ? table : `public.${table}`;
96825
+ const qualified$6 = (table) => table.includes(".") ? table : `public.${table}`;
96400
96826
  /**
96401
96827
  * The metrics declared in `options.metrics`. A metric over a subject table with
96402
96828
  * `deletedAt` skips soft-deleted rows unless `where` names that column or the
@@ -96405,7 +96831,7 @@ const qualified$5 = (table) => table.includes(".") ? table : `public.${table}`;
96405
96831
  function declaredMetrics(ctx) {
96406
96832
  return metricsOf(ctx.option("metrics")).map((metric) => {
96407
96833
  if (metric.includeDeleted === true) return metric;
96408
- const column = Object.values(ctx.subjects).find((entry) => entry.deletedAt !== void 0 && qualified$5(entry.table) === qualified$5(metric.table))?.deletedAt;
96834
+ const column = Object.values(ctx.subjects).find((entry) => entry.deletedAt !== void 0 && qualified$6(entry.table) === qualified$6(metric.table))?.deletedAt;
96409
96835
  if (column === void 0 || Object.hasOwn(metric.where ?? {}, column)) return metric;
96410
96836
  return {
96411
96837
  ...metric,
@@ -102036,7 +102462,7 @@ function contract$40() {
102036
102462
  const OAUTH_SERVER = {
102037
102463
  name: "oauth-server",
102038
102464
  title: "OAuth server",
102039
- description: "Storage for an OAuth 2.1 authorization server: registered clients (RFC 7591) with hashed secrets, a grant per user and client, single-use authorization codes bound to a PKCE S256 challenge, device codes (RFC 8628) and a revocation list of access token jtis. It issues no tokens. createOAuthServer() in better-supabase/blocks/oauth-server hashes secrets and checks PKCE, and its isRevoked plugs into accessTokenResolver.",
102465
+ description: "Storage for an OAuth 2.1 authorization server: registered clients (RFC 7591) with hashed secrets, a grant per user and client, single-use authorization codes bound to a PKCE S256 challenge, device codes (RFC 8628) and a revocation list of access token jtis. It issues no tokens. createOauthServer() in better-supabase/blocks/oauth-server hashes secrets and checks PKCE, and its isRevoked plugs into accessTokenResolver.",
102040
102466
  requires: [],
102041
102467
  integrates: ["outbox", "audit"],
102042
102468
  target: "schema",
@@ -102903,7 +103329,7 @@ begin
102903
103329
  end if;
102904
103330
  return ${fn("order_from_document")}(v_quote.${q("tenant")}, v_attrs || jsonb_build_object(
102905
103331
  'currency', v_quote.${q("currency")}, 'taxInclusive', ${inclusive},
102906
- 'subtotal', v_quote.${q("listTotal")}::text, 'discountTotal', v_quote.${q("discountTotal")}::text, 'shippingTotal', '0',
103332
+ 'subtotal', v_quote.${q(quotes.has("quotes", "listTotal") ? "listTotal" : "subtotal")}::text, 'discountTotal', ${quotes.has("quotes", "discountTotal") ? `v_quote.${q("discountTotal")}::text` : "'0'"}, 'shippingTotal', '0',
102907
103333
  'taxTotal', v_quote.${q("taxTotal")}::text, 'total', v_quote.${q("total")}::text,
102908
103334
  'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text)),
102909
103335
  v_lines, nullif(v_attrs ->> 'locationId', '')::uuid);
@@ -111360,7 +111786,7 @@ function guard$5(names, tenant) {
111360
111786
  /** `options.extraColumns`, added to the promotions table. */
111361
111787
  const promotionExtras = (ctx) => ctx.extraColumns("promotions");
111362
111788
  /** Normalizes a shopper-typed code: trimmed and upper case. */
111363
- const normalized = (code) => `upper(btrim(${code}))`;
111789
+ const normalized$1 = (code) => `upper(btrim(${code}))`;
111364
111790
  function promotionFunctions(ctx, names) {
111365
111791
  const { fn } = names;
111366
111792
  const extras = promotionExtras(ctx);
@@ -111566,7 +111992,7 @@ declare
111566
111992
  v_code text;
111567
111993
  v_id uuid;
111568
111994
  v_out jsonb := '[]';
111569
- v_prefix text := coalesce(${normalized("create_promotion_codes.prefix")}, '');
111995
+ v_prefix text := coalesce(${normalized$1("create_promotion_codes.prefix")}, '');
111570
111996
  v_bytes bytea;
111571
111997
  v_attempts integer := 0;
111572
111998
  begin
@@ -111589,7 +112015,7 @@ begin
111589
112015
  end if;
111590
112016
  if create_promotion_codes.codes is not null then
111591
112017
  foreach v_code in array create_promotion_codes.codes loop
111592
- v_code := ${normalized("v_code")};
112018
+ v_code := ${normalized$1("v_code")};
111593
112019
  if v_code is null or v_code !~ '^[A-Z0-9_-]{3,40}$' then
111594
112020
  ${fail$1("PROMOTIONS_CODE_FORMAT", "a code has 3 to 40 letters, digits, dashes or underscores", "22023")}
111595
112021
  end if;
@@ -111678,7 +112104,7 @@ begin
111678
112104
  x.${p("usageLimit")} as usage_limit, x.${p("redemptions")} as used
111679
112105
  into v_code
111680
112106
  from ${codes} k join ${ctx.table("promotions")} x on x.${p("id")} = k.${k("promotion")}
111681
- where k.${k("tenant")} = v_cart.tenant and k.${k("code")} = ${normalized("apply_promotion_code.code")}
112107
+ where k.${k("tenant")} = v_cart.tenant and k.${k("code")} = ${normalized$1("apply_promotion_code.code")}
111682
112108
  and x.${p("active")} and (x.${p("startsAt")} is null or x.${p("startsAt")} <= now())
111683
112109
  and (x.${p("endsAt")} is null or x.${p("endsAt")} > now());
111684
112110
  if not found then
@@ -111718,7 +112144,7 @@ begin
111718
112144
  end if;
111719
112145
  delete from ${ctx.table("cartCodes")} x
111720
112146
  where x.${cc("cart")} = remove_promotion_code.cart
111721
- and x.${cc("code")} in (select k.${k("id")} from ${codes} k where k.${k("code")} = ${normalized("remove_promotion_code.code")});
112147
+ and x.${cc("code")} in (select k.${k("id")} from ${codes} k where k.${k("code")} = ${normalized$1("remove_promotion_code.code")});
111722
112148
  return found;
111723
112149
  end;
111724
112150
  $$;
@@ -114126,7 +114552,8 @@ const NAMES$35 = {
114126
114552
  "versionLines",
114127
114553
  "versionLineExtraColumns",
114128
114554
  "totals",
114129
- "resend"
114555
+ "resend",
114556
+ "notifications"
114130
114557
  ],
114131
114558
  tables: {
114132
114559
  quotes: {
@@ -114200,7 +114627,9 @@ const NAMES$35 = {
114200
114627
  "depositRequired",
114201
114628
  "depositDue",
114202
114629
  "unpublishedChanges",
114203
- "createdBy"
114630
+ "createdBy",
114631
+ "listTotal",
114632
+ "discountTotal"
114204
114633
  ],
114205
114634
  typed: ["status"]
114206
114635
  },
@@ -114301,7 +114730,7 @@ function tables$5(ctx, n) {
114301
114730
  ].filter(([logical]) => ctx.has("quotes", logical)).map(([logical, type]) => `alter table ${t("quotes")} add column if not exists ${q(logical)} ${type(q(logical))};\n`).join("");
114302
114731
  const constraints = [
114303
114732
  `unique (${q("tenant")}, ${q("number")}, ${q("revision")})`,
114304
- ...company ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
114733
+ ...company === "pair" ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
114305
114734
  ...origin ? [`check ((${q("originType")} is null) = (${q("originId")} is null))`] : []
114306
114735
  ];
114307
114736
  return `
@@ -114515,7 +114944,11 @@ function contract$32(ctx) {
114515
114944
  },
114516
114945
  {
114517
114946
  name: "withdraw_quote",
114518
- args: ["uuid", "jsonb"],
114947
+ args: [
114948
+ "uuid",
114949
+ "jsonb",
114950
+ "text"
114951
+ ],
114519
114952
  returns: "jsonb"
114520
114953
  },
114521
114954
  {
@@ -116450,14 +116883,48 @@ const NAMES$31 = {
116450
116883
  }
116451
116884
  } }
116452
116885
  };
116886
+ const KIND_OPTIONS = [
116887
+ "inverse",
116888
+ "acyclic",
116889
+ "cardinality",
116890
+ "symmetric",
116891
+ "types"
116892
+ ];
116893
+ /** `types.source` or `types.target` of a kind, checked. */
116894
+ function typeList(where, value) {
116895
+ if (value === void 0) return;
116896
+ const list = Array.isArray(value) ? value : [];
116897
+ const types = list.filter((type) => typeof type === "string" && NAME$1.test(type));
116898
+ if (types.length === 0 || types.length !== list.length) throw new TypeError(`${where} must be a non-empty list of subject types (lowercase letters, digits and underscores)`);
116899
+ return types;
116900
+ }
116901
+ /** `types` of a kind, checked. */
116902
+ function kindTypes(where, value) {
116903
+ if (value === void 0) return {
116904
+ sourceTypes: void 0,
116905
+ targetTypes: void 0
116906
+ };
116907
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${where} must be an object with source and target`);
116908
+ const entry = new Map(Object.entries(value));
116909
+ for (const key of entry.keys()) if (key !== "source" && key !== "target") throw new TypeError(`${where}.${key} is not an option. Options: source, target`);
116910
+ return {
116911
+ sourceTypes: typeList(`${where}.source`, entry.get("source")),
116912
+ targetTypes: typeList(`${where}.target`, entry.get("target"))
116913
+ };
116914
+ }
116453
116915
  /**
116454
- * `options.kinds`, checked: names, inverses that clash, and symmetric kinds
116455
- * without direction.
116916
+ * `options.kinds` (or the defaults), then the kinds other blocks contribute
116917
+ * that the app doesn't name, checked: names, inverses that clash, and symmetric
116918
+ * kinds without direction.
116456
116919
  */
116457
116920
  function relationKinds(ctx) {
116458
116921
  const where = "blocks.relations.options.kinds";
116459
116922
  const raw = ctx.option("kinds") ?? DEFAULT_RELATION_KINDS;
116460
116923
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new TypeError(`${where} must be an object of kind name to options`);
116924
+ const own = new Map(Object.entries(raw));
116925
+ const contributions = uniqueContributions("relations", ctx.contributions("relations"), (contribution) => contribution.kind).filter((contribution) => !own.has(contribution.kind));
116926
+ const contributed = contributions.map(({ kind, data: _data, ...entry }) => [kind, entry]);
116927
+ const checks = new Map(contributions.map((contribution) => [contribution.kind, contribution.data]));
116461
116928
  const kinds = [];
116462
116929
  const names = /* @__PURE__ */ new Set();
116463
116930
  const claim = (name) => {
@@ -116465,16 +116932,11 @@ function relationKinds(ctx) {
116465
116932
  if (names.has(name)) throw new TypeError(`${where}: "${name}" is named twice`);
116466
116933
  names.add(name);
116467
116934
  };
116468
- for (const [name, value] of new Map(Object.entries(raw))) {
116935
+ for (const [name, value] of [...own, ...contributed]) {
116469
116936
  claim(name);
116470
116937
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${where}.${name} must be an object`);
116471
116938
  const entry = new Map(Object.entries(value));
116472
- for (const key of entry.keys()) if (![
116473
- "inverse",
116474
- "acyclic",
116475
- "cardinality",
116476
- "symmetric"
116477
- ].includes(key)) throw new TypeError(`${where}.${name}.${key} is not an option. Options: inverse, acyclic, cardinality, symmetric`);
116939
+ for (const key of entry.keys()) if (!KIND_OPTIONS.includes(key)) throw new TypeError(`${where}.${name}.${key} is not an option. Options: ${KIND_OPTIONS.join(", ")}`);
116478
116940
  const inverse = entry.get("inverse");
116479
116941
  if (inverse !== void 0 && typeof inverse !== "string") throw new TypeError(`${where}.${name}.inverse must be a string`);
116480
116942
  const cardinality = entry.get("cardinality") ?? "many";
@@ -116487,11 +116949,36 @@ function relationKinds(ctx) {
116487
116949
  inverse,
116488
116950
  acyclic: entry.get("acyclic") === true,
116489
116951
  single: cardinality === "one",
116490
- symmetric
116952
+ symmetric,
116953
+ ...kindTypes(`${where}.${name}.types`, entry.get("types")),
116954
+ data: checks.get(name)
116491
116955
  });
116492
116956
  }
116493
116957
  return kinds;
116494
116958
  }
116959
+ /**
116960
+ * The checks `link` runs on the stored ends of each kind that names its subject
116961
+ * types. A symmetric kind accepts either order.
116962
+ */
116963
+ function typeChecks(kinds) {
116964
+ const within = (column, types) => types === void 0 ? void 0 : `${column} in (${types.map((type) => sqlString(type)).join(", ")})`;
116965
+ const both = (source, target, kind) => [within(source, kind.sourceTypes), within(target, kind.targetTypes)].filter((part) => part !== void 0).join(" and ");
116966
+ return kinds.filter((kind) => kind.sourceTypes !== void 0 || kind.targetTypes !== void 0).map((kind) => {
116967
+ const forward = both("v_source_type", "v_target_type", kind);
116968
+ const allowed = kind.symmetric ? `(${forward}) or (${both("v_target_type", "v_source_type", kind)})` : forward;
116969
+ return `
116970
+ if v_kind = ${sqlString(kind.name)} and not (${allowed}) then
116971
+ ${fail$1("RELATION_TYPE_NOT_ALLOWED", `this kind of link doesn't accept these record types`, "22023")}
116972
+ end if;`;
116973
+ }).join("");
116974
+ }
116975
+ /** The checks `link` runs on the data it stores, for kinds that check it. */
116976
+ function dataChecks(kinds, data) {
116977
+ return kinds.flatMap((kind) => kind.data === void 0 ? [] : [`
116978
+ if v_kind = ${sqlString(kind.name)} and not coalesce(${kind.data(data)}, false) then
116979
+ ${fail$1("RELATION_DATA_INVALID", "this kind of link doesn't accept this data", "22023")}
116980
+ end if;`]).join("");
116981
+ }
116495
116982
  /** A `values` list of every name a caller may pass, with the kind it stands for. */
116496
116983
  function kindTable(kinds) {
116497
116984
  return `(values ${kinds.flatMap((kind) => {
@@ -116668,7 +117155,7 @@ begin
116668
117155
  if link.source_type = link.target_type and link.source_id = link.target_id then
116669
117156
  ${fail$1("RELATION_SELF", "a record can't link to itself", "22023")}
116670
117157
  end if;
116671
- ${canonical("link")}
117158
+ ${canonical("link")}${typeChecks(kinds)}
116672
117159
  if not (${readable("link", "link.source_type", "link.source_id")})
116673
117160
  or not (${readable("link", "link.target_type", "link.target_id")}) then
116674
117161
  ${fail$1("RELATION_SUBJECT_FORBIDDEN", "not allowed to link these records")}
@@ -116688,7 +117175,7 @@ ${canonical("link")}
116688
117175
  where ${tenant} = link.tenant and ${kind} = v_kind
116689
117176
  and ${sourceType} = v_source_type and ${sourceId} = v_source_id
116690
117177
  and ${targetType} = v_target_type and ${targetId} = v_target_id;
116691
- if v_id is null then
117178
+ if v_id is null then${dataChecks(kinds, "coalesce(link.data, '{}'::jsonb)")}
116692
117179
  if v_acyclic and exists (
116693
117180
  with recursive reach(t, i, depth) as (
116694
117181
  select v_target_type, v_target_id, 0
@@ -116723,7 +117210,7 @@ ${canonical("link")}
116723
117210
  returning ${id} into v_id;
116724
117211
  v_created := true;
116725
117212
  ${event("subject.linked", "v_id", "link.tenant")}
116726
- elsif link.data is not null then
117213
+ elsif link.data is not null then${dataChecks(kinds, "link.data")}
116727
117214
  update ${relations} set ${data} = link.data where ${id} = v_id;
116728
117215
  end if;${writeExtraColumns(relations, extras, "link.fields", `x.${id} = v_id`)}
116729
117216
  ${ctx.hook("after_relation_link", [["uuid", "v_id"]])}
@@ -123498,19 +123985,30 @@ function bootstrapFunctions(ctx) {
123498
123985
  });
123499
123986
  }
123500
123987
  /**
123988
+ * Whether the database keeps a live authorization version: the module's own
123989
+ * table (`authzVersions`) or the provider's (`authorization.versions`).
123990
+ */
123991
+ function hasVersionSource(ctx, layout) {
123992
+ return layout.authzVersionsProvider !== void 0 || ctx.flag("authzVersions", false);
123993
+ }
123994
+ /**
123501
123995
  * One wrapper per `bootstrap` entry: the session check, the authorization
123502
123996
  * version and the app function's data in one jsonb, so a page's first query
123503
123997
  * carries all three. It runs as the caller, so the app function's policies
123504
- * apply.
123998
+ * apply. `authz_version` is the live version when the database keeps one, so a
123999
+ * seeded version cache never hides a role change the token predates;
124000
+ * `token_authz_version` is the token's.
123505
124001
  */
123506
- function bootstrapWrappers(ctx) {
124002
+ function bootstrapWrappers(ctx, layout) {
123507
124003
  const functions = bootstrapFunctions(ctx);
123508
124004
  if (functions.length === 0) return "";
124005
+ const live = hasVersionSource(ctx, layout) ? "to_jsonb(better_supabase.caller_authz_version())" : "auth.jwt() -> 'authz_ver'";
123509
124006
  return `
123510
124007
 
123511
124008
  -- blocks['sessions'].options.bootstrap: bsb.bootstrap({ rpc }) calls these.
123512
124009
  -- Each checks the session and returns the caller's authorization version
123513
- -- with the app function's data, so a cache miss is one query.
124010
+ -- (the live one when the database keeps it, and the token's) with the app
124011
+ -- function's data, so a cache miss is one query.
123514
124012
  ${functions.map(([name, fn]) => {
123515
124013
  const wrapper = `better_supabase.bootstrap_${name}`;
123516
124014
  return `create or replace function ${wrapper}(args jsonb default '{}'::jsonb)
@@ -123524,13 +124022,15 @@ begin
123524
124022
  return jsonb_build_object(
123525
124023
  'session_active', false,
123526
124024
  'authz_version', auth.jwt() -> 'authz_ver',
124025
+ 'token_authz_version', auth.jwt() -> 'authz_ver',
123527
124026
  'tenant', args ->> 'tenant',
123528
124027
  'data', null
123529
124028
  );
123530
124029
  end if;
123531
124030
  return jsonb_build_object(
123532
124031
  'session_active', true,
123533
- 'authz_version', auth.jwt() -> 'authz_ver',
124032
+ 'authz_version', ${live},
124033
+ 'token_authz_version', auth.jwt() -> 'authz_ver',
123534
124034
  'tenant', args ->> 'tenant',
123535
124035
  'data', to_jsonb(${fn}(args))
123536
124036
  );
@@ -123542,12 +124042,46 @@ grant execute on function ${wrapper}(jsonb) to authenticated;`;
123542
124042
  }).join("\n\n")}`;
123543
124043
  }
123544
124044
  /**
124045
+ * `better_supabase.caller_authz_version()`: the caller's own live version, for
124046
+ * the bootstrap wrappers and for clients that catch up after a missed
124047
+ * broadcast. Reads the provider's function when it keeps the versions.
124048
+ */
124049
+ function callerAuthzVersion(ctx, layout) {
124050
+ if (!hasVersionSource(ctx, layout)) return "";
124051
+ const provider = layout.authzVersionsProvider;
124052
+ const source = provider ? `${provider.function}(auth.uid())` : "better_supabase.authz_version(auth.uid())";
124053
+ return `
124054
+
124055
+ -- The caller's own authorization version, null without a signed-in user.
124056
+ -- Clients compare it with the token's authz_ver to catch up on a broadcast
124057
+ -- they missed.${provider ? `\n-- ${provider.name} keeps the versions in ${provider.function}.` : ""}
124058
+ create or replace function better_supabase.caller_authz_version()
124059
+ returns bigint
124060
+ language plpgsql
124061
+ stable
124062
+ security definer
124063
+ set search_path = ''
124064
+ as $$
124065
+ begin
124066
+ if auth.uid() is null then
124067
+ return null;
124068
+ end if;
124069
+ return ${source};
124070
+ end;
124071
+ $$;
124072
+
124073
+ revoke execute on function better_supabase.caller_authz_version() from public, anon;
124074
+ grant execute on function better_supabase.caller_authz_version() to authenticated;`;
124075
+ }
124076
+ /**
123545
124077
  * `blocks['sessions'].options.authzVersions`: a version per user that a trigger
123546
124078
  * bumps, the access token hook copies into `authz_ver`, and Realtime broadcasts
123547
- * on the shared server topic and on the user's own `authz:<uid>`.
124079
+ * on the shared server topic and on the user's own `authz:<uid>`. A provider
124080
+ * that keeps the versions (`authorization.versions`) owns all of that, so the
124081
+ * module writes none of it.
123548
124082
  */
123549
- function authzVersions(ctx) {
123550
- if (!ctx.flag("authzVersions", false)) return "";
124083
+ function authzVersions(ctx, layout) {
124084
+ if (!ctx.flag("authzVersions", false) || layout.authzVersionsProvider !== void 0) return "";
123551
124085
  const payload = "jsonb_build_object('user_id', new.user_id, 'version', new.version)";
123552
124086
  return `
123553
124087
 
@@ -123796,7 +124330,7 @@ grant execute on function better_supabase.end_my_session(uuid) to authenticated;
123796
124330
  -- create policy session_required on public.invoices as restrictive
123797
124331
  -- for all to authenticated
123798
124332
  -- using ((select better_supabase.session_active()))
123799
- -- with check ((select better_supabase.session_active()));${sessionPolicies(ctx, layout)}${bootstrapWrappers(ctx)}${authzVersions(ctx)}`
124333
+ -- with check ((select better_supabase.session_active()));${sessionPolicies(ctx, layout)}${authzVersions(ctx, layout)}${callerAuthzVersion(ctx, layout)}${bootstrapWrappers(ctx, layout)}`
123800
124334
  };
123801
124335
  // src/sql/modules/settings.ts
123802
124336
  const EVENTS$4 = {
@@ -124225,6 +124759,20 @@ as $$
124225
124759
  select exists (select 1 from removed)
124226
124760
  $$;
124227
124761
 
124762
+ -- One organization setting for other modules' security definer functions,
124763
+ -- which decide who may see it. Returns null when the key is not set.
124764
+ create or replace function ${fn("organization_setting")}(tenant ${id}, key text)
124765
+ returns jsonb
124766
+ language sql
124767
+ stable
124768
+ security definer
124769
+ set search_path = ''
124770
+ as $$
124771
+ select s.${oc("value")}
124772
+ from ${o} s
124773
+ where s.${oc("tenant")} = organization_setting.tenant and s.${oc("key")} = organization_setting.key
124774
+ $$;
124775
+
124228
124776
  create or replace function ${fn("get_platform_settings")}()
124229
124777
  returns jsonb
124230
124778
  language sql
@@ -124280,6 +124828,7 @@ grant execute on function ${fn("reset_user_setting")}(text) to authenticated, se
124280
124828
  grant execute on function ${fn("get_organization_settings")}(${id}) to authenticated, service_role;
124281
124829
  grant execute on function ${fn("set_organization_setting")}(${id}, text, jsonb) to authenticated, service_role;
124282
124830
  grant execute on function ${fn("reset_organization_setting")}(${id}, text) to authenticated, service_role;
124831
+ ${serviceGrant(`${fn("organization_setting")}(${id}, text)`)}
124283
124832
 
124284
124833
  -- Records organization and platform setting changes; user settings are not
124285
124834
  -- recorded.
@@ -124333,6 +124882,11 @@ function contract$19() {
124333
124882
  args: ["{id}", "text"],
124334
124883
  returns: "boolean"
124335
124884
  },
124885
+ {
124886
+ name: "organization_setting",
124887
+ args: ["{id}", "text"],
124888
+ returns: "jsonb"
124889
+ },
124336
124890
  {
124337
124891
  name: "get_platform_settings",
124338
124892
  args: [],
@@ -125593,7 +126147,8 @@ const NAMES$18 = {
125593
126147
  payload: [
125594
126148
  ...SUBJECT_PAYLOAD$1,
125595
126149
  "id",
125596
- "versionId"
126150
+ "versionId",
126151
+ "meaning"
125597
126152
  ]
125598
126153
  },
125599
126154
  "signature.declined": {
@@ -125615,7 +126170,7 @@ const NAMES$18 = {
125615
126170
  "before_signature_sign",
125616
126171
  "after_signature_sign"
125617
126172
  ],
125618
- options: ["extraColumns"],
126173
+ options: ["extraColumns", "meanings"],
125619
126174
  tables: {
125620
126175
  requests: {
125621
126176
  name: "signature_requests",
@@ -125625,6 +126180,7 @@ const NAMES$18 = {
125625
126180
  user: "requestedBy",
125626
126181
  export: true
125627
126182
  },
126183
+ optional: ["meaning"],
125628
126184
  columns: {
125629
126185
  id: "id",
125630
126186
  tenant: "tenant_id",
@@ -125637,6 +126193,7 @@ const NAMES$18 = {
125637
126193
  status: "status",
125638
126194
  approval: "approval_request_id",
125639
126195
  message: "message",
126196
+ meaning: "meaning",
125640
126197
  requestedBy: "requested_by",
125641
126198
  createdAt: "created_at",
125642
126199
  completedAt: "completed_at"
@@ -125668,6 +126225,23 @@ const NAMES$18 = {
125668
126225
  };
125669
126226
  /** How many people one request can ask to sign. */
125670
126227
  const MAX_SIGNERS = 20;
126228
+ /** What a signature can mean when `options.meanings` is unset. */
126229
+ const SIGNATURE_MEANINGS = [
126230
+ "authored",
126231
+ "reviewed",
126232
+ "approved",
126233
+ "released",
126234
+ "acknowledged"
126235
+ ];
126236
+ const MEANING = /^[a-z][a-z0-9_]{0,62}$/;
126237
+ /** `blocks.signatures.options.meanings`: what a signature can mean. */
126238
+ function meaningsOf(ctx) {
126239
+ const meanings = ctx.list("meanings", SIGNATURE_MEANINGS);
126240
+ if (meanings.length === 0 || meanings.some((item) => !MEANING.test(item))) throw new TypeError("blocks.signatures.options.meanings must be a non-empty list of lowercase names such as approved");
126241
+ return meanings;
126242
+ }
126243
+ /** The arguments of create_signature_request before it took a meaning. */
126244
+ const PREVIOUS_REQUEST_ARGS = "text, text, uuid[], uuid, text, uuid, text";
125671
126245
  /** The hash `versions` stores for a version's content. */
125672
126246
  const versionHash = (content, storagePath) => sha256Hex$1(`coalesce(${content}::text, '') || coalesce(${storagePath}, '')`);
125673
126247
  /**
@@ -125697,8 +126271,11 @@ function build$18(ctx) {
125697
126271
  const forbidden = (message) => fail$1("SIGNATURE_FORBIDDEN", message);
125698
126272
  const extras = ctx.extraColumns("requests", ["fields"]);
125699
126273
  const extra = extraFieldsArg(extras);
125700
- const requestJson = (row) => `jsonb_build_object('id', ${row}.${r("id")}, 'organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'versionId', ${row}.${r("version")}, 'contentHash', ${row}.${r("contentHash")}, 'signers', to_jsonb(${row}.${r("signers")}), 'order', ${row}.${r("order")}, 'status', ${row}.${r("status")}, 'approvalRequestId', ${row}.${r("approval")}, 'message', ${row}.${r("message")}, 'requestedBy', ${row}.${r("requestedBy")}, 'createdAt', ${row}.${r("createdAt")}, 'completedAt', ${row}.${r("completedAt")}${extraFieldsJson(row, extras)})`;
126274
+ const requestJson = (row) => `jsonb_build_object('id', ${row}.${r("id")}, 'organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'versionId', ${row}.${r("version")}, 'contentHash', ${row}.${r("contentHash")}, 'signers', to_jsonb(${row}.${r("signers")}), 'order', ${row}.${r("order")}, 'status', ${row}.${r("status")}, 'approvalRequestId', ${row}.${r("approval")}, 'message', ${row}.${r("message")}, 'meaning', ${meaning(row)}, 'requestedBy', ${row}.${r("requestedBy")}, 'createdAt', ${row}.${r("createdAt")}, 'completedAt', ${row}.${r("completedAt")}${extraFieldsJson(row, extras)})`;
125701
126275
  const signatureJson = (row) => `jsonb_build_object('id', ${row}.${s("id")}, 'requestId', ${row}.${s("request")}, 'signer', ${row}.${s("signer")}, 'method', ${row}.${s("method")}, 'typedName', ${row}.${s("typedName")}, 'imageAttachmentId', ${row}.${s("image")}, 'signedHash', ${row}.${s("signedHash")}, 'ip', ${row}.${s("ip")}, 'userAgent', ${row}.${s("userAgent")}, 'signedAt', ${row}.${s("signedAt")})`;
126276
+ const hasMeaning = ctx.has("requests", "meaning");
126277
+ const meanings = meaningsOf(ctx);
126278
+ const meaning = (row) => hasMeaning ? `${row}.${r("meaning")}` : "null::text";
125702
126279
  const requestRecord = (type, row, extra, audit) => ctx.record({
125703
126280
  type,
125704
126281
  payload: `jsonb_build_object('organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'id', ${row}.${r("id")}${extra})`,
@@ -125753,10 +126330,13 @@ function build$18(ctx) {
125753
126330
  ${r("status")} text not null default 'pending' check (${r("status")} in ('pending', 'completed', 'declined', 'cancelled')),
125754
126331
  ${r("approval")} uuid,
125755
126332
  ${r("message")} text check (${r("message")} is null or length(${r("message")}) <= 2000),
126333
+ ${r("meaning")} text,
125756
126334
  ${r("requestedBy")} uuid,
125757
126335
  ${r("createdAt")} timestamptz not null default now(),
125758
126336
  ${r("completedAt")} timestamptz
125759
- );${addExtraColumns(requests, extras)}
126337
+ );
126338
+ -- What signing means (blocks.signatures.options.meanings), such as approved.
126339
+ alter table ${requests} add column if not exists ${r("meaning")} text;${addExtraColumns(requests, extras)}
125760
126340
  create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_subject_idx`)} on ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")});
125761
126341
  create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_version_idx`)} on ${requests} (${r("version")});
125762
126342
  create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_signers_idx`)} on ${requests} using gin (${r("signers")});
@@ -125813,10 +126393,13 @@ ${renderPolicy(policy$1({
125813
126393
  ${tables}
125814
126394
  -- Asks members to sign one version of a record. The version is frozen, so
125815
126395
  -- retention and delete_version keep it; without one, the record's columns
125816
- -- are snapshotted first. fields: the extra columns
126396
+ -- are snapshotted first. meaning says what signing means, one of
126397
+ -- blocks.signatures.options.meanings. fields: the extra columns
125817
126398
  -- (blocks.signatures.options.extraColumns) to set.
125818
- ${extra.drop(fn("create_signature_request"), `${ctx.idType}, text, text, uuid[], uuid, text, uuid, text`)}
125819
- create or replace function ${fn("create_signature_request")}(tenant ${ctx.idType}, subject_type text, subject_id text, signers uuid[], version_id uuid default null, sign_order text default 'parallel', approval_request_id uuid default null, message text default null${extra.param})
126399
+ drop function if exists ${fn("create_signature_request")}(${ctx.idType}, ${PREVIOUS_REQUEST_ARGS});
126400
+ drop function if exists ${fn("create_signature_request")}(${ctx.idType}, ${PREVIOUS_REQUEST_ARGS}, jsonb);
126401
+ ${extra.drop(fn("create_signature_request"), `${ctx.idType}, ${PREVIOUS_REQUEST_ARGS}, text`)}
126402
+ create or replace function ${fn("create_signature_request")}(tenant ${ctx.idType}, subject_type text, subject_id text, signers uuid[], version_id uuid default null, sign_order text default 'parallel', approval_request_id uuid default null, message text default null, meaning text default null${extra.param})
125820
126403
  returns jsonb
125821
126404
  language plpgsql
125822
126405
  security definer
@@ -125835,6 +126418,9 @@ begin
125835
126418
  })})) then
125836
126419
  ${forbidden("not allowed to request signatures on this record")}
125837
126420
  end if;
126421
+ if create_signature_request.meaning is not null and create_signature_request.meaning not in (${meanings.map((item) => `'${item}'`).join(", ")}) then
126422
+ ${fail$1("SIGNATURE_REQUEST_MEANING_UNKNOWN", `meaning must be one of ${meanings.join(", ")}`, "22023")}
126423
+ end if;
125838
126424
  if create_signature_request.sign_order not in ('parallel', 'sequential') then
125839
126425
  ${fail$1("SIGNATURE_ORDER_INVALID", "sign_order must be parallel or sequential", "22023")}
125840
126426
  end if;
@@ -125872,15 +126458,15 @@ begin
125872
126458
  ["uuid", "v_version"]
125873
126459
  ])}
125874
126460
  update ${vt} x set ${v("frozen")} = true where x.${v("id")} = v_version and not x.${v("frozen")};
125875
- insert into ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")}, ${r("version")}, ${r("contentHash")}, ${r("signers")}, ${r("order")}, ${r("approval")}, ${r("message")}, ${r("requestedBy")})
125876
- values (create_signature_request.tenant, create_signature_request.subject_type, create_signature_request.subject_id, v_version, v_hash, create_signature_request.signers, create_signature_request.sign_order, create_signature_request.approval_request_id, nullif(trim(create_signature_request.message), ''), auth.uid())
126461
+ insert into ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")}, ${r("version")}, ${r("contentHash")}, ${r("signers")}, ${r("order")}, ${r("approval")}, ${r("message")}${hasMeaning ? `, ${r("meaning")}` : ""}, ${r("requestedBy")})
126462
+ values (create_signature_request.tenant, create_signature_request.subject_type, create_signature_request.subject_id, v_version, v_hash, create_signature_request.signers, create_signature_request.sign_order, create_signature_request.approval_request_id, nullif(trim(create_signature_request.message), '')${hasMeaning ? ", create_signature_request.meaning" : ""}, auth.uid())
125877
126463
  returning * into v_row;${writeExtraColumns(requests, extras, "create_signature_request.fields", `x.${r("id")} = v_row.${r("id")}`, "v_row")}
125878
126464
  ${requestRecord("signature.requested", "v_row", `, 'versionId', v_row.${r("version")}`, `'requested signatures on ' || v_row.${r("subjectType")} || ' ' || v_row.${r("subjectId")}`)}
125879
126465
  ${ctx.hook("after_signature_request", [["uuid", `v_row.${r("id")}`]])}
125880
126466
  return ${requestJson("v_row")};
125881
126467
  end;
125882
126468
  $$;
125883
- ${userGrant(`${fn("create_signature_request")}(${ctx.idType}, text, text, uuid[], uuid, text, uuid, text${extra.type})`)}
126469
+ ${userGrant(`${fn("create_signature_request")}(${ctx.idType}, text, text, uuid[], uuid, text, uuid, text, text${extra.type})`)}
125884
126470
 
125885
126471
  -- Recomputes the signed version's hash from its content and each signature's
125886
126472
  -- hash, and reports whether the record has a newer version since.
@@ -126004,7 +126590,7 @@ begin
126004
126590
  update ${requests} x set ${r("status")} = 'completed', ${r("completedAt")} = v_at
126005
126591
  where x.${r("id")} = v_req.${r("id")}
126006
126592
  returning * into v_req;
126007
- ${requestRecord("signature.completed", "v_req", `, 'versionId', v_req.${r("version")}`, false)}
126593
+ ${requestRecord("signature.completed", "v_req", `, 'versionId', v_req.${r("version")}, 'meaning', ${meaning("v_req")}`, false)}
126008
126594
  end if;
126009
126595
  ${ctx.hook("after_signature_sign", [["uuid", `v_row.${s("id")}`], ["text", `v_req.${r("status")}`]])}
126010
126596
  return ${signatureJson("v_row")} || jsonb_build_object('requestStatus', v_req.${r("status")});
@@ -126142,6 +126728,7 @@ function contract$17(ctx) {
126142
126728
  "text",
126143
126729
  "uuid",
126144
126730
  "text",
126731
+ "text",
126145
126732
  ...extraFieldsArg(ctx.extraColumns("requests", ["fields"])).contract
126146
126733
  ],
126147
126734
  returns: "jsonb"
@@ -130753,10 +131340,13 @@ const REASON = "nullif(current_setting('better_supabase.transition_reason', true
130753
131340
  * role passes for the user it acts for.
130754
131341
  */
130755
131342
  const ACTOR_ID = `coalesce(auth.uid(), nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> 'id', '')::uuid)`;
130756
- /** One field of the actor `transition()` passed, as SQL. */
131343
+ /** One field of the actor `transition()` passed, as text SQL. */
131344
+ function actorText(field) {
131345
+ return `nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> ${sqlString(field)}, '')`;
131346
+ }
131347
+ /** One field of the actor `transition()` passed, as SQL of its column type. */
130757
131348
  function actorField(field) {
130758
- const value = `nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> ${sqlString(field)}, '')`;
130759
- return field === "ip" ? `${value}::inet` : value;
131349
+ return field === "ip" ? `${actorText(field)}::inet` : actorText(field);
130760
131350
  }
130761
131351
  /** The history columns and values a transition writes. */
130762
131352
  function historyWrite(ctx, item) {
@@ -130775,7 +131365,7 @@ function historyWrite(ctx, item) {
130775
131365
  [hist.reason, REASON],
130776
131366
  ...ACTOR_FIELDS.flatMap(([key, field]) => {
130777
131367
  const column = hist[key];
130778
- return column === void 0 ? [] : [[column, asColumnType(table, column, actorField(field))]];
131368
+ return column === void 0 ? [] : [[column, asColumnType(table, column, actorText(field))]];
130779
131369
  })
130780
131370
  ];
130781
131371
  return `insert into ${table} (${columns.map(([column]) => sqlIdent(column)).join(", ")})
@@ -136758,6 +137348,10 @@ const TIME_TRACKING = {
136758
137348
  build: build$8
136759
137349
  };
136760
137350
  // src/sql/modules/timeline-reads.ts
137351
+ const NO_BRANCH = {
137352
+ sql: "",
137353
+ covers: ""
137354
+ };
136761
137355
  const DELIVERIES_SIGNATURE = (ctx) => `${ctx.fn("activity_subject_deliveries")}(${ctx.idType}, text, text, timestamptz, integer)`;
136762
137356
  /**
136763
137357
  * How the activity feed reads through the `subjects` registry and the audit
@@ -136776,6 +137370,7 @@ function activityReads(ctx) {
136776
137370
  auditSetup: "",
136777
137371
  auditBranch: "",
136778
137372
  sourceBranches: "",
137373
+ eventDedupe: "",
136779
137374
  helpers: `\ndrop function if exists ${DELIVERIES_SIGNATURE(ctx)};`,
136780
137375
  sources: ["event"]
136781
137376
  };
@@ -136790,6 +137385,8 @@ function activityReads(ctx) {
136790
137385
  const runs = runBranch(ctx, types);
136791
137386
  const transitions = transitionBranch(ctx, types);
136792
137387
  const messages = messageBranch(ctx, types);
137388
+ const type = `y.${ctx.col("activity", "type")}`;
137389
+ const covered = [...transitions.covers === "" ? [] : [`(${type} = 'status.changed' and ${transitions.covers})`], ...messages.covers === "" ? [] : [`(${type} in ('message.sent', 'comment.posted') and ${messages.covers})`]];
136793
137390
  const deliveries = deliveryHelper(ctx, types);
136794
137391
  return {
136795
137392
  readable: `-- Whether the caller can read a registered subject (can_subject).
@@ -136824,20 +137421,22 @@ ${registry.map((subject) => ` when ${sqlString(subject.type)} then ${sqlStr
136824
137421
  end;
136825
137422
  end if;` : "",
136826
137423
  auditBranch: auditOn ? auditBranch(ctx, audit) : "",
136827
- sourceBranches: `${runs}${transitions}${messages}${deliveries === void 0 ? "" : `
137424
+ sourceBranches: `${runs}${transitions.sql}${messages.sql}${deliveries === void 0 ? "" : `
136828
137425
  union all
136829
137426
  (select d.entry, d.at, d.id
136830
137427
  from ${ctx.fn("activity_subject_deliveries")}(list_activity.tenant, list_activity.subject_type, list_activity.subject_id, list_activity.before, v_limit) d
136831
137428
  where list_activity.subject_id is not null
136832
137429
  and (list_activity.sources is null or 'delivery' = any (list_activity.sources)))`}`,
137430
+ eventDedupe: covered.length === 0 ? "" : `
137431
+ and not (${covered.join("\n or ")})`,
136833
137432
  helpers: deliveries ?? `\ndrop function if exists ${DELIVERIES_SIGNATURE(ctx)};`,
136834
137433
  sources: [
136835
137434
  "event",
136836
137435
  ...auditOn ? ["audit"] : [],
136837
137436
  ...deliveries === void 0 ? [] : ["delivery"],
136838
137437
  ...runs === "" ? [] : ["run"],
136839
- ...transitions === "" ? [] : ["transition"],
136840
- ...messages === "" ? [] : ["message"]
137438
+ ...transitions.sql === "" ? [] : ["transition"],
137439
+ ...messages.sql === "" ? [] : ["message"]
136841
137440
  ]
136842
137441
  };
136843
137442
  }
@@ -136906,20 +137505,18 @@ function runBranch(ctx, types) {
136906
137505
  * skipped). As the caller, so the history's read policy applies.
136907
137506
  */
136908
137507
  function transitionBranch(ctx, types) {
136909
- if (ctx.scope.kind !== "tenant" || !ctx.installed("state-machine")) return "";
137508
+ if (ctx.scope.kind !== "tenant" || !ctx.installed("state-machine")) return NO_BRANCH;
136910
137509
  const sm = ctx.of("state-machine");
136911
- if (sm.mode === "custom") return "";
137510
+ if (sm.mode === "custom") return NO_BRANCH;
136912
137511
  const names = machines(sm).filter((item) => item.history === void 0).map((item) => item.name);
136913
- if (names.length === 0) return "";
137512
+ if (names.length === 0) return NO_BRANCH;
136914
137513
  const h = (logical) => `h.${sm.col("history", logical)}`;
136915
137514
  const data = [
136916
137515
  `'from', ${h("fromStatus")}::text`,
136917
137516
  `'to', ${h("toStatus")}::text`,
136918
137517
  `'reason', ${h("reason")}`
136919
137518
  ];
136920
- return `
136921
- union all
136922
- (select jsonb_build_object(${entry$1(ctx, {
137519
+ const values = {
136923
137520
  id: `${h("id")}::text`,
136924
137521
  tenant: h("tenant"),
136925
137522
  event: "null::text",
@@ -136930,28 +137527,35 @@ function transitionBranch(ctx, types) {
136930
137527
  summary: "null::text",
136931
137528
  data: `jsonb_strip_nulls(jsonb_build_object(${data.join(", ")}))`,
136932
137529
  occurredAt: h("createdAt")
136933
- }, "transition")}) as entry,
136934
- ${h("createdAt")} as at, ${h("id")}::text as id
136935
- from ${sm.table("history")} h
136936
- where list_activity.subject_id is not null
137530
+ };
137531
+ const covers = `list_activity.subject_id is not null
136937
137532
  and list_activity.subject_type = any (${types})
136938
137533
  and list_activity.subject_type = any (${sqlString(`{${names.join(",")}}`)}::text[])
136939
- and (list_activity.sources is null or 'transition' = any (list_activity.sources))
137534
+ and (list_activity.sources is null or 'transition' = any (list_activity.sources))`;
137535
+ return {
137536
+ sql: `
137537
+ union all
137538
+ (select jsonb_build_object(${entry$1(ctx, values, "transition")}) as entry,
137539
+ ${h("createdAt")} as at, ${h("id")}::text as id
137540
+ from ${sm.table("history")} h
137541
+ where ${covers}
136940
137542
  and ${h("tenant")} = list_activity.tenant
136941
137543
  and ${h("subjectType")} = list_activity.subject_type
136942
137544
  and ${h("subjectId")} = list_activity.subject_id
136943
137545
  and (list_activity.before is null or ${h("createdAt")} < list_activity.before)
136944
137546
  order by ${h("createdAt")} desc, ${h("id")} desc
136945
- limit v_limit)`;
137547
+ limit v_limit)`,
137548
+ covers
137549
+ };
136946
137550
  }
136947
137551
  /**
136948
137552
  * The sent messages of the subject's conversation in messaging. As the caller,
136949
137553
  * so the conversation's access decides which the caller sees.
136950
137554
  */
136951
137555
  function messageBranch(ctx, types) {
136952
- if (ctx.scope.kind !== "tenant" || !ctx.installed("messaging")) return "";
137556
+ if (ctx.scope.kind !== "tenant" || !ctx.installed("messaging")) return NO_BRANCH;
136953
137557
  const ms = ctx.of("messaging");
136954
- if (!(ms.mode !== "custom" && ms.has("conversations", "subjectType") && ms.has("conversations", "subjectId"))) return "";
137558
+ if (!(ms.mode !== "custom" && ms.has("conversations", "subjectType") && ms.has("conversations", "subjectId"))) return NO_BRANCH;
136955
137559
  const m = (logical) => `m.${ms.col("messages", logical)}`;
136956
137560
  const c = (logical) => `c.${ms.col("conversations", logical)}`;
136957
137561
  const data = [
@@ -136960,26 +137564,29 @@ function messageBranch(ctx, types) {
136960
137564
  `'threadId', ${m("thread")}`,
136961
137565
  `'kind', ${m("kind")}::text`
136962
137566
  ];
136963
- return `
136964
- union all
136965
- (select jsonb_build_object(${entry$1(ctx, {
137567
+ const values = {
136966
137568
  id: `${m("id")}::text`,
136967
137569
  tenant: m("tenant"),
136968
137570
  event: "null::text",
136969
- type: "'message.sent'",
137571
+ type: `case when ${c("kind")} = 'subject' then 'comment.posted' else 'message.sent' end`,
136970
137572
  actor: m("author"),
136971
137573
  subjectType: "list_activity.subject_type",
136972
137574
  subjectId: "list_activity.subject_id",
136973
137575
  summary: `left(${m("body")}, 280)`,
136974
137576
  data: `jsonb_strip_nulls(jsonb_build_object(${data.join(", ")}))`,
136975
137577
  occurredAt: m("sentAt")
136976
- }, "message")}) as entry,
137578
+ };
137579
+ const covers = `list_activity.subject_id is not null
137580
+ and list_activity.subject_type = any (${types})
137581
+ and (list_activity.sources is null or 'message' = any (list_activity.sources))`;
137582
+ return {
137583
+ sql: `
137584
+ union all
137585
+ (select jsonb_build_object(${entry$1(ctx, values, "message")}) as entry,
136977
137586
  ${m("sentAt")} as at, ${m("id")}::text as id
136978
137587
  from ${ms.table("messages")} m
136979
137588
  join ${ms.table("conversations")} c on ${c("id")} = ${m("conversation")}
136980
- where list_activity.subject_id is not null
136981
- and list_activity.subject_type = any (${types})
136982
- and (list_activity.sources is null or 'message' = any (list_activity.sources))
137589
+ where ${covers}
136983
137590
  and ${c("tenant")} = list_activity.tenant
136984
137591
  and ${c("subjectType")} = list_activity.subject_type
136985
137592
  and ${c("subjectId")} = list_activity.subject_id
@@ -136987,7 +137594,9 @@ function messageBranch(ctx, types) {
136987
137594
  and ${m("deletedAt")} is null
136988
137595
  and (list_activity.before is null or ${m("sentAt")} < list_activity.before)
136989
137596
  order by ${m("sentAt")} desc, ${m("id")} desc
136990
- limit v_limit)`;
137597
+ limit v_limit)`,
137598
+ covers
137599
+ };
136991
137600
  }
136992
137601
  /**
136993
137602
  * Activity_subject_deliveries: the deliveries of the notifications about a
@@ -137274,7 +137883,7 @@ begin${reads.gate}${reads.auditSetup}
137274
137883
  and (list_activity.sources is null or 'event' = any (list_activity.sources))
137275
137884
  and (list_activity.subject_type is null or y.${a("subjectType")} = list_activity.subject_type)
137276
137885
  and (list_activity.subject_id is null or y.${a("subjectId")} = list_activity.subject_id)
137277
- and (list_activity.before is null or y.${a("occurredAt")} < list_activity.before)
137886
+ and (list_activity.before is null or y.${a("occurredAt")} < list_activity.before)${reads.eventDedupe}
137278
137887
  order by y.${a("occurredAt")} desc, y.${a("id")} desc
137279
137888
  limit v_limit)${reads.auditBranch}${reads.sourceBranches}
137280
137889
  ) u
@@ -147466,7 +148075,7 @@ const SQL_MODULES = Object.fromEntries([
147466
148075
  built(DISPATCH),
147467
148076
  built(SHIPMENTS),
147468
148077
  built(CONTRACTS),
147469
- built(CONTROLS),
148078
+ built(COMPLIANCE),
147470
148079
  built(INCIDENTS),
147471
148080
  built(COURSES),
147472
148081
  built(MESSAGING),
@@ -147919,6 +148528,14 @@ function columnAccessRefusals(table) {
147919
148528
  return [...hidden.map((column) => `select extensions.throws_ok($$select ${sqlIdent(column)} from ${target}$$, '42501', null, ${sqlString(`a signed-in user cannot read ${SCHEMA$4}.${table.name}.${column}`)});`), ...restricted.map((column) => `select extensions.throws_ok($$update ${target} set ${sqlIdent(column)} = null where false$$, '42501', null, ${sqlString(`a signed-in user cannot write ${SCHEMA$4}.${table.name}.${column}`)});`)];
147920
148529
  }
147921
148530
  // src/sql/modules/app-table-checks.ts
148531
+ /** A value of each checked text format that passes its check. */
148532
+ const TEXT_SAMPLES = {
148533
+ email: "'test@example.com'",
148534
+ url: "'https://example.com'",
148535
+ phone_e164: "'+31201234567'",
148536
+ bsn: "'111222333'",
148537
+ iban: "'NL91ABNA0417164300'"
148538
+ };
147922
148539
  /**
147923
148540
  * The conditions of a column's check on the `ident` expression: its format,
147924
148541
  * options and bounds.
@@ -147926,7 +148543,7 @@ function columnAccessRefusals(table) {
147926
148543
  function constraintChecks(column, ident) {
147927
148544
  const conditions = [];
147928
148545
  const format = column.format === void 0 || column.domain !== void 0 ? void 0 : FIELD_FORMATS[column.format];
147929
- if (format?.pattern !== void 0) conditions.push(`${ident} ~* ${sqlString(format.pattern)}`);
148546
+ if (format !== void 0 && column.format !== void 0) conditions.push(...formatConditions(column.format, ident, "public"));
147930
148547
  if (column.options !== void 0) {
147931
148548
  const list = column.options.map((option) => sqlString(option)).join(", ");
147932
148549
  conditions.push(column.type === "text[]" ? `${ident} <@ array[${list}]::text[]` : `${ident} in (${list})`);
@@ -147952,10 +148569,11 @@ function sampleValue(column) {
147952
148569
  const format = column.format === void 0 ? void 0 : FIELD_FORMATS[column.format];
147953
148570
  const low = column.min ?? format?.bounds?.[0];
147954
148571
  switch (column.type) {
147955
- case "text":
147956
- if (column.format === "email") return "'test@example.com'";
147957
- if (column.format === "url") return "'https://example.com'";
148572
+ case "text": {
148573
+ const sample = column.format === void 0 ? void 0 : TEXT_SAMPLES[column.format];
148574
+ if (sample !== void 0) return sample;
147958
148575
  return `repeat('x', ${String(Math.max(low ?? 1, 1))})`;
148576
+ }
147959
148577
  case "integer":
147960
148578
  case "bigint":
147961
148579
  case "numeric": return String(low ?? 0);
@@ -147985,7 +148603,7 @@ const scopePolicyName = (table, command) => `${table.enrich ? "bsb_" : ""}${tabl
147985
148603
  function grantsPrelude(target, enriched) {
147986
148604
  return enriched ? `-- ${target} keeps the app's own grants; these add what the scope needs.` : revokeTable(target);
147987
148605
  }
147988
- const qualified$4 = (table) => `${sqlIdent(SCHEMA$3)}.${sqlIdent(table)}`;
148606
+ const qualified$5 = (table) => `${sqlIdent(SCHEMA$3)}.${sqlIdent(table)}`;
147989
148607
  /**
147990
148608
  * Each implicit column the app's table lacks, added with `add column if not
147991
148609
  * exists`, nullable unless it has a default. The id is unique instead of the
@@ -147994,7 +148612,7 @@ const qualified$4 = (table) => `${sqlIdent(SCHEMA$3)}.${sqlIdent(table)}`;
147994
148612
  * complete.
147995
148613
  */
147996
148614
  function enrichSql(table) {
147997
- const target = qualified$4(table.name);
148615
+ const target = qualified$5(table.name);
147998
148616
  const columns = [
147999
148617
  ...table.existing.has("id") ? [] : [table.config.id === "bigint" ? "id bigint generated by default as identity unique" : "id uuid not null default gen_random_uuid() unique"],
148000
148618
  ...table.scope && !table.existing.has(table.scope.name) ? [`${sqlIdent(table.scope.name)} ${table.scope.addable}`] : [],
@@ -148016,10 +148634,10 @@ function enrichSql(table) {
148016
148634
  function enrichChecks(table, policies) {
148017
148635
  const name = sqlString(table.name);
148018
148636
  const label = `${SCHEMA$3}.${table.name}`;
148019
- const regclass = `${sqlString(qualified$4(table.name))}::regclass`;
148637
+ const regclass = `${sqlString(qualified$5(table.name))}::regclass`;
148020
148638
  const checks = [`select extensions.ok(array[${policies.map((policy) => sqlString(policy)).join(", ")}]::name[] <@ array(select p.policyname from pg_catalog.pg_policies p where p.schemaname = '${SCHEMA$3}' and p.tablename = ${name}), ${sqlString(`${label} has the policies for its scope`)});`];
148021
148639
  if (table.scope) {
148022
- const constraint = notNullCheckName(qualified$4(table.name), sqlIdent(table.scope.name));
148640
+ const constraint = notNullCheckName(qualified$5(table.name), sqlIdent(table.scope.name));
148023
148641
  checks.push(`select extensions.has_column('${SCHEMA$3}', ${name}, ${sqlString(table.scope.name)}, ${sqlString(`${label} has the scope column ${table.scope.name}`)});`, `select extensions.ok(exists (select 1 from pg_catalog.pg_constraint k where k.conrelid = ${regclass} and k.conname = ${sqlString(constraint)} and k.contype = 'c'), ${sqlString(`new rows of ${label} must fill ${table.scope.name}`)});`);
148024
148642
  }
148025
148643
  return checks;
@@ -148048,9 +148666,19 @@ function privilegeChecks(table) {
148048
148666
  const SCHEMA$2 = "public";
148049
148667
  /** The most ids one `<table>_reveal` call decrypts. */
148050
148668
  const APP_REVEAL_LIMIT = 500;
148051
- const qualified$3 = (table) => `${sqlIdent(SCHEMA$2)}.${sqlIdent(table)}`;
148669
+ const qualified$4 = (table) => `${sqlIdent(SCHEMA$2)}.${sqlIdent(table)}`;
148052
148670
  /** The reveal function of `table`, quoted. */
148053
- const revealFunction = (table) => qualified$3(`${table}_reveal`);
148671
+ const revealFunction = (table) => qualified$4(`${table}_reveal`);
148672
+ /** The find function of `table`, quoted. */
148673
+ const findFunction = (table) => qualified$4(`${table}_find`);
148674
+ /** The encrypted columns of `config` that keep a lookup hash. */
148675
+ function lookupColumns(config) {
148676
+ return encryptedColumns(config).filter((name) => config.columns?.[name]?.lookup === true);
148677
+ }
148678
+ /** The plaintext `value` as the column type prints it, as the trigger hashes it. */
148679
+ function normalized(column, value) {
148680
+ return column.type === "text" ? value : `((${value})::${column.type})::text`;
148681
+ }
148054
148682
  /** The SQL type of the table's id. */
148055
148683
  const idType = (config) => config.id === "bigint" ? "bigint" : "uuid";
148056
148684
  /** The SQL that names the data key a row of `table` is encrypted with. */
@@ -148088,27 +148716,48 @@ function sealSql(table, checks) {
148088
148716
  const open = encryption.fn("field_open");
148089
148717
  const fn = ctx.fn(`${table.name}_seal`);
148090
148718
  const trigger = ctx.trigger("seal_fields");
148091
- const target = qualified$3(table.name);
148719
+ const target = qualified$4(table.name);
148092
148720
  const prefix = sqlString(FIELD_CIPHER_PREFIX);
148093
148721
  const width = String(5);
148722
+ const lookupKey = encryption.fn("field_lookup_key");
148723
+ const hash = encryption.fn("field_hash");
148724
+ const lookups = new Set(lookupColumns(table.config));
148094
148725
  const branch = (name) => {
148095
148726
  const column = table.config.columns?.[name] ?? { type: "text" };
148096
148727
  const value = `new.${sqlIdent(name)}`;
148097
148728
  const conditions = plainChecks(column, checks, value);
148729
+ const lookup = lookups.has(name) ? sqlIdent(lookupColumn(name)) : void 0;
148098
148730
  const normalize = column.type === "text" ? "" : `\n ${value} := ((${value})::${column.type})::text;`;
148099
148731
  const check = conditions.length === 0 ? "" : `\n if not (${conditions.join(" and ")}) then
148100
148732
  raise exception 'new row for relation "%" violates check constraint "%"', ${sqlString(table.name)}, ${sqlString(`${table.name}_${name}_check`)}
148101
148733
  using errcode = '23514';
148102
148734
  end if;`;
148103
- return ` if ${value} is not null and (${`case when tg_op = 'INSERT' then true else ${value} is distinct from old.${sqlIdent(name)} end`} or left(${value}, ${width}) <> ${prefix}) then${normalize}${check}
148735
+ const fresh = `case when tg_op = 'INSERT' then true else ${value} is distinct from old.${sqlIdent(name)} end`;
148736
+ const hashed = (plain) => `\n v_lookup_key := coalesce(v_lookup_key, ${lookupKey}(v_owner, true));\n new.${lookup ?? ""} := ${hash}(v_lookup_key, ${plain});`;
148737
+ if (lookup === void 0) return ` if ${value} is not null and (${fresh} or left(${value}, ${width}) <> ${prefix}) then${normalize}${check}
148104
148738
  v_key := coalesce(v_key, ${key}(v_owner, true));
148105
148739
  ${value} := ${seal}(v_key, ${value});
148106
148740
  elsif ${value} is not null and v_moved then
148107
148741
  v_key := coalesce(v_key, ${key}(v_owner, true));
148108
148742
  ${value} := ${seal}(v_key, ${open}(${key}(v_old_owner, false), ${value}));
148743
+ end if;`;
148744
+ return ` if ${value} is not null and (${fresh} or left(${value}, ${width}) <> ${prefix}) then${normalize}${check}${hashed(value)}
148745
+ v_key := coalesce(v_key, ${key}(v_owner, true));
148746
+ ${value} := ${seal}(v_key, ${value});
148747
+ elsif ${value} is not null and v_moved then
148748
+ v_plain := ${open}(${key}(v_old_owner, false), ${value});${hashed("v_plain")}
148749
+ v_key := coalesce(v_key, ${key}(v_owner, true));
148750
+ ${value} := ${seal}(v_key, v_plain);
148751
+ elsif ${value} is null then
148752
+ new.${lookup} := null;
148753
+ elsif new.${lookup} is null or (tg_op = 'UPDATE' and new.${lookup} is distinct from old.${lookup}) then${hashed(`${open}(${key}(v_owner, false), ${value})`)}
148109
148754
  end if;`;
148110
148755
  };
148111
- const watched = [...table.scope ? [table.scope.name] : [], ...columns].map((column) => sqlIdent(column));
148756
+ const watched = [
148757
+ ...table.scope ? [table.scope.name] : [],
148758
+ ...columns,
148759
+ ...[...lookups].map((name) => lookupColumn(name))
148760
+ ].map((column) => sqlIdent(column));
148112
148761
  return `-- Encrypts ${columns.join(", ")} with the row's data key before the row is written.
148113
148762
  create or replace function ${fn}()
148114
148763
  returns trigger
@@ -148120,7 +148769,7 @@ declare
148120
148769
  v_owner text := ${ownerOf(table, "new")};
148121
148770
  v_old_owner text;
148122
148771
  v_moved boolean := false;
148123
- v_key text;
148772
+ v_key text;${lookups.size === 0 ? "" : "\n v_lookup_key text;\n v_plain text;"}
148124
148773
  begin
148125
148774
  if tg_op = 'UPDATE' then
148126
148775
  v_old_owner := ${ownerOf(table, "old")};
@@ -148152,7 +148801,7 @@ function revealSql(table) {
148152
148801
  const fn = ctx.fn(`${table.name}_reveal`);
148153
148802
  const wrapper = revealFunction(table.name);
148154
148803
  const id = idType(table.config);
148155
- const target = qualified$3(table.name);
148804
+ const target = qualified$4(table.name);
148156
148805
  const ids = `${ctx.fnName(`${table.name}_reveal`)}.ids`;
148157
148806
  const filter = `t.id = any (${ids}) and (v_service or (${[table.own, ...table.sessionPolicy ? ["(select better_supabase.session_active())"] : []].join(" and ")}))`;
148158
148807
  const outputs = columns.map((name) => {
@@ -148209,6 +148858,86 @@ $$;
148209
148858
  revoke execute on function ${wrapper}(${id}[]) from public, anon;
148210
148859
  grant execute on function ${wrapper}(${id}[]) to authenticated, service_role;`;
148211
148860
  }
148861
+ /**
148862
+ * `public.<table>_find(lookup_column, value)`: the ids of the rows the caller
148863
+ * reaches whose lookup column holds the hash of `value`. It hashes `value` once
148864
+ * per owner the caller can reach: the tenants they are a member of, or
148865
+ * themselves, and for the service role every owner in the table. Like
148866
+ * `<table>_reveal`, a `security invoker` wrapper in `public` calls the definer
148867
+ * function in `better_supabase`.
148868
+ */
148869
+ function findSql(table) {
148870
+ const columns = lookupColumns(table.config);
148871
+ if (columns.length === 0) return "";
148872
+ const { ctx } = table;
148873
+ const encryption = ctx.of("field-encryption");
148874
+ const fn = ctx.fn(`${table.name}_find`);
148875
+ const name = ctx.fnName(`${table.name}_find`);
148876
+ const wrapper = findFunction(table.name);
148877
+ const id = idType(table.config);
148878
+ const target = qualified$4(table.name);
148879
+ const scope = table.scope;
148880
+ const reach = [table.own, ...table.sessionPolicy ? ["(select better_supabase.session_active())"] : []].join(" and ");
148881
+ const kind = ctx.scope.kind === "user" ? "user" : "tenant";
148882
+ const owners = scope === void 0 ? `select ${fieldKeyOwner("none", "")} as bsb_owner` : `select distinct ${fieldKeyOwner(kind, "o.id")} as bsb_owner
148883
+ from (
148884
+ select t.${sqlIdent(scope.name)} as id from ${target} t where v_service
148885
+ union all
148886
+ select m.id from ${ctx.scope.members()} as m(id) where not v_service
148887
+ ) o
148888
+ where o.id is not null`;
148889
+ const branches = columns.map((column, index) => {
148890
+ const config = table.config.columns?.[column] ?? { type: "text" };
148891
+ return ` ${index === 0 ? "if" : "elsif"} ${name}.lookup_column = ${sqlString(column)} then
148892
+ return query
148893
+ with k as materialized (
148894
+ select w.bsb_owner, ${encryption.fn("field_hash")}(${encryption.fn("field_lookup_key")}(w.bsb_owner, false), ${normalized(config, `${name}.value`)}) as bsb_hash
148895
+ from (${owners}) w
148896
+ )
148897
+ select t.id
148898
+ from ${target} t
148899
+ join k on k.bsb_hash = t.${sqlIdent(lookupColumn(column))} and k.bsb_owner = ${ownerOf(table, "t")}
148900
+ where v_service or (${reach});`;
148901
+ });
148902
+ return `-- Finds the rows whose ${columns.join(", ")} equal a value, by their lookup hash, as the table's policies allow.
148903
+ create or replace function ${fn}(lookup_column text, value text)
148904
+ returns table (id ${id})
148905
+ language plpgsql
148906
+ stable
148907
+ security definer
148908
+ set search_path = ''
148909
+ as $$
148910
+ #variable_conflict use_column
148911
+ declare
148912
+ v_service boolean := ${SERVICE_CALLER$1};
148913
+ begin
148914
+ if (select auth.uid()) is null and not v_service then
148915
+ ${fail$1("APP_FIND_FORBIDDEN", `only signed-in users and the service role find ${table.name}`)}
148916
+ end if;
148917
+ if ${name}.value is null then
148918
+ return;
148919
+ end if;
148920
+ ${branches.join("\n")}
148921
+ else
148922
+ ${fail$1("APP_FIND_COLUMN", `${table.name} keeps a lookup for ${columns.join(", ")} only`, "22023")}
148923
+ end if;
148924
+ end;
148925
+ $$;
148926
+ revoke execute on function ${fn}(text, text) from public, anon;
148927
+ grant execute on function ${fn}(text, text) to authenticated, service_role;
148928
+ -- The API entry point for ${fn}; the definer function stays out of the exposed schemas.
148929
+ create or replace function ${wrapper}(lookup_column text, value text)
148930
+ returns table (id ${id})
148931
+ language sql
148932
+ stable
148933
+ security invoker
148934
+ set search_path = ''
148935
+ as $$
148936
+ select * from ${fn}(lookup_column, value);
148937
+ $$;
148938
+ revoke execute on function ${wrapper}(text, text) from public, anon;
148939
+ grant execute on function ${wrapper}(text, text) to authenticated, service_role;`;
148940
+ }
148212
148941
  /** The audit entries of one reveal call: one per tenant, naming its rows. */
148213
148942
  function auditSql(table, columns, filter) {
148214
148943
  if (table.config.auditReads !== true) return "";
@@ -148230,7 +148959,7 @@ function auditSql(table, columns, filter) {
148230
148959
  return `
148231
148960
  for v_read in
148232
148961
  select ${tenant} as tenant, jsonb_agg(t.id order by t.id) as ids
148233
- from ${qualified$3(table.name)} t
148962
+ from ${qualified$4(table.name)} t
148234
148963
  where ${filter}
148235
148964
  group by 1
148236
148965
  loop
@@ -148285,10 +149014,10 @@ function sealChecks(table, seeded, sample) {
148285
149014
  return {
148286
149015
  static: statics,
148287
149016
  seeded: [
148288
- `update ${qualified$3(table.name)} set ${columns.map((column) => `${sqlIdent(column)} = (${plain(column)})::text`).join(", ")};`,
148289
- `select set_config(${sqlString(REVEAL_IDS)}, (select array_agg(id)::text from ${qualified$3(table.name)}), true);`,
149017
+ `update ${qualified$4(table.name)} set ${columns.map((column) => `${sqlIdent(column)} = (${plain(column)})::text`).join(", ")};`,
149018
+ `select set_config(${sqlString(REVEAL_IDS)}, (select array_agg(id)::text from ${qualified$4(table.name)}), true);`,
148290
149019
  `select set_config('request.jwt.claims', json_build_object('role', 'service_role')::text, true);`,
148291
- ...columns.flatMap((column) => [`select extensions.ok((select bool_and(left(${sqlIdent(column)}, ${String(5)}) = ${sqlString(FIELD_CIPHER_PREFIX)} and ${sqlIdent(column)} <> (${plain(column)})::text) from ${qualified$3(table.name)}), ${sqlString(`${label}.${column} is ciphertext at rest`)});`, `select extensions.is((select r.${sqlIdent(column)}::text from ${reveal} r limit 1), (${plain(column)})::text, ${sqlString(`the service role reveals ${label}.${column}`)});`])
149020
+ ...columns.flatMap((column) => [`select extensions.ok((select bool_and(left(${sqlIdent(column)}, ${String(5)}) = ${sqlString(FIELD_CIPHER_PREFIX)} and ${sqlIdent(column)} <> (${plain(column)})::text) from ${qualified$4(table.name)}), ${sqlString(`${label}.${column} is ciphertext at rest`)});`, `select extensions.is((select r.${sqlIdent(column)}::text from ${reveal} r limit 1), (${plain(column)})::text, ${sqlString(`the service role reveals ${label}.${column}`)});`])
148292
149021
  ],
148293
149022
  behaviour: [`select extensions.is((select count(*)::integer from ${reveal}), 0, ${sqlString(`a signed-in user does not reveal a row of ${label} outside their scope`)});`]
148294
149023
  };
@@ -148357,6 +149086,49 @@ end;
148357
149086
  $$;
148358
149087
  ${userGrant(`${fn}(${idType}, text, text, jsonb)`)}`;
148359
149088
  }
149089
+ // src/sql/modules/app-table-tenant-keys.ts
149090
+ const qualified$3 = (table) => `${sqlIdent("public")}.${sqlIdent(table)}`;
149091
+ /**
149092
+ * The references of a tenant-scoped table to another tenant-scoped app table
149093
+ * (itself included), which `tenantKeysSql` checks per tenant.
149094
+ */
149095
+ function tenantReferencesOf(table, tenantScoped) {
149096
+ const references = /* @__PURE__ */ new Map();
149097
+ if (table.ctx.scope.kind !== "tenant" || !table.scope) return references;
149098
+ for (const [column, config] of Object.entries(table.config.columns ?? {})) {
149099
+ const reference = config.references;
149100
+ if (reference !== void 0 && !("block" in reference) && tenantScoped.has(reference.table)) references.set(column, {
149101
+ column,
149102
+ target: reference.table,
149103
+ tenant: table.scope.name,
149104
+ onDelete: reference.onDelete
149105
+ });
149106
+ }
149107
+ return references;
149108
+ }
149109
+ /**
149110
+ * The unique `(tenant, id)` index on every target of a tenant reference, then
149111
+ * each reference as a foreign key on `(tenant, column)`. The key is dropped and
149112
+ * added again so a re-run replaces the single-column key an earlier version
149113
+ * wrote under the same name. `set null` names the column (Postgres 15), so the
149114
+ * tenant column keeps its value.
149115
+ */
149116
+ function tenantKeysSql(tables) {
149117
+ const references = tables.flatMap((table) => [...table.tenantReferences.values()].map((reference) => ({
149118
+ table: table.name,
149119
+ reference
149120
+ })));
149121
+ const indexes = [...new Map(references.map(({ reference }) => [reference.target, reference.tenant]))].map(([target, tenant]) => `create unique index if not exists ${sqlIdent(`${target}_${tenant}_id_key`)} on ${qualified$3(target)} (${sqlIdent(tenant)}, id);`);
149122
+ const keys = references.map(({ table, reference }) => {
149123
+ const name = sqlIdent(`${table}_${reference.column}_fkey`);
149124
+ const tenant = sqlIdent(reference.tenant);
149125
+ const column = sqlIdent(reference.column);
149126
+ const onDelete = reference.onDelete === void 0 ? "" : reference.onDelete === "set null" ? ` on delete set null (${column})` : ` on delete ${reference.onDelete}`;
149127
+ return `alter table ${qualified$3(table)} drop constraint if exists ${name};
149128
+ alter table ${qualified$3(table)} add constraint ${name} foreign key (${tenant}, ${column}) references ${qualified$3(reference.target)} (${tenant}, id)${onDelete};`;
149129
+ });
149130
+ return [...indexes, ...keys].join("\n");
149131
+ }
148360
149132
  // src/sql/modules/app-views.ts
148361
149133
  const SCHEMA$1 = "public";
148362
149134
  const qualified$2 = (table) => `${sqlIdent(SCHEMA$1)}.${sqlIdent(table)}`;
@@ -148520,47 +149292,6 @@ function columnSql(table, name, column) {
148520
149292
  column.references === void 0 || table.tenantReferences.has(name) ? "" : referenceSql(`tables.${table.name}.columns.${name}`, column.references, table.ctx)
148521
149293
  ].join("");
148522
149294
  }
148523
- /**
148524
- * The references of a tenant-scoped table to another tenant-scoped app table
148525
- * (itself included), which `tenantKeysSql` checks per tenant.
148526
- */
148527
- function tenantReferencesOf(table, tenantScoped) {
148528
- const references = /* @__PURE__ */ new Map();
148529
- if (table.ctx.scope.kind !== "tenant" || !table.scope) return references;
148530
- for (const [column, config] of Object.entries(table.config.columns ?? {})) {
148531
- const reference = config.references;
148532
- if (reference !== void 0 && !("block" in reference) && tenantScoped.has(reference.table)) references.set(column, {
148533
- column,
148534
- target: reference.table,
148535
- tenant: table.scope.name,
148536
- onDelete: reference.onDelete
148537
- });
148538
- }
148539
- return references;
148540
- }
148541
- /**
148542
- * The unique `(tenant, id)` index on every target of a tenant reference, then
148543
- * each reference as a foreign key on `(tenant, column)`. The key is dropped and
148544
- * added again so a re-run replaces the single-column key an earlier version
148545
- * wrote under the same name. `set null` names the column (Postgres 15), so the
148546
- * tenant column keeps its value.
148547
- */
148548
- function tenantKeysSql(tables) {
148549
- const references = tables.flatMap((table) => [...table.tenantReferences.values()].map((reference) => ({
148550
- table: table.name,
148551
- reference
148552
- })));
148553
- const indexes = [...new Map(references.map(({ reference }) => [reference.target, reference.tenant]))].map(([target, tenant]) => `create unique index if not exists ${sqlIdent(`${target}_${tenant}_id_key`)} on ${qualified$1(target)} (${sqlIdent(tenant)}, id);`);
148554
- const keys = references.map(({ table, reference }) => {
148555
- const name = sqlIdent(`${table}_${reference.column}_fkey`);
148556
- const tenant = sqlIdent(reference.tenant);
148557
- const column = sqlIdent(reference.column);
148558
- const onDelete = reference.onDelete === void 0 ? "" : reference.onDelete === "set null" ? ` on delete set null (${column})` : ` on delete ${reference.onDelete}`;
148559
- return `alter table ${qualified$1(table)} drop constraint if exists ${name};
148560
- alter table ${qualified$1(table)} add constraint ${name} foreign key (${tenant}, ${column}) references ${qualified$1(reference.target)} (${tenant}, id)${onDelete};`;
148561
- });
148562
- return [...indexes, ...keys].join("\n");
148563
- }
148564
149295
  function createSql(table) {
148565
149296
  if (table.enrich) return enrichSql(table.enrich);
148566
149297
  const timestamps = table.config.timestamps !== false;
@@ -148579,7 +149310,11 @@ function subjectColumnsSql(table) {
148579
149310
  return [...subject?.rank === void 0 ? [] : [`${sqlIdent(APP_RANK_COLUMN)} text collate "C" not null default 'V'`], ...subject?.softDelete === true ? [`${sqlIdent(APP_DELETED_AT_COLUMN)} timestamptz`] : []];
148580
149311
  }
148581
149312
  function columnsSql(table) {
148582
- return [...Object.entries(table.config.columns ?? {}).filter(([name]) => !table.enrich?.existing.has(name)).map(([name, column]) => columnSql(table, name, column)), ...subjectColumnsSql(table)].map((column) => `alter table ${qualified$1(table.name)} add column if not exists ${column};`).join("\n");
149313
+ return [
149314
+ ...Object.entries(table.config.columns ?? {}).filter(([name]) => !table.enrich?.existing.has(name)).map(([name, column]) => columnSql(table, name, column)),
149315
+ ...subjectColumnsSql(table),
149316
+ ...lookupColumns(table.config).map((name) => `${sqlIdent(lookupColumn(name))} bytea`)
149317
+ ].map((column) => `alter table ${qualified$1(table.name)} add column if not exists ${column};`).join("\n");
148583
149318
  }
148584
149319
  /** The rank key's index, within its group when the subject sets one. */
148585
149320
  function rankIndex(table) {
@@ -148591,7 +149326,8 @@ function indexesSql(table) {
148591
149326
  return [
148592
149327
  ...[...table.scope ? [table.scope.name] : [], ...Object.entries(table.config.columns ?? {}).filter(([, column]) => column.references !== void 0 && column.unique !== true).map(([name]) => name)].map((column) => [column]),
148593
149328
  ...rankIndex(table),
148594
- ...table.config.indexes ?? []
149329
+ ...table.config.indexes ?? [],
149330
+ ...lookupColumns(table.config).map((name) => [lookupColumn(name)])
148595
149331
  ].map((columns) => `create index if not exists ${sqlIdent(`${table.name}_${columns.join("_")}_idx`)} on ${qualified$1(table.name)} (${columns.map((column) => sqlIdent(column)).join(", ")});`).join("\n");
148596
149332
  }
148597
149333
  /** Every column of the table, implicit ones first. */
@@ -148864,7 +149600,8 @@ function tableSql(table) {
148864
149600
  triggerSql(table),
148865
149601
  eventsSql(table),
148866
149602
  sealSql(sealTable(table), constraintChecks),
148867
- revealSql(sealTable(table))
149603
+ revealSql(sealTable(table)),
149604
+ findSql(sealTable(table))
148868
149605
  ].filter((part) => part !== "").join("\n");
148869
149606
  }
148870
149607
  /**
@@ -149040,6 +149777,7 @@ function appTablesFiles(layout, installed) {
149040
149777
  ...managed
149041
149778
  ].join("\n");
149042
149779
  const body = [
149780
+ formatValidatorSql(SCHEMA, validatorsOf(tables.flatMap((table) => Object.values(table.config.columns ?? {}).map((column) => column.format)))),
149043
149781
  tables.map((table) => createSql(table)).join("\n\n"),
149044
149782
  tables.map((table) => columnsSql(table)).filter((part) => part !== "").join("\n\n"),
149045
149783
  ...tables.map((table) => tableSql(table)),
@@ -149297,7 +150035,7 @@ function withoutBlockPolicies(sql, skip, restrictive = false) {
149297
150035
  });
149298
150036
  return statements.map(({ masked: statement }, index) => {
149299
150037
  const edit = POLICY_EDIT.exec(statement);
149300
- return edit !== null && skipped.has(`${qualified$8(edit[2])}\u0000${unquote$5(edit[1])}`) ? "" : kept[index];
150038
+ return edit !== null && skipped.has(`${qualified$9(edit[2])}\u0000${unquote$5(edit[1])}`) ? "" : kept[index];
149301
150039
  }).join("");
149302
150040
  }
149303
150041
  /**
@@ -149355,7 +150093,7 @@ function declaredPolicies(sources, schemas) {
149355
150093
  continue;
149356
150094
  }
149357
150095
  const drop = DROP_POLICY.exec(statement);
149358
- if (drop !== null) found.get(qualified$8(drop[2]))?.delete(unquote$5(drop[1]));
150096
+ if (drop !== null) found.get(qualified$9(drop[2]))?.delete(unquote$5(drop[1]));
149359
150097
  }
149360
150098
  }
149361
150099
  return Object.fromEntries([...found].map(([table, named]) => [table, [...named.values()]]));
@@ -149944,6 +150682,10 @@ function moduleLayout(config, testsDir = config.sql.testsDir, readSets = [], ent
149944
150682
  ...entitlementsProvider ? { entitlementsProvider } : {},
149945
150683
  ...accessProvider ? { accessProvider } : {},
149946
150684
  ...permissionCatalog ? { permissionCatalog } : {},
150685
+ ...config.authorization?.versions ? { authzVersionsProvider: {
150686
+ name: config.authorization.name,
150687
+ function: config.authorization.versions.function
150688
+ } } : {},
149947
150689
  ...config.authorization?.delegation?.scopes ? { delegationScopes: config.authorization.delegation.scopes } : {},
149948
150690
  dir: config.sql.dir,
149949
150691
  prefix: config.sql.prefix,
@@ -150173,7 +150915,7 @@ function computedWrites(sql) {
150173
150915
  const text = withoutComments(sql);
150174
150916
  const found = /* @__PURE__ */ new Map();
150175
150917
  for (const match of text.matchAll(INSERT)) {
150176
- const table = qualified$8(match[1]);
150918
+ const table = qualified$9(match[1]);
150177
150919
  const open = match.index + match[0].length - 1;
150178
150920
  const close = closingParen(text, open);
150179
150921
  if (close === -1) continue;
@@ -150192,7 +150934,7 @@ function computedWrites(sql) {
150192
150934
  }
150193
150935
  }
150194
150936
  for (const match of text.matchAll(UPDATE)) {
150195
- const table = qualified$8(match[1]);
150937
+ const table = qualified$9(match[1]);
150196
150938
  const start = match.index + match[0].length;
150197
150939
  assignments(found, table, text.slice(start, partEnd(text, start, SET_END)));
150198
150940
  }
@@ -150343,8 +151085,8 @@ function enumColumnProblems(modules, files, schemas, ownTables, context) {
150343
151085
  return table.textColumns.flatMap((logical) => {
150344
151086
  const column = table.columns[logical];
150345
151087
  const type = column === void 0 ? void 0 : declared.get(column);
150346
- if (column === void 0 || type === void 0 || type.endsWith("]") || !enums.has(qualified$8(type))) return [];
150347
- return [enumColumnProblem(table, logical, column, qualified$8(type))];
151088
+ if (column === void 0 || type === void 0 || type.endsWith("]") || !enums.has(qualified$9(type))) return [];
151089
+ return [enumColumnProblem(table, logical, column, qualified$9(type))];
150348
151090
  });
150349
151091
  });
150350
151092
  }
@@ -150390,7 +151132,7 @@ function constraintOf(table, text) {
150390
151132
  return {
150391
151133
  table,
150392
151134
  columns: names(match[1]),
150393
- references: qualified$8(match[2]),
151135
+ references: qualified$9(match[2]),
150394
151136
  referencedColumns: names(match[3])
150395
151137
  };
150396
151138
  }
@@ -150407,7 +151149,7 @@ function declaredForeignKeys(files, schemas) {
150407
151149
  const text = withoutComments(file.text);
150408
151150
  const found = [];
150409
151151
  for (const match of text.matchAll(TABLE$2)) {
150410
- const table = qualified$8(match[1]);
151152
+ const table = qualified$9(match[1]);
150411
151153
  const open = match.index + match[0].length - 1;
150412
151154
  const close = closingParen(text, open);
150413
151155
  if (close === -1) continue;
@@ -150434,14 +151176,14 @@ function declaredForeignKeys(files, schemas) {
150434
151176
  key: {
150435
151177
  table,
150436
151178
  columns: [unquote$5(column)],
150437
- references: qualified$8(inline[1]),
151179
+ references: qualified$9(inline[1]),
150438
151180
  referencedColumns: names(inline[2])
150439
151181
  }
150440
151182
  });
150441
151183
  }
150442
151184
  }
150443
151185
  for (const match of text.matchAll(ALTER)) {
150444
- const key = constraintOf(qualified$8(match[1]), match[2]);
151186
+ const key = constraintOf(qualified$9(match[1]), match[2]);
150445
151187
  if (key !== void 0) found.push({
150446
151188
  index: match.index,
150447
151189
  key
@@ -151011,6 +151753,7 @@ const TABLE_FEATURES = [
151011
151753
  "json",
151012
151754
  "expose",
151013
151755
  "encrypted",
151756
+ "lookup",
151014
151757
  "server",
151015
151758
  "events",
151016
151759
  "vector-search"