@opensaas/stack-core 0.43.0 → 0.44.0-alpha.2

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 (641) hide show
  1. package/CHANGELOG.md +2753 -0
  2. package/README.md +182 -115
  3. package/dist/.build-hash +1 -0
  4. package/dist/access/declared-dependencies.d.ts +102 -88
  5. package/dist/access/declared-dependencies.d.ts.map +1 -1
  6. package/dist/access/declared-dependencies.js +83 -71
  7. package/dist/access/declared-dependencies.js.map +1 -1
  8. package/dist/access/depth-limits.d.ts +4 -0
  9. package/dist/access/depth-limits.d.ts.map +1 -1
  10. package/dist/access/depth-limits.js +4 -0
  11. package/dist/access/depth-limits.js.map +1 -1
  12. package/dist/access/engine.d.ts +68 -20
  13. package/dist/access/engine.d.ts.map +1 -1
  14. package/dist/access/engine.js +151 -37
  15. package/dist/access/engine.js.map +1 -1
  16. package/dist/access/errors.d.ts +33 -48
  17. package/dist/access/errors.d.ts.map +1 -1
  18. package/dist/access/errors.js +73 -63
  19. package/dist/access/errors.js.map +1 -1
  20. package/dist/access/field-access.d.ts +76 -5
  21. package/dist/access/field-access.d.ts.map +1 -1
  22. package/dist/access/field-access.js +235 -61
  23. package/dist/access/field-access.js.map +1 -1
  24. package/dist/access/field-visibility.d.ts +50 -4
  25. package/dist/access/field-visibility.d.ts.map +1 -1
  26. package/dist/access/field-visibility.js +143 -160
  27. package/dist/access/field-visibility.js.map +1 -1
  28. package/dist/access/index.d.ts +5 -12
  29. package/dist/access/index.d.ts.map +1 -1
  30. package/dist/access/index.js +6 -19
  31. package/dist/access/index.js.map +1 -1
  32. package/dist/access/orm-client.d.ts +19 -0
  33. package/dist/access/orm-client.d.ts.map +1 -0
  34. package/dist/access/orm-client.js +37 -0
  35. package/dist/access/orm-client.js.map +1 -0
  36. package/dist/access/query-validation.d.ts +7 -129
  37. package/dist/access/query-validation.d.ts.map +1 -1
  38. package/dist/access/query-validation.js +12 -314
  39. package/dist/access/query-validation.js.map +1 -1
  40. package/dist/access/system-fields.d.ts +2 -0
  41. package/dist/access/system-fields.d.ts.map +1 -0
  42. package/dist/access/system-fields.js +7 -0
  43. package/dist/access/system-fields.js.map +1 -0
  44. package/dist/access/transaction-registry.d.ts +25 -2
  45. package/dist/access/transaction-registry.d.ts.map +1 -1
  46. package/dist/access/transaction-registry.js +34 -17
  47. package/dist/access/transaction-registry.js.map +1 -1
  48. package/dist/access/types.d.ts +217 -131
  49. package/dist/access/types.d.ts.map +1 -1
  50. package/dist/config/field-kind.d.ts +66 -0
  51. package/dist/config/field-kind.d.ts.map +1 -0
  52. package/dist/config/field-kind.js +63 -0
  53. package/dist/config/field-kind.js.map +1 -0
  54. package/dist/config/hook-only-fields.d.ts +3 -0
  55. package/dist/config/hook-only-fields.d.ts.map +1 -0
  56. package/dist/config/hook-only-fields.js +17 -0
  57. package/dist/config/hook-only-fields.js.map +1 -0
  58. package/dist/config/index.d.ts +3 -1
  59. package/dist/config/index.d.ts.map +1 -1
  60. package/dist/config/index.js +6 -3
  61. package/dist/config/index.js.map +1 -1
  62. package/dist/config/mcp-tool-names.d.ts +3 -0
  63. package/dist/config/mcp-tool-names.d.ts.map +1 -0
  64. package/dist/config/mcp-tool-names.js +25 -0
  65. package/dist/config/mcp-tool-names.js.map +1 -0
  66. package/dist/config/nav-count.d.ts.map +1 -1
  67. package/dist/config/nav-count.js +4 -4
  68. package/dist/config/nav-count.js.map +1 -1
  69. package/dist/config/plugin-engine.d.ts +8 -2
  70. package/dist/config/plugin-engine.d.ts.map +1 -1
  71. package/dist/config/plugin-engine.js +102 -38
  72. package/dist/config/plugin-engine.js.map +1 -1
  73. package/dist/config/types.d.ts +1035 -611
  74. package/dist/config/types.d.ts.map +1 -1
  75. package/dist/context/apply-defaults.d.ts +18 -1
  76. package/dist/context/apply-defaults.d.ts.map +1 -1
  77. package/dist/context/apply-defaults.js +30 -4
  78. package/dist/context/apply-defaults.js.map +1 -1
  79. package/dist/context/engine-context.d.ts +73 -0
  80. package/dist/context/engine-context.d.ts.map +1 -0
  81. package/dist/context/engine-context.js +67 -0
  82. package/dist/context/engine-context.js.map +1 -0
  83. package/dist/context/hook-pipeline.d.ts +9 -2
  84. package/dist/context/hook-pipeline.d.ts.map +1 -1
  85. package/dist/context/hook-pipeline.js +5 -4
  86. package/dist/context/hook-pipeline.js.map +1 -1
  87. package/dist/context/index.d.ts +98 -89
  88. package/dist/context/index.d.ts.map +1 -1
  89. package/dist/context/index.js +917 -722
  90. package/dist/context/index.js.map +1 -1
  91. package/dist/context/junction.d.ts +59 -0
  92. package/dist/context/junction.d.ts.map +1 -0
  93. package/dist/context/junction.js +126 -0
  94. package/dist/context/junction.js.map +1 -0
  95. package/dist/context/plugin-field-read.d.ts +33 -0
  96. package/dist/context/plugin-field-read.d.ts.map +1 -0
  97. package/dist/context/plugin-field-read.js +41 -0
  98. package/dist/context/plugin-field-read.js.map +1 -0
  99. package/dist/context/plugin-field-write.d.ts +104 -0
  100. package/dist/context/plugin-field-write.d.ts.map +1 -0
  101. package/dist/context/plugin-field-write.js +184 -0
  102. package/dist/context/plugin-field-write.js.map +1 -0
  103. package/dist/context/relationship-input.d.ts +146 -0
  104. package/dist/context/relationship-input.d.ts.map +1 -0
  105. package/dist/context/relationship-input.js +453 -0
  106. package/dist/context/relationship-input.js.map +1 -0
  107. package/dist/context/transaction-boundary.d.ts +54 -28
  108. package/dist/context/transaction-boundary.d.ts.map +1 -1
  109. package/dist/context/transaction-boundary.js +87 -169
  110. package/dist/context/transaction-boundary.js.map +1 -1
  111. package/dist/context/write-pipeline.d.ts +33 -51
  112. package/dist/context/write-pipeline.d.ts.map +1 -1
  113. package/dist/context/write-pipeline.js +372 -185
  114. package/dist/context/write-pipeline.js.map +1 -1
  115. package/dist/contract/dependencies.d.ts +88 -0
  116. package/dist/contract/dependencies.d.ts.map +1 -0
  117. package/dist/contract/dependencies.js +237 -0
  118. package/dist/contract/dependencies.js.map +1 -0
  119. package/dist/contract/derive.d.ts +49 -0
  120. package/dist/contract/derive.d.ts.map +1 -0
  121. package/dist/contract/derive.js +629 -0
  122. package/dist/contract/derive.js.map +1 -0
  123. package/dist/contract/fixtures/contract-configs.d.ts +64 -0
  124. package/dist/contract/fixtures/contract-configs.d.ts.map +1 -0
  125. package/dist/contract/fixtures/contract-configs.js +345 -0
  126. package/dist/contract/fixtures/contract-configs.js.map +1 -0
  127. package/dist/contract/id-boundary.d.ts +53 -0
  128. package/dist/contract/id-boundary.d.ts.map +1 -0
  129. package/dist/contract/id-boundary.js +76 -0
  130. package/dist/contract/id-boundary.js.map +1 -0
  131. package/dist/contract/index.d.ts +8 -0
  132. package/dist/contract/index.d.ts.map +1 -0
  133. package/dist/contract/index.js +11 -0
  134. package/dist/contract/index.js.map +1 -0
  135. package/dist/contract/prisma.d.ts +58 -0
  136. package/dist/contract/prisma.d.ts.map +1 -0
  137. package/dist/contract/prisma.js +294 -0
  138. package/dist/contract/prisma.js.map +1 -0
  139. package/dist/contract/relation-graph.d.ts +70 -0
  140. package/dist/contract/relation-graph.d.ts.map +1 -0
  141. package/dist/contract/relation-graph.js +113 -0
  142. package/dist/contract/relation-graph.js.map +1 -0
  143. package/dist/contract/types.d.ts +153 -0
  144. package/dist/contract/types.d.ts.map +1 -0
  145. package/dist/contract/types.js +2 -0
  146. package/dist/contract/types.js.map +1 -0
  147. package/dist/db/client.d.ts +55 -0
  148. package/dist/db/client.d.ts.map +1 -0
  149. package/dist/db/client.js +73 -0
  150. package/dist/db/client.js.map +1 -0
  151. package/dist/db/dev-database.d.ts +124 -0
  152. package/dist/db/dev-database.d.ts.map +1 -0
  153. package/dist/db/dev-database.js +291 -0
  154. package/dist/db/dev-database.js.map +1 -0
  155. package/dist/db/password-front.d.ts +10 -0
  156. package/dist/db/password-front.d.ts.map +1 -0
  157. package/dist/db/password-front.js +147 -0
  158. package/dist/db/password-front.js.map +1 -0
  159. package/dist/db/process-identity.d.ts +36 -0
  160. package/dist/db/process-identity.d.ts.map +1 -0
  161. package/dist/db/process-identity.js +114 -0
  162. package/dist/db/process-identity.js.map +1 -0
  163. package/dist/db/state-file.d.ts +54 -0
  164. package/dist/db/state-file.d.ts.map +1 -0
  165. package/dist/db/state-file.js +91 -0
  166. package/dist/db/state-file.js.map +1 -0
  167. package/dist/db/url.d.ts +89 -0
  168. package/dist/db/url.d.ts.map +1 -0
  169. package/dist/db/url.js +118 -0
  170. package/dist/db/url.js.map +1 -0
  171. package/dist/extend.d.ts +13 -2
  172. package/dist/extend.d.ts.map +1 -1
  173. package/dist/extend.js +24 -1
  174. package/dist/extend.js.map +1 -1
  175. package/dist/fields/index.d.ts +87 -42
  176. package/dist/fields/index.d.ts.map +1 -1
  177. package/dist/fields/index.js +462 -678
  178. package/dist/fields/index.js.map +1 -1
  179. package/dist/filter/collect.d.ts +3 -4
  180. package/dist/filter/collect.d.ts.map +1 -1
  181. package/dist/filter/collect.js +2 -2
  182. package/dist/filter/collect.js.map +1 -1
  183. package/dist/filter/index.d.ts +1 -2
  184. package/dist/filter/index.d.ts.map +1 -1
  185. package/dist/filter/index.js +0 -1
  186. package/dist/filter/index.js.map +1 -1
  187. package/dist/filter/map.d.ts +12 -5
  188. package/dist/filter/map.d.ts.map +1 -1
  189. package/dist/filter/map.js +47 -19
  190. package/dist/filter/map.js.map +1 -1
  191. package/dist/filter/types.d.ts +10 -24
  192. package/dist/filter/types.d.ts.map +1 -1
  193. package/dist/filter/types.js +2 -11
  194. package/dist/filter/types.js.map +1 -1
  195. package/dist/hooks/index.d.ts +22 -31
  196. package/dist/hooks/index.d.ts.map +1 -1
  197. package/dist/hooks/index.js +33 -37
  198. package/dist/hooks/index.js.map +1 -1
  199. package/dist/hooks/transition-guard.d.ts +61 -0
  200. package/dist/hooks/transition-guard.d.ts.map +1 -0
  201. package/dist/hooks/transition-guard.js +93 -0
  202. package/dist/hooks/transition-guard.js.map +1 -0
  203. package/dist/index.d.ts +52 -16
  204. package/dist/index.d.ts.map +1 -1
  205. package/dist/index.js +105 -51
  206. package/dist/index.js.map +1 -1
  207. package/dist/internal.d.ts +4 -2
  208. package/dist/internal.d.ts.map +1 -1
  209. package/dist/internal.js +16 -0
  210. package/dist/internal.js.map +1 -1
  211. package/dist/lib/case-utils.d.ts +0 -1
  212. package/dist/lib/case-utils.d.ts.map +1 -1
  213. package/dist/lib/case-utils.js +0 -3
  214. package/dist/lib/case-utils.js.map +1 -1
  215. package/dist/lib/client-safe-error.d.ts +9 -0
  216. package/dist/lib/client-safe-error.d.ts.map +1 -0
  217. package/dist/lib/client-safe-error.js +23 -0
  218. package/dist/lib/client-safe-error.js.map +1 -0
  219. package/dist/lib/database-errors.d.ts +78 -0
  220. package/dist/lib/database-errors.d.ts.map +1 -0
  221. package/dist/lib/database-errors.js +148 -0
  222. package/dist/lib/database-errors.js.map +1 -0
  223. package/dist/lib/null-prototype-registry.d.ts +9 -0
  224. package/dist/lib/null-prototype-registry.d.ts.map +1 -0
  225. package/dist/lib/null-prototype-registry.js +11 -0
  226. package/dist/lib/null-prototype-registry.js.map +1 -0
  227. package/dist/lib/prisma-errors.d.ts +30 -32
  228. package/dist/lib/prisma-errors.d.ts.map +1 -1
  229. package/dist/lib/prisma-errors.js +86 -46
  230. package/dist/lib/prisma-errors.js.map +1 -1
  231. package/dist/lib/process-global.d.ts +23 -0
  232. package/dist/lib/process-global.d.ts.map +1 -0
  233. package/dist/lib/process-global.js +33 -0
  234. package/dist/lib/process-global.js.map +1 -0
  235. package/dist/lib/warn-once.d.ts +7 -0
  236. package/dist/lib/warn-once.d.ts.map +1 -0
  237. package/dist/lib/warn-once.js +13 -0
  238. package/dist/lib/warn-once.js.map +1 -0
  239. package/dist/mcp/advertise.d.ts +16 -0
  240. package/dist/mcp/advertise.d.ts.map +1 -0
  241. package/dist/mcp/advertise.js +25 -0
  242. package/dist/mcp/advertise.js.map +1 -0
  243. package/dist/mcp/arguments.d.ts +10 -0
  244. package/dist/mcp/arguments.d.ts.map +1 -0
  245. package/dist/mcp/arguments.js +143 -0
  246. package/dist/mcp/arguments.js.map +1 -0
  247. package/dist/mcp/field-schema.d.ts +50 -5
  248. package/dist/mcp/field-schema.d.ts.map +1 -1
  249. package/dist/mcp/field-schema.js +137 -14
  250. package/dist/mcp/field-schema.js.map +1 -1
  251. package/dist/mcp/handler.d.ts +16 -5
  252. package/dist/mcp/handler.d.ts.map +1 -1
  253. package/dist/mcp/handler.js +404 -126
  254. package/dist/mcp/handler.js.map +1 -1
  255. package/dist/mcp/index.d.ts +1 -0
  256. package/dist/mcp/index.d.ts.map +1 -1
  257. package/dist/mcp/index.js +1 -0
  258. package/dist/mcp/index.js.map +1 -1
  259. package/dist/mcp/projection.d.ts +42 -34
  260. package/dist/mcp/projection.d.ts.map +1 -1
  261. package/dist/mcp/projection.js +246 -200
  262. package/dist/mcp/projection.js.map +1 -1
  263. package/dist/mcp/tool-error.d.ts +8 -0
  264. package/dist/mcp/tool-error.d.ts.map +1 -0
  265. package/dist/mcp/tool-error.js +11 -0
  266. package/dist/mcp/tool-error.js.map +1 -0
  267. package/dist/mcp/types.d.ts +3 -2
  268. package/dist/mcp/types.d.ts.map +1 -1
  269. package/dist/mcp/where-id-boundary.d.ts +28 -0
  270. package/dist/mcp/where-id-boundary.d.ts.map +1 -0
  271. package/dist/mcp/where-id-boundary.js +187 -0
  272. package/dist/mcp/where-id-boundary.js.map +1 -0
  273. package/dist/origin.d.ts +147 -0
  274. package/dist/origin.d.ts.map +1 -0
  275. package/dist/origin.js +191 -0
  276. package/dist/origin.js.map +1 -0
  277. package/dist/query/relationship-options.d.ts +35 -6
  278. package/dist/query/relationship-options.d.ts.map +1 -1
  279. package/dist/query/relationship-options.js +33 -23
  280. package/dist/query/relationship-options.js.map +1 -1
  281. package/dist/secured/aggregate.d.ts +32 -0
  282. package/dist/secured/aggregate.d.ts.map +1 -0
  283. package/dist/secured/aggregate.js +31 -0
  284. package/dist/secured/aggregate.js.map +1 -0
  285. package/dist/secured/include.d.ts +320 -0
  286. package/dist/secured/include.d.ts.map +1 -0
  287. package/dist/secured/include.js +650 -0
  288. package/dist/secured/include.js.map +1 -0
  289. package/dist/secured/lock.d.ts +127 -0
  290. package/dist/secured/lock.d.ts.map +1 -0
  291. package/dist/secured/lock.js +275 -0
  292. package/dist/secured/lock.js.map +1 -0
  293. package/dist/secured/lower.d.ts +82 -0
  294. package/dist/secured/lower.d.ts.map +1 -0
  295. package/dist/secured/lower.js +162 -0
  296. package/dist/secured/lower.js.map +1 -0
  297. package/dist/secured/operators.d.ts +7 -0
  298. package/dist/secured/operators.d.ts.map +1 -0
  299. package/dist/secured/operators.js +18 -0
  300. package/dist/secured/operators.js.map +1 -0
  301. package/dist/secured/read.d.ts +208 -0
  302. package/dist/secured/read.d.ts.map +1 -0
  303. package/dist/secured/read.js +1245 -0
  304. package/dist/secured/read.js.map +1 -0
  305. package/dist/secured/select.d.ts +87 -0
  306. package/dist/secured/select.d.ts.map +1 -0
  307. package/dist/secured/select.js +250 -0
  308. package/dist/secured/select.js.map +1 -0
  309. package/dist/secured/vector.d.ts +58 -0
  310. package/dist/secured/vector.d.ts.map +1 -0
  311. package/dist/secured/vector.js +113 -0
  312. package/dist/secured/vector.js.map +1 -0
  313. package/dist/secured/vocabulary.d.ts +227 -0
  314. package/dist/secured/vocabulary.d.ts.map +1 -0
  315. package/dist/secured/vocabulary.js +578 -0
  316. package/dist/secured/vocabulary.js.map +1 -0
  317. package/dist/secured/write.d.ts +58 -0
  318. package/dist/secured/write.d.ts.map +1 -0
  319. package/dist/secured/write.js +87 -0
  320. package/dist/secured/write.js.map +1 -0
  321. package/dist/testing/context.d.ts +236 -0
  322. package/dist/testing/context.d.ts.map +1 -0
  323. package/dist/testing/context.js +457 -0
  324. package/dist/testing/context.js.map +1 -0
  325. package/dist/testing/escape.d.ts +83 -0
  326. package/dist/testing/escape.d.ts.map +1 -0
  327. package/dist/testing/escape.js +148 -0
  328. package/dist/testing/escape.js.map +1 -0
  329. package/dist/testing/extensions.d.ts +48 -0
  330. package/dist/testing/extensions.d.ts.map +1 -0
  331. package/dist/testing/extensions.js +107 -0
  332. package/dist/testing/extensions.js.map +1 -0
  333. package/dist/testing/index.d.ts +5 -0
  334. package/dist/testing/index.d.ts.map +1 -0
  335. package/dist/testing/index.js +11 -0
  336. package/dist/testing/index.js.map +1 -0
  337. package/dist/testing/plans.d.ts +64 -0
  338. package/dist/testing/plans.d.ts.map +1 -0
  339. package/dist/testing/plans.js +47 -0
  340. package/dist/testing/plans.js.map +1 -0
  341. package/dist/types/context.d.ts +110 -0
  342. package/dist/types/context.d.ts.map +1 -0
  343. package/dist/types/context.js +2 -0
  344. package/dist/types/context.js.map +1 -0
  345. package/dist/types/contract.d.ts +198 -0
  346. package/dist/types/contract.d.ts.map +1 -0
  347. package/dist/types/contract.js +2 -0
  348. package/dist/types/contract.js.map +1 -0
  349. package/dist/types/index.d.ts +6 -0
  350. package/dist/types/index.d.ts.map +1 -0
  351. package/dist/types/index.js +11 -0
  352. package/dist/types/index.js.map +1 -0
  353. package/dist/types/inputs.d.ts +83 -0
  354. package/dist/types/inputs.d.ts.map +1 -0
  355. package/dist/types/inputs.js +2 -0
  356. package/dist/types/inputs.js.map +1 -0
  357. package/dist/types/rows.d.ts +76 -0
  358. package/dist/types/rows.d.ts.map +1 -0
  359. package/dist/types/rows.js +2 -0
  360. package/dist/types/rows.js.map +1 -0
  361. package/dist/types/secured-list.d.ts +396 -0
  362. package/dist/types/secured-list.d.ts.map +1 -0
  363. package/dist/types/secured-list.js +2 -0
  364. package/dist/types/secured-list.js.map +1 -0
  365. package/dist/unsafe.d.ts +162 -0
  366. package/dist/unsafe.d.ts.map +1 -0
  367. package/dist/unsafe.js +177 -0
  368. package/dist/unsafe.js.map +1 -0
  369. package/dist/validation/config-refusal.d.ts +16 -0
  370. package/dist/validation/config-refusal.d.ts.map +1 -0
  371. package/dist/validation/config-refusal.js +2 -0
  372. package/dist/validation/config-refusal.js.map +1 -0
  373. package/dist/validation/database-config.d.ts +19 -0
  374. package/dist/validation/database-config.d.ts.map +1 -0
  375. package/dist/validation/database-config.js +237 -0
  376. package/dist/validation/database-config.js.map +1 -0
  377. package/dist/validation/default-value.d.ts +21 -0
  378. package/dist/validation/default-value.d.ts.map +1 -0
  379. package/dist/validation/default-value.js +72 -0
  380. package/dist/validation/default-value.js.map +1 -0
  381. package/dist/validation/extension-packs.d.ts +11 -0
  382. package/dist/validation/extension-packs.d.ts.map +1 -0
  383. package/dist/validation/extension-packs.js +53 -0
  384. package/dist/validation/extension-packs.js.map +1 -0
  385. package/dist/validation/field-config.d.ts +35 -21
  386. package/dist/validation/field-config.d.ts.map +1 -1
  387. package/dist/validation/field-config.js +51 -41
  388. package/dist/validation/field-config.js.map +1 -1
  389. package/dist/validation/field-names.d.ts +15 -0
  390. package/dist/validation/field-names.d.ts.map +1 -0
  391. package/dist/validation/field-names.js +155 -0
  392. package/dist/validation/field-names.js.map +1 -0
  393. package/dist/validation/identifier-names.d.ts +4 -0
  394. package/dist/validation/identifier-names.d.ts.map +1 -0
  395. package/dist/validation/identifier-names.js +39 -0
  396. package/dist/validation/identifier-names.js.map +1 -0
  397. package/dist/validation/needs-closure.d.ts +20 -30
  398. package/dist/validation/needs-closure.d.ts.map +1 -1
  399. package/dist/validation/needs-closure.js +29 -105
  400. package/dist/validation/needs-closure.js.map +1 -1
  401. package/dist/validation/relations.d.ts +17 -0
  402. package/dist/validation/relations.d.ts.map +1 -0
  403. package/dist/validation/relations.js +268 -0
  404. package/dist/validation/relations.js.map +1 -0
  405. package/dist/validation/schema.d.ts.map +1 -1
  406. package/dist/validation/schema.js +1 -3
  407. package/dist/validation/schema.js.map +1 -1
  408. package/dist/where/like.d.ts +32 -0
  409. package/dist/where/like.d.ts.map +1 -0
  410. package/dist/where/like.js +42 -0
  411. package/dist/where/like.js.map +1 -0
  412. package/package.json +70 -8
  413. package/.turbo/turbo-build.log +0 -4
  414. package/CLAUDE.md +0 -609
  415. package/dist/access/access-filter.d.ts +0 -241
  416. package/dist/access/access-filter.d.ts.map +0 -1
  417. package/dist/access/access-filter.js +0 -692
  418. package/dist/access/access-filter.js.map +0 -1
  419. package/dist/access/access-filter.test.d.ts +0 -2
  420. package/dist/access/access-filter.test.d.ts.map +0 -1
  421. package/dist/access/access-filter.test.js +0 -1256
  422. package/dist/access/access-filter.test.js.map +0 -1
  423. package/dist/access/declared-dependencies.test.d.ts +0 -2
  424. package/dist/access/declared-dependencies.test.d.ts.map +0 -1
  425. package/dist/access/declared-dependencies.test.js +0 -226
  426. package/dist/access/declared-dependencies.test.js.map +0 -1
  427. package/dist/access/denied-relation-visibility.test.d.ts +0 -2
  428. package/dist/access/denied-relation-visibility.test.d.ts.map +0 -1
  429. package/dist/access/denied-relation-visibility.test.js +0 -114
  430. package/dist/access/denied-relation-visibility.test.js.map +0 -1
  431. package/dist/access/engine.test.d.ts +0 -2
  432. package/dist/access/engine.test.d.ts.map +0 -1
  433. package/dist/access/engine.test.js +0 -56
  434. package/dist/access/engine.test.js.map +0 -1
  435. package/dist/access/field-access.test.d.ts +0 -2
  436. package/dist/access/field-access.test.d.ts.map +0 -1
  437. package/dist/access/field-access.test.js +0 -635
  438. package/dist/access/field-access.test.js.map +0 -1
  439. package/dist/access/multi-column-read-write.test.d.ts +0 -2
  440. package/dist/access/multi-column-read-write.test.d.ts.map +0 -1
  441. package/dist/access/multi-column-read-write.test.js +0 -183
  442. package/dist/access/multi-column-read-write.test.js.map +0 -1
  443. package/dist/access/relationship-count.d.ts +0 -98
  444. package/dist/access/relationship-count.d.ts.map +0 -1
  445. package/dist/access/relationship-count.js +0 -262
  446. package/dist/access/relationship-count.js.map +0 -1
  447. package/dist/access/relationship-count.test.d.ts +0 -2
  448. package/dist/access/relationship-count.test.d.ts.map +0 -1
  449. package/dist/access/relationship-count.test.js +0 -247
  450. package/dist/access/relationship-count.test.js.map +0 -1
  451. package/dist/access/relationship-label-filter.d.ts +0 -45
  452. package/dist/access/relationship-label-filter.d.ts.map +0 -1
  453. package/dist/access/relationship-label-filter.js +0 -22
  454. package/dist/access/relationship-label-filter.js.map +0 -1
  455. package/dist/access/relationship-label-filter.test.d.ts +0 -2
  456. package/dist/access/relationship-label-filter.test.d.ts.map +0 -1
  457. package/dist/access/relationship-label-filter.test.js +0 -89
  458. package/dist/access/relationship-label-filter.test.js.map +0 -1
  459. package/dist/access/synthetic-include-read.test.d.ts +0 -2
  460. package/dist/access/synthetic-include-read.test.d.ts.map +0 -1
  461. package/dist/access/synthetic-include-read.test.js +0 -121
  462. package/dist/access/synthetic-include-read.test.js.map +0 -1
  463. package/dist/context/nested-operations.d.ts +0 -74
  464. package/dist/context/nested-operations.d.ts.map +0 -1
  465. package/dist/context/nested-operations.js +0 -847
  466. package/dist/context/nested-operations.js.map +0 -1
  467. package/dist/fields/calendar-day.test.d.ts +0 -2
  468. package/dist/fields/calendar-day.test.d.ts.map +0 -1
  469. package/dist/fields/calendar-day.test.js +0 -246
  470. package/dist/fields/calendar-day.test.js.map +0 -1
  471. package/dist/fields/format-prisma-default.d.ts +0 -35
  472. package/dist/fields/format-prisma-default.d.ts.map +0 -1
  473. package/dist/fields/format-prisma-default.js +0 -49
  474. package/dist/fields/format-prisma-default.js.map +0 -1
  475. package/dist/fields/format-prisma-default.test.d.ts +0 -2
  476. package/dist/fields/format-prisma-default.test.d.ts.map +0 -1
  477. package/dist/fields/format-prisma-default.test.js +0 -54
  478. package/dist/fields/format-prisma-default.test.js.map +0 -1
  479. package/dist/fields/relationship-foreign-key.test.d.ts +0 -2
  480. package/dist/fields/relationship-foreign-key.test.d.ts.map +0 -1
  481. package/dist/fields/relationship-foreign-key.test.js +0 -18
  482. package/dist/fields/relationship-foreign-key.test.js.map +0 -1
  483. package/dist/fields/select.test.d.ts +0 -2
  484. package/dist/fields/select.test.d.ts.map +0 -1
  485. package/dist/fields/select.test.js +0 -279
  486. package/dist/fields/select.test.js.map +0 -1
  487. package/dist/fields/text-keystone-compat.test.d.ts +0 -2
  488. package/dist/fields/text-keystone-compat.test.d.ts.map +0 -1
  489. package/dist/fields/text-keystone-compat.test.js +0 -93
  490. package/dist/fields/text-keystone-compat.test.js.map +0 -1
  491. package/dist/filter/filter.test.d.ts +0 -2
  492. package/dist/filter/filter.test.d.ts.map +0 -1
  493. package/dist/filter/filter.test.js +0 -431
  494. package/dist/filter/filter.test.js.map +0 -1
  495. package/dist/filter/serialize.test.d.ts +0 -2
  496. package/dist/filter/serialize.test.d.ts.map +0 -1
  497. package/dist/filter/serialize.test.js +0 -83
  498. package/dist/filter/serialize.test.js.map +0 -1
  499. package/dist/index.test.d.ts +0 -2
  500. package/dist/index.test.d.ts.map +0 -1
  501. package/dist/index.test.js +0 -33
  502. package/dist/index.test.js.map +0 -1
  503. package/dist/lib/case-utils.test.d.ts +0 -2
  504. package/dist/lib/case-utils.test.d.ts.map +0 -1
  505. package/dist/lib/case-utils.test.js +0 -123
  506. package/dist/lib/case-utils.test.js.map +0 -1
  507. package/dist/query/index.d.ts +0 -127
  508. package/dist/query/index.d.ts.map +0 -1
  509. package/dist/query/index.js +0 -179
  510. package/dist/query/index.js.map +0 -1
  511. package/dist/query/index.test.d.ts +0 -2
  512. package/dist/query/index.test.d.ts.map +0 -1
  513. package/dist/query/index.test.js +0 -632
  514. package/dist/query/index.test.js.map +0 -1
  515. package/dist/query/relationship-options.test.d.ts +0 -2
  516. package/dist/query/relationship-options.test.d.ts.map +0 -1
  517. package/dist/query/relationship-options.test.js +0 -150
  518. package/dist/query/relationship-options.test.js.map +0 -1
  519. package/dist/validation/field-config.test.d.ts +0 -2
  520. package/dist/validation/field-config.test.d.ts.map +0 -1
  521. package/dist/validation/field-config.test.js +0 -159
  522. package/dist/validation/field-config.test.js.map +0 -1
  523. package/dist/validation/schema.test.d.ts +0 -2
  524. package/dist/validation/schema.test.d.ts.map +0 -1
  525. package/dist/validation/schema.test.js +0 -409
  526. package/dist/validation/schema.test.js.map +0 -1
  527. package/docs/type-distribution-fix.md +0 -136
  528. package/src/access/access-filter.test.ts +0 -1919
  529. package/src/access/access-filter.ts +0 -1041
  530. package/src/access/declared-dependencies.test.ts +0 -277
  531. package/src/access/declared-dependencies.ts +0 -220
  532. package/src/access/denied-relation-visibility.test.ts +0 -173
  533. package/src/access/depth-limits.ts +0 -27
  534. package/src/access/engine.test.ts +0 -67
  535. package/src/access/engine.ts +0 -193
  536. package/src/access/errors.ts +0 -242
  537. package/src/access/field-access.test.ts +0 -792
  538. package/src/access/field-access.ts +0 -353
  539. package/src/access/field-transforms.ts +0 -68
  540. package/src/access/field-visibility.ts +0 -569
  541. package/src/access/index.ts +0 -82
  542. package/src/access/multi-column-read-write.test.ts +0 -305
  543. package/src/access/query-validation.ts +0 -486
  544. package/src/access/relationship-count.test.ts +0 -344
  545. package/src/access/relationship-count.ts +0 -346
  546. package/src/access/relationship-label-filter.test.ts +0 -128
  547. package/src/access/relationship-label-filter.ts +0 -63
  548. package/src/access/synthetic-include-read.test.ts +0 -179
  549. package/src/access/transaction-registry.ts +0 -58
  550. package/src/access/types.ts +0 -391
  551. package/src/config/index.ts +0 -177
  552. package/src/config/label.ts +0 -51
  553. package/src/config/nav-count.ts +0 -77
  554. package/src/config/plugin-engine.ts +0 -261
  555. package/src/config/types.ts +0 -3270
  556. package/src/context/apply-defaults.ts +0 -47
  557. package/src/context/hook-pipeline.ts +0 -137
  558. package/src/context/index.ts +0 -1737
  559. package/src/context/nested-operations.ts +0 -1470
  560. package/src/context/transaction-boundary.ts +0 -485
  561. package/src/context/write-pipeline.ts +0 -732
  562. package/src/extend.ts +0 -28
  563. package/src/fields/calendar-day.test.ts +0 -291
  564. package/src/fields/format-prisma-default.test.ts +0 -64
  565. package/src/fields/format-prisma-default.ts +0 -64
  566. package/src/fields/index.ts +0 -1901
  567. package/src/fields/relationship-foreign-key.test.ts +0 -29
  568. package/src/fields/select.test.ts +0 -336
  569. package/src/fields/text-keystone-compat.test.ts +0 -126
  570. package/src/filter/collect.ts +0 -108
  571. package/src/filter/filter.test.ts +0 -538
  572. package/src/filter/index.ts +0 -26
  573. package/src/filter/map.ts +0 -63
  574. package/src/filter/parse.ts +0 -99
  575. package/src/filter/serialize.test.ts +0 -115
  576. package/src/filter/serialize.ts +0 -73
  577. package/src/filter/types.ts +0 -120
  578. package/src/hooks/index.ts +0 -752
  579. package/src/index.test.ts +0 -50
  580. package/src/index.ts +0 -192
  581. package/src/internal.ts +0 -61
  582. package/src/lib/case-utils.test.ts +0 -159
  583. package/src/lib/case-utils.ts +0 -68
  584. package/src/lib/prisma-errors.ts +0 -86
  585. package/src/mcp/constants.ts +0 -24
  586. package/src/mcp/field-schema.ts +0 -84
  587. package/src/mcp/handler.ts +0 -633
  588. package/src/mcp/index.ts +0 -7
  589. package/src/mcp/projection.ts +0 -497
  590. package/src/mcp/types.ts +0 -18
  591. package/src/query/index.test.ts +0 -830
  592. package/src/query/index.ts +0 -352
  593. package/src/query/relationship-options.test.ts +0 -194
  594. package/src/query/relationship-options.ts +0 -78
  595. package/src/utils/password.ts +0 -80
  596. package/src/validation/field-config.test.ts +0 -199
  597. package/src/validation/field-config.ts +0 -139
  598. package/src/validation/needs-closure.ts +0 -188
  599. package/src/validation/schema.test.ts +0 -487
  600. package/src/validation/schema.ts +0 -51
  601. package/tests/access-relationships.test.ts +0 -646
  602. package/tests/access.test.ts +0 -590
  603. package/tests/apply-defaults.test.ts +0 -119
  604. package/tests/bare-read-scalars.test.ts +0 -147
  605. package/tests/computed-field-selective-evaluation.test.ts +0 -418
  606. package/tests/config.test.ts +0 -242
  607. package/tests/context.test.ts +0 -3146
  608. package/tests/default-value-create.test.ts +0 -299
  609. package/tests/field-hooks.test.ts +0 -410
  610. package/tests/field-types.test.ts +0 -1291
  611. package/tests/hook-context-secured.test.ts +0 -424
  612. package/tests/hook-pipeline.test.ts +0 -233
  613. package/tests/hooks.test.ts +0 -481
  614. package/tests/interactive-transaction.test.ts +0 -444
  615. package/tests/label.test.ts +0 -135
  616. package/tests/mcp-fields-projection-access.test.ts +0 -250
  617. package/tests/mcp-handler.test.ts +0 -1411
  618. package/tests/multi-column-validation-ordering.test.ts +0 -305
  619. package/tests/nav-count.test.ts +0 -189
  620. package/tests/needs-declared-dependencies.test.ts +0 -503
  621. package/tests/nested-access-and-hooks.test.ts +0 -2566
  622. package/tests/nested-operation-registry.test.ts +0 -317
  623. package/tests/nested-write-hooks.test.ts +0 -864
  624. package/tests/nested-write-synthetic-relation.test.ts +0 -437
  625. package/tests/password-type-distribution.test.ts +0 -154
  626. package/tests/password-types.test.ts +0 -174
  627. package/tests/password.test.ts +0 -263
  628. package/tests/plugin-engine.test.ts +0 -1155
  629. package/tests/prisma-errors.test.ts +0 -141
  630. package/tests/resolve-chain.test.ts +0 -411
  631. package/tests/singleton.test.ts +0 -421
  632. package/tests/sudo.test.ts +0 -676
  633. package/tests/to-one-include-access-filter.test.ts +0 -172
  634. package/tests/transaction-boundary-hooks.test.ts +0 -710
  635. package/tests/transaction-boundary-outermost.test.ts +0 -530
  636. package/tests/virtual-fields.test.ts +0 -421
  637. package/tests/with-session.test.ts +0 -243
  638. package/tests/write-pipeline.test.ts +0 -617
  639. package/tsconfig.json +0 -12
  640. package/tsconfig.tsbuildinfo +0 -1
  641. package/vitest.config.ts +0 -69
