@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,1470 +0,0 @@
1
- import type { OpenSaasConfig, ListConfig, FieldConfig } from '../config/types.js'
2
- import type { FieldAccess, PrismaFilter } from '../access/types.js'
3
- import type { StackContext } from './index.js'
4
- import {
5
- checkAccess,
6
- checkCreateAccess,
7
- filterWritableFields,
8
- getRelatedListConfig,
9
- mergeFilters,
10
- resolveSyntheticReverseRelation,
11
- } from '../access/index.js'
12
- import { checkFieldAccess } from '../access/field-access.js'
13
- import {
14
- executeResolveInput,
15
- executeValidate,
16
- executeFieldResolveInputHooks,
17
- executeBeforeOperation,
18
- executeAfterOperation,
19
- executeFieldBeforeOperationHooks,
20
- executeFieldAfterOperationHooks,
21
- executeFieldValidateHooks,
22
- validateFieldRules,
23
- splitMultiColumnFields,
24
- ValidationError,
25
- } from '../hooks/index.js'
26
- import { getDbKey } from '../lib/case-utils.js'
27
- import { applyCreateDefaults } from './apply-defaults.js'
28
-
29
- /**
30
- * Nested writes (#569 / ADR-0010): give nested `create`/`update`/`delete` the
31
- * same before/afterOperation hooks as an equivalent top-level write, inside
32
- * the one transaction the Write Pipeline opens. `processNestedOperations`
33
- * transforms the payload and runs `beforeOperation`, returning deferred
34
- * {@link AfterTask}s that {@link runAfterTasks} runs once the parent has
35
- * persisted. See ADR-0010 for the full mechanism.
36
- */
37
-
38
- /**
39
- * Thrown when a non-sudo write's payload carries a nested `set`, `updateMany`
40
- * or `deleteMany` under a relationship key (#1384). These three kinds were
41
- * historically a pass-through straight to Prisma: the target list's
42
- * `operation.update`/`operation.delete` access was never consulted, no hooks
43
- * ran, and an unscoped `updateMany`/`deleteMany` `where` reached rows well
44
- * outside the parent's own subtree. ADR-0050 removes nested relation input
45
- * from the secured write surface entirely on the `prisma-8` line, so building
46
- * per-kind access machinery for these three kinds on `main` would be work
47
- * that major deletes wholesale — this refuses them instead, an interim
48
- * fail-closed fix mirroring ADR-0050's own refusal shape.
49
- *
50
- * The refusal fires before any part of the write executes, so a payload
51
- * mixing a refused kind with a permitted one persists nothing. `sudo()`
52
- * still accepts all three kinds unchanged — the same escape hatch every
53
- * other access-control refusal in this module leans on.
54
- *
55
- * Replacement: author the writes against the target list directly, via
56
- * `context.db.<targetList>`, wrapped in `context.transaction` when they must
57
- * land atomically with this write.
58
- */
59
- export class NestedRelationInputError extends Error {
60
- public listKey: string
61
- public fieldKey: string
62
- public kinds: readonly string[]
63
-
64
- constructor(listKey: string, fieldKey: string, kinds: readonly string[]) {
65
- const kindList = kinds.map((kind) => `"${kind}"`).join(', ')
66
- super(
67
- `Cannot write "${listKey}.${fieldKey}" — this payload carries a nested ${kindList} ` +
68
- `operation, which non-sudo contexts no longer accept (#1384): the target list's access ` +
69
- `rules were never consulted for these kinds. Author the writes against the target list ` +
70
- `directly (\`context.db.<targetList>\`), wrapped in \`context.transaction\` when they must ` +
71
- `land atomically with this write, or use \`context.sudo()\` if this write is trusted to ` +
72
- `bypass the target list's access entirely.`,
73
- )
74
- this.name = 'NestedRelationInputError'
75
- this.listKey = listKey
76
- this.fieldKey = fieldKey
77
- this.kinds = kinds
78
- }
79
- }
80
-
81
- /** Nested-op kinds refused outright for non-sudo contexts. See {@link NestedRelationInputError}. */
82
- const REFUSED_KINDS = ['set', 'updateMany', 'deleteMany'] as const
83
-
84
- /** A deferred nested `afterOperation` task, run once the parent has persisted. */
85
- export interface AfterTask {
86
- /** Field name on the parent linking to the related list (for include lookup). */
87
- fieldName: string
88
- run(parentResult: Record<string, unknown>): Promise<void>
89
- }
90
-
91
- /**
92
- * Result of processing nested operations: the transformed write payload plus
93
- * the deferred `afterOperation` tasks and the relation fields the parent write
94
- * must `include` so those tasks can recover their persisted `item`.
95
- */
96
- export interface NestedOpsResult {
97
- /** The transformed write payload handed to Prisma. */
98
- data: Record<string, unknown>
99
- /** Deferred `afterOperation` tasks to run after the parent persist. */
100
- afterTasks: AfterTask[]
101
- /** Relationship field names to `include` in the parent write result. */
102
- includeFields: Set<string>
103
- }
104
-
105
- function isRelationshipField(fieldConfig: FieldConfig | undefined): boolean {
106
- return fieldConfig?.type === 'relationship'
107
- }
108
-
109
- /** Resolve a list name by matching config object identity, not by name. */
110
- function findListName(
111
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
112
- relatedListConfig: ListConfig<any>,
113
- config: OpenSaasConfig,
114
- ): string {
115
- for (const [listKey, listCfg] of Object.entries(config.lists)) {
116
- if (listCfg === relatedListConfig) {
117
- return listKey
118
- }
119
- }
120
- return ''
121
- }
122
-
123
- /**
124
- * Read the rows of a parent's included relation as an array.
125
- *
126
- * A to-one relation comes back as a single row (or `null`); a to-many relation
127
- * comes back as an array. Normalises both so callers can apply a uniform id-diff.
128
- */
129
- function includedRows(
130
- parentResult: Record<string, unknown>,
131
- fieldName: string,
132
- ): Array<Record<string, unknown>> {
133
- const included = parentResult[fieldName]
134
- if (included == null) return []
135
- if (Array.isArray(included)) return included as Array<Record<string, unknown>>
136
- return [included as Record<string, unknown>]
137
- }
138
-
139
- /**
140
- * Recover an UPDATED nested row from the parent result by its known id.
141
- *
142
- * The updated row's id is known up front (it was fetched for access as
143
- * `originalItem`), so the persisted row is the included row with that id.
144
- */
145
- function recoverUpdatedRow(
146
- parentResult: Record<string, unknown>,
147
- fieldName: string,
148
- knownId: string | undefined,
149
- ): Record<string, unknown> | undefined {
150
- if (knownId === undefined) return undefined
151
- return includedRows(parentResult, fieldName).find((r) => r.id === knownId)
152
- }
153
-
154
- /**
155
- * Recover the CREATED nested rows from the parent result by id-diff: the
156
- * included rows whose ids are NOT in `preExistingIds`. Returned in include
157
- * order, which {@link CreatedRowRecovery} pairs to create-payload entries by
158
- * position — reordering this would break that pairing.
159
- */
160
- function recoverCreatedRows(
161
- parentResult: Record<string, unknown>,
162
- fieldName: string,
163
- preExistingIds: Set<string>,
164
- ): Array<Record<string, unknown>> {
165
- return includedRows(parentResult, fieldName).filter(
166
- (r) => typeof r.id === 'string' && !preExistingIds.has(r.id as string),
167
- )
168
- }
169
-
170
- /**
171
- * Shared, memoised recovery of the rows created for ONE nested `create` payload
172
- * on ONE relation field, by id-diff against the parent's pre-persist related
173
- * ids, paired to create-payload entries by position. See ADR-0010. The id-diff
174
- * is cached per parent result so every entry's task shares it.
175
- *
176
- * `inputData`↔row pairing is positional and best-effort; `item` correctness
177
- * (each task gets a genuinely-created, distinct row) is guaranteed — a
178
- * pre-existing row can never be returned because the diff excludes it.
179
- */
180
- interface CreatedRowRecovery {
181
- /** Recover the created row for the create-payload entry at `index`. */
182
- rowAt(parentResult: Record<string, unknown>, index: number): Record<string, unknown> | undefined
183
- }
184
-
185
- function createCreatedRowRecovery(
186
- fieldName: string,
187
- preExistingIds: Set<string>,
188
- ): CreatedRowRecovery {
189
- let cache: { source: Record<string, unknown>; rows: Array<Record<string, unknown>> } | undefined
190
- return {
191
- rowAt(parentResult, index) {
192
- if (!cache || cache.source !== parentResult) {
193
- cache = {
194
- source: parentResult,
195
- rows: recoverCreatedRows(parentResult, fieldName, preExistingIds),
196
- }
197
- }
198
- return cache.rows[index]
199
- },
200
- }
201
- }
202
-
203
- /**
204
- * Capture the ids of the rows currently linked to the parent via `fieldName`,
205
- * BEFORE the parent persists, so created rows can later be identified by id-diff.
206
- * Empty for a parent CREATE (no parent row exists yet to have related rows).
207
- *
208
- * `prisma` must be the transaction client — the read has to participate in the
209
- * transaction to see a consistent snapshot.
210
- */
211
- async function capturePreExistingIds(
212
- parentListName: string,
213
- parentOriginalItem: Record<string, unknown> | undefined,
214
- fieldName: string,
215
- prisma: unknown,
216
- ): Promise<Set<string>> {
217
- const ids = new Set<string>()
218
- const parentId = parentOriginalItem?.id
219
- if (typeof parentId !== 'string') {
220
- // Parent create (no existing row) — nothing pre-exists.
221
- return ids
222
- }
223
-
224
- // Access Prisma model dynamically - required because model names are generated at runtime
225
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
226
- const parentModel = (prisma as any)[getDbKey(parentListName)]
227
- if (!parentModel?.findUnique) return ids
228
-
229
- const current = await parentModel.findUnique({
230
- where: { id: parentId },
231
- include: { [fieldName]: true },
232
- })
233
- for (const row of includedRows((current ?? {}) as Record<string, unknown>, fieldName)) {
234
- if (typeof row.id === 'string') ids.add(row.id)
235
- }
236
- return ids
237
- }
238
-
239
- /**
240
- * Process nested create operations: run the target list's full input pipeline
241
- * and `beforeOperation`, then register an `afterOperation` task keyed to the
242
- * parent's included relation.
243
- */
244
- async function processNestedCreate(
245
- items: Record<string, unknown> | Array<Record<string, unknown>>,
246
- fieldName: string,
247
- relatedListName: string,
248
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
249
- relatedListConfig: ListConfig<any>,
250
- context: StackContext,
251
- config: OpenSaasConfig,
252
- prisma: unknown,
253
- afterTasks: AfterTask[],
254
- recovery: CreatedRowRecovery,
255
- ): Promise<Record<string, unknown> | Array<Record<string, unknown>>> {
256
- const itemsArray = Array.isArray(items) ? items : [items]
257
-
258
- const processedItems = await Promise.all(
259
- itemsArray.map(async (item, index) => {
260
- if (!context._isSudo) {
261
- const createAccess = relatedListConfig.access?.operation?.create
262
- const allowed = await checkCreateAccess(relatedListName, createAccess, {
263
- session: context.session,
264
- context,
265
- })
266
-
267
- if (!allowed) {
268
- throw new Error('Access denied: Cannot create related item')
269
- }
270
- }
271
-
272
- let resolvedData = await executeResolveInput(relatedListConfig.hooks, {
273
- listKey: relatedListName,
274
- operation: 'create',
275
- inputData: item,
276
- resolvedData: item,
277
- item: undefined,
278
- context,
279
- })
280
-
281
- resolvedData = await executeFieldResolveInputHooks(
282
- item,
283
- resolvedData,
284
- relatedListConfig.fields,
285
- 'create',
286
- context,
287
- relatedListName,
288
- )
289
-
290
- // Apply field defaults to omitted inputs (resolve-then-validate, #615) so
291
- // a nested required-with-default field resolves before `isRequired` runs,
292
- // mirroring the top-level pipeline. Create-only.
293
- resolvedData = applyCreateDefaults(resolvedData, relatedListConfig.fields)
294
-
295
- await executeValidate(relatedListConfig.hooks, {
296
- listKey: relatedListName,
297
- operation: 'create',
298
- inputData: item,
299
- resolvedData,
300
- item: undefined,
301
- context,
302
- })
303
-
304
- await executeFieldValidateHooks(
305
- item,
306
- resolvedData,
307
- relatedListConfig.fields,
308
- 'create',
309
- context,
310
- relatedListName,
311
- )
312
-
313
- const validation = validateFieldRules(resolvedData, relatedListConfig.fields, 'create')
314
- if (validation.errors.length > 0) {
315
- throw new ValidationError(validation.errors, validation.fieldErrors)
316
- }
317
-
318
- // Split multi-column fields into physical columns (#789) — must run after
319
- // validation, which operates on the logical (pre-split) value.
320
- resolvedData = await splitMultiColumnFields(
321
- item,
322
- resolvedData,
323
- relatedListConfig.fields,
324
- 'create',
325
- context,
326
- )
327
-
328
- const filtered = await filterWritableFields(
329
- resolvedData,
330
- relatedListConfig.fields,
331
- 'create',
332
- {
333
- session: context.session,
334
- context,
335
- inputData: item,
336
- listName: relatedListName,
337
- config,
338
- },
339
- )
340
-
341
- // This nested row is itself being created, so it has no pre-existing
342
- // related rows of its own (parent originalItem is undefined below).
343
- const { data: nestedData, afterTasks: childAfterTasks } = await processNestedOperations(
344
- filtered,
345
- relatedListConfig.fields,
346
- config,
347
- { ...context, prisma },
348
- 'create',
349
- relatedListName,
350
- undefined,
351
- // Its own create payload is the enclosing inputData for the connect-site
352
- // owning-field gate (#588).
353
- item,
354
- )
355
-
356
- await executeFieldBeforeOperationHooks(
357
- item,
358
- resolvedData,
359
- relatedListConfig.fields,
360
- 'create',
361
- context,
362
- relatedListName,
363
- )
364
-
365
- await executeBeforeOperation(relatedListConfig.hooks, {
366
- listKey: relatedListName,
367
- operation: 'create',
368
- inputData: item,
369
- resolvedData,
370
- context,
371
- })
372
-
373
- // Fires once the parent has persisted. The row is recovered by id-diff and
374
- // paired to THIS entry by position (see CreatedRowRecovery), so a to-many
375
- // `create: [{A},{B}]` fires once per row against its own distinct row.
376
- afterTasks.push({
377
- fieldName,
378
- run: async (parentResult) => {
379
- const createdItem = recovery.rowAt(parentResult, index)
380
- if (!createdItem) {
381
- // Could not identify the created row by id-diff — the parent write
382
- // didn't echo this nested relation (e.g. a client/mock that doesn't
383
- // honour `include`; real Prisma always does). Deliberately SKIP this
384
- // record's `afterOperation` rather than fabricate an id-less item —
385
- // `item` correctness is the must-have, so a missing row is never faked.
386
- return
387
- }
388
-
389
- await executeAfterOperation(relatedListConfig.hooks, {
390
- listKey: relatedListName,
391
- operation: 'create',
392
- inputData: item,
393
- item: createdItem,
394
- resolvedData,
395
- context,
396
- })
397
-
398
- await executeFieldAfterOperationHooks(
399
- createdItem,
400
- item,
401
- resolvedData,
402
- relatedListConfig.fields,
403
- 'create',
404
- context,
405
- relatedListName,
406
- )
407
-
408
- await runAfterTasks(childAfterTasks, createdItem)
409
- },
410
- })
411
-
412
- return nestedData
413
- }),
414
- )
415
-
416
- return Array.isArray(items) ? processedItems : processedItems[0]
417
- }
418
-
419
- /**
420
- * Verify that a single connection (or, for `disconnect`, disconnection)
421
- * target is reachable for the caller.
422
- *
423
- * Both directions reference an existing row rather than modifying it, so —
424
- * mirroring Keystone — they require **read/query** access on the target
425
- * (#578/#1384), not update. A filter-result query access is evaluated in the
426
- * DATABASE via `findFirst({ where: { AND: [connection, accessFilter] } })`
427
- * rather than in memory, so it correctly handles arbitrary nested-relation
428
- * predicates and boolean combinators; a non-existent id is folded into the
429
- * same check.
430
- *
431
- * For `connect` (the default, `action: 'connect'`), the OWNING relationship
432
- * field's field-level access (e.g. `Post.author`'s `create`/`update` access)
433
- * must ADDITIONALLY permit the connect (#588) — the other half Keystone
434
- * requires: read access on the target AND write access on the owning field. A
435
- * deny here denies the connect even when the target row is readable/reachable.
436
- *
437
- * For `disconnect` (`action: 'disconnect'`), the caller passes
438
- * `owningFieldAccess: undefined`, which makes this second gate a no-op
439
- * (`checkFieldAccess` defaults an absent rule to allow) — deliberately: the
440
- * owning field's write access is already enforced by Phase 5's
441
- * `filterWritableFields` before nested-op processing ever sees this payload,
442
- * so re-running it here would only duplicate that gate, not add one. See
443
- * {@link processNestedDisconnect}.
444
- *
445
- * Sudo bypasses the entire check (handled by the caller).
446
- */
447
- async function verifyConnectReachable(
448
- connection: Record<string, unknown>,
449
- relatedListName: string,
450
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
451
- relatedListConfig: ListConfig<any>,
452
- context: StackContext,
453
- prisma: unknown,
454
- owningFieldAccess: FieldAccess | undefined,
455
- enclosingOperation: 'create' | 'update',
456
- enclosingItem: Record<string, unknown> | undefined,
457
- enclosingInputData: Record<string, unknown> | undefined,
458
- action: 'connect' | 'disconnect' = 'connect',
459
- ): Promise<void> {
460
- // Access Prisma model dynamically - required because model names are generated at runtime
461
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
462
- const model = (prisma as any)[getDbKey(relatedListName)]
463
- const deniedMessage =
464
- action === 'connect'
465
- ? 'Access denied: Cannot connect to this item'
466
- : 'Access denied: Cannot disconnect from this item'
467
-
468
- // #588 owning-field gate (see docblock above). `item`/`inputData` are the
469
- // ENCLOSING write's `originalItem`/`inputData` — the same values the canonical
470
- // Phase-5 `filterWritableFields` call passes for this field — so an
471
- // item-/inputData-dependent field-access rule can't diverge between the two gates.
472
- const owningFieldAllowed = await checkFieldAccess(owningFieldAccess, enclosingOperation, {
473
- session: context.session,
474
- item: enclosingItem,
475
- inputData: enclosingInputData,
476
- context,
477
- })
478
- if (!owningFieldAllowed) {
479
- throw new Error(deniedMessage)
480
- }
481
-
482
- const queryAccess = relatedListConfig.access?.operation?.query
483
- const accessResult = await checkAccess(queryAccess, {
484
- session: context.session,
485
- context,
486
- })
487
-
488
- if (accessResult === false) {
489
- throw new Error(deniedMessage)
490
- }
491
-
492
- // Full access still verifies the row exists, to keep "Item not found" behaviour.
493
- if (accessResult === true) {
494
- const item = await model.findUnique({ where: connection })
495
- if (!item) {
496
- throw new Error(`Cannot ${action}: Item not found`)
497
- }
498
- return
499
- }
500
-
501
- // Filter result: reachable iff AND-combining the connection with the filter
502
- // returns a row (see docblock above).
503
- const reachable = await model.findFirst({
504
- where: { AND: [connection, accessResult] },
505
- })
506
-
507
- if (!reachable) {
508
- throw new Error(deniedMessage)
509
- }
510
- }
511
-
512
- /**
513
- * Process nested connect operations.
514
- * Verifies read (query) access to the items being connected via DB reachability
515
- * AND the owning relationship field's field-level access (#588).
516
- */
517
- async function processNestedConnect(
518
- connections: Record<string, unknown> | Array<Record<string, unknown>>,
519
- relatedListName: string,
520
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
521
- relatedListConfig: ListConfig<any>,
522
- context: StackContext,
523
- prisma: unknown,
524
- owningFieldAccess: FieldAccess | undefined,
525
- enclosingOperation: 'create' | 'update',
526
- enclosingItem: Record<string, unknown> | undefined,
527
- enclosingInputData: Record<string, unknown> | undefined,
528
- ): Promise<Record<string, unknown> | Array<Record<string, unknown>>> {
529
- const connectionsArray = Array.isArray(connections) ? connections : [connections]
530
-
531
- if (!context._isSudo) {
532
- for (const connection of connectionsArray) {
533
- await verifyConnectReachable(
534
- connection,
535
- relatedListName,
536
- relatedListConfig,
537
- context,
538
- prisma,
539
- owningFieldAccess,
540
- enclosingOperation,
541
- enclosingItem,
542
- enclosingInputData,
543
- )
544
- }
545
- }
546
-
547
- return connections
548
- }
549
-
550
- /**
551
- * Process a nested `disconnect` (#1384).
552
- *
553
- * `{ disconnect: true }` — the to-one boolean form — nulls the foreign key on
554
- * the row already being updated; that row's own update access has already
555
- * been checked (by the enclosing write), so it is left permitted, unchanged,
556
- * with no target-list check. This is the form the admin UI's `removeRelated`
557
- * action emits for a to-one back-reference (ADR-0018).
558
- *
559
- * `{ disconnect: { <criteria> } }` — or an array of criteria, for a to-many —
560
- * names a target row on the OTHER list. This requires that target's
561
- * `operation.query` access, Keystone's semantic, reusing `verifyConnectReachable`
562
- * (see its docblock for why the owning-field gate is skipped here) rather than
563
- * a second reachability check.
564
- */
565
- async function processNestedDisconnect(
566
- value: unknown,
567
- relatedListName: string,
568
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
569
- relatedListConfig: ListConfig<any>,
570
- context: StackContext,
571
- prisma: unknown,
572
- enclosingOperation: 'create' | 'update',
573
- ): Promise<unknown> {
574
- if (value === true || context._isSudo) {
575
- return value
576
- }
577
-
578
- const criteriaArray = Array.isArray(value)
579
- ? (value as Array<Record<string, unknown>>)
580
- : [value as Record<string, unknown>]
581
-
582
- for (const criteria of criteriaArray) {
583
- await verifyConnectReachable(
584
- criteria,
585
- relatedListName,
586
- relatedListConfig,
587
- context,
588
- prisma,
589
- undefined,
590
- enclosingOperation,
591
- undefined,
592
- undefined,
593
- 'disconnect',
594
- )
595
- }
596
-
597
- return value
598
- }
599
-
600
- /**
601
- * Re-check a nested update/delete access result against the target row,
602
- * mirroring the Write Pipeline's `resolveExistingTarget` (#1081): `false`
603
- * denies, `true` allows outright (the row's existence is already established
604
- * by the caller's own `findUnique`), and a returned PrismaFilter must
605
- * additionally match the row, re-checked in the DATABASE via
606
- * `findFirst(mergeFilters(where, accessResult))` rather than in memory — the
607
- * same requirement `connect`'s reachability check already applies (#578), so
608
- * nested-relation predicates and boolean combinators are honoured correctly.
609
- */
610
- async function isExistingTargetAccessible(
611
- model: { findFirst: (args: { where: Record<string, unknown> }) => Promise<unknown> },
612
- where: Record<string, unknown>,
613
- accessResult: boolean | PrismaFilter,
614
- ): Promise<boolean> {
615
- if (accessResult === false) return false
616
- if (accessResult === true) return true
617
-
618
- const matchesFilter = await model.findFirst({ where: mergeFilters(where, accessResult) ?? {} })
619
- return matchesFilter !== null
620
- }
621
-
622
- /**
623
- * Process nested update operations.
624
- *
625
- * Runs the target list's full update input pipeline AND its `beforeOperation`,
626
- * then registers an `afterOperation` task receiving `originalItem` (the row
627
- * fetched before the write) and the persisted updated `item`.
628
- */
629
- async function processNestedUpdate(
630
- updates: Record<string, unknown> | Array<Record<string, unknown>>,
631
- fieldName: string,
632
- relatedListName: string,
633
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
634
- relatedListConfig: ListConfig<any>,
635
- context: StackContext,
636
- config: OpenSaasConfig,
637
- prisma: unknown,
638
- afterTasks: AfterTask[],
639
- ): Promise<Record<string, unknown> | Array<Record<string, unknown>>> {
640
- const updatesArray = Array.isArray(updates) ? updates : [updates]
641
-
642
- const processedUpdates = await Promise.all(
643
- updatesArray.map(async (update) => {
644
- // Access Prisma model dynamically - required because model names are generated at runtime
645
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
646
- const model = (prisma as any)[getDbKey(relatedListName)]
647
-
648
- const where = (update as Record<string, unknown>).where as Record<string, unknown>
649
-
650
- // Fetched here and reused as `originalItem` for afterOperation.
651
- const originalItem = await model.findUnique({ where })
652
-
653
- if (!originalItem) {
654
- throw new Error('Cannot update: Item not found')
655
- }
656
-
657
- const knownId = typeof originalItem.id === 'string' ? (originalItem.id as string) : undefined
658
-
659
- if (!context._isSudo) {
660
- const updateAccess = relatedListConfig.access?.operation?.update
661
- const accessResult = await checkAccess(updateAccess, {
662
- session: context.session,
663
- item: originalItem,
664
- context,
665
- })
666
-
667
- if (!(await isExistingTargetAccessible(model, where, accessResult))) {
668
- throw new Error('Access denied: Cannot update related item')
669
- }
670
- }
671
-
672
- const updateData = (update as Record<string, unknown>).data as Record<string, unknown>
673
- let resolvedData = await executeResolveInput(relatedListConfig.hooks, {
674
- listKey: relatedListName,
675
- operation: 'update',
676
- inputData: updateData,
677
- resolvedData: updateData,
678
- item: originalItem,
679
- context,
680
- })
681
-
682
- resolvedData = await executeFieldResolveInputHooks(
683
- updateData,
684
- resolvedData,
685
- relatedListConfig.fields,
686
- 'update',
687
- context,
688
- relatedListName,
689
- originalItem,
690
- )
691
-
692
- await executeValidate(relatedListConfig.hooks, {
693
- listKey: relatedListName,
694
- operation: 'update',
695
- inputData: updateData,
696
- resolvedData,
697
- item: originalItem,
698
- context,
699
- })
700
-
701
- await executeFieldValidateHooks(
702
- updateData,
703
- resolvedData,
704
- relatedListConfig.fields,
705
- 'update',
706
- context,
707
- relatedListName,
708
- originalItem,
709
- )
710
-
711
- const validation = validateFieldRules(resolvedData, relatedListConfig.fields, 'update')
712
- if (validation.errors.length > 0) {
713
- throw new ValidationError(validation.errors, validation.fieldErrors)
714
- }
715
-
716
- // Split multi-column fields into physical columns (#789) — must run after
717
- // validation, which operates on the logical (pre-split) value.
718
- resolvedData = await splitMultiColumnFields(
719
- updateData,
720
- resolvedData,
721
- relatedListConfig.fields,
722
- 'update',
723
- context,
724
- originalItem,
725
- )
726
-
727
- const filtered = await filterWritableFields(
728
- resolvedData,
729
- relatedListConfig.fields,
730
- 'update',
731
- {
732
- session: context.session,
733
- item: originalItem,
734
- context,
735
- inputData: updateData,
736
- listName: relatedListName,
737
- config,
738
- },
739
- )
740
-
741
- // This nested row is being updated, so its own relations' pre-existing
742
- // rows are captured from `originalItem` below.
743
- const { data: nestedData, afterTasks: childAfterTasks } = await processNestedOperations(
744
- filtered,
745
- relatedListConfig.fields,
746
- config,
747
- { ...context, prisma },
748
- 'update',
749
- relatedListName,
750
- originalItem,
751
- // Its own update payload is the enclosing inputData for the connect-site
752
- // owning-field gate (#588).
753
- updateData,
754
- )
755
-
756
- await executeFieldBeforeOperationHooks(
757
- updateData,
758
- resolvedData,
759
- relatedListConfig.fields,
760
- 'update',
761
- context,
762
- relatedListName,
763
- originalItem,
764
- )
765
-
766
- await executeBeforeOperation(relatedListConfig.hooks, {
767
- listKey: relatedListName,
768
- operation: 'update',
769
- inputData: updateData,
770
- item: originalItem,
771
- resolvedData,
772
- context,
773
- })
774
-
775
- // Fires after the parent persist; the row is recovered by its known id.
776
- afterTasks.push({
777
- fieldName,
778
- run: async (parentResult) => {
779
- const persisted = recoverUpdatedRow(parentResult, fieldName, knownId)
780
- const updatedItem = persisted ?? originalItem
781
-
782
- await executeAfterOperation(relatedListConfig.hooks, {
783
- listKey: relatedListName,
784
- operation: 'update',
785
- inputData: updateData,
786
- originalItem,
787
- item: updatedItem,
788
- resolvedData,
789
- context,
790
- })
791
-
792
- await executeFieldAfterOperationHooks(
793
- updatedItem,
794
- updateData,
795
- resolvedData,
796
- relatedListConfig.fields,
797
- 'update',
798
- context,
799
- relatedListName,
800
- originalItem,
801
- )
802
-
803
- await runAfterTasks(childAfterTasks, updatedItem)
804
- },
805
- })
806
-
807
- return {
808
- where,
809
- data: nestedData,
810
- }
811
- }),
812
- )
813
-
814
- return Array.isArray(updates) ? processedUpdates : processedUpdates[0]
815
- }
816
-
817
- /**
818
- * Process nested delete operations.
819
- *
820
- * Runs the target list's delete pipeline (validate/field-validate +
821
- * `beforeOperation`) before the parent persist, and registers an
822
- * `afterOperation` task receiving the `originalItem` (the row before deletion).
823
- * Persistence is performed by Prisma's nested write; the row no longer exists
824
- * after, so `originalItem` is the authoritative record for after-hooks.
825
- */
826
- async function processNestedDelete(
827
- deletes: Record<string, unknown> | Array<Record<string, unknown>> | boolean,
828
- relatedListName: string,
829
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
830
- relatedListConfig: ListConfig<any>,
831
- context: StackContext,
832
- prisma: unknown,
833
- afterTasks: AfterTask[],
834
- ): Promise<Record<string, unknown> | Array<Record<string, unknown>> | boolean> {
835
- // A to-one relation delete can be a boolean (`{ delete: true }`); there is no
836
- // identifying `where`, so we cannot run target-resolved hooks. Pass through.
837
- if (typeof deletes === 'boolean') {
838
- return deletes
839
- }
840
-
841
- const deletesArray = Array.isArray(deletes) ? deletes : [deletes]
842
-
843
- await Promise.all(
844
- deletesArray.map(async (del) => {
845
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
846
- const model = (prisma as any)[getDbKey(relatedListName)]
847
-
848
- // A nested delete entry is itself the unique `where` (e.g. `{ id }`).
849
- const where = del as Record<string, unknown>
850
-
851
- const originalItem = await model.findUnique({ where })
852
- if (!originalItem) {
853
- throw new Error('Cannot delete: Item not found')
854
- }
855
-
856
- if (!context._isSudo) {
857
- const deleteAccess = relatedListConfig.access?.operation?.delete
858
- const accessResult = await checkAccess(deleteAccess, {
859
- session: context.session,
860
- item: originalItem,
861
- context,
862
- })
863
-
864
- if (!(await isExistingTargetAccessible(model, where, accessResult))) {
865
- throw new Error('Access denied: Cannot delete related item')
866
- }
867
- }
868
-
869
- await executeValidate(relatedListConfig.hooks, {
870
- listKey: relatedListName,
871
- operation: 'delete',
872
- item: originalItem,
873
- context,
874
- })
875
-
876
- await executeFieldValidateHooks(
877
- undefined,
878
- undefined,
879
- relatedListConfig.fields,
880
- 'delete',
881
- context,
882
- relatedListName,
883
- originalItem,
884
- )
885
-
886
- await executeFieldBeforeOperationHooks(
887
- {},
888
- {},
889
- relatedListConfig.fields,
890
- 'delete',
891
- context,
892
- relatedListName,
893
- originalItem,
894
- )
895
-
896
- await executeBeforeOperation(relatedListConfig.hooks, {
897
- listKey: relatedListName,
898
- operation: 'delete',
899
- item: originalItem,
900
- context,
901
- })
902
-
903
- // The row is gone after persist, so originalItem is the authoritative
904
- // record passed to the after-hooks below.
905
- afterTasks.push({
906
- fieldName: '',
907
- run: async () => {
908
- await executeAfterOperation(relatedListConfig.hooks, {
909
- listKey: relatedListName,
910
- operation: 'delete',
911
- originalItem,
912
- context,
913
- })
914
-
915
- await executeFieldAfterOperationHooks(
916
- originalItem,
917
- undefined,
918
- undefined,
919
- relatedListConfig.fields,
920
- 'delete',
921
- context,
922
- relatedListName,
923
- originalItem,
924
- )
925
- },
926
- })
927
- }),
928
- )
929
-
930
- return deletes
931
- }
932
-
933
- async function processNestedConnectOrCreate(
934
- operations: Record<string, unknown> | Array<Record<string, unknown>>,
935
- fieldName: string,
936
- relatedListName: string,
937
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
938
- relatedListConfig: ListConfig<any>,
939
- context: StackContext,
940
- config: OpenSaasConfig,
941
- prisma: unknown,
942
- afterTasks: AfterTask[],
943
- recovery: CreatedRowRecovery,
944
- owningFieldAccess: FieldAccess | undefined,
945
- enclosingOperation: 'create' | 'update',
946
- enclosingItem: Record<string, unknown> | undefined,
947
- enclosingInputData: Record<string, unknown> | undefined,
948
- ): Promise<Record<string, unknown> | Array<Record<string, unknown>>> {
949
- const operationsArray = Array.isArray(operations) ? operations : [operations]
950
-
951
- const processedOps = await Promise.all(
952
- operationsArray.map(async (op) => {
953
- const opRecord = op as Record<string, unknown>
954
-
955
- // When the target row exists, connectOrCreate applies the same connect
956
- // semantics as processNestedConnect (read access + #588 owning-field gate,
957
- // both evaluated via DB reachability); otherwise it falls through to
958
- // create. An access-denied error must NOT be swallowed into that fallback
959
- // — only a genuine "row absent" may fall back to create.
960
- let rowExists = false
961
- if (!context._isSudo) {
962
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
963
- const model = (prisma as any)[getDbKey(relatedListName)]
964
- const where = opRecord.where as Record<string, unknown>
965
-
966
- const existingItem = await model.findUnique({ where })
967
-
968
- if (existingItem) {
969
- rowExists = true
970
-
971
- const owningFieldAllowed = await checkFieldAccess(owningFieldAccess, enclosingOperation, {
972
- session: context.session,
973
- item: enclosingItem,
974
- inputData: enclosingInputData,
975
- context,
976
- })
977
- if (!owningFieldAllowed) {
978
- throw new Error('Access denied: Cannot connect to existing item')
979
- }
980
-
981
- const queryAccess = relatedListConfig.access?.operation?.query
982
- const accessResult = await checkAccess(queryAccess, {
983
- session: context.session,
984
- item: existingItem,
985
- context,
986
- })
987
-
988
- if (accessResult === false) {
989
- throw new Error('Access denied: Cannot connect to existing item')
990
- }
991
-
992
- if (accessResult !== true) {
993
- const reachable = await model.findFirst({
994
- where: { AND: [where, accessResult] },
995
- })
996
-
997
- if (!reachable) {
998
- throw new Error('Access denied: Cannot connect to existing item')
999
- }
1000
- }
1001
- }
1002
- }
1003
-
1004
- // Only register an afterOperation task when the create branch will
1005
- // actually run (row absent), so a pure connect doesn't fire create hooks.
1006
- // Under sudo we can't tell statically, so the create pipeline always runs
1007
- // its hooks there (sudo bypasses access only, not hooks).
1008
- const runCreateHooks = context._isSudo || !rowExists
1009
- const createAfterTasks: AfterTask[] = runCreateHooks ? afterTasks : []
1010
- const processedCreate = await processNestedCreate(
1011
- opRecord.create as Record<string, unknown> | Array<Record<string, unknown>>,
1012
- fieldName,
1013
- relatedListName,
1014
- relatedListConfig,
1015
- context,
1016
- config,
1017
- prisma,
1018
- createAfterTasks,
1019
- recovery,
1020
- )
1021
-
1022
- return {
1023
- where: opRecord.where,
1024
- create: processedCreate,
1025
- }
1026
- }),
1027
- )
1028
-
1029
- return Array.isArray(operations) ? processedOps : processedOps[0]
1030
- }
1031
-
1032
- /**
1033
- * Arguments passed to every nested-operation handler.
1034
- */
1035
- interface NestedOpHandlerArgs {
1036
- /** Raw payload supplied for this nested-op kind (e.g. the value of `value.create`). */
1037
- value: unknown
1038
- /** The owning relationship field name on the parent (for include read-back). */
1039
- fieldName: string
1040
- /** The list name of the related model (e.g. `'User'`). */
1041
- relatedListName: string
1042
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1043
- relatedListConfig: ListConfig<any>
1044
- /**
1045
- * Field-level `access` of the OWNING relationship field (e.g. `Post.author`).
1046
- * Gates connect/connectOrCreate by the owning field's create/update access —
1047
- * see the #588 gate in {@link verifyConnectReachable}.
1048
- */
1049
- owningFieldAccess: FieldAccess | undefined
1050
- /** The enclosing write's operation, used as the owning-field gate's field-access operation. */
1051
- enclosingOperation: 'create' | 'update'
1052
- /**
1053
- * The enclosing write's `originalItem` (`undefined` for an enclosing create).
1054
- * Passed to the owning-field gate so it matches the canonical Phase-5
1055
- * `filterWritableFields` call and the two can't diverge (#588).
1056
- */
1057
- enclosingItem: Record<string, unknown> | undefined
1058
- /** The enclosing write's input data, passed to the owning-field gate for the same reason as `enclosingItem`. */
1059
- enclosingInputData: Record<string, unknown> | undefined
1060
- context: StackContext
1061
- config: OpenSaasConfig
1062
- /** Prisma client used for dynamic model access during access checks. */
1063
- prisma: unknown
1064
- /** Collector for deferred nested `afterOperation` tasks. */
1065
- afterTasks: AfterTask[]
1066
- /**
1067
- * Recovery of the rows created on THIS field by id-diff (created kinds only —
1068
- * `create` and `connectOrCreate`'s create branch). Identifies each created row
1069
- * by excluding the ids that existed before the persist, and pairs them to the
1070
- * create-payload entries by position. Created lazily because it requires a
1071
- * pre-persist DB read; `undefined` for kinds that never create.
1072
- */
1073
- recovery: CreatedRowRecovery | undefined
1074
- }
1075
-
1076
- /**
1077
- * Narrow the lazily-built {@link CreatedRowRecovery} to a present value for the
1078
- * created kinds (`create`, `connectOrCreate`). It is always provided for these
1079
- * kinds by {@link processFieldNestedOps}; the guard backstops a programming
1080
- * error rather than a user-facing path.
1081
- */
1082
- function requireRecovery(
1083
- recovery: CreatedRowRecovery | undefined,
1084
- kind: string,
1085
- ): CreatedRowRecovery {
1086
- if (!recovery) {
1087
- throw new Error(`Internal error: missing created-row recovery for nested "${kind}"`)
1088
- }
1089
- return recovery
1090
- }
1091
-
1092
- /** Nested-op kinds that can create new rows and so need created-row recovery. */
1093
- const CREATING_KINDS = new Set(['create', 'connectOrCreate'])
1094
-
1095
- /**
1096
- * A nested-operation handler describes how a single nested-op kind
1097
- * (`create`, `connect`, …) is processed before it reaches Prisma.
1098
- */
1099
- interface NestedOpHandler {
1100
- /** Produce the processed payload for this nested-op kind. */
1101
- execute(args: NestedOpHandlerArgs): Promise<unknown>
1102
- /**
1103
- * Whether this kind needs the parent write to `include` the relation so its
1104
- * persisted row can be read back for `afterOperation` (`create`/`update`).
1105
- */
1106
- needsInclude: boolean
1107
- }
1108
-
1109
- /**
1110
- * Registry of nested-operation handlers keyed by nested-op kind.
1111
- *
1112
- * Kinds that run the full hook pipeline (`create`, `update`, `delete`, and the
1113
- * create branch of `connectOrCreate`) run `beforeOperation` inline and register
1114
- * deferred `afterOperation` tasks. `connect`/`connectOrCreate`'s connect branch,
1115
- * and `disconnect`'s target-row form, enforce access only — no hooks (#1384;
1116
- * this settles the `disconnect` half of #569's original scope note, which is
1117
- * now closed).
1118
- *
1119
- * `set`, `updateMany` and `deleteMany` are refused outright for non-sudo
1120
- * contexts before dispatch even reaches this registry (see `REFUSED_KINDS` /
1121
- * {@link NestedRelationInputError} near the top of this file) rather than
1122
- * given their own access machinery — ADR-0050 removes nested relation input
1123
- * from the secured write surface entirely on the `prisma-8` line, so that
1124
- * machinery would be built into a module the next major deletes wholesale.
1125
- * Their entries below therefore only ever run under `sudo()`, where they
1126
- * remain an unchecked, hook-free pass-through to Prisma, unchanged.
1127
- */
1128
- const nestedOpRegistry: Record<string, NestedOpHandler> = {
1129
- create: {
1130
- needsInclude: true,
1131
- execute: ({
1132
- value,
1133
- fieldName,
1134
- relatedListName,
1135
- relatedListConfig,
1136
- context,
1137
- config,
1138
- prisma,
1139
- afterTasks,
1140
- recovery,
1141
- }) =>
1142
- processNestedCreate(
1143
- value as Record<string, unknown> | Array<Record<string, unknown>>,
1144
- fieldName,
1145
- relatedListName,
1146
- relatedListConfig,
1147
- context,
1148
- config,
1149
- prisma,
1150
- afterTasks,
1151
- requireRecovery(recovery, 'create'),
1152
- ),
1153
- },
1154
- connect: {
1155
- needsInclude: false,
1156
- execute: ({
1157
- value,
1158
- relatedListName,
1159
- relatedListConfig,
1160
- context,
1161
- prisma,
1162
- owningFieldAccess,
1163
- enclosingOperation,
1164
- enclosingItem,
1165
- enclosingInputData,
1166
- }) =>
1167
- processNestedConnect(
1168
- value as Record<string, unknown> | Array<Record<string, unknown>>,
1169
- relatedListName,
1170
- relatedListConfig,
1171
- context,
1172
- prisma,
1173
- owningFieldAccess,
1174
- enclosingOperation,
1175
- enclosingItem,
1176
- enclosingInputData,
1177
- ),
1178
- },
1179
- connectOrCreate: {
1180
- needsInclude: true,
1181
- execute: ({
1182
- value,
1183
- fieldName,
1184
- relatedListName,
1185
- relatedListConfig,
1186
- context,
1187
- config,
1188
- prisma,
1189
- afterTasks,
1190
- recovery,
1191
- owningFieldAccess,
1192
- enclosingOperation,
1193
- enclosingItem,
1194
- enclosingInputData,
1195
- }) =>
1196
- processNestedConnectOrCreate(
1197
- value as Record<string, unknown> | Array<Record<string, unknown>>,
1198
- fieldName,
1199
- relatedListName,
1200
- relatedListConfig,
1201
- context,
1202
- config,
1203
- prisma,
1204
- afterTasks,
1205
- requireRecovery(recovery, 'connectOrCreate'),
1206
- owningFieldAccess,
1207
- enclosingOperation,
1208
- enclosingItem,
1209
- enclosingInputData,
1210
- ),
1211
- },
1212
- update: {
1213
- needsInclude: true,
1214
- execute: ({
1215
- value,
1216
- fieldName,
1217
- relatedListName,
1218
- relatedListConfig,
1219
- context,
1220
- config,
1221
- prisma,
1222
- afterTasks,
1223
- }) =>
1224
- processNestedUpdate(
1225
- value as Record<string, unknown> | Array<Record<string, unknown>>,
1226
- fieldName,
1227
- relatedListName,
1228
- relatedListConfig,
1229
- context,
1230
- config,
1231
- prisma,
1232
- afterTasks,
1233
- ),
1234
- },
1235
- delete: {
1236
- // The row no longer exists after the parent write, so no read-back include.
1237
- needsInclude: false,
1238
- execute: ({ value, relatedListName, relatedListConfig, context, prisma, afterTasks }) =>
1239
- processNestedDelete(
1240
- value as Record<string, unknown> | Array<Record<string, unknown>> | boolean,
1241
- relatedListName,
1242
- relatedListConfig,
1243
- context,
1244
- prisma,
1245
- afterTasks,
1246
- ),
1247
- },
1248
- // Gated pass-through: no hooks, but the target-row form requires the target
1249
- // list's operation.query access (#1384). See processNestedDisconnect.
1250
- disconnect: {
1251
- needsInclude: false,
1252
- execute: ({ value, relatedListName, relatedListConfig, context, prisma, enclosingOperation }) =>
1253
- processNestedDisconnect(
1254
- value,
1255
- relatedListName,
1256
- relatedListConfig,
1257
- context,
1258
- prisma,
1259
- enclosingOperation,
1260
- ),
1261
- },
1262
- // Refused for non-sudo before dispatch reaches here (see REFUSED_KINDS) —
1263
- // these entries only ever run under sudo, as an unchecked pass-through.
1264
- deleteMany: { needsInclude: false, execute: ({ value }) => Promise.resolve(value) },
1265
- set: { needsInclude: false, execute: ({ value }) => Promise.resolve(value) },
1266
- updateMany: { needsInclude: false, execute: ({ value }) => Promise.resolve(value) },
1267
- }
1268
-
1269
- /**
1270
- * Order in which nested-op kinds are processed for a single relationship field.
1271
- */
1272
- const nestedOpOrder = [
1273
- 'create',
1274
- 'connect',
1275
- 'connectOrCreate',
1276
- 'update',
1277
- 'disconnect',
1278
- 'delete',
1279
- 'deleteMany',
1280
- 'set',
1281
- 'updateMany',
1282
- ] as const
1283
-
1284
- /**
1285
- * Process the nested relationship operations supplied for a single
1286
- * relationship field's value, dispatching each present nested-op kind through
1287
- * the {@link nestedOpRegistry}.
1288
- */
1289
- async function processFieldNestedOps(
1290
- fieldName: string,
1291
- valueRecord: Record<string, unknown>,
1292
- args: Omit<NestedOpHandlerArgs, 'value' | 'fieldName' | 'recovery'>,
1293
- includeFields: Set<string>,
1294
- parentListName: string,
1295
- parentOriginalItem: Record<string, unknown> | undefined,
1296
- ): Promise<Record<string, unknown>> {
1297
- // Refuse a non-sudo payload carrying a refused kind BEFORE any part of the
1298
- // write executes — including before another kind on this same field
1299
- // dispatches (see NestedRelationInputError's docblock). Collects every
1300
- // refused kind present so a payload mixing e.g. `set` and `updateMany`
1301
- // reports both in one error, not just the first found.
1302
- if (!args.context._isSudo) {
1303
- const refusedKinds = REFUSED_KINDS.filter((kind) => valueRecord[kind] !== undefined)
1304
- if (refusedKinds.length > 0) {
1305
- throw new NestedRelationInputError(parentListName, fieldName, refusedKinds)
1306
- }
1307
- }
1308
-
1309
- const nestedOp: Record<string, unknown> = {}
1310
-
1311
- // Created-row recovery is only needed when this field has a creating kind
1312
- // (`create`/`connectOrCreate`). When present it requires a pre-persist read of
1313
- // the parent's current related ids, so build it once, lazily, and share it
1314
- // across the creating kinds on this field.
1315
- let recovery: CreatedRowRecovery | undefined
1316
- const hasCreatingKind = nestedOpOrder.some(
1317
- (kind) => CREATING_KINDS.has(kind) && valueRecord[kind] !== undefined,
1318
- )
1319
- if (hasCreatingKind) {
1320
- const preExistingIds = await capturePreExistingIds(
1321
- parentListName,
1322
- parentOriginalItem,
1323
- fieldName,
1324
- args.prisma,
1325
- )
1326
- recovery = createCreatedRowRecovery(fieldName, preExistingIds)
1327
- }
1328
-
1329
- for (const kind of nestedOpOrder) {
1330
- const value = valueRecord[kind]
1331
- if (value === undefined) {
1332
- continue
1333
- }
1334
-
1335
- const handler = nestedOpRegistry[kind]
1336
- if (handler.needsInclude) {
1337
- includeFields.add(fieldName)
1338
- }
1339
- nestedOp[kind] = await handler.execute({
1340
- ...args,
1341
- value,
1342
- fieldName,
1343
- recovery,
1344
- })
1345
- }
1346
-
1347
- return nestedOp
1348
- }
1349
-
1350
- /**
1351
- * Process all nested operations in a data payload.
1352
- *
1353
- * Recursively handles relationship fields with nested writes. In addition to
1354
- * transforming the payload it runs each nested record's `beforeOperation` and
1355
- * collects deferred `afterOperation` tasks (run by the Write Pipeline after the
1356
- * parent persist via {@link runAfterTasks}). See ADR-0010.
1357
- */
1358
- export async function processNestedOperations(
1359
- data: Record<string, unknown>,
1360
- fieldConfigs: Record<string, FieldConfig>,
1361
- config: OpenSaasConfig,
1362
- context: StackContext & { prisma: unknown },
1363
- operation: 'create' | 'update',
1364
- parentListName: string,
1365
- parentOriginalItem: Record<string, unknown> | undefined,
1366
- // The enclosing write's inputData, for the #588 owning-field gate (see
1367
- // verifyConnectReachable). `undefined` is tolerated (defaults to `{}`).
1368
- parentInputData: Record<string, unknown> | undefined = undefined,
1369
- ): Promise<NestedOpsResult> {
1370
- const afterTasks: AfterTask[] = []
1371
- const includeFields = new Set<string>()
1372
-
1373
- const processed: Record<string, unknown> = {}
1374
-
1375
- for (const [fieldName, value] of Object.entries(data)) {
1376
- if (value === null || value === undefined) {
1377
- processed[fieldName] = value
1378
- continue
1379
- }
1380
-
1381
- const fieldConfig = fieldConfigs[fieldName]
1382
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ListConfig must accept any TypeInfo
1383
- let relatedListConfig: ListConfig<any>
1384
- let resolvedListName: string
1385
- let owningFieldAccess: FieldAccess | undefined
1386
-
1387
- if (isRelationshipField(fieldConfig)) {
1388
- const relationshipField = fieldConfig as { type: 'relationship'; ref: string }
1389
- const relatedConfig = getRelatedListConfig(relationshipField.ref, config)
1390
- if (!relatedConfig) {
1391
- processed[fieldName] = value
1392
- continue
1393
- }
1394
-
1395
- const { listName: relatedListName, listConfig } = relatedConfig
1396
- resolvedListName = relatedListName || findListName(listConfig, config)
1397
- relatedListConfig = listConfig
1398
- // The owning relationship field's field-level access, for the #588 gate
1399
- // in verifyConnectReachable.
1400
- owningFieldAccess = fieldConfig.access
1401
- } else if (!fieldConfig) {
1402
- // Not a field the parent's config declares — check whether it names the
1403
- // synthetic back-relation a list-only `ref` generates on this list
1404
- // (`from_<List>_<field>`, #978). Resolved, it is processed exactly like a
1405
- // nested write through the declared field that owns it; unresolved, it
1406
- // is left untouched. This is NOT solely a sudo path: a multi-column
1407
- // field's raw per-part columns (e.g. `m_url`/`m_size`, #789) are ALSO
1408
- // undeclared from this list's `fieldConfigs` perspective and reach here
1409
- // on every write, sudo or not — `filterWritableFields` already
1410
- // recognises and gates those via its own `splitColumnOwners` map before
1411
- // its undeclared-key branch, and this function has no such map to tell
1412
- // them apart from a genuinely-unrecognised key, so it must not throw
1413
- // here. A genuinely unrecognised key under sudo is refused instead by
1414
- // `filterWritableFields`'s own resolution attempt, one level up.
1415
- const synthetic = resolveSyntheticReverseRelation(fieldName, parentListName, config)
1416
- if (!synthetic) {
1417
- processed[fieldName] = value
1418
- continue
1419
- }
1420
-
1421
- resolvedListName = synthetic.sourceListName
1422
- relatedListConfig = synthetic.sourceListConfig
1423
- // There is no parent-side field here (unlike the declared-relationship
1424
- // branch above) — the FK-owning field genuinely IS the one the source
1425
- // list declares, so its access is the owning-field gate.
1426
- owningFieldAccess = synthetic.sourceFieldConfig.access
1427
- } else {
1428
- processed[fieldName] = value
1429
- continue
1430
- }
1431
-
1432
- processed[fieldName] = await processFieldNestedOps(
1433
- fieldName,
1434
- value as Record<string, unknown>,
1435
- {
1436
- relatedListName: resolvedListName,
1437
- relatedListConfig,
1438
- owningFieldAccess,
1439
- enclosingOperation: operation,
1440
- // Same values Phase-5 `filterWritableFields` passes for this field, so
1441
- // the #588 owning-field gate can't diverge from it.
1442
- enclosingItem: parentOriginalItem,
1443
- enclosingInputData: parentInputData ?? {},
1444
- context,
1445
- config,
1446
- prisma: context.prisma,
1447
- afterTasks,
1448
- },
1449
- includeFields,
1450
- parentListName,
1451
- parentOriginalItem,
1452
- )
1453
- }
1454
-
1455
- return { data: processed, afterTasks, includeFields }
1456
- }
1457
-
1458
- /**
1459
- * Run a set of deferred nested `afterOperation` tasks against a persisted parent
1460
- * row. Tasks run sequentially so a throwing after-hook aborts the rest (and, run
1461
- * inside the transaction by the Write Pipeline, rolls the whole write back).
1462
- */
1463
- export async function runAfterTasks(
1464
- afterTasks: AfterTask[],
1465
- parentResult: Record<string, unknown>,
1466
- ): Promise<void> {
1467
- for (const task of afterTasks) {
1468
- await task.run(parentResult)
1469
- }
1470
- }