@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,100 +1,216 @@
1
1
  import { z } from 'zod';
2
2
  import { hashPassword, isHashedPassword, HashedPassword } from '../utils/password.js';
3
- import { formatPrismaDefault } from './format-prisma-default.js';
4
3
  import { getLabelFieldName } from '../config/label.js';
5
- import { RELATIONSHIP_COUNT_FILTER_KEY } from '../filter/types.js';
4
+ function quoteStringLiteral(value) {
5
+ const escaped = value
6
+ .replace(/\\/g, '\\\\')
7
+ .replace(/'/g, "\\'")
8
+ .replace(/\n/g, '\\n')
9
+ .replace(/\r/g, '\\r')
10
+ .replace(/\u2028/g, '\\u2028')
11
+ .replace(/\u2029/g, '\\u2029');
12
+ return `'${escaped}'`;
13
+ }
6
14
  /** Operators shared by numeric/date fields' `getFilterSpec`. */
7
15
  const COMPARISON_OPERATORS = ['eq', 'gt', 'gte', 'lt', 'lte'];
8
16
  function prismaComparisonKey(operator) {
9
17
  return operator === 'eq' ? 'equals' : operator;
10
18
  }
11
- function formatFieldName(fieldName) {
19
+ /**
20
+ * Renders a field key the way validation messages address the user:
21
+ * `internalNotes` becomes `Internal notes`.
22
+ *
23
+ * Exported on `/extend` so a third-party field's messages read the same as a
24
+ * built-in one's — a `richText()` and a `json()` on the same form should not
25
+ * disagree about whether the field is called `content` or `Content`.
26
+ */
27
+ export function formatFieldName(fieldName) {
12
28
  return fieldName
13
29
  .replace(/([A-Z])/g, ' $1')
14
30
  .replace(/^./, (str) => str.toUpperCase())
15
31
  .trim();
16
32
  }
33
+ function pgType(type, args) {
34
+ return args ? { pack: 'pg', type, args } : { pack: 'pg', type };
35
+ }
36
+ function isContractLiteral(value) {
37
+ if (value === null)
38
+ return true;
39
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
40
+ return true;
41
+ }
42
+ if (Array.isArray(value))
43
+ return value.every(isContractLiteral);
44
+ if (typeof value !== 'object')
45
+ return false;
46
+ const proto = Object.getPrototypeOf(value);
47
+ return ((proto === Object.prototype || proto === null) && Object.values(value).every(isContractLiteral));
48
+ }
49
+ function describeDefault(value) {
50
+ if (typeof value !== 'object' || value === null)
51
+ return `a ${typeof value}`;
52
+ return `an instance of ${value.constructor?.name ?? 'an unnamed class'}`;
53
+ }
54
+ function literalDefault(value, listKey, fieldName) {
55
+ if (value === undefined)
56
+ return undefined;
57
+ if (!isContractLiteral(value)) {
58
+ throw new Error(`"${listKey}.${fieldName}" has a defaultValue the contract cannot carry: expected a JSON ` +
59
+ `literal (string, number, boolean, null, array or plain object), got ${describeDefault(value)}.`);
60
+ }
61
+ return { kind: 'literal', value };
62
+ }
63
+ function checkedDefault(value, listKey, fieldName, expected, accepts) {
64
+ if (value === undefined || value === null || accepts(value))
65
+ return;
66
+ throw new Error(`"${listKey}.${fieldName}" has an invalid defaultValue: expected ${expected}, got ${typeof value === 'string' ? JSON.stringify(value) : describeDefault(value)}.`);
67
+ }
68
+ const DECIMAL_GRAMMAR = /^([+-])?(\d*)(?:\.(\d*))?$/;
69
+ function decimalParts(text) {
70
+ const parts = DECIMAL_GRAMMAR.exec(text);
71
+ return parts !== null && (parts[2] !== '' || (parts[3] ?? '') !== '') ? parts : null;
72
+ }
73
+ function fitsDecimal(value, precision, scale) {
74
+ if (typeof value === 'number' && !Number.isFinite(value))
75
+ return false;
76
+ if (typeof value !== 'number' && typeof value !== 'string')
77
+ return false;
78
+ const text = typeof value === 'number' ? value.toFixed(20).replace(/\.?0+$/, '') : value.trim();
79
+ const parts = decimalParts(text);
80
+ if (parts === null)
81
+ return false;
82
+ const integerDigits = parts[2].replace(/^0+/, '').length;
83
+ return integerDigits <= precision - scale;
84
+ }
85
+ function isCalendarDate(value) {
86
+ if (typeof value !== 'string')
87
+ return false;
88
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
89
+ if (match === null)
90
+ return false;
91
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
92
+ const date = new Date(0);
93
+ date.setUTCFullYear(year, month - 1, day);
94
+ return (date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day);
95
+ }
96
+ function isBigIntDefault(value) {
97
+ return (typeof value === 'bigint' ||
98
+ (typeof value === 'number' && Number.isSafeInteger(value)) ||
99
+ (typeof value === 'string' && /^[+-]?\d+$/.test(value)));
100
+ }
101
+ function checkedDecimalSize(precision, scale, listKey, fieldName) {
102
+ if (typeof precision !== 'number' ||
103
+ !Number.isInteger(precision) ||
104
+ precision < 1 ||
105
+ precision > 1000) {
106
+ throw new Error(`"${listKey}.${fieldName}" has an invalid precision: expected an integer from 1 to 1000, got ${typeof precision === 'string' ? JSON.stringify(precision) : String(precision)}.`);
107
+ }
108
+ if (typeof scale !== 'number' || !Number.isInteger(scale) || scale < 0 || scale > precision) {
109
+ throw new Error(`"${listKey}.${fieldName}" has an invalid scale: expected an integer from 0 to precision (${precision}), got ${typeof scale === 'string' ? JSON.stringify(scale) : String(scale)}.`);
110
+ }
111
+ return { precision, scale };
112
+ }
113
+ function decimalDefault(value, listKey, fieldName, precision, scale) {
114
+ const literal = literalDefault(value, listKey, fieldName);
115
+ if (literal === undefined || literal.kind !== 'literal')
116
+ return literal;
117
+ const text = String(literal.value).trim();
118
+ const parts = decimalParts(text);
119
+ let operand = `'${text.replace(/'/g, "''")}'`;
120
+ if (parts !== null) {
121
+ const integer = parts[2].replace(/^0+(?=\d)/, '') || '0';
122
+ const fraction = parts[3] ?? '';
123
+ const magnitude = fraction === '' ? integer : `${integer}.${fraction}`;
124
+ if (parts[1] === '-')
125
+ operand = `'-${magnitude}'`;
126
+ else
127
+ operand = fraction === '' ? `(${magnitude})` : magnitude;
128
+ }
129
+ return { kind: 'sql', expression: `${operand}::numeric(${precision},${scale})` };
130
+ }
131
+ function scalarColumn(fieldName, column) {
132
+ const descriptor = {
133
+ kind: 'column',
134
+ name: fieldName,
135
+ type: column.type,
136
+ nullable: column.nullable,
137
+ };
138
+ if (column.nativeType !== undefined)
139
+ descriptor.nativeType = column.nativeType;
140
+ if (column.map !== undefined)
141
+ descriptor.map = column.map;
142
+ if (column.isIndexed === 'unique')
143
+ descriptor.unique = true;
144
+ if (column.isIndexed === true)
145
+ descriptor.index = true;
146
+ if (column.default !== undefined)
147
+ descriptor.default = column.default;
148
+ if (column.enum !== undefined)
149
+ descriptor.enum = column.enum;
150
+ return descriptor;
151
+ }
17
152
  /**
18
153
  * Text field
19
154
  */
20
155
  export function text(options) {
156
+ const zodSchema = (fieldName, operation) => {
157
+ const validation = options?.validation;
158
+ const isRequired = validation?.isRequired;
159
+ const length = validation?.length;
160
+ const declaredMin = length?.min !== undefined && length.min > 0 ? length.min : undefined;
161
+ const minLength = declaredMin ?? 1;
162
+ const baseSchema = z.string({
163
+ message: `${formatFieldName(fieldName)} must be text`,
164
+ });
165
+ const withMin = isRequired || declaredMin !== undefined
166
+ ? baseSchema.min(minLength, {
167
+ message: minLength > 1
168
+ ? `${formatFieldName(fieldName)} must be at least ${minLength} characters`
169
+ : `${formatFieldName(fieldName)} is required`,
170
+ })
171
+ : baseSchema;
172
+ const withMax = length?.max !== undefined
173
+ ? withMin.max(length.max, {
174
+ message: `${formatFieldName(fieldName)} must be at most ${length.max} characters`,
175
+ })
176
+ : withMin;
177
+ if (isRequired && operation === 'update') {
178
+ return withMax.optional();
179
+ }
180
+ return !isRequired ? withMax.optional().nullable() : withMax;
181
+ };
21
182
  return {
22
183
  type: 'text',
23
184
  ...options,
24
- getZodSchema: (fieldName, operation) => {
25
- const validation = options?.validation;
26
- const isRequired = validation?.isRequired;
27
- const length = validation?.length;
28
- const minLength = length?.min && length.min > 0 ? length.min : 1;
29
- const baseSchema = z.string({
30
- message: `${formatFieldName(fieldName)} must be text`,
185
+ getZodSchema: zodSchema,
186
+ getContractField: (fieldName, listKey, config) => {
187
+ const nullable = options?.db?.isNullable ?? !options?.validation?.isRequired;
188
+ // Keystone 6 gives every non-null text column an implicit empty-string
189
+ // default; `db.keystoneCompat` mirrors that so a migrating project
190
+ // reaches parity without hand-setting `defaultValue: ''`.
191
+ //
192
+ // A column default makes the field optional on `CreateInput`
193
+ // (`RequiredCreateColumn`, `types/inputs.ts`), so the column may only
194
+ // carry one where the create validator both accepts the omission it
195
+ // fills and accepts `''` itself. Both are asked of the schema rather
196
+ // than restated, so the column and the validator cannot drift apart —
197
+ // and an implicit compat default reaches the same verdict as the
198
+ // explicit `defaultValue: ''` that `applyCreateDefaults` fills.
199
+ const createSchema = zodSchema(fieldName, 'create');
200
+ const compatDefault = options?.defaultValue === undefined &&
201
+ config.db.keystoneCompat === true &&
202
+ !nullable &&
203
+ createSchema.safeParse(undefined).success &&
204
+ createSchema.safeParse('').success;
205
+ const defaultSource = compatDefault ? '' : options?.defaultValue;
206
+ return scalarColumn(fieldName, {
207
+ type: pgType('text'),
208
+ nullable,
209
+ nativeType: options?.db?.nativeType,
210
+ map: options?.db?.map,
211
+ isIndexed: options?.isIndexed,
212
+ default: literalDefault(defaultSource, listKey, fieldName),
31
213
  });
32
- const withMin = isRequired || length?.min !== undefined
33
- ? baseSchema.min(minLength, {
34
- message: minLength > 1
35
- ? `${formatFieldName(fieldName)} must be at least ${minLength} characters`
36
- : `${formatFieldName(fieldName)} is required`,
37
- })
38
- : baseSchema;
39
- const withMax = length?.max !== undefined
40
- ? withMin.max(length.max, {
41
- message: `${formatFieldName(fieldName)} must be at most ${length.max} characters`,
42
- })
43
- : withMin;
44
- if (isRequired && operation === 'update') {
45
- return withMax.optional();
46
- }
47
- return !isRequired ? withMax.optional().nullable() : withMax;
48
- },
49
- getPrismaType: (_fieldName, _provider, _listName, keystoneCompat) => {
50
- const validation = options?.validation;
51
- const db = options?.db;
52
- const isRequired = validation?.isRequired;
53
- const isNullable = db?.isNullable ?? !isRequired;
54
- let modifiers = '';
55
- if (isNullable) {
56
- modifiers += '?';
57
- }
58
- if (db?.nativeType) {
59
- modifiers += ` @db.${db.nativeType}`;
60
- }
61
- // Default value. An explicit `defaultValue` always wins. When none is set
62
- // and Keystone-compat mode is on, a non-null text column gets Keystone's
63
- // implicit empty-string default. Both go through formatPrismaDefault, so
64
- // the empty-string literal (`""`) is produced the same way as any other
65
- // text default. Independent of the nullable `?` modifier above — the
66
- // default never overwrites nullability.
67
- const defaultSource = options?.defaultValue !== undefined
68
- ? options.defaultValue
69
- : keystoneCompat && !isNullable
70
- ? ''
71
- : undefined;
72
- const defaultLiteral = formatPrismaDefault(defaultSource, 'text');
73
- if (defaultLiteral !== undefined) {
74
- modifiers += ` @default(${defaultLiteral})`;
75
- }
76
- // Unique modifier. A non-unique index has no field-level form in Prisma,
77
- // so it is requested out-of-line via `index` below and emitted by the
78
- // generator as `@@index([...])` on the model.
79
- if (options?.isIndexed === 'unique') {
80
- modifiers += ' @unique';
81
- }
82
- if (db?.map) {
83
- modifiers += ` @map("${db.map}")`;
84
- }
85
- return {
86
- type: 'String',
87
- modifiers: modifiers.trimStart() || undefined,
88
- index: options?.isIndexed === true ? true : undefined,
89
- };
90
- },
91
- getTypeScriptType: () => {
92
- const validation = options?.validation;
93
- const isRequired = validation?.isRequired;
94
- return {
95
- type: 'string',
96
- optional: !isRequired,
97
- };
98
214
  },
99
215
  getFilterSpec: (fieldName) => ({
100
216
  operators: ['eq'],
@@ -125,46 +241,24 @@ export function integer(options) {
125
241
  message: `${formatFieldName(fieldName)} must be at most ${options.validation.max}`,
126
242
  })
127
243
  : withMin;
128
- return !options?.validation?.isRequired || operation === 'update'
129
- ? withMax.optional().nullable()
130
- : withMax;
131
- },
132
- getPrismaType: (_fieldName) => {
133
- const validation = options?.validation;
134
- const db = options?.db;
135
- const isRequired = validation?.isRequired;
136
- const isNullable = db?.isNullable ?? !isRequired;
137
- let modifiers = '';
138
- if (isNullable) {
139
- modifiers += '?';
140
- }
141
- if (db?.nativeType) {
142
- modifiers += ` @db.${db.nativeType}`;
143
- }
144
- const defaultLiteral = formatPrismaDefault(options?.defaultValue, 'integer');
145
- if (defaultLiteral !== undefined) {
146
- modifiers += ` @default(${defaultLiteral})`;
147
- }
148
- if (db?.map) {
149
- modifiers += ` @map("${db.map}")`;
150
- }
151
- // Unique modifier — non-unique index routes through `index` below,
152
- // same as `text()`'s getPrismaType.
153
- if (options?.isIndexed === 'unique') {
154
- modifiers += ' @unique';
155
- }
156
- return {
157
- type: 'Int',
158
- modifiers: modifiers.trimStart() || undefined,
159
- index: options?.isIndexed === true ? true : undefined,
160
- };
161
- },
162
- getTypeScriptType: () => {
163
244
  const isRequired = options?.validation?.isRequired;
164
- return {
165
- type: 'number',
166
- optional: !isRequired,
167
- };
245
+ if (isRequired && operation === 'update')
246
+ return withMax.optional();
247
+ return !isRequired ? withMax.optional().nullable() : withMax;
248
+ },
249
+ getContractField: (fieldName, listKey) => {
250
+ checkedDefault(options?.defaultValue, listKey, fieldName, 'an integer within the 32-bit range', (value) => typeof value === 'number' &&
251
+ Number.isInteger(value) &&
252
+ value >= -2147483648 &&
253
+ value <= 2147483647);
254
+ return scalarColumn(fieldName, {
255
+ type: pgType('int'),
256
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
257
+ nativeType: options?.db?.nativeType,
258
+ map: options?.db?.map,
259
+ isIndexed: options?.isIndexed,
260
+ default: literalDefault(options?.defaultValue, listKey, fieldName),
261
+ });
168
262
  },
169
263
  // A non-integer token can't be interpreted, so it degrades to free text.
170
264
  getFilterSpec: (fieldName) => ({
@@ -184,7 +278,10 @@ export function integer(options) {
184
278
  *
185
279
  * **Features:**
186
280
  * - Stores decimal numbers with configurable precision and scale
187
- * - Uses Prisma's Decimal type (backed by decimal.js for precision)
281
+ * - Read and write as a plain numeric-text string (e.g. `'19.99'`) — Prisma
282
+ * 8's numeric codec is a branded `string`, never a `decimal.js` `Decimal`
283
+ * (ADR-0029's amendment), so full precision survives every boundary with
284
+ * no special handling
188
285
  * - Default precision: 18 digits, scale: 4 decimal places
189
286
  * - Validation for min/max values
190
287
  * - Optional database column mapping and nullability control
@@ -211,10 +308,10 @@ export function integer(options) {
211
308
  * }
212
309
  *
213
310
  * // Creating with decimal values
214
- * const product = await context.db.product.create({
311
+ * const product = await context.db.Product.create({
215
312
  * data: {
216
313
  * price: '19.99', // Can use string
217
- * // price: 19.99, // or number (converted to Decimal)
314
+ * // price: 19.99, // or number
218
315
  * }
219
316
  * })
220
317
  * ```
@@ -260,58 +357,25 @@ export function decimal(options) {
260
357
  message: `${formatFieldName(fieldName)} must be at most ${options.validation.max}`,
261
358
  });
262
359
  }
263
- return !options?.validation?.isRequired || operation === 'update'
264
- ? schema.optional().nullable()
265
- : schema;
266
- },
267
- getPrismaType: (_fieldName) => {
268
- const validation = options?.validation;
269
- const db = options?.db;
270
- const isRequired = validation?.isRequired;
271
- const isNullable = db?.isNullable ?? !isRequired;
272
- let modifiers = '';
273
- if (isNullable) {
274
- modifiers += '?';
275
- }
276
- modifiers += ` @db.Decimal(${precision}, ${scale})`;
277
- if (options?.defaultValue !== undefined) {
278
- modifiers += ` @default(${options.defaultValue})`;
279
- }
280
- if (db?.map) {
281
- modifiers += ` @map("${db.map}")`;
282
- }
283
- // Unique modifier — non-unique index routes through `index` below,
284
- // same as `text()`'s getPrismaType.
285
- if (options?.isIndexed === 'unique') {
286
- modifiers += ' @unique';
287
- }
288
- return {
289
- type: 'Decimal',
290
- modifiers: modifiers.trimStart() || undefined,
291
- index: options?.isIndexed === true ? true : undefined,
292
- };
293
- },
294
- getTypeScriptType: () => {
295
- const validation = options?.validation;
296
- const db = options?.db;
297
- const isRequired = validation?.isRequired;
298
- const isNullable = db?.isNullable ?? !isRequired;
299
- return {
300
- type: "import('decimal.js').Decimal",
301
- optional: isNullable,
302
- };
360
+ const isRequired = options?.validation?.isRequired;
361
+ if (isRequired && operation === 'update')
362
+ return schema.optional();
363
+ return !isRequired ? schema.optional().nullable() : schema;
303
364
  },
304
- getTypeScriptImports: () => {
305
- return [
306
- {
307
- names: ['Decimal'],
308
- from: 'decimal.js',
309
- typeOnly: true,
310
- },
311
- ];
365
+ getContractField: (fieldName, listKey) => {
366
+ const size = checkedDecimalSize(options?.precision ?? 18, options?.scale ?? 4, listKey, fieldName);
367
+ checkedDefault(options?.defaultValue, listKey, fieldName, `a finite number or numeric string with at most ${size.precision - size.scale} integer digits`, (value) => fitsDecimal(value, size.precision, size.scale));
368
+ return scalarColumn(fieldName, {
369
+ type: pgType('decimal', [size.precision, size.scale]),
370
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
371
+ nativeType: options?.db?.nativeType,
372
+ map: options?.db?.map,
373
+ isIndexed: options?.isIndexed,
374
+ default: decimalDefault(options?.defaultValue, listKey, fieldName, size.precision, size.scale),
375
+ });
312
376
  },
313
- // Decimals compare like integers, but the value stays a string so Prisma's
314
- // Decimal keeps full precision. A non-numeric value degrades to free text.
377
+ // Decimals compare like integers, but the value stays a string so full
378
+ // precision survives the filter. A non-numeric value degrades to free text.
315
379
  getFilterSpec: (fieldName) => ({
316
380
  operators: COMPARISON_OPERATORS,
317
381
  toCondition: (operator, value) => {
@@ -383,43 +447,23 @@ export function bigInt(options) {
383
447
  message: `${formatFieldName(fieldName)} must be at most ${max}`,
384
448
  });
385
449
  }
386
- return !isRequired || operation === 'update' ? schema.optional().nullable() : schema;
387
- },
388
- getPrismaType: (_fieldName) => {
389
- const validation = options?.validation;
390
- const db = options?.db;
391
- const isRequired = validation?.isRequired;
392
- const isNullable = db?.isNullable ?? !isRequired;
393
- let modifiers = '';
394
- if (isNullable) {
395
- modifiers += '?';
396
- }
397
- if (db?.nativeType) {
398
- modifiers += ` @db.${db.nativeType}`;
399
- }
400
- if (options?.defaultValue !== undefined) {
401
- modifiers += ` @default(${options.defaultValue})`;
402
- }
403
- if (db?.map) {
404
- modifiers += ` @map("${db.map}")`;
405
- }
406
- // Unique modifier — non-unique index routes through `index` below,
407
- // same as `text()`'s getPrismaType.
408
- if (options?.isIndexed === 'unique') {
409
- modifiers += ' @unique';
410
- }
411
- return {
412
- type: 'BigInt',
413
- modifiers: modifiers.trimStart() || undefined,
414
- index: options?.isIndexed === true ? true : undefined,
415
- };
450
+ if (isRequired && operation === 'update')
451
+ return schema.optional();
452
+ return !isRequired ? schema.optional().nullable() : schema;
416
453
  },
417
- getTypeScriptType: () => {
418
- const isRequired = options?.validation?.isRequired;
419
- return {
420
- type: 'bigint',
421
- optional: !isRequired,
422
- };
454
+ getContractField: (fieldName, listKey) => {
455
+ const defaultValue = options?.defaultValue;
456
+ checkedDefault(defaultValue, listKey, fieldName, 'an integer number, a bigint, or a string of base-10 integer digits', isBigIntDefault);
457
+ return scalarColumn(fieldName, {
458
+ type: pgType('bigint'),
459
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
460
+ nativeType: options?.db?.nativeType,
461
+ map: options?.db?.map,
462
+ isIndexed: options?.isIndexed,
463
+ default: literalDefault(typeof defaultValue === 'bigint' || typeof defaultValue === 'number'
464
+ ? defaultValue.toString()
465
+ : defaultValue, listKey, fieldName),
466
+ });
423
467
  },
424
468
  // A non-integer token degrades to free text.
425
469
  getFilterSpec: (fieldName) => ({
@@ -441,35 +485,18 @@ export function checkbox(options) {
441
485
  return {
442
486
  type: 'checkbox',
443
487
  ...options,
488
+ defaultValue: options?.defaultValue ?? false,
444
489
  getZodSchema: () => {
445
490
  return z.boolean().optional().nullable();
446
491
  },
447
- getPrismaType: (_fieldName) => {
448
- const db = options?.db;
449
- const hasDefault = options?.defaultValue !== undefined;
450
- let modifiers = '';
451
- // Checkboxes are non-nullable by default (must be true or false), unlike
452
- // the other scalar fields' nullable-unless-required default — set
453
- // db.isNullable: true to allow NULL.
454
- if (db?.isNullable === true) {
455
- modifiers += '?';
456
- }
457
- if (hasDefault) {
458
- modifiers += ` @default(${options.defaultValue})`;
459
- }
460
- if (db?.map) {
461
- modifiers += ` @map("${db.map}")`;
462
- }
463
- return {
464
- type: 'Boolean',
465
- modifiers: modifiers.trimStart() || undefined,
466
- };
467
- },
468
- getTypeScriptType: () => {
469
- return {
470
- type: 'boolean',
471
- optional: options?.defaultValue === undefined,
472
- };
492
+ getContractField: (fieldName, listKey) => {
493
+ checkedDefault(options?.defaultValue, listKey, fieldName, 'a boolean', (value) => typeof value === 'boolean');
494
+ return scalarColumn(fieldName, {
495
+ type: pgType('boolean'),
496
+ nullable: options?.db?.isNullable === true,
497
+ map: options?.db?.map,
498
+ default: literalDefault(options?.defaultValue ?? false, listKey, fieldName),
499
+ });
473
500
  },
474
501
  // Anything other than true/false degrades to free text.
475
502
  getFilterSpec: (fieldName) => ({
@@ -506,46 +533,20 @@ export function timestamp(options) {
506
533
  getZodSchema: () => {
507
534
  return z.union([z.date(), z.iso.datetime()]).optional().nullable();
508
535
  },
509
- getPrismaType: (_fieldName) => {
510
- const db = options?.db;
511
- const hasDefaultNow = options?.defaultValue &&
512
- typeof options.defaultValue === 'object' &&
513
- 'kind' in options.defaultValue &&
514
- options.defaultValue.kind === 'now';
515
- const isNullable = db?.isNullable ?? !hasDefaultNow;
516
- let modifiers = '';
517
- if (isNullable) {
518
- modifiers += '?';
519
- }
520
- if (hasDefaultNow) {
521
- modifiers += ' @default(now())';
522
- }
523
- if (db?.nativeType) {
524
- modifiers += ` @db.${db.nativeType}`;
525
- }
526
- if (db?.map) {
527
- modifiers += ` @map("${db.map}")`;
528
- }
529
- // Unique modifier — non-unique index routes through `index` below,
530
- // same as `text()`'s getPrismaType.
531
- if (options?.isIndexed === 'unique') {
532
- modifiers += ' @unique';
533
- }
534
- return {
535
- type: 'DateTime',
536
- modifiers: modifiers.trimStart() || undefined,
537
- index: options?.isIndexed === true ? true : undefined,
538
- };
539
- },
540
- getTypeScriptType: () => {
541
- const hasDefault = options?.defaultValue &&
542
- typeof options.defaultValue === 'object' &&
543
- 'kind' in options.defaultValue &&
544
- options.defaultValue.kind === 'now';
545
- return {
546
- type: 'Date',
547
- optional: !hasDefault,
548
- };
536
+ getContractField: (fieldName) => {
537
+ const defaultValue = options?.defaultValue;
538
+ const hasDefaultNow = typeof defaultValue === 'object' &&
539
+ defaultValue !== null &&
540
+ 'kind' in defaultValue &&
541
+ defaultValue.kind === 'now';
542
+ return scalarColumn(fieldName, {
543
+ type: pgType('dateTime'),
544
+ nullable: options?.db?.isNullable ?? !hasDefaultNow,
545
+ nativeType: options?.db?.nativeType,
546
+ map: options?.db?.map,
547
+ isIndexed: options?.isIndexed,
548
+ default: hasDefaultNow ? { kind: 'now' } : undefined,
549
+ });
549
550
  },
550
551
  // An unparseable date degrades to free text.
551
552
  getFilterSpec: (fieldName) => ({
@@ -570,20 +571,16 @@ export function timestamp(options) {
570
571
  *
571
572
  * **Features:**
572
573
  * - Stores date values only (no time component)
573
- * - PostgreSQL/MySQL: Uses native DATE type via @db.Date
574
- * - SQLite: Uses String representation
575
- * - **Writes:** pass a `YYYY-MM-DD` string (the declared type). A
576
- * `resolveInput` hook converts a valid string to a UTC-midnight `Date`
577
- * before validation, since Prisma 7's client validator rejects a bare date
578
- * string for a `@db.Date` column (#621); a `Date` is also accepted
579
- * directly. A malformed string is rejected at runtime by validation (a
580
- * `ValidationError`). Genuine compile-time rejection of a `Date` at the
581
- * `context.db` call site is tracked in #599.
582
- * - **Reads:** always return a `YYYY-MM-DD` string. Even though the underlying
583
- * `@db.Date` column hands Prisma a `Date`, a `resolveOutput` transform
584
- * normalises it back to a `YYYY-MM-DD` string so the runtime value matches
585
- * the declared `string` type. UTC components are used to avoid timezone
586
- * off-by-one errors.
574
+ * - PostgreSQL: a native `date` column bound to a string codec, so the value
575
+ * in flight is a `YYYY-MM-DD` string on both sides of the driver
576
+ * - **Writes:** pass a `YYYY-MM-DD` string (the declared type) straight
577
+ * through to the column. A malformed string is rejected at runtime by
578
+ * validation (a `ValidationError`). Genuine compile-time rejection of a
579
+ * `Date` at the `context.db` call site is tracked in #599.
580
+ * - **Reads:** always return a `YYYY-MM-DD` string. A `resolveOutput`
581
+ * transform normalises the column's value — ordinarily already a string,
582
+ * but tolerant of a `Date` from a differently-configured column — using its
583
+ * UTC components so the result never drifts a day in a non-UTC timezone.
587
584
  * - Optional validation for required fields
588
585
  * - Database column mapping and nullability control
589
586
  * - Index support (boolean or 'unique')
@@ -605,7 +602,7 @@ export function timestamp(options) {
605
602
  * }
606
603
  *
607
604
  * // Creating with date values — pass YYYY-MM-DD strings (NOT Date objects)
608
- * const event = await context.db.event.create({
605
+ * const event = await context.db.Event.create({
609
606
  * data: {
610
607
  * startDate: '2025-01-15',
611
608
  * endDate: '2025-01-20'
@@ -613,7 +610,7 @@ export function timestamp(options) {
613
610
  * })
614
611
  *
615
612
  * // Reading — values come back as YYYY-MM-DD strings
616
- * const e = await context.db.event.findUnique({ where: { id } })
613
+ * const e = await context.db.Event.where({ id }).first()
617
614
  * e?.startDate // => '2025-01-15' (a string, not a Date)
618
615
  * ```
619
616
  *
@@ -623,23 +620,10 @@ export function timestamp(options) {
623
620
  export function calendarDay(options) {
624
621
  return {
625
622
  type: 'calendarDay',
623
+ outputType: 'string',
624
+ inputType: 'string',
626
625
  ...options,
627
- // Hook Pipeline runs field resolveInput before zod validation — the only
628
- // point a YYYY-MM-DD string can be turned into what Prisma's `@db.Date`
629
- // write validator accepts (#621). Reads resolvedData[fieldKey], not raw
630
- // inputData, so a list-level resolveInput's injected default for an
631
- // omitted key is still coerced rather than overwritten.
632
626
  hooks: {
633
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
634
- resolveInput: ({ resolvedData, fieldKey }) => {
635
- const value = resolvedData?.[fieldKey];
636
- if (value == null || value instanceof Date)
637
- return value;
638
- if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
639
- return new Date(`${value}T00:00:00.000Z`);
640
- }
641
- return value;
642
- },
643
627
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field builder hooks must be generic
644
628
  resolveOutput: ({ value }) => formatCalendarDay(value),
645
629
  ...options?.hooks,
@@ -648,17 +632,13 @@ export function calendarDay(options) {
648
632
  getZodSchema: (fieldName, operation) => {
649
633
  const validation = options?.validation;
650
634
  const isRequired = validation?.isRequired;
651
- // Accepts a `Date` because resolveInput above already converted a valid
652
- // string to one before this schema runs; a malformed string falls
653
- // through resolveInput untouched and fails the regex here instead.
654
- const stringSchema = z
635
+ const dateSchema = z
655
636
  .string({
656
637
  message: `${formatFieldName(fieldName)} must be a valid date in ISO8601 format (YYYY-MM-DD)`,
657
638
  })
658
639
  .regex(/^\d{4}-\d{2}-\d{2}$/, {
659
640
  message: `${formatFieldName(fieldName)} must be in YYYY-MM-DD format`,
660
641
  });
661
- const dateSchema = z.union([stringSchema, z.date()]);
662
642
  if (isRequired && operation === 'create') {
663
643
  return dateSchema;
664
644
  }
@@ -669,60 +649,32 @@ export function calendarDay(options) {
669
649
  return dateSchema.optional().nullable();
670
650
  }
671
651
  },
672
- getPrismaType: (_fieldName, provider) => {
673
- const validation = options?.validation;
674
- const db = options?.db;
675
- const isRequired = validation?.isRequired;
676
- const isNullable = db?.isNullable ?? !isRequired;
677
- let modifiers = '';
678
- if (isNullable) {
679
- modifiers += '?';
680
- }
681
- // SQLite has no native DATE type and falls back to TEXT for DateTime
682
- // columns, so @db.Date only applies on PostgreSQL/MySQL.
683
- if (provider && provider.toLowerCase() !== 'sqlite') {
684
- modifiers += ' @db.Date';
685
- }
686
- if (options?.defaultValue !== undefined) {
687
- modifiers += ` @default("${options.defaultValue}")`;
688
- }
689
- if (db?.map) {
690
- modifiers += ` @map("${db.map}")`;
691
- }
692
- // Unique modifier — non-unique index routes through `index` below,
693
- // same as `text()`'s getPrismaType.
694
- if (options?.isIndexed === 'unique') {
695
- modifiers += ' @unique';
696
- }
697
- return {
698
- type: 'DateTime',
699
- modifiers: modifiers.trimStart() || undefined,
700
- index: options?.isIndexed === true ? true : undefined,
701
- };
702
- },
703
- getTypeScriptType: () => {
704
- const validation = options?.validation;
705
- const db = options?.db;
706
- const isRequired = validation?.isRequired;
707
- const isNullable = db?.isNullable ?? !isRequired;
708
- return {
709
- type: 'string',
710
- optional: isNullable,
711
- };
652
+ getContractField: (fieldName, listKey) => {
653
+ checkedDefault(options?.defaultValue, listKey, fieldName, 'a valid YYYY-MM-DD calendar date', isCalendarDate);
654
+ return scalarColumn(fieldName, {
655
+ type: pgType('dateTime'),
656
+ nativeType: 'date',
657
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
658
+ map: options?.db?.map,
659
+ isIndexed: options?.isIndexed,
660
+ default: literalDefault(options?.defaultValue, listKey, fieldName),
661
+ });
712
662
  },
713
- // Calendar days compare on the `YYYY-MM-DD` value (coerced to a UTC-midnight
714
- // Date so it matches the `@db.Date` column). A malformed value degrades to
715
- // free text.
663
+ // Calendar days compare on the `YYYY-MM-DD` value itself — the column's
664
+ // string codec passes it straight to the driver, so a Date built here
665
+ // would hit the same local-timezone drift the write path had (#1437). A
666
+ // malformed value, including an out-of-range month/day the regex alone
667
+ // cannot catch (e.g. '2025-13-01'), degrades to free text instead of
668
+ // reaching Postgres as an invalid date literal.
716
669
  getFilterSpec: (fieldName) => ({
717
670
  operators: COMPARISON_OPERATORS,
718
671
  toCondition: (operator, value) => {
719
672
  const trimmed = value.trim();
720
673
  if (!/^\d{4}-\d{2}-\d{2}$/.test(trimmed))
721
674
  return null;
722
- const date = new Date(`${trimmed}T00:00:00.000Z`);
723
- if (Number.isNaN(date.getTime()))
675
+ if (Number.isNaN(new Date(`${trimmed}T00:00:00.000Z`).getTime()))
724
676
  return null;
725
- return { [fieldName]: { [prismaComparisonKey(operator)]: date } };
677
+ return { [fieldName]: { [prismaComparisonKey(operator)]: trimmed } };
726
678
  },
727
679
  suggestions: { valueSource: { kind: 'none' } },
728
680
  }),
@@ -772,7 +724,7 @@ function formatCalendarDay(value) {
772
724
  * }
773
725
  *
774
726
  * // Creating a user - password is automatically hashed
775
- * const user = await context.db.user.create({
727
+ * const user = await context.db.User.create({
776
728
  * data: {
777
729
  * email: 'user@example.com',
778
730
  * password: 'plaintextPassword' // Automatically hashed before storage
@@ -780,9 +732,7 @@ function formatCalendarDay(value) {
780
732
  * })
781
733
  *
782
734
  * // Authenticating - use the compare() method
783
- * const user = await context.db.user.findUnique({
784
- * where: { email: 'user@example.com' }
785
- * })
735
+ * const user = await context.db.User.where({ email: 'user@example.com' }).first()
786
736
  *
787
737
  * if (user && await user.password.compare('plaintextPassword')) {
788
738
  * // Password is correct - login successful
@@ -810,10 +760,9 @@ function formatCalendarDay(value) {
810
760
  export function password(options) {
811
761
  return {
812
762
  type: 'password',
763
+ outputType: "import('@opensaas/stack-core/internal').HashedPassword",
813
764
  ...options,
814
- resultExtension: {
815
- outputType: "import('@opensaas/stack-core/internal').HashedPassword",
816
- },
765
+ isFilterable: false,
817
766
  ui: {
818
767
  ...options?.ui,
819
768
  // Excluded from default admin table columns (issue #1018) — declared
@@ -880,33 +829,12 @@ export function password(options) {
880
829
  .nullable();
881
830
  }
882
831
  },
883
- getPrismaType: (_fieldName) => {
884
- const validation = options?.validation;
885
- const db = options?.db;
886
- const isRequired = validation?.isRequired;
887
- const isNullable = db?.isNullable ?? !isRequired;
888
- let modifiers = '';
889
- if (isNullable) {
890
- modifiers += '?';
891
- }
892
- if (db?.nativeType) {
893
- modifiers += ` @db.${db.nativeType}`;
894
- }
895
- if (db?.map) {
896
- modifiers += ` @map("${db.map}")`;
897
- }
898
- return {
899
- type: 'String',
900
- modifiers: modifiers.trimStart() || undefined,
901
- };
902
- },
903
- getTypeScriptType: () => {
904
- const isRequired = options?.validation?.isRequired;
905
- return {
906
- type: 'string',
907
- optional: !isRequired,
908
- };
909
- },
832
+ getContractField: (fieldName) => scalarColumn(fieldName, {
833
+ type: pgType('text'),
834
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
835
+ nativeType: options?.db?.nativeType,
836
+ map: options?.db?.map,
837
+ }),
910
838
  };
911
839
  }
912
840
  /**
@@ -929,85 +857,50 @@ export function select(options) {
929
857
  throw new Error(`Enum select field values must be valid Prisma identifiers (letters, numbers, and underscores, starting with a letter). Invalid values: ${invalidValues.join(', ')}`);
930
858
  }
931
859
  }
860
+ const unionType = options.options.map((opt) => quoteStringLiteral(opt.value)).join(' | ');
932
861
  return {
933
862
  type: 'select',
863
+ outputType: unionType,
864
+ inputType: unionType,
934
865
  ...options,
935
866
  getZodSchema: (fieldName, operation) => {
936
867
  const values = options.options.map((opt) => opt.value);
937
868
  let schema = z.enum(values, {
938
869
  message: `${formatFieldName(fieldName)} must be one of: ${values.join(', ')}`,
939
870
  });
940
- if (!options.validation?.isRequired || operation === 'update') {
871
+ if (options.validation?.isRequired) {
872
+ if (operation === 'update')
873
+ schema = schema.optional();
874
+ }
875
+ else {
941
876
  schema = schema.optional().nullable();
942
877
  }
943
878
  return schema;
944
879
  },
945
- getPrismaType: (fieldName, _provider, listName) => {
946
- const isRequired = options.validation?.isRequired;
880
+ getContractField: (fieldName, listName) => {
947
881
  const hasDefault = options.defaultValue !== undefined;
948
- // Nullability rules (Keystone parity):
949
- // - `db.isNullable` is an explicit override and always wins. Setting it
950
- // `true` forces the `?` even when a `defaultValue` is present.
951
- // - Otherwise a select is nullable only when it is neither required nor
952
- // carrying a default: a `defaultValue` makes the column NOT NULL (the
953
- // long-standing default behaviour). This mirrors the previous logic
954
- // where a present default overwrote the `?`.
955
- // Nullability and the default are assembled independently with `+=`
956
- // (mirroring text/integer) so the default never overwrites the `?`.
957
- const isNullable = options.db?.isNullable ?? (!isRequired && !hasDefault);
958
- let modifiers = '';
959
- if (isNullable) {
960
- modifiers += '?';
961
- }
962
- if (isNativeEnum) {
963
- // Enum type name: explicit `db.enumName` wins, otherwise derive from
964
- // list name + field name in PascalCase. The same name is used for the
965
- // generated enum block (via `result.type`) and the column reference.
966
- const capitalizedField = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
967
- const derivedEnumName = listName ? `${listName}${capitalizedField}` : capitalizedField;
968
- const enumName = options.db?.enumName ?? derivedEnumName;
969
- // No quotes for enum default values (unlike the string branch below).
970
- if (hasDefault) {
971
- modifiers += ` @default(${options.defaultValue})`;
972
- }
973
- if (options.db?.map) {
974
- modifiers += ` @map("${options.db.map}")`;
975
- }
976
- // Unique modifier — non-unique index routes through `index` below,
977
- // same as `text()`'s getPrismaType.
978
- if (options.isIndexed === 'unique') {
979
- modifiers += ' @unique';
980
- }
981
- return {
982
- type: enumName,
983
- modifiers: modifiers || undefined,
984
- enumValues: options.options.map((opt) => opt.value),
985
- index: options.isIndexed === true ? true : undefined,
986
- };
987
- }
988
- // String type (default)
989
- if (hasDefault) {
990
- modifiers += ` @default("${options.defaultValue}")`;
991
- }
992
- if (options.db?.map) {
993
- modifiers += ` @map("${options.db.map}")`;
994
- }
995
- if (options.isIndexed === 'unique') {
996
- modifiers += ' @unique';
882
+ const nullable = options.db?.isNullable ?? (!options.validation?.isRequired && !hasDefault);
883
+ if (!isNativeEnum) {
884
+ return scalarColumn(fieldName, {
885
+ type: pgType('text'),
886
+ nullable,
887
+ map: options.db?.map,
888
+ isIndexed: options.isIndexed,
889
+ default: literalDefault(options.defaultValue, listName, fieldName),
890
+ });
997
891
  }
998
- return {
999
- type: 'String',
1000
- modifiers: modifiers || undefined,
1001
- index: options.isIndexed === true ? true : undefined,
1002
- };
1003
- },
1004
- getTypeScriptType: () => {
1005
- // Generate union type from options (same for both string and enum db types)
1006
- const unionType = options.options.map((opt) => `'${opt.value}'`).join(' | ');
1007
- return {
1008
- type: unionType,
1009
- optional: !options.validation?.isRequired || options.defaultValue !== undefined,
1010
- };
892
+ const capitalizedField = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
893
+ return scalarColumn(fieldName, {
894
+ type: pgType('enum'),
895
+ nullable,
896
+ map: options.db?.map,
897
+ isIndexed: options.isIndexed,
898
+ default: literalDefault(options.defaultValue, listName, fieldName),
899
+ enum: {
900
+ name: options.db?.enumName ?? `${listName}${capitalizedField}`,
901
+ values: options.options.map((opt) => opt.value),
902
+ },
903
+ });
1011
904
  },
1012
905
  // Selects filter by equality against their enumerated options. The token
1013
906
  // value is matched (case-insensitively) against option value or label and
@@ -1057,7 +950,30 @@ function parseRelationshipRef(ref) {
1057
950
  throw new Error(`Invalid relationship ref: ${ref}`);
1058
951
  }
1059
952
  }
1060
- function isOneToOneRelationship(fieldName, field, config) {
953
+ /** Narrow a field config to the relationship variant. */
954
+ export function isRelationshipField(field) {
955
+ return field?.type === 'relationship';
956
+ }
957
+ /**
958
+ * Whether a field is a to-many relationship — the only field kind that
959
+ * carries a relationship count (a to-one relationship has at most one
960
+ * related row).
961
+ */
962
+ export function isToManyRelationshipField(field) {
963
+ return (field?.type === 'relationship' &&
964
+ 'many' in field &&
965
+ field.many === true &&
966
+ 'ref' in field &&
967
+ typeof field.ref === 'string' &&
968
+ field.ref.length > 0);
969
+ }
970
+ /**
971
+ * Whether `field` declares one end of a one-to-one: a bidirectional ref with
972
+ * `many: false` on both ends. A list-only ref is never one-to-one. Throws
973
+ * when the ref's target list or field does not exist or is not a
974
+ * relationship.
975
+ */
976
+ export function isOneToOneRelationship(fieldName, field, config) {
1061
977
  const { list: targetList, field: targetField } = parseRelationshipRef(field.ref);
1062
978
  if (!targetField) {
1063
979
  return false;
@@ -1078,7 +994,23 @@ function isOneToOneRelationship(fieldName, field, config) {
1078
994
  }
1079
995
  return !targetFieldConfig.many;
1080
996
  }
1081
- function shouldHaveForeignKey(listKey, fieldName, field, config) {
997
+ /**
998
+ * Whether `field` claims the foreign key column of its one-to-one with
999
+ * `db.foreignKey: true`. The `{ map }` form renames the column without
1000
+ * claiming it.
1001
+ */
1002
+ export function claimsForeignKey(field) {
1003
+ return field.db?.foreignKey === true;
1004
+ }
1005
+ /**
1006
+ * Whether `field`'s side of its relationship owns the foreign key column: a
1007
+ * list-only ref or the to-one side of a one-to-many always does; the to-many
1008
+ * side never does; on a one-to-one the end that claims it with
1009
+ * `db.foreignKey: true` does, else the alphabetically smaller list name, else
1010
+ * (self-referential) the alphabetically smaller field name (ADR-0064).
1011
+ * Throws when both ends claim it.
1012
+ */
1013
+ export function shouldHaveForeignKey(listKey, fieldName, field, config) {
1082
1014
  const { list: targetList, field: targetField } = parseRelationshipRef(field.ref);
1083
1015
  if (!targetField) {
1084
1016
  return true;
@@ -1092,15 +1024,15 @@ function shouldHaveForeignKey(listKey, fieldName, field, config) {
1092
1024
  }
1093
1025
  const targetListConfig = config.lists[targetList];
1094
1026
  const targetFieldConfig = targetListConfig.fields[targetField];
1095
- const thisSideExplicit = field.db?.foreignKey;
1096
- const otherSideExplicit = targetFieldConfig.db?.foreignKey;
1097
- if (thisSideExplicit === true && otherSideExplicit === true) {
1027
+ const thisSideClaims = claimsForeignKey(field);
1028
+ const otherSideClaims = claimsForeignKey(targetFieldConfig);
1029
+ if (thisSideClaims && otherSideClaims) {
1098
1030
  throw new Error(`Invalid one-to-one relationship: both "${listKey}.${fieldName}" and "${targetList}.${targetField}" have db.foreignKey set to true. Only one side can store the foreign key.`);
1099
1031
  }
1100
- if (thisSideExplicit === true) {
1032
+ if (thisSideClaims) {
1101
1033
  return true;
1102
1034
  }
1103
- if (otherSideExplicit === true) {
1035
+ if (otherSideClaims) {
1104
1036
  return false;
1105
1037
  }
1106
1038
  // Default: the alphabetically "smaller" list name gets the foreign key
@@ -1111,60 +1043,6 @@ function shouldHaveForeignKey(listKey, fieldName, field, config) {
1111
1043
  // Self-referential: use field name ordering
1112
1044
  return fieldName.localeCompare(targetField) < 0;
1113
1045
  }
1114
- function isManyToMany(fieldName, field, config) {
1115
- if (!field.many) {
1116
- return false;
1117
- }
1118
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref);
1119
- // List-only ref with many: true is implicitly many-to-many
1120
- if (!targetField) {
1121
- return true;
1122
- }
1123
- const targetFieldConfig = config.lists[targetList]?.fields[targetField];
1124
- if (!targetFieldConfig || targetFieldConfig.type !== 'relationship') {
1125
- return false;
1126
- }
1127
- return !!targetFieldConfig.many;
1128
- }
1129
- /**
1130
- * Compute the explicit relation name for a bidirectional many-to-many relationship,
1131
- * or `undefined` when Prisma's default naming should be used.
1132
- *
1133
- * Honours per-field `db.relationName` (which must match on both sides) and the
1134
- * global `db.joinTableNaming: 'keystone'` setting, picking a deterministic owner
1135
- * for bidirectional relationships so both sides resolve to the same name.
1136
- */
1137
- function computeManyToManyRelationName(listKey, fieldName, field, config) {
1138
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref);
1139
- const joinTableNaming = config.db.joinTableNaming || 'prisma';
1140
- const sourceRelationName = field.db?.relationName;
1141
- let targetRelationName;
1142
- if (targetField) {
1143
- const targetFieldConfig = config.lists[targetList]?.fields[targetField];
1144
- if (targetFieldConfig?.type === 'relationship') {
1145
- targetRelationName = targetFieldConfig.db?.relationName;
1146
- }
1147
- }
1148
- if (sourceRelationName && targetRelationName && sourceRelationName !== targetRelationName) {
1149
- throw new Error(`Relation name mismatch: ${listKey}.${fieldName} has relationName "${sourceRelationName}" but ${targetList}.${targetField} has "${targetRelationName}". Both sides must use the same relationName.`);
1150
- }
1151
- const explicitRelationName = sourceRelationName || targetRelationName;
1152
- if (explicitRelationName) {
1153
- return explicitRelationName;
1154
- }
1155
- if (joinTableNaming === 'keystone') {
1156
- if (targetField) {
1157
- // Pick a deterministic owner so both sides agree on the relation name
1158
- const sourceKey = `${listKey}.${fieldName}`;
1159
- const targetKey = `${targetList}.${targetField}`;
1160
- return sourceKey.localeCompare(targetKey) < 0
1161
- ? `${listKey}_${fieldName}`
1162
- : `${targetList}_${targetField}`;
1163
- }
1164
- return `${listKey}_${fieldName}`;
1165
- }
1166
- return undefined;
1167
- }
1168
1046
  /**
1169
1047
  * The name Prisma generation synthesizes for the back-relation a list-only
1170
1048
  * `ref` (`ref: 'ListName'`, no target field) creates on its target model —
@@ -1176,84 +1054,36 @@ function computeManyToManyRelationName(listKey, fieldName, field, config) {
1176
1054
  export function getSyntheticFieldName(listKey, fieldName) {
1177
1055
  return `from_${listKey}_${fieldName}`;
1178
1056
  }
1179
- function getPrismaRelation(field, fieldName, listKey, config) {
1180
- const { list: targetList, field: targetField } = parseRelationshipRef(field.ref);
1181
- const paddedName = fieldName.padEnd(12);
1182
- // Synthetic back-relation for list-only refs (Prisma requires an opposite field)
1183
- let backRelation;
1184
- if (!targetField) {
1185
- const syntheticFieldName = getSyntheticFieldName(listKey, fieldName);
1186
- const relationName = field.db?.relationName ?? `${listKey}_${fieldName}`;
1187
- backRelation = {
1188
- targetList,
1189
- line: ` ${syntheticFieldName.padEnd(12)} ${listKey}[] @relation("${relationName}")`,
1190
- };
1191
- }
1057
+ function nullableOnNonOwningSideMessage(listKey, fieldName, targetList, targetField) {
1058
+ return (`db.isNullable can only be used on the foreign-key-owning side of a relationship. ` +
1059
+ `"${listKey}.${fieldName}" does not own the foreign key for this one-to-one relationship — ` +
1060
+ `set db.isNullable on "${targetList}.${targetField}" instead, or make this side own the ` +
1061
+ `foreign key via db.foreignKey.`);
1062
+ }
1063
+ function getContractRelation(field, fieldName, listKey, config) {
1064
+ const { list: target, field: targetField } = parseRelationshipRef(field.ref);
1065
+ const inverse = targetField
1066
+ ? { field: targetField, synthetic: false }
1067
+ : { field: getSyntheticFieldName(listKey, fieldName), synthetic: true };
1192
1068
  if (field.many) {
1193
- let relationLine;
1194
- if (targetField) {
1195
- // Bidirectional many side: use explicit relation name only for true many-to-many
1196
- const m2mName = isManyToMany(fieldName, field, config)
1197
- ? computeManyToManyRelationName(listKey, fieldName, field, config)
1198
- : undefined;
1199
- relationLine = m2mName
1200
- ? ` ${paddedName} ${targetList}[] @relation("${m2mName}")`
1201
- : ` ${paddedName} ${targetList}[]`;
1202
- }
1203
- else {
1204
- // List-only ref many side: always a named relation paired with the synthetic field
1205
- const relationName = field.db?.relationName ?? `${listKey}_${fieldName}`;
1206
- relationLine = ` ${paddedName} ${targetList}[] @relation("${relationName}")`;
1207
- }
1208
- if (field.db?.extendPrismaSchema) {
1209
- relationLine = field.db.extendPrismaSchema({ relationLine }).relationLine;
1210
- }
1211
- return { modelLines: [relationLine], backRelation };
1069
+ return { kind: 'relation', target, inverse, many: true };
1212
1070
  }
1213
- // Single relationship
1214
- if (shouldHaveForeignKey(listKey, fieldName, field, config)) {
1215
- const foreignKeyField = `${fieldName}Id`;
1216
- const fkPaddedName = foreignKeyField.padEnd(12);
1217
- const uniqueModifier = isOneToOneRelationship(fieldName, field, config) ? ' @unique' : '';
1218
- const mapModifier = typeof field.db?.foreignKey === 'object' && field.db.foreignKey.map
1219
- ? ` @map("${field.db.foreignKey.map}")`
1220
- : ` @map("${fieldName}")`;
1221
- // Nullability: explicit db.isNullable overrides the default (nullable),
1222
- // matching the scalar fields' `db.isNullable` convention. It moves the FK
1223
- // column and its relation field together — they can never disagree.
1224
- const isNullable = field.db?.isNullable ?? true;
1225
- const nullModifier = isNullable ? '?' : '';
1226
- let fkLine = ` ${fkPaddedName} String${nullModifier}${uniqueModifier}${mapModifier}`;
1227
- let relationLine = targetField
1228
- ? ` ${paddedName} ${targetList}${nullModifier} @relation(fields: [${foreignKeyField}], references: [id])`
1229
- : ` ${paddedName} ${targetList}${nullModifier} @relation("${listKey}_${fieldName}", fields: [${foreignKeyField}], references: [id])`;
1230
- if (field.db?.extendPrismaSchema) {
1231
- const extended = field.db.extendPrismaSchema({ fkLine, relationLine });
1232
- fkLine = extended.fkLine ?? fkLine;
1233
- relationLine = extended.relationLine;
1071
+ if (!shouldHaveForeignKey(listKey, fieldName, field, config)) {
1072
+ if (field.db?.isNullable === false) {
1073
+ throw new Error(nullableOnNonOwningSideMessage(listKey, fieldName, target, targetField));
1234
1074
  }
1235
- // Default to indexing foreign keys (matching Keystone behaviour) unless disabled
1236
- const indexType = field.isIndexed ?? true;
1237
- const foreignKeyIndex = indexType !== false ? { foreignKeyField, indexType } : undefined;
1238
- return { modelLines: [fkLine, relationLine], foreignKeyField, foreignKeyIndex, backRelation };
1239
- }
1240
- // Non-FK side of a one-to-one relationship: just the relation field. This
1241
- // side has no foreign key column, so `db.isNullable` (which only makes
1242
- // sense paired with a column) cannot be honoured here — reject rather than
1243
- // silently ignore a developer's stated intent (the FK-owning side is
1244
- // determined by `db.foreignKey`/alphabetical ordering, not by which field
1245
- // declares `isNullable`).
1246
- if (field.db?.isNullable === false) {
1247
- throw new Error(`db.isNullable can only be used on the foreign-key-owning side of a relationship. ` +
1248
- `"${listKey}.${fieldName}" does not own the foreign key for this one-to-one relationship — ` +
1249
- `set db.isNullable on "${targetList}.${targetField}" instead, or make this side own the ` +
1250
- `foreign key via db.foreignKey.`);
1251
- }
1252
- let relationLine = ` ${paddedName} ${targetList}?`;
1253
- if (field.db?.extendPrismaSchema) {
1254
- relationLine = field.db.extendPrismaSchema({ relationLine }).relationLine;
1075
+ return { kind: 'relation', target, inverse, many: false };
1255
1076
  }
1256
- return { modelLines: [relationLine], backRelation };
1077
+ const explicitMap = typeof field.db?.foreignKey === 'object' ? field.db.foreignKey.map : undefined;
1078
+ const foreignKey = {
1079
+ name: `${fieldName}Id`,
1080
+ ...(explicitMap !== undefined ? { map: explicitMap } : {}),
1081
+ nullable: field.db?.isNullable ?? true,
1082
+ unique: field.isIndexed === 'unique' || isOneToOneRelationship(fieldName, field, config),
1083
+ index: field.isIndexed === undefined || field.isIndexed === true,
1084
+ references: { list: target, field: 'id' },
1085
+ };
1086
+ return { kind: 'relation', target, inverse, many: false, foreignKey };
1257
1087
  }
1258
1088
  /**
1259
1089
  * Relationship field
@@ -1286,18 +1116,17 @@ export function relationship(options) {
1286
1116
  type: 'relationship',
1287
1117
  ...options,
1288
1118
  };
1289
- field.getPrismaRelation = (fieldName, _allFields, listKey, config) => getPrismaRelation(field, fieldName, listKey, config);
1290
- // Relationships filter differently by cardinality (issue #732):
1119
+ field.getContractField = (fieldName, listKey, config) => getContractRelation(field, fieldName, listKey, config);
1120
+ // Relationships filter differently by cardinality (issue #732, ADR-0055):
1291
1121
  // • to-one filters by the related Item's label — `author:"Ada Lovelace"`
1292
- // becomes a nested `is` `contains` on the target list's Label field.
1293
- // • to-many filters by the access-visible related COUNT with numeric
1294
- // comparisons — `orders:>5`. Prisma cannot compare a relation count in a
1295
- // `where`, so the mapper emits a structured count marker
1296
- // (RELATIONSHIP_COUNT_FILTER_KEY) that `resolveRelationshipCountFilters`
1297
- // later turns into an access-scoped `{ id: { in } }`.
1298
- // The mapper stays pure in both cases (no DB lookup). Suggestions point a
1299
- // to-one at the target list's label lookup; a to-many exposes no value source
1300
- // (a numeric compare, like an integer field).
1122
+ // becomes a `some` over the target list's Label field. Prisma 8 has no
1123
+ // to-one predicate form: every relation predicate is an EXISTS, and its
1124
+ // accessor is the same for both cardinalities.
1125
+ // • to-many filters by PRESENCE. Prisma 8 cannot compare a relation count
1126
+ // in a `where`, so `orders:0` is `none`, `orders:>0`/`orders:>=1` are
1127
+ // `some`, and any other comparison degrades to free text.
1128
+ // The mapper stays pure in both cases (no DB lookup); the engine ANDs the
1129
+ // related list's own `query` access inside the EXISTS when it lowers this.
1301
1130
  field.getFilterSpec = (_fieldName, _listKey, config) => {
1302
1131
  const { list: targetList } = parseRelationshipRef(field.ref);
1303
1132
  const relatedListConfig = config.lists[targetList];
@@ -1308,29 +1137,36 @@ export function relationship(options) {
1308
1137
  operators: COMPARISON_OPERATORS,
1309
1138
  toCondition: (operator, value) => {
1310
1139
  const trimmed = value.trim();
1311
- // A non-integer count comparison can't be interpreted → degrade to
1312
- // free text (matching the integer field's behaviour).
1313
1140
  if (!/^-?\d+$/.test(trimmed))
1314
1141
  return null;
1315
- return {
1316
- [_fieldName]: { [RELATIONSHIP_COUNT_FILTER_KEY]: { operator, value: Number(trimmed) } },
1317
- };
1142
+ const count = Number(trimmed);
1143
+ if (operator === 'eq' && count === 0)
1144
+ return { [_fieldName]: { none: {} } };
1145
+ if (operator === 'gt' && count === 0)
1146
+ return { [_fieldName]: { some: {} } };
1147
+ if (operator === 'gte' && count === 1)
1148
+ return { [_fieldName]: { some: {} } };
1149
+ return null;
1318
1150
  },
1319
1151
  suggestions: { valueSource: { kind: 'none' } },
1320
1152
  };
1321
1153
  }
1322
1154
  const labelField = getLabelFieldName(relatedListConfig);
1323
1155
  const labelFieldConfig = relatedListConfig.fields[labelField];
1324
- // A virtual label field has no queryable column, so `contains` can't run
1325
- // against it — the relationship is then not filterable.
1326
- if (labelFieldConfig?.virtual === true)
1156
+ // `contains` only runs against a real text column (ADR-0055's `ilike`
1157
+ // accessor). That rules out: a list with no `name`/`title`/`ui.labelField`,
1158
+ // which resolves to `id` — a field absent from `fields` entirely, since
1159
+ // it's never user-declared; a virtual label field, which has no backing
1160
+ // column at all; and a non-text label (`ui.labelField` may point at an
1161
+ // integer, checkbox, select, etc.). None of these is filterable (#1359).
1162
+ if (labelFieldConfig?.type !== 'text' || labelFieldConfig.virtual === true)
1327
1163
  return undefined;
1328
1164
  return {
1329
1165
  operators: ['eq'],
1330
1166
  toCondition: (operator, value) => {
1331
1167
  if (operator !== 'eq')
1332
1168
  return null;
1333
- return { [_fieldName]: { is: { [labelField]: { contains: value } } } };
1169
+ return { [_fieldName]: { some: { [labelField]: { contains: value } } } };
1334
1170
  },
1335
1171
  suggestions: { valueSource: { kind: 'relationship', listKey: targetList, many: false } },
1336
1172
  };
@@ -1364,16 +1200,14 @@ export function relationship(options) {
1364
1200
  * }
1365
1201
  *
1366
1202
  * // Creating with JSON data
1367
- * const item = await context.db.item.create({
1203
+ * const item = await context.db.Item.create({
1368
1204
  * data: {
1369
1205
  * metadata: { key: 'value', nested: { data: [1, 2, 3] } }
1370
1206
  * }
1371
1207
  * })
1372
1208
  *
1373
1209
  * // Querying returns parsed JSON
1374
- * const item = await context.db.item.findUnique({
1375
- * where: { id: '...' }
1376
- * })
1210
+ * const item = await context.db.Item.where({ id: '...' }).first()
1377
1211
  * console.log(item.metadata.key) // 'value'
1378
1212
  * ```
1379
1213
  *
@@ -1416,37 +1250,13 @@ export function json(options) {
1416
1250
  return baseSchema.optional().nullable();
1417
1251
  }
1418
1252
  },
1419
- getPrismaType: (_fieldName) => {
1420
- const validation = options?.validation;
1421
- const db = options?.db;
1422
- const isRequired = validation?.isRequired;
1423
- const isNullable = db?.isNullable ?? !isRequired;
1424
- let modifiers = '';
1425
- if (isNullable) {
1426
- modifiers += '?';
1427
- }
1428
- if (db?.nativeType) {
1429
- modifiers += ` @db.${db.nativeType}`;
1430
- }
1431
- const defaultLiteral = formatPrismaDefault(options?.defaultValue, 'json');
1432
- if (defaultLiteral !== undefined) {
1433
- modifiers += ` @default(${defaultLiteral})`;
1434
- }
1435
- if (db?.map) {
1436
- modifiers += ` @map("${db.map}")`;
1437
- }
1438
- return {
1439
- type: 'Json',
1440
- modifiers: modifiers.trimStart() || undefined,
1441
- };
1442
- },
1443
- getTypeScriptType: () => {
1444
- const isRequired = options?.validation?.isRequired;
1445
- return {
1446
- type: 'unknown',
1447
- optional: !isRequired,
1448
- };
1449
- },
1253
+ getContractField: (fieldName, listKey) => scalarColumn(fieldName, {
1254
+ type: pgType('jsonb'),
1255
+ nullable: options?.db?.isNullable ?? !options?.validation?.isRequired,
1256
+ nativeType: options?.db?.nativeType,
1257
+ map: options?.db?.map,
1258
+ default: literalDefault(options?.defaultValue, listKey, fieldName),
1259
+ }),
1450
1260
  };
1451
1261
  }
1452
1262
  /**
@@ -1456,36 +1266,16 @@ export function json(options) {
1456
1266
  * 2. Import string: "import('decimal.js').Decimal" -> returned as-is
1457
1267
  * 3. Type object: { value: Decimal, from: 'decimal.js' } -> "import('decimal.js').Decimal"
1458
1268
  */
1459
- function typeDescriptorToString(descriptor) {
1269
+ export function typeDescriptorToTypeString(descriptor) {
1460
1270
  if (typeof descriptor === 'string') {
1461
1271
  return descriptor;
1462
1272
  }
1463
1273
  const typeName = descriptor.name || descriptor.value.name;
1464
- return `import('${descriptor.from}').${typeName}`;
1465
- }
1466
- function typeDescriptorToImports(descriptor) {
1467
- if (typeof descriptor === 'string') {
1468
- const importMatch = descriptor.match(/import\('([^']+)'\)\.(\w+)/);
1469
- if (importMatch) {
1470
- return [
1471
- {
1472
- names: [importMatch[2]],
1473
- from: importMatch[1],
1474
- typeOnly: true,
1475
- },
1476
- ];
1477
- }
1478
- return [];
1479
- }
1480
- // Type object descriptor
1481
- const typeName = descriptor.name || descriptor.value.name;
1482
- return [
1483
- {
1484
- names: [typeName],
1485
- from: descriptor.from,
1486
- typeOnly: true,
1487
- },
1488
- ];
1274
+ const from = descriptor.from
1275
+ .replace(/\\/g, '\\\\')
1276
+ .replace(/'/g, "\\'")
1277
+ .replace(/[\n\r\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
1278
+ return `import('${from}').${typeName}`;
1489
1279
  }
1490
1280
  /**
1491
1281
  * Virtual field - not stored in database, computed via hooks
@@ -1506,6 +1296,7 @@ function typeDescriptorToImports(descriptor) {
1506
1296
  * lastName: text(),
1507
1297
  * fullName: virtual({
1508
1298
  * type: 'string',
1299
+ * needs: ['firstName', 'lastName'],
1509
1300
  * hooks: {
1510
1301
  * resolveOutput: ({ item }) => `${item.firstName} ${item.lastName}`
1511
1302
  * }
@@ -1516,6 +1307,7 @@ function typeDescriptorToImports(descriptor) {
1516
1307
  * fields: {
1517
1308
  * totalPrice: virtual({
1518
1309
  * type: "import('decimal.js').Decimal",
1310
+ * needs: ['price', 'quantity'],
1519
1311
  * hooks: {
1520
1312
  * resolveOutput: ({ item }) => new Decimal(item.price).times(item.quantity)
1521
1313
  * }
@@ -1528,6 +1320,7 @@ function typeDescriptorToImports(descriptor) {
1528
1320
  * fields: {
1529
1321
  * totalPrice: virtual({
1530
1322
  * type: { value: Decimal, from: 'decimal.js' },
1323
+ * needs: ['price', 'quantity'],
1531
1324
  * hooks: {
1532
1325
  * resolveOutput: ({ item }) => new Decimal(item.price).times(item.quantity)
1533
1326
  * }
@@ -1562,23 +1355,14 @@ export function virtual(options) {
1562
1355
  throw new Error('Virtual fields must provide a resolveOutput hook to compute their value. ' +
1563
1356
  'Example: hooks: { resolveOutput: ({ item }) => computeValue(item) }');
1564
1357
  }
1565
- const outputType = typeDescriptorToString(options.type);
1566
- const imports = typeDescriptorToImports(options.type);
1358
+ const outputType = typeDescriptorToTypeString(options.type);
1567
1359
  const { type: _, ...rest } = options;
1568
1360
  return {
1569
1361
  type: 'virtual',
1570
1362
  virtual: true,
1571
1363
  outputType,
1572
1364
  ...rest,
1573
- // undefined signals the generator to skip creating a database column.
1574
- getPrismaType: undefined,
1575
- getTypeScriptType: () => {
1576
- return {
1577
- type: outputType,
1578
- optional: false, // A virtual field always computes a value.
1579
- };
1580
- },
1581
- getTypeScriptImports: imports.length > 0 ? () => imports : undefined,
1365
+ getContractField: () => ({ kind: 'computed' }),
1582
1366
  // Virtual fields don't accept database input, so validation always fails.
1583
1367
  getZodSchema: () => {
1584
1368
  return z.never();