@strapi/content-manager 0.0.0-experimental.0e316dc69ac15cab63af4c7f91191d12fc2bbc27

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