@@ -1,6 +1,8 @@
1
- import type { AccessControl, AccessControlledDB, FieldAccess, PrismaClientLike } from '../access/types.js';
1
+ import type { AccessControlledDB, AccessControl, FieldAccess } from '../access/types.js';
2
+ import type { GeneratedTables } from '../contract/dependencies.js';
2
3
  import type { FilterSpec } from '../filter/types.js';
3
4
  import type { z } from 'zod';
5
+ import type { PostgresOptionsBase, PostgresOptions } from '@prisma/orm-postgres/runtime';
4
6
  export type FieldType = 'text' | 'integer' | 'checkbox' | 'timestamp' | 'password' | 'select' | 'relationship' | string;
5
7
  /**
6
8
  * Field-level hook argument types (exported for user annotations)
@@ -13,7 +15,7 @@ export type FieldResolveInputHookArgs<TTypeInfo extends TypeInfo, TFieldKey exte
13
15
  inputData: TTypeInfo['inputs']['create'];
14
16
  item: undefined;
15
17
  resolvedData: TTypeInfo['inputs']['create'];
16
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
18
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
17
19
  } | {
18
20
  listKey: string;
19
21
  fieldKey: TFieldKey;
@@ -21,7 +23,7 @@ export type FieldResolveInputHookArgs<TTypeInfo extends TypeInfo, TFieldKey exte
21
23
  inputData: TTypeInfo['inputs']['update'];
22
24
  item: TTypeInfo['item'];
23
25
  resolvedData: TTypeInfo['inputs']['update'];
24
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
26
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
25
27
  };
26
28
  /** Arguments for {@link FieldHooks.validate} (and its deprecated `validateInput` alias). */
27
29
  export type FieldValidateHookArgs<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = {
@@ -31,7 +33,7 @@ export type FieldValidateHookArgs<TTypeInfo extends TypeInfo, TFieldKey extends
31
33
  inputData: TTypeInfo['inputs']['create'];
32
34
  item: undefined;
33
35
  resolvedData: TTypeInfo['inputs']['create'];
34
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
36
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
35
37
  addValidationError: (msg: string) => void;
36
38
  } | {
37
39
  listKey: string;
@@ -40,14 +42,14 @@ export type FieldValidateHookArgs<TTypeInfo extends TypeInfo, TFieldKey extends
40
42
  inputData: TTypeInfo['inputs']['update'];
41
43
  item: TTypeInfo['item'];
42
44
  resolvedData: TTypeInfo['inputs']['update'];
43
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
45
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
44
46
  addValidationError: (msg: string) => void;
45
47
  } | {
46
48
  listKey: string;
47
49
  fieldKey: TFieldKey;
48
50
  operation: 'delete';
49
51
  item: TTypeInfo['item'];
50
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
52
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
51
53
  addValidationError: (msg: string) => void;
52
54
  };
53
55
  /** Arguments for {@link FieldHooks.beforeOperation}. */
@@ -57,7 +59,7 @@ export type FieldBeforeOperationHookArgs<TTypeInfo extends TypeInfo, TFieldKey e
57
59
  operation: 'create';
58
60
  inputData: TTypeInfo['inputs']['create'];
59
61
  resolvedData: TTypeInfo['inputs']['create'];
60
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
62
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
61
63
  } | {
62
64
  listKey: string;
63
65
  fieldKey: TFieldKey;
@@ -65,13 +67,13 @@ export type FieldBeforeOperationHookArgs<TTypeInfo extends TypeInfo, TFieldKey e
65
67
  inputData: TTypeInfo['inputs']['update'];
66
68
  item: TTypeInfo['item'];
67
69
  resolvedData: TTypeInfo['inputs']['update'];
68
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
70
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
69
71
  } | {
70
72
  listKey: string;
71
73
  fieldKey: TFieldKey;
72
74
  operation: 'delete';
73
75
  item: TTypeInfo['item'];
74
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
76
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
75
77
  };
76
78
  /** Arguments for {@link FieldHooks.afterOperation}. */
77
79
  export type FieldAfterOperationHookArgs<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = {
@@ -81,7 +83,7 @@ export type FieldAfterOperationHookArgs<TTypeInfo extends TypeInfo, TFieldKey ex
81
83
  inputData: TTypeInfo['inputs']['create'];
82
84
  item: TTypeInfo['item'];
83
85
  resolvedData: TTypeInfo['inputs']['create'];
84
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
86
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
85
87
  } | {
86
88
  listKey: string;
87
89
  fieldKey: TFieldKey;
@@ -90,13 +92,13 @@ export type FieldAfterOperationHookArgs<TTypeInfo extends TypeInfo, TFieldKey ex
90
92
  originalItem: TTypeInfo['item'];
91
93
  item: TTypeInfo['item'];
92
94
  resolvedData: TTypeInfo['inputs']['update'];
93
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
95
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
94
96
  } | {
95
97
  listKey: string;
96
98
  fieldKey: TFieldKey;
97
99
  operation: 'delete';
98
100
  originalItem: TTypeInfo['item'];
99
- context: import('../context/index.js').StackContext<TTypeInfo['prisma'], TTypeInfo['db']>;
101
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
100
102
  };
