permdock 0.25.1 → 0.26.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 (969) hide show
  1. package/README.md +1 -1
  2. package/dist/2020-bJfT8aIA.js +6760 -0
  3. package/dist/a2a/index.d.ts +5 -9
  4. package/dist/a2a/index.js +13 -15
  5. package/dist/adapter-context-lHq_i_77.js +28 -0
  6. package/dist/adoption-scan-b0_Xpab8.js +106 -0
  7. package/dist/agent/index.d.ts +2 -2
  8. package/dist/agent/index.js +1 -1
  9. package/dist/ai-sdk/index.d.ts +4 -6
  10. package/dist/ai-sdk/index.js +6 -7
  11. package/dist/annotate-doc-BCOCOrq_.js +214 -0
  12. package/dist/annotate-routes-BvSuEht3.js +75 -0
  13. package/dist/annotate-uZVGIRym.js +25 -0
  14. package/dist/app/index.d.ts +2 -103
  15. package/dist/app/index.js +1 -114
  16. package/dist/app-data-DbSPSPIl.js +62 -0
  17. package/dist/approval-header-BvszJE3l.js +25 -0
  18. package/dist/approval-normalize-Cpp8R0rY.js +190 -0
  19. package/dist/approval-prompt-C-vjNZyd.d.ts +57 -0
  20. package/dist/approval-prompt-Covyx_DB.js +60 -0
  21. package/dist/approval-required-B-R4Yw3J.js +5 -0
  22. package/dist/approvals/index.d.ts +5 -5
  23. package/dist/approvals/index.js +8 -8
  24. package/dist/approvals-7jHYXocE.js +1039 -0
  25. package/dist/approvers-BkY_ZfWl.js +76 -0
  26. package/dist/arazzo-DMmcumRx.js +76 -0
  27. package/dist/arazzo-Hxerfx3_.js +35 -0
  28. package/dist/args-0EWFk-4S.js +311 -0
  29. package/dist/astro/index.d.ts +6 -8
  30. package/dist/astro/index.js +3 -4
  31. package/dist/audience-DauhRBNg.js +54 -0
  32. package/dist/auth-WHKYWtnS.js +187 -0
  33. package/dist/authz-topic-D8x24Jv-.js +14 -0
  34. package/dist/authzen/index.d.ts +37 -22
  35. package/dist/authzen/index.js +69 -27
  36. package/dist/automation-CUcWz8uu.d.ts +122 -0
  37. package/dist/automation-CpPdFX91.js +157 -0
  38. package/dist/base-url--yJPQlIK.js +8 -0
  39. package/dist/better-auth/index.d.ts +2 -8
  40. package/dist/better-auth/index.js +10 -13
  41. package/dist/better-supabase/index.d.ts +141 -95
  42. package/dist/better-supabase/index.js +239 -794
  43. package/dist/better-supabase-DSbs4MtQ.js +201 -0
  44. package/dist/bind-B3MHrzw4.d.ts +56 -0
  45. package/dist/bind-up3QptTt.js +124 -0
  46. package/dist/body-W1_8r6Tw.js +9 -0
  47. package/dist/body-text-B-m3p-qY.js +55 -0
  48. package/dist/boundary--5Swp7sN.js +18 -0
  49. package/dist/boundary-DJqHADKu.d.ts +22 -0
  50. package/dist/budget-5LJ8kfZk.d.ts +12 -0
  51. package/dist/budget-BH81q2cj.js +19 -0
  52. package/dist/build-instance-hLKYe3-E.js +30 -0
  53. package/dist/canonical-json-BibZkXtE.js +28 -0
  54. package/dist/capability-CVt3lpVK.d.ts +128 -0
  55. package/dist/capability-_ZsyfYxU.js +204 -0
  56. package/dist/casbin-CYwbggCS.js +29 -0
  57. package/dist/casbin-Co1KcLWU.js +241 -0
  58. package/dist/casl-CrltbDPa.js +23 -0
  59. package/dist/casl-D7n7yE-h.js +307 -0
  60. package/dist/catalog/index.d.ts +6 -20
  61. package/dist/catalog/index.js +13 -15
  62. package/dist/catalog-B3MJShnZ.js +51 -0
  63. package/dist/catalog-CgK_L4Qf.js +1 -0
  64. package/dist/catalog-DyC3LKc7.js +130 -0
  65. package/dist/catalog-doc-Bp5khmCG.js +352 -0
  66. package/dist/catalog-fingerprint-DAWZARy6.js +31 -0
  67. package/dist/catalog-operations-dxuOZr4J.js +59 -0
  68. package/dist/catalog-path-bG0XxHMu.js +11 -0
  69. package/dist/challenge-CjwmjcuX.js +518 -0
  70. package/dist/chat/index.d.ts +1 -1
  71. package/dist/chat/index.js +10 -13
  72. package/dist/chat-sdk/index.d.ts +3 -11
  73. package/dist/chat-sdk/index.js +7 -11
  74. package/dist/checks-DSm45qH7.js +71 -0
  75. package/dist/claims-map-BGbpbvGD.js +15 -0
  76. package/dist/claims-map-CLKQWxJG.d.ts +33 -0
  77. package/dist/claims-size-DcjhvUv5.js +58 -0
  78. package/dist/claude-agent/index.d.ts +3 -5
  79. package/dist/claude-agent/index.js +4 -5
  80. package/dist/clerk/index.d.ts +4 -8
  81. package/dist/clerk/index.js +7 -8
  82. package/dist/cli/bin.js +6 -7
  83. package/dist/cli/generate/watch-worker.d.ts +20 -0
  84. package/dist/cli/generate/watch-worker.js +69 -0
  85. package/dist/cli/index.d.ts +11 -20
  86. package/dist/cli/index.js +8 -8
  87. package/dist/cli/plugins/app.d.ts +18 -0
  88. package/dist/cli/plugins/app.js +26 -0
  89. package/dist/cli/plugins/better-supabase.d.ts +10 -0
  90. package/dist/cli/plugins/better-supabase.js +18 -0
  91. package/dist/cli/plugins/openapi.d.ts +19 -0
  92. package/dist/cli/plugins/openapi.js +40 -0
  93. package/dist/cli/plugins/powersync.d.ts +7 -0
  94. package/dist/cli/plugins/powersync.js +29 -0
  95. package/dist/cli/plugins/rls.d.ts +8 -0
  96. package/dist/cli/plugins/rls.js +27 -0
  97. package/dist/cli/plugins/schemas.d.ts +13 -0
  98. package/dist/cli/plugins/schemas.js +23 -0
  99. package/dist/cli/plugins/scim.d.ts +10 -0
  100. package/dist/cli/plugins/scim.js +32 -0
  101. package/dist/cli/plugins/supabase-hook.d.ts +13 -0
  102. package/dist/cli/plugins/supabase-hook.js +40 -0
  103. package/dist/cli/plugins/supabase.d.ts +27 -0
  104. package/dist/cli/plugins/supabase.js +69 -0
  105. package/dist/cli/plugins/ui.d.ts +11 -0
  106. package/dist/cli/plugins/ui.js +19 -0
  107. package/dist/client-V95IvZsF.d.ts +43 -0
  108. package/dist/client-subject-v89t811z.d.ts +25 -0
  109. package/dist/clients-Bb_33pRE.js +22 -0
  110. package/dist/clients-DGcyFDCc.d.ts +10 -0
  111. package/dist/cloud/index.d.ts +8 -26
  112. package/dist/cloud/index.js +22 -28
  113. package/dist/cloud-BfEI9TLS.js +85 -0
  114. package/dist/codemod-DwH0IZ2x.js +2159 -0
  115. package/dist/codemod-p67ePW25.js +35 -0
  116. package/dist/collect-BJZsuBW4.js +535 -0
  117. package/dist/collect-CPvCXMQ-.js +1 -0
  118. package/dist/collect-CpGnmGpL.js +54 -0
  119. package/dist/command-9GAzSI7E.js +5 -0
  120. package/dist/compact-C4LFuqbW.js +28 -0
  121. package/dist/compare-dfHDj8kT.js +11 -0
  122. package/dist/compile/index.d.ts +2 -2
  123. package/dist/compile/index.js +1 -1
  124. package/dist/compile-BUKXrueE.js +685 -0
  125. package/dist/compile-Blrr5WWw.js +724 -0
  126. package/dist/compile-D8c1nFGy.d.ts +118 -0
  127. package/dist/completion-CfrZOGcB.js +150 -0
  128. package/dist/conditions-CkHgXoZB.js +385 -0
  129. package/dist/config-D6gh_xvs.js +25 -0
  130. package/dist/config-iyy90IOU.js +143 -0
  131. package/dist/config-report-BaHEBpt-.js +55 -0
  132. package/dist/config-shape-B6tdyBju.js +149 -0
  133. package/dist/connection-BnoSqYU1.js +196 -0
  134. package/dist/connector-schema-BSRMyq4M.js +433 -0
  135. package/dist/constants-PCJiir_3.js +19 -0
  136. package/dist/context-DmH-Eyvx.js +95 -0
  137. package/dist/convex/index.d.ts +5 -9
  138. package/dist/convex/index.js +7 -8
  139. package/dist/core-CnC47rSf.d.ts +200 -0
  140. package/dist/core-DKqrD_xW.js +338 -0
  141. package/dist/coverage-DL7JCZmb.d.ts +133 -0
  142. package/dist/coverage-nFSMjFxH.js +42 -0
  143. package/dist/create-BAMPoEga.js +133 -0
  144. package/dist/create-BsRcXm_m.d.ts +125 -0
  145. package/dist/create-D3oXoXxM.js +373 -0
  146. package/dist/create-DeQ5t8mZ.d.ts +124 -0
  147. package/dist/create-sGl1ccTp.d.ts +185 -0
  148. package/dist/credential-ke0KMQeB.js +430 -0
  149. package/dist/credentials-6ZWbJ-Re.js +72 -0
  150. package/dist/credentials-BfzdL5kv.d.ts +123 -0
  151. package/dist/credentials-DOeqknte.js +309 -0
  152. package/dist/decide-set-CgNcE6pP.js +99 -0
  153. package/dist/deciding-columns-BnglEKqU.js +143 -0
  154. package/dist/decision-hHv4UZgy.js +20 -0
  155. package/dist/define-permdock-BLpQ0m95.d.ts +99 -0
  156. package/dist/define-permdock-CIxHBykk.js +148 -0
  157. package/dist/definition-options-9o8Hdww3.js +370 -0
  158. package/dist/delegation-BaUNCrE_.js +263 -0
  159. package/dist/delegation-input-7Y5Rlja7.js +18 -0
  160. package/dist/delivery/index.d.ts +4 -4
  161. package/dist/delivery/index.js +5 -5
  162. package/dist/delivery-Cb3VCij5.js +555 -0
  163. package/dist/delivery-event-D5b9yhaJ.js +39 -0
  164. package/dist/denied-text-D6JJTDr3.d.ts +20 -0
  165. package/dist/describe-B7EosIKA.js +100 -0
  166. package/dist/describe-lAafaRQQ.d.ts +43 -0
  167. package/dist/device-f3JEnqa0.js +195 -0
  168. package/dist/diff-BIqibFnm.js +464 -0
  169. package/dist/diff-n6LONVwL.js +36 -0
  170. package/dist/digest-BaP8bQzX.js +26 -0
  171. package/dist/digest-BcIZRYvp.d.ts +17 -0
  172. package/dist/doctor-Bg12v-8M.js +4847 -0
  173. package/dist/doctor-DCsyH7YR.js +53 -0
  174. package/dist/drizzle/index.d.ts +5 -9
  175. package/dist/drizzle/index.js +5 -6
  176. package/dist/elysia/index.d.ts +6 -8
  177. package/dist/elysia/index.js +6 -7
  178. package/dist/env-hbYumkRp.js +7 -0
  179. package/dist/errors-DOSkVeTC.js +127 -0
  180. package/dist/errors-DUJ7wLlE.d.ts +137 -0
  181. package/dist/errors-Da88YLm5.js +26 -0
  182. package/dist/errors-DgLOqc6j.js +148 -0
  183. package/dist/errors-KngVdJT9.d.ts +12 -0
  184. package/dist/evaluate-D8SdfP3h.js +1948 -0
  185. package/dist/evaluations-BQkpE7hC.js +609 -0
  186. package/dist/evaluations-K9qglDP7.d.ts +36 -0
  187. package/dist/evaluator-Dlhn2d7D.js +2 -0
  188. package/dist/evaluator-eager-UuJK6NX_.js +8 -0
  189. package/dist/eve/index.d.ts +11 -10
  190. package/dist/eve/index.js +7 -8
  191. package/dist/event-time-ChIrhzy5.js +26 -0
  192. package/dist/execute-SN8_dlch.js +166 -0
  193. package/dist/express/index.d.ts +6 -8
  194. package/dist/express/index.js +6 -7
  195. package/dist/fastify/index.d.ts +5 -11
  196. package/dist/fastify/index.js +6 -8
  197. package/dist/fetch-adapter-gmTCu4FR.d.ts +32 -0
  198. package/dist/fetch-adapter-ovZdSvlT.js +124 -0
  199. package/dist/fields-6d1j-q3c.js +502 -0
  200. package/dist/fields-C0L2FoZk.js +25 -0
  201. package/dist/files-DAR51W3J.js +157 -0
  202. package/dist/files-DuV7wRim.js +139 -0
  203. package/dist/fixtures-Bm0G0A7H.js +79 -0
  204. package/dist/flags-C0e-BzGW.js +112 -0
  205. package/dist/freeze-DGfJq_j2.js +86 -0
  206. package/dist/from-snapshot-CCDF_ihX.js +173 -0
  207. package/dist/gen-B4GUqsfM.js +1160 -0
  208. package/dist/gen-BC66z5Fd.js +1 -0
  209. package/dist/gen-kind-Bahz_i3U.js +67 -0
  210. package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
  211. package/dist/generate-5_kz2309.js +305 -0
  212. package/dist/generate-B-msjuaO.js +2339 -0
  213. package/dist/generate-CbtjKcjn.js +67 -0
  214. package/dist/generate-DhP0jQDR.js +97 -0
  215. package/dist/generate-options-BDgadlwe.js +1104 -0
  216. package/dist/grantee-BPUG6f0r.js +109 -0
  217. package/dist/grantee-conditions-Dob6QQAc.js +270 -0
  218. package/dist/grantee-match-CFQ-LRcL.js +147 -0
  219. package/dist/grants-BzjbUCdR.js +139 -0
  220. package/dist/graph-sql-Ds3nbevr.d.ts +27 -0
  221. package/dist/h3/index.d.ts +4 -6
  222. package/dist/h3/index.js +4 -5
  223. package/dist/headers-D1oRr-js.d.ts +8 -0
  224. package/dist/helpers-DSmj6SHi.js +533 -0
  225. package/dist/hono/index.d.ts +6 -8
  226. package/dist/hono/index.js +7 -8
  227. package/dist/hook-sql-BIR4fL7i.js +3412 -0
  228. package/dist/hosted-DMJKJPoc.js +361 -0
  229. package/dist/hosted-DUbuh0Td.d.ts +100 -0
  230. package/dist/http-BUIYu1Kc.d.ts +10 -0
  231. package/dist/http-BbX_Ou3_.js +48 -0
  232. package/dist/http-C9jDw_bZ.js +82 -0
  233. package/dist/http-dNltTpC8.js +71 -0
  234. package/dist/ids-0QDIxtxL.js +53 -0
  235. package/dist/import-BZi1tZxq.js +318 -0
  236. package/dist/import-BqoDHpFt.js +1158 -0
  237. package/dist/index-BXz-XXC3.d.ts +1108 -0
  238. package/dist/index-CVuc3E1O.d.ts +196 -0
  239. package/dist/index-Cq9N5B92.d.ts +506 -0
  240. package/dist/index-D8A1d_Tt.d.ts +214 -0
  241. package/dist/index-DegTwZxD.d.ts +93 -0
  242. package/dist/index-O0qbI8Ha.d.ts +221 -0
  243. package/dist/index.d.ts +24 -25
  244. package/dist/index.js +47 -46
  245. package/dist/init-9cqnSJWG.js +95 -0
  246. package/dist/init-K3tKOwf4.js +94 -0
  247. package/dist/instance-options-B4MD2wgl.d.ts +9 -0
  248. package/dist/instance-options-CLErhA76.js +23 -0
  249. package/dist/instance-snapshot-DdGOpSfN.js +716 -0
  250. package/dist/instant-Ih5riY_A.js +18 -0
  251. package/dist/interactive-only-BZu9rLpa.js +1567 -0
  252. package/dist/internals-D58TnmDB.js +19 -0
  253. package/dist/json-schema-SDkWXxhu.d.ts +38 -0
  254. package/dist/json-schema-jtX26ydD.js +148 -0
  255. package/dist/jwt/index.d.ts +6 -24
  256. package/dist/jwt/index.js +18 -26
  257. package/dist/kernel-Dn6pKMAF.js +423 -0
  258. package/dist/kysely/index.d.ts +5 -9
  259. package/dist/kysely/index.js +5 -6
  260. package/dist/lazy-provider-CydlnKkS.d.ts +4 -0
  261. package/dist/lazy-provider-DG5rMeqL.js +28 -0
  262. package/dist/limits-DpTxX6N4.js +166 -0
  263. package/dist/live-options-CIUmc-YQ.js +70 -0
  264. package/dist/load-BPzIqlGB.js +1 -0
  265. package/dist/load-CZnlAyZ8.js +98 -0
  266. package/dist/load-jose-CjzIBSKI.js +7 -0
  267. package/dist/login-C1I5KIsK.js +67 -0
  268. package/dist/login-CP0UxnLw.js +255 -0
  269. package/dist/lru-Cp-AEvpR.js +27 -0
  270. package/dist/manifest-B-8d2lhG.js +45 -0
  271. package/dist/manifest-CRHphHxo.d.ts +362 -0
  272. package/dist/manifest-DvS2IoXo.js +399 -0
  273. package/dist/manifest-json-DMaBWmcG.js +8 -0
  274. package/dist/manifest-schema-DJY5Q_pR.js +507 -0
  275. package/dist/map-claims-BKdnPwep.js +386 -0
  276. package/dist/map-error-DTi_JZT8.js +22 -0
  277. package/dist/markers-C-kThnKN.js +79 -0
  278. package/dist/may-use-Died1tNU.js +233 -0
  279. package/dist/mcp/index.d.ts +11 -21
  280. package/dist/mcp/index.js +56 -43
  281. package/dist/membership-filter-CSKH48eD.js +66 -0
  282. package/dist/migrate-CmTMk7rd.js +536 -0
  283. package/dist/model-B4EKVHMK.js +188 -0
  284. package/dist/module-values-Ddx0GLaJ.js +106 -0
  285. package/dist/nest/index.d.ts +7 -13
  286. package/dist/nest/index.js +12 -15
  287. package/dist/next/client.d.ts +1 -3
  288. package/dist/next/client.js +2 -3
  289. package/dist/next/index.d.ts +36 -16
  290. package/dist/next/index.js +161 -31
  291. package/dist/next/plugin.d.ts +1 -3
  292. package/dist/next/plugin.js +3 -4
  293. package/dist/node/index.d.ts +6 -8
  294. package/dist/node/index.js +4 -5
  295. package/dist/oauth-security-C8fjzFRF.js +25 -0
  296. package/dist/ocsf-DKRQc6uv.js +135 -0
  297. package/dist/openai/index.d.ts +5 -7
  298. package/dist/openai/index.js +5 -6
  299. package/dist/openapi/index.d.ts +4 -16
  300. package/dist/openapi/index.js +4 -3
  301. package/dist/openapi-BHqqNSoG.js +95 -0
  302. package/dist/openapi-BT5XY7HY.js +260 -0
  303. package/dist/openapi-D2dmyWZK.js +411 -0
  304. package/dist/openapi-document-Ca5yAjc6.js +35 -0
  305. package/dist/operation-findings-D5Uo-dcm.js +35 -0
  306. package/dist/operation-risks-BD-j14dj.js +12 -0
  307. package/dist/operations-B0yO77Zz.js +290 -0
  308. package/dist/operations-BS8ExH5A.d.ts +58 -0
  309. package/dist/operations-De3F7tlf.js +88 -0
  310. package/dist/optional-CaQWp9HA.js +46 -0
  311. package/dist/orpc/index.d.ts +8 -12
  312. package/dist/orpc/index.js +10 -12
  313. package/dist/otel/index.d.ts +3 -5
  314. package/dist/otel/index.js +5 -7
  315. package/dist/output-djxu62oH.js +244 -0
  316. package/dist/output-files-C5LFnQa4.js +1 -0
  317. package/dist/output-files-DNid6TBl.js +197 -0
  318. package/dist/ownership-BO0sI5FB.js +558 -0
  319. package/dist/parse-local-manifest-BGLWVchi.d.ts +8 -0
  320. package/dist/parse-local-manifest-CfMjZAFi.js +67 -0
  321. package/dist/parse-nfHSt1Wy.js +149 -0
  322. package/dist/parse-request-IEEzVFM8.js +24 -0
  323. package/dist/parse-sink-events-B6nZx41L.js +125 -0
  324. package/dist/paths-CeS_gpHf.js +44 -0
  325. package/dist/pdp/index.d.ts +3 -9
  326. package/dist/pdp/index.js +22 -18
  327. package/dist/peer-BWTpSLs2.js +1 -0
  328. package/dist/peer-D77JpXe-.js +978 -0
  329. package/dist/perf-token-dFGVP14-.js +155 -0
  330. package/dist/permdock-BueSeg7X.js +1514 -0
  331. package/dist/permdock-Dz3yzWrp.d.ts +853 -0
  332. package/dist/permission-registry-DMYRZVcn.js +413 -0
  333. package/dist/permissions-CQW3cr2S.js +17 -0
  334. package/dist/permissions-DWULToSb.d.ts +52 -0
  335. package/dist/permissions-ijDw4sO1.js +144 -0
  336. package/dist/pg-CA651850.js +59 -0
  337. package/dist/pins-CXXkVEiD.js +14 -0
  338. package/dist/pipeline-CXuwijr2.js +307 -0
  339. package/dist/pkce-DdsRBK7n.js +20 -0
  340. package/dist/plugin-DGmbeXwA.d.ts +221 -0
  341. package/dist/plugin-MQVfUBUS.js +93 -0
  342. package/dist/plugin-outputs-BE2YCiMj.js +28 -0
  343. package/dist/policy-BhSUlHRr.js +37 -0
  344. package/dist/policy-C-Lzp3Zh.d.ts +18 -0
  345. package/dist/policy-DFD2J5o_.js +476 -0
  346. package/dist/policy-bundle-97xaDULc.js +82 -0
  347. package/dist/policy-from-catalog-YKaTeaco.js +452 -0
  348. package/dist/policy-module-Bp4HvsRg.js +107 -0
  349. package/dist/policy-types-93NwI8iI.d.ts +2855 -0
  350. package/dist/postgres-store-CYFvw98w.js +1023 -0
  351. package/dist/postgrest-DyrYo_XT.d.ts +138 -0
  352. package/dist/powersync-CN7IQIKk.js +40 -0
  353. package/dist/powersync-DdDLP02A.js +1630 -0
  354. package/dist/powersync-m9uYgCFF.js +1 -0
  355. package/dist/preset/index.d.ts +0 -12
  356. package/dist/preset/index.js +1 -1
  357. package/dist/preset-BcFDaeqd.js +1849 -0
  358. package/dist/principal-source-BIcukkB3.js +102 -0
  359. package/dist/prisma/index.d.ts +4 -12
  360. package/dist/prisma/index.js +10 -14
  361. package/dist/problem-BZB7zPC7.js +202 -0
  362. package/dist/problem-details-EJHcvYCz.js +154 -0
  363. package/dist/problem-types-81BEw0IN.js +7 -0
  364. package/dist/prompt-CSXHcJxy.js +931 -0
  365. package/dist/protected-action-BMb0ftEu.js +241 -0
  366. package/dist/protected-action-D6T3eJyW.d.ts +73 -0
  367. package/dist/protected-action-DiXulRVj.js +78 -0
  368. package/dist/provider-BnnFjtWI.js +893 -0
  369. package/dist/provider-ClD4rfgT.js +11 -0
  370. package/dist/provider-CydlnKkS.d.ts +4 -0
  371. package/dist/provider-store-atQUfsVO.js +51 -0
  372. package/dist/provider-with-CSw4mBDU.js +70 -0
  373. package/dist/public-api-DIMZmzWi.js +5579 -0
  374. package/dist/pull-9oQvY18T.js +252 -0
  375. package/dist/pull-jvJPMQhP.js +1 -0
  376. package/dist/push-Cb7PqXdO.js +158 -0
  377. package/dist/pushed-policy-pH-EFWyx.d.ts +61 -0
  378. package/dist/pushed-policy-rpB6k77P.js +240 -0
  379. package/dist/quote-BKrTBbcH.js +36 -0
  380. package/dist/rbac-B-49toAp.js +90 -0
  381. package/dist/react/index.d.ts +10 -9
  382. package/dist/react/index.js +8 -7
  383. package/dist/react/lazy.d.ts +10 -12
  384. package/dist/react/lazy.js +8 -35
  385. package/dist/react/provider-client-lazy.d.ts +2 -0
  386. package/dist/react/provider-client-lazy.js +2 -0
  387. package/dist/react/provider-client.d.ts +1 -1
  388. package/dist/react/provider-client.js +1 -1
  389. package/dist/react-native/index.d.ts +12 -30
  390. package/dist/react-native/index.js +31 -41
  391. package/dist/read-memberships-BkePIa1F.js +63 -0
  392. package/dist/refresh-on-C1zIMtJr.d.ts +47 -0
  393. package/dist/refresh-online-CYGZNo6V.js +19 -0
  394. package/dist/refresh-online-vtUfV6dk.d.ts +10 -0
  395. package/dist/refs-Cix9Zjis.js +103 -0
  396. package/dist/relation-walk-BlWy9gBK.js +188 -0
  397. package/dist/relations-CIgB5KPJ.js +162 -0
  398. package/dist/replay-ClGIMp5p.d.ts +3 -0
  399. package/dist/replay-X2m6moK1.js +28 -0
  400. package/dist/request-context-CVJodWx8.js +70 -0
  401. package/dist/request-context-E3-ps-H_.d.ts +3 -0
  402. package/dist/request-schema-DzEoR310.js +155 -0
  403. package/dist/resend/index.d.ts +4 -10
  404. package/dist/resend/index.js +14 -17
  405. package/dist/resolve-names-Cmg6SPAa.js +266 -0
  406. package/dist/resolver-kdZ4HrpC.js +404 -0
  407. package/dist/resource-ref-BiQtFK-I.js +19 -0
  408. package/dist/resource-relations-Ck5sjYQR.js +251 -0
  409. package/dist/retire-BNiXnbBR.js +248 -0
  410. package/dist/revocations-3jyzniOz.js +26 -0
  411. package/dist/revocations-ku_f2d2y.d.ts +24 -0
  412. package/dist/rls-BrsMogAP.js +321 -0
  413. package/dist/rls-Cv1V8YfI.js +946 -0
  414. package/dist/rls-files-Bj446vbj.js +114 -0
  415. package/dist/rls-options-Dpj_pEyU.d.ts +26 -0
  416. package/dist/role-builder-DhsGEVq-.js +501 -0
  417. package/dist/role-grants-Bk6ZsaS0.js +46 -0
  418. package/dist/roles-B29psCem.js +29 -0
  419. package/dist/rolldown-runtime-B8NLbhFH.js +3 -0
  420. package/dist/row-conditions-DwIJocfQ.js +27 -0
  421. package/dist/row-pair-CxEhErJU.js +33 -0
  422. package/dist/rpc-B-4IZOiU.js +111 -0
  423. package/dist/rpc-DjgxFbjK.d.ts +18 -0
  424. package/dist/run-DX4D6S6V.js +726 -0
  425. package/dist/run-decqEKNa.js +1 -0
  426. package/dist/run-ticket-D6T39Xdi.js +370 -0
  427. package/dist/run-ticket-DXwrko2J.d.ts +157 -0
  428. package/dist/runtime-Cl6xSbEq.js +13 -0
  429. package/dist/saas-DzjKUQr5.js +1218 -0
  430. package/dist/scan-Cj7PQLrS.js +28 -0
  431. package/dist/schema-BeY3croo.js +403 -0
  432. package/dist/schema-CJPvTfeN.js +133 -0
  433. package/dist/scim/index.d.ts +2 -2
  434. package/dist/scim/index.js +2 -2
  435. package/dist/scim-B9QyJ23q.js +1046 -0
  436. package/dist/scopes-B-KX9EI8.js +238 -0
  437. package/dist/seed-sql-CjF7u0aX.js +60 -0
  438. package/dist/seeds/index.d.ts +2 -0
  439. package/dist/seeds/index.js +1 -0
  440. package/dist/seeds-BDTG7xl-.js +53 -0
  441. package/dist/seeds-uG196Ev4.d.ts +73 -0
  442. package/dist/server/index.d.ts +13 -13
  443. package/dist/server/index.js +14 -14
  444. package/dist/server-Co9CYGqk.js +146 -0
  445. package/dist/server-types-BrHOGAYx.d.ts +318 -0
  446. package/dist/sha256-DFsnyVPo.js +157 -0
  447. package/dist/shared-BOsJIQf4.js +124 -0
  448. package/dist/shared-BdF5DJDQ.js +330 -0
  449. package/dist/signals-a1NxAP0X.js +31 -0
  450. package/dist/sink-BD34OS8T.d.ts +247 -0
  451. package/dist/sink-Bgvf9lIz.js +966 -0
  452. package/dist/size-DF7xQ-nH.js +95 -0
  453. package/dist/skills-B5bc6JIA.js +50 -0
  454. package/dist/skills-Cr1C0b9D.js +202 -0
  455. package/dist/snapshot-DckMnHk8.js +352 -0
  456. package/dist/snapshot-cache-DTTEfmxv.js +69 -0
  457. package/dist/snapshot-cache-DoP3avLl.d.ts +68 -0
  458. package/dist/snapshot-compact-CwAop_6C.js +119 -0
  459. package/dist/snapshot-empty-DZ6sZ83n.js +17 -0
  460. package/dist/snapshot-evaluate-9RGy7J3N.js +552 -0
  461. package/dist/snapshot-reads-D775amTL.js +65 -0
  462. package/dist/snapshot-size-D-pCR8x0.js +139 -0
  463. package/dist/snapshot-size-DU7CvpMt.js +1 -0
  464. package/dist/solid/index.d.ts +18 -20
  465. package/dist/solid/index.js +15 -19
  466. package/dist/solid-start/index.d.ts +6 -8
  467. package/dist/solid-start/index.js +4 -5
  468. package/dist/sources-BbSUNmFX.js +10 -0
  469. package/dist/sources-DnjJPGfb.js +657 -0
  470. package/dist/sources-NQio1yFq.d.ts +727 -0
  471. package/dist/sql-BYYNi1lu.d.ts +8 -0
  472. package/dist/sql-T4GaBh9X.js +93 -0
  473. package/dist/src-D6_T4zd7.js +1811 -0
  474. package/dist/ssf/index.d.ts +3 -3
  475. package/dist/ssf/index.js +20 -31
  476. package/dist/standard-webhooks-B3MQihcP.d.ts +86 -0
  477. package/dist/standard-webhooks-BtIkXclH.js +227 -0
  478. package/dist/storage-BhGDhsXm.js +131 -0
  479. package/dist/store-AH8bmaxW.js +377 -0
  480. package/dist/store-core-eqG8jijs.d.ts +306 -0
  481. package/dist/store-options-C8x39AHa.js +1034 -0
  482. package/dist/stores-4DOaL4ZP.d.ts +58 -0
  483. package/dist/stores-DoA7ACkz.js +127 -0
  484. package/dist/stream-DdF94h7T.js +73 -0
  485. package/dist/style-CQDaLJtP.js +24 -0
  486. package/dist/style-Crf-90o6.js +1 -0
  487. package/dist/subject-DkxY-AhF.js +23 -0
  488. package/dist/subject-cache-BZeSj4Xf.d.ts +156 -0
  489. package/dist/subject-settings-BO-frcYx.js +147 -0
  490. package/dist/subject-settings-C9F1sU1d.d.ts +48 -0
  491. package/dist/supabase/client.d.ts +1 -1
  492. package/dist/supabase/client.js +2 -3
  493. package/dist/supabase/index.d.ts +77 -24
  494. package/dist/supabase/index.js +9 -8
  495. package/dist/supabase/middleware.d.ts +27 -9
  496. package/dist/supabase/middleware.js +51 -21
  497. package/dist/supabase-BG1HPdQU.js +30 -0
  498. package/dist/supabase-BI5ZhzLl.js +792 -0
  499. package/dist/supabase-config-mXcggV5I.js +890 -0
  500. package/dist/supabase-hook-hd9abKy4.js +2 -0
  501. package/dist/supabase-hook-tdR45aXY.js +405 -0
  502. package/dist/supabase-outcome-CMLuLW-V.js +9 -0
  503. package/dist/supautils-DXzJ2E2Q.js +96 -0
  504. package/dist/support-session-B8xrW28B.js +157 -0
  505. package/dist/svelte/index.d.ts +8 -10
  506. package/dist/svelte/index.js +12 -15
  507. package/dist/svelte/runtime.d.ts +4 -6
  508. package/dist/svelte/runtime.js +4 -4
  509. package/dist/svelte/source.d.ts +8 -10
  510. package/dist/svelte/source.js +6 -7
  511. package/dist/sveltekit/index.d.ts +6 -8
  512. package/dist/sveltekit/index.js +3 -4
  513. package/dist/tables-CRTCBuFi.js +3240 -0
  514. package/dist/tanstack-start/index.d.ts +6 -8
  515. package/dist/tanstack-start/index.js +3 -4
  516. package/dist/target-BGpxgKsN.js +50 -0
  517. package/dist/tenancy-B5Xxt9Sc.js +223 -0
  518. package/dist/terminal/index.d.ts +6 -16
  519. package/dist/terminal/index.js +18 -23
  520. package/dist/testing/core.d.ts +1 -1
  521. package/dist/testing/core.js +1 -1
  522. package/dist/testing/fixtures/index.d.ts +12 -10
  523. package/dist/testing/fixtures/index.js +48 -25
  524. package/dist/testing/index.d.ts +85 -85
  525. package/dist/testing/index.js +226 -115
  526. package/dist/testing/saas/index.d.ts +5 -15
  527. package/dist/testing/saas/index.js +2 -2
  528. package/dist/testing/saas/permissions.d.ts +1 -1
  529. package/dist/testing/saas/permissions.js +1 -1
  530. package/dist/text-D704xHVl.js +7 -0
  531. package/dist/text-diff-CsglY49A.js +440 -0
  532. package/dist/thenable-BxMy2v8w.js +39 -0
  533. package/dist/time-r0CKBm57.js +94 -0
  534. package/dist/timeout-nOqLpU2I.js +7 -0
  535. package/dist/token-BgswTQzt.d.ts +9 -0
  536. package/dist/token-CSljQqzA.js +76 -0
  537. package/dist/tool-refusal-DzCSbjp8.js +43 -0
  538. package/dist/trpc/index.d.ts +7 -9
  539. package/dist/trpc/index.js +7 -8
  540. package/dist/type-helpers-DHCQEPj8.d.ts +47 -0
  541. package/dist/types-3pRMqcvw.d.ts +84 -0
  542. package/dist/types-BFtFaI1W.d.ts +66 -0
  543. package/dist/types-BdNdMix7.d.ts +263 -0
  544. package/dist/types-C7QtRn3n.d.ts +66 -0
  545. package/dist/types-CVCRFYY_.d.ts +102 -0
  546. package/dist/types-CWmBZtQN.d.ts +274 -0
  547. package/dist/types-Cakw89Wx.d.ts +372 -0
  548. package/dist/types-D3tjoLwT.d.ts +124 -0
  549. package/dist/types-D8VXQxKL.d.ts +1231 -0
  550. package/dist/types-DFZKovb3.js +77 -0
  551. package/dist/types-DONLJQjY.d.ts +134 -0
  552. package/dist/types-OzSal_K_.d.ts +178 -0
  553. package/dist/types-XSfi6ihL.d.ts +65 -0
  554. package/dist/unplugin/index.d.ts +1 -3
  555. package/dist/unplugin/index.js +3 -4
  556. package/dist/usage-B-E747wO.js +31 -0
  557. package/dist/usage-B7nx0_aa.js +761 -0
  558. package/dist/usage-rqQ9ViXv.js +1 -0
  559. package/dist/validation-error-BAO1W1yk.d.ts +27 -0
  560. package/dist/validation-error-CgDOA6VS.js +35 -0
  561. package/dist/validity-YNEEm2MZ.js +56 -0
  562. package/dist/verifier-BIYkGcJc.js +530 -0
  563. package/dist/verify-9HObfifg.js +1102 -0
  564. package/dist/version-CU6e2wxV.js +7 -0
  565. package/dist/version-D-jWyJb9.js +46 -0
  566. package/dist/version-DcZCjWXb.js +1 -0
  567. package/dist/version-cache-BXkl7-Fz.js +462 -0
  568. package/dist/views-Dpr1uB16.js +164 -0
  569. package/dist/vocabulary-CE2k7s1a.js +157 -0
  570. package/dist/vocabulary-FYgI_NoI.d.ts +400 -0
  571. package/dist/vue/index.d.ts +18 -20
  572. package/dist/vue/index.js +13 -18
  573. package/dist/waiter-DKdFHKVZ.js +66 -0
  574. package/dist/waiter-hYLJXA7r.d.ts +37 -0
  575. package/dist/watch-BecZtEdU.js +155 -0
  576. package/dist/watch-CiN6WU9k.js +221 -0
  577. package/dist/watch-NAUnUXph.js +1 -0
  578. package/dist/webmcp/index.d.ts +2 -6
  579. package/dist/webmcp/index.js +8 -9
  580. package/dist/who-can-rUSZfLvI.js +366 -0
  581. package/dist/wire-delegation-DC5Cyec4.js +35 -0
  582. package/dist/wire-denial-BcRQnA7p.js +26 -0
  583. package/dist/workflow/index.d.ts +3 -3
  584. package/dist/workflow/index.js +12 -14
  585. package/dist/workflow-sdk/index.d.ts +6 -8
  586. package/dist/workflow-sdk/index.js +2 -3
  587. package/dist/wrap-CsfsaJhd.js +32 -0
  588. package/dist/wrap-D-KvhzaC.d.ts +16 -0
  589. package/package.json +83 -39
  590. package/schemas/catalog-v2.json +665 -0
  591. package/schemas/cli-commands-v1.json +1 -1
  592. package/schemas/cli-result-v2.json +163 -0
  593. package/schemas/cloud-api-v1.json +1 -1
  594. package/schemas/snapshot-v1.json +26 -0
  595. package/schemas/supabase-claims-v1.json +5 -1
  596. package/schemas/supabase-manifest-v1.json +11 -2
  597. package/skills/permdock/SKILL.md +1 -1
  598. package/skills/permdock-data/references/queries-and-rls.md +2 -1
  599. package/skills/permdock-wire/references/adapters.md +5 -3
  600. package/dist/2020-CJbO8Bvz.js +0 -6773
  601. package/dist/active-tenant-DVee32-T.js +0 -39
  602. package/dist/adapter-context-OHikyRqV.js +0 -29
  603. package/dist/adoption-scan-8F9VSQrK.js +0 -107
  604. package/dist/app-J9PE1LNm.js +0 -24
  605. package/dist/app-data-UNNm07jV.js +0 -63
  606. package/dist/approval-header-8QV6MU4H.js +0 -26
  607. package/dist/approval-normalize-KfhzpD93.js +0 -196
  608. package/dist/approval-policies-BiXMlYBu.d.ts +0 -138
  609. package/dist/approval-prompt-B8hQY69x.js +0 -61
  610. package/dist/approval-prompt-j5PTItiy.d.ts +0 -59
  611. package/dist/approval-required-TzNB9oQA.js +0 -6
  612. package/dist/approvals-BfzI8Foe.js +0 -1048
  613. package/dist/approvers-BaNwKYgd.js +0 -77
  614. package/dist/arazzo-BUVqRmaJ.js +0 -36
  615. package/dist/arazzo-CWmM8pWw.js +0 -77
  616. package/dist/args-iafbHiXn.js +0 -311
  617. package/dist/audience-DLoopY4q.js +0 -55
  618. package/dist/auth-BxXHxWRy.js +0 -189
  619. package/dist/authz-topic-Dbc-HDOS.js +0 -15
  620. package/dist/automation-BueW05db.js +0 -158
  621. package/dist/automation-_iGeP54L.d.ts +0 -124
  622. package/dist/base-url-BQbddZO5.js +0 -9
  623. package/dist/better-supabase-DF8f8oly.js +0 -194
  624. package/dist/bind-CTj4dHc1.d.ts +0 -58
  625. package/dist/bind-LQ6zbARV.js +0 -125
  626. package/dist/body-Cy9S8zhw.js +0 -10
  627. package/dist/body-text-DQhcmqdY.js +0 -56
  628. package/dist/boundary-BV3O1eud.js +0 -19
  629. package/dist/boundary-C9ck-3uK.d.ts +0 -24
  630. package/dist/budget-BBCPDOGP.js +0 -14
  631. package/dist/budget-CNLsV2SL.d.ts +0 -14
  632. package/dist/build-instance-Bq8wkJ4i.js +0 -31
  633. package/dist/canonical-json-DwilZ1iB.js +0 -29
  634. package/dist/capability-CenWwTMR.js +0 -205
  635. package/dist/capability-DqCyFGip.d.ts +0 -130
  636. package/dist/casbin-DIvUMac7.js +0 -242
  637. package/dist/casbin-qpG_ZphP.js +0 -30
  638. package/dist/casl-CjBVJj8R.js +0 -24
  639. package/dist/casl-CkBssiB1.js +0 -308
  640. package/dist/catalog-B1MAmRQI.js +0 -131
  641. package/dist/catalog-BCVIH7kq.js +0 -1
  642. package/dist/catalog-CaZoXBD8.js +0 -52
  643. package/dist/catalog-doc-DnQDviXY.js +0 -353
  644. package/dist/catalog-fingerprint-e6aCWosn.js +0 -157
  645. package/dist/catalog-operations-Do1eD-Rt.js +0 -60
  646. package/dist/catalog-path-CnI0XTFK.js +0 -12
  647. package/dist/challenge-DKJpP-5P.js +0 -521
  648. package/dist/checks-fyDOhcz0.js +0 -72
  649. package/dist/claims-map-CKkoAAYF.js +0 -16
  650. package/dist/claims-map-D1Pb5oRq.d.ts +0 -35
  651. package/dist/client-JK504UCq.d.ts +0 -45
  652. package/dist/clients-C_NOET3z.d.ts +0 -12
  653. package/dist/clients-DYr3U86j.js +0 -23
  654. package/dist/cloud-CXgE1qpa.js +0 -86
  655. package/dist/codemod-BJ0Kgv9b.js +0 -36
  656. package/dist/codemod-DjgVx3RQ.js +0 -2800
  657. package/dist/collect-BG-SXFQv.js +0 -537
  658. package/dist/collect-CxPJRjoc.js +0 -55
  659. package/dist/collect-ZLgHgujd.js +0 -1
  660. package/dist/command-L8EstFNm.js +0 -6
  661. package/dist/compact-CAf557ZB.js +0 -29
  662. package/dist/compare-DTfyUunF.js +0 -12
  663. package/dist/compile-Cvru58id.js +0 -661
  664. package/dist/compile-Dh9pW_Co.d.ts +0 -120
  665. package/dist/completion-DUHSRdoQ.js +0 -152
  666. package/dist/config-CgA_Z5Ts.js +0 -26
  667. package/dist/config-DC7aiuhP.js +0 -116
  668. package/dist/config-report-B31MnuKf.js +0 -56
  669. package/dist/config-shape-ChhsuGSV.js +0 -147
  670. package/dist/connection-zoAgwdsD.js +0 -197
  671. package/dist/connector-schema-CYLQNMYq.js +0 -434
  672. package/dist/constants-DcJABbLW.js +0 -20
  673. package/dist/context-BXM0MDB0.js +0 -95
  674. package/dist/core-BTJlqWsv.js +0 -341
  675. package/dist/core-BhZEo5Le.d.ts +0 -206
  676. package/dist/coverage-BuGlwUms.d.ts +0 -135
  677. package/dist/coverage-CGu_Kovx.js +0 -261
  678. package/dist/create--q7-j0hX.d.ts +0 -127
  679. package/dist/create-C5IQw_-i.d.ts +0 -191
  680. package/dist/create-CYj0cjTu.d.ts +0 -128
  681. package/dist/create-D7D94oNh.js +0 -376
  682. package/dist/create-DaddhCIg.js +0 -134
  683. package/dist/credential-BMsbcaeP.js +0 -431
  684. package/dist/credentials-BZU7Twpt.js +0 -310
  685. package/dist/credentials-Bq-Xa7Vq.d.ts +0 -125
  686. package/dist/credentials-dkycUsY3.js +0 -74
  687. package/dist/decide-set-DXEPepY1.js +0 -100
  688. package/dist/deciding-columns-NB4wcyBf.js +0 -134
  689. package/dist/decision-CaG5_eNJ.js +0 -21
  690. package/dist/delegation-CrdqnesZ.js +0 -262
  691. package/dist/delegation-input-DcXhiMkf.js +0 -19
  692. package/dist/delivery-BupfvJIV.js +0 -560
  693. package/dist/delivery-event-JioK5YbS.js +0 -40
  694. package/dist/denied-text-B6s29jcf.d.ts +0 -22
  695. package/dist/describe-BZAlPHxT.js +0 -101
  696. package/dist/describe-DwcoWMLB.d.ts +0 -45
  697. package/dist/device-BkSynWdg.js +0 -196
  698. package/dist/diff-BnYHpRSI.js +0 -466
  699. package/dist/diff-H75YU6Q-.js +0 -37
  700. package/dist/digest-8Yx2CchM.d.ts +0 -19
  701. package/dist/digest-BI-6aa6d.js +0 -27
  702. package/dist/doctor-Dvt1_ROJ.js +0 -3560
  703. package/dist/doctor-JLouRSQt.js +0 -54
  704. package/dist/env-DJZrPjRi.js +0 -8
  705. package/dist/errors-BDUwg2qC.js +0 -27
  706. package/dist/errors-BhRkoNS7.js +0 -145
  707. package/dist/errors-CHwoRRpB.d.ts +0 -14
  708. package/dist/errors-D_SnqcRn.d.ts +0 -141
  709. package/dist/errors-ynga1EQy.js +0 -128
  710. package/dist/evaluate-BQ2nWOki.js +0 -1905
  711. package/dist/evaluations-BVtY66lF.d.ts +0 -38
  712. package/dist/evaluations-Bj5xw0EM.js +0 -612
  713. package/dist/evaluator-CDl2YUd_.js +0 -2
  714. package/dist/evaluator-eager-CULtQ8t6.js +0 -9
  715. package/dist/event-time-BGy48400.js +0 -27
  716. package/dist/fetch-adapter-BJ76IZZg.d.ts +0 -34
  717. package/dist/fetch-adapter-CXeBg4CH.js +0 -124
  718. package/dist/fields-D9PIYlJy.js +0 -504
  719. package/dist/fields-DlKwZYiy.js +0 -26
  720. package/dist/files-BSjrtIHw.js +0 -141
  721. package/dist/files-CfiRtQ-m.js +0 -140
  722. package/dist/fixtures-BVZc7OCF.js +0 -80
  723. package/dist/flags-BlmpmXoY.js +0 -86
  724. package/dist/freeze-jjan0lCv.js +0 -63
  725. package/dist/from-snapshot-FdVXG_QZ.js +0 -159
  726. package/dist/gen-D17P8vo0.js +0 -827
  727. package/dist/gen-YA3SK59O.js +0 -58
  728. package/dist/generate-BqkZq8Dr.js +0 -165
  729. package/dist/generate-CezbCaTI.js +0 -275
  730. package/dist/grantee-OG4klcNr.js +0 -110
  731. package/dist/grantee-conditions-Dzprappv.js +0 -271
  732. package/dist/grantee-match-CPQ9zV-H.js +0 -148
  733. package/dist/graph-sql-BwFC4Qjs.d.ts +0 -29
  734. package/dist/headers-B9jQxjtW.d.ts +0 -10
  735. package/dist/helpers-CO2hDpBU.js +0 -537
  736. package/dist/hosted-CQW_YNx7.js +0 -362
  737. package/dist/hosted-D5StFpKa.d.ts +0 -102
  738. package/dist/http-B_LphE5Y.d.ts +0 -12
  739. package/dist/http-DH94eh6f.js +0 -72
  740. package/dist/http-DKLXrFGk.js +0 -83
  741. package/dist/http-dptLQzPP.js +0 -49
  742. package/dist/ids-DzhJaCUj.js +0 -55
  743. package/dist/import-B8zbuskR.js +0 -5950
  744. package/dist/import-BYYXmHvP.js +0 -1143
  745. package/dist/index-B1-tE0Kx.d.ts +0 -1159
  746. package/dist/index-BwSEp_O5.d.ts +0 -210
  747. package/dist/index-CB_eM-qx.d.ts +0 -101
  748. package/dist/index-CvcE9mYP.d.ts +0 -234
  749. package/dist/index-D7sMtTf6.d.ts +0 -542
  750. package/dist/index-d7f0hNss.d.ts +0 -233
  751. package/dist/init-BdgWNuc3.js +0 -96
  752. package/dist/init-DKRhYiGW.js +0 -95
  753. package/dist/instance-options-DhQVCuhT.d.ts +0 -11
  754. package/dist/instance-options-URVwqpMW.js +0 -24
  755. package/dist/instance-snapshot-DyG_5ASl.js +0 -693
  756. package/dist/instant-DK3Iz83e.js +0 -19
  757. package/dist/internals-B3IgHrvo.js +0 -20
  758. package/dist/json-schema-BPGa-RjQ.js +0 -149
  759. package/dist/json-schema-BfXgnRNT.d.ts +0 -40
  760. package/dist/kernel-D9AxUqmz.js +0 -427
  761. package/dist/limits-CAhpRrhk.js +0 -167
  762. package/dist/live-options-BBIT68le.js +0 -73
  763. package/dist/load-C4p4VgwR.js +0 -99
  764. package/dist/load-DiBUJx77.js +0 -1
  765. package/dist/load-jose-DZ4dnjri.js +0 -8
  766. package/dist/login-DEvccJwP.js +0 -68
  767. package/dist/login-IIUDSAYW.js +0 -257
  768. package/dist/lru-8q4WZjBV.js +0 -28
  769. package/dist/manifest-BoCYBbQL.js +0 -46
  770. package/dist/manifest-C6eFl3Vo.d.ts +0 -349
  771. package/dist/manifest-CZ-GmsOL.js +0 -401
  772. package/dist/manifest-json-CAGzls-C.js +0 -9
  773. package/dist/manifest-schema-svAkgqMc.js +0 -501
  774. package/dist/map-claims-CAa_bQt9.js +0 -387
  775. package/dist/map-error-BCdb2Nrp.js +0 -23
  776. package/dist/markers-BeHZ4x9Q.js +0 -80
  777. package/dist/may-use-WDhFPqGG.js +0 -125
  778. package/dist/membership-filter-BWnfRQzo.js +0 -68
  779. package/dist/migrate-DVsxeE0y.js +0 -537
  780. package/dist/module-values-CdaVwrab.js +0 -107
  781. package/dist/oauth-security-X7Em8DbH.js +0 -26
  782. package/dist/ocsf-TcjRBgIs.js +0 -136
  783. package/dist/openapi-BFUnL8Yi.js +0 -137
  784. package/dist/openapi-Cc-aS9xC.js +0 -416
  785. package/dist/openapi-DcjyfR1g.js +0 -256
  786. package/dist/operation-findings-CVwJHEu_.js +0 -36
  787. package/dist/operation-risks-BKOcTv8J.js +0 -13
  788. package/dist/operations-BMPx7HyO.d.ts +0 -62
  789. package/dist/operations-Bm9HFecz.js +0 -89
  790. package/dist/optional-8TKc-0j4.js +0 -47
  791. package/dist/output-LDciF_4t.js +0 -96
  792. package/dist/output-files-BYscrQl-.js +0 -1
  793. package/dist/output-files-CM0BnH05.js +0 -150
  794. package/dist/ownership-DvK6INyx.js +0 -1062
  795. package/dist/parse-CORUNcCo.js +0 -151
  796. package/dist/parse-local-manifest-Ce2N-Opr.js +0 -69
  797. package/dist/parse-local-manifest-w_ksIkB9.d.ts +0 -10
  798. package/dist/parse-request-DOBVaeiQ.js +0 -25
  799. package/dist/paths-CUvURzHp.js +0 -45
  800. package/dist/peer-BuK9F53f.js +0 -982
  801. package/dist/peer-n-swIV4H.js +0 -1
  802. package/dist/permdock-B3zE16To.js +0 -1203
  803. package/dist/permdock-DV3opaI3.d.ts +0 -674
  804. package/dist/permission-registry-B8tYxPIt.js +0 -398
  805. package/dist/permissions-BaoLxy66.js +0 -18
  806. package/dist/permissions-D-M48hW-.js +0 -146
  807. package/dist/permissions-DriWkV7q.d.ts +0 -54
  808. package/dist/pg-Ddxsd5ZB.js +0 -60
  809. package/dist/pins-nqarl3oE.js +0 -15
  810. package/dist/pkce-CnmmYqUZ.js +0 -21
  811. package/dist/policy-DIHfTqm6.d.ts +0 -20
  812. package/dist/policy-DnNOTENd.js +0 -430
  813. package/dist/policy-from-catalog-Z0hvSffr.js +0 -454
  814. package/dist/policy-module-xym9fnSq.js +0 -95
  815. package/dist/policy-types-DU389Elz.d.ts +0 -2809
  816. package/dist/postgres-store-DcyrPS-r.js +0 -1028
  817. package/dist/postgrest-3dE9SGx9.d.ts +0 -124
  818. package/dist/powersync-B5YjtUGd.js +0 -1532
  819. package/dist/powersync-BgUsk2Nf.js +0 -1
  820. package/dist/powersync-Dx7odzyw.js +0 -62
  821. package/dist/preset-Bn5Z54cH.js +0 -1858
  822. package/dist/principal-source-C6N60GtM.js +0 -103
  823. package/dist/problem-CPB8kqk7.js +0 -203
  824. package/dist/problem-details-CLDgX1KV.js +0 -156
  825. package/dist/problem-types-DSsRfONQ.js +0 -8
  826. package/dist/prompt-D1Gj1W4Y.js +0 -938
  827. package/dist/protected-action-CjSUoPGx.d.ts +0 -76
  828. package/dist/protected-action-D41o5LvP.js +0 -244
  829. package/dist/protected-action-OpOxtTsN.js +0 -80
  830. package/dist/provider-Bzzux0TR.js +0 -12
  831. package/dist/provider-D1jsNJ85.d.ts +0 -6
  832. package/dist/provider-store-tIAwP4aW.js +0 -52
  833. package/dist/provider-with-Do28DhxP.js +0 -69
  834. package/dist/pull-Pde1lapF.js +0 -257
  835. package/dist/pull-a4RpDxk8.js +0 -1
  836. package/dist/push-sJ5dy46a.js +0 -162
  837. package/dist/pushed-policy-Db651nih.d.ts +0 -63
  838. package/dist/pushed-policy-UZyQinrL.js +0 -241
  839. package/dist/refresh-on-L9UOwATg.d.ts +0 -49
  840. package/dist/refs-C8BKxc_e.js +0 -105
  841. package/dist/relation-walk-BDTaTKTM.js +0 -189
  842. package/dist/relations-CMsJ1ARY.js +0 -163
  843. package/dist/replay-BU09ad4L.js +0 -29
  844. package/dist/replay-BpmpY2ev.d.ts +0 -5
  845. package/dist/request-context-C2_1lchh.d.ts +0 -5
  846. package/dist/request-context-dyCY4V1t.js +0 -71
  847. package/dist/request-schema-CMP8Cmxd.js +0 -156
  848. package/dist/resolve-names-D5_kABup.js +0 -206
  849. package/dist/resource-ref-CaS9yVPi.js +0 -20
  850. package/dist/resource-relations-8-pCScBO.js +0 -252
  851. package/dist/retire-B2xffQgY.js +0 -249
  852. package/dist/revocations-BaUXHM1N.d.ts +0 -26
  853. package/dist/revocations-Bhr0aMIC.js +0 -27
  854. package/dist/rls-BI687j8q.js +0 -2700
  855. package/dist/rls-CKLHLcRl.js +0 -367
  856. package/dist/role-builder-BXdhhQcB.js +0 -507
  857. package/dist/rolldown-runtime-C3I60J0A.js +0 -4
  858. package/dist/row-conditions-BAGHOmVq.js +0 -28
  859. package/dist/row-pair-DglMdRFh.js +0 -34
  860. package/dist/rpc-BdFGYcWm.js +0 -112
  861. package/dist/rpc-DKRQobOX.d.ts +0 -22
  862. package/dist/run-B4heHtD1.js +0 -1
  863. package/dist/run-BG2kPruh.js +0 -694
  864. package/dist/run-ticket-Ddxt9OuU.js +0 -371
  865. package/dist/run-ticket-o4RxoaEN.d.ts +0 -159
  866. package/dist/runtime-rf0ZuyF3.js +0 -14
  867. package/dist/saas-D9maBt0q.js +0 -1223
  868. package/dist/scan-BvTBo9-D.js +0 -29
  869. package/dist/schema-BlnU_TzE.js +0 -414
  870. package/dist/schema-grK6TTBH.js +0 -134
  871. package/dist/scim-BG6uPUeW.js +0 -1056
  872. package/dist/scim-CovliQUg.js +0 -44
  873. package/dist/scopes-gdH__vDZ.js +0 -239
  874. package/dist/server-CKjFooaJ.js +0 -147
  875. package/dist/server-types-C4q8_8MM.d.ts +0 -325
  876. package/dist/sha256-C-4WXKIu.js +0 -158
  877. package/dist/shared-BRmCJxDK.js +0 -125
  878. package/dist/shared-DfaIWvIJ.js +0 -354
  879. package/dist/signals-B1vHR3fN.js +0 -32
  880. package/dist/sink-C3KDccl9.d.ts +0 -249
  881. package/dist/sink-D9_vh372.js +0 -968
  882. package/dist/skills-DzNdLezx.js +0 -51
  883. package/dist/skills-nPLVGtGH.js +0 -204
  884. package/dist/snapshot-D0VOanxQ.js +0 -334
  885. package/dist/snapshot-cache-B66h7FBK.js +0 -70
  886. package/dist/snapshot-cache-C1mN0pXe.d.ts +0 -70
  887. package/dist/snapshot-compact-CUtXsx6i.js +0 -75
  888. package/dist/snapshot-empty-F7d5BRlc.js +0 -18
  889. package/dist/snapshot-evaluate-C3ZA35O_.js +0 -501
  890. package/dist/snapshot-reads-CNNmp1cK.js +0 -66
  891. package/dist/sources-2virTxHt.d.ts +0 -721
  892. package/dist/sources-C4vkzZJV.js +0 -660
  893. package/dist/sources-qoIJQrJv.js +0 -11
  894. package/dist/sql-0WjxIp9g.js +0 -80
  895. package/dist/sql-B80DFdpG.d.ts +0 -10
  896. package/dist/src-ieIv22BA.js +0 -2080
  897. package/dist/standard-webhooks-B2g_yWK8.d.ts +0 -88
  898. package/dist/standard-webhooks-D67a3nzk.js +0 -228
  899. package/dist/storage-C2bWdvJH.js +0 -132
  900. package/dist/store-DXO0aVgf.js +0 -380
  901. package/dist/store-core-BI-9ZU-5.d.ts +0 -311
  902. package/dist/store-options-BYKNX_JG.js +0 -993
  903. package/dist/stores-DtM8pt8o.js +0 -128
  904. package/dist/stores-DwGfIcmq.d.ts +0 -57
  905. package/dist/stream-DQ3rbO3J.js +0 -74
  906. package/dist/style-DblOtSga.js +0 -1
  907. package/dist/style-Ds11Hmk4.js +0 -25
  908. package/dist/subject-C7RddW0G.js +0 -24
  909. package/dist/subject-cache-BT1fGuea.js +0 -193
  910. package/dist/subject-cache-TY2tw-k9.d.ts +0 -144
  911. package/dist/subject-jG6o8eKo.js +0 -556
  912. package/dist/subject-settings-8sH5HlII.js +0 -150
  913. package/dist/subject-settings-vNW8qmUH.d.ts +0 -52
  914. package/dist/supabase-BlAqmxD8.js +0 -723
  915. package/dist/supabase-dk1kB9bJ.js +0 -92
  916. package/dist/supabase-hook-Bu5gkzix.js +0 -1
  917. package/dist/supabase-hook-Cf9zKz8T.js +0 -4263
  918. package/dist/supautils-BREOPaHY.js +0 -1186
  919. package/dist/support-session-BGeEYDSq.js +0 -158
  920. package/dist/tables-DnNACfAr.js +0 -4003
  921. package/dist/target-qdEAnnhU.js +0 -51
  922. package/dist/tenancy-BlxY5T0q.js +0 -224
  923. package/dist/text-BMFRfBqc.js +0 -8
  924. package/dist/text-diff-BtfSmdUo.js +0 -444
  925. package/dist/thenable-BNSM1U2R.js +0 -40
  926. package/dist/time-nR1JesoH.js +0 -95
  927. package/dist/timeout-D51niuQP.js +0 -8
  928. package/dist/token-D6pWn8Uj.d.ts +0 -11
  929. package/dist/token-DaMnIU9O.js +0 -77
  930. package/dist/tool-refusal-D4spOJ7I.js +0 -44
  931. package/dist/type-helpers-tDoGEIsd.d.ts +0 -49
  932. package/dist/types-61f3KMtI.d.ts +0 -1136
  933. package/dist/types-BDgMzK1i.d.ts +0 -368
  934. package/dist/types-BIvkpVoc.d.ts +0 -180
  935. package/dist/types-BWjNPQkS.d.ts +0 -67
  936. package/dist/types-Bq4AU68k.d.ts +0 -105
  937. package/dist/types-BsqLNNvG.d.ts +0 -68
  938. package/dist/types-CH67RMvL.d.ts +0 -136
  939. package/dist/types-CcUXciSj.js +0 -79
  940. package/dist/types-DAyp592k.d.ts +0 -276
  941. package/dist/types-DEDocm4c.d.ts +0 -81
  942. package/dist/types-DQQkzF97.d.ts +0 -126
  943. package/dist/types-DdeivUBP.d.ts +0 -68
  944. package/dist/types-X40XNxRP.d.ts +0 -265
  945. package/dist/usage-BkDU1dYf.js +0 -762
  946. package/dist/usage-DNj42KHA.js +0 -32
  947. package/dist/usage-DrB_tDNk.js +0 -1
  948. package/dist/validation-error-CV0nV6_L.d.ts +0 -29
  949. package/dist/validation-error-CYg2kJEw.js +0 -36
  950. package/dist/validity-IcjQSR7I.js +0 -57
  951. package/dist/verifier-DUV6pLqZ.js +0 -519
  952. package/dist/verify-Boehaks6.js +0 -1736
  953. package/dist/version-DMQ0dnN5.js +0 -48
  954. package/dist/version-DizhmD72.js +0 -1
  955. package/dist/version-sources-BRb9ZteH.js +0 -34
  956. package/dist/views-MWmJ6Y4P.js +0 -147
  957. package/dist/vocabulary-BuYFWeCU.js +0 -158
  958. package/dist/vocabulary-DeZvUaTw.d.ts +0 -401
  959. package/dist/waiter-BophA4BT.d.ts +0 -39
  960. package/dist/waiter-aBLM63_f.js +0 -67
  961. package/dist/watch-CJKYQYNb.js +0 -167
  962. package/dist/watch-Cv-xvI6e.js +0 -1
  963. package/dist/who-can-Yh9WdiwK.js +0 -367
  964. package/dist/wire-delegation-Cv3W2eaM.js +0 -36
  965. package/dist/wire-denial-C7PaVYEM.js +0 -27
  966. package/dist/wrap-Bq9fHwuT.d.ts +0 -18
  967. package/dist/wrap-C5PWzgkq.js +0 -33
  968. package/schemas/catalog-v1.json +0 -679
  969. package/schemas/cli-result-v1.json +0 -95
