better-supabase 0.20.0 → 0.22.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 (513) hide show
  1. package/dist/{adapter-CfuBICuG.js → adapter-D4aNBxhm.js} +4 -4
  2. package/dist/{ai-cache-BuNbWEFI.js → ai-cache-BFRKxgZ4.js} +2 -2
  3. package/dist/{ai-files-DeMWQfzs.js → ai-files-m_2z3rH1.js} +3 -3
  4. package/dist/{ai-schedules-Bp-U0cZG.d.ts → ai-schedules-7uQNMXve.d.ts} +1 -1
  5. package/dist/ai-sdk/agents/index.d.ts +2 -2
  6. package/dist/ai-sdk/batches/index.js +3 -3
  7. package/dist/ai-sdk/cache/index.js +1 -1
  8. package/dist/ai-sdk/chat/index.js +1 -1
  9. package/dist/ai-sdk/files/index.js +2 -2
  10. package/dist/ai-sdk/index.js +3 -3
  11. package/dist/ai-sdk/mcp/index.js +2 -2
  12. package/dist/ai-sdk/workflow/index.js +2 -2
  13. package/dist/api-3C0AWFeP.js +696 -0
  14. package/dist/{api-BIw5g_4V.d.ts → api-CHObZL7m.d.ts} +2 -2
  15. package/dist/{app-tables-oYkgtcRM.d.ts → app-tables-BGzdnQm5.d.ts} +1 -1
  16. package/dist/astro/index.d.ts +3 -3
  17. package/dist/astro/index.js +5 -5
  18. package/dist/{attachments-BTIwCuwm.js → attachments-BXbLnNxm.js} +5 -5
  19. package/dist/{authorization-08F77H2w.d.ts → authorization-DhoA7dsD.d.ts} +22 -8
  20. package/dist/{automations-jIIaT9EJ.js → automations-BMuqwZZn.js} +5 -5
  21. package/dist/better-result/index.d.ts +2 -2
  22. package/dist/{bind-BwQGUqdQ.d.ts → bind-CFsctoFJ.d.ts} +4 -4
  23. package/dist/{block-authors-D9hyCizs.js → block-authors-Bw3zdzgl.js} +1 -1
  24. package/dist/{block-env-Dh0Fe-fK.d.ts → block-env-BrUNeuJ_.d.ts} +4 -4
  25. package/dist/{block-events-pBXPzwnW.js → block-events-IWAyafO3.js} +1 -1
  26. package/dist/{block-fields-DE_FgpOU.js → block-fields-BjXgX_5c.js} +4 -3
  27. package/dist/{block-helpers-DnCtsKtv.js → block-helpers-B0f0ZVb5.js} +169 -4
  28. package/dist/{block-hooks-DbIpkq7a.js → block-hooks-DKtz0HRh.js} +1 -1
  29. package/dist/{block-subjects-BRJO0IqO.js → block-subjects-DFSuFY1a.js} +1 -1
  30. package/dist/blocks/access-requests/index.d.ts +1 -1
  31. package/dist/blocks/access-requests/index.js +4 -5
  32. package/dist/blocks/activities/index.d.ts +1 -1
  33. package/dist/blocks/activities/index.js +4 -5
  34. package/dist/blocks/agents/index.d.ts +1 -1
  35. package/dist/blocks/agents/index.js +3 -4
  36. package/dist/blocks/ai-cache/index.d.ts +1 -1
  37. package/dist/blocks/ai-cache/index.js +2 -2
  38. package/dist/blocks/ai-chat/index.d.ts +4 -4
  39. package/dist/blocks/ai-chat/index.js +4 -5
  40. package/dist/blocks/ai-files/index.d.ts +1 -1
  41. package/dist/blocks/ai-files/index.js +2 -2
  42. package/dist/blocks/ai-keys/index.d.ts +1 -1
  43. package/dist/blocks/ai-keys/index.js +3 -4
  44. package/dist/blocks/ai-schedules/index.d.ts +2 -2
  45. package/dist/blocks/ai-schedules/index.js +5 -6
  46. package/dist/blocks/announcements/index.d.ts +4 -4
  47. package/dist/blocks/announcements/index.js +4 -5
  48. package/dist/blocks/api-keys/index.d.ts +2 -2
  49. package/dist/blocks/api-keys/index.js +5 -6
  50. package/dist/blocks/approvals/index.d.ts +1 -1
  51. package/dist/blocks/approvals/index.js +4 -5
  52. package/dist/blocks/assets/index.d.ts +1 -1
  53. package/dist/blocks/assets/index.js +3 -4
  54. package/dist/blocks/assignment/index.d.ts +1 -1
  55. package/dist/blocks/assignment/index.js +4 -5
  56. package/dist/blocks/attachments/index.d.ts +2 -2
  57. package/dist/blocks/attachments/index.js +5 -6
  58. package/dist/blocks/audit/index.d.ts +5 -5
  59. package/dist/blocks/audit/index.js +8 -9
  60. package/dist/blocks/automations/index.d.ts +3 -3
  61. package/dist/blocks/automations/index.js +6 -6
  62. package/dist/blocks/billable-time/index.d.ts +1 -1
  63. package/dist/blocks/billable-time/index.js +6 -7
  64. package/dist/blocks/billing/index.d.ts +3 -3
  65. package/dist/blocks/billing/index.js +6 -7
  66. package/dist/blocks/bookings/index.d.ts +3 -3
  67. package/dist/blocks/bookings/index.js +7 -7
  68. package/dist/blocks/bulk/index.d.ts +4 -3
  69. package/dist/blocks/bulk/index.js +4 -4
  70. package/dist/blocks/calendar/index.d.ts +2 -2
  71. package/dist/blocks/calendar/index.js +7 -7
  72. package/dist/blocks/catalog/index.d.ts +1 -1
  73. package/dist/blocks/catalog/index.js +5 -6
  74. package/dist/blocks/channels/index.d.ts +1 -1
  75. package/dist/blocks/channels/index.js +3 -4
  76. package/dist/blocks/collections/index.d.ts +1 -1
  77. package/dist/blocks/collections/index.js +3 -4
  78. package/dist/blocks/comments/index.d.ts +5 -5
  79. package/dist/blocks/comments/index.js +8 -9
  80. package/dist/blocks/compliance/index.d.ts +1 -1
  81. package/dist/blocks/compliance/index.js +5 -6
  82. package/dist/blocks/connectors/index.d.ts +1 -1
  83. package/dist/blocks/connectors/index.js +3 -4
  84. package/dist/blocks/contacts/index.d.ts +1 -1
  85. package/dist/blocks/contacts/index.js +4 -5
  86. package/dist/blocks/content/index.d.ts +1 -1
  87. package/dist/blocks/content/index.js +3 -4
  88. package/dist/blocks/contracts/index.d.ts +1 -1
  89. package/dist/blocks/contracts/index.js +8 -9
  90. package/dist/blocks/courses/index.d.ts +1 -1
  91. package/dist/blocks/courses/index.js +5 -6
  92. package/dist/blocks/created-by/index.d.ts +1 -1
  93. package/dist/blocks/custom-fields/index.d.ts +1 -1
  94. package/dist/blocks/custom-fields/index.js +2 -2
  95. package/dist/blocks/data-lifecycle/index.d.ts +1 -1
  96. package/dist/blocks/data-lifecycle/index.js +3 -4
  97. package/dist/blocks/deals/index.d.ts +1 -1
  98. package/dist/blocks/deals/index.js +9 -10
  99. package/dist/blocks/dispatch/index.d.ts +1 -1
  100. package/dist/blocks/dispatch/index.js +7 -8
  101. package/dist/blocks/documents/index.d.ts +1 -1
  102. package/dist/blocks/documents/index.js +2 -3
  103. package/dist/blocks/domains/index.d.ts +1 -1
  104. package/dist/blocks/domains/index.js +3 -4
  105. package/dist/blocks/donations/index.d.ts +1 -1
  106. package/dist/blocks/donations/index.js +7 -8
  107. package/dist/blocks/drive/index.d.ts +5 -1
  108. package/dist/blocks/drive/index.js +6 -7
  109. package/dist/blocks/employees/index.d.ts +2 -2
  110. package/dist/blocks/employees/index.js +7 -8
  111. package/dist/blocks/enrichment/index.d.ts +1 -1
  112. package/dist/blocks/enrichment/index.js +2 -3
  113. package/dist/blocks/enrollments/index.d.ts +1 -1
  114. package/dist/blocks/enrollments/index.js +3 -4
  115. package/dist/blocks/entitlements/index.d.ts +3 -3
  116. package/dist/blocks/entitlements/index.js +2 -2
  117. package/dist/blocks/expenses/index.d.ts +1 -1
  118. package/dist/blocks/expenses/index.js +6 -7
  119. package/dist/blocks/field-history/index.d.ts +1 -1
  120. package/dist/blocks/field-history/index.js +2 -3
  121. package/dist/blocks/flags/index.d.ts +1 -1
  122. package/dist/blocks/flags/index.js +4 -5
  123. package/dist/blocks/forecasts/index.d.ts +1 -1
  124. package/dist/blocks/forecasts/index.js +5 -6
  125. package/dist/blocks/forms/index.d.ts +2 -2
  126. package/dist/blocks/forms/index.js +4 -5
  127. package/dist/blocks/goals/index.d.ts +1 -1
  128. package/dist/blocks/goals/index.js +4 -5
  129. package/dist/blocks/guests/index.d.ts +1 -1
  130. package/dist/blocks/guests/index.js +4 -5
  131. package/dist/blocks/hiring/index.d.ts +1 -1
  132. package/dist/blocks/hiring/index.js +4 -5
  133. package/dist/blocks/identities/index.d.ts +1 -1
  134. package/dist/blocks/identities/index.js +2 -3
  135. package/dist/blocks/imports/index.d.ts +1 -1
  136. package/dist/blocks/imports/index.js +3 -3
  137. package/dist/blocks/inbox/index.d.ts +5 -5
  138. package/dist/blocks/inbox/index.js +4 -5
  139. package/dist/blocks/incidents/index.d.ts +1 -1
  140. package/dist/blocks/incidents/index.js +5 -6
  141. package/dist/blocks/index.d.ts +2 -2
  142. package/dist/blocks/index.js +7 -7
  143. package/dist/blocks/inventory/index.d.ts +1 -1
  144. package/dist/blocks/inventory/index.js +3 -4
  145. package/dist/blocks/invoices/index.d.ts +1 -1
  146. package/dist/blocks/invoices/index.js +6 -7
  147. package/dist/blocks/knowledge/index.d.ts +1 -1
  148. package/dist/blocks/knowledge/index.js +2 -2
  149. package/dist/blocks/lead-scoring/index.d.ts +1 -1
  150. package/dist/blocks/lead-scoring/index.js +4 -5
  151. package/dist/blocks/leases/index.d.ts +1 -1
  152. package/dist/blocks/leases/index.js +7 -8
  153. package/dist/blocks/leave/index.d.ts +1 -1
  154. package/dist/blocks/leave/index.js +4 -5
  155. package/dist/blocks/ledger/index.d.ts +1 -1
  156. package/dist/blocks/ledger/index.js +3 -4
  157. package/dist/blocks/mail-sync/index.d.ts +1 -1
  158. package/dist/blocks/mail-sync/index.js +5 -6
  159. package/dist/blocks/memberships/index.d.ts +1 -1
  160. package/dist/blocks/memory/index.d.ts +1 -1
  161. package/dist/blocks/memory/index.js +3 -4
  162. package/dist/blocks/messaging/index.d.ts +5 -5
  163. package/dist/blocks/messaging/index.js +6 -7
  164. package/dist/blocks/metrics/index.d.ts +1 -1
  165. package/dist/blocks/metrics/index.js +4 -5
  166. package/dist/blocks/mfa/index.d.ts +2 -2
  167. package/dist/blocks/moderation/index.d.ts +1 -1
  168. package/dist/blocks/moderation/index.js +3 -4
  169. package/dist/blocks/notifications/index.d.ts +4 -4
  170. package/dist/blocks/notifications/index.js +8 -9
  171. package/dist/blocks/numbering/index.d.ts +1 -1
  172. package/dist/blocks/numbering/index.js +2 -2
  173. package/dist/blocks/oauth-server/index.d.ts +1 -1
  174. package/dist/blocks/oauth-server/index.js +3 -4
  175. package/dist/blocks/onboarding/index.d.ts +2 -2
  176. package/dist/blocks/onboarding/index.js +2 -3
  177. package/dist/blocks/orders/index.d.ts +9 -2
  178. package/dist/blocks/orders/index.js +7 -8
  179. package/dist/blocks/organizations/index.d.ts +3 -3
  180. package/dist/blocks/organizations/index.js +5 -6
  181. package/dist/blocks/outbox/index.d.ts +1 -1
  182. package/dist/blocks/outbox/index.js +3 -4
  183. package/dist/blocks/passes/index.d.ts +2 -2
  184. package/dist/blocks/passes/index.js +7 -8
  185. package/dist/blocks/permissions/index.d.ts +3 -3
  186. package/dist/blocks/permissions/index.js +2 -3
  187. package/dist/blocks/pipelines/index.d.ts +1 -1
  188. package/dist/blocks/pipelines/index.js +4 -5
  189. package/dist/blocks/posts/index.d.ts +1 -1
  190. package/dist/blocks/posts/index.js +4 -5
  191. package/dist/blocks/profiles/index.d.ts +1 -1
  192. package/dist/blocks/profiles/index.js +3 -4
  193. package/dist/blocks/promotions/index.d.ts +1 -1
  194. package/dist/blocks/promotions/index.js +4 -5
  195. package/dist/blocks/push/index.d.ts +2 -2
  196. package/dist/blocks/push/index.js +5 -6
  197. package/dist/blocks/queue/index.d.ts +1 -1
  198. package/dist/blocks/queue/index.js +7 -8
  199. package/dist/blocks/quotes/index.d.ts +1 -1
  200. package/dist/blocks/quotes/index.js +6 -7
  201. package/dist/blocks/rank/index.d.ts +1 -1
  202. package/dist/blocks/rank/index.js +2 -2
  203. package/dist/blocks/reactions/index.d.ts +4 -4
  204. package/dist/blocks/reactions/index.js +4 -5
  205. package/dist/blocks/relations/index.d.ts +3 -2
  206. package/dist/blocks/relations/index.js +8 -8
  207. package/dist/blocks/reminders/index.d.ts +10 -6
  208. package/dist/blocks/reminders/index.js +13 -12
  209. package/dist/blocks/reviews/index.d.ts +1 -1
  210. package/dist/blocks/reviews/index.js +3 -4
  211. package/dist/blocks/saved-views/index.d.ts +3 -3
  212. package/dist/blocks/saved-views/index.js +4 -4
  213. package/dist/blocks/scores/index.d.ts +1 -1
  214. package/dist/blocks/scores/index.js +4 -4
  215. package/dist/blocks/search/index.d.ts +3 -3
  216. package/dist/blocks/search/index.js +3 -4
  217. package/dist/blocks/security-events/index.d.ts +1 -1
  218. package/dist/blocks/security-events/index.js +2 -3
  219. package/dist/blocks/segments/index.d.ts +1 -1
  220. package/dist/blocks/segments/index.js +4 -5
  221. package/dist/blocks/sequences/index.d.ts +1 -1
  222. package/dist/blocks/sequences/index.js +3 -4
  223. package/dist/blocks/service-accounts/index.d.ts +1 -1
  224. package/dist/blocks/service-accounts/index.js +3 -4
  225. package/dist/blocks/sessions/index.d.ts +2 -2
  226. package/dist/blocks/sessions/index.js +1 -1
  227. package/dist/blocks/settings/index.d.ts +2 -2
  228. package/dist/blocks/settings/index.js +3 -4
  229. package/dist/blocks/share-links/index.d.ts +1 -1
  230. package/dist/blocks/share-links/index.js +6 -6
  231. package/dist/blocks/shipments/index.d.ts +1 -1
  232. package/dist/blocks/shipments/index.js +9 -10
  233. package/dist/blocks/signatures/index.d.ts +1 -1
  234. package/dist/blocks/signatures/index.js +3 -4
  235. package/dist/blocks/signing-keys/index.d.ts +1 -1
  236. package/dist/blocks/signing-keys/index.js +2 -2
  237. package/dist/blocks/sla/index.d.ts +1 -1
  238. package/dist/blocks/sla/index.js +7 -8
  239. package/dist/blocks/sso/index.d.ts +1 -1
  240. package/dist/blocks/sso/index.js +2 -3
  241. package/dist/blocks/state-machine/index.d.ts +1 -1
  242. package/dist/blocks/state-machine/index.js +3 -3
  243. package/dist/blocks/subjects/index.d.ts +2 -2
  244. package/dist/blocks/subjects/index.js +3 -4
  245. package/dist/blocks/tags/index.d.ts +2 -2
  246. package/dist/blocks/tags/index.js +6 -6
  247. package/dist/blocks/tasks/index.d.ts +2 -2
  248. package/dist/blocks/tasks/index.js +7 -8
  249. package/dist/blocks/teams/index.d.ts +1 -1
  250. package/dist/blocks/teams/index.js +3 -3
  251. package/dist/blocks/templates/index.d.ts +3 -3
  252. package/dist/blocks/templates/index.js +3 -4
  253. package/dist/blocks/time-tracking/index.d.ts +8 -1
  254. package/dist/blocks/time-tracking/index.js +9 -10
  255. package/dist/blocks/timeline/index.d.ts +3 -3
  256. package/dist/blocks/timeline/index.js +4 -5
  257. package/dist/blocks/trash/index.d.ts +1 -1
  258. package/dist/blocks/trash/index.js +3 -4
  259. package/dist/blocks/undo/index.d.ts +2 -2
  260. package/dist/blocks/undo/index.js +2 -2
  261. package/dist/blocks/updated-at/index.d.ts +1 -1
  262. package/dist/blocks/usage/index.d.ts +2 -2
  263. package/dist/blocks/usage/index.js +2 -3
  264. package/dist/blocks/vercel-marketplace/index.d.ts +1 -1
  265. package/dist/blocks/vercel-marketplace/index.js +3 -4
  266. package/dist/blocks/versions/index.d.ts +1 -1
  267. package/dist/blocks/versions/index.js +6 -7
  268. package/dist/blocks/waitlist/index.d.ts +1 -1
  269. package/dist/blocks/waitlist/index.js +4 -5
  270. package/dist/blocks/webhooks/index.d.ts +3 -3
  271. package/dist/blocks/webhooks/index.js +13 -14
  272. package/dist/blocks/workflow-editor/index.d.ts +6 -6
  273. package/dist/blocks/workflow-editor/index.js +10 -11
  274. package/dist/blocks/workflows/index.d.ts +4 -4
  275. package/dist/blocks/workflows/index.js +5 -6
  276. package/dist/{bookings-Dox2rced.d.ts → bookings-BpCNphYp.d.ts} +1 -2
  277. package/dist/{build-D9lWi5bk.js → build-CH2N3Yf0.js} +4 -4
  278. package/dist/{build-BFC8nFiL.js → build-DbIRFcHQ.js} +3 -65
  279. package/dist/chat-sdk/index.js +2 -3
  280. package/dist/cli/{add-CH7dC6UR.js → add-B6CQOt3A.js} +2 -2
  281. package/dist/cli/{add-CtLjnwds.js → add-BXFzr0Wf.js} +9 -9
  282. package/dist/cli/add-w_HumDPX.js +1 -0
  283. package/dist/cli/{backfill-DBJIMzcy.js → backfill-Dflp6JZk.js} +1 -1
  284. package/dist/cli/bin.js +1 -1
  285. package/dist/cli/{blocks-i1w0EEvs.js → blocks-CBH3N7Fy.js} +1 -1
  286. package/dist/cli/{blocks-CS58-xnw.js → blocks-FtOIcUbu.js} +1 -1
  287. package/dist/cli/{cache-Cn3crN0v.js → cache-61VwYKEv.js} +1 -1
  288. package/dist/cli/{codemod-D6wifOAH.js → codemod-CqPRa25J.js} +1 -1
  289. package/dist/cli/{content-mapper-Q9We297z.js → content-mapper-DGQQY5IA.js} +2 -2
  290. package/dist/cli/{doctor-DmfdE5Ct.js → doctor-BxxSO193.js} +62 -58
  291. package/dist/cli/{gen-D68A0uN8.js → gen-D2cqqqTH.js} +11 -11
  292. package/dist/cli/index.d.ts +1 -1
  293. package/dist/cli/index.js +6 -6
  294. package/dist/cli/{init-N7pkBbJn.js → init-BnG1IE1y.js} +5 -5
  295. package/dist/cli/{live-0xAAlTK_.js → live-D26OWOAb.js} +2 -2
  296. package/dist/cli/{mcp-CbN3ulRF.js → mcp-1l3C_GdB.js} +2 -2
  297. package/dist/cli/{metadata-417ldpf4.js → metadata-DDfPBHwI.js} +3 -3
  298. package/dist/cli/{migration-safety-BC_UI4jC.js → migration-safety-CQbrfZIx.js} +1 -1
  299. package/dist/cli/{migrations-DdBKwrvG.js → migrations-Ch5Uuvyj.js} +1 -1
  300. package/dist/cli/{module-migration-DdxPdqMC.js → module-migration-Dul1uTYX.js} +2 -2
  301. package/dist/cli/{powersync-CJTEz-uY.js → powersync-CfT-tRx1.js} +2 -2
  302. package/dist/cli/powersync-Vmhw5c1N.js +1 -0
  303. package/dist/cli/{print-DyFm91R-.js → print-CbPT4PTL.js} +2 -2
  304. package/dist/cli/{remove-CPY0xsVm.js → remove-kDH1yxKZ.js} +5 -5
  305. package/dist/cli/{render-DE3O1OFq.js → render-0Vd7BaNA.js} +22 -5
  306. package/dist/cli/{run-WtIEFGvP.js → run-Dafms0D2.js} +8 -8
  307. package/dist/cli/{run-CcrNGX9C.js → run-DxTd55Ug.js} +21 -21
  308. package/dist/cli/{shared-SlukBuKn.js → shared-BQAMXvwd.js} +1 -1
  309. package/dist/cli/{snapshot-pyIsJjUV.js → snapshot-B8K6gYjA.js} +2 -2
  310. package/dist/cli/{source-Bclt9D0Y.js → source-CXDyCWz5.js} +1 -1
  311. package/dist/cli/{spec-D7zsEVj_.js → spec-BGsnTkIl.js} +2 -2
  312. package/dist/cli/{spec-BsdLx7tZ.js → spec-CaN7nOqI.js} +1 -1
  313. package/dist/cli/{sql-layout-C6baAM5t.js → sql-layout-BGAlcp1U.js} +2 -2
  314. package/dist/cli/{sync-Cse8VXAU.js → sync-CT_5VG0E.js} +3 -3
  315. package/dist/cli/{upgrade-28ENjIJU.js → upgrade-DA7aO88E.js} +2 -2
  316. package/dist/cli/{upgrade-Cwc1RiAE.js → upgrade-frUtPDDb.js} +4 -4
  317. package/dist/cli/{version-yWIaLG04.js → version-CUdPyV6J.js} +1 -1
  318. package/dist/client/index.d.ts +5 -5
  319. package/dist/client/index.js +1 -1
  320. package/dist/client/native/index.d.ts +4 -4
  321. package/dist/client/native/index.js +1 -1
  322. package/dist/{codecs-BfmQSbM6.js → codecs-CSUFGrdP.js} +3 -3
  323. package/dist/commerce/index.js +3 -3
  324. package/dist/{composite-D24L5RIY.js → composite-CBRbvn5j.js} +2 -2
  325. package/dist/{composite-DbRuu6Jb.d.ts → composite-ChzHhSB0.d.ts} +3 -3
  326. package/dist/config/index.d.ts +2 -2
  327. package/dist/config/index.js +5 -5
  328. package/dist/{config-CD2OGfCG.js → config-C9AOcQ9S.js} +1 -1
  329. package/dist/{config-D74JT0qL.js → config-CH-D2B-4.js} +4 -4
  330. package/dist/{context-CjHXhCck.d.ts → context-DEisra3V.d.ts} +19 -7
  331. package/dist/{controller-BeqcjERs.d.ts → controller-B6vWdKSa.d.ts} +1 -1
  332. package/dist/{controller-BNZKd6bJ.js → controller-qG-B1eDn.js} +1 -1
  333. package/dist/{conversion-BqDvi8ty.d.ts → conversion-DBgMck5U.d.ts} +1 -1
  334. package/dist/create/index.d.ts +72 -451
  335. package/dist/create/index.js +15 -1687
  336. package/dist/create/lite/index.d.ts +250 -13
  337. package/dist/create/lite/index.js +1007 -24
  338. package/dist/{create-blocks-0pWKQ6x4.js → create-blocks-BfrDUSM6.js} +14 -10
  339. package/dist/credentials/index.js +3 -4
  340. package/dist/{cron-CgHTKwYG.js → cron-DdT4ti8a.js} +1 -1
  341. package/dist/{cron-route-UU9i5i9J.js → cron-route-FjKgRvTY.js} +1 -1
  342. package/dist/{deal-forecast-DikouYGj.js → deal-forecast-CKBnRodz.js} +2 -2
  343. package/dist/{define-Djgn3HQQ.js → define-D-dLADd5.js} +16 -19
  344. package/dist/{define-BqaUwrIC.d.ts → define-Lf6rI2QN.d.ts} +14 -8
  345. package/dist/{define-block-CRwHsxZO.d.ts → define-block-DCAiOrNX.d.ts} +12 -3
  346. package/dist/edge/index.d.ts +5 -5
  347. package/dist/edge/index.js +7 -7
  348. package/dist/elysia/index.js +1 -1
  349. package/dist/{entitlements-mDz7GfA_.d.ts → entitlements-BPaPd3MD.d.ts} +1 -1
  350. package/dist/{entitlements-DBir2qwB.js → entitlements-tGL6-69B.js} +2 -2
  351. package/dist/{entity-schema-BDv6w-OQ.js → entity-schema-B1YmMtP8.js} +1 -1
  352. package/dist/events/index.js +3 -3
  353. package/dist/{executor-3qcMhg6R.js → executor-C2Ne-Scm.js} +3 -2
  354. package/dist/{executor-Bi056Cnj.d.ts → executor-DNK401lZ.d.ts} +1 -1
  355. package/dist/{executor-D3gB-9si.js → executor-DqIci3Jb.js} +3 -3
  356. package/dist/{executor-BQ7dYw4E.js → executor-WolvKszH.js} +3 -3
  357. package/dist/{executor-_O-CqCPl.d.ts → executor-aFV7nEBs.d.ts} +2 -2
  358. package/dist/expo/index.d.ts +2 -2
  359. package/dist/expo/index.js +3 -3
  360. package/dist/{field-errors-Cfvcg-C3.d.ts → field-errors-DBgDCITw.d.ts} +6 -6
  361. package/dist/{fields--5a88KJe.js → fields-BBm49w-E.js} +1 -1
  362. package/dist/{filter-evaluate-w1XOIUOL.js → filter-evaluate-lCToXzZI.js} +2 -2
  363. package/dist/{filter-query-DMoKo82_.js → filter-query-CQ6d5GnQ.js} +1 -1
  364. package/dist/{flags-ClOQY-p5.js → flags-DF_SCqp5.js} +1 -1
  365. package/dist/flags-sdk/index.js +2 -2
  366. package/dist/{framework-B-1Ka0GW.d.ts → framework-DKA3fTHl.d.ts} +3 -3
  367. package/dist/{framework-CNhTg0th.js → framework-DYEUraqt.js} +1 -1
  368. package/dist/h3/index.js +1 -1
  369. package/dist/h3/v1/index.js +1 -1
  370. package/dist/hono/index.d.ts +4 -4
  371. package/dist/hono/index.js +6 -6
  372. package/dist/{index-CjnDGAJr.d.ts → index-3p_oWttZ.d.ts} +77 -2
  373. package/dist/{index-BzW1T3oI.d.ts → index-ByF22_C6.d.ts} +3 -3
  374. package/dist/{index-BdzfjFnd.d.ts → index-C4sjewrr.d.ts} +9 -9
  375. package/dist/{index-CYzckGOz.d.ts → index-CM2aGNRo.d.ts} +9 -5
  376. package/dist/{index-DfgP-9eC.d.ts → index-CdMZQCYR.d.ts} +3 -3
  377. package/dist/{index-EieRHooI.d.ts → index-ClvuSZEz.d.ts} +2 -2
  378. package/dist/index.d.ts +2 -2
  379. package/dist/index.js +8 -7
  380. package/dist/{app-tables-DyswUg6J.js → instances-CK0jR3Pc.js} +147 -3
  381. package/dist/{json-schema-Ca6gYbEP.js → json-schema-DHJxiizN.js} +1 -1
  382. package/dist/{kit-DhlB-vv_.js → kit-Bcd9wYCV.js} +1 -1
  383. package/dist/{knowledge-CV6OSirC.js → knowledge-tCrrU99q.js} +2 -2
  384. package/dist/list/index.d.ts +1 -1
  385. package/dist/list/index.js +3 -3
  386. package/dist/{list-query-BKy2zBaT.js → list-query-BnpA2BDg.js} +1 -1
  387. package/dist/{list-query-6vTI1VN6.d.ts → list-query-XYfUZb0j.d.ts} +1 -1
  388. package/dist/mapper/bin.js +5 -5
  389. package/dist/mcp/index.d.ts +4 -4
  390. package/dist/mcp/index.js +7 -7
  391. package/dist/mcp/sdk/index.d.ts +2 -2
  392. package/dist/mcp/sdk/index.js +2 -2
  393. package/dist/{messages-D4XWuRTj.js → messages-ecPW_nOv.js} +1 -1
  394. package/dist/{model-messages-CKG0zwdF.js → model-messages-CkZSDDHP.js} +1 -1
  395. package/dist/{money-codec-uV5WbT60.js → money-codec-BJuS2zEW.js} +1 -1
  396. package/dist/nestjs/index.js +1 -1
  397. package/dist/next/index.d.ts +14 -14
  398. package/dist/next/index.js +8 -8
  399. package/dist/node/index.js +1 -1
  400. package/dist/{operations-DbNAgo7E.d.ts → operations-DC3wU3Sy.d.ts} +1 -1
  401. package/dist/orpc/index.d.ts +4 -4
  402. package/dist/orpc/index.js +5 -5
  403. package/dist/otel/index.js +5 -5
  404. package/dist/{ports-DO3tgLTo.d.ts → ports-BbBJVyS0.d.ts} +1 -1
  405. package/dist/{ports-CaVRXjxq.js → ports-DvpNseap.js} +1 -1
  406. package/dist/postgres/index.js +5 -4
  407. package/dist/{postgrest-executor-BFW4oWte.js → postgrest-executor-B_Uezhrm.js} +7 -3
  408. package/dist/powersync/index.d.ts +3 -3
  409. package/dist/powersync/index.js +1 -1
  410. package/dist/preset/index.d.ts +4 -4
  411. package/dist/preset/index.js +4 -4
  412. package/dist/{preset-B3CukUhu.js → preset-CS490mYJ.js} +179 -7
  413. package/dist/project-NmP1NdLi.js +1760 -0
  414. package/dist/{push-token-IFGi8jvd.d.ts → push-token-CPJfPFa2.d.ts} +1 -1
  415. package/dist/query/index.d.ts +1 -1
  416. package/dist/query/index.js +1 -1
  417. package/dist/{rate-limit-BPuUWz4U.js → rate-limit-fZ_d8gSE.js} +4 -5
  418. package/dist/react/index.d.ts +5 -5
  419. package/dist/react/index.js +2 -2
  420. package/dist/react/native/index.d.ts +1 -1
  421. package/dist/react/server.d.ts +6 -6
  422. package/dist/react/server.js +2 -2
  423. package/dist/{react-D-p70_wL.js → react-CcrQQl0_.js} +4 -4
  424. package/dist/react-router/index.d.ts +3 -3
  425. package/dist/react-router/index.js +5 -5
  426. package/dist/{read-set-BnKnofIj.js → read-set-B1sDib5O.js} +1 -1
  427. package/dist/realtime/index.d.ts +3 -3
  428. package/dist/realtime/index.js +2 -2
  429. package/dist/{record-bindings-DkBJpC5A.js → record-bindings-Z51mGfhB.js} +1 -1
  430. package/dist/{record-form-yMVvkPiQ.d.ts → record-form-BbZpwsEi.d.ts} +1 -1
  431. package/dist/records/index.d.ts +7 -7
  432. package/dist/records/index.js +3 -3
  433. package/dist/{refusal-D48CMqpQ.js → refusal-DDlInPff.js} +2 -2
  434. package/dist/{instances-DDt7NdVl.js → resolved-names-DdlJzoMK.js} +2 -146
  435. package/dist/{resource-R3KToNze.js → resource-BUJcZKiW.js} +2 -2
  436. package/dist/{resource-execute-LR71zWej.d.ts → resource-execute-CUG6xUuh.d.ts} +1 -1
  437. package/dist/{resource-types-eXuFxVt7.d.ts → resource-types-DjZ91WKA.d.ts} +1 -1
  438. package/dist/{resources-Dpz3h8Fe.d.ts → resources-6Ncdt9XT.d.ts} +1 -1
  439. package/dist/{resources-DqIwoQsP.js → resources-jb3R6rEa.js} +1 -1
  440. package/dist/{rows-EGAbu7MG.js → rows-BdqXmiB-.js} +2 -2
  441. package/dist/{rows-Bh9QemqN.js → rows-jijHLVE_.js} +1 -1
  442. package/dist/{rrule-79K2c3Nr.js → rrule-C9Ot6ax8.js} +1 -1
  443. package/dist/{sales-lines-CP4Z_LyE.js → sales-lines-DO7oRu1o.js} +3 -3
  444. package/dist/{sales-shared-BKXXA5qV.js → sales-shared-BuTA8JK7.js} +2 -2
  445. package/dist/{schemas-BSTNfGsQ.js → schemas-CLOTvdsC.js} +1 -1
  446. package/dist/{scores-CsgM-dw7.js → scores-bY2Is0kx.js} +2 -2
  447. package/dist/server/index.d.ts +7 -7
  448. package/dist/server/index.js +9 -9
  449. package/dist/{server-types-BTBzrzOH.d.ts → server-types-BH6AjDBN.d.ts} +1 -1
  450. package/dist/{session-BgYGk_FS.d.ts → session-Y5SSYO2C.d.ts} +1 -1
  451. package/dist/{shared-C47zAh2A.js → shared-BeHTi8Fu.js} +1 -1
  452. package/dist/{sign-in-BTaRWS-L.js → sign-in-NO7LWlw4.js} +5 -5
  453. package/dist/{signatures-CNcoq392.js → signatures-CX1b4WHa.js} +2 -2
  454. package/dist/{signers-BAEzvTJ0.d.ts → signers-BKgmVh6A.d.ts} +2 -2
  455. package/dist/{signing-keys-DqI-gB_C.js → signing-keys-CWtpMask.js} +3 -3
  456. package/dist/solid/index.d.ts +6 -6
  457. package/dist/solid/index.js +1 -1
  458. package/dist/solid-start/index.d.ts +3 -3
  459. package/dist/solid-start/index.js +5 -5
  460. package/dist/spec/index.d.ts +2 -2
  461. package/dist/spec/index.js +2 -693
  462. package/dist/{spec-DTWkHzYZ.js → spec-BMvCCNnd.js} +1 -1
  463. package/dist/sql/index.d.ts +4 -4
  464. package/dist/sql/index.js +2 -2
  465. package/dist/{sql-B0wb7XA5.js → sql-BMXEHTvr.js} +9685 -6254
  466. package/dist/{sql-BPbbPzRJ.js → sql-CYt7EhH0.js} +2 -2
  467. package/dist/sqlite/index.d.ts +1 -1
  468. package/dist/sqlite/index.js +1 -1
  469. package/dist/{sso-Co2TbnEy.js → sso-DdDpJQzw.js} +2 -2
  470. package/dist/ssr/index.d.ts +1 -1
  471. package/dist/storage/index.js +3 -3
  472. package/dist/streams/index.js +1 -2
  473. package/dist/{subject-readers-F1xvRY-d.js → subject-readers-CeeJJOQ4.js} +1 -1
  474. package/dist/svelte/index.d.ts +6 -6
  475. package/dist/svelte/index.js +1 -1
  476. package/dist/sveltekit/index.d.ts +4 -4
  477. package/dist/sveltekit/index.js +5 -5
  478. package/dist/{table-schema-CD8cJz_M.js → table-schema-C80xItaV.js} +1 -1
  479. package/dist/{tags-CXeJu332.d.ts → tags-Cjtcp5cN.d.ts} +1 -1
  480. package/dist/tanstack-db/index.d.ts +1 -1
  481. package/dist/tanstack-start/index.d.ts +3 -3
  482. package/dist/tanstack-start/index.js +5 -5
  483. package/dist/{temporal-DLZlWbOi.js → temporal-Dbo0fLzc.js} +12 -2
  484. package/dist/{temporal-required-Dy0GGD8E.js → temporal-required-DcLhnDhQ.js} +1 -1
  485. package/dist/{tenant-DzymQ9sv.d.ts → tenant-BHvMFNXl.d.ts} +1 -1
  486. package/dist/testing/index.d.ts +10 -10
  487. package/dist/testing/index.js +10 -10
  488. package/dist/{timeline-BMVOKokJ.d.ts → timeline-CEzj9v1z.d.ts} +3 -3
  489. package/dist/{topic-0uK4db_2.d.ts → topic-gTVjLGTk.d.ts} +2 -2
  490. package/dist/types-BC1HLEVx.d.ts +461 -0
  491. package/dist/{types-DsRfiQ0v.d.ts → types-yj8VF4oY.d.ts} +5 -0
  492. package/dist/{undo-B3FQvuAd.js → undo-BbftL9-4.js} +2 -2
  493. package/dist/vercel-connect/index.js +1 -1
  494. package/dist/{verify-ZLFUdlqE.js → verify-7EucfCnv.js} +3 -3
  495. package/dist/{verify-DexkIx4t.d.ts → verify-B0KLBb3j.d.ts} +1 -1
  496. package/dist/vue/index.d.ts +6 -6
  497. package/dist/vue/index.js +1 -1
  498. package/dist/{watch-topic-CG3kOX-D.d.ts → watch-topic-C6HhbnVz.d.ts} +1 -1
  499. package/dist/wire-ChYn1g21.js +91 -0
  500. package/dist/workflow-sdk/builder/index.d.ts +2 -2
  501. package/dist/workflow-sdk/builder/index.js +1 -1
  502. package/dist/workflow-sdk/world/index.js +1 -1
  503. package/dist/yjs/index.d.ts +1 -1
  504. package/dist/yjs/index.js +1 -1
  505. package/package.json +1 -1
  506. package/skills/better-supabase/references/ui-recipes.md +1 -1
  507. package/dist/block-transport-PNea4lfQ.js +0 -84
  508. package/dist/cli/add-DyCrVejx.js +0 -1
  509. package/dist/cli/powersync-CYQ4Ljcz.js +0 -1
  510. package/dist/types-DGHfTW8_.d.ts +0 -9
  511. package/dist/{data-hooks-tgF1Ct0F.js → data-hooks-CdcZfVS1.js} +1 -1
  512. package/dist/{respond-3RKp6VgU.js → respond-CZMWbUs3.js} +1 -1
  513. package/dist/{topic-DXbA-jwr.js → topic-DClSoqY7.js} +2 -2
