@abloatai/transaction 0.37.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 (723) hide show
  1. package/CONVENTIONS.md +83 -0
  2. package/README.md +48 -0
  3. package/dist/ablo.d.ts +90 -0
  4. package/dist/ablo.d.ts.map +1 -0
  5. package/dist/ablo.js +34 -0
  6. package/dist/ablo.js.map +1 -0
  7. package/dist/ai-sdk/coordinatedTool.d.ts +123 -0
  8. package/dist/ai-sdk/coordinatedTool.d.ts.map +1 -0
  9. package/dist/ai-sdk/coordinatedTool.js +135 -0
  10. package/dist/ai-sdk/coordinatedTool.js.map +1 -0
  11. package/dist/ai-sdk/index.d.ts +2 -0
  12. package/dist/ai-sdk/index.d.ts.map +1 -0
  13. package/dist/ai-sdk/index.js +2 -0
  14. package/dist/ai-sdk/index.js.map +1 -0
  15. package/dist/auth/apiKey.d.ts +154 -0
  16. package/dist/auth/apiKey.d.ts.map +1 -0
  17. package/dist/auth/apiKey.js +408 -0
  18. package/dist/auth/apiKey.js.map +1 -0
  19. package/dist/auth/bootstrapScope.d.ts +16 -0
  20. package/dist/auth/bootstrapScope.d.ts.map +1 -0
  21. package/dist/auth/bootstrapScope.js +2 -0
  22. package/dist/auth/bootstrapScope.js.map +1 -0
  23. package/dist/auth/browserCredentialSafety.d.ts +7 -0
  24. package/dist/auth/browserCredentialSafety.d.ts.map +1 -0
  25. package/dist/auth/browserCredentialSafety.js +29 -0
  26. package/dist/auth/browserCredentialSafety.js.map +1 -0
  27. package/dist/auth/capability.d.ts +241 -0
  28. package/dist/auth/capability.d.ts.map +1 -0
  29. package/dist/auth/capability.js +253 -0
  30. package/dist/auth/capability.js.map +1 -0
  31. package/dist/auth/capabilityLifecycle.d.ts +47 -0
  32. package/dist/auth/capabilityLifecycle.d.ts.map +1 -0
  33. package/dist/auth/capabilityLifecycle.js +108 -0
  34. package/dist/auth/capabilityLifecycle.js.map +1 -0
  35. package/dist/auth/credentialEndpoint.d.ts +10 -0
  36. package/dist/auth/credentialEndpoint.d.ts.map +1 -0
  37. package/dist/auth/credentialEndpoint.js +58 -0
  38. package/dist/auth/credentialEndpoint.js.map +1 -0
  39. package/dist/auth/credentialEndpointProtocol.d.ts +24 -0
  40. package/dist/auth/credentialEndpointProtocol.d.ts.map +1 -0
  41. package/dist/auth/credentialEndpointProtocol.js +34 -0
  42. package/dist/auth/credentialEndpointProtocol.js.map +1 -0
  43. package/dist/auth/credentialKind.d.ts +4 -0
  44. package/dist/auth/credentialKind.d.ts.map +1 -0
  45. package/dist/auth/credentialKind.js +15 -0
  46. package/dist/auth/credentialKind.js.map +1 -0
  47. package/dist/auth/credentialPolicy.d.ts +141 -0
  48. package/dist/auth/credentialPolicy.d.ts.map +1 -0
  49. package/dist/auth/credentialPolicy.js +113 -0
  50. package/dist/auth/credentialPolicy.js.map +1 -0
  51. package/dist/auth/credentialResult.d.ts +7 -0
  52. package/dist/auth/credentialResult.d.ts.map +1 -0
  53. package/dist/auth/credentialResult.js +9 -0
  54. package/dist/auth/credentialResult.js.map +1 -0
  55. package/dist/auth/credentialSource.d.ts +31 -0
  56. package/dist/auth/credentialSource.d.ts.map +1 -0
  57. package/dist/auth/credentialSource.js +56 -0
  58. package/dist/auth/credentialSource.js.map +1 -0
  59. package/dist/auth/hostedEndpoints.d.ts +22 -0
  60. package/dist/auth/hostedEndpoints.d.ts.map +1 -0
  61. package/dist/auth/hostedEndpoints.js +22 -0
  62. package/dist/auth/hostedEndpoints.js.map +1 -0
  63. package/dist/auth/identity.d.ts +62 -0
  64. package/dist/auth/identity.d.ts.map +1 -0
  65. package/dist/auth/identity.js +224 -0
  66. package/dist/auth/identity.js.map +1 -0
  67. package/dist/auth/index.d.ts +189 -0
  68. package/dist/auth/index.d.ts.map +1 -0
  69. package/dist/auth/index.js +312 -0
  70. package/dist/auth/index.js.map +1 -0
  71. package/dist/auth/schemas.d.ts +41 -0
  72. package/dist/auth/schemas.d.ts.map +1 -0
  73. package/dist/auth/schemas.js +69 -0
  74. package/dist/auth/schemas.js.map +1 -0
  75. package/dist/auth/sessionMint.d.ts +29 -0
  76. package/dist/auth/sessionMint.d.ts.map +1 -0
  77. package/dist/auth/sessionMint.js +92 -0
  78. package/dist/auth/sessionMint.js.map +1 -0
  79. package/dist/auth/token.d.ts +4 -0
  80. package/dist/auth/token.d.ts.map +1 -0
  81. package/dist/auth/token.js +4 -0
  82. package/dist/auth/token.js.map +1 -0
  83. package/dist/batching/index.d.ts +56 -0
  84. package/dist/batching/index.d.ts.map +1 -0
  85. package/dist/batching/index.js +148 -0
  86. package/dist/batching/index.js.map +1 -0
  87. package/dist/coordination/awaitClaimGrant.d.ts +57 -0
  88. package/dist/coordination/awaitClaimGrant.d.ts.map +1 -0
  89. package/dist/coordination/awaitClaimGrant.js +138 -0
  90. package/dist/coordination/awaitClaimGrant.js.map +1 -0
  91. package/dist/coordination/claimHeartbeatLoop.d.ts +85 -0
  92. package/dist/coordination/claimHeartbeatLoop.d.ts.map +1 -0
  93. package/dist/coordination/claimHeartbeatLoop.js +109 -0
  94. package/dist/coordination/claimHeartbeatLoop.js.map +1 -0
  95. package/dist/coordination/claimMeta.d.ts +50 -0
  96. package/dist/coordination/claimMeta.d.ts.map +1 -0
  97. package/dist/coordination/claimMeta.js +53 -0
  98. package/dist/coordination/claimMeta.js.map +1 -0
  99. package/dist/coordination/events.d.ts +75 -0
  100. package/dist/coordination/events.d.ts.map +1 -0
  101. package/dist/coordination/events.js +8 -0
  102. package/dist/coordination/events.js.map +1 -0
  103. package/dist/coordination/index.d.ts +20 -0
  104. package/dist/coordination/index.d.ts.map +1 -0
  105. package/dist/coordination/index.js +46 -0
  106. package/dist/coordination/index.js.map +1 -0
  107. package/dist/coordination/locator.d.ts +106 -0
  108. package/dist/coordination/locator.d.ts.map +1 -0
  109. package/dist/coordination/locator.js +110 -0
  110. package/dist/coordination/locator.js.map +1 -0
  111. package/dist/coordination/schema.d.ts +1332 -0
  112. package/dist/coordination/schema.d.ts.map +1 -0
  113. package/dist/coordination/schema.js +1137 -0
  114. package/dist/coordination/schema.js.map +1 -0
  115. package/dist/coordination/targetConflict.d.ts +3 -0
  116. package/dist/coordination/targetConflict.d.ts.map +1 -0
  117. package/dist/coordination/targetConflict.js +74 -0
  118. package/dist/coordination/targetConflict.js.map +1 -0
  119. package/dist/coordination/trace.d.ts +79 -0
  120. package/dist/coordination/trace.d.ts.map +1 -0
  121. package/dist/coordination/trace.js +139 -0
  122. package/dist/coordination/trace.js.map +1 -0
  123. package/dist/docs/catalog.d.ts +73 -0
  124. package/dist/docs/catalog.d.ts.map +1 -0
  125. package/dist/docs/catalog.js +231 -0
  126. package/dist/docs/catalog.js.map +1 -0
  127. package/dist/docs/index.d.ts +11 -0
  128. package/dist/docs/index.d.ts.map +1 -0
  129. package/dist/docs/index.js +11 -0
  130. package/dist/docs/index.js.map +1 -0
  131. package/dist/durableWrites.d.ts +63 -0
  132. package/dist/durableWrites.d.ts.map +1 -0
  133. package/dist/durableWrites.js +72 -0
  134. package/dist/durableWrites.js.map +1 -0
  135. package/dist/environment.d.ts +106 -0
  136. package/dist/environment.d.ts.map +1 -0
  137. package/dist/environment.js +109 -0
  138. package/dist/environment.js.map +1 -0
  139. package/dist/errorCodes.d.ts +411 -0
  140. package/dist/errorCodes.d.ts.map +1 -0
  141. package/dist/errorCodes.js +500 -0
  142. package/dist/errorCodes.js.map +1 -0
  143. package/dist/errors.d.ts +429 -0
  144. package/dist/errors.d.ts.map +1 -0
  145. package/dist/errors.js +687 -0
  146. package/dist/errors.js.map +1 -0
  147. package/dist/footprint.d.ts +112 -0
  148. package/dist/footprint.d.ts.map +1 -0
  149. package/dist/footprint.js +0 -0
  150. package/dist/footprint.js.map +1 -0
  151. package/dist/headlessClient.d.ts +10 -0
  152. package/dist/headlessClient.d.ts.map +1 -0
  153. package/dist/headlessClient.js +114 -0
  154. package/dist/headlessClient.js.map +1 -0
  155. package/dist/index.d.ts +21 -0
  156. package/dist/index.d.ts.map +1 -0
  157. package/dist/index.js +21 -0
  158. package/dist/index.js.map +1 -0
  159. package/dist/keys/index.d.ts +88 -0
  160. package/dist/keys/index.d.ts.map +1 -0
  161. package/dist/keys/index.js +208 -0
  162. package/dist/keys/index.js.map +1 -0
  163. package/dist/log/syncDeltaRow.d.ts +159 -0
  164. package/dist/log/syncDeltaRow.d.ts.map +1 -0
  165. package/dist/log/syncDeltaRow.js +96 -0
  166. package/dist/log/syncDeltaRow.js.map +1 -0
  167. package/dist/logger.d.ts +17 -0
  168. package/dist/logger.d.ts.map +1 -0
  169. package/dist/logger.js +8 -0
  170. package/dist/logger.js.map +1 -0
  171. package/dist/observability.d.ts +54 -0
  172. package/dist/observability.d.ts.map +1 -0
  173. package/dist/observability.js +20 -0
  174. package/dist/observability.js.map +1 -0
  175. package/dist/policy/types.d.ts +218 -0
  176. package/dist/policy/types.d.ts.map +1 -0
  177. package/dist/policy/types.js +127 -0
  178. package/dist/policy/types.js.map +1 -0
  179. package/dist/resources/functionalUpdate.d.ts +80 -0
  180. package/dist/resources/functionalUpdate.d.ts.map +1 -0
  181. package/dist/resources/functionalUpdate.js +88 -0
  182. package/dist/resources/functionalUpdate.js.map +1 -0
  183. package/dist/resources/httpResources.d.ts +449 -0
  184. package/dist/resources/httpResources.d.ts.map +1 -0
  185. package/dist/resources/httpResources.js +8 -0
  186. package/dist/resources/httpResources.js.map +1 -0
  187. package/dist/resources/modelOperations.d.ts +380 -0
  188. package/dist/resources/modelOperations.d.ts.map +1 -0
  189. package/dist/resources/modelOperations.js +13 -0
  190. package/dist/resources/modelOperations.js.map +1 -0
  191. package/dist/resources/mutationOptions.d.ts +67 -0
  192. package/dist/resources/mutationOptions.d.ts.map +1 -0
  193. package/dist/resources/mutationOptions.js +10 -0
  194. package/dist/resources/mutationOptions.js.map +1 -0
  195. package/dist/resources/where.d.ts +102 -0
  196. package/dist/resources/where.d.ts.map +1 -0
  197. package/dist/resources/where.js +116 -0
  198. package/dist/resources/where.js.map +1 -0
  199. package/dist/resources/writeOptionsSchema.d.ts +48 -0
  200. package/dist/resources/writeOptionsSchema.d.ts.map +1 -0
  201. package/dist/resources/writeOptionsSchema.js +74 -0
  202. package/dist/resources/writeOptionsSchema.js.map +1 -0
  203. package/dist/schema/coordination.d.ts +113 -0
  204. package/dist/schema/coordination.d.ts.map +1 -0
  205. package/dist/schema/coordination.js +134 -0
  206. package/dist/schema/coordination.js.map +1 -0
  207. package/dist/schema/ddl.d.ts +98 -0
  208. package/dist/schema/ddl.d.ts.map +1 -0
  209. package/dist/schema/ddl.js +492 -0
  210. package/dist/schema/ddl.js.map +1 -0
  211. package/dist/schema/ddlLock.d.ts +36 -0
  212. package/dist/schema/ddlLock.d.ts.map +1 -0
  213. package/dist/schema/ddlLock.js +47 -0
  214. package/dist/schema/ddlLock.js.map +1 -0
  215. package/dist/schema/diff.d.ts +226 -0
  216. package/dist/schema/diff.d.ts.map +1 -0
  217. package/dist/schema/diff.js +290 -0
  218. package/dist/schema/diff.js.map +1 -0
  219. package/dist/schema/field.d.ts +121 -0
  220. package/dist/schema/field.d.ts.map +1 -0
  221. package/dist/schema/field.js +266 -0
  222. package/dist/schema/field.js.map +1 -0
  223. package/dist/schema/fieldRef.d.ts +58 -0
  224. package/dist/schema/fieldRef.d.ts.map +1 -0
  225. package/dist/schema/fieldRef.js +26 -0
  226. package/dist/schema/fieldRef.js.map +1 -0
  227. package/dist/schema/generate.d.ts +20 -0
  228. package/dist/schema/generate.d.ts.map +1 -0
  229. package/dist/schema/generate.js +87 -0
  230. package/dist/schema/generate.js.map +1 -0
  231. package/dist/schema/index.d.ts +43 -0
  232. package/dist/schema/index.d.ts.map +1 -0
  233. package/dist/schema/index.js +81 -0
  234. package/dist/schema/index.js.map +1 -0
  235. package/dist/schema/loadStrategy.d.ts +46 -0
  236. package/dist/schema/loadStrategy.d.ts.map +1 -0
  237. package/dist/schema/loadStrategy.js +47 -0
  238. package/dist/schema/loadStrategy.js.map +1 -0
  239. package/dist/schema/model.d.ts +380 -0
  240. package/dist/schema/model.d.ts.map +1 -0
  241. package/dist/schema/model.js +124 -0
  242. package/dist/schema/model.js.map +1 -0
  243. package/dist/schema/openapi.d.ts +59 -0
  244. package/dist/schema/openapi.d.ts.map +1 -0
  245. package/dist/schema/openapi.js +508 -0
  246. package/dist/schema/openapi.js.map +1 -0
  247. package/dist/schema/queries.d.ts +202 -0
  248. package/dist/schema/queries.d.ts.map +1 -0
  249. package/dist/schema/queries.js +144 -0
  250. package/dist/schema/queries.js.map +1 -0
  251. package/dist/schema/relation.d.ts +205 -0
  252. package/dist/schema/relation.d.ts.map +1 -0
  253. package/dist/schema/relation.js +105 -0
  254. package/dist/schema/relation.js.map +1 -0
  255. package/dist/schema/residency.d.ts +30 -0
  256. package/dist/schema/residency.d.ts.map +1 -0
  257. package/dist/schema/residency.js +26 -0
  258. package/dist/schema/residency.js.map +1 -0
  259. package/dist/schema/roles.d.ts +250 -0
  260. package/dist/schema/roles.d.ts.map +1 -0
  261. package/dist/schema/roles.js +231 -0
  262. package/dist/schema/roles.js.map +1 -0
  263. package/dist/schema/schema.d.ts +352 -0
  264. package/dist/schema/schema.d.ts.map +1 -0
  265. package/dist/schema/schema.js +326 -0
  266. package/dist/schema/schema.js.map +1 -0
  267. package/dist/schema/select.d.ts +41 -0
  268. package/dist/schema/select.d.ts.map +1 -0
  269. package/dist/schema/select.js +91 -0
  270. package/dist/schema/select.js.map +1 -0
  271. package/dist/schema/serialize.d.ts +116 -0
  272. package/dist/schema/serialize.d.ts.map +1 -0
  273. package/dist/schema/serialize.js +278 -0
  274. package/dist/schema/serialize.js.map +1 -0
  275. package/dist/schema/sugar.d.ts +110 -0
  276. package/dist/schema/sugar.d.ts.map +1 -0
  277. package/dist/schema/sugar.js +84 -0
  278. package/dist/schema/sugar.js.map +1 -0
  279. package/dist/schema/tenancy.d.ts +140 -0
  280. package/dist/schema/tenancy.d.ts.map +1 -0
  281. package/dist/schema/tenancy.js +191 -0
  282. package/dist/schema/tenancy.js.map +1 -0
  283. package/dist/server/adapter.d.ts +174 -0
  284. package/dist/server/adapter.d.ts.map +1 -0
  285. package/dist/server/adapter.js +19 -0
  286. package/dist/server/adapter.js.map +1 -0
  287. package/dist/server/commit.d.ts +108 -0
  288. package/dist/server/commit.d.ts.map +1 -0
  289. package/dist/server/commit.js +2 -0
  290. package/dist/server/commit.js.map +1 -0
  291. package/dist/server/index.d.ts +15 -0
  292. package/dist/server/index.d.ts.map +1 -0
  293. package/dist/server/index.js +3 -0
  294. package/dist/server/index.js.map +1 -0
  295. package/dist/server/readConfig.d.ts +81 -0
  296. package/dist/server/readConfig.d.ts.map +1 -0
  297. package/dist/server/readConfig.js +9 -0
  298. package/dist/server/readConfig.js.map +1 -0
  299. package/dist/server/storageMode.d.ts +24 -0
  300. package/dist/server/storageMode.d.ts.map +1 -0
  301. package/dist/server/storageMode.js +18 -0
  302. package/dist/server/storageMode.js.map +1 -0
  303. package/dist/source/adapter.d.ts +84 -0
  304. package/dist/source/adapter.d.ts.map +1 -0
  305. package/dist/source/adapter.js +25 -0
  306. package/dist/source/adapter.js.map +1 -0
  307. package/dist/source/adapters/drizzle.d.ts +49 -0
  308. package/dist/source/adapters/drizzle.d.ts.map +1 -0
  309. package/dist/source/adapters/drizzle.js +220 -0
  310. package/dist/source/adapters/drizzle.js.map +1 -0
  311. package/dist/source/adapters/kysely.d.ts +43 -0
  312. package/dist/source/adapters/kysely.d.ts.map +1 -0
  313. package/dist/source/adapters/kysely.js +206 -0
  314. package/dist/source/adapters/kysely.js.map +1 -0
  315. package/dist/source/adapters/kyselyMutationCore.d.ts +77 -0
  316. package/dist/source/adapters/kyselyMutationCore.d.ts.map +1 -0
  317. package/dist/source/adapters/kyselyMutationCore.js +126 -0
  318. package/dist/source/adapters/kyselyMutationCore.js.map +1 -0
  319. package/dist/source/adapters/memory.d.ts +14 -0
  320. package/dist/source/adapters/memory.d.ts.map +1 -0
  321. package/dist/source/adapters/memory.js +131 -0
  322. package/dist/source/adapters/memory.js.map +1 -0
  323. package/dist/source/adapters/prisma.d.ts +64 -0
  324. package/dist/source/adapters/prisma.d.ts.map +1 -0
  325. package/dist/source/adapters/prisma.js +203 -0
  326. package/dist/source/adapters/prisma.js.map +1 -0
  327. package/dist/source/conformance.d.ts +38 -0
  328. package/dist/source/conformance.d.ts.map +1 -0
  329. package/dist/source/conformance.js +216 -0
  330. package/dist/source/conformance.js.map +1 -0
  331. package/dist/source/connector.d.ts +96 -0
  332. package/dist/source/connector.d.ts.map +1 -0
  333. package/dist/source/connector.js +267 -0
  334. package/dist/source/connector.js.map +1 -0
  335. package/dist/source/connectorProtocol.d.ts +155 -0
  336. package/dist/source/connectorProtocol.d.ts.map +1 -0
  337. package/dist/source/connectorProtocol.js +164 -0
  338. package/dist/source/connectorProtocol.js.map +1 -0
  339. package/dist/source/contract.d.ts +196 -0
  340. package/dist/source/contract.d.ts.map +1 -0
  341. package/dist/source/contract.js +165 -0
  342. package/dist/source/contract.js.map +1 -0
  343. package/dist/source/drizzle.d.ts +2 -0
  344. package/dist/source/drizzle.d.ts.map +1 -0
  345. package/dist/source/drizzle.js +2 -0
  346. package/dist/source/drizzle.js.map +1 -0
  347. package/dist/source/factory.d.ts +93 -0
  348. package/dist/source/factory.d.ts.map +1 -0
  349. package/dist/source/factory.js +287 -0
  350. package/dist/source/factory.js.map +1 -0
  351. package/dist/source/idempotency.d.ts +62 -0
  352. package/dist/source/idempotency.d.ts.map +1 -0
  353. package/dist/source/idempotency.js +145 -0
  354. package/dist/source/idempotency.js.map +1 -0
  355. package/dist/source/index.d.ts +24 -0
  356. package/dist/source/index.d.ts.map +1 -0
  357. package/dist/source/index.js +29 -0
  358. package/dist/source/index.js.map +1 -0
  359. package/dist/source/kysely.d.ts +3 -0
  360. package/dist/source/kysely.d.ts.map +1 -0
  361. package/dist/source/kysely.js +3 -0
  362. package/dist/source/kysely.js.map +1 -0
  363. package/dist/source/migrations.d.ts +22 -0
  364. package/dist/source/migrations.d.ts.map +1 -0
  365. package/dist/source/migrations.js +104 -0
  366. package/dist/source/migrations.js.map +1 -0
  367. package/dist/source/next.d.ts +33 -0
  368. package/dist/source/next.d.ts.map +1 -0
  369. package/dist/source/next.js +26 -0
  370. package/dist/source/next.js.map +1 -0
  371. package/dist/source/pushQueue.d.ts +135 -0
  372. package/dist/source/pushQueue.d.ts.map +1 -0
  373. package/dist/source/pushQueue.js +257 -0
  374. package/dist/source/pushQueue.js.map +1 -0
  375. package/dist/source/signing.d.ts +93 -0
  376. package/dist/source/signing.d.ts.map +1 -0
  377. package/dist/source/signing.js +163 -0
  378. package/dist/source/signing.js.map +1 -0
  379. package/dist/source/types.d.ts +402 -0
  380. package/dist/source/types.d.ts.map +1 -0
  381. package/dist/source/types.js +60 -0
  382. package/dist/source/types.js.map +1 -0
  383. package/dist/syncLog/contract.d.ts +21 -0
  384. package/dist/syncLog/contract.d.ts.map +1 -0
  385. package/dist/syncLog/contract.js +20 -0
  386. package/dist/syncLog/contract.js.map +1 -0
  387. package/dist/syncLog/index.d.ts +2 -0
  388. package/dist/syncLog/index.d.ts.map +1 -0
  389. package/dist/syncLog/index.js +2 -0
  390. package/dist/syncLog/index.js.map +1 -0
  391. package/dist/testing/fixtures/httpResponses.d.ts +74 -0
  392. package/dist/testing/fixtures/httpResponses.d.ts.map +1 -0
  393. package/dist/testing/fixtures/httpResponses.js +102 -0
  394. package/dist/testing/fixtures/httpResponses.js.map +1 -0
  395. package/dist/transactionLayer.d.ts +110 -0
  396. package/dist/transactionLayer.d.ts.map +1 -0
  397. package/dist/transactionLayer.js +25 -0
  398. package/dist/transactionLayer.js.map +1 -0
  399. package/dist/transactions/settlement/commitEnvelope.d.ts +144 -0
  400. package/dist/transactions/settlement/commitEnvelope.d.ts.map +1 -0
  401. package/dist/transactions/settlement/commitEnvelope.js +162 -0
  402. package/dist/transactions/settlement/commitEnvelope.js.map +1 -0
  403. package/dist/transactions/settlement/httpCommitEnvelope.d.ts +54 -0
  404. package/dist/transactions/settlement/httpCommitEnvelope.d.ts.map +1 -0
  405. package/dist/transactions/settlement/httpCommitEnvelope.js +208 -0
  406. package/dist/transactions/settlement/httpCommitEnvelope.js.map +1 -0
  407. package/dist/transactions/settlement/idempotencyKey.d.ts +11 -0
  408. package/dist/transactions/settlement/idempotencyKey.d.ts.map +1 -0
  409. package/dist/transactions/settlement/idempotencyKey.js +10 -0
  410. package/dist/transactions/settlement/idempotencyKey.js.map +1 -0
  411. package/dist/transactions/settlement/pendingWrite.d.ts +113 -0
  412. package/dist/transactions/settlement/pendingWrite.d.ts.map +1 -0
  413. package/dist/transactions/settlement/pendingWrite.js +21 -0
  414. package/dist/transactions/settlement/pendingWrite.js.map +1 -0
  415. package/dist/transport/commitFrames.d.ts +91 -0
  416. package/dist/transport/commitFrames.d.ts.map +1 -0
  417. package/dist/transport/commitFrames.js +135 -0
  418. package/dist/transport/commitFrames.js.map +1 -0
  419. package/dist/transport/connectionManager.d.ts +216 -0
  420. package/dist/transport/connectionManager.d.ts.map +1 -0
  421. package/dist/transport/connectionManager.js +674 -0
  422. package/dist/transport/connectionManager.js.map +1 -0
  423. package/dist/transport/credentialLifecycle.d.ts +178 -0
  424. package/dist/transport/credentialLifecycle.d.ts.map +1 -0
  425. package/dist/transport/credentialLifecycle.js +324 -0
  426. package/dist/transport/credentialLifecycle.js.map +1 -0
  427. package/dist/transport/heartbeat.d.ts +66 -0
  428. package/dist/transport/heartbeat.d.ts.map +1 -0
  429. package/dist/transport/heartbeat.js +94 -0
  430. package/dist/transport/heartbeat.js.map +1 -0
  431. package/dist/transport/httpClient.d.ts +143 -0
  432. package/dist/transport/httpClient.d.ts.map +1 -0
  433. package/dist/transport/httpClient.js +150 -0
  434. package/dist/transport/httpClient.js.map +1 -0
  435. package/dist/transport/httpFeed.d.ts +4 -0
  436. package/dist/transport/httpFeed.d.ts.map +1 -0
  437. package/dist/transport/httpFeed.js +94 -0
  438. package/dist/transport/httpFeed.js.map +1 -0
  439. package/dist/transport/httpOptions.d.ts +34 -0
  440. package/dist/transport/httpOptions.d.ts.map +1 -0
  441. package/dist/transport/httpOptions.js +13 -0
  442. package/dist/transport/httpOptions.js.map +1 -0
  443. package/dist/transport/httpTransport.d.ts +68 -0
  444. package/dist/transport/httpTransport.d.ts.map +1 -0
  445. package/dist/transport/httpTransport.js +1433 -0
  446. package/dist/transport/httpTransport.js.map +1 -0
  447. package/dist/transport/networkProbe.d.ts +85 -0
  448. package/dist/transport/networkProbe.d.ts.map +1 -0
  449. package/dist/transport/networkProbe.js +208 -0
  450. package/dist/transport/networkProbe.js.map +1 -0
  451. package/dist/transport/wsFrameHandlers.d.ts +129 -0
  452. package/dist/transport/wsFrameHandlers.d.ts.map +1 -0
  453. package/dist/transport/wsFrameHandlers.js +429 -0
  454. package/dist/transport/wsFrameHandlers.js.map +1 -0
  455. package/dist/transport/wsTransport.d.ts +575 -0
  456. package/dist/transport/wsTransport.d.ts.map +1 -0
  457. package/dist/transport/wsTransport.js +1024 -0
  458. package/dist/transport/wsTransport.js.map +1 -0
  459. package/dist/types/assertExact.d.ts +18 -0
  460. package/dist/types/assertExact.d.ts.map +1 -0
  461. package/dist/types/assertExact.js +2 -0
  462. package/dist/types/assertExact.js.map +1 -0
  463. package/dist/types/global.d.ts +108 -0
  464. package/dist/types/global.d.ts.map +1 -0
  465. package/dist/types/global.js +41 -0
  466. package/dist/types/global.js.map +1 -0
  467. package/dist/types/index.d.ts +206 -0
  468. package/dist/types/index.d.ts.map +1 -0
  469. package/dist/types/index.js +57 -0
  470. package/dist/types/index.js.map +1 -0
  471. package/dist/types/modelData.d.ts +11 -0
  472. package/dist/types/modelData.d.ts.map +1 -0
  473. package/dist/types/modelData.js +10 -0
  474. package/dist/types/modelData.js.map +1 -0
  475. package/dist/types/participant.d.ts +21 -0
  476. package/dist/types/participant.d.ts.map +1 -0
  477. package/dist/types/participant.js +11 -0
  478. package/dist/types/participant.js.map +1 -0
  479. package/dist/types/streams.d.ts +545 -0
  480. package/dist/types/streams.d.ts.map +1 -0
  481. package/dist/types/streams.js +12 -0
  482. package/dist/types/streams.js.map +1 -0
  483. package/dist/utils/asyncIterator.d.ts +35 -0
  484. package/dist/utils/asyncIterator.d.ts.map +1 -0
  485. package/dist/utils/asyncIterator.js +136 -0
  486. package/dist/utils/asyncIterator.js.map +1 -0
  487. package/dist/utils/duration.d.ts +51 -0
  488. package/dist/utils/duration.d.ts.map +1 -0
  489. package/dist/utils/duration.js +78 -0
  490. package/dist/utils/duration.js.map +1 -0
  491. package/dist/utils/json.d.ts +58 -0
  492. package/dist/utils/json.d.ts.map +1 -0
  493. package/dist/utils/json.js +277 -0
  494. package/dist/utils/json.js.map +1 -0
  495. package/dist/webhooks/events.d.ts +44 -0
  496. package/dist/webhooks/events.d.ts.map +1 -0
  497. package/dist/webhooks/events.js +43 -0
  498. package/dist/webhooks/events.js.map +1 -0
  499. package/dist/webhooks/index.d.ts +9 -0
  500. package/dist/webhooks/index.d.ts.map +1 -0
  501. package/dist/webhooks/index.js +9 -0
  502. package/dist/webhooks/index.js.map +1 -0
  503. package/dist/wire/accountResponses.d.ts +463 -0
  504. package/dist/wire/accountResponses.d.ts.map +1 -0
  505. package/dist/wire/accountResponses.js +294 -0
  506. package/dist/wire/accountResponses.js.map +1 -0
  507. package/dist/wire/auth.d.ts +57 -0
  508. package/dist/wire/auth.d.ts.map +1 -0
  509. package/dist/wire/auth.js +71 -0
  510. package/dist/wire/auth.js.map +1 -0
  511. package/dist/wire/bootstrapReason.d.ts +10 -0
  512. package/dist/wire/bootstrapReason.d.ts.map +1 -0
  513. package/dist/wire/bootstrapReason.js +9 -0
  514. package/dist/wire/bootstrapReason.js.map +1 -0
  515. package/dist/wire/claimEvent.d.ts +70 -0
  516. package/dist/wire/claimEvent.d.ts.map +1 -0
  517. package/dist/wire/claimEvent.js +74 -0
  518. package/dist/wire/claimEvent.js.map +1 -0
  519. package/dist/wire/claims.d.ts +475 -0
  520. package/dist/wire/claims.d.ts.map +1 -0
  521. package/dist/wire/claims.js +326 -0
  522. package/dist/wire/claims.js.map +1 -0
  523. package/dist/wire/commit.d.ts +604 -0
  524. package/dist/wire/commit.d.ts.map +1 -0
  525. package/dist/wire/commit.js +322 -0
  526. package/dist/wire/commit.js.map +1 -0
  527. package/dist/wire/delta.d.ts +251 -0
  528. package/dist/wire/delta.d.ts.map +1 -0
  529. package/dist/wire/delta.js +148 -0
  530. package/dist/wire/delta.js.map +1 -0
  531. package/dist/wire/errorEnvelope.d.ts +73 -0
  532. package/dist/wire/errorEnvelope.d.ts.map +1 -0
  533. package/dist/wire/errorEnvelope.js +124 -0
  534. package/dist/wire/errorEnvelope.js.map +1 -0
  535. package/dist/wire/feedCursor.d.ts +61 -0
  536. package/dist/wire/feedCursor.d.ts.map +1 -0
  537. package/dist/wire/feedCursor.js +83 -0
  538. package/dist/wire/feedCursor.js.map +1 -0
  539. package/dist/wire/feedEvent.d.ts +264 -0
  540. package/dist/wire/feedEvent.d.ts.map +1 -0
  541. package/dist/wire/feedEvent.js +66 -0
  542. package/dist/wire/feedEvent.js.map +1 -0
  543. package/dist/wire/frames.d.ts +195 -0
  544. package/dist/wire/frames.d.ts.map +1 -0
  545. package/dist/wire/frames.js +51 -0
  546. package/dist/wire/frames.js.map +1 -0
  547. package/dist/wire/inboundFrames.d.ts +490 -0
  548. package/dist/wire/inboundFrames.d.ts.map +1 -0
  549. package/dist/wire/inboundFrames.js +117 -0
  550. package/dist/wire/inboundFrames.js.map +1 -0
  551. package/dist/wire/index.d.ts +55 -0
  552. package/dist/wire/index.d.ts.map +1 -0
  553. package/dist/wire/index.js +84 -0
  554. package/dist/wire/index.js.map +1 -0
  555. package/dist/wire/listEnvelope.d.ts +38 -0
  556. package/dist/wire/listEnvelope.d.ts.map +1 -0
  557. package/dist/wire/listEnvelope.js +43 -0
  558. package/dist/wire/listEnvelope.js.map +1 -0
  559. package/dist/wire/modelMutations.d.ts +32 -0
  560. package/dist/wire/modelMutations.d.ts.map +1 -0
  561. package/dist/wire/modelMutations.js +53 -0
  562. package/dist/wire/modelMutations.js.map +1 -0
  563. package/dist/wire/modelResponses.d.ts +79 -0
  564. package/dist/wire/modelResponses.d.ts.map +1 -0
  565. package/dist/wire/modelResponses.js +44 -0
  566. package/dist/wire/modelResponses.js.map +1 -0
  567. package/dist/wire/modelShape.d.ts +79 -0
  568. package/dist/wire/modelShape.d.ts.map +1 -0
  569. package/dist/wire/modelShape.js +75 -0
  570. package/dist/wire/modelShape.js.map +1 -0
  571. package/dist/wire/protocol.d.ts +39 -0
  572. package/dist/wire/protocol.d.ts.map +1 -0
  573. package/dist/wire/protocol.js +39 -0
  574. package/dist/wire/protocol.js.map +1 -0
  575. package/dist/wire/protocolVersion.d.ts +74 -0
  576. package/dist/wire/protocolVersion.d.ts.map +1 -0
  577. package/dist/wire/protocolVersion.js +84 -0
  578. package/dist/wire/protocolVersion.js.map +1 -0
  579. package/package.json +187 -0
  580. package/src/ablo.ts +139 -0
  581. package/src/ai-sdk/coordinatedTool.ts +214 -0
  582. package/src/ai-sdk/index.ts +7 -0
  583. package/src/auth/apiKey.ts +540 -0
  584. package/src/auth/bootstrapScope.ts +15 -0
  585. package/src/auth/browserCredentialSafety.ts +48 -0
  586. package/src/auth/capability.ts +326 -0
  587. package/src/auth/capabilityLifecycle.ts +174 -0
  588. package/src/auth/credentialEndpoint.ts +79 -0
  589. package/src/auth/credentialEndpointProtocol.ts +51 -0
  590. package/src/auth/credentialKind.ts +20 -0
  591. package/src/auth/credentialPolicy.ts +244 -0
  592. package/src/auth/credentialResult.ts +23 -0
  593. package/src/auth/credentialSource.ts +99 -0
  594. package/src/auth/hostedEndpoints.ts +24 -0
  595. package/src/auth/identity.ts +330 -0
  596. package/src/auth/index.ts +592 -0
  597. package/src/auth/schemas.ts +94 -0
  598. package/src/auth/sessionMint.ts +126 -0
  599. package/src/auth/token.ts +4 -0
  600. package/src/batching/index.ts +200 -0
  601. package/src/coordination/awaitClaimGrant.ts +243 -0
  602. package/src/coordination/claimHeartbeatLoop.ts +165 -0
  603. package/src/coordination/claimMeta.ts +56 -0
  604. package/src/coordination/events.ts +86 -0
  605. package/src/coordination/index.ts +181 -0
  606. package/src/coordination/locator.ts +200 -0
  607. package/src/coordination/schema.ts +1346 -0
  608. package/src/coordination/targetConflict.ts +85 -0
  609. package/src/coordination/trace.ts +173 -0
  610. package/src/docs/catalog.ts +274 -0
  611. package/src/docs/index.ts +18 -0
  612. package/src/durableWrites.ts +134 -0
  613. package/src/environment.ts +132 -0
  614. package/src/errorCodes.ts +1591 -0
  615. package/src/errors.ts +918 -0
  616. package/src/footprint.ts +0 -0
  617. package/src/headlessClient.ts +161 -0
  618. package/src/index.ts +52 -0
  619. package/src/keys/index.ts +254 -0
  620. package/src/log/syncDeltaRow.ts +119 -0
  621. package/src/logger.ts +22 -0
  622. package/src/observability.ts +85 -0
  623. package/src/policy/types.ts +292 -0
  624. package/src/resources/functionalUpdate.ts +151 -0
  625. package/src/resources/httpResources.ts +520 -0
  626. package/src/resources/modelOperations.ts +444 -0
  627. package/src/resources/mutationOptions.ts +66 -0
  628. package/src/resources/where.ts +160 -0
  629. package/src/resources/writeOptionsSchema.ts +91 -0
  630. package/src/schema/coordination.ts +161 -0
  631. package/src/schema/ddl.ts +593 -0
  632. package/src/schema/ddlLock.ts +53 -0
  633. package/src/schema/diff.ts +489 -0
  634. package/src/schema/field.ts +321 -0
  635. package/src/schema/fieldRef.ts +88 -0
  636. package/src/schema/generate.ts +95 -0
  637. package/src/schema/index.ts +278 -0
  638. package/src/schema/loadStrategy.ts +52 -0
  639. package/src/schema/model.ts +476 -0
  640. package/src/schema/openapi.ts +658 -0
  641. package/src/schema/queries.ts +273 -0
  642. package/src/schema/relation.ts +291 -0
  643. package/src/schema/residency.ts +30 -0
  644. package/src/schema/roles.ts +325 -0
  645. package/src/schema/schema.ts +825 -0
  646. package/src/schema/select.ts +115 -0
  647. package/src/schema/serialize.ts +373 -0
  648. package/src/schema/sugar.ts +194 -0
  649. package/src/schema/tenancy.ts +221 -0
  650. package/src/server/adapter.ts +203 -0
  651. package/src/server/commit.ts +109 -0
  652. package/src/server/index.ts +26 -0
  653. package/src/server/readConfig.ts +82 -0
  654. package/src/server/storageMode.ts +20 -0
  655. package/src/source/adapter.ts +85 -0
  656. package/src/source/adapters/drizzle.ts +291 -0
  657. package/src/source/adapters/kysely.ts +346 -0
  658. package/src/source/adapters/kyselyMutationCore.ts +220 -0
  659. package/src/source/adapters/memory.ts +154 -0
  660. package/src/source/adapters/prisma.ts +282 -0
  661. package/src/source/conformance.ts +287 -0
  662. package/src/source/connector.ts +394 -0
  663. package/src/source/connectorProtocol.ts +189 -0
  664. package/src/source/contract.ts +221 -0
  665. package/src/source/drizzle.ts +1 -0
  666. package/src/source/factory.ts +444 -0
  667. package/src/source/idempotency.ts +189 -0
  668. package/src/source/index.ts +182 -0
  669. package/src/source/kysely.ts +2 -0
  670. package/src/source/migrations.ts +109 -0
  671. package/src/source/next.ts +38 -0
  672. package/src/source/pushQueue.ts +368 -0
  673. package/src/source/signing.ts +279 -0
  674. package/src/source/types.ts +502 -0
  675. package/src/syncLog/contract.ts +32 -0
  676. package/src/syncLog/index.ts +1 -0
  677. package/src/testing/fixtures/httpResponses.ts +155 -0
  678. package/src/transactionLayer.ts +122 -0
  679. package/src/transactions/settlement/commitEnvelope.ts +192 -0
  680. package/src/transactions/settlement/httpCommitEnvelope.ts +250 -0
  681. package/src/transactions/settlement/idempotencyKey.ts +11 -0
  682. package/src/transactions/settlement/pendingWrite.ts +24 -0
  683. package/src/transport/commitFrames.ts +225 -0
  684. package/src/transport/connectionManager.ts +856 -0
  685. package/src/transport/credentialLifecycle.ts +389 -0
  686. package/src/transport/heartbeat.ts +118 -0
  687. package/src/transport/httpClient.ts +354 -0
  688. package/src/transport/httpFeed.ts +111 -0
  689. package/src/transport/httpOptions.ts +41 -0
  690. package/src/transport/httpTransport.ts +1976 -0
  691. package/src/transport/networkProbe.ts +249 -0
  692. package/src/transport/wsFrameHandlers.ts +619 -0
  693. package/src/transport/wsTransport.ts +1491 -0
  694. package/src/types/assertExact.ts +17 -0
  695. package/src/types/global.ts +123 -0
  696. package/src/types/index.ts +270 -0
  697. package/src/types/modelData.ts +11 -0
  698. package/src/types/participant.ts +22 -0
  699. package/src/types/streams.ts +702 -0
  700. package/src/utils/asyncIterator.ts +141 -0
  701. package/src/utils/duration.ts +88 -0
  702. package/src/utils/json.ts +281 -0
  703. package/src/webhooks/events.ts +96 -0
  704. package/src/webhooks/index.ts +12 -0
  705. package/src/wire/accountResponses.ts +328 -0
  706. package/src/wire/auth.ts +86 -0
  707. package/src/wire/bootstrapReason.ts +10 -0
  708. package/src/wire/claimEvent.ts +85 -0
  709. package/src/wire/claims.ts +370 -0
  710. package/src/wire/commit.ts +379 -0
  711. package/src/wire/delta.ts +173 -0
  712. package/src/wire/errorEnvelope.ts +133 -0
  713. package/src/wire/feedCursor.ts +91 -0
  714. package/src/wire/feedEvent.ts +74 -0
  715. package/src/wire/frames.ts +77 -0
  716. package/src/wire/inboundFrames.ts +182 -0
  717. package/src/wire/index.ts +328 -0
  718. package/src/wire/listEnvelope.ts +51 -0
  719. package/src/wire/modelMutations.ts +55 -0
  720. package/src/wire/modelResponses.ts +48 -0
  721. package/src/wire/modelShape.ts +83 -0
  722. package/src/wire/protocol.ts +39 -0
  723. package/src/wire/protocolVersion.ts +97 -0
