@strapi/content-manager 0.0.0 → 5.0.0-beta.10

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 (510) hide show
  1. package/README.md +9 -1
  2. package/dist/_chunks/CardDragPreview-C0QyJgRA.js +69 -0
  3. package/dist/_chunks/CardDragPreview-C0QyJgRA.js.map +1 -0
  4. package/dist/_chunks/CardDragPreview-DOxamsuj.mjs +70 -0
  5. package/dist/_chunks/CardDragPreview-DOxamsuj.mjs.map +1 -0
  6. package/dist/_chunks/ComponentConfigurationPage-BNrZY1Rt.js +255 -0
  7. package/dist/_chunks/ComponentConfigurationPage-BNrZY1Rt.js.map +1 -0
  8. package/dist/_chunks/ComponentConfigurationPage-DF4KsgJw.mjs +236 -0
  9. package/dist/_chunks/ComponentConfigurationPage-DF4KsgJw.mjs.map +1 -0
  10. package/dist/_chunks/ComponentIcon-BXdiCGQp.js +176 -0
  11. package/dist/_chunks/ComponentIcon-BXdiCGQp.js.map +1 -0
  12. package/dist/_chunks/ComponentIcon-u4bIXTFY.mjs +157 -0
  13. package/dist/_chunks/ComponentIcon-u4bIXTFY.mjs.map +1 -0
  14. package/dist/_chunks/EditConfigurationPage-CzBCnSlY.js +151 -0
  15. package/dist/_chunks/EditConfigurationPage-CzBCnSlY.js.map +1 -0
  16. package/dist/_chunks/EditConfigurationPage-Dn7sFfOu.mjs +132 -0
  17. package/dist/_chunks/EditConfigurationPage-Dn7sFfOu.mjs.map +1 -0
  18. package/dist/_chunks/EditViewPage-CEemNwSu.js +222 -0
  19. package/dist/_chunks/EditViewPage-CEemNwSu.js.map +1 -0
  20. package/dist/_chunks/EditViewPage-D2uq2uZS.mjs +203 -0
  21. package/dist/_chunks/EditViewPage-D2uq2uZS.mjs.map +1 -0
  22. package/dist/_chunks/Field-DvB4ig_f.mjs +5466 -0
  23. package/dist/_chunks/Field-DvB4ig_f.mjs.map +1 -0
  24. package/dist/_chunks/Field-KHBYihjn.js +5498 -0
  25. package/dist/_chunks/Field-KHBYihjn.js.map +1 -0
  26. package/dist/_chunks/FieldTypeIcon-CMlNO8PE.mjs +50 -0
  27. package/dist/_chunks/FieldTypeIcon-CMlNO8PE.mjs.map +1 -0
  28. package/dist/_chunks/FieldTypeIcon-Dnwq_IRF.js +49 -0
  29. package/dist/_chunks/FieldTypeIcon-Dnwq_IRF.js.map +1 -0
  30. package/dist/_chunks/Form-BGmF27Mb.mjs +739 -0
  31. package/dist/_chunks/Form-BGmF27Mb.mjs.map +1 -0
  32. package/dist/_chunks/Form-De_O8dNp.js +760 -0
  33. package/dist/_chunks/Form-De_O8dNp.js.map +1 -0
  34. package/dist/_chunks/History-Cqq6Csvj.mjs +1007 -0
  35. package/dist/_chunks/History-Cqq6Csvj.mjs.map +1 -0
  36. package/dist/_chunks/History-aALwb_34.js +1028 -0
  37. package/dist/_chunks/History-aALwb_34.js.map +1 -0
  38. package/dist/_chunks/ListConfigurationPage-Bke2024Z.mjs +620 -0
  39. package/dist/_chunks/ListConfigurationPage-Bke2024Z.mjs.map +1 -0
  40. package/dist/_chunks/ListConfigurationPage-DimG1pln.js +640 -0
  41. package/dist/_chunks/ListConfigurationPage-DimG1pln.js.map +1 -0
  42. package/dist/_chunks/ListViewPage-BO-JvrUA.js +834 -0
  43. package/dist/_chunks/ListViewPage-BO-JvrUA.js.map +1 -0
  44. package/dist/_chunks/ListViewPage-Cjbh5jyY.mjs +810 -0
  45. package/dist/_chunks/ListViewPage-Cjbh5jyY.mjs.map +1 -0
  46. package/dist/_chunks/NoContentTypePage-S-R1DXX2.js +51 -0
  47. package/dist/_chunks/NoContentTypePage-S-R1DXX2.js.map +1 -0
  48. package/dist/_chunks/NoContentTypePage-m6_m6mFn.mjs +51 -0
  49. package/dist/_chunks/NoContentTypePage-m6_m6mFn.mjs.map +1 -0
  50. package/dist/_chunks/NoPermissionsPage-CCMchuOR.mjs +23 -0
  51. package/dist/_chunks/NoPermissionsPage-CCMchuOR.mjs.map +1 -0
  52. package/dist/_chunks/NoPermissionsPage-wFEMKcdV.js +23 -0
  53. package/dist/_chunks/NoPermissionsPage-wFEMKcdV.js.map +1 -0
  54. package/dist/_chunks/Relations-PjEVbLqZ.js +714 -0
  55. package/dist/_chunks/Relations-PjEVbLqZ.js.map +1 -0
  56. package/dist/_chunks/Relations-i8F_imXr.mjs +694 -0
  57. package/dist/_chunks/Relations-i8F_imXr.mjs.map +1 -0
  58. package/dist/_chunks/ar-BUUWXIYu.js +226 -0
  59. package/dist/_chunks/ar-BUUWXIYu.js.map +1 -0
  60. package/dist/_chunks/ar-CCEVvqGG.mjs +226 -0
  61. package/dist/_chunks/ar-CCEVvqGG.mjs.map +1 -0
  62. package/dist/_chunks/ca-5U32ON2v.mjs +201 -0
  63. package/dist/_chunks/ca-5U32ON2v.mjs.map +1 -0
  64. package/dist/_chunks/ca-Cmk45QO6.js +201 -0
  65. package/dist/_chunks/ca-Cmk45QO6.js.map +1 -0
  66. package/dist/_chunks/cs-CM2aBUar.mjs +125 -0
  67. package/dist/_chunks/cs-CM2aBUar.mjs.map +1 -0
  68. package/dist/_chunks/cs-CkJy6B2v.js +125 -0
  69. package/dist/_chunks/cs-CkJy6B2v.js.map +1 -0
  70. package/dist/_chunks/de-C72KDNOl.mjs +199 -0
  71. package/dist/_chunks/de-C72KDNOl.mjs.map +1 -0
  72. package/dist/_chunks/de-CCEmbAah.js +199 -0
  73. package/dist/_chunks/de-CCEmbAah.js.map +1 -0
  74. package/dist/_chunks/en-Ux26r5pl.mjs +291 -0
  75. package/dist/_chunks/en-Ux26r5pl.mjs.map +1 -0
  76. package/dist/_chunks/en-fbKQxLGn.js +291 -0
  77. package/dist/_chunks/en-fbKQxLGn.js.map +1 -0
  78. package/dist/_chunks/es-CeXiYflN.mjs +196 -0
  79. package/dist/_chunks/es-CeXiYflN.mjs.map +1 -0
  80. package/dist/_chunks/es-EUonQTon.js +196 -0
  81. package/dist/_chunks/es-EUonQTon.js.map +1 -0
  82. package/dist/_chunks/eu-CdALomew.mjs +202 -0
  83. package/dist/_chunks/eu-CdALomew.mjs.map +1 -0
  84. package/dist/_chunks/eu-VDH-3ovk.js +202 -0
  85. package/dist/_chunks/eu-VDH-3ovk.js.map +1 -0
  86. package/dist/_chunks/fr-B7kGGg3E.js +206 -0
  87. package/dist/_chunks/fr-B7kGGg3E.js.map +1 -0
  88. package/dist/_chunks/fr-CD9VFbPM.mjs +206 -0
  89. package/dist/_chunks/fr-CD9VFbPM.mjs.map +1 -0
  90. package/dist/_chunks/gu-BRmF601H.js +200 -0
  91. package/dist/_chunks/gu-BRmF601H.js.map +1 -0
  92. package/dist/_chunks/gu-CNpaMDpH.mjs +200 -0
  93. package/dist/_chunks/gu-CNpaMDpH.mjs.map +1 -0
  94. package/dist/_chunks/hi-CCJBptSq.js +200 -0
  95. package/dist/_chunks/hi-CCJBptSq.js.map +1 -0
  96. package/dist/_chunks/hi-Dwvd04m3.mjs +200 -0
  97. package/dist/_chunks/hi-Dwvd04m3.mjs.map +1 -0
  98. package/dist/_chunks/hooks-BAaaKPS_.js +7 -0
  99. package/dist/_chunks/hooks-BAaaKPS_.js.map +1 -0
  100. package/dist/_chunks/hooks-E5u1mcgM.mjs +8 -0
  101. package/dist/_chunks/hooks-E5u1mcgM.mjs.map +1 -0
  102. package/dist/_chunks/hu-CeYvaaO0.mjs +202 -0
  103. package/dist/_chunks/hu-CeYvaaO0.mjs.map +1 -0
  104. package/dist/_chunks/hu-sNV_yLYy.js +202 -0
  105. package/dist/_chunks/hu-sNV_yLYy.js.map +1 -0
  106. package/dist/_chunks/id-B5Ser98A.js +160 -0
  107. package/dist/_chunks/id-B5Ser98A.js.map +1 -0
  108. package/dist/_chunks/id-BtwA9WJT.mjs +160 -0
  109. package/dist/_chunks/id-BtwA9WJT.mjs.map +1 -0
  110. package/dist/_chunks/index-B4Gj2Oe9.js +3791 -0
  111. package/dist/_chunks/index-B4Gj2Oe9.js.map +1 -0
  112. package/dist/_chunks/index-BAGok3Xa.mjs +3772 -0
  113. package/dist/_chunks/index-BAGok3Xa.mjs.map +1 -0
  114. package/dist/_chunks/it-BrVPqaf1.mjs +162 -0
  115. package/dist/_chunks/it-BrVPqaf1.mjs.map +1 -0
  116. package/dist/_chunks/it-DkBIs7vD.js +162 -0
  117. package/dist/_chunks/it-DkBIs7vD.js.map +1 -0
  118. package/dist/_chunks/ja-CcFe8diO.js +196 -0
  119. package/dist/_chunks/ja-CcFe8diO.js.map +1 -0
  120. package/dist/_chunks/ja-CtsUxOvk.mjs +196 -0
  121. package/dist/_chunks/ja-CtsUxOvk.mjs.map +1 -0
  122. package/dist/_chunks/ko-HVQRlfUI.mjs +195 -0
  123. package/dist/_chunks/ko-HVQRlfUI.mjs.map +1 -0
  124. package/dist/_chunks/ko-woFZPmLk.js +195 -0
  125. package/dist/_chunks/ko-woFZPmLk.js.map +1 -0
  126. package/dist/_chunks/layout-BybbePH7.mjs +458 -0
  127. package/dist/_chunks/layout-BybbePH7.mjs.map +1 -0
  128. package/dist/_chunks/layout-aK6fNSLK.js +476 -0
  129. package/dist/_chunks/layout-aK6fNSLK.js.map +1 -0
  130. package/dist/_chunks/ml-BihZwQit.mjs +200 -0
  131. package/dist/_chunks/ml-BihZwQit.mjs.map +1 -0
  132. package/dist/_chunks/ml-C2W8N8k1.js +200 -0
  133. package/dist/_chunks/ml-C2W8N8k1.js.map +1 -0
  134. package/dist/_chunks/ms-BuFotyP_.js +144 -0
  135. package/dist/_chunks/ms-BuFotyP_.js.map +1 -0
  136. package/dist/_chunks/ms-m_WjyWx7.mjs +144 -0
  137. package/dist/_chunks/ms-m_WjyWx7.mjs.map +1 -0
  138. package/dist/_chunks/nl-D4R9gHx5.mjs +202 -0
  139. package/dist/_chunks/nl-D4R9gHx5.mjs.map +1 -0
  140. package/dist/_chunks/nl-bbEOHChV.js +202 -0
  141. package/dist/_chunks/nl-bbEOHChV.js.map +1 -0
  142. package/dist/_chunks/objects-gigeqt7s.js +49 -0
  143. package/dist/_chunks/objects-gigeqt7s.js.map +1 -0
  144. package/dist/_chunks/objects-mKMAmfec.mjs +47 -0
  145. package/dist/_chunks/objects-mKMAmfec.mjs.map +1 -0
  146. package/dist/_chunks/pl-sbx9mSt_.mjs +199 -0
  147. package/dist/_chunks/pl-sbx9mSt_.mjs.map +1 -0
  148. package/dist/_chunks/pl-uzwG-hk7.js +199 -0
  149. package/dist/_chunks/pl-uzwG-hk7.js.map +1 -0
  150. package/dist/_chunks/pt-BR-BiOz37D9.js +201 -0
  151. package/dist/_chunks/pt-BR-BiOz37D9.js.map +1 -0
  152. package/dist/_chunks/pt-BR-C71iDxnh.mjs +201 -0
  153. package/dist/_chunks/pt-BR-C71iDxnh.mjs.map +1 -0
  154. package/dist/_chunks/pt-BsaFvS8-.mjs +95 -0
  155. package/dist/_chunks/pt-BsaFvS8-.mjs.map +1 -0
  156. package/dist/_chunks/pt-CeXQuq50.js +95 -0
  157. package/dist/_chunks/pt-CeXQuq50.js.map +1 -0
  158. package/dist/_chunks/relations-BZicUuRc.mjs +135 -0
  159. package/dist/_chunks/relations-BZicUuRc.mjs.map +1 -0
  160. package/dist/_chunks/relations-yBDEAWeN.js +134 -0
  161. package/dist/_chunks/relations-yBDEAWeN.js.map +1 -0
  162. package/dist/_chunks/ru-BE6A4Exp.mjs +231 -0
  163. package/dist/_chunks/ru-BE6A4Exp.mjs.map +1 -0
  164. package/dist/_chunks/ru-BT3ybNny.js +231 -0
  165. package/dist/_chunks/ru-BT3ybNny.js.map +1 -0
  166. package/dist/_chunks/sa-CcvkYInH.js +200 -0
  167. package/dist/_chunks/sa-CcvkYInH.js.map +1 -0
  168. package/dist/_chunks/sa-Dag0k-Z8.mjs +200 -0
  169. package/dist/_chunks/sa-Dag0k-Z8.mjs.map +1 -0
  170. package/dist/_chunks/sk-BFg-R8qJ.mjs +202 -0
  171. package/dist/_chunks/sk-BFg-R8qJ.mjs.map +1 -0
  172. package/dist/_chunks/sk-CvY09Xjv.js +202 -0
  173. package/dist/_chunks/sk-CvY09Xjv.js.map +1 -0
  174. package/dist/_chunks/sv-CUnfWGsh.mjs +202 -0
  175. package/dist/_chunks/sv-CUnfWGsh.mjs.map +1 -0
  176. package/dist/_chunks/sv-MYDuzgvT.js +202 -0
  177. package/dist/_chunks/sv-MYDuzgvT.js.map +1 -0
  178. package/dist/_chunks/th-BqbI8lIT.mjs +148 -0
  179. package/dist/_chunks/th-BqbI8lIT.mjs.map +1 -0
  180. package/dist/_chunks/th-D9_GfAjc.js +148 -0
  181. package/dist/_chunks/th-D9_GfAjc.js.map +1 -0
  182. package/dist/_chunks/tr-CgeK3wJM.mjs +199 -0
  183. package/dist/_chunks/tr-CgeK3wJM.mjs.map +1 -0
  184. package/dist/_chunks/tr-D9UH-O_R.js +199 -0
  185. package/dist/_chunks/tr-D9UH-O_R.js.map +1 -0
  186. package/dist/_chunks/uk-C8EiqJY7.js +144 -0
  187. package/dist/_chunks/uk-C8EiqJY7.js.map +1 -0
  188. package/dist/_chunks/uk-CR-zDhAY.mjs +144 -0
  189. package/dist/_chunks/uk-CR-zDhAY.mjs.map +1 -0
  190. package/dist/_chunks/useDragAndDrop-DdHgKsqq.mjs +231 -0
  191. package/dist/_chunks/useDragAndDrop-DdHgKsqq.mjs.map +1 -0
  192. package/dist/_chunks/useDragAndDrop-J0TUUbR6.js +249 -0
  193. package/dist/_chunks/useDragAndDrop-J0TUUbR6.js.map +1 -0
  194. package/dist/_chunks/usePrev-B9w_-eYc.js +15 -0
  195. package/dist/_chunks/usePrev-B9w_-eYc.js.map +1 -0
  196. package/dist/_chunks/usePrev-DH6iah0A.mjs +16 -0
  197. package/dist/_chunks/usePrev-DH6iah0A.mjs.map +1 -0
  198. package/dist/_chunks/vi-CJlYDheJ.js +111 -0
  199. package/dist/_chunks/vi-CJlYDheJ.js.map +1 -0
  200. package/dist/_chunks/vi-DUXIk_fw.mjs +111 -0
  201. package/dist/_chunks/vi-DUXIk_fw.mjs.map +1 -0
  202. package/dist/_chunks/zh-BWZspA60.mjs +209 -0
  203. package/dist/_chunks/zh-BWZspA60.mjs.map +1 -0
  204. package/dist/_chunks/zh-CQQfszqR.js +209 -0
  205. package/dist/_chunks/zh-CQQfszqR.js.map +1 -0
  206. package/dist/_chunks/zh-Hans-9kOncHGw.js +952 -0
  207. package/dist/_chunks/zh-Hans-9kOncHGw.js.map +1 -0
  208. package/dist/_chunks/zh-Hans-BPQcRIyH.mjs +952 -0
  209. package/dist/_chunks/zh-Hans-BPQcRIyH.mjs.map +1 -0
  210. package/dist/admin/index.js +12 -0
  211. package/dist/admin/index.js.map +1 -0
  212. package/dist/admin/index.mjs +12 -0
  213. package/dist/admin/index.mjs.map +1 -0
  214. package/dist/admin/src/components/ComponentIcon.d.ts +11 -0
  215. package/dist/admin/src/components/ConfigurationForm/EditFieldForm.d.ts +9 -0
  216. package/dist/admin/src/components/ConfigurationForm/Fields.d.ts +21 -0
  217. package/dist/admin/src/components/ConfigurationForm/Form.d.ts +32 -0
  218. package/dist/admin/src/components/DragLayer.d.ts +13 -0
  219. package/dist/admin/src/components/DragPreviews/CardDragPreview.d.ts +7 -0
  220. package/dist/admin/src/components/DragPreviews/ComponentDragPreview.d.ts +6 -0
  221. package/dist/admin/src/components/DragPreviews/RelationDragPreview.d.ts +11 -0
  222. package/dist/admin/src/components/FieldTypeIcon.d.ts +9 -0
  223. package/dist/admin/src/components/InjectionZone.d.ts +45 -0
  224. package/dist/admin/src/components/LeftMenu.d.ts +2 -0
  225. package/dist/admin/src/components/RelativeTime.d.ts +28 -0
  226. package/dist/admin/src/constants/attributes.d.ts +14 -0
  227. package/dist/admin/src/constants/collections.d.ts +3 -0
  228. package/dist/admin/src/constants/dragAndDrop.d.ts +8 -0
  229. package/dist/admin/src/constants/hooks.d.ts +26 -0
  230. package/dist/admin/src/constants/plugin.d.ts +3 -0
  231. package/dist/admin/src/content-manager.d.ts +133 -0
  232. package/dist/admin/src/exports.d.ts +12 -0
  233. package/dist/admin/src/features/DocumentRBAC.d.ts +36 -0
  234. package/dist/admin/src/history/components/HistoryAction.d.ts +3 -0
  235. package/dist/admin/src/history/components/VersionContent.d.ts +17 -0
  236. package/dist/admin/src/history/components/VersionHeader.d.ts +5 -0
  237. package/dist/admin/src/history/components/VersionInputRenderer.d.ts +19 -0
  238. package/dist/admin/src/history/components/VersionsList.d.ts +2 -0
  239. package/dist/admin/src/history/pages/History.d.ts +27 -0
  240. package/dist/admin/src/history/routes.d.ts +6 -0
  241. package/dist/admin/src/history/services/historyVersion.d.ts +12 -0
  242. package/dist/admin/src/hooks/useContentManagerInitData.d.ts +15 -0
  243. package/dist/admin/src/hooks/useContentTypeSchema.d.ts +25 -0
  244. package/dist/admin/src/hooks/useDebounce.d.ts +1 -0
  245. package/dist/admin/src/hooks/useDocument.d.ts +87 -0
  246. package/dist/admin/src/hooks/useDocumentActions.d.ts +123 -0
  247. package/dist/admin/src/hooks/useDocumentLayout.d.ts +137 -0
  248. package/dist/admin/src/hooks/useDragAndDrop.d.ts +51 -0
  249. package/dist/admin/src/hooks/useKeyboardDragAndDrop.d.ts +14 -0
  250. package/dist/admin/src/hooks/useLazyComponents.d.ts +13 -0
  251. package/dist/admin/src/hooks/useOnce.d.ts +2 -0
  252. package/dist/admin/src/hooks/usePrev.d.ts +1 -0
  253. package/dist/admin/src/index.d.ts +16 -0
  254. package/dist/admin/src/layout.d.ts +2 -0
  255. package/dist/admin/src/modules/app.d.ts +20 -0
  256. package/dist/admin/src/modules/hooks.d.ts +10 -0
  257. package/dist/admin/src/modules/reducers.d.ts +6 -0
  258. package/dist/admin/src/pages/ComponentConfigurationPage.d.ts +3 -0
  259. package/dist/admin/src/pages/EditConfigurationPage.d.ts +3 -0
  260. package/dist/admin/src/pages/EditView/EditViewPage.d.ts +3 -0
  261. package/dist/admin/src/pages/EditView/components/DocumentActions.d.ts +75 -0
  262. package/dist/admin/src/pages/EditView/components/DocumentStatus.d.ts +16 -0
  263. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Code.d.ts +3 -0
  264. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Heading.d.ts +3 -0
  265. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Image.d.ts +3 -0
  266. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Link.d.ts +3 -0
  267. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/List.d.ts +3 -0
  268. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Paragraph.d.ts +3 -0
  269. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Blocks/Quote.d.ts +3 -0
  270. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksContent.d.ts +6 -0
  271. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksEditor.d.ts +61 -0
  272. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksInput.d.ts +11 -0
  273. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/BlocksToolbar.d.ts +10 -0
  274. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/EditorLayout.d.ts +10 -0
  275. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/Modifiers.d.ts +16 -0
  276. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withImages.d.ts +11 -0
  277. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withLinks.d.ts +9 -0
  278. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/plugins/withStrapiSchema.d.ts +8 -0
  279. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/constants.d.ts +4 -0
  280. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/conversions.d.ts +13 -0
  281. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/enterKey.d.ts +6 -0
  282. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/links.d.ts +10 -0
  283. package/dist/admin/src/pages/EditView/components/FormInputs/BlocksInput/utils/types.d.ts +10 -0
  284. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Initializer.d.ts +9 -0
  285. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Input.d.ts +18 -0
  286. package/dist/admin/src/pages/EditView/components/FormInputs/Component/NonRepeatable.d.ts +5 -0
  287. package/dist/admin/src/pages/EditView/components/FormInputs/Component/Repeatable.d.ts +5 -0
  288. package/dist/admin/src/pages/EditView/components/FormInputs/ComponentContext.d.ts +42 -0
  289. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/AddComponentButton.d.ts +11 -0
  290. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentCard.d.ts +9 -0
  291. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentCategory.d.ts +15 -0
  292. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/ComponentPicker.d.ts +9 -0
  293. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/DynamicComponent.d.ts +14 -0
  294. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/DynamicZoneLabel.d.ts +12 -0
  295. package/dist/admin/src/pages/EditView/components/FormInputs/DynamicZone/Field.d.ts +14 -0
  296. package/dist/admin/src/pages/EditView/components/FormInputs/NotAllowed.d.ts +7 -0
  297. package/dist/admin/src/pages/EditView/components/FormInputs/Relations.d.ts +18 -0
  298. package/dist/admin/src/pages/EditView/components/FormInputs/UID.d.ts +9 -0
  299. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/Editor.d.ts +17 -0
  300. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/EditorLayout.d.ts +14 -0
  301. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/Field.d.ts +11 -0
  302. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/PreviewWysiwyg.d.ts +5 -0
  303. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygFooter.d.ts +7 -0
  304. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygNav.d.ts +17 -0
  305. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/WysiwygStyles.d.ts +62 -0
  306. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/continueList.d.ts +5 -0
  307. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/mdRenderer.d.ts +4 -0
  308. package/dist/admin/src/pages/EditView/components/FormInputs/Wysiwyg/utils/utils.d.ts +16 -0
  309. package/dist/admin/src/pages/EditView/components/FormLayout.d.ts +5 -0
  310. package/dist/admin/src/pages/EditView/components/Header.d.ts +35 -0
  311. package/dist/admin/src/pages/EditView/components/InputRenderer.d.ts +9 -0
  312. package/dist/admin/src/pages/EditView/components/Panels.d.ts +10 -0
  313. package/dist/admin/src/pages/EditView/utils/data.d.ts +33 -0
  314. package/dist/admin/src/pages/EditView/utils/forms.d.ts +9 -0
  315. package/dist/admin/src/pages/ListConfiguration/ListConfigurationPage.d.ts +10 -0
  316. package/dist/admin/src/pages/ListConfiguration/components/DraggableCard.d.ts +12 -0
  317. package/dist/admin/src/pages/ListConfiguration/components/EditFieldForm.d.ts +8 -0
  318. package/dist/admin/src/pages/ListConfiguration/components/Header.d.ts +8 -0
  319. package/dist/admin/src/pages/ListConfiguration/components/Settings.d.ts +19 -0
  320. package/dist/admin/src/pages/ListConfiguration/components/SortDisplayedFields.d.ts +6 -0
  321. package/dist/admin/src/pages/ListView/ListViewPage.d.ts +3 -0
  322. package/dist/admin/src/pages/ListView/components/AutoCloneFailureModal.d.ts +7 -0
  323. package/dist/admin/src/pages/ListView/components/BulkActions/Actions.d.ts +24 -0
  324. package/dist/admin/src/pages/ListView/components/BulkActions/ConfirmBulkActionDialog.d.ts +15 -0
  325. package/dist/admin/src/pages/ListView/components/BulkActions/PublishAction.d.ts +14 -0
  326. package/dist/admin/src/pages/ListView/components/Filters.d.ts +8 -0
  327. package/dist/admin/src/pages/ListView/components/TableActions.d.ts +8 -0
  328. package/dist/admin/src/pages/ListView/components/TableCells/CellContent.d.ts +9 -0
  329. package/dist/admin/src/pages/ListView/components/TableCells/CellValue.d.ts +8 -0
  330. package/dist/admin/src/pages/ListView/components/TableCells/Components.d.ts +12 -0
  331. package/dist/admin/src/pages/ListView/components/TableCells/Media.d.ts +23 -0
  332. package/dist/admin/src/pages/ListView/components/TableCells/Relations.d.ts +12 -0
  333. package/dist/admin/src/pages/ListView/components/ViewSettingsMenu.d.ts +10 -0
  334. package/dist/admin/src/pages/NoContentTypePage.d.ts +2 -0
  335. package/dist/admin/src/pages/NoPermissionsPage.d.ts +2 -0
  336. package/dist/admin/src/router.d.ts +5 -0
  337. package/dist/admin/src/services/api.d.ts +2 -0
  338. package/dist/admin/src/services/components.d.ts +5 -0
  339. package/dist/admin/src/services/contentTypes.d.ts +17 -0
  340. package/dist/admin/src/services/documents.d.ts +101 -0
  341. package/dist/admin/src/services/init.d.ts +9 -0
  342. package/dist/admin/src/services/relations.d.ts +49 -0
  343. package/dist/admin/src/services/uid.d.ts +32 -0
  344. package/dist/admin/src/utils/api.d.ts +24 -0
  345. package/dist/admin/src/utils/attributes.d.ts +19 -0
  346. package/dist/admin/src/utils/objects.d.ts +33 -0
  347. package/dist/admin/src/utils/relations.d.ts +12 -0
  348. package/dist/admin/src/utils/strings.d.ts +2 -0
  349. package/dist/admin/src/utils/translations.d.ts +4 -0
  350. package/dist/admin/src/utils/urls.d.ts +2 -0
  351. package/dist/admin/src/utils/users.d.ts +6 -0
  352. package/dist/admin/src/utils/validation.d.ts +7 -0
  353. package/dist/server/index.js +4365 -0
  354. package/dist/server/index.js.map +1 -0
  355. package/dist/server/index.mjs +4341 -0
  356. package/dist/server/index.mjs.map +1 -0
  357. package/dist/server/src/bootstrap.d.ts +3 -0
  358. package/dist/server/src/bootstrap.d.ts.map +1 -0
  359. package/dist/server/src/config.d.ts +6 -0
  360. package/dist/server/src/config.d.ts.map +1 -0
  361. package/dist/server/src/constants/index.d.ts +6 -0
  362. package/dist/server/src/constants/index.d.ts.map +1 -0
  363. package/dist/server/src/controllers/collection-types.d.ts +23 -0
  364. package/dist/server/src/controllers/collection-types.d.ts.map +1 -0
  365. package/dist/server/src/controllers/components.d.ts +7 -0
  366. package/dist/server/src/controllers/components.d.ts.map +1 -0
  367. package/dist/server/src/controllers/content-types.d.ts +8 -0
  368. package/dist/server/src/controllers/content-types.d.ts.map +1 -0
  369. package/dist/server/src/controllers/index.d.ts +53 -0
  370. package/dist/server/src/controllers/index.d.ts.map +1 -0
  371. package/dist/server/src/controllers/init.d.ts +5 -0
  372. package/dist/server/src/controllers/init.d.ts.map +1 -0
  373. package/dist/server/src/controllers/relations.d.ts +13 -0
  374. package/dist/server/src/controllers/relations.d.ts.map +1 -0
  375. package/dist/server/src/controllers/single-types.d.ts +11 -0
  376. package/dist/server/src/controllers/single-types.d.ts.map +1 -0
  377. package/dist/server/src/controllers/uid.d.ts +6 -0
  378. package/dist/server/src/controllers/uid.d.ts.map +1 -0
  379. package/dist/server/src/controllers/utils/clone.d.ts +12 -0
  380. package/dist/server/src/controllers/utils/clone.d.ts.map +1 -0
  381. package/dist/server/src/controllers/utils/metadata.d.ts +8 -0
  382. package/dist/server/src/controllers/utils/metadata.d.ts.map +1 -0
  383. package/dist/server/src/controllers/validation/dimensions.d.ts +9 -0
  384. package/dist/server/src/controllers/validation/dimensions.d.ts.map +1 -0
  385. package/dist/server/src/controllers/validation/index.d.ts +20 -0
  386. package/dist/server/src/controllers/validation/index.d.ts.map +1 -0
  387. package/dist/server/src/controllers/validation/model-configuration.d.ts +22 -0
  388. package/dist/server/src/controllers/validation/model-configuration.d.ts.map +1 -0
  389. package/dist/server/src/controllers/validation/relations.d.ts +4 -0
  390. package/dist/server/src/controllers/validation/relations.d.ts.map +1 -0
  391. package/dist/server/src/destroy.d.ts +4 -0
  392. package/dist/server/src/destroy.d.ts.map +1 -0
  393. package/dist/server/src/history/constants.d.ts +3 -0
  394. package/dist/server/src/history/constants.d.ts.map +1 -0
  395. package/dist/server/src/history/controllers/history-version.d.ts +19 -0
  396. package/dist/server/src/history/controllers/history-version.d.ts.map +1 -0
  397. package/dist/server/src/history/controllers/index.d.ts +2 -0
  398. package/dist/server/src/history/controllers/index.d.ts.map +1 -0
  399. package/dist/server/src/history/controllers/validation/history-version.d.ts +2 -0
  400. package/dist/server/src/history/controllers/validation/history-version.d.ts.map +1 -0
  401. package/dist/server/src/history/index.d.ts +4 -0
  402. package/dist/server/src/history/index.d.ts.map +1 -0
  403. package/dist/server/src/history/models/history-version.d.ts +4 -0
  404. package/dist/server/src/history/models/history-version.d.ts.map +1 -0
  405. package/dist/server/src/history/routes/history-version.d.ts +4 -0
  406. package/dist/server/src/history/routes/history-version.d.ts.map +1 -0
  407. package/dist/server/src/history/routes/index.d.ts +8 -0
  408. package/dist/server/src/history/routes/index.d.ts.map +1 -0
  409. package/dist/server/src/history/services/history.d.ts +16 -0
  410. package/dist/server/src/history/services/history.d.ts.map +1 -0
  411. package/dist/server/src/history/services/index.d.ts +19 -0
  412. package/dist/server/src/history/services/index.d.ts.map +1 -0
  413. package/dist/server/src/history/services/lifecycles.d.ts +9 -0
  414. package/dist/server/src/history/services/lifecycles.d.ts.map +1 -0
  415. package/dist/server/src/history/services/utils.d.ts +44 -0
  416. package/dist/server/src/history/services/utils.d.ts.map +1 -0
  417. package/dist/server/src/history/utils.d.ts +22 -0
  418. package/dist/server/src/history/utils.d.ts.map +1 -0
  419. package/dist/server/src/index.d.ts +353 -0
  420. package/dist/server/src/index.d.ts.map +1 -0
  421. package/dist/server/src/middlewares/index.d.ts +3 -0
  422. package/dist/server/src/middlewares/index.d.ts.map +1 -0
  423. package/dist/server/src/middlewares/routing.d.ts +4 -0
  424. package/dist/server/src/middlewares/routing.d.ts.map +1 -0
  425. package/dist/server/src/policies/hasPermissions.d.ts +7 -0
  426. package/dist/server/src/policies/hasPermissions.d.ts.map +1 -0
  427. package/dist/server/src/policies/index.d.ts +9 -0
  428. package/dist/server/src/policies/index.d.ts.map +1 -0
  429. package/dist/server/src/register.d.ts +4 -0
  430. package/dist/server/src/register.d.ts.map +1 -0
  431. package/dist/server/src/routes/admin.d.ts +41 -0
  432. package/dist/server/src/routes/admin.d.ts.map +1 -0
  433. package/dist/server/src/routes/index.d.ts +43 -0
  434. package/dist/server/src/routes/index.d.ts.map +1 -0
  435. package/dist/server/src/services/components.d.ts +32 -0
  436. package/dist/server/src/services/components.d.ts.map +1 -0
  437. package/dist/server/src/services/configuration.d.ts +20 -0
  438. package/dist/server/src/services/configuration.d.ts.map +1 -0
  439. package/dist/server/src/services/content-types.d.ts +18 -0
  440. package/dist/server/src/services/content-types.d.ts.map +1 -0
  441. package/dist/server/src/services/data-mapper.d.ts +20 -0
  442. package/dist/server/src/services/data-mapper.d.ts.map +1 -0
  443. package/dist/server/src/services/document-manager.d.ts +48 -0
  444. package/dist/server/src/services/document-manager.d.ts.map +1 -0
  445. package/dist/server/src/services/document-metadata.d.ts +67 -0
  446. package/dist/server/src/services/document-metadata.d.ts.map +1 -0
  447. package/dist/server/src/services/field-sizes.d.ts +19 -0
  448. package/dist/server/src/services/field-sizes.d.ts.map +1 -0
  449. package/dist/server/src/services/index.d.ts +245 -0
  450. package/dist/server/src/services/index.d.ts.map +1 -0
  451. package/dist/server/src/services/metrics.d.ts +9 -0
  452. package/dist/server/src/services/metrics.d.ts.map +1 -0
  453. package/dist/server/src/services/permission-checker.d.ts +54 -0
  454. package/dist/server/src/services/permission-checker.d.ts.map +1 -0
  455. package/dist/server/src/services/permission.d.ts +12 -0
  456. package/dist/server/src/services/permission.d.ts.map +1 -0
  457. package/dist/server/src/services/populate-builder.d.ts +30 -0
  458. package/dist/server/src/services/populate-builder.d.ts.map +1 -0
  459. package/dist/server/src/services/uid.d.ts +25 -0
  460. package/dist/server/src/services/uid.d.ts.map +1 -0
  461. package/dist/server/src/services/utils/configuration/attributes.d.ts +17 -0
  462. package/dist/server/src/services/utils/configuration/attributes.d.ts.map +1 -0
  463. package/dist/server/src/services/utils/configuration/index.d.ts +21 -0
  464. package/dist/server/src/services/utils/configuration/index.d.ts.map +1 -0
  465. package/dist/server/src/services/utils/configuration/layouts.d.ts +14 -0
  466. package/dist/server/src/services/utils/configuration/layouts.d.ts.map +1 -0
  467. package/dist/server/src/services/utils/configuration/metadatas.d.ts +5 -0
  468. package/dist/server/src/services/utils/configuration/metadatas.d.ts.map +1 -0
  469. package/dist/server/src/services/utils/configuration/settings.d.ts +5 -0
  470. package/dist/server/src/services/utils/configuration/settings.d.ts.map +1 -0
  471. package/dist/server/src/services/utils/count.d.ts +5 -0
  472. package/dist/server/src/services/utils/count.d.ts.map +1 -0
  473. package/dist/server/src/services/utils/draft.d.ts +11 -0
  474. package/dist/server/src/services/utils/draft.d.ts.map +1 -0
  475. package/dist/server/src/services/utils/populate.d.ts +42 -0
  476. package/dist/server/src/services/utils/populate.d.ts.map +1 -0
  477. package/dist/server/src/services/utils/store.d.ts +16 -0
  478. package/dist/server/src/services/utils/store.d.ts.map +1 -0
  479. package/dist/server/src/utils/index.d.ts +9 -0
  480. package/dist/server/src/utils/index.d.ts.map +1 -0
  481. package/dist/server/src/validation/policies/hasPermissions.d.ts +2 -0
  482. package/dist/server/src/validation/policies/hasPermissions.d.ts.map +1 -0
  483. package/dist/shared/contracts/collection-types.d.ts +336 -0
  484. package/dist/shared/contracts/collection-types.d.ts.map +1 -0
  485. package/dist/shared/contracts/components.d.ts +65 -0
  486. package/dist/shared/contracts/components.d.ts.map +1 -0
  487. package/dist/shared/contracts/content-types.d.ts +113 -0
  488. package/dist/shared/contracts/content-types.d.ts.map +1 -0
  489. package/dist/shared/contracts/history-versions.d.ts +92 -0
  490. package/dist/shared/contracts/history-versions.d.ts.map +1 -0
  491. package/dist/shared/contracts/index.d.ts +10 -0
  492. package/dist/shared/contracts/index.d.ts.map +1 -0
  493. package/dist/shared/contracts/init.d.ts +24 -0
  494. package/dist/shared/contracts/init.d.ts.map +1 -0
  495. package/dist/shared/contracts/relations.d.ts +70 -0
  496. package/dist/shared/contracts/relations.d.ts.map +1 -0
  497. package/dist/shared/contracts/review-workflows.d.ts +78 -0
  498. package/dist/shared/contracts/review-workflows.d.ts.map +1 -0
  499. package/dist/shared/contracts/single-types.d.ts +113 -0
  500. package/dist/shared/contracts/single-types.d.ts.map +1 -0
  501. package/dist/shared/contracts/uid.d.ts +48 -0
  502. package/dist/shared/contracts/uid.d.ts.map +1 -0
  503. package/dist/shared/index.d.ts +2 -0
  504. package/dist/shared/index.d.ts.map +1 -0
  505. package/dist/shared/index.js +43 -0
  506. package/dist/shared/index.js.map +1 -0
  507. package/dist/shared/index.mjs +43 -0
  508. package/dist/shared/index.mjs.map +1 -0
  509. package/package.json +113 -2
  510. package/strapi-server.js +3 -0