101
103
  /**
102
104
  * Arguments for field-level beforeTransaction hook (#590 / ADR-0010).
@@ -115,20 +117,20 @@ export type FieldBeforeTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
115
117
  fieldKey: TFieldKey;
116
118
  operation: 'create';
117
119
  inputData: TTypeInfo['inputs']['create'];
118
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
120
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
119
121
  } | {
120
122
  listKey: string;
121
123
  fieldKey: TFieldKey;
122
124
  operation: 'update';
123
125
  inputData: TTypeInfo['inputs']['update'];
124
126
  item: TTypeInfo['item'] | undefined;
125
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
127
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
126
128
  } | {
127
129
  listKey: string;
128
130
  fieldKey: TFieldKey;
129
131
  operation: 'delete';
130
132
  item: TTypeInfo['item'] | undefined;
131
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
133
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
132
134
  };
133
135
  /**
134
136
  * Arguments for field-level afterTransaction hook (#590 / ADR-0010).
@@ -142,6 +144,11 @@ export type FieldBeforeTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
142
144
  * transaction, and these hooks fire at per-(list, operation) granularity, not
143
145
  * per record. For per-record nested compensation use the in-transaction
144
146
  * `afterOperation` (which receives the correct nested `item`).
147
+ * - An update whose resolved payload is empty still reports `committed`, with
148
+ * `item` equal to `originalItem`; compare the two to skip a no-op.
149
+ * - `item` is the raw persisted row, the same one `afterOperation` receives —
150
+ * not the session's Field Visibility projection: columns the session cannot
151
+ * read are present and `resolveOutput` transforms are not applied.
145
152
  * - `rolled-back`: NO persisted `item`; the hook gets `inputData` and the
146
153
  * `error` that caused the rollback so it can compensate for whatever
147
154
  * `beforeTransaction` did externally.
@@ -154,7 +161,7 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
154
161
  inputData: TTypeInfo['inputs']['create'];
155
162
  /** Persisted row — populated for the top-level list only; `undefined` for nested lists. */
156
163
  item: TTypeInfo['item'] | undefined;
157
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
164
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
158
165
  } | {
159
166
  listKey: string;
160
167
  fieldKey: TFieldKey;
@@ -162,7 +169,7 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
162
169
  status: 'rolled-back';
163
170
  inputData: TTypeInfo['inputs']['create'];
164
171
  error: unknown;
165
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
172
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
166
173
  } | {
167
174
  listKey: string;
168
175
  fieldKey: TFieldKey;
@@ -173,7 +180,7 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
173
180
  originalItem: TTypeInfo['item'] | undefined;
174
181
  /** Persisted row — populated for the top-level list only; `undefined` for nested lists. */
175
182
  item: TTypeInfo['item'] | undefined;
176
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
183
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
177
184
  } | {
178
185
  listKey: string;
179
186
  fieldKey: TFieldKey;
@@ -182,7 +189,7 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
182
189
  inputData: TTypeInfo['inputs']['update'];
183
190
  originalItem: TTypeInfo['item'] | undefined;
184
191
  error: unknown;
185
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
192
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
186
193
  } | {
187
194
  listKey: string;
188
195
  fieldKey: TFieldKey;
@@ -190,7 +197,7 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
190
197
  status: 'committed';
191
198
  /** Pre-write row — populated for the top-level list only; `undefined` for nested lists. */
192
199
  originalItem: TTypeInfo['item'] | undefined;
193
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
200
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
194
201
  } | {
195
202
  listKey: string;
196
203
  fieldKey: TFieldKey;
@@ -198,16 +205,21 @@ export type FieldAfterTransactionHookArgs<TTypeInfo extends TypeInfo, TFieldKey
198
205
  status: 'rolled-back';
199
206
  originalItem: TTypeInfo['item'] | undefined;
200
207
  error: unknown;
201
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
208
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
202
209
  };
203
210
  /** Arguments for {@link FieldHooks.resolveOutput}. */
204
211
  export type FieldResolveOutputHookArgs<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = {
205
212
  operation: 'query';
206
- value: GetFieldValueType<TTypeInfo['fields'], TFieldKey>;
207
- item: TTypeInfo['item'];
213
+ value: GetFieldValueType<TTypeInfo, TFieldKey>;
214
+ /**
215
+ * Exactly the field's declared dependency set plus the list's system
216
+ * fields — what the runtime fetches for it (ADR-0051). Reading a column
217
+ * this field did not declare in `needs` is a compile error.
218
+ */
219
+ item: FieldNeedsItem<TTypeInfo, TFieldKey>;
208
220
  listKey: string;
209
221
  fieldName: TFieldKey;
210
- context: import('../access/types.js').AccessContext<TTypeInfo['prisma'], TTypeInfo['db']>;
222
+ context: import('../access/types.js').AccessContext<HookDb<TTypeInfo>>;
211
223
  };
212
224
  /**
213
225
  * Field-level hooks for data transformation and side effects
@@ -246,7 +258,7 @@ export type FieldHooks<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<T
246
258
  * }
247
259
  * ```
248
260
  */
249
- resolveInput?: (args: FieldResolveInputHookArgs<TTypeInfo, TFieldKey>) => Promise<GetFieldValueType<TTypeInfo['fields'], TFieldKey> | undefined> | GetFieldValueType<TTypeInfo['fields'], TFieldKey> | undefined;
261
+ resolveInput?: (args: FieldResolveInputHookArgs<TTypeInfo, TFieldKey>) => Promise<GetFieldValueType<TTypeInfo, TFieldKey> | undefined> | GetFieldValueType<TTypeInfo, TFieldKey> | undefined;
250
262
  /**
251
263
  * Validate field value after resolveInput
252
264
  * Called during create/update operations after resolveInput hooks but before database write
@@ -345,6 +357,8 @@ export type FieldHooks<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<T
345
357
  * }
346
358
  * }
347
359
  * ```
360
+ *
361
+ * A throw is reported to `onAfterTransactionError`, never propagated.
348
362
  */
349
363
  afterTransaction?: (args: FieldAfterTransactionHookArgs<TTypeInfo, TFieldKey>) => Promise<void> | void;
350
364
  /**
@@ -365,70 +379,42 @@ export type FieldHooks<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<T
365
379
  * return value
366
380
  * }
367
381
  *
368
- * // Async example (e.g., for virtual fields that query the database)
382
+ * // Async example (e.g., for virtual fields that query the database).
383
+ * // `item.relatedId` requires the field to declare `needs: ['relatedId']` —
384
+ * // a hook's `item` carries only its own declared dependency set.
369
385
  * resolveOutput: async ({ item, context }) => {
370
- * const related = await context.db.otherList.findUnique({ where: { id: item.relatedId } })
386
+ * const related = await context.db.OtherList.where({ id: item.relatedId }).first()
371
387
  * return related?.name
372
388
  * }
373
389
  * ```
374
390
  */
375
- resolveOutput?: (args: FieldResolveOutputHookArgs<TTypeInfo, TFieldKey>) => GetFieldValueType<TTypeInfo['fields'], TFieldKey> | undefined | Promise<GetFieldValueType<TTypeInfo['fields'], TFieldKey> | undefined>;
376
- };
377
- /**
378
- * Configuration for Prisma result extensions
379
- * Allows fields to transform their runtime values and types in query results
380
- *
381
- * Runtime transformation is delegated to the field's resolveOutput hook.
382
- * This config only specifies the TypeScript output type for generated types.
383
- */
384
- export type ResultExtensionConfig = {
385
- /**
386
- * The TypeScript type to use in query result types
387
- * This is a type expression like: "import('@opensaas/stack-core').HashedPassword"
388
- *
389
- * The actual runtime transformation is performed by the field's resolveOutput hook.
390
- * The Prisma extension will automatically call the hook if it exists.
391
- *
392
- * @example "import('@opensaas/stack-core').HashedPassword"
393
- * @example "import('./types').MyCustomType"
394
- */
395
- outputType: string;
396
- /**
397
- * @deprecated No longer used. Runtime transformations are handled by resolveOutput hooks.
398
- * This field is kept for backwards compatibility but should not be used in new code.
399
- */
400
- compute?: string;
391
+ resolveOutput?: (args: FieldResolveOutputHookArgs<TTypeInfo, TFieldKey>) => GetFieldValueType<TTypeInfo, TFieldKey> | undefined | Promise<GetFieldValueType<TTypeInfo, TFieldKey> | undefined>;
401
392
  };
402
- export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
393
+ export type BaseFieldConfig<TTypeInfo extends TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = {
403
394
  type: string;
404
395
  access?: FieldAccess<TTypeInfo['item'], TTypeInfo['inputs']['create'], TTypeInfo['inputs']['update']>;
405
396
  defaultValue?: unknown;
406
- hooks?: FieldHooks<TTypeInfo>;
397
+ hooks?: FieldHooks<TTypeInfo, TKey>;
407
398
  /**
408
399
  * Marks this field as virtual — not stored in database, computed via
409
- * `resolveInput`/`resolveOutput` hooks, and excluded from the Prisma
410
- * schema and input types. Computed whenever the read is going to return
400
+ * `resolveInput`/`resolveOutput` hooks, and excluded from the contract
401
+ * and input types. Computed whenever the read is going to return
411
402
  * it (ADR-0027) — not gated behind an explicit `include`/selection.
412
403
  */
413
404
  virtual?: boolean;
414
- /**
415
- * Prisma result extension configuration
416
- * Transforms field values and types in query results using Prisma's native extension system
417
- */
418
- resultExtension?: ResultExtensionConfig;
419
405
  /**
420
406
  * Database configuration
421
407
  */
422
408
  db?: {
423
409
  /**
424
- * Custom database column name
425
- * Adds a @map attribute in Prisma schema
410
+ * Custom database column name. Carried on the contract column as `map`,
411
+ * when it differs from the field's own name.
426
412
  * @example
427
413
  * ```typescript
428
414
  * fields: {
429
415
  * firstName: text({ db: { map: 'first_name' } })
430
416
  * }
431
- * // Generates: firstName String @map("first_name")
417
+ * // Contract: the firstName column maps to 'first_name'
432
418
  * ```
433
419
  */
434
420
  map?: string;
@@ -448,32 +434,33 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
448
434
  * phoneNumber: text({
449
435
  * db: { isNullable: false }
450
436
  * })
451
- * // Generates: phoneNumber String (non-nullable)
437
+ * // Contract: the phoneNumber column is non-nullable
452
438
  *
453
439
  * // DB nullable (explicit), regardless of validation
454
440
  * lastMessagePreview: text({
455
441
  * db: { isNullable: true }
456
442
  * })
457
- * // Generates: lastMessagePreview String? (nullable)
443
+ * // Contract: the lastMessagePreview column is nullable
458
444
  * }
459
445
  * ```
460
446
  */
461
447
  isNullable?: boolean;
462
448
  /**
463
- * Override the native database type for the column.
464
- * Generates a @db.<nativeType> attribute in the Prisma schema.
465
- * The available types depend on your database provider.
449
+ * Override the native database type for the column. Folded into the
450
+ * contract column's own type constructor (`ColumnTypeDescriptor`), so the
451
+ * column is typed by `nativeType` directly rather than the field's
452
+ * default. The available types depend on your database provider.
466
453
  *
467
454
  * @example
468
455
  * ```typescript
469
456
  * // PostgreSQL: use TEXT instead of VARCHAR
470
457
  * fields: {
471
458
  * description: text({ db: { nativeType: 'Text' } })
472
- * // Generates: description String? @db.Text
459
+ * // Contract: description is a Text column
473
460
  *
474
461
  * // PostgreSQL: use SMALLINT instead of INT
475
462
  * count: integer({ db: { nativeType: 'SmallInt' } })
476
- * // Generates: count Int? @db.SmallInt
463
+ * // Contract: count is a SmallInt column
477
464
  * }
478
465
  * ```
479
466
  */
@@ -557,54 +544,6 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
557
544
  * @param operation - Whether this is a create or update operation
558
545
  */
559
546
  getZodSchema?: (fieldName: string, operation: 'create' | 'update') => z.ZodTypeAny;
560
- /**
561
- * Get Prisma type and modifiers for schema generation
562
- * @param fieldName - The name of the field (for generating modifiers)
563
- * @param provider - Optional database provider ('sqlite', 'postgresql', 'mysql', etc.)
564
- * @param listName - Optional list name (used for generating enum type names)
565
- * @param keystoneCompat - Whether Keystone-compat mode is enabled (db.keystoneCompat).
566
- * When true, non-null text columns without an explicit defaultValue emit
567
- * `@default("")` to match Keystone 6's implicit empty-string text default.
568
- * @returns Prisma type string, optional modifiers, optional enum values, and
569
- * an optional block-level index request
570
- */
571
- getPrismaType?: (fieldName: string, provider?: string, listName?: string, keystoneCompat?: boolean) => {
572
- type: string;
573
- modifiers?: string;
574
- /**
575
- * If set, this field requires a Prisma enum definition with these values.
576
- * The enum name is the value of `type`.
577
- */
578
- enumValues?: string[];
579
- /**
580
- * If set, this field requires a block-level index on the owning model:
581
- * `@@index([fieldName])` for `true`, `@@unique([fieldName])` for
582
- * `'unique'`. `false` and `undefined` both mean "no index".
583
- *
584
- * Prisma has no field-level `@index` attribute — a non-unique index can
585
- * ONLY be expressed as the model-level `@@index([...])` — so a field that
586
- * wants one has to ask for it out-of-line rather than appending to
587
- * {@link modifiers}. (A unique index has both forms available; the
588
- * built-in scalars keep emitting the inline `@unique` modifier for that
589
- * case, so this channel carries only what cannot be written inline.)
590
- *
591
- * Same shape as {@link PrismaRelationResult.foreignKeyIndex}, which is how
592
- * relationship fields have always emitted their foreign-key indexes. The
593
- * generator handles both through one emit pass, so the field stays the
594
- * authority on whether it can be indexed by name at all — a multi-column
595
- * field (see {@link getPrismaColumns}) has no single column matching its
596
- * field name and can decline, or name a real column of its own.
597
- */
598
- index?: boolean | 'unique';
599
- };
600
- /**
601
- * Get TypeScript type information for type generation
602
- * @returns TypeScript type string and optionality
603
- */
604
- getTypeScriptType?: () => {
605
- type: string;
606
- optional: boolean;
607
- };
608
547
  /**
609
548
  * Declare this field's filtering capability — its {@link FilterSpec} — for the
610
549
  * admin UI's Filter builder (ADR-0017). Optional and additive: a field that
@@ -612,8 +551,8 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
612
551
  * hasn't adopted filtering) is simply not filterable and never suggested, so
613
552
  * absence degrades gracefully everywhere.
614
553
  *
615
- * Self-contained, like {@link getPrismaType} and friends — the filter engine
616
- * delegates to each field's spec rather than switching on field type. The
554
+ * Self-contained, like {@link getContractField} and friends — the filter
555
+ * engine delegates to each field's spec rather than switching on field type. The
617
556
  * returned `toCondition` mapper must stay pure (no DB/Prisma imports); its
618
557
  * output is ANDed with the access filter through the secured context.
619
558
  *
@@ -625,49 +564,11 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
625
564
  */
626
565
  getFilterSpec?: (fieldName: string, listKey: string, config: OpenSaasConfig) => FilterSpec | undefined;
627
566
  /**
628
- * Get TypeScript imports needed for this field's type
629
- * @returns Array of import statements needed for the generated types file
630
- */
631
- getTypeScriptImports?: () => Array<{
632
- /**
633
- * The type/value names to import
634
- * e.g., ['StoredEmbedding', 'EmbeddingMetadata']
635
- */
636
- names: string[];
637
- /**
638
- * The module to import from
639
- * e.g., '@opensaas/stack-rag'
640
- */
641
- from: string;
642
- /**
643
- * Whether this is a type-only import
644
- * @default true
645
- */
646
- typeOnly?: boolean;
647
- }>;
648
- /**
649
- * Multi-column Prisma emission.
650
- *
651
- * Most scalar fields back a single Prisma column via {@link getPrismaType}.
652
- * A field that maps onto SEVERAL physical columns (e.g. the storage
653
- * `image()`/`file()` fields in multi-column / Keystone-parity mode — see
654
- * ADR-0006) implements this instead: it returns one descriptor per column,
655
- * each becoming its own line in the generated model. When present, the
656
- * generator emits these lines and skips the single-column `getPrismaType`
657
- * path. The field itself owns the column layout — the generator stays a
658
- * neutral coordinator (no field-type switches), mirroring how relationship
659
- * fields emit FK + relation lines through `getPrismaRelation`.
660
- *
661
- * @param fieldName - The field's config key (used to derive default column names)
662
- * @returns One descriptor per physical column, or `undefined` to fall back to
663
- * the single-column `getPrismaType` path.
664
- */
665
- getPrismaColumns?: (fieldName: string) => MultiColumnPrismaResult[] | undefined;
666
- /**
667
- * The physical Prisma column names this field owns when it spans multiple
668
- * columns (see {@link getPrismaColumns}). The read path uses this to strip the
669
- * raw per-part columns from query results so only the assembled logical value
670
- * (produced by {@link assembleColumns}) is exposed.
567
+ * The physical column names this field owns when its
568
+ * {@link getContractField} descriptor is a multi-column one (`kind:
569
+ * 'columns'`). The read path uses this to strip the raw per-part columns
570
+ * from query results so only the assembled logical value (produced by
571
+ * {@link assembleColumns}) is exposed.
671
572
  *
672
573
  * @param fieldName - The field's config key
673
574
  */
@@ -693,34 +594,99 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
693
594
  */
694
595
  splitColumns?: (fieldName: string, value: unknown) => Record<string, unknown>;
695
596
  /**
696
- * Declares the immediate sibling relations this field's `resolveOutput`
697
- * hook cannot compute without (ADR-0025 — the "Declared dependency" glossary
698
- * entry in `CONTEXT.md`). The read fetches each declared relation wherever
699
- * this field is computed — at the root of a read and at every nested level
700
- * alike — and scopes it through the Access Filter exactly like a
701
- * caller-named relation: a dependency a session cannot query is not
702
- * fetched, and the hook sees nothing in its place.
597
+ * Describe what this field contributes to the contract (ADR-0040,
598
+ * ADR-0049): its stored column(s) as a pack-qualified type constructor with
599
+ * native type, nullability and column mapping; for a relationship, the
600
+ * relation and the foreign-key column this side owns; for a virtual field,
601
+ * nothing.
602
+ *
603
+ * @param fieldName - The field's config key
604
+ * @param listKey - The owning list's key
605
+ * @param config - The full config (a relationship resolves its target and
606
+ * foreign-key ownership from it)
607
+ *
608
+ * @example
609
+ * ```typescript
610
+ * getContractField: (fieldName) => ({
611
+ * kind: 'column',
612
+ * name: fieldName,
613
+ * type: { pack: 'pgvector', type: 'Vector', args: [1536] },
614
+ * nullable: true,
615
+ * })
616
+ * ```
617
+ */
618
+ getContractField?: (fieldName: string, listKey: string, config: OpenSaasConfig) => ContractFieldDescriptor;
619
+ /**
620
+ * Describe this field's stored vector column, when it has one: the column
621
+ * `nearest()` measures against and the distance function that measurement
622
+ * is made with (ADR-0045). A field that does not answer this is not
623
+ * searchable, which is what makes `nearest('title', …)` a refusal rather
624
+ * than a query the database rejects.
625
+ *
626
+ * @param fieldName - The field's config key
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * getVectorColumn: (fieldName) => ({
631
+ * column: fieldName,
632
+ * dimensions: 1536,
633
+ * distanceFunction: 'cosine',
634
+ * })
635
+ * ```
636
+ */
637
+ getVectorColumn?: (fieldName: string) => VectorColumnDescriptor;
638
+ /**
639
+ * Set to `false` to keep this field out of the predicate, order and distinct
640
+ * vocabulary: a `where`, `orderBy`, `distinct` or `distinctOn` naming it is
641
+ * refused exactly as an undeclared column is. The field is still readable
642
+ * and writable under its own access rules. `password()` sets this so a hash
643
+ * cannot be extracted byte-by-byte with `contains`/`startsWith`/`gt`.
644
+ */
645
+ isFilterable?: boolean;
646
+ /**
647
+ * The TypeScript type a read returns for this field, when it differs from
648
+ * the column's codec type (ADR-0052). Required on a virtual field, where it
649
+ * is the contract remainder's computed entry; on a stored field it is an
650
+ * override — `password` reads as `HashedPassword` over a text column —
651
+ * and absence means the codec's own type.
652
+ *
653
+ * @example "import('@opensaas/stack-core/internal').HashedPassword"
654
+ * @example { value: Decimal, from: 'decimal.js' }
655
+ */
656
+ outputType?: TypeDescriptor;
657
+ /**
658
+ * The TypeScript type a write accepts for this field, when it differs from
659
+ * the column's codec input type (ADR-0052) — `calendarDay` accepts a
660
+ * `YYYY-MM-DD` string where the codec would take more. Absence means the
661
+ * codec's own input type.
662
+ */
663
+ inputType?: TypeDescriptor;
664
+ /**
665
+ * Declares the immediate sibling columns and relations this field's
666
+ * `resolveOutput` hook cannot compute without (ADR-0025, widened to columns
667
+ * by ADR-0051 — the "Declared dependency" glossary entry in `CONTEXT.md`).
668
+ * The read fetches each declared dependency wherever this field is
669
+ * computed — at the root of a read and at every nested level alike — and
670
+ * scopes a relation through the Access Filter exactly like a caller-named
671
+ * one: a dependency a session cannot query is not fetched, and the hook
672
+ * sees nothing in its place.
703
673
  *
704
674
  * A declared dependency is private plumbing, not an implicit `include`: it
705
675
  * is stripped from the result unless the caller named it too, so declaring
706
676
  * or removing one changes this field's implementation, never the shape of
707
677
  * every read of the list.
708
678
  *
709
- * Names immediate relations only — no dotted paths. Reach beyond one hop
710
- * comes from the recursive fold: a dependency's own list declares its own
711
- * dependencies.
679
+ * Names stored columns and immediate relations on the same list only — no
680
+ * dotted paths, and never a computed field. A declaration on a field with
681
+ * no `resolveOutput` hook is dead config and fails `pnpm generate`.
712
682
  *
713
683
  * Typed as a plain `string[]`, not narrowed to this list's own relation
714
- * keys: `BaseFieldConfig` is the contextual type EVERY field builder's
715
- * return type is checked against, including non-generic third-party ones
716
- * (`richText(): RichTextField`, with no `TTypeInfo` parameter of its own —
717
- * the documented third-party field pattern). Narrowing `needs` per-list
718
- * would make `needs`'s type on a fixed, unparameterized third-party field
719
- * config disagree with the narrower type this list's own slot expects,
720
- * breaking assignability for every such field regardless of whether it
721
- * uses `needs` at all. A misspelled or non-relation entry is instead
722
- * caught by `pnpm generate` (`validateNeedsDeclarations`), which has no
723
- * such constraint.
684
+ * keys, unlike {@link BaseFieldConfig}'s own `TKey` (issue #1306): a
685
+ * `needs` entry names a DIFFERENT field on the SAME list, so narrowing it
686
+ * would require threading that field's key too, for no reader-facing
687
+ * benefit `pnpm generate` (`validateNeedsDeclarations`) doesn't already
688
+ * provide by rejecting a misspelled or non-relation entry at generate
689
+ * time.
724
690
  *
725
691
  * @example
726
692
  * ```typescript
@@ -737,24 +703,165 @@ export type BaseFieldConfig<TTypeInfo extends TypeInfo> = {
737
703
  needs?: string[];
738
704
  };
739
705
  /**
740
- * A single physical column contributed by a multi-column field
741
- * (see {@link BaseFieldConfig.getPrismaColumns}).
706
+ * A JSON-serialisable literal. What a column default can hold, and the
707
+ * argument vocabulary of a {@link ColumnTypeDescriptor} — the Contract module
708
+ * is fully literal (ADR-0040), so nothing that cannot be re-emitted as source
709
+ * belongs here.
742
710
  */
743
- export type MultiColumnPrismaResult = {
744
- /** The Prisma model field name (the property the column is declared as). */
745
- name: string;
746
- /** The Prisma scalar type, e.g. `'String'` or `'Int'`. */
711
+ export type ContractLiteral = string | number | boolean | null | ContractLiteral[] | {
712
+ [key: string]: ContractLiteral;
713
+ };
714
+ /**
715
+ * A column's type as a pack-qualified type constructor —
716
+ * `type.<pack>.<type>(...args)` in the Contract module (ADR-0049). Core's
717
+ * scalars live in the `pg` pack (`{ pack: 'pg', type: 'text' }`,
718
+ * `{ pack: 'pg', type: 'decimal', args: [18, 4] }`); a field over an extension
719
+ * pack names it (`{ pack: 'pgvector', type: 'Vector', args: [1536] }`), and the
720
+ * generator refuses a config that uses a pack `db.extensions` does not declare.
721
+ */
722
+ export type ColumnTypeDescriptor = {
723
+ /** The pack that owns the type constructor — `'pg'` for core's scalars, else an extension pack's `name`. */
724
+ pack: string;
725
+ /** The type constructor's name within the pack. */
747
726
  type: string;
727
+ /** Positional arguments to the constructor (a length, a precision/scale pair, a dimension). */
728
+ args?: ContractLiteral[];
729
+ };
730
+ /**
731
+ * A column's default. `'literal'` carries a value the Contract module emits as
732
+ * source; `'now'` is the database clock at insert; `'sql'` is a database-side
733
+ * expression, for a column whose live default the verifier only recognises in
734
+ * its normalised SQL form. A `bigint` column's default
735
+ * is carried as its decimal string — `42n`, `42` and `'42'` all become `'42'`,
736
+ * the form the generator writes into `@default`. A default that is not a
737
+ * JSON literal (a `Date`, a `Decimal`, a `Map`) is refused by the builder.
738
+ */
739
+ export type ColumnDefaultDescriptor = {
740
+ kind: 'literal';
741
+ value: ContractLiteral;
742
+ } | {
743
+ kind: 'now';
744
+ } | {
745
+ kind: 'sql';
746
+ expression: string;
747
+ };
748
+ /**
749
+ * One stored column a field contributes to the contract.
750
+ */
751
+ export type ContractColumnDescriptor = {
752
+ /** The model field name — the property the column is declared as. Equals the field key for a single-column field. */
753
+ name: string;
754
+ /** The column's type constructor. */
755
+ type: ColumnTypeDescriptor;
756
+ /** A native-type override for the column (`db.nativeType`), when the constructor's default is not wanted. */
757
+ nativeType?: string;
758
+ /** Whether the column accepts NULL. */
759
+ nullable: boolean;
760
+ /** The physical column name, when it differs from {@link name} (`db.map`). */
761
+ map?: string;
762
+ /** Whether the column carries a unique constraint (`isIndexed: 'unique'`). */
763
+ unique?: boolean;
764
+ /** Whether the column carries a non-unique index (`isIndexed: true`). */
765
+ index?: boolean;
766
+ /** The column's default, when it has one. */
767
+ default?: ColumnDefaultDescriptor;
768
+ /**
769
+ * The native enum this column is typed by, when {@link type} is an enum
770
+ * constructor — the contract declares the enum entity once and the column
771
+ * references it.
772
+ */
773
+ enum?: {
774
+ name: string;
775
+ values: string[];
776
+ };
777
+ };
778
+ /**
779
+ * The foreign-key column a relationship's owning side contributes. The
780
+ * column's type is the referenced list's id type, resolved from that list's
781
+ * `db.idField`.
782
+ */
783
+ export type ContractForeignKeyDescriptor = {
784
+ /** The model field name of the foreign-key column (`<field>Id`). */
785
+ name: string;
786
+ /** The physical column name, when it differs from {@link name}. */
787
+ map?: string;
788
+ /** Whether the column accepts NULL (`db.isNullable`, default `true`). */
789
+ nullable: boolean;
790
+ /** Whether the column carries a unique constraint — the owning side of a one-to-one. */
791
+ unique: boolean;
792
+ /** Whether the column carries a non-unique index (`isIndexed`, default `true`). */
793
+ index: boolean;
794
+ /** The list and field the column references. */
795
+ references: {
796
+ list: string;
797
+ field: 'id';
798
+ };
799
+ };
800
+ /**
801
+ * A relationship field's contract contribution: the relation itself and, on
802
+ * the owning side of a to-one, its foreign-key column.
803
+ */
804
+ export type ContractRelationDescriptor = {
805
+ kind: 'relation';
806
+ /** The list this field points at. */
807
+ target: string;
748
808
  /**
749
- * Field modifiers, e.g. `'?'` for nullable. A leading `'?'` attaches to the
750
- * type; anything after it is treated as trailing attributes (matching the
751
- * single-column `getPrismaType` modifier convention).
809
+ * The field on {@link target} that is this relation's other side. Declared
810
+ * (`ref: 'List.field'`) or, for a list-only `ref: 'List'`, synthesised as
811
+ * `from_<List>_<field>` on the target.
752
812
  */
753
- modifiers?: string;
754
- /** Physical column name for the `@map` attribute, when it differs from `name`. */
755
- map?: string;
813
+ inverse: {
814
+ field: string;
815
+ synthetic: boolean;
816
+ };
817
+ /** Whether this side holds many rows. */
818
+ many: boolean;
819
+ /**
820
+ * The foreign-key column this side owns. Absent on a to-many side and on
821
+ * the non-owning side of a one-to-one, which have no column.
822
+ */
823
+ foreignKey?: ContractForeignKeyDescriptor;
824
+ };
825
+ /**
826
+ * What a field contributes to the contract (ADR-0040, ADR-0049):
827
+ *
828
+ * - `'column'` — one stored column; the common scalar case.
829
+ * - `'columns'` — several stored columns owned by one field (the multi-column
830
+ * path ADR-0006 gave storage fields; each entry is its own column).
831
+ * - `'relation'` — a relation and, when this side owns it, a foreign key.
832
+ * - `'computed'` — no storage at all; a virtual field. Its TypeScript face is
833
+ * {@link BaseFieldConfig.outputType}, the contract remainder's computed entry.
834
+ */
835
+ export type ContractFieldDescriptor = ({
836
+ kind: 'column';
837
+ } & ContractColumnDescriptor) | {
838
+ kind: 'columns';
839
+ columns: ContractColumnDescriptor[];
840
+ } | ContractRelationDescriptor | {
841
+ kind: 'computed';
842
+ };
843
+ /**
844
+ * How similarity is measured over a vector column. The three pgvector
845
+ * supports, in the spelling the RAG field builder already used: `cosine`
846
+ * (`<=>`), `l2` (`<->`) and `inner_product` (`<#>`, which yields the
847
+ * *negative* inner product — the direction `distanceToScore` hides).
848
+ */
849
+ export type VectorDistanceFunction = 'cosine' | 'l2' | 'inner_product';
850
+ /**
851
+ * A field's stored vector column, as `nearest()` needs to see it
852
+ * (ADR-0045). The field owns the column, its dimension and the distance
853
+ * function together, because the index's operator class must agree with all
854
+ * three.
855
+ */
856
+ export type VectorColumnDescriptor = {
857
+ /** The model field name of the vector column. */
858
+ column: string;
859
+ /** The column's declared dimension. A query vector of another length is refused. */
860
+ dimensions: number;
861
+ /** How a distance over this column is measured. */
862
+ distanceFunction: VectorDistanceFunction;
756
863
  };
757
- export type TextField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
864
+ export type TextField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
758
865
  type: 'text';
759
866
  validation?: {
760
867
  isRequired?: boolean;
@@ -768,7 +875,7 @@ export type TextField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<T
768
875
  displayMode?: 'input' | 'textarea';
769
876
  };
770
877
  };
771
- export type IntegerField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
878
+ export type IntegerField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
772
879
  type: 'integer';
773
880
  validation?: {
774
881
  isRequired?: boolean;
@@ -777,7 +884,7 @@ export type IntegerField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfi
777
884
  };
778
885
  isIndexed?: boolean | 'unique';
779
886
  };