@@ -1,4 +1,47 @@
1
+ import { y as appDefaultError } from "../../instances-CK0jR3Pc.js";
2
+ import { n as loadProject } from "../../project-NmP1NdLi.js";
1
3
  import { n as loadLite, t as LITE_INSTALL } from "../../runtime-CoKxZibd.js";
4
+ import { t as defineApi } from "../../api-3C0AWFeP.js";
5
+ //#region src/create/lite/apply.ts
6
+ const MISSING_EXTENSION = /extension "([^"]+)" is not available/u;
7
+ function messageOf$1(error) {
8
+ return (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, " ").slice(0, 300);
9
+ }
10
+ /**
11
+ * Runs each file in order. A module that needs an extension PGlite doesn't ship
12
+ * is skipped, with its other files. pgTAP test files are left out.
13
+ */
14
+ async function applyFiles(driver, files) {
15
+ const issues = [];
16
+ const skipped = /* @__PURE__ */ new Map();
17
+ for (const file of files) {
18
+ if (file.path.includes("/tests/") || skipped.has(file.module)) continue;
19
+ try {
20
+ await driver.exec(file.contents);
21
+ } catch (error) {
22
+ const message = messageOf$1(error);
23
+ const extension = MISSING_EXTENSION.exec(message)?.[1];
24
+ if (extension === void 0) issues.push({
25
+ code: "sql_error",
26
+ severity: "error",
27
+ source: "sql",
28
+ path: "",
29
+ table: file.module,
30
+ file: file.path,
31
+ message
32
+ });
33
+ else skipped.set(file.module, `Needs the ${extension} extension, which PGlite doesn't ship.`);
34
+ }
35
+ }
36
+ return {
37
+ issues,
38
+ skipped: [...skipped].map(([module, reason]) => ({
39
+ module,
40
+ reason
41
+ }))
42
+ };
43
+ }
44
+ //#endregion
2
45
  //#region src/create/lite/prelude.ts