@@ -0,0 +1,2339 @@
1
+ import { c as listPermissions, u as renamedKeys } from "./permission-registry-DMYRZVcn.js";
2
+ import { t as policyRowConditionKeys } from "./row-conditions-DwIJocfQ.js";
3
+ import { a as describeError, i as configError, o as exitCodeOfError } from "./errors-DgLOqc6j.js";
4
+ import { D as seedSql, G as closureBackfillSql, M as guardAuthAdminGrants, N as unguardAuthAdminGrants, S as accessSql, T as helpersSql, Y as graphSql, c as permissionHelpersSql, d as permittedByPermissionHelper, i as tableNames, o as PERMISSION_HELPERS, r as tableNameOf, s as checkName, u as permissionKeysHelper } from "./tables-CRTCBuFi.js";
5
+ import { i as qualifySqlTable } from "./sql-T4GaBh9X.js";
6
+ import { c as indexesSql, i as tableFor, l as pruneIndexTargets, n as compileGrants, r as inferredCommand, s as indexTargets, u as readTableIndexFacts } from "./compile-Blrr5WWw.js";
7
+ import { a as CANDIDATES, c as rowHelpersSql, d as rebuildPlan, i as buildContext, l as rowSetSql, n as isRefusal, o as inheritTargets, r as splitsPart, s as levelKeys, t as generateOptions, u as DROPPED_LIST } from "./generate-options-BDgadlwe.js";
8
+ import { t as policyFromCatalog } from "./policy-from-catalog-YKaTeaco.js";
9
+ import { t as fetchProjectPolicy } from "./pull-9oQvY18T.js";
10
+ import { c as requirePolicy } from "./load-CZnlAyZ8.js";
11
+ import { t as compact } from "./compact-C4LFuqbW.js";
12
+ import { a as nonEmptyOr } from "./output-djxu62oH.js";
13
+ import { i as INDEXES_MARKER, n as GRANTS_MARKER, o as SEEDS_MARKER, t as BACKFILL_MARKER } from "./markers-C-kThnKN.js";
14
+ import { G as graphHelper, H as byKey, K as graphSqlName, U as BOOTSTRAP_PERMISSIONS, lt as scopeSources, rt as memberIdsHelper, st as permittedIdsHelper, ut as scopeTable } from "./interactive-only-BZu9rLpa.js";
15
+ import { a as quoteIdent, c as quoteTable, i as qualified$1, o as quoteLiteral, s as quoteQualified } from "./quote-BKrTBbcH.js";
16
+ import { D as idTypeOf, O as scopeTypeOf, _ as subjectClaimJsonSql, c as SESSION_LIVE_HELPER, g as sessionLiveHelperSql, o as rootName, r as HELPERS, t as CUSTOM_ROLES, y as subjectIdSql } from "./shared-BdF5DJDQ.js";
17
+ import { a as supabaseHookSql, c as asideAuthzReceive, h as declarativeSql, p as resolveSchemas, t as grantsLabel, u as approvalsSql } from "./hook-sql-BIR4fL7i.js";
18
+ import { i as assignmentSql, n as ownershipSql } from "./ownership-BO0sI5FB.js";
19
+ import { p as scopeField } from "./tenancy-B5Xxt9Sc.js";
20
+ import { i as collectGrants, n as breakGlassHolder, r as breakGlassKey } from "./grants-BzjbUCdR.js";
21
+ import { t as supautilsRejections } from "./supautils-DXzJ2E2Q.js";
22
+ import { a as fieldViewsSql, c as ACTOR_MAY_WRITE, d as assemblePolicies, i as fieldViews, l as actorMayWriteCall, m as readOnlyActorPolicies, n as columnGrantSql, o as rowBranches, p as readOnlyActorKinds, r as columnRevokeSql, u as actorMayWriteSql } from "./fields-6d1j-q3c.js";
23
+ import { l as isFieldRelation } from "./resource-relations-Ck5sjYQR.js";
24
+ import { c as rootScope } from "./scopes-B-KX9EI8.js";
25
+ import { n as permissionHoldersSql } from "./resolve-names-Cmg6SPAa.js";
26
+ import { i as rbacScaffold } from "./rbac-B-49toAp.js";
27
+ import { i as dateAt } from "./time-r0CKBm57.js";
28
+ import { _ as writeOutputFiles, a as isSeedsDirectory, d as pgDeltaPath, g as underSchemaDir, h as serviceRel, l as parseSplit, m as seedsMigration, n as dataMigrationFile, p as seedDeltaNote, r as driftOf, u as partPath } from "./output-files-DNid6TBl.js";
29
+ import { i as readSupabaseConfig } from "./supabase-config-mXcggV5I.js";
30
+ import { a as splitUndiffed } from "./deciding-columns-BnglEKqU.js";
31
+ import { o as sqlFiles } from "./files-DAR51W3J.js";
32
+ import { n as MIGRATION_DIRS } from "./constants-PCJiir_3.js";
33
+ import { readFileSync } from "node:fs";
34
+ import { basename } from "node:path";
35
+ // src/cli/rls/bindings.ts
36
+ /**
37
+ * The table each resource with row policies binds to. With `helpersOnly`, a
38
+ * resource `rls.tables` does not name has no table and no binding.
39
+ */
40
+ function tableBindings(resources, tables, helpersOnly) {
41
+ const out = [];
42
+ for (const resource of [...new Set(resources)].toSorted()) {
43
+ const named = tables !== void 0 && Object.hasOwn(tables, resource);
44
+ if (helpersOnly && !named) continue;
45
+ out.push({
46
+ resource,
47
+ table: qualifySqlTable(tableFor(resource, tables)),
48
+ inferred: !named
49
+ });
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * The generate notes for `bindings`: the inferred ones, and where to see them
55
+ * all.
56
+ */
57
+ function bindingNotes(bindings, withDatabase) {
58
+ const inferred = bindings.filter((binding) => binding.inferred);
59
+ if (inferred.length === 0) return [];
60
+ return [`table bindings (no rls.tables entry, so the table is named after the resource): ${inferred.map((binding) => `${binding.resource} -> ${binding.table}`).join(", ")}${withDatabase ? "" : "; run permdock rls explain, or generate with --db-url-stdin, to check each table exists"}`];
61
+ }
62
+ /**
63
+ * The generate notes for the bindings whose table no project SQL file creates.
64
+ * A project with no `create table` in those files gets none: its schema lives
65
+ * elsewhere (an ORM, another repository).
66
+ */
67
+ function unknownTableNotes(bindings, created) {
68
+ if (created.size === 0) return [];
69
+ return bindings.filter((binding) => !created.has(binding.table) && !created.has(binding.table.toLowerCase())).map((binding) => `resource ${binding.resource} is bound to ${binding.table}, which no SQL file in the migration or schema folders creates; name its table in rls.tables, or set rls.tables.${binding.resource}: false when it has none`);
70
+ }
71
+ /** The inferred bindings whose table `facts` shows missing. */
72
+ function missingBindings(bindings, columns) {
73
+ return bindings.filter((binding) => binding.inferred && columns[binding.table] === void 0);
74
+ }
75
+ // src/cli/rls/trigger-notes.ts
76
+ const CREATE = /^create trigger\s+("[^"]+"|[\w$]+)[^;]*?\bon\s+("[^"]+"(?:\."[^"]+")?|[\w$.]+)/gmu;
77
+ function unquote(name) {
78
+ return name.replaceAll("\"", "");
79
+ }
80
+ function reasonOf(name) {
81
+ if (name === "permdock_custom_role_name_guard") return "customRoleWrites.roles: a tenant role cannot take a declared or shared role's name";
82
+ if (name === "permdock_custom_role_cascade") return "customRoleWrites.roles: a rename or delete of a role carries its grants";
83
+ if (name.startsWith("permdock_sync_custom_role_guard")) return "customRoles.from.sync: a signed-in caller writes only entries they may hand out";
84
+ if (name.startsWith("permdock_sync_custom_role")) return "customRoles.from.sync: each write to the legacy table rebuilds the role's grants";
85
+ if (name.startsWith("permdock_holders") || name.startsWith("permdock_transfer_only")) return "ownershipTriggers; set rls.ownershipTriggers.<scope>: false to skip";
86
+ if (name === "permdock_assignment") return "assignments: a role assignment is checked against the caller's own roles";
87
+ if (name.startsWith("permdock_closure")) return "the relationship closure table follows its source table";
88
+ return "generated by rls generate";
89
+ }
90
+ /** The triggers `sql` creates, in order, each with the option behind it. */
91
+ function generatedTriggers(sql) {
92
+ const found = [];
93
+ for (const match of sql.matchAll(CREATE)) {
94
+ const name = unquote(match.slice(1, 2).join(""));
95
+ const table = unquote(match.slice(2, 3).join(""));
96
+ found.push({
97
+ name,
98
+ table,
99
+ reason: reasonOf(name)
100
+ });
101
+ }
102
+ return found;
103
+ }
104
+ /** One generate note per trigger. */
105
+ function triggerNotes(sql) {
106
+ return generatedTriggers(sql).map((trigger) => `generated trigger ${trigger.name} on ${trigger.table} (${trigger.reason})`);
107
+ }
108
+ // src/cli/rls/explain.ts
109
+ function holds(table) {
110
+ if (table.tenant === void 0) return ["global"];
111
+ return [
112
+ "tenant",
113
+ ...table.shared === void 0 ? [] : ["shared"],
114
+ "global"
115
+ ];
116
+ }
117
+ function explainRls(input) {
118
+ const { config, ctx, generated } = input;
119
+ const rls = config.rls;
120
+ const bindings = tableBindings(generated.compiled.rowColumns.map((item) => item.resource), tableNames(rls?.tables), generated.helpersOnly);
121
+ const sources = ctx.memberSources ?? ctx.sources ?? [];
122
+ const roles = rls?.customRoleWrites?.roles;
123
+ const wanted = rls?.rowHelpers;
124
+ const resources = wanted === void 0 ? [] : wanted === true ? [...new Set(generated.compiled.branches.flatMap((branch) => branch.resource === void 0 ? [] : [branch.resource]))].toSorted() : [...new Set(wanted)];
125
+ return {
126
+ schema: input.schema,
127
+ authorize: input.authorize,
128
+ scopes: ctx.scopes.map((scope) => scope.within === void 0 ? {
129
+ name: scope.name,
130
+ key: scope.key ?? scope.name
131
+ } : {
132
+ name: scope.name,
133
+ key: scope.key ?? scope.name,
134
+ within: scope.within
135
+ }),
136
+ bindings: bindings.map((binding) => {
137
+ const via = ctx.vias?.[binding.resource];
138
+ return via === void 0 ? binding : Object.assign({}, binding, { via: `${via.helper} over ${via.table}.${via.column} (${binding.table}.${via.key})` });
139
+ }),
140
+ membershipSources: sources.map((source) => ({
141
+ table: source.sql.table,
142
+ select: source.sql.select("$1")
143
+ })),
144
+ ...roles === void 0 ? {} : { customRoles: {
145
+ table: roles.table,
146
+ key: roles.key,
147
+ ...roles.tenant === void 0 ? {} : { tenant: roles.tenant },
148
+ ...roles.shared === void 0 ? {} : { shared: roles.shared },
149
+ ...roles.skip === void 0 ? {} : { skip: roles.skip },
150
+ holds: holds(roles)
151
+ } },
152
+ rowHelpers: resources.map((resource) => ({
153
+ resource,
154
+ permissions: [...new Set(generated.compiled.branches.flatMap((branch) => branch.resource === resource && branch.coverage !== true ? [branch.permissionKey] : []))].toSorted()
155
+ })),
156
+ inferredActions: inferredActions(generated, rls?.actions),
157
+ triggers: generatedTriggers(input.text)
158
+ };
159
+ }
160
+ function inferredActions(generated, actions) {
161
+ const found = /* @__PURE__ */ new Map();
162
+ for (const branch of generated.compiled.branches) {
163
+ if (branch.resource === void 0) continue;
164
+ const base = branch.permissionKey.split("@")[0] ?? branch.permissionKey;
165
+ const action = base.slice(branch.resource.length + 1);
166
+ const command = inferredCommand(action, actions);
167
+ if (command !== void 0) {
168
+ const entry = found.get(action) ?? {
169
+ command,
170
+ keys: /* @__PURE__ */ new Set()
171
+ };
172
+ entry.keys.add(base);
173
+ found.set(action, entry);
174
+ }
175
+ }
176
+ return [...found.entries()].toSorted(([a], [b]) => a < b ? -1 : 1).map(([action, { command, keys }]) => ({
177
+ action,
178
+ command,
179
+ permissions: [...keys].toSorted()
180
+ }));
181
+ }
182
+ /** The text report of `explain`. */
183
+ function describeExplain(explain) {
184
+ const lines = [
185
+ `schema ${explain.schema}, authorize ${explain.authorize}`,
186
+ `scopes: ${explain.scopes.map((scope) => `${scope.name} (${scope.key}${scope.within === void 0 ? "" : `, within ${scope.within}`})`).join(", ")}`,
187
+ "",
188
+ "table bindings:",
189
+ ...explain.bindings.map((binding) => ` ${binding.resource} -> ${binding.table}${binding.inferred ? " (named after the resource; set rls.tables to change)" : ""}${binding.via === void 0 ? "" : ` via ${binding.via}`}${binding.exists === false ? " MISSING" : ""}`)
190
+ ];
191
+ if (explain.membershipSources.length > 0) {
192
+ lines.push("", "membership sources:");
193
+ for (const source of explain.membershipSources) lines.push(` ${source.table}`, ` ${source.select.replaceAll("\n", "\n ")}`);
194
+ }
195
+ if (explain.customRoles !== void 0) {
196
+ const roles = explain.customRoles;
197
+ const columns = [
198
+ `key ${roles.key}`,
199
+ ...roles.tenant === void 0 ? [] : [`tenant ${roles.tenant}`],
200
+ ...roles.shared === void 0 ? [] : [`shared ${roles.shared}`],
201
+ ...roles.skip === void 0 ? [] : [`skip ${roles.skip}`]
202
+ ];
203
+ lines.push("", `custom roles: ${roles.table} (${columns.join(", ")}); holds ${roles.holds.join(", ")} roles`);
204
+ }
205
+ if (explain.rowHelpers.length > 0) {
206
+ lines.push("", "row helpers:");
207
+ for (const helper of explain.rowHelpers) lines.push(` ${helper.resource}: ${helper.permissions.join(", ")}`);
208
+ }
209
+ if (explain.inferredActions.length > 0) {
210
+ lines.push("", "inferred actions (set rls.actions to change):");
211
+ for (const item of explain.inferredActions) lines.push(` ${item.action} -> ${item.command}: ${item.permissions.join(", ")}`);
212
+ }
213
+ if (explain.triggers.length > 0) {
214
+ lines.push("", "generated triggers:");
215
+ for (const trigger of explain.triggers) lines.push(` ${trigger.name} on ${trigger.table} (${trigger.reason})`);
216
+ }
217
+ return lines.join("\n");
218
+ }
219
+ // src/cli/rls/generate-load.ts
220
+ const PROJECT_COMMAND = "permdock rls generate";
221
+ /** The policy module the generate run reads, or the Cloud project's copy. */
222
+ function loadGeneratePolicy(input) {
223
+ if (input.project !== void 0 && input.from !== void 0 && input.from !== "drizzle") return Promise.resolve({
224
+ code: 2,
225
+ output: "rls generate takes the policy from --project or from a --policy module, not both",
226
+ text: ""
227
+ });
228
+ if (input.project === void 0) return loadPolicy(input.cwd, input.config, input.from);
229
+ return projectPolicyOf(input, input.project);
230
+ }
231
+ function loadPolicy(cwd, config, from) {
232
+ const policyPath = from === "drizzle" ? config.policy : from ?? config.policy;
233
+ return requirePolicy(cwd, policyPath, "rls generate needs policy in permdock.config.ts or --policy");
234
+ }
235
+ /**
236
+ * The policy `policyFromCatalog` rebuilds from the project's pushed catalog and
237
+ * policy; a project with no pushed policy fails.
238
+ */
239
+ async function projectPolicyOf(input, project) {
240
+ const fetched = await fetchProjectPolicy({
241
+ command: PROJECT_COMMAND,
242
+ url: input.url,
243
+ project,
244
+ json: input.json === true,
245
+ env: input.io.env ?? process.env,
246
+ io: input.io
247
+ });
248
+ if (!fetched.ok) return {
249
+ ...fetched.result,
250
+ text: ""
251
+ };
252
+ const { catalog, policy } = fetched.value;
253
+ if (policy === void 0) {
254
+ const detail = `project ${project} has a pushed catalog but no policy; push from a project whose permdock.config.ts names one`;
255
+ return {
256
+ code: 1,
257
+ output: `${PROJECT_COMMAND}: ${detail}`,
258
+ text: ""
259
+ };
260
+ }
261
+ try {
262
+ return policyFromCatalog(catalog, policy);
263
+ } catch (cause) {
264
+ return {
265
+ code: 1,
266
+ output: `${PROJECT_COMMAND}: the pushed policy does not rebuild: ${describeError(cause)}`,
267
+ text: ""
268
+ };
269
+ }
270
+ }
271
+ function isPolicyLoadFailure(value) {
272
+ return "text" in value && "code" in value;
273
+ }
274
+ // src/cli/rls/backfill.ts
275
+ /**
276
+ * The `--backfill-out` migration: every custom role in the application's roles
277
+ * table that has no rows in `custom_role_permissions` or `custom_role_includes`
278
+ * yet is saved through `permdock_trusted_replace_custom_role_grants`, with the
279
+ * entries PermDock cannot hold left out and listed in one warning. Running it
280
+ * again copies nothing, so a role edited after the copy keeps its edits.
281
+ */
282
+ function backfillSql(ctx, from, migrate) {
283
+ const plan = rebuildPlan(ctx, from, migrate);
284
+ const { rolesTable, perms, includes, replace, scopes } = plan;
285
+ const fn = quoteQualified(`${ctx.schema ?? "permdock"}.permdock_backfill_custom_roles`);
286
+ return `${BACKFILL_MARKER} schema=${ctx.schema ?? "permdock"}
287
+ -- custom roles copied from ${qualifySqlTable(plan.roles.table)} (rls.customRoles.from) through ${replace}
288
+ -- a role that already has rows is left as it is; entries PermDock cannot hold are dropped and listed in one warning
289
+ create or replace function ${fn}()
290
+ returns void
291
+ language plpgsql
292
+ volatile
293
+ security definer
294
+ set search_path = ''
295
+ as $permdock$
296
+ declare
297
+ v record;
298
+ v_allow text[];
299
+ v_deny text[];
300
+ v_include text[];
301
+ v_lost text[];
302
+ v_dropped text[] := '{}'::text[];
303
+ v_copied integer := 0;
304
+ v_present integer := 0;
305
+ begin
306
+ for v in
307
+ ${plan.identity}
308
+ from ${rolesTable} r
309
+ where ${plan.eligible}
310
+ order by 4, 2, 1, 3
311
+ loop
312
+ if v.role is null or not (v.scope = 'global' or v.scope = any(${scopes})) then
313
+ v_dropped := v_dropped || (coalesce(v.role, 'null') || ': scope ' || coalesce(v.scope, 'null') || ' is not declared');
314
+ continue;
315
+ end if;
316
+ if exists (
317
+ select 1 from ${perms} c
318
+ where (v.tenant_id is null and c.tenant_id is null or c.tenant_id = v.tenant_id) and c.scope = v.scope and (v.scope_id is null and c.scope_id is null or c.scope_id = v.scope_id) and c.role = v.role
319
+ ) or exists (
320
+ select 1 from ${includes} c
321
+ where (v.tenant_id is null and c.tenant_id is null or c.tenant_id = v.tenant_id) and c.scope = v.scope and (v.scope_id is null and c.scope_id is null or c.scope_id = v.scope_id) and c.role = v.role
322
+ ) then
323
+ v_present := v_present + 1;
324
+ continue;
325
+ end if;
326
+ ${plan.collect}
327
+ if v_allow is null and v_deny is null and v_include is null then
328
+ continue;
329
+ end if;
330
+ perform ${replace}(v.tenant_id, v.scope, v.scope_id, v.role, v_allow, v_deny, v_include);
331
+ v_copied := v_copied + 1;
332
+ end loop;
333
+ raise notice 'permdock backfill: copied % custom role(s), % already present', v_copied, v_present;
334
+ if cardinality(v_dropped) > 0 then
335
+ raise warning 'permdock backfill: dropped % entr(ies) PermDock cannot hold: %', cardinality(v_dropped), ${DROPPED_LIST};
336
+ end if;
337
+ end
338
+ $permdock$;
339
+ revoke execute on function ${fn}() from public, anon, authenticated;
340
+ select ${fn}();
341
+ `;
342
+ }
343
+ // src/cli/rls/break-glass.ts
344
+ /**
345
+ * The audit table every generated break-glass read writes to. Part of the SQL
346
+ * contract.
347
+ */
348
+ const BREAK_GLASS_AUDIT = "permdock_break_glass_audit";
349
+ const IDENT$2 = /^[a-z][a-z0-9_]*$/u;
350
+ /**
351
+ * The resources a `breakGlass` grant targets, with the table each reads. A
352
+ * break-glass grant is non-portable, so `compileGrants` never turns it into a
353
+ * policy; the server reads restricted rows through the generated function
354
+ * instead, which is why plain RLS keeps denying them.
355
+ */
356
+ function breakGlassEntries(policy, tables) {
357
+ const byResource = /* @__PURE__ */ new Map();
358
+ for (const item of collectGrants(policy)) {
359
+ const { grant } = item;
360
+ if (grant.breakGlass === void 0) continue;
361
+ const holder = breakGlassHolder(item);
362
+ const resource = grant.permission.resource;
363
+ const grants = byResource.get(resource) ?? [];
364
+ byResource.set(resource, grants);
365
+ if (holder === void 0) {
366
+ const root = policy.scopes[0];
367
+ grants.push({
368
+ permission: grant.permission.key,
369
+ scope: "anyone",
370
+ column: root === void 0 ? void 0 : scopeField(policy.resources.get(resource), root.name, policy.scopes),
371
+ ...root === void 0 ? {} : { root: root.name }
372
+ });
373
+ continue;
374
+ }
375
+ grants.push({
376
+ permission: grant.permission.key,
377
+ scope: holder.scope,
378
+ column: holder.scope === "global" ? void 0 : scopeField(policy.resources.get(resource), holder.scope, policy.scopes)
379
+ });
380
+ }
381
+ return [...byResource].map(([resource, grants]) => ({
382
+ resource,
383
+ table: tableFor(resource, tables),
384
+ grants
385
+ }));
386
+ }
387
+ /**
388
+ * Rows the subject's roles reach for `p_permission`: a break-glass grant lifts
389
+ * denies, never the tenant boundary. A grant to no role reads the rows of the
390
+ * root scopes the subject is a member of, or every row when the policy declares
391
+ * no scopes.
392
+ */
393
+ function rowsFilter(ctx, entry) {
394
+ const arms = entry.grants.flatMap((grant) => {
395
+ const asked = `p_permission = ${quoteLiteral(grant.permission)}`;
396
+ if (grant.scope === "anyone") {
397
+ if (grant.root === void 0) return [`(${asked})`];
398
+ return grant.column === void 0 ? [] : [`(${asked} and ${quoteIdent(grant.column)} = any(array(select ${qualified$1(ctx, memberIdsHelper(grant.root))}())))`];
399
+ }
400
+ if (grant.scope !== "global" && grant.column === void 0) return [];
401
+ return [`(${asked} and ${accessSql(ctx, grant.scope, breakGlassKey(grant.permission), grant.column)})`];
402
+ });
403
+ return arms.length === 0 ? "false" : [...new Set(arms)].join("\n or ");
404
+ }
405
+ function functionName$1(resource) {
406
+ if (!IDENT$2.test(resource)) throw configError(`PermDock CLI: unsafe break-glass resource '${resource}'`);
407
+ return `permdock_break_glass_${resource}`;
408
+ }
409
+ function auditSql$1(ctx) {
410
+ const audit = qualified$1(ctx, quoteIdent(BREAK_GLASS_AUDIT));
411
+ return `-- break-glass audit: one row per session that read restricted data
412
+ -- RLS never compiles a break-glass override, so restricted rows stay denied to a direct read
413
+ create table if not exists ${audit} (
414
+ id bigint generated always as identity primary key,
415
+ at timestamptz not null default now(),
416
+ subject text,
417
+ permission text not null,
418
+ purpose text,
419
+ reason text not null
420
+ );
421
+ alter table ${audit} enable row level security;
422
+ revoke all on table ${audit} from anon, authenticated, public;`;
423
+ }
424
+ function readFunctionSql(ctx, entry) {
425
+ const fn = qualified$1(ctx, functionName$1(entry.resource));
426
+ const audit = qualified$1(ctx, quoteIdent(BREAK_GLASS_AUDIT));
427
+ const table = quoteQualified(entry.table);
428
+ const session = subjectClaimJsonSql(ctx, "break_glass");
429
+ const subject = subjectIdSql(ctx);
430
+ return `-- ${entry.resource}: reads restricted rows through a checked, audited break-glass session
431
+ create or replace function ${fn}(p_permission text)
432
+ returns setof ${table}
433
+ language plpgsql
434
+ security definer
435
+ set search_path = ''
436
+ as $$
437
+ declare
438
+ session jsonb := ${session};
439
+ begin
440
+ if session is null
441
+ or jsonb_typeof(session) <> 'object'
442
+ or session ->> 'v' <> '1'
443
+ or session ->> 'permission' <> p_permission
444
+ or coalesce(session ->> 'reason', '') = ''
445
+ or jsonb_typeof(session -> 'expires_at') <> 'number'
446
+ or (session ->> 'expires_at')::numeric <= extract(epoch from now())
447
+ then
448
+ raise exception 'PermDock: no valid break-glass session for %', p_permission
449
+ using errcode = '42501';
450
+ end if;
451
+ insert into ${audit} (subject, permission, purpose, reason)
452
+ values (
453
+ nullif((${subject})::text, ''),
454
+ p_permission,
455
+ session ->> 'purpose',
456
+ session ->> 'reason'
457
+ );
458
+ return query select * from ${table}
459
+ where ${rowsFilter(ctx, entry)};
460
+ end;
461
+ $$;
462
+ revoke execute on function ${fn}(text) from public, anon;
463
+ grant execute on function ${fn}(text) to authenticated;`;
464
+ }
465
+ /**
466
+ * The `security definer` read path for every `breakGlass` grant: an audit table
467
+ * and one `permdock_break_glass_<resource>(permission)` per resource that
468
+ * checks a signed break-glass session, writes an audit row and returns the rows
469
+ * in the scope instances where the subject holds a role with the break-glass
470
+ * grant (bypassing the table's policies as the definer). Empty when the policy
471
+ * has no break-glass grant.
472
+ */
473
+ function breakGlassSql(ctx, entries) {
474
+ if (entries.length === 0) return "";
475
+ return [auditSql$1(ctx), ...entries.map((entry) => readFunctionSql(ctx, entry))].join("\n\n");
476
+ }
477
+ // src/cli/rls/emit.ts
478
+ const HEADER = "-- generated by permdock rls generate\n-- fail-closed: never target a bypass role\n";
479
+ const TRUSTED_READER_GRANT = /^grant usage on schema "[^"\n]+" to [^\n;]+;\ngrant execute on function [^\n]+\.permdock_trusted_role_permissions(?:_by_id)?\([^)\n]*\) to [^\n;]+;$/gmu;
480
+ function assertNoServiceRole(text) {
481
+ if (/\bservice_role\b/iu.test(text.replaceAll(TRUSTED_READER_GRANT, ""))) throw new Error("PermDock CLI: generated RLS must never emit service_role");
482
+ }
483
+ function assertSupautilsSafe(text) {
484
+ const [first] = supautilsRejections(text);
485
+ if (first !== void 0) throw new Error(`PermDock CLI: generated SQL line ${String(first.line)} ${first.reason}, which supautils rejects on Supabase`);
486
+ }
487
+ /**
488
+ * Neon's Data API and `pg_session_jwt` name the anonymous role `anonymous`;
489
+ * Supabase, PostgREST and the GUC pattern use `anon`. Role lists end a line or
490
+ * a statement after `to` or `from`, so only those are renamed.
491
+ */
492
+ function dialectRoles(text, dialect) {
493
+ if (dialect !== "neon") return text;
494
+ return text.replaceAll(/\b(to|from) ((?:[a-z_]+, )*[a-z_]+)(?=;|\n)/gu, (_match, keyword, list) => `${keyword} ${list.split(", ").map((role) => role === "anon" ? "anonymous" : role).join(", ")}`);
495
+ }
496
+ function tablesOf(policies) {
497
+ return [...new Set(policies.map((item) => item.table))];
498
+ }
499
+ /**
500
+ * Enable (and force) row level security, then the table grants for the commands
501
+ * a policy allows.
502
+ */
503
+ function tableSql(table, policies, force, views) {
504
+ const closed = views.find((view) => view.table === table && view.companion !== void 0);
505
+ const target = quoteQualified(table);
506
+ const lines = [`alter table ${target} enable row level security;`];
507
+ if (force) lines.push(`alter table ${target} force row level security;`);
508
+ lines.push(`revoke all on table ${target} from anon, authenticated;`);
509
+ for (const role of ["anon", "authenticated"]) {
510
+ const cmds = new Set(policies.filter((item) => item.table === table && item.effect === "allow" && item.roles.includes(role)).map((item) => item.command));
511
+ const grants = [
512
+ "select",
513
+ "insert",
514
+ "update",
515
+ "delete"
516
+ ].filter((cmd) => cmds.has(cmd) && (closed === void 0 || cmd !== "select"));
517
+ if (grants.length > 0) lines.push(`grant ${grants.join(", ")} on table ${target} to ${role};`);
518
+ if (closed !== void 0 && cmds.has("select")) lines.push(columnGrantSql(closed, role));
519
+ }
520
+ if (closed !== void 0) lines.push(columnRevokeSql(closed));
521
+ return lines.join("\n");
522
+ }
523
+ /**
524
+ * `drop policy if exists` and `create policy` for one policy, without the
525
+ * table's grants.
526
+ */
527
+ function policySql(item) {
528
+ const target = quoteQualified(item.table);
529
+ const lines = [
530
+ `drop policy if exists ${quoteIdent(item.name)} on ${target};`,
531
+ `create policy ${quoteIdent(item.name)}`,
532
+ ` on ${target}`,
533
+ ` as ${item.effect === "deny" ? "restrictive" : "permissive"}`,
534
+ ` for ${item.command}`,
535
+ ` to ${item.roles.join(", ")}`
536
+ ];
537
+ if (item.using !== void 0) lines.push(` using (${item.using})`);
538
+ if (item.check !== void 0) lines.push(` with check (${item.check})`);
539
+ return `${lines.join("\n")};\n`;
540
+ }
541
+ function emitSql(policies, preamble, force = false, views = []) {
542
+ const chunks = [HEADER];
543
+ if (preamble !== "") chunks.push(preamble);
544
+ for (const table of tablesOf(policies)) chunks.push(tableSql(table, policies, force, views), "");
545
+ for (const item of policies) chunks.push(policySql(item));
546
+ if (views.length > 0) chunks.push(fieldViewsSql(views));
547
+ const text = `${chunks.join("\n").trim()}\n`;
548
+ assertNoServiceRole(text);
549
+ assertSupautilsSafe(text);
550
+ return text;
551
+ }
552
+ /**
553
+ * The SQL a Drizzle or Prisma schema cannot declare: helpers, grants, `force`
554
+ * and field views. `rls generate` writes it next to `out` for a custom
555
+ * migration.
556
+ */
557
+ function migrationSql(policies, preamble, force, views) {
558
+ const parts = [
559
+ preamble.trim(),
560
+ ...tablesOf(policies).map((table) => tableSql(table, policies, force, views)),
561
+ fieldViewsSql(views)
562
+ ].filter((part) => part !== "");
563
+ if (parts.length === 0) return "";
564
+ const text = `${HEADER}\n${parts.join("\n\n")}\n`;
565
+ assertNoServiceRole(text);
566
+ assertSupautilsSafe(text);
567
+ return text;
568
+ }
569
+ function helpersNote(helpers, how) {
570
+ return helpers === void 0 ? [] : [`// run ${helpers} ${how}`];
571
+ }
572
+ function camelCase(name) {
573
+ return name.replaceAll(/[_-]+([a-z0-9])/giu, (_, char) => char.toUpperCase());
574
+ }
575
+ function tableName(table) {
576
+ return table.slice(table.lastIndexOf(".") + 1);
577
+ }
578
+ function pascalCase(name) {
579
+ const camel = camelCase(name);
580
+ return camel.charAt(0).toUpperCase() + camel.slice(1);
581
+ }
582
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;
583
+ function identifier(name, what) {
584
+ if (!IDENTIFIER.test(name)) throw configError(`PermDock CLI: ${what} ${JSON.stringify(name)} is not an identifier`);
585
+ return name;
586
+ }
587
+ function quoted(text) {
588
+ return `'${text.replaceAll(/[\\']/gu, (match) => `\\${match}`)}'`;
589
+ }
590
+ function templateText(text) {
591
+ return text.replaceAll(/[\\`]|\$\{/gu, (match) => `\\${match}`);
592
+ }
593
+ const AUTH_UID = "(select auth.uid())";
594
+ function drizzleRoles(list) {
595
+ return list.includes("anon") ? "[anonRole, authenticatedRole]" : "authenticatedRole";
596
+ }
597
+ function emitDrizzle(policies, options) {
598
+ const supabase = options.dialect === "supabase";
599
+ const anon = policies.some((item) => item.roles.includes("anon"));
600
+ const sqlOf = (text) => {
601
+ const parts = text.split(AUTH_UID).map(templateText);
602
+ return `sql\`${supabase ? parts.join("${authUid}") : parts.join(AUTH_UID)}\``;
603
+ };
604
+ const usesUid = supabase && policies.some((item) => item.using?.includes(AUTH_UID) === true || item.check?.includes(AUTH_UID) === true);
605
+ const lines = [
606
+ "// generated by permdock rls generate",
607
+ "// fail-closed: never target a bypass role",
608
+ ...helpersNote(options.helpers, "in a custom migration (drizzle-kit generate --custom)"),
609
+ "import { sql } from 'drizzle-orm'"
610
+ ];
611
+ if (supabase) {
612
+ const named = [
613
+ anon ? "anonRole" : "",
614
+ "authenticatedRole",
615
+ usesUid ? "authUid" : ""
616
+ ].filter((name) => name !== "").join(", ");
617
+ lines.push("import { pgPolicy } from 'drizzle-orm/pg-core'", `import { ${named} } from 'drizzle-orm/supabase'`);
618
+ } else lines.push("import { pgPolicy, pgRole } from 'drizzle-orm/pg-core'");
619
+ lines.push(`import * as schema from ${quoted(options.schema ?? "./schema")}`, "");
620
+ if (!supabase) {
621
+ if (anon) lines.push(`export const anonRole = pgRole('${options.dialect === "neon" ? "anonymous" : "anon"}').existing()`);
622
+ lines.push("export const authenticatedRole = pgRole('authenticated').existing()", "");
623
+ }
624
+ for (const item of policies) {
625
+ const as = item.effect === "deny" ? "restrictive" : "permissive";
626
+ const table = identifier(options.exports?.[item.table] ?? camelCase(tableName(item.table)), "table export");
627
+ const name = identifier(camelCase(item.name), "policy export");
628
+ const using = item.using === void 0 ? "" : `\n using: ${sqlOf(item.using)},`;
629
+ const check = item.check === void 0 ? "" : `\n withCheck: ${sqlOf(item.check)},`;
630
+ lines.push(`export const ${name} = pgPolicy(${quoted(item.name)}, {`, ` as: '${as}',`, ` for: '${item.command}',`, ` to: ${drizzleRoles(item.roles)},${using}${check}`, `}).link(schema.${table})`, "");
631
+ }
632
+ const text = `${lines.join("\n").trimEnd()}\n`;
633
+ assertNoServiceRole(text);
634
+ return text;
635
+ }
636
+ /**
637
+ * Prisma 8 `policy_<command>` blocks; each target model declares `@@rls`
638
+ * itself.
639
+ */
640
+ function emitPrisma(policies, options = {}) {
641
+ const modelOf = (table) => identifier(options.models?.[table] ?? pascalCase(tableName(table)), "model");
642
+ const models = [...new Set(policies.map((item) => modelOf(item.table)))];
643
+ const lines = [
644
+ "// generated by permdock rls generate (Prisma 8 policy blocks)",
645
+ "// fail-closed: never target a bypass role",
646
+ `// add @@rls to ${models.length === 1 ? "model" : "models"} ${models.join(", ")}; keep these blocks in their namespace`,
647
+ ...helpersNote(options.helpers, "in a migration before these policies"),
648
+ ""
649
+ ];
650
+ for (const item of policies) {
651
+ if (item.effect === "deny") throw configError(`PermDock CLI: Prisma policy blocks are permissive only, so ${item.name} (a deny) needs --target sql`);
652
+ lines.push(`policy_${item.command} ${identifier(item.name, "policy name")} {`, ` target = ${modelOf(item.table)}`, ` roles = [${item.roles.join(", ")}]`);
653
+ if (item.using !== void 0) lines.push(` using = ${JSON.stringify(item.using)}`);
654
+ if (item.check !== void 0) lines.push(` withCheck = ${JSON.stringify(item.check)}`);
655
+ lines.push("}", "");
656
+ }
657
+ const text = `${lines.join("\n").trimEnd()}\n`;
658
+ assertNoServiceRole(text);
659
+ return text;
660
+ }
661
+ /** The migration file written next to `out`. */
662
+ function migrationOut(out) {
663
+ const dot = out.lastIndexOf(".");
664
+ return `${dot > Math.max(out.lastIndexOf("/"), out.lastIndexOf("\\")) ? out.slice(0, dot) : out}.migration.sql`;
665
+ }
666
+ function defaultOut(target) {
667
+ switch (target) {
668
+ case "sql": return "rls.sql";
669
+ case "drizzle": return "src/db/policies.ts";
670
+ case "prisma": return "prisma/policies.prisma";
671
+ default: return target;
672
+ }
673
+ }
674
+ // src/cli/rls/follows.ts
675
+ function isOwner$1(entry) {
676
+ return typeof entry === "object" && !("tableOf" in entry);
677
+ }
678
+ function bare$1(table) {
679
+ return table.slice(table.lastIndexOf(".") + 1);
680
+ }
681
+ function policyName$1(table, command) {
682
+ const full = `permdock_follow_${bare$1(table).replaceAll(/[^A-Za-z0-9]+/gu, "_").replaceAll(/^_|_$/gu, "")}_${command}`;
683
+ if (new TextEncoder().encode(full).length > 63) throw configError(`PermDock CLI: the follows policy name ${full} is longer than Postgres's 63 bytes; shorten '${table}'`);
684
+ return full;
685
+ }
686
+ /**
687
+ * Child policies for `rls.tables.<resource>.follows`. Select calls `<fk> =
688
+ * any(array(<parent rows the permission reaches>))` with `<resource>.read`, a
689
+ * set read once per statement and led by the caller's tenants where the
690
+ * permission allows it. Insert, update and delete use `<resource>.update`. The
691
+ * child resource gets no permission of its own.
692
+ */
693
+ function followPolicies(ctx, policy, tables) {
694
+ const out = [];
695
+ for (const [resource, entry] of Object.entries(tables ?? {})) {
696
+ if (!isOwner$1(entry) || entry.follows === void 0) continue;
697
+ const node = policy.resources.get(resource);
698
+ if (node === void 0) throw configError(`PermDock CLI: rls.tables.${resource}.follows names a resource the policy does not declare`);
699
+ if (graphSqlName(resource) === void 0) throw configError(`PermDock CLI: rls.tables.${resource} is not a SQL name, so follows cannot call can_${resource}`);
700
+ for (const [child, fk] of Object.entries(entry.follows)) {
701
+ const childName = quoteIdent(bare$1(child));
702
+ const column = quoteIdent(fk);
703
+ const exists = (action) => `${childName}.${column} = any(array(${rowSetSql(ctx, policy, node, `${resource}.${action}`)}))`;
704
+ for (const [command, action, place] of [
705
+ [
706
+ "select",
707
+ "read",
708
+ "using"
709
+ ],
710
+ [
711
+ "insert",
712
+ "update",
713
+ "check"
714
+ ],
715
+ [
716
+ "update",
717
+ "update",
718
+ "both"
719
+ ],
720
+ [
721
+ "delete",
722
+ "update",
723
+ "using"
724
+ ]
725
+ ]) {
726
+ const expression = exists(action);
727
+ out.push({
728
+ name: policyName$1(child, command),
729
+ table: child,
730
+ command,
731
+ effect: "allow",
732
+ roles: ["authenticated"],
733
+ ...place === "check" ? {} : { using: expression },
734
+ ...place === "using" ? {} : { check: expression }
735
+ });
736
+ }
737
+ }
738
+ }
739
+ return out;
740
+ }
741
+ /** The relation-walk maximum: a chain stops this many steps below its start. */
742
+ const WALK_DEPTH = 32;
743
+ /**
744
+ * `walk: "recursive"`: one set of the rows below the caller on a self-parented
745
+ * resource. The walk starts at the caller's own row, the one whose
746
+ * `tables.<resource>.user` column (the id column by default) is the caller, and
747
+ * stays in that row's tenant. A path guard and a depth cap of 32 end a cycle or
748
+ * a self-parented row. The caller's row is not in the result. With approval
749
+ * delegations, each delegator whose cover is active adds their row and every
750
+ * row below it.
751
+ */
752
+ function walkChainSql(ctx, policy, tables, covers) {
753
+ const root = rootScope(ctx.scopes);
754
+ const chunks = [];
755
+ for (const [resource, entry] of Object.entries(tables ?? {})) {
756
+ if (!isOwner$1(entry) || entry.walk !== "recursive") continue;
757
+ const node = policy.resources.get(resource);
758
+ const parent = node?.parent;
759
+ if (node === void 0 || parent === void 0 || parent.resource !== resource) throw configError(`PermDock CLI: rls.tables.${resource}.walk needs a self-parented resource`);
760
+ const sql = graphSqlName(resource);
761
+ if (sql === void 0) throw configError(`PermDock CLI: rls.tables.${resource}.walk is not a SQL name`);
762
+ const type = idTypeOf(ctx, resource);
763
+ const table = quoteQualified(tableNameOf(entry, resource, tables));
764
+ const id = quoteIdent(node.id);
765
+ const up = quoteIdent(parent.field);
766
+ const user = quoteIdent(entry.user ?? node.id);
767
+ const tenantColumn = root === void 0 ? void 0 : tenantField(policy, resource, root);
768
+ const tenant = tenantColumn === void 0 ? void 0 : quoteIdent(tenantColumn);
769
+ const fn = qualified$1(ctx, `permdock_${sql}_chain`);
770
+ const me = `(select ${qualified$1(ctx, "permdock_user_id")}())`;
771
+ const startTenant = tenant === void 0 ? "null" : `t.${tenant}`;
772
+ const stepTenant = tenant === void 0 ? "" : `\n and c.${tenant} = w.tenant`;
773
+ const cover = covers ? `
774
+ union all
775
+ select t.${id}, ${startTenant}, 0, array[t.${id}], true
776
+ from ${table} t
777
+ join ${qualified$1(ctx, "approval_delegations")} d on t.${user} = d.delegator
778
+ where d.delegate = ${me}
779
+ and d."from" <= now()
780
+ and d."until" > now()` : "";
781
+ chunks.push(`-- ${resource}: rows below the caller's row, one recursive set
782
+ create or replace function ${fn}()
783
+ returns setof ${type}
784
+ language sql
785
+ stable
786
+ security definer
787
+ cost 1000
788
+ rows 100
789
+ parallel safe
790
+ set search_path = ''
791
+ as $$
792
+ with recursive walk(id, tenant, depth, path, cover) as (
793
+ select t.${id}, ${startTenant}, 0, array[t.${id}], false
794
+ from ${table} t
795
+ where t.${user} = ${me}${cover}
796
+ union all
797
+ select c.${id}, w.tenant, w.depth + 1, w.path || c.${id}, false
798
+ from ${table} c
799
+ join walk w on c.${up} = w.id
800
+ where not c.${id} = any (w.path)
801
+ and w.depth < ${String(WALK_DEPTH)}${stepTenant}
802
+ )
803
+ select id from walk where depth >= 1 or cover
804
+ $$;
805
+ revoke execute on function ${fn}() from public, anon;
806
+ grant execute on function ${fn}() to authenticated;`);
807
+ }
808
+ return chunks.join("\n\n");
809
+ }
810
+ function sameTable(left, right) {
811
+ return qualifySqlTable(left) === qualifySqlTable(right);
812
+ }
813
+ function folderOf$1(policy, tables, table) {
814
+ let byName;
815
+ let first;
816
+ const folders = [];
817
+ for (const [resource, node] of policy.resources) {
818
+ if (sameTable(tableNameOf(tables?.[resource], resource, tables), table)) {
819
+ first ??= resource;
820
+ if (node.parent?.resource === resource) folders.push(resource);
821
+ }
822
+ if (resource === bare$1(table)) byName = resource;
823
+ }
824
+ if (folders.length > 1) throw configError(`PermDock CLI: rls.treeValues.${table} maps to more than one self-parented resource (${folders.join(", ")}), so the folder is ambiguous`);
825
+ return folders[0] ?? first ?? byName;
826
+ }
827
+ function tenantField(policy, resource, root) {
828
+ const node = policy.resources.get(resource);
829
+ if (node === void 0) return;
830
+ for (const relation of Object.values(node.relations)) if (isFieldRelation(relation) && relation.memberOf === root) return relation.field;
831
+ }
832
+ /**
833
+ * One helper per `rls.treeValues` table: the folder rows in the caller's
834
+ * tenants, walked on that table alone.
835
+ */
836
+ function treeHelperSql(ctx, policy, tables, treeValues) {
837
+ const root = rootScope(ctx.scopes);
838
+ const chunks = [];
839
+ for (const table of Object.keys(treeValues ?? {}).toSorted()) {
840
+ const resource = folderOf$1(policy, tables, table);
841
+ const node = resource === void 0 ? void 0 : policy.resources.get(resource);
842
+ const parent = node?.parent;
843
+ const tenant = root === void 0 || resource === void 0 ? void 0 : tenantField(policy, resource, root);
844
+ if (resource === void 0 || node === void 0 || parent === void 0 || parent.resource !== resource || tenant === void 0 || root === void 0) throw configError(`PermDock CLI: rls.treeValues.${table} must be a self-parented folder in the caller's root scope`);
845
+ const sql = graphSqlName(resource);
846
+ if (sql === void 0) throw configError(`PermDock CLI: rls.treeValues.${table} is not a SQL name`);
847
+ const type = idTypeOf(ctx, resource);
848
+ const fn = qualified$1(ctx, `permdock_tree_${sql}`);
849
+ const id = quoteIdent(node.id);
850
+ const up = quoteIdent(parent.field);
851
+ const org = quoteIdent(tenant);
852
+ const from = quoteQualified(tableNameOf(tables?.[resource], resource, tables));
853
+ const members = qualified$1(ctx, memberIdsHelper(root));
854
+ chunks.push(`-- ${resource}: folder rows in the caller's tenants
855
+ create or replace function ${fn}()
856
+ returns setof ${type}
857
+ language sql
858
+ stable
859
+ security definer
860
+ set search_path = ''
861
+ as $$
862
+ with recursive tree(id) as (
863
+ select t.${id}
864
+ from ${from} t
865
+ where t.${org} in (select ${members}())
866
+ union
867
+ select c.${id}
868
+ from ${from} c
869
+ join tree w on c.${up} = w.id
870
+ where c.${org} in (select ${members}())
871
+ )
872
+ select id from tree
873
+ $$;
874
+ revoke execute on function ${fn}() from public, anon;
875
+ grant execute on function ${fn}() to authenticated;`);
876
+ }
877
+ return chunks.join("\n\n");
878
+ }
879
+ // src/cli/rls/realtime-storage.ts
880
+ const SCOPE_SEGMENT = /^\{([a-z][a-z0-9_]*)\}$/u;
881
+ const LITERAL_SEGMENT = /^[^{}:\s]+$/u;
882
+ const TOPIC = "(select realtime.topic())";
883
+ function policyName(prefix, name, command) {
884
+ const full = `permdock_${prefix}_${name.replaceAll(/[^A-Za-z0-9]+/gu, "_").replaceAll(/^_|_$/gu, "")}_${command}`;
885
+ if (new TextEncoder().encode(full).length > 63) throw configError(`PermDock CLI: the ${prefix} policy name ${full} is longer than Postgres's 63 bytes; shorten '${name}'`);
886
+ return full;
887
+ }
888
+ function grantKey(facts, ref, where, warnings, conditioned) {
889
+ if (ref === void 0) return;
890
+ const key = typeof ref === "object" && ref !== null ? Reflect.get(ref, "key") : ref;
891
+ if (typeof key !== "string" || !facts.keys.has(key)) throw configError(`PermDock CLI: ${where} must be a permission reference from the definitions (got ${JSON.stringify(key)})`);
892
+ if (conditioned === "scope" && facts.rowConditions.has(key)) warnings.push(`${where} is ${key}, whose grants carry row conditions (a relation, a where or another condition): the policy admits only the instances its role allows without a condition reach, through permitted_<scope>_ids_by_permission`);
893
+ return key;
894
+ }
895
+ /**
896
+ * Resources a storage bucket calls `can_<resource>(id, permission)` for. Those
897
+ * id helpers have to exist even when `rls.rowHelpers` does not name them.
898
+ */
899
+ function storageResources(storage) {
900
+ if (storage === void 0) return [];
901
+ const names = /* @__PURE__ */ new Set();
902
+ for (const bucket of Object.values(storage.buckets)) for (const ref of [
903
+ bucket.read,
904
+ bucket.write,
905
+ bucket.delete
906
+ ]) if (ref !== void 0) names.add(resourceOf(ref.key));
907
+ return [...names].toSorted();
908
+ }
909
+ /** The resource a permission key names, before its action, group and level. */
910
+ function resourceOf(key) {
911
+ const base = key.split("#")[0]?.split("@")[0] ?? key;
912
+ const dot = base.lastIndexOf(".");
913
+ return dot <= 0 ? base : base.slice(0, dot);
914
+ }
915
+ function declaredScope(facts, scope, where) {
916
+ if (!facts.scopes.has(scope)) throw configError(`PermDock CLI: ${where} names the scope '${scope}', which definePolicy({ scopes }) does not declare`);
917
+ return scope;
918
+ }
919
+ /**
920
+ * The ids of `scope` where the subject holds `key` through an allow without a
921
+ * row condition, minus a deny of it, as text: `<value> in (…)`. A relationship
922
+ * or a `where` on the same permission never widens it.
923
+ */
924
+ function permitted(ctx, value, scope, key) {
925
+ return `${value} in (select x::text from ${qualified$1(ctx, permittedByPermissionHelper(scope))}(${quoteLiteral(key)}) x)`;
926
+ }
927
+ function escapeRegex(text) {
928
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
929
+ }
930
+ function realtimePolicies(ctx, facts, realtime, warnings) {
931
+ return Object.entries(realtime.topics).flatMap(([pattern, topic]) => {
932
+ const where = `rls.realtime.topics['${pattern}']`;
933
+ const segments = pattern.split(":");
934
+ const placeholders = segments.flatMap((segment, index) => {
935
+ const match = SCOPE_SEGMENT.exec(segment);
936
+ return match === null ? [] : [{
937
+ index,
938
+ scope: match[1] ?? ""
939
+ }];
940
+ });
941
+ const [placeholder] = placeholders;
942
+ if (placeholder === void 0 || placeholders.length > 1 || segments.some((segment, index) => index !== placeholder.index && !LITERAL_SEGMENT.test(segment))) throw configError(`PermDock CLI: ${where} must be ':'-separated segments with exactly one '{<scope>}' segment, such as 'org:{organization}:chat'`);
943
+ const scope = declaredScope(facts, placeholder.scope, where);
944
+ const regex = `^${segments.map((segment, index) => index === placeholder.index ? "[^:]+" : escapeRegex(segment)).join(":")}$`;
945
+ const id = `split_part(${TOPIC}, ':', ${String(placeholder.index + 1)})`;
946
+ const condition = (key) => `extension in ('broadcast', 'presence')
947
+ and ${TOPIC} ~ ${quoteLiteral(regex)}
948
+ and ${permitted(ctx, id, scope, key)}`;
949
+ const read = grantKey(facts, topic.read, `${where}.read`, warnings, "scope");
950
+ const write = grantKey(facts, topic.write, `${where}.write`, warnings, "scope");
951
+ if (read === void 0) throw configError(`PermDock CLI: ${where}.read is required`);
952
+ const policies = [{
953
+ name: policyName("realtime", pattern, "select"),
954
+ table: "realtime.messages",
955
+ command: "select",
956
+ effect: "allow",
957
+ roles: ["authenticated"],
958
+ using: condition(read)
959
+ }];
960
+ if (write !== void 0) policies.push({
961
+ name: policyName("realtime", pattern, "insert"),
962
+ table: "realtime.messages",
963
+ command: "insert",
964
+ effect: "allow",
965
+ roles: ["authenticated"],
966
+ check: condition(write)
967
+ });
968
+ return policies;
969
+ });
970
+ }
971
+ function folderOf(bucket, where) {
972
+ const folder = bucket.folder ?? 1;
973
+ if (!Number.isInteger(folder) || folder < 1) throw configError(`PermDock CLI: ${where}.folder must be a positive integer (got ${String(folder)})`);
974
+ return folder;
975
+ }
976
+ /**
977
+ * The column that holds `scope` on `resource`: a `memberOf` relation's field.
978
+ * The folder id is that scope instance, and also the resource id.
979
+ */
980
+ function memberField(policy, resource, scope) {
981
+ const node = policy?.resources.get(resource);
982
+ if (node === void 0) return;
983
+ for (const relation of Object.values(node.relations)) if ("memberOf" in relation && relation.memberOf === scope) return relation.field;
984
+ }
985
+ function storagePolicies(ctx, facts, storage, warnings, policy) {
986
+ return Object.entries(storage.buckets).flatMap(([id, bucket]) => {
987
+ const where = `rls.storage.buckets['${id}']`;
988
+ declaredScope(facts, bucket.scope, `${where}.scope`);
989
+ const folder = folderOf(bucket, where);
990
+ const condition = (key) => {
991
+ const resource = resourceOf(key);
992
+ const sql = graphSqlName(resource);
993
+ if (sql === void 0) throw configError(`PermDock CLI: ${where} permission '${key}' does not name a SQL resource`);
994
+ const path = `(storage.foldername(name))[${String(folder)}]`;
995
+ const idType = idTypeOf(ctx, resource);
996
+ const idName = (policy?.resources.get(resource))?.id ?? "id";
997
+ const pairs = [`${quoteLiteral(idName)}, ${path}::${idType}`];
998
+ const scopeField = memberField(policy, resource, bucket.scope);
999
+ if (scopeField !== void 0 && scopeField !== idName) pairs.push(`${quoteLiteral(scopeField)}, ${path}::${scopeTypeOf(ctx, bucket.scope)}`);
1000
+ const row = `json_populate_record(null::${quoteQualified(tableFor(resource, ctx.graph?.tables))}, json_build_object(${pairs.join(", ")}))`;
1001
+ return `bucket_id = ${quoteLiteral(id)}
1002
+ and ${qualified$1(ctx, `can_${sql}`)}(${row}, ${quoteLiteral(key)}::text)`;
1003
+ };
1004
+ const policies = [
1005
+ [
1006
+ "select",
1007
+ bucket.read,
1008
+ "read"
1009
+ ],
1010
+ [
1011
+ "insert",
1012
+ bucket.write,
1013
+ "write"
1014
+ ],
1015
+ [
1016
+ "update",
1017
+ bucket.write,
1018
+ "write"
1019
+ ],
1020
+ [
1021
+ "delete",
1022
+ bucket.delete,
1023
+ "delete"
1024
+ ]
1025
+ ].flatMap(([command, ref, field]) => {
1026
+ const key = grantKey(facts, ref, `${where}.${field}`, warnings, "row");
1027
+ if (key === void 0) return [];
1028
+ const expression = condition(key);
1029
+ return [{
1030
+ name: policyName("storage", id, command),
1031
+ table: "storage.objects",
1032
+ command,
1033
+ effect: "allow",
1034
+ roles: ["authenticated"],
1035
+ ...command === "insert" ? {} : { using: expression },
1036
+ ...command === "select" || command === "delete" ? {} : { check: expression }
1037
+ }];
1038
+ });
1039
+ if (policies.length === 0) throw configError(`PermDock CLI: ${where} needs read, write or delete`);
1040
+ return policies;
1041
+ });
1042
+ }
1043
+ /**
1044
+ * The `realtime.messages` and `storage.objects` policies `rls.realtime` and
1045
+ * `rls.storage` describe. A topic admits a row only where the subject holds the
1046
+ * permission in the scope instance its segment names, through an allow without
1047
+ * a row condition. A bucket builds a row whose id and scope column are the
1048
+ * folder, each cast to that column's type, and calls `can_<resource>` so the
1049
+ * resource's row conditions apply.
1050
+ */
1051
+ function realtimeStoragePolicies(ctx, facts, config, warnings = [], policy) {
1052
+ if (config.realtime === void 0 && config.storage === void 0) return [];
1053
+ if (ctx.dialect !== "supabase") throw configError(`PermDock CLI: rls.realtime and rls.storage need --dialect supabase (got ${ctx.dialect})`);
1054
+ const policies = [...config.realtime === void 0 ? [] : realtimePolicies(ctx, facts, config.realtime, warnings), ...config.storage === void 0 ? [] : storagePolicies(ctx, facts, config.storage, warnings, policy)];
1055
+ const seen = /* @__PURE__ */ new Set();
1056
+ for (const { name } of policies) {
1057
+ if (seen.has(name)) throw configError(`PermDock CLI: two rls.realtime or rls.storage entries both name the policy ${name}; rename one`);
1058
+ seen.add(name);
1059
+ }
1060
+ return policies;
1061
+ }
1062
+ // src/cli/rls/generate-policies.ts
1063
+ const ACTOR_GUARDS_HEADER = "-- rls.readOnlyActors with --helpers-only: restrictive policies on the write commands, which narrow the hand-written policies and grant nothing. Apply this after the migrations that create the tables.";
1064
+ const SERVICE_TABLES_HEADER = "-- Supabase Realtime and Storage: rls.realtime and rls.storage. RLS on both tables is Supabase's.";
1065
+ const REALTIME_HEADER = `-- Supabase Realtime policies from rls.realtime.
1066
+ -- These policies sit outside the scoped declarative sync: pg-delta's shadow database has no realtime.messages.
1067
+ -- Apply this file with an unscoped sync only where the Realtime service has created the table.`;
1068
+ const STORAGE_HEADER = `-- Supabase Storage policies from rls.storage.
1069
+ -- These policies sit outside the scoped declarative sync: pg-delta's shadow database has no storage.objects.
1070
+ -- Apply this file with an unscoped sync only where the Storage service has created the table.`;
1071
+ function serviceFile(header, items) {
1072
+ if (items.length === 0) return;
1073
+ return `${header}\n${items.map((item) => policySql(item)).join("\n")}`;
1074
+ }
1075
+ /**
1076
+ * Appends the `realtime.messages` and `storage.objects` policies, which never
1077
+ * get `tableSql`.
1078
+ */
1079
+ function withHelperTables(sql, helperTables) {
1080
+ if (helperTables === void 0) return sql;
1081
+ const tables = `${helperTables.trimEnd()}\n`;
1082
+ return sql.trim() === "" ? tables : `${sql.trimEnd()}\n\n${tables}`;
1083
+ }
1084
+ /**
1085
+ * The read-only actor policies `--helpers-only` writes: those on a table
1086
+ * `rls.tables` names. A resource it does not name has no known table, so its
1087
+ * write commands get a warning instead.
1088
+ */
1089
+ function helpersOnlyActorGuards(guards, tables, actorMayWrite, warnings) {
1090
+ const named = new Set(Object.values(tableNames(tables) ?? {}).map((table) => qualifySqlTable(table)));
1091
+ const kept = guards.filter((guard) => named.has(qualifySqlTable(guard.table)));
1092
+ const unmapped = [...new Set(guards.filter((guard) => !named.has(qualifySqlTable(guard.table))).map((guard) => qualifySqlTable(guard.table)))].toSorted();
1093
+ if (unmapped.length > 0) warnings.push(`rls.readOnlyActors with --helpers-only writes read-only actor policies only on tables rls.tables names; for ${unmapped.join(", ")}, name the table in rls.tables, or add \`and (select ${actorMayWrite}())\` to each hand-written insert, update and delete policy`);
1094
+ return kept;
1095
+ }
1096
+ function databaseModeWarnings(policy, { ctx }, warnings) {
1097
+ if (ctx.authorize !== "database") return;
1098
+ for (const { name } of ctx.scopes) if (policy.grants.some((grant) => grant.scope === name) && scopeTable(ctx, name) === void 0 && scopeSources(ctx, name).length === 0) warnings.push(`${name}-scoped grants read the ${name} memberships table in database mode: set rls.memberships.scopes.${name}, rls.membershipSources or supabase.hook.memberships (or --memberships for the first scope), otherwise they deny`);
1099
+ }
1100
+ /**
1101
+ * The grants compiled into table policies, and the Realtime and Storage
1102
+ * policies beside them.
1103
+ */
1104
+ function generatePolicies(input, policy, options, built, warnings) {
1105
+ const rls = input.config.rls;
1106
+ const { ctx } = built;
1107
+ const { fieldsMode, revokeColumns } = options;
1108
+ databaseModeWarnings(policy, built, warnings);
1109
+ const compiled = compileGrants(policy, ctx, tableNames(rls?.tables), warnings, input.skipClosures, rls?.rowHelpers !== void 0 || inheritTargets(policy).length > 0);
1110
+ const helpersOnly = input.helpersOnly === true || rls?.helpersOnly === true;
1111
+ if (helpersOnly && (input.target !== "sql" || revokeColumns)) return { refusal: "rls generate --helpers-only needs --target sql and no --revoke-columns: the table grants are hand-written, so revoke the restricted columns there" };
1112
+ const views = fieldsMode === void 0 ? [] : fieldViews(policy, ctx, compiled.branches, {
1113
+ revokeColumns,
1114
+ helpersOnly,
1115
+ mask: fieldsMode === "mask"
1116
+ }, warnings);
1117
+ const force = input.force === true || rls?.force === true;
1118
+ if (force && views.some((view) => view.companion !== void 0)) warnings.push("--force with --revoke-columns: each <table>_visible_fields companion reads as its owner, so its owner needs BYPASSRLS or the restricted columns read as null");
1119
+ const policyName = input.policyName ?? rls?.policyName;
1120
+ const assembled = assemblePolicies(fieldsMode === void 0 ? compiled.branches : rowBranches(compiled.branches), {
1121
+ perRole: input.policyPerRole === true || rls?.policyPerRole === true,
1122
+ ...policyName === void 0 ? {} : { name: policyName }
1123
+ });
1124
+ const actorKinds = readOnlyActorKinds(rls?.readOnlyActors);
1125
+ const actorGuards = actorKinds === void 0 || !helpersOnly ? [] : helpersOnlyActorGuards(readOnlyActorPolicies(assembled, actorMayWriteCall(ctx)), rls?.tables, qualified$1(ctx, ACTOR_MAY_WRITE), warnings);
1126
+ const withActors = (items) => actorKinds === void 0 ? items : [...items, ...readOnlyActorPolicies(items, actorMayWriteCall(ctx))];
1127
+ let tablePolicies;
1128
+ try {
1129
+ tablePolicies = realtimeStoragePolicies(ctx, {
1130
+ scopes: new Set(ctx.scopes.map((scope) => scope.name)),
1131
+ keys: new Set(listPermissions(policy.vocabulary.permissions).map((leaf) => leaf.key)),
1132
+ rowConditions: new Set(policyRowConditionKeys(policy))
1133
+ }, compact({
1134
+ realtime: rls?.realtime,
1135
+ storage: rls?.storage
1136
+ }), warnings, policy);
1137
+ } catch (cause) {
1138
+ return { refusal: describeError(cause) };
1139
+ }
1140
+ if (tablePolicies.length > 0 && helpersOnly) warnings.push("rls.realtime and rls.storage add policies, and --helpers-only writes none: no realtime.messages or storage.objects policy is written");
1141
+ const servicePolicies = tablePolicies.length === 0 || helpersOnly ? [] : withActors(tablePolicies);
1142
+ const parentPolicies = helpersOnly ? [] : withActors(assembled);
1143
+ const childPolicies = helpersOnly ? [] : withActors(followPolicies(ctx, policy, rls?.tables));
1144
+ const generated = {
1145
+ compiled,
1146
+ helpersOnly,
1147
+ force,
1148
+ views,
1149
+ policies: [...parentPolicies, ...childPolicies],
1150
+ parentPolicies,
1151
+ followPolicies: childPolicies,
1152
+ ...actorGuards.length === 0 ? {} : { actorGuards: [ACTOR_GUARDS_HEADER, ...actorGuards.map((item) => policySql(item))].join("\n") }
1153
+ };
1154
+ if (servicePolicies.length === 0) return generated;
1155
+ const realtimePolicies = serviceFile(REALTIME_HEADER, servicePolicies.filter((item) => qualifySqlTable(item.table) === "realtime.messages"));
1156
+ const storagePolicies = serviceFile(STORAGE_HEADER, servicePolicies.filter((item) => qualifySqlTable(item.table) === "storage.objects"));
1157
+ return {
1158
+ ...generated,
1159
+ helperTables: [SERVICE_TABLES_HEADER, ...servicePolicies.map(policySql)].join("\n"),
1160
+ ...realtimePolicies === void 0 ? {} : { realtimePolicies },
1161
+ ...storagePolicies === void 0 ? {} : { storagePolicies }
1162
+ };
1163
+ }
1164
+ // src/cli/rls/helper-bootstrap.ts
1165
+ function textArray(values) {
1166
+ return values.length === 0 ? "array[]::text[]" : `array[${values.map(quoteLiteral).join(", ")}]::text[]`;
1167
+ }
1168
+ /**
1169
+ * The bitset of the key indexes `indexes` selects (column `n`, 0-based) over
1170
+ * `bytes` bytes, as better-supabase's `compactBootstrapPermissions` writes it:
1171
+ * bit `n % 8` of byte `n / 8`, least significant first, in base64url without
1172
+ * padding. Postgres `encode(…, 'base64')` breaks lines every 76 characters, so
1173
+ * the newlines go with the padding.
1174
+ */
1175
+ function bitsetSql(indexes, bytes) {
1176
+ return `(select translate(encode(coalesce(decode(string_agg(lpad(to_hex(coalesce(b.v, 0)), 2, '0'), '' order by g.i), 'hex'), ''::bytea), 'base64'), '+/=' || chr(10), '-_')
1177
+ from generate_series(0, ${String(bytes - 1)}) g(i)
1178
+ left join (
1179
+ select x.n / 8 as i, sum(1 << (x.n % 8)) as v from (${indexes}) x(n) group by 1
1180
+ ) b on b.i = g.i)`;
1181
+ }
1182
+ /**
1183
+ * `permdock_bootstrap_permissions(p_tenant text default null) returns jsonb`:
1184
+ * the caller's permissions as better-supabase's compact
1185
+ * `BootstrapPermissionsWire` (`apiVersion: 1`, `form: 'compact'`). `keys` is
1186
+ * every permission key of the policy, sorted; each root-scope instance the
1187
+ * caller is a member of (only `p_tenant` when it is given) gets one bitset of
1188
+ * the keys `permitted_<root>_permission_keys` answers there, and `platform` the
1189
+ * keys `permdock_has_permission` grants. A tenant the caller is no member of,
1190
+ * an unknown or a malformed one answers no tenants. `security invoker`: every
1191
+ * helper it calls answers for the caller only. Execute belongs to
1192
+ * `authenticated`.
1193
+ */
1194
+ function bootstrapPermissionsSql(ctx, keys, grants) {
1195
+ const fn = qualified$1(ctx, BOOTSTRAP_PERMISSIONS);
1196
+ const root = rootName(ctx);
1197
+ const bytes = Math.ceil(keys.length / 8);
1198
+ const platform = Object.entries(grants.get("global") ?? {}).filter(([key, effects]) => effects.allow.length > 0 && keys.includes(key)).map(([key]) => key).toSorted();
1199
+ const memberIds = qualified$1(ctx, memberIdsHelper(root));
1200
+ const held = qualified$1(ctx, checkName(permissionKeysHelper(root)));
1201
+ const has = qualified$1(ctx, PERMISSION_HELPERS.has);
1202
+ return `-- the caller's permissions in better-supabase's compact BootstrapPermissionsWire: the policy's keys once, a bitset per ${root} the caller is a member of (p_tenant alone when given) and one for platform
1203
+ create or replace function ${fn}(p_tenant text default null)
1204
+ returns jsonb
1205
+ language sql
1206
+ stable
1207
+ security invoker
1208
+ set search_path = ''
1209
+ as $$
1210
+ with pdk_k(key, n) as (
1211
+ select k.key, (k.n - 1)::integer
1212
+ from unnest(${textArray(keys)}) with ordinality as k(key, n)
1213
+ ),
1214
+ pdk_t(id) as (
1215
+ select t.id from ${memberIds}() as t(id)
1216
+ where p_tenant is null or t.id::text = p_tenant
1217
+ ),
1218
+ pdk_p(n) as (
1219
+ select k.n from pdk_k k
1220
+ where k.key = any(${textArray(platform)}) and ${has}(k.key)
1221
+ )
1222
+ select jsonb_strip_nulls(jsonb_build_object(
1223
+ 'apiVersion', 1,
1224
+ 'form', 'compact',
1225
+ 'keys', to_jsonb(${textArray(keys)}),
1226
+ 'tenants', coalesce((
1227
+ select jsonb_object_agg(t.id::text, ${bitsetSql(`select k.n from ${held}(t.id) h(key) join pdk_k k on k.key = h.key`, bytes)})
1228
+ from pdk_t t
1229
+ ), '{}'::jsonb),
1230
+ 'platform', case when exists (select 1 from pdk_p) then ${bitsetSql("select p.n from pdk_p p", bytes)} end
1231
+ ))
1232
+ $$;
1233
+ revoke execute on function ${fn}(text) from public, anon, authenticated;
1234
+ grant execute on function ${fn}(text) to authenticated;
1235
+ `;
1236
+ }
1237
+ // src/cli/rls/rule-indexes.ts
1238
+ function isOwner(entry) {
1239
+ return typeof entry === "object" && !("tableOf" in entry);
1240
+ }
1241
+ /**
1242
+ * The indexes the generated rules read through, beyond the scope keys: the
1243
+ * foreign key of each `follows` child, the parent and user columns of a
1244
+ * recursive `walk`, and the manager table's user and manager columns, each led
1245
+ * by the column the walk compares and followed by the edge's tenant.
1246
+ */
1247
+ function ruleIndexTargets(policy, config) {
1248
+ const out = [];
1249
+ const add = (table, columns) => {
1250
+ out.push({
1251
+ table: qualifySqlTable(table),
1252
+ columns
1253
+ });
1254
+ };
1255
+ for (const [name, entry] of Object.entries(config.tables ?? {})) {
1256
+ if (!isOwner(entry)) continue;
1257
+ for (const [child, column] of Object.entries(entry.follows ?? {})) add(child, [column]);
1258
+ if (entry.walk === "recursive") {
1259
+ const node = policy.resources.get(name);
1260
+ const table = tableNameOf(entry, name, config.tables);
1261
+ if (node?.parent !== void 0) add(table, [node.parent.field]);
1262
+ add(table, [entry.user ?? node?.id ?? "id"]);
1263
+ }
1264
+ }
1265
+ const managers = config.managers;
1266
+ if (managers !== void 0) {
1267
+ const tenant = managers.tenant === void 0 ? [] : [managers.tenant];
1268
+ add(managers.table, [managers.user, ...tenant]);
1269
+ add(managers.table, [managers.manager, ...tenant]);
1270
+ }
1271
+ return out;
1272
+ }
1273
+ /**
1274
+ * `targets` without a second index on the same table and leading columns, in a
1275
+ * stable order.
1276
+ */
1277
+ function mergeIndexTargets(...lists) {
1278
+ const seen = /* @__PURE__ */ new Map();
1279
+ for (const target of lists.flat()) {
1280
+ const key = `${target.table}\u0000${target.columns.join("\0")}\u0000${target.where ?? ""}`;
1281
+ if (!seen.has(key)) seen.set(key, target);
1282
+ }
1283
+ return [...seen.values()].toSorted((a, b) => {
1284
+ const left = `${a.table}.${a.columns.join(",")}`;
1285
+ const right = `${b.table}.${b.columns.join(",")}`;
1286
+ return left < right ? -1 : left > right ? 1 : 0;
1287
+ });
1288
+ }
1289
+ // src/cli/rls/shims.ts
1290
+ const NAME$1 = /^[a-z_][a-z0-9_]*$/u;
1291
+ /**
1292
+ * The key a legacy caller passes, mapped the way `rls migrate` maps it: `keys`
1293
+ * and `renamed` exactly, then the longest `prefixes` entry.
1294
+ */
1295
+ function mappedKey(config, renamed) {
1296
+ const exact = {
1297
+ ...renamed,
1298
+ ...config.keys
1299
+ };
1300
+ const prefixes = Object.entries(config.prefixes ?? {}).toSorted(([a], [b]) => b.length - a.length);
1301
+ const fallback = prefixes.length === 0 ? "p_key" : `case ${prefixes.map(([from, to]) => `when pg_catalog.starts_with(p_key, ${quoteLiteral(from)}) then ${quoteLiteral(to)} || pg_catalog.substr(p_key, ${String(from.length + 1)})`).join(" ")} else p_key end`;
1302
+ if (Object.keys(exact).length === 0) return fallback;
1303
+ return `coalesce(${quoteLiteral(JSON.stringify(exact))}::jsonb ->> p_key, ${fallback})`;
1304
+ }
1305
+ function scopeOf(ctx, scope) {
1306
+ if (!ctx.scopes.some((item) => item.name === scope)) throw configError(`PermDock CLI: rls.migrate helper scope '${scope}' is not a declared scope`);
1307
+ return scope;
1308
+ }
1309
+ function addKey(list, key) {
1310
+ if (!list.includes(key)) list.push(key);
1311
+ }
1312
+ /**
1313
+ * The grant keys behind each permission, per scope: the keys of its
1314
+ * unconditional allows, and every deny key. A shim cannot apply a row condition
1315
+ * or a validity window, so a conditional allow answers nothing and a
1316
+ * conditional deny always subtracts; the conditioned keys are listed apart. A
1317
+ * break-glass key answers only the break-glass read, so it is left out too.
1318
+ * Rows seeded under a former key are left out; the shim maps a former key to
1319
+ * the current one first.
1320
+ */
1321
+ function shimGrants(rows, conditioned, renamed) {
1322
+ const byScope = /* @__PURE__ */ new Map();
1323
+ for (const row of rows.toSorted((a, b) => a.grantKey < b.grantKey ? -1 : a.grantKey > b.grantKey ? 1 : 0)) {
1324
+ if (Object.hasOwn(renamed, row.permission) || row.effect === "allow" && row.grantKey === breakGlassKey(row.permission)) continue;
1325
+ const scope = byScope.get(row.scope) ?? {};
1326
+ byScope.set(row.scope, scope);
1327
+ const keys = (Object.hasOwn(scope, row.permission) ? scope[row.permission] : void 0) ?? {
1328
+ allow: [],
1329
+ deny: []
1330
+ };
1331
+ scope[row.permission] = keys;
1332
+ const isConditioned = conditioned.has(row.grantKey);
1333
+ if (row.effect === "allow") {
1334
+ if (isConditioned) {
1335
+ keys["conditioned-allow"] ??= [];
1336
+ addKey(keys["conditioned-allow"], row.grantKey);
1337
+ } else addKey(keys.allow, row.grantKey);
1338
+ continue;
1339
+ }
1340
+ addKey(keys.deny, row.grantKey);
1341
+ if (isConditioned) {
1342
+ keys["conditioned-deny"] ??= [];
1343
+ addKey(keys["conditioned-deny"], row.grantKey);
1344
+ }
1345
+ }
1346
+ return byScope;
1347
+ }
1348
+ function shimMap(grants, scope) {
1349
+ const entries = Object.entries(grants.get(scope) ?? {}).flatMap(([permission, keys]) => keys.allow.length === 0 && keys.deny.length === 0 ? [] : [[permission, {
1350
+ allow: keys.allow,
1351
+ deny: keys.deny
1352
+ }]]);
1353
+ return JSON.stringify(Object.fromEntries(entries));
1354
+ }
1355
+ function shimFunction(name, args, argTypes, returns, sql) {
1356
+ return `create or replace function ${name}(${args})
1357
+ returns ${returns}
1358
+ language sql
1359
+ stable
1360
+ security definer
1361
+ set search_path = ''
1362
+ as $$
1363
+ ${sql}
1364
+ $$;
1365
+ revoke execute on function ${name}(${argTypes}) from public, anon;
1366
+ grant execute on function ${name}(${argTypes}) to authenticated;`;
1367
+ }
1368
+ function grantKeys(keys, scope, effect) {
1369
+ return `pg_catalog.jsonb_array_elements_text(coalesce(${keys.map(scope)} -> (${keys.key}) -> ${quoteLiteral(effect)}, '[]'::jsonb)) g(grant_key)`;
1370
+ }
1371
+ /**
1372
+ * The instances of `scope` the caller holds an unconditional allow of the key
1373
+ * in, minus those it holds a deny in.
1374
+ */
1375
+ function idsSql(ctx, keys, scope) {
1376
+ const helper = qualified$1(ctx, permittedIdsHelper(scope));
1377
+ return ` select a.id
1378
+ from ${grantKeys(keys, scope, "allow")}
1379
+ cross join lateral ${helper}(g.grant_key) a(id)
1380
+ except
1381
+ select d.id
1382
+ from ${grantKeys(keys, scope, "deny")}
1383
+ cross join lateral ${helper}(g.grant_key) d(id)`;
1384
+ }
1385
+ function hasSql(ctx, keys) {
1386
+ const has = qualified$1(ctx, HELPERS.has);
1387
+ return `exists (select 1 from ${grantKeys(keys, "global", "allow")} where ${has}(g.grant_key))
1388
+ and not exists (select 1 from ${grantKeys(keys, "global", "deny")} where ${has}(g.grant_key))`;
1389
+ }
1390
+ function shim(ctx, config, keys, fn, helper) {
1391
+ switch (helper.form) {
1392
+ case "ids": {
1393
+ const scope = scopeOf(ctx, helper.scope);
1394
+ return shimFunction(fn, "p_key text", "text", `setof ${scopeTypeOf(ctx, scope)}`, idsSql(ctx, keys, scope));
1395
+ }
1396
+ case "row": {
1397
+ const scope = scopeOf(ctx, helper.scope);
1398
+ const type = scopeTypeOf(ctx, scope);
1399
+ return shimFunction(fn, `p_id ${type}, p_key text`, `${type}, text`, "boolean", ` select coalesce(p_id in (\n${idsSql(ctx, keys, scope)}\n ), false)`);
1400
+ }
1401
+ case "membership": {
1402
+ const scope = scopeOf(ctx, helper.scope);
1403
+ const type = scopeTypeOf(ctx, scope);
1404
+ return shimFunction(fn, `p_id ${type}`, type, "boolean", ` select coalesce(p_id in (select ${qualified$1(ctx, memberIdsHelper(scope))}()), false)`);
1405
+ }
1406
+ case "role": {
1407
+ const scope = scopeOf(ctx, helper.scope);
1408
+ const type = scopeTypeOf(ctx, scope);
1409
+ const values = Object.entries(ctx.roleValues ?? {});
1410
+ const role = values.length === 0 ? "p_role" : `case p_role ${values.map(([from, to]) => `when ${quoteLiteral(from)} then ${quoteLiteral(to)}`).join(" ")} else p_role end`;
1411
+ return shimFunction(fn, `p_id ${type}, p_role text`, `${type}, text`, "boolean", ` select coalesce(p_id in (select ${qualified$1(ctx, memberIdsHelper(scope))}(array[${role}])), false)`);
1412
+ }
1413
+ case "global": return shimFunction(fn, "p_key text", "text", "boolean", ` select ${hasSql(ctx, keys)}`);
1414
+ case "scoped": {
1415
+ const literals = /* @__PURE__ */ new Map();
1416
+ for (const scope of ctx.scopes) literals.set(scope.name, scope.name);
1417
+ for (const [literal, scope] of Object.entries(config.scopes ?? {})) literals.set(literal, scopeOf(ctx, scope));
1418
+ const global = config.globalScopes ?? [];
1419
+ return shimFunction(fn, "p_scope text, p_id text, p_key text", "text, text, text", "boolean", ` select case\n${[...global.length === 0 ? [] : [` when p_scope in (${global.map(quoteLiteral).join(", ")}) then ${hasSql(ctx, keys)}`], ...[...literals].filter(([literal]) => !global.includes(literal)).map(([literal, scope]) => ` when p_scope = ${quoteLiteral(literal)} then coalesce(p_id in (select s.id::text from (\n${idsSql(ctx, keys, scope)}\n ) s(id)), false)`)].join("\n")}\n else false\n end`);
1420
+ }
1421
+ default: return helper;
1422
+ }
1423
+ }
1424
+ /**
1425
+ * One wrapper per `rls.migrate.helpers` entry under its legacy name, so SQL
1426
+ * that `rls migrate` has not rewritten yet (function bodies, views, triggers)
1427
+ * answers from the PermDock helpers. A wrapper maps the legacy key to the
1428
+ * permission key, then to the grant keys `grants` lists for the helper's scope,
1429
+ * so a permission whose grants are split by condition still answers. Each is
1430
+ * `security definer` with an empty `search_path`, so a caller needs `execute`
1431
+ * on the wrapper only, not usage on the helper schema.
1432
+ */
1433
+ function shimsSql(ctx, config, shims, renamed, grants) {
1434
+ const schema = shims.schema ?? "public";
1435
+ const keys = {
1436
+ key: mappedKey(config, renamed),
1437
+ map: (scope) => `${quoteLiteral(shimMap(grants, scope))}::jsonb`
1438
+ };
1439
+ const chunks = [`-- permdock shims: legacy helper names over the permdock helpers; drop each once doctor reports no caller (PD056)`];
1440
+ for (const [name, helper] of Object.entries(config.helpers).toSorted(byKey)) {
1441
+ if (!NAME$1.test(name)) throw configError(`PermDock CLI: unsafe rls.migrate helper name '${name}'`);
1442
+ chunks.push(shim(ctx, config, keys, `${quoteIdent(schema)}.${name}`, helper));
1443
+ }
1444
+ return `${chunks.join("\n\n")}\n`;
1445
+ }
1446
+ // src/cli/rls/triggers.ts
1447
+ const PREFIX = "PermDock CLI";
1448
+ const EVENTS = /* @__PURE__ */ new Set([
1449
+ "insert",
1450
+ "update",
1451
+ "delete",
1452
+ "truncate"
1453
+ ]);
1454
+ const AUDITED = [
1455
+ CUSTOM_ROLES.permissions,
1456
+ CUSTOM_ROLES.includes,
1457
+ "user_roles"
1458
+ ];
1459
+ const IDENT$1 = /^[a-z_][a-z0-9_$]*$/u;
1460
+ /** The tables `sql` creates in `schema`, by name without the schema. */
1461
+ function generatedTables(sql, schema) {
1462
+ const prefix = `create table if not exists ${quoteIdent(schema)}.`;
1463
+ const found = /* @__PURE__ */ new Set();
1464
+ for (const line of sql.split("\n")) {
1465
+ if (!line.startsWith(prefix)) continue;
1466
+ const name = /^"?([A-Za-z_][\w$]*)"?/u.exec(line.slice(prefix.length))?.[1];
1467
+ if (name !== void 0) found.add(name);
1468
+ }
1469
+ return [...found].toSorted();
1470
+ }
1471
+ function functionName(name, label) {
1472
+ if (typeof name !== "string" || name.split(".").length !== 2) throw configError(`${PREFIX}: ${label} must be a schema-qualified function such as audit.log_change, got ${JSON.stringify(name)}`);
1473
+ return quoteTable(name);
1474
+ }
1475
+ function knownTable(table, tables, label) {
1476
+ if (!tables.includes(table)) throw configError(`${PREFIX}: ${label} names ${table}, which rls generate does not create with this config; it creates ${tables.join(", ")}`);
1477
+ }
1478
+ function triggerSql(table, trigger, label) {
1479
+ if (typeof trigger.name !== "string" || trigger.name === "" || trigger.name.toLowerCase().startsWith("permdock_")) throw configError(`${PREFIX}: ${label}.name must be a name outside permdock_, which generated triggers use, got ${JSON.stringify(trigger.name)}`);
1480
+ if (trigger.when !== "before" && trigger.when !== "after") throw configError(`${PREFIX}: ${label}.when must be before or after`);
1481
+ const events = trigger.events;
1482
+ if (events.length === 0 || !events.every((event) => EVENTS.has(event))) throw configError(`${PREFIX}: ${label}.events must list insert, update, delete or truncate`);
1483
+ const level = trigger.level ?? "row";
1484
+ if (level !== "row" && level !== "statement") throw configError(`${PREFIX}: ${label}.level must be row or statement`);
1485
+ if (level === "row" && events.includes("truncate")) throw configError(`${PREFIX}: ${label} fires on truncate, which Postgres allows only with level: 'statement'`);
1486
+ const fn = functionName(trigger.function, `${label}.function`);
1487
+ const args = (trigger.args ?? []).map((arg) => quoteLiteral(arg));
1488
+ const name = quoteIdent(trigger.name);
1489
+ return `drop trigger if exists ${name} on ${table};
1490
+ create trigger ${name}
1491
+ ${trigger.when} ${[...new Set(events)].join(" or ")} on ${table}
1492
+ for each ${level} execute function ${fn}(${args.join(", ")});`;
1493
+ }
1494
+ /**
1495
+ * `rls.triggers`: the application's triggers on generated tables, after the
1496
+ * tables. A table this run does not create is an error, so a trigger never
1497
+ * silently goes missing.
1498
+ */
1499
+ function triggersSql(triggers, schema, tables) {
1500
+ if (triggers === void 0) return "";
1501
+ const chunks = [];
1502
+ for (const [table, list] of Object.entries(triggers).toSorted(byKey)) {
1503
+ knownTable(table, tables, `rls.triggers.${table}`);
1504
+ const target = `${quoteIdent(schema)}.${quoteIdent(table)}`;
1505
+ for (const [index, trigger] of list.entries()) chunks.push(triggerSql(target, trigger, `rls.triggers.${table}[${String(index)}]`));
1506
+ }
1507
+ return chunks.length === 0 ? "" : `-- rls.triggers: triggers the application owns on generated tables\n${chunks.join("\n")}\n`;
1508
+ }
1509
+ /**
1510
+ * `rls.audit`: one call of the audit function per generated table, which
1511
+ * registers the table with the application's audit module. Statements that run
1512
+ * code, so they travel with the seeds.
1513
+ */
1514
+ function auditSql(audit, schema, tables) {
1515
+ if (audit === void 0) return "";
1516
+ const fn = functionName(audit.function, "rls.audit.function");
1517
+ const listed = audit.tables;
1518
+ if (listed !== void 0) for (const table of listed) knownTable(table, tables, "rls.audit.tables");
1519
+ const targets = listed ?? AUDITED.filter((table) => tables.includes(table));
1520
+ const args = Object.entries(audit.args ?? {}).map(([name, value]) => {
1521
+ if (!IDENT$1.test(name)) throw configError(`${PREFIX}: rls.audit.args names ${JSON.stringify(name)}, which is not a lower-case parameter name`);
1522
+ return `, ${quoteIdent(name)} => ${quoteLiteral(value)}`;
1523
+ });
1524
+ if (targets.length === 0) return "";
1525
+ return `-- rls.audit: generated tables registered with ${audit.function}
1526
+ ${targets.map((table) => `select ${fn}(${quoteLiteral(`${quoteIdent(schema)}.${quoteIdent(table)}`)}::regclass${args.join("")});`).join("\n")}
1527
+ `;
1528
+ }
1529
+ // src/cli/rls/generate-sql.ts
1530
+ /**
1531
+ * The checks that need the SQL context: `--backfill-out`,
1532
+ * `rls.anonymousSignIns`, `rls.jsonSchema`.
1533
+ */
1534
+ function preflight(input, { ctx }) {
1535
+ const rls = input.config.rls;
1536
+ const from = typeof rls?.customRoles === "object" ? rls.customRoles.from : void 0;
1537
+ if (input.backfillOut !== void 0 && from === void 0) return { refusal: "rls generate --backfill-out needs rls.customRoles.from in permdock.config.ts" };
1538
+ let backfill;
1539
+ if (from !== void 0) try {
1540
+ backfill = backfillSql(ctx, from, rls?.migrate);
1541
+ } catch (cause) {
1542
+ return { refusal: describeError(cause) };
1543
+ }
1544
+ if (ctx.anonymousSignIns === "deny" && ctx.dialect !== "supabase") return { refusal: `rls.anonymousSignIns needs --dialect supabase (got ${ctx.dialect})` };
1545
+ const jsonSchema = rls?.jsonSchema;
1546
+ if (jsonSchema === "auto") return { refusal: "rls.jsonSchema: 'auto' is not supported. Set true or false. 'auto' needed a do block, which a schema file cannot carry." };
1547
+ if (jsonSchema !== void 0 && typeof jsonSchema !== "boolean") return { refusal: `rls.jsonSchema must be true or false (got ${JSON.stringify(jsonSchema)})` };
1548
+ return {
1549
+ backfill,
1550
+ jsonSchema: typeof jsonSchema === "boolean" ? jsonSchema : void 0
1551
+ };
1552
+ }
1553
+ function rbacPart(input, policy, { ctx, schema, authorize }, warnings) {
1554
+ const rootMapped = ctx.scopes[0] === void 0 ? void 0 : scopeTable(ctx, ctx.scopes[0].name);
1555
+ const rootTable = rootMapped === void 0 ? void 0 : {
1556
+ ...rootMapped.table,
1557
+ tenant: rootMapped.column
1558
+ };
1559
+ const rbac = input.rbac ? rbacScaffold(policy, {
1560
+ schema,
1561
+ authorize,
1562
+ ...rootTable === void 0 ? {} : { memberships: rootTable },
1563
+ ...ctx.scopes[0] === void 0 ? {} : { scope: ctx.scopes[0].name },
1564
+ ...ctx.customRoles === void 0 ? {} : { customRoles: {
1565
+ declared: ctx.customRoles.declared,
1566
+ ...ctx.customRoles.levels === true ? { levels: true } : {}
1567
+ } },
1568
+ context: ctx
1569
+ }) : void 0;
1570
+ if (rbac !== void 0) warnings.push(...rbac.warnings);
1571
+ if (input.rbac) warnings.push("the token hook that writes user_role and memberships comes from permdock supabase hook generate");
1572
+ return rbac;
1573
+ }
1574
+ /** The ownership, approval store, graph, row-helper and break-glass sections. */
1575
+ function sectionsSql(input, policy, options, built, generated, jsonSchema, warnings) {
1576
+ const rls = input.config.rls;
1577
+ const { ctx, graph, ownership } = built;
1578
+ const { compiled } = generated;
1579
+ const owned = [ownershipSql(ctx), assignmentSql(ctx)].filter((part) => part !== "").join("\n");
1580
+ if (ctx.assignments !== void 0 && (ownership === void 0 || ownership.assigns.length === 0)) warnings.push("rls.assignments needs a role that declares assigns: no assignment trigger is written");
1581
+ let approvals;
1582
+ try {
1583
+ approvals = approvalsSql(ctx, rls?.approvals, jsonSchema ?? false, readOnlyActorKinds(rls?.readOnlyActors) !== void 0);
1584
+ } catch (cause) {
1585
+ return { refusal: describeError(cause) };
1586
+ }
1587
+ if (typeof rls?.approvals === "object" && rls.approvals.delegations === true && ctx.authorize !== "database") warnings.push("rls.approvals.delegations with --authorize jwt: permdock_is_approver cannot read a delegator's permissions from the caller's token, so in SQL a cover never satisfies a holder() approver; approvalsHandler still does");
1588
+ const graphed = graphSql(ctx, graph, tableNames(rls?.tables));
1589
+ let rowHelpers = "";
1590
+ const storageRows = storageResources(rls?.storage);
1591
+ const asked = rls?.rowHelpers;
1592
+ const select = asked === true ? true : [...asked ?? [], ...storageRows];
1593
+ if (asked !== void 0 || inheritTargets(policy).length > 0 || storageRows.length > 0) {
1594
+ const readable = (grants) => [...options.fieldsMode === void 0 ? grants.branches : rowBranches(grants.branches), ...grants.actionBranches];
1595
+ try {
1596
+ const rowCtx = {
1597
+ ...ctx,
1598
+ reuseMemo: true,
1599
+ memoTouches: []
1600
+ };
1601
+ const narrowed = compileGrants(policy, {
1602
+ ...rowCtx,
1603
+ candidates: CANDIDATES
1604
+ }, tableNames(rls?.tables), [], input.skipClosures, true);
1605
+ rowHelpers = rowHelpersSql(rowCtx, policy, readable(compiled), select, tableNames(rls?.tables), warnings, readable(narrowed));
1606
+ } catch (cause) {
1607
+ return { refusal: describeError(cause) };
1608
+ }
1609
+ }
1610
+ const breakGlass = breakGlassSql(ctx, breakGlassEntries(policy, tableNames(rls?.tables)));
1611
+ const chain = walkChainSql(ctx, policy, rls?.tables, typeof rls?.approvals === "object" && rls.approvals.delegations === true);
1612
+ const tree = treeHelperSql(ctx, policy, rls?.tables, rls?.treeValues);
1613
+ return [
1614
+ approvals,
1615
+ owned === "" ? void 0 : owned,
1616
+ graphed === "" ? void 0 : graphed,
1617
+ breakGlass === "" ? void 0 : breakGlass,
1618
+ rowHelpers === "" ? void 0 : rowHelpers,
1619
+ chain === "" ? void 0 : chain,
1620
+ tree === "" ? void 0 : tree
1621
+ ];
1622
+ }
1623
+ /**
1624
+ * Whether `anon` calls a helper: `rls.anonExecute`, an anon field view or an
1625
+ * anon branch reading the user id.
1626
+ */
1627
+ function anonExecutes(input, { compiled, views }) {
1628
+ return input.config.rls?.anonExecute === true || views.some((view) => view.roles.includes("anon")) || compiled.branches.some((branch) => branch.roles.includes("anon") && [
1629
+ branch.access,
1630
+ branch.using,
1631
+ branch.check
1632
+ ].some((sql) => sql?.includes("permdock_user_id") === true));
1633
+ }
1634
+ /**
1635
+ * Everything before the table policies: helpers, sections, shims, scaffold and
1636
+ * triggers.
1637
+ */
1638
+ function preambleSql(input, policy, options, built, generated, jsonSchema, warnings) {
1639
+ const rls = input.config.rls;
1640
+ const { ctx } = built;
1641
+ const { compiled } = generated;
1642
+ const rbac = rbacPart(input, policy, built, warnings);
1643
+ const sections = sectionsSql(input, policy, options, built, generated, jsonSchema, warnings);
1644
+ if (isRefusal(sections)) return sections;
1645
+ const configured = rls?.shims;
1646
+ const shimsConfig = typeof configured === "object" ? configured : configured === true || input.shims === true ? {} : void 0;
1647
+ if (shimsConfig !== void 0 && rls?.migrate === void 0) return { refusal: "PermDock CLI: rls generate --shims needs rls.migrate.helpers in permdock.config.ts" };
1648
+ const renamed = Object.fromEntries(renamedKeys(policy.vocabulary.permissions));
1649
+ const grants = shimGrants(compiled.rolePermissions, compiled.conditionedKeys, renamed);
1650
+ const anonExecute = anonExecutes(input, generated);
1651
+ const actorKinds = readOnlyActorKinds(rls?.readOnlyActors);
1652
+ const usesLiveSession = compiled.branches.some((branch) => [
1653
+ branch.access,
1654
+ branch.using,
1655
+ branch.check
1656
+ ].some((sql) => sql?.includes(SESSION_LIVE_HELPER) === true));
1657
+ const shims = shimsConfig === void 0 || rls?.migrate === void 0 ? void 0 : shimsSql(ctx, rls.migrate, shimsConfig, renamed, grants);
1658
+ const core = [
1659
+ rbac?.head,
1660
+ helpersSql(ctx, compiled.rolePermissions, {
1661
+ levelReach: compiled.levelReach,
1662
+ permissions: listPermissions(policy.permissions).map((leaf) => leaf.key).toSorted(),
1663
+ userRoles: !input.rbac,
1664
+ anonExecute,
1665
+ withoutSeeds: splitsPart(input.split, "seeds"),
1666
+ ...rls?.trustedReaders === void 0 ? {} : { trustedReaders: rls.trustedReaders }
1667
+ }),
1668
+ permissionHelpersSql(ctx, grants, renamed, anonExecute),
1669
+ ctx.dialect === "supabase" ? bootstrapPermissionsSql(ctx, listPermissions(policy.permissions).map((leaf) => leaf.key).toSorted(), grants) : void 0,
1670
+ nonEmptyOr(permissionHoldersSql(ctx), void 0),
1671
+ actorKinds === void 0 ? void 0 : actorMayWriteSql(ctx, actorKinds),
1672
+ usesLiveSession ? sessionLiveHelperSql(ctx) : void 0,
1673
+ ...sections,
1674
+ shims,
1675
+ rbac?.tail
1676
+ ].filter((part) => part !== void 0).join("\n");
1677
+ const created = generatedTables(core, built.schema);
1678
+ let ownTriggers;
1679
+ let audit;
1680
+ try {
1681
+ ownTriggers = triggersSql(rls?.triggers, built.schema, created);
1682
+ audit = auditSql(rls?.audit, built.schema, created);
1683
+ } catch (cause) {
1684
+ return { refusal: describeError(cause) };
1685
+ }
1686
+ const seedsSplit = splitsPart(input.split, "seeds");
1687
+ const closure = seedsSplit || ctx.seeds === "view" ? "" : closureBackfillSql(ctx, built.graph, tableNames(rls?.tables));
1688
+ return {
1689
+ preamble: [
1690
+ core,
1691
+ ownTriggers,
1692
+ seedsSplit ? "" : audit,
1693
+ closure
1694
+ ].filter((part) => part !== "").join("\n"),
1695
+ audit
1696
+ };
1697
+ }
1698
+ function seedsBody(ctx, schema, rows, closure) {
1699
+ let body;
1700
+ switch (ctx.seeds) {
1701
+ case "function":
1702
+ body = `select ${quoteQualified(`${schema}.seed`)}();`;
1703
+ break;
1704
+ case "view":
1705
+ body = ctx.staticGrants === "ref" ? "-- rls.staticGrants: 'ref': load the policy bundle with permdock policy bundle --kind sql" : "-- rls.seeds: 'view': the role_permissions rows are in the helpers part";
1706
+ break;
1707
+ case void 0:
1708
+ body = seedSql(ctx, rows);
1709
+ break;
1710
+ default: return ctx.seeds;
1711
+ }
1712
+ return closure === "" ? body : `${body}\n${closure}`;
1713
+ }
1714
+ function forceWarnings({ graph }, warnings) {
1715
+ for (const entry of graph.values()) {
1716
+ const own = [...entry.relations].filter((name) => !("edge" in (entry.node.relations[name] ?? {})));
1717
+ if (own.length > 0) warnings.push(`--force: ${entry.node.name} relations ${own.join(", ")} are read from the ${entry.node.name} table itself, so ${graphHelper(entry.node.name)} would recurse through its own policy; keep ${entry.node.name} unforced or move them to edge tables`);
1718
+ }
1719
+ }
1720
+ /**
1721
+ * The row columns that belong to a table. With `rls.tables` set, a resource it
1722
+ * does not name is a table only when generated policies are written for it;
1723
+ * with `--helpers-only` it has none, so it gets no index.
1724
+ */
1725
+ function tableColumns(rowColumns, tables, helpersOnly, warnings) {
1726
+ if (tables === void 0) return rowColumns;
1727
+ const unmapped = [...new Set(rowColumns.map((item) => item.resource).filter((resource) => !Object.hasOwn(tables, resource)))].toSorted();
1728
+ if (unmapped.length === 0) return rowColumns;
1729
+ if (helpersOnly) {
1730
+ warnings.push(`no index is suggested for resources without an rls.tables entry: ${unmapped.join(", ")}; map each one that is a table`);
1731
+ return rowColumns.filter((item) => Object.hasOwn(tables, item.resource));
1732
+ }
1733
+ warnings.push(`policies for resources without an rls.tables entry target a table named after the resource: ${unmapped.map((resource) => qualifySqlTable(resource)).join(", ")}; map each one to its table`);
1734
+ return rowColumns;
1735
+ }
1736
+ /** The `--target` file, and for Drizzle and Prisma the SQL migration beside it. */
1737
+ function emitTarget(input, built, generated, preamble) {
1738
+ const rls = input.config.rls;
1739
+ const { ctx } = built;
1740
+ const { policies, force, views, helperTables, actorGuards } = generated;
1741
+ const outRel = input.out ?? rls?.out ?? defaultOut(input.target);
1742
+ const migration = input.target === "sql" ? "" : dialectRoles(migrationSql(policies, withHelperTables(preamble, helperTables), force, views), ctx.dialect);
1743
+ const migrationRel = migration === "" ? void 0 : migrationOut(outRel);
1744
+ const helpers = migrationRel === void 0 ? void 0 : basename(migrationRel);
1745
+ let text;
1746
+ switch (input.target) {
1747
+ case "sql":
1748
+ text = dialectRoles(withHelperTables(withHelperTables(emitSql(policies, preamble, force, views), helperTables), actorGuards), ctx.dialect);
1749
+ break;
1750
+ case "drizzle":
1751
+ text = emitDrizzle(policies, compact({
1752
+ dialect: ctx.dialect,
1753
+ schema: rls?.drizzle?.schema,
1754
+ exports: rls?.drizzle?.exports,
1755
+ helpers
1756
+ }));
1757
+ break;
1758
+ case "prisma":
1759
+ text = emitPrisma(policies, compact({
1760
+ models: rls?.prisma?.models,
1761
+ helpers
1762
+ }));
1763
+ break;
1764
+ default: return input.target;
1765
+ }
1766
+ return {
1767
+ text,
1768
+ migration,
1769
+ migrationRel,
1770
+ outRel
1771
+ };
1772
+ }
1773
+ /**
1774
+ * The generated SQL for one run, before `--db-url-stdin` prunes the index
1775
+ * targets.
1776
+ */
1777
+ function generateSql(input, policy, options, built, warnings) {
1778
+ const rls = input.config.rls;
1779
+ const { ctx } = built;
1780
+ const checked = preflight(input, built);
1781
+ if (isRefusal(checked)) return checked;
1782
+ const { jsonSchema } = checked;
1783
+ if (jsonSchema !== void 0 && jsonSchema !== false && (rls?.approvals === void 0 || rls.approvals === false || typeof rls.approvals === "object" && rls.approvals.store === false)) warnings.push("rls.jsonSchema constrains the approval store's body, which needs rls.approvals: true; nothing else is jsonb");
1784
+ const generated = generatePolicies(input, policy, options, built, warnings);
1785
+ if (isRefusal(generated)) return generated;
1786
+ const assembled = preambleSql(input, policy, options, built, generated, jsonSchema, warnings);
1787
+ if (isRefusal(assembled)) return assembled;
1788
+ const { preamble, audit } = assembled;
1789
+ if (generated.force) forceWarnings(built, warnings);
1790
+ const emitted = emitTarget(input, built, generated, preamble);
1791
+ const { parentPolicies, followPolicies: childPolicies, force, views, helperTables, realtimePolicies, storagePolicies, helpersOnly, actorGuards } = generated;
1792
+ const seedsSplit = splitsPart(input.split, "seeds");
1793
+ return {
1794
+ ...generated,
1795
+ ...emitted,
1796
+ backfill: checked.backfill,
1797
+ indexes: mergeIndexTargets(indexTargets(ctx, tableColumns(generated.compiled.rowColumns, tableNames(rls?.tables), helpersOnly, warnings)), ruleIndexTargets(policy, {
1798
+ ...rls?.tables === void 0 ? {} : { tables: rls.tables },
1799
+ ...typeof rls?.approvals === "object" && rls.approvals.managers !== void 0 ? { managers: rls.approvals.managers } : {}
1800
+ })),
1801
+ parts: (indexes) => ({
1802
+ policies: dialectRoles(withHelperTables(emitSql(parentPolicies, "", force, views), helperTables), ctx.dialect),
1803
+ declarativePolicies: dialectRoles(emitSql(parentPolicies, "", force, views), ctx.dialect),
1804
+ ...childPolicies.length === 0 ? {} : { follows: dialectRoles(emitSql(childPolicies, "", force, []), ctx.dialect) },
1805
+ ...realtimePolicies === void 0 ? {} : { realtimePolicies: dialectRoles(realtimePolicies, ctx.dialect) },
1806
+ ...storagePolicies === void 0 ? {} : { storagePolicies: dialectRoles(storagePolicies, ctx.dialect) },
1807
+ helpers: dialectRoles(withHelperTables(emitSql([], preamble, false, helpersOnly ? views : []), actorGuards), ctx.dialect),
1808
+ seeds: `${SEEDS_MARKER} schema=${built.schema}\n${seedsBody(ctx, built.schema, generated.compiled.rolePermissions, closureBackfillSql(ctx, built.graph, tableNames(rls?.tables)))}\n${seedsSplit ? audit : ""}`,
1809
+ indexes: `${INDEXES_MARKER}\n${indexesSql(indexes)}\n`
1810
+ })
1811
+ };
1812
+ }
1813
+ // src/cli/rls/emit/output-plan.ts
1814
+ function moveUndiffed(sql, label, part) {
1815
+ const { kept, moved } = splitUndiffed(sql);
1816
+ const [first = "", ...rest] = kept.split("\n");
1817
+ return {
1818
+ sql: [
1819
+ first,
1820
+ `-- what supabase db diff drops from this part is in ${label}`,
1821
+ ...rest
1822
+ ].join("\n"),
1823
+ grants: `-- the privileges and view options supabase db diff drops from the ${part} part\n${moved.join("\n")}`
1824
+ };
1825
+ }
1826
+ /** Why `--split` cannot be written for `mode`, or `undefined`. */
1827
+ function splitRefusal(mode, plan) {
1828
+ const seedsWithoutOut = plan.split.includes("seeds") && plan.seedsOut === void 0 && !plan.noSeeds && !plan.seedView;
1829
+ const helpersWithoutSeeds = plan.split.includes("helpers") && !plan.noSeeds && !plan.split.includes("seeds") && !plan.seedFunction && !plan.seedView;
1830
+ switch (mode) {
1831
+ case "pg-delta":
1832
+ if (plan.explicitOut && !plan.placeholder) return `rls generate --split needs {part} in --out, or no --out for pg-delta's per-schema layout (got ${plan.outRel})`;
1833
+ if (plan.grantsOut !== void 0) return "rls generate --grants-out is for --schemas migra: pg-delta keeps the grants in each part, so drop --grants-out";
1834
+ if (helpersWithoutSeeds) return "rls generate --split helpers under pg-delta needs the seeds part with --seeds-out: pg-delta rejects the role_permissions rows in a declarative file";
1835
+ if (seedsWithoutOut) return "rls generate --split seeds under pg-delta needs --seeds-out: pg-delta does not diff the role_permissions rows, so they go in a migration";
1836
+ return;
1837
+ case "migra":
1838
+ if (!plan.placeholder) return `rls generate --split under migra needs {part} in --out, for example supabase/schemas/identity/056_permdock_{part}.sql (got ${plan.outRel})`;
1839
+ if (helpersWithoutSeeds) return "rls generate --split helpers under migra needs the seeds part with --seeds-out: supabase db diff does not carry the role_permissions rows from a schema file";
1840
+ if (seedsWithoutOut) return "rls generate --split seeds under migra needs --seeds-out: supabase db diff does not carry the role_permissions rows, so they go in a migration";
1841
+ return;
1842
+ case "migrations":
1843
+ if (!plan.placeholder) return `rls generate --split needs {part} in --out, for example supabase/migrations/20260101000000_permdock_{part}.sql (got ${plan.outRel})`;
1844
+ if (plan.grantsOut !== void 0) return "rls generate --grants-out is for --schemas migra: a hand-written migration keeps its grants, so drop --grants-out";
1845
+ return;
1846
+ default: return mode;
1847
+ }
1848
+ }
1849
+ /**
1850
+ * The files `generate` writes: one, or one per `--split` part, plus the hook's
1851
+ * grants under migra.
1852
+ */
1853
+ function outputFiles(plan) {
1854
+ const { input } = plan;
1855
+ const split = parseSplit(input.split);
1856
+ if (typeof split === "string") return split;
1857
+ if (split?.includes("policies") === true && plan.helpersOnly) return "rls generate --helpers-only writes no policies part; drop it from --split";
1858
+ if (split === void 0) {
1859
+ if (input.grantsOut !== void 0) return "rls generate --grants-out needs --split with the helpers or hook part";
1860
+ if (input.seedsOut !== void 0) return "rls generate --seeds-out needs --split with the seeds part";
1861
+ if (input.noSeeds === true) return "rls generate --no-seeds needs --split: without it the seeds are part of the one file";
1862
+ const files = [{
1863
+ part: "rls",
1864
+ rel: plan.outRel,
1865
+ text: plan.text
1866
+ }];
1867
+ const pgDeltaSchemas = resolveSchemas(input.cwd, input.config, input.schemas);
1868
+ const indexes = plan.sql().indexes;
1869
+ if (pgDeltaSchemas.mode === "pg-delta" && input.target === "sql" && plan.declarativeConfig && indexes.includes("create index")) files.push({
1870
+ part: "indexes",
1871
+ rel: pgDeltaPath(pgDeltaSchemas.schemaDir, "indexes", plan.schema),
1872
+ text: declarativeSql(indexes)
1873
+ });
1874
+ return files;
1875
+ }
1876
+ if (input.target !== "sql") return "rls generate --split needs --target sql";
1877
+ const schemas = resolveSchemas(input.cwd, input.config, input.schemas);
1878
+ const pgDelta = schemas.mode === "pg-delta" ? schemas : void 0;
1879
+ const placeholder = plan.outRel.includes("{part}");
1880
+ const refused = splitRefusal(schemas.mode, {
1881
+ split,
1882
+ placeholder,
1883
+ explicitOut: input.out !== void 0,
1884
+ outRel: plan.outRel,
1885
+ grantsOut: input.grantsOut,
1886
+ seedsOut: input.seedsOut,
1887
+ noSeeds: input.noSeeds === true,
1888
+ seedFunction: input.config.rls?.seeds === "function",
1889
+ seedView: input.config.rls?.seeds === "view" || input.config.rls?.staticGrants === "ref"
1890
+ });
1891
+ if (refused !== void 0) return refused;
1892
+ const at = (part, schema = plan.schema) => pgDelta === void 0 || placeholder ? partPath(plan.outRel, part) : pgDeltaPath(pgDelta.schemaDir, part, schema);
1893
+ if (input.grantsOut !== void 0 && !split.includes("hook") && !split.includes("helpers")) return "rls generate --grants-out needs the helpers or hook part in --split";
1894
+ if (input.noSeeds === true && input.seedsOut !== void 0) return "rls generate --no-seeds and --seeds-out exclude each other: drop one";
1895
+ if (input.seedsOut !== void 0 && !split.includes("seeds")) return "rls generate --seeds-out needs the seeds part in --split";
1896
+ if (split.includes("hook") && input.config.supabase?.hook === void 0) return "rls generate --split hook needs supabase.hook in permdock.config.ts";
1897
+ const sql = plan.sql();
1898
+ const seeds = sql.seeds;
1899
+ const files = [];
1900
+ const label = grantsLabel(input.grantsOut);
1901
+ let grantsMarker = `${GRANTS_MARKER} schema=${plan.schema}`;
1902
+ const grants = [];
1903
+ for (const part of split) switch (part) {
1904
+ case "helpers": {
1905
+ const helpers = unguardAuthAdminGrants(sql.helpers);
1906
+ if (label === void 0) {
1907
+ files.push({
1908
+ part,
1909
+ rel: at(part),
1910
+ text: helpers
1911
+ });
1912
+ break;
1913
+ }
1914
+ const moved = moveUndiffed(helpers, label, part);
1915
+ files.push({
1916
+ part,
1917
+ rel: at(part),
1918
+ text: moved.sql
1919
+ });
1920
+ grants.push(guardAuthAdminGrants(moved.grants));
1921
+ break;
1922
+ }
1923
+ case "seeds": {
1924
+ if (input.noSeeds === true) break;
1925
+ const out = input.seedsOut;
1926
+ if (out !== void 0 && isSeedsDirectory(input.cwd, out)) {
1927
+ const planned = seedsMigration(input.cwd, out, SEEDS_MARKER, seeds, input.io.now?.() ?? dateAt());
1928
+ if (!planned.current || input.check) files.push({
1929
+ part,
1930
+ rel: planned.rel,
1931
+ text: seeds
1932
+ });
1933
+ if (!planned.current && planned.delta !== void 0) input.io.stderr(`${seedDeltaNote(planned.delta)}\n`);
1934
+ break;
1935
+ }
1936
+ files.push({
1937
+ part,
1938
+ rel: out ?? at(part),
1939
+ text: seeds
1940
+ });
1941
+ break;
1942
+ }
1943
+ case "indexes":
1944
+ files.push({
1945
+ part,
1946
+ rel: at(part),
1947
+ text: sql.indexes
1948
+ });
1949
+ break;
1950
+ case "policies":
1951
+ files.push({
1952
+ part,
1953
+ rel: at(part),
1954
+ text: pgDelta === void 0 ? sql.policies : sql.declarativePolicies
1955
+ });
1956
+ break;
1957
+ case "hook": {
1958
+ const hook = supabaseHookSql(plan.scopes, input.config, {}, label);
1959
+ const rel = at(part, hook.manifest.hook.schema);
1960
+ const aside = pgDelta !== void 0 && underSchemaDir(rel, pgDelta.schemaDir) ? asideAuthzReceive(hook.sql) : {
1961
+ sql: hook.sql,
1962
+ receive: void 0
1963
+ };
1964
+ files.push({
1965
+ part,
1966
+ rel,
1967
+ text: aside.sql
1968
+ });
1969
+ if (aside.receive !== void 0 && pgDelta !== void 0) files.push({
1970
+ part: "realtime",
1971
+ rel: serviceRel(pgDelta.schemaDir, "realtime/authz.sql"),
1972
+ text: aside.receive
1973
+ });
1974
+ const [marker = grantsMarker, ...rest] = hook.grants.split("\n");
1975
+ grantsMarker = marker;
1976
+ grants.push(rest.join("\n").trimEnd());
1977
+ break;
1978
+ }
1979
+ default: return part;
1980
+ }
1981
+ if (sql.follows !== void 0) files.push({
1982
+ part: "follows",
1983
+ rel: pgDelta === void 0 || placeholder ? partPath(plan.outRel, "follows") : `${pgDelta.schemaDir.replace(/\/$/u, "")}/permdock/follows.sql`,
1984
+ text: sql.follows
1985
+ });
1986
+ if (pgDelta !== void 0 && split.includes("policies")) {
1987
+ if (sql.realtimePolicies !== void 0) files.push({
1988
+ part: "realtime",
1989
+ rel: serviceRel(pgDelta.schemaDir, "realtime/permdock.sql"),
1990
+ text: sql.realtimePolicies
1991
+ });
1992
+ if (sql.storagePolicies !== void 0) files.push({
1993
+ part: "storage",
1994
+ rel: serviceRel(pgDelta.schemaDir, "storage/permdock.sql"),
1995
+ text: sql.storagePolicies
1996
+ });
1997
+ }
1998
+ if (pgDelta !== void 0) for (const [index, file] of files.entries()) {
1999
+ if (file.part === "seeds" && input.seedsOut !== void 0 || !underSchemaDir(file.rel, pgDelta.schemaDir)) continue;
2000
+ files[index] = {
2001
+ ...file,
2002
+ text: declarativeSql(file.text)
2003
+ };
2004
+ }
2005
+ if (input.grantsOut !== void 0) files.push({
2006
+ part: "grants",
2007
+ rel: input.grantsOut,
2008
+ text: `${[grantsMarker, ...grants].join("\n")}\n`
2009
+ });
2010
+ return files;
2011
+ }
2012
+ // src/cli/rls/generate-write.ts
2013
+ /**
2014
+ * Writes the emitted parts, or reports drift. Nothing is written when `check`
2015
+ * is set. `--out -` prints the SQL on stdout and the notes on stderr.
2016
+ */
2017
+ /**
2018
+ * The files `generate` would write, including the Drizzle or Prisma migration
2019
+ * and the custom-role backfill. A string is a refusal.
2020
+ */
2021
+ function generatedFiles(plan) {
2022
+ const { input } = plan;
2023
+ const schemas = resolveSchemas(input.cwd, input.config, input.schemas);
2024
+ const read = readSupabaseConfig(input.cwd);
2025
+ const planned = outputFiles({
2026
+ declarativeConfig: schemas.mode === "pg-delta" && read?.ok === true && read.config.pgDelta !== void 0,
2027
+ input,
2028
+ outRel: plan.outRel,
2029
+ text: plan.text,
2030
+ helpersOnly: plan.helpersOnly,
2031
+ sql: plan.parts,
2032
+ scopes: plan.scopes,
2033
+ schema: plan.schema
2034
+ });
2035
+ if (typeof planned === "string") return planned;
2036
+ const files = [...planned];
2037
+ if (plan.migrationRel !== void 0) files.push({
2038
+ part: "migration",
2039
+ rel: plan.migrationRel,
2040
+ text: plan.migration
2041
+ });
2042
+ if (input.backfillOut !== void 0 && plan.backfill !== void 0) {
2043
+ const file = dataMigrationFile({
2044
+ cwd: input.cwd,
2045
+ out: input.backfillOut,
2046
+ part: "backfill",
2047
+ marker: BACKFILL_MARKER,
2048
+ text: plan.backfill,
2049
+ now: input.io.now?.() ?? dateAt(),
2050
+ check: input.check,
2051
+ reserved: files.map((other) => other.rel)
2052
+ });
2053
+ if (file !== void 0) files.push(file);
2054
+ }
2055
+ return files;
2056
+ }
2057
+ function writeGenerated(plan) {
2058
+ const { input, text, extras } = plan;
2059
+ const planned = generatedFiles(plan);
2060
+ if (typeof planned === "string") return {
2061
+ code: 2,
2062
+ output: planned,
2063
+ text,
2064
+ ...extras
2065
+ };
2066
+ const files = planned;
2067
+ if (input.check) {
2068
+ const drift = driftOf(input.cwd, files);
2069
+ return drift.length === 0 ? {
2070
+ code: 0,
2071
+ output: "rls generate up to date",
2072
+ text,
2073
+ ...extras
2074
+ } : {
2075
+ code: 1,
2076
+ output: drift.map((line) => `rls generate drift: ${line}`).join("\n"),
2077
+ text,
2078
+ ...extras
2079
+ };
2080
+ }
2081
+ const written = writeOutputFiles(input.cwd, files);
2082
+ const notes = [...written.wrote.length === 0 ? [] : [`wrote ${written.wrote.join(", ")}`], ...plan.warnings];
2083
+ if (written.printed !== "") for (const note of notes) input.io.stderr(note);
2084
+ return {
2085
+ code: 0,
2086
+ output: written.printed === "" ? notes.join("\n") : written.printed,
2087
+ text,
2088
+ ...extras
2089
+ };
2090
+ }
2091
+ // src/cli/rls/index-scan.ts
2092
+ /**
2093
+ * An index PermDock generated (`permdock_<table>_<columns>_idx`), in the
2094
+ * indexes part or in a migration derived from it: it never counts as serving
2095
+ * its own target.
2096
+ */
2097
+ const GENERATED_INDEX = /\bcreate\s+index\s+(?:if\s+not\s+exists\s+)?"?permdock_\w*_idx"?[^;]*;/giu;
2098
+ const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`;
2099
+ const NAME = String.raw`${IDENT}(?:\s*\.\s*${IDENT})?`;
2100
+ const CREATE_INDEX = new RegExp(String.raw`\bcreate\s+(?:unique\s+)?index\s+(?:concurrently\s+)?(?:if\s+not\s+exists\s+)?(?:${IDENT}\s+)?on\s+(?:only\s+)?(${NAME})\s*(?:using\s+\w+\s*)?\(`, "giu");
2101
+ const ADD_KEY = new RegExp(String.raw`\balter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(${NAME})\s+add\s+(?:constraint\s+${IDENT}\s+)?(?:unique|primary\s+key)\s*(?:nulls\s+not\s+distinct\s*)?\(`, "giu");
2102
+ const CREATE_TABLE = new RegExp(String.raw`\bcreate\s+(?:unlogged\s+|temp(?:orary)?\s+)?table\s+(?:if\s+not\s+exists\s+)?(${NAME})\s*\(`, "giu");
2103
+ const TABLE_NAME = new RegExp(String.raw`\bcreate\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(${NAME})`, "giu");
2104
+ const TABLE_KEY = new RegExp(String.raw`^(?:constraint\s+${IDENT}\s+)?(?:unique|primary\s+key)\s*(?:nulls\s+not\s+distinct\s*)?\(`, "iu");
2105
+ const COLUMN_KEY = new RegExp(String.raw`^(${IDENT})\s+[^,]*?\b(?:primary\s+key|unique)\b`, "iu");
2106
+ const NOT_A_COLUMN = /^(?:constraint|check|foreign|exclude|like)\b/iu;
2107
+ function bare(part) {
2108
+ const trimmed = part.trim();
2109
+ return trimmed.startsWith("\"") ? trimmed.slice(1, -1).replaceAll("\"\"", "\"") : trimmed.toLowerCase();
2110
+ }
2111
+ /** `schema.table`, with `public` for an unqualified name. */
2112
+ function qualified(raw) {
2113
+ const parts = raw.split(".").map(bare);
2114
+ return parts.length === 1 ? `public.${parts.join("")}` : parts.join(".");
2115
+ }
2116
+ function stripComments(sql) {
2117
+ return sql.replaceAll(/\/\*[\s\S]*?\*\//gu, " ").replaceAll(/--[^\n]*/gu, " ");
2118
+ }
2119
+ /**
2120
+ * The text between the `(` that ends `match` and its closing `)`, and the index
2121
+ * after it.
2122
+ */
2123
+ function group(text, open) {
2124
+ let depth = 1;
2125
+ for (let index = open; index < text.length; index += 1) {
2126
+ const char = text[index];
2127
+ if (char === "'" || char === "\"") {
2128
+ const close = text.indexOf(char, index + 1);
2129
+ if (close === -1) return;
2130
+ index = close;
2131
+ } else if (char === "(") depth += 1;
2132
+ else if (char === ")") {
2133
+ depth -= 1;
2134
+ if (depth === 0) return {
2135
+ body: text.slice(open, index),
2136
+ end: index + 1
2137
+ };
2138
+ }
2139
+ }
2140
+ }
2141
+ function splitTop(body) {
2142
+ const items = [];
2143
+ let depth = 0;
2144
+ let from = 0;
2145
+ for (let index = 0; index < body.length; index += 1) {
2146
+ const char = body[index];
2147
+ if (char === "'" || char === "\"") index = Math.max(body.indexOf(char, index + 1), index);
2148
+ else if (char === "(") depth += 1;
2149
+ else if (char === ")") depth -= 1;
2150
+ else if (char === "," && depth === 0) {
2151
+ items.push(body.slice(from, index));
2152
+ from = index + 1;
2153
+ }
2154
+ }
2155
+ items.push(body.slice(from));
2156
+ return items.map((item) => item.trim());
2157
+ }
2158
+ /** The first capture group of a match; every pattern here captures it. */
2159
+ function captured(match) {
2160
+ return match.slice(1, 2).join("");
2161
+ }
2162
+ /** The index just past a match. */
2163
+ function endOf(match) {
2164
+ return match.index + match[0].length;
2165
+ }
2166
+ /** The plain key columns of an index column list, cut at the first expression. */
2167
+ function keyColumns(body) {
2168
+ const columns = [];
2169
+ for (const item of splitTop(body)) {
2170
+ const match = new RegExp(`^(${IDENT})(?:\\s|$)`, "u").exec(item);
2171
+ if (match === null || item.startsWith("(")) break;
2172
+ columns.push(bare(captured(match)));
2173
+ }
2174
+ return columns;
2175
+ }
2176
+ /**
2177
+ * Key columns of each index, unique constraint and primary key the SQL creates,
2178
+ * per `schema.table`.
2179
+ */
2180
+ function indexKeysFromSql(sql) {
2181
+ const text = stripComments(sql);
2182
+ const keys = {};
2183
+ const add = (table, columns) => {
2184
+ if (columns.length > 0) (keys[qualified(table)] ??= []).push(columns);
2185
+ };
2186
+ for (const pattern of [CREATE_INDEX, ADD_KEY]) for (const match of text.matchAll(pattern)) {
2187
+ const found = group(text, endOf(match));
2188
+ if (found !== void 0) add(captured(match), keyColumns(found.body));
2189
+ }
2190
+ for (const match of text.matchAll(CREATE_TABLE)) {
2191
+ const found = group(text, endOf(match));
2192
+ if (found === void 0) continue;
2193
+ for (const item of splitTop(found.body)) if (TABLE_KEY.test(item)) {
2194
+ const inner = group(item, item.indexOf("(") + 1);
2195
+ if (inner !== void 0) add(captured(match), keyColumns(inner.body));
2196
+ } else if (!NOT_A_COLUMN.test(item)) {
2197
+ const column = COLUMN_KEY.exec(item)?.[1];
2198
+ if (column !== void 0) add(captured(match), [bare(column)]);
2199
+ }
2200
+ }
2201
+ return keys;
2202
+ }
2203
+ /**
2204
+ * The index keys of the SQL files under the migration and schema folders of
2205
+ * `cwd`.
2206
+ */
2207
+ function indexKeysFromProject(cwd) {
2208
+ const all = {};
2209
+ for (const file of sqlFiles(cwd, [...MIGRATION_DIRS])) {
2210
+ const keys = indexKeysFromSql(readFileSync(file, "utf8").replaceAll(GENERATED_INDEX, ""));
2211
+ for (const [table, list] of Object.entries(keys)) (all[table] ??= []).push(...list);
2212
+ }
2213
+ return all;
2214
+ }
2215
+ /** Every `schema.table` the SQL creates, temporary tables left out. */
2216
+ function tablesFromSql(sql) {
2217
+ return new Set([...stripComments(sql).matchAll(TABLE_NAME)].map((match) => qualified(captured(match))));
2218
+ }
2219
+ /**
2220
+ * Every `schema.table` the SQL files under the migration and schema folders of
2221
+ * `cwd` create.
2222
+ */
2223
+ function tablesFromProject(cwd) {
2224
+ const all = /* @__PURE__ */ new Set();
2225
+ for (const file of sqlFiles(cwd, [...MIGRATION_DIRS])) for (const table of tablesFromSql(readFileSync(file, "utf8"))) all.add(table);
2226
+ return all;
2227
+ }
2228
+ /**
2229
+ * The targets no index in `keys` leads with: its key columns start with the
2230
+ * target's, as `pruneIndexTargets` reads a database.
2231
+ */
2232
+ function withoutServedTargets(targets, keys) {
2233
+ return targets.filter((target) => !(keys[target.table] ?? []).some((key) => target.columns.every((column, at) => key[at] === column)));
2234
+ }
2235
+ // src/cli/rls/generate.ts
2236
+ function refused(output) {
2237
+ return {
2238
+ code: 2,
2239
+ output,
2240
+ text: ""
2241
+ };
2242
+ }
2243
+ async function runRlsGenerate(input) {
2244
+ const options = generateOptions(input);
2245
+ if (isRefusal(options)) return refused(options.refusal);
2246
+ const loaded = await loadGeneratePolicy(input);
2247
+ if (isPolicyLoadFailure(loaded)) return loaded;
2248
+ const policy = loaded;
2249
+ const built = buildContext(input, policy, options);
2250
+ if (isRefusal(built)) return refused(built.refusal);
2251
+ const warnings = [];
2252
+ const generated = generateSql(input, policy, options, built, warnings);
2253
+ if (isRefusal(generated)) return refused(generated.refusal);
2254
+ const { ctx } = built;
2255
+ const { text, migration, migrationRel, helpersOnly } = generated;
2256
+ let indexes = generated.indexes;
2257
+ const bindings = tableBindings(generated.compiled.rowColumns.map((item) => item.resource), tableNames(input.config.rls?.tables), helpersOnly);
2258
+ if (input.config.rls?.tables === void 0) warnings.push(...bindingNotes(bindings, input.db !== void 0));
2259
+ warnings.push(...triggerNotes(text));
2260
+ if (ctx.seeds === "function") warnings.push(`run select ${built.schema}.seed(); after each deploy`);
2261
+ if (input.db === void 0) {
2262
+ indexes = withoutServedTargets(indexes, indexKeysFromProject(input.cwd));
2263
+ warnings.push(...unknownTableNotes(bindings, tablesFromProject(input.cwd)));
2264
+ }
2265
+ if (input.db !== void 0) try {
2266
+ const facts = await readTableIndexFacts(input.db, [.../* @__PURE__ */ new Set([...indexes.map((target) => target.table), ...bindings.map((binding) => binding.table)])], input.connect);
2267
+ const missing = missingBindings(bindings, facts.columns);
2268
+ if (missing.length > 0) return refused(`rls generate: ${missing.map((binding) => `resource ${binding.resource} is bound to ${binding.table}, which the database does not have`).join("; ")}; name the table in rls.tables, or set rls.tables.<resource>: false for a resource with no table`);
2269
+ const pruned = pruneIndexTargets(indexes, facts);
2270
+ indexes = pruned.targets;
2271
+ warnings.push(...pruned.warnings);
2272
+ } catch (cause) {
2273
+ return {
2274
+ code: exitCodeOfError(cause),
2275
+ output: describeError(cause),
2276
+ text: ""
2277
+ };
2278
+ }
2279
+ if (input.split !== void 0 && !splitsPart(input.split, "policies") && !helpersOnly) warnings.push(`skipped policies: rls.split has no policies part, so no table policy is written${generated.followPolicies.length === 0 ? "" : "; the rls.tables.<resource>.follows policies are still written to the follows part"}`);
2280
+ if (!splitsPart(input.split, "indexes")) for (const target of indexes) warnings.push(`index suggestion: create index on ${target.table} (${target.columns.join(", ")}), or add indexes to --split`);
2281
+ const extras = migration === "" ? {} : { migration };
2282
+ const listed = input.write === false && input.listFiles === true ? generatedFiles({
2283
+ input,
2284
+ outRel: generated.outRel,
2285
+ text,
2286
+ helpersOnly,
2287
+ parts: () => generated.parts(indexes),
2288
+ scopes: ctx.scopes,
2289
+ schema: built.schema,
2290
+ migration,
2291
+ migrationRel,
2292
+ backfill: generated.backfill
2293
+ }) : void 0;
2294
+ if (typeof listed === "string") return refused(listed);
2295
+ if (input.write === false) return {
2296
+ code: 0,
2297
+ output: warnings.join("\n"),
2298
+ text,
2299
+ policies: generated.policies,
2300
+ seeds: generated.compiled.rolePermissions,
2301
+ indexes,
2302
+ keys: {
2303
+ permissions: listPermissions(policy.vocabulary.permissions).map((leaf) => leaf.key),
2304
+ rowConditions: [...policyRowConditionKeys(policy)],
2305
+ levels: levelKeys(policy),
2306
+ renamed: Object.fromEntries(renamedKeys(policy.vocabulary.permissions))
2307
+ },
2308
+ schema: built.schema,
2309
+ helpersOnly,
2310
+ explain: explainRls({
2311
+ config: input.config,
2312
+ ctx,
2313
+ schema: built.schema,
2314
+ authorize: built.authorize,
2315
+ generated,
2316
+ text
2317
+ }),
2318
+ ...listed === void 0 ? {} : { files: listed.map((file) => ({
2319
+ path: file.rel,
2320
+ contents: file.text
2321
+ })) },
2322
+ ...extras
2323
+ };
2324
+ return writeGenerated({
2325
+ input,
2326
+ outRel: generated.outRel,
2327
+ text,
2328
+ helpersOnly,
2329
+ parts: () => generated.parts(indexes),
2330
+ scopes: ctx.scopes,
2331
+ schema: built.schema,
2332
+ migration,
2333
+ migrationRel,
2334
+ backfill: generated.backfill,
2335
+ warnings,
2336
+ extras
2337
+ });
2338
+ }
2339
+ export { describeExplain as n, runRlsGenerate as t };