780
- export type DecimalField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
887
+ export type DecimalField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
781
888
  type: 'decimal';
782
889
  defaultValue?: string;
783
890
  precision?: number;
@@ -797,7 +904,7 @@ export type DecimalField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfi
797
904
  * string over MCP — `bigint` is not JSON-serialisable, so the MCP handler
798
905
  * renders it as a string rather than throwing.
799
906
  */
800
- export type BigIntField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
907
+ export type BigIntField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
801
908
  type: 'bigInt';
802
909
  defaultValue?: bigint | number | string;
803
910
  validation?: {
@@ -807,17 +914,19 @@ export type BigIntField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
807
914
  };
808
915
  isIndexed?: boolean | 'unique';
809
916
  };
810
- export type CheckboxField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
917
+ export type CheckboxField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
811
918
  type: 'checkbox';
919
+ /** Value filled when the field is omitted on create. Defaults to `false`. */
920
+ defaultValue?: boolean;
812
921
  };
813
- export type TimestampField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
922
+ export type TimestampField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
814
923
  type: 'timestamp';
815
924
  defaultValue?: {
816
925
  kind: 'now';
817
926
  } | Date;
818
927
  isIndexed?: boolean | 'unique';
819
928
  };
820
- export type CalendarDayField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
929
+ export type CalendarDayField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
821
930
  type: 'calendarDay';
822
931
  defaultValue?: string;
823
932
  validation?: {
@@ -825,7 +934,7 @@ export type CalendarDayField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldC
825
934
  };
826
935
  isIndexed?: boolean | 'unique';
827
936
  };
828
- export type PasswordField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
937
+ export type PasswordField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
829
938
  type: 'password';
830
939
  validation?: {
831
940
  isRequired?: boolean;
@@ -853,7 +962,7 @@ export type SelectOption = {
853
962
  variant?: SelectOptionVariant;
854
963
  };
855
964
  };
856
- export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
965
+ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
857
966
  type: 'select';
858
967
  options: Array<SelectOption>;
859
968
  defaultValue?: string;
@@ -861,9 +970,10 @@ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
861
970
  /**
862
971
  * Whether to store as a native database enum type.
863
972
  * - 'string' (default): stores as a plain string/varchar column
864
- * - 'enum': stores as a Prisma enum, generating a native enum type in the schema
973
+ * - 'enum': stores as a native enum column, declared once in the contract's
974
+ * `enums` and referenced by this column's type
865
975
  *
866
- * Note: enum values must be valid Prisma identifiers (letters, numbers, underscores,
976
+ * Note: enum values must be valid identifiers (letters, numbers, underscores,
867
977
  * starting with a letter) when using 'enum' type.
868
978
  *
869
979
  * @default 'string'
@@ -871,11 +981,11 @@ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
871
981
  type?: 'string' | 'enum';
872
982
  map?: string;
873
983
  /**
874
- * Force the generated column to be nullable (`?`) even when a `defaultValue`
875
- * is present. By default a select with a `defaultValue` generates NOT NULL;
984
+ * Force the column to be nullable even when a `defaultValue` is present.
985
+ * By default a select with a `defaultValue` produces a NOT NULL column;
876
986
  * set this to `true` for an explicit opt-in to a nullable column with a
877
- * default (e.g. `String? @default("X")` or `<Enum>? @default(X)`), so that
878
- * a live column containing NULLs migrates without a NOT NULL failure.
987
+ * default, so that a live column containing NULLs migrates without a NOT
988
+ * NULL failure.
879
989
  *
880
990
  * @default undefined (NOT NULL when a default is present — unchanged behaviour)
881
991
  *
@@ -887,18 +997,18 @@ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
887
997
  * defaultValue: 'draft',
888
998
  * db: { isNullable: true },
889
999
  * })
890
- * // Generates: String? @default("draft")
1000
+ * // Contract: a nullable column with a default of 'draft'
891
1001
  * ```
892
1002
  */
893
1003
  isNullable?: boolean;
894
1004
  /**
895
- * Override the generated Prisma enum type name for native-enum selects
896
- * (only applies when `type: 'enum'`). By default the enum is named
1005
+ * Override the native enum type name for native-enum selects (only
1006
+ * applies when `type: 'enum'`). By default the enum is named
897
1007
  * `<List><Field>` (e.g. `AccountNoteStatus`); set this to match a live DB
898
1008
  * enum type whose name differs (e.g. Keystone's `…Type` suffix).
899
1009
  *
900
- * The custom name is applied to both the generated `enum` block and every
901
- * reference to it in the owning model.
1010
+ * The custom name is carried on the contract's declared `enums` entry and
1011
+ * every column referencing it.
902
1012
  *
903
1013
  * @example
904
1014
  * ```typescript
@@ -906,7 +1016,7 @@ export type SelectField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig
906
1016
  * options: [{ label: 'Open', value: 'open' }],
907
1017
  * db: { type: 'enum', enumName: 'AccountNoteStatusType' },
908
1018
  * })
909
- * // Generates: enum AccountNoteStatusType { ... } and the column references it
1019
+ * // Contract: declares enum AccountNoteStatusType and the column references it
910
1020
  * ```
911
1021
  */
912
1022
  enumName?: string;
@@ -1007,14 +1117,15 @@ export type RelationshipItemViewConfig = {
1007
1117
  */
1008
1118
  removeAction?: 'disconnect' | 'delete' | 'none';
1009
1119
  };
1010
- export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
1120
+ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
1011
1121
  type: 'relationship';
1012
1122
  ref: string;
1013
1123
  many?: boolean;
1014
1124
  /**
1015
- * Controls whether to create an index on the foreign key field
1016
- * Defaults to true for all foreign key fields (matching Keystone behavior)
1017
- * Can be set to 'unique' for unique constraints or false to disable indexing
1125
+ * Controls whether the foreign key column carries a contract-level index
1126
+ * or unique constraint. Defaults to true for all foreign key fields
1127
+ * (matching Keystone behavior). Can be set to 'unique' for a unique
1128
+ * constraint or false to leave the column unindexed.
1018
1129
  *
1019
1130
  * @default true (for foreign key fields)
1020
1131
  *
@@ -1022,15 +1133,15 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1022
1133
  * ```typescript
1023
1134
  * // Standard indexed foreign key (default)
1024
1135
  * author: relationship({ ref: 'User.posts' })
1025
- * // Generates: @@index([authorId])
1136
+ * // Contract: an index on the authorId column
1026
1137
  *
1027
1138
  * // Unique foreign key (one-to-one)
1028
1139
  * author: relationship({ ref: 'User.posts', isIndexed: 'unique' })
1029
- * // Generates: @@unique([authorId])
1140
+ * // Contract: a unique constraint on the authorId column
1030
1141
  *
1031
1142
  * // Disable indexing (not recommended, may cause performance issues)
1032
1143
  * author: relationship({ ref: 'User.posts', isIndexed: false })
1033
- * // No index generated
1144
+ * // No index or constraint on the column
1034
1145
  * ```
1035
1146
  */
1036
1147
  isIndexed?: boolean | 'unique';
@@ -1052,8 +1163,8 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1052
1163
  * ref: 'User.sessions',
1053
1164
  * db: { isNullable: false },
1054
1165
  * })
1055
- * // Generates: userId String (was String?)
1056
- * // user User @relation(...) (was User?)
1166
+ * // Contract: the userId column and the user relation are both
1167
+ * // non-nullable (were nullable by default)
1057
1168
  * ```
1058
1169
  */
1059
1170
  isNullable?: boolean;
@@ -1079,7 +1190,7 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1079
1190
  * User: list({
1080
1191
  * fields: {
1081
1192
  * account: relationship({ ref: 'Account.user', db: { foreignKey: true } })
1082
- * // Generates: accountId String? @unique
1193
+ * // Contract: a unique accountId column
1083
1194
  * }
1084
1195
  * })
1085
1196
  *
@@ -1087,7 +1198,7 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1087
1198
  * User: list({
1088
1199
  * fields: {
1089
1200
  * account: relationship({ ref: 'Account.user', db: { foreignKey: { map: 'account_id' } } })
1090
- * // Generates: accountId String? @unique @map("account_id")
1201
+ * // Contract: a unique accountId column mapped to 'account_id'
1091
1202
  * }
1092
1203
  * })
1093
1204
  *
@@ -1101,7 +1212,7 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1101
1212
  * Post: list({
1102
1213
  * fields: {
1103
1214
  * category: relationship({ ref: 'Category', db: { foreignKey: { map: 'category_id' } } })
1104
- * // Generates: categoryId String? @map("category_id")
1215
+ * // Contract: the categoryId column mapped to 'category_id'
1105
1216
  * }
1106
1217
  * })
1107
1218
  * ```
@@ -1110,64 +1221,23 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1110
1221
  map?: string;
1111
1222
  };
1112
1223
  /**
1113
- * Custom relation name for many-to-many relationships
1114
- * Overrides the global joinTableNaming setting
1115
- * Prisma will create an implicit join table named _relationName
1116
- * Only needs to be set on one side of a bidirectional relationship
1117
- *
1118
- * @example KeystoneJS-style naming for migration
1119
- * ```typescript
1120
- * Lesson: list({
1121
- * fields: {
1122
- * teachers: relationship({
1123
- * ref: 'Teacher.lessons',
1124
- * many: true,
1125
- * db: { relationName: 'Lesson_teachers' }
1126
- * // Prisma creates join table _Lesson_teachers
1127
- * })
1128
- * }
1129
- * })
1130
- *
1131
- * Teacher: list({
1132
- * fields: {
1133
- * lessons: relationship({ ref: 'Lesson.teachers', many: true })
1134
- * // Automatically uses same relationName from other side
1135
- * }
1136
- * })
1137
- * ```
1138
- */
1139
- relationName?: string;
1140
- /**
1141
- * Extend or modify the generated Prisma schema lines for this relationship field
1142
- * Receives the generated FK line (if applicable) and relation line
1143
- * Returns the modified lines
1224
+ * What the database does to this row when the referenced row is
1225
+ * deleted. Only meaningful on the foreign-key-owning side.
1144
1226
  *
1145
- * @example Add onDelete cascade for self-referential relationship
1227
+ * @example Detach children when a parent category goes
1146
1228
  * ```typescript
1147
1229
  * parent: relationship({
1148
1230
  * ref: 'Category.children',
1149
- * db: {
1150
- * foreignKey: true,
1151
- * extendPrismaSchema: ({ fkLine, relationLine }) => ({
1152
- * fkLine,
1153
- * relationLine: relationLine.replace(
1154
- * '@relation(',
1155
- * '@relation(onDelete: SetNull, '
1156
- * )
1157
- * })
1158
- * }
1231
+ * db: { foreignKey: true, onDelete: 'setNull' },
1159
1232
  * })
1160
1233
  * ```
1161
1234
  */