@@ -0,0 +1,593 @@
1
+ /**
2
+ * Turns a schema definition into the ordered Postgres DDL that provisions and
3
+ * migrates its tables. A schema built with `defineSchema(...)` and serialized to
4
+ * {@link SchemaJSON} is the single source of truth, and this module lowers it to
5
+ * ordered SQL strings.
6
+ *
7
+ * The same generators run wherever tables are created — in a hosted server
8
+ * applying them to the Postgres it manages, and in the `ablo migrate` CLI
9
+ * applying them to a customer's own Postgres — so the SQL, from column types to
10
+ * row-level security to enum checks, is identical no matter who runs it.
11
+ *
12
+ * Everything here is pure: it returns strings and touches no database. The
13
+ * execution side — the transaction and advisory lock that actually run the
14
+ * statements — lives with each caller, because it is coupled to that caller's
15
+ * Postgres client and error types.
16
+ *
17
+ * - {@link generateProvisionPlan} builds an additive, idempotent plan (CREATE
18
+ * and ADD … IF NOT EXISTS, plus row-level security) that never loses data —
19
+ * the "create my tables" primitive.
20
+ * - {@link generateMigrationPlan} is its destructive-aware counterpart, driven
21
+ * by a {@link diffSchema} step list: drops, renames, type casts, and
22
+ * backfills.
23
+ */
24
+
25
+ import { AbloValidationError } from '../errors.js';
26
+ import type { SchemaJSON, ModelJSON } from './serialize.js';
27
+ import type { MigrationStep, BackfillValue, FieldType } from './diff.js';
28
+ import type { FieldMeta } from './field.js';
29
+ import { resolveTenancy, tenancyColumn } from './tenancy.js';
30
+
31
+ export interface ProvisionPlan {
32
+ /** The Postgres schema the tables live in (`app_<id>` or `public`). */
33
+ readonly appSchema: string;
34
+ /** Ordered, idempotent DDL statements. Safe to run repeatedly. Executors run
35
+ * these together in one transaction. */
36
+ readonly statements: readonly string[];
37
+ /** Post-commit, non-transactional DDL (`VALIDATE CONSTRAINT`, `CREATE INDEX
38
+ * CONCURRENTLY`) — run after {@link statements} commit, each outside any
39
+ * transaction, best-effort. Keeps the lock-heavy and scan-heavy work off the
40
+ * main transaction so adding a foreign key never freezes a large, live table.
41
+ * Optional: when absent, there is nothing to run. */
42
+ readonly concurrent?: readonly string[];
43
+ }
44
+
45
+ export interface ProvisionOptions {
46
+ /**
47
+ * Emit `DEFERRABLE INITIALLY DEFERRED` foreign-key constraints for the
48
+ * belongsTo relations that opt in; see {@link foreignKeyStatements} for exactly
49
+ * which relations qualify. Off by default, so soft references keep out-of-order
50
+ * sync robust. Turn it on for a customer's own database, where a clean,
51
+ * navigable relational schema is wanted and the database starts empty, so a
52
+ * constraint has nothing to fail against.
53
+ */
54
+ readonly foreignKeys?: boolean;
55
+ }
56
+
57
+ export interface MigrationPlan {
58
+ /** The app Postgres schema the DDL targets (`app_<id>` or `public`). */
59
+ readonly appSchema: string;
60
+ /** Ordered DDL statements (expand → contract). Run in one transaction. */
61
+ readonly statements: readonly string[];
62
+ /** Post-commit, non-transactional DDL — see {@link ProvisionPlan.concurrent}. */
63
+ readonly concurrent?: readonly string[];
64
+ }
65
+
66
+ // ── Identifier safety ────────────────────────────────────────────────────────
67
+
68
+ /** Postgres unquoted-identifier-safe slug: lowercase `[a-z0-9_]`, ≤50 chars. */
69
+ function slug(raw: string): string {
70
+ const s = raw.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
71
+ return s.slice(0, 50) || 'x';
72
+ }
73
+
74
+ /** Per-app schema name for an app (organization) id. */
75
+ export function appSchemaName(organizationId: string): string {
76
+ return `app_${slug(organizationId)}`;
77
+ }
78
+
79
+ export function camelToSnake(identifier: string): string {
80
+ return identifier.replace(/[A-Z]/g, (ch) => `_${ch.toLowerCase()}`);
81
+ }
82
+
83
+ /**
84
+ * Converts snake_case to camelCase — the inverse of {@link camelToSnake}. This
85
+ * is the read-side translation: a column read back from a customer's own
86
+ * database maps to the same JavaScript field the SDK wrote, so
87
+ * `camelToSnake('operatorId') === 'operator_id'` and
88
+ * `snakeToCamel('operator_id') === 'operatorId'` round-trip.
89
+ */
90
+ export function snakeToCamel(identifier: string): string {
91
+ return identifier.replace(/_+([a-z0-9])/g, (_, ch: string) => ch.toUpperCase());
92
+ }
93
+
94
+ /** Quote an identifier (defense-in-depth; inputs are already slug/snake). */
95
+ export function q(identifier: string): string {
96
+ return `"${identifier.replace(/"/g, '""')}"`;
97
+ }
98
+
99
+ // ── Field type mapping ───────────────────────────────────────────────────────
100
+
101
+ export function sqlType(fieldType: ModelJSON['fields'][string]['type']): string {
102
+ switch (fieldType) {
103
+ case 'string':
104
+ case 'enum':
105
+ return 'TEXT';
106
+ case 'number':
107
+ // DOUBLE PRECISION, not INTEGER — a Zod `number` may be fractional and
108
+ // truncating to INTEGER is silent data loss.
109
+ return 'DOUBLE PRECISION';
110
+ case 'boolean':
111
+ return 'BOOLEAN';
112
+ case 'date':
113
+ return 'TIMESTAMPTZ';
114
+ case 'json':
115
+ default:
116
+ return 'JSONB';
117
+ }
118
+ }
119
+
120
+ const BASE_COLUMNS = new Set(['id', 'organization_id', 'created_by', 'created_at', 'updated_at']);
121
+
122
+ // ── Foreign keys (relation-driven, sync-safe) ────────────────────────────────
123
+
124
+ /**
125
+ * A Postgres-identifier-safe constraint name ≤63 bytes. When the natural
126
+ * `<table>_<col>_<suffix>` exceeds the limit, fall back to a deterministic
127
+ * hashed form so the name stays stable and matches what Postgres actually stores
128
+ * — a silently-truncated name would never match the DO-block existence guard,
129
+ * breaking idempotency (re-adds every push) and risking prefix collisions.
130
+ */
131
+ function constraintName(table: string, col: string, suffix: string): string {
132
+ const full = `${table}_${col}_${suffix}`;
133
+ if (full.length <= 63) return full;
134
+ let h = 5381;
135
+ for (let i = 0; i < full.length; i++) h = ((h * 33) + full.charCodeAt(i)) >>> 0;
136
+ const hash = h.toString(36);
137
+ const prefix = full.slice(0, Math.max(1, 63 - suffix.length - hash.length - 2));
138
+ return `${prefix}_${hash}_${suffix}`;
139
+ }
140
+
141
+ interface ForeignKeyDdl {
142
+ /** Run inside the provisioning transaction — instant `ADD ... NOT VALID` (no
143
+ * child-table scan, only a brief lock), plus the authoritative drop/recreate
144
+ * guard. */
145
+ readonly statements: string[];
146
+ /** Run after commit, each outside any transaction, best-effort: `VALIDATE
147
+ * CONSTRAINT` + `CREATE INDEX CONCURRENTLY` — validates existing rows and
148
+ * builds the child index without blocking writes on a large, live table. */
149
+ readonly concurrent: string[];
150
+ }
151
+
152
+ /**
153
+ * Builds the foreign-key constraints for a model's belongsTo relations that opt
154
+ * in by setting `{ fk: true }`.
155
+ *
156
+ * The `fk` marker is deliberately separate from `parent`: `parent` controls
157
+ * sync-group fan-out and visibility, while `fk` requests physical referential
158
+ * integrity in the database. A relation sets `fk` only when its target lives in
159
+ * the same database, is written in the same commit, and is a strong, contained
160
+ * entity. Soft references — provenance or template pointers such as
161
+ * `sourceSlideId` or `templateId` — stay plain columns; a hard foreign key there
162
+ * would reject a write that points across scopes or at an absent row and break
163
+ * sync.
164
+ *
165
+ * On a live, populated table a plain `ADD CONSTRAINT` takes a heavy lock and
166
+ * scans the whole child table, which would freeze writes on a customer's
167
+ * production database. To avoid that, the constraint is added `NOT VALID`
168
+ * (instant, no scan, brief lock) inside the transaction, and the existing-row
169
+ * check (`VALIDATE CONSTRAINT`, which allows concurrent writes) plus the child
170
+ * index (`CREATE INDEX CONCURRENTLY`) are returned separately in {@link
171
+ * ForeignKeyDdl.concurrent}, to run after commit, outside any transaction, and
172
+ * best-effort: if existing data violates a freshly added constraint the
173
+ * validation is skipped (logged, never fatal), the constraint still enforces
174
+ * every new write, and nothing is destroyed.
175
+ *
176
+ * The constraint is a `DEFERRABLE INITIALLY DEFERRED` integrity guard with `ON
177
+ * DELETE NO ACTION`; it never mutates a child row itself. A `SET NULL` or
178
+ * `CASCADE` action would change data in the database with no matching
179
+ * sync_delta — invisible to other clients until they re-bootstrap — and would
180
+ * override the application layer's own onDelete handling. The application layer
181
+ * owns deletes and nullification and emits the deltas; the deferred check only
182
+ * verifies, at commit time (so a same-batch child-before-parent write and the
183
+ * application's own cascade both pass), that integrity holds, failing loudly
184
+ * only when a dangling reference is left behind.
185
+ *
186
+ * Emission is idempotent and authoritative: a same-named constraint that is not
187
+ * deferrable or carries the wrong delete action (a hand-added or older foreign
188
+ * key) is dropped and recreated, while an already-correct one is left untouched
189
+ * with no revalidation cost. It runs in a final pass, after every referenced
190
+ * table exists.
191
+ *
192
+ * The foreign-key column is resolved the same way the table loop names columns
193
+ * (`fieldMeta.column ?? camelToSnake(field)`), not from `rel.foreignKeyColumn`:
194
+ * the table loop ignores relation casing, so trusting `foreignKeyColumn` would
195
+ * mismatch the real column whenever `casing` is unset.
196
+ */
197
+ function foreignKeyStatements(
198
+ table: string,
199
+ model: ModelJSON,
200
+ models: SchemaJSON['models'],
201
+ qs: string,
202
+ ): ForeignKeyDdl {
203
+ const qt = `${qs}.${q(table)}`;
204
+ // The model's provisioned column set — guard so a relation whose FK field
205
+ // isn't actually declared (no column) never produces a broken ALTER.
206
+ const orgCol = tenancyColumn(resolveTenancy(model));
207
+ const columns = new Set<string>(['id', 'created_by', 'created_at', 'updated_at']);
208
+ if (orgCol) columns.add(orgCol);
209
+ for (const [fieldName, meta] of Object.entries(model.fields)) {
210
+ columns.add(meta.column ?? camelToSnake(fieldName));
211
+ }
212
+
213
+ const statements: string[] = [];
214
+ const concurrent: string[] = [];
215
+ for (const rel of Object.values(model.relations)) {
216
+ if (rel.type !== 'belongsTo') continue; // only relations whose FK column lives on this table
217
+ if (rel.options?.fk !== true) continue; // explicit `fk` marker — decoupled from `parent` (visibility)
218
+ const targetModel = models[rel.target];
219
+ if (!targetModel) continue; // target not provisioned into this DB → can't reference it
220
+ if ((targetModel.plane ?? 'tenant') === 'control') continue; // control-plane table absent in a tenant DB
221
+ const col = model.fields[rel.foreignKey]?.column ?? camelToSnake(rel.foreignKey);
222
+ if (!columns.has(col)) continue; // FK field isn't a provisioned column
223
+ const targetTable = targetModel.tableName ?? rel.target;
224
+ const cname = constraintName(table, col, 'fkey');
225
+ const lit = cname.replace(/'/g, "''");
226
+ const iname = constraintName(table, col, 'idx');
227
+ const targetQt = `${qs}.${q(targetTable)}`;
228
+ // In-tx: authoritative create as NOT VALID — instant, no child-table scan,
229
+ // only a brief lock. confdeltype 'a' = NO ACTION; recreate only when absent /
230
+ // not deferrable / wrong delete action, so a correct constraint is untouched.
231
+ statements.push(
232
+ `DO $$ BEGIN\n` +
233
+ ` IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '${lit}' AND (NOT condeferrable OR confdeltype <> 'a')) THEN\n` +
234
+ ` ALTER TABLE ${qt} DROP CONSTRAINT ${q(cname)};\n` +
235
+ ` END IF;\n` +
236
+ ` IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '${lit}') THEN\n` +
237
+ ` ALTER TABLE ${qt} ADD CONSTRAINT ${q(cname)} FOREIGN KEY (${q(col)}) ` +
238
+ `REFERENCES ${targetQt} (${q('id')}) ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED NOT VALID;\n` +
239
+ ` END IF;\nEND $$;`,
240
+ );
241
+ // Post-commit, non-blocking: validate existing rows (SHARE UPDATE EXCLUSIVE,
242
+ // allows concurrent writes) then index the child column (Postgres does not
243
+ // auto-index the referencing column → parent deletes would seq-scan it).
244
+ concurrent.push(`ALTER TABLE ${qt} VALIDATE CONSTRAINT ${q(cname)};`);
245
+ concurrent.push(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${q(iname)} ON ${qt} (${q(col)});`);
246
+ }
247
+ return { statements, concurrent };
248
+ }
249
+
250
+ // ── Provisioning (additive, idempotent) ─────────────────────────────────────
251
+
252
+ /**
253
+ * Builds the additive, idempotent provisioning plan for an app. Pure — it does
254
+ * not touch a database.
255
+ *
256
+ * `targetSchema` is where the tables live: a per-app Postgres schema such as
257
+ * `app_<id>`, or `public` when the database itself is the isolation boundary
258
+ * (for example a customer's own database). For `public` the `CREATE SCHEMA`
259
+ * statement is skipped, since it always exists.
260
+ */
261
+ export function generateProvisionPlan(
262
+ schema: SchemaJSON,
263
+ targetSchema: string,
264
+ opts: ProvisionOptions = {},
265
+ ): ProvisionPlan {
266
+ const appSchema = targetSchema;
267
+ const qs = q(appSchema);
268
+ const statements: string[] = appSchema === 'public' ? [] : [`CREATE SCHEMA IF NOT EXISTS ${qs};`];
269
+ const concurrent: string[] = [];
270
+
271
+ for (const [key, model] of Object.entries(schema.models)) {
272
+ // Control-plane models (the engine's own sync log, attribution, and audit
273
+ // tables) are never emitted into a tenant database — only `tenant`-plane
274
+ // models are. A model with no declared plane defaults to `tenant`. This
275
+ // declared boundary is what makes the set of tables a customer's own
276
+ // database receives derivable instead of hand-coded.
277
+ if ((model.plane ?? 'tenant') === 'control') continue;
278
+
279
+ // Default the physical table to the model key when `tableName` is omitted —
280
+ // same fallback the migration path uses (`tableOfModel: m.tableName ?? key`).
281
+ // Without this, a schema that doesn't set `tableName` (e.g. the `ablo init`
282
+ // starter) provisions zero tables.
283
+ const table = model.tableName ?? key;
284
+ const qt = `${qs}.${q(table)}`;
285
+
286
+ // Base columns are schema-driven, not blanket. `organization_id` (and its
287
+ // index + tenant-isolation RLS below) is emitted only for org-scoped models.
288
+ // A model that declares `orgScoped: false` (users, organizations, and other
289
+ // tables scoped via a FK / app layer) genuinely has no `organization_id`
290
+ // column — forcing one would add a NOT NULL column that fails on existing
291
+ // rows and contradicts the model's own declaration.
292
+ // Tenancy column: present only for column-scoped models, with the
293
+ // configured name (default `organization_id`). `parent`/`none` tenancy emit
294
+ // no tenancy column — they're scoped via a parent FK or not at all.
295
+ const orgCol = tenancyColumn(resolveTenancy(model));
296
+ const baseColumns = [
297
+ ` ${q('id')} TEXT PRIMARY KEY,`,
298
+ ...(orgCol ? [` ${q(orgCol)} TEXT NOT NULL,`] : []),
299
+ ` ${q('created_by')} TEXT,`,
300
+ ` ${q('created_at')} TIMESTAMPTZ NOT NULL DEFAULT NOW(),`,
301
+ ` ${q('updated_at')} TIMESTAMPTZ NOT NULL DEFAULT NOW()`,
302
+ ];
303
+ statements.push(`CREATE TABLE IF NOT EXISTS ${qt} (\n${baseColumns.join('\n')}\n);`);
304
+
305
+ for (const [fieldName, meta] of Object.entries(model.fields)) {
306
+ const col = meta.column ?? camelToSnake(fieldName);
307
+ if (BASE_COLUMNS.has(col) || col === orgCol) continue;
308
+ statements.push(`ALTER TABLE ${qt} ADD COLUMN IF NOT EXISTS ${q(col)} ${sqlType(meta.type)};`);
309
+ if (meta.type === 'enum' && meta.enumValues && meta.enumValues.length > 0) {
310
+ const cname = `${table}_${col}_enum`;
311
+ const allowed = meta.enumValues.map((v) => `'${v.replace(/'/g, "''")}'`).join(', ');
312
+ statements.push(
313
+ `DO $$ BEGIN\n` +
314
+ ` IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '${cname}') THEN\n` +
315
+ ` ALTER TABLE ${qt} ADD CONSTRAINT ${q(cname)} CHECK (${q(col)} IN (${allowed}));\n` +
316
+ ` END IF;\n` +
317
+ `END $$;`,
318
+ );
319
+ }
320
+ }
321
+
322
+ // Org index + tenant-isolation RLS only where there's an `organization_id`
323
+ // to isolate on. Non-org-scoped tables rely on FK/app-layer scoping.
324
+ if (orgCol) {
325
+ statements.push(
326
+ `CREATE INDEX IF NOT EXISTS ${q(`${table}_${orgCol}_idx`)} ON ${qt} (${q(orgCol)});`,
327
+ );
328
+ statements.push(`ALTER TABLE ${qt} ENABLE ROW LEVEL SECURITY;`);
329
+ statements.push(`ALTER TABLE ${qt} FORCE ROW LEVEL SECURITY;`);
330
+ const policy = `${table}_tenant_isolation`;
331
+ const predicate = `${q(orgCol)} = current_setting('app.current_org_id', true)`;
332
+ statements.push(`DROP POLICY IF EXISTS ${q(policy)} ON ${qt};`);
333
+ statements.push(`CREATE POLICY ${q(policy)} ON ${qt}\n USING (${predicate})\n WITH CHECK (${predicate});`);
334
+ }
335
+ }
336
+
337
+ // Foreign keys (opt-in) — a final pass so every referenced table already
338
+ // exists when its constraint is added.
339
+ if (opts.foreignKeys) {
340
+ for (const [key, m] of Object.entries(schema.models)) {
341
+ if ((m.plane ?? 'tenant') === 'control') continue;
342
+ const t = m.tableName ?? key;
343
+ const fk = foreignKeyStatements(t, m, schema.models, qs);
344
+ statements.push(...fk.statements);
345
+ concurrent.push(...fk.concurrent);
346
+ }
347
+ }
348
+
349
+ return { appSchema, statements, concurrent };
350
+ }
351
+
352
+ // ── Migration (destructive-aware, diff-driven) ──────────────────────────────
353
+
354
+ function enumCheckStatements(table: string, col: string, qt: string, values: readonly string[]): string[] {
355
+ const cname = `${table}_${col}_enum`;
356
+ const stmts = [`ALTER TABLE ${qt} DROP CONSTRAINT IF EXISTS ${q(cname)};`];
357
+ if (values.length > 0) {
358
+ const allowed = values.map((v) => `'${v.replace(/'/g, "''")}'`).join(', ');
359
+ stmts.push(`ALTER TABLE ${qt} ADD CONSTRAINT ${q(cname)} CHECK (${q(col)} IN (${allowed}));`);
360
+ }
361
+ return stmts;
362
+ }
363
+
364
+ function indexName(table: string, col: string): string {
365
+ return `${table}_${col}_idx`;
366
+ }
367
+
368
+ function columnNameOf(fieldName: string, meta: Pick<FieldMeta, 'column'> | undefined): string {
369
+ return meta?.column ?? camelToSnake(fieldName);
370
+ }
371
+
372
+ /**
373
+ * Encode a constant backfill value as a typed SQL literal. Inputs are operator-
374
+ * supplied (via the authed push), but we still encode by the field's declared
375
+ * type and escape strings rather than interpolate raw — defense-in-depth.
376
+ */
377
+ function sqlLiteral(value: BackfillValue['value'], fieldType: FieldType): string {
378
+ switch (fieldType) {
379
+ case 'number':
380
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
381
+ throw new AbloValidationError(`backfill for a number field must be a finite number, got ${JSON.stringify(value)}`, { code: 'schema_definition_invalid' });
382
+ }
383
+ return String(value);
384
+ case 'boolean':
385
+ return value ? 'TRUE' : 'FALSE';
386
+ case 'date':
387
+ return `'${String(value).replace(/'/g, "''")}'::timestamptz`;
388
+ case 'json':
389
+ return `'${JSON.stringify(value).replace(/'/g, "''")}'::jsonb`;
390
+ case 'string':
391
+ case 'enum':
392
+ default:
393
+ return `'${String(value).replace(/'/g, "''")}'`;
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Lower an ordered migration step list to DDL. `next` is the schema being pushed
399
+ * (the target column shapes are read from it), `prev` the active one (used to
400
+ * resolve the *old* table name on a model rename).
401
+ */
402
+ export function generateMigrationPlan(
403
+ steps: readonly MigrationStep[],
404
+ opts: {
405
+ readonly prev: SchemaJSON | null;
406
+ readonly next: SchemaJSON;
407
+ readonly targetSchema: string;
408
+ /** Constant seed values that let a required-field add / made-required step
409
+ * set NOT NULL on a non-empty table. Keyed by (model, field). */
410
+ readonly backfills?: readonly BackfillValue[];
411
+ /** Emit deferrable foreign-key constraints for the relations that opt in.
412
+ * Off by default — see {@link ProvisionOptions.foreignKeys}. */
413
+ readonly foreignKeys?: boolean;
414
+ },
415
+ ): MigrationPlan {
416
+ const { prev, next, targetSchema, backfills = [], foreignKeys = false } = opts;
417
+ const qs = q(targetSchema);
418
+ const statements: string[] = [];
419
+ const concurrent: string[] = [];
420
+
421
+ // The app schema must exist before any statement targets it. On a fresh
422
+ // org's first push (`prev = null`) the migration plan is the provisioning —
423
+ // `app_<orgId>` has never been created, and skipping this line made every
424
+ // first push die with `3F000 invalid_schema_name` at statement 0. Idempotent
425
+ // (`IF NOT EXISTS`), so emitting it on every later migration is free.
426
+ if (steps.length > 0 && targetSchema !== 'public') {
427
+ statements.push(`CREATE SCHEMA IF NOT EXISTS ${qs};`);
428
+ }
429
+
430
+ const qtFor = (table: string) => `${qs}.${q(table)}`;
431
+ const tableOfModel = (schema: SchemaJSON | null, key: string): string | null => {
432
+ const m = schema?.models[key];
433
+ if (!m) return null;
434
+ return m.tableName ?? key;
435
+ };
436
+ const backfillFor = (model: string, field: string): BackfillValue | undefined =>
437
+ backfills.find((b) => b.model === model && b.field === field);
438
+
439
+ for (const step of steps) {
440
+ switch (step.kind) {
441
+ case 'create_model': {
442
+ // Reuse the provisioner for the full table (base cols + fields + enum
443
+ // checks + RLS), minus its `CREATE SCHEMA` (the plan header above
444
+ // already emitted it once — don't repeat it per model).
445
+ const def = next.models[step.model];
446
+ if (!def) break;
447
+ const sub: SchemaJSON = { v: next.v, models: { [step.model]: def }, identityRoles: next.identityRoles };
448
+ for (const s of generateProvisionPlan(sub, targetSchema).statements) {
449
+ if (!s.startsWith('CREATE SCHEMA')) statements.push(s);
450
+ }
451
+ break;
452
+ }
453
+
454
+ case 'drop_model':
455
+ statements.push(`DROP TABLE IF EXISTS ${qtFor(step.tableName)};`);
456
+ break;
457
+
458
+ case 'rename_model': {
459
+ const fromTable = tableOfModel(prev, step.from);
460
+ const toTable = tableOfModel(next, step.to);
461
+ // A logical model rename only needs SQL when the physical table name
462
+ // actually changes; if tableName is unchanged the rename is metadata.
463
+ if (fromTable && toTable && fromTable !== toTable) {
464
+ statements.push(`ALTER TABLE ${qtFor(fromTable)} RENAME TO ${q(toTable)};`);
465
+ }
466
+ break;
467
+ }
468
+
469
+ case 'add_field': {
470
+ const table = tableOfModel(next, step.model);
471
+ if (!table) break;
472
+ const qt = qtFor(table);
473
+ const col = columnNameOf(step.field, step.meta);
474
+ // Added nullable first (the column is born NULL on every existing row).
475
+ statements.push(`ALTER TABLE ${qt} ADD COLUMN IF NOT EXISTS ${q(col)} ${sqlType(step.meta.type)};`);
476
+ if (step.meta.type === 'enum' && step.meta.enumValues?.length) {
477
+ statements.push(...enumCheckStatements(table, col, qt, step.meta.enumValues));
478
+ }
479
+ // Backfill + enforce NOT NULL only with a supplied seed value. Without
480
+ // one, a required field stays nullable (gated `unexecutable` upstream).
481
+ const addBf = backfillFor(step.model, step.field);
482
+ if (addBf !== undefined) {
483
+ statements.push(`UPDATE ${qt} SET ${q(col)} = ${sqlLiteral(addBf.value, step.meta.type)} WHERE ${q(col)} IS NULL;`);
484
+ if (!step.meta.isOptional) {
485
+ statements.push(`ALTER TABLE ${qt} ALTER COLUMN ${q(col)} SET NOT NULL;`);
486
+ }
487
+ }
488
+ if (step.meta.isIndexed) {
489
+ statements.push(`CREATE INDEX IF NOT EXISTS ${q(indexName(table, col))} ON ${qt} (${q(col)});`);
490
+ }
491
+ break;
492
+ }
493
+
494
+ case 'drop_field': {
495
+ const table = tableOfModel(next, step.model);
496
+ if (!table) break;
497
+ const prevMeta = prev?.models[step.model]?.fields[step.field];
498
+ statements.push(`ALTER TABLE ${qtFor(table)} DROP COLUMN IF EXISTS ${q(columnNameOf(step.field, prevMeta))};`);
499
+ break;
500
+ }
501
+
502
+ case 'rename_field': {
503
+ const table = tableOfModel(next, step.model);
504
+ if (!table) break;
505
+ const prevMeta = prev?.models[step.model]?.fields[step.from];
506
+ const nextMeta = next.models[step.model]?.fields[step.to];
507
+ const fromCol = columnNameOf(step.from, prevMeta);
508
+ const toCol = columnNameOf(step.to, nextMeta);
509
+ if (fromCol === toCol) break;
510
+ statements.push(`ALTER TABLE ${qtFor(table)} RENAME COLUMN ${q(fromCol)} TO ${q(toCol)};`);
511
+ break;
512
+ }
513
+
514
+ case 'alter_field': {
515
+ const table = tableOfModel(next, step.model);
516
+ if (!table) break;
517
+ const qt = qtFor(table);
518
+ const nextMeta = next.models[step.model]?.fields[step.field];
519
+ let col = columnNameOf(step.field, nextMeta);
520
+ const ch = step.changes;
521
+
522
+ // 0. Physical column rename. Subsequent alterations must address
523
+ // the new name.
524
+ if (ch.column) {
525
+ statements.push(`ALTER TABLE ${qt} RENAME COLUMN ${q(ch.column.from)} TO ${q(ch.column.to)};`);
526
+ col = ch.column.to;
527
+ }
528
+
529
+ // 1. Type — in-place cast or lossy drop-and-recreate.
530
+ if (ch.type) {
531
+ const target = sqlType(ch.type.to);
532
+ if (ch.type.cast === 'notCastable') {
533
+ statements.push(`ALTER TABLE ${qt} DROP COLUMN IF EXISTS ${q(col)};`);
534
+ statements.push(`ALTER TABLE ${qt} ADD COLUMN IF NOT EXISTS ${q(col)} ${target};`);
535
+ } else {
536
+ statements.push(`ALTER TABLE ${qt} ALTER COLUMN ${q(col)} TYPE ${target} USING ${q(col)}::${target};`);
537
+ }
538
+ }
539
+
540
+ // 2. Enum CHECK — drop when leaving enum; (re)build when arriving at or
541
+ // re-valuing an enum. Reads the full target value set from `next`.
542
+ if (ch.type?.from === 'enum' && nextMeta?.type !== 'enum') {
543
+ statements.push(`ALTER TABLE ${qt} DROP CONSTRAINT IF EXISTS ${q(`${table}_${col}_enum`)};`);
544
+ } else if (nextMeta?.type === 'enum' && (ch.enumValues || ch.type)) {
545
+ statements.push(...enumCheckStatements(table, col, qt, nextMeta.enumValues ?? []));
546
+ }
547
+
548
+ // 3. Nullability. DROP NOT NULL is always safe. SET NOT NULL is gated
549
+ // upstream (unexecutable on a table with NULLs); a supplied backfill
550
+ // seeds the existing NULLs first so the constraint can take.
551
+ if (ch.nullability) {
552
+ if (ch.nullability.toOptional) {
553
+ statements.push(`ALTER TABLE ${qt} ALTER COLUMN ${q(col)} DROP NOT NULL;`);
554
+ } else {
555
+ const bf = backfillFor(step.model, step.field);
556
+ if (bf !== undefined && nextMeta) {
557
+ statements.push(`UPDATE ${qt} SET ${q(col)} = ${sqlLiteral(bf.value, nextMeta.type)} WHERE ${q(col)} IS NULL;`);
558
+ }
559
+ statements.push(`ALTER TABLE ${qt} ALTER COLUMN ${q(col)} SET NOT NULL;`);
560
+ }
561
+ }
562
+
563
+ // 4. Index.
564
+ if (ch.indexed) {
565
+ statements.push(
566
+ ch.indexed.to
567
+ ? `CREATE INDEX IF NOT EXISTS ${q(indexName(table, col))} ON ${qt} (${q(col)});`
568
+ : `DROP INDEX IF EXISTS ${qs}.${q(indexName(table, col))};`,
569
+ );
570
+ }
571
+ break;
572
+ }
573
+ }
574
+ }
575
+
576
+ // Foreign keys (opt-in). Reconcile against the full `next` schema, not just
577
+ // create_model steps: a parent edge added to an existing model surfaces only as
578
+ // an add_field (relation changes aren't diffed), so a create_model-only pass
579
+ // would never materialize its FK. The DO-block is authoritative + idempotent
580
+ // (a no-op when the constraint is already correct), so emitting the full set
581
+ // each push is cheap and self-healing. Appended after every table/column step.
582
+ if (foreignKeys) {
583
+ for (const [key, def] of Object.entries(next.models)) {
584
+ if ((def.plane ?? 'tenant') === 'control') continue;
585
+ const table = def.tableName ?? key;
586
+ const fk = foreignKeyStatements(table, def, next.models, qs);
587
+ statements.push(...fk.statements);
588
+ concurrent.push(...fk.concurrent);
589
+ }
590
+ }
591
+
592
+ return { appSchema: targetSchema, statements, concurrent };
593
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Canonical lock settings for schema-change (DDL) statements. When a schema push alters a
3
+ * table, these values control how quickly the change gives up on a contended
4
+ * lock and how many times it retries. The command-line `ablo migrate` and the
5
+ * host that applies a schema push both resolve their lock behavior through this
6
+ * module, so tuning the environment variables below changes both paths the same
7
+ * way.
8
+ *
9
+ * The defaults follow the standard safe-migration recipe: a short `lock_timeout`
10
+ * so a blocked `ALTER` aborts quickly instead of parking an `ACCESS EXCLUSIVE`
11
+ * lock request at the head of the queue — which would freeze every other query
12
+ * on that table behind it — paired with a bounded retry-and-backoff on the
13
+ * resulting timeout.
14
+ *
15
+ * The environment variables are read each time a resolver is called, not once
16
+ * at import, so a long-running process or a test that changes them sees the
17
+ * update: `ABLO_SCHEMA_LOCK_TIMEOUT` and `ABLO_SCHEMA_LOCK_ATTEMPTS`. The older
18
+ * `ABLO_DDL_*` names are also accepted.
19
+ */
20
+
21
+ /** The Postgres SQLSTATE `55P03` (`lock_not_available`), raised when a statement
22
+ * gives up waiting for a lock after `lock_timeout`. This is the one DDL failure
23
+ * worth retrying; any other error is a genuine problem. */
24
+ export const PG_LOCK_NOT_AVAILABLE = '55P03';
25
+
26
+ const DEFAULT_LOCK_TIMEOUT = '5s';
27
+ const DEFAULT_MAX_LOCK_ATTEMPTS = 5;
28
+
29
+ /** The subset of environment variables the resolvers in this module read. It is
30
+ * passed in explicitly so tests can supply their own values. */
31
+ export type DdlLockEnv = Readonly<Record<string, string | undefined>>;
32
+
33
+ /** `lock_timeout` for the DDL transaction (a Postgres duration string). */
34
+ export function resolveDdlLockTimeout(env: DdlLockEnv = process.env): string {
35
+ return env.ABLO_SCHEMA_LOCK_TIMEOUT ?? env.ABLO_DDL_LOCK_TIMEOUT ?? DEFAULT_LOCK_TIMEOUT;
36
+ }
37
+
38
+ /** How many times the whole DDL transaction is attempted on `55P03` lock
39
+ * contention. Always ≥ 1; a malformed value falls back to the default
40
+ * instead of silently disabling retries. */
41
+ export function resolveDdlMaxLockAttempts(env: DdlLockEnv = process.env): number {
42
+ const raw = env.ABLO_SCHEMA_LOCK_ATTEMPTS ?? env.ABLO_DDL_LOCK_ATTEMPTS;
43
+ if (raw === undefined) return DEFAULT_MAX_LOCK_ATTEMPTS;
44
+ const parsed = Number(raw);
45
+ if (!Number.isFinite(parsed)) return DEFAULT_MAX_LOCK_ATTEMPTS;
46
+ return Math.max(1, Math.floor(parsed));
47
+ }
48
+
49
+ /** Backoff before retry N (1-based): capped exponential + a little jitter so
50
+ * two contending migrators don't re-collide in lockstep. */
51
+ export function ddlLockRetryBackoffMs(attempt: number): number {
52
+ return Math.min(60_000, 10 * 2 ** attempt) + Math.floor(Math.random() * 50);
53
+ }