@strapi/content-type-builder 0.0.0-experimental.0e316dc69ac15cab63af4c7f91191d12fc2bbc27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/LICENSE +37 -0
  2. package/README.md +1 -0
  3. package/dist/_chunks/ListView-BBUIU-Ay.js +964 -0
  4. package/dist/_chunks/ListView-BBUIU-Ay.js.map +1 -0
  5. package/dist/_chunks/ListView-Dvefai4e.mjs +959 -0
  6. package/dist/_chunks/ListView-Dvefai4e.mjs.map +1 -0
  7. package/dist/_chunks/ar-BYDB75EB.mjs +51 -0
  8. package/dist/_chunks/ar-BYDB75EB.mjs.map +1 -0
  9. package/dist/_chunks/ar-OCxhAFUy.js +51 -0
  10. package/dist/_chunks/ar-OCxhAFUy.js.map +1 -0
  11. package/dist/_chunks/cs-ChL4LaFY.mjs +139 -0
  12. package/dist/_chunks/cs-ChL4LaFY.mjs.map +1 -0
  13. package/dist/_chunks/cs-Ci3js5EC.js +139 -0
  14. package/dist/_chunks/cs-Ci3js5EC.js.map +1 -0
  15. package/dist/_chunks/de-DnlblIOh.js +193 -0
  16. package/dist/_chunks/de-DnlblIOh.js.map +1 -0
  17. package/dist/_chunks/de-DsHQNzp2.mjs +193 -0
  18. package/dist/_chunks/de-DsHQNzp2.mjs.map +1 -0
  19. package/dist/_chunks/dk-BC7NAQR2.mjs +183 -0
  20. package/dist/_chunks/dk-BC7NAQR2.mjs.map +1 -0
  21. package/dist/_chunks/dk-D3XnOjYz.js +183 -0
  22. package/dist/_chunks/dk-D3XnOjYz.js.map +1 -0
  23. package/dist/_chunks/en-CXG5y_vo.js +216 -0
  24. package/dist/_chunks/en-CXG5y_vo.js.map +1 -0
  25. package/dist/_chunks/en-jBwb53yg.mjs +216 -0
  26. package/dist/_chunks/en-jBwb53yg.mjs.map +1 -0
  27. package/dist/_chunks/es-BE_zx2_w.mjs +183 -0
  28. package/dist/_chunks/es-BE_zx2_w.mjs.map +1 -0
  29. package/dist/_chunks/es-DL8lez9W.js +183 -0
  30. package/dist/_chunks/es-DL8lez9W.js.map +1 -0
  31. package/dist/_chunks/fr-DnTxugIo.js +75 -0
  32. package/dist/_chunks/fr-DnTxugIo.js.map +1 -0
  33. package/dist/_chunks/fr-lU_OMJma.mjs +75 -0
  34. package/dist/_chunks/fr-lU_OMJma.mjs.map +1 -0
  35. package/dist/_chunks/id-DYuTgqcc.js +166 -0
  36. package/dist/_chunks/id-DYuTgqcc.js.map +1 -0
  37. package/dist/_chunks/id-W1sKBFEw.mjs +166 -0
  38. package/dist/_chunks/id-W1sKBFEw.mjs.map +1 -0
  39. package/dist/_chunks/index-CW3_BcbS.js +6742 -0
  40. package/dist/_chunks/index-CW3_BcbS.js.map +1 -0
  41. package/dist/_chunks/index-DWK63j70.mjs +6705 -0
  42. package/dist/_chunks/index-DWK63j70.mjs.map +1 -0
  43. package/dist/_chunks/index-DdDQ4Urn.mjs +1322 -0
  44. package/dist/_chunks/index-DdDQ4Urn.mjs.map +1 -0
  45. package/dist/_chunks/index-Dn4kcqyl.js +1349 -0
  46. package/dist/_chunks/index-Dn4kcqyl.js.map +1 -0
  47. package/dist/_chunks/it-D04lb2Wc.mjs +167 -0
  48. package/dist/_chunks/it-D04lb2Wc.mjs.map +1 -0
  49. package/dist/_chunks/it-DS4sM3km.js +167 -0
  50. package/dist/_chunks/it-DS4sM3km.js.map +1 -0
  51. package/dist/_chunks/ja-BHLK_2_g.mjs +50 -0
  52. package/dist/_chunks/ja-BHLK_2_g.mjs.map +1 -0
  53. package/dist/_chunks/ja-BjouJgZf.js +50 -0
  54. package/dist/_chunks/ja-BjouJgZf.js.map +1 -0
  55. package/dist/_chunks/ko-D_71Pdfn.js +183 -0
  56. package/dist/_chunks/ko-D_71Pdfn.js.map +1 -0
  57. package/dist/_chunks/ko-DoNsXHXA.mjs +183 -0
  58. package/dist/_chunks/ko-DoNsXHXA.mjs.map +1 -0
  59. package/dist/_chunks/ms-BtGFDB9t.mjs +163 -0
  60. package/dist/_chunks/ms-BtGFDB9t.mjs.map +1 -0
  61. package/dist/_chunks/ms-Re1pSHmx.js +163 -0
  62. package/dist/_chunks/ms-Re1pSHmx.js.map +1 -0
  63. package/dist/_chunks/nl-BaTAuelQ.mjs +156 -0
  64. package/dist/_chunks/nl-BaTAuelQ.mjs.map +1 -0
  65. package/dist/_chunks/nl-DQjrDEw0.js +156 -0
  66. package/dist/_chunks/nl-DQjrDEw0.js.map +1 -0
  67. package/dist/_chunks/pl-BGwXgwH7.js +193 -0
  68. package/dist/_chunks/pl-BGwXgwH7.js.map +1 -0
  69. package/dist/_chunks/pl-CP2Zgp01.mjs +193 -0
  70. package/dist/_chunks/pl-CP2Zgp01.mjs.map +1 -0
  71. package/dist/_chunks/pt-BR-CCQGwXs0.mjs +193 -0
  72. package/dist/_chunks/pt-BR-CCQGwXs0.mjs.map +1 -0
  73. package/dist/_chunks/pt-BR-DPd5nRnl.js +193 -0
  74. package/dist/_chunks/pt-BR-DPd5nRnl.js.map +1 -0
  75. package/dist/_chunks/pt-CJoUDTHQ.js +51 -0
  76. package/dist/_chunks/pt-CJoUDTHQ.js.map +1 -0
  77. package/dist/_chunks/pt-DMeTMW2x.mjs +51 -0
  78. package/dist/_chunks/pt-DMeTMW2x.mjs.map +1 -0
  79. package/dist/_chunks/ru-C8A_4j0w.js +168 -0
  80. package/dist/_chunks/ru-C8A_4j0w.js.map +1 -0
  81. package/dist/_chunks/ru-DGSjru5m.mjs +168 -0
  82. package/dist/_chunks/ru-DGSjru5m.mjs.map +1 -0
  83. package/dist/_chunks/sk-DVK4HfSC.mjs +167 -0
  84. package/dist/_chunks/sk-DVK4HfSC.mjs.map +1 -0
  85. package/dist/_chunks/sk-raWRcmPT.js +167 -0
  86. package/dist/_chunks/sk-raWRcmPT.js.map +1 -0
  87. package/dist/_chunks/sv-BGb12eW3.mjs +202 -0
  88. package/dist/_chunks/sv-BGb12eW3.mjs.map +1 -0
  89. package/dist/_chunks/sv-BNN71SFE.js +202 -0
  90. package/dist/_chunks/sv-BNN71SFE.js.map +1 -0
  91. package/dist/_chunks/th--u3VqsON.mjs +164 -0
  92. package/dist/_chunks/th--u3VqsON.mjs.map +1 -0
  93. package/dist/_chunks/th-C83Bb_kR.js +164 -0
  94. package/dist/_chunks/th-C83Bb_kR.js.map +1 -0
  95. package/dist/_chunks/tr-BW20CfcO.js +179 -0
  96. package/dist/_chunks/tr-BW20CfcO.js.map +1 -0
  97. package/dist/_chunks/tr-DsUerr-c.mjs +179 -0
  98. package/dist/_chunks/tr-DsUerr-c.mjs.map +1 -0
  99. package/dist/_chunks/uk-Bx5IlOKX.mjs +164 -0
  100. package/dist/_chunks/uk-Bx5IlOKX.mjs.map +1 -0
  101. package/dist/_chunks/uk-VwB0oiuV.js +164 -0
  102. package/dist/_chunks/uk-VwB0oiuV.js.map +1 -0
  103. package/dist/_chunks/zh-BiOCwPJu.js +202 -0
  104. package/dist/_chunks/zh-BiOCwPJu.js.map +1 -0
  105. package/dist/_chunks/zh-CsUDN13W.mjs +202 -0
  106. package/dist/_chunks/zh-CsUDN13W.mjs.map +1 -0
  107. package/dist/_chunks/zh-Hans-CLTLm_nt.js +147 -0
  108. package/dist/_chunks/zh-Hans-CLTLm_nt.js.map +1 -0
  109. package/dist/_chunks/zh-Hans-Cc0M5PXr.mjs +147 -0
  110. package/dist/_chunks/zh-Hans-Cc0M5PXr.mjs.map +1 -0
  111. package/dist/admin/index.js +8 -0
  112. package/dist/admin/index.js.map +1 -0
  113. package/dist/admin/index.mjs +8 -0
  114. package/dist/admin/index.mjs.map +1 -0
  115. package/dist/admin/src/components/AllowedTypesSelect.d.ts +9 -0
  116. package/dist/admin/src/components/AttributeIcon.d.ts +9 -0
  117. package/dist/admin/src/components/AttributeOptions/AttributeList.d.ts +6 -0
  118. package/dist/admin/src/components/AttributeOptions/AttributeOption.d.ts +11 -0
  119. package/dist/admin/src/components/AttributeOptions/AttributeOptions.d.ts +13 -0
  120. package/dist/admin/src/components/AttributeOptions/CustomFieldOption.d.ts +22 -0
  121. package/dist/admin/src/components/AttributeOptions/CustomFieldsList.d.ts +1 -0
  122. package/dist/admin/src/components/AttributeOptions/EmptyAttributes.d.ts +2 -0
  123. package/dist/admin/src/components/AttributeOptions/OptionBoxWrapper.d.ts +8 -0
  124. package/dist/admin/src/components/AutoReloadOverlayBlocker.d.ts +25 -0
  125. package/dist/admin/src/components/BooleanDefaultValueSelect.d.ts +20 -0
  126. package/dist/admin/src/components/BooleanRadioGroup.d.ts +8 -0
  127. package/dist/admin/src/components/BoxWrapper.d.ts +8 -0
  128. package/dist/admin/src/components/CheckboxWithNumberField.d.ts +11 -0
  129. package/dist/admin/src/components/ComponentCard/ComponentCard.d.ts +10 -0
  130. package/dist/admin/src/components/ComponentCard/ComponentIcon/ComponentIcon.d.ts +7 -0
  131. package/dist/admin/src/components/ComponentCard/ComponentIcon/index.d.ts +1 -0
  132. package/dist/admin/src/components/ComponentCard/index.d.ts +1 -0
  133. package/dist/admin/src/components/ComponentList.d.ts +10 -0
  134. package/dist/admin/src/components/ContentTypeBuilderNav/ContentTypeBuilderNav.d.ts +1 -0
  135. package/dist/admin/src/components/ContentTypeBuilderNav/useContentTypeBuilderMenu.d.ts +19 -0
  136. package/dist/admin/src/components/ContentTypeRadioGroup.d.ts +15 -0
  137. package/dist/admin/src/components/CustomRadioGroup/CustomRadioGroup.d.ts +15 -0
  138. package/dist/admin/src/components/CustomRadioGroup/Styles.d.ts +5 -0
  139. package/dist/admin/src/components/CustomRadioGroup/index.d.ts +1 -0
  140. package/dist/admin/src/components/DataManagerProvider/DataManagerProvider.d.ts +6 -0
  141. package/dist/admin/src/components/DataManagerProvider/constants.d.ts +17 -0
  142. package/dist/admin/src/components/DataManagerProvider/reducer.d.ts +12 -0
  143. package/dist/admin/src/components/DataManagerProvider/selectors.d.ts +17 -0
  144. package/dist/admin/src/components/DataManagerProvider/utils/cleanData.d.ts +23 -0
  145. package/dist/admin/src/components/DataManagerProvider/utils/createDataObject.d.ts +2 -0
  146. package/dist/admin/src/components/DataManagerProvider/utils/createModifiedDataSchema.d.ts +6 -0
  147. package/dist/admin/src/components/DataManagerProvider/utils/formatSchemas.d.ts +6 -0
  148. package/dist/admin/src/components/DataManagerProvider/utils/retrieveComponentsFromSchema.d.ts +4 -0
  149. package/dist/admin/src/components/DataManagerProvider/utils/retrieveComponentsThatHaveComponents.d.ts +12 -0
  150. package/dist/admin/src/components/DataManagerProvider/utils/retrieveNestedComponents.d.ts +8 -0
  151. package/dist/admin/src/components/DataManagerProvider/utils/retrieveSpecificInfoFromComponents.d.ts +1 -0
  152. package/dist/admin/src/components/DataManagerProvider/utils/serverRestartWatcher.d.ts +6 -0
  153. package/dist/admin/src/components/DataManagerProvider/utils/validateSchema.d.ts +1 -0
  154. package/dist/admin/src/components/DisplayedType.d.ts +7 -0
  155. package/dist/admin/src/components/DraftAndPublishToggle.d.ts +27 -0
  156. package/dist/admin/src/components/DynamicZoneList.d.ts +10 -0
  157. package/dist/admin/src/components/FormModal/FormModal.d.ts +1 -0
  158. package/dist/admin/src/components/FormModal/attributes/advancedForm.d.ts +416 -0
  159. package/dist/admin/src/components/FormModal/attributes/attributeOptions.d.ts +90 -0
  160. package/dist/admin/src/components/FormModal/attributes/baseForm.d.ts +376 -0
  161. package/dist/admin/src/components/FormModal/attributes/commonBaseForm.d.ts +17 -0
  162. package/dist/admin/src/components/FormModal/attributes/form.d.ts +792 -0
  163. package/dist/admin/src/components/FormModal/attributes/nameField.d.ts +12 -0
  164. package/dist/admin/src/components/FormModal/attributes/types.d.ts +325 -0
  165. package/dist/admin/src/components/FormModal/attributes/validation/common.d.ts +29 -0
  166. package/dist/admin/src/components/FormModal/category/createCategorySchema.d.ts +5 -0
  167. package/dist/admin/src/components/FormModal/category/form.d.ts +20 -0
  168. package/dist/admin/src/components/FormModal/category/regex.d.ts +1 -0
  169. package/dist/admin/src/components/FormModal/component/componentField.d.ts +20 -0
  170. package/dist/admin/src/components/FormModal/component/componentForm.d.ts +25 -0
  171. package/dist/admin/src/components/FormModal/component/createComponentSchema.d.ts +10 -0
  172. package/dist/admin/src/components/FormModal/constants.d.ts +12 -0
  173. package/dist/admin/src/components/FormModal/contentType/contentTypeForm.d.ts +116 -0
  174. package/dist/admin/src/components/FormModal/contentType/createContentTypeSchema.d.ts +24 -0
  175. package/dist/admin/src/components/FormModal/dynamiczoneForm.d.ts +68 -0
  176. package/dist/admin/src/components/FormModal/forms/forms.d.ts +207 -0
  177. package/dist/admin/src/components/FormModal/forms/utils/addItemsToFormSection.d.ts +38 -0
  178. package/dist/admin/src/components/FormModal/forms/utils/createCollectionName.d.ts +2 -0
  179. package/dist/admin/src/components/FormModal/forms/utils/getUsedAttributeNames.d.ts +11 -0
  180. package/dist/admin/src/components/FormModal/reducer.d.ts +4 -0
  181. package/dist/admin/src/components/FormModal/selectors.d.ts +16 -0
  182. package/dist/admin/src/components/FormModal/utils/canEditContentType.d.ts +18 -0
  183. package/dist/admin/src/components/FormModal/utils/createUid.d.ts +4 -0
  184. package/dist/admin/src/components/FormModal/utils/customFieldDefaultOptionsReducer.d.ts +1 -0
  185. package/dist/admin/src/components/FormModal/utils/getAttributesToDisplay.d.ts +4 -0
  186. package/dist/admin/src/components/FormModal/utils/getFormInputNames.d.ts +1 -0
  187. package/dist/admin/src/components/FormModal/utils/relations.d.ts +4 -0
  188. package/dist/admin/src/components/FormModalEndActions.d.ts +42 -0
  189. package/dist/admin/src/components/FormModalHeader.d.ts +18 -0
  190. package/dist/admin/src/components/FormModalNavigationProvider/FormModalNavigationProvider.d.ts +22 -0
  191. package/dist/admin/src/components/FormModalNavigationProvider/constants.d.ts +17 -0
  192. package/dist/admin/src/components/FormModalSubHeader.d.ts +22 -0
  193. package/dist/admin/src/components/GenericInputs.d.ts +57 -0
  194. package/dist/admin/src/components/IconPicker/IconPicker.d.ts +13 -0
  195. package/dist/admin/src/components/IconPicker/constants.d.ts +5 -0
  196. package/dist/admin/src/components/IconPicker/index.d.ts +1 -0
  197. package/dist/admin/src/components/List.d.ts +18 -0
  198. package/dist/admin/src/components/ListRow.d.ts +26 -0
  199. package/dist/admin/src/components/NestedFooter.d.ts +9 -0
  200. package/dist/admin/src/components/PluralName.d.ts +22 -0
  201. package/dist/admin/src/components/Relation/Relation.d.ts +9 -0
  202. package/dist/admin/src/components/Relation/RelationField/RelationField.d.ts +13 -0
  203. package/dist/admin/src/components/Relation/RelationField/RelationTargetPicker/RelationTargetPicker.d.ts +6 -0
  204. package/dist/admin/src/components/Relation/RelationNaturePicker/Components.d.ts +22 -0
  205. package/dist/admin/src/components/Relation/RelationNaturePicker/RelationNaturePicker.d.ts +8 -0
  206. package/dist/admin/src/components/SelectCategory.d.ts +21 -0
  207. package/dist/admin/src/components/SelectComponent.d.ts +20 -0
  208. package/dist/admin/src/components/SelectComponents.d.ts +19 -0
  209. package/dist/admin/src/components/SelectDateType.d.ts +38 -0
  210. package/dist/admin/src/components/SelectNumber.d.ts +42 -0
  211. package/dist/admin/src/components/SingularName.d.ts +17 -0
  212. package/dist/admin/src/components/TabForm.d.ts +9 -0
  213. package/dist/admin/src/components/TextareaEnum.d.ts +20 -0
  214. package/dist/admin/src/components/Tr.d.ts +5 -0
  215. package/dist/admin/src/components/UpperFirst.d.ts +3 -0
  216. package/dist/admin/src/constants.d.ts +7 -0
  217. package/dist/admin/src/contexts/DataManagerContext.d.ts +41 -0
  218. package/dist/admin/src/contexts/FormModalNavigationContext.d.ts +40 -0
  219. package/dist/admin/src/exports.d.ts +15 -0
  220. package/dist/admin/src/hooks/useDataManager.d.ts +1 -0
  221. package/dist/admin/src/hooks/useFormModalNavigation.d.ts +1 -0
  222. package/dist/admin/src/icons/Curve.d.ts +5 -0
  223. package/dist/admin/src/index.d.ts +17 -0
  224. package/dist/admin/src/pages/App/index.d.ts +2 -0
  225. package/dist/admin/src/pages/ListView/LinkToCMSettingsView.d.ts +10 -0
  226. package/dist/admin/src/pages/ListView/ListView.d.ts +2 -0
  227. package/dist/admin/src/pages/RecursivePath/RecursivePath.d.ts +1 -0
  228. package/dist/admin/src/pluginId.d.ts +1 -0
  229. package/dist/admin/src/reducers.d.ts +3 -0
  230. package/dist/admin/src/types.d.ts +57 -0
  231. package/dist/admin/src/utils/findAttribute.d.ts +2 -0
  232. package/dist/admin/src/utils/formAPI.d.ts +1 -0
  233. package/dist/admin/src/utils/getAttributeDisplayedType.d.ts +1 -0
  234. package/dist/admin/src/utils/getMaxDepth.d.ts +23 -0
  235. package/dist/admin/src/utils/getRelationType.d.ts +6 -0
  236. package/dist/admin/src/utils/getTrad.d.ts +1 -0
  237. package/dist/admin/src/utils/getYupInnerErrors.d.ts +7 -0
  238. package/dist/admin/src/utils/index.d.ts +2 -0
  239. package/dist/admin/src/utils/isAllowedContentTypesForRelations.d.ts +2 -0
  240. package/dist/admin/src/utils/makeUnique.d.ts +2 -0
  241. package/dist/admin/src/utils/nameToSlug.d.ts +1 -0
  242. package/dist/admin/src/utils/parseDateValue.d.ts +1 -0
  243. package/dist/admin/src/utils/prefixPluginTranslations.d.ts +3 -0
  244. package/dist/admin/src/utils/startsWithANumber.d.ts +1 -0
  245. package/dist/admin/src/utils/timeFormat.d.ts +16 -0
  246. package/dist/admin/src/utils/toRegressedEnumValue.d.ts +1 -0
  247. package/dist/server/index.js +2330 -0
  248. package/dist/server/index.js.map +1 -0
  249. package/dist/server/index.mjs +2309 -0
  250. package/dist/server/index.mjs.map +1 -0
  251. package/dist/server/src/bootstrap.d.ts +6 -0
  252. package/dist/server/src/bootstrap.d.ts.map +1 -0
  253. package/dist/server/src/config.d.ts +6 -0
  254. package/dist/server/src/config.d.ts.map +1 -0
  255. package/dist/server/src/controllers/builder.d.ts +6 -0
  256. package/dist/server/src/controllers/builder.d.ts.map +1 -0
  257. package/dist/server/src/controllers/component-categories.d.ts +7 -0
  258. package/dist/server/src/controllers/component-categories.d.ts.map +1 -0
  259. package/dist/server/src/controllers/components.d.ts +38 -0
  260. package/dist/server/src/controllers/components.d.ts.map +1 -0
  261. package/dist/server/src/controllers/content-types.d.ts +10 -0
  262. package/dist/server/src/controllers/content-types.d.ts.map +1 -0
  263. package/dist/server/src/controllers/index.d.ts +25 -0
  264. package/dist/server/src/controllers/index.d.ts.map +1 -0
  265. package/dist/server/src/controllers/validation/common.d.ts +25 -0
  266. package/dist/server/src/controllers/validation/common.d.ts.map +1 -0
  267. package/dist/server/src/controllers/validation/component-category.d.ts +5 -0
  268. package/dist/server/src/controllers/validation/component-category.d.ts.map +1 -0
  269. package/dist/server/src/controllers/validation/component.d.ts +25 -0
  270. package/dist/server/src/controllers/validation/component.d.ts.map +1 -0
  271. package/dist/server/src/controllers/validation/content-type.d.ts +36 -0
  272. package/dist/server/src/controllers/validation/content-type.d.ts.map +1 -0
  273. package/dist/server/src/controllers/validation/data-transform.d.ts +4 -0
  274. package/dist/server/src/controllers/validation/data-transform.d.ts.map +1 -0
  275. package/dist/server/src/controllers/validation/model-schema.d.ts +12 -0
  276. package/dist/server/src/controllers/validation/model-schema.d.ts.map +1 -0
  277. package/dist/server/src/controllers/validation/relations.d.ts +16 -0
  278. package/dist/server/src/controllers/validation/relations.d.ts.map +1 -0
  279. package/dist/server/src/controllers/validation/types.d.ts +9 -0
  280. package/dist/server/src/controllers/validation/types.d.ts.map +1 -0
  281. package/dist/server/src/index.d.ts +68 -0
  282. package/dist/server/src/index.d.ts.map +1 -0
  283. package/dist/server/src/routes/admin.d.ts +18 -0
  284. package/dist/server/src/routes/admin.d.ts.map +1 -0
  285. package/dist/server/src/routes/content-api.d.ts +10 -0
  286. package/dist/server/src/routes/content-api.d.ts.map +1 -0
  287. package/dist/server/src/routes/index.d.ts +28 -0
  288. package/dist/server/src/routes/index.d.ts.map +1 -0
  289. package/dist/server/src/services/api-handler.d.ts +15 -0
  290. package/dist/server/src/services/api-handler.d.ts.map +1 -0
  291. package/dist/server/src/services/builder.d.ts +9 -0
  292. package/dist/server/src/services/builder.d.ts.map +1 -0
  293. package/dist/server/src/services/component-categories.d.ts +13 -0
  294. package/dist/server/src/services/component-categories.d.ts.map +1 -0
  295. package/dist/server/src/services/components.d.ts +54 -0
  296. package/dist/server/src/services/components.d.ts.map +1 -0
  297. package/dist/server/src/services/constants.d.ts +18 -0
  298. package/dist/server/src/services/constants.d.ts.map +1 -0
  299. package/dist/server/src/services/content-types.d.ts +60 -0
  300. package/dist/server/src/services/content-types.d.ts.map +1 -0
  301. package/dist/server/src/services/index.d.ts +14 -0
  302. package/dist/server/src/services/index.d.ts.map +1 -0
  303. package/dist/server/src/services/schema-builder/component-builder.d.ts +39 -0
  304. package/dist/server/src/services/schema-builder/component-builder.d.ts.map +1 -0
  305. package/dist/server/src/services/schema-builder/content-type-builder.d.ts +38 -0
  306. package/dist/server/src/services/schema-builder/content-type-builder.d.ts.map +1 -0
  307. package/dist/server/src/services/schema-builder/index.d.ts +78 -0
  308. package/dist/server/src/services/schema-builder/index.d.ts.map +1 -0
  309. package/dist/server/src/services/schema-builder/schema-handler.d.ts +36 -0
  310. package/dist/server/src/services/schema-builder/schema-handler.d.ts.map +1 -0
  311. package/dist/server/src/utils/attributes.d.ts +191 -0
  312. package/dist/server/src/utils/attributes.d.ts.map +1 -0
  313. package/dist/server/src/utils/helpers.d.ts +3 -0
  314. package/dist/server/src/utils/helpers.d.ts.map +1 -0
  315. package/dist/server/src/utils/index.d.ts +15 -0
  316. package/dist/server/src/utils/index.d.ts.map +1 -0
  317. package/dist/server/src/utils/typeguards.d.ts +3 -0
  318. package/dist/server/src/utils/typeguards.d.ts.map +1 -0
  319. package/package.json +111 -0