1162
- extendPrismaSchema?: (lines: {
1163
- /** The foreign key field line (e.g., "parentId String?"), only present for single relationships that own the FK */
1164
- fkLine?: string;
1165
- /** The relation field line (e.g., "parent Category? @relation(...)") */
1166
- relationLine: string;
1167
- }) => {
1168
- fkLine?: string;
1169
- relationLine: string;
1170
- };
1235
+ onDelete?: ReferentialAction;
1236
+ /**
1237
+ * What the database does to this row's foreign key when the referenced
1238
+ * row's id changes. Only meaningful on the foreign-key-owning side.
1239
+ */
1240
+ onUpdate?: ReferentialAction;
1171
1241
  };
1172
1242
  ui?: {
1173
1243
  displayMode?: 'select' | 'cards';
@@ -1179,61 +1249,8 @@ export type RelationshipField<TTypeInfo extends TypeInfo = TypeInfo> = BaseField
1179
1249
  */
1180
1250
  itemView?: RelationshipItemViewConfig;
1181
1251
  };
1182
- /**
1183
- * Get the complete Prisma schema contribution for this relationship field.
1184
- *
1185
- * Relationships are special: unlike scalar fields (which return a single
1186
- * type via `getPrismaType`), a relationship can contribute a foreign key
1187
- * line, a relation line on the owning model, and a synthetic back-relation
1188
- * line on the target model. This method encapsulates all of that logic so
1189
- * the generator can remain a neutral coordinator.
1190
- *
1191
- * @param fieldName - The name of this relationship field
1192
- * @param allFields - All fields on the list this relationship belongs to
1193
- * @param listKey - The name of the list this relationship belongs to
1194
- * @param config - The full OpenSaas config (used to resolve the target list/field)
1195
- */
1196
- getPrismaRelation?: (fieldName: string, allFields: Record<string, FieldConfig>, listKey: string, config: OpenSaasConfig) => PrismaRelationResult;
1197
1252
  };
1198
- /**
1199
- * The complete Prisma schema contribution of a relationship field.
1200
- */
1201
- export type PrismaRelationResult = {
1202
- /**
1203
- * Lines to add to the owning model.
1204
- * For an FK-owning single relationship this is `[fkLine, relationLine]`;
1205
- * for the many side or the non-FK side it is `[relationLine]`.
1206
- */
1207
- modelLines: string[];
1208
- /**
1209
- * The Prisma-level foreign key field name this side owns (e.g. `authorId`),
1210
- * regardless of whether it is indexed. `undefined` when this side doesn't
1211
- * own a foreign key column at all (the many side, or the non-FK side of a
1212
- * one-to-one). Lets other generator passes resolve a relationship field
1213
- * name to its physical column — e.g. a model-level composite index
1214
- * ({@link ListIndex}) naming a relationship field — without duplicating
1215
- * {@link foreignKeyIndex}'s narrower, indexing-conditional presence.
1216
- */
1217
- foreignKeyField?: string;
1218
- /**
1219
- * Foreign key index to add to the owning model, if this side owns an
1220
- * indexed foreign key.
1221
- */
1222
- foreignKeyIndex?: {
1223
- foreignKeyField: string;
1224
- indexType: boolean | 'unique';
1225
- };
1226
- /**
1227
- * Synthetic back-relation field to add to the target model. Only present
1228
- * for list-only refs (e.g., `ref: 'Category'`), where the target model
1229
- * needs an opposite relation field for Prisma to validate the relation.
1230
- */
1231
- backRelation?: {
1232
- targetList: string;
1233
- line: string;
1234
- };
1235
- };
1236
- export type JsonField<TTypeInfo extends TypeInfo = TypeInfo> = BaseFieldConfig<TTypeInfo> & {
1253
+ export type JsonField<TTypeInfo extends TypeInfo = TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
1237
1254
  type: 'json';
1238
1255
  validation?: {
1239
1256
  isRequired?: boolean;
@@ -1271,14 +1288,9 @@ export type TypeDescriptor = string | {
1271
1288
  */
1272
1289
  name?: string;
1273
1290
  };
1274
- export type VirtualField<TTypeInfo extends TypeInfo> = BaseFieldConfig<TTypeInfo> & {
1291
+ export type VirtualField<TTypeInfo extends TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey> & {
1275
1292
  type: 'virtual';
1276
1293
  virtual: true;
1277
- /**
1278
- * TypeScript type string for the virtual field output
1279
- * e.g., 'string', 'number', 'boolean', 'string[]', etc.
1280
- */
1281
- outputType: string;
1282
1294
  };
1283
1295
  /**
1284
1296
  * Generic field configuration type
@@ -1287,9 +1299,37 @@ export type VirtualField<TTypeInfo extends TypeInfo> = BaseFieldConfig<TTypeInfo
1287
1299
  * but at the config level we treat all fields uniformly
1288
1300
  */
1289
1301
  export type FieldConfig = BaseFieldConfig<TypeInfo>;
1290
- type WithTypeInfo<TTypeInfo extends TypeInfo> = BaseFieldConfig<TTypeInfo>;
1291
- export type FieldsWithTypeInfo<TTypeInfo extends TypeInfo> = {
1302
+ type WithTypeInfo<TTypeInfo extends TypeInfo, TKey extends FieldKeys<TTypeInfo['fields']> = FieldKeys<TTypeInfo['fields']>> = BaseFieldConfig<TTypeInfo, TKey>;
1303
+ /**
1304
+ * The type every entry of `list()`'s `fields` object is checked against.
1305
+ *
1306
+ * Gated on `TTypeInfo['item']` being concrete (issue #1306): once a real,
1307
+ * generated `TypeInfo` is in hand (`list<Lists.Post.TypeInfo>({...})`), each
1308
+ * entry is checked against {@link WithTypeInfo} pinned to ITS OWN key, so a
1309
+ * field builder written the same way as every field in this repo — generic
1310
+ * over `TTypeInfo` — has that key flow all the way into its `hooks`, and
1311
+ * `GetFieldValueType` resolves precisely rather than falling back to
1312
+ * `unknown`.
1313
+ *
1314
+ * The pre-generation flow (`list({ fields: {...} })`, no explicit
1315
+ * `TTypeInfo`) has no per-field key to pin — `TTypeInfo` defaults to the
1316
+ * bare, unbound `TypeInfo`. The conditional keeps that flow on the untouched,
1317
+ * unkeyed index signature: a naked conditional type blocks TypeScript's
1318
+ * reverse-mapped-type inference from firing while `TTypeInfo` is itself
1319
+ * still being inferred, so this flow types exactly as it did before
1320
+ * `BaseFieldConfig` gained a key parameter at all.
1321
+ *
1322
+ * Each entry stays OPTIONAL, exactly as the index signature it replaces never
1323
+ * required any key at all: `list<Lists.X.TypeInfo>({...})` is additive type
1324
+ * safety over an already-generated config, not a completeness check, and a
1325
+ * type-level fixture testing one field's hook in isolation is a legitimate
1326
+ * partial `fields` object. A key outside `TTypeInfo['fields']` is still
1327
+ * refused — the mapped type has no index signature of its own.
1328
+ */
1329
+ export type FieldsWithTypeInfo<TTypeInfo extends TypeInfo> = IsAny<TTypeInfo['item']> extends true ? {
1292
1330
  [key: string]: WithTypeInfo<TTypeInfo>;
1331
+ } : {
1332
+ [K in FieldKeys<TTypeInfo['fields']>]?: WithTypeInfo<TTypeInfo, K>;
1293
1333
  };
1294
1334
  /**
1295
1335
  * Parse TypeScript type string to actual type
@@ -1302,26 +1342,6 @@ export type FieldsWithTypeInfo<TTypeInfo extends TypeInfo> = {
1302
1342
  * ParseTypeString<"import('@opensaas/stack-core').HashedPassword"> => any (fallback for imports)
1303
1343
  */
1304
1344
  type ParseTypeString<T extends string> = T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'Date' ? Date : T extends 'unknown' ? unknown : T extends `'${infer U}'` ? U : T extends `${infer U} | ${infer V}` ? ParseTypeString<U> | ParseTypeString<V> : T extends `import(${string}).${string}` ? any : unknown;
1305
- /**
1306
- * Extract field value type from a field config
1307
- * Uses the field's getTypeScriptType() method result
1308
- * If resultExtension is present, uses its outputType instead
1309
- *
1310
- * @example
1311
- * ExtractFieldValueType<TextField> => string | null | undefined (if optional)
1312
- * ExtractFieldValueType<IntegerField> => number
1313
- * ExtractFieldValueType<PasswordField> => HashedPassword (from resultExtension)
1314
- */
1315
- type ExtractFieldValueType<TField extends BaseFieldConfig<any>> = TField extends {
1316
- resultExtension: {
1317
- outputType: infer O;
1318
- };
1319
- } ? ParseTypeString<O & string> : TField extends {
1320
- getTypeScriptType(): {
1321
- type: infer T;
1322
- optional: infer Opt;
1323
- };
1324
- } ? Opt extends true ? ParseTypeString<T & string> | null | undefined : ParseTypeString<T & string> : unknown;
1325
1345
  /**
1326
1346
  * Extract field names as union of string literals
1327
1347
  *
@@ -1338,14 +1358,57 @@ export type FieldKeys<TFields extends Record<string, any>> = keyof TFields & str
1338
1358
  */
1339
1359
  export type GetFieldConfig<TFields extends Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any -- Generic utility type needs to accept any field record
1340
1360
  TFieldKey extends FieldKeys<TFields>> = TFields[TFieldKey];
1361
+ /** Whether `T` is `any`, which `keyof` would otherwise widen a lookup through. */
1362
+ type IsAny<T> = 0 extends 1 & T ? true : false;
1363
+ /**
1364
+ * A stored field's value type: the property the generated `Lists.<List>.Item`
1365
+ * carries for it (ADR-0052 — the contract column types the field, and `item`
1366
+ * is where that lands). `unknown` only for a hand-authored `TypeInfo`, whose
1367
+ * `item` carries no per-field facts to read.
1368
+ */
1369
+ type StoredFieldValueType<TTypeInfo extends TypeInfo, TFieldKey extends PropertyKey> = IsAny<TTypeInfo['item']> extends true ? unknown : TFieldKey extends keyof TTypeInfo['item'] ? TTypeInfo['item'][TFieldKey] : unknown;
1341
1370
  /**
1342
- * Get value type for a specific field
1371
+ * Whether `TKey` names more than one field. Every branch below is written
1372
+ * non-distributively over a single key, so a union has to be turned away
1373
+ * before it reaches them.
1374
+ */
1375
+ type IsSeveralKeys<TKey, TAll = TKey> = TKey extends unknown ? [TAll] extends [TKey] ? false : true : never;
1376
+ /**
1377
+ * One field's value type: its declared `outputType` when its static type
1378
+ * declares one, and otherwise the stored row's property — so a stored field is
1379
+ * typed by its contract column rather than left open.
1380
+ *
1381
+ * `unknown` when `TFieldKey` names several fields — the fallback for a
1382
+ * `FieldHooks<TTypeInfo>` instantiated with no key of its own (a third-party
1383
+ * field that doesn't thread {@link BaseFieldConfig}'s `TKey` through, or a
1384
+ * hand-authored `TypeInfo` used generically). Resolving a genuine union would
1385
+ * type each field's hook by the whole row: a `text()` hook would accept a
1386
+ * `Date` and reject its own `string`. At the real, generated-`TypeInfo`
1387
+ * instantiation (`list<Lists.Post.TypeInfo>({ fields: { title: text(...) } })`)
1388
+ * {@link FieldsWithTypeInfo} pins each field's own key before it ever reaches
1389
+ * here, so this guard is a fallback, not the common case (issue #1306).
1343
1390
  *
1344
1391
  * @example
1345
- * GetFieldValueType<{ title: TextField }, 'title'> => string
1392
+ * GetFieldValueType<Lists.Post.TypeInfo, 'title'> => string
1346
1393
  */
1347
- export type GetFieldValueType<TFields extends Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any -- Generic utility type needs to accept any field record
1348
- TFieldKey extends FieldKeys<TFields>> = ExtractFieldValueType<GetFieldConfig<TFields, TFieldKey>>;
1394
+ export type GetFieldValueType<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<TTypeInfo['fields']>> = IsSeveralKeys<TFieldKey> extends false ? DeclaredOrStoredValueType<TTypeInfo, TFieldKey> : unknown;
1395
+ /**
1396
+ * The resolution for a single field key: `outputType` in either spelling,
1397
+ * falling through to the stored row. Written as tuple comparisons so nothing
1398
+ * distributes and no marker type is needed to spell "declared none" — a
1399
+ * sentinel here would surface verbatim in a consumer's error message.
1400
+ */
1401
+ type DeclaredOrStoredValueType<TTypeInfo extends TypeInfo, TFieldKey extends FieldKeys<TTypeInfo['fields']>> = [GetFieldConfig<TTypeInfo['fields'], TFieldKey>] extends [
1402
+ {
1403
+ outputType: infer O extends string;
1404
+ }
1405
+ ] ? ParseTypeString<O> : [GetFieldConfig<TTypeInfo['fields'], TFieldKey>] extends [
1406
+ {
1407
+ outputType: {
1408
+ value: new (...args: any[]) => infer I;
1409
+ };
1410
+ }
1411
+ ] ? I : StoredFieldValueType<TTypeInfo, TFieldKey>;
1349
1412
  /**
1350
1413
  * TypeInfo interface for list type information
1351
1414
  * Provides a structured way to pass all type information for a list
@@ -1353,17 +1416,18 @@ TFieldKey extends FieldKeys<TFields>> = ExtractFieldValueType<GetFieldConfig<TFi
1353
1416
  *
1354
1417
  * @template TKey - The list key/name (e.g., 'Post', 'User')
1355
1418
  * @template TFields - The fields configuration for the list
1356
- * @template TPrisma - The consuming app's own Prisma client type. Defaults to
1357
- * {@link PrismaClientLike} so a `TypeInfo` written (or defaulted) without it
1358
- * keeps today's behaviour — a hook's `context` resolves to `StackContext`
1359
- * over an unnamed client, same as before this member existed.
1419
+ * @template TDb - The app's generated `db` surface (ADR-0052's `DB`, the same
1420
+ * type the generated `Context`/`BaseContext` instantiate). Defaults to
1421
+ * `unknown`, never {@link AccessControlledDB} directly: the generated `DB`
1422
+ * is an `interface` with no index signature (ADR-0032), so pinning the
1423
+ * default there would make `TypeInfo` (bare, as every field builder bounds
1424
+ * its own `TTypeInfo extends TypeInfo`) demand one from every list's real
1425
+ * `db` and reject it as "index signature is missing" on every field. A
1426
+ * `TypeInfo` written (or defaulted) without `TDb` keeps today's behaviour —
1427
+ * `HookDb` resolves the hook's `context.db` to {@link AccessControlledDB}.
1360
1428
  * @template TItem - The output type (Prisma model type)
1361
1429
  * @template TCreateInput - The Prisma create input type
1362
1430
  * @template TUpdateInput - The Prisma update input type
1363
- * @template TDb - The app's own generated `db` surface (the CLI's `CustomDB`),
1364
- * with virtual and transformed fields folded into every list's payload.
1365
- * Defaults to `AccessControlledDB<TPrisma>` — the plain Prisma-shaped view —
1366
- * so a `TypeInfo` written (or defaulted) without it keeps today's behaviour.
1367
1431
  *
1368
1432
  * @example
1369
1433
  * ```typescript
@@ -1375,13 +1439,12 @@ TFieldKey extends FieldKeys<TFields>> = ExtractFieldValueType<GetFieldConfig<TFi
1375
1439
  * create: Prisma.PostCreateInput
1376
1440
  * update: Prisma.PostUpdateInput
1377
1441
  * }
1378
- * prisma: PrismaClient
1379
- * db: CustomDB
1442
+ * db: DB
1380
1443
  * }
1381
1444
  * ```
1382
1445
  */
1383
1446
  export interface TypeInfo<TKey extends string = string, TFields extends Record<string, any> = Record<string, any>, // eslint-disable-line @typescript-eslint/no-explicit-any -- TypeInfo must accept any field record
1384
- TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> {
1447
+ TDb = unknown> {
1385
1448
  key: TKey;
1386
1449
  fields: TFields;
1387
1450
  item: any;
@@ -1390,18 +1453,71 @@ TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TP
1390
1453
  update: any;
1391
1454
  };
1392
1455
  /**
1393
- * The consuming app's own Prisma client type, so a hook's `context` can be
1394
- * keyed as `StackContext<TPrisma>`/`AccessContext<TPrisma>` instead of
1395
- * resolving through the unparameterised {@link PrismaClientLike} default.
1456
+ * What a caller receives from a read of this list — the stored row plus its
1457
+ * computed fields. `item` is the narrower stored row a hook sees, which
1458
+ * never carries a computed value (ADR-0027).
1396
1459
  */
1397
- prisma: TPrisma;
1460
+ output?: unknown;
1398
1461
  /**
1399
- * The app's own generated `db` surface (see {@link TDb}), so a hook's
1400
- * `context.db` describes the same virtual/transformed-field-augmented rows
1401
- * the app's own generated `db` surface produces for the same read (#1232).
1462
+ * Per-field declared-dependency facts (ADR-0051). `needs` is the field's
1463
+ * declared set as a union of column and relation keys; `item` is that set
1464
+ * resolved against the contract — exactly what the runtime hands the
1465
+ * field's `resolveOutput` hook, which is what makes reading an undeclared
1466
+ * column a compile error.
1467
+ *
1468
+ * Written by `pnpm generate`; absent on a hand-authored `TypeInfo`, where
1469
+ * a hook's `item` falls back to the whole stored row.
1470
+ */
1471
+ needs?: Record<string, {
1472
+ needs?: string;
1473
+ item?: unknown;
1474
+ }>;
1475
+ /**
1476
+ * The app's generated `db` surface — the same `DB` the generated `Context`
1477
+ * and `BaseContext` instantiate. A hook's `context` is keyed off it, so
1478
+ * `context.db.<misspelled list>` is a compile error and `context.db.<real
1479
+ * list>` is that list's own `SecuredList` (ADR-0052's amendment for
1480
+ * #1211/#1213).
1481
+ *
1482
+ * Written by `pnpm generate`; absent (or `unknown`) on a hand-authored
1483
+ * `TypeInfo`, where {@link HookDb} falls back to {@link AccessControlledDB}.
1402
1484
  */
1403
- db: TDb;
1485
+ db?: TDb;
1404
1486
  }
1487
+ /**
1488
+ * The `db` surface a hook's `context` is keyed to: {@link TypeInfo.db} when
1489
+ * the `TypeInfo` carries a real one, else {@link AccessControlledDB} —
1490
+ * applied both where a hand-authored `TypeInfo` omits the member entirely
1491
+ * (mirrors {@link FieldNeedsItem}'s `NonNullable<TTypeInfo['needs']>` pattern
1492
+ * for the same reason) and where `TypeInfo`'s own `TDb` default (`unknown`)
1493
+ * is standing in for it.
1494
+ *
1495
+ * Also falls back for `TTypeInfo = any` — the untyped `list()` shape
1496
+ * (`OpenSaasConfig['lists']` is `Record<string, ListConfig<any>>`) — where
1497
+ * `TTypeInfo['db']` would otherwise resolve to bare `any` and poison every
1498
+ * `context.db.<list>` chain in the hook to `any`, turning a genuine
1499
+ * `noImplicitAny` violation on the caller's own code into a silent pass.
1500
+ *
1501
+ * A hand-authored `TypeInfo.db` (the third-party-field pattern) is trusted
1502
+ * as given, unlike `StackContext`/`StackBaseContext`'s `DB extends
1503
+ * StackDb<DB>` (`types/context.ts`): that self-referential constraint can't
1504
+ * be re-verified through this indexed-access alias applied to an
1505
+ * as-yet-unresolved `TTypeInfo` without rejecting every real, generated `DB`
1506
+ * as "index signature is missing" (see the constraint dropped from
1507
+ * `AccessContext` in `access/types.ts`, and from `TypeInfo`'s own `TDb`
1508
+ * above). So a `TypeInfo.db` naming a raw ORM client, rather than a `DB`
1509
+ * surface, is not caught here the way it would be on `StackContext`.
1510
+ */
1511
+ export type HookDb<TTypeInfo extends TypeInfo> = IsAny<TTypeInfo> extends true ? AccessControlledDB : unknown extends TTypeInfo['db'] ? AccessControlledDB : NonNullable<TTypeInfo['db']>;
1512
+ /**
1513
+ * The `item` a field's `resolveOutput` hook is handed: its declared
1514
+ * dependency set plus the list's system fields, resolved by `pnpm generate`
1515
+ * and read back off {@link TypeInfo.needs}. Falls back to the whole stored
1516
+ * row for a `TypeInfo` that carries no declared-dependency facts.
1517
+ */
1518
+ export type FieldNeedsItem<TTypeInfo extends TypeInfo, TFieldKey extends PropertyKey> = NonNullable<TTypeInfo['needs']> extends infer TNeeds ? TFieldKey extends keyof TNeeds ? TNeeds[TFieldKey] extends {
1519
+ item: infer TItem;
1520
+ } ? TItem : TTypeInfo['item'] : TTypeInfo['item'] : TTypeInfo['item'];
1405
1521
  export type OperationAccess<T = any> = {
1406
1522
  query?: AccessControl<T>;
1407
1523
  /**
@@ -1409,7 +1525,7 @@ export type OperationAccess<T = any> = {
1409
1525
  * but at runtime `create` accepts a `boolean` result only. There is no
1410
1526
  * existing row to scope with a filter, and — unlike `update`/`delete`,
1411
1527
  * which re-check a returned filter against the target row via
1412
- * `findFirst` — no equivalent re-check exists for a row that doesn't exist
1528
+ * a read of the target — no equivalent re-check exists for a row that doesn't exist
1413
1529
  * in the database yet. A rule that returns a filter (or any other
1414
1530
  * non-boolean) throws `InvalidCreateAccessResultError` rather than being
1415
1531
  * treated as an allow (see #1009, ADR-0022, ADR-0030). To scope create by
@@ -1463,20 +1579,20 @@ export type ListAccessControl<T = any> = AccessControl<T> | {
1463
1579
  * - create: resolvedData is CreateInput, item is undefined
1464
1580
  * - update: resolvedData is UpdateInput, item is the existing record
1465
1581
  */
1466
- export type ResolveInputHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1582
+ export type ResolveInputHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1467
1583
  listKey: string;
1468
1584
  operation: 'create';
1469
1585
  inputData: TCreateInput;
1470
1586
  resolvedData: TCreateInput;
1471
1587
  item: undefined;
1472
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1588
+ context: import('../access/types.js').AccessContext<TDb>;
1473
1589
  } | {
1474
1590
  listKey: string;
1475
1591
  operation: 'update';
1476
1592
  inputData: TUpdateInput;
1477
1593
  resolvedData: TUpdateInput;
1478
1594
  item: TOutput;
1479
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1595
+ context: import('../access/types.js').AccessContext<TDb>;
1480
1596
  };
1481
1597
  /**
1482
1598
  * Hook arguments for the list-level `validate` hook (renamed from `validateInput` for Keystone compatibility).
@@ -1484,13 +1600,13 @@ export type ResolveInputHookArgs<TOutput = Record<string, unknown>, TCreateInput
1484
1600
  * - update: resolvedData is UpdateInput, item is the existing record
1485
1601
  * - delete: item is the item being deleted
1486
1602
  */
1487
- export type ValidateHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1603
+ export type ValidateHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1488
1604
  listKey: string;
1489
1605
  operation: 'create';
1490
1606
  inputData: TCreateInput;
1491
1607
  resolvedData: TCreateInput;
1492
1608
  item: undefined;
1493
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1609
+ context: import('../access/types.js').AccessContext<TDb>;
1494
1610
  addValidationError: (msg: string) => void;
1495
1611
  } | {
1496
1612
  listKey: string;
@@ -1498,13 +1614,13 @@ export type ValidateHookArgs<TOutput = Record<string, unknown>, TCreateInput = R
1498
1614
  inputData: TUpdateInput;
1499
1615
  resolvedData: TUpdateInput;
1500
1616
  item: TOutput;
1501
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1617
+ context: import('../access/types.js').AccessContext<TDb>;
1502
1618
  addValidationError: (msg: string) => void;
1503
1619
  } | {
1504
1620
  listKey: string;
1505
1621
  operation: 'delete';
1506
1622
  item: TOutput;
1507
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1623
+ context: import('../access/types.js').AccessContext<TDb>;
1508
1624
  addValidationError: (msg: string) => void;
1509
1625
  };
1510
1626
  /**
@@ -1513,38 +1629,42 @@ export type ValidateHookArgs<TOutput = Record<string, unknown>, TCreateInput = R
1513
1629
  * - update: has inputData, resolvedData, and item
1514
1630
  * - delete: has item only
1515
1631
  */
1516
- export type BeforeOperationHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1632
+ export type BeforeOperationHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1517
1633
  listKey: string;
1518
1634
  operation: 'create';
1519
1635
  inputData: TCreateInput;
1520
1636
  resolvedData: TCreateInput;
1521
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1637
+ context: import('../access/types.js').AccessContext<TDb>;
1522
1638
  } | {
1523
1639
  listKey: string;
1524
1640
  operation: 'update';
1525
1641
  inputData: TUpdateInput;
1526
1642
  item: TOutput;
1527
1643
  resolvedData: TUpdateInput;
1528
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1644
+ context: import('../access/types.js').AccessContext<TDb>;
1529
1645
  } | {
1530
1646
  listKey: string;
1531
1647
  operation: 'delete';
1532
1648
  item: TOutput;
1533
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1649
+ context: import('../access/types.js').AccessContext<TDb>;
1534
1650
  };
1535
1651
  /**
1536
1652
  * Hook arguments for the list-level `afterOperation` hook.
1537
1653
  * - create: has item, inputData, and resolvedData, no originalItem
1538
1654
  * - update: has item, originalItem, inputData, and resolvedData
1539
1655
  * - delete: has originalItem only
1656
+ *
1657
+ * An update whose resolved payload is empty writes nothing (and does not move
1658
+ * `updatedAt`) but still runs `afterOperation`, with `item` equal to
1659
+ * `originalItem`. A hook that must skip no-ops compares the two.
1540
1660
  */
1541
- export type AfterOperationHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1661
+ export type AfterOperationHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1542
1662
  listKey: string;
1543
1663
  operation: 'create';
1544
1664
  inputData: TCreateInput;
1545
1665
  item: TOutput;
1546
1666
  resolvedData: TCreateInput;
1547
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1667
+ context: import('../access/types.js').AccessContext<TDb>;
1548
1668
  } | {
1549
1669
  listKey: string;
1550
1670
  operation: 'update';
@@ -1552,12 +1672,12 @@ export type AfterOperationHookArgs<TOutput = Record<string, unknown>, TCreateInp
1552
1672
  originalItem: TOutput;
1553
1673
  item: TOutput;
1554
1674
  resolvedData: TUpdateInput;
1555
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1675
+ context: import('../access/types.js').AccessContext<TDb>;
1556
1676
  } | {
1557
1677
  listKey: string;
1558
1678
  operation: 'delete';
1559
1679
  originalItem: TOutput;
1560
- context: import('../context/index.js').StackContext<TPrisma, TDb>;
1680
+ context: import('../access/types.js').AccessContext<TDb>;
1561
1681
  };
1562
1682
  /**
1563
1683
  * Hook arguments for the list-level beforeTransaction hook (#590 / ADR-0010).
@@ -1568,22 +1688,22 @@ export type AfterOperationHookArgs<TOutput = Record<string, unknown>, TCreateInp
1568
1688
  * `undefined` for nested targets. For non-transactional side effects whose
1569
1689
  * compensation pairs with `afterTransaction`.
1570
1690
  */
1571
- export type BeforeTransactionHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1691
+ export type BeforeTransactionHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1572
1692
  listKey: string;
1573
1693
  operation: 'create';
1574
1694
  inputData: TCreateInput;
1575
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1695
+ context: import('../access/types.js').AccessContext<TDb>;
1576
1696
  } | {
1577
1697
  listKey: string;
1578
1698
  operation: 'update';
1579
1699
  inputData: TUpdateInput;
1580
1700
  item: TOutput | undefined;
1581
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1701
+ context: import('../access/types.js').AccessContext<TDb>;
1582
1702
  } | {
1583
1703
  listKey: string;
1584
1704
  operation: 'delete';
1585
1705
  item: TOutput | undefined;
1586
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1706
+ context: import('../access/types.js').AccessContext<TDb>;
1587
1707
  };