@@ -0,0 +1,4365 @@
1
+ "use strict";
2
+ const strapiUtils = require("@strapi/utils");
3
+ const fp = require("lodash/fp");
4
+ require("@strapi/types");
5
+ const yup = require("yup");
6
+ const nodeSchedule = require("node-schedule");
7
+ const isNil = require("lodash/isNil");
8
+ const _ = require("lodash");
9
+ const qs = require("qs");
10
+ const slugify = require("@sindresorhus/slugify");
11
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule)
14
+ return e;
15
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
16
+ if (e) {
17
+ for (const k in e) {
18
+ if (k !== "default") {
19
+ const d = Object.getOwnPropertyDescriptor(e, k);
20
+ Object.defineProperty(n, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: () => e[k]
23
+ });
24
+ }
25
+ }
26
+ }
27
+ n.default = e;
28
+ return Object.freeze(n);
29
+ }
30
+ const strapiUtils__default = /* @__PURE__ */ _interopDefault(strapiUtils);
31
+ const yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
32
+ const isNil__default = /* @__PURE__ */ _interopDefault(isNil);
33
+ const ___default = /* @__PURE__ */ _interopDefault(_);
34
+ const qs__default = /* @__PURE__ */ _interopDefault(qs);
35
+ const slugify__default = /* @__PURE__ */ _interopDefault(slugify);
36
+ const getService$1 = (name) => {
37
+ return strapi.plugin("content-manager").service(name);
38
+ };
39
+ function getService(strapi2, name) {
40
+ return strapi2.service(`plugin::content-manager.${name}`);
41
+ }
42
+ const historyRestoreVersionSchema = yup__namespace.object().shape({
43
+ contentType: yup__namespace.string().trim().required()
44
+ }).required();
45
+ const validateRestoreVersion = strapiUtils.validateYupSchema(historyRestoreVersionSchema);
46
+ const getValidPagination = ({ page, pageSize }) => {
47
+ let pageNumber = 1;
48
+ let pageSizeNumber = 20;
49
+ if (page) {
50
+ const parsedPage = parseInt(page, 10);
51
+ pageNumber = parseInt(page, 10);
52
+ if (!Number.isNaN(parsedPage) && parsedPage >= 1) {
53
+ pageNumber = parsedPage;
54
+ }
55
+ }
56
+ if (pageSize) {
57
+ const parsedPageSize = parseInt(pageSize, 10);
58
+ if (!Number.isNaN(parsedPageSize) && parsedPageSize >= 1 && parsedPageSize <= 100) {
59
+ pageSizeNumber = parsedPageSize;
60
+ }
61
+ }
62
+ return { page: pageNumber, pageSize: pageSizeNumber };
63
+ };
64
+ const createHistoryVersionController = ({ strapi: strapi2 }) => {
65
+ return {
66
+ async findMany(ctx) {
67
+ const contentTypeUid = ctx.query.contentType;
68
+ const isSingleType = strapi2.getModel(contentTypeUid)?.kind === "singleType";
69
+ if (isSingleType && !contentTypeUid) {
70
+ throw new strapiUtils.errors.ForbiddenError("contentType is required");
71
+ }
72
+ if (!isSingleType && (!contentTypeUid || !ctx.query.documentId)) {
73
+ throw new strapiUtils.errors.ForbiddenError("contentType and documentId are required");
74
+ }
75
+ const permissionChecker2 = getService$1("permission-checker").create({
76
+ userAbility: ctx.state.userAbility,
77
+ model: ctx.query.contentType
78
+ });
79
+ if (permissionChecker2.cannot.read()) {
80
+ return ctx.forbidden();
81
+ }
82
+ const query = await permissionChecker2.sanitizeQuery(ctx.query);
83
+ const { results, pagination } = await getService(strapi2, "history").findVersionsPage({
84
+ query: {
85
+ ...query,
86
+ ...getValidPagination({ page: query.page, pageSize: query.pageSize })
87
+ },
88
+ state: { userAbility: ctx.state.userAbility }
89
+ });
90
+ const sanitizedResults = await strapiUtils.async.map(
91
+ results,
92
+ async (version) => {
93
+ return {
94
+ ...version,
95
+ data: await permissionChecker2.sanitizeOutput(version.data),
96
+ createdBy: version.createdBy ? fp.pick(["id", "firstname", "lastname", "username", "email"], version.createdBy) : void 0
97
+ };
98
+ }
99
+ );
100
+ return {
101
+ data: sanitizedResults,
102
+ meta: { pagination }
103
+ };
104
+ },
105
+ async restoreVersion(ctx) {
106
+ const request = ctx.request;
107
+ await validateRestoreVersion(request.body, "contentType is required");
108
+ const permissionChecker2 = getService$1("permission-checker").create({
109
+ userAbility: ctx.state.userAbility,
110
+ model: request.body.contentType
111
+ });
112
+ if (permissionChecker2.cannot.update()) {
113
+ throw new strapiUtils.errors.ForbiddenError();
114
+ }
115
+ const restoredDocument = await getService(strapi2, "history").restoreVersion(
116
+ request.params.versionId
117
+ );
118
+ return {
119
+ data: { documentId: restoredDocument.documentId }
120
+ };
121
+ }
122
+ };
123
+ };
124
+ const controllers$1 = {
125
+ "history-version": createHistoryVersionController
126
+ /**
127
+ * Casting is needed because the types aren't aware that Strapi supports
128
+ * passing a controller factory as the value, instead of a controller object directly
129
+ */
130
+ };
131
+ const HISTORY_VERSION_UID = "plugin::content-manager.history-version";
132
+ const FIELDS_TO_IGNORE = [
133
+ "createdAt",
134
+ "updatedAt",
135
+ "publishedAt",
136
+ "createdBy",
137
+ "updatedBy",
138
+ "strapi_stage",
139
+ "strapi_assignee"
140
+ ];
141
+ const DEFAULT_RETENTION_DAYS = 90;
142
+ const createServiceUtils = ({ strapi: strapi2 }) => {
143
+ const getSchemaAttributesDiff = (versionSchemaAttributes, contentTypeSchemaAttributes) => {
144
+ const sanitizedContentTypeSchemaAttributes = fp.omit(
145
+ FIELDS_TO_IGNORE,
146
+ contentTypeSchemaAttributes
147
+ );
148
+ const reduceDifferenceToAttributesObject = (diffKeys, source) => {
149
+ return diffKeys.reduce(
150
+ (previousAttributesObject, diffKey) => {
151
+ previousAttributesObject[diffKey] = source[diffKey];
152
+ return previousAttributesObject;
153
+ },
154
+ {}
155
+ );
156
+ };
157
+ const versionSchemaKeys = Object.keys(versionSchemaAttributes);
158
+ const contentTypeSchemaAttributesKeys = Object.keys(sanitizedContentTypeSchemaAttributes);
159
+ const uniqueToContentType = fp.difference(contentTypeSchemaAttributesKeys, versionSchemaKeys);
160
+ const added = reduceDifferenceToAttributesObject(
161
+ uniqueToContentType,
162
+ sanitizedContentTypeSchemaAttributes
163
+ );
164
+ const uniqueToVersion = fp.difference(versionSchemaKeys, contentTypeSchemaAttributesKeys);
165
+ const removed = reduceDifferenceToAttributesObject(uniqueToVersion, versionSchemaAttributes);
166
+ return { added, removed };
167
+ };
168
+ const getRelationRestoreValue = async (versionRelationData, attribute) => {
169
+ if (Array.isArray(versionRelationData)) {
170
+ if (versionRelationData.length === 0)
171
+ return versionRelationData;
172
+ const existingAndMissingRelations = await Promise.all(
173
+ versionRelationData.map((relation) => {
174
+ return strapi2.documents(attribute.target).findOne({
175
+ documentId: relation.documentId,
176
+ locale: relation.locale || void 0
177
+ });
178
+ })
179
+ );
180
+ return existingAndMissingRelations.filter(
181
+ (relation) => relation !== null
182
+ );
183
+ }
184
+ return strapi2.documents(attribute.target).findOne({
185
+ documentId: versionRelationData.documentId,
186
+ locale: versionRelationData.locale || void 0
187
+ });
188
+ };
189
+ const getMediaRestoreValue = async (versionRelationData, attribute) => {
190
+ if (attribute.multiple) {
191
+ const existingAndMissingMedias = await Promise.all(
192
+ // @ts-expect-error Fix the type definitions so this isn't any
193
+ versionRelationData.map((media) => {
194
+ return strapi2.db.query("plugin::upload.file").findOne({ where: { id: media.id } });
195
+ })
196
+ );
197
+ return existingAndMissingMedias.filter((media) => media != null);
198
+ }
199
+ return strapi2.db.query("plugin::upload.file").findOne({ where: { id: versionRelationData.id } });
200
+ };
201
+ const localesService = strapi2.plugin("i18n")?.service("locales");
202
+ const getDefaultLocale = async () => localesService ? localesService.getDefaultLocale() : null;
203
+ const getLocaleDictionary = async () => {
204
+ if (!localesService)
205
+ return {};
206
+ const locales = await localesService.find() || [];
207
+ return locales.reduce(
208
+ (acc, locale) => {
209
+ acc[locale.code] = { name: locale.name, code: locale.code };
210
+ return acc;
211
+ },
212
+ {}
213
+ );
214
+ };
215
+ const getRetentionDays = () => {
216
+ const featureConfig = strapi2.ee.features.get("cms-content-history");
217
+ const licenseRetentionDays = typeof featureConfig === "object" && featureConfig?.options.retentionDays;
218
+ const userRetentionDays = strapi2.config.get("admin.history.retentionDays");
219
+ if (userRetentionDays && userRetentionDays < licenseRetentionDays) {
220
+ return userRetentionDays;
221
+ }
222
+ return Math.min(licenseRetentionDays, DEFAULT_RETENTION_DAYS);
223
+ };
224
+ const getVersionStatus = async (contentTypeUid, document) => {
225
+ const documentMetadataService = strapi2.plugin("content-manager").service("document-metadata");
226
+ const meta = await documentMetadataService.getMetadata(contentTypeUid, document);
227
+ return documentMetadataService.getStatus(document, meta.availableStatus);
228
+ };
229
+ const getDeepPopulate2 = (uid2) => {
230
+ const model = strapi2.getModel(uid2);
231
+ const attributes = Object.entries(model.attributes);
232
+ return attributes.reduce((acc, [attributeName, attribute]) => {
233
+ switch (attribute.type) {
234
+ case "relation": {
235
+ const isVisible2 = strapiUtils.contentTypes.isVisibleAttribute(model, attributeName);
236
+ if (isVisible2) {
237
+ acc[attributeName] = { fields: ["documentId", "locale", "publishedAt"] };
238
+ }
239
+ break;
240
+ }
241
+ case "media": {
242
+ acc[attributeName] = { fields: ["id"] };
243
+ break;
244
+ }
245
+ case "component": {
246
+ const populate = getDeepPopulate2(attribute.component);
247
+ acc[attributeName] = { populate };
248
+ break;
249
+ }
250
+ case "dynamiczone": {
251
+ const populatedComponents = (attribute.components || []).reduce(
252
+ (acc2, componentUID) => {
253
+ acc2[componentUID] = { populate: getDeepPopulate2(componentUID) };
254
+ return acc2;
255
+ },
256
+ {}
257
+ );
258
+ acc[attributeName] = { on: populatedComponents };
259
+ break;
260
+ }
261
+ }
262
+ return acc;
263
+ }, {});
264
+ };
265
+ const buildMediaResponse = async (values) => {
266
+ return values.slice(0, 25).reduce(
267
+ async (currentRelationDataPromise, entry) => {
268
+ const currentRelationData = await currentRelationDataPromise;
269
+ if (!entry) {
270
+ return currentRelationData;
271
+ }
272
+ const relatedEntry = await strapi2.db.query("plugin::upload.file").findOne({ where: { id: entry.id } });
273
+ if (relatedEntry) {
274
+ currentRelationData.results.push(relatedEntry);
275
+ } else {
276
+ currentRelationData.meta.missingCount += 1;
277
+ }
278
+ return currentRelationData;
279
+ },
280
+ Promise.resolve({
281
+ results: [],
282
+ meta: { missingCount: 0 }
283
+ })
284
+ );
285
+ };
286
+ const buildRelationReponse = async (values, attributeSchema) => {
287
+ return values.slice(0, 25).reduce(
288
+ async (currentRelationDataPromise, entry) => {
289
+ const currentRelationData = await currentRelationDataPromise;
290
+ if (!entry) {
291
+ return currentRelationData;
292
+ }
293
+ const relatedEntry = await strapi2.documents(attributeSchema.target).findOne({ documentId: entry.documentId, locale: entry.locale || void 0 });
294
+ if (relatedEntry) {
295
+ currentRelationData.results.push({
296
+ ...relatedEntry,
297
+ status: await getVersionStatus(attributeSchema.target, relatedEntry)
298
+ });
299
+ } else {
300
+ currentRelationData.meta.missingCount += 1;
301
+ }
302
+ return currentRelationData;
303
+ },
304
+ Promise.resolve({
305
+ results: [],
306
+ meta: { missingCount: 0 }
307
+ })
308
+ );
309
+ };
310
+ return {
311
+ getSchemaAttributesDiff,
312
+ getRelationRestoreValue,
313
+ getMediaRestoreValue,
314
+ getDefaultLocale,
315
+ getLocaleDictionary,
316
+ getRetentionDays,
317
+ getVersionStatus,
318
+ getDeepPopulate: getDeepPopulate2,
319
+ buildMediaResponse,
320
+ buildRelationReponse
321
+ };
322
+ };
323
+ const createHistoryService = ({ strapi: strapi2 }) => {
324
+ const query = strapi2.db.query(HISTORY_VERSION_UID);
325
+ const serviceUtils = createServiceUtils({ strapi: strapi2 });
326
+ return {
327
+ async createVersion(historyVersionData) {
328
+ await query.create({
329
+ data: {
330
+ ...historyVersionData,
331
+ createdAt: /* @__PURE__ */ new Date(),
332
+ createdBy: strapi2.requestContext.get()?.state?.user.id
333
+ }
334
+ });
335
+ },
336
+ async findVersionsPage(params) {
337
+ const locale = params.query.locale || await serviceUtils.getDefaultLocale();
338
+ const [{ results, pagination }, localeDictionary] = await Promise.all([
339
+ query.findPage({
340
+ ...params.query,
341
+ where: {
342
+ $and: [
343
+ { contentType: params.query.contentType },
344
+ ...params.query.documentId ? [{ relatedDocumentId: params.query.documentId }] : [],
345
+ ...locale ? [{ locale }] : []
346
+ ]
347
+ },
348
+ populate: ["createdBy"],
349
+ orderBy: [{ createdAt: "desc" }]
350
+ }),
351
+ serviceUtils.getLocaleDictionary()
352
+ ]);
353
+ const populateEntryRelations = async (entry) => {
354
+ const entryWithRelations = await Object.entries(entry.schema).reduce(
355
+ async (currentDataWithRelations, [attributeKey, attributeSchema]) => {
356
+ const attributeValue = entry.data[attributeKey];
357
+ const attributeValues = Array.isArray(attributeValue) ? attributeValue : [attributeValue];
358
+ if (attributeSchema.type === "media") {
359
+ const permissionChecker2 = getService$1("permission-checker").create({
360
+ userAbility: params.state.userAbility,
361
+ model: "plugin::upload.file"
362
+ });
363
+ const response = await serviceUtils.buildMediaResponse(attributeValues);
364
+ const sanitizedResults = await Promise.all(
365
+ response.results.map((media) => permissionChecker2.sanitizeOutput(media))
366
+ );
367
+ return {
368
+ ...await currentDataWithRelations,
369
+ [attributeKey]: {
370
+ results: sanitizedResults,
371
+ meta: response.meta
372
+ }
373
+ };
374
+ }
375
+ if (attributeSchema.type === "relation" && attributeSchema.relation !== "morphToOne" && attributeSchema.relation !== "morphToMany") {
376
+ if (attributeSchema.target === "admin::user") {
377
+ const adminUsers = await Promise.all(
378
+ attributeValues.map((userToPopulate) => {
379
+ if (userToPopulate == null) {
380
+ return null;
381
+ }
382
+ return strapi2.query("admin::user").findOne({ where: { id: userToPopulate.id } });
383
+ })
384
+ );
385
+ return {
386
+ ...await currentDataWithRelations,
387
+ /**
388
+ * Ideally we would return the same "{results: [], meta: {}}" shape, however,
389
+ * when sanitizing the data as a whole in the controller before sending to the client,
390
+ * the data for admin relation user is completely sanitized if we return an object here as opposed to an array.
391
+ */
392
+ [attributeKey]: adminUsers
393
+ };
394
+ }
395
+ const permissionChecker2 = getService$1("permission-checker").create({
396
+ userAbility: params.state.userAbility,
397
+ model: attributeSchema.target
398
+ });
399
+ const response = await serviceUtils.buildRelationReponse(
400
+ attributeValues,
401
+ attributeSchema
402
+ );
403
+ const sanitizedResults = await Promise.all(
404
+ response.results.map((media) => permissionChecker2.sanitizeOutput(media))
405
+ );
406
+ return {
407
+ ...await currentDataWithRelations,
408
+ [attributeKey]: {
409
+ results: sanitizedResults,
410
+ meta: response.meta
411
+ }
412
+ };
413
+ }
414
+ return currentDataWithRelations;
415
+ },
416
+ Promise.resolve(entry.data)
417
+ );
418
+ return entryWithRelations;
419
+ };
420
+ const formattedResults = await Promise.all(
421
+ results.map(async (result) => {
422
+ return {
423
+ ...result,
424
+ data: await populateEntryRelations(result),
425
+ meta: {
426
+ unknownAttributes: serviceUtils.getSchemaAttributesDiff(
427
+ result.schema,
428
+ strapi2.getModel(params.query.contentType).attributes
429
+ )
430
+ },
431
+ locale: result.locale ? localeDictionary[result.locale] : null
432
+ };
433
+ })
434
+ );
435
+ return {
436
+ results: formattedResults,
437
+ pagination
438
+ };
439
+ },
440
+ async restoreVersion(versionId) {
441
+ const version = await query.findOne({ where: { id: versionId } });
442
+ const contentTypeSchemaAttributes = strapi2.getModel(version.contentType).attributes;
443
+ const schemaDiff = serviceUtils.getSchemaAttributesDiff(
444
+ version.schema,
445
+ contentTypeSchemaAttributes
446
+ );
447
+ const dataWithoutAddedAttributes = Object.keys(schemaDiff.added).reduce(
448
+ (currentData, addedKey) => {
449
+ currentData[addedKey] = null;
450
+ return currentData;
451
+ },
452
+ // Clone to avoid mutating the original version data
453
+ structuredClone(version.data)
454
+ );
455
+ const sanitizedSchemaAttributes = fp.omit(
456
+ FIELDS_TO_IGNORE,
457
+ contentTypeSchemaAttributes
458
+ );
459
+ const reducer = strapiUtils.async.reduce(Object.entries(sanitizedSchemaAttributes));
460
+ const dataWithoutMissingRelations = await reducer(
461
+ async (previousRelationAttributes, [name, attribute]) => {
462
+ const versionRelationData = version.data[name];
463
+ if (!versionRelationData) {
464
+ return previousRelationAttributes;
465
+ }
466
+ if (attribute.type === "relation" && // TODO: handle polymorphic relations
467
+ attribute.relation !== "morphToOne" && attribute.relation !== "morphToMany") {
468
+ const data2 = await serviceUtils.getRelationRestoreValue(versionRelationData, attribute);
469
+ previousRelationAttributes[name] = data2;
470
+ }
471
+ if (attribute.type === "media") {
472
+ const data2 = await serviceUtils.getMediaRestoreValue(versionRelationData, attribute);
473
+ previousRelationAttributes[name] = data2;
474
+ }
475
+ return previousRelationAttributes;
476
+ },
477
+ // Clone to avoid mutating the original version data
478
+ structuredClone(dataWithoutAddedAttributes)
479
+ );
480
+ const data = fp.omit(["id", ...Object.keys(schemaDiff.removed)], dataWithoutMissingRelations);
481
+ const restoredDocument = await strapi2.documents(version.contentType).update({
482
+ documentId: version.relatedDocumentId,
483
+ locale: version.locale,
484
+ data
485
+ });
486
+ if (!restoredDocument) {
487
+ throw new strapiUtils.errors.ApplicationError("Failed to restore version");
488
+ }
489
+ return restoredDocument;
490
+ }
491
+ };
492
+ };
493
+ const createLifecyclesService = ({ strapi: strapi2 }) => {
494
+ const state = {
495
+ deleteExpiredJob: null,
496
+ isInitialized: false
497
+ };
498
+ const serviceUtils = createServiceUtils({ strapi: strapi2 });
499
+ return {
500
+ async bootstrap() {
501
+ if (state.isInitialized) {
502
+ return;
503
+ }
504
+ strapi2.documents.use(async (context, next) => {
505
+ if (!strapi2.requestContext.get()?.request.url.startsWith("/content-manager")) {
506
+ return next();
507
+ }
508
+ if (context.action !== "create" && context.action !== "update" && context.action !== "clone" && context.action !== "publish" && context.action !== "unpublish" && context.action !== "discardDraft") {
509
+ return next();
510
+ }
511
+ if (context.action === "update" && strapi2.requestContext.get()?.request.url.endsWith("/actions/publish")) {
512
+ return next();
513
+ }
514
+ const contentTypeUid = context.contentType.uid;
515
+ if (!contentTypeUid.startsWith("api::")) {
516
+ return next();
517
+ }
518
+ const result = await next();
519
+ const documentContext = {
520
+ documentId: context.action === "create" || context.action === "clone" ? result.documentId : context.params.documentId,
521
+ locale: context.params?.locale
522
+ };
523
+ const defaultLocale = await serviceUtils.getDefaultLocale();
524
+ const locale = documentContext.locale || defaultLocale;
525
+ if (Array.isArray(locale)) {
526
+ strapi2.log.warn(
527
+ "[Content manager history middleware]: An array of locales was provided, but only a single locale is supported for the findOne operation."
528
+ );
529
+ return next();
530
+ }
531
+ const document = await strapi2.documents(contentTypeUid).findOne({
532
+ documentId: documentContext.documentId,
533
+ locale,
534
+ populate: serviceUtils.getDeepPopulate(contentTypeUid)
535
+ });
536
+ const status = await serviceUtils.getVersionStatus(contentTypeUid, document);
537
+ const attributesSchema = strapi2.getModel(contentTypeUid).attributes;
538
+ const componentsSchemas = Object.keys(
539
+ attributesSchema
540
+ ).reduce((currentComponentSchemas, key) => {
541
+ const fieldSchema = attributesSchema[key];
542
+ if (fieldSchema.type === "component") {
543
+ const componentSchema = strapi2.getModel(fieldSchema.component).attributes;
544
+ return {
545
+ ...currentComponentSchemas,
546
+ [fieldSchema.component]: componentSchema
547
+ };
548
+ }
549
+ return currentComponentSchemas;
550
+ }, {});
551
+ await strapi2.db.transaction(async ({ onCommit }) => {
552
+ onCommit(() => {
553
+ getService(strapi2, "history").createVersion({
554
+ contentType: contentTypeUid,
555
+ data: fp.omit(FIELDS_TO_IGNORE, document),
556
+ schema: fp.omit(FIELDS_TO_IGNORE, attributesSchema),
557
+ componentsSchemas,
558
+ relatedDocumentId: documentContext.documentId,
559
+ locale,
560
+ status
561
+ });
562
+ });
563
+ });
564
+ return result;
565
+ });
566
+ state.deleteExpiredJob = nodeSchedule.scheduleJob("0 0 * * *", () => {
567
+ const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1e3;
568
+ const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
569
+ strapi2.db.query(HISTORY_VERSION_UID).deleteMany({
570
+ where: {
571
+ created_at: {
572
+ $lt: expirationDate.toISOString()
573
+ }
574
+ }
575
+ });
576
+ });
577
+ state.isInitialized = true;
578
+ },
579
+ async destroy() {
580
+ if (state.deleteExpiredJob) {
581
+ state.deleteExpiredJob.cancel();
582
+ }
583
+ }
584
+ };
585
+ };
586
+ const services$1 = {
587
+ history: createHistoryService,
588
+ lifecycles: createLifecyclesService
589
+ };
590
+ const info = { pluginName: "content-manager", type: "admin" };
591
+ const historyVersionRouter = {
592
+ type: "admin",
593
+ routes: [
594
+ {
595
+ method: "GET",
596
+ info,
597
+ path: "/history-versions",
598
+ handler: "history-version.findMany",
599
+ config: {
600
+ policies: ["admin::isAuthenticatedAdmin"]
601
+ }
602
+ },
603
+ {
604
+ method: "PUT",
605
+ info,
606
+ path: "/history-versions/:versionId/restore",
607
+ handler: "history-version.restoreVersion",
608
+ config: {
609
+ policies: ["admin::isAuthenticatedAdmin"]
610
+ }
611
+ }
612
+ ]
613
+ };
614
+ const routes$1 = {
615
+ "history-version": historyVersionRouter
616
+ };
617
+ const historyVersion = {
618
+ uid: HISTORY_VERSION_UID,
619
+ tableName: "strapi_history_versions",
620
+ singularName: "history-version",
621
+ attributes: {
622
+ id: {
623
+ type: "increments"
624
+ },
625
+ contentType: {
626
+ type: "string",
627
+ column: { notNullable: true }
628
+ },
629
+ relatedDocumentId: {
630
+ type: "string",
631
+ // TODO: notNullable should be true once history can record publish actions
632
+ column: { notNullable: false }
633
+ },
634
+ locale: {
635
+ type: "string"
636
+ },
637
+ status: {
638
+ type: "enumeration",
639
+ enum: ["draft", "published", "modified"]
640
+ },
641
+ data: {
642
+ type: "json"
643
+ },
644
+ schema: {
645
+ type: "json"
646
+ },
647
+ createdAt: {
648
+ type: "datetime",
649
+ default: () => /* @__PURE__ */ new Date()
650
+ },
651
+ // FIXME: joinTable should be optional
652
+ // @ts-expect-error database model is not yet updated to support useJoinTable
653
+ createdBy: {
654
+ type: "relation",
655
+ relation: "oneToOne",
656
+ target: "admin::user",
657
+ useJoinTable: false
658
+ }
659
+ }
660
+ };
661
+ const getFeature = () => {
662
+ if (strapi.ee.features.isEnabled("cms-content-history")) {
663
+ return {
664
+ register({ strapi: strapi2 }) {
665
+ strapi2.get("models").add(historyVersion);
666
+ },
667
+ bootstrap({ strapi: strapi2 }) {
668
+ getService(strapi2, "lifecycles").bootstrap();
669
+ },
670
+ destroy({ strapi: strapi2 }) {
671
+ getService(strapi2, "lifecycles").destroy();
672
+ },
673
+ controllers: controllers$1,
674
+ services: services$1,
675
+ routes: routes$1
676
+ };
677
+ }
678
+ return {
679
+ register({ strapi: strapi2 }) {
680
+ strapi2.get("models").add(historyVersion);
681
+ }
682
+ };
683
+ };
684
+ const history = getFeature();
685
+ const register = async ({ strapi: strapi2 }) => {
686
+ await history.register?.({ strapi: strapi2 });
687
+ };
688
+ const ALLOWED_WEBHOOK_EVENTS = {
689
+ ENTRY_PUBLISH: "entry.publish",
690
+ ENTRY_UNPUBLISH: "entry.unpublish"
691
+ };
692
+ const bootstrap = async () => {
693
+ Object.entries(ALLOWED_WEBHOOK_EVENTS).forEach(([key, value]) => {
694
+ strapi.get("webhookStore").addAllowedEvent(key, value);
695
+ });
696
+ getService$1("field-sizes").setCustomFieldInputSizes();
697
+ await getService$1("components").syncConfigurations();
698
+ await getService$1("content-types").syncConfigurations();
699
+ await getService$1("permission").registerPermissions();
700
+ await history.bootstrap?.({ strapi });
701
+ };
702
+ const destroy = async ({ strapi: strapi2 }) => {
703
+ await history.destroy?.({ strapi: strapi2 });
704
+ };
705
+ const routing = async (ctx, next) => {
706
+ const { model } = ctx.params;
707
+ const ct = strapi.contentTypes[model];
708
+ if (!ct) {
709
+ return ctx.send({ error: "contentType.notFound" }, 404);
710
+ }
711
+ let controllers2;
712
+ if (!ct.plugin || ct.plugin === "admin") {
713
+ controllers2 = strapi.admin.controllers;
714
+ } else {
715
+ controllers2 = strapi.plugin(ct.plugin).controllers;
716
+ }
717
+ const { route } = ctx.state;
718
+ if (typeof route.handler !== "string") {
719
+ return next();
720
+ }
721
+ const [, action] = route.handler.split(".");
722
+ let actionConfig;
723
+ if (!ct.plugin || ct.plugin === "admin") {
724
+ actionConfig = strapi.config.get(`admin.layout.${ct.modelName}.actions.${action}`);
725
+ } else {
726
+ actionConfig = strapi.plugin(ct.plugin).config(`layout.${ct.modelName}.actions.${action}`);
727
+ }
728
+ if (!isNil__default.default(actionConfig)) {
729
+ const [controller, action2] = actionConfig.split(".");
730
+ if (controller && action2) {
731
+ return controllers2[controller.toLowerCase()][action2](ctx, next);
732
+ }
733
+ }
734
+ await next();
735
+ };
736
+ const admin = {
737
+ type: "admin",
738
+ routes: [
739
+ {
740
+ method: "GET",
741
+ path: "/init",
742
+ handler: "init.getInitData",
743
+ config: {
744
+ policies: []
745
+ }
746
+ },
747
+ {
748
+ method: "GET",
749
+ path: "/content-types",
750
+ handler: "content-types.findContentTypes",
751
+ config: {
752
+ policies: []
753
+ }
754
+ },
755
+ {
756
+ method: "GET",
757
+ path: "/content-types-settings",
758
+ handler: "content-types.findContentTypesSettings",
759
+ config: {
760
+ policies: []
761
+ }
762
+ },
763
+ {
764
+ method: "GET",
765
+ path: "/content-types/:uid/configuration",
766
+ handler: "content-types.findContentTypeConfiguration",
767
+ config: {
768
+ policies: []
769
+ }
770
+ },
771
+ {
772
+ method: "PUT",
773
+ path: "/content-types/:uid/configuration",
774
+ handler: "content-types.updateContentTypeConfiguration",
775
+ config: {
776
+ policies: ["admin::isAuthenticatedAdmin"]
777
+ }
778
+ },
779
+ {
780
+ method: "GET",
781
+ path: "/components",
782
+ handler: "components.findComponents",
783
+ config: {
784
+ policies: []
785
+ }
786
+ },
787
+ {
788
+ method: "GET",
789
+ path: "/components/:uid/configuration",
790
+ handler: "components.findComponentConfiguration",
791
+ config: {
792
+ policies: []
793
+ }
794
+ },
795
+ {
796
+ method: "PUT",
797
+ path: "/components/:uid/configuration",
798
+ handler: "components.updateComponentConfiguration",
799
+ config: {
800
+ policies: []
801
+ }
802
+ },
803
+ {
804
+ method: "POST",
805
+ path: "/uid/generate",
806
+ handler: "uid.generateUID",
807
+ config: {
808
+ policies: []
809
+ }
810
+ },
811
+ {
812
+ method: "POST",
813
+ path: "/uid/check-availability",
814
+ handler: "uid.checkUIDAvailability",
815
+ config: {
816
+ policies: []
817
+ }
818
+ },
819
+ {
820
+ method: "GET",
821
+ path: "/relations/:model/:targetField",
822
+ handler: "relations.findAvailable",
823
+ config: {
824
+ policies: ["admin::isAuthenticatedAdmin"]
825
+ }
826
+ },
827
+ {
828
+ method: "GET",
829
+ path: "/relations/:model/:id/:targetField",
830
+ handler: "relations.findExisting",
831
+ config: {
832
+ policies: ["admin::isAuthenticatedAdmin"]
833
+ }
834
+ },
835
+ {
836
+ method: "GET",
837
+ path: "/single-types/:model",
838
+ handler: "single-types.find",
839
+ config: {
840
+ middlewares: [routing],
841
+ policies: [
842
+ "admin::isAuthenticatedAdmin",
843
+ {
844
+ name: "plugin::content-manager.hasPermissions",
845
+ config: { actions: ["plugin::content-manager.explorer.read"] }
846
+ }
847
+ ]
848
+ }
849
+ },
850
+ {
851
+ method: "PUT",
852
+ path: "/single-types/:model",
853
+ handler: "single-types.createOrUpdate",
854
+ config: {
855
+ middlewares: [routing],
856
+ policies: [
857
+ "admin::isAuthenticatedAdmin",
858
+ {
859
+ name: "plugin::content-manager.hasPermissions",
860
+ config: {
861
+ actions: [
862
+ "plugin::content-manager.explorer.create",
863
+ "plugin::content-manager.explorer.update"
864
+ ],
865
+ hasAtLeastOne: true
866
+ }
867
+ }
868
+ ]
869
+ }
870
+ },
871
+ {
872
+ method: "DELETE",
873
+ path: "/single-types/:model",
874
+ handler: "single-types.delete",
875
+ config: {
876
+ middlewares: [routing],
877
+ policies: [
878
+ "admin::isAuthenticatedAdmin",
879
+ {
880
+ name: "plugin::content-manager.hasPermissions",
881
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
882
+ }
883
+ ]
884
+ }
885
+ },
886
+ {
887
+ method: "POST",
888
+ path: "/single-types/:model/actions/publish",
889
+ handler: "single-types.publish",
890
+ config: {
891
+ middlewares: [routing],
892
+ policies: [
893
+ "admin::isAuthenticatedAdmin",
894
+ {
895
+ name: "plugin::content-manager.hasPermissions",
896
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
897
+ }
898
+ ]
899
+ }
900
+ },
901
+ {
902
+ method: "POST",
903
+ path: "/single-types/:model/actions/unpublish",
904
+ handler: "single-types.unpublish",
905
+ config: {
906
+ middlewares: [routing],
907
+ policies: [
908
+ "admin::isAuthenticatedAdmin",
909
+ {
910
+ name: "plugin::content-manager.hasPermissions",
911
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
912
+ }
913
+ ]
914
+ }
915
+ },
916
+ {
917
+ method: "POST",
918
+ path: "/single-types/:model/actions/discard",
919
+ handler: "single-types.discard",
920
+ config: {
921
+ middlewares: [routing],
922
+ policies: [
923
+ "admin::isAuthenticatedAdmin",
924
+ {
925
+ name: "plugin::content-manager.hasPermissions",
926
+ config: { actions: ["plugin::content-manager.explorer.update"] }
927
+ }
928
+ ]
929
+ }
930
+ },
931
+ {
932
+ method: "GET",
933
+ path: "/single-types/:model/actions/countDraftRelations",
934
+ handler: "single-types.countDraftRelations",
935
+ config: {
936
+ middlewares: [routing],
937
+ policies: [
938
+ "admin::isAuthenticatedAdmin",
939
+ {
940
+ name: "plugin::content-manager.hasPermissions",
941
+ config: { actions: ["plugin::content-manager.explorer.read"] }
942
+ }
943
+ ]
944
+ }
945
+ },
946
+ {
947
+ method: "GET",
948
+ path: "/collection-types/:model",
949
+ handler: "collection-types.find",
950
+ config: {
951
+ middlewares: [routing],
952
+ policies: [
953
+ "admin::isAuthenticatedAdmin",
954
+ {
955
+ name: "plugin::content-manager.hasPermissions",
956
+ config: { actions: ["plugin::content-manager.explorer.read"] }
957
+ }
958
+ ]
959
+ }
960
+ },
961
+ {
962
+ method: "POST",
963
+ path: "/collection-types/:model",
964
+ handler: "collection-types.create",
965
+ config: {
966
+ middlewares: [routing],
967
+ policies: [
968
+ "admin::isAuthenticatedAdmin",
969
+ {
970
+ name: "plugin::content-manager.hasPermissions",
971
+ config: { actions: ["plugin::content-manager.explorer.create"] }
972
+ }
973
+ ]
974
+ }
975
+ },
976
+ {
977
+ method: "POST",
978
+ path: "/collection-types/:model/clone/:sourceId",
979
+ handler: "collection-types.clone",
980
+ config: {
981
+ middlewares: [routing],
982
+ policies: [
983
+ "admin::isAuthenticatedAdmin",
984
+ {
985
+ name: "plugin::content-manager.hasPermissions",
986
+ config: { actions: ["plugin::content-manager.explorer.create"] }
987
+ }
988
+ ]
989
+ }
990
+ },
991
+ {
992
+ method: "POST",
993
+ path: "/collection-types/:model/auto-clone/:sourceId",
994
+ handler: "collection-types.autoClone",
995
+ config: {
996
+ middlewares: [routing],
997
+ policies: [
998
+ "admin::isAuthenticatedAdmin",
999
+ {
1000
+ name: "plugin::content-manager.hasPermissions",
1001
+ config: { actions: ["plugin::content-manager.explorer.create"] }
1002
+ }
1003
+ ]
1004
+ }
1005
+ },
1006
+ {
1007
+ method: "GET",
1008
+ path: "/collection-types/:model/:id",
1009
+ handler: "collection-types.findOne",
1010
+ config: {
1011
+ middlewares: [routing],
1012
+ policies: [
1013
+ "admin::isAuthenticatedAdmin",
1014
+ {
1015
+ name: "plugin::content-manager.hasPermissions",
1016
+ config: { actions: ["plugin::content-manager.explorer.read"] }
1017
+ }
1018
+ ]
1019
+ }
1020
+ },
1021
+ {
1022
+ method: "PUT",
1023
+ path: "/collection-types/:model/:id",
1024
+ handler: "collection-types.update",
1025
+ config: {
1026
+ middlewares: [routing],
1027
+ policies: [
1028
+ "admin::isAuthenticatedAdmin",
1029
+ {
1030
+ name: "plugin::content-manager.hasPermissions",
1031
+ config: { actions: ["plugin::content-manager.explorer.update"] }
1032
+ }
1033
+ ]
1034
+ }
1035
+ },
1036
+ {
1037
+ method: "DELETE",
1038
+ path: "/collection-types/:model/:id",
1039
+ handler: "collection-types.delete",
1040
+ config: {
1041
+ middlewares: [routing],
1042
+ policies: [
1043
+ "admin::isAuthenticatedAdmin",
1044
+ {
1045
+ name: "plugin::content-manager.hasPermissions",
1046
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
1047
+ }
1048
+ ]
1049
+ }
1050
+ },
1051
+ {
1052
+ method: "POST",
1053
+ path: "/collection-types/:model/actions/publish",
1054
+ handler: "collection-types.publish",
1055
+ config: {
1056
+ middlewares: [routing],
1057
+ policies: [
1058
+ "admin::isAuthenticatedAdmin",
1059
+ {
1060
+ name: "plugin::content-manager.hasPermissions",
1061
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1062
+ }
1063
+ ]
1064
+ }
1065
+ },
1066
+ {
1067
+ method: "POST",
1068
+ path: "/collection-types/:model/:id/actions/publish",
1069
+ handler: "collection-types.publish",
1070
+ config: {
1071
+ middlewares: [routing],
1072
+ policies: [
1073
+ "admin::isAuthenticatedAdmin",
1074
+ {
1075
+ name: "plugin::content-manager.hasPermissions",
1076
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1077
+ }
1078
+ ]
1079
+ }
1080
+ },
1081
+ {
1082
+ method: "POST",
1083
+ path: "/collection-types/:model/:id/actions/unpublish",
1084
+ handler: "collection-types.unpublish",
1085
+ config: {
1086
+ middlewares: [routing],
1087
+ policies: [
1088
+ "admin::isAuthenticatedAdmin",
1089
+ {
1090
+ name: "plugin::content-manager.hasPermissions",
1091
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1092
+ }
1093
+ ]
1094
+ }
1095
+ },
1096
+ {
1097
+ method: "POST",
1098
+ path: "/collection-types/:model/:id/actions/discard",
1099
+ handler: "collection-types.discard",
1100
+ config: {
1101
+ middlewares: [routing],
1102
+ policies: [
1103
+ "admin::isAuthenticatedAdmin",
1104
+ {
1105
+ name: "plugin::content-manager.hasPermissions",
1106
+ config: { actions: ["plugin::content-manager.explorer.update"] }
1107
+ }
1108
+ ]
1109
+ }
1110
+ },
1111
+ {
1112
+ method: "POST",
1113
+ path: "/collection-types/:model/actions/bulkDelete",
1114
+ handler: "collection-types.bulkDelete",
1115
+ config: {
1116
+ middlewares: [routing],
1117
+ policies: [
1118
+ "admin::isAuthenticatedAdmin",
1119
+ {
1120
+ name: "plugin::content-manager.hasPermissions",
1121
+ config: { actions: ["plugin::content-manager.explorer.delete"] }
1122
+ }
1123
+ ]
1124
+ }
1125
+ },
1126
+ {
1127
+ method: "POST",
1128
+ path: "/collection-types/:model/actions/bulkPublish",
1129
+ handler: "collection-types.bulkPublish",
1130
+ config: {
1131
+ middlewares: [routing],
1132
+ policies: [
1133
+ "admin::isAuthenticatedAdmin",
1134
+ {
1135
+ name: "plugin::content-manager.hasPermissions",
1136
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1137
+ }
1138
+ ]
1139
+ }
1140
+ },
1141
+ {
1142
+ method: "POST",
1143
+ path: "/collection-types/:model/actions/bulkUnpublish",
1144
+ handler: "collection-types.bulkUnpublish",
1145
+ config: {
1146
+ middlewares: [routing],
1147
+ policies: [
1148
+ "admin::isAuthenticatedAdmin",
1149
+ {
1150
+ name: "plugin::content-manager.hasPermissions",
1151
+ config: { actions: ["plugin::content-manager.explorer.publish"] }
1152
+ }
1153
+ ]
1154
+ }
1155
+ },
1156
+ {
1157
+ method: "GET",
1158
+ path: "/collection-types/:model/:id/actions/countDraftRelations",
1159
+ handler: "collection-types.countDraftRelations",
1160
+ config: {
1161
+ middlewares: [routing],
1162
+ policies: [
1163
+ "admin::isAuthenticatedAdmin",
1164
+ {
1165
+ name: "plugin::content-manager.hasPermissions",
1166
+ config: { actions: ["plugin::content-manager.explorer.read"] }
1167
+ }
1168
+ ]
1169
+ }
1170
+ },
1171
+ {
1172
+ method: "GET",
1173
+ path: "/collection-types/:model/actions/countManyEntriesDraftRelations",
1174
+ handler: "collection-types.countManyEntriesDraftRelations",
1175
+ config: {
1176
+ middlewares: [routing],
1177
+ policies: [
1178
+ "admin::isAuthenticatedAdmin",
1179
+ {
1180
+ name: "plugin::content-manager.hasPermissions",
1181
+ config: { actions: ["plugin::content-manager.explorer.read"] }
1182
+ }
1183
+ ]
1184
+ }
1185
+ }
1186
+ ]
1187
+ };
1188
+ const routes = {
1189
+ admin,
1190
+ ...history.routes ? history.routes : {}
1191
+ };
1192
+ const hasPermissionsSchema = strapiUtils.yup.object({
1193
+ actions: strapiUtils.yup.array().of(strapiUtils.yup.string()),
1194
+ hasAtLeastOne: strapiUtils.yup.boolean()
1195
+ });
1196
+ const validateHasPermissionsInput = strapiUtils.validateYupSchemaSync(hasPermissionsSchema);
1197
+ const { createPolicy } = strapiUtils.policy;
1198
+ const hasPermissions = createPolicy({
1199
+ name: "plugin::content-manager.hasPermissions",
1200
+ validator: validateHasPermissionsInput,
1201
+ handler(ctx, config = {}) {
1202
+ const { actions = [], hasAtLeastOne = false } = config;
1203
+ const { userAbility } = ctx.state;
1204
+ const { model } = ctx.params;
1205
+ const isAuthorized = hasAtLeastOne ? actions.some((action) => userAbility.can(action, model)) : actions.every((action) => userAbility.can(action, model));
1206
+ return isAuthorized;
1207
+ }
1208
+ });
1209
+ const policies = {
1210
+ hasPermissions
1211
+ };
1212
+ const { getNonVisibleAttributes, getWritableAttributes } = strapiUtils.contentTypes;
1213
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$3, CREATED_BY_ATTRIBUTE, UPDATED_BY_ATTRIBUTE } = strapiUtils.contentTypes.constants;
1214
+ const NON_SORTABLES = ["component", "json", "media", "richtext", "dynamiczone", "blocks"];
1215
+ const SORTABLE_RELATIONS = ["oneToOne", "manyToOne"];
1216
+ const NON_LISTABLES = ["json", "password", "richtext", "dynamiczone", "blocks"];
1217
+ const LISTABLE_RELATIONS = ["oneToOne", "oneToMany", "manyToOne", "manyToMany"];
1218
+ const isHidden = (schema, name) => {
1219
+ if (!___default.default.has(schema.attributes, name)) {
1220
+ return false;
1221
+ }
1222
+ const isHidden2 = ___default.default.get(schema, ["config", "attributes", name, "hidden"], false);
1223
+ if (isHidden2 === true) {
1224
+ return true;
1225
+ }
1226
+ return false;
1227
+ };
1228
+ const isListable = (schema, name) => {
1229
+ if (!___default.default.has(schema.attributes, name)) {
1230
+ return false;
1231
+ }
1232
+ if (isHidden(schema, name)) {
1233
+ return false;
1234
+ }
1235
+ const attribute = schema.attributes[name];
1236
+ if (NON_LISTABLES.includes(attribute.type)) {
1237
+ return false;
1238
+ }
1239
+ if (isRelation$1(attribute) && !LISTABLE_RELATIONS.includes(attribute.relationType)) {
1240
+ return false;
1241
+ }
1242
+ return true;
1243
+ };
1244
+ const isSortable = (schema, name) => {
1245
+ if (!___default.default.has(schema.attributes, name)) {
1246
+ return false;
1247
+ }
1248
+ if (schema.modelType === "component" && name === "id")
1249
+ return false;
1250
+ const attribute = schema.attributes[name];
1251
+ if (NON_SORTABLES.includes(attribute.type)) {
1252
+ return false;
1253
+ }
1254
+ if (isRelation$1(attribute) && !SORTABLE_RELATIONS.includes(attribute.relationType)) {
1255
+ return false;
1256
+ }
1257
+ return true;
1258
+ };
1259
+ const isSearchable = (schema, name) => {
1260
+ return isSortable(schema, name);
1261
+ };
1262
+ const isVisible$1 = (schema, name) => {
1263
+ if (!___default.default.has(schema.attributes, name)) {
1264
+ return false;
1265
+ }
1266
+ if (isHidden(schema, name)) {
1267
+ return false;
1268
+ }
1269
+ if (isTimestamp(schema, name) || name === "id") {
1270
+ return false;
1271
+ }
1272
+ if (isPublicationField(name)) {
1273
+ return false;
1274
+ }
1275
+ if (isCreatorField(schema, name)) {
1276
+ return false;
1277
+ }
1278
+ return true;
1279
+ };
1280
+ const isPublicationField = (name) => PUBLISHED_AT_ATTRIBUTE$3 === name;
1281
+ const isTimestamp = (schema, name) => {
1282
+ if (!___default.default.has(schema.attributes, name)) {
1283
+ return false;
1284
+ }
1285
+ const timestamps = strapiUtils.contentTypes.getTimestamps(schema);
1286
+ if (!timestamps || !Array.isArray(timestamps)) {
1287
+ return false;
1288
+ }
1289
+ if (timestamps.includes(name)) {
1290
+ return true;
1291
+ }
1292
+ };
1293
+ const isCreatorField = (schema, name) => {
1294
+ if (!___default.default.has(schema.attributes, name)) {
1295
+ return false;
1296
+ }
1297
+ const creatorFields = strapiUtils.contentTypes.getCreatorFields(schema);
1298
+ if (!creatorFields || !Array.isArray(creatorFields)) {
1299
+ return false;
1300
+ }
1301
+ if (creatorFields.includes(name)) {
1302
+ return true;
1303
+ }
1304
+ };
1305
+ const isRelation$1 = (attribute) => attribute.type === "relation";
1306
+ const hasRelationAttribute = (schema, name) => {
1307
+ if (!___default.default.has(schema.attributes, name)) {
1308
+ return false;
1309
+ }
1310
+ if (isHidden(schema, name)) {
1311
+ return false;
1312
+ }
1313
+ if (!isVisible$1(schema, name)) {
1314
+ return false;
1315
+ }
1316
+ return isRelation$1(schema.attributes[name]);
1317
+ };
1318
+ const hasEditableAttribute = (schema, name) => {
1319
+ if (!___default.default.has(schema.attributes, name)) {
1320
+ return false;
1321
+ }
1322
+ if (isHidden(schema, name)) {
1323
+ return false;
1324
+ }
1325
+ if (!isVisible$1(schema, name)) {
1326
+ return false;
1327
+ }
1328
+ return true;
1329
+ };
1330
+ const findFirstStringAttribute = (schema) => {
1331
+ return Object.keys(schema.attributes || {}).find((key) => {
1332
+ const { type } = schema.attributes[key];
1333
+ return type === "string" && key !== "id";
1334
+ });
1335
+ };
1336
+ const getDefaultMainField = (schema) => findFirstStringAttribute(schema) || "id";
1337
+ const getSortableAttributes = (schema) => {
1338
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1339
+ const model = strapi.getModel(schema.uid);
1340
+ const nonVisibleWritableAttributes = fp.intersection(
1341
+ getNonVisibleAttributes(model),
1342
+ getWritableAttributes(model)
1343
+ );
1344
+ return [
1345
+ "id",
1346
+ ...validAttributes,
1347
+ ...nonVisibleWritableAttributes,
1348
+ CREATED_BY_ATTRIBUTE,
1349
+ UPDATED_BY_ATTRIBUTE
1350
+ ];
1351
+ };
1352
+ const DEFAULT_SETTINGS = {
1353
+ bulkable: true,
1354
+ filterable: true,
1355
+ searchable: true,
1356
+ pageSize: 10
1357
+ };
1358
+ const settingsFields = [
1359
+ "searchable",
1360
+ "filterable",
1361
+ "bulkable",
1362
+ "pageSize",
1363
+ "mainField",
1364
+ "defaultSortBy",
1365
+ "defaultSortOrder"
1366
+ ];
1367
+ const getModelSettings = fp.pipe([fp.propOr({}, "config.settings"), fp.pick(settingsFields)]);
1368
+ async function isValidDefaultSort(schema, value) {
1369
+ const parsedValue = qs__default.default.parse(value);
1370
+ const omitNonSortableAttributes = ({ schema: schema2, key }, { remove }) => {
1371
+ const sortableAttributes = getSortableAttributes(schema2);
1372
+ if (!sortableAttributes.includes(key)) {
1373
+ remove(key);
1374
+ }
1375
+ };
1376
+ const sanitizedValue = await strapiUtils.traverse.traverseQuerySort(
1377
+ omitNonSortableAttributes,
1378
+ { schema, getModel: strapi.getModel.bind(strapi) },
1379
+ parsedValue
1380
+ );
1381
+ return fp.isEqual(parsedValue, sanitizedValue);
1382
+ }
1383
+ const createDefaultSettings = async (schema) => {
1384
+ const defaultField = getDefaultMainField(schema);
1385
+ return {
1386
+ ...DEFAULT_SETTINGS,
1387
+ mainField: defaultField,
1388
+ defaultSortBy: defaultField,
1389
+ defaultSortOrder: "ASC",
1390
+ ...getModelSettings(schema)
1391
+ };
1392
+ };
1393
+ const syncSettings = async (configuration, schema) => {
1394
+ if (fp.isEmpty(configuration.settings))
1395
+ return createDefaultSettings(schema);
1396
+ const defaultField = getDefaultMainField(schema);
1397
+ const { mainField = defaultField, defaultSortBy = defaultField } = configuration.settings || {};
1398
+ return {
1399
+ ...configuration.settings,
1400
+ mainField: isSortable(schema, mainField) ? mainField : defaultField,
1401
+ defaultSortBy: await isValidDefaultSort(schema, defaultSortBy) ? defaultSortBy : defaultField
1402
+ };
1403
+ };
1404
+ const createModelConfigurationSchema = (schema, opts = {}) => strapiUtils.yup.object().shape({
1405
+ settings: createSettingsSchema(schema).default(null).nullable(),
1406
+ metadatas: createMetadasSchema(schema).default(null).nullable(),
1407
+ layouts: createLayoutsSchema(schema, opts).default(null).nullable(),
1408
+ options: strapiUtils.yup.object().optional()
1409
+ }).noUnknown();
1410
+ const createSettingsSchema = (schema) => {
1411
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1412
+ return strapiUtils.yup.object().shape({
1413
+ bulkable: strapiUtils.yup.boolean().required(),
1414
+ filterable: strapiUtils.yup.boolean().required(),
1415
+ pageSize: strapiUtils.yup.number().integer().min(10).max(100).required(),
1416
+ searchable: strapiUtils.yup.boolean().required(),
1417
+ // should be reset when the type changes
1418
+ mainField: strapiUtils.yup.string().oneOf(validAttributes.concat("id")).default("id"),
1419
+ // should be reset when the type changes
1420
+ defaultSortBy: strapiUtils.yup.string().test(
1421
+ "is-valid-sort-attribute",
1422
+ "${path} is not a valid sort attribute",
1423
+ async (value) => isValidDefaultSort(schema, value)
1424
+ ).default("id"),
1425
+ defaultSortOrder: strapiUtils.yup.string().oneOf(["ASC", "DESC"]).default("ASC")
1426
+ }).noUnknown();
1427
+ };
1428
+ const createMetadasSchema = (schema) => {
1429
+ return strapiUtils.yup.object().shape(
1430
+ Object.keys(schema.attributes).reduce((acc, key) => {
1431
+ acc[key] = strapiUtils.yup.object().shape({
1432
+ edit: strapiUtils.yup.object().shape({
1433
+ label: strapiUtils.yup.string(),
1434
+ description: strapiUtils.yup.string(),
1435
+ placeholder: strapiUtils.yup.string(),
1436
+ editable: strapiUtils.yup.boolean(),
1437
+ visible: strapiUtils.yup.boolean(),
1438
+ mainField: strapiUtils.yup.lazy((value) => {
1439
+ if (!value) {
1440
+ return strapiUtils.yup.string();
1441
+ }
1442
+ const targetSchema = getService$1("content-types").findContentType(
1443
+ schema.attributes[key].targetModel
1444
+ );
1445
+ if (!targetSchema) {
1446
+ return strapiUtils.yup.string();
1447
+ }
1448
+ const validAttributes = Object.keys(targetSchema.attributes).filter(
1449
+ (key2) => isListable(targetSchema, key2)
1450
+ );
1451
+ return strapiUtils.yup.string().oneOf(validAttributes.concat("id")).default("id");
1452
+ })
1453
+ }).noUnknown().required(),
1454
+ list: strapiUtils.yup.object().shape({
1455
+ label: strapiUtils.yup.string(),
1456
+ searchable: strapiUtils.yup.boolean(),
1457
+ sortable: strapiUtils.yup.boolean()
1458
+ }).noUnknown().required()
1459
+ }).noUnknown();
1460
+ return acc;
1461
+ }, {})
1462
+ );
1463
+ };
1464
+ const createArrayTest = ({ allowUndefined = false } = {}) => ({
1465
+ name: "isArray",
1466
+ message: "${path} is required and must be an array",
1467
+ test: (val) => allowUndefined === true && val === void 0 ? true : Array.isArray(val)
1468
+ });
1469
+ const createLayoutsSchema = (schema, opts = {}) => {
1470
+ const validAttributes = Object.keys(schema.attributes).filter((key) => isListable(schema, key));
1471
+ const editAttributes = Object.keys(schema.attributes).filter(
1472
+ (key) => hasEditableAttribute(schema, key)
1473
+ );
1474
+ return strapiUtils.yup.object().shape({
1475
+ edit: strapiUtils.yup.array().of(
1476
+ strapiUtils.yup.array().of(
1477
+ strapiUtils.yup.object().shape({
1478
+ name: strapiUtils.yup.string().oneOf(editAttributes).required(),
1479
+ size: strapiUtils.yup.number().integer().positive().required()
1480
+ }).noUnknown()
1481
+ )
1482
+ ).test(createArrayTest(opts)),
1483
+ list: strapiUtils.yup.array().of(strapiUtils.yup.string().oneOf(validAttributes)).test(createArrayTest(opts))
1484
+ });
1485
+ };
1486
+ const { PaginationError, ValidationError } = strapiUtils.errors;
1487
+ const TYPES = ["singleType", "collectionType"];
1488
+ const kindSchema = strapiUtils.yup.string().oneOf(TYPES).nullable();
1489
+ const bulkActionInputSchema = strapiUtils.yup.object({
1490
+ documentIds: strapiUtils.yup.array().of(strapiUtils.yup.strapiID()).min(1).required()
1491
+ }).required();
1492
+ const generateUIDInputSchema = strapiUtils.yup.object({
1493
+ contentTypeUID: strapiUtils.yup.string().required(),
1494
+ field: strapiUtils.yup.string().required(),
1495
+ data: strapiUtils.yup.object().required()
1496
+ });
1497
+ const checkUIDAvailabilityInputSchema = strapiUtils.yup.object({
1498
+ contentTypeUID: strapiUtils.yup.string().required(),
1499
+ field: strapiUtils.yup.string().required(),
1500
+ value: strapiUtils.yup.string().matches(/^[A-Za-z0-9-_.~]*$/).required()
1501
+ });
1502
+ const validateUIDField = (contentTypeUID, field) => {
1503
+ const model = strapi.contentTypes[contentTypeUID];
1504
+ if (!model) {
1505
+ throw new ValidationError("ContentType not found");
1506
+ }
1507
+ if (!___default.default.has(model, ["attributes", field]) || ___default.default.get(model, ["attributes", field, "type"]) !== "uid") {
1508
+ throw new ValidationError(`${field} must be a valid \`uid\` attribute`);
1509
+ }
1510
+ };
1511
+ const validateKind = strapiUtils.validateYupSchema(kindSchema);
1512
+ const validateBulkActionInput = strapiUtils.validateYupSchema(bulkActionInputSchema);
1513
+ const validateGenerateUIDInput = strapiUtils.validateYupSchema(generateUIDInputSchema);
1514
+ const validateCheckUIDAvailabilityInput = strapiUtils.validateYupSchema(checkUIDAvailabilityInputSchema);
1515
+ const { isVisibleAttribute: isVisibleAttribute$2 } = strapiUtils__default.default.contentTypes;
1516
+ function checkRelation(model, attributeName, path) {
1517
+ if (!isVisibleAttribute$2(model, attributeName)) {
1518
+ return [];
1519
+ }
1520
+ const { relation, inversedBy, mappedBy } = model.attributes[attributeName];
1521
+ if (["oneToOne", "oneToMany"].includes(relation) && [mappedBy, inversedBy].some((key) => key != null)) {
1522
+ return [[[...path, attributeName], "relation"]];
1523
+ }
1524
+ return [];
1525
+ }
1526
+ const getProhibitedCloningFields = (uid2, pathPrefix = []) => {
1527
+ const model = strapi.getModel(uid2);
1528
+ const prohibitedFields = Object.keys(model.attributes).reduce(
1529
+ (acc, attributeName) => {
1530
+ const attribute = model.attributes[attributeName];
1531
+ const attributePath = [...pathPrefix, attributeName];
1532
+ switch (attribute.type) {
1533
+ case "relation":
1534
+ return [...acc, ...checkRelation(model, attributeName, pathPrefix)];
1535
+ case "component":
1536
+ return [...acc, ...getProhibitedCloningFields(attribute.component, attributePath)];
1537
+ case "dynamiczone":
1538
+ return [
1539
+ ...acc,
1540
+ ...(attribute.components || []).flatMap(
1541
+ (componentUID) => getProhibitedCloningFields(componentUID, [
1542
+ ...attributePath,
1543
+ strapi.getModel(componentUID).info.displayName
1544
+ ])
1545
+ )
1546
+ ];
1547
+ case "uid":
1548
+ return [...acc, [attributePath, "unique"]];
1549
+ default:
1550
+ if (attribute?.unique) {
1551
+ return [...acc, [attributePath, "unique"]];
1552
+ }
1553
+ return acc;
1554
+ }
1555
+ },
1556
+ []
1557
+ );
1558
+ return prohibitedFields;
1559
+ };
1560
+ const excludeNotCreatableFields = (uid2, permissionChecker2) => (body, path = []) => {
1561
+ const model = strapi.getModel(uid2);
1562
+ const canCreate = (path2) => permissionChecker2.can.create(null, path2);
1563
+ return Object.keys(model.attributes).reduce((body2, attributeName) => {
1564
+ const attribute = model.attributes[attributeName];
1565
+ const attributePath = [...path, attributeName].join(".");
1566
+ if (!isVisibleAttribute$2(model, attributeName)) {
1567
+ return body2;
1568
+ }
1569
+ switch (attribute.type) {
1570
+ case "relation": {
1571
+ if (canCreate(attributePath))
1572
+ return body2;
1573
+ return fp.set(attributePath, { set: [] }, body2);
1574
+ }
1575
+ case "component": {
1576
+ return excludeNotCreatableFields(attribute.component, permissionChecker2)(body2, [
1577
+ ...path,
1578
+ attributeName
1579
+ ]);
1580
+ }
1581
+ default: {
1582
+ if (canCreate(attributePath))
1583
+ return body2;
1584
+ return fp.set(attributePath, null, body2);
1585
+ }
1586
+ }
1587
+ }, body);
1588
+ };
1589
+ const singleLocaleSchema = strapiUtils.yup.string().nullable();
1590
+ const multipleLocaleSchema = strapiUtils.yup.lazy(
1591
+ (value) => Array.isArray(value) ? strapiUtils.yup.array().of(singleLocaleSchema.required()) : singleLocaleSchema
1592
+ );
1593
+ const statusSchema = strapiUtils.yup.mixed().oneOf(["draft", "published"], "Invalid status");
1594
+ const getDocumentLocaleAndStatus = async (request, opts = { allowMultipleLocales: false }) => {
1595
+ const { allowMultipleLocales } = opts;
1596
+ const { locale, status, ...rest } = request || {};
1597
+ const schema = strapiUtils.yup.object().shape({
1598
+ locale: allowMultipleLocales ? multipleLocaleSchema : singleLocaleSchema,
1599
+ status: statusSchema
1600
+ });
1601
+ try {
1602
+ await strapiUtils.validateYupSchema(schema, { strict: true, abortEarly: false })(request);
1603
+ return { locale, status, ...rest };
1604
+ } catch (error) {
1605
+ throw new strapiUtils.errors.ValidationError(`Validation error: ${error.message}`);
1606
+ }
1607
+ };
1608
+ const formatDocumentWithMetadata = async (permissionChecker2, uid2, document, opts = {}) => {
1609
+ const documentMetadata2 = getService$1("document-metadata");
1610
+ const serviceOutput = await documentMetadata2.formatDocumentWithMetadata(uid2, document, opts);
1611
+ let {
1612
+ meta: { availableLocales, availableStatus }
1613
+ } = serviceOutput;
1614
+ const metadataSanitizer = permissionChecker2.sanitizeOutput;
1615
+ availableLocales = await strapiUtils.async.map(
1616
+ availableLocales,
1617
+ async (localeDocument) => metadataSanitizer(localeDocument)
1618
+ );
1619
+ availableStatus = await strapiUtils.async.map(
1620
+ availableStatus,
1621
+ async (statusDocument) => metadataSanitizer(statusDocument)
1622
+ );
1623
+ return {
1624
+ ...serviceOutput,
1625
+ meta: {
1626
+ availableLocales,
1627
+ availableStatus
1628
+ }
1629
+ };
1630
+ };
1631
+ const createDocument = async (ctx, opts) => {
1632
+ const { userAbility, user } = ctx.state;
1633
+ const { model } = ctx.params;
1634
+ const { body } = ctx.request;
1635
+ const documentManager2 = getService$1("document-manager");
1636
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1637
+ if (permissionChecker2.cannot.create()) {
1638
+ throw new strapiUtils.errors.ForbiddenError();
1639
+ }
1640
+ const pickPermittedFields = permissionChecker2.sanitizeCreateInput;
1641
+ const setCreator = strapiUtils.setCreatorFields({ user });
1642
+ const sanitizeFn = strapiUtils.async.pipe(pickPermittedFields, setCreator);
1643
+ const sanitizedBody = await sanitizeFn(body);
1644
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(body);
1645
+ return documentManager2.create(model, {
1646
+ data: sanitizedBody,
1647
+ locale,
1648
+ status,
1649
+ populate: opts?.populate
1650
+ });
1651
+ };
1652
+ const updateDocument = async (ctx, opts) => {
1653
+ const { userAbility, user } = ctx.state;
1654
+ const { id, model } = ctx.params;
1655
+ const { body } = ctx.request;
1656
+ const documentManager2 = getService$1("document-manager");
1657
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1658
+ if (permissionChecker2.cannot.update()) {
1659
+ throw new strapiUtils.errors.ForbiddenError();
1660
+ }
1661
+ const permissionQuery = await permissionChecker2.sanitizedQuery.update(ctx.query);
1662
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1663
+ const { locale } = await getDocumentLocaleAndStatus(body);
1664
+ const [documentVersion, documentExists] = await Promise.all([
1665
+ documentManager2.findOne(id, model, { populate, locale, status: "draft" }),
1666
+ documentManager2.exists(model, id)
1667
+ ]);
1668
+ if (!documentExists) {
1669
+ throw new strapiUtils.errors.NotFoundError();
1670
+ }
1671
+ if (documentVersion) {
1672
+ if (permissionChecker2.cannot.update(documentVersion)) {
1673
+ throw new strapiUtils.errors.ForbiddenError();
1674
+ }
1675
+ } else if (permissionChecker2.cannot.create()) {
1676
+ throw new strapiUtils.errors.ForbiddenError();
1677
+ }
1678
+ const pickPermittedFields = documentVersion ? permissionChecker2.sanitizeUpdateInput(documentVersion) : permissionChecker2.sanitizeCreateInput;
1679
+ const setCreator = strapiUtils.setCreatorFields({ user, isEdition: true });
1680
+ const sanitizeFn = strapiUtils.async.pipe(pickPermittedFields, setCreator);
1681
+ const sanitizedBody = await sanitizeFn(body);
1682
+ return documentManager2.update(documentVersion?.documentId || id, model, {
1683
+ data: sanitizedBody,
1684
+ populate: opts?.populate,
1685
+ locale
1686
+ });
1687
+ };
1688
+ const collectionTypes = {
1689
+ async find(ctx) {
1690
+ const { userAbility } = ctx.state;
1691
+ const { model } = ctx.params;
1692
+ const { query } = ctx.request;
1693
+ const documentMetadata2 = getService$1("document-metadata");
1694
+ const documentManager2 = getService$1("document-manager");
1695
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1696
+ if (permissionChecker2.cannot.read()) {
1697
+ return ctx.forbidden();
1698
+ }
1699
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
1700
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(1).countRelations({ toOne: false, toMany: true }).build();
1701
+ const { locale, status } = await getDocumentLocaleAndStatus(query);
1702
+ const { results: documents, pagination } = await documentManager2.findPage(
1703
+ { ...permissionQuery, populate, locale, status },
1704
+ model
1705
+ );
1706
+ const documentsAvailableStatus = await documentMetadata2.getManyAvailableStatus(
1707
+ model,
1708
+ documents
1709
+ );
1710
+ const setStatus = (document) => {
1711
+ const availableStatuses = documentsAvailableStatus.filter(
1712
+ (d) => d.documentId === document.documentId
1713
+ );
1714
+ document.status = documentMetadata2.getStatus(document, availableStatuses);
1715
+ return document;
1716
+ };
1717
+ const results = await strapiUtils.async.map(
1718
+ documents,
1719
+ strapiUtils.async.pipe(permissionChecker2.sanitizeOutput, setStatus)
1720
+ );
1721
+ ctx.body = {
1722
+ results,
1723
+ pagination
1724
+ };
1725
+ },
1726
+ async findOne(ctx) {
1727
+ const { userAbility } = ctx.state;
1728
+ const { model, id } = ctx.params;
1729
+ const documentManager2 = getService$1("document-manager");
1730
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1731
+ if (permissionChecker2.cannot.read()) {
1732
+ return ctx.forbidden();
1733
+ }
1734
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
1735
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1736
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(ctx.query);
1737
+ const version = await documentManager2.findOne(id, model, {
1738
+ populate,
1739
+ locale,
1740
+ status
1741
+ });
1742
+ if (!version) {
1743
+ const exists = await documentManager2.exists(model, id);
1744
+ if (!exists) {
1745
+ return ctx.notFound();
1746
+ }
1747
+ const { meta } = await formatDocumentWithMetadata(
1748
+ permissionChecker2,
1749
+ model,
1750
+ // @ts-expect-error TODO: fix
1751
+ { id, locale, publishedAt: null },
1752
+ { availableLocales: true, availableStatus: false }
1753
+ );
1754
+ ctx.body = { data: {}, meta };
1755
+ return;
1756
+ }
1757
+ if (permissionChecker2.cannot.read(version)) {
1758
+ return ctx.forbidden();
1759
+ }
1760
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(version);
1761
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
1762
+ },
1763
+ async create(ctx) {
1764
+ const { userAbility } = ctx.state;
1765
+ const { model } = ctx.params;
1766
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1767
+ const [totalEntries, document] = await Promise.all([
1768
+ strapi.db.query(model).count(),
1769
+ createDocument(ctx)
1770
+ ]);
1771
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(document);
1772
+ ctx.status = 201;
1773
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument, {
1774
+ // Empty metadata as it's not relevant for a new document
1775
+ availableLocales: false,
1776
+ availableStatus: false
1777
+ });
1778
+ if (totalEntries === 0) {
1779
+ strapi.telemetry.send("didCreateFirstContentTypeEntry", {
1780
+ eventProperties: { model }
1781
+ });
1782
+ }
1783
+ },
1784
+ async update(ctx) {
1785
+ const { userAbility } = ctx.state;
1786
+ const { model } = ctx.params;
1787
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1788
+ const updatedVersion = await updateDocument(ctx);
1789
+ const sanitizedVersion = await permissionChecker2.sanitizeOutput(updatedVersion);
1790
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedVersion);
1791
+ },
1792
+ async clone(ctx) {
1793
+ const { userAbility, user } = ctx.state;
1794
+ const { model, sourceId: id } = ctx.params;
1795
+ const { body } = ctx.request;
1796
+ const documentManager2 = getService$1("document-manager");
1797
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1798
+ if (permissionChecker2.cannot.create()) {
1799
+ return ctx.forbidden();
1800
+ }
1801
+ const permissionQuery = await permissionChecker2.sanitizedQuery.create(ctx.query);
1802
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1803
+ const { locale } = await getDocumentLocaleAndStatus(body);
1804
+ const document = await documentManager2.findOne(id, model, {
1805
+ populate,
1806
+ locale,
1807
+ status: "draft"
1808
+ });
1809
+ if (!document) {
1810
+ return ctx.notFound();
1811
+ }
1812
+ const pickPermittedFields = permissionChecker2.sanitizeCreateInput;
1813
+ const setCreator = strapiUtils.setCreatorFields({ user });
1814
+ const excludeNotCreatable = excludeNotCreatableFields(model, permissionChecker2);
1815
+ const sanitizeFn = strapiUtils.async.pipe(pickPermittedFields, setCreator, excludeNotCreatable);
1816
+ const sanitizedBody = await sanitizeFn(body);
1817
+ const clonedDocument = await documentManager2.clone(document.documentId, sanitizedBody, model);
1818
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(clonedDocument);
1819
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument, {
1820
+ // Empty metadata as it's not relevant for a new document
1821
+ availableLocales: false,
1822
+ availableStatus: false
1823
+ });
1824
+ },
1825
+ async autoClone(ctx) {
1826
+ const { model } = ctx.params;
1827
+ const prohibitedFields = getProhibitedCloningFields(model);
1828
+ if (prohibitedFields.length > 0) {
1829
+ return ctx.badRequest(
1830
+ "Entity could not be cloned as it has unique and/or relational fields. Please edit those fields manually and save to complete the cloning.",
1831
+ {
1832
+ prohibitedFields
1833
+ }
1834
+ );
1835
+ }
1836
+ await this.clone(ctx);
1837
+ },
1838
+ async delete(ctx) {
1839
+ const { userAbility } = ctx.state;
1840
+ const { id, model } = ctx.params;
1841
+ const documentManager2 = getService$1("document-manager");
1842
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1843
+ if (permissionChecker2.cannot.delete()) {
1844
+ return ctx.forbidden();
1845
+ }
1846
+ const permissionQuery = await permissionChecker2.sanitizedQuery.delete(ctx.query);
1847
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1848
+ const { locale } = await getDocumentLocaleAndStatus(ctx.query);
1849
+ const documentLocales = await documentManager2.findLocales(id, model, { populate, locale });
1850
+ if (documentLocales.length === 0) {
1851
+ return ctx.notFound();
1852
+ }
1853
+ for (const document of documentLocales) {
1854
+ if (permissionChecker2.cannot.delete(document)) {
1855
+ return ctx.forbidden();
1856
+ }
1857
+ }
1858
+ const result = await documentManager2.delete(id, model, { locale });
1859
+ ctx.body = await permissionChecker2.sanitizeOutput(result);
1860
+ },
1861
+ /**
1862
+ * Publish a document version.
1863
+ * Supports creating/saving a document and publishing it in one request.
1864
+ */
1865
+ async publish(ctx) {
1866
+ const { userAbility } = ctx.state;
1867
+ const { id, model } = ctx.params;
1868
+ const { body } = ctx.request;
1869
+ const documentManager2 = getService$1("document-manager");
1870
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1871
+ if (permissionChecker2.cannot.publish()) {
1872
+ return ctx.forbidden();
1873
+ }
1874
+ const publishedDocument = await strapi.db.transaction(async () => {
1875
+ const permissionQuery = await permissionChecker2.sanitizedQuery.publish(ctx.query);
1876
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1877
+ const document = id ? await updateDocument(ctx, { populate }) : await createDocument(ctx, { populate });
1878
+ if (permissionChecker2.cannot.publish(document)) {
1879
+ throw new strapiUtils.errors.ForbiddenError();
1880
+ }
1881
+ const { locale } = await getDocumentLocaleAndStatus(body);
1882
+ const publishResult = await documentManager2.publish(document.documentId, model, {
1883
+ locale
1884
+ // TODO: Allow setting creator fields on publish
1885
+ // data: setCreatorFields({ user, isEdition: true })({}),
1886
+ });
1887
+ if (!publishResult || publishResult.length === 0) {
1888
+ throw new strapiUtils.errors.NotFoundError("Document not found or already published.");
1889
+ }
1890
+ return publishResult[0];
1891
+ });
1892
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(publishedDocument);
1893
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
1894
+ },
1895
+ async bulkPublish(ctx) {
1896
+ const { userAbility } = ctx.state;
1897
+ const { model } = ctx.params;
1898
+ const { body } = ctx.request;
1899
+ const { documentIds } = body;
1900
+ await validateBulkActionInput(body);
1901
+ const documentManager2 = getService$1("document-manager");
1902
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1903
+ if (permissionChecker2.cannot.publish()) {
1904
+ return ctx.forbidden();
1905
+ }
1906
+ const permissionQuery = await permissionChecker2.sanitizedQuery.publish(ctx.query);
1907
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).populateDeep(Infinity).countRelations().build();
1908
+ const { locale } = await getDocumentLocaleAndStatus(body, { allowMultipleLocales: true });
1909
+ const entityPromises = documentIds.map(
1910
+ (documentId) => documentManager2.findLocales(documentId, model, { populate, locale, isPublished: false })
1911
+ );
1912
+ const entities = (await Promise.all(entityPromises)).flat();
1913
+ for (const entity of entities) {
1914
+ if (!entity) {
1915
+ return ctx.notFound();
1916
+ }
1917
+ if (permissionChecker2.cannot.publish(entity)) {
1918
+ return ctx.forbidden();
1919
+ }
1920
+ }
1921
+ const count = await documentManager2.publishMany(model, documentIds, locale);
1922
+ ctx.body = { count };
1923
+ },
1924
+ async bulkUnpublish(ctx) {
1925
+ const { userAbility } = ctx.state;
1926
+ const { model } = ctx.params;
1927
+ const { body } = ctx.request;
1928
+ const { documentIds } = body;
1929
+ await validateBulkActionInput(body);
1930
+ const documentManager2 = getService$1("document-manager");
1931
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1932
+ if (permissionChecker2.cannot.unpublish()) {
1933
+ return ctx.forbidden();
1934
+ }
1935
+ const { locale } = await getDocumentLocaleAndStatus(body);
1936
+ const entityPromises = documentIds.map(
1937
+ (documentId) => documentManager2.findLocales(documentId, model, { locale, isPublished: true })
1938
+ );
1939
+ const entities = (await Promise.all(entityPromises)).flat();
1940
+ for (const entity of entities) {
1941
+ if (!entity) {
1942
+ return ctx.notFound();
1943
+ }
1944
+ if (permissionChecker2.cannot.publish(entity)) {
1945
+ return ctx.forbidden();
1946
+ }
1947
+ }
1948
+ const entitiesIds = entities.map((document) => document.documentId);
1949
+ const { count } = await documentManager2.unpublishMany(entitiesIds, model, { locale });
1950
+ ctx.body = { count };
1951
+ },
1952
+ async unpublish(ctx) {
1953
+ const { userAbility } = ctx.state;
1954
+ const { id, model } = ctx.params;
1955
+ const {
1956
+ body: { discardDraft, ...body }
1957
+ } = ctx.request;
1958
+ const documentManager2 = getService$1("document-manager");
1959
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
1960
+ if (permissionChecker2.cannot.unpublish()) {
1961
+ return ctx.forbidden();
1962
+ }
1963
+ if (discardDraft && permissionChecker2.cannot.discard()) {
1964
+ return ctx.forbidden();
1965
+ }
1966
+ const permissionQuery = await permissionChecker2.sanitizedQuery.unpublish(ctx.query);
1967
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
1968
+ const { locale } = await getDocumentLocaleAndStatus(body);
1969
+ const document = await documentManager2.findOne(id, model, {
1970
+ populate,
1971
+ locale,
1972
+ status: "published"
1973
+ });
1974
+ if (!document) {
1975
+ throw new strapiUtils.errors.NotFoundError();
1976
+ }
1977
+ if (permissionChecker2.cannot.unpublish(document)) {
1978
+ throw new strapiUtils.errors.ForbiddenError();
1979
+ }
1980
+ if (discardDraft && permissionChecker2.cannot.discard(document)) {
1981
+ throw new strapiUtils.errors.ForbiddenError();
1982
+ }
1983
+ await strapi.db.transaction(async () => {
1984
+ if (discardDraft) {
1985
+ await documentManager2.discardDraft(document.documentId, model, { locale });
1986
+ }
1987
+ ctx.body = await strapiUtils.async.pipe(
1988
+ (document2) => documentManager2.unpublish(document2.documentId, model, { locale }),
1989
+ permissionChecker2.sanitizeOutput,
1990
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
1991
+ )(document);
1992
+ });
1993
+ },
1994
+ async discard(ctx) {
1995
+ const { userAbility } = ctx.state;
1996
+ const { id, model } = ctx.params;
1997
+ const { body } = ctx.request;
1998
+ const documentManager2 = getService$1("document-manager");
1999
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2000
+ if (permissionChecker2.cannot.discard()) {
2001
+ return ctx.forbidden();
2002
+ }
2003
+ const permissionQuery = await permissionChecker2.sanitizedQuery.discard(ctx.query);
2004
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2005
+ const { locale } = await getDocumentLocaleAndStatus(body);
2006
+ const document = await documentManager2.findOne(id, model, {
2007
+ populate,
2008
+ locale,
2009
+ status: "published"
2010
+ });
2011
+ if (!document) {
2012
+ return ctx.notFound();
2013
+ }
2014
+ if (permissionChecker2.cannot.discard(document)) {
2015
+ return ctx.forbidden();
2016
+ }
2017
+ ctx.body = await strapiUtils.async.pipe(
2018
+ (document2) => documentManager2.discardDraft(document2.documentId, model, { locale }),
2019
+ permissionChecker2.sanitizeOutput,
2020
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
2021
+ )(document);
2022
+ },
2023
+ async bulkDelete(ctx) {
2024
+ const { userAbility } = ctx.state;
2025
+ const { model } = ctx.params;
2026
+ const { query, body } = ctx.request;
2027
+ const { documentIds } = body;
2028
+ await validateBulkActionInput(body);
2029
+ const documentManager2 = getService$1("document-manager");
2030
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2031
+ if (permissionChecker2.cannot.delete()) {
2032
+ return ctx.forbidden();
2033
+ }
2034
+ const permissionQuery = await permissionChecker2.sanitizedQuery.delete(query);
2035
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2036
+ const { locale } = await getDocumentLocaleAndStatus(body);
2037
+ const documentLocales = await documentManager2.findLocales(documentIds, model, {
2038
+ populate,
2039
+ locale
2040
+ });
2041
+ if (documentLocales.length === 0) {
2042
+ return ctx.notFound();
2043
+ }
2044
+ for (const document of documentLocales) {
2045
+ if (permissionChecker2.cannot.delete(document)) {
2046
+ return ctx.forbidden();
2047
+ }
2048
+ }
2049
+ const localeDocumentsIds = documentLocales.map((document) => document.documentId);
2050
+ const { count } = await documentManager2.deleteMany(localeDocumentsIds, model, { locale });
2051
+ ctx.body = { count };
2052
+ },
2053
+ async countDraftRelations(ctx) {
2054
+ const { userAbility } = ctx.state;
2055
+ const { model, id } = ctx.params;
2056
+ const documentManager2 = getService$1("document-manager");
2057
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2058
+ if (permissionChecker2.cannot.read()) {
2059
+ return ctx.forbidden();
2060
+ }
2061
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
2062
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2063
+ const { locale, status = "draft" } = await getDocumentLocaleAndStatus(ctx.query);
2064
+ const entity = await documentManager2.findOne(id, model, { populate, locale, status });
2065
+ if (!entity) {
2066
+ return ctx.notFound();
2067
+ }
2068
+ if (permissionChecker2.cannot.read(entity)) {
2069
+ return ctx.forbidden();
2070
+ }
2071
+ const number = await documentManager2.countDraftRelations(id, model, locale);
2072
+ return {
2073
+ data: number
2074
+ };
2075
+ },
2076
+ async countManyEntriesDraftRelations(ctx) {
2077
+ const { userAbility } = ctx.state;
2078
+ const ids = ctx.request.query.documentIds;
2079
+ const locale = ctx.request.query.locale;
2080
+ const { model } = ctx.params;
2081
+ const documentManager2 = getService$1("document-manager");
2082
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2083
+ if (permissionChecker2.cannot.read()) {
2084
+ return ctx.forbidden();
2085
+ }
2086
+ const entities = await documentManager2.findMany(
2087
+ {
2088
+ filters: {
2089
+ documentId: ids
2090
+ },
2091
+ locale
2092
+ },
2093
+ model
2094
+ );
2095
+ if (!entities) {
2096
+ return ctx.notFound();
2097
+ }
2098
+ const number = await documentManager2.countManyEntriesDraftRelations(ids, model, locale);
2099
+ return {
2100
+ data: number
2101
+ };
2102
+ }
2103
+ };
2104
+ const components$1 = {
2105
+ findComponents(ctx) {
2106
+ const components2 = getService$1("components").findAllComponents();
2107
+ const { toDto } = getService$1("data-mapper");
2108
+ ctx.body = { data: components2.map(toDto) };
2109
+ },
2110
+ async findComponentConfiguration(ctx) {
2111
+ const { uid: uid2 } = ctx.params;
2112
+ const componentService = getService$1("components");
2113
+ const component = componentService.findComponent(uid2);
2114
+ if (!component) {
2115
+ return ctx.notFound("component.notFound");
2116
+ }
2117
+ const configuration = await componentService.findConfiguration(component);
2118
+ const componentsConfigurations = await componentService.findComponentsConfigurations(component);
2119
+ ctx.body = {
2120
+ data: {
2121
+ component: configuration,
2122
+ components: componentsConfigurations
2123
+ }
2124
+ };
2125
+ },
2126
+ async updateComponentConfiguration(ctx) {
2127
+ const { uid: uid2 } = ctx.params;
2128
+ const { body } = ctx.request;
2129
+ const componentService = getService$1("components");
2130
+ const component = componentService.findComponent(uid2);
2131
+ if (!component) {
2132
+ return ctx.notFound("component.notFound");
2133
+ }
2134
+ let input;
2135
+ try {
2136
+ input = await createModelConfigurationSchema(component).validate(body, {
2137
+ abortEarly: false,
2138
+ stripUnknown: true,
2139
+ strict: true
2140
+ });
2141
+ } catch (error) {
2142
+ return ctx.badRequest(null, {
2143
+ name: "validationError",
2144
+ errors: error.errors
2145
+ });
2146
+ }
2147
+ const newConfiguration = await componentService.updateConfiguration(component, input);
2148
+ ctx.body = { data: newConfiguration };
2149
+ }
2150
+ };
2151
+ const hasEditMainField = fp.has("edit.mainField");
2152
+ const getEditMainField = fp.prop("edit.mainField");
2153
+ const assocListMainField = fp.assoc("list.mainField");
2154
+ const assocMainField = (metadata) => hasEditMainField(metadata) ? assocListMainField(getEditMainField(metadata), metadata) : metadata;
2155
+ const contentTypes = {
2156
+ async findContentTypes(ctx) {
2157
+ const { kind } = ctx.query;
2158
+ try {
2159
+ await validateKind(kind);
2160
+ } catch (error) {
2161
+ return ctx.send({ error }, 400);
2162
+ }
2163
+ const contentTypes2 = getService$1("content-types").findContentTypesByKind(kind);
2164
+ const { toDto } = getService$1("data-mapper");
2165
+ ctx.body = { data: contentTypes2.map(toDto) };
2166
+ },
2167
+ async findContentTypesSettings(ctx) {
2168
+ const { findAllContentTypes, findConfiguration } = getService$1("content-types");
2169
+ const contentTypes2 = await findAllContentTypes();
2170
+ const configurations = await Promise.all(
2171
+ contentTypes2.map(async (contentType) => {
2172
+ const { uid: uid2, settings } = await findConfiguration(contentType);
2173
+ return { uid: uid2, settings };
2174
+ })
2175
+ );
2176
+ ctx.body = {
2177
+ data: configurations
2178
+ };
2179
+ },
2180
+ async findContentTypeConfiguration(ctx) {
2181
+ const { uid: uid2 } = ctx.params;
2182
+ const contentTypeService = getService$1("content-types");
2183
+ const contentType = await contentTypeService.findContentType(uid2);
2184
+ if (!contentType) {
2185
+ return ctx.notFound("contentType.notFound");
2186
+ }
2187
+ const configuration = await contentTypeService.findConfiguration(contentType);
2188
+ const confWithUpdatedMetadata = {
2189
+ ...configuration,
2190
+ metadatas: fp.mapValues(assocMainField, configuration.metadatas)
2191
+ };
2192
+ const components2 = await contentTypeService.findComponentsConfigurations(contentType);
2193
+ ctx.body = {
2194
+ data: {
2195
+ contentType: confWithUpdatedMetadata,
2196
+ components: components2
2197
+ }
2198
+ };
2199
+ },
2200
+ async updateContentTypeConfiguration(ctx) {
2201
+ const { userAbility } = ctx.state;
2202
+ const { uid: uid2 } = ctx.params;
2203
+ const { body } = ctx.request;
2204
+ const contentTypeService = getService$1("content-types");
2205
+ const metricsService = getService$1("metrics");
2206
+ const contentType = await contentTypeService.findContentType(uid2);
2207
+ if (!contentType) {
2208
+ return ctx.notFound("contentType.notFound");
2209
+ }
2210
+ if (!getService$1("permission").canConfigureContentType({ userAbility, contentType })) {
2211
+ return ctx.forbidden();
2212
+ }
2213
+ let input;
2214
+ try {
2215
+ input = await createModelConfigurationSchema(contentType).validate(body, {
2216
+ abortEarly: false,
2217
+ stripUnknown: true,
2218
+ strict: true
2219
+ });
2220
+ } catch (error) {
2221
+ return ctx.badRequest(null, {
2222
+ name: "validationError",
2223
+ errors: error.errors
2224
+ });
2225
+ }
2226
+ const newConfiguration = await contentTypeService.updateConfiguration(contentType, input);
2227
+ await metricsService.sendDidConfigureListView(contentType, newConfiguration);
2228
+ const confWithUpdatedMetadata = {
2229
+ ...newConfiguration,
2230
+ metadatas: fp.mapValues(assocMainField, newConfiguration.metadatas)
2231
+ };
2232
+ const components2 = await contentTypeService.findComponentsConfigurations(contentType);
2233
+ ctx.body = {
2234
+ data: {
2235
+ contentType: confWithUpdatedMetadata,
2236
+ components: components2
2237
+ }
2238
+ };
2239
+ }
2240
+ };
2241
+ const init = {
2242
+ getInitData(ctx) {
2243
+ const { toDto } = getService$1("data-mapper");
2244
+ const { findAllComponents } = getService$1("components");
2245
+ const { getAllFieldSizes } = getService$1("field-sizes");
2246
+ const { findAllContentTypes } = getService$1("content-types");
2247
+ ctx.body = {
2248
+ data: {
2249
+ fieldSizes: getAllFieldSizes(),
2250
+ components: findAllComponents().map(toDto),
2251
+ contentTypes: findAllContentTypes().map(toDto)
2252
+ }
2253
+ };
2254
+ }
2255
+ };
2256
+ const validateFindAvailableSchema = strapiUtils.yup.object().shape({
2257
+ component: strapiUtils.yup.string(),
2258
+ id: strapiUtils.yup.strapiID(),
2259
+ _q: strapiUtils.yup.string(),
2260
+ idsToOmit: strapiUtils.yup.array().of(strapiUtils.yup.strapiID()),
2261
+ idsToInclude: strapiUtils.yup.array().of(strapiUtils.yup.strapiID()),
2262
+ page: strapiUtils.yup.number().integer().min(1),
2263
+ pageSize: strapiUtils.yup.number().integer().min(1).max(100),
2264
+ locale: strapiUtils.yup.string().nullable(),
2265
+ status: strapiUtils.yup.string().oneOf(["published", "draft"]).nullable()
2266
+ }).required();
2267
+ const validateFindExistingSchema = strapiUtils.yup.object().shape({
2268
+ page: strapiUtils.yup.number().integer().min(1),
2269
+ pageSize: strapiUtils.yup.number().integer().min(1).max(100),
2270
+ locale: strapiUtils.yup.string().nullable(),
2271
+ status: strapiUtils.yup.string().oneOf(["published", "draft"]).nullable()
2272
+ }).required();
2273
+ const validateFindAvailable = strapiUtils.validateYupSchema(validateFindAvailableSchema, { strict: false });
2274
+ const validateFindExisting = strapiUtils.validateYupSchema(validateFindExistingSchema, { strict: false });
2275
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$2, UPDATED_AT_ATTRIBUTE } = strapiUtils.contentTypes.constants;
2276
+ const addFiltersClause = (params, filtersClause) => {
2277
+ params.filters = params.filters || {};
2278
+ params.filters.$and = params.filters.$and || [];
2279
+ params.filters.$and.push(filtersClause);
2280
+ };
2281
+ const sanitizeMainField = (model, mainField, userAbility) => {
2282
+ const permissionChecker2 = getService$1("permission-checker").create({
2283
+ userAbility,
2284
+ model: model.uid
2285
+ });
2286
+ if (!isListable(model, mainField)) {
2287
+ return "id";
2288
+ }
2289
+ if (permissionChecker2.cannot.read(null, mainField)) {
2290
+ if (model.uid === "plugin::users-permissions.role") {
2291
+ const userPermissionChecker = getService$1("permission-checker").create({
2292
+ userAbility,
2293
+ model: "plugin::users-permissions.user"
2294
+ });
2295
+ if (userPermissionChecker.can.read()) {
2296
+ return "name";
2297
+ }
2298
+ }
2299
+ return "id";
2300
+ }
2301
+ return mainField;
2302
+ };
2303
+ const addStatusToRelations = async (uid2, relations2) => {
2304
+ if (!strapiUtils.contentTypes.hasDraftAndPublish(strapi.contentTypes[uid2])) {
2305
+ return relations2;
2306
+ }
2307
+ const documentMetadata2 = getService$1("document-metadata");
2308
+ const documentsAvailableStatus = await documentMetadata2.getManyAvailableStatus(uid2, relations2);
2309
+ return relations2.map((relation) => {
2310
+ const availableStatuses = documentsAvailableStatus.filter(
2311
+ (availableDocument) => availableDocument.documentId === relation.documentId
2312
+ );
2313
+ return {
2314
+ ...relation,
2315
+ status: documentMetadata2.getStatus(relation, availableStatuses)
2316
+ };
2317
+ });
2318
+ };
2319
+ const getPublishedAtClause = (status, uid2) => {
2320
+ const model = strapi.getModel(uid2);
2321
+ if (!model || !strapiUtils.contentTypes.hasDraftAndPublish(model)) {
2322
+ return {};
2323
+ }
2324
+ return status === "published" ? { $notNull: true } : { $null: true };
2325
+ };
2326
+ const validateLocale = (sourceUid, targetUid, locale) => {
2327
+ const sourceModel = strapi.getModel(sourceUid);
2328
+ const targetModel = strapi.getModel(targetUid);
2329
+ const isLocalized = strapi.plugin("i18n").service("content-types").isLocalizedContentType;
2330
+ const isSourceLocalized = isLocalized(sourceModel);
2331
+ const isTargetLocalized = isLocalized(targetModel);
2332
+ let validatedLocale = locale;
2333
+ if (!targetModel || !isTargetLocalized)
2334
+ validatedLocale = void 0;
2335
+ return {
2336
+ locale: validatedLocale,
2337
+ isSourceLocalized,
2338
+ isTargetLocalized
2339
+ };
2340
+ };
2341
+ const validateStatus = (sourceUid, status) => {
2342
+ const sourceModel = strapi.getModel(sourceUid);
2343
+ const isDP = strapiUtils.contentTypes.hasDraftAndPublish;
2344
+ const isSourceDP = isDP(sourceModel);
2345
+ if (!isSourceDP)
2346
+ return { status: void 0 };
2347
+ switch (status) {
2348
+ case "published":
2349
+ return { status: "published" };
2350
+ default:
2351
+ return { status: "draft" };
2352
+ }
2353
+ };
2354
+ const relations = {
2355
+ async extractAndValidateRequestInfo(ctx, id) {
2356
+ const { userAbility } = ctx.state;
2357
+ const { model, targetField } = ctx.params;
2358
+ const sourceSchema = strapi.getModel(model);
2359
+ if (!sourceSchema) {
2360
+ throw new strapiUtils.errors.ValidationError(`The model ${model} doesn't exist`);
2361
+ }
2362
+ const attribute = sourceSchema.attributes[targetField];
2363
+ if (!attribute || attribute.type !== "relation") {
2364
+ throw new strapiUtils.errors.ValidationError(
2365
+ `The relational field ${targetField} doesn't exist on ${model}`
2366
+ );
2367
+ }
2368
+ const sourceUid = model;
2369
+ const targetUid = attribute.target;
2370
+ const { locale, isSourceLocalized, isTargetLocalized } = validateLocale(
2371
+ sourceUid,
2372
+ targetUid,
2373
+ ctx.request?.query?.locale
2374
+ );
2375
+ const { status } = validateStatus(sourceUid, ctx.request?.query?.status);
2376
+ const permissionChecker2 = getService$1("permission-checker").create({
2377
+ userAbility,
2378
+ model
2379
+ });
2380
+ const isComponent2 = sourceSchema.modelType === "component";
2381
+ if (!isComponent2) {
2382
+ if (permissionChecker2.cannot.read(null, targetField)) {
2383
+ return ctx.forbidden();
2384
+ }
2385
+ }
2386
+ let entryId = null;
2387
+ if (id) {
2388
+ const where = {};
2389
+ if (!isComponent2) {
2390
+ where.documentId = id;
2391
+ if (status) {
2392
+ where.publishedAt = getPublishedAtClause(status, sourceUid);
2393
+ }
2394
+ if (locale && isSourceLocalized) {
2395
+ where.locale = locale;
2396
+ }
2397
+ } else {
2398
+ where.id = id;
2399
+ }
2400
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(ctx.query);
2401
+ const populate = await getService$1("populate-builder")(model).populateFromQuery(permissionQuery).build();
2402
+ const currentEntity = await strapi.db.query(model).findOne({
2403
+ where,
2404
+ populate
2405
+ });
2406
+ if (!currentEntity) {
2407
+ throw new strapiUtils.errors.NotFoundError();
2408
+ }
2409
+ if (!isComponent2) {
2410
+ if (permissionChecker2.cannot.read(currentEntity, targetField)) {
2411
+ throw new strapiUtils.errors.ForbiddenError();
2412
+ }
2413
+ }
2414
+ entryId = currentEntity.id;
2415
+ }
2416
+ const modelConfig = isComponent2 ? await getService$1("components").findConfiguration(sourceSchema) : await getService$1("content-types").findConfiguration(sourceSchema);
2417
+ const targetSchema = strapi.getModel(targetUid);
2418
+ const mainField = fp.flow(
2419
+ fp.prop(`metadatas.${targetField}.edit.mainField`),
2420
+ (mainField2) => mainField2 || "id",
2421
+ (mainField2) => sanitizeMainField(targetSchema, mainField2, userAbility)
2422
+ )(modelConfig);
2423
+ const fieldsToSelect = fp.uniq([
2424
+ mainField,
2425
+ PUBLISHED_AT_ATTRIBUTE$2,
2426
+ UPDATED_AT_ATTRIBUTE,
2427
+ "documentId"
2428
+ ]);
2429
+ if (isTargetLocalized) {
2430
+ fieldsToSelect.push("locale");
2431
+ }
2432
+ return {
2433
+ entryId,
2434
+ locale,
2435
+ status,
2436
+ attribute,
2437
+ fieldsToSelect,
2438
+ mainField,
2439
+ source: { schema: sourceSchema },
2440
+ target: { schema: targetSchema, isLocalized: isTargetLocalized },
2441
+ sourceSchema,
2442
+ targetSchema,
2443
+ targetField
2444
+ };
2445
+ },
2446
+ /**
2447
+ * Used to find new relations to add in a relational field.
2448
+ *
2449
+ * Component and document relations are dealt a bit differently (they don't have a document_id).
2450
+ */
2451
+ async findAvailable(ctx) {
2452
+ const { id } = ctx.request.query;
2453
+ await validateFindAvailable(ctx.request.query);
2454
+ const {
2455
+ locale,
2456
+ status,
2457
+ targetField,
2458
+ fieldsToSelect,
2459
+ mainField,
2460
+ source: {
2461
+ schema: { uid: sourceUid, modelType: sourceModelType }
2462
+ },
2463
+ target: {
2464
+ schema: { uid: targetUid },
2465
+ isLocalized: isTargetLocalized
2466
+ }
2467
+ } = await this.extractAndValidateRequestInfo(ctx, id);
2468
+ const { idsToOmit, idsToInclude, _q, ...query } = ctx.request.query;
2469
+ const permissionChecker2 = getService$1("permission-checker").create({
2470
+ userAbility: ctx.state.userAbility,
2471
+ model: targetUid
2472
+ });
2473
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
2474
+ const queryParams = {
2475
+ sort: mainField,
2476
+ // cannot select other fields as the user may not have the permissions
2477
+ fields: fieldsToSelect,
2478
+ ...permissionQuery
2479
+ };
2480
+ addFiltersClause(queryParams, {
2481
+ publishedAt: getPublishedAtClause(status, targetUid)
2482
+ });
2483
+ const filterByLocale = isTargetLocalized && locale;
2484
+ if (filterByLocale) {
2485
+ addFiltersClause(queryParams, { locale });
2486
+ }
2487
+ if (id) {
2488
+ const subQuery = strapi.db.queryBuilder(sourceUid);
2489
+ const alias = subQuery.getAlias();
2490
+ const where = {
2491
+ [`${alias}.id`]: { $notNull: true },
2492
+ [`${alias}.document_id`]: { $notNull: true }
2493
+ };
2494
+ if (sourceModelType === "contentType") {
2495
+ where.document_id = id;
2496
+ } else {
2497
+ where.id = id;
2498
+ }
2499
+ if (status) {
2500
+ where[`${alias}.published_at`] = getPublishedAtClause(status, targetUid);
2501
+ }
2502
+ if (filterByLocale) {
2503
+ where[`${alias}.locale`] = locale;
2504
+ }
2505
+ if ((idsToInclude?.length ?? 0) !== 0) {
2506
+ where[`${alias}.id`].$notIn = idsToInclude;
2507
+ }
2508
+ const knexSubQuery = subQuery.where(where).join({ alias, targetField }).select(`${alias}.id`).getKnexQuery();
2509
+ addFiltersClause(queryParams, {
2510
+ id: { $notIn: knexSubQuery }
2511
+ });
2512
+ }
2513
+ if (_q) {
2514
+ const _filter = strapiUtils.isOperatorOfType("where", query._filter) ? query._filter : "$containsi";
2515
+ addFiltersClause(queryParams, { [mainField]: { [_filter]: _q } });
2516
+ }
2517
+ if (idsToOmit?.length > 0) {
2518
+ addFiltersClause(queryParams, {
2519
+ id: { $notIn: fp.uniq(idsToOmit) }
2520
+ });
2521
+ }
2522
+ const res = await strapi.db.query(targetUid).findPage(strapi.get("query-params").transform(targetUid, queryParams));
2523
+ ctx.body = {
2524
+ ...res,
2525
+ results: await addStatusToRelations(targetUid, res.results)
2526
+ };
2527
+ },
2528
+ async findExisting(ctx) {
2529
+ const { userAbility } = ctx.state;
2530
+ const { id } = ctx.params;
2531
+ await validateFindExisting(ctx.request.query);
2532
+ const {
2533
+ entryId,
2534
+ attribute,
2535
+ targetField,
2536
+ fieldsToSelect,
2537
+ source: {
2538
+ schema: { uid: sourceUid }
2539
+ },
2540
+ target: {
2541
+ schema: { uid: targetUid }
2542
+ }
2543
+ } = await this.extractAndValidateRequestInfo(ctx, id);
2544
+ const permissionQuery = await getService$1("permission-checker").create({ userAbility, model: targetUid }).sanitizedQuery.read({ fields: fieldsToSelect });
2545
+ const dbQuery = strapi.db.query(sourceUid);
2546
+ const loadRelations = strapiUtils.relations.isAnyToMany(attribute) ? (...args) => dbQuery.loadPages(...args) : (...args) => dbQuery.load(...args).then((res2) => ({ results: res2 ? [res2] : [] }));
2547
+ const res = await loadRelations({ id: entryId }, targetField, {
2548
+ select: ["id", "documentId", "locale", "publishedAt"],
2549
+ ordering: "desc",
2550
+ page: ctx.request.query.page,
2551
+ pageSize: ctx.request.query.pageSize
2552
+ });
2553
+ const loadedIds = res.results.map((item) => item.id);
2554
+ addFiltersClause(permissionQuery, { id: { $in: loadedIds } });
2555
+ const sanitizedRes = await loadRelations({ id: entryId }, targetField, {
2556
+ ...strapi.get("query-params").transform(targetUid, permissionQuery),
2557
+ ordering: "desc",
2558
+ page: ctx.request.query.page,
2559
+ pageSize: ctx.request.query.pageSize
2560
+ });
2561
+ const relationsUnion = fp.uniqBy("id", fp.concat(sanitizedRes.results, res.results));
2562
+ ctx.body = {
2563
+ pagination: res.pagination || {
2564
+ page: 1,
2565
+ pageCount: 1,
2566
+ pageSize: 10,
2567
+ total: relationsUnion.length
2568
+ },
2569
+ results: await addStatusToRelations(targetUid, relationsUnion)
2570
+ };
2571
+ }
2572
+ };
2573
+ const buildPopulateFromQuery = async (query, model) => {
2574
+ return getService$1("populate-builder")(model).populateFromQuery(query).populateDeep(Infinity).countRelations().build();
2575
+ };
2576
+ const findDocument = async (query, uid2, opts = {}) => {
2577
+ const documentManager2 = getService$1("document-manager");
2578
+ const populate = await buildPopulateFromQuery(query, uid2);
2579
+ return documentManager2.findMany({ ...opts, populate }, uid2).then((documents) => documents[0]);
2580
+ };
2581
+ const createOrUpdateDocument = async (ctx, opts) => {
2582
+ const { user, userAbility } = ctx.state;
2583
+ const { model } = ctx.params;
2584
+ const { body, query } = ctx.request;
2585
+ const documentManager2 = getService$1("document-manager");
2586
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2587
+ if (permissionChecker2.cannot.create() && permissionChecker2.cannot.update()) {
2588
+ throw new strapiUtils.errors.ForbiddenError();
2589
+ }
2590
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.update(query);
2591
+ const { locale } = await getDocumentLocaleAndStatus(body);
2592
+ const [documentVersion, otherDocumentVersion] = await Promise.all([
2593
+ findDocument(sanitizedQuery, model, { locale, status: "draft" }),
2594
+ // Find the first document to check if it exists
2595
+ strapi.db.query(model).findOne({ select: ["documentId"] })
2596
+ ]);
2597
+ const documentId = otherDocumentVersion?.documentId;
2598
+ const pickPermittedFields = documentVersion ? permissionChecker2.sanitizeUpdateInput(documentVersion) : permissionChecker2.sanitizeCreateInput;
2599
+ const setCreator = documentVersion ? strapiUtils.setCreatorFields({ user, isEdition: true }) : strapiUtils.setCreatorFields({ user });
2600
+ const sanitizeFn = strapiUtils.async.pipe(pickPermittedFields, setCreator);
2601
+ if (documentVersion) {
2602
+ if (permissionChecker2.cannot.update(documentVersion)) {
2603
+ throw new strapiUtils.errors.ForbiddenError();
2604
+ }
2605
+ } else if (permissionChecker2.cannot.create()) {
2606
+ throw new strapiUtils.errors.ForbiddenError();
2607
+ }
2608
+ const sanitizedBody = await sanitizeFn(body);
2609
+ if (!documentId) {
2610
+ return documentManager2.create(model, {
2611
+ data: sanitizedBody,
2612
+ ...sanitizedQuery,
2613
+ locale
2614
+ });
2615
+ }
2616
+ return documentManager2.update(documentId, model, {
2617
+ data: sanitizedBody,
2618
+ populate: opts?.populate,
2619
+ locale
2620
+ });
2621
+ };
2622
+ const singleTypes = {
2623
+ async find(ctx) {
2624
+ const { userAbility } = ctx.state;
2625
+ const { model } = ctx.params;
2626
+ const { query = {} } = ctx.request;
2627
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2628
+ if (permissionChecker2.cannot.read()) {
2629
+ return ctx.forbidden();
2630
+ }
2631
+ const permissionQuery = await permissionChecker2.sanitizedQuery.read(query);
2632
+ const { locale, status } = await getDocumentLocaleAndStatus(query);
2633
+ const version = await findDocument(permissionQuery, model, { locale, status });
2634
+ if (!version) {
2635
+ if (permissionChecker2.cannot.create()) {
2636
+ return ctx.forbidden();
2637
+ }
2638
+ const document = await strapi.db.query(model).findOne({});
2639
+ if (!document) {
2640
+ return ctx.notFound();
2641
+ }
2642
+ const { meta } = await formatDocumentWithMetadata(
2643
+ permissionChecker2,
2644
+ model,
2645
+ // @ts-expect-error - fix types
2646
+ { id: document.documentId, locale, publishedAt: null },
2647
+ { availableLocales: true, availableStatus: false }
2648
+ );
2649
+ ctx.body = { data: {}, meta };
2650
+ return;
2651
+ }
2652
+ if (permissionChecker2.cannot.read(version)) {
2653
+ return ctx.forbidden();
2654
+ }
2655
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(version);
2656
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2657
+ },
2658
+ async createOrUpdate(ctx) {
2659
+ const { userAbility } = ctx.state;
2660
+ const { model } = ctx.params;
2661
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2662
+ const document = await createOrUpdateDocument(ctx);
2663
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(document);
2664
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2665
+ },
2666
+ async delete(ctx) {
2667
+ const { userAbility } = ctx.state;
2668
+ const { model } = ctx.params;
2669
+ const { query = {} } = ctx.request;
2670
+ const documentManager2 = getService$1("document-manager");
2671
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2672
+ if (permissionChecker2.cannot.delete()) {
2673
+ return ctx.forbidden();
2674
+ }
2675
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.delete(query);
2676
+ const populate = await buildPopulateFromQuery(sanitizedQuery, model);
2677
+ const { locale } = await getDocumentLocaleAndStatus(query);
2678
+ const documentLocales = await documentManager2.findLocales(void 0, model, {
2679
+ populate,
2680
+ locale
2681
+ });
2682
+ if (documentLocales.length === 0) {
2683
+ return ctx.notFound();
2684
+ }
2685
+ for (const document of documentLocales) {
2686
+ if (permissionChecker2.cannot.delete(document)) {
2687
+ return ctx.forbidden();
2688
+ }
2689
+ }
2690
+ const deletedEntity = await documentManager2.delete(documentLocales.at(0).documentId, model, {
2691
+ locale
2692
+ });
2693
+ ctx.body = await permissionChecker2.sanitizeOutput(deletedEntity);
2694
+ },
2695
+ async publish(ctx) {
2696
+ const { userAbility } = ctx.state;
2697
+ const { model } = ctx.params;
2698
+ const { query = {} } = ctx.request;
2699
+ const documentManager2 = getService$1("document-manager");
2700
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2701
+ if (permissionChecker2.cannot.publish()) {
2702
+ return ctx.forbidden();
2703
+ }
2704
+ const publishedDocument = await strapi.db.transaction(async () => {
2705
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.publish(query);
2706
+ const populate = await buildPopulateFromQuery(sanitizedQuery, model);
2707
+ const document = await createOrUpdateDocument(ctx, { populate });
2708
+ if (!document) {
2709
+ throw new strapiUtils.errors.NotFoundError();
2710
+ }
2711
+ if (permissionChecker2.cannot.publish(document)) {
2712
+ throw new strapiUtils.errors.ForbiddenError();
2713
+ }
2714
+ const { locale } = await getDocumentLocaleAndStatus(document);
2715
+ const publishResult = await documentManager2.publish(document.documentId, model, { locale });
2716
+ return publishResult.at(0);
2717
+ });
2718
+ const sanitizedDocument = await permissionChecker2.sanitizeOutput(publishedDocument);
2719
+ ctx.body = await formatDocumentWithMetadata(permissionChecker2, model, sanitizedDocument);
2720
+ },
2721
+ async unpublish(ctx) {
2722
+ const { userAbility } = ctx.state;
2723
+ const { model } = ctx.params;
2724
+ const {
2725
+ body: { discardDraft, ...body },
2726
+ query = {}
2727
+ } = ctx.request;
2728
+ const documentManager2 = getService$1("document-manager");
2729
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2730
+ if (permissionChecker2.cannot.unpublish()) {
2731
+ return ctx.forbidden();
2732
+ }
2733
+ if (discardDraft && permissionChecker2.cannot.discard()) {
2734
+ return ctx.forbidden();
2735
+ }
2736
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.unpublish(query);
2737
+ const { locale } = await getDocumentLocaleAndStatus(body);
2738
+ const document = await findDocument(sanitizedQuery, model, { locale });
2739
+ if (!document) {
2740
+ return ctx.notFound();
2741
+ }
2742
+ if (permissionChecker2.cannot.unpublish(document)) {
2743
+ return ctx.forbidden();
2744
+ }
2745
+ if (discardDraft && permissionChecker2.cannot.discard(document)) {
2746
+ return ctx.forbidden();
2747
+ }
2748
+ await strapi.db.transaction(async () => {
2749
+ if (discardDraft) {
2750
+ await documentManager2.discardDraft(document.documentId, model, { locale });
2751
+ }
2752
+ ctx.body = await strapiUtils.async.pipe(
2753
+ (document2) => documentManager2.unpublish(document2.documentId, model, { locale }),
2754
+ permissionChecker2.sanitizeOutput,
2755
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
2756
+ )(document);
2757
+ });
2758
+ },
2759
+ async discard(ctx) {
2760
+ const { userAbility } = ctx.state;
2761
+ const { model } = ctx.params;
2762
+ const { body, query = {} } = ctx.request;
2763
+ const documentManager2 = getService$1("document-manager");
2764
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2765
+ if (permissionChecker2.cannot.discard()) {
2766
+ return ctx.forbidden();
2767
+ }
2768
+ const sanitizedQuery = await permissionChecker2.sanitizedQuery.discard(query);
2769
+ const { locale } = await getDocumentLocaleAndStatus(body);
2770
+ const document = await findDocument(sanitizedQuery, model, { locale, status: "published" });
2771
+ if (!document) {
2772
+ return ctx.notFound();
2773
+ }
2774
+ if (permissionChecker2.cannot.discard(document)) {
2775
+ return ctx.forbidden();
2776
+ }
2777
+ ctx.body = await strapiUtils.async.pipe(
2778
+ (document2) => documentManager2.discardDraft(document2.documentId, model, { locale }),
2779
+ permissionChecker2.sanitizeOutput,
2780
+ (document2) => formatDocumentWithMetadata(permissionChecker2, model, document2)
2781
+ )(document);
2782
+ },
2783
+ async countDraftRelations(ctx) {
2784
+ const { userAbility } = ctx.state;
2785
+ const { model } = ctx.params;
2786
+ const { query } = ctx.request;
2787
+ const documentManager2 = getService$1("document-manager");
2788
+ const permissionChecker2 = getService$1("permission-checker").create({ userAbility, model });
2789
+ const { locale } = await getDocumentLocaleAndStatus(query);
2790
+ if (permissionChecker2.cannot.read()) {
2791
+ return ctx.forbidden();
2792
+ }
2793
+ const document = await findDocument({}, model);
2794
+ if (!document) {
2795
+ return ctx.notFound();
2796
+ }
2797
+ if (permissionChecker2.cannot.read(document)) {
2798
+ return ctx.forbidden();
2799
+ }
2800
+ const number = await documentManager2.countDraftRelations(document.documentId, model, locale);
2801
+ return {
2802
+ data: number
2803
+ };
2804
+ }
2805
+ };
2806
+ const uid$1 = {
2807
+ async generateUID(ctx) {
2808
+ const { contentTypeUID, field, data } = await validateGenerateUIDInput(ctx.request.body);
2809
+ const { query = {} } = ctx.request;
2810
+ const { locale } = await getDocumentLocaleAndStatus(query);
2811
+ await validateUIDField(contentTypeUID, field);
2812
+ const uidService = getService$1("uid");
2813
+ ctx.body = {
2814
+ data: await uidService.generateUIDField({ contentTypeUID, field, data, locale })
2815
+ };
2816
+ },
2817
+ async checkUIDAvailability(ctx) {
2818
+ const { contentTypeUID, field, value } = await validateCheckUIDAvailabilityInput(
2819
+ ctx.request.body
2820
+ );
2821
+ const { query = {} } = ctx.request;
2822
+ const { locale } = await getDocumentLocaleAndStatus(query);
2823
+ await validateUIDField(contentTypeUID, field);
2824
+ const uidService = getService$1("uid");
2825
+ const isAvailable = await uidService.checkUIDAvailability({
2826
+ contentTypeUID,
2827
+ field,
2828
+ value,
2829
+ locale
2830
+ });
2831
+ ctx.body = {
2832
+ isAvailable,
2833
+ suggestion: !isAvailable ? await uidService.findUniqueUID({ contentTypeUID, field, value, locale }) : null
2834
+ };
2835
+ }
2836
+ };
2837
+ const controllers = {
2838
+ "collection-types": collectionTypes,
2839
+ components: components$1,
2840
+ "content-types": contentTypes,
2841
+ init,
2842
+ relations,
2843
+ "single-types": singleTypes,
2844
+ uid: uid$1,
2845
+ ...history.controllers ? history.controllers : {}
2846
+ };
2847
+ const keys = {
2848
+ CONFIGURATION: "configuration"
2849
+ };
2850
+ const getStore = () => strapi.store({ type: "plugin", name: "content_manager" });
2851
+ const EMPTY_CONFIG = {
2852
+ settings: {},
2853
+ metadatas: {},
2854
+ layouts: {}
2855
+ };
2856
+ const configurationKey = (key) => `${keys.CONFIGURATION}_${key}`;
2857
+ const getModelConfiguration = async (key) => {
2858
+ const config = await getStore().get({ key: configurationKey(key) });
2859
+ return ___default.default.merge({}, EMPTY_CONFIG, config);
2860
+ };
2861
+ const setModelConfiguration = async (key, value) => {
2862
+ const storedConfig = await getStore().get({ key: configurationKey(key) }) || {};
2863
+ const currentConfig = { ...storedConfig };
2864
+ Object.keys(value).forEach((key2) => {
2865
+ if (value[key2] !== null && value[key2] !== void 0) {
2866
+ ___default.default.set(currentConfig, key2, value[key2]);
2867
+ }
2868
+ });
2869
+ if (!___default.default.isEqual(currentConfig, storedConfig)) {
2870
+ return getStore().set({
2871
+ key: configurationKey(key),
2872
+ value: currentConfig
2873
+ });
2874
+ }
2875
+ };
2876
+ const deleteKey = (key) => {
2877
+ return strapi.db.query("strapi::core-store").delete({ where: { key: `plugin_content_manager_configuration_${key}` } });
2878
+ };
2879
+ const findByKey = async (key) => {
2880
+ const results = await strapi.db.query("strapi::core-store").findMany({
2881
+ where: {
2882
+ key: {
2883
+ $startsWith: key
2884
+ }
2885
+ }
2886
+ });
2887
+ return results.map(({ value }) => JSON.parse(value));
2888
+ };
2889
+ const getAllConfigurations = () => findByKey("plugin_content_manager_configuration");
2890
+ const storeUtils = {
2891
+ getAllConfigurations,
2892
+ findByKey,
2893
+ getModelConfiguration,
2894
+ setModelConfiguration,
2895
+ deleteKey,
2896
+ keys
2897
+ };
2898
+ function createDefaultMetadatas(schema) {
2899
+ return {
2900
+ ...Object.keys(schema.attributes).reduce((acc, name) => {
2901
+ acc[name] = createDefaultMetadata(schema, name);
2902
+ return acc;
2903
+ }, {}),
2904
+ id: {
2905
+ edit: {},
2906
+ list: {
2907
+ label: "id",
2908
+ searchable: true,
2909
+ sortable: true
2910
+ }
2911
+ }
2912
+ };
2913
+ }
2914
+ function createDefaultMetadata(schema, name) {
2915
+ const edit = {
2916
+ label: name,
2917
+ description: "",
2918
+ placeholder: "",
2919
+ visible: isVisible$1(schema, name),
2920
+ editable: true
2921
+ };
2922
+ const fieldAttributes = schema.attributes[name];
2923
+ if (isRelation$1(fieldAttributes)) {
2924
+ const { targetModel } = fieldAttributes;
2925
+ const targetSchema = getTargetSchema(targetModel);
2926
+ if (targetSchema) {
2927
+ edit.mainField = getDefaultMainField(targetSchema);
2928
+ }
2929
+ }
2930
+ ___default.default.assign(
2931
+ edit,
2932
+ ___default.default.pick(___default.default.get(schema, ["config", "metadatas", name, "edit"], {}), [
2933
+ "label",
2934
+ "description",
2935
+ "placeholder",
2936
+ "visible",
2937
+ "editable",
2938
+ "mainField"
2939
+ ])
2940
+ );
2941
+ const list = {
2942
+ // @ts-expect-error we need to specify these properties
2943
+ label: name,
2944
+ // @ts-expect-error we need to specify these properties
2945
+ searchable: isSearchable(schema, name),
2946
+ // @ts-expect-error we need to specify these properties
2947
+ sortable: isSortable(schema, name),
2948
+ ...___default.default.pick(___default.default.get(schema, ["config", "metadatas", name, "list"], {}), [
2949
+ "label",
2950
+ "searchable",
2951
+ "sortable"
2952
+ ])
2953
+ };
2954
+ return { edit, list };
2955
+ }
2956
+ async function syncMetadatas(configuration, schema) {
2957
+ if (___default.default.isEmpty(configuration.metadatas)) {
2958
+ return createDefaultMetadatas(schema);
2959
+ }
2960
+ const metasWithValidKeys = ___default.default.pick(configuration.metadatas, Object.keys(schema.attributes));
2961
+ const metasWithDefaults = ___default.default.merge({}, createDefaultMetadatas(schema), metasWithValidKeys);
2962
+ const updatedMetas = Object.keys(metasWithDefaults).reduce((acc, key) => {
2963
+ const { edit, list } = metasWithDefaults[key];
2964
+ const attr = schema.attributes[key];
2965
+ const updatedMeta = { edit, list };
2966
+ if (list.sortable && !isSortable(schema, key)) {
2967
+ ___default.default.set(updatedMeta, ["list", "sortable"], false);
2968
+ ___default.default.set(acc, [key], updatedMeta);
2969
+ }
2970
+ if (list.searchable && !isSearchable(schema, key)) {
2971
+ ___default.default.set(updatedMeta, ["list", "searchable"], false);
2972
+ ___default.default.set(acc, [key], updatedMeta);
2973
+ }
2974
+ if (!___default.default.has(edit, "mainField"))
2975
+ return acc;
2976
+ if (!isRelation$1(attr)) {
2977
+ ___default.default.set(updatedMeta, "edit", ___default.default.omit(edit, ["mainField"]));
2978
+ ___default.default.set(acc, [key], updatedMeta);
2979
+ return acc;
2980
+ }
2981
+ if (edit.mainField === "id")
2982
+ return acc;
2983
+ const targetSchema = getTargetSchema(attr.targetModel);
2984
+ if (!targetSchema)
2985
+ return acc;
2986
+ if (!isSortable(targetSchema, edit.mainField) && !isListable(targetSchema, edit.mainField)) {
2987
+ ___default.default.set(updatedMeta, ["edit", "mainField"], getDefaultMainField(targetSchema));
2988
+ ___default.default.set(acc, [key], updatedMeta);
2989
+ return acc;
2990
+ }
2991
+ return acc;
2992
+ }, {});
2993
+ return ___default.default.assign(metasWithDefaults, updatedMetas);
2994
+ }
2995
+ const getTargetSchema = (targetModel) => {
2996
+ return getService$1("content-types").findContentType(targetModel);
2997
+ };
2998
+ const DEFAULT_LIST_LENGTH = 4;
2999
+ const MAX_ROW_SIZE = 12;
3000
+ const isAllowedFieldSize = (type, size) => {
3001
+ const { getFieldSize } = getService$1("field-sizes");
3002
+ const fieldSize = getFieldSize(type);
3003
+ if (!fieldSize.isResizable && size !== fieldSize.default) {
3004
+ return false;
3005
+ }
3006
+ return size <= MAX_ROW_SIZE;
3007
+ };
3008
+ const getDefaultFieldSize = (attribute) => {
3009
+ const { hasFieldSize, getFieldSize } = getService$1("field-sizes");
3010
+ return getFieldSize(hasFieldSize(attribute.customField) ? attribute.customField : attribute.type).default;
3011
+ };
3012
+ async function createDefaultLayouts(schema) {
3013
+ return {
3014
+ // @ts-expect-error necessary to provide this default layout
3015
+ list: createDefaultListLayout(schema),
3016
+ // @ts-expect-error necessary to provide this default layout
3017
+ edit: createDefaultEditLayout(schema),
3018
+ ...___default.default.pick(___default.default.get(schema, ["config", "layouts"], {}), ["list", "edit"])
3019
+ };
3020
+ }
3021
+ function createDefaultListLayout(schema) {
3022
+ return Object.keys(schema.attributes).filter((name) => isListable(schema, name)).slice(0, DEFAULT_LIST_LENGTH);
3023
+ }
3024
+ const rowSize = (els) => els.reduce((sum, el) => sum + el.size, 0);
3025
+ function createDefaultEditLayout(schema) {
3026
+ const keys2 = Object.keys(schema.attributes).filter((name) => hasEditableAttribute(schema, name));
3027
+ return appendToEditLayout([], keys2, schema);
3028
+ }
3029
+ function syncLayouts(configuration, schema) {
3030
+ if (___default.default.isEmpty(configuration.layouts))
3031
+ return createDefaultLayouts(schema);
3032
+ const { list = [], editRelations = [], edit = [] } = configuration.layouts || {};
3033
+ let cleanList = list.filter((attr) => isListable(schema, attr));
3034
+ const cleanEditRelations = editRelations.filter(
3035
+ (attr) => hasRelationAttribute(schema, attr)
3036
+ );
3037
+ const elementsToReAppend = [...cleanEditRelations];
3038
+ let cleanEdit = [];
3039
+ for (const row of edit) {
3040
+ const newRow = [];
3041
+ for (const el of row) {
3042
+ if (!hasEditableAttribute(schema, el.name))
3043
+ continue;
3044
+ const { hasFieldSize } = getService$1("field-sizes");
3045
+ const fieldType = hasFieldSize(schema.attributes[el.name].customField) ? schema.attributes[el.name].customField : schema.attributes[el.name].type;
3046
+ if (!isAllowedFieldSize(fieldType, el.size)) {
3047
+ elementsToReAppend.push(el.name);
3048
+ continue;
3049
+ }
3050
+ newRow.push(el);
3051
+ }
3052
+ if (newRow.length > 0) {
3053
+ cleanEdit.push(newRow);
3054
+ }
3055
+ }
3056
+ cleanEdit = appendToEditLayout(cleanEdit, elementsToReAppend, schema);
3057
+ const newAttributes = ___default.default.difference(
3058
+ Object.keys(schema.attributes),
3059
+ Object.keys(configuration.metadatas)
3060
+ );
3061
+ if (cleanList.length < DEFAULT_LIST_LENGTH) {
3062
+ cleanList = ___default.default.uniq(
3063
+ cleanList.concat(newAttributes.filter((key) => isListable(schema, key))).slice(0, DEFAULT_LIST_LENGTH)
3064
+ );
3065
+ }
3066
+ const newEditAttributes = newAttributes.filter((key) => hasEditableAttribute(schema, key));
3067
+ cleanEdit = appendToEditLayout(cleanEdit, newEditAttributes, schema);
3068
+ return {
3069
+ list: cleanList.length > 0 ? cleanList : createDefaultListLayout(schema),
3070
+ edit: cleanEdit.length > 0 ? cleanEdit : createDefaultEditLayout(schema)
3071
+ };
3072
+ }
3073
+ const appendToEditLayout = (layout = [], keysToAppend, schema) => {
3074
+ if (keysToAppend.length === 0)
3075
+ return layout;
3076
+ let currentRowIndex = Math.max(layout.length - 1, 0);
3077
+ if (!layout[currentRowIndex]) {
3078
+ layout[currentRowIndex] = [];
3079
+ }
3080
+ for (const key of keysToAppend) {
3081
+ const attribute = schema.attributes[key];
3082
+ const attributeSize = getDefaultFieldSize(attribute);
3083
+ const currenRowSize = rowSize(layout[currentRowIndex]);
3084
+ if (currenRowSize + attributeSize > MAX_ROW_SIZE) {
3085
+ currentRowIndex += 1;
3086
+ layout[currentRowIndex] = [];
3087
+ }
3088
+ layout[currentRowIndex].push({
3089
+ name: key,
3090
+ size: attributeSize
3091
+ });
3092
+ }
3093
+ return layout;
3094
+ };
3095
+ async function validateCustomConfig(schema) {
3096
+ try {
3097
+ await createModelConfigurationSchema(schema, {
3098
+ allowUndefined: true
3099
+ }).validate(schema.config);
3100
+ } catch (error) {
3101
+ throw new Error(
3102
+ `Invalid Model configuration for model ${schema.uid}. Verify your {{ modelName }}.config.js(on) file:
3103
+ - ${error.message}
3104
+ `
3105
+ );
3106
+ }
3107
+ }
3108
+ async function createDefaultConfiguration(schema) {
3109
+ await validateCustomConfig(schema);
3110
+ return {
3111
+ settings: await createDefaultSettings(schema),
3112
+ metadatas: await createDefaultMetadatas(schema),
3113
+ layouts: await createDefaultLayouts(schema)
3114
+ };
3115
+ }
3116
+ async function syncConfiguration(conf, schema) {
3117
+ await validateCustomConfig(schema);
3118
+ return {
3119
+ settings: await syncSettings(conf, schema),
3120
+ layouts: await syncLayouts(conf, schema),
3121
+ metadatas: await syncMetadatas(conf, schema)
3122
+ };
3123
+ }
3124
+ const createConfigurationService = ({
3125
+ isComponent: isComponent2,
3126
+ prefix,
3127
+ storeUtils: storeUtils2,
3128
+ getModels
3129
+ }) => {
3130
+ const uidToStoreKey = (uid2) => {
3131
+ return `${prefix}::${uid2}`;
3132
+ };
3133
+ const getConfiguration = (uid2) => {
3134
+ const storeKey = uidToStoreKey(uid2);
3135
+ return storeUtils2.getModelConfiguration(storeKey);
3136
+ };
3137
+ const setConfiguration = (uid2, input) => {
3138
+ const configuration = {
3139
+ ...input,
3140
+ uid: uid2,
3141
+ isComponent: isComponent2 ?? void 0
3142
+ };
3143
+ const storeKey = uidToStoreKey(uid2);
3144
+ return storeUtils2.setModelConfiguration(storeKey, configuration);
3145
+ };
3146
+ const deleteConfiguration = (uid2) => {
3147
+ const storeKey = uidToStoreKey(uid2);
3148
+ return storeUtils2.deleteKey(storeKey);
3149
+ };
3150
+ const syncConfigurations = async () => {
3151
+ const models = getModels();
3152
+ const configurations = await storeUtils2.findByKey(
3153
+ `plugin_content_manager_configuration_${prefix}`
3154
+ );
3155
+ const updateConfiguration = async (uid2) => {
3156
+ const conf = configurations.find((conf2) => conf2.uid === uid2);
3157
+ return setConfiguration(uid2, await syncConfiguration(conf, models[uid2]));
3158
+ };
3159
+ const generateNewConfiguration = async (uid2) => {
3160
+ return setConfiguration(uid2, await createDefaultConfiguration(models[uid2]));
3161
+ };
3162
+ const currentUIDS = Object.keys(models);
3163
+ const DBUIDs = configurations.map(({ uid: uid2 }) => uid2);
3164
+ const contentTypesToUpdate = _.intersection(currentUIDS, DBUIDs);
3165
+ const contentTypesToAdd = _.difference(currentUIDS, DBUIDs);
3166
+ const contentTypesToDelete = _.difference(DBUIDs, currentUIDS);
3167
+ await Promise.all(contentTypesToDelete.map((uid2) => deleteConfiguration(uid2)));
3168
+ await Promise.all(contentTypesToAdd.map((uid2) => generateNewConfiguration(uid2)));
3169
+ await Promise.all(contentTypesToUpdate.map((uid2) => updateConfiguration(uid2)));
3170
+ };
3171
+ return {
3172
+ getConfiguration,
3173
+ setConfiguration,
3174
+ deleteConfiguration,
3175
+ syncConfigurations
3176
+ };
3177
+ };
3178
+ const STORE_KEY_PREFIX = "components";
3179
+ const configurationService$1 = createConfigurationService({
3180
+ storeUtils,
3181
+ isComponent: true,
3182
+ prefix: STORE_KEY_PREFIX,
3183
+ getModels() {
3184
+ const { toContentManagerModel } = getService$1("data-mapper");
3185
+ return fp.mapValues(toContentManagerModel, strapi.components);
3186
+ }
3187
+ });
3188
+ const components = ({ strapi: strapi2 }) => ({
3189
+ findAllComponents() {
3190
+ const { toContentManagerModel } = getService$1("data-mapper");
3191
+ return Object.values(strapi2.components).map(toContentManagerModel);
3192
+ },
3193
+ findComponent(uid2) {
3194
+ const { toContentManagerModel } = getService$1("data-mapper");
3195
+ const component = strapi2.components[uid2];
3196
+ return fp.isNil(component) ? component : toContentManagerModel(component);
3197
+ },
3198
+ async findConfiguration(component) {
3199
+ const configuration = await configurationService$1.getConfiguration(component.uid);
3200
+ return {
3201
+ uid: component.uid,
3202
+ category: component.category,
3203
+ ...configuration
3204
+ };
3205
+ },
3206
+ async updateConfiguration(component, newConfiguration) {
3207
+ await configurationService$1.setConfiguration(component.uid, newConfiguration);
3208
+ return this.findConfiguration(component);
3209
+ },
3210
+ async findComponentsConfigurations(model) {
3211
+ const componentsMap = {};
3212
+ const getComponentConfigurations = async (uid2) => {
3213
+ const component = this.findComponent(uid2);
3214
+ if (fp.has(uid2, componentsMap)) {
3215
+ return;
3216
+ }
3217
+ const componentConfiguration = await this.findConfiguration(component);
3218
+ const componentsConfigurations = await this.findComponentsConfigurations(component);
3219
+ Object.assign(componentsMap, {
3220
+ [uid2]: componentConfiguration,
3221
+ ...componentsConfigurations
3222
+ });
3223
+ };
3224
+ for (const key of Object.keys(model.attributes)) {
3225
+ const attribute = model.attributes[key];
3226
+ if (attribute.type === "component") {
3227
+ await getComponentConfigurations(attribute.component);
3228
+ }
3229
+ if (attribute.type === "dynamiczone") {
3230
+ for (const componentUid of attribute.components) {
3231
+ await getComponentConfigurations(componentUid);
3232
+ }
3233
+ }
3234
+ }
3235
+ return componentsMap;
3236
+ },
3237
+ syncConfigurations() {
3238
+ return configurationService$1.syncConfigurations();
3239
+ }
3240
+ });
3241
+ const configurationService = createConfigurationService({
3242
+ storeUtils,
3243
+ prefix: "content_types",
3244
+ getModels() {
3245
+ const { toContentManagerModel } = getService$1("data-mapper");
3246
+ return fp.mapValues(toContentManagerModel, strapi.contentTypes);
3247
+ }
3248
+ });
3249
+ const service = ({ strapi: strapi2 }) => ({
3250
+ findAllContentTypes() {
3251
+ const { toContentManagerModel } = getService$1("data-mapper");
3252
+ return Object.values(strapi2.contentTypes).map(toContentManagerModel);
3253
+ },
3254
+ findContentType(uid2) {
3255
+ const { toContentManagerModel } = getService$1("data-mapper");
3256
+ const contentType = strapi2.contentTypes[uid2];
3257
+ return fp.isNil(contentType) ? contentType : toContentManagerModel(contentType);
3258
+ },
3259
+ findDisplayedContentTypes() {
3260
+ return this.findAllContentTypes().filter(
3261
+ // TODO
3262
+ // @ts-expect-error should be resolved from data-mapper types
3263
+ ({ isDisplayed }) => isDisplayed === true
3264
+ );
3265
+ },
3266
+ findContentTypesByKind(kind) {
3267
+ if (!kind) {
3268
+ return this.findAllContentTypes();
3269
+ }
3270
+ return this.findAllContentTypes().filter(strapiUtils.contentTypes.isKind(kind));
3271
+ },
3272
+ async findConfiguration(contentType) {
3273
+ const configuration = await configurationService.getConfiguration(contentType.uid);
3274
+ return {
3275
+ uid: contentType.uid,
3276
+ ...configuration
3277
+ };
3278
+ },
3279
+ async updateConfiguration(contentType, newConfiguration) {
3280
+ await configurationService.setConfiguration(contentType.uid, newConfiguration);
3281
+ return this.findConfiguration(contentType);
3282
+ },
3283
+ findComponentsConfigurations(contentType) {
3284
+ return getService$1("components").findComponentsConfigurations(contentType);
3285
+ },
3286
+ syncConfigurations() {
3287
+ return configurationService.syncConfigurations();
3288
+ }
3289
+ });
3290
+ const dtoFields = [
3291
+ "uid",
3292
+ "isDisplayed",
3293
+ "apiID",
3294
+ "kind",
3295
+ "category",
3296
+ "info",
3297
+ "options",
3298
+ "pluginOptions",
3299
+ "attributes",
3300
+ "pluginOptions"
3301
+ ];
3302
+ const dataMapper = () => ({
3303
+ toContentManagerModel(contentType) {
3304
+ return {
3305
+ ...contentType,
3306
+ apiID: contentType.modelName,
3307
+ isDisplayed: isVisible(contentType),
3308
+ attributes: {
3309
+ id: {
3310
+ type: "integer"
3311
+ },
3312
+ ...formatAttributes(contentType)
3313
+ }
3314
+ };
3315
+ },
3316
+ toDto: fp.pick(dtoFields)
3317
+ });
3318
+ const formatAttributes = (contentType) => {
3319
+ const { getVisibleAttributes, getTimestamps, getCreatorFields } = strapiUtils.contentTypes;
3320
+ return getVisibleAttributes(contentType).concat(getTimestamps(contentType)).concat(getCreatorFields(contentType)).reduce((acc, key) => {
3321
+ const attribute = contentType.attributes[key];
3322
+ if (attribute.type === "relation" && attribute.relation.toLowerCase().includes("morph")) {
3323
+ return acc;
3324
+ }
3325
+ acc[key] = formatAttribute(key, attribute);
3326
+ return acc;
3327
+ }, {});
3328
+ };
3329
+ const formatAttribute = (key, attribute) => {
3330
+ if (attribute.type === "relation") {
3331
+ return toRelation(attribute);
3332
+ }
3333
+ return attribute;
3334
+ };
3335
+ const toRelation = (attribute) => {
3336
+ return {
3337
+ ...attribute,
3338
+ type: "relation",
3339
+ targetModel: "target" in attribute ? attribute.target : void 0,
3340
+ relationType: attribute.relation
3341
+ };
3342
+ };
3343
+ const isVisible = (model) => fp.getOr(true, "pluginOptions.content-manager.visible", model) === true;
3344
+ const { ApplicationError: ApplicationError$1 } = strapiUtils.errors;
3345
+ const needsFullSize = {
3346
+ default: 12,
3347
+ isResizable: false
3348
+ };
3349
+ const smallSize = {
3350
+ default: 4,
3351
+ isResizable: true
3352
+ };
3353
+ const defaultSize = {
3354
+ default: 6,
3355
+ isResizable: true
3356
+ };
3357
+ const fieldSizes = {
3358
+ // Full row and not resizable
3359
+ dynamiczone: needsFullSize,
3360
+ component: needsFullSize,
3361
+ json: needsFullSize,
3362
+ richtext: needsFullSize,
3363
+ blocks: needsFullSize,
3364
+ // Small and resizable
3365
+ checkbox: smallSize,
3366
+ boolean: smallSize,
3367
+ date: smallSize,
3368
+ time: smallSize,
3369
+ biginteger: smallSize,
3370
+ decimal: smallSize,
3371
+ float: smallSize,
3372
+ integer: smallSize,
3373
+ number: smallSize,
3374
+ // Medium and resizable
3375
+ datetime: defaultSize,
3376
+ email: defaultSize,
3377
+ enumeration: defaultSize,
3378
+ media: defaultSize,
3379
+ password: defaultSize,
3380
+ relation: defaultSize,
3381
+ string: defaultSize,
3382
+ text: defaultSize,
3383
+ timestamp: defaultSize,
3384
+ uid: defaultSize
3385
+ };
3386
+ const createFieldSizesService = ({ strapi: strapi2 }) => {
3387
+ const fieldSizesService = {
3388
+ getAllFieldSizes() {
3389
+ return fieldSizes;
3390
+ },
3391
+ hasFieldSize(type) {
3392
+ return !!fieldSizes[type];
3393
+ },
3394
+ getFieldSize(type) {
3395
+ if (!type) {
3396
+ throw new ApplicationError$1("The type is required");
3397
+ }
3398
+ const fieldSize = fieldSizes[type];
3399
+ if (!fieldSize) {
3400
+ throw new ApplicationError$1(`Could not find field size for type ${type}`);
3401
+ }
3402
+ return fieldSize;
3403
+ },
3404
+ setFieldSize(type, size) {
3405
+ if (!type) {
3406
+ throw new ApplicationError$1("The type is required");
3407
+ }
3408
+ if (!size) {
3409
+ throw new ApplicationError$1("The size is required");
3410
+ }
3411
+ fieldSizes[type] = size;
3412
+ },
3413
+ setCustomFieldInputSizes() {
3414
+ const customFields = strapi2.get("custom-fields").getAll();
3415
+ Object.entries(customFields).forEach(([uid2, customField]) => {
3416
+ if (customField.inputSize) {
3417
+ fieldSizesService.setFieldSize(uid2, customField.inputSize);
3418
+ }
3419
+ });
3420
+ }
3421
+ };
3422
+ return fieldSizesService;
3423
+ };
3424
+ const { getRelationalFields } = strapiUtils.relations;
3425
+ const metrics = ({ strapi: strapi2 }) => {
3426
+ const sendDidConfigureListView = async (contentType, configuration) => {
3427
+ const displayedFields = fp.prop("length", configuration.layouts.list);
3428
+ const relationalFields = getRelationalFields(contentType);
3429
+ const displayedRelationalFields = fp.intersection(
3430
+ relationalFields,
3431
+ configuration.layouts.list
3432
+ ).length;
3433
+ const data = {
3434
+ eventProperties: { containsRelationalFields: !!displayedRelationalFields }
3435
+ };
3436
+ if (data.eventProperties.containsRelationalFields) {
3437
+ Object.assign(data.eventProperties, {
3438
+ displayedFields,
3439
+ displayedRelationalFields
3440
+ });
3441
+ }
3442
+ try {
3443
+ await strapi2.telemetry.send("didConfigureListView", data);
3444
+ } catch (e) {
3445
+ }
3446
+ };
3447
+ return {
3448
+ sendDidConfigureListView
3449
+ };
3450
+ };
3451
+ const ACTIONS = {
3452
+ read: "plugin::content-manager.explorer.read",
3453
+ create: "plugin::content-manager.explorer.create",
3454
+ update: "plugin::content-manager.explorer.update",
3455
+ delete: "plugin::content-manager.explorer.delete",
3456
+ publish: "plugin::content-manager.explorer.publish",
3457
+ unpublish: "plugin::content-manager.explorer.publish",
3458
+ discard: "plugin::content-manager.explorer.update"
3459
+ };
3460
+ const createPermissionChecker = (strapi2) => ({ userAbility, model }) => {
3461
+ const permissionsManager = strapi2.service("admin::permission").createPermissionsManager({
3462
+ ability: userAbility,
3463
+ model
3464
+ });
3465
+ const toSubject = (entity) => entity ? permissionsManager.toSubject(entity, model) : model;
3466
+ const can = (action, entity, field) => {
3467
+ return userAbility.can(action, toSubject(entity), field);
3468
+ };
3469
+ const cannot = (action, entity, field) => {
3470
+ return userAbility.cannot(action, toSubject(entity), field);
3471
+ };
3472
+ const sanitizeOutput = (data, { action = ACTIONS.read } = {}) => {
3473
+ return permissionsManager.sanitizeOutput(data, { subject: toSubject(data), action });
3474
+ };
3475
+ const sanitizeQuery = (query, { action = ACTIONS.read } = {}) => {
3476
+ return permissionsManager.sanitizeQuery(query, { subject: model, action });
3477
+ };
3478
+ const sanitizeInput = (action, data, entity) => {
3479
+ return permissionsManager.sanitizeInput(data, {
3480
+ subject: entity ? toSubject(entity) : model,
3481
+ action
3482
+ });
3483
+ };
3484
+ const validateQuery = (query, { action = ACTIONS.read } = {}) => {
3485
+ return permissionsManager.validateQuery(query, { subject: model, action });
3486
+ };
3487
+ const validateInput = (action, data, entity) => {
3488
+ return permissionsManager.validateInput(data, {
3489
+ subject: entity ? toSubject(entity) : model,
3490
+ action
3491
+ });
3492
+ };
3493
+ const sanitizeCreateInput = (data) => sanitizeInput(ACTIONS.create, data);
3494
+ const sanitizeUpdateInput = (entity) => (data) => sanitizeInput(ACTIONS.update, data, entity);
3495
+ const buildPermissionQuery = (query, action = {}) => {
3496
+ return permissionsManager.addPermissionsQueryTo(query, action);
3497
+ };
3498
+ const sanitizedQuery = (query, action = {}) => {
3499
+ return strapiUtils.async.pipe(
3500
+ (q) => sanitizeQuery(q, action),
3501
+ (q) => buildPermissionQuery(q, action)
3502
+ )(query);
3503
+ };
3504
+ Object.keys(ACTIONS).forEach((action) => {
3505
+ sanitizedQuery[action] = (query) => sanitizedQuery(query, ACTIONS[action]);
3506
+ });
3507
+ Object.keys(ACTIONS).forEach((action) => {
3508
+ can[action] = (...args) => can(ACTIONS[action], ...args);
3509
+ cannot[action] = (...args) => cannot(ACTIONS[action], ...args);
3510
+ });
3511
+ return {
3512
+ // Permission utils
3513
+ can,
3514
+ // check if you have the permission
3515
+ cannot,
3516
+ // check if you don't have the permission
3517
+ // Sanitizers
3518
+ sanitizeOutput,
3519
+ sanitizeQuery,
3520
+ sanitizeCreateInput,
3521
+ sanitizeUpdateInput,
3522
+ // Validators
3523
+ validateQuery,
3524
+ validateInput,
3525
+ // Queries Builder
3526
+ sanitizedQuery
3527
+ };
3528
+ };
3529
+ const permissionChecker = ({ strapi: strapi2 }) => ({
3530
+ create: createPermissionChecker(strapi2)
3531
+ });
3532
+ const permission = ({ strapi: strapi2 }) => ({
3533
+ canConfigureContentType({
3534
+ userAbility,
3535
+ contentType
3536
+ }) {
3537
+ const action = strapiUtils.contentTypes.isSingleType(contentType) ? "plugin::content-manager.single-types.configure-view" : "plugin::content-manager.collection-types.configure-view";
3538
+ return userAbility.can(action);
3539
+ },
3540
+ async registerPermissions() {
3541
+ const displayedContentTypes = getService$1("content-types").findDisplayedContentTypes();
3542
+ const contentTypesUids = displayedContentTypes.map(fp.prop("uid"));
3543
+ const actions = [
3544
+ {
3545
+ section: "contentTypes",
3546
+ displayName: "Create",
3547
+ uid: "explorer.create",
3548
+ pluginName: "content-manager",
3549
+ subjects: contentTypesUids,
3550
+ options: {
3551
+ applyToProperties: ["fields"]
3552
+ }
3553
+ },
3554
+ {
3555
+ section: "contentTypes",
3556
+ displayName: "Read",
3557
+ uid: "explorer.read",
3558
+ pluginName: "content-manager",
3559
+ subjects: contentTypesUids,
3560
+ options: {
3561
+ applyToProperties: ["fields"]
3562
+ }
3563
+ },
3564
+ {
3565
+ section: "contentTypes",
3566
+ displayName: "Update",
3567
+ uid: "explorer.update",
3568
+ pluginName: "content-manager",
3569
+ subjects: contentTypesUids,
3570
+ options: {
3571
+ applyToProperties: ["fields"]
3572
+ }
3573
+ },
3574
+ {
3575
+ section: "contentTypes",
3576
+ displayName: "Delete",
3577
+ uid: "explorer.delete",
3578
+ pluginName: "content-manager",
3579
+ subjects: contentTypesUids
3580
+ },
3581
+ {
3582
+ section: "contentTypes",
3583
+ displayName: "Publish",
3584
+ uid: "explorer.publish",
3585
+ pluginName: "content-manager",
3586
+ subjects: contentTypesUids
3587
+ },
3588
+ {
3589
+ section: "plugins",
3590
+ displayName: "Configure view",
3591
+ uid: "single-types.configure-view",
3592
+ subCategory: "single types",
3593
+ pluginName: "content-manager"
3594
+ },
3595
+ {
3596
+ section: "plugins",
3597
+ displayName: "Configure view",
3598
+ uid: "collection-types.configure-view",
3599
+ subCategory: "collection types",
3600
+ pluginName: "content-manager"
3601
+ },
3602
+ {
3603
+ section: "plugins",
3604
+ displayName: "Configure Layout",
3605
+ uid: "components.configure-layout",
3606
+ subCategory: "components",
3607
+ pluginName: "content-manager"
3608
+ }
3609
+ ];
3610
+ await strapi2.service("admin::permission").actionProvider.registerMany(actions);
3611
+ }
3612
+ });
3613
+ const { isVisibleAttribute: isVisibleAttribute$1, isScalarAttribute, getDoesAttributeRequireValidation } = strapiUtils__default.default.contentTypes;
3614
+ const { isAnyToMany } = strapiUtils__default.default.relations;
3615
+ const { PUBLISHED_AT_ATTRIBUTE: PUBLISHED_AT_ATTRIBUTE$1 } = strapiUtils__default.default.contentTypes.constants;
3616
+ const isMorphToRelation = (attribute) => isRelation(attribute) && attribute.relation.includes("morphTo");
3617
+ const isMedia = fp.propEq("type", "media");
3618
+ const isRelation = fp.propEq("type", "relation");
3619
+ const isComponent = fp.propEq("type", "component");
3620
+ const isDynamicZone = fp.propEq("type", "dynamiczone");
3621
+ function getPopulateForRelation(attribute, model, attributeName, { countMany, countOne, initialPopulate }) {
3622
+ const isManyRelation = isAnyToMany(attribute);
3623
+ if (initialPopulate) {
3624
+ return initialPopulate;
3625
+ }
3626
+ if (!isVisibleAttribute$1(model, attributeName)) {
3627
+ return true;
3628
+ }
3629
+ if (isManyRelation && countMany || !isManyRelation && countOne) {
3630
+ return { count: true };
3631
+ }
3632
+ return true;
3633
+ }
3634
+ function getPopulateForDZ(attribute, options, level) {
3635
+ const populatedComponents = (attribute.components || []).reduce(
3636
+ (acc, componentUID) => ({
3637
+ ...acc,
3638
+ [componentUID]: {
3639
+ populate: getDeepPopulate(componentUID, options, level + 1)
3640
+ }
3641
+ }),
3642
+ {}
3643
+ );
3644
+ return { on: populatedComponents };
3645
+ }
3646
+ function getPopulateFor(attributeName, model, options, level) {
3647
+ const attribute = model.attributes[attributeName];
3648
+ switch (attribute.type) {
3649
+ case "relation":
3650
+ return {
3651
+ [attributeName]: getPopulateForRelation(attribute, model, attributeName, options)
3652
+ };
3653
+ case "component":
3654
+ return {
3655
+ [attributeName]: {
3656
+ populate: getDeepPopulate(attribute.component, options, level + 1)
3657
+ }
3658
+ };
3659
+ case "media":
3660
+ return {
3661
+ [attributeName]: {
3662
+ populate: {
3663
+ folder: true
3664
+ }
3665
+ }
3666
+ };
3667
+ case "dynamiczone":
3668
+ return {
3669
+ [attributeName]: getPopulateForDZ(attribute, options, level)
3670
+ };
3671
+ default:
3672
+ return {};
3673
+ }
3674
+ }
3675
+ const getDeepPopulate = (uid2, {
3676
+ initialPopulate = {},
3677
+ countMany = false,
3678
+ countOne = false,
3679
+ maxLevel = Infinity
3680
+ } = {}, level = 1) => {
3681
+ if (level > maxLevel) {
3682
+ return {};
3683
+ }
3684
+ const model = strapi.getModel(uid2);
3685
+ return Object.keys(model.attributes).reduce(
3686
+ (populateAcc, attributeName) => fp.merge(
3687
+ populateAcc,
3688
+ getPopulateFor(
3689
+ attributeName,
3690
+ model,
3691
+ {
3692
+ // @ts-expect-error - improve types
3693
+ initialPopulate: initialPopulate?.[attributeName],
3694
+ countMany,
3695
+ countOne,
3696
+ maxLevel
3697
+ },
3698
+ level
3699
+ )
3700
+ ),
3701
+ {}
3702
+ );
3703
+ };
3704
+ const getValidatableFieldsPopulate = (uid2, {
3705
+ initialPopulate = {},
3706
+ countMany = false,
3707
+ countOne = false,
3708
+ maxLevel = Infinity
3709
+ } = {}, level = 1) => {
3710
+ if (level > maxLevel) {
3711
+ return {};
3712
+ }
3713
+ const model = strapi.getModel(uid2);
3714
+ return Object.entries(model.attributes).reduce((populateAcc, [attributeName, attribute]) => {
3715
+ if (!getDoesAttributeRequireValidation(attribute)) {
3716
+ return populateAcc;
3717
+ }
3718
+ if (isScalarAttribute(attribute)) {
3719
+ return fp.merge(populateAcc, {
3720
+ [attributeName]: true
3721
+ });
3722
+ }
3723
+ return fp.merge(
3724
+ populateAcc,
3725
+ getPopulateFor(
3726
+ attributeName,
3727
+ model,
3728
+ {
3729
+ // @ts-expect-error - improve types
3730
+ initialPopulate: initialPopulate?.[attributeName],
3731
+ countMany,
3732
+ countOne,
3733
+ maxLevel
3734
+ },
3735
+ level
3736
+ )
3737
+ );
3738
+ }, {});
3739
+ };
3740
+ const getDeepPopulateDraftCount = (uid2) => {
3741
+ const model = strapi.getModel(uid2);
3742
+ let hasRelations = false;
3743
+ const populate = Object.keys(model.attributes).reduce((populateAcc, attributeName) => {
3744
+ const attribute = model.attributes[attributeName];
3745
+ switch (attribute.type) {
3746
+ case "relation": {
3747
+ if (isVisibleAttribute$1(model, attributeName)) {
3748
+ populateAcc[attributeName] = {
3749
+ count: true,
3750
+ filters: { [PUBLISHED_AT_ATTRIBUTE$1]: { $null: true } }
3751
+ };
3752
+ hasRelations = true;
3753
+ }
3754
+ break;
3755
+ }
3756
+ case "component": {
3757
+ const { populate: populate2, hasRelations: childHasRelations } = getDeepPopulateDraftCount(
3758
+ attribute.component
3759
+ );
3760
+ if (childHasRelations) {
3761
+ populateAcc[attributeName] = {
3762
+ populate: populate2
3763
+ };
3764
+ hasRelations = true;
3765
+ }
3766
+ break;
3767
+ }
3768
+ case "dynamiczone": {
3769
+ const dzPopulateFragment = attribute.components?.reduce((acc, componentUID) => {
3770
+ const { populate: componentPopulate, hasRelations: componentHasRelations } = getDeepPopulateDraftCount(componentUID);
3771
+ if (componentHasRelations) {
3772
+ hasRelations = true;
3773
+ return { ...acc, [componentUID]: { populate: componentPopulate } };
3774
+ }
3775
+ return acc;
3776
+ }, {});
3777
+ if (!fp.isEmpty(dzPopulateFragment)) {
3778
+ populateAcc[attributeName] = { on: dzPopulateFragment };
3779
+ }
3780
+ break;
3781
+ }
3782
+ }
3783
+ return populateAcc;
3784
+ }, {});
3785
+ return { populate, hasRelations };
3786
+ };
3787
+ const getQueryPopulate = async (uid2, query) => {
3788
+ let populateQuery = {};
3789
+ await strapiUtils__default.default.traverse.traverseQueryFilters(
3790
+ /**
3791
+ *
3792
+ * @param {Object} param0
3793
+ * @param {string} param0.key - Attribute name
3794
+ * @param {Object} param0.attribute - Attribute definition
3795
+ * @param {string} param0.path - Content Type path to the attribute
3796
+ * @returns
3797
+ */
3798
+ ({ attribute, path }) => {
3799
+ if (!attribute || isDynamicZone(attribute) || isMorphToRelation(attribute)) {
3800
+ return;
3801
+ }
3802
+ if (isRelation(attribute) || isMedia(attribute) || isComponent(attribute)) {
3803
+ const populatePath = path.attribute.replace(/\./g, ".populate.");
3804
+ populateQuery = fp.set(populatePath, {}, populateQuery);
3805
+ }
3806
+ },
3807
+ { schema: strapi.getModel(uid2), getModel: strapi.getModel.bind(strapi) },
3808
+ query
3809
+ );
3810
+ return populateQuery;
3811
+ };
3812
+ const buildDeepPopulate = (uid2) => {
3813
+ return getService$1("populate-builder")(uid2).populateDeep(Infinity).countRelations().build();
3814
+ };
3815
+ const populateBuilder = (uid2) => {
3816
+ let getInitialPopulate = async () => {
3817
+ return void 0;
3818
+ };
3819
+ const deepPopulateOptions = {
3820
+ countMany: false,
3821
+ countOne: false,
3822
+ maxLevel: -1
3823
+ };
3824
+ const builder = {
3825
+ /**
3826
+ * Populates all attribute fields present in a query.
3827
+ * @param query - Strapi query object
3828
+ */
3829
+ populateFromQuery(query) {
3830
+ getInitialPopulate = async () => getQueryPopulate(uid2, query);
3831
+ return builder;
3832
+ },
3833
+ /**
3834
+ * Populate relations as count.
3835
+ * @param [options]
3836
+ * @param [options.toMany] - Populate XtoMany relations as count if true.
3837
+ * @param [options.toOne] - Populate XtoOne relations as count if true.
3838
+ */
3839
+ countRelations({ toMany, toOne } = { toMany: true, toOne: true }) {
3840
+ if (!fp.isNil(toMany)) {
3841
+ deepPopulateOptions.countMany = toMany;
3842
+ }
3843
+ if (!fp.isNil(toOne)) {
3844
+ deepPopulateOptions.countOne = toOne;
3845
+ }
3846
+ return builder;
3847
+ },
3848
+ /**
3849
+ * Populate relations deeply, up to a certain level.
3850
+ * @param [level=Infinity] - Max level of nested populate.
3851
+ */
3852
+ populateDeep(level = Infinity) {
3853
+ deepPopulateOptions.maxLevel = level;
3854
+ return builder;
3855
+ },
3856
+ /**
3857
+ * Construct the populate object based on the builder options.
3858
+ * @returns Populate object
3859
+ */
3860
+ async build() {
3861
+ const initialPopulate = await getInitialPopulate();
3862
+ if (deepPopulateOptions.maxLevel === -1) {
3863
+ return initialPopulate;
3864
+ }
3865
+ return getDeepPopulate(uid2, { ...deepPopulateOptions, initialPopulate });
3866
+ }
3867
+ };
3868
+ return builder;
3869
+ };
3870
+ const populateBuilder$1 = () => populateBuilder;
3871
+ const uid = ({ strapi: strapi2 }) => ({
3872
+ async generateUIDField({
3873
+ contentTypeUID,
3874
+ field,
3875
+ data,
3876
+ locale
3877
+ }) {
3878
+ const contentType = strapi2.contentTypes[contentTypeUID];
3879
+ const { attributes } = contentType;
3880
+ const {
3881
+ targetField,
3882
+ default: defaultValue,
3883
+ options
3884
+ } = attributes[field];
3885
+ const targetValue = ___default.default.get(data, targetField);
3886
+ if (!___default.default.isEmpty(targetValue)) {
3887
+ return this.findUniqueUID({
3888
+ contentTypeUID,
3889
+ field,
3890
+ value: slugify__default.default(targetValue, options),
3891
+ locale
3892
+ });
3893
+ }
3894
+ return this.findUniqueUID({
3895
+ contentTypeUID,
3896
+ field,
3897
+ value: slugify__default.default(
3898
+ ___default.default.isFunction(defaultValue) ? defaultValue() : defaultValue || contentType.modelName,
3899
+ options
3900
+ ),
3901
+ locale
3902
+ });
3903
+ },
3904
+ async findUniqueUID({
3905
+ contentTypeUID,
3906
+ field,
3907
+ value,
3908
+ locale
3909
+ }) {
3910
+ const foundDocuments = await strapi2.documents(contentTypeUID).findMany({
3911
+ filters: {
3912
+ [field]: { $startsWith: value }
3913
+ },
3914
+ locale,
3915
+ // TODO: Check UX. When modifying an entry, it only makes sense to check for collisions with other drafts
3916
+ // However, when publishing this "available" UID might collide with another published entry
3917
+ status: "draft"
3918
+ });
3919
+ if (!foundDocuments || foundDocuments.length === 0) {
3920
+ return value;
3921
+ }
3922
+ let possibleCollisions;
3923
+ if (!Array.isArray(foundDocuments)) {
3924
+ possibleCollisions = [foundDocuments[field]];
3925
+ } else {
3926
+ possibleCollisions = foundDocuments.map((doc) => doc[field]);
3927
+ }
3928
+ if (!possibleCollisions.includes(value)) {
3929
+ return value;
3930
+ }
3931
+ let i = 1;
3932
+ let tmpUId = `${value}-${i}`;
3933
+ while (possibleCollisions.includes(tmpUId)) {
3934
+ i += 1;
3935
+ tmpUId = `${value}-${i}`;
3936
+ }
3937
+ return tmpUId;
3938
+ },
3939
+ async checkUIDAvailability({
3940
+ contentTypeUID,
3941
+ field,
3942
+ value,
3943
+ locale
3944
+ }) {
3945
+ const documentCount = await strapi2.documents(contentTypeUID).count({
3946
+ filters: {
3947
+ [field]: value
3948
+ },
3949
+ locale,
3950
+ // TODO: Check UX. When modifying an entry, it only makes sense to check for collisions with other drafts
3951
+ // However, when publishing this "available" UID might collide with another published entry
3952
+ status: "draft"
3953
+ });
3954
+ if (documentCount && documentCount > 0) {
3955
+ return false;
3956
+ }
3957
+ return true;
3958
+ }
3959
+ });
3960
+ const AVAILABLE_STATUS_FIELDS = [
3961
+ "id",
3962
+ "locale",
3963
+ "updatedAt",
3964
+ "createdAt",
3965
+ "publishedAt",
3966
+ "createdBy",
3967
+ "updatedBy",
3968
+ "status"
3969
+ ];
3970
+ const AVAILABLE_LOCALES_FIELDS = [
3971
+ "id",
3972
+ "locale",
3973
+ "updatedAt",
3974
+ "createdAt",
3975
+ "status",
3976
+ "publishedAt",
3977
+ "documentId"
3978
+ ];
3979
+ const CONTENT_MANAGER_STATUS = {
3980
+ PUBLISHED: "published",
3981
+ DRAFT: "draft",
3982
+ MODIFIED: "modified"
3983
+ };
3984
+ const getIsVersionLatestModification = (version, otherVersion) => {
3985
+ if (!version || !version.updatedAt) {
3986
+ return false;
3987
+ }
3988
+ const versionUpdatedAt = version?.updatedAt ? new Date(version.updatedAt).getTime() : 0;
3989
+ const otherUpdatedAt = otherVersion?.updatedAt ? new Date(otherVersion.updatedAt).getTime() : 0;
3990
+ return versionUpdatedAt > otherUpdatedAt;
3991
+ };
3992
+ const documentMetadata = ({ strapi: strapi2 }) => ({
3993
+ /**
3994
+ * Returns available locales of a document for the current status
3995
+ */
3996
+ async getAvailableLocales(uid2, version, allVersions, validatableFields = []) {
3997
+ const versionsByLocale = fp.groupBy("locale", allVersions);
3998
+ delete versionsByLocale[version.locale];
3999
+ const model = strapi2.getModel(uid2);
4000
+ const keysToKeep = [...AVAILABLE_LOCALES_FIELDS, ...validatableFields];
4001
+ const traversalFunction = async (localeVersion) => strapiUtils.traverseEntity(
4002
+ ({ key }, { remove }) => {
4003
+ if (keysToKeep.includes(key)) {
4004
+ return;
4005
+ }
4006
+ remove(key);
4007
+ },
4008
+ { schema: model, getModel: strapi2.getModel.bind(strapi2) },
4009
+ // @ts-expect-error fix types DocumentVersion incompatible with Data
4010
+ localeVersion
4011
+ );
4012
+ const mappingResult = await strapiUtils.async.map(
4013
+ Object.values(versionsByLocale),
4014
+ async (localeVersions) => {
4015
+ const mappedLocaleVersions = await strapiUtils.async.map(
4016
+ localeVersions,
4017
+ traversalFunction
4018
+ );
4019
+ if (!strapiUtils.contentTypes.hasDraftAndPublish(model)) {
4020
+ return mappedLocaleVersions[0];
4021
+ }
4022
+ const draftVersion = mappedLocaleVersions.find((v) => v.publishedAt === null);
4023
+ const otherVersions = mappedLocaleVersions.filter((v) => v.id !== draftVersion?.id);
4024
+ if (!draftVersion) {
4025
+ return;
4026
+ }
4027
+ return {
4028
+ ...draftVersion,
4029
+ status: this.getStatus(draftVersion, otherVersions)
4030
+ };
4031
+ }
4032
+ );
4033
+ return mappingResult.filter(Boolean);
4034
+ },
4035
+ /**
4036
+ * Returns available status of a document for the current locale
4037
+ */
4038
+ getAvailableStatus(version, allVersions) {
4039
+ const status = version.publishedAt !== null ? CONTENT_MANAGER_STATUS.DRAFT : CONTENT_MANAGER_STATUS.PUBLISHED;
4040
+ const availableStatus = allVersions.find((v) => {
4041
+ const matchLocale = v.locale === version.locale;
4042
+ const matchStatus = status === "published" ? v.publishedAt !== null : v.publishedAt === null;
4043
+ return matchLocale && matchStatus;
4044
+ });
4045
+ if (!availableStatus)
4046
+ return availableStatus;
4047
+ return fp.pick(AVAILABLE_STATUS_FIELDS, availableStatus);
4048
+ },
4049
+ /**
4050
+ * Get the available status of many documents, useful for batch operations
4051
+ * @param uid
4052
+ * @param documents
4053
+ * @returns
4054
+ */
4055
+ async getManyAvailableStatus(uid2, documents) {
4056
+ if (!documents.length)
4057
+ return [];
4058
+ const status = documents[0].publishedAt !== null ? "published" : "draft";
4059
+ const locale = documents[0]?.locale;
4060
+ const otherStatus = status === "published" ? "draft" : "published";
4061
+ return strapi2.documents(uid2).findMany({
4062
+ filters: {
4063
+ documentId: { $in: documents.map((d) => d.documentId).filter(Boolean) }
4064
+ },
4065
+ status: otherStatus,
4066
+ locale,
4067
+ fields: ["documentId", "locale", "updatedAt", "createdAt", "publishedAt"]
4068
+ });
4069
+ },
4070
+ getStatus(version, otherDocumentStatuses) {
4071
+ let draftVersion;
4072
+ let publishedVersion;
4073
+ if (version.publishedAt) {
4074
+ publishedVersion = version;
4075
+ } else {
4076
+ draftVersion = version;
4077
+ }
4078
+ const otherVersion = otherDocumentStatuses?.at(0);
4079
+ if (otherVersion?.publishedAt) {
4080
+ publishedVersion = otherVersion;
4081
+ } else if (otherVersion) {
4082
+ draftVersion = otherVersion;
4083
+ }
4084
+ if (!draftVersion)
4085
+ return CONTENT_MANAGER_STATUS.PUBLISHED;
4086
+ if (!publishedVersion)
4087
+ return CONTENT_MANAGER_STATUS.DRAFT;
4088
+ const isDraftModified = getIsVersionLatestModification(draftVersion, publishedVersion);
4089
+ return isDraftModified ? CONTENT_MANAGER_STATUS.MODIFIED : CONTENT_MANAGER_STATUS.PUBLISHED;
4090
+ },
4091
+ // TODO is it necessary to return metadata on every page of the CM
4092
+ // We could refactor this so the locales are only loaded when they're
4093
+ // needed. e.g. in the bulk locale action modal.
4094
+ async getMetadata(uid2, version, { availableLocales = true, availableStatus = true } = {}) {
4095
+ const populate = getValidatableFieldsPopulate(uid2);
4096
+ const versions = await strapi2.db.query(uid2).findMany({
4097
+ where: { documentId: version.documentId },
4098
+ populate: {
4099
+ // Populate only fields that require validation for bulk locale actions
4100
+ ...populate,
4101
+ // NOTE: creator fields are selected in this way to avoid exposing sensitive data
4102
+ createdBy: {
4103
+ select: ["id", "firstname", "lastname", "email"]
4104
+ },
4105
+ updatedBy: {
4106
+ select: ["id", "firstname", "lastname", "email"]
4107
+ }
4108
+ }
4109
+ });
4110
+ const availableLocalesResult = availableLocales ? await this.getAvailableLocales(uid2, version, versions, Object.keys(populate)) : [];
4111
+ const availableStatusResult = availableStatus ? this.getAvailableStatus(version, versions) : null;
4112
+ return {
4113
+ availableLocales: availableLocalesResult,
4114
+ availableStatus: availableStatusResult ? [availableStatusResult] : []
4115
+ };
4116
+ },
4117
+ /**
4118
+ * Returns associated metadata of a document:
4119
+ * - Available locales of the document for the current status
4120
+ * - Available status of the document for the current locale
4121
+ */
4122
+ async formatDocumentWithMetadata(uid2, document, opts = {}) {
4123
+ if (!document) {
4124
+ return document;
4125
+ }
4126
+ const hasDraftAndPublish = strapiUtils.contentTypes.hasDraftAndPublish(strapi2.getModel(uid2));
4127
+ if (!hasDraftAndPublish) {
4128
+ opts.availableStatus = false;
4129
+ }
4130
+ const meta = await this.getMetadata(uid2, document, opts);
4131
+ return {
4132
+ data: {
4133
+ ...document,
4134
+ // Add status to the document only if draft and publish is enabled
4135
+ status: hasDraftAndPublish ? this.getStatus(document, meta.availableStatus) : void 0
4136
+ },
4137
+ meta
4138
+ };
4139
+ }
4140
+ });
4141
+ const { isVisibleAttribute } = strapiUtils__default.default.contentTypes;
4142
+ const sumDraftCounts = (entity, uid2) => {
4143
+ const model = strapi.getModel(uid2);
4144
+ return Object.keys(model.attributes).reduce((sum, attributeName) => {
4145
+ const attribute = model.attributes[attributeName];
4146
+ const value = entity[attributeName];
4147
+ if (!value) {
4148
+ return sum;
4149
+ }
4150
+ switch (attribute.type) {
4151
+ case "relation": {
4152
+ if (isVisibleAttribute(model, attributeName)) {
4153
+ return sum + value.count;
4154
+ }
4155
+ return sum;
4156
+ }
4157
+ case "component": {
4158
+ const compoSum = fp.castArray(value).reduce((acc, componentValue) => {
4159
+ return acc + sumDraftCounts(componentValue, attribute.component);
4160
+ }, 0);
4161
+ return sum + compoSum;
4162
+ }
4163
+ case "dynamiczone": {
4164
+ const dzSum = value.reduce((acc, componentValue) => {
4165
+ return acc + sumDraftCounts(componentValue, componentValue.__component);
4166
+ }, 0);
4167
+ return sum + dzSum;
4168
+ }
4169
+ default:
4170
+ return sum;
4171
+ }
4172
+ }, 0);
4173
+ };
4174
+ const { ApplicationError } = strapiUtils.errors;
4175
+ const { PUBLISHED_AT_ATTRIBUTE } = strapiUtils.contentTypes.constants;
4176
+ const omitPublishedAtField = fp.omit(PUBLISHED_AT_ATTRIBUTE);
4177
+ const omitIdField = fp.omit("id");
4178
+ const documentManager = ({ strapi: strapi2 }) => {
4179
+ return {
4180
+ async findOne(id, uid2, opts = {}) {
4181
+ return strapi2.documents(uid2).findOne({ ...opts, documentId: id });
4182
+ },
4183
+ /**
4184
+ * Find multiple (or all) locales for a document
4185
+ */
4186
+ async findLocales(id, uid2, opts) {
4187
+ const where = {};
4188
+ if (id) {
4189
+ where.documentId = id;
4190
+ }
4191
+ if (Array.isArray(opts.locale)) {
4192
+ where.locale = { $in: opts.locale };
4193
+ } else if (opts.locale && opts.locale !== "*") {
4194
+ where.locale = opts.locale;
4195
+ }
4196
+ if (typeof opts.isPublished === "boolean") {
4197
+ where.publishedAt = { $notNull: opts.isPublished };
4198
+ }
4199
+ return strapi2.db.query(uid2).findMany({ populate: opts.populate, where });
4200
+ },
4201
+ async findMany(opts, uid2) {
4202
+ const params = { ...opts, populate: getDeepPopulate(uid2) };
4203
+ return strapi2.documents(uid2).findMany(params);
4204
+ },
4205
+ async findPage(opts, uid2) {
4206
+ const params = strapiUtils.pagination.withDefaultPagination(opts || {}, {
4207
+ maxLimit: 1e3
4208
+ });
4209
+ const [documents, total = 0] = await Promise.all([
4210
+ strapi2.documents(uid2).findMany(params),
4211
+ strapi2.documents(uid2).count(params)
4212
+ ]);
4213
+ return {
4214
+ results: documents,
4215
+ pagination: strapiUtils.pagination.transformPagedPaginationInfo(params, total)
4216
+ };
4217
+ },
4218
+ async create(uid2, opts = {}) {
4219
+ const populate = opts.populate ?? await buildDeepPopulate(uid2);
4220
+ const params = { ...opts, status: "draft", populate };
4221
+ return strapi2.documents(uid2).create(params);
4222
+ },
4223
+ async update(id, uid2, opts = {}) {
4224
+ const publishData = fp.pipe(omitPublishedAtField, omitIdField)(opts.data || {});
4225
+ const populate = opts.populate ?? await buildDeepPopulate(uid2);
4226
+ const params = { ...opts, data: publishData, populate, status: "draft" };
4227
+ return strapi2.documents(uid2).update({ ...params, documentId: id });
4228
+ },
4229
+ async clone(id, body, uid2) {
4230
+ const populate = await buildDeepPopulate(uid2);
4231
+ const params = {
4232
+ data: {
4233
+ ...omitIdField(body),
4234
+ [PUBLISHED_AT_ATTRIBUTE]: null
4235
+ },
4236
+ populate
4237
+ };
4238
+ return strapi2.documents(uid2).clone({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4239
+ },
4240
+ /**
4241
+ * Check if a document exists
4242
+ */
4243
+ async exists(uid2, id) {
4244
+ if (id) {
4245
+ const count2 = await strapi2.db.query(uid2).count({ where: { documentId: id } });
4246
+ return count2 > 0;
4247
+ }
4248
+ const count = await strapi2.db.query(uid2).count();
4249
+ return count > 0;
4250
+ },
4251
+ async delete(id, uid2, opts = {}) {
4252
+ const populate = await buildDeepPopulate(uid2);
4253
+ await strapi2.documents(uid2).delete({
4254
+ ...opts,
4255
+ documentId: id,
4256
+ populate
4257
+ });
4258
+ return {};
4259
+ },
4260
+ // FIXME: handle relations
4261
+ async deleteMany(documentIds, uid2, opts = {}) {
4262
+ const deletedEntries = await strapi2.db.transaction(async () => {
4263
+ return Promise.all(documentIds.map(async (id) => this.delete(id, uid2, opts)));
4264
+ });
4265
+ return { count: deletedEntries.length };
4266
+ },
4267
+ async publish(id, uid2, opts = {}) {
4268
+ const populate = await buildDeepPopulate(uid2);
4269
+ const params = { ...opts, populate };
4270
+ return strapi2.documents(uid2).publish({ ...params, documentId: id }).then((result) => result?.entries);
4271
+ },
4272
+ async publishMany(uid2, documentIds, locale) {
4273
+ return strapi2.db.transaction(async () => {
4274
+ const results = await Promise.all(
4275
+ documentIds.map((documentId) => this.publish(documentId, uid2, { locale }))
4276
+ );
4277
+ const publishedEntitiesCount = results.flat().filter(Boolean).length;
4278
+ return publishedEntitiesCount;
4279
+ });
4280
+ },
4281
+ async unpublishMany(documentIds, uid2, opts = {}) {
4282
+ const unpublishedEntries = await strapi2.db.transaction(async () => {
4283
+ return Promise.all(
4284
+ documentIds.map(
4285
+ (id) => strapi2.documents(uid2).unpublish({ ...opts, documentId: id }).then((result) => result?.entries)
4286
+ )
4287
+ );
4288
+ });
4289
+ const unpublishedEntitiesCount = unpublishedEntries.flat().filter(Boolean).length;
4290
+ return { count: unpublishedEntitiesCount };
4291
+ },
4292
+ async unpublish(id, uid2, opts = {}) {
4293
+ const populate = await buildDeepPopulate(uid2);
4294
+ const params = { ...opts, populate };
4295
+ return strapi2.documents(uid2).unpublish({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4296
+ },
4297
+ async discardDraft(id, uid2, opts = {}) {
4298
+ const populate = await buildDeepPopulate(uid2);
4299
+ const params = { ...opts, populate };
4300
+ return strapi2.documents(uid2).discardDraft({ ...params, documentId: id }).then((result) => result?.entries.at(0));
4301
+ },
4302
+ async countDraftRelations(id, uid2, locale) {
4303
+ const { populate, hasRelations } = getDeepPopulateDraftCount(uid2);
4304
+ if (!hasRelations) {
4305
+ return 0;
4306
+ }
4307
+ const document = await strapi2.documents(uid2).findOne({ documentId: id, populate, locale });
4308
+ if (!document) {
4309
+ throw new ApplicationError(
4310
+ `Unable to count draft relations, document with id ${id} and locale ${locale} not found`
4311
+ );
4312
+ }
4313
+ return sumDraftCounts(document, uid2);
4314
+ },
4315
+ async countManyEntriesDraftRelations(documentIds, uid2, locale) {
4316
+ const { populate, hasRelations } = getDeepPopulateDraftCount(uid2);
4317
+ if (!hasRelations) {
4318
+ return 0;
4319
+ }
4320
+ let localeFilter = {};
4321
+ if (locale) {
4322
+ localeFilter = Array.isArray(locale) ? { locale: { $in: locale } } : { locale };
4323
+ }
4324
+ const entities = await strapi2.db.query(uid2).findMany({
4325
+ populate,
4326
+ where: {
4327
+ documentId: { $in: documentIds },
4328
+ ...localeFilter
4329
+ }
4330
+ });
4331
+ const totalNumberDraftRelations = entities.reduce(
4332
+ (count, entity) => sumDraftCounts(entity, uid2) + count,
4333
+ 0
4334
+ );
4335
+ return totalNumberDraftRelations;
4336
+ }
4337
+ };
4338
+ };
4339
+ const services = {
4340
+ components,
4341
+ "content-types": service,
4342
+ "data-mapper": dataMapper,
4343
+ "document-metadata": documentMetadata,
4344
+ "document-manager": documentManager,
4345
+ "field-sizes": createFieldSizesService,
4346
+ metrics,
4347
+ "permission-checker": permissionChecker,
4348
+ permission,
4349
+ "populate-builder": populateBuilder$1,
4350
+ uid,
4351
+ ...history.services ? history.services : {}
4352
+ };
4353
+ const index = () => {
4354
+ return {
4355
+ register,
4356
+ bootstrap,
4357
+ destroy,
4358
+ controllers,
4359
+ routes,
4360
+ policies,
4361
+ services
4362
+ };
4363
+ };
4364
+ module.exports = index;
4365
+ //# sourceMappingURL=index.js.map