@@ -0,0 +1,2309 @@
1
+ import _, { get, has } from "lodash";
2
+ import { getOr, snakeCase, isUndefined, has as has$1, flatMap } from "lodash/fp";
3
+ import utils, { errors, strings, contentTypes as contentTypes$2, yup, validateYupSchema } from "@strapi/utils";
4
+ import * as path from "path";
5
+ import path__default, { join } from "path";
6
+ import * as fse from "fs-extra";
7
+ import fse__default from "fs-extra";
8
+ import pluralize from "pluralize";
9
+ const config = {
10
+ default: {},
11
+ validator() {
12
+ }
13
+ };
14
+ const bootstrap = async ({ strapi: strapi2 }) => {
15
+ const actions = [
16
+ {
17
+ section: "plugins",
18
+ displayName: "Read",
19
+ uid: "read",
20
+ pluginName: "content-type-builder"
21
+ }
22
+ ];
23
+ await strapi2.service("admin::permission").actionProvider.registerMany(actions);
24
+ };
25
+ const { ApplicationError: ApplicationError$3 } = errors;
26
+ const isConfigurable = (attribute) => _.get(attribute, "configurable", true);
27
+ const isRelation = (attribute) => attribute.type === "relation";
28
+ const formatAttributes = (model) => {
29
+ const { getVisibleAttributes } = utils.contentTypes;
30
+ return getVisibleAttributes(model).reduce((acc, key) => {
31
+ acc[key] = formatAttribute(model.attributes[key]);
32
+ return acc;
33
+ }, {});
34
+ };
35
+ const formatAttribute = (attribute) => {
36
+ const { configurable, required, autoPopulate, pluginOptions } = attribute;
37
+ if (attribute.type === "media") {
38
+ return {
39
+ type: "media",
40
+ multiple: !!attribute.multiple,
41
+ required: !!required,
42
+ configurable: configurable === false ? false : void 0,
43
+ private: !!attribute.private,
44
+ allowedTypes: attribute.allowedTypes,
45
+ pluginOptions
46
+ };
47
+ }
48
+ if (attribute.type === "relation") {
49
+ return {
50
+ ...attribute,
51
+ type: "relation",
52
+ target: attribute.target,
53
+ targetAttribute: attribute.inversedBy || attribute.mappedBy || null,
54
+ configurable: configurable === false ? false : void 0,
55
+ private: !!attribute.private,
56
+ pluginOptions,
57
+ // TODO: remove
58
+ autoPopulate
59
+ };
60
+ }
61
+ return attribute;
62
+ };
63
+ const replaceTemporaryUIDs = (uidMap) => (schema) => {
64
+ return {
65
+ ...schema,
66
+ attributes: Object.keys(schema.attributes).reduce((acc, key) => {
67
+ const attr = schema.attributes[key];
68
+ if (attr.type === "component") {
69
+ if (_.has(uidMap, attr.component)) {
70
+ acc[key] = {
71
+ ...attr,
72
+ component: uidMap[attr.component]
73
+ };
74
+ return acc;
75
+ }
76
+ if (!_.has(strapi.components, attr.component)) {
77
+ throw new ApplicationError$3("component.notFound");
78
+ }
79
+ }
80
+ if (attr.type === "dynamiczone" && _.intersection(attr.components, Object.keys(uidMap)).length > 0) {
81
+ acc[key] = {
82
+ ...attr,
83
+ components: attr.components.map((value) => {
84
+ if (_.has(uidMap, value))
85
+ return uidMap[value];
86
+ if (!_.has(strapi.components, value)) {
87
+ throw new ApplicationError$3("component.notFound");
88
+ }
89
+ return value;
90
+ })
91
+ };
92
+ return acc;
93
+ }
94
+ acc[key] = attr;
95
+ return acc;
96
+ }, {})
97
+ };
98
+ };
99
+ function createSchemaHandler(infos) {
100
+ const { category, modelName, plugin, uid, dir, filename, schema } = infos;
101
+ const initialState = {
102
+ modelName,
103
+ plugin,
104
+ category,
105
+ uid,
106
+ dir,
107
+ filename,
108
+ schema: schema || {
109
+ info: {},
110
+ options: {},
111
+ attributes: {}
112
+ }
113
+ };
114
+ const state = _.cloneDeep(initialState);
115
+ Object.freeze(initialState.schema);
116
+ let modified = false;
117
+ let deleted = false;
118
+ return {
119
+ get modelName() {
120
+ return initialState.modelName;
121
+ },
122
+ get plugin() {
123
+ return initialState.plugin;
124
+ },
125
+ get category() {
126
+ return initialState.category;
127
+ },
128
+ get kind() {
129
+ return _.get(state.schema, "kind", "collectionType");
130
+ },
131
+ get uid() {
132
+ return state.uid;
133
+ },
134
+ get writable() {
135
+ return _.get(state, "plugin") !== "admin";
136
+ },
137
+ setUID(val) {
138
+ modified = true;
139
+ state.uid = val;
140
+ return this;
141
+ },
142
+ setDir(val) {
143
+ modified = true;
144
+ state.dir = val;
145
+ return this;
146
+ },
147
+ get schema() {
148
+ return _.cloneDeep(state.schema);
149
+ },
150
+ setSchema(val) {
151
+ modified = true;
152
+ state.schema = _.cloneDeep(val);
153
+ return this;
154
+ },
155
+ // get a particular path inside the schema
156
+ get(path2) {
157
+ return _.get(state.schema, path2);
158
+ },
159
+ // set a particular path inside the schema
160
+ set(path2, val) {
161
+ if (!state.schema)
162
+ return this;
163
+ modified = true;
164
+ const value = _.defaultTo(val, _.get(state.schema, path2));
165
+ _.set(state.schema, path2, value);
166
+ return this;
167
+ },
168
+ // delete a particular path inside the schema
169
+ unset(path2) {
170
+ modified = true;
171
+ _.unset(state.schema, path2);
172
+ return this;
173
+ },
174
+ delete() {
175
+ deleted = true;
176
+ return this;
177
+ },
178
+ getAttribute(key) {
179
+ return this.get(["attributes", key]);
180
+ },
181
+ setAttribute(key, attribute) {
182
+ return this.set(["attributes", key], attribute);
183
+ },
184
+ deleteAttribute(key) {
185
+ return this.unset(["attributes", key]);
186
+ },
187
+ setAttributes(newAttributes) {
188
+ if (!this.schema)
189
+ return this;
190
+ for (const key in this.schema.attributes) {
191
+ if (isConfigurable(this.schema.attributes[key])) {
192
+ this.deleteAttribute(key);
193
+ }
194
+ }
195
+ for (const key of Object.keys(newAttributes)) {
196
+ this.setAttribute(key, newAttributes[key]);
197
+ }
198
+ return this;
199
+ },
200
+ removeContentType(uid2) {
201
+ if (!state.schema)
202
+ return this;
203
+ const attributes = state.schema.attributes;
204
+ Object.keys(attributes).forEach((key) => {
205
+ const attribute = attributes[key];
206
+ if (attribute.target === uid2) {
207
+ this.deleteAttribute(key);
208
+ }
209
+ });
210
+ return this;
211
+ },
212
+ // utils
213
+ removeComponent(uid2) {
214
+ if (!state.schema)
215
+ return this;
216
+ const attributes = state.schema.attributes;
217
+ Object.keys(attributes).forEach((key) => {
218
+ const attr = attributes[key];
219
+ if (attr.type === "component" && attr.component === uid2) {
220
+ this.deleteAttribute(key);
221
+ }
222
+ if (attr.type === "dynamiczone" && Array.isArray(attr.components) && attr.components.includes(uid2)) {
223
+ const updatedComponentList = attributes[key].components.filter(
224
+ (val) => val !== uid2
225
+ );
226
+ this.set(["attributes", key, "components"], updatedComponentList);
227
+ }
228
+ });
229
+ return this;
230
+ },
231
+ updateComponent(uid2, newUID) {
232
+ if (!state.schema)
233
+ return this;
234
+ const attributes = state.schema.attributes;
235
+ Object.keys(attributes).forEach((key) => {
236
+ const attr = attributes[key];
237
+ if (attr.type === "component" && attr.component === uid2) {
238
+ this.set(["attributes", key, "component"], newUID);
239
+ }
240
+ if (attr.type === "dynamiczone" && Array.isArray(attr.components) && attr.components.includes(uid2)) {
241
+ const updatedComponentList = attr.components.map(
242
+ (val) => val === uid2 ? newUID : val
243
+ );
244
+ this.set(["attributes", key, "components"], updatedComponentList);
245
+ }
246
+ });
247
+ return this;
248
+ },
249
+ // save the schema to disk
250
+ async flush() {
251
+ if (!this.writable) {
252
+ return;
253
+ }
254
+ const initialPath = path__default.join(initialState.dir, initialState.filename);
255
+ const filePath = path__default.join(state.dir, state.filename);
256
+ if (deleted) {
257
+ await fse__default.remove(initialPath);
258
+ const list = await fse__default.readdir(initialState.dir);
259
+ if (list.length === 0) {
260
+ await fse__default.remove(initialState.dir);
261
+ }
262
+ return;
263
+ }
264
+ if (modified) {
265
+ if (!state.schema)
266
+ return Promise.resolve();
267
+ await fse__default.ensureFile(filePath);
268
+ await fse__default.writeJSON(
269
+ filePath,
270
+ {
271
+ kind: state.schema.kind,
272
+ collectionName: state.schema.collectionName,
273
+ info: state.schema.info,
274
+ options: state.schema.options,
275
+ pluginOptions: state.schema.pluginOptions,
276
+ attributes: state.schema.attributes,
277
+ config: state.schema.config
278
+ },
279
+ { spaces: 2 }
280
+ );
281
+ if (initialPath !== filePath) {
282
+ await fse__default.remove(initialPath);
283
+ const list = await fse__default.readdir(initialState.dir);
284
+ if (list.length === 0) {
285
+ await fse__default.remove(initialState.dir);
286
+ }
287
+ }
288
+ return;
289
+ }
290
+ return Promise.resolve();
291
+ },
292
+ // reset the schema to its initial value
293
+ async rollback() {
294
+ if (!this.writable) {
295
+ return;
296
+ }
297
+ const initialPath = path__default.join(initialState.dir, initialState.filename);
298
+ const filePath = path__default.join(state.dir, state.filename);
299
+ if (!initialState.uid) {
300
+ await fse__default.remove(filePath);
301
+ const list = await fse__default.readdir(state.dir);
302
+ if (list.length === 0) {
303
+ await fse__default.remove(state.dir);
304
+ }
305
+ return;
306
+ }
307
+ if (modified || deleted) {
308
+ await fse__default.ensureFile(initialPath);
309
+ await fse__default.writeJSON(initialPath, initialState.schema, { spaces: 2 });
310
+ if (initialPath !== filePath) {
311
+ await fse__default.remove(filePath);
312
+ const list = await fse__default.readdir(state.dir);
313
+ if (list.length === 0) {
314
+ await fse__default.remove(state.dir);
315
+ }
316
+ }
317
+ }
318
+ return Promise.resolve();
319
+ }
320
+ };
321
+ }
322
+ const { ApplicationError: ApplicationError$2 } = errors;
323
+ function createComponentBuilder$1() {
324
+ return {
325
+ createComponentUID({ category, displayName }) {
326
+ return `${strings.nameToSlug(category)}.${strings.nameToSlug(displayName)}`;
327
+ },
328
+ createNewComponentUIDMap(components2) {
329
+ return components2.reduce((uidMap, component) => {
330
+ uidMap[component.tmpUID] = this.createComponentUID(component);
331
+ return uidMap;
332
+ }, {});
333
+ },
334
+ /**
335
+ * create a component in the tmpComponent map
336
+ */
337
+ createComponent(infos) {
338
+ const uid = this.createComponentUID(infos);
339
+ if (this.components.has(uid)) {
340
+ throw new ApplicationError$2("component.alreadyExists");
341
+ }
342
+ const handler = createSchemaHandler({
343
+ dir: path__default.join(strapi.dirs.app.components, strings.nameToSlug(infos.category)),
344
+ filename: `${strings.nameToSlug(infos.displayName)}.json`
345
+ });
346
+ const collectionName = `components_${strings.nameToCollectionName(
347
+ infos.category
348
+ )}_${strings.nameToCollectionName(pluralize(infos.displayName))}`;
349
+ this.components.forEach((compo) => {
350
+ if (compo.schema.collectionName === collectionName) {
351
+ throw new ApplicationError$2("component.alreadyExists");
352
+ }
353
+ });
354
+ handler.setUID(uid).set("collectionName", collectionName).set(["info", "displayName"], infos.displayName).set(["info", "icon"], infos.icon).set(["info", "description"], infos.description).set("pluginOptions", infos.pluginOptions).set("config", infos.config).setAttributes(this.convertAttributes(infos.attributes));
355
+ if (this.components.size === 0) {
356
+ strapi.telemetry.send("didCreateFirstComponent");
357
+ } else {
358
+ strapi.telemetry.send("didCreateComponent");
359
+ }
360
+ this.components.set(uid, handler);
361
+ return handler;
362
+ },
363
+ /**
364
+ * create a component in the tmpComponent map
365
+ */
366
+ editComponent(infos) {
367
+ const { uid } = infos;
368
+ if (!this.components.has(uid)) {
369
+ throw new errors.ApplicationError("component.notFound");
370
+ }
371
+ const component = this.components.get(uid);
372
+ const [, nameUID] = uid.split(".");
373
+ const newCategory = strings.nameToSlug(infos.category);
374
+ const newUID = `${newCategory}.${nameUID}`;
375
+ if (newUID !== uid && this.components.has(newUID)) {
376
+ throw new errors.ApplicationError("component.edit.alreadyExists");
377
+ }
378
+ const newDir = path__default.join(strapi.dirs.app.components, newCategory);
379
+ const oldAttributes = component.schema.attributes;
380
+ const newAttributes = _.omitBy(infos.attributes, (attr, key) => {
381
+ return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);
382
+ });
383
+ component.setUID(newUID).setDir(newDir).set(["info", "displayName"], infos.displayName).set(["info", "icon"], infos.icon).set(["info", "description"], infos.description).set("pluginOptions", infos.pluginOptions).setAttributes(this.convertAttributes(newAttributes));
384
+ if (newUID !== uid) {
385
+ this.components.forEach((compo) => {
386
+ compo.updateComponent(uid, newUID);
387
+ });
388
+ this.contentTypes.forEach((ct) => {
389
+ ct.updateComponent(uid, newUID);
390
+ });
391
+ }
392
+ return component;
393
+ },
394
+ deleteComponent(uid) {
395
+ if (!this.components.has(uid)) {
396
+ throw new errors.ApplicationError("component.notFound");
397
+ }
398
+ this.components.forEach((compo) => {
399
+ compo.removeComponent(uid);
400
+ });
401
+ this.contentTypes.forEach((ct) => {
402
+ ct.removeComponent(uid);
403
+ });
404
+ return this.components.get(uid).delete();
405
+ }
406
+ };
407
+ }
408
+ const modelTypes = {
409
+ CONTENT_TYPE: "CONTENT_TYPE",
410
+ COMPONENT: "COMPONENT"
411
+ };
412
+ const typeKinds = {
413
+ SINGLE_TYPE: "singleType",
414
+ COLLECTION_TYPE: "collectionType"
415
+ };
416
+ const DEFAULT_TYPES = [
417
+ // advanced types
418
+ "media",
419
+ // scalar types
420
+ "string",
421
+ "text",
422
+ "richtext",
423
+ "blocks",
424
+ "json",
425
+ "enumeration",
426
+ "password",
427
+ "email",
428
+ "integer",
429
+ "biginteger",
430
+ "float",
431
+ "decimal",
432
+ "date",
433
+ "time",
434
+ "datetime",
435
+ "timestamp",
436
+ "boolean",
437
+ "relation"
438
+ ];
439
+ const VALID_UID_TARGETS = ["string", "text"];
440
+ const coreUids = {
441
+ STRAPI_USER: "admin::user",
442
+ PREFIX: "strapi::"
443
+ };
444
+ const pluginsUids = {
445
+ UPLOAD_FILE: "plugin::upload.file"
446
+ };
447
+ const { ApplicationError: ApplicationError$1 } = errors;
448
+ const reuseUnsetPreviousProperties = (newAttribute, oldAttribute) => {
449
+ _.defaults(
450
+ newAttribute,
451
+ _.omit(oldAttribute, [
452
+ "configurable",
453
+ "required",
454
+ "private",
455
+ "unique",
456
+ "pluginOptions",
457
+ "inversedBy",
458
+ "mappedBy"
459
+ ])
460
+ );
461
+ };
462
+ function createComponentBuilder() {
463
+ return {
464
+ setRelation({ key, uid, attribute }) {
465
+ if (!_.has(attribute, "target")) {
466
+ return;
467
+ }
468
+ const targetCT = this.contentTypes.get(attribute.target);
469
+ const targetAttribute = targetCT.getAttribute(attribute.targetAttribute);
470
+ if (!attribute.targetAttribute) {
471
+ return;
472
+ }
473
+ targetCT.setAttribute(
474
+ attribute.targetAttribute,
475
+ generateRelation({ key, attribute, uid, targetAttribute })
476
+ );
477
+ },
478
+ unsetRelation(attribute) {
479
+ if (!_.has(attribute, "target")) {
480
+ return;
481
+ }
482
+ const targetCT = this.contentTypes.get(attribute.target);
483
+ const targetAttributeName = attribute.inversedBy || attribute.mappedBy;
484
+ const targetAttribute = targetCT.getAttribute(targetAttributeName);
485
+ if (!targetAttribute)
486
+ return;
487
+ return targetCT.deleteAttribute(targetAttributeName);
488
+ },
489
+ /**
490
+ * Creates a content type in memory to be written to files later on
491
+ */
492
+ createContentType(infos) {
493
+ const uid = createContentTypeUID(infos);
494
+ if (this.contentTypes.has(uid)) {
495
+ throw new ApplicationError$1("contentType.alreadyExists");
496
+ }
497
+ const contentType = createSchemaHandler({
498
+ modelName: infos.singularName,
499
+ dir: path__default.join(
500
+ strapi.dirs.app.api,
501
+ infos.singularName,
502
+ "content-types",
503
+ infos.singularName
504
+ ),
505
+ filename: `schema.json`
506
+ });
507
+ this.contentTypes.set(uid, contentType);
508
+ Object.keys(infos.attributes).forEach((key) => {
509
+ const { target } = infos.attributes[key];
510
+ if (target === "__self__") {
511
+ infos.attributes[key].target = uid;
512
+ }
513
+ });
514
+ contentType.setUID(uid).set("kind", infos.kind || typeKinds.COLLECTION_TYPE).set(
515
+ "collectionName",
516
+ infos.collectionName || strings.nameToCollectionName(infos.pluralName)
517
+ ).set("info", {
518
+ singularName: infos.singularName,
519
+ pluralName: infos.pluralName,
520
+ displayName: infos.displayName,
521
+ description: infos.description
522
+ }).set("options", {
523
+ ...infos.options ?? {},
524
+ draftAndPublish: infos.draftAndPublish
525
+ }).set("pluginOptions", infos.pluginOptions).set("config", infos.config).setAttributes(this.convertAttributes(infos.attributes));
526
+ Object.keys(infos.attributes).forEach((key) => {
527
+ const attribute = infos.attributes[key];
528
+ if (isRelation(attribute)) {
529
+ if (["manyToMany", "oneToOne"].includes(attribute.relation)) {
530
+ if (attribute.target === uid && attribute.targetAttribute !== void 0) {
531
+ const targetAttribute = infos.attributes[attribute.targetAttribute];
532
+ if (targetAttribute.dominant === void 0) {
533
+ attribute.dominant = true;
534
+ } else {
535
+ attribute.dominant = false;
536
+ }
537
+ } else {
538
+ attribute.dominant = true;
539
+ }
540
+ }
541
+ this.setRelation({
542
+ key,
543
+ uid,
544
+ attribute
545
+ });
546
+ }
547
+ });
548
+ return contentType;
549
+ },
550
+ editContentType(infos) {
551
+ const { uid } = infos;
552
+ if (!this.contentTypes.has(uid)) {
553
+ throw new ApplicationError$1("contentType.notFound");
554
+ }
555
+ const contentType = this.contentTypes.get(uid);
556
+ const oldAttributes = contentType.schema.attributes;
557
+ const newAttributes = _.omitBy(infos.attributes, (attr, key) => {
558
+ return _.has(oldAttributes, key) && !isConfigurable(oldAttributes[key]);
559
+ });
560
+ const newKeys = _.difference(Object.keys(newAttributes), Object.keys(oldAttributes));
561
+ const deletedKeys = _.difference(Object.keys(oldAttributes), Object.keys(newAttributes));
562
+ const remainingKeys = _.intersection(Object.keys(oldAttributes), Object.keys(newAttributes));
563
+ deletedKeys.forEach((key) => {
564
+ const attribute = oldAttributes[key];
565
+ const targetAttributeName = attribute.inversedBy || attribute.mappedBy;
566
+ if (isConfigurable(attribute) && isRelation(attribute) && !_.isNil(targetAttributeName)) {
567
+ this.unsetRelation(attribute);
568
+ }
569
+ });
570
+ remainingKeys.forEach((key) => {
571
+ const oldAttribute = oldAttributes[key];
572
+ const newAttribute = newAttributes[key];
573
+ if (!isRelation(oldAttribute) && isRelation(newAttribute)) {
574
+ return this.setRelation({
575
+ key,
576
+ uid,
577
+ attribute: newAttributes[key]
578
+ });
579
+ }
580
+ if (isRelation(oldAttribute) && !isRelation(newAttribute)) {
581
+ return this.unsetRelation(oldAttribute);
582
+ }
583
+ if (isRelation(oldAttribute) && isRelation(newAttribute)) {
584
+ const oldTargetAttributeName = oldAttribute.inversedBy || oldAttribute.mappedBy;
585
+ const sameRelation = oldAttribute.relation === newAttribute.relation;
586
+ const targetAttributeHasChanged = oldTargetAttributeName !== newAttribute.targetAttribute;
587
+ if (!sameRelation || targetAttributeHasChanged) {
588
+ this.unsetRelation(oldAttribute);
589
+ }
590
+ reuseUnsetPreviousProperties(newAttribute, oldAttribute);
591
+ if (oldAttribute.inversedBy) {
592
+ newAttribute.dominant = true;
593
+ } else if (oldAttribute.mappedBy) {
594
+ newAttribute.dominant = false;
595
+ }
596
+ return this.setRelation({
597
+ key,
598
+ uid,
599
+ attribute: newAttribute
600
+ });
601
+ }
602
+ });
603
+ newKeys.forEach((key) => {
604
+ const attribute = newAttributes[key];
605
+ if (isRelation(attribute)) {
606
+ if (["manyToMany", "oneToOne"].includes(attribute.relation)) {
607
+ if (attribute.target === uid && attribute.targetAttribute !== void 0) {
608
+ const targetAttribute = newAttributes[attribute.targetAttribute];
609
+ if (targetAttribute.dominant === void 0) {
610
+ attribute.dominant = true;
611
+ } else {
612
+ attribute.dominant = false;
613
+ }
614
+ } else {
615
+ attribute.dominant = true;
616
+ }
617
+ }
618
+ this.setRelation({
619
+ key,
620
+ uid,
621
+ attribute
622
+ });
623
+ }
624
+ });
625
+ contentType.set("kind", infos.kind || contentType.schema.kind).set(["info", "displayName"], infos.displayName).set(["info", "description"], infos.description).set("options", {
626
+ ...infos.options ?? {},
627
+ draftAndPublish: infos.draftAndPublish
628
+ }).set("pluginOptions", infos.pluginOptions).setAttributes(this.convertAttributes(newAttributes));
629
+ return contentType;
630
+ },
631
+ deleteContentType(uid) {
632
+ if (!this.contentTypes.has(uid)) {
633
+ throw new ApplicationError$1("contentType.notFound");
634
+ }
635
+ this.components.forEach((compo) => {
636
+ compo.removeContentType(uid);
637
+ });
638
+ this.contentTypes.forEach((ct) => {
639
+ ct.removeContentType(uid);
640
+ });
641
+ return this.contentTypes.get(uid).delete();
642
+ }
643
+ };
644
+ }
645
+ const createContentTypeUID = ({
646
+ singularName
647
+ }) => `api::${singularName}.${singularName}`;
648
+ const generateRelation = ({ key, attribute, uid, targetAttribute = {} }) => {
649
+ const opts = {
650
+ type: "relation",
651
+ target: uid,
652
+ autoPopulate: targetAttribute.autoPopulate,
653
+ private: targetAttribute.private || void 0,
654
+ pluginOptions: targetAttribute.pluginOptions || void 0
655
+ };
656
+ switch (attribute.relation) {
657
+ case "oneToOne": {
658
+ opts.relation = "oneToOne";
659
+ if (attribute.dominant) {
660
+ opts.mappedBy = key;
661
+ } else {
662
+ opts.inversedBy = key;
663
+ }
664
+ break;
665
+ }
666
+ case "oneToMany": {
667
+ opts.relation = "manyToOne";
668
+ opts.inversedBy = key;
669
+ break;
670
+ }
671
+ case "manyToOne": {
672
+ opts.relation = "oneToMany";
673
+ opts.mappedBy = key;
674
+ break;
675
+ }
676
+ case "manyToMany": {
677
+ opts.relation = "manyToMany";
678
+ if (attribute.dominant) {
679
+ opts.mappedBy = key;
680
+ } else {
681
+ opts.inversedBy = key;
682
+ }
683
+ break;
684
+ }
685
+ }
686
+ const { type, relation, target, ...restOptions } = opts;
687
+ return {
688
+ type,
689
+ relation,
690
+ target,
691
+ ...restOptions
692
+ };
693
+ };
694
+ function createBuilder() {
695
+ const components2 = Object.values(strapi.components).map((componentInput) => ({
696
+ category: componentInput.category,
697
+ modelName: componentInput.modelName,
698
+ plugin: componentInput.modelName,
699
+ uid: componentInput.uid,
700
+ filename: componentInput.__filename__,
701
+ dir: join(strapi.dirs.app.components, componentInput.category),
702
+ schema: componentInput.__schema__,
703
+ config: componentInput.config
704
+ }));
705
+ const contentTypes2 = Object.values(strapi.contentTypes).map((contentTypeInput) => {
706
+ const dir = contentTypeInput.plugin ? join(
707
+ strapi.dirs.app.extensions,
708
+ contentTypeInput.plugin,
709
+ "content-types",
710
+ contentTypeInput.info.singularName
711
+ ) : join(
712
+ strapi.dirs.app.api,
713
+ contentTypeInput.apiName,
714
+ "content-types",
715
+ contentTypeInput.info.singularName
716
+ );
717
+ return {
718
+ modelName: contentTypeInput.modelName,
719
+ plugin: contentTypeInput.plugin,
720
+ uid: contentTypeInput.uid,
721
+ filename: "schema.json",
722
+ dir,
723
+ schema: contentTypeInput.__schema__,
724
+ config: contentTypeInput.config
725
+ };
726
+ });
727
+ return createSchemaBuilder({
728
+ components: components2,
729
+ contentTypes: contentTypes2
730
+ });
731
+ }
732
+ function createSchemaBuilder({ components: components2, contentTypes: contentTypes2 }) {
733
+ const tmpComponents = /* @__PURE__ */ new Map();
734
+ const tmpContentTypes = /* @__PURE__ */ new Map();
735
+ Object.keys(contentTypes2).forEach((key) => {
736
+ tmpContentTypes.set(contentTypes2[key].uid, createSchemaHandler(contentTypes2[key]));
737
+ });
738
+ Object.keys(components2).forEach((key) => {
739
+ tmpComponents.set(components2[key].uid, createSchemaHandler(components2[key]));
740
+ });
741
+ return {
742
+ get components() {
743
+ return tmpComponents;
744
+ },
745
+ get contentTypes() {
746
+ return tmpContentTypes;
747
+ },
748
+ /**
749
+ * Convert Attributes received from the API to the right syntax
750
+ */
751
+ convertAttributes(attributes) {
752
+ return Object.keys(attributes).reduce(
753
+ (acc, key) => {
754
+ const attribute = attributes[key];
755
+ const { configurable, private: isPrivate } = attribute;
756
+ const baseProperties = {
757
+ private: isPrivate === true ? true : void 0,
758
+ configurable: configurable === false ? false : void 0
759
+ };
760
+ if (attribute.type === "relation") {
761
+ const { target, relation, targetAttribute, dominant, ...restOfProperties } = attribute;
762
+ const attr = {
763
+ type: "relation",
764
+ relation,
765
+ target,
766
+ ...restOfProperties,
767
+ ...baseProperties
768
+ };
769
+ acc[key] = attr;
770
+ if (target && !this.contentTypes.has(target)) {
771
+ throw new errors.ApplicationError(`target: ${target} does not exist`);
772
+ }
773
+ if (_.isNil(targetAttribute)) {
774
+ return acc;
775
+ }
776
+ if (["oneToOne", "manyToMany"].includes(relation) && dominant === true) {
777
+ attr.inversedBy = targetAttribute;
778
+ } else if (["oneToOne", "manyToMany"].includes(relation) && dominant === false) {
779
+ attr.mappedBy = targetAttribute;
780
+ } else if (["oneToOne", "manyToOne", "manyToMany"].includes(relation)) {
781
+ attr.inversedBy = targetAttribute;
782
+ } else if (["oneToMany"].includes(relation)) {
783
+ attr.mappedBy = targetAttribute;
784
+ }
785
+ return acc;
786
+ }
787
+ acc[key] = {
788
+ ...attribute,
789
+ ...baseProperties
790
+ };
791
+ return acc;
792
+ },
793
+ {}
794
+ );
795
+ },
796
+ ...createComponentBuilder$1(),
797
+ ...createComponentBuilder(),
798
+ /**
799
+ * Write all type to files
800
+ */
801
+ writeFiles() {
802
+ const schemas = [
803
+ ...Array.from(tmpComponents.values()),
804
+ ...Array.from(tmpContentTypes.values())
805
+ ];
806
+ return Promise.all(schemas.map((schema) => schema.flush())).catch((error) => {
807
+ strapi.log.error("Error writing schema files");
808
+ strapi.log.error(error);
809
+ return this.rollback();
810
+ }).catch((error) => {
811
+ strapi.log.error(
812
+ "Error rolling back schema files. You might need to fix your files manually"
813
+ );
814
+ strapi.log.error(error);
815
+ throw new errors.ApplicationError("Invalid schema edition");
816
+ });
817
+ },
818
+ /**
819
+ * rollback all files
820
+ */
821
+ rollback() {
822
+ return Promise.all(
823
+ [...Array.from(tmpComponents.values()), ...Array.from(tmpContentTypes.values())].map(
824
+ (schema) => schema.rollback()
825
+ )
826
+ );
827
+ }
828
+ };
829
+ }
830
+ const { ApplicationError } = errors;
831
+ const isContentTypeVisible = (model) => getOr(true, "pluginOptions.content-type-builder.visible", model) === true;
832
+ const getRestrictRelationsTo = (contentType) => {
833
+ const { uid } = contentType;
834
+ if (uid === coreUids.STRAPI_USER) {
835
+ return ["oneWay", "manyWay"];
836
+ }
837
+ if (uid.startsWith(coreUids.PREFIX) || uid === pluginsUids.UPLOAD_FILE || !isContentTypeVisible(contentType)) {
838
+ return [];
839
+ }
840
+ return null;
841
+ };
842
+ const formatContentType = (contentType) => {
843
+ const { uid, kind, modelName, plugin, collectionName, info } = contentType;
844
+ return {
845
+ uid,
846
+ plugin,
847
+ apiID: modelName,
848
+ schema: {
849
+ ...contentTypes$2.getOptions(contentType),
850
+ displayName: info.displayName,
851
+ singularName: info.singularName,
852
+ pluralName: info.pluralName,
853
+ description: _.get(info, "description", ""),
854
+ pluginOptions: contentType.pluginOptions,
855
+ kind: kind || "collectionType",
856
+ collectionName,
857
+ attributes: formatAttributes(contentType),
858
+ visible: isContentTypeVisible(contentType),
859
+ restrictRelationsTo: getRestrictRelationsTo(contentType)
860
+ }
861
+ };
862
+ };
863
+ const createContentTypes = async (contentTypes2) => {
864
+ const builder2 = createBuilder();
865
+ const createdContentTypes = [];
866
+ for (const contentType of contentTypes2) {
867
+ createdContentTypes.push(await createContentType(contentType, { defaultBuilder: builder2 }));
868
+ }
869
+ await builder2.writeFiles();
870
+ return createdContentTypes;
871
+ };
872
+ const createContentType = async ({ contentType, components: components2 }, options = {}) => {
873
+ const builder2 = options.defaultBuilder || createBuilder();
874
+ const uidMap = builder2.createNewComponentUIDMap(components2 || []);
875
+ const replaceTmpUIDs = replaceTemporaryUIDs(uidMap);
876
+ const newContentType = builder2.createContentType(replaceTmpUIDs(contentType));
877
+ const targetContentType = (infos) => {
878
+ Object.keys(infos.attributes).forEach((key) => {
879
+ const { target } = infos.attributes[key];
880
+ if (target === "__contentType__") {
881
+ infos.attributes[key].target = newContentType.uid;
882
+ }
883
+ });
884
+ return infos;
885
+ };
886
+ components2?.forEach((component) => {
887
+ const options2 = replaceTmpUIDs(targetContentType(component));
888
+ if (!_.has(component, "uid")) {
889
+ return builder2.createComponent(options2);
890
+ }
891
+ return builder2.editComponent(options2);
892
+ });
893
+ await generateAPI({
894
+ displayName: contentType.displayName || contentType.info.displayName,
895
+ singularName: contentType.singularName,
896
+ pluralName: contentType.pluralName,
897
+ kind: contentType.kind
898
+ });
899
+ if (!options.defaultBuilder) {
900
+ await builder2.writeFiles();
901
+ }
902
+ strapi.eventHub.emit("content-type.create", { contentType: newContentType });
903
+ return newContentType;
904
+ };
905
+ const generateAPI = ({
906
+ singularName,
907
+ kind = "collectionType",
908
+ pluralName,
909
+ displayName
910
+ }) => {
911
+ const strapiGenerators = require("@strapi/generators");
912
+ return strapiGenerators.generate(
913
+ "content-type",
914
+ {
915
+ kind,
916
+ singularName,
917
+ id: singularName,
918
+ pluralName,
919
+ displayName,
920
+ destination: "new",
921
+ bootstrapApi: true,
922
+ attributes: []
923
+ },
924
+ { dir: strapi.dirs.app.root }
925
+ );
926
+ };
927
+ const editContentType = async (uid, { contentType, components: components2 = [] }) => {
928
+ const builder2 = createBuilder();
929
+ const previousSchema = builder2.contentTypes.get(uid).schema;
930
+ const previousKind = previousSchema.kind;
931
+ const newKind = contentType.kind || previousKind;
932
+ const previousAttributes = previousSchema.attributes;
933
+ const prevNonVisibleAttributes = contentTypes$2.getNonVisibleAttributes(previousSchema).reduce((acc, key) => {
934
+ if (key in previousAttributes) {
935
+ acc[key] = previousAttributes[key];
936
+ }
937
+ return acc;
938
+ }, {});
939
+ contentType.attributes = _.merge(prevNonVisibleAttributes, contentType.attributes);
940
+ if (newKind !== previousKind && newKind === "singleType") {
941
+ const entryCount = await strapi.db.query(uid).count();
942
+ if (entryCount > 1) {
943
+ throw new ApplicationError(
944
+ "You cannot convert a collectionType to a singleType when having multiple entries in DB"
945
+ );
946
+ }
947
+ }
948
+ const uidMap = builder2.createNewComponentUIDMap(components2);
949
+ const replaceTmpUIDs = replaceTemporaryUIDs(uidMap);
950
+ const updatedContentType = builder2.editContentType({
951
+ uid,
952
+ ...replaceTmpUIDs(contentType)
953
+ });
954
+ components2.forEach((component) => {
955
+ if (!_.has(component, "uid")) {
956
+ return builder2.createComponent(replaceTmpUIDs(component));
957
+ }
958
+ return builder2.editComponent(replaceTmpUIDs(component));
959
+ });
960
+ if (newKind !== previousKind) {
961
+ const apiHandler2 = strapi.plugin("content-type-builder").service("api-handler");
962
+ await apiHandler2.backup(uid);
963
+ try {
964
+ await apiHandler2.clear(uid);
965
+ await generateAPI({
966
+ displayName: updatedContentType.schema.info.displayName,
967
+ singularName: updatedContentType.schema.info.singularName,
968
+ pluralName: updatedContentType.schema.info.pluralName,
969
+ kind: updatedContentType.schema.kind
970
+ });
971
+ await builder2.writeFiles();
972
+ } catch (error) {
973
+ strapi.log.error(error);
974
+ await apiHandler2.rollback(uid);
975
+ }
976
+ return updatedContentType;
977
+ }
978
+ await builder2.writeFiles();
979
+ strapi.eventHub.emit("content-type.update", { contentType: updatedContentType });
980
+ return updatedContentType;
981
+ };
982
+ const deleteContentTypes = async (uids) => {
983
+ const builder2 = createBuilder();
984
+ const apiHandler2 = strapi.plugin("content-type-builder").service("api-handler");
985
+ for (const uid of uids) {
986
+ await deleteContentType(uid, builder2);
987
+ }
988
+ await builder2.writeFiles();
989
+ for (const uid of uids) {
990
+ try {
991
+ await apiHandler2.clear(uid);
992
+ } catch (error) {
993
+ strapi.log.error(error);
994
+ await apiHandler2.rollback(uid);
995
+ }
996
+ }
997
+ };
998
+ const deleteContentType = async (uid, defaultBuilder = void 0) => {
999
+ const builder2 = defaultBuilder || createBuilder();
1000
+ const apiHandler2 = strapi.plugin("content-type-builder").service("api-handler");
1001
+ await apiHandler2.backup(uid);
1002
+ const contentType = builder2.deleteContentType(uid);
1003
+ if (!defaultBuilder) {
1004
+ try {
1005
+ await builder2.writeFiles();
1006
+ await apiHandler2.clear(uid);
1007
+ } catch (error) {
1008
+ await apiHandler2.rollback(uid);
1009
+ }
1010
+ }
1011
+ strapi.eventHub.emit("content-type.delete", { contentType });
1012
+ return contentType;
1013
+ };
1014
+ const contentTypes$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1015
+ __proto__: null,
1016
+ createContentType,
1017
+ createContentTypes,
1018
+ deleteContentType,
1019
+ deleteContentTypes,
1020
+ editContentType,
1021
+ formatContentType,
1022
+ generateAPI,
1023
+ getRestrictRelationsTo,
1024
+ isContentTypeVisible
1025
+ }, Symbol.toStringTag, { value: "Module" }));
1026
+ const formatComponent = (component) => {
1027
+ const { uid, modelName, connection, collectionName, info, category } = component;
1028
+ return {
1029
+ uid,
1030
+ category,
1031
+ apiId: modelName,
1032
+ schema: {
1033
+ displayName: get(info, "displayName"),
1034
+ description: get(info, "description", ""),
1035
+ icon: get(info, "icon"),
1036
+ connection,
1037
+ collectionName,
1038
+ pluginOptions: component.pluginOptions,
1039
+ attributes: formatAttributes(component)
1040
+ }
1041
+ };
1042
+ };
1043
+ const createComponent = async ({ component, components: components2 = [] }) => {
1044
+ const builder2 = createBuilder();
1045
+ const uidMap = builder2.createNewComponentUIDMap(components2);
1046
+ const replaceTmpUIDs = replaceTemporaryUIDs(uidMap);
1047
+ const newComponent = builder2.createComponent(replaceTmpUIDs(component));
1048
+ components2.forEach((component2) => {
1049
+ if (!has(component2, "uid")) {
1050
+ return builder2.createComponent(replaceTmpUIDs(component2));
1051
+ }
1052
+ return builder2.editComponent(replaceTmpUIDs(component2));
1053
+ });
1054
+ await builder2.writeFiles();
1055
+ strapi.eventHub.emit("component.create", { component: newComponent });
1056
+ return newComponent;
1057
+ };
1058
+ const editComponent = async (uid, { component, components: components2 = [] }) => {
1059
+ const builder2 = createBuilder();
1060
+ const uidMap = builder2.createNewComponentUIDMap(components2);
1061
+ const replaceTmpUIDs = replaceTemporaryUIDs(uidMap);
1062
+ const updatedComponent = builder2.editComponent({
1063
+ uid,
1064
+ ...replaceTmpUIDs(component)
1065
+ });
1066
+ components2.forEach((component2) => {
1067
+ if (!has(component2, "uid")) {
1068
+ return builder2.createComponent(replaceTmpUIDs(component2));
1069
+ }
1070
+ return builder2.editComponent(replaceTmpUIDs(component2));
1071
+ });
1072
+ await builder2.writeFiles();
1073
+ strapi.eventHub.emit("component.update", { component: updatedComponent });
1074
+ return updatedComponent;
1075
+ };
1076
+ const deleteComponent = async (uid) => {
1077
+ const builder2 = createBuilder();
1078
+ const deletedComponent = builder2.deleteComponent(uid);
1079
+ await builder2.writeFiles();
1080
+ strapi.eventHub.emit("component.delete", { component: deletedComponent });
1081
+ return deletedComponent;
1082
+ };
1083
+ const components$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1084
+ __proto__: null,
1085
+ createComponent,
1086
+ deleteComponent,
1087
+ editComponent,
1088
+ formatComponent
1089
+ }, Symbol.toStringTag, { value: "Module" }));
1090
+ const editCategory = async (name, infos) => {
1091
+ const newName = strings.nameToSlug(infos.name);
1092
+ if (name === newName)
1093
+ return;
1094
+ if (!categoryExists(name)) {
1095
+ throw new errors.ApplicationError("category not found");
1096
+ }
1097
+ if (categoryExists(newName)) {
1098
+ throw new errors.ApplicationError("Name already taken");
1099
+ }
1100
+ const builder2 = createBuilder();
1101
+ builder2.components.forEach((component) => {
1102
+ const oldUID = component.uid;
1103
+ const newUID = `${newName}.${component.modelName}`;
1104
+ if (component.category !== name)
1105
+ return;
1106
+ component.setUID(newUID).setDir(join(strapi.dirs.app.components, newName));
1107
+ builder2.components.forEach((compo) => {
1108
+ compo.updateComponent(oldUID, newUID);
1109
+ });
1110
+ builder2.contentTypes.forEach((ct) => {
1111
+ ct.updateComponent(oldUID, newUID);
1112
+ });
1113
+ });
1114
+ await builder2.writeFiles();
1115
+ return newName;
1116
+ };
1117
+ const deleteCategory = async (name) => {
1118
+ if (!categoryExists(name)) {
1119
+ throw new errors.ApplicationError("category not found");
1120
+ }
1121
+ const builder2 = createBuilder();
1122
+ builder2.components.forEach((component) => {
1123
+ if (component.category === name) {
1124
+ builder2.deleteComponent(component.uid);
1125
+ }
1126
+ });
1127
+ await builder2.writeFiles();
1128
+ };
1129
+ const categoryExists = (name) => {
1130
+ const matchingIndex = Object.values(strapi.components).findIndex(
1131
+ (component) => component.category === name
1132
+ );
1133
+ return matchingIndex > -1;
1134
+ };
1135
+ const componentCategories$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1136
+ __proto__: null,
1137
+ deleteCategory,
1138
+ editCategory
1139
+ }, Symbol.toStringTag, { value: "Module" }));
1140
+ const reservedAttributes = [
1141
+ // TODO: these need to come from a centralized place so we don't break things accidentally in the future and can share them outside the CTB, for example on Strapi bootstrap prior to schema db sync
1142
+ // ID fields
1143
+ "id",
1144
+ "document_id",
1145
+ // Creator fields
1146
+ "created_at",
1147
+ "updated_at",
1148
+ "published_at",
1149
+ "created_by_id",
1150
+ "updated_by_id",
1151
+ // does not actually conflict because the fields are called *_by_id but we'll leave it to avoid confusion
1152
+ "created_by",
1153
+ "updated_by",
1154
+ // Used for Strapi functionality
1155
+ "entry_id",
1156
+ "status",
1157
+ "localizations",
1158
+ "meta",
1159
+ "locale",
1160
+ "__component",
1161
+ "__contentType",
1162
+ // We support ending with * to denote prefixes
1163
+ "strapi*",
1164
+ "_strapi*",
1165
+ "__strapi*"
1166
+ ];
1167
+ const reservedModels = [
1168
+ "boolean",
1169
+ "date",
1170
+ "date_time",
1171
+ "time",
1172
+ "upload",
1173
+ "document",
1174
+ "then",
1175
+ // no longer an issue but still restricting for being a javascript keyword
1176
+ // We support ending with * to denote prefixes
1177
+ "strapi*",
1178
+ "_strapi*",
1179
+ "__strapi*"
1180
+ ];
1181
+ const getReservedNames = () => {
1182
+ return {
1183
+ models: reservedModels,
1184
+ attributes: reservedAttributes
1185
+ };
1186
+ };
1187
+ const isReservedModelName = (name) => {
1188
+ const snakeCaseName = snakeCase(name);
1189
+ if (reservedModels.includes(snakeCaseName)) {
1190
+ return true;
1191
+ }
1192
+ if (reservedModels.filter((key) => key.endsWith("*")).map((key) => key.slice(0, -1)).some((prefix) => snakeCaseName.startsWith(prefix))) {
1193
+ return true;
1194
+ }
1195
+ return false;
1196
+ };
1197
+ const isReservedAttributeName = (name) => {
1198
+ const snakeCaseName = snakeCase(name);
1199
+ if (reservedAttributes.includes(snakeCaseName)) {
1200
+ return true;
1201
+ }
1202
+ if (reservedAttributes.filter((key) => key.endsWith("*")).map((key) => key.slice(0, -1)).some((prefix) => snakeCaseName.startsWith(prefix))) {
1203
+ return true;
1204
+ }
1205
+ return false;
1206
+ };
1207
+ const builder$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1208
+ __proto__: null,
1209
+ getReservedNames,
1210
+ isReservedAttributeName,
1211
+ isReservedModelName,
1212
+ reservedAttributes,
1213
+ reservedModels
1214
+ }, Symbol.toStringTag, { value: "Module" }));
1215
+ async function clear(uid) {
1216
+ const { apiName, modelName } = strapi.contentTypes[uid];
1217
+ const apiFolder = path.join(strapi.dirs.app.api, apiName);
1218
+ await recursiveRemoveFiles(apiFolder, createDeleteApiFunction(modelName));
1219
+ await deleteBackup(uid);
1220
+ }
1221
+ async function backup(uid) {
1222
+ const { apiName } = strapi.contentTypes[uid];
1223
+ const apiFolder = path.join(strapi.dirs.app.api, apiName);
1224
+ const backupFolder = path.join(strapi.dirs.app.api, ".backup", apiName);
1225
+ await fse.copy(apiFolder, backupFolder);
1226
+ }
1227
+ async function deleteBackup(uid) {
1228
+ const { apiName } = strapi.contentTypes[uid];
1229
+ const backupFolder = path.join(strapi.dirs.app.api, ".backup");
1230
+ const apiBackupFolder = path.join(strapi.dirs.app.api, ".backup", apiName);
1231
+ await fse.remove(apiBackupFolder);
1232
+ const list = await fse.readdir(backupFolder);
1233
+ if (list.length === 0) {
1234
+ await fse.remove(backupFolder);
1235
+ }
1236
+ }
1237
+ async function rollback(uid) {
1238
+ const { apiName } = strapi.contentTypes[uid];
1239
+ const apiFolder = path.join(strapi.dirs.app.api, apiName);
1240
+ const backupFolder = path.join(strapi.dirs.app.api, ".backup", apiName);
1241
+ try {
1242
+ await fse.access(backupFolder);
1243
+ } catch {
1244
+ throw new Error("Cannot rollback api that was not backed up");
1245
+ }
1246
+ await fse.remove(apiFolder);
1247
+ await fse.copy(backupFolder, apiFolder);
1248
+ await deleteBackup(uid);
1249
+ }
1250
+ const createDeleteApiFunction = (baseName) => {
1251
+ return async (filePath) => {
1252
+ const fileName = path.basename(filePath, path.extname(filePath));
1253
+ const isSchemaFile = filePath.endsWith(`${baseName}/schema.json`);
1254
+ if (fileName === baseName || isSchemaFile) {
1255
+ return fse.remove(filePath);
1256
+ }
1257
+ };
1258
+ };
1259
+ const recursiveRemoveFiles = async (folder, deleteFn) => {
1260
+ const filesName = await fse.readdir(folder);
1261
+ for (const fileName of filesName) {
1262
+ const filePath = path.join(folder, fileName);
1263
+ const stat = await fse.stat(filePath);
1264
+ if (stat.isDirectory()) {
1265
+ await recursiveRemoveFiles(filePath, deleteFn);
1266
+ } else {
1267
+ await deleteFn(filePath);
1268
+ }
1269
+ }
1270
+ const files = await fse.readdir(folder);
1271
+ if (files.length === 0) {
1272
+ await fse.remove(folder);
1273
+ }
1274
+ };
1275
+ const apiHandler = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1276
+ __proto__: null,
1277
+ backup,
1278
+ clear,
1279
+ rollback
1280
+ }, Symbol.toStringTag, { value: "Module" }));
1281
+ const services = {
1282
+ "content-types": contentTypes$1,
1283
+ components: components$1,
1284
+ "component-categories": componentCategories$1,
1285
+ builder: builder$1,
1286
+ "api-handler": apiHandler
1287
+ };
1288
+ function getService(name) {
1289
+ return strapi.plugin("content-type-builder").service(name);
1290
+ }
1291
+ const builder = {
1292
+ getReservedNames(ctx) {
1293
+ ctx.body = getService("builder").getReservedNames();
1294
+ }
1295
+ };
1296
+ const validators = {
1297
+ required: yup.boolean(),
1298
+ unique: yup.boolean(),
1299
+ minLength: yup.number().integer().positive(),
1300
+ maxLength: yup.number().integer().positive()
1301
+ };
1302
+ const NAME_REGEX = /^[A-Za-z][_0-9A-Za-z]*$/;
1303
+ const COLLECTION_NAME_REGEX = /^[A-Za-z][-_0-9A-Za-z]*$/;
1304
+ const CATEGORY_NAME_REGEX = /^[A-Za-z][-_0-9A-Za-z]*$/;
1305
+ const ICON_REGEX = /^[A-Za-z0-9][-A-Za-z0-9]*$/;
1306
+ const UID_REGEX = /^[A-Za-z0-9-_.~]*$/;
1307
+ const isValidName = {
1308
+ name: "isValidName",
1309
+ message: `\${path} must match the following regex: ${NAME_REGEX}`,
1310
+ test: (val) => val === "" || NAME_REGEX.test(val)
1311
+ };
1312
+ const isValidIcon = {
1313
+ name: "isValidIcon",
1314
+ message: `\${path} is not a valid icon name. Make sure your icon name starts with an alphanumeric character and only includes alphanumeric characters or dashes.`,
1315
+ test: (val) => val === "" || ICON_REGEX.test(val)
1316
+ };
1317
+ const isValidUID = {
1318
+ name: "isValidUID",
1319
+ message: `\${path} must match the following regex: ${UID_REGEX}`,
1320
+ test: (val) => val === "" || UID_REGEX.test(val)
1321
+ };
1322
+ const isValidCategoryName = {
1323
+ name: "isValidCategoryName",
1324
+ message: `\${path} must match the following regex: ${CATEGORY_NAME_REGEX}`,
1325
+ test: (val) => val === "" || CATEGORY_NAME_REGEX.test(val)
1326
+ };
1327
+ const isValidCollectionName = {
1328
+ name: "isValidCollectionName",
1329
+ message: `\${path} must match the following regex: ${COLLECTION_NAME_REGEX}`,
1330
+ test: (val) => val === "" || COLLECTION_NAME_REGEX.test(val)
1331
+ };
1332
+ const isValidKey = (key) => ({
1333
+ name: "isValidKey",
1334
+ message: `Attribute name '${key}' must match the following regex: ${NAME_REGEX}`,
1335
+ test: () => NAME_REGEX.test(key)
1336
+ });
1337
+ const isValidEnum = {
1338
+ name: "isValidEnum",
1339
+ message: "${path} should not start with number",
1340
+ test: (val) => val === "" || !strings.startsWithANumber(val)
1341
+ };
1342
+ const areEnumValuesUnique = {
1343
+ name: "areEnumValuesUnique",
1344
+ message: "${path} cannot contain duplicate values",
1345
+ test(values) {
1346
+ const filtered = [...new Set(values)];
1347
+ return filtered.length === values.length;
1348
+ }
1349
+ };
1350
+ const isValidRegExpPattern = {
1351
+ name: "isValidRegExpPattern",
1352
+ message: "${path} must be a valid RexExp pattern string",
1353
+ test: (val) => val === "" || !!new RegExp(val)
1354
+ };
1355
+ const isValidDefaultJSON = {
1356
+ name: "isValidDefaultJSON",
1357
+ message: "${path} is not a valid JSON",
1358
+ test(val) {
1359
+ if (val === void 0) {
1360
+ return true;
1361
+ }
1362
+ if (_.isNumber(val) || _.isNull(val) || _.isObject(val) || _.isArray(val)) {
1363
+ return true;
1364
+ }
1365
+ try {
1366
+ JSON.parse(val);
1367
+ return true;
1368
+ } catch (err) {
1369
+ return false;
1370
+ }
1371
+ }
1372
+ };
1373
+ const componentCategorySchema = yup.object({
1374
+ name: yup.string().min(3).test(isValidCategoryName).required("name.required")
1375
+ }).noUnknown();
1376
+ const validateComponentCategory = validateYupSchema(componentCategorySchema);
1377
+ const componentCategories = {
1378
+ async editCategory(ctx) {
1379
+ const body = ctx.request.body;
1380
+ try {
1381
+ await validateComponentCategory(body);
1382
+ } catch (error) {
1383
+ return ctx.send({ error }, 400);
1384
+ }
1385
+ const { name } = ctx.params;
1386
+ strapi.reload.isWatching = false;
1387
+ const componentCategoryService = getService("component-categories");
1388
+ const newName = await componentCategoryService.editCategory(name, body);
1389
+ setImmediate(() => strapi.reload());
1390
+ ctx.send({ name: newName });
1391
+ },
1392
+ async deleteCategory(ctx) {
1393
+ const { name } = ctx.params;
1394
+ strapi.reload.isWatching = false;
1395
+ const componentCategoryService = getService("component-categories");
1396
+ await componentCategoryService.deleteCategory(name);
1397
+ setImmediate(() => strapi.reload());
1398
+ ctx.send({ name });
1399
+ }
1400
+ };
1401
+ const maxLengthIsGreaterThanOrEqualToMinLength = {
1402
+ name: "isGreaterThanMin",
1403
+ message: "maxLength must be greater or equal to minLength",
1404
+ test(value) {
1405
+ const { minLength } = this.parent;
1406
+ return !(!_.isUndefined(minLength) && !_.isUndefined(value) && value < minLength);
1407
+ }
1408
+ };
1409
+ const getTypeValidator = (attribute, { types, modelType, attributes }) => {
1410
+ return yup.object({
1411
+ type: yup.string().oneOf([...types]).required(),
1412
+ configurable: yup.boolean().nullable(),
1413
+ private: yup.boolean().nullable(),
1414
+ pluginOptions: yup.object(),
1415
+ ...getTypeShape(attribute, { modelType, attributes })
1416
+ });
1417
+ };
1418
+ const getTypeShape = (attribute, { attributes } = {}) => {
1419
+ switch (attribute.type) {
1420
+ case "media": {
1421
+ return {
1422
+ multiple: yup.boolean(),
1423
+ required: validators.required,
1424
+ allowedTypes: yup.array().of(yup.string().oneOf(["images", "videos", "files", "audios"])).min(1)
1425
+ };
1426
+ }
1427
+ case "uid": {
1428
+ return {
1429
+ required: validators.required,
1430
+ targetField: yup.string().oneOf(
1431
+ Object.keys(attributes).filter(
1432
+ (key) => VALID_UID_TARGETS.includes(_.get(attributes[key], "type"))
1433
+ )
1434
+ ).nullable(),
1435
+ default: yup.string().test(
1436
+ "isValidDefaultUID",
1437
+ "cannot define a default UID if the targetField is set",
1438
+ function(value) {
1439
+ const { targetField } = this.parent;
1440
+ return !!(_.isNil(targetField) || _.isNil(value));
1441
+ }
1442
+ ).test(isValidUID),
1443
+ minLength: validators.minLength,
1444
+ maxLength: validators.maxLength.max(256).test(maxLengthIsGreaterThanOrEqualToMinLength),
1445
+ options: yup.object().shape({
1446
+ separator: yup.string(),
1447
+ lowercase: yup.boolean(),
1448
+ decamelize: yup.boolean(),
1449
+ customReplacements: yup.array().of(yup.array().of(yup.string()).min(2).max(2)),
1450
+ preserveLeadingUnderscore: yup.boolean()
1451
+ })
1452
+ };
1453
+ }
1454
+ case "string":
1455
+ case "text": {
1456
+ return {
1457
+ default: yup.string(),
1458
+ required: validators.required,
1459
+ unique: validators.unique,
1460
+ minLength: validators.minLength,
1461
+ maxLength: validators.maxLength,
1462
+ regex: yup.string().test(isValidRegExpPattern)
1463
+ };
1464
+ }
1465
+ case "richtext": {
1466
+ return {
1467
+ default: yup.string(),
1468
+ required: validators.required,
1469
+ minLength: validators.minLength,
1470
+ maxLength: validators.maxLength
1471
+ };
1472
+ }
1473
+ case "blocks": {
1474
+ return {
1475
+ required: validators.required
1476
+ };
1477
+ }
1478
+ case "json": {
1479
+ return {
1480
+ default: yup.mixed().test(isValidDefaultJSON),
1481
+ required: validators.required
1482
+ };
1483
+ }
1484
+ case "enumeration": {
1485
+ return {
1486
+ enum: yup.array().of(yup.string().test(isValidEnum).required()).min(1).test(areEnumValuesUnique).required(),
1487
+ default: yup.string().when("enum", (enumVal) => yup.string().oneOf(enumVal)),
1488
+ enumName: yup.string().test(isValidName),
1489
+ required: validators.required
1490
+ };
1491
+ }
1492
+ case "password": {
1493
+ return {
1494
+ required: validators.required,
1495
+ minLength: validators.minLength,
1496
+ maxLength: validators.maxLength
1497
+ };
1498
+ }
1499
+ case "email": {
1500
+ return {
1501
+ default: yup.string().email(),
1502
+ required: validators.required,
1503
+ unique: validators.unique,
1504
+ minLength: validators.minLength,
1505
+ maxLength: validators.maxLength
1506
+ };
1507
+ }
1508
+ case "integer": {
1509
+ return {
1510
+ default: yup.number().integer(),
1511
+ required: validators.required,
1512
+ unique: validators.unique,
1513
+ min: yup.number().integer(),
1514
+ max: yup.number().integer()
1515
+ };
1516
+ }
1517
+ case "biginteger": {
1518
+ return {
1519
+ default: yup.string().nullable().matches(/^\d*$/),
1520
+ required: validators.required,
1521
+ unique: validators.unique,
1522
+ min: yup.string().nullable().matches(/^\d*$/),
1523
+ max: yup.string().nullable().matches(/^\d*$/)
1524
+ };
1525
+ }
1526
+ case "float": {
1527
+ return {
1528
+ default: yup.number(),
1529
+ required: validators.required,
1530
+ unique: validators.unique,
1531
+ min: yup.number(),
1532
+ max: yup.number()
1533
+ };
1534
+ }
1535
+ case "decimal": {
1536
+ return {
1537
+ default: yup.number(),
1538
+ required: validators.required,
1539
+ unique: validators.unique,
1540
+ min: yup.number(),
1541
+ max: yup.number()
1542
+ };
1543
+ }
1544
+ case "time":
1545
+ case "datetime":
1546
+ case "date": {
1547
+ return {
1548
+ default: yup.string(),
1549
+ required: validators.required,
1550
+ unique: validators.unique
1551
+ };
1552
+ }
1553
+ case "boolean": {
1554
+ return {
1555
+ default: yup.boolean(),
1556
+ required: validators.required
1557
+ };
1558
+ }
1559
+ case "component": {
1560
+ return {
1561
+ required: validators.required,
1562
+ repeatable: yup.boolean(),
1563
+ // TODO: Add correct server validation for nested components
1564
+ component: yup.string().required(),
1565
+ min: yup.number(),
1566
+ max: yup.number()
1567
+ };
1568
+ }
1569
+ case "dynamiczone": {
1570
+ return {
1571
+ required: validators.required,
1572
+ components: yup.array().of(yup.string().required()).test("isArray", "${path} must be an array", (value) => Array.isArray(value)).min(1),
1573
+ min: yup.number(),
1574
+ max: yup.number()
1575
+ };
1576
+ }
1577
+ default: {
1578
+ return {};
1579
+ }
1580
+ }
1581
+ };
1582
+ const STRAPI_USER_RELATIONS = ["oneToOne", "oneToMany"];
1583
+ const isValidRelation = (validNatures) => function(value) {
1584
+ if (value === void 0) {
1585
+ return true;
1586
+ }
1587
+ if (this.parent.target === coreUids.STRAPI_USER) {
1588
+ if (!validNatures.includes(value) || !isUndefined(this.parent.targetAttribute)) {
1589
+ return this.createError({
1590
+ path: this.path,
1591
+ message: `must be one of the following values: ${STRAPI_USER_RELATIONS.join(", ")}`
1592
+ });
1593
+ }
1594
+ }
1595
+ return validNatures.includes(value) ? true : this.createError({
1596
+ path: this.path,
1597
+ message: `must be one of the following values: ${validNatures.join(", ")}`
1598
+ });
1599
+ };
1600
+ const getRelationValidator = (attribute, allowedRelations) => {
1601
+ const contentTypesUIDs = Object.keys(strapi.contentTypes).filter((key) => strapi.contentTypes[key].kind === typeKinds.COLLECTION_TYPE).filter((key) => !key.startsWith(coreUids.PREFIX) || key === coreUids.STRAPI_USER).concat(["__self__", "__contentType__"]);
1602
+ const base = {
1603
+ type: yup.string().oneOf(["relation"]).required(),
1604
+ relation: yup.string().test("isValidRelation", isValidRelation(allowedRelations)).required(),
1605
+ configurable: yup.boolean().nullable(),
1606
+ private: yup.boolean().nullable(),
1607
+ pluginOptions: yup.object()
1608
+ };
1609
+ switch (attribute.relation) {
1610
+ case "oneToOne":
1611
+ case "oneToMany":
1612
+ case "manyToOne":
1613
+ case "manyToMany":
1614
+ case "morphOne":
1615
+ case "morphMany": {
1616
+ return yup.object({
1617
+ ...base,
1618
+ target: yup.string().oneOf(contentTypesUIDs).required(),
1619
+ targetAttribute: yup.string().test(isValidName).nullable()
1620
+ });
1621
+ }
1622
+ case "morphToOne":
1623
+ case "morphToMany":
1624
+ default: {
1625
+ return yup.object({ ...base });
1626
+ }
1627
+ }
1628
+ };
1629
+ const createSchema = (types, relations, { modelType } = {}) => {
1630
+ const shape = {
1631
+ description: yup.string(),
1632
+ options: yup.object(),
1633
+ pluginOptions: yup.object(),
1634
+ collectionName: yup.string().nullable().test(isValidCollectionName),
1635
+ attributes: createAttributesValidator({ types, relations, modelType }),
1636
+ reviewWorkflows: yup.boolean(),
1637
+ draftAndPublish: yup.boolean()
1638
+ };
1639
+ if (modelType === modelTypes.CONTENT_TYPE) {
1640
+ shape.kind = yup.string().oneOf([typeKinds.SINGLE_TYPE, typeKinds.COLLECTION_TYPE]).nullable();
1641
+ }
1642
+ return yup.object(shape).noUnknown();
1643
+ };
1644
+ const createAttributesValidator = ({ types, modelType, relations }) => {
1645
+ return yup.lazy((attributes) => {
1646
+ return yup.object().shape(
1647
+ _.mapValues(attributes, (attribute, key) => {
1648
+ if (isForbiddenKey(key)) {
1649
+ return forbiddenValidator();
1650
+ }
1651
+ if (isConflictingKey(key, attributes)) {
1652
+ return conflictingKeysValidator(key);
1653
+ }
1654
+ if (attribute.type === "relation") {
1655
+ return getRelationValidator(attribute, relations).test(isValidKey(key));
1656
+ }
1657
+ if (_.has(attribute, "type")) {
1658
+ return getTypeValidator(attribute, { types, modelType, attributes }).test(
1659
+ isValidKey(key)
1660
+ );
1661
+ }
1662
+ return typeOrRelationValidator;
1663
+ })
1664
+ ).required("attributes.required");
1665
+ });
1666
+ };
1667
+ const isConflictingKey = (key, attributes) => {
1668
+ const snakeCaseKey = snakeCase(key);
1669
+ return Object.keys(attributes).some((existingKey) => {
1670
+ if (existingKey === key)
1671
+ return false;
1672
+ return snakeCase(existingKey) === snakeCaseKey;
1673
+ });
1674
+ };
1675
+ const isForbiddenKey = (key) => {
1676
+ return getService("builder").isReservedAttributeName(key);
1677
+ };
1678
+ const forbiddenValidator = () => {
1679
+ const reservedNames = [...getService("builder").getReservedNames().attributes];
1680
+ return yup.mixed().test({
1681
+ name: "forbiddenKeys",
1682
+ message: `Attribute keys cannot be one of ${reservedNames.join(", ")}`,
1683
+ test: () => false
1684
+ });
1685
+ };
1686
+ const conflictingKeysValidator = (key) => {
1687
+ return yup.mixed().test({
1688
+ name: "conflictingKeys",
1689
+ message: `Attribute ${key} conflicts with an existing key`,
1690
+ test: () => false
1691
+ });
1692
+ };
1693
+ const typeOrRelationValidator = yup.object().test({
1694
+ name: "mustHaveTypeOrTarget",
1695
+ message: "Attribute must have either a type or a target",
1696
+ test: () => false
1697
+ });
1698
+ const hasDefaultAttribute = (attribute) => {
1699
+ return "default" in attribute;
1700
+ };
1701
+ const removeEmptyDefaults = (data) => {
1702
+ const { attributes } = data || {};
1703
+ Object.keys(attributes).forEach((attributeName) => {
1704
+ const attribute = attributes[attributeName];
1705
+ if (hasDefaultAttribute(attribute) && attribute.default === "") {
1706
+ attribute.default = void 0;
1707
+ }
1708
+ });
1709
+ };
1710
+ const removeDeletedUIDTargetFields = (data) => {
1711
+ if (_.has(data, "attributes")) {
1712
+ Object.values(data.attributes).forEach((attribute) => {
1713
+ if (attribute.type === "uid" && !_.isUndefined(attribute.targetField) && !_.has(data.attributes, attribute.targetField)) {
1714
+ attribute.targetField = void 0;
1715
+ }
1716
+ });
1717
+ }
1718
+ };
1719
+ const VALID_RELATIONS$1 = ["oneToOne", "oneToMany"];
1720
+ const VALID_TYPES$1 = [...DEFAULT_TYPES, "component", "customField"];
1721
+ const componentSchema = createSchema(VALID_TYPES$1, VALID_RELATIONS$1, {
1722
+ modelType: modelTypes.COMPONENT
1723
+ }).shape({
1724
+ displayName: yup.string().min(1).required("displayName.required"),
1725
+ icon: yup.string().nullable().test(isValidIcon),
1726
+ category: yup.string().nullable().test(isValidCategoryName).required("category.required")
1727
+ }).required().noUnknown();
1728
+ const nestedComponentSchema = yup.array().of(
1729
+ componentSchema.shape({
1730
+ uid: yup.string(),
1731
+ tmpUID: yup.string()
1732
+ }).test({
1733
+ name: "mustHaveUIDOrTmpUID",
1734
+ message: "Component must have a uid or a tmpUID",
1735
+ test(attr) {
1736
+ if (_.has(attr, "uid") && _.has(attr, "tmpUID"))
1737
+ return false;
1738
+ if (!_.has(attr, "uid") && !_.has(attr, "tmpUID"))
1739
+ return false;
1740
+ return true;
1741
+ }
1742
+ }).required().noUnknown()
1743
+ );
1744
+ const componentInputSchema = yup.object({
1745
+ component: componentSchema,
1746
+ components: nestedComponentSchema
1747
+ }).noUnknown();
1748
+ const validateComponentInput = validateYupSchema(componentInputSchema);
1749
+ const updateComponentInputSchema = yup.object({
1750
+ component: componentSchema,
1751
+ components: nestedComponentSchema
1752
+ }).noUnknown();
1753
+ const validateUpdateComponentInput = (data) => {
1754
+ if (_.has(data, "component") && data.component) {
1755
+ removeEmptyDefaults(data.component);
1756
+ }
1757
+ if (_.has(data, "components") && Array.isArray(data.components)) {
1758
+ data.components.forEach((data2) => {
1759
+ if (_.has(data2, "uid")) {
1760
+ removeEmptyDefaults(data2);
1761
+ }
1762
+ });
1763
+ }
1764
+ return validateYupSchema(updateComponentInputSchema)(data);
1765
+ };
1766
+ const components = {
1767
+ /**
1768
+ * GET /components handler
1769
+ * Returns a list of available components
1770
+ * @param {Object} ctx - koa context
1771
+ */
1772
+ async getComponents(ctx) {
1773
+ const componentService = getService("components");
1774
+ const componentUIDs = Object.keys(strapi.components);
1775
+ const data = componentUIDs.map((uid) => {
1776
+ return componentService.formatComponent(strapi.components[uid]);
1777
+ });
1778
+ ctx.send({ data });
1779
+ },
1780
+ /**
1781
+ * GET /components/:uid
1782
+ * Returns a specific component
1783
+ * @param {Object} ctx - koa context
1784
+ */
1785
+ async getComponent(ctx) {
1786
+ const { uid } = ctx.params;
1787
+ const component = strapi.components[uid];
1788
+ if (!component) {
1789
+ return ctx.send({ error: "component.notFound" }, 404);
1790
+ }
1791
+ const componentService = getService("components");
1792
+ ctx.send({ data: componentService.formatComponent(component) });
1793
+ },
1794
+ /**
1795
+ * POST /components
1796
+ * Creates a component and returns its infos
1797
+ * @param {Object} ctx - koa context
1798
+ */
1799
+ async createComponent(ctx) {
1800
+ const body = ctx.request.body;
1801
+ try {
1802
+ await validateComponentInput(body);
1803
+ } catch (error) {
1804
+ return ctx.send({ error }, 400);
1805
+ }
1806
+ try {
1807
+ strapi.reload.isWatching = false;
1808
+ const componentService = getService("components");
1809
+ const component = await componentService.createComponent({
1810
+ component: body.component,
1811
+ components: body.components
1812
+ });
1813
+ setImmediate(() => strapi.reload());
1814
+ ctx.send({ data: { uid: component.uid } }, 201);
1815
+ } catch (error) {
1816
+ strapi.log.error(error);
1817
+ ctx.send({ error: error?.message || "Unknown error" }, 400);
1818
+ }
1819
+ },
1820
+ /**
1821
+ * PUT /components/:uid
1822
+ * Updates a component and return its infos
1823
+ * @param {Object} ctx - koa context - enhanced koa context
1824
+ */
1825
+ async updateComponent(ctx) {
1826
+ const { uid } = ctx.params;
1827
+ const body = ctx.request.body;
1828
+ if (!_.has(strapi.components, uid)) {
1829
+ return ctx.send({ error: "component.notFound" }, 404);
1830
+ }
1831
+ try {
1832
+ await validateUpdateComponentInput(body);
1833
+ } catch (error) {
1834
+ return ctx.send({ error }, 400);
1835
+ }
1836
+ try {
1837
+ strapi.reload.isWatching = false;
1838
+ const componentService = getService("components");
1839
+ const component = await componentService.editComponent(uid, {
1840
+ component: body.component,
1841
+ components: body.components
1842
+ });
1843
+ setImmediate(() => strapi.reload());
1844
+ ctx.send({ data: { uid: component.uid } });
1845
+ } catch (error) {
1846
+ strapi.log.error(error);
1847
+ ctx.send({ error: error?.message || "Unknown error" }, 400);
1848
+ }
1849
+ },
1850
+ /**
1851
+ * DELETE /components/:uid
1852
+ * Deletes a components and returns its old infos
1853
+ * @param {Object} ctx - koa context
1854
+ */
1855
+ async deleteComponent(ctx) {
1856
+ const { uid } = ctx.params;
1857
+ if (!_.has(strapi.components, uid)) {
1858
+ return ctx.send({ error: "component.notFound" }, 404);
1859
+ }
1860
+ try {
1861
+ strapi.reload.isWatching = false;
1862
+ const componentService = getService("components");
1863
+ const component = await componentService.deleteComponent(uid);
1864
+ setImmediate(() => strapi.reload());
1865
+ ctx.send({ data: { uid: component.uid } });
1866
+ } catch (error) {
1867
+ strapi.log.error(error);
1868
+ ctx.send({ error: error?.message || "Unknown error" }, 400);
1869
+ }
1870
+ }
1871
+ };
1872
+ const VALID_RELATIONS = {
1873
+ [typeKinds.SINGLE_TYPE]: [
1874
+ "oneToOne",
1875
+ "oneToMany",
1876
+ "morphOne",
1877
+ "morphMany",
1878
+ "morphToOne",
1879
+ "morphToMany"
1880
+ ],
1881
+ [typeKinds.COLLECTION_TYPE]: [
1882
+ "oneToOne",
1883
+ "oneToMany",
1884
+ "manyToOne",
1885
+ "manyToMany",
1886
+ "morphOne",
1887
+ "morphMany",
1888
+ "morphToOne",
1889
+ "morphToMany"
1890
+ ]
1891
+ };
1892
+ const VALID_TYPES = [...DEFAULT_TYPES, "uid", "component", "dynamiczone", "customField"];
1893
+ const createContentTypeSchema = (data, { isEdition = false } = {}) => {
1894
+ const kind = getOr(
1895
+ typeKinds.COLLECTION_TYPE,
1896
+ "contentType.kind",
1897
+ data
1898
+ );
1899
+ const contentTypeSchema = createSchema(VALID_TYPES, VALID_RELATIONS[kind] || [], {
1900
+ modelType: modelTypes.CONTENT_TYPE
1901
+ }).shape({
1902
+ displayName: yup.string().min(1).required(),
1903
+ singularName: yup.string().min(1).test(nameIsAvailable(isEdition)).test(forbiddenContentTypeNameValidator()).isKebabCase().required(),
1904
+ pluralName: yup.string().min(1).test(nameIsAvailable(isEdition)).test(nameIsNotExistingCollectionName(isEdition)).test(forbiddenContentTypeNameValidator()).isKebabCase().required()
1905
+ }).test(
1906
+ "singularName-not-equal-pluralName",
1907
+ "${path}: singularName and pluralName should be different",
1908
+ (value) => value.singularName !== value.pluralName
1909
+ );
1910
+ return yup.object({
1911
+ // FIXME .noUnknown(false) will strip off the unwanted properties without throwing an error
1912
+ // Why not having .noUnknown() ? Because we want to be able to add options relatable to EE features
1913
+ // without having any reference to them in CE.
1914
+ // Why not handle an "options" object in the content-type ? The admin panel needs lots of rework
1915
+ // to be able to send this options object instead of top-level attributes.
1916
+ // @nathan-pichon 20/02/2023
1917
+ contentType: contentTypeSchema.required().noUnknown(false),
1918
+ components: nestedComponentSchema
1919
+ }).noUnknown();
1920
+ };
1921
+ const validateContentTypeInput = (data) => {
1922
+ return validateYupSchema(createContentTypeSchema(data))(data);
1923
+ };
1924
+ const validateUpdateContentTypeInput = (data) => {
1925
+ if (has$1("contentType", data)) {
1926
+ removeEmptyDefaults(data.contentType);
1927
+ removeDeletedUIDTargetFields(data.contentType);
1928
+ }
1929
+ if (has$1("components", data) && Array.isArray(data.components)) {
1930
+ data.components.forEach((comp) => {
1931
+ if (has$1("uid", comp)) {
1932
+ removeEmptyDefaults(comp);
1933
+ }
1934
+ });
1935
+ }
1936
+ return validateYupSchema(createContentTypeSchema(data, { isEdition: true }))(data);
1937
+ };
1938
+ const forbiddenContentTypeNameValidator = () => {
1939
+ const reservedNames = getService("builder").getReservedNames().models;
1940
+ return {
1941
+ name: "forbiddenContentTypeName",
1942
+ message: `Content Type name cannot be one of ${reservedNames.join(", ")}`,
1943
+ test(value) {
1944
+ if (typeof value !== "string") {
1945
+ return true;
1946
+ }
1947
+ return !getService("builder").isReservedModelName(value);
1948
+ }
1949
+ };
1950
+ };
1951
+ const nameIsAvailable = (isEdition) => {
1952
+ const usedNames = flatMap((ct) => {
1953
+ return [ct.info?.singularName, ct.info?.pluralName];
1954
+ })(strapi.contentTypes);
1955
+ return {
1956
+ name: "nameAlreadyUsed",
1957
+ message: "contentType: name `${value}` is already being used by another content type.",
1958
+ test(value) {
1959
+ if (isEdition)
1960
+ return true;
1961
+ if (typeof value !== "string") {
1962
+ return true;
1963
+ }
1964
+ return usedNames.every((usedName) => snakeCase(usedName) !== snakeCase(value));
1965
+ }
1966
+ };
1967
+ };
1968
+ const nameIsNotExistingCollectionName = (isEdition) => {
1969
+ const usedNames = Object.keys(strapi.contentTypes).map(
1970
+ (key) => strapi.contentTypes[key].collectionName
1971
+ );
1972
+ return {
1973
+ name: "nameAlreadyUsed",
1974
+ message: "contentType: name `${value}` is already being used by another content type.",
1975
+ test(value) {
1976
+ if (isEdition)
1977
+ return true;
1978
+ if (typeof value !== "string") {
1979
+ return true;
1980
+ }
1981
+ return usedNames.every((usedName) => snakeCase(usedName) !== snakeCase(value));
1982
+ }
1983
+ };
1984
+ };
1985
+ const kindSchema = yup.string().oneOf([typeKinds.SINGLE_TYPE, typeKinds.COLLECTION_TYPE]);
1986
+ const validateKind = validateYupSchema(kindSchema);
1987
+ const contentTypes = {
1988
+ async getContentTypes(ctx) {
1989
+ const { kind } = ctx.query;
1990
+ try {
1991
+ await validateKind(kind);
1992
+ } catch (error) {
1993
+ return ctx.send({ error }, 400);
1994
+ }
1995
+ const contentTypeService = getService("content-types");
1996
+ const contentTypes2 = Object.keys(strapi.contentTypes).filter(
1997
+ (uid) => !kind || _.get(strapi.contentTypes[uid], "kind", "collectionType") === kind
1998
+ ).map(
1999
+ (uid) => contentTypeService.formatContentType(strapi.contentTypes[uid])
2000
+ );
2001
+ ctx.send({
2002
+ data: contentTypes2
2003
+ });
2004
+ },
2005
+ getContentType(ctx) {
2006
+ const { uid } = ctx.params;
2007
+ const contentType = strapi.contentTypes[uid];
2008
+ if (!contentType) {
2009
+ return ctx.send({ error: "contentType.notFound" }, 404);
2010
+ }
2011
+ const contentTypeService = getService("content-types");
2012
+ ctx.send({ data: contentTypeService.formatContentType(contentType) });
2013
+ },
2014
+ async createContentType(ctx) {
2015
+ const body = ctx.request.body;
2016
+ try {
2017
+ await validateContentTypeInput(body);
2018
+ } catch (error) {
2019
+ return ctx.send({ error }, 400);
2020
+ }
2021
+ try {
2022
+ strapi.reload.isWatching = false;
2023
+ const contentTypeService = getService("content-types");
2024
+ const contentType = await contentTypeService.createContentType({
2025
+ contentType: body.contentType,
2026
+ components: body.components
2027
+ });
2028
+ const metricsPayload = {
2029
+ eventProperties: {
2030
+ kind: contentType.kind
2031
+ }
2032
+ };
2033
+ if (_.isEmpty(strapi.apis)) {
2034
+ await strapi.telemetry.send("didCreateFirstContentType", metricsPayload);
2035
+ } else {
2036
+ await strapi.telemetry.send("didCreateContentType", metricsPayload);
2037
+ }
2038
+ setImmediate(() => strapi.reload());
2039
+ ctx.send({ data: { uid: contentType.uid } }, 201);
2040
+ } catch (err) {
2041
+ strapi.log.error(err);
2042
+ await strapi.telemetry.send("didNotCreateContentType", {
2043
+ eventProperties: { error: err.message || err }
2044
+ });
2045
+ ctx.send({ error: err.message || "Unknown error" }, 400);
2046
+ }
2047
+ },
2048
+ async updateContentType(ctx) {
2049
+ const { uid } = ctx.params;
2050
+ const body = ctx.request.body;
2051
+ if (!_.has(strapi.contentTypes, uid)) {
2052
+ return ctx.send({ error: "contentType.notFound" }, 404);
2053
+ }
2054
+ try {
2055
+ await validateUpdateContentTypeInput(body);
2056
+ } catch (error) {
2057
+ return ctx.send({ error }, 400);
2058
+ }
2059
+ try {
2060
+ strapi.reload.isWatching = false;
2061
+ const contentTypeService = getService("content-types");
2062
+ const component = await contentTypeService.editContentType(uid, {
2063
+ contentType: body.contentType,
2064
+ components: body.components
2065
+ });
2066
+ setImmediate(() => strapi.reload());
2067
+ ctx.send({ data: { uid: component.uid } }, 201);
2068
+ } catch (error) {
2069
+ strapi.log.error(error);
2070
+ ctx.send({ error: error?.message || "Unknown error" }, 400);
2071
+ }
2072
+ },
2073
+ async deleteContentType(ctx) {
2074
+ const { uid } = ctx.params;
2075
+ if (!_.has(strapi.contentTypes, uid)) {
2076
+ return ctx.send({ error: "contentType.notFound" }, 404);
2077
+ }
2078
+ try {
2079
+ strapi.reload.isWatching = false;
2080
+ const contentTypeService = getService("content-types");
2081
+ const component = await contentTypeService.deleteContentType(uid);
2082
+ setImmediate(() => strapi.reload());
2083
+ ctx.send({ data: { uid: component.uid } });
2084
+ } catch (error) {
2085
+ strapi.log.error(error);
2086
+ ctx.send({ error: error?.message || "Unknown error" }, 400);
2087
+ }
2088
+ }
2089
+ };
2090
+ const exportObject = {
2091
+ builder,
2092
+ "component-categories": componentCategories,
2093
+ components,
2094
+ "content-types": contentTypes
2095
+ };
2096
+ const admin = {
2097
+ type: "admin",
2098
+ routes: [
2099
+ {
2100
+ method: "GET",
2101
+ path: "/reserved-names",
2102
+ handler: "builder.getReservedNames",
2103
+ config: {
2104
+ policies: [
2105
+ {
2106
+ name: "admin::hasPermissions",
2107
+ config: { actions: ["plugin::content-type-builder.read"] }
2108
+ }
2109
+ ]
2110
+ }
2111
+ },
2112
+ {
2113
+ method: "GET",
2114
+ path: "/content-types",
2115
+ handler: "content-types.getContentTypes",
2116
+ config: {
2117
+ policies: [
2118
+ {
2119
+ name: "admin::hasPermissions",
2120
+ config: { actions: ["plugin::content-type-builder.read"] }
2121
+ }
2122
+ ]
2123
+ }
2124
+ },
2125
+ {
2126
+ method: "GET",
2127
+ path: "/content-types/:uid",
2128
+ handler: "content-types.getContentType",
2129
+ config: {
2130
+ policies: [
2131
+ {
2132
+ name: "admin::hasPermissions",
2133
+ config: { actions: ["plugin::content-type-builder.read"] }
2134
+ }
2135
+ ]
2136
+ }
2137
+ },
2138
+ {
2139
+ method: "POST",
2140
+ path: "/content-types",
2141
+ handler: "content-types.createContentType",
2142
+ config: {
2143
+ policies: [
2144
+ {
2145
+ name: "admin::hasPermissions",
2146
+ config: { actions: ["plugin::content-type-builder.read"] }
2147
+ }
2148
+ ]
2149
+ }
2150
+ },
2151
+ {
2152
+ method: "PUT",
2153
+ path: "/content-types/:uid",
2154
+ handler: "content-types.updateContentType",
2155
+ config: {
2156
+ policies: [
2157
+ {
2158
+ name: "admin::hasPermissions",
2159
+ config: { actions: ["plugin::content-type-builder.read"] }
2160
+ }
2161
+ ]
2162
+ }
2163
+ },
2164
+ {
2165
+ method: "DELETE",
2166
+ path: "/content-types/:uid",
2167
+ handler: "content-types.deleteContentType",
2168
+ config: {
2169
+ policies: [
2170
+ {
2171
+ name: "admin::hasPermissions",
2172
+ config: { actions: ["plugin::content-type-builder.read"] }
2173
+ }
2174
+ ]
2175
+ }
2176
+ },
2177
+ {
2178
+ method: "GET",
2179
+ path: "/components",
2180
+ handler: "components.getComponents",
2181
+ config: {
2182
+ policies: [
2183
+ {
2184
+ name: "admin::hasPermissions",
2185
+ config: { actions: ["plugin::content-type-builder.read"] }
2186
+ }
2187
+ ]
2188
+ }
2189
+ },
2190
+ {
2191
+ method: "GET",
2192
+ path: "/components/:uid",
2193
+ handler: "components.getComponent",
2194
+ config: {
2195
+ policies: [
2196
+ {
2197
+ name: "admin::hasPermissions",
2198
+ config: { actions: ["plugin::content-type-builder.read"] }
2199
+ }
2200
+ ]
2201
+ }
2202
+ },
2203
+ {
2204
+ method: "POST",
2205
+ path: "/components",
2206
+ handler: "components.createComponent",
2207
+ config: {
2208
+ policies: [
2209
+ {
2210
+ name: "admin::hasPermissions",
2211
+ config: { actions: ["plugin::content-type-builder.read"] }
2212
+ }
2213
+ ]
2214
+ }
2215
+ },
2216
+ {
2217
+ method: "PUT",
2218
+ path: "/components/:uid",
2219
+ handler: "components.updateComponent",
2220
+ config: {
2221
+ policies: [
2222
+ {
2223
+ name: "admin::hasPermissions",
2224
+ config: { actions: ["plugin::content-type-builder.read"] }
2225
+ }
2226
+ ]
2227
+ }
2228
+ },
2229
+ {
2230
+ method: "DELETE",
2231
+ path: "/components/:uid",
2232
+ handler: "components.deleteComponent",
2233
+ config: {
2234
+ policies: [
2235
+ {
2236
+ name: "admin::hasPermissions",
2237
+ config: { actions: ["plugin::content-type-builder.read"] }
2238
+ }
2239
+ ]
2240
+ }
2241
+ },
2242
+ {
2243
+ method: "PUT",
2244
+ path: "/component-categories/:name",
2245
+ handler: "component-categories.editCategory",
2246
+ config: {
2247
+ policies: [
2248
+ {
2249
+ name: "admin::hasPermissions",
2250
+ config: { actions: ["plugin::content-type-builder.read"] }
2251
+ }
2252
+ ]
2253
+ }
2254
+ },
2255
+ {
2256
+ method: "DELETE",
2257
+ path: "/component-categories/:name",
2258
+ handler: "component-categories.deleteCategory",
2259
+ config: {
2260
+ policies: [
2261
+ {
2262
+ name: "admin::hasPermissions",
2263
+ config: { actions: ["plugin::content-type-builder.read"] }
2264
+ }
2265
+ ]
2266
+ }
2267
+ }
2268
+ ]
2269
+ };
2270
+ const contentApi = {
2271
+ type: "content-api",
2272
+ routes: [
2273
+ {
2274
+ method: "GET",
2275
+ path: "/content-types",
2276
+ handler: "content-types.getContentTypes"
2277
+ },
2278
+ {
2279
+ method: "GET",
2280
+ path: "/content-types/:uid",
2281
+ handler: "content-types.getContentType"
2282
+ },
2283
+ {
2284
+ method: "GET",
2285
+ path: "/components",
2286
+ handler: "components.getComponents"
2287
+ },
2288
+ {
2289
+ method: "GET",
2290
+ path: "/components/:uid",
2291
+ handler: "components.getComponent"
2292
+ }
2293
+ ]
2294
+ };
2295
+ const routes = {
2296
+ admin,
2297
+ "content-api": contentApi
2298
+ };
2299
+ const index = () => ({
2300
+ config,
2301
+ bootstrap,
2302
+ services,
2303
+ controllers: exportObject,
2304
+ routes
2305
+ });
2306
+ export {
2307
+ index as default
2308
+ };
2309
+ //# sourceMappingURL=index.mjs.map