1588
1708
  /**
1589
1709
  * Hook arguments for the list-level afterTransaction hook (#590 / ADR-0010).
@@ -1600,24 +1720,27 @@ export type BeforeTransactionHookArgs<TOutput = Record<string, unknown>, TCreate
1600
1720
  * `afterOperation` (which receives the correct nested `item`);
1601
1721
  * transaction-boundary hooks are for external-call compensation keyed off
1602
1722
  * `status`/`inputData`.
1723
+ * - `item` is the raw persisted row, the same one `afterOperation` receives —
1724
+ * not the session's Field Visibility projection: columns the session cannot
1725
+ * read are present and `resolveOutput` transforms are not applied.
1603
1726
  * - `rolled-back`: NO persisted `item`; the hook gets `inputData` and the
1604
1727
  * `error` that caused the rollback so it can compensate.
1605
1728
  */
1606
- export type AfterTransactionHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1729
+ export type AfterTransactionHookArgs<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1607
1730
  listKey: string;
1608
1731
  operation: 'create';
1609
1732
  status: 'committed';
1610
1733
  inputData: TCreateInput;
1611
1734
  /** Persisted row — populated for the top-level list only; `undefined` for nested lists. */
1612
1735
  item: TOutput | undefined;
1613
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1736
+ context: import('../access/types.js').AccessContext<TDb>;
1614
1737
  } | {
1615
1738
  listKey: string;
1616
1739
  operation: 'create';
1617
1740
  status: 'rolled-back';
1618
1741
  inputData: TCreateInput;
1619
1742
  error: unknown;
1620
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1743
+ context: import('../access/types.js').AccessContext<TDb>;
1621
1744
  } | {
1622
1745
  listKey: string;
1623
1746
  operation: 'update';
@@ -1627,7 +1750,7 @@ export type AfterTransactionHookArgs<TOutput = Record<string, unknown>, TCreateI
1627
1750
  originalItem: TOutput | undefined;
1628
1751
  /** Persisted row — populated for the top-level list only; `undefined` for nested lists. */
1629
1752
  item: TOutput | undefined;
1630
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1753
+ context: import('../access/types.js').AccessContext<TDb>;
1631
1754
  } | {
1632
1755
  listKey: string;
1633
1756
  operation: 'update';
@@ -1635,34 +1758,34 @@ export type AfterTransactionHookArgs<TOutput = Record<string, unknown>, TCreateI
1635
1758
  inputData: TUpdateInput;
1636
1759
  originalItem: TOutput | undefined;
1637
1760
  error: unknown;
1638
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1761
+ context: import('../access/types.js').AccessContext<TDb>;
1639
1762
  } | {
1640
1763
  listKey: string;
1641
1764
  operation: 'delete';
1642
1765
  status: 'committed';
1643
1766
  /** Pre-write row — populated for the top-level list only; `undefined` for nested lists. */
1644
1767
  originalItem: TOutput | undefined;
1645
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1768
+ context: import('../access/types.js').AccessContext<TDb>;
1646
1769
  } | {
1647
1770
  listKey: string;
1648
1771
  operation: 'delete';
1649
1772
  status: 'rolled-back';
1650
1773
  originalItem: TOutput | undefined;
1651
1774
  error: unknown;
1652
- context: import('../access/types.js').AccessContext<TPrisma, TDb>;
1775
+ context: import('../access/types.js').AccessContext<TDb>;
1653
1776
  };
