better-supabase 0.30.0 → 0.31.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 (205) hide show
  1. package/dist/{adapter-D4aNBxhm.js → adapter-BTbj5N9C.js} +2 -52
  2. package/dist/ai-sdk/agents/index.d.ts +2 -2
  3. package/dist/{app-tables-yyVncXEt.d.ts → app-tables-B2mKMNRQ.d.ts} +1 -1
  4. package/dist/astro/index.js +2 -2
  5. package/dist/{authorization-CDU9tYA_.d.ts → authorization-DfEkyFt_.d.ts} +10 -3
  6. package/dist/{bind-p7asfI6H.d.ts → bind-DAx0bMSi.d.ts} +2 -2
  7. package/dist/{block-env-B8wG3xeh.d.ts → block-env-Dz7Caxk0.d.ts} +3 -3
  8. package/dist/blocks/ai-chat/index.d.ts +3 -3
  9. package/dist/blocks/announcements/index.d.ts +3 -3
  10. package/dist/blocks/api-keys/index.d.ts +1 -1
  11. package/dist/blocks/attachments/index.d.ts +1 -1
  12. package/dist/blocks/audit/index.d.ts +2 -2
  13. package/dist/blocks/automations/index.d.ts +1 -1
  14. package/dist/blocks/billing/index.d.ts +1 -1
  15. package/dist/blocks/bookings/index.d.ts +1 -1
  16. package/dist/blocks/calendar/index.d.ts +7 -3
  17. package/dist/blocks/calendar/index.js +5 -1
  18. package/dist/blocks/comments/index.d.ts +4 -4
  19. package/dist/blocks/employees/index.js +1 -4
  20. package/dist/blocks/entitlements/index.d.ts +2 -2
  21. package/dist/blocks/forms/index.d.ts +1 -1
  22. package/dist/blocks/inbox/index.d.ts +4 -4
  23. package/dist/blocks/index.d.ts +1 -1
  24. package/dist/blocks/messaging/index.d.ts +4 -4
  25. package/dist/blocks/mfa/index.d.ts +1 -1
  26. package/dist/blocks/notifications/index.d.ts +3 -3
  27. package/dist/blocks/notifications/index.js +5 -43
  28. package/dist/blocks/onboarding/index.d.ts +1 -1
  29. package/dist/blocks/organizations/index.d.ts +34 -21
  30. package/dist/blocks/organizations/index.js +5 -1
  31. package/dist/blocks/permissions/index.d.ts +32 -3
  32. package/dist/blocks/permissions/index.js +23 -2
  33. package/dist/blocks/push/index.d.ts +10 -2
  34. package/dist/blocks/push/index.js +23 -7
  35. package/dist/blocks/reactions/index.d.ts +3 -3
  36. package/dist/blocks/saved-views/index.d.ts +1 -1
  37. package/dist/blocks/search/index.d.ts +2 -2
  38. package/dist/blocks/sessions/index.d.ts +1 -1
  39. package/dist/blocks/settings/index.d.ts +1 -1
  40. package/dist/blocks/subjects/index.d.ts +1 -1
  41. package/dist/blocks/tags/index.d.ts +1 -1
  42. package/dist/blocks/tasks/index.js +1 -1
  43. package/dist/blocks/teams/index.d.ts +7 -1
  44. package/dist/blocks/teams/index.js +8 -7
  45. package/dist/blocks/undo/index.d.ts +1 -1
  46. package/dist/blocks/usage/index.d.ts +1 -1
  47. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  48. package/dist/blocks/workflows/index.d.ts +3 -3
  49. package/dist/cli/{add-Dggyehsy.js → add-B9wP0YGU.js} +2 -2
  50. package/dist/cli/{add-D4w-Axib.js → add-DjZXKd7X.js} +10 -10
  51. package/dist/cli/add-ZcEOEK23.js +1 -0
  52. package/dist/cli/{app-table-files-CiGuwLkO.js → app-table-files-mtvjHa48.js} +2 -2
  53. package/dist/cli/{backfill-DjVjXW_P.js → backfill-Coshdvh_.js} +2 -2
  54. package/dist/cli/bin.js +1 -1
  55. package/dist/cli/{blocks-jRL9K1R8.js → blocks-BWCuA0nq.js} +2 -2
  56. package/dist/cli/{blocks-Bbmb6W_F.js → blocks-hiSazThw.js} +1 -1
  57. package/dist/cli/{cache-BuoIFlUJ.js → cache-x2wWAy0h.js} +1 -1
  58. package/dist/cli/{codemod-DRavXBCb.js → codemod-BnjV7BpC.js} +210 -11
  59. package/dist/cli/{command-DIPmo0wh.js → command-CCAwhiOh.js} +6 -0
  60. package/dist/cli/{completion-DxPxMtyP.js → completion-BJaB84Pe.js} +2 -2
  61. package/dist/cli/{completion-DyLMSjOD.js → completion-BkUhs1ms.js} +1 -1
  62. package/dist/cli/{completion-FUgqm2-N.js → completion-DmUVsUVQ.js} +2 -2
  63. package/dist/cli/{config-BfapErxs.js → config-zId1jkLx.js} +1 -1
  64. package/dist/cli/{content-mapper-BCtyfKXl.js → content-mapper-DvOSOdTE.js} +2 -2
  65. package/dist/cli/{db-CWvH1_46.js → db-DXKyVEDF.js} +1 -1
  66. package/dist/cli/{doctor-Di2ZekfN.js → doctor-Ywy8oJEU.js} +41 -16
  67. package/dist/cli/env-CNjT_uOV.js +1 -0
  68. package/dist/cli/{env-B2CbnbzD.js → env-XMiKvhtV.js} +1 -1
  69. package/dist/cli/{gen-STKC9vkK.js → gen-B-FbQmG1.js} +14 -14
  70. package/dist/cli/index.d.ts +1 -1
  71. package/dist/cli/index.js +7 -7
  72. package/dist/cli/{init-DW6_nIwj.js → init-fb9e1BKX.js} +9 -9
  73. package/dist/cli/{keys-V-HcO-21.js → keys-ORiPz1sM.js} +1 -1
  74. package/dist/cli/{live-0G4Plw3K.js → live-DIt7TP-N.js} +2 -2
  75. package/dist/cli/{mcp-flKS8iU5.js → mcp-CVWwraga.js} +3 -3
  76. package/dist/cli/{metadata-VARUbXEe.js → metadata-CannIjel.js} +3 -3
  77. package/dist/cli/{migrate-Bkq07XcT.js → migrate-Ht2TzIQF.js} +2 -2
  78. package/dist/cli/{migration-safety-BfVeza5j.js → migration-safety-nNyB05I-.js} +1 -1
  79. package/dist/cli/{migrations-BCq7Zs2E.js → migrations-bAd7dpk1.js} +2 -2
  80. package/dist/cli/{module-migration-lbeUrsYv.js → module-migration-CkNux8dr.js} +2 -2
  81. package/dist/cli/{moved-DNOtp9LA.js → moved-C3WyRHkA.js} +1 -1
  82. package/dist/cli/{parse-BPf3kGnc.js → parse-DjHbTaFI.js} +1 -1
  83. package/dist/cli/{powersync-B15CfH5Y.js → powersync-B2v0tDwp.js} +100 -7
  84. package/dist/cli/powersync-D3mAQ6QE.js +1 -0
  85. package/dist/cli/{print-DjxpBRnv.js → print-CxQ0rBKT.js} +2 -2
  86. package/dist/cli/{providers-dyxcHQY3.js → providers-DtI90lSw.js} +1 -1
  87. package/dist/cli/{remove-BLq5gbal.js → remove-DYtE4IZ4.js} +6 -6
  88. package/dist/cli/{render-CizUf3RW.js → render-QGWfEoiB.js} +3 -3
  89. package/dist/cli/{run-ChEjR7yw.js → run-B5aMwErM.js} +2 -2
  90. package/dist/cli/{run-MwM__teL.js → run-BNoJKf5I.js} +40 -39
  91. package/dist/cli/{run-ChOY6s4o.js → run-DiYX1XEa.js} +8 -8
  92. package/dist/cli/{seed-CDnL4Tnc.js → seed-C-Hu2n_E.js} +1 -1
  93. package/dist/cli/seed-Cm-c0BDd.js +1 -0
  94. package/dist/cli/{shared-DV5wIv-7.js → shared-D_CFi5di.js} +1 -1
  95. package/dist/cli/{skills-DM3oeIxY.js → skills-D98y0bSB.js} +1 -1
  96. package/dist/cli/{snapshot-B5LXkVMC.js → snapshot-BlQ4DDcJ.js} +9 -4
  97. package/dist/cli/{source-BoLNG_2A.js → source-CelMBQMj.js} +1 -1
  98. package/dist/cli/{spec-D6QeE2Zx.js → spec-BxcoGE0h.js} +1 -1
  99. package/dist/cli/{spec-Dz-PGCaM.js → spec-iBx1LcYO.js} +3 -3
  100. package/dist/cli/{sql-layout-zo02f3Dm.js → sql-layout-Dp4Rottt.js} +2 -2
  101. package/dist/cli/{stack-ClESAZYf.js → stack-B2slzrYH.js} +1 -1
  102. package/dist/cli/{sync-m-oZ_SyI.js → sync-BnORI43S.js} +4 -4
  103. package/dist/cli/{table-dyKddjwo.js → table-D6HUECKI.js} +1 -1
  104. package/dist/cli/{upgrade-C9sgVZ5z.js → upgrade-CR6-WmIc.js} +5 -5
  105. package/dist/cli/{upgrade-WwEJaX3i.js → upgrade-fz92aCnh.js} +3 -3
  106. package/dist/cli/{version-D2BQuqta.js → version-Dz8ZlOuh.js} +1 -1
  107. package/dist/client/index.d.ts +5 -5
  108. package/dist/client/native/index.d.ts +4 -4
  109. package/dist/{composite-CBRbvn5j.js → composite-B4qB6k31.js} +2 -2
  110. package/dist/config/index.d.ts +2 -2
  111. package/dist/config/index.js +4 -4
  112. package/dist/{config-r7njjNgh.js → config-B7g-HDis.js} +3 -3
  113. package/dist/{config-bqKaPjst.js → config-R0m0fBiD.js} +1 -1
  114. package/dist/{context-nbYYjv7U.d.ts → context-DWWoP1wK.d.ts} +1 -1
  115. package/dist/{controller-TRocodqG.d.ts → controller-Br9dGKGe.d.ts} +1 -1
  116. package/dist/{controller-qG-B1eDn.js → controller-W97g2WGG.js} +1 -1
  117. package/dist/create/index.d.ts +3 -3
  118. package/dist/create/index.js +3 -3
  119. package/dist/create/lite/index.d.ts +3 -3
  120. package/dist/create/lite/index.js +3 -3
  121. package/dist/delivery-events-DbL8IHIY.js +53 -0
  122. package/dist/edge/index.js +3 -3
  123. package/dist/{entitlements-B1i1-wfe.d.ts → entitlements-CBjm2lvD.d.ts} +1 -1
  124. package/dist/eve/index.js +1 -1
  125. package/dist/expo/index.js +3 -2
  126. package/dist/{field-errors-tJvehEFc.d.ts → field-errors-CEjsMAgd.d.ts} +4 -4
  127. package/dist/{framework-DYEUraqt.js → framework-CqiZk89W.js} +1 -1
  128. package/dist/hono/index.js +2 -2
  129. package/dist/{index-BkzXwuIN.d.ts → index-Clyd2Goi.d.ts} +1 -1
  130. package/dist/{index-zsgNmE8m.d.ts → index-D98bQs8a.d.ts} +7 -7
  131. package/dist/{index-BKrxynq9.d.ts → index-DIdPoQtO.d.ts} +2 -2
  132. package/dist/{index-CWAQRWY8.d.ts → index-I8YLxKq8.d.ts} +2 -2
  133. package/dist/{index-8US7qlvW.d.ts → index-eRBuKtMt.d.ts} +2 -2
  134. package/dist/{index-BM6NmKSc.d.ts → index-uIU65iEn.d.ts} +6 -6
  135. package/dist/{instances-C7qUTjhJ.js → instances-DY_ORk5g.js} +2 -0
  136. package/dist/mapper/bin.js +5 -5
  137. package/dist/mcp/index.d.ts +1 -1
  138. package/dist/mcp/index.js +1 -1
  139. package/dist/mcp/sdk/index.js +1 -1
  140. package/dist/next/index.d.ts +73 -6
  141. package/dist/next/index.js +88 -35
  142. package/dist/{operations-CB9atU2e.d.ts → operations-hm1Isvvs.d.ts} +1 -1
  143. package/dist/{options-BKBy5wM_.js → options-CF6EVF_G.js} +2 -1
  144. package/dist/{options-COo7_3MX.js → options-DSCW40_5.js} +3 -1
  145. package/dist/orpc/index.js +2 -1
  146. package/dist/otel/index.js +4 -4
  147. package/dist/{ports-hpbyMySO.d.ts → ports-DOrPTJzl.d.ts} +1 -1
  148. package/dist/powersync/index.d.ts +204 -4
  149. package/dist/powersync/index.js +361 -4
  150. package/dist/preset/index.d.ts +3 -3
  151. package/dist/preset/index.js +3 -3
  152. package/dist/{preset-DCdEnJj9.js → preset-CXhpPmPV.js} +2 -2
  153. package/dist/{project-B32wb5J6.js → project-DJ9Uo0sT.js} +5 -5
  154. package/dist/{push-token-DQ1ycFPU.d.ts → push-token-B4vcIU4s.d.ts} +1 -1
  155. package/dist/query/index.d.ts +1 -1
  156. package/dist/query/index.js +1 -1
  157. package/dist/react/index.d.ts +5 -5
  158. package/dist/react/index.js +1 -1
  159. package/dist/react/native/index.d.ts +1 -1
  160. package/dist/react/server.d.ts +5 -5
  161. package/dist/react/server.js +1 -1
  162. package/dist/{react-CcrQQl0_.js → react-mdVjpewL.js} +2 -2
  163. package/dist/react-router/index.js +2 -2
  164. package/dist/realtime/index.d.ts +3 -3
  165. package/dist/{record-type-DRbnlj5q.js → record-type-BEUyEsFx.js} +2 -2
  166. package/dist/records/index.d.ts +5 -5
  167. package/dist/records/index.js +3 -3
  168. package/dist/{replicas-Dyoh3CEg.js → refresh-DLBgnxjL.js} +51 -1
  169. package/dist/{resolved-names-iLBOUaib.js → resolved-names-kMRjmSIy.js} +1 -1
  170. package/dist/{runtime-CoKxZibd.js → runtime-LRJM7UqY.js} +19 -20
  171. package/dist/server/index.d.ts +1 -1
  172. package/dist/server/index.js +4 -4
  173. package/dist/{sign-in-Cyj3ZlFX.js → sign-in-CuZ1Ag7O.js} +17 -2
  174. package/dist/solid/index.d.ts +5 -5
  175. package/dist/solid-start/index.js +2 -2
  176. package/dist/spec/index.js +1 -1
  177. package/dist/sql/index.d.ts +4 -4
  178. package/dist/sql/index.js +3 -3
  179. package/dist/{sql-CyeDg3Yh.js → sql-DHp0L7zK.js} +404 -165
  180. package/dist/ssr/index.d.ts +1 -1
  181. package/dist/svelte/index.d.ts +5 -5
  182. package/dist/sveltekit/index.js +2 -2
  183. package/dist/tanstack-start/index.js +2 -2
  184. package/dist/{tenant-C9YE_kqK.d.ts → tenant-FfgNhd5x.d.ts} +1 -1
  185. package/dist/testing/index.d.ts +13 -4
  186. package/dist/testing/index.js +17 -15
  187. package/dist/{timeline-DvXtXq5q.d.ts → timeline-DqEoD8bb.d.ts} +1 -1
  188. package/dist/{timeline--VU3A1e4.js → timeline-Dz3hO2I6.js} +1 -1
  189. package/dist/{topic-breZqx_4.d.ts → topic-BaUElNw2.d.ts} +1 -1
  190. package/dist/{types-C3I7S51U.d.ts → types-CMN0h_Ix.d.ts} +2 -2
  191. package/dist/vue/index.d.ts +5 -5
  192. package/dist/{watch-topic-ItO3dz8m.d.ts → watch-topic-BabDTZ-L.d.ts} +1 -1
  193. package/dist/workflow-sdk/world/index.js +2 -2
  194. package/dist/{workflow-sdk-BWPsdzVK.js → workflow-sdk-DJJkP0dT.js} +12 -1
  195. package/dist/yjs/index.d.ts +1 -1
  196. package/package.json +1 -1
  197. package/schemas/config-v1.json +9 -1
  198. package/schemas/doctor-report-v1.json +1 -0
  199. package/skills/better-supabase/references/ui-recipes.md +524 -295
  200. package/skills/better-supabase-api/references/powersync.md +16 -0
  201. package/skills/better-supabase-auth/SKILL.md +4 -1
  202. package/dist/cli/add-BdhGOwkB.js +0 -1
  203. package/dist/cli/env-CynGCICL.js +0 -1
  204. package/dist/cli/powersync-DnBsDchT.js +0 -1
  205. package/dist/cli/seed-BOun22-k.js +0 -1