3
46
  /**
4
47
  * What a Supabase project already has before the first migration runs: the API
@@ -71,11 +114,963 @@ create table if not exists storage.objects (
71
114
  );
72
115
  `;
73
116
  //#endregion
74
- //#region src/create/lite/index.ts
75
- const MISSING_EXTENSION = /extension "([^"]+)" is not available/u;
117
+ //#region src/create/lite/catalog.ts
118
+ function schemaList(schemas) {
119
+ return schemas.map((name) => `'${name.replaceAll("'", "''")}'`).join(", ");
120
+ }
121
+ /**
122
+ * One query that returns the whole catalog as JSON, so it runs through the
123
+ * Management API's read-only endpoint in a single call.
124
+ */
125
+ function catalogQuery(schemas = ["public"]) {
126
+ const list = schemaList(schemas);
127
+ return `select json_build_object(
128
+ 'tables', (
129
+ select coalesce(json_agg(t order by t.schema, t.name), '[]'::json) from (
130
+ select n.nspname as schema, c.relname as name, c.relkind::text as kind,
131
+ c.relrowsecurity as rls,
132
+ obj_description(c.oid, 'pg_class') as comment,
133
+ (select coalesce(json_agg(json_build_object(
134
+ 'name', a.attname,
135
+ 'type', format_type(a.atttypid, a.atttypmod),
136
+ 'nullable', not a.attnotnull,
137
+ 'default', pg_get_expr(d.adbin, d.adrelid),
138
+ 'identity', nullif(a.attidentity::text, ''),
139
+ 'generated', a.attgenerated::text <> '',
140
+ 'comment', col_description(c.oid, a.attnum),
141
+ 'udt', coalesce(el.typname, ty.typname),
142
+ 'array', ty.typcategory = 'A',
143
+ 'enumValues', (select coalesce(json_agg(e.enumlabel order by e.enumsortorder), '[]'::json)
144
+ from pg_enum e where e.enumtypid = coalesce(el.oid, ty.oid))
145
+ ) order by a.attnum), '[]'::json)
146
+ from pg_attribute a
147
+ join pg_type ty on ty.oid = a.atttypid
148
+ left join pg_type el on el.oid = ty.typelem and ty.typcategory = 'A'
149
+ left join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum
150
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as columns,
151
+ (select coalesce(json_agg(json_build_object(
152
+ 'name', k.conname,
153
+ 'type', k.contype::text,
154
+ 'columns', (select json_agg(a.attname order by u.ord)
155
+ from unnest(k.conkey) with ordinality as u(attnum, ord)
156
+ join pg_attribute a on a.attrelid = k.conrelid and a.attnum = u.attnum),
157
+ 'refSchema', fn.nspname,
158
+ 'refTable', fc.relname,
159
+ 'refColumns', (select json_agg(a.attname order by u.ord)
160
+ from unnest(k.confkey) with ordinality as u(attnum, ord)
161
+ join pg_attribute a on a.attrelid = k.confrelid and a.attnum = u.attnum),
162
+ 'onDelete', k.confdeltype::text
163
+ )), '[]'::json)
164
+ from pg_constraint k
165
+ left join pg_class fc on fc.oid = k.confrelid
166
+ left join pg_namespace fn on fn.oid = fc.relnamespace
167
+ where k.conrelid = c.oid and k.contype in ('p', 'u', 'f')) as constraints,
168
+ (select coalesce(json_agg(json_build_object(
169
+ 'columns', (select json_agg(a.attname order by u.ord)
170
+ from unnest(i.indkey::int2[]) with ordinality as u(attnum, ord)
171
+ join pg_attribute a on a.attrelid = i.indrelid and a.attnum = u.attnum),
172
+ 'plain', (not i.indisunique and not i.indisprimary
173
+ and i.indpred is null and i.indexprs is null
174
+ and am.amname = 'btree')
175
+ )), '[]'::json)
176
+ from pg_index i
177
+ join pg_class ic on ic.oid = i.indexrelid
178
+ join pg_am am on am.oid = ic.relam
179
+ where i.indrelid = c.oid and not i.indisprimary and not i.indisunique) as indexes,
180
+ (select count(*)::int from pg_policy p where p.polrelid = c.oid) as policies,
181
+ (select count(*)::int from pg_trigger g
182
+ where g.tgrelid = c.oid and not g.tgisinternal) as triggers
183
+ from pg_class c
184
+ join pg_namespace n on n.oid = c.relnamespace
185
+ where n.nspname in (${list}) and c.relkind in ('r', 'p', 'v', 'm')
186
+ ) t
187
+ ),
188
+ 'functions', (
189
+ select coalesce(json_agg(n.nspname || '.' || p.proname order by n.nspname, p.proname), '[]'::json)
190
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
191
+ where n.nspname in (${list}) and p.prokind in ('f', 'p')
192
+ )
193
+ ) as catalog`;
194
+ }
195
+ function isRecord(value) {
196
+ return typeof value === "object" && value !== null && !Array.isArray(value);
197
+ }
198
+ function str(value) {
199
+ return typeof value === "string" ? value : null;
200
+ }
201
+ function strings(value) {
202
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
203
+ }
204
+ function records(value) {
205
+ return Array.isArray(value) ? value.filter((item) => isRecord(item)) : [];
206
+ }
207
+ function readColumn(row) {
208
+ return {
209
+ name: str(row["name"]) ?? "",
210
+ type: str(row["type"]) ?? "",
211
+ nullable: row["nullable"] !== false,
212
+ default: str(row["default"]),
213
+ identity: str(row["identity"]),
214
+ generated: row["generated"] === true,
215
+ comment: str(row["comment"]),
216
+ udt: str(row["udt"]) ?? "",
217
+ array: row["array"] === true,
218
+ enumValues: strings(row["enumValues"])
219
+ };
220
+ }
221
+ function readConstraint(row) {
222
+ const type = str(row["type"]);
223
+ return {
224
+ name: str(row["name"]) ?? "",
225
+ type: type === "p" || type === "u" ? type : "f",
226
+ columns: strings(row["columns"]),
227
+ refSchema: str(row["refSchema"]),
228
+ refTable: str(row["refTable"]),
229
+ refColumns: Array.isArray(row["refColumns"]) ? strings(row["refColumns"]) : null,
230
+ onDelete: str(row["onDelete"])
231
+ };
232
+ }
233
+ function readTable(row) {
234
+ return {
235
+ schema: str(row["schema"]) ?? "public",
236
+ name: str(row["name"]) ?? "",
237
+ kind: str(row["kind"]) ?? "r",
238
+ rls: row["rls"] === true,
239
+ comment: str(row["comment"]),
240
+ columns: records(row["columns"]).map((each) => readColumn(each)),
241
+ constraints: records(row["constraints"]).map((each) => readConstraint(each)),
242
+ indexes: records(row["indexes"]).map((each) => ({
243
+ columns: strings(each["columns"]),
244
+ plain: each["plain"] === true
245
+ })),
246
+ policies: typeof row["policies"] === "number" ? row["policies"] : 0,
247
+ triggers: typeof row["triggers"] === "number" ? row["triggers"] : 0
248
+ };
249
+ }
250
+ /** Reads the one row `catalogQuery` returns; the JSON may arrive as text. */
251
+ function readCatalog(rows) {
252
+ const [row] = rows;
253
+ const cell = isRecord(row) ? row["catalog"] : void 0;
254
+ const catalog = typeof cell === "string" ? JSON.parse(cell) : cell;
255
+ if (!isRecord(catalog)) throw new TypeError("The catalog query returned an unexpected result.");
256
+ return {
257
+ tables: records(catalog["tables"]).map((each) => readTable(each)),
258
+ functions: strings(catalog["functions"])
259
+ };
260
+ }
261
+ //#endregion
262
+ //#region src/create/lite/import.ts
263
+ const BLOCK_PREFIX = "bsb_";
264
+ const SIMPLE_TYPES = [
265
+ [/^(?:text|character varying(?:\(\d+\))?|character(?:\(\d+\))?|citext)$/u, "text"],
266
+ [/^uuid$/u, "uuid"],
267
+ [/^(?:integer|smallint)$/u, "integer"],
268
+ [/^bigint$/u, "bigint"],
269
+ [/^numeric(?:\(\d+(?:,\d+)?\))?$/u, "numeric"],
270
+ [/^boolean$/u, "boolean"],
271
+ [/^timestamp with time zone$/u, "timestamptz"],
272
+ [/^date$/u, "date"],
273
+ [/^(?:jsonb|json)$/u, "jsonb"],
274
+ [/^(?:text|character varying(?:\(\d+\))?)\[\]$/u, "text[]"]
275
+ ];
276
+ function columnType(type) {
277
+ return SIMPLE_TYPES.find(([pattern]) => pattern.test(type))?.[1];
278
+ }
279
+ /** `'x'::text` and `(0)::bigint` print as `'x'` and `0`. */
280
+ function plainDefault(value) {
281
+ return value.replace(/^\((.*)\)(?:::[\w\s."[\]]+)$/u, "$1").replace(/^('(?:[^']|'')*')(?:::[\w\s."[\]]+)$/u, "$1");
282
+ }
283
+ function onDelete(code) {
284
+ switch (code ?? "a") {
285
+ case "r": return "restrict";
286
+ case "c": return "cascade";
287
+ case "n": return "set null";
288
+ default: return "no action";
289
+ }
290
+ }
291
+ function rungOf(table) {
292
+ if (!table.rls) return "open";
293
+ return table.policies === 0 ? "locked" : "protected";
294
+ }
295
+ const qualified = (table) => `${table.schema}.${table.name}`;
296
+ /** A table the design can model: `public`, a single `id` key, no generated id. */
297
+ function idOf(table) {
298
+ const keys = table.constraints.filter((each) => each.type === "p");
299
+ if (keys.length !== 1 || keys[0]?.columns.length !== 1) return;
300
+ if (keys[0].columns[0] !== "id") return;
301
+ const type = table.columns.find((each) => each.name === "id")?.type;
302
+ if (type === "uuid") return "uuid";
303
+ return type === "bigint" ? "bigint" : void 0;
304
+ }
305
+ function modelTable(table, modeled, preserved) {
306
+ const id = idOf(table);
307
+ if (id === void 0) return;
308
+ const names = new Set(table.columns.map((each) => each.name));
309
+ const timestamps = ["created_at", "updated_at"].every((name) => table.columns.find((each) => each.name === name)?.type === "timestamp with time zone");
310
+ const implicit = /* @__PURE__ */ new Set(["id", ...timestamps ? ["created_at", "updated_at"] : []]);
311
+ const unique = /* @__PURE__ */ new Set();
312
+ const uniqueSets = [];
313
+ const references = /* @__PURE__ */ new Map();
314
+ for (const constraint of table.constraints) {
315
+ if (constraint.type === "u") {
316
+ if (constraint.columns.length === 1 && constraint.columns[0] !== void 0) unique.add(constraint.columns[0]);
317
+ else uniqueSets.push([...constraint.columns]);
318
+ }
319
+ if (constraint.type !== "f") continue;
320
+ const [column] = constraint.columns;
321
+ const target = `${constraint.refSchema ?? ""}.${constraint.refTable ?? ""}`;
322
+ const onlyOne = constraint.columns.length === 1 && column !== void 0;
323
+ const toId = constraint.refColumns?.join(",") === "id";
324
+ if (onlyOne && toId && target === "auth.users") references.set(column, {
325
+ table: "auth.users",
326
+ onDelete: onDelete(constraint.onDelete)
327
+ });
328
+ else if (onlyOne && toId && constraint.refSchema === "public" && modeled.has(target)) references.set(column, {
329
+ table: constraint.refTable ?? "",
330
+ onDelete: onDelete(constraint.onDelete)
331
+ });
332
+ else preserved.push({
333
+ kind: "foreign_key",
334
+ name: `${qualified(table)}(${constraint.columns.join(", ")})`,
335
+ reason: `References ${target}, which a design can't express.`
336
+ });
337
+ }
338
+ const columns = {};
339
+ for (const column of table.columns) {
340
+ if (implicit.has(column.name)) continue;
341
+ const type = columnType(column.type);
342
+ if (type === void 0 || column.generated) {
343
+ preserved.push({
344
+ kind: "column",
345
+ name: `${qualified(table)}.${column.name}`,
346
+ reason: column.generated ? "A generated column is kept as it is." : `The type ${column.type} is kept as it is.`
347
+ });
348
+ continue;
349
+ }
350
+ const reference = references.get(column.name);
351
+ let fallback;
352
+ if (column.default !== null) {
353
+ const value = plainDefault(column.default);
354
+ if (appDefaultError({ type }, value) === void 0) fallback = value;
355
+ else preserved.push({
356
+ kind: "default",
357
+ name: `${qualified(table)}.${column.name}`,
358
+ reason: `The default ${column.default} is kept as it is.`
359
+ });
360
+ }
361
+ columns[column.name] = {
362
+ type,
363
+ ...column.nullable ? {} : { nullable: false },
364
+ ...fallback === void 0 ? {} : { default: fallback },
365
+ ...unique.has(column.name) ? { unique: true } : {},
366
+ ...reference === void 0 ? {} : { references: reference },
367
+ ...column.identity === null ? {} : { identity: true },
368
+ ...column.comment === null ? {} : { comment: column.comment }
369
+ };
370
+ }
371
+ const indexes = [];
372
+ for (const index of table.indexes) if (index.plain && index.columns.every((name) => names.has(name))) indexes.push([...index.columns]);
373
+ else preserved.push({
374
+ kind: "index",
375
+ name: `${qualified(table)}(${index.columns.join(", ")})`,
376
+ reason: "An expression, partial or non-btree index is kept as it is."
377
+ });
378
+ return {
379
+ columns,
380
+ scope: "none",
381
+ ...timestamps ? {} : { timestamps: false },
382
+ ...id === "bigint" ? { id } : {},
383
+ ...uniqueSets.length === 0 ? {} : { unique: uniqueSets },
384
+ ...indexes.length === 0 ? {} : { indexes },
385
+ ...table.comment === null ? {} : { comment: table.comment }
386
+ };
387
+ }
388
+ /** Turns a catalog into a design and the report the import shows. */
389
+ function designFromCatalog(catalog, issues = []) {
390
+ const preserved = [];
391
+ const verifier = [];
392
+ const blockOwned = [];
393
+ const imported = [];
394
+ const appTables = {};
395
+ const candidates = catalog.tables.filter((table) => {
396
+ if (table.kind === "v" || table.kind === "m") {
397
+ preserved.push({
398
+ kind: "view",
399
+ name: qualified(table),
400
+ reason: "A view is kept as it is."
401
+ });
402
+ return false;
403
+ }
404
+ if (table.name.startsWith(BLOCK_PREFIX)) {
405
+ blockOwned.push(qualified(table));
406
+ return false;
407
+ }
408
+ return true;
409
+ });
410
+ const modeled = new Set(candidates.filter((table) => table.schema === "public" && idOf(table) !== void 0).map((table) => qualified(table)));
411
+ for (const table of candidates) {
412
+ const model = modeled.has(qualified(table)) ? modelTable(table, modeled, preserved) : void 0;
413
+ if (model === void 0) preserved.push({
414
+ kind: "table",
415
+ name: qualified(table),
416
+ reason: table.schema === "public" ? "It has no single uuid or bigint id key, so it is kept as it is." : "Only the public schema is modeled."
417
+ });
418
+ else appTables[table.name] = model;
419
+ imported.push({
420
+ schema: table.schema,
421
+ name: table.name,
422
+ rung: rungOf(table),
423
+ modeled: model !== void 0,
424
+ columns: table.columns.length
425
+ });
426
+ if (!table.rls) verifier.push({
427
+ code: "verify_rls_disabled",
428
+ severity: "error",
429
+ source: "verifier",
430
+ path: "",
431
+ table: table.name,
432
+ message: `${qualified(table)} has row level security off, so the Data API exposes every row.`
433
+ });
434
+ else if (table.policies === 0) verifier.push({
435
+ code: "verify_no_policies",
436
+ severity: "info",
437
+ source: "verifier",
438
+ path: "",
439
+ table: table.name,
440
+ message: `${qualified(table)} has row level security on and no policies, so only the service role can read it.`
441
+ });
442
+ if (table.triggers > 0) preserved.push({
443
+ kind: "trigger",
444
+ name: qualified(table),
445
+ reason: `${String(table.triggers)} trigger(s) are kept as they are.`
446
+ });
447
+ if (table.policies > 0) preserved.push({
448
+ kind: "policy",
449
+ name: qualified(table),
450
+ reason: `${String(table.policies)} polic${table.policies === 1 ? "y is" : "ies are"} kept as ${table.policies === 1 ? "it is" : "they are"}.`
451
+ });
452
+ }
453
+ for (const name of catalog.functions) preserved.push({
454
+ kind: "function",
455
+ name,
456
+ reason: "A function is kept as it is."
457
+ });
458
+ return {
459
+ design: Object.keys(appTables).length === 0 ? {} : { appTables },
460
+ report: {
461
+ counts: {
462
+ tables: candidates.length,
463
+ modeledTables: Object.keys(appTables).length,
464
+ columns: candidates.reduce((sum, table) => sum + table.columns.length, 0),
465
+ views: catalog.tables.filter((table) => table.kind !== "r" && table.kind !== "p").length,
466
+ functions: catalog.functions.length,
467
+ triggers: catalog.tables.reduce((sum, table) => sum + table.triggers, 0),
468
+ policies: catalog.tables.reduce((sum, table) => sum + table.policies, 0)
469
+ },
470
+ tables: imported,
471
+ blockOwned,
472
+ preserved,
473
+ issues: [...issues, ...verifier]
474
+ }
475
+ };
476
+ }
76
477
  function messageOf(error) {
77
478
  return (error instanceof Error ? error.message : String(error)).replaceAll(/\s+/gu, " ").slice(0, 300);
78
479
  }