1654
- export type Hooks<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TPrisma extends PrismaClientLike = PrismaClientLike, TDb = AccessControlledDB<TPrisma>> = {
1655
- resolveInput?: (args: ResolveInputHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<TCreateInput | TUpdateInput>;
1656
- validate?: (args: ValidateHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void>;
1657
- beforeOperation?: (args: BeforeOperationHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void>;
1658
- afterOperation?: (args: AfterOperationHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void>;
1777
+ export type Hooks<TOutput = Record<string, unknown>, TCreateInput = Record<string, unknown>, TUpdateInput = Record<string, unknown>, TDb = AccessControlledDB> = {
1778
+ resolveInput?: (args: ResolveInputHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<TCreateInput | TUpdateInput>;
1779
+ validate?: (args: ValidateHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void>;
1780
+ beforeOperation?: (args: BeforeOperationHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void>;
1781
+ afterOperation?: (args: AfterOperationHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void>;
1659
1782
  /**
1660
1783
  * Side effect BEFORE the write's transaction opens (#590 / ADR-0010).
1661
1784
  * Runs OUTSIDE the transaction — for non-transactional work (external API
1662
1785
  * calls). Throwing aborts the write; the paired `afterTransaction` then fires
1663
1786
  * with `status: 'rolled-back'`. See {@link BeforeTransactionHookArgs}.
1664
1787
  */
1665
- beforeTransaction?: (args: BeforeTransactionHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void> | void;
1788
+ beforeTransaction?: (args: BeforeTransactionHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void> | void;
1666
1789
  /**
1667
1790
  * Side effect AFTER the write's transaction settles (#590 / ADR-0010).
1668
1791
  * ALWAYS runs when `beforeTransaction` ran; receives `committed | rolled-back`
@@ -1670,27 +1793,34 @@ export type Hooks<TOutput = Record<string, unknown>, TCreateInput = Record<strin
1670
1793
  * AND only for the top-level record (`undefined` for nested lists). The
1671
1794
  * compensation half of the transaction-boundary bracket. See
1672
1795
  * {@link AfterTransactionHookArgs}.
1796
+ *
1797
+ * A throw is reported to `onAfterTransactionError`, never propagated: the
1798
+ * write's result is unchanged and every other compensator still runs.
1673
1799
  */
1674
- afterTransaction?: (args: AfterTransactionHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void> | void;
1800
+ afterTransaction?: (args: AfterTransactionHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void> | void;
1675
1801
  /**
1676
1802
  * @deprecated Use 'validate' instead. This alias is provided for backwards compatibility.
1677
1803
  */
1678
- validateInput?: (args: ValidateHookArgs<TOutput, TCreateInput, TUpdateInput, TPrisma, TDb>) => Promise<void>;
1804
+ validateInput?: (args: ValidateHookArgs<TOutput, TCreateInput, TUpdateInput, TDb>) => Promise<void>;
1679
1805
  };
1680
1806
  /**
1681
- * A single field reference within a model-level {@link ListIndex}. Either
1682
- * just the OpenSaaS field name, or an object naming it alongside a sort
1683
- * direction.
1807
+ * The five referential actions a foreign key can carry, in the ORM's own
1808
+ * spelling so the generated contract re-emits the value verbatim.
1809
+ */
1810
+ export type ReferentialAction = 'cascade' | 'restrict' | 'noAction' | 'setNull' | 'setDefault';
1811
+ /**
1812
+ * A single field reference within a model-level {@link ListIndex}: the
1813
+ * OpenSaaS field name, bare or wrapped. An index column carries no sort
1814
+ * direction (ADR-0040); a `sort` key on the wrapped form is refused at
1815
+ * generation.
1684
1816
  */
1685
1817
  export type ListIndexFieldRef = string | {
1686
1818
  field: string;
1687
- /** Sort direction for this column within the index/constraint. */
1688
- sort?: 'asc' | 'desc';
1689
1819
  };
1690
1820
  /**
1691
- * A model-level `@@unique`/`@@index` constraint spanning one or more of a
1692
- * list's own fields. See {@link ListConfig.db}'s `indexes` for the full
1693
- * explanation and examples (#864, #918).
1821
+ * A model-level unique constraint or index spanning one or more of a list's
1822
+ * own fields. See {@link ListConfig.db}'s `indexes` for the full explanation
1823
+ * and examples (#864, #918).
1694
1824
  */
1695
1825
  export type ListIndex = {
1696
1826
  /**
@@ -1698,23 +1828,55 @@ export type ListIndex = {
1698
1828
  * OpenSaaS field names, not raw database column names.
1699
1829
  *
1700
1830
  * One or more fields — a named single-column constraint is as legitimate
1701
- * as a composite one, and is the form to reach for when a live table's
1702
- * constraint carries a name Prisma wouldn't derive on its own. Field-level
1703
- * `isIndexed` remains the sugar for the unnamed single-column case; this
1704
- * is the full form when a name or a sort direction is needed.
1831
+ * as a composite one. Field-level `isIndexed` remains the sugar for the
1832
+ * unnamed single-column case; this is the full form when a name is needed.
1705
1833
  */
1706
1834
  fields: ListIndexFieldRef[];
1707
1835
  /**
1708
- * Emit `@@unique([...])` instead of `@@index([...])`.
1836
+ * Emit a unique constraint instead of an index.
1709
1837
  * @default false
1710
1838
  */
1711
1839
  unique?: boolean;
1712
1840
  /**
1713
- * Constraint/index name, emitted as Prisma's `map:` argument — lets an
1714
- * existing live constraint be adopted under its current name rather than
1715
- * renamed.
1841
+ * The constraint/index's wire name, emitted as the contract's `name:`.
1716
1842
  */
1717
1843
  name?: string;
1844
+ /**
1845
+ * A partial index's predicate: raw SQL, the body of a `WHERE` clause without
1846
+ * the keyword. Written in database column names. A unique entry with `where`
1847
+ * is a partial unique index rather than a unique constraint. It must also carry a `name`, which is adopted as the index's exact name.
1848
+ *
1849
+ * Drift detection compares this text byte-for-byte with how PostgreSQL
1850
+ * prints the predicate back, so write it in that form — copy it from the
1851
+ * `WHERE` clause of `pg_indexes.indexdef` (`("twilioSid" <> ''::text)`).
1852
+ */
1853
+ where?: string;
1854
+ };
1855
+ /**
1856
+ * A table-level foreign key constraint spanning one or more of a list's own
1857
+ * fields. It declares a constraint only: it adds no relationship, include or
1858
+ * `connect` semantics. See {@link ListConfig.db}'s `foreignKeys`.
1859
+ */
1860
+ export type ListForeignKey = {
1861
+ /**
1862
+ * This list's own OpenSaaS field names, in constraint order. A to-one
1863
+ * relationship that owns its foreign key resolves to its `<field>Id` column.
1864
+ */
1865
+ fields: ListIndexFieldRef[];
1866
+ references: {
1867
+ /** The referenced list's key. */
1868
+ list: string;
1869
+ /**
1870
+ * The referenced list's field names, positionally matching `fields`. Must
1871
+ * equal a declared unique on that list (`db.indexes` with `unique: true`,
1872
+ * or a single-field `isIndexed: 'unique'`), or be `['id']`.
1873
+ */
1874
+ fields: string[];
1875
+ };
1876
+ onDelete?: ReferentialAction;
1877
+ onUpdate?: ReferentialAction;
1878
+ /** The constraint's exact physical name, adopted verbatim. */
1879
+ name?: string;
1718
1880
  };
1719
1881
  /**
1720
1882
  * Internal list configuration type (after normalization by list() function)
@@ -1730,33 +1892,33 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1730
1892
  access?: {
1731
1893
  operation?: OperationAccess<TTypeInfo['item']>;
1732
1894
  };
1733
- hooks?: Hooks<TTypeInfo['item'], TTypeInfo['inputs']['create'], TTypeInfo['inputs']['update'], TTypeInfo['prisma'], TTypeInfo['db']>;
1895
+ hooks?: Hooks<TTypeInfo['item'], TTypeInfo['inputs']['create'], TTypeInfo['inputs']['update'], HookDb<TTypeInfo>>;
1734
1896
  /**
1735
1897
  * Database configuration for this list (model level)
1736
1898
  */
1737
1899
  db?: {
1738
1900
  /**
1739
- * Custom database table name.
1740
- * Adds a `@@map` attribute to the generated Prisma model.
1901
+ * Custom database table name. Carried on the contract model as `table`,
1902
+ * so the model name (the list key) can differ from the physical table.
1741
1903
  *
1742
- * Useful when the Prisma model name (the list key) must differ from the
1904
+ * Useful when the model name (the list key) must differ from the
1743
1905
  * physical table name — e.g. adopting an existing better-auth installation
1744
1906
  * whose tables were created under a different name.
1745
1907
  *
1746
1908
  * @example
1747
1909
  * ```typescript
1748
1910
  * AuthUser: list({ fields: { ... }, db: { map: 'user' } })
1749
- * // Generates: model AuthUser { ... @@map("user") }
1911
+ * // Contract: model AuthUser has table 'user'
1750
1912
  * ```
1751
1913
  */
1752
1914
  map?: string;
1753
1915
  /**
1754
- * Database schema for this model (Postgres multi-schema).
1755
- * Adds a `@@schema` attribute to the generated Prisma model.
1916
+ * Database schema for this model (Postgres multi-schema). Carried on the
1917
+ * contract model as its `namespace`.
1756
1918
  *
1757
- * Requires the schema to be listed in the datasource `schemas` array (see
1758
- * {@link DatabaseConfig.schemas}) and the `multiSchema` preview feature,
1759
- * both of which the generator emits automatically when `db.schemas` is set.
1919
+ * The schema must also appear in {@link DatabaseConfig.schemas}, which the
1920
+ * contract collects into its own `namespaces` list — Prisma resolves a
1921
+ * model's `namespace` against that list.
1760
1922
  *
1761
1923
  * Useful when adopting an existing installation whose tables live in a
1762
1924
  * non-`public` schema — e.g. a separate-schema better-auth layout.
@@ -1764,7 +1926,7 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1764
1926
  * @example
1765
1927
  * ```typescript
1766
1928
  * AuthUser: list({ fields: { ... }, db: { schema: 'auth' } })
1767
- * // Generates: model AuthUser { ... @@schema("auth") }
1929
+ * // Contract: model AuthUser has namespace 'auth'
1768
1930
  * ```
1769
1931
  */
1770
1932
  schema?: string;
@@ -1778,7 +1940,7 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1778
1940
  *
1779
1941
  * When timestamps resolve to on but the list already declares its own `createdAt`/
1780
1942
  * `updatedAt` field, the auto column is skipped for the declared field(s) so Prisma
1781
- * never sees a duplicate (`P1012`).
1943
+ * never sees a duplicate column.
1782
1944
  *
1783
1945
  * @example Opt a single list out of timestamps even when enabled globally
1784
1946
  * ```typescript
@@ -1790,21 +1952,40 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1790
1952
  */
1791
1953
  timestamps?: boolean;
1792
1954
  /**
1793
- * Model-level `@@unique`/`@@index` constraints spanning one or more of
1955
+ * How this list's `id` is minted, overriding the config-level
1956
+ * `db.idField` default (ADR-0048). A plugin pins this on every list it
1957
+ * injects so an app-level default cannot reach a table it owns.
1958
+ *
1959
+ * Refused on a singleton list: a singleton's id is derived from
1960
+ * `isSingleton`, and that is the one knob.
1961
+ *
1962
+ * @example A list with a serial integer key
1963
+ * ```typescript
1964
+ * Invoice: list({
1965
+ * fields: { total: integer() },
1966
+ * db: { idField: 'int autoincrement' },
1967
+ * })
1968
+ * ```
1969
+ */
1970
+ idField?: IdFieldStrategy;
1971
+ /**
1972
+ * Model-level unique constraints and indexes spanning one or more of
1794
1973
  * this list's own fields (#864, #918). See the [reference
1795
1974
  * docs](https://stack.opensaas.au/docs/reference/config-api#dbindexes)
1796
1975
  * for the full explanation, arity, and error conditions.
1797
1976
  *
1798
1977
  * Field-level `isIndexed` (on a scalar or relationship field) is the
1799
1978
  * sugar for the unnamed single-column case. `db.indexes` is the full
1800
- * form — reach for it when a constraint needs a `name` (Prisma's `map:`,
1801
- * for adopting an existing live constraint), a `sort` direction, or spans
1802
- * more than one column. Arity is incidental: each entry names one or
1803
- * more of the list's own OpenSaaS field names, not raw database column
1804
- * names. The generator resolves each to its underlying Prisma column — a
1805
- * scalar field's own name (its Prisma field name is unaffected by
1806
- * `db.map`), or a relationship field's foreign key column (`<field>Id`)
1807
- * when this side owns it.
1979
+ * form — reach for it when a constraint needs a `name` or spans more
1980
+ * than one column. Arity is incidental: each entry names one or more of
1981
+ * the list's own OpenSaaS field names, not raw database column names.
1982
+ * The generator resolves each to its underlying column — a scalar
1983
+ * field's own name (unaffected by `db.map`), or a relationship field's
1984
+ * foreign key column (`<field>Id`) when this side owns it.
1985
+ *
1986
+ * An index column carries no sort direction (ADR-0040): a `sort` key on
1987
+ * an entry's field reference fails `pnpm generate` naming the list and
1988
+ * the entry.
1808
1989
  *
1809
1990
  * A **unique** entry is the load-bearing case: it's the database-level
1810
1991
  * backstop for a business rule concurrent writes could otherwise both
@@ -1842,10 +2023,10 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1842
2023
  * indexes: [{ fields: ['student', 'production'], unique: true }],
1843
2024
  * },
1844
2025
  * })
1845
- * // Generates: @@unique([studentId, productionId])
2026
+ * // Contract: a unique constraint on [studentId, productionId]
1846
2027
  * ```
1847
2028
  *
1848
- * @example Hot lookup path (composite index) with a sort direction and an adopted constraint name
2029
+ * @example Hot lookup path (composite index) with a name
1849
2030
  * ```typescript
1850
2031
  * AuthVerification: list({
1851
2032
  * fields: {
@@ -1855,16 +2036,15 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1855
2036
  * db: {
1856
2037
  * indexes: [
1857
2038
  * {
1858
- * fields: ['identifier', { field: 'createdAt', sort: 'desc' }],
2039
+ * fields: ['identifier', 'createdAt'],
1859
2040
  * name: 'AuthVerification_identifier_createdAt_idx',
1860
2041
  * },
1861
2042
  * ],
1862
2043
  * },
1863
2044
  * })
1864
- * // Generates: @@index([identifier, createdAt(sort: Desc)], map: "AuthVerification_identifier_createdAt_idx")
1865
2045
  * ```
1866
2046
  *
1867
- * @example Naming a single-column unique constraint (adopting a live table's existing name)
2047
+ * @example Naming a single-column unique constraint
1868
2048
  * ```typescript
1869
2049
  * RateLimit: list({
1870
2050
  * fields: { key: text() }, // no isIndexed here — db.indexes owns this column instead
@@ -1872,21 +2052,49 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1872
2052
  * indexes: [{ fields: ['key'], unique: true, name: 'RateLimit_key_key' }],
1873
2053
  * },
1874
2054
  * })
1875
- * // Generates: @@unique([key], map: "RateLimit_key_key")
1876
2055
  * // Setting key's own isIndexed too would duplicate this constraint and
1877
2056
  * // fail generation — one of the two must own the column.
1878
2057
  * ```
1879
2058
  */
1880
2059
  indexes?: ListIndex[];
2060
+ /**
2061
+ * Table-level foreign key constraints, including composite ones that
2062
+ * reference a composite unique on the target. Constraint-only: no
2063
+ * relationship, include or `connect` semantics come with it.
2064
+ *
2065
+ * `fields` resolve to columns the way `db.indexes` does. `references.fields`
2066
+ * must equal a declared unique on the target or its id; generation refuses
2067
+ * an unknown or virtual field, a to-many field, mismatched arity, and a
2068
+ * reference set that is not a declared unique.
2069
+ *
2070
+ * @example
2071
+ * ```typescript
2072
+ * LessonSourceSlot: list({
2073
+ * fields: { enrolment: text(), student: text(), lessonTerm: text() },
2074
+ * db: {
2075
+ * foreignKeys: [
2076
+ * {
2077
+ * fields: ['enrolment', 'student', 'lessonTerm'],
2078
+ * references: { list: 'Enrolment', fields: ['id', 'student', 'lessonTerm'] },
2079
+ * onDelete: 'restrict',
2080
+ * onUpdate: 'restrict',
2081
+ * },
2082
+ * ],
2083
+ * },
2084
+ * })
2085
+ * ```
2086
+ */
2087
+ foreignKeys?: ListForeignKey[];
1881
2088
  };
1882
2089
  mcp?: ListMcpConfig;
1883
2090
  /**
1884
2091
  * Restricts this list to a single record (singleton pattern)
1885
2092
  * When true:
1886
2093
  * - Prevents creating multiple records
1887
- * - Auto-creates the single record on first access (if autoCreate: true, which is the default)
2094
+ * - Auto-creates the single record on first access (if autoCreate: true, which is the default,
2095
+ * and the list's `query` access rule answers a strict `true`, or the context is `sudo`)
1888
2096
  * - Provides a get() method for easy access to the singleton
1889
- * - Blocks delete and findMany operations
2097
+ * - Blocks delete and the many-row read surface
1890
2098
  * - Changes UI to show edit form instead of list view
1891
2099
  *
1892
2100
  * @example Simple boolean (auto-create enabled)
@@ -1903,7 +2111,13 @@ export type ListConfig<TTypeInfo extends TypeInfo> = {
1903
2111
  */
1904
2112
  isSingleton?: boolean | {
1905
2113
  /**
1906
- * Auto-create the singleton record on first access using field defaults
2114
+ * Auto-create the singleton record on first access using field defaults.
2115
+ *
2116
+ * Fires only for a `query` access rule that answers a strict `true`, or
2117
+ * under `sudo`. A rule that answers a filter, answers `false`, or is
2118
+ * absent makes `get()` answer `null` and write nothing — a filter-scoped
2119
+ * singleton needs `query: () => true` with the scoping moved onto the
2120
+ * fields if the row is to be auto-created.
1907
2121
  * @default true
1908
2122
  */
1909
2123
  autoCreate?: boolean;
@@ -1978,7 +2192,40 @@ export type ListUIConfig = {
1978
2192
  * ```
1979
2193
  */
1980
2194
  avatar?: boolean;
2195
+ /**
2196
+ * Hide every Create affordance for this list in the admin UI — the list
2197
+ * header, the empty state, the dashboard quick actions and a relationship
2198
+ * table's create drawer — and render the `/create` route as not-found.
2199
+ * Takes a boolean, or a function of the session resolved on the server. Only
2200
+ * what the UI offers changes; access control, hooks and server actions are
2201
+ * untouched, so a write that bypasses the UI behaves exactly as before.
2202
+ *
2203
+ * @example
2204
+ * ```typescript
2205
+ * ui: { hideCreate: ({ session }) => session?.role !== 'SUPPORT' }
2206
+ * ```
2207
+ */
2208
+ hideCreate?: ListUIOption<boolean>;
2209
+ /**
2210
+ * Hide every Delete affordance for this list in the admin UI — the list view
2211
+ * (row and bulk) and the item view. Same shape and guarantees as
2212
+ * {@link ListUIConfig.hideCreate}.
2213
+ *
2214
+ * @example
2215
+ * ```typescript
2216
+ * ui: { hideDelete: true }
2217
+ * ```
2218
+ */
2219
+ hideDelete?: ListUIOption<boolean>;
1981
2220
  };
2221
+ /**
2222
+ * A list-level UI option: a literal, or a function of the live session
2223
+ * resolved on the server. The function never crosses to the client.
2224
+ */
2225
+ export type ListUIOption<TValue> = TValue | ((args: {
2226
+ session: import('../access/types.js').AccessContext['session'];
2227
+ context: import('../access/types.js').AccessContext;
2228
+ }) => TValue | Promise<TValue>);
1982
2229
  /**
1983
2230
  * Item-view (record edit page) configuration, mirroring the `ui.listView`
1984
2231
  * shape but for the shape-derived item layout (issue #734).
@@ -2001,6 +2248,18 @@ export type ItemViewUIConfig = {
2001
2248
  * ```
2002
2249
  */
2003
2250
  order?: string[];
2251
+ /**
2252
+ * The mode the item view renders its fields in. `'read'` renders every field
2253
+ * read-only with no Save action; relationship sections still render. Takes a
2254
+ * value, or a function of the session resolved on the server. Defaults to
2255
+ * `'edit'`. UI-only: access control and server actions are unchanged.
2256
+ *
2257
+ * @example
2258
+ * ```typescript
2259
+ * ui: { itemView: { defaultFieldMode: 'read' } }
2260
+ * ```
2261
+ */
2262
+ defaultFieldMode?: ListUIOption<'edit' | 'read'>;
2004
2263
  };
2005
2264
  /**
2006
2265
  * A button variant for a custom Bulk action, matching the admin UI's Button
@@ -2138,7 +2397,7 @@ export type ListViewUIConfig = {
2138
2397
  * handler: async ({ ids, context }) => {
2139
2398
  * let n = 0
2140
2399
  * for (const id of ids) {
2141
- * const r = await context.db.post.update({
2400
+ * const r = await context.db.Post.update({
2142
2401
  * where: { id },
2143
2402
  * data: { status: 'published' },
2144
2403
  * })
@@ -2175,84 +2434,149 @@ export type ListConfigInput<TTypeInfo extends TypeInfo> = Omit<ListConfig<TTypeI
2175
2434
  */
2176
2435
  access?: ListAccessControl<TTypeInfo['item']>;
2177
2436
  };
2178
- export type DatabaseConfig = {
2179
- provider: 'postgresql' | 'mysql' | 'sqlite';
2437
+ /**
2438
+ * How a list's `id` column is minted (ADR-0048). Every list carries a single
2439
+ * `id` column; this picks its shape.
2440
+ *
2441
+ * - `'uuid7'` — time-sortable UUID, minted by the ORM. The default.
2442
+ * - `'cuid2'` — CUID, minted by the ORM.
2443
+ * - `'cuid'` — a `text` column minted as cuid2. Use it to adopt a database whose
2444
+ * ids are `text` holding cuid v1 values; existing values are left alone.
2445
+ * - `'int autoincrement'` — a serial integer key.
2446
+ *
2447
+ * A singleton list derives its id from `isSingleton` and refuses this option.
2448
+ */
2449
+ export type IdFieldStrategy = 'uuid7' | 'cuid2' | 'cuid' | 'int autoincrement';
2450
+ /**
2451
+ * A Prisma extension pack the contract declares (ADR-0049, ADR-0065). An
2452
+ * import descriptor rather than a pack value: the generated contract module is
2453
+ * standalone and fully literal, so it re-emits `from` as an import instead of
2454
+ * serialising an object out of the config.
2455
+ */
2456
+ export type ExtensionDescriptor = {
2180
2457
  /**
2181
- * Factory function to create a Prisma client instance with a database adapter
2182
- * Required in Prisma 7+ - receives the PrismaClient class and returns a configured instance
2183
- *
2184
- * The connection URL is passed directly to the adapter, not to the config.
2458
+ * The pack's binding name — the key that spells its types on a field
2459
+ * (`type.pgvector.Vector(n)`), and the identity two declarations are merged
2460
+ * on. The same `name` declared twice with a different `from` is refused.
2461
+ */
2462
+ name: string;
2463
+ /**
2464
+ * The pack's package name (e.g. `'@prisma/orm-extension-pgvector'`). The
2465
+ * generator derives the `/pack`, `/control` and `/runtime` subpaths per
2466
+ * emission.
2467
+ */
2468
+ from: string;
2469
+ };
2470
+ type PostgresBindingOptions = PostgresOptions<never>;
2471
+ /**
2472
+ * Per-deployment pool binding for the generated runtime client (ADR-0049,
2473
+ * ADR-0054). Nothing here reaches the contract; it is read only by the
2474
+ * generated `.opensaas/context.ts` when it constructs the client.
2475
+ */
2476
+ export type DatabaseClientConfig = {
2477
+ /**
2478
+ * Pool options handed to the ORM client as-is when no `pg` factory is
2479
+ * given.
2480
+ */
2481
+ poolOptions?: PostgresOptionsBase['poolOptions'];
2482
+ /**
2483
+ * A lazy factory for the `pg` pool or client the runtime should bind to.
2484
+ * A factory, not an instance: the config is loaded by the CLI and by tooling
2485
+ * that never issues a query, and none of it should open a connection. Called
2486
+ * at most once, after the config promise resolves, under the runtime's
2487
+ * client singleton.
2185
2488
  *
2186
- * @example SQLite with better-sqlite3
2489
+ * @example Serverless Postgres over a WebSocket pool
2187
2490
  * ```typescript
2188
- * import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
2491
+ * import { Pool, neonConfig } from '@neondatabase/serverless'
2492
+ * import ws from 'ws'
2189
2493
  *
2190
- * prismaClientConstructor: (PrismaClient) => {
2191
- * const adapter = new PrismaBetterSqlite3({ url: process.env.DATABASE_URL || 'file:./dev.db' })
2192
- * return new PrismaClient({ adapter })
2494
+ * db: {
2495
+ * provider: 'postgresql',
2496
+ * client: {
2497
+ * pg: () => {
2498
+ * neonConfig.webSocketConstructor = ws
2499
+ * return new Pool({ connectionString: process.env.DATABASE_URL })
2500
+ * },
2501
+ * },
2193
2502
  * }
2194
2503
  * ```
2504
+ */
2505
+ pg?: () => NonNullable<PostgresBindingOptions['pg']>;
2506
+ };
2507
+ export type DatabaseConfig = {
2508
+ /**
2509
+ * The database the stack targets. Postgres only.
2510
+ */
2511
+ provider: 'postgresql';
2512
+ /**
2513
+ * The id strategy every list gets unless it declares its own
2514
+ * `db.idField` (ADR-0048).
2195
2515
  *
2196
- * @example PostgreSQL with pg
2197
- * ```typescript
2198
- * import { PrismaPg } from '@prisma/adapter-pg'
2199
- * import pg from 'pg'
2516
+ * @default 'uuid7'
2200
2517
  *
2201
- * prismaClientConstructor: (PrismaClient) => {
2202
- * const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
2203
- * const adapter = new PrismaPg(pool)
2204
- * return new PrismaClient({ adapter })
2518
+ * @example Small integer keys across the whole app
2519
+ * ```typescript
2520
+ * db: {
2521
+ * provider: 'postgresql',
2522
+ * idField: 'int autoincrement',
2205
2523
  * }
2206
2524
  * ```
2525
+ */
2526
+ idField?: IdFieldStrategy;
2527
+ /**
2528
+ * Column defaults applied to every field of a type, plugin lists and the
2529
+ * auto `createdAt` included (`updatedAt` is not affected). A field's own `db.nativeType` wins.
2207
2530
  *
2208
- * @example Neon serverless (PostgreSQL)
2531
+ * @example Keep `timestamp(3)` columns across every list, auth lists too
2209
2532
  * ```typescript
2210
- * import { PrismaNeon } from '@prisma/adapter-neon'
2211
- * import { neonConfig } from '@neondatabase/serverless'
2212
- * import ws from 'ws'
2213
- *
2214
- * prismaClientConstructor: (PrismaClient) => {
2215
- * neonConfig.webSocketConstructor = ws
2216
- * const adapter = new PrismaNeon({
2217
- * connectionString: process.env.DATABASE_URL
2218
- * })
2219
- * return new PrismaClient({ adapter })
2533
+ * db: {
2534
+ * provider: 'postgresql',
2535
+ * defaults: { timestamp: { nativeType: 'Timestamp(3)' } },
2220
2536
  * }
2221
2537
  * ```
2222
2538
  */
2223
- prismaClientConstructor: (PrismaClientClass: any) => any;
2539
+ defaults?: {
2540
+ /** Applied to every `timestamp()` field that sets no `db.nativeType`. Must be a `Timestamp` or `Timestamptz` type. */
2541
+ timestamp?: {
2542
+ nativeType?: string;
2543
+ };
2544
+ };
2224
2545
  /**
2225
- * Join table naming strategy for many-to-many relationships
2226
- * - 'prisma': Use Prisma's default alphabetically-sorted naming (e.g., `_LessonToTeacher`)
2227
- * - 'keystone': Use KeystoneJS-compatible naming based on field location (e.g., `_Lesson_teachers`)
2546
+ * Extension packs the contract declares (ADR-0049). Each descriptor names a
2547
+ * package; one declaration drives the contract module, `prisma.config.ts`,
2548
+ * the runtime client and the pack's extension contract space under
2549
+ * `migrations/`. A plugin adds its own through
2550
+ * {@link PluginContext.addExtension}.
2228
2551
  *
2229
- * Default: 'prisma'
2552
+ * Two entries with the same `name` are one declaration when their `from`
2553
+ * agrees and a config error when it does not.
2230
2554
  *
2231
- * **Important for KeystoneJS migration:**
2232
- * When migrating from KeystoneJS, set this to 'keystone' to preserve existing join table names
2233
- * and avoid data loss. Keystone names join tables as `_Model_fieldName` based on where the
2234
- * relationship is defined in the schema.
2235
- *
2236
- * @example Preserve Keystone join table names during migration
2555
+ * @example Declare pgvector for a native vector column
2237
2556
  * ```typescript
2238
2557
  * db: {
2239
2558
  * provider: 'postgresql',
2240
- * joinTableNaming: 'keystone', // Use KeystoneJS naming convention
2241
- * // ... rest of config
2559
+ * extensions: [{ name: 'pgvector', from: '@prisma/orm-extension-pgvector' }],
2242
2560
  * }
2243
2561
  * ```
2244
2562
  */
2245
- joinTableNaming?: 'prisma' | 'keystone';
2563
+ extensions?: ExtensionDescriptor[];
2564
+ /**
2565
+ * Pool binding for the generated runtime client — see
2566
+ * {@link DatabaseClientConfig}. Omit it to let the runtime open its own pool
2567
+ * from the resolved database URL.
2568
+ */
2569
+ client?: DatabaseClientConfig;
2246
2570
  /**
2247
2571
  * Postgres multi-schema support.
2248
2572
  *
2249
- * When set, the generator enables Prisma's `multiSchema` preview feature and
2250
- * emits the `schemas = [...]` array on the datasource block. Combine with a
2251
- * per-list `db.schema` (see {@link ListConfig}) to place models in a specific
2252
- * schema via `@@schema(...)`.
2573
+ * When set, the contract's `namespaces` collects these schemas (unioned
2574
+ * with every `db.schema` a list uses — see {@link ListConfig}) and Prisma
2575
+ * resolves each model's `namespace` against that list. Combine with a
2576
+ * per-list `db.schema` to place a model in a specific schema.
2253
2577
  *
2254
- * Only applies to the `postgresql` provider. When unset, the generated schema
2255
- * is unchanged (single `public` schema, no `@@schema` attributes).
2578
+ * Only applies to the `postgresql` provider. When unset, every model stays
2579
+ * in the default `public` schema.
2256
2580
  *
2257
2581
  * @example Separate `auth` schema alongside the default `public`
2258
2582
  * ```typescript
@@ -2272,16 +2596,14 @@ export type DatabaseConfig = {
2272
2596
  * Keystone 6, which never adds timestamps automatically, and keeps Keystone → stack
2273
2597
  * migrations non-destructive (Schema parity). See ADR-0004.
2274
2598
  *
2275
- * When `true`, every list receives:
2276
- * ```prisma
2277
- * createdAt DateTime @default(now())
2278
- * updatedAt DateTime @default(now()) @updatedAt
2279
- * ```
2599
+ * When `true`, every list receives a `createdAt` column (a database `now()`
2600
+ * default) and an `updatedAt` column, maintained application-side with no
2601
+ * database backstop (ADR-0048).
2280
2602
  *
2281
2603
  * A per-list `db.timestamps` override takes precedence over this global setting. When
2282
2604
  * timestamps are enabled but a list already declares its own `createdAt`/`updatedAt`
2283
- * field, the auto column is skipped for the declared field(s) so Prisma never sees a
2284
- * duplicate (`P1012`).
2605
+ * field, the auto column is skipped for the declared field(s) so the contract never
2606
+ * carries a duplicate column.
2285
2607
  *
2286
2608
  * @default false
2287
2609
  *
@@ -2295,27 +2617,61 @@ export type DatabaseConfig = {
2295
2617
  * ```
2296
2618
  */
2297
2619
  timestamps?: boolean;
2620
+ /**
2621
+ * Name every derived index, unique constraint and foreign key the way Prisma 7
2622
+ * did (`<Table>_<cols>_idx`, `_key`, `_fkey`, truncated to 63 bytes), so a plan
2623
+ * against a database Prisma 7 created shows no renames. Turning this on for a database
2624
+ * already migrated under Prisma 8's default names renames every index and foreign key.
2625
+ * Primary-key names are not affected. An explicit `name` on a
2626
+ * `db.indexes` entry still wins. Unset, Prisma 8's own derived names apply.
2627
+ *
2628
+ * @example
2629
+ * ```typescript
2630
+ * db: { provider: 'postgresql', indexNaming: 'prisma7' }
2631
+ * ```
2632
+ */
2633
+ indexNaming?: 'prisma7';
2298
2634
  /**
2299
2635
  * Opt into Keystone-compat mode for generated schema defaults.
2300
2636
  *
2301
2637
  * Keystone 6 gives every non-null text column an implicit empty-string
2302
- * default. With `keystoneCompat: true`, the generator mirrors that: any
2303
- * non-null `text()` column that has no explicit `defaultValue` emits
2304
- * `@default("")`, so a migrating project reaches Schema parity without
2305
- * hand-setting `defaultValue: ''` on dozens of columns.
2638
+ * default. With `keystoneCompat: true`, the contract mirrors that: a
2639
+ * non-null `text()` column that has no explicit `defaultValue` carries `''`,
2640
+ * so a migrating project reaches schema parity without hand-setting
2641
+ * `defaultValue: ''` on dozens of columns.
2306
2642
  *
2307
2643
  * Stays opt-in (default `false`) because a greenfield project would not want
2308
2644
  * implicit empty-string text defaults cluttering its schema. The flag never
2309
2645
  * affects nullable text, fields with an explicit `defaultValue`, or any
2310
2646
  * non-text field — an explicit `text({ defaultValue: 'x' })` always wins.
2311
2647
  *
2648
+ * A column default also makes the column optional on the generated create
2649
+ * input, so the compat default is carried only where the field's own create
2650
+ * validator accepts both the omission it fills and `''` itself — the same
2651
+ * verdict an explicit `defaultValue: ''` reaches through
2652
+ * `applyCreateDefaults`.
2653
+ *
2654
+ * **Known limit — the flag is inert for `validation: { isRequired: true }`
2655
+ * and for `validation: { length: { min: N } }` with `N > 0`, and
2656
+ * `isRequired` is Keystone's commonest text column.** Keystone 6 renders
2657
+ * both as `NOT NULL DEFAULT ''`, but here `''` is a value the field's own
2658
+ * validator refuses (and `isRequired` refuses the omission besides), so
2659
+ * carrying the default would write a row the config forbids. Full parity
2660
+ * would need the flag to relax the create validator too, which
2661
+ * `getZodSchema` has no config to read. Until then a migrating project sees
2662
+ * `DROP DEFAULT` in `prisma db update --dry-run` for those columns and must set
2663
+ * `defaultValue: ''` on them by hand — which is refused at runtime for the
2664
+ * same reason, so the validation has to be relaxed alongside it. A column
2665
+ * made non-null through `db: { isNullable: false }` alone still gets the
2666
+ * default, as does one declaring `length: { min: 0 }` or a `length.max`.
2667
+ *
2312
2668
  * @default false
2313
2669
  *
2314
- * @example Reach Schema parity when migrating from Keystone
2670
+ * @example Reach schema parity when migrating from Keystone
2315
2671
  * ```typescript
2316
2672
  * db: {
2317
2673
  * provider: 'postgresql',
2318
- * keystoneCompat: true, // non-null text without a default → @default("")
2674
+ * keystoneCompat: true, // non-null text without a default → default ''
2319
2675
  * // ... rest of config
2320
2676
  * }
2321
2677
  * ```
@@ -2323,37 +2679,6 @@ export type DatabaseConfig = {
2323
2679
  * @see ADR-0004 (Keystone-compatible generator defaults)
2324
2680
  */
2325
2681
  keystoneCompat?: boolean;
2326
- /**
2327
- * Optional function to extend or modify the generated Prisma schema
2328
- * Receives the generated schema as a string and should return the modified schema
2329
- * Useful for advanced Prisma features not directly supported by the config API
2330
- *
2331
- * @example Add multi-schema support for PostgreSQL
2332
- * ```typescript
2333
- * extendPrismaSchema: (schema) => {
2334
- * // Add schemas array to datasource
2335
- * let modifiedSchema = schema
2336
- * .replace(
2337
- * /(datasource db \{[^}]+provider\s*=\s*"postgresql")/,
2338
- * '$1\n schemas = ["public", "auth"]'
2339
- * )
2340
- *
2341
- * // Add @@schema("public") to all models
2342
- * modifiedSchema = modifiedSchema.replace(
2343
- * /^(model \w+\s*\{[\s\S]*?)(^}$)/gm,
2344
- * (match, modelContent) => {
2345
- * if (!modelContent.includes('@@schema')) {
2346
- * return `${modelContent}\n @@schema("public")\n}`
2347
- * }
2348
- * return match
2349
- * }
2350
- * )
2351
- *
2352
- * return modifiedSchema
2353
- * }
2354
- * ```
2355
- */
2356
- extendPrismaSchema?: (schema: string) => string;
2357
2682
  /**
2358
2683
  * Override the Prisma `generator client { ... }` options the CLI emits for the
2359
2684
  * `.opensaas` prisma-client subtree.
@@ -2482,9 +2807,35 @@ export type ThemeConfig = {
2482
2807
  */
2483
2808
  shadows?: ThemeShadows;
2484
2809
  };
2810
+ export type ActionErrorClassification = {
2811
+ code: string;
2812
+ message: string;
2813
+ };
2485
2814
  export type UIConfig = {
2486
2815
  basePath?: string;
2487
2816
  theme?: ThemeConfig;
2817
+ /**
2818
+ * Maps an error thrown during a server action to a typed failure, applied
2819
+ * before the stack's default mapping. When it returns a value, the action
2820
+ * resolves `{ success: false, error: message, code }`. Returning `undefined`,
2821
+ * or throwing (the throw is logged, never surfaced), falls through to the
2822
+ * default mapping.
2823
+ *
2824
+ * @example
2825
+ * ```typescript
2826
+ * config({
2827
+ * db: { provider: 'postgresql' },
2828
+ * lists: {},
2829
+ * ui: {
2830
+ * classifyActionError: (error) =>
2831
+ * error instanceof ClaimConflict
2832
+ * ? { code: 'CLAIM_CONFLICT', message: 'Reload and try again.' }
2833
+ * : undefined,
2834
+ * },
2835
+ * })
2836
+ * ```
2837
+ */
2838
+ classifyActionError?: (error: unknown) => ActionErrorClassification | undefined;
2488
2839
  };
2489
2840
  /**
2490
2841
  * MCP (Model Context Protocol) configuration
@@ -2524,6 +2875,17 @@ export type McpCustomTool = {
2524
2875
  */
2525
2876
  name: string;
2526
2877
  description: string;
2878
+ /**
2879
+ * OAuth scopes the session's token must carry to see or call this tool.
2880
+ * A token missing any of them gets a tool error naming them, and the tool is
2881
+ * left out of `tools/list`.
2882
+ *
2883
+ * On a list custom tool, omitting this requires the configured write scope
2884
+ * (`mcp.scopes.write`, or the list's own override) when scopes are
2885
+ * configured, and nothing otherwise. Pass `[]` to opt out explicitly.
2886
+ * A plugin-registered tool with no scopes requires nothing.
2887
+ */
2888
+ scopes?: string[];
2527
2889
  /**
2528
2890
  * Input schema (Zod schema)
2529
2891
  */
@@ -2533,12 +2895,32 @@ export type McpCustomTool = {
2533
2895
  context: import('../access/types.js').AccessContext;
2534
2896
  }) => Promise<unknown>;
2535
2897
  };
2898
+ /**
2899
+ * OAuth scopes gating the CRUD tools. `read` gates `query`; `write` gates
2900
+ * `create`, `update` and `delete`. Scopes are only enforced where configured.
2901
+ *
2902
+ * @example
2903
+ * ```typescript
2904
+ * mcp: { enabled: true, scopes: { read: 'mcp:read', write: ['mcp:write'] } }
2905
+ * ```
2906
+ */
2907
+ export type McpScopesConfig = {
2908
+ /** Scope(s) a token must carry to call `query` tools */
2909
+ read?: string | string[];
2910
+ /** Scope(s) a token must carry to call `create`, `update` and `delete` tools */
2911
+ write?: string | string[];
2912
+ };
2536
2913
  export type ListMcpConfig = {
2537
2914
  /**
2538
2915
  * Enable MCP tools for this list
2539
2916
  * @default true
2540
2917
  */
2541
2918
  enabled?: boolean;
2919
+ /**
2920
+ * Scopes required by this list's CRUD tools. Each of `read` and `write`
2921
+ * set here takes precedence over the config-level `mcp.scopes`.
2922
+ */
2923
+ scopes?: McpScopesConfig;
2542
2924
  /**
2543
2925
  * Configure which CRUD tools to enable
2544
2926
  */
@@ -2626,6 +3008,11 @@ export type McpConfig = {
2626
3008
  * Can be overridden per-list
2627
3009
  */
2628
3010
  defaultTools?: McpToolsConfig;
3011
+ /**
3012
+ * OAuth scopes the session's token must carry for CRUD tools. Not enforced
3013
+ * unless configured. Overridable per list with `list.mcp.scopes`.
3014
+ */
3015
+ scopes?: McpScopesConfig;
2629
3016
  /**
2630
3017
  * Resource identifier for OAuth protected resource metadata
2631
3018
  * @default "https://yourdomain.com"
@@ -2690,6 +3077,15 @@ export interface ImageTransformationResult {
2690
3077
  height: number;
2691
3078
  /** File size in bytes */
2692
3079
  size: number;
3080
+ /**
3081
+ * The storage key the provider's own `upload()` returned for this
3082
+ * transformation. Cleanup deletes by this key, never by parsing `url` —
3083
+ * a stored `url` is not a trustworthy source of a storage key (issue
3084
+ * #1619). Optional so a value written before this field existed still
3085
+ * type-checks; such a row's transformations are left undeleted by cleanup
3086
+ * rather than deleted by a parsed guess.
3087
+ */
3088
+ filename?: string;
2693
3089
  }
2694
3090
  export type StorageConfig = Record<string, {
2695
3091
  type: string;
@@ -2703,7 +3099,7 @@ export type StorageConfig = Record<string, {
2703
3099
  * Plugins can modify these during afterGenerate hooks
2704
3100
  */
2705
3101
  export type GeneratedFiles = {
2706
- prismaSchema: string;
3102
+ contractModule: string;
2707
3103
  types: string;
2708
3104
  context: string;
2709
3105
  [key: string]: string;
@@ -2748,6 +3144,20 @@ export type PluginContext = {
2748
3144
  * Tools are added to the global MCP server
2749
3145
  */
2750
3146
  registerMcpTool?: (tool: McpCustomTool) => void;
3147
+ /**
3148
+ * Declare an extension pack the plugin's field types need (ADR-0049), as
3149
+ * if the app had listed it under `db.extensions`. Idempotent when the
3150
+ * config already declares the same `name` from the same package; throws
3151
+ * when it declares that `name` from a different one.
3152
+ *
3153
+ * @example
3154
+ * ```typescript
3155
+ * init: async (context) => {
3156
+ * context.addExtension({ name: 'pgvector', from: '@prisma/orm-extension-pgvector' })
3157
+ * }
3158
+ * ```
3159
+ */
3160
+ addExtension: (descriptor: ExtensionDescriptor) => void;
2751
3161
  /**
2752
3162
  * Store plugin-specific data in config for runtime access
2753
3163
  * Prefixed with plugin name to avoid conflicts
@@ -2778,13 +3188,19 @@ export type Plugin = {
2778
3188
  */
2779
3189
  init: (context: PluginContext) => void | Promise<void>;
2780
3190
  /**
2781
- * Optional: Modify config before Prisma schema generation
3191
+ * Optional: Modify config before contract generation
2782
3192
  * Useful for programmatic config transformations
2783
3193
  */
2784
3194
  beforeGenerate?: (config: OpenSaasConfig) => OpenSaasConfig | Promise<OpenSaasConfig>;
2785
3195
  /**
2786
3196
  * Optional: Post-process generated files
2787
- * Allows plugins to modify Prisma schema, types, or add custom generated files
3197
+ * Allows plugins to modify the Contract module, types, or add custom generated files
3198
+ *
3199
+ * Runs before `prisma contract emit`, so a rewritten `contractModule` is the
3200
+ * one the emitted `contract.json` / `contract.d.ts` describe and the one the
3201
+ * relation-graph agreement gate checks. A rewrite that the contract toolchain
3202
+ * rejects therefore fails `opensaas generate` rather than landing on disk
3203
+ * unemitted.
2788
3204
  */
2789
3205
  afterGenerate?: (files: GeneratedFiles) => GeneratedFiles | Promise<GeneratedFiles>;
2790
3206
  /**
@@ -2792,7 +3208,7 @@ export type Plugin = {
2792
3208
  * Called when creating context to provide plugin-specific services
2793
3209
  * Return value is stored in context.plugins[pluginName]
2794
3210
  *
2795
- * `sudo` returns an access-bypassing (but still hook-firing) `AccessContext`
3211
+ * `sudo` returns an access-bypassing (but still hook-firing) `StackContext`
2796
3212
  * for the same request — use `sudo().db` for reads/writes that must not
2797
3213
  * depend on the caller's own list access policy (e.g. an identity lookup
2798
3214
  * like "who is this session"). Deliberately NOT a method on `AccessContext`
@@ -2801,8 +3217,14 @@ export type Plugin = {
2801
3217
  * of unrelated generated Prisma types elsewhere (nullable JSON `CreateInput`
2802
3218
  * fields) in a downstream app; passing it as a plain second argument avoids
2803
3219
  * that recursion entirely.
3220
+ *
3221
+ * It is a `StackContext`, not the `AccessContext` of the first argument:
3222
+ * the two differ, and the difference bites. `StackContext` omits
3223
+ * `ormHandle`, `_isSudo`'s internal companions and `_config`, so a core
3224
+ * surface that needs the engine's own plumbing — `writePluginOwnedField`,
3225
+ * say — takes the first argument, never this one (ADR-0068).
2804
3226
  */
2805
- runtime?: (context: import('../access/types.js').AccessContext, sudo: () => import('../access/types.js').AccessContext) => unknown;
3227
+ runtime?: (context: import('../access/types.js').AccessContext, sudo: () => import('../types/context.js').StackContext) => unknown;
2806
3228
  /**
2807
3229
  * Optional: Type metadata for runtime services
2808
3230
  * Enables type-safe code generation for context.plugins
@@ -2831,62 +3253,37 @@ export type Plugin = {
2831
3253
  /**
2832
3254
  * Configurable generator output locations.
2833
3255
  *
2834
- * Lets a project relocate the generated Prisma schema and the `.opensaas`
3256
+ * Lets a project relocate the generated Contract module and the `.opensaas`
2835
3257
  * bundle directory. Paths are interpreted relative to the project root.
2836
3258
  *
2837
3259
  * @example
2838
3260
  * ```typescript
2839
3261
  * output: {
2840
- * prismaSchema: 'prisma-opensaas/schema.prisma',
3262
+ * contractModule: 'prisma-opensaas/contract.ts',
2841
3263
  * opensaasDir: '.opensaas',
2842
3264
  * }
2843
3265
  * ```
2844
3266
  */
2845
3267
  export interface OutputConfig {
2846
3268
  /**
2847
- * Path to the generated Prisma schema file.
2848
- * @default "prisma/schema.prisma"
3269
+ * Path to the generated Contract module. `contract.json` and `contract.d.ts`
3270
+ * are emitted into its directory, and `prisma.config.ts` points at it.
3271
+ * @default "prisma/contract.ts"
2849
3272
  */
2850
- prismaSchema?: string;
3273
+ contractModule?: string;
2851
3274
  /**
2852
- * Directory for the generated `.opensaas` bundle (types, lists, context,
2853
- * plugin-types, and the patched Prisma client).
3275
+ * Directory for the generated `.opensaas` bundle (types, lists, context and
3276
+ * plugin types).
2854
3277
  * @default ".opensaas"
2855
3278
  */
2856
3279
  opensaasDir?: string;
2857
- /**
2858
- * Opt in to an additional **Node build** of the Generated bundle.
2859
- *
2860
- * By default (omitted) the generator emits only the bundler-loadable `.ts`
2861
- * form (ADR-0008): TypeScript with explicit `.ts` import extensions, traced
2862
- * and transpiled by the host's bundler. That form cannot execute under plain
2863
- * Node, so a live module that must run in BOTH a bundled and a bundler-less
2864
- * runtime (e.g. better-auth's Prisma adapter, imported by the Next server AND
2865
- * by a Playwright e2e helper or a build-time script) has no Node-loadable
2866
- * entry to point at.
2867
- *
2868
- * Setting `buildTarget: 'node'` additionally compiles the bundle to a
2869
- * plain-Node-loadable ESM form under `<opensaasDir>/dist/` (`.js` + `.d.ts`,
2870
- * with a `{"type":"module"}` marker). The compiled entry is
2871
- * `<opensaasDir>/dist/context.js`; a portable module imports it directly so
2872
- * the bundler traces it AND plain Node executes it (one specifier, both
2873
- * runtimes — see ADR-0011). The default `.ts` form is unchanged and still
2874
- * emitted; the Node build is purely additive.
2875
- *
2876
- * `'node'` is the only target today. The field is a string-literal union so
2877
- * future compiled targets can be added without a breaking change.
2878
- *
2879
- * @example
2880
- * ```typescript
2881
- * export default config({
2882
- * output: { buildTarget: 'node' },
2883
- * // ...
2884
- * })
2885
- * // Then import the compiled entry from a plain-Node consumer:
2886
- * // const { rawOpensaasContext } = await import('./.opensaas/dist/context.js')
2887
- * ```
2888
- */
2889
- buildTarget?: 'node';
3280
+ }
3281
+ /** What {@link OpenSaasConfig.onAfterTransactionError} receives for one failed `afterTransaction` hook. */
3282
+ export interface AfterTransactionErrorReport {
3283
+ error: unknown;
3284
+ status: 'committed' | 'rolled-back';
3285
+ listKey: string;
3286
+ operation: 'create' | 'update' | 'delete';
2890
3287
  }
2891
3288
  /**
2892
3289
  * Main configuration type.
@@ -2894,6 +3291,25 @@ export interface OutputConfig {
2894
3291
  */
2895
3292
  export interface OpenSaasConfig {
2896
3293
  db: DatabaseConfig;
3294
+ /**
3295
+ * Receives every error an `afterTransaction` hook throws. Such an error never
3296
+ * changes the write's or transaction's result: a committed write resolves and
3297
+ * a rolled-back one still rejects with its own error. Called once per failed
3298
+ * hook. When unset, or when this callback itself throws, the error is written
3299
+ * to `console.error`.
3300
+ *
3301
+ * @example
3302
+ * ```typescript
3303
+ * config({
3304
+ * db: { provider: 'postgresql' },
3305
+ * lists: {},
3306
+ * onAfterTransactionError: ({ error, status, listKey, operation }) => {
3307
+ * logger.error({ error, status, listKey, operation }, 'afterTransaction failed')
3308
+ * },
3309
+ * })
3310
+ * ```
3311
+ */
3312
+ onAfterTransactionError?: (report: AfterTransactionErrorReport) => void | Promise<void>;
2897
3313
  lists: Record<string, ListConfig<any>>;
2898
3314
  session?: SessionConfig;
2899
3315
  ui?: UIConfig;
@@ -2916,13 +3332,13 @@ export interface OpenSaasConfig {
2916
3332
  * existing `prisma/` directory (e.g. during a Keystone → stack migration).
2917
3333
  *
2918
3334
  * Both fields are resolved relative to the project root (the directory the
2919
- * CLI runs in). When omitted, defaults are unchanged: the schema is written to
2920
- * `prisma/schema.prisma` and the `.opensaas` bundle to `.opensaas/`.
3335
+ * CLI runs in). When omitted, defaults are unchanged: the Contract module is
3336
+ * written to `prisma/contract.ts` and the `.opensaas` bundle to `.opensaas/`.
2921
3337
  *
2922
3338
  * The generated files' cross-references follow these locations — `context.ts`
2923
3339
  * imports the generated types/lists from the resolved `.opensaas` dir, and the
2924
- * top-level `prisma.config.ts` points at the configured schema path so the
2925
- * `prisma` CLI keeps working.
3340
+ * top-level `prisma.config.ts` points at the configured Contract module path
3341
+ * so the `prisma` CLI keeps working.
2926
3342
  */
2927
3343
  output?: OutputConfig;
2928
3344
  /**
@@ -2942,6 +3358,14 @@ export interface OpenSaasConfig {
2942
3358
  * @internal
2943
3359
  */
2944
3360
  _plugins?: Plugin[];
3361
+ /**
3362
+ * The dependency-set table and unique-constraint map `pnpm generate`
3363
+ * emitted (ADR-0051, ADR-0042), supplied by the generated context. Absent
3364
+ * for a config reached without generation, in which case the engine derives
3365
+ * the dependency table from this config through the same computation.
3366
+ * @internal
3367
+ */
3368
+ _tables?: GeneratedTables;
2945
3369
  }
2946
3370
  export {};
2947
3371
  //# sourceMappingURL=types.d.ts.map