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

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