480
+ async function readFiles(files, schemas, runtime) {
481
+ const lite = runtime ?? await loadLite();
482
+ if (lite === void 0) throw new Error(LITE_INSTALL);
483
+ const connection = await lite.createPgliteConnection();
484
+ try {
485
+ const { driver } = connection;
486
+ const issues = [];
487
+ await driver.exec(SUPABASE_PRELUDE);
488
+ const ordered = files.toSorted((left, right) => left.path.localeCompare(right.path));
489
+ for (const file of ordered) try {
490
+ await driver.exec(file.contents);
491
+ } catch (error) {
492
+ issues.push({
493
+ code: "sql_error",
494
+ severity: "error",
495
+ source: "sql",
496
+ path: "",
497
+ table: file.path,
498
+ file: file.path,
499
+ message: messageOf(error)
500
+ });
501
+ }
502
+ const { rows } = await driver.query(catalogQuery(schemas));
503
+ return designFromCatalog(readCatalog(rows), issues);
504
+ } finally {
505
+ await connection.close();
506
+ }
507
+ }
508
+ async function readSupabase(source, schemas) {
509
+ const base = (source.apiUrl ?? "https://api.supabase.com").replace(/\/$/u, "");
510
+ const response = await (source.fetch ?? fetch)(`${base}/v1/projects/${encodeURIComponent(source.projectRef)}/database/query/read-only`, {
511
+ method: "POST",
512
+ headers: {
513
+ authorization: `Bearer ${source.accessToken}`,
514
+ "content-type": "application/json"
515
+ },
516
+ body: JSON.stringify({ query: catalogQuery(schemas) })
517
+ });
518
+ if (!response.ok) throw new Error(`Supabase answered ${String(response.status)} for project ${source.projectRef}.`);
519
+ const rows = await response.json();
520
+ if (!Array.isArray(rows)) throw new TypeError(`Supabase sent an unexpected body for project ${source.projectRef}.`);
521
+ return designFromCatalog(readCatalog(rows));
522
+ }
523
+ /**
524
+ * Reads an existing project into a `Design` and a report (ADR 0100). The design
525
+ * models the tables Create can express: `public` tables with a single `uuid` or
526
+ * `bigint` `id` key, their columns, references to other modeled tables or
527
+ * `auth.users`, unique keys and plain indexes. Everything else is listed under
528
+ * `report.preserved` and is never dropped: a deploy applies only what the
529
+ * design adds. Tables named `bsb_*` belong to blocks. The report also carries
530
+ * each table's adoption rung and the security findings (`source: "verifier"`).
531
+ *
532
+ * Throws when a `files` source needs `@supabase/lite` and it isn't installed,
533
+ * or when a `supabase` source answers with an error.
534
+ */
535
+ async function importProject(options) {
536
+ const schemas = options.schemas ?? ["public"];
537
+ const { source } = options;
538
+ switch (source.kind) {
539
+ case "files": return readFiles(source.files, schemas, options.runtime);
540
+ case "queryable": {
541
+ const { rows } = await source.queryable.query(catalogQuery(schemas));
542
+ return designFromCatalog(readCatalog(rows));
543
+ }
544
+ case "supabase": return readSupabase(source, schemas);
545
+ default: return source;
546
+ }
547
+ }
548
+ /** Files in the shape `previewFiles` returns, for callers that hold those. */
549
+ function importFilesOf(files) {
550
+ return files.filter((file) => !file.path.includes("/tests/")).map(({ path, contents }) => ({
551
+ path,
552
+ contents
553
+ }));
554
+ }
555
+ //#endregion
556
+ //#region src/create/lite/rest.ts
557
+ const FILTERS = {
558
+ eq: "=",
559
+ neq: "<>",
560
+ gt: ">",
561
+ gte: ">=",
562
+ lt: "<",
563
+ lte: "<=",
564
+ like: "like",
565
+ ilike: "ilike"
566
+ };
567
+ const RESERVED = /* @__PURE__ */ new Set([
568
+ "select",
569
+ "order",
570
+ "limit",
571
+ "offset",
572
+ "columns",
573
+ "on_conflict"
574
+ ]);
575
+ const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
576
+ const bad = (message, code = "PGRST100") => ({
577
+ status: 400,
578
+ code,
579
+ message
580
+ });
581
+ function json(status, body) {
582
+ return Response.json(body, { status });
583
+ }
584
+ function problem(error) {
585
+ return json(error.status, {
586
+ code: error.code,
587
+ message: error.message,
588
+ details: null,
589
+ hint: null
590
+ });
591
+ }
592
+ function decodeClaims(token) {
593
+ const [, payload] = token.split(".");
594
+ if (payload === void 0) return;
595
+ try {
596
+ const text = atob(payload.replaceAll("-", "+").replaceAll("_", "/"));
597
+ const parsed = JSON.parse(text);
598
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? Object.fromEntries(Object.entries(parsed)) : void 0;
599
+ } catch {
600
+ return;
601
+ }
602
+ }
603
+ /**
604
+ * The persona a request's bearer token names. The sandbox decodes the payload
605
+ * and does not verify the signature.
606
+ */
607
+ function personaOf(request) {
608
+ const header = request.headers.get("authorization") ?? "";
609
+ const token = header.startsWith("Bearer ") ? header.slice(7) : "";
610
+ const claims = token === "" ? void 0 : decodeClaims(token);
611
+ if (claims === void 0) return { role: "anon" };
612
+ const { sub, role, ...rest } = claims;
613
+ const known = role === "anon" || role === "authenticated" || role === "service_role" ? role : void 0;
614
+ return {
615
+ ...typeof sub === "string" ? { sub } : {},
616
+ ...known === void 0 ? {} : { role: known },
617
+ claims: rest
618
+ };
619
+ }
620
+ async function columnsOf(run, table) {
621
+ const result = await run({ role: "service_role" }, `select a.attname as name, t.typname as type, t.typcategory = 'A' as array
622
+ from pg_attribute a
623
+ join pg_class c on c.oid = a.attrelid
624
+ join pg_namespace n on n.oid = c.relnamespace
625
+ join pg_type t on t.oid = a.atttypid
626
+ where n.nspname = 'public' and c.relname = $1
627
+ and c.relkind in ('r', 'p', 'v', 'm')
628
+ and a.attnum > 0 and not a.attisdropped`, [table]);
629
+ if (!result.ok || result.rows.length === 0) return;
630
+ const columns = /* @__PURE__ */ new Map();
631
+ for (const row of result.rows) if (typeof row === "object" && row !== null && "name" in row && typeof row.name === "string" && "type" in row && typeof row.type === "string") columns.set(row.name, {
632
+ type: row.type,
633
+ array: "array" in row && row.array === true
634
+ });
635
+ return columns;
636
+ }
637
+ /** A value as the driver takes it for `column`. */
638
+ function bound(value, column) {
639
+ if (value === null || value === void 0) return null;
640
+ if (column?.array === true && Array.isArray(value)) return `{${value.map((item) => `"${String(item).replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`).join(",")}}`;
641
+ return typeof value === "object" ? JSON.stringify(value) : value;
642
+ }
643
+ var Builder = class {
644
+ params = [];
645
+ add(value) {
646
+ this.params.push(value);
647
+ return `$${String(this.params.length)}`;
648
+ }
649
+ };
650
+ function conditionOf(column, expression, columns, builder) {
651
+ if (columns.get(column) === void 0) return bad(`Could not find the column ${column}.`, "42703");
652
+ let negate = false;
653
+ let rest = expression;
654
+ if (rest.startsWith("not.")) {
655
+ negate = true;
656
+ rest = rest.slice(4);
657
+ }
658
+ const dot = rest.indexOf(".");
659
+ const op = dot === -1 ? rest : rest.slice(0, dot);
660
+ const value = dot === -1 ? "" : rest.slice(dot + 1);
661
+ const left = quote(column);
662
+ let sql;
663
+ if (op === "is") {
664
+ const keyword = value.toLowerCase();
665
+ if (![
666
+ "null",
667
+ "true",
668
+ "false",
669
+ "unknown"
670
+ ].includes(keyword)) return bad(`Unsupported value for is: ${value}.`);
671
+ sql = `${left} is ${keyword}`;
672
+ } else if (op === "in") {
673
+ const inner = /^\((.*)\)$/u.exec(value)?.[1];
674
+ if (inner === void 0) return bad("in expects a parenthesized list.");
675
+ sql = `${left} in (${inner.split(",").map((item) => item.trim().replace(/^"(.*)"$/u, "$1")).map((item) => builder.add(item)).join(", ")})`;
676
+ } else if (op in FILTERS) {
677
+ const operator = FILTERS[op] ?? "=";
678
+ const pattern = op === "like" || op === "ilike" ? value.replaceAll("*", "%") : value;
679
+ sql = `${left} ${operator} ${builder.add(pattern)}`;
680
+ } else return bad(`Unsupported operator ${op}.`);
681
+ return negate ? `not (${sql})` : sql;
682
+ }
683
+ function whereOf(url, columns, builder) {
684
+ const conditions = [];
685
+ for (const [key, expression] of url.searchParams) {
686
+ if (RESERVED.has(key)) continue;
687
+ if (key === "or" || key === "and" || key === "not") return bad(`${key} filters are not supported by the sandbox.`);
688
+ const condition = conditionOf(key, expression, columns, builder);
689
+ if (typeof condition !== "string") return condition;
690
+ conditions.push(condition);
691
+ }
692
+ return conditions.length === 0 ? "" : ` where ${conditions.join(" and ")}`;
693
+ }
694
+ function selectOf(url, columns) {
695
+ const select = url.searchParams.get("select");
696
+ if (select === null || select === "*") return "*";
697
+ if (select.includes("(")) return bad("Embedding is not supported by the sandbox.");
698
+ const names = select.split(",").map((name) => name.trim());
699
+ const missing = names.find((name) => !columns.has(name));
700
+ return missing === void 0 ? names.map((name) => quote(name)).join(", ") : bad(`Could not find the column ${missing}.`, "42703");
701
+ }
702
+ function tailOf(url, columns) {
703
+ let sql = "";
704
+ const order = url.searchParams.get("order");
705
+ if (order !== null) {
706
+ const parts = [];
707
+ for (const item of order.split(",")) {
708
+ const [name = "", ...flags] = item.split(".");
709
+ if (!columns.has(name)) return bad(`Could not find the column ${name}.`, "42703");
710
+ parts.push(`${quote(name)}${flags.includes("desc") ? " desc" : ""}${flags.includes("nullsfirst") ? " nulls first" : flags.includes("nullslast") ? " nulls last" : ""}`);
711
+ }
712
+ sql += ` order by ${parts.join(", ")}`;
713
+ }
714
+ for (const key of ["limit", "offset"]) {
715
+ const value = url.searchParams.get(key);
716
+ if (value !== null) {
717
+ if (!/^\d+$/u.test(value)) return bad(`${key} must be a number.`);
718
+ sql += ` ${key} ${value}`;
719
+ }
720
+ }
721
+ return sql;
722
+ }
723
+ function statusOf(code, persona) {
724
+ switch (code) {
725
+ case "42501": return persona.sub === void 0 && persona.role !== "service_role" ? 401 : 403;
726
+ case "23505":
727
+ case "23503":
728
+ case "23P01": return 409;
729
+ case "42P01":
730
+ case "42883": return 404;
731
+ default: return 400;
732
+ }
733
+ }
734
+ async function readBody(request) {
735
+ const text = await request.text();
736
+ return text === "" ? void 0 : JSON.parse(text);
737
+ }
738
+ function isRow(value) {
739
+ return typeof value === "object" && value !== null && !Array.isArray(value);
740
+ }
741
+ async function writeRows(request, table, columns, url, builder) {
742
+ let body;
743
+ try {
744
+ body = await readBody(request);
745
+ } catch {
746
+ return bad("The body is not valid JSON.", "PGRST102");
747
+ }
748
+ const returning = request.headers.get("prefer")?.includes("return=representation") ? " returning *" : "";
749
+ if (request.method === "POST") {
750
+ const rows = (Array.isArray(body) ? body : [body]).filter((row) => isRow(row));
751
+ if (rows.length === 0) return bad("The body must be a JSON object or an array of objects.", "PGRST102");
752
+ const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
753
+ const unknown = keys.find((key) => !columns.has(key));
754
+ if (unknown !== void 0) return bad(`Could not find the ${unknown} column of ${table}.`, "PGRST204");
755
+ if (keys.length === 0) return `insert into public.${quote(table)} default values${returning}`;
756
+ const values = rows.map((row) => `(${keys.map((key) => Object.hasOwn(row, key) ? builder.add(bound(row[key], columns.get(key))) : "default").join(", ")})`);
757
+ return `insert into public.${quote(table)} (${keys.map((key) => quote(key)).join(", ")}) values ${values.join(", ")}${returning}`;
758
+ }
759
+ if (!isRow(body)) return bad("The body must be a JSON object.", "PGRST102");
760
+ const keys = Object.keys(body);
761
+ const unknown = keys.find((key) => !columns.has(key));
762
+ if (unknown !== void 0) return bad(`Could not find the ${unknown} column of ${table}.`, "PGRST204");
763
+ if (keys.length === 0) return bad("There is nothing to update.", "PGRST102");
764
+ const sets = keys.map((key) => `${quote(key)} = ${builder.add(bound(body[key], columns.get(key)))}`);
765
+ const where = whereOf(url, columns, builder);
766
+ return typeof where === "string" ? `update public.${quote(table)} set ${sets.join(", ")}${where}${returning}` : where;
767
+ }
768
+ async function callFunction(request, name, persona, run) {
769
+ let body;
770
+ try {
771
+ body = await readBody(request);
772
+ } catch {
773
+ return problem(bad("The body is not valid JSON.", "PGRST102"));
774
+ }
775
+ const args = isRow(body) ? Object.entries(body) : [];
776
+ const builder = new Builder();
777
+ const list = args.map(([key, value]) => `${quote(key)} => ${builder.add(bound(value, void 0))}`).join(", ");
778
+ const result = await run(persona, `select * from public.${quote(name)}(${list})`, builder.params);
779
+ if (!result.ok) return problem({
780
+ status: statusOf(result.error.code, persona),
781
+ code: result.error.code,
782
+ message: result.error.message
783
+ });
784
+ const [first] = result.rows;
785
+ if (result.rows.length === 1 && isRow(first) && Object.keys(first).length === 1 && Object.hasOwn(first, name)) return json(200, first[name]);
786
+ return json(200, result.rows);
787
+ }
788
+ /**
789
+ * A subset of PostgREST: `GET`, `POST`, `PATCH` and `DELETE` on
790
+ * `/rest/v1/<table>` and `POST` on `/rest/v1/rpc/<function>`. With no `fixed`
791
+ * persona the bearer token names one.
792
+ */
793
+ async function handleRest(request, run, fixed) {
794
+ const persona = fixed ?? personaOf(request);
795
+ const url = new URL(request.url);
796
+ const [name = "", extra] = url.pathname.replace(/^\/rest\/v1\/?/u, "").replace(/^\//u, "").split("/");
797
+ const isRpc = name === "rpc";
798
+ const target = isRpc ? extra ?? "" : name;
799
+ if (target === "" || !/^[\w$]+$/u.test(target)) return problem({
800
+ status: 404,
801
+ code: "PGRST125",
802
+ message: `Invalid path specified in request URL: ${url.pathname}`
803
+ });
804
+ if (isRpc) return request.method === "POST" ? callFunction(request, target, persona, run) : problem({
805
+ status: 405,
806
+ code: "PGRST101",
807
+ message: "Functions take POST."
808
+ });
809
+ const columns = await columnsOf(run, target);
810
+ if (columns === void 0) return problem({
811
+ status: 404,
812
+ code: "PGRST205",
813
+ message: `Could not find the table public.${target} in the schema cache`
814
+ });
815
+ const builder = new Builder();
816
+ let sql;
817
+ switch (request.method) {
818
+ case "GET":
819
+ case "HEAD": {
820
+ const select = selectOf(url, columns);
821
+ const where = whereOf(url, columns, builder);
822
+ const tail = tailOf(url, columns);
823
+ sql = [
824
+ select,
825
+ where,
826
+ tail
827
+ ].find((part) => typeof part !== "string") ?? `select ${String(select)} from public.${quote(target)}${String(where)}${String(tail)}`;
828
+ break;
829
+ }
830
+ case "POST":
831
+ case "PATCH":
832
+ sql = await writeRows(request, target, columns, url, builder);
833
+ break;
834
+ case "DELETE": {
835
+ const where = whereOf(url, columns, builder);
836
+ const returning = request.headers.get("prefer")?.includes("return=representation") ? " returning *" : "";
837
+ sql = typeof where === "string" ? `delete from public.${quote(target)}${where}${returning}` : where;
838
+ break;
839
+ }
840
+ default: return problem({
841
+ status: 405,
842
+ code: "PGRST101",
843
+ message: `Unsupported HTTP method: ${request.method}`
844
+ });
845
+ }
846
+ if (typeof sql !== "string") return problem(sql);
847
+ const result = await run(persona, sql, builder.params);
848
+ if (!result.ok) return problem({
849
+ status: statusOf(result.error.code, persona),
850
+ code: result.error.code,
851
+ message: result.error.message
852
+ });
853
+ if (!(request.method === "GET" || request.method === "HEAD" || request.headers.get("prefer")?.includes("return=representation") === true)) return new Response(null, { status: request.method === "POST" ? 201 : 204 });
854
+ const status = request.method === "POST" ? 201 : 200;
855
+ if (request.headers.get("accept")?.includes("application/vnd.pgrst.object+json") === true) {
856
+ if (result.rows.length !== 1) return problem({
857
+ status: 406,
858
+ code: "PGRST116",
859
+ message: "JSON object requested, multiple (or no) rows returned"
860
+ });
861
+ return json(status, result.rows[0]);
862
+ }
863
+ return request.method === "HEAD" ? new Response(null, { status }) : json(status, result.rows);
864
+ }
865
+ //#endregion
866
+ //#region src/create/lite/sandbox.ts
867
+ /** What Supabase grants the API roles on `public` by default. */
868
+ const API_GRANTS = `
869
+ grant usage on schema public to anon, authenticated, service_role;
870
+ alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
871
+ alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;
872
+ alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
873
+ `;
874
+ const ROLES = /* @__PURE__ */ new Set([
875
+ "anon",
876
+ "authenticated",
877
+ "service_role"
878
+ ]);
879
+ function roleOf(persona) {
880
+ return persona.role ?? (persona.sub === void 0 ? "anon" : "authenticated");
881
+ }
882
+ function claimsOf(persona) {
883
+ return {
884
+ ...persona.claims,
885
+ role: roleOf(persona),
886
+ ...persona.sub === void 0 ? {} : { sub: persona.sub }
887
+ };
888
+ }
889
+ function errorOf(error) {
890
+ return {
891
+ code: typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "XX000",
892
+ message: messageOf$1(error)
893
+ };
894
+ }
895
+ /** Rows, as a plain array, from whatever PGlite returned. */
896
+ function rowsOf(result) {
897
+ return result.rows;
898
+ }
899
+ var Queue = class {
900
+ tail = Promise.resolve();
901
+ run(task) {
902
+ const next = this.tail.then(task);
903
+ this.tail = next.catch(() => void 0);
904
+ return next;
905
+ }
906
+ };
907
+ async function asPersona(driver, queue, persona, sql, params) {
908
+ return queue.run(async () => {
909
+ const role = roleOf(persona);
910
+ if (!ROLES.has(role)) return {
911
+ ok: false,
912
+ error: {
913
+ code: "22023",
914
+ message: `Unknown role ${role}.`
915
+ }
916
+ };
917
+ await driver.exec("begin");
918
+ try {
919
+ await driver.query(`select set_config('role', $1, true),
920
+ set_config('request.jwt.claims', $2, true),
921
+ set_config('request.jwt.claim.sub', $3, true),
922
+ set_config('request.jwt.claim.role', $1, true)`, [
923
+ role,
924
+ JSON.stringify(claimsOf(persona)),
925
+ persona.sub ?? ""
926
+ ]);
927
+ const rows = rowsOf(await driver.query(sql, params));
928
+ await driver.exec("commit");
929
+ return {
930
+ ok: true,
931
+ rows
932
+ };
933
+ } catch (error) {
934
+ await driver.exec("rollback").catch(() => void 0);
935
+ return {
936
+ ok: false,
937
+ error: errorOf(error)
938
+ };
939
+ }
940
+ });
941
+ }
942
+ /**
943
+ * Opens an in-memory PGlite database with a project's files applied, the
944
+ * Supabase roles in place and the API roles granted what Supabase grants them
945
+ * by default. Queries run as the database owner, or as a persona through `as({
946
+ * sub, role, claims })` with row level security applied, and `rest` answers a
947
+ * subset of PostgREST: table reads and writes with `select`, filters, `order`,
948
+ * `limit` and `offset`, and `rpc` calls. Embedding, `or`, `and` and range
949
+ * headers are not supported. Throws when `@supabase/lite` isn't installed.
950
+ */
951
+ async function openSandbox(project, options = {}) {
952
+ const runtime = options.runtime ?? await loadLite();
953
+ if (runtime === void 0) throw new Error(LITE_INSTALL);
954
+ const connection = await runtime.createPgliteConnection();
955
+ const { driver } = connection;
956
+ const queue = new Queue();
957
+ await driver.exec(SUPABASE_PRELUDE);
958
+ await driver.exec(API_GRANTS);
959
+ const { issues, skipped } = await applyFiles(driver, project.files);
960
+ const run = (persona, sql, params) => asPersona(driver, queue, persona, sql, params);
961
+ const session = (persona) => ({
962
+ query: (sql, params = []) => run(persona, sql, params),
963
+ rest: (request) => handleRest(request, run, persona)
964
+ });
965
+ const owner = (sql, params = []) => queue.run(async () => {
966
+ try {
967
+ return {
968
+ ok: true,
969
+ rows: rowsOf(await driver.query(sql, params))
970
+ };
971
+ } catch (error) {
972
+ return {
973
+ ok: false,
974
+ error: errorOf(error)
975
+ };
976
+ }
977
+ });
978
+ return {
979
+ query: owner,
980
+ rest: (request) => handleRest(request, run),
981
+ as: session,
982
+ issues,
983
+ skipped,
984
+ catalog: async () => {
985
+ const { rows } = await driver.query(catalogQuery(["public"]));
986
+ return readCatalog(rows);
987
+ },
988
+ close: () => connection.close()
989
+ };
990
+ }
991
+ //#endregion
992
+ //#region src/create/lite/data-api.ts
993
+ const JSON_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]);
994
+ function columnMeta(column) {
995
+ const identity = column.identity === "a" ? "always" : column.identity === "d" ? "by default" : void 0;
996
+ return {
997
+ db: column.name,
998
+ type: column.udt,
999
+ nullable: column.nullable,
1000
+ hasDefault: column.default !== null || identity !== void 0,
1001
+ ...column.generated ? { generated: true } : {},
1002
+ ...identity === void 0 ? {} : { identity },
1003
+ ...column.array ? { array: true } : {},
1004
+ ...JSON_TYPES.has(column.udt) ? { json: true } : {},
1005
+ ...column.enumValues.length > 0 ? { enum: column.enumValues } : {},
1006
+ ...column.comment === null ? {} : { description: column.comment }
1007
+ };
1008
+ }
1009
+ function tableMeta(table) {
1010
+ const uniqueKeys = {};
1011
+ for (const constraint of table.constraints) if (constraint.type === "u") uniqueKeys[constraint.name] = constraint.columns;
1012
+ return {
1013
+ key: table.name,
1014
+ name: table.name,
1015
+ schema: table.schema,
1016
+ kind: table.kind === "r" || table.kind === "p" ? "table" : "view",
1017
+ columns: Object.fromEntries(table.columns.map((column) => [column.name, columnMeta(column)])),
1018
+ primaryKey: table.constraints.find((each) => each.type === "p")?.columns ?? [],
1019
+ uniqueKeys,
1020
+ relations: {},
1021
+ flags: {},
1022
+ ...table.comment === null ? {} : { description: table.comment }
1023
+ };
1024
+ }
1025
+ /**
1026
+ * The runtime metadata of a catalog's `public` tables and views, in snake
1027
+ * casing, keyed by table name. It carries what the Data API document needs:
1028
+ * columns, keys and enums. Relations and functions are left out.
1029
+ */
1030
+ function schemaMetaFromCatalog(catalog) {
1031
+ const tables = catalog.tables.filter((table) => table.schema === "public");
1032
+ const enums = {};
1033
+ for (const table of tables) for (const column of table.columns) if (column.enumValues.length > 0) enums[column.udt] = column.enumValues;
1034
+ return {
1035
+ version: 1,
1036
+ casing: "snake",
1037
+ tables: Object.fromEntries(tables.map((table) => [table.name, tableMeta(table)])),
1038
+ enums,
1039
+ functions: {}
1040
+ };
1041
+ }
1042
+ /**
1043
+ * The OpenAPI document of the Data API a design produces: the files render to a
1044
+ * PGlite database, and the tables that come out become `/rest/v1` paths with
1045
+ * row, insert and update schemas. It never touches a project. Throws when
1046
+ * `@supabase/lite` isn't installed.
1047
+ */
1048
+ async function designDataApi(preset, design = {}, options = {}) {
1049
+ const loaded = await loadProject(design, { preset });
1050
+ if (!loaded.ok) return loaded;
1051
+ const sandbox = await openSandbox(loaded.project, options);
1052
+ try {
1053
+ const meta = schemaMetaFromCatalog(await sandbox.catalog());
1054
+ const { document, diagnostics } = defineApi({ meta }, {
1055
+ info: {
1056
+ title: options.title ?? "Data API",
1057
+ version: options.version ?? "1.0.0"
1058
+ },
1059
+ dataApi: { tables: true },
1060
+ ...options.supabaseUrl === void 0 ? {} : { supabaseUrl: options.supabaseUrl }
1061
+ }).openapi();
1062
+ return {
1063
+ ok: true,
1064
+ document,
1065
+ diagnostics,
1066
+ tables: Object.keys(meta.tables).toSorted()
1067
+ };
1068
+ } finally {
1069
+ await sandbox.close();
1070
+ }
1071
+ }
1072
+ //#endregion
1073
+ //#region src/create/lite/index.ts
79
1074
  /**
80
1075
  * Applies the files `previewFiles` returns to an in-memory PGlite database and
81
1076
  * reports what Postgres rejects. A module that needs an extension PGlite
@@ -90,38 +1085,26 @@ async function validateDesign(files, options = {}) {
90
1085
  try {
91
1086
  const { driver } = connection;
92
1087
  await driver.exec(SUPABASE_PRELUDE);
93
- const issues = [];
94
- const skipped = /* @__PURE__ */ new Map();
95
- for (const file of files) {
96
- if (file.path.includes("/tests/") || skipped.has(file.module)) continue;
97
- try {
98
- await driver.exec(file.contents);
99
- } catch (error) {
100
- const message = messageOf(error);
101
- const extension = MISSING_EXTENSION.exec(message)?.[1];
102
- if (extension === void 0) issues.push({
103
- module: file.module,
104
- path: file.path,
105
- message
106
- });
107
- else skipped.set(file.module, `Needs the ${extension} extension, which PGlite doesn't ship.`);
108
- }
109
- }
1088
+ const { issues, skipped } = await applyFiles(driver, files);
110
1089
  const { rows } = await driver.query("select count(*)::int as count from pg_tables where schemaname = 'public'");
111
1090
  const [row] = rows;
112
1091
  const tables = typeof row === "object" && row !== null && "count" in row ? Number(row.count) : 0;
113
1092
  return {
114
1093
  ok: issues.length === 0,
115
1094
  issues,
116
- skipped: [...skipped].map(([module, reason]) => ({
117
- module,
118
- reason
119
- })),
1095
+ skipped,
120
1096
  tables
121
1097
  };
122
1098
  } finally {
123
1099
  await connection.close();
124
1100
  }
125
1101
  }
1102
+ /**
1103
+ * The issues `validateDesign` finds, for `checkProject`'s `sql` option:
1104
+ * `checkProject(project, { sql: sqlIssues })`.
1105
+ */
1106
+ async function sqlIssues(files) {
1107
+ return (await validateDesign(files)).issues;
1108
+ }
126
1109
  //#endregion
127
- export { SUPABASE_PRELUDE, validateDesign };
1110
+ export { SUPABASE_PRELUDE, designDataApi, designFromCatalog, importFilesOf, importProject, openSandbox, schemaMetaFromCatalog, sqlIssues, validateDesign };