@@ -3,16 +3,16 @@ import { d as temporalText } from "./temporal-Dbo0fLzc.js";
3
3
  import { r as NEGATIVE, t as FILTER_OPERATORS } from "./filter-query-CQ6d5GnQ.js";
4
4
  import { a as ok } from "./result-ntFBW2p2.js";
5
5
  import { a as hasPlaceholder, l as splitPlaceholders, s as placeholderOf } from "./read-set-B1sDib5O.js";
6
- import { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-iLBOUaib.js";
6
+ import { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-kMRjmSIy.js";
7
7
  import { t as DEFAULT_CLAIMS } from "./claims-Bp9My7XP.js";
8
8
  import { o as tenantNames, r as composeNames } from "./entity-naming-Dtyq5sKE.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-C7qUTjhJ.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-DY_ORk5g.js";
10
10
  import { a as RATING_BOUNDS, n as CUSTOM_FIELD_TYPES, r as FIELD_FORMATS, t as CUSTOM_FIELD_FORM_TYPES } from "./field-formats-C6QKA3UR.js";
11
11
  import { t as isSqlType } from "./sql-type-iUSZpaUu.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-Drgg3v2J.js";
13
13
  import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-CTDNuxRv.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DKVQDz4o.js";
15
- import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-BWPsdzVK.js";
15
+ import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-DJJkP0dT.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-CfVPctAw.js";
17
17
  import { t as accessRequestsSqlOptions } from "./options-gUvfr3no.js";
18
18
  import { t as activitiesSqlOptions } from "./options-sU_zGkiV.js";
@@ -32,7 +32,7 @@ import { t as automationsSqlOptions } from "./options-DcHl59RC.js";
32
32
  import { t as billingSqlOptions } from "./options-DZHZYlpD.js";
33
33
  import { t as bookingsSqlOptions } from "./options-CZDmtsbV.js";
34
34
  import { t as bulkSqlOptions } from "./options-CTl8T88w.js";
35
- import { t as calendarSqlOptions } from "./options-BKBy5wM_.js";
35
+ import { t as calendarSqlOptions } from "./options-CF6EVF_G.js";
36
36
  import { t as catalogSqlOptions } from "./options-D0sj5abR.js";
37
37
  import { t as collectionsSqlOptions } from "./options-CyjL9lTf.js";
38
38
  import { t as commentsSqlOptions } from "./options-CoSPgWKy.js";
@@ -110,7 +110,7 @@ import { t as slaSqlOptions } from "./options-Dz9Yo52Z.js";
110
110
  import { t as ssoSqlOptions } from "./options-3OYOU56e.js";
111
111
  import { t as stateMachineSqlOptions } from "./options-aT89JqlB.js";
112
112
  import { t as tagsSqlOptions } from "./options-BJtdsK7b.js";
113
- import { t as tasksSqlOptions } from "./options-COo7_3MX.js";
113
+ import { t as tasksSqlOptions } from "./options-DSCW40_5.js";
114
114
  import { t as teamsSqlOptions } from "./options-jsOCvLUz.js";
115
115
  import { t as templatesSqlOptions } from "./options-BKDxrPvE.js";
116
116
  import { t as timeTrackingSqlOptions } from "./options-eTepQ1rZ.js";
@@ -1929,7 +1929,7 @@ const CLIENT_FUNCTIONS = {
1929
1929
  organizations: "create_organization delete_organization leave_organization list_members list_my_organizations mark_used organization_slug_problem remove_member resume_member suspend_member switch_organization transfer_ownership update_member_role update_organization",
1930
1930
  outbox: "emit_event outbox_ack outbox_claim outbox_dead_letters outbox_fail outbox_history outbox_register outbox_unregister purge_outbox",
1931
1931
  passes: "check_in_pass get_pass issue_pass list_pass_check_ins list_passes my_passes revoke_pass",
1932
- permissions: "can my_permissions",
1932
+ permissions: "can list_roles my_permissions set_permission_override",
1933
1933
  pipelines: "archive_pipeline archive_pipeline_stage list_pipelines pipeline_board pipeline_health pipeline_stats rank_pipeline_stage save_pipeline save_pipeline_stage set_pipeline_transitions",
1934
1934
  posts: "create_post delete_post get_post list_post_boards list_posts merge_posts save_post_board set_post_state update_post vote_on_post",
1935
1935
  profiles: "my_profile update_my_profile",
@@ -4817,7 +4817,7 @@ begin
4817
4817
  if not found then
4818
4818
  ${fail$1("ACCESS_REQUEST_NOT_FOUND", "access request not found", "P0002")}
4819
4819
  end if;
4820
- if not (${SERVICE_CALLER$1} or v_row.${c("user")} = auth.uid() or ${ctx.can("tenant", `v_row.${c("tenant")}`, manage)}) then
4820
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${c("user")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${c("tenant")}`, manage)}) then
4821
4821
  ${fail$1("ACCESS_REQUEST_FORBIDDEN", "not allowed to end this access")}
4822
4822
  end if;
4823
4823
  if v_row.${c("grantedAt")} is null or v_row.${c("endedAt")} is not null then
@@ -4870,7 +4870,7 @@ declare
4870
4870
  v_approval ${ar}%rowtype;
4871
4871
  begin
4872
4872
  select * into v_row from ${requests} r where r.${c("id")} = get_access_request.request_id;
4873
- if not found or not (${SERVICE_CALLER$1} or v_row.${c("user")} = auth.uid() or ${ctx.can("tenant", `v_row.${c("tenant")}`, read)}) then
4873
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${c("user")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${c("tenant")}`, read)}) then
4874
4874
  ${fail$1("ACCESS_REQUEST_NOT_FOUND", "access request not found", "P0002")}
4875
4875
  end if;
4876
4876
  select * into v_approval from ${ar} x where x.${a("id")} = v_row.${c("approval")};
@@ -5045,7 +5045,7 @@ function checkPermission(where, action, value) {
5045
5045
  * (`organization_id`, or `workspace_id` for
5046
5046
  * `blocks.memberships.names.organization: workspace`).
5047
5047
  */
5048
- function registeredSubjects(subjects, naming = tenantNames()) {
5048
+ function registeredSubjects$1(subjects, naming = tenantNames()) {
5049
5049
  const idents = /* @__PURE__ */ new Map();
5050
5050
  for (const type of Object.keys(subjects)) {
5051
5051
  const other = idents.get(subjectTypeIdent(type));
@@ -5162,7 +5162,7 @@ function urlExpression(template, alias = "s") {
5162
5162
  * module must require `subjects`.
5163
5163
  */
5164
5164
  function subjectInTenant(ctx, type, id, tenant) {
5165
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5165
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5166
5166
  if (subjects.length === 0) return "false";
5167
5167
  const canSubject = ctx.of("subjects").fn("can_subject");
5168
5168
  return `(case ${type}
@@ -5176,7 +5176,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then exists (
5176
5176
  * security definer code after checking the caller.
5177
5177
  */
5178
5178
  function subjectTenant(ctx, type, id) {
5179
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5179
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5180
5180
  if (subjects.length === 0) return "null::text";
5181
5181
  return `(case ${type}
5182
5182
  ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select s.${subject.tenant ?? ""}::text from ${subject.qualified} s where ${registeredIdMatches(subject, id)})`).join("\n")}
@@ -5189,7 +5189,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select
5189
5189
  * one. Reads the table directly, so check the caller first.
5190
5190
  */
5191
5191
  function subjectTitle(ctx, type, id) {
5192
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.title !== void 0);
5192
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.title !== void 0);
5193
5193
  if (subjects.length === 0) return "null::text";
5194
5194
  return `(case ${type}
5195
5195
  ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select s.${sqlIdent(subject.config.title ?? "")}::text from ${subject.qualified} s where ${registeredIdMatches(subject, id)})`).join("\n")}
@@ -6718,7 +6718,7 @@ function build$116(ctx) {
6718
6718
  returning * into v_row;` : "";
6719
6719
  const installCount = (change, indent) => agent("installCount") ? `\n${indent}update ${ctx.table("agents")} x set ${a.installCount} = ${change} where x.${a.id} = install_agent.agent_id;` : "";
6720
6720
  const readable = (row) => `(${row}.${a.owner} = (select auth.uid()) or (${row}.${a.publishedAt} is not null and (${row}.${a.visibility} = 'public' or (${row}.${a.visibility} = 'organization' and ${ctx.scope.check(`${row}.${a.tenant}`, read)}))) or ${ctx.scope.check(`${row}.${a.tenant}`, moderate)})`;
6721
- const canChange = (row) => `(${SERVICE_CALLER$1} or ${row}.${a.owner} = auth.uid() or ${ctx.scope.can(`${row}.${a.tenant}`, moderate)})`;
6721
+ const canChange = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${a.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${a.tenant}`, moderate)})`;
6722
6722
  const notFound = (agent) => raise$1("agent % not found", "P0002", "AGENT_NOT_FOUND", agent);
6723
6723
  const agentEvent = (type, row, extra = "") => ctx.record({
6724
6724
  type,
@@ -6906,7 +6906,7 @@ begin
6906
6906
  ${notFound("publish_agent.id")}
6907
6907
  end if;
6908
6908
  if publish_agent.visibility <> 'private' and not (${SERVICE_CALLER$1} or ${ctx.scope.can(`v_row.${a.tenant}`, moderate)}
6909
- or (v_row.${a.owner} = auth.uid() and ${ctx.scope.can(`v_row.${a.tenant}`, publish)})) then
6909
+ or (coalesce(v_row.${a.owner} = auth.uid(), false) and ${ctx.scope.can(`v_row.${a.tenant}`, publish)})) then
6910
6910
  ${raise$1("you may not publish agents here", "42501", "AGENT_FORBIDDEN")}
6911
6911
  end if;
6912
6912
  update ${agents} x set
@@ -9575,7 +9575,7 @@ ${userGrant(`${fn("my_work")}(${ctx.idType}, integer)`)}
9575
9575
  }
9576
9576
  function build$113(ctx, layout) {
9577
9577
  if (ctx.mode === "custom") return "";
9578
- const subjects = registeredSubjects(ctx.subjects, ctx.naming);
9578
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming);
9579
9579
  const provider = accessModel(ctx) === "provider" ? layout.accessProvider : void 0;
9580
9580
  const fn = (name) => ctx.fn(name);
9581
9581
  return `${schemaPreamble(ctx)}
@@ -9981,6 +9981,7 @@ function build$112(ctx, layout) {
9981
9981
  const mu = members.col("memberships", "user");
9982
9982
  const mt = members.col("memberships", "tenant");
9983
9983
  const mr = members.col("memberships", "role");
9984
+ const approverRole = roleValue(ctx, "v_approvers ->> 'role'", `v_req.${c("tenant")}`);
9984
9985
  const memberIdsFor = providerMembers(ctx, layout).idsFor;
9985
9986
  const delegateMember = memberIdsFor === void 0 ? `exists (
9986
9987
  select 1 from ${members.table("memberships")} m
@@ -10043,7 +10044,7 @@ ${indent}end if;`;
10043
10044
  select x::uuid from jsonb_array_elements_text(coalesce(v_approvers -> 'users', '[]'::jsonb)) x
10044
10045
  union
10045
10046
  select m.${mu} from ${members.table("memberships")} m
10046
- where m.${mt} = v_req.${c("tenant")} and m.${mr} = v_approvers ->> 'role'${teamMembers}${delegation ? `
10047
+ where m.${mt} = v_req.${c("tenant")} and m.${mr} = ${approverRole}${teamMembers}${delegation ? `
10047
10048
  union
10048
10049
  select x.${d("delegateTo")} from ${decisions} x
10049
10050
  where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("decision")} = 'delegated'
@@ -10183,7 +10184,7 @@ begin
10183
10184
  or (v_approvers ->> 'permission' is not null and ${ctx.can("tenant", `v_req.${c("tenant")}`, "v_approvers ->> 'permission'")})
10184
10185
  or (v_approvers ->> 'role' is not null and exists (
10185
10186
  select 1 from ${members.table("memberships")} m
10186
- where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = v_approvers ->> 'role'
10187
+ where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = ${approverRole}
10187
10188
  ))
10188
10189
  or (v_approvers ->> 'team' is not null and ${teamMatch("v_me")})${delegation ? `
10189
10190
  or exists (
@@ -10445,7 +10446,7 @@ begin
10445
10446
  if not found then
10446
10447
  ${notFound}
10447
10448
  end if;
10448
- if not (${SERVICE_CALLER$1} or v_req.${c("requestedBy")} = auth.uid() or ${ctx.can("tenant", `v_req.${c("tenant")}`, manage)}) then
10449
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${c("requestedBy")} = auth.uid(), false) or ${ctx.can("tenant", `v_req.${c("tenant")}`, manage)}) then
10449
10450
  ${fail$1("APPROVAL_FORBIDDEN", "only the requester or a manager can cancel this request")}
10450
10451
  end if;
10451
10452
  if v_req.${c("status")} <> 'pending' then
@@ -10473,7 +10474,7 @@ begin
10473
10474
  if not found then
10474
10475
  ${notFound}
10475
10476
  end if;
10476
- if not (${SERVICE_CALLER$1} or v_req.${c("requestedBy")} = auth.uid() or ${fn("approval_eligible")}(v_req.${c("id")})
10477
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${c("requestedBy")} = auth.uid(), false) or ${fn("approval_eligible")}(v_req.${c("id")})
10477
10478
  or (${ctx.can("tenant", `v_req.${c("tenant")}`, read)} and ${readable("v_req")})) then
10478
10479
  ${notFound}
10479
10480
  end if;
@@ -11022,7 +11023,7 @@ declare
11022
11023
  v_row ${t.inputs};
11023
11024
  begin
11024
11025
  select * into v_row from ${t.inputs} x where x.${i.id} = answer_ai_pending_input.id for update;
11025
- if not found or not (${SERVICE_CALLER$1} or v_row.${i.owner} = (select auth.uid())) then
11026
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${i.owner} = (select auth.uid()), false)) then
11026
11027
  ${raise$1("No question %", "P0002", "AI_INPUT_NOT_FOUND", "answer_ai_pending_input.id")}
11027
11028
  end if;
11028
11029
  if v_row.${i.answeredAt} is not null then
@@ -12292,7 +12293,7 @@ function aiChatMessages(ctx, names) {
12292
12293
  const st = (column) => streams.col("streams", column);
12293
12294
  const ownChat = (name) => `
12294
12295
  select * into v_chat from ${t.chats} x where x.${ch.id} = ${name}.chat for update;
12295
- if not found or not (${SERVICE_CALLER$1} or v_chat.${ch.owner} = (select auth.uid())) then
12296
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_chat.${ch.owner} = (select auth.uid()), false)) then
12296
12297
  ${raise$1("No chat %", "P0002", "AI_CHAT_NOT_FOUND", `${name}.chat`)}
12297
12298
  end if;`;
12298
12299
  const metering = runMetering(ctx, names);
@@ -12941,7 +12942,7 @@ declare
12941
12942
  v_project uuid := (v_fields ->> 'project_id')::uuid;
12942
12943
  begin
12943
12944
  select * into v_row from ${t.chats} x where x.${ch.id} = update_ai_chat.chat for update;
12944
- if not found or not (${SERVICE_CALLER$1} or v_row.${ch.owner} = (select auth.uid())) then
12945
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${ch.owner} = (select auth.uid()), false)) then
12945
12946
  ${notFound.replace("%CHAT%", "update_ai_chat.chat")}
12946
12947
  end if;
12947
12948
  if v_project is not null and not ${ownProject("v_project", `v_row.${ch.owner}`, `v_row.${ch.tenant}`)} then
@@ -12981,7 +12982,7 @@ begin
12981
12982
  if not found then
12982
12983
  return false;
12983
12984
  end if;
12984
- if not (${SERVICE_CALLER$1} or v_row.${ch.owner} = (select auth.uid()) or ${can(`v_row.${ch.tenant}`, perm.admin)}) then
12985
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${ch.owner} = (select auth.uid()), false) or ${can(`v_row.${ch.tenant}`, perm.admin)}) then
12985
12986
  ${notFound.replace("%CHAT%", "delete_ai_chat.chat")}
12986
12987
  end if;
12987
12988
  delete from ${t.chats} x where x.${ch.id} = delete_ai_chat.chat;
@@ -13210,7 +13211,8 @@ const NAMES$111 = {
13210
13211
  lifecycle: {
13211
13212
  tenant: "tenant",
13212
13213
  user: "createdBy",
13213
- export: true
13214
+ export: true,
13215
+ omit: ["tokenHash"]
13214
13216
  },
13215
13217
  columns: {
13216
13218
  id: "id",
@@ -13316,10 +13318,34 @@ function blockSubjects(ctx) {
13316
13318
  * (`config.subjects` or `on`) check the row's tenant and the subject's read
13317
13319
  * permission. Any other type fails.
13318
13320
  */
13321
+ function allowedTypes(ctx) {
13322
+ const on = ctx.on;
13323
+ if (on === void 0) return;
13324
+ return Array.isArray(on) ? on.map(String) : Object.keys(on);
13325
+ }
13326
+ function allowedCheck(ctx) {
13327
+ const allowed = allowedTypes(ctx);
13328
+ return allowed === void 0 ? "" : `
13329
+ if create_share_link.subject_type is null or create_share_link.subject_type <> all (array[${allowed.map(sqlString).join(", ")}]::text[]) then
13330
+ ${fail$1("SHARE_SUBJECT_UNKNOWN", "this subject type can't be shared", "22023")}
13331
+ end if;`;
13332
+ }
13333
+ function registeredSubjects(ctx) {
13334
+ const owned = new Set(blockSubjects(ctx).map(([type]) => type));
13335
+ const on = ctx.on;
13336
+ if (on === void 0) return subjectsOption(ctx);
13337
+ const listed = Array.isArray(on) ? on.filter((type) => !owned.has(String(type))) : Object.fromEntries(Object.entries(on).filter(([type]) => !owned.has(type)));
13338
+ return Object.keys(listed).length === 0 ? [] : subjectsOption({
13339
+ ...ctx,
13340
+ on: listed
13341
+ });
13342
+ }
13319
13343
  function subjectCheck(ctx) {
13320
- const blocks = blockSubjects(ctx);
13321
- const owned = new Set(blocks.map(([type]) => type));
13322
- const registered = subjectsOption(ctx).filter(([type]) => !owned.has(type));
13344
+ const allowed = allowedTypes(ctx);
13345
+ const every = blockSubjects(ctx);
13346
+ const owned = new Set(every.map(([type]) => type));
13347
+ const blocks = every.filter(([type]) => allowed === void 0 || allowed.includes(type));
13348
+ const registered = registeredSubjects(ctx).filter(([type]) => !owned.has(type));
13323
13349
  const sharable = subjectActionCheck(ctx, registered, SUBJECT_ARGS, ["share"]);
13324
13350
  const readable = registered.length === 0 ? "null" : subjectReadable(ctx, registered, SUBJECT_ARGS).replace(/else false\s+end$/, "else null\n end");
13325
13351
  const others = sharable === void 0 || readable === "null" ? readable : `case when ${readable} then ${sharable} else ${readable} end`;
@@ -13397,7 +13423,7 @@ function build$111(ctx) {
13397
13423
  const linkId = ctx.col("links", "id");
13398
13424
  const hashed = ctx.flag("tokenHash", false);
13399
13425
  const full = ctx.flag("fullRows", false);
13400
- const subjects = subjectsOption(ctx);
13426
+ const subjects = registeredSubjects(ctx);
13401
13427
  const l = (column) => `l.${ctx.col("links", column)}`;
13402
13428
  const shareOn = (type, id) => subjectActionCheck(ctx, subjects, {
13403
13429
  type,
@@ -13485,6 +13511,7 @@ begin
13485
13511
  if create_share_link.token_hash is not null and create_share_link.token_hash !~ '^[0-9a-f]{64}$' then
13486
13512
  ${fail$1("SHARE_TOKEN_HASH_INVALID", "token_hash must be 64 lowercase hex characters", "22023")}
13487
13513
  end if;` : ""}
13514
+ ${allowedCheck(ctx)}
13488
13515
  ${subjectCheck(ctx)}
13489
13516
  ${versionCheck(ctx)}
13490
13517
  insert into ${links} (${ctx.col("links", "tenant")}, ${ctx.col("links", "subjectType")}, ${ctx.col("links", "subjectId")}, ${ctx.col("links", "tokenHash")}, ${ctx.col("links", "role")}, ${ctx.col("links", "expiresAt")}, ${ctx.col("links", "maxUses")}, ${ctx.col("links", "createdBy")}${pinned ? `, ${ctx.col("links", "versionId")}` : ""})
@@ -13521,7 +13548,7 @@ begin
13521
13548
  for update;
13522
13549
  if not found or not (
13523
13550
  auth.role() = 'service_role'
13524
- or (v_creator is not null and v_creator = auth.uid())
13551
+ or (v_creator is not null and coalesce(v_creator = auth.uid(), false))
13525
13552
  or ${revokeShare === void 0 ? ctx.scope.can("v_tenant", create) : `(${ctx.scope.can("v_tenant", create)} and ${revokeShare})`}
13526
13553
  ) then
13527
13554
  ${fail$1("SHARE_NOT_FOUND", "share link not found", "P0002")}
@@ -15007,8 +15034,8 @@ function build$109(ctx) {
15007
15034
  const versionJson = (row) => `jsonb_build_object('document_id', ${row}.${v.document}, 'version', ${row}.${v.version}, 'content', ${row}.${v.content}, 'storage_path', ${or("versions", row, "storagePath", "null")}, 'created_by_message_id', ${or("versions", row, "message", "null")}, 'created_by', ${or("versions", row, "createdBy", "null")}, 'created_at', ${or("versions", row, "createdAt", "null")})`;
15008
15035
  const suggestionJson = (row) => `jsonb_build_object('id', ${row}.${sg.id}, 'document_id', ${row}.${sg.document}, 'version', ${row}.${sg.version}, 'original_text', ${row}.${sg.original}, 'suggested_text', ${row}.${sg.suggested}, 'description', ${or("suggestions", row, "description", "null")}, 'created_by', ${or("suggestions", row, "createdBy", "null")}, 'created_at', ${or("suggestions", row, "createdAt", "null")}, 'resolved_at', ${row}.${sg.resolvedAt}, 'accepted', ${row}.${sg.accepted})`;
15009
15036
  const readable = (prefix, owner, tenant, chat) => `(${prefix}${owner} = (select auth.uid()) or ${prefix === "" ? ctx.scope.check(tenant, manage) : ctx.scope.can(`${prefix}${tenant}`, manage)} or ${chatReadable(`${prefix}${chat}`)})`;
15010
- const ownFile = (row) => `(${SERVICE_CALLER$1} or ${row}.${f.owner} = auth.uid() or ${ctx.scope.can(`${row}.${f.tenant}`, manage)})`;
15011
- const ownDocument = (row) => `(${SERVICE_CALLER$1} or ${row}.${d.owner} = auth.uid() or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
15037
+ const ownFile = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${f.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${f.tenant}`, manage)})`;
15038
+ const ownDocument = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${d.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
15012
15039
  const reserveInsert = [
15013
15040
  ["tenant", "reserve_ai_file.tenant"],
15014
15041
  ["owner", "auth.uid()"],
@@ -15290,7 +15317,7 @@ declare
15290
15317
  v_size bigint;
15291
15318
  begin
15292
15319
  select * into v_row from ${files} x where x.${f.id} = confirm_ai_file.file_id for update;
15293
- if not found or not (${SERVICE_CALLER$1} or v_row.${f.owner} = auth.uid()) then
15320
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${f.owner} = auth.uid(), false)) then
15294
15321
  ${raise$1("file % not found", "P0002", "AI_FILE_NOT_FOUND", "file_id")}
15295
15322
  end if;
15296
15323
  if v_row.${f.status} <> 'pending' then
@@ -16800,7 +16827,7 @@ function build$106(ctx) {
16800
16827
  const line = (present, definition) => present ? `\n ${definition},` : "";
16801
16828
  const enqueue = (run) => ctx.installed("queue") ? `
16802
16829
  ${ctx.enqueue(queue, `jsonb_build_object('run_id', ${run})`, `'ai-task:' || ${run}::text`)}` : "";
16803
- const mayEdit = (row) => `(${SERVICE_CALLER$1} or ${row}.${t.user} = auth.uid() or ${ctx.scope.can(`${row}.${t.tenant}`, manage)})`;
16830
+ const mayEdit = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${t.user} = auth.uid(), false) or ${ctx.scope.can(`${row}.${t.tenant}`, manage)})`;
16804
16831
  const notFound = raise$1("task % not found", "P0002", "AI_TASK_NOT_FOUND", "v_id");
16805
16832
  return `${schemaPreamble(ctx)}
16806
16833
  -- Prompts a user schedules to run on a cron. next_run_at is computed by the
@@ -18170,7 +18197,7 @@ function assetsFunctions(ctx) {
18170
18197
  const workItems = ctx.installed("tasks") && ctx.of("tasks").manages ? ctx.of("tasks") : void 0;
18171
18198
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
18172
18199
  const readsLocation = (row) => allowed(`${row}.${l("tenant")}`, read);
18173
- const readsAsset = (row) => `(${allowed(`${row}.${s("tenant")}`, read)} or (${row}.${s("assigneeType")} = 'member' and ${row}.${s("assigneeId")} = auth.uid()::text))`;
18200
+ const readsAsset = (row) => `(${allowed(`${row}.${s("tenant")}`, read)} or (${row}.${s("assigneeType")} = 'member' and coalesce(${row}.${s("assigneeId")} = auth.uid()::text, false)))`;
18174
18201
  const forbidden = (message) => fail$1("ASSETS_FORBIDDEN", message);
18175
18202
  const invalid = (code, message) => fail$1(code, message, "22023");
18176
18203
  const locationMissing = fail$1("ASSETS_LOCATION_NOT_FOUND", "location not found", "P0002");
@@ -20925,7 +20952,7 @@ end;`;
20925
20952
  id,
20926
20953
  tenantless: tenantless.length > 0,
20927
20954
  json,
20928
- mayVersion: `(v_row.${c("uploadedBy")} = auth.uid() and ${inTenant("v_row", "upload")}) or ${canManage("v_row")} or (${SERVICE_CALLER$1})`
20955
+ mayVersion: `(coalesce(v_row.${c("uploadedBy")} = auth.uid(), false) and ${inTenant("v_row", "upload")}) or ${canManage("v_row")} or (${SERVICE_CALLER$1})`
20929
20956
  });
20930
20957
  const policy = (name) => sqlIdent(`bsb_attachments_${name}`);
20931
20958
  const offlineSql = offline ? attachmentsOfflineSql(ctx, {
@@ -25861,7 +25888,7 @@ function timeOwner(ctx, statusMode) {
25861
25888
  const myEmployee = (tenant) => staff === void 0 ? "null::uuid" : `(select y.${staff.col("employees", "id")} from ${staff.table("employees")} y where y.${staff.col("employees", "tenant")} = ${tenant} and y.${staff.col("employees", "user")} = auth.uid())`;
25862
25889
  const employeeOf = (tenant, employee) => staff === void 0 ? "" : `select y.${staff.col("employees", "id")}, y.${staff.col("employees", "user")} into v_owner, v_user from ${staff.table("employees")} y where y.${staff.col("employees", "id")} = ${employee} and y.${staff.col("employees", "tenant")} = ${tenant};`;
25863
25890
  const employeeOfUser = (tenant, user) => staff === void 0 ? "" : `select y.${staff.col("employees", "id")}, y.${staff.col("employees", "user")} into v_owner, v_user from ${staff.table("employees")} y where y.${staff.col("employees", "tenant")} = ${tenant} and y.${staff.col("employees", "user")} = ${user};`;
25864
- const ownedByMe = (row) => employeeMode ? `(${row}.${ctx.col("entries", "user")} = auth.uid() or ${row}.${ctx.col("entries", "employee")} = ${myEmployee(`${row}.${ctx.col("entries", "tenant")}`)})` : `${row}.${ctx.col("entries", "user")} = auth.uid()`;
25891
+ const ownedByMe = (row) => employeeMode ? `(coalesce(${row}.${ctx.col("entries", "user")} = auth.uid(), false) or ${row}.${ctx.col("entries", "employee")} = ${myEmployee(`${row}.${ctx.col("entries", "tenant")}`)})` : `coalesce(${row}.${ctx.col("entries", "user")} = auth.uid(), false)`;
25865
25892
  const sheetUserJson = (row) => `'userId', ${sheetUser ? `${row}.${ctx.col("timesheets", "user")}` : "null::uuid"}${employeeMode ? `, 'employeeId', ${row}.${ctx.col("timesheets", "employee")}` : ""}`;
25866
25893
  return {
25867
25894
  employeeMode,
@@ -26431,7 +26458,7 @@ ${userGrant(`${fn("list_invoiced_time")}(uuid, integer)`)}
26431
26458
  }
26432
26459
  /** Moves the rates on a merged registered subject to the record it merged into. */
26433
26460
  function rateMerges(ctx) {
26434
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
26461
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
26435
26462
  table: `${subject.schema}.${subject.table}`,
26436
26463
  extra: {}
26437
26464
  }]), moveSubjectRows({
@@ -27982,7 +28009,7 @@ function seriesFunctions(p) {
27982
28009
  const series = ctx.table("series");
27983
28010
  const e = (column) => ctx.col("series", column);
27984
28011
  const seriesJsonOf = (alias) => `jsonb_build_object('id', ${alias}.${e("id")}, 'organizationId', ${alias}.${e("tenant")}::text, 'serviceId', ${alias}.${e("service")}, 'resourceId', ${alias}.${e("resource")}, 'rule', ${alias}.${e("rule")}, 'startsAt', ${alias}.${e("startsAt")}, 'tz', ${alias}.${e("tz")}, 'customerName', ${alias}.${e("customerName")}, 'customerEmail', ${alias}.${e("customerEmail")}, 'customerUserId', ${alias}.${e("customerUser")}, 'status', ${alias}.${e("status")}, 'endsAt', ${alias}.${e("endsAt")}, 'createdAt', ${alias}.${e("createdAt")})`;
27985
- const mayChange = (tenant, customer) => `(${allowed(p.scope, tenant, p.manage)} or (${customer} = auth.uid() and ${allowed(p.scope, tenant, p.create)}))`;
28012
+ const mayChange = (tenant, customer) => `(${allowed(p.scope, tenant, p.manage)} or (coalesce(${customer} = auth.uid(), false) and ${allowed(p.scope, tenant, p.create)}))`;
27986
28013
  return `
27987
28014
  -- The starts of a rule's occurrences from first_start: { freq: daily or
27988
28015
  -- weekly, interval, weekdays (1 is Monday, weekly only), count or until }.
@@ -29215,7 +29242,7 @@ begin
29215
29242
  if not (
29216
29243
  ${allowed(p.scope, `v_booking.${b("tenant")}`, p.manage)}
29217
29244
  or (change_booking.access_token is not null and v_booking.${b("accessHash")} = ${sha256Hex$1("convert_to(change_booking.access_token, 'utf8')")})
29218
- or (change_booking.access_token is null and v_booking.${b("customerUser")} = auth.uid() and ${allowed(p.scope, `v_booking.${b("tenant")}`, p.create)})
29245
+ or (change_booking.access_token is null and coalesce(v_booking.${b("customerUser")} = auth.uid(), false) and ${allowed(p.scope, `v_booking.${b("tenant")}`, p.create)})
29219
29246
  ) then
29220
29247
  ${fail$1("BOOKING_FORBIDDEN", "not allowed to change this booking")}
29221
29248
  end if;
@@ -30273,6 +30300,36 @@ ${lockTable(dates, { read: true })}
30273
30300
  ${readPolicy(dates, datesName, calendarFeatures(ctx).access ? d("event") : d("tenant"))}
30274
30301
  `;
30275
30302
  }
30303
+ function readOnlyRule(ctx) {
30304
+ const raw = ctx.option("readOnly");
30305
+ if (raw === void 0) return;
30306
+ const rule = typeof raw === "object" && raw !== null ? Object.fromEntries(Object.entries(raw)) : {};
30307
+ const column = rule["column"];
30308
+ const given = Array.isArray(rule["values"]) ? rule["values"] : [];
30309
+ const values = given.filter((value) => typeof value === "string");
30310
+ if (typeof column !== "string" || column === "" || values.length === 0 || values.length !== given.length) throw new TypeError("blocks.calendar.options.readOnly must be { column, values } with a column of the events table and at least one value");
30311
+ return {
30312
+ column,
30313
+ values
30314
+ };
30315
+ }
30316
+ function eventGuards(ctx, allowed) {
30317
+ const readOnly = readOnlyRule(ctx);
30318
+ const e = (column) => ctx.col("events", column);
30319
+ return {
30320
+ actionCheck: (action, tenant) => {
30321
+ const key = ctx.config.permissions[action];
30322
+ return key === void 0 ? "" : `
30323
+ if not ${allowed(tenant, sqlString(key))} then
30324
+ ${fail$1("CALENDAR_FORBIDDEN", `not allowed to ${action} calendar events`)}
30325
+ end if;`;
30326
+ },
30327
+ readOnlyCheck: (id) => readOnly === void 0 ? "" : `
30328
+ if auth.role() is distinct from 'service_role' and exists (select 1 from ${ctx.table("events")} x where x.${e("id")} = ${id} and x.${sqlIdent(readOnly.column)}::text = any (array[${readOnly.values.map(sqlString).join(", ")}]::text[])) then
30329
+ ${fail$1("CALENDAR_EVENT_READ_ONLY", "this event is read-only", "42501")}
30330
+ end if;`
30331
+ };
30332
+ }
30276
30333
  //#endregion
30277
30334
  //#region src/sql/modules/calendar-rows.ts
30278
30335
  const STATUSES$1 = "('confirmed', 'tentative', 'cancelled')";
@@ -31096,7 +31153,7 @@ begin
31096
31153
  end if;
31097
31154
  if not (
31098
31155
  ${allowed("set_calendar_working_hours.tenant", manage)}
31099
- or (v_user = auth.uid() and ${ctx.scope.can("set_calendar_working_hours.tenant", read)})
31156
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.scope.can("set_calendar_working_hours.tenant", read)})
31100
31157
  ) then
31101
31158
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to set these working hours")}
31102
31159
  end if;
@@ -31581,7 +31638,8 @@ const CALENDAR_NAMES = {
31581
31638
  "rdates",
31582
31639
  "attendeeKey",
31583
31640
  "calendarDetails",
31584
- "ruleDialect"
31641
+ "ruleDialect",
31642
+ "readOnly"
31585
31643
  ],
31586
31644
  tables: {
31587
31645
  calendars: {
@@ -31672,8 +31730,12 @@ const CALENDAR_NAMES = {
31672
31730
  "owner",
31673
31731
  "rdates"
31674
31732
  ],
31675
- typed: ["status", "visibility"],
31676
- mappable: ["kind", "transparency"]
31733
+ typed: [
31734
+ "status",
31735
+ "visibility",
31736
+ "kind",
31737
+ "transparency"
31738
+ ]
31677
31739
  },
31678
31740
  attendees: {
31679
31741
  name: "calendar_attendees",
@@ -31707,7 +31769,7 @@ const CALENDAR_NAMES = {
31707
31769
  "organizer",
31708
31770
  "optional"
31709
31771
  ],
31710
- mappable: ["role", "response"]
31772
+ typed: ["role", "response"]
31711
31773
  },
31712
31774
  workingHours: WORKING_HOURS_TABLE,
31713
31775
  grants: {
@@ -31814,6 +31876,9 @@ function build$95(ctx) {
31814
31876
  const features = calendarFeatures(ctx);
31815
31877
  const writesCalendar = (calendar, tenant) => features.access ? accessCall(ctx, calendar, "write") : allowed(tenant, write);
31816
31878
  const writesEvent = (event, tenant) => features.access ? eventAccessCall(ctx, event, "write") : allowed(tenant, write);
31879
+ const { actionCheck, readOnlyCheck } = eventGuards(ctx, allowed);
31880
+ const saveChecks = `${actionCheck("create", "v_tenant")}${readOnlyCheck("v_master")}`;
31881
+ const changeChecks = `${actionCheck("update", "v_tenant")}${readOnlyCheck("v_id")}`;
31817
31882
  const recurrence = recurrenceSql(ctx);
31818
31883
  const me = "(select auth.uid())";
31819
31884
  const calendarColumns = `${features.access && ctx.has("calendars", "visibility") ? `
@@ -32148,6 +32213,10 @@ begin
32148
32213
  if v_id is not null and not ${eventAccessCall(ctx, "v_id", "write")} then
32149
32214
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this event")}
32150
32215
  end if;${visibilityCheck("visibility", "('public', 'private')", "CALENDAR_EVENT_INVALID")}` : ""}
32216
+ ${saveChecks === "" && changeChecks === "" ? "" : `
32217
+ if v_id is null then${saveChecks || "\n null;"}
32218
+ else${changeChecks || "\n null;"}
32219
+ end if;`}
32151
32220
  if v_item ? 'status' and v_item ->> 'status' not in ${STATUSES$1} then
32152
32221
  ${fail$1("CALENDAR_EVENT_INVALID", "status must be confirmed, tentative or cancelled", "22023")}
32153
32222
  end if;
@@ -32227,7 +32296,7 @@ begin
32227
32296
  end if;
32228
32297
  if not ${writesEvent("v_id", "v_tenant")} then
32229
32298
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32230
- end if;
32299
+ end if;${actionCheck("delete", "v_tenant")}${readOnlyCheck("v_id")}
32231
32300
  delete from ${events} where ${e("id")} = v_id;
32232
32301
  ${reminderRule(ctx, "delete")}
32233
32302
  ${record("calendar_event.deleted", "v_id", "v_calendar", "v_tenant")}
@@ -32256,7 +32325,7 @@ begin
32256
32325
  end if;
32257
32326
  if not ${writesEvent("v_id", "v_tenant")} then
32258
32327
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32259
- end if;
32328
+ end if;${actionCheck("delete", "v_tenant")}${readOnlyCheck("v_id")}
32260
32329
  ${features.table ? `if not (cancel_calendar_occurrence.original_start = any (${recurrence.exdatesOf("v_id")})) then
32261
32330
  ${addDate(ctx, "v_id", "v_tenant", "exdate", "cancel_calendar_occurrence.original_start")}
32262
32331
  end if;
@@ -32301,7 +32370,7 @@ begin
32301
32370
  end if;
32302
32371
  if not ${writesEvent("v_id", "v_tenant")} then
32303
32372
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32304
- end if;
32373
+ end if;${changeChecks}${actionCheck("create", "v_tenant")}
32305
32374
  if split_calendar_event.split_at <= v_starts or nullif(split_calendar_event.before_rrule, '') is null then
32306
32375
  ${fail$1("CALENDAR_SPLIT_INVALID", "split at a later occurrence, with the rule that ends the series before it", "22023")}
32307
32376
  end if;
@@ -36150,7 +36219,7 @@ function messagingSql(ctx, provider) {
36150
36219
  if (!Number.isInteger(editWindow) || editWindow < 0) throw new TypeError("blocks.messaging.options.editWindow must be 0 (always) or a number of seconds");
36151
36220
  const scheduleQueue = ctx.text("scheduleQueue", "messaging");
36152
36221
  if (!QUEUE$2.test(scheduleQueue)) throw new TypeError("blocks.messaging.options.scheduleQueue must be a lowercase queue name");
36153
- const scoped = registeredSubjects(ctx.subjects, ctx.naming).flatMap((subject) => subject.config.scope === void 0 ? [] : [{
36222
+ const scoped = registeredSubjects$1(ctx.subjects, ctx.naming).flatMap((subject) => subject.config.scope === void 0 ? [] : [{
36154
36223
  type: subject.type,
36155
36224
  scope: subject.config.scope
36156
36225
  }]);
@@ -37487,11 +37556,11 @@ function collectionFunctions(ctx, names) {
37487
37556
  const setExtras = (source, id) => writeExtraColumns(t("collections"), extras, source, `x.${co("id")} = ${id}`);
37488
37557
  const en = (column) => names.c("entries", column);
37489
37558
  const maySee = (alias) => `(${SERVICE$1} or (${ctx.scope.can(`${alias}.${co("tenant")}`, names.read)} and (
37490
- (${alias}.${co("scope")} = 'user' and ${alias}.${co("owner")} = auth.uid())
37559
+ (${alias}.${co("scope")} = 'user' and coalesce(${alias}.${co("owner")} = auth.uid(), false))
37491
37560
  or (${alias}.${co("scope")} = 'team' and ${names.inTeam(`${alias}.${co("team")}`)})
37492
37561
  or ${alias}.${co("scope")} = 'tenant')))`;
37493
37562
  const mayManage = (alias) => `(${SERVICE$1}
37494
- or (${alias}.${co("scope")} = 'user' and ${alias}.${co("owner")} = auth.uid() and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)})
37563
+ or (${alias}.${co("scope")} = 'user' and coalesce(${alias}.${co("owner")} = auth.uid(), false) and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)})
37495
37564
  or (${alias}.${co("scope")} <> 'user' and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.share)}))`;
37496
37565
  const mayFill = (alias) => `(${SERVICE$1} or (${maySee(alias)} and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)}))`;
37497
37566
  const json = (alias) => `jsonb_build_object(
@@ -38428,7 +38497,7 @@ ${renderPolicy(policy$1({
38428
38497
  }
38429
38498
  /** The registry types whose `cascade: true` deletes their entries and stars. */
38430
38499
  function cascading(ctx) {
38431
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.cascade === true).map((subject) => [subject.type, {
38500
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.cascade === true).map((subject) => [subject.type, {
38432
38501
  table: subject.config.table,
38433
38502
  ...subject.config.id === void 0 ? {} : { id: subject.config.id },
38434
38503
  cascade: true,
@@ -38439,7 +38508,7 @@ function build$91(ctx, layout) {
38439
38508
  if (ctx.mode === "custom") return "";
38440
38509
  const keys = moduleOperations("collections");
38441
38510
  const teams = callerTeamIdsSql(ctx, layout);
38442
- const subjectTypes = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0).map((subject) => subject.type);
38511
+ const subjectTypes = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0).map((subject) => subject.type);
38443
38512
  const read = ctx.permission("read", keys.read);
38444
38513
  const names = {
38445
38514
  scope: ctx.scope,
@@ -40235,7 +40304,7 @@ begin
40235
40304
  ${fail$1("EVIDENCE_TASK_NOT_FOUND", "the evidence task isn't a task of this control", "P0002")}
40236
40305
  end if;
40237
40306
  end if;
40238
- if not (${allowed(`v_control.${k("tenant")}`, collect)}${assignee ? ` or (v_task.${t("assignee")} is not null and v_task.${t("assignee")} = auth.uid())` : ""}) then
40307
+ if not (${allowed(`v_control.${k("tenant")}`, collect)}${assignee ? ` or (v_task.${t("assignee")} is not null and coalesce(v_task.${t("assignee")} = auth.uid(), false))` : ""}) then
40239
40308
  ${forbidden("not allowed to collect evidence")}
40240
40309
  end if;
40241
40310
  ${has("evidence", "note") ? `if add_control_evidence.attachment_id is null and nullif(trim(add_control_evidence.note), '') is null then
@@ -44506,7 +44575,7 @@ begin
44506
44575
  if not found then
44507
44576
  ${fail$1("OBLIGATION_NOT_FOUND", "obligation not found", "P0002")}
44508
44577
  end if;
44509
- if not (${allowed(`v_row.${o("tenant")}`, write)} or v_row.${o("owner")} = auth.uid()) then
44578
+ if not (${allowed(`v_row.${o("tenant")}`, write)} or coalesce(v_row.${o("owner")} = auth.uid(), false)) then
44510
44579
  ${forbidden("not allowed to change this obligation")}
44511
44580
  end if;
44512
44581
  if set_obligation_status.status is null or set_obligation_status.status not in ('open', 'done', 'waived') then
@@ -44806,7 +44875,7 @@ ${renderPolicy(policy$1({
44806
44875
  /** Moves the contracts of a merged counterparty to the record it merged into. */
44807
44876
  function counterpartyMerges(ctx) {
44808
44877
  if (!keepsContract(ctx, "counterpartyType")) return "";
44809
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
44878
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
44810
44879
  table: `${subject.schema}.${subject.table}`,
44811
44880
  extra: {}
44812
44881
  }]), moveSubjectRows({
@@ -45807,7 +45876,7 @@ begin
45807
45876
  if v_user is distinct from auth.uid() and not ${q.allowed(`v_course.${c("tenant")}`, q.enroll)} then
45808
45877
  ${q.forbidden("not allowed to enroll others in courses")}
45809
45878
  end if;
45810
- if v_user = auth.uid() and not (${q.allowed(`v_course.${c("tenant")}`, q.read)} or ${q.allowed(`v_course.${c("tenant")}`, q.enroll)}) then
45879
+ if coalesce(v_user = auth.uid(), false) and not (${q.allowed(`v_course.${c("tenant")}`, q.read)} or ${q.allowed(`v_course.${c("tenant")}`, q.enroll)}) then
45811
45880
  ${q.forbidden("not allowed to enroll in courses")}
45812
45881
  end if;
45813
45882
  if v_course.${c("status")} <> 'published' then
@@ -46778,7 +46847,7 @@ function keyedFields(ctx, keys, options) {
46778
46847
  s("label"),
46779
46848
  ctx.cast("values", "type", "v_type"),
46780
46849
  ...assignments.map(([, expression]) => expression),
46781
- ...ctx.has("values", "rank") ? [rankValue(s("rank"))] : []
46850
+ ...ctx.has("values", "rank") ? [integerRank ? `coalesce(${rankValue(s("rank"))}, (select coalesce(max(v.${c("rank")}), 0) + 1 from ${values} v where v.${c("tenant")} = ${s("tenant")} and ${subjectMatch(ctx, "v", s("subject_type"), s("subject_id"))}))` : rankValue(s("rank"))] : []
46782
46851
  ];
46783
46852
  const updates = [
46784
46853
  `${c("label")} = ${s("label")}`,
@@ -49093,7 +49162,7 @@ begin
49093
49162
  if v_row.${cd("tenant")} is null then
49094
49163
  return null;
49095
49164
  end if;
49096
- if not (${SERVICE_CALLER$1} or ${requested("requestedBy") ? `v_row.${cd("requestedBy")} = auth.uid() or ` : ""}${allowed})${platform} then
49165
+ if not (${SERVICE_CALLER$1} or ${requested("requestedBy") ? `coalesce(v_row.${cd("requestedBy")} = auth.uid(), false) or ` : ""}${allowed})${platform} then
49097
49166
  ${fail$1("ORGANIZATION_DELETION_FORBIDDEN", "You may not cancel this deletion")}
49098
49167
  end if;
49099
49168
  update ${d} x set ${cd("cancelledAt")} = now()
@@ -50058,7 +50127,7 @@ function dealFunctions(ctx, n) {
50058
50127
  const stages = pipelines.table("stages");
50059
50128
  const s = (column) => pipelines.col("stages", column);
50060
50129
  const rotting = pipelines.has("stages", "rottingAfterDays") ? `st.${s("rottingAfterDays")} is not null and now() - coalesce(x.${d("stageEnteredAt")}, x.${d("createdAt")}) > make_interval(days => st.${s("rottingAfterDays")})` : "false";
50061
- const editable = (alias) => `(${n.service} or (${ctx.scope.can(`${alias}.${d("tenant")}`, n.write)} and (${n.readAll ? "true" : "false"} or ${alias}.${d("owner")} = auth.uid()
50130
+ const editable = (alias) => `(${n.service} or (${ctx.scope.can(`${alias}.${d("tenant")}`, n.write)} and (${n.readAll ? "true" : "false"} or coalesce(${alias}.${d("owner")} = auth.uid(), false)
50062
50131
  or ${ctx.scope.can(`${alias}.${d("tenant")}`, n.manage)}
50063
50132
  or exists (select 1 from ${t("members")} mm where mm.${m("deal")} = ${alias}.${d("id")} and mm.${m("user")} = auth.uid()))))`;
50064
50133
  const has = (column) => n.has("deals", column);
@@ -51674,7 +51743,7 @@ function functions$10(ctx, extras) {
51674
51743
  const { assets, bookings, catalog, inventory } = linked(ctx);
51675
51744
  const fields = extraFieldsArg(extras);
51676
51745
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
51677
- const worker = (row) => `(${allowed(`${row}.${w("tenant")}`, manage)} or (${row}.${w("technician")} = auth.uid() and ${ctx.can("tenant", `${row}.${w("tenant")}`, work)}))`;
51746
+ const worker = (row) => `(${allowed(`${row}.${w("tenant")}`, manage)} or (coalesce(${row}.${w("technician")} = auth.uid(), false) and ${ctx.can("tenant", `${row}.${w("tenant")}`, work)}))`;
51678
51747
  const busy = list$6(BUSY);
51679
51748
  const orderJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${w("id")}, 'organizationId', ${row}.${w("tenant")}::text, 'title', ${row}.${w("title")}, 'description', ${or("workOrders", row, "description")}, 'priority', ${row}.${w("priority")}, 'status', ${row}.${w("status")}, 'technicianId', ${row}.${w("technician")}, 'startsAt', ${row}.${w("startsAt")}, 'endsAt', ${row}.${w("endsAt")}, 'day', (${row}.${w("startsAt")} at time zone ${zone})::date, 'locationId', ${row}.${w("location")}, 'assetId', ${row}.${w("asset")}, 'bookingId', ${or("workOrders", row, "booking")}, 'subjectType', ${row}.${w("subjectType")}, 'subjectId', ${row}.${w("subjectId")}, 'address', ${or("workOrders", row, "address")}, 'enRouteAt', ${or("workOrders", row, "enRouteAt")}, 'arrivedAt', ${or("workOrders", row, "arrivedAt")}, 'completedAt', ${row}.${w("completedAt")}, 'cancelledAt', ${row}.${w("cancelledAt")}, 'cancelReason', ${or("workOrders", row, "cancelReason")}, 'completionNote', ${or("workOrders", row, "completionNote")}, 'createdBy', ${row}.${w("createdBy")}, 'createdAt', ${row}.${w("createdAt")}, 'updatedAt', ${row}.${w("updatedAt")})`, row, extras);
51680
51749
  const partJson = (row) => `jsonb_build_object('id', ${row}.${q("id")}, 'organizationId', ${row}.${q("tenant")}::text, 'workOrderId', ${row}.${q("workOrder")}, 'name', ${row}.${q("name")}, 'quantity', ${row}.${q("quantity")}::text, 'unit', ${or("parts", row, "unit")}, 'assetId', ${row}.${q("asset")}, 'variantId', ${row}.${q("variant")}, 'locationId', ${row}.${q("location")}, 'recordedBy', ${row}.${q("recordedBy")}, 'createdAt', ${row}.${q("createdAt")})`;
@@ -52130,7 +52199,7 @@ declare
52130
52199
  begin
52131
52200
  if v_technician is null or not (
52132
52201
  ${allowed("technician_day.tenant", read)}
52133
- or (v_technician = auth.uid() and ${ctx.can("tenant", "technician_day.tenant", work)})
52202
+ or (coalesce(v_technician = auth.uid(), false) and ${ctx.can("tenant", "technician_day.tenant", work)})
52134
52203
  ) then
52135
52204
  ${fail$1("DISPATCH_FORBIDDEN", "not allowed to read this technician's day")}
52136
52205
  end if;
@@ -52178,7 +52247,7 @@ declare
52178
52247
  begin
52179
52248
  if plan_dispatch_route.technician is null or not (
52180
52249
  ${allowed("plan_dispatch_route.tenant", manage)}
52181
- or (plan_dispatch_route.technician = auth.uid() and ${ctx.can("tenant", "plan_dispatch_route.tenant", work)})
52250
+ or (coalesce(plan_dispatch_route.technician = auth.uid(), false) and ${ctx.can("tenant", "plan_dispatch_route.tenant", work)})
52182
52251
  ) then
52183
52252
  ${fail$1("DISPATCH_FORBIDDEN", "not allowed to plan this technician's route")}
52184
52253
  end if;
@@ -52298,7 +52367,7 @@ begin
52298
52367
  select * into v_row from ${parts} y where y.${q("id")} = remove_work_order_part.part_id for update;
52299
52368
  if not found or not (
52300
52369
  ${allowed(`v_row.${q("tenant")}`, manage)}
52301
- or (v_row.${q("recordedBy")} = auth.uid() and ${ctx.can("tenant", `v_row.${q("tenant")}`, work)})
52370
+ or (coalesce(v_row.${q("recordedBy")} = auth.uid(), false) and ${ctx.can("tenant", `v_row.${q("tenant")}`, work)})
52302
52371
  ) then
52303
52372
  return false;
52304
52373
  end if;
@@ -52314,7 +52383,7 @@ ${userGrant(`${fn("remove_work_order_part")}(uuid)`)}
52314
52383
  * into.
52315
52384
  */
52316
52385
  function workOrderMerges(ctx) {
52317
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
52386
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
52318
52387
  table: `${subject.schema}.${subject.table}`,
52319
52388
  extra: {}
52320
52389
  }]), moveSubjectRows({
@@ -52991,14 +53060,14 @@ begin
52991
53060
  if found then
52992
53061
  select * into v_doc from ${documents} d where d.${c("id")} = v_suggestion.${g("document")};
52993
53062
  end if;
52994
- if v_suggestion.${g("id")} is null or not (${SERVICE_CALLER$1} or ${canRead("v_doc")} or v_suggestion.${g("createdBy")} = auth.uid()) then
53063
+ if v_suggestion.${g("id")} is null or not (${SERVICE_CALLER$1} or ${canRead("v_doc")} or coalesce(v_suggestion.${g("createdBy")} = auth.uid(), false)) then
52995
53064
  ${fail$1("DOCUMENT_SUGGESTION_NOT_FOUND", "suggestion not found", "P0002")}
52996
53065
  end if;
52997
53066
  if decide_document_suggestion.decision is null or decide_document_suggestion.decision not in ('accepted', 'rejected', 'withdrawn') then
52998
53067
  ${fail$1("DOCUMENT_SUGGESTION_INVALID", "decide with accepted, rejected or withdrawn", "22023")}
52999
53068
  end if;
53000
53069
  if decide_document_suggestion.decision = 'withdrawn' then
53001
- if not (${SERVICE_CALLER$1} or v_suggestion.${g("createdBy")} = auth.uid()) then
53070
+ if not (${SERVICE_CALLER$1} or coalesce(v_suggestion.${g("createdBy")} = auth.uid(), false)) then
53002
53071
  ${fail$1("DOCUMENT_FORBIDDEN", "only the author can withdraw a suggestion")}
53003
53072
  end if;
53004
53073
  elsif not (${SERVICE_CALLER$1} or ${canWrite("v_doc")}) then
@@ -55355,7 +55424,7 @@ ${ctx.has("donations", "refundTransaction") ? `create index if not exists ${inde
55355
55424
  }
55356
55425
  /** Moves a merged donor's gifts, pledges and receipts to the record kept. */
55357
55426
  function donorMerges(ctx) {
55358
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
55427
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
55359
55428
  table: `${subject.schema}.${subject.table}`,
55360
55429
  extra: {}
55361
55430
  }]);
@@ -57479,7 +57548,7 @@ function choice(ctx, name, values) {
57479
57548
  return value;
57480
57549
  }
57481
57550
  function candidateSubjectIdType(ctx, candidate) {
57482
- return registeredSubjects(ctx.subjects, ctx.naming).find((item) => item.type === candidate)?.config.idType ?? "text";
57551
+ return registeredSubjects$1(ctx.subjects, ctx.naming).find((item) => item.type === candidate)?.config.idType ?? "text";
57483
57552
  }
57484
57553
  function reviewable(check, editable, from) {
57485
57554
  return check === void 0 ? `(${editable})` : `(${editable} or exists (
@@ -58218,17 +58287,16 @@ function employeeFunctions(ctx, n) {
58218
58287
  ...list.map((field) => e(field.column)),
58219
58288
  e("status"),
58220
58289
  ...origin ? [e("originType"), e("originId")] : [],
58221
- ...has("createdBy") ? [e("createdBy")] : [],
58222
- ...n.extras.map((extra) => extra.ident)
58290
+ ...has("createdBy") ? [e("createdBy")] : []
58223
58291
  ];
58224
58292
  const insertValues = [
58225
58293
  "create_employee.tenant",
58226
58294
  ...list.map((field) => field.column === "employmentType" ? ctx.cast("employees", "employmentType", `coalesce(${typeText(`create_employee.attrs -> 'employmentType'`)}, (${n.types})[1])`) : attr(field)),
58227
58295
  ctx.cast("employees", "status", "v_status"),
58228
58296
  ...origin ? ["create_employee.attrs -> 'origin' ->> 'type'", "create_employee.attrs -> 'origin' ->> 'id'"] : [],
58229
- ...has("createdBy") ? ["auth.uid()"] : [],
58230
- ...n.extras.map((extra) => extraValue("create_employee.attrs", extra.ident))
58297
+ ...has("createdBy") ? ["auth.uid()"] : []
58231
58298
  ];
58299
+ const extrasInsert = insertExtraColumns(table, n.extras, "create_employee.attrs");
58232
58300
  const existing = origin ? `
58233
58301
  if create_employee.attrs -> 'origin' ->> 'id' is not null then
58234
58302
  select * into v_row from ${table} x
@@ -58288,8 +58356,8 @@ begin
58288
58356
  if v_status = 'offboarded' then
58289
58357
  ${fail$1("EMPLOYEE_STATUS_INVALID", "create the employee, then offboard them", "22023")}
58290
58358
  end if;
58291
- insert into ${table} (${insertColumns.join(", ")})
58292
- values (${insertValues.join(", ")})
58359
+ insert into ${table} (${insertColumns.join(", ")}${extrasInsert.columns})
58360
+ values (${insertValues.join(", ")}${extrasInsert.values})
58293
58361
  returning * into v_row;
58294
58362
  exception
58295
58363
  when unique_violation then
@@ -58627,13 +58695,13 @@ const CONTACT_KEYS = {
58627
58695
  function sensitiveFunctions(ctx, n) {
58628
58696
  const e = (column) => n.c("employees", column);
58629
58697
  const employees = n.t("employees");
58630
- const reader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.sensitive)} or ${alias}.${e("user")} = auth.uid())`;
58698
+ const reader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.sensitive)} or coalesce(${alias}.${e("user")} = auth.uid(), false))`;
58631
58699
  const load = (fnName, arg, allowed) => `
58632
58700
  select * into v_employee from ${employees} x where x.${e("id")} = ${fnName}.${arg};
58633
58701
  if v_employee.${e("id")} is null or not ${allowed} then
58634
58702
  ${fail$1("EMPLOYEE_NOT_FOUND", "no such employee whose details you can see", "P0002")}
58635
58703
  end if;`;
58636
- const contractReader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.contractsRead)} or ${alias}.${e("user")} = auth.uid())`;
58704
+ const contractReader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.contractsRead)} or coalesce(${alias}.${e("user")} = auth.uid(), false))`;
58637
58705
  return `${privateSql(ctx, n, reader, load)}${contractsSql(ctx, n, contractReader, load)}`;
58638
58706
  }
58639
58707
  function privateSql(ctx, n, reader, load) {
@@ -58702,7 +58770,7 @@ as $$
58702
58770
  declare
58703
58771
  v_employee ${n.t("employees")};
58704
58772
  v_row ${table};
58705
- begin${load("save_employee_private_details", "employee", n.privateDetailsWrite === void 0 ? reader("v_employee") : `(${n.service} or (${ctx.scope.can(`v_employee.${e("tenant")}`, n.sensitive)} and ${ctx.scope.can(`v_employee.${e("tenant")}`, n.privateDetailsWrite)}) or v_employee.${e("user")} = auth.uid())`)}
58773
+ begin${load("save_employee_private_details", "employee", n.privateDetailsWrite === void 0 ? reader("v_employee") : `(${n.service} or (${ctx.scope.can(`v_employee.${e("tenant")}`, n.sensitive)} and ${ctx.scope.can(`v_employee.${e("tenant")}`, n.privateDetailsWrite)}) or coalesce(v_employee.${e("user")} = auth.uid(), false))`)}
58706
58774
  if jsonb_typeof(coalesce(save_employee_private_details.attrs, '{}')) <> 'object' then
58707
58775
  ${fail$1("EMPLOYEE_PRIVATE_INVALID", "attrs must be an object", "22023")}
58708
58776
  end if;
@@ -58857,7 +58925,7 @@ function editContractsSql(ctx, n, names) {
58857
58925
  patch("endsOn", "endsOn", `(${text("endsOn")})::date`),
58858
58926
  patch("hoursPerWeek", "hoursPerWeek", `(${text("hoursPerWeek")})::numeric`),
58859
58927
  ...has("salary") ? [patch("salary", "salary", salaryValue(text("salary"), has("currency") ? `coalesce(upper(${text("currency")}), x.${k("currency")})` : "null"))] : [],
58860
- ...has("currency") ? [`${k("currency")} = case when ${attrs} ? 'salary' or ${attrs} ? 'currency' then upper(${text("currency")}) else x.${k("currency")} end`] : [],
58928
+ ...has("currency") ? [`${k("currency")} = case when ${attrs} ? 'currency' then upper(${text("currency")})${ctx.owns("contracts") ? ` when ${attrs} ? 'salary' and ${text("salary")} is null then null` : ""} else x.${k("currency")} end`] : [],
58861
58929
  ...has("salaryPeriod") ? [patch("salaryPeriod", "salaryPeriod", ctx.cast("contracts", "salaryPeriod", text("salaryPeriod")))] : [],
58862
58930
  ...has("note") ? [patch("note", "note", `nullif(trim(${text("note")}), '')`)] : []
58863
58931
  ];
@@ -59916,7 +59984,7 @@ function enrollmentsFunctions(ctx) {
59916
59984
  ["steps", "enrollment_ensure.steps"],
59917
59985
  ["enrolledBy", "enrollment_ensure.actor"]
59918
59986
  ].filter(([column]) => ctx.has("enrollments", column));
59919
- const self = (row) => `(${row}.${e("user")} is not null and ${row}.${e("user")} = auth.uid())`;
59987
+ const self = (row) => `(${row}.${e("user")} is not null and coalesce(${row}.${e("user")} = auth.uid(), false))`;
59920
59988
  const programJson = (row) => `jsonb_build_object('id', ${row}.${p("id")}, 'organizationId', ${row}.${p("tenant")}, 'key', ${row}.${p("key")}, 'name', ${row}.${p("name")}, 'description', ${field("programs", row, "description")}, 'subjectTypes', to_jsonb(${row}.${p("subjectTypes")}), 'steps', ${row}.${p("steps")}, 'enabled', ${row}.${p("enabled")}, 'version', ${row}.${p("version")}, 'createdBy', ${field("programs", row, "createdBy")}, 'createdAt', ${field("programs", row, "createdAt")}, 'updatedAt', ${field("programs", row, "updatedAt")})`;
59921
59989
  const programRecord = (type, row, summary) => ctx.record({
59922
59990
  type,
@@ -60294,7 +60362,7 @@ as $$
60294
60362
  declare
60295
60363
  v_id uuid;
60296
60364
  begin
60297
- if not (${allowed("enrollment.tenant", read)} or (enrollment.subject_type = 'user' and enrollment.subject_id = auth.uid()::text)) then
60365
+ if not (${allowed("enrollment.tenant", read)} or (enrollment.subject_type = 'user' and coalesce(enrollment.subject_id = auth.uid()::text, false))) then
60298
60366
  ${forbidden("not allowed to read enrollments")}
60299
60367
  end if;
60300
60368
  select x.${e("id")} into v_id from ${enrollments} x
@@ -61263,7 +61331,7 @@ function expensesFunctions(ctx) {
61263
61331
  end if;
61264
61332
  select * into v_approval from ${ar} p where p.${a("id")} = v_row.${r("approval")};`;
61265
61333
  const ownerOnly = `
61266
- if not (v_row.${r("user")} = auth.uid() and ${ctx.can("tenant", `v_row.${r("tenant")}`, submit)}) then
61334
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) and ${ctx.can("tenant", `v_row.${r("tenant")}`, submit)}) then
61267
61335
  ${forbidden("only the member who owns the report can change it")}
61268
61336
  end if;`;
61269
61337
  const editable = `
@@ -61271,7 +61339,7 @@ function expensesFunctions(ctx) {
61271
61339
  ${fail$1("EXPENSE_REPORT_LOCKED", "only a draft or rejected report can change", "55000")}
61272
61340
  end if;`;
61273
61341
  const reader = `
61274
- if not (v_row.${r("user")} = auth.uid() or ${can(`v_row.${r("tenant")}`, read)}) then
61342
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) or ${can(`v_row.${r("tenant")}`, read)}) then
61275
61343
  ${fail$1("EXPENSE_REPORT_NOT_FOUND", "no such expense report", "P0002")}
61276
61344
  end if;`;
61277
61345
  const categoryCheck = (category, tenant) => `
@@ -61662,7 +61730,7 @@ declare
61662
61730
  v_row ${reports}%rowtype;
61663
61731
  v_approval ${ar}%rowtype;
61664
61732
  begin${loadReport("cancel_expense_report.report_id", true)}
61665
- if not (v_row.${r("user")} = auth.uid() or ${can(`v_row.${r("tenant")}`, manage)}) then
61733
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) or ${can(`v_row.${r("tenant")}`, manage)}) then
61666
61734
  ${forbidden("not allowed to cancel this expense report")}
61667
61735
  end if;
61668
61736
  if ${status("v_row", "v_approval")} not in ('draft', 'submitted', 'rejected') then
@@ -61712,7 +61780,7 @@ begin
61712
61780
  if not (v_reader or ${ctx.can("tenant", "list_expense_reports.tenant", submit)}) then
61713
61781
  ${forbidden("not allowed to list expense reports")}
61714
61782
  end if;
61715
- if not v_reader and (coalesce(list_expense_reports.everyone, false) or (list_expense_reports.user_id is not null and list_expense_reports.user_id <> auth.uid())) then
61783
+ if not v_reader and (coalesce(list_expense_reports.everyone, false) or (list_expense_reports.user_id is not null and list_expense_reports.user_id is distinct from auth.uid())) then
61716
61784
  ${forbidden("not allowed to read another member's expenses")}
61717
61785
  end if;
61718
61786
  return (
@@ -62144,7 +62212,7 @@ const COLUMN$5 = /^[a-z_][a-z0-9_]{0,62}$/u;
62144
62212
  * `config.subjects`.
62145
62213
  */
62146
62214
  function historyBindings(ctx) {
62147
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
62215
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
62148
62216
  return Object.entries(onSettings(ctx)).map(([type, settings]) => {
62149
62217
  const where = `blocks.field-history.on.${type}`;
62150
62218
  const subject = registry.find((item) => item.type === type);
@@ -64649,7 +64717,7 @@ begin
64649
64717
  if not found then
64650
64718
  ${submissionNotFound}
64651
64719
  end if;
64652
- if not (${SERVICE_CALLER$1} or v_row.${s("respondent")} = auth.uid() or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}) then
64720
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${s("respondent")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}) then
64653
64721
  ${submissionNotFound}
64654
64722
  end if;
64655
64723
  return ${submissionJson("v_row")};
@@ -64742,7 +64810,7 @@ begin
64742
64810
  ${submissionNotFound}
64743
64811
  end if;
64744
64812
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}
64745
- or (v_row.${s("respondent")} = auth.uid() and v_row.${s("status")} = 'draft')) then
64813
+ or (coalesce(v_row.${s("respondent")} = auth.uid(), false) and v_row.${s("status")} = 'draft')) then
64746
64814
  ${fail$1("FORM_FORBIDDEN", "not allowed to delete this submission")}
64747
64815
  end if;
64748
64816
  delete from ${submissions} x where x.${s("id")} = delete_form_submission.submission_id;
@@ -64858,7 +64926,7 @@ function ledgerFunctions(ctx) {
64858
64926
  const hasMemo = ctx.has("transactions", "memo");
64859
64927
  const memo = (row) => hasMemo ? `${row}.${t("memo")}` : "null::text";
64860
64928
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
64861
- const visible = (row) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", `${row}.${a("tenant")}`, read)} or ${row}.${a("owner")} = auth.uid() or (${row}.${a("readPermission")} is not null and ${ctx.can("tenant", `${row}.${a("tenant")}`, `${row}.${a("readPermission")}`)}))`;
64929
+ const visible = (row) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", `${row}.${a("tenant")}`, read)} or coalesce(${row}.${a("owner")} = auth.uid(), false) or (${row}.${a("readPermission")} is not null and ${ctx.can("tenant", `${row}.${a("tenant")}`, `${row}.${a("readPermission")}`)}))`;
64862
64930
  const forbidden = (message) => fail$1("LEDGER_FORBIDDEN", message);
64863
64931
  const invalid = (code, message) => fail$1(code, message, "22023");
64864
64932
  const accountJson = (row, balance) => `jsonb_build_object('id', ${row}.${a("id")}, 'organizationId', ${row}.${a("tenant")}, 'kind', ${row}.${a("kind")}, 'code', ${row}.${a("code")}, 'name', ${row}.${a("name")}, 'unit', ${row}.${a("unit")}, 'scale', ${row}.${a("scale")}, 'holderType', ${row}.${a("holderType")}, 'holderId', ${row}.${a("holderId")}, 'ownerId', ${row}.${a("owner")}, 'allowNegative', ${row}.${a("allowNegative")}, 'readPermission', ${row}.${a("readPermission")}, 'managedBy', ${row}.${a("managedBy")}, 'metadata', ${row}.${a("metadata")}, 'closedAt', ${row}.${a("closedAt")}, 'createdAt', ${row}.${a("createdAt")}, 'balance', coalesce(${balance}.${b("balance")}, 0)::text, 'held', coalesce(${balance}.${b("held")}, 0)::text, 'available', coalesce(${balance}.${b("balance")} - ${balance}.${b("held")}, 0)::text)`;
@@ -67084,7 +67152,7 @@ ${tables$19(ctx)}${functions$7(ctx, layout)}${grantMerges(ctx)}`;
67084
67152
  }
67085
67153
  /** Moves the grants on a merged registered subject to the record it merged into. */
67086
67154
  function grantMerges(ctx) {
67087
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
67155
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
67088
67156
  table: `${subject.schema}.${subject.table}`,
67089
67157
  extra: {}
67090
67158
  }]), moveSubjectRows({
@@ -70611,7 +70679,7 @@ declare
70611
70679
  v_before uuid;${notifyDeclare}
70612
70680
  begin
70613
70681
  ${loadConversation("assign_conversation.conversation")}
70614
- if not (${service} or ${command("assign", "assign")} or (assignee = (select auth.uid()) and ${staffCan("reply")})) then
70682
+ if not (${service} or ${command("assign", "assign")} or (coalesce(assignee = (select auth.uid()), false) and ${staffCan("reply")})) then
70615
70683
  ${forbidden("not allowed to assign this conversation")}
70616
70684
  end if;
70617
70685
  if assignee is not null and not ${ctx.scope.canUser("assignee", `v_conv.${cv("tenant")}`, q.key("read"))} then
@@ -70776,7 +70844,7 @@ begin
70776
70844
  if not found then
70777
70845
  ${missing("message", "MESSAGE_NOT_FOUND")}
70778
70846
  end if;
70779
- if not (${service} or (v_msg.${cm("author")} is not null and v_msg.${cm("author")} = (select auth.uid()))) then
70847
+ if not (${service} or (v_msg.${cm("author")} is not null and coalesce(v_msg.${cm("author")} = (select auth.uid()), false))) then
70780
70848
  ${forbidden("only the author edits a message")}
70781
70849
  end if;
70782
70850
  if v_msg.${cm("deletedAt")} is not null then
@@ -75014,7 +75082,7 @@ function build$56(ctx, layout) {
75014
75082
  const restoring = ctx.flag("restore", false);
75015
75083
  const derivedSlug = "trim(both '-' from regexp_replace(lower(create_team.name), '[^a-z0-9]+', '-', 'g'))";
75016
75084
  const drops = (fn, head, tails) => tails.map((tail) => `drop function if exists ${fn}(${head}${tail});`).join("\n");
75017
- const teamJson = (alias) => `jsonb_build_object('id', ${alias}.${id}, 'slug', ${alias}.${slug}${extraFieldsJson(alias, extras)})`;
75085
+ const teamJson = (alias) => `jsonb_build_object('id', ${alias}.${id}, 'name', ${alias}.${name}, 'slug', ${alias}.${slug}, 'description', ${alias}.${description}, 'status', ${alias}.${status}${extraFieldsJson(alias, extras)})`;
75018
75086
  const idDefault = idType === "uuid" ? " default gen_random_uuid()" : " generated always as identity";
75019
75087
  const tables = ctx.manages ? `create table if not exists ${teams} (
75020
75088
  ${id} ${idType} primary key${idDefault},
@@ -75093,7 +75161,8 @@ ${patching ? drops(fn("create_team"), `${ctx.idType}, text, text`, [
75093
75161
  "",
75094
75162
  ", jsonb",
75095
75163
  extras.length === 0 ? ", text, jsonb" : ", text"
75096
- ]) : extra.drop(fn("create_team"), `${ctx.idType}, text, text`)}
75164
+ ]) : `${extra.drop(fn("create_team"), `${ctx.idType}, text, text`)}
75165
+ ${drops(fn("create_team"), `${ctx.idType}, text, text`, [", text", ", text, jsonb"])}`}
75097
75166
  create or replace function ${fn("create_team")}(tenant ${ctx.idType}, name text, description text${patching ? ", slug text default null" : ""}${extra.param})
75098
75167
  returns jsonb
75099
75168
  language plpgsql
@@ -75159,7 +75228,7 @@ ${patching ? ` if update_team.patch is not null and (jsonb_typeof(update_team.p
75159
75228
  ${updatedAt} = now()`}
75160
75229
  where t.${id} = update_team.team;${writeExtraColumns(teams, extras, "update_team.fields", `x.${id} = update_team.team`)}
75161
75230
  ${record$1(ctx, "team.updated", "update_team.team", "v_tenant", "update_team.name")}
75162
- return ${extras.length === 0 ? "jsonb_build_object('id', update_team.team)" : `(select ${teamJson("x")} from ${teams} x where x.${id} = update_team.team)`};
75231
+ return (select ${teamJson("x")} from ${teams} x where x.${id} = update_team.team);
75163
75232
  end;
75164
75233
  $$;
75165
75234
  ${userGrant(`${fn("update_team")}(${idType}, text, text${patching ? ", jsonb" : ""}${extra.type})`)}
@@ -75294,8 +75363,14 @@ as $$
75294
75363
  'id', t.${id},
75295
75364
  'name', t.${name},
75296
75365
  'slug', t.${slug},
75297
- 'status', t.${status}${extraFieldsJson("t", extras)}
75298
- )), '[]'::jsonb)
75366
+ 'description', t.${description},
75367
+ 'status', t.${status},
75368
+ 'member_ids', coalesce((
75369
+ select jsonb_agg(m.${memberUser} order by m.${memberCreated})
75370
+ from ${members} m
75371
+ where m.${memberTeam} = t.${id}
75372
+ ), '[]'::jsonb)${extraFieldsJson("t", extras)}
75373
+ ) order by t.${name}), '[]'::jsonb)
75299
75374
  from ${teams} t
75300
75375
  where t.${tenant} = list_teams.tenant
75301
75376
  and (
@@ -75316,7 +75391,8 @@ function membershipFk(ctx, members, tenant, user) {
75316
75391
  alter table ${members}
75317
75392
  add constraint ${ctx.naming.rename("team_members_membership_fkey")}
75318
75393
  foreign key (${tenant}, ${user})
75319
- references ${memberships.table("memberships")} (${memberships.col("memberships", "tenant")}, ${memberships.col("memberships", "user")});`;
75394
+ references ${memberships.table("memberships")} (${memberships.col("memberships", "tenant")}, ${memberships.col("memberships", "user")})
75395
+ on delete cascade;`;
75320
75396
  }
75321
75397
  function membershipCheck(ctx, tenant, user) {
75322
75398
  if (!ctx.installed("memberships")) return "";
@@ -76234,6 +76310,147 @@ as $$
76234
76310
  $$;`;
76235
76311
  }
76236
76312
  //#endregion
76313
+ //#region src/sql/modules/permissions-roles.ts
76314
+ /**
76315
+ * `list_roles` and `set_permission_override`: the catalog's tenant roles with
76316
+ * their keys in one tenant, and the per-tenant grant or deny of one key. Only
76317
+ * the catalog model with the overrides table renders them.
76318
+ */
76319
+ const rendersRoleFunctions = (ctx) => accessModel(ctx) === "catalog" && ctx.hasTable("overrides");
76320
+ function catalogRoleFunctions(ctx) {
76321
+ const id = ctx.idType;
76322
+ if (!rendersRoleFunctions(ctx)) return `
76323
+ drop function if exists ${ctx.fn("list_roles")}(${id});
76324
+ drop function if exists ${ctx.fn("set_permission_override")}(${id}, text, text, boolean);`;
76325
+ const members = ctx.of("memberships");
76326
+ const m = members.table("memberships");
76327
+ const mTenant = members.col("memberships", "tenant");
76328
+ const mUser = members.col("memberships", "user");
76329
+ const mRole = members.col("memberships", "role");
76330
+ const roles = ctx.table("roles");
76331
+ const rId = ctx.col("roles", "id");
76332
+ const rKey = ctx.col("roles", "key");
76333
+ const perms = ctx.table("permissions");
76334
+ const pId = ctx.col("permissions", "id");
76335
+ const pKey = ctx.col("permissions", "key");
76336
+ const rp = ctx.table("rolePermissions");
76337
+ const rpRole = ctx.col("rolePermissions", "role");
76338
+ const rpPermission = ctx.col("rolePermissions", "permission");
76339
+ const o = ctx.table("overrides");
76340
+ const oTenant = ctx.col("overrides", "tenant");
76341
+ const oRole = ctx.col("overrides", "role");
76342
+ const oPermission = ctx.col("overrides", "permission");
76343
+ const oGranted = ctx.col("overrides", "granted");
76344
+ const listKey = ctx.permission("listRoles", OPERATIONS["permissions.listRoles"]);
76345
+ const manageKey = ctx.permission("setOverride", OPERATIONS["permissions.setOverride"]);
76346
+ const tenantRole = roleScopeIs(ctx, "r", "tenant");
76347
+ const scoped = tenantRole ? ` and ${tenantRole}` : "";
76348
+ const memberCan = (tenant, key) => `coalesce(better_supabase.member_can(auth.uid(), ${tenant}, ${key}), false)`;
76349
+ const roleJson = (tenant) => `jsonb_build_object(
76350
+ 'id', r.${rId},
76351
+ 'key', r.${rKey},
76352
+ 'members', (select count(*) from ${m} mm where mm.${mTenant} = ${tenant} and mm.${mRole} = r.${rId}),
76353
+ 'default_permissions', coalesce((
76354
+ select jsonb_agg(p.${pKey} order by p.${pKey})
76355
+ from ${rp} x join ${perms} p on p.${pId} = x.${rpPermission}
76356
+ where x.${rpRole} = r.${rId}
76357
+ ), '[]'::jsonb),
76358
+ 'permissions', coalesce((
76359
+ select jsonb_agg(p.${pKey} order by p.${pKey})
76360
+ from ${perms} p
76361
+ where coalesce(
76362
+ (select bool_and(ov.${oGranted}) from ${o} ov
76363
+ where ov.${oTenant} = ${tenant} and ov.${oRole} = r.${rId} and ov.${oPermission} = p.${pId}),
76364
+ exists (select 1 from ${rp} x where x.${rpRole} = r.${rId} and x.${rpPermission} = p.${pId})
76365
+ )
76366
+ ), '[]'::jsonb),
76367
+ 'overrides', coalesce((
76368
+ select jsonb_agg(jsonb_build_object('permission', p.${pKey}, 'granted', ov.${oGranted}) order by p.${pKey})
76369
+ from ${o} ov join ${perms} p on p.${pId} = ov.${oPermission}
76370
+ where ov.${oTenant} = ${tenant} and ov.${oRole} = r.${rId}
76371
+ ), '[]'::jsonb)
76372
+ )`;
76373
+ return `
76374
+ -- The tenant roles of the catalog with their keys in one tenant: the role's
76375
+ -- defaults, the keys after this tenant's overrides, the overrides and how many
76376
+ -- members hold the role.
76377
+ create or replace function ${ctx.fn("list_roles")}(tenant ${id})
76378
+ returns jsonb
76379
+ language plpgsql
76380
+ stable
76381
+ security definer
76382
+ set search_path = ''
76383
+ as $$
76384
+ begin
76385
+ if not (${SERVICE_CALLER$1} or ${memberCan("list_roles.tenant", listKey)}) then
76386
+ ${fail$1("PERMISSIONS_FORBIDDEN", "Not allowed to read roles")}
76387
+ end if;
76388
+ return coalesce((
76389
+ select jsonb_agg(${roleJson("list_roles.tenant")} order by r.${rKey})
76390
+ from ${roles} r
76391
+ where true${scoped}
76392
+ ), '[]'::jsonb);
76393
+ end;
76394
+ $$;
76395
+ ${userGrant(`${ctx.fn("list_roles")}(${id})`)}
76396
+
76397
+ -- Grants (true) or denies (false) one key to a role in one tenant; null
76398
+ -- clears the override, so the role's default applies again. Members change
76399
+ -- only roles they could assign, and only keys they hold themselves.
76400
+ -- Errors carry a code in the hint: PERMISSIONS_FORBIDDEN, PERMISSIONS_ROLE_UNKNOWN,
76401
+ -- PERMISSIONS_KEY_UNKNOWN, PERMISSIONS_ROLE_CEILING, PERMISSIONS_KEY_CEILING,
76402
+ -- PERMISSIONS_SELF_LOCKOUT.
76403
+ create or replace function ${ctx.fn("set_permission_override")}(tenant ${id}, role text, permission text, granted boolean)
76404
+ returns jsonb
76405
+ language plpgsql
76406
+ security definer
76407
+ set search_path = ''
76408
+ as $$
76409
+ #variable_conflict use_variable
76410
+ declare
76411
+ v_role uuid;
76412
+ v_permission uuid;
76413
+ v_service boolean := ${SERVICE_CALLER$1};
76414
+ begin
76415
+ if not (v_service or ${memberCan("tenant", manageKey)}) then
76416
+ ${fail$1("PERMISSIONS_FORBIDDEN", "Not allowed to change role permissions")}
76417
+ end if;
76418
+ select r.${rId} into v_role from ${roles} r
76419
+ where (r.${rId}::text = role or r.${rKey} = role)${scoped};
76420
+ if v_role is null then
76421
+ ${fail$1("PERMISSIONS_ROLE_UNKNOWN", "Unknown role", "P0002")}
76422
+ end if;
76423
+ select p.${pId} into v_permission from ${perms} p where p.${pKey} = permission;
76424
+ if v_permission is null then
76425
+ ${fail$1("PERMISSIONS_KEY_UNKNOWN", "Unknown permission", "P0002")}
76426
+ end if;
76427
+ if not v_service then
76428
+ if not better_supabase.can_assign(tenant, v_role::text) then
76429
+ ${fail$1("PERMISSIONS_ROLE_CEILING", "That role is above your own")}
76430
+ end if;
76431
+ if not ${memberCan("tenant", "permission")} then
76432
+ ${fail$1("PERMISSIONS_KEY_CEILING", "You can only change keys you hold")}
76433
+ end if;
76434
+ if granted is distinct from true and permission = ${manageKey} and exists (
76435
+ select 1 from ${m} mm where mm.${mTenant} = tenant and mm.${mUser} = auth.uid() and mm.${mRole} = v_role
76436
+ ) then
76437
+ ${fail$1("PERMISSIONS_SELF_LOCKOUT", "You cannot take this key from your own role")}
76438
+ end if;
76439
+ end if;
76440
+ if granted is null then
76441
+ delete from ${o} ov
76442
+ where ov.${oTenant} = tenant and ov.${oRole} = v_role and ov.${oPermission} = v_permission;
76443
+ else
76444
+ insert into ${o} (${oTenant}, ${oRole}, ${oPermission}, ${oGranted})
76445
+ values (tenant, v_role, v_permission, granted)
76446
+ on conflict (${oTenant}, ${oRole}, ${oPermission}) do update set ${oGranted} = excluded.${oGranted};
76447
+ end if;
76448
+ return (select ${roleJson("set_permission_override.tenant")} from ${roles} r where r.${rId} = v_role);
76449
+ end;
76450
+ $$;
76451
+ ${userGrant(`${ctx.fn("set_permission_override")}(${id}, text, text, boolean)`)}`;
76452
+ }
76453
+ //#endregion
76237
76454
  //#region src/sql/modules/permissions.ts
76238
76455
  const SERVICE = `coalesce(auth.jwt() ->> 'role', '') = 'service_role'`;
76239
76456
  const NOT_ACTING = `(platform_can.member is distinct from auth.uid() or auth.jwt() -> 'act' is null)`;
@@ -76999,7 +77216,7 @@ as $$
76999
77216
  select coalesce(better_supabase.platform_can(auth.uid(), is_platform.permission), false)
77000
77217
  $$;
77001
77218
 
77002
- ${myPermissionsSql(id)}${providerGuestFunctions(ctx.installedModules, layout)}
77219
+ ${myPermissionsSql(id)}${providerGuestFunctions(ctx.installedModules, layout)}${catalogRoleFunctions(ctx)}
77003
77220
 
77004
77221
  ${[
77005
77222
  "permission_matches(text, text)",
@@ -77160,6 +77377,7 @@ const ACCESS = {
77160
77377
  returns: "jsonb"
77161
77378
  }
77162
77379
  ],
77380
+ unusedPermissions: (ctx) => rendersRoleFunctions(ctx) ? [] : ["listRoles", "setOverride"],
77163
77381
  build: accessSql
77164
77382
  };
77165
77383
  //#endregion
@@ -79207,7 +79425,7 @@ function build$54(ctx, layout) {
79207
79425
  ];
79208
79426
  const unique = (table, what, columns) => ctx.owns(table) ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${ctx.tableName(table).name}_${what}_key`)} on ${ctx.table(table)} (${columns});`;
79209
79427
  const readable = `(${d.owner} = (select auth.uid()) or (${d.scope} in ('organization', 'agent') and ${ctx.scope.check(d.tenant, read)}) or ${ctx.scope.check(d.tenant, manage)} or (${d.scope} = 'chat' and ${chatReadable(d.scopeId)}))`;
79210
- const ownDocument = (row) => `(${SERVICE_CALLER$1} or ${row}.${d.owner} = auth.uid() or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
79428
+ const ownDocument = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${d.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
79211
79429
  const notFound = raise$1("document % not found", "P0002", "KNOWLEDGE_NOT_FOUND", "document_id");
79212
79430
  return `${schemaPreamble(ctx)}
79213
79431
  -- Documents for retrieval: uploaded files, pasted text and synced rows, split
@@ -80719,7 +80937,7 @@ ${renderPolicy(policy$1({
80719
80937
  }
80720
80938
  /** Moves the leases of a merged party to the record it merged into. */
80721
80939
  function partyMerges(ctx) {
80722
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
80940
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
80723
80941
  table: `${subject.schema}.${subject.table}`,
80724
80942
  extra: {}
80725
80943
  }]), moveSubjectRows({
@@ -81006,7 +81224,7 @@ declare
81006
81224
  v_rows jsonb;
81007
81225
  begin
81008
81226
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "leave_balances.tenant", read)}
81009
- or (v_user = auth.uid() and ${ctx.can("tenant", "leave_balances.tenant", request)})) then
81227
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "leave_balances.tenant", request)})) then
81010
81228
  ${forbidden("not allowed to read this member's leave balance")}
81011
81229
  end if;
81012
81230
  if v_user is null then
@@ -81051,7 +81269,7 @@ declare
81051
81269
  v_rows jsonb;
81052
81270
  begin
81053
81271
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "leave_ledger_entries.tenant", read)}
81054
- or (v_user = auth.uid() and ${ctx.can("tenant", "leave_ledger_entries.tenant", request)})) then
81272
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "leave_ledger_entries.tenant", request)})) then
81055
81273
  ${forbidden("not allowed to read this member's leave balance")}
81056
81274
  end if;
81057
81275
  select coalesce(jsonb_agg(${entryJson} order by y.${le("createdAt")} desc, y.${le("id")} desc), '[]'::jsonb) into v_rows
@@ -81752,7 +81970,7 @@ begin
81752
81970
  ${fail$1("LEAVE_REQUEST_NOT_FOUND", "leave request not found", "P0002")}
81753
81971
  end if;
81754
81972
  v_manager := ${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${q("tenant")}`, manage)};
81755
- if not (v_manager or v_row.${q("user")} = auth.uid()) then
81973
+ if not (v_manager or coalesce(v_row.${q("user")} = auth.uid(), false)) then
81756
81974
  ${forbidden("not allowed to cancel this leave request")}
81757
81975
  end if;
81758
81976
  if v_row.${q("cancelledAt")} is not null then
@@ -81794,7 +82012,7 @@ begin
81794
82012
  if not (v_reader or ${ctx.can("tenant", "list_leave_requests.tenant", request)}) then
81795
82013
  ${forbidden("not allowed to list leave requests")}
81796
82014
  end if;
81797
- if not v_reader and (coalesce(list_leave_requests.everyone, false) or (list_leave_requests.user_id is not null and list_leave_requests.user_id <> auth.uid())) then
82015
+ if not v_reader and (coalesce(list_leave_requests.everyone, false) or (list_leave_requests.user_id is not null and list_leave_requests.user_id is distinct from auth.uid())) then
81798
82016
  ${forbidden("not allowed to read another member's leave")}
81799
82017
  end if;
81800
82018
  select coalesce(jsonb_agg(z.item order by z.starts, z.created), '[]'::jsonb) into v_rows
@@ -83877,7 +84095,7 @@ declare
83877
84095
  v_row ${memories}%rowtype;
83878
84096
  begin
83879
84097
  select * into v_row from ${memories} x where x.${m.id} = memory_forget.memory_id;
83880
- if not found or not (${SERVICE_CALLER$1} or v_row.${m.owner} = auth.uid() or (v_row.${m.scope} = 'organization' and ${ctx.scope.can(`v_row.${m.tenant}`, manage)})) then
84098
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${m.owner} = auth.uid(), false) or (v_row.${m.scope} = 'organization' and ${ctx.scope.can(`v_row.${m.tenant}`, manage)})) then
83881
84099
  return false;
83882
84100
  end if;
83883
84101
  if memory_forget.superseded_by is null then
@@ -84414,8 +84632,8 @@ begin
84414
84632
  end if;
84415
84633
  if not (${q.service}
84416
84634
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84417
- or (${fn("can_conversation")}(v_conv.${cv("id")}, 'send') and (v_conv.${cv("access")} = 'members' or add_conversation_members.users <@ array[auth.uid()]))
84418
- or (v_conv.${cv("access")} = 'tenant' and v_conv.${cv("archivedAt")} is null and add_conversation_members.users <@ array[auth.uid()])) then
84635
+ or (${fn("can_conversation")}(v_conv.${cv("id")}, 'send') and (v_conv.${cv("access")} = 'members' or coalesce(add_conversation_members.users <@ array[auth.uid()], false)))
84636
+ or (v_conv.${cv("access")} = 'tenant' and v_conv.${cv("archivedAt")} is null and coalesce(add_conversation_members.users <@ array[auth.uid()], false))) then
84419
84637
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to add members here")}
84420
84638
  end if;
84421
84639
  for v_user in select distinct x from unnest(add_conversation_members.users) x where x is not null loop
@@ -84454,7 +84672,7 @@ begin
84454
84672
  ${fail$1("MESSAGING_MEMBERS_FIXED", "this conversation's members can't change", "22023")}
84455
84673
  end if;
84456
84674
  if not (${q.service}
84457
- or remove_conversation_member.member = auth.uid()
84675
+ or coalesce(remove_conversation_member.member = auth.uid(), false)
84458
84676
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84459
84677
  or exists (select 1 from ${t("members")} k where k.${mb("conversation")} = v_conv.${cv("id")} and k.${mb("user")} = auth.uid() and k.${mb("role")} = 'owner')) then
84460
84678
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to remove this member")}
@@ -84486,7 +84704,7 @@ begin
84486
84704
  end if;
84487
84705
  if not (${q.service}
84488
84706
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84489
- or v_conv.${cv("createdBy")} = auth.uid()
84707
+ or coalesce(v_conv.${cv("createdBy")} = auth.uid(), false)
84490
84708
  or exists (select 1 from ${t("members")} k where k.${mb("conversation")} = v_conv.${cv("id")} and k.${mb("user")} = auth.uid() and k.${mb("role")} = 'owner')) then
84491
84709
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to archive this conversation")}
84492
84710
  end if;
@@ -84893,7 +85111,7 @@ function sentEffects(q) {
84893
85111
  'summary', left(v_msg.${ms("body")}, 140),
84894
85112
  'data', jsonb_build_object(${messageId}, v_msg.${ms("id")}, ${sqlString(q.e("conversationId"))}, v_msg.${ms("conversation")})${extra}
84895
85113
  )`, { indent: " " });
84896
- const keyed = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.permissions?.["read"] !== void 0).map((subject) => subject.type);
85114
+ const keyed = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.permissions?.["read"] !== void 0).map((subject) => subject.type);
84897
85115
  const readsRecord = (user) => keyed.length === 0 ? "" : `
84898
85116
  and (v_conv.${cv("access")} <> 'subject' or case v_conv.${cv("subjectType")} ${keyed.map((type) => `when ${sqlString(type)} then coalesce(${ctx.of("subjects").fn("can_subject_for")}(${user}, v_conv.${cv("subjectType")}, v_conv.${cv("subjectId")}, 'read'), false)`).join(" ")} else true end)`;
84899
85117
  const canRead = (user) => `${ctx.scope.canUser(user, `v_msg.${ms("tenant")}`, q.key("read"))}
@@ -85384,7 +85602,7 @@ begin
85384
85602
  if not found then
85385
85603
  return false;
85386
85604
  end if;
85387
- if not (${q.service} or v_msg.${ms("author")} = auth.uid() or ${fn("can_conversation")}(v_msg.${ms("conversation")}, 'moderate')) then
85605
+ if not (${q.service} or coalesce(v_msg.${ms("author")} = auth.uid(), false) or ${fn("can_conversation")}(v_msg.${ms("conversation")}, 'moderate')) then
85388
85606
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to delete this message")}
85389
85607
  end if;
85390
85608
  update ${t("messages")} m set ${ms("body")} = '', ${ms("document")} = null, ${ms("mentions")} = '{}', ${ms("mentionScope")} = null,
@@ -92517,7 +92735,7 @@ declare
92517
92735
  v_units integer := 0;
92518
92736
  begin
92519
92737
  ${load("request_return.order_id")}
92520
- if not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.manage)}) then
92738
+ if not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.manage)}) then
92521
92739
  ${fail$1("ORDERS_FORBIDDEN", "not allowed to return this order")}
92522
92740
  end if;
92523
92741
  if v_order.status not in ('paid', 'fulfilled', 'completed') then
@@ -92747,7 +92965,7 @@ function ownCart(ctx, id, options = {}) {
92747
92965
  return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status,
92748
92966
  x.${c("currency")} as currency, x.${c("priceList")} as price_list, x.${c("shippingAddress")} as shipping_address
92749
92967
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = ${id}${options.lock ? " for update" : ""};
92750
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()${readers}) then
92968
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)${readers}) then
92751
92969
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
92752
92970
  end if;`;
92753
92971
  }
@@ -93752,10 +93970,10 @@ declare
93752
93970
  v_order record;
93753
93971
  begin
93754
93972
  ${load("cancel_order.order_id", true)}
93755
- if not found or not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.read)}) then
93973
+ if not found or not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.read)}) then
93756
93974
  ${fail$1("ORDERS_ORDER_NOT_FOUND", "order not found", "P0002")}
93757
93975
  end if;
93758
- if not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.manage)}) then
93976
+ if not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.manage)}) then
93759
93977
  ${fail$1("ORDERS_FORBIDDEN", "not allowed to cancel this order")}
93760
93978
  end if;
93761
93979
  if v_order.status = 'cancelled' then
@@ -93811,7 +94029,7 @@ declare
93811
94029
  v_order record;
93812
94030
  begin
93813
94031
  ${load("get_order.order_id", false)}
93814
- if not found or not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.read)}) then
94032
+ if not found or not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.read)}) then
93815
94033
  ${fail$1("ORDERS_ORDER_NOT_FOUND", "order not found", "P0002")}
93816
94034
  end if;
93817
94035
  return ${fn("order_json")}(v_order.id);
@@ -96037,7 +96255,7 @@ begin
96037
96255
  if not exists (select 1 from ${n.m} m where m.${n.tenant} = organization and m.${n.user} = member) then
96038
96256
  ${fail$1("ORGANIZATION_NOT_MEMBER", "Not a member", "P0002")}
96039
96257
  end if;
96040
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96258
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
96041
96259
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
96042
96260
  end if;
96043
96261
  if not better_supabase.can_assign(organization, role) then
@@ -96078,7 +96296,7 @@ begin
96078
96296
  if not exists (select 1 from ${mr} r where r.${n.tenant} = organization and r.${n.user} = member and r."role" = role) then
96079
96297
  return false;
96080
96298
  end if;
96081
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96299
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
96082
96300
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
96083
96301
  end if;
96084
96302
  if not better_supabase.can_assign(organization, role) then
@@ -96137,7 +96355,7 @@ begin
96137
96355
  end if;
96138
96356
  -- Checked here whatever blocks.organizations.options.assignmentGuard
96139
96357
  -- says: a guard that checks only client writes never sees this function's.
96140
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96358
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
96141
96359
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
96142
96360
  end if;
96143
96361
  if not better_supabase.can_assign(organization, previous_assignable)
@@ -97277,7 +97495,7 @@ declare
97277
97495
  v_entry uuid;
97278
97496
  begin
97279
97497
  select * into v_pass from ${passes} x where x.${p("id")} = book_with_credit.pass_id for update;
97280
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, manage)}) then
97498
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, manage)}) then
97281
97499
  ${fail$1("PASS_NOT_FOUND", "pass not found", "P0002")}
97282
97500
  end if;
97283
97501
  if v_pass.${p("status")} <> 'active' then
@@ -97364,7 +97582,7 @@ declare
97364
97582
  v_pass ${passes}%rowtype;
97365
97583
  begin
97366
97584
  select * into v_pass from ${passes} x where x.${p("id")} = list_pass_credits.pass_id;
97367
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, read)}) then
97585
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, read)}) then
97368
97586
  ${fail$1("PASS_NOT_FOUND", "pass not found", "P0002")}
97369
97587
  end if;
97370
97588
  return coalesce((
@@ -97919,7 +98137,7 @@ declare
97919
98137
  v_row ${passes}%rowtype;
97920
98138
  begin
97921
98139
  select * into v_row from ${passes} x where x.${p("id")} = get_pass.pass_id;
97922
- if not found or not (v_row.${p("holderUser")} = auth.uid() or ${allowed(`v_row.${p("tenant")}`, manage)}) then
98140
+ if not found or not (coalesce(v_row.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_row.${p("tenant")}`, manage)}) then
97923
98141
  return null;
97924
98142
  end if;
97925
98143
  return ${withNonce("v_row")};
@@ -98039,7 +98257,7 @@ declare
98039
98257
  v_pass ${passes}%rowtype;
98040
98258
  begin
98041
98259
  select * into v_pass from ${passes} x where x.${p("id")} = list_pass_check_ins.pass_id;
98042
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, read)}) then
98260
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, read)}) then
98043
98261
  return '[]'::jsonb;
98044
98262
  end if;
98045
98263
  return (
@@ -98061,7 +98279,7 @@ ${occupancy}`;
98061
98279
  /** Moves the passes on a merged registered subject to the record it merged into. */
98062
98280
  function passMerges(ctx) {
98063
98281
  if (!keepsSubject(ctx)) return "";
98064
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
98282
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
98065
98283
  table: `${subject.schema}.${subject.table}`,
98066
98284
  extra: {}
98067
98285
  }]), moveSubjectRows({
@@ -98483,7 +98701,7 @@ function pipelineBindings(ctx) {
98483
98701
  };
98484
98702
  }
98485
98703
  for (const [type, entry] of Object.entries(configured)) if (!(type in raw)) raw[type] = entry;
98486
- const registry = registeredSubjects({
98704
+ const registry = registeredSubjects$1({
98487
98705
  ...builtInSubjects,
98488
98706
  ...ctx.subjects
98489
98707
  }, ctx.naming);
@@ -101005,7 +101223,7 @@ declare
101005
101223
  begin
101006
101224
  select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status
101007
101225
  into v_cart from ${orders.table("carts")} x where x.${c("id")} = apply_promotion_code.cart for update;
101008
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()) then
101226
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)) then
101009
101227
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
101010
101228
  end if;
101011
101229
  if v_cart.status <> 'open' then
@@ -101048,7 +101266,7 @@ declare
101048
101266
  begin
101049
101267
  select x.${c("user")} as owner, x.${c("status")} as status
101050
101268
  into v_cart from ${orders.table("carts")} x where x.${c("id")} = remove_promotion_code.cart;
101051
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()) then
101269
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)) then
101052
101270
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
101053
101271
  end if;
101054
101272
  if v_cart.status <> 'open' then
@@ -101695,22 +101913,27 @@ function pushTickets(ctx) {
101695
101913
  const events = recordsEvents(ctx) ? `
101696
101914
  -- The delivery's provider message id is Expo's first ticket id, so every
101697
101915
  -- receipt of the delivery records its event on that message, once per
101698
- -- ticket.
101699
- perform ${notifications.fn("record_delivery_event")}(
101700
- 'expo',
101701
- d.${d("providerMessageId")},
101702
- case when r ->> 'status' = 'ok' then 'delivered' else 'bounced' end,
101703
- 'expo-receipt:' || (r ->> 'id'),
101704
- now(),
101705
- jsonb_strip_nulls(jsonb_build_object('token', x.${c("token")}, 'error', r ->> 'error', 'message', r ->> 'message')),
101706
- false
101707
- )
101708
- from ${t} x
101709
- join ${notifications.table("deliveries")} d on d.${d("id")} = x.${c("delivery")}
101710
- cross join jsonb_array_elements(complete_push_receipts.receipts) r
101711
- where x.${c("ticket")} = r ->> 'id'
101712
- and x.${c("checkedAt")} is null
101713
- and d.${d("providerMessageId")} is not null;` : "";
101916
+ -- ticket. The events stored now come back for the client to emit.
101917
+ select coalesce(jsonb_agg(e.recorded || jsonb_build_object('provider_event_id', e.event_id)), '[]'::jsonb)
101918
+ into v_events
101919
+ from (
101920
+ select ${notifications.fn("record_delivery_event")}(
101921
+ 'expo',
101922
+ d.${d("providerMessageId")},
101923
+ case when r ->> 'status' = 'ok' then 'delivered' else 'bounced' end,
101924
+ 'expo-receipt:' || (r ->> 'id'),
101925
+ now(),
101926
+ jsonb_strip_nulls(jsonb_build_object('token', x.${c("token")}, 'error', r ->> 'error', 'message', r ->> 'message')),
101927
+ false
101928
+ ) as recorded, 'expo-receipt:' || (r ->> 'id') as event_id
101929
+ from ${t} x
101930
+ join ${notifications.table("deliveries")} d on d.${d("id")} = x.${c("delivery")}
101931
+ cross join jsonb_array_elements(complete_push_receipts.receipts) r
101932
+ where x.${c("ticket")} = r ->> 'id'
101933
+ and x.${c("checkedAt")} is null
101934
+ and d.${d("providerMessageId")} is not null
101935
+ ) e
101936
+ where coalesce((e.recorded ->> 'recorded')::boolean, false);` : "";
101714
101937
  return `
101715
101938
  -- One row per delivery and device: the Expo ticket id, or the error Expo
101716
101939
  -- answered. A retried delivery skips the devices that already have a ticket.
@@ -101814,15 +102037,20 @@ $$;
101814
102037
  -- Stores what Expo answered for each ticket, [{ id, status: ok | error,
101815
102038
  -- error, message }], and records notification.delivered or bounced on the
101816
102039
  -- delivery when the notifications block tracks provider events. A ticket
101817
- -- Expo has no receipt for yet stays unchecked. Returns how many it stored.
102040
+ -- Expo has no receipt for yet stays unchecked. Returns { updated, events }:
102041
+ -- how many tickets it stored and the provider events it recorded for the
102042
+ -- first time, as record_delivery_event returns them. Postgres can't change
102043
+ -- a return type in place, so the integer version is dropped first.
102044
+ drop function if exists ${fn("complete_push_receipts")}(jsonb);
101818
102045
  create or replace function ${fn("complete_push_receipts")}(receipts jsonb)
101819
- returns integer
102046
+ returns jsonb
101820
102047
  language plpgsql
101821
102048
  security definer
101822
102049
  set search_path = ''
101823
102050
  as $$
101824
102051
  declare
101825
102052
  v_count integer;
102053
+ v_events jsonb := '[]'::jsonb;
101826
102054
  begin${serviceOnly}
101827
102055
  if jsonb_typeof(complete_push_receipts.receipts) <> 'array' or jsonb_array_length(complete_push_receipts.receipts) > 1000 then
101828
102056
  ${fail$1("PUSH_TOO_MANY", "pass at most 1000 receipts", "22023")}
@@ -101834,7 +102062,7 @@ begin${serviceOnly}
101834
102062
  where x.${c("ticket")} = r ->> 'id'
101835
102063
  and x.${c("checkedAt")} is null;
101836
102064
  get diagnostics v_count = row_count;
101837
- return v_count;
102065
+ return jsonb_build_object('updated', v_count, 'events', v_events);
101838
102066
  end;
101839
102067
  $$;
101840
102068
  ${TICKET_FUNCTIONS.map(([name, args]) => `revoke execute on function ${fn(name)}(${args}) from public, anon, authenticated;
@@ -101861,7 +102089,7 @@ function ticketsContract(ctx) {
101861
102089
  {
101862
102090
  name: "complete_push_receipts",
101863
102091
  args: ["jsonb"],
101864
- returns: "integer"
102092
+ returns: "jsonb"
101865
102093
  }
101866
102094
  ];
101867
102095
  }
@@ -102194,11 +102422,15 @@ const PUSH = {
102194
102422
  integrates: ["notifications"],
102195
102423
  target: "schema",
102196
102424
  modes: ["managed", "custom"],
102197
- version: 2,
102425
+ version: 3,
102198
102426
  upgrades: [{
102199
102427
  from: 1,
102200
102428
  description: "With the notifications block installed, push_tickets stores Expo's tickets per delivery; record_push_tickets, push_tickets_for, unchecked_push_tickets and complete_push_receipts are new, for retries that skip devices already sent to and the receipt check.",
102201
102429
  sql: () => ""
102430
+ }, {
102431
+ from: 2,
102432
+ description: "complete_push_receipts returns { updated, events }: the ticket count and the provider events it recorded for the first time, so the client emits notification.delivered and notification.bounced like recordDeliveryEvent does.",
102433
+ sql: () => ""
102202
102434
  }],
102203
102435
  names: NAMES$37,
102204
102436
  contract: contract$33,
@@ -103694,7 +103926,7 @@ const RANK_REBALANCE_LENGTH = 24;
103694
103926
  /** The rebalance job's queue. */
103695
103927
  const ALPHABET = sqlString(RANK_ALPHABET);
103696
103928
  function ranked(ctx) {
103697
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.rank !== void 0);
103929
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.rank !== void 0);
103698
103930
  }
103699
103931
  function cases(selector, subjects, branch, otherwise) {
103700
103932
  if (subjects.length === 0) return otherwise;
@@ -107721,11 +107953,11 @@ ${lockTable(views, { read: true })}
107721
107953
  or ${scope} = 'tenant'
107722
107954
  )`;
107723
107955
  const mayEdit = (alias) => `(auth.role() = 'service_role'
107724
- or (${alias}.${scope} = 'user' and ${alias}.${owner} = auth.uid())
107956
+ or (${alias}.${scope} = 'user' and coalesce(${alias}.${owner} = auth.uid(), false))
107725
107957
  or (${alias}.${scope} <> 'user' and ${ctx.scope.can(`${alias}.${tenant}`, share)}))`;
107726
107958
  const maySee = (alias) => `(auth.role() = 'service_role'
107727
107959
  or (${ctx.scope.can(`${alias}.${tenant}`, read)} and (
107728
- (${alias}.${scope} = 'user' and ${alias}.${owner} = auth.uid())
107960
+ (${alias}.${scope} = 'user' and coalesce(${alias}.${owner} = auth.uid(), false))
107729
107961
  or (${alias}.${scope} = 'team' and ${inTeam(`${alias}.${team}`)})
107730
107962
  or ${alias}.${scope} = 'tenant')))`;
107731
107963
  const collection = ctx.installed("collections") ? collectionCheck(ctx.of("collections")) : "";
@@ -108940,7 +109172,7 @@ function dimensionsOf(ctx) {
108940
109172
  }
108941
109173
  /** The registered subjects with a `search` entry and a tenant column. */
108942
109174
  function searchedSubjects(ctx) {
108943
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.search !== void 0 && subject.tenant !== void 0 && (subject.config.search.title ?? subject.config.title) !== void 0);
109175
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.search !== void 0 && subject.tenant !== void 0 && (subject.config.search.title ?? subject.config.title) !== void 0);
108944
109176
  }
108945
109177
  /** Whether any searched subject returns a description with its hits. */
108946
109178
  const describes = (subjects) => subjects.some((subject) => subject.config.search?.description !== void 0);
@@ -110394,7 +110626,7 @@ function names$1(ctx) {
110394
110626
  read: ctx.permission("read", keys.read),
110395
110627
  edit: ctx.permission("edit", keys.edit),
110396
110628
  maxMembers,
110397
- subjects: registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0)
110629
+ subjects: registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0)
110398
110630
  };
110399
110631
  }
110400
110632
  function tables$4(ctx, n) {
@@ -113857,7 +114089,7 @@ ${userGrant(`${fn("list_tracking_events")}(uuid)`)}
113857
114089
  */
113858
114090
  function shipmentMerges(ctx) {
113859
114091
  if (!ctx.has("shipments", "subjectType") || !ctx.has("shipments", "subjectId")) return "";
113860
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
114092
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
113861
114093
  table: `${subject.schema}.${subject.table}`,
113862
114094
  extra: {}
113863
114095
  }]), moveSubjectRows({
@@ -114478,7 +114710,7 @@ begin
114478
114710
  if not found then
114479
114711
  ${notFound}
114480
114712
  end if;
114481
- if not (${SERVICE_CALLER$1} or v_req.${r("requestedBy")} = auth.uid() or ${ctx.can("tenant", `v_req.${r("tenant")}`, manage)}) then
114713
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${r("requestedBy")} = auth.uid(), false) or ${ctx.can("tenant", `v_req.${r("tenant")}`, manage)}) then
114482
114714
  ${forbidden("not allowed to cancel this request")}
114483
114715
  end if;
114484
114716
  if v_req.${r("status")} <> 'pending' then
@@ -114508,7 +114740,7 @@ begin
114508
114740
  if not found then
114509
114741
  ${notFound}
114510
114742
  end if;
114511
- if not (${SERVICE_CALLER$1} or auth.uid() = any (v_req.${r("signers")}) or ${readableRequest("v_req")}) then
114743
+ if not (${SERVICE_CALLER$1} or coalesce(auth.uid() = any (v_req.${r("signers")}), false) or ${readableRequest("v_req")}) then
114512
114744
  ${forbidden("not allowed to read this request")}
114513
114745
  end if;
114514
114746
  select coalesce(jsonb_agg(${signatureJson("g")} order by g.${s("signedAt")}), '[]'::jsonb) into v_items
@@ -115470,7 +115702,8 @@ function workItemFunctions(ctx, n) {
115470
115702
  subjectType: item,
115471
115703
  subjectId: `v_row.${w("id")}::text`
115472
115704
  });
115473
- const notify = ctx.installed("notifications") ? `
115705
+ const actionPath = n.actionPath === "" ? "null" : `replace(replace(${sqlString(n.actionPath)}, '{id}', v_row.${w("id")}::text), '{identifier}', ${ctx.has("items", "identifier") ? `coalesce(v_row.${w("identifier")}, '')` : "''"})`;
115706
+ const notify = ctx.installed("notifications") && n.notify ? `
115474
115707
  if cardinality(v_new) > 0 then
115475
115708
  ${ctx.notify(`jsonb_build_object(
115476
115709
  'type', ${sqlString(e("work_item.assigned"))},
@@ -115478,7 +115711,9 @@ function workItemFunctions(ctx, n) {
115478
115711
  'actor', auth.uid(),
115479
115712
  'subject_type', ${item},
115480
115713
  'subject_id', v_row.${w("id")}::text,
115714
+ 'subject_label', v_row.${w("title")},
115481
115715
  'summary', v_row.${w("title")},
115716
+ 'action_path', ${actionPath},
115482
115717
  'recipients', to_jsonb(v_new),
115483
115718
  'watchers', false,
115484
115719
  'key', ${sqlString(e("work_item.assigned:"))} || v_row.${w("id")}::text || ':' || md5(array_to_string(v_new, ',')),
@@ -115978,7 +116213,9 @@ const NAMES$16 = {
115978
116213
  "prefix",
115979
116214
  "maxAssignees",
115980
116215
  "extraColumns",
115981
- "authorCanDelete"
116216
+ "authorCanDelete",
116217
+ "notify",
116218
+ "actionPath"
115982
116219
  ],
115983
116220
  tables: {
115984
116221
  items: {
@@ -116322,6 +116559,8 @@ function build$16(ctx) {
116322
116559
  create: sqlString(ctx.config.permissions["create"] ?? ctx.permissionKey("write", keys.write)),
116323
116560
  remove: sqlString(ctx.config.permissions["delete"] ?? ctx.permissionKey("manage", keys.manage)),
116324
116561
  authorCanDelete: ctx.flag("authorCanDelete", true),
116562
+ notify: ctx.flag("notify", true),
116563
+ actionPath: ctx.text("actionPath", ""),
116325
116564
  prefix: ctx.text("prefix", "TASK-"),
116326
116565
  maxAssignees,
116327
116566
  service: "(auth.role() = 'service_role')",
@@ -116640,7 +116879,7 @@ function businessHours(ctx) {
116640
116879
  };
116641
116880
  }
116642
116881
  function bindings(ctx) {
116643
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
116882
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
116644
116883
  return Object.entries(onSettings(ctx)).map(([type, entry]) => {
116645
116884
  const where = `blocks.${ctx.instance}.on.${type}`;
116646
116885
  const subject = registry.find((item) => item.type === type);
@@ -122785,7 +123024,7 @@ declare
122785
123024
  v_entries jsonb;
122786
123025
  v_totals jsonb;
122787
123026
  begin
122788
- if not (${SERVICE_CALLER$1} or (v_user = auth.uid() and ${ctx.can("tenant", "get_timesheet.tenant", track)}) or ${ctx.can("tenant", "get_timesheet.tenant", read)}) then
123027
+ if not (${SERVICE_CALLER$1} or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "get_timesheet.tenant", track)}) or ${ctx.can("tenant", "get_timesheet.tenant", read)}) then
122789
123028
  ${forbidden("not allowed to read this timesheet")}
122790
123029
  end if;
122791
123030
  select * into v_sheet from ${timesheets} s
@@ -122955,7 +123194,7 @@ begin
122955
123194
  if not (v_reader or ${ctx.can("tenant", "list_timesheets.tenant", track)}) then
122956
123195
  ${forbidden("not allowed to list timesheets")}
122957
123196
  end if;
122958
- if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id <> auth.uid() then
123197
+ if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id is distinct from auth.uid() then
122959
123198
  ${forbidden("not allowed to read another member's timesheets")}
122960
123199
  end if;
122961
123200
  select coalesce(jsonb_agg(q.item order by q.week desc, q.created desc), '[]'::jsonb) into v_rows
@@ -123091,7 +123330,7 @@ function statusTimesheetFunctions(ctx, names) {
123091
123330
  const { ended, running, owner } = names;
123092
123331
  const by = owner.employee;
123093
123332
  const ownerVar = by ? "v_owner" : "v_user";
123094
- const sheetMine = (row) => by ? `(${owner.sheetUser ? `${row}.${t("user")} = auth.uid() or ` : ""}${row}.${owner.timesheets} = ${owner.mine(`${row}.${t("tenant")}`)})` : `${row}.${t("user")} = auth.uid()`;
123333
+ const sheetMine = (row) => by ? `(${owner.sheetUser ? `coalesce(${row}.${t("user")} = auth.uid(), false) or ` : ""}${row}.${owner.timesheets} = ${owner.mine(`${row}.${t("tenant")}`)})` : `coalesce(${row}.${t("user")} = auth.uid(), false)`;
123095
123334
  const ownerParam = by ? ", employee_id uuid default null" : "";
123096
123335
  const ownerType = by ? ", uuid" : "";
123097
123336
  const fn = (name) => ctx.fn(name);
@@ -123306,7 +123545,7 @@ begin
123306
123545
  if not (v_reader or ${ctx.can("tenant", "list_timesheets.tenant", track)}) then
123307
123546
  ${forbidden("not allowed to list timesheets")}
123308
123547
  end if;
123309
- if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id <> auth.uid() then
123548
+ if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id is distinct from auth.uid() then
123310
123549
  ${forbidden("not allowed to read another member's timesheets")}
123311
123550
  end if;${by ? `
123312
123551
  if not v_reader and list_timesheets.employee_id is not null and list_timesheets.employee_id is distinct from ${owner.mine("list_timesheets.tenant")} then
@@ -124027,7 +124266,7 @@ begin
124027
124266
  if not (${SERVICE_CALLER$1} or ((v_owner = ${myEmployee("list_time_entries.tenant")} and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then` : ` v_user uuid := coalesce(list_time_entries.user_id, auth.uid());
124028
124267
  v_rows jsonb;
124029
124268
  begin
124030
- if not (${SERVICE_CALLER$1} or ((v_user = auth.uid() and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then`}
124269
+ if not (${SERVICE_CALLER$1} or ((coalesce(v_user = auth.uid(), false) and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then`}
124031
124270
  ${forbidden("not allowed to read these entries")}
124032
124271
  end if;
124033
124272
  select coalesce(jsonb_agg(${entryJson("q")} order by q.${e("startedAt")} desc), '[]'::jsonb) into v_rows
@@ -124214,7 +124453,7 @@ function activityReads(ctx) {
124214
124453
  sources: ["event"]
124215
124454
  };
124216
124455
  if (!ctx.installed("subjects")) return none;
124217
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
124456
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
124218
124457
  if (registry.length === 0) return none;
124219
124458
  const a = (logical) => ctx.col("activity", logical);
124220
124459
  const readable = ctx.fn("activity_subject_readable");