@strapi/upload 0.0.0-experimental.145e7d7ddefd1aef71aaf3d9bb86440d013035bf

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 (210) hide show
  1. package/LICENSE +37 -0
  2. package/README.md +1 -0
  3. package/dist/_chunks/ca-B2_I-q1t.mjs +121 -0
  4. package/dist/_chunks/ca-B2_I-q1t.mjs.map +1 -0
  5. package/dist/_chunks/ca-BUpuZx8N.js +121 -0
  6. package/dist/_chunks/ca-BUpuZx8N.js.map +1 -0
  7. package/dist/_chunks/de-A7mEKx6c.mjs +107 -0
  8. package/dist/_chunks/de-A7mEKx6c.mjs.map +1 -0
  9. package/dist/_chunks/de-uGb_Pkq7.js +107 -0
  10. package/dist/_chunks/de-uGb_Pkq7.js.map +1 -0
  11. package/dist/_chunks/dk-BPfkJb9q.mjs +103 -0
  12. package/dist/_chunks/dk-BPfkJb9q.mjs.map +1 -0
  13. package/dist/_chunks/dk-Cd8oFO-O.js +103 -0
  14. package/dist/_chunks/dk-Cd8oFO-O.js.map +1 -0
  15. package/dist/_chunks/en-BcOqhiNe.js +144 -0
  16. package/dist/_chunks/en-BcOqhiNe.js.map +1 -0
  17. package/dist/_chunks/en-oDx2Gnre.mjs +144 -0
  18. package/dist/_chunks/en-oDx2Gnre.mjs.map +1 -0
  19. package/dist/_chunks/es-CuWi2pOn.mjs +120 -0
  20. package/dist/_chunks/es-CuWi2pOn.mjs.map +1 -0
  21. package/dist/_chunks/es-DWFtw_h4.js +120 -0
  22. package/dist/_chunks/es-DWFtw_h4.js.map +1 -0
  23. package/dist/_chunks/fr-BN6ndmWf.mjs +144 -0
  24. package/dist/_chunks/fr-BN6ndmWf.mjs.map +1 -0
  25. package/dist/_chunks/fr-D2bop66d.js +144 -0
  26. package/dist/_chunks/fr-D2bop66d.js.map +1 -0
  27. package/dist/_chunks/graphql-BjGMWMOu.js +71 -0
  28. package/dist/_chunks/graphql-BjGMWMOu.js.map +1 -0
  29. package/dist/_chunks/graphql-CNptEo9C.mjs +71 -0
  30. package/dist/_chunks/graphql-CNptEo9C.mjs.map +1 -0
  31. package/dist/_chunks/he-BpxHjaZg.js +76 -0
  32. package/dist/_chunks/he-BpxHjaZg.js.map +1 -0
  33. package/dist/_chunks/he-C9ZOXBB-.mjs +76 -0
  34. package/dist/_chunks/he-C9ZOXBB-.mjs.map +1 -0
  35. package/dist/_chunks/index-BCcXIErg.mjs +224 -0
  36. package/dist/_chunks/index-BCcXIErg.mjs.map +1 -0
  37. package/dist/_chunks/index-BDYIKKrJ.js +6651 -0
  38. package/dist/_chunks/index-BDYIKKrJ.js.map +1 -0
  39. package/dist/_chunks/index-CPo-QoT2.mjs +6625 -0
  40. package/dist/_chunks/index-CPo-QoT2.mjs.map +1 -0
  41. package/dist/_chunks/index-CZA6-NdH.js +2724 -0
  42. package/dist/_chunks/index-CZA6-NdH.js.map +1 -0
  43. package/dist/_chunks/index-CoTVL7lJ.mjs +2713 -0
  44. package/dist/_chunks/index-CoTVL7lJ.mjs.map +1 -0
  45. package/dist/_chunks/index-CzVTdszL.js +266 -0
  46. package/dist/_chunks/index-CzVTdszL.js.map +1 -0
  47. package/dist/_chunks/index-DS5ATP82.js +856 -0
  48. package/dist/_chunks/index-DS5ATP82.js.map +1 -0
  49. package/dist/_chunks/index-DlSTVFYd.js +229 -0
  50. package/dist/_chunks/index-DlSTVFYd.js.map +1 -0
  51. package/dist/_chunks/index-DoOeVmlB.mjs +835 -0
  52. package/dist/_chunks/index-DoOeVmlB.mjs.map +1 -0
  53. package/dist/_chunks/index-G4FtILKc.mjs +262 -0
  54. package/dist/_chunks/index-G4FtILKc.mjs.map +1 -0
  55. package/dist/_chunks/it-B7rmoZNx.mjs +76 -0
  56. package/dist/_chunks/it-B7rmoZNx.mjs.map +1 -0
  57. package/dist/_chunks/it-BKCWXl8t.js +76 -0
  58. package/dist/_chunks/it-BKCWXl8t.js.map +1 -0
  59. package/dist/_chunks/ja-DlaJTi_3.mjs +76 -0
  60. package/dist/_chunks/ja-DlaJTi_3.mjs.map +1 -0
  61. package/dist/_chunks/ja-ajHzIJz6.js +76 -0
  62. package/dist/_chunks/ja-ajHzIJz6.js.map +1 -0
  63. package/dist/_chunks/ko-Pzj-818C.js +106 -0
  64. package/dist/_chunks/ko-Pzj-818C.js.map +1 -0
  65. package/dist/_chunks/ko-vJl9kPpn.mjs +106 -0
  66. package/dist/_chunks/ko-vJl9kPpn.mjs.map +1 -0
  67. package/dist/_chunks/ms-CqwG8v8l.mjs +68 -0
  68. package/dist/_chunks/ms-CqwG8v8l.mjs.map +1 -0
  69. package/dist/_chunks/ms-h3gjldBy.js +68 -0
  70. package/dist/_chunks/ms-h3gjldBy.js.map +1 -0
  71. package/dist/_chunks/pl-Cj8jChOO.mjs +105 -0
  72. package/dist/_chunks/pl-Cj8jChOO.mjs.map +1 -0
  73. package/dist/_chunks/pl-esgZ7ltN.js +105 -0
  74. package/dist/_chunks/pl-esgZ7ltN.js.map +1 -0
  75. package/dist/_chunks/pt-BR-B4LJHJIp.mjs +76 -0
  76. package/dist/_chunks/pt-BR-B4LJHJIp.mjs.map +1 -0
  77. package/dist/_chunks/pt-BR-Cazr7Z5I.js +76 -0
  78. package/dist/_chunks/pt-BR-Cazr7Z5I.js.map +1 -0
  79. package/dist/_chunks/pt-CNOOM_7x.mjs +76 -0
  80. package/dist/_chunks/pt-CNOOM_7x.mjs.map +1 -0
  81. package/dist/_chunks/pt-cbUnkHM5.js +76 -0
  82. package/dist/_chunks/pt-cbUnkHM5.js.map +1 -0
  83. package/dist/_chunks/ru-DqglvSUC.mjs +76 -0
  84. package/dist/_chunks/ru-DqglvSUC.mjs.map +1 -0
  85. package/dist/_chunks/ru-H6MzFUxp.js +76 -0
  86. package/dist/_chunks/ru-H6MzFUxp.js.map +1 -0
  87. package/dist/_chunks/sk-CZxC4dFY.js +122 -0
  88. package/dist/_chunks/sk-CZxC4dFY.js.map +1 -0
  89. package/dist/_chunks/sk-Dgpb3lnz.mjs +122 -0
  90. package/dist/_chunks/sk-Dgpb3lnz.mjs.map +1 -0
  91. package/dist/_chunks/th-C6unJZ8j.js +76 -0
  92. package/dist/_chunks/th-C6unJZ8j.js.map +1 -0
  93. package/dist/_chunks/th-DRfzuiFf.mjs +76 -0
  94. package/dist/_chunks/th-DRfzuiFf.mjs.map +1 -0
  95. package/dist/_chunks/tr--GzWXE_A.mjs +122 -0
  96. package/dist/_chunks/tr--GzWXE_A.mjs.map +1 -0
  97. package/dist/_chunks/tr-CY6AwX50.js +122 -0
  98. package/dist/_chunks/tr-CY6AwX50.js.map +1 -0
  99. package/dist/_chunks/uk-BniyNsD4.js +73 -0
  100. package/dist/_chunks/uk-BniyNsD4.js.map +1 -0
  101. package/dist/_chunks/uk-DVMT2Piq.mjs +73 -0
  102. package/dist/_chunks/uk-DVMT2Piq.mjs.map +1 -0
  103. package/dist/_chunks/zh-CsZw0IpM.js +129 -0
  104. package/dist/_chunks/zh-CsZw0IpM.js.map +1 -0
  105. package/dist/_chunks/zh-HOnih0is.mjs +129 -0
  106. package/dist/_chunks/zh-HOnih0is.mjs.map +1 -0
  107. package/dist/_chunks/zh-Hans-Cpmhg8uH.mjs +152 -0
  108. package/dist/_chunks/zh-Hans-Cpmhg8uH.mjs.map +1 -0
  109. package/dist/_chunks/zh-Hans-k_xAc6nm.js +152 -0
  110. package/dist/_chunks/zh-Hans-k_xAc6nm.js.map +1 -0
  111. package/dist/admin/index.js +5 -0
  112. package/dist/admin/index.js.map +1 -0
  113. package/dist/admin/index.mjs +6 -0
  114. package/dist/admin/index.mjs.map +1 -0
  115. package/dist/server/index.js +4 -0
  116. package/dist/server/index.js.map +1 -0
  117. package/dist/server/index.mjs +5 -0
  118. package/dist/server/index.mjs.map +1 -0
  119. package/dist/server/src/bootstrap.d.ts +5 -0
  120. package/dist/server/src/bootstrap.d.ts.map +1 -0
  121. package/dist/server/src/config.d.ts +10 -0
  122. package/dist/server/src/config.d.ts.map +1 -0
  123. package/dist/server/src/constants.d.ts +20 -0
  124. package/dist/server/src/constants.d.ts.map +1 -0
  125. package/dist/server/src/content-types/file.d.ts +110 -0
  126. package/dist/server/src/content-types/file.d.ts.map +1 -0
  127. package/dist/server/src/content-types/folder.d.ts +61 -0
  128. package/dist/server/src/content-types/folder.d.ts.map +1 -0
  129. package/dist/server/src/content-types/index.d.ts +170 -0
  130. package/dist/server/src/content-types/index.d.ts.map +1 -0
  131. package/dist/server/src/controllers/admin-file.d.ts +16 -0
  132. package/dist/server/src/controllers/admin-file.d.ts.map +1 -0
  133. package/dist/server/src/controllers/admin-folder-file.d.ts +7 -0
  134. package/dist/server/src/controllers/admin-folder-file.d.ts.map +1 -0
  135. package/dist/server/src/controllers/admin-folder.d.ts +10 -0
  136. package/dist/server/src/controllers/admin-folder.d.ts.map +1 -0
  137. package/dist/server/src/controllers/admin-settings.d.ts +7 -0
  138. package/dist/server/src/controllers/admin-settings.d.ts.map +1 -0
  139. package/dist/server/src/controllers/admin-upload.d.ts +9 -0
  140. package/dist/server/src/controllers/admin-upload.d.ts.map +1 -0
  141. package/dist/server/src/controllers/content-api.d.ts +15 -0
  142. package/dist/server/src/controllers/content-api.d.ts.map +1 -0
  143. package/dist/server/src/controllers/index.d.ts +53 -0
  144. package/dist/server/src/controllers/index.d.ts.map +1 -0
  145. package/dist/server/src/controllers/utils/find-entity-and-check-permissions.d.ts +6 -0
  146. package/dist/server/src/controllers/utils/find-entity-and-check-permissions.d.ts.map +1 -0
  147. package/dist/server/src/controllers/utils/folders.d.ts +4 -0
  148. package/dist/server/src/controllers/utils/folders.d.ts.map +1 -0
  149. package/dist/server/src/controllers/validation/admin/configureView.d.ts +15 -0
  150. package/dist/server/src/controllers/validation/admin/configureView.d.ts.map +1 -0
  151. package/dist/server/src/controllers/validation/admin/folder-file.d.ts +3 -0
  152. package/dist/server/src/controllers/validation/admin/folder-file.d.ts.map +1 -0
  153. package/dist/server/src/controllers/validation/admin/folder.d.ts +3 -0
  154. package/dist/server/src/controllers/validation/admin/folder.d.ts.map +1 -0
  155. package/dist/server/src/controllers/validation/admin/settings.d.ts +18 -0
  156. package/dist/server/src/controllers/validation/admin/settings.d.ts.map +1 -0
  157. package/dist/server/src/controllers/validation/admin/upload.d.ts +109 -0
  158. package/dist/server/src/controllers/validation/admin/upload.d.ts.map +1 -0
  159. package/dist/server/src/controllers/validation/admin/utils.d.ts +3 -0
  160. package/dist/server/src/controllers/validation/admin/utils.d.ts.map +1 -0
  161. package/dist/server/src/controllers/validation/content-api/upload.d.ts +91 -0
  162. package/dist/server/src/controllers/validation/content-api/upload.d.ts.map +1 -0
  163. package/dist/server/src/controllers/view-configuration.d.ts +7 -0
  164. package/dist/server/src/controllers/view-configuration.d.ts.map +1 -0
  165. package/dist/server/src/graphql.d.ts +5 -0
  166. package/dist/server/src/graphql.d.ts.map +1 -0
  167. package/dist/server/src/index.d.ts +431 -0
  168. package/dist/server/src/index.d.ts.map +1 -0
  169. package/dist/server/src/middlewares/upload.d.ts +9 -0
  170. package/dist/server/src/middlewares/upload.d.ts.map +1 -0
  171. package/dist/server/src/register.d.ts +8 -0
  172. package/dist/server/src/register.d.ts.map +1 -0
  173. package/dist/server/src/routes/admin.d.ts +17 -0
  174. package/dist/server/src/routes/admin.d.ts.map +1 -0
  175. package/dist/server/src/routes/content-api.d.ts +9 -0
  176. package/dist/server/src/routes/content-api.d.ts.map +1 -0
  177. package/dist/server/src/routes/index.d.ts +43 -0
  178. package/dist/server/src/routes/index.d.ts.map +1 -0
  179. package/dist/server/src/routes/view-configuration.d.ts +17 -0
  180. package/dist/server/src/routes/view-configuration.d.ts.map +1 -0
  181. package/dist/server/src/services/api-upload-folder.d.ts +5 -0
  182. package/dist/server/src/services/api-upload-folder.d.ts.map +1 -0
  183. package/dist/server/src/services/extensions/index.d.ts +5 -0
  184. package/dist/server/src/services/extensions/index.d.ts.map +1 -0
  185. package/dist/server/src/services/extensions/utils.d.ts +14 -0
  186. package/dist/server/src/services/extensions/utils.d.ts.map +1 -0
  187. package/dist/server/src/services/file.d.ts +8 -0
  188. package/dist/server/src/services/file.d.ts.map +1 -0
  189. package/dist/server/src/services/folder.d.ts +32 -0
  190. package/dist/server/src/services/folder.d.ts.map +1 -0
  191. package/dist/server/src/services/image-manipulation.d.ts +20 -0
  192. package/dist/server/src/services/image-manipulation.d.ts.map +1 -0
  193. package/dist/server/src/services/index.d.ts +152 -0
  194. package/dist/server/src/services/index.d.ts.map +1 -0
  195. package/dist/server/src/services/metrics.d.ts +8 -0
  196. package/dist/server/src/services/metrics.d.ts.map +1 -0
  197. package/dist/server/src/services/provider.d.ts +10 -0
  198. package/dist/server/src/services/provider.d.ts.map +1 -0
  199. package/dist/server/src/services/upload.d.ts +67 -0
  200. package/dist/server/src/services/upload.d.ts.map +1 -0
  201. package/dist/server/src/services/weekly-metrics.d.ts +17 -0
  202. package/dist/server/src/services/weekly-metrics.d.ts.map +1 -0
  203. package/dist/server/src/types.d.ts +75 -0
  204. package/dist/server/src/types.d.ts.map +1 -0
  205. package/dist/server/src/utils/cron.d.ts +3 -0
  206. package/dist/server/src/utils/cron.d.ts.map +1 -0
  207. package/dist/server/src/utils/index.d.ts +23 -0
  208. package/dist/server/src/utils/index.d.ts.map +1 -0
  209. package/package.json +111 -0
  210. package/strapi-server.js +3 -0
@@ -0,0 +1,2724 @@
1
+ "use strict";
2
+ const _ = require("lodash");
3
+ const utils = require("@strapi/utils");
4
+ const range = require("koa-range");
5
+ const koaStatic = require("koa-static");
6
+ const fp = require("lodash/fp");
7
+ const os = require("os");
8
+ const path = require("path");
9
+ const crypto = require("crypto");
10
+ const fs = require("fs");
11
+ const fse = require("fs-extra");
12
+ const mimeTypes = require("mime-types");
13
+ const sharp = require("sharp");
14
+ const add = require("date-fns/add");
15
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
16
+ const ___default = /* @__PURE__ */ _interopDefault(_);
17
+ const utils__default = /* @__PURE__ */ _interopDefault(utils);
18
+ const range__default = /* @__PURE__ */ _interopDefault(range);
19
+ const koaStatic__default = /* @__PURE__ */ _interopDefault(koaStatic);
20
+ const os__default = /* @__PURE__ */ _interopDefault(os);
21
+ const path__default = /* @__PURE__ */ _interopDefault(path);
22
+ const crypto__default = /* @__PURE__ */ _interopDefault(crypto);
23
+ const fs__default = /* @__PURE__ */ _interopDefault(fs);
24
+ const fse__default = /* @__PURE__ */ _interopDefault(fse);
25
+ const sharp__default = /* @__PURE__ */ _interopDefault(sharp);
26
+ const add__default = /* @__PURE__ */ _interopDefault(add);
27
+ const registerUploadMiddleware = ({ strapi: strapi2 }) => {
28
+ strapi2.server.app.on("error", (err) => {
29
+ if (err.code === "EPIPE") {
30
+ return;
31
+ }
32
+ strapi2.server.app.onerror(err);
33
+ });
34
+ const localServerConfig = strapi2.config.get("plugin::upload.providerOptions.localServer", {});
35
+ strapi2.server.routes([
36
+ {
37
+ method: "GET",
38
+ path: "/uploads/(.*)",
39
+ handler: [range__default.default, koaStatic__default.default(strapi2.dirs.static.public, { defer: true, ...localServerConfig })],
40
+ config: { auth: false }
41
+ }
42
+ ]);
43
+ };
44
+ const paths = {
45
+ "/upload": {
46
+ post: {
47
+ description: "Upload files",
48
+ responses: {
49
+ "200": {
50
+ description: "response",
51
+ content: {
52
+ "application/json": {
53
+ schema: {
54
+ type: "array",
55
+ items: {
56
+ $ref: "#/components/schemas/UploadFile"
57
+ }
58
+ }
59
+ }
60
+ }
61
+ }
62
+ },
63
+ summary: "",
64
+ tags: [
65
+ "Upload - File"
66
+ ],
67
+ requestBody: {
68
+ description: "Upload files",
69
+ required: true,
70
+ content: {
71
+ "multipart/form-data": {
72
+ schema: {
73
+ required: [
74
+ "files"
75
+ ],
76
+ type: "object",
77
+ properties: {
78
+ path: {
79
+ type: "string",
80
+ description: "The folder where the file(s) will be uploaded to (only supported on strapi-provider-upload-aws-s3)."
81
+ },
82
+ refId: {
83
+ type: "string",
84
+ description: "The ID of the entry which the file(s) will be linked to"
85
+ },
86
+ ref: {
87
+ type: "string",
88
+ description: "The unique ID (uid) of the model which the file(s) will be linked to (api::restaurant.restaurant)."
89
+ },
90
+ field: {
91
+ type: "string",
92
+ description: "The field of the entry which the file(s) will be precisely linked to."
93
+ },
94
+ files: {
95
+ type: "array",
96
+ items: {
97
+ type: "string",
98
+ format: "binary"
99
+ }
100
+ }
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+ }
107
+ },
108
+ "/upload?id={id}": {
109
+ post: {
110
+ parameters: [
111
+ {
112
+ name: "id",
113
+ "in": "query",
114
+ description: "File id",
115
+ required: true,
116
+ schema: {
117
+ type: "string"
118
+ }
119
+ }
120
+ ],
121
+ description: "Upload file information",
122
+ responses: {
123
+ "200": {
124
+ description: "response",
125
+ content: {
126
+ "application/json": {
127
+ schema: {
128
+ type: "array",
129
+ items: {
130
+ $ref: "#/components/schemas/UploadFile"
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ },
137
+ summary: "",
138
+ tags: [
139
+ "Upload - File"
140
+ ],
141
+ requestBody: {
142
+ description: "Upload files",
143
+ required: true,
144
+ content: {
145
+ "multipart/form-data": {
146
+ schema: {
147
+ type: "object",
148
+ properties: {
149
+ fileInfo: {
150
+ type: "object",
151
+ properties: {
152
+ name: {
153
+ type: "string"
154
+ },
155
+ alternativeText: {
156
+ type: "string"
157
+ },
158
+ caption: {
159
+ type: "string"
160
+ }
161
+ }
162
+ },
163
+ files: {
164
+ type: "string",
165
+ format: "binary"
166
+ }
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ }
173
+ },
174
+ "/upload/files": {
175
+ get: {
176
+ tags: [
177
+ "Upload - File"
178
+ ],
179
+ responses: {
180
+ "200": {
181
+ description: "Get a list of files",
182
+ content: {
183
+ "application/json": {
184
+ schema: {
185
+ type: "array",
186
+ items: {
187
+ $ref: "#/components/schemas/UploadFile"
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+ }
194
+ }
195
+ },
196
+ "/upload/files/{id}": {
197
+ get: {
198
+ parameters: [
199
+ {
200
+ name: "id",
201
+ "in": "path",
202
+ description: "",
203
+ deprecated: false,
204
+ required: true,
205
+ schema: {
206
+ type: "string"
207
+ }
208
+ }
209
+ ],
210
+ tags: [
211
+ "Upload - File"
212
+ ],
213
+ responses: {
214
+ "200": {
215
+ description: "Get a specific file",
216
+ content: {
217
+ "application/json": {
218
+ schema: {
219
+ $ref: "#/components/schemas/UploadFile"
220
+ }
221
+ }
222
+ }
223
+ }
224
+ }
225
+ },
226
+ "delete": {
227
+ parameters: [
228
+ {
229
+ name: "id",
230
+ "in": "path",
231
+ description: "",
232
+ deprecated: false,
233
+ required: true,
234
+ schema: {
235
+ type: "string"
236
+ }
237
+ }
238
+ ],
239
+ tags: [
240
+ "Upload - File"
241
+ ],
242
+ responses: {
243
+ "200": {
244
+ description: "Delete a file",
245
+ content: {
246
+ "application/json": {
247
+ schema: {
248
+ $ref: "#/components/schemas/UploadFile"
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+ }
255
+ }
256
+ };
257
+ const components = {
258
+ schemas: {
259
+ UploadFile: {
260
+ properties: {
261
+ id: {
262
+ type: "number"
263
+ },
264
+ name: {
265
+ type: "string"
266
+ },
267
+ alternativeText: {
268
+ type: "string"
269
+ },
270
+ caption: {
271
+ type: "string"
272
+ },
273
+ width: {
274
+ type: "number",
275
+ format: "integer"
276
+ },
277
+ height: {
278
+ type: "number",
279
+ format: "integer"
280
+ },
281
+ formats: {
282
+ type: "number"
283
+ },
284
+ hash: {
285
+ type: "string"
286
+ },
287
+ ext: {
288
+ type: "string"
289
+ },
290
+ mime: {
291
+ type: "string"
292
+ },
293
+ size: {
294
+ type: "number",
295
+ format: "double"
296
+ },
297
+ url: {
298
+ type: "string"
299
+ },
300
+ previewUrl: {
301
+ type: "string"
302
+ },
303
+ provider: {
304
+ type: "string"
305
+ },
306
+ provider_metadata: {
307
+ type: "object"
308
+ },
309
+ createdAt: {
310
+ type: "string",
311
+ format: "date-time"
312
+ },
313
+ updatedAt: {
314
+ type: "string",
315
+ format: "date-time"
316
+ }
317
+ }
318
+ }
319
+ }
320
+ };
321
+ const spec = {
322
+ paths,
323
+ components
324
+ };
325
+ const { PayloadTooLargeError } = utils.errors;
326
+ const { bytesToHumanReadable, kbytesToBytes } = utils.file;
327
+ async function register({ strapi: strapi2 }) {
328
+ strapi2.plugin("upload").provider = createProvider(strapi2.config.get("plugin::upload"));
329
+ await registerUploadMiddleware({ strapi: strapi2 });
330
+ if (strapi2.plugin("graphql")) {
331
+ const { installGraphqlExtension } = await Promise.resolve().then(() => require("./graphql-BjGMWMOu.js"));
332
+ installGraphqlExtension({ strapi: strapi2 });
333
+ }
334
+ if (strapi2.plugin("documentation")) {
335
+ strapi2.plugin("documentation").service("override").registerOverride(spec, {
336
+ pluginOrigin: "upload",
337
+ excludeFromGeneration: ["upload"]
338
+ });
339
+ }
340
+ }
341
+ const createProvider = (config2) => {
342
+ const { providerOptions, actionOptions = {} } = config2;
343
+ const providerName = ___default.default.toLower(config2.provider);
344
+ let provider2;
345
+ let modulePath;
346
+ try {
347
+ modulePath = require.resolve(`@strapi/provider-upload-${providerName}`);
348
+ } catch (error) {
349
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "MODULE_NOT_FOUND") {
350
+ modulePath = providerName;
351
+ } else {
352
+ throw error;
353
+ }
354
+ }
355
+ try {
356
+ provider2 = require(modulePath);
357
+ } catch (err) {
358
+ const newError = new Error(`Could not load upload provider "${providerName}".`);
359
+ if (err instanceof Error) {
360
+ newError.stack = err.stack;
361
+ }
362
+ throw newError;
363
+ }
364
+ const providerInstance = provider2.init(providerOptions);
365
+ if (!providerInstance.delete) {
366
+ throw new Error(`The upload provider "${providerName}" doesn't implement the delete method.`);
367
+ }
368
+ if (!providerInstance.upload && !providerInstance.uploadStream) {
369
+ throw new Error(
370
+ `The upload provider "${providerName}" doesn't implement the uploadStream nor the upload method.`
371
+ );
372
+ }
373
+ if (!providerInstance.uploadStream) {
374
+ process.emitWarning(
375
+ `The upload provider "${providerName}" doesn't implement the uploadStream function. Strapi will fallback on the upload method. Some performance issues may occur.`
376
+ );
377
+ }
378
+ const wrappedProvider = ___default.default.mapValues(providerInstance, (method, methodName) => {
379
+ return async (file2, options = actionOptions[methodName]) => providerInstance[methodName](file2, options);
380
+ });
381
+ return Object.assign(Object.create(baseProvider), wrappedProvider);
382
+ };
383
+ const baseProvider = {
384
+ extend(obj) {
385
+ Object.assign(this, obj);
386
+ },
387
+ checkFileSize(file2, { sizeLimit }) {
388
+ if (sizeLimit && kbytesToBytes(file2.size) > sizeLimit) {
389
+ throw new PayloadTooLargeError(
390
+ `${file2.originalFilename} exceeds size limit of ${bytesToHumanReadable(sizeLimit)}.`
391
+ );
392
+ }
393
+ },
394
+ getSignedUrl(file2) {
395
+ return file2;
396
+ },
397
+ isPrivate() {
398
+ return false;
399
+ }
400
+ };
401
+ const getService = (name) => {
402
+ return strapi.plugin("upload").service(name);
403
+ };
404
+ const ACTIONS = {
405
+ read: "plugin::upload.read",
406
+ readSettings: "plugin::upload.settings.read",
407
+ create: "plugin::upload.assets.create",
408
+ update: "plugin::upload.assets.update",
409
+ download: "plugin::upload.assets.download",
410
+ copyLink: "plugin::upload.assets.copy-link",
411
+ configureView: "plugin::upload.configure-view"
412
+ };
413
+ const ALLOWED_SORT_STRINGS = [
414
+ "createdAt:DESC",
415
+ "createdAt:ASC",
416
+ "name:ASC",
417
+ "name:DESC",
418
+ "updatedAt:DESC",
419
+ "updatedAt:ASC"
420
+ ];
421
+ const ALLOWED_WEBHOOK_EVENTS = {
422
+ MEDIA_CREATE: "media.create",
423
+ MEDIA_UPDATE: "media.update",
424
+ MEDIA_DELETE: "media.delete"
425
+ };
426
+ const FOLDER_MODEL_UID = "plugin::upload.folder";
427
+ const FILE_MODEL_UID = "plugin::upload.file";
428
+ const API_UPLOAD_FOLDER_BASE_NAME = "API Uploads";
429
+ async function bootstrap({ strapi: strapi2 }) {
430
+ const defaultConfig = {
431
+ settings: {
432
+ sizeOptimization: true,
433
+ responsiveDimensions: true,
434
+ autoOrientation: false
435
+ },
436
+ view_configuration: {
437
+ pageSize: 10,
438
+ sort: ALLOWED_SORT_STRINGS[0]
439
+ }
440
+ };
441
+ for (const [key, defaultValue] of Object.entries(defaultConfig)) {
442
+ const configurator = strapi2.store({ type: "plugin", name: "upload", key });
443
+ const config2 = await configurator.get({});
444
+ if (config2 && Object.keys(defaultValue).every((key2) => Object.prototype.hasOwnProperty.call(config2, key2))) {
445
+ continue;
446
+ }
447
+ await configurator.set({
448
+ value: Object.assign(defaultValue, config2 || {})
449
+ });
450
+ }
451
+ await registerPermissionActions();
452
+ await registerWebhookEvents();
453
+ await getService("weeklyMetrics").registerCron();
454
+ getService("metrics").sendUploadPluginMetrics();
455
+ getService("extensions").signFileUrlsOnDocumentService();
456
+ }
457
+ const registerWebhookEvents = async () => Object.entries(ALLOWED_WEBHOOK_EVENTS).forEach(([key, value]) => {
458
+ strapi.get("webhookStore").addAllowedEvent(key, value);
459
+ });
460
+ const registerPermissionActions = async () => {
461
+ const actions = [
462
+ {
463
+ section: "plugins",
464
+ displayName: "Access the Media Library",
465
+ uid: "read",
466
+ pluginName: "upload"
467
+ },
468
+ {
469
+ section: "plugins",
470
+ displayName: "Create (upload)",
471
+ uid: "assets.create",
472
+ subCategory: "assets",
473
+ pluginName: "upload"
474
+ },
475
+ {
476
+ section: "plugins",
477
+ displayName: "Update (crop, details, replace) + delete",
478
+ uid: "assets.update",
479
+ subCategory: "assets",
480
+ pluginName: "upload"
481
+ },
482
+ {
483
+ section: "plugins",
484
+ displayName: "Download",
485
+ uid: "assets.download",
486
+ subCategory: "assets",
487
+ pluginName: "upload"
488
+ },
489
+ {
490
+ section: "plugins",
491
+ displayName: "Copy link",
492
+ uid: "assets.copy-link",
493
+ subCategory: "assets",
494
+ pluginName: "upload"
495
+ },
496
+ {
497
+ section: "plugins",
498
+ displayName: "Configure view",
499
+ uid: "configure-view",
500
+ pluginName: "upload"
501
+ },
502
+ {
503
+ section: "settings",
504
+ displayName: "Access the Media Library settings page",
505
+ uid: "settings.read",
506
+ category: "media library",
507
+ pluginName: "upload"
508
+ }
509
+ ];
510
+ await strapi.service("admin::permission").actionProvider.registerMany(actions);
511
+ };
512
+ const file$1 = {
513
+ schema: {
514
+ collectionName: "files",
515
+ info: {
516
+ singularName: "file",
517
+ pluralName: "files",
518
+ displayName: "File",
519
+ description: ""
520
+ },
521
+ options: {},
522
+ pluginOptions: {
523
+ "content-manager": {
524
+ visible: false
525
+ },
526
+ "content-type-builder": {
527
+ visible: false
528
+ }
529
+ },
530
+ attributes: {
531
+ name: {
532
+ type: "string",
533
+ configurable: false,
534
+ required: true
535
+ },
536
+ alternativeText: {
537
+ type: "string",
538
+ configurable: false
539
+ },
540
+ caption: {
541
+ type: "string",
542
+ configurable: false
543
+ },
544
+ width: {
545
+ type: "integer",
546
+ configurable: false
547
+ },
548
+ height: {
549
+ type: "integer",
550
+ configurable: false
551
+ },
552
+ formats: {
553
+ type: "json",
554
+ configurable: false
555
+ },
556
+ hash: {
557
+ type: "string",
558
+ configurable: false,
559
+ required: true
560
+ },
561
+ ext: {
562
+ type: "string",
563
+ configurable: false
564
+ },
565
+ mime: {
566
+ type: "string",
567
+ configurable: false,
568
+ required: true
569
+ },
570
+ size: {
571
+ type: "decimal",
572
+ configurable: false,
573
+ required: true
574
+ },
575
+ url: {
576
+ type: "string",
577
+ configurable: false,
578
+ required: true
579
+ },
580
+ previewUrl: {
581
+ type: "string",
582
+ configurable: false
583
+ },
584
+ provider: {
585
+ type: "string",
586
+ configurable: false,
587
+ required: true
588
+ },
589
+ provider_metadata: {
590
+ type: "json",
591
+ configurable: false
592
+ },
593
+ related: {
594
+ type: "relation",
595
+ relation: "morphToMany",
596
+ configurable: false
597
+ },
598
+ folder: {
599
+ type: "relation",
600
+ relation: "manyToOne",
601
+ target: FOLDER_MODEL_UID,
602
+ inversedBy: "files",
603
+ private: true
604
+ },
605
+ folderPath: {
606
+ type: "string",
607
+ minLength: 1,
608
+ required: true,
609
+ private: true,
610
+ searchable: false
611
+ }
612
+ },
613
+ // experimental feature:
614
+ indexes: [
615
+ {
616
+ name: "upload_files_folder_path_index",
617
+ columns: ["folder_path"],
618
+ type: null
619
+ },
620
+ {
621
+ name: `upload_files_created_at_index`,
622
+ columns: ["created_at"],
623
+ type: null
624
+ },
625
+ {
626
+ name: `upload_files_updated_at_index`,
627
+ columns: ["updated_at"],
628
+ type: null
629
+ },
630
+ {
631
+ name: `upload_files_name_index`,
632
+ columns: ["name"],
633
+ type: null
634
+ },
635
+ {
636
+ name: `upload_files_size_index`,
637
+ columns: ["size"],
638
+ type: null
639
+ },
640
+ {
641
+ name: `upload_files_ext_index`,
642
+ columns: ["ext"],
643
+ type: null
644
+ }
645
+ ]
646
+ }
647
+ };
648
+ const folder$1 = {
649
+ schema: {
650
+ collectionName: "upload_folders",
651
+ info: {
652
+ singularName: "folder",
653
+ pluralName: "folders",
654
+ displayName: "Folder"
655
+ },
656
+ options: {},
657
+ pluginOptions: {
658
+ "content-manager": {
659
+ visible: false
660
+ },
661
+ "content-type-builder": {
662
+ visible: false
663
+ }
664
+ },
665
+ attributes: {
666
+ name: {
667
+ type: "string",
668
+ minLength: 1,
669
+ required: true
670
+ },
671
+ pathId: {
672
+ type: "integer",
673
+ unique: true,
674
+ required: true
675
+ },
676
+ parent: {
677
+ type: "relation",
678
+ relation: "manyToOne",
679
+ target: FOLDER_MODEL_UID,
680
+ inversedBy: "children"
681
+ },
682
+ children: {
683
+ type: "relation",
684
+ relation: "oneToMany",
685
+ target: FOLDER_MODEL_UID,
686
+ mappedBy: "parent"
687
+ },
688
+ files: {
689
+ type: "relation",
690
+ relation: "oneToMany",
691
+ target: FILE_MODEL_UID,
692
+ mappedBy: "folder"
693
+ },
694
+ path: {
695
+ type: "string",
696
+ minLength: 1,
697
+ required: true
698
+ }
699
+ },
700
+ // experimental feature:
701
+ indexes: [
702
+ {
703
+ name: "upload_folders_path_id_index",
704
+ columns: ["path_id"],
705
+ type: "unique"
706
+ },
707
+ {
708
+ name: "upload_folders_path_index",
709
+ columns: ["path"],
710
+ type: "unique"
711
+ }
712
+ ]
713
+ }
714
+ };
715
+ const contentTypes = {
716
+ file: file$1,
717
+ folder: folder$1
718
+ };
719
+ const provider = ({ strapi: strapi2 }) => ({
720
+ async checkFileSize(file2) {
721
+ const { sizeLimit } = strapi2.config.get("plugin::upload");
722
+ await strapi2.plugin("upload").provider.checkFileSize(file2, { sizeLimit });
723
+ },
724
+ async upload(file2) {
725
+ if (fp.isFunction(strapi2.plugin("upload").provider.uploadStream)) {
726
+ file2.stream = file2.getStream();
727
+ await strapi2.plugin("upload").provider.uploadStream(file2);
728
+ delete file2.stream;
729
+ if ("filepath" in file2) {
730
+ delete file2.filepath;
731
+ }
732
+ } else {
733
+ file2.buffer = await utils.file.streamToBuffer(file2.getStream());
734
+ await strapi2.plugin("upload").provider.upload(file2);
735
+ delete file2.buffer;
736
+ if ("filepath" in file2) {
737
+ delete file2.filepath;
738
+ }
739
+ }
740
+ }
741
+ });
742
+ const { UPDATED_BY_ATTRIBUTE, CREATED_BY_ATTRIBUTE } = utils.contentTypes.constants;
743
+ const { MEDIA_CREATE, MEDIA_UPDATE, MEDIA_DELETE } = ALLOWED_WEBHOOK_EVENTS;
744
+ const { ApplicationError, NotFoundError } = utils.errors;
745
+ const { bytesToKbytes: bytesToKbytes$1 } = utils.file;
746
+ const upload = ({ strapi: strapi2 }) => {
747
+ const randomSuffix = () => crypto__default.default.randomBytes(5).toString("hex");
748
+ const generateFileName = (name) => {
749
+ const baseName = utils.strings.nameToSlug(name, { separator: "_", lowercase: false });
750
+ return `${baseName}_${randomSuffix()}`;
751
+ };
752
+ const sendMediaMetrics = (data) => {
753
+ if (___default.default.has(data, "caption") && !___default.default.isEmpty(data.caption)) {
754
+ strapi2.telemetry.send("didSaveMediaWithCaption");
755
+ }
756
+ if (___default.default.has(data, "alternativeText") && !___default.default.isEmpty(data.alternativeText)) {
757
+ strapi2.telemetry.send("didSaveMediaWithAlternativeText");
758
+ }
759
+ };
760
+ const createAndAssignTmpWorkingDirectoryToFiles = async (files) => {
761
+ const tmpWorkingDirectory = await fse__default.default.mkdtemp(path__default.default.join(os__default.default.tmpdir(), "strapi-upload-"));
762
+ if (Array.isArray(files)) {
763
+ files.forEach((file2) => {
764
+ file2.tmpWorkingDirectory = tmpWorkingDirectory;
765
+ });
766
+ } else {
767
+ files.tmpWorkingDirectory = tmpWorkingDirectory;
768
+ }
769
+ return tmpWorkingDirectory;
770
+ };
771
+ function filenameReservedRegex() {
772
+ return /[<>:"/\\|?*\u0000-\u001F]/g;
773
+ }
774
+ function windowsReservedNameRegex() {
775
+ return /^(con|prn|aux|nul|com\d|lpt\d)$/i;
776
+ }
777
+ function isValidFilename(string) {
778
+ if (!string || string.length > 255) {
779
+ return false;
780
+ }
781
+ if (filenameReservedRegex().test(string) || windowsReservedNameRegex().test(string)) {
782
+ return false;
783
+ }
784
+ if (string === "." || string === "..") {
785
+ return false;
786
+ }
787
+ return true;
788
+ }
789
+ async function emitEvent(event, data) {
790
+ const modelDef = strapi2.getModel(FILE_MODEL_UID);
791
+ const sanitizedData = await utils.sanitize.sanitizers.defaultSanitizeOutput(
792
+ {
793
+ schema: modelDef,
794
+ getModel(uid) {
795
+ return strapi2.getModel(uid);
796
+ }
797
+ },
798
+ data
799
+ );
800
+ strapi2.eventHub.emit(event, { media: sanitizedData });
801
+ }
802
+ async function formatFileInfo({ filename, type, size }, fileInfo = {}, metas = {}) {
803
+ const fileService = getService("file");
804
+ if (!isValidFilename(filename)) {
805
+ throw new ApplicationError("File name contains invalid characters");
806
+ }
807
+ let ext = path__default.default.extname(filename);
808
+ if (!ext) {
809
+ ext = `.${mimeTypes.extension(type)}`;
810
+ }
811
+ const usedName = (fileInfo.name || filename).normalize();
812
+ const basename = path__default.default.basename(usedName, ext);
813
+ if (!isValidFilename(filename)) {
814
+ throw new ApplicationError("File name contains invalid characters");
815
+ }
816
+ const entity = {
817
+ name: usedName,
818
+ alternativeText: fileInfo.alternativeText,
819
+ caption: fileInfo.caption,
820
+ folder: fileInfo.folder,
821
+ folderPath: await fileService.getFolderPath(fileInfo.folder),
822
+ hash: generateFileName(basename),
823
+ ext,
824
+ mime: type,
825
+ size: bytesToKbytes$1(size),
826
+ sizeInBytes: size
827
+ };
828
+ const { refId, ref, field } = metas;
829
+ if (refId && ref && field) {
830
+ entity.related = [
831
+ {
832
+ id: refId,
833
+ __type: ref,
834
+ __pivot: { field }
835
+ }
836
+ ];
837
+ }
838
+ if (metas.path) {
839
+ entity.path = metas.path;
840
+ }
841
+ if (metas.tmpWorkingDirectory) {
842
+ entity.tmpWorkingDirectory = metas.tmpWorkingDirectory;
843
+ }
844
+ return entity;
845
+ }
846
+ async function enhanceAndValidateFile(file2, fileInfo, metas) {
847
+ const currentFile = await formatFileInfo(
848
+ {
849
+ filename: file2.originalFilename ?? "unamed",
850
+ type: file2.mimetype ?? "application/octet-stream",
851
+ size: file2.size
852
+ },
853
+ fileInfo,
854
+ {
855
+ ...metas,
856
+ tmpWorkingDirectory: file2.tmpWorkingDirectory
857
+ }
858
+ );
859
+ currentFile.filepath = file2.filepath;
860
+ currentFile.getStream = () => fs__default.default.createReadStream(file2.filepath);
861
+ const { optimize: optimize2, isImage: isImage2, isFaultyImage: isFaultyImage2, isOptimizableImage: isOptimizableImage2 } = strapi2.plugin("upload").service("image-manipulation");
862
+ if (await isImage2(currentFile)) {
863
+ if (await isFaultyImage2(currentFile)) {
864
+ throw new ApplicationError("File is not a valid image");
865
+ }
866
+ if (await isOptimizableImage2(currentFile)) {
867
+ return optimize2(currentFile);
868
+ }
869
+ }
870
+ return currentFile;
871
+ }
872
+ async function upload2({
873
+ data,
874
+ files
875
+ }, opts) {
876
+ const { user } = opts ?? {};
877
+ const tmpWorkingDirectory = await createAndAssignTmpWorkingDirectoryToFiles(files);
878
+ let uploadedFiles = [];
879
+ try {
880
+ const { fileInfo, ...metas } = data;
881
+ const fileArray = Array.isArray(files) ? files : [files];
882
+ const fileInfoArray = Array.isArray(fileInfo) ? fileInfo : [fileInfo];
883
+ const doUpload = async (file2, fileInfo2) => {
884
+ const fileData = await enhanceAndValidateFile(file2, fileInfo2, metas);
885
+ return uploadFileAndPersist(fileData, { user });
886
+ };
887
+ uploadedFiles = await Promise.all(
888
+ fileArray.map((file2, idx) => doUpload(file2, fileInfoArray[idx] || {}))
889
+ );
890
+ } finally {
891
+ await fse__default.default.remove(tmpWorkingDirectory);
892
+ }
893
+ return uploadedFiles;
894
+ }
895
+ async function uploadImage(fileData) {
896
+ const { getDimensions: getDimensions2, generateThumbnail: generateThumbnail2, generateResponsiveFormats: generateResponsiveFormats2, isResizableImage: isResizableImage2 } = getService("image-manipulation");
897
+ const { width, height } = await getDimensions2(fileData);
898
+ ___default.default.assign(fileData, {
899
+ width,
900
+ height
901
+ });
902
+ const uploadThumbnail = async (thumbnailFile) => {
903
+ await getService("provider").upload(thumbnailFile);
904
+ ___default.default.set(fileData, "formats.thumbnail", thumbnailFile);
905
+ };
906
+ const uploadResponsiveFormat = async (format) => {
907
+ const { key, file: file2 } = format;
908
+ await getService("provider").upload(file2);
909
+ ___default.default.set(fileData, ["formats", key], file2);
910
+ };
911
+ const uploadPromises = [];
912
+ uploadPromises.push(getService("provider").upload(fileData));
913
+ if (await isResizableImage2(fileData)) {
914
+ const thumbnailFile = await generateThumbnail2(fileData);
915
+ if (thumbnailFile) {
916
+ uploadPromises.push(uploadThumbnail(thumbnailFile));
917
+ }
918
+ const formats = await generateResponsiveFormats2(fileData);
919
+ if (Array.isArray(formats) && formats.length > 0) {
920
+ for (const format of formats) {
921
+ if (!format)
922
+ continue;
923
+ uploadPromises.push(uploadResponsiveFormat(format));
924
+ }
925
+ }
926
+ }
927
+ await Promise.all(uploadPromises);
928
+ }
929
+ async function uploadFileAndPersist(fileData, opts) {
930
+ const { user } = opts ?? {};
931
+ const config2 = strapi2.config.get("plugin::upload");
932
+ const { isImage: isImage2 } = getService("image-manipulation");
933
+ await getService("provider").checkFileSize(fileData);
934
+ if (await isImage2(fileData)) {
935
+ await uploadImage(fileData);
936
+ } else {
937
+ await getService("provider").upload(fileData);
938
+ }
939
+ ___default.default.set(fileData, "provider", config2.provider);
940
+ return add2(fileData, { user });
941
+ }
942
+ async function updateFileInfo(id, { name, alternativeText, caption, folder: folder2 }, opts) {
943
+ const { user } = opts ?? {};
944
+ const dbFile = await findOne(id);
945
+ if (!dbFile) {
946
+ throw new NotFoundError();
947
+ }
948
+ const fileService = getService("file");
949
+ const newName = ___default.default.isNil(name) ? dbFile.name : name;
950
+ const newInfos = {
951
+ name: newName,
952
+ alternativeText: ___default.default.isNil(alternativeText) ? dbFile.alternativeText : alternativeText,
953
+ caption: ___default.default.isNil(caption) ? dbFile.caption : caption,
954
+ folder: ___default.default.isUndefined(folder2) ? dbFile.folder : folder2,
955
+ folderPath: ___default.default.isUndefined(folder2) ? dbFile.path : await fileService.getFolderPath(folder2)
956
+ };
957
+ return update2(id, newInfos, { user });
958
+ }
959
+ async function replace(id, { data, file: file2 }, opts) {
960
+ const { user } = opts ?? {};
961
+ const config2 = strapi2.config.get("plugin::upload");
962
+ const { isImage: isImage2 } = getService("image-manipulation");
963
+ const dbFile = await findOne(id);
964
+ if (!dbFile) {
965
+ throw new NotFoundError();
966
+ }
967
+ const tmpWorkingDirectory = await createAndAssignTmpWorkingDirectoryToFiles(file2);
968
+ let fileData;
969
+ try {
970
+ const { fileInfo } = data;
971
+ fileData = await enhanceAndValidateFile(file2, fileInfo);
972
+ ___default.default.assign(fileData, {
973
+ hash: dbFile.hash,
974
+ ext: dbFile.ext
975
+ });
976
+ if (dbFile.provider === config2.provider) {
977
+ await strapi2.plugin("upload").provider.delete(dbFile);
978
+ if (dbFile.formats) {
979
+ await Promise.all(
980
+ Object.keys(dbFile.formats).map((key) => {
981
+ return strapi2.plugin("upload").provider.delete(dbFile.formats[key]);
982
+ })
983
+ );
984
+ }
985
+ }
986
+ ___default.default.set(fileData, "formats", {});
987
+ if (await isImage2(fileData)) {
988
+ await uploadImage(fileData);
989
+ } else {
990
+ await getService("provider").upload(fileData);
991
+ }
992
+ ___default.default.set(fileData, "provider", config2.provider);
993
+ } finally {
994
+ await fse__default.default.remove(tmpWorkingDirectory);
995
+ }
996
+ return update2(id, fileData, { user });
997
+ }
998
+ async function update2(id, values, opts) {
999
+ const { user } = opts ?? {};
1000
+ const fileValues = { ...values };
1001
+ if (user) {
1002
+ Object.assign(fileValues, {
1003
+ [UPDATED_BY_ATTRIBUTE]: user.id
1004
+ });
1005
+ }
1006
+ sendMediaMetrics(fileValues);
1007
+ const res = await strapi2.db.query(FILE_MODEL_UID).update({ where: { id }, data: fileValues });
1008
+ await emitEvent(MEDIA_UPDATE, res);
1009
+ return res;
1010
+ }
1011
+ async function add2(values, opts) {
1012
+ const { user } = opts ?? {};
1013
+ const fileValues = { ...values };
1014
+ if (user) {
1015
+ Object.assign(fileValues, {
1016
+ [UPDATED_BY_ATTRIBUTE]: user.id,
1017
+ [CREATED_BY_ATTRIBUTE]: user.id
1018
+ });
1019
+ }
1020
+ sendMediaMetrics(fileValues);
1021
+ const res = await strapi2.db.query(FILE_MODEL_UID).create({ data: fileValues });
1022
+ await emitEvent(MEDIA_CREATE, res);
1023
+ return res;
1024
+ }
1025
+ function findOne(id, populate = {}) {
1026
+ const query = strapi2.get("query-params").transform(FILE_MODEL_UID, {
1027
+ populate
1028
+ });
1029
+ return strapi2.db.query(FILE_MODEL_UID).findOne({
1030
+ where: { id },
1031
+ ...query
1032
+ });
1033
+ }
1034
+ function findMany(query = {}) {
1035
+ return strapi2.db.query(FILE_MODEL_UID).findMany(strapi2.get("query-params").transform(FILE_MODEL_UID, query));
1036
+ }
1037
+ function findPage(query = {}) {
1038
+ return strapi2.db.query(FILE_MODEL_UID).findPage(strapi2.get("query-params").transform(FILE_MODEL_UID, query));
1039
+ }
1040
+ async function remove(file2) {
1041
+ const config2 = strapi2.config.get("plugin::upload");
1042
+ if (file2.provider === config2.provider) {
1043
+ await strapi2.plugin("upload").provider.delete(file2);
1044
+ if (file2.formats) {
1045
+ const keys = Object.keys(file2.formats);
1046
+ await Promise.all(
1047
+ keys.map((key) => {
1048
+ return strapi2.plugin("upload").provider.delete(file2.formats[key]);
1049
+ })
1050
+ );
1051
+ }
1052
+ }
1053
+ const media = await strapi2.db.query(FILE_MODEL_UID).findOne({
1054
+ where: { id: file2.id }
1055
+ });
1056
+ await emitEvent(MEDIA_DELETE, media);
1057
+ return strapi2.db.query(FILE_MODEL_UID).delete({ where: { id: file2.id } });
1058
+ }
1059
+ async function getSettings() {
1060
+ const res = await strapi2.store({ type: "plugin", name: "upload", key: "settings" }).get({});
1061
+ return res;
1062
+ }
1063
+ function setSettings(value) {
1064
+ if (value.responsiveDimensions === true) {
1065
+ strapi2.telemetry.send("didEnableResponsiveDimensions");
1066
+ } else {
1067
+ strapi2.telemetry.send("didDisableResponsiveDimensions");
1068
+ }
1069
+ return strapi2.store({ type: "plugin", name: "upload", key: "settings" }).set({ value });
1070
+ }
1071
+ async function getConfiguration() {
1072
+ const res = await strapi2.store({
1073
+ type: "plugin",
1074
+ name: "upload",
1075
+ key: "view_configuration"
1076
+ }).get({});
1077
+ return res;
1078
+ }
1079
+ function setConfiguration(value) {
1080
+ return strapi2.store({ type: "plugin", name: "upload", key: "view_configuration" }).set({
1081
+ value
1082
+ });
1083
+ }
1084
+ return {
1085
+ formatFileInfo,
1086
+ upload: upload2,
1087
+ updateFileInfo,
1088
+ replace,
1089
+ findOne,
1090
+ findMany,
1091
+ findPage,
1092
+ remove,
1093
+ getSettings,
1094
+ setSettings,
1095
+ getConfiguration,
1096
+ setConfiguration,
1097
+ /**
1098
+ * exposed for testing only
1099
+ * @internal
1100
+ */
1101
+ _uploadImage: uploadImage
1102
+ };
1103
+ };
1104
+ const { bytesToKbytes } = utils.file;
1105
+ const FORMATS_TO_RESIZE = ["jpeg", "png", "webp", "tiff", "gif"];
1106
+ const FORMATS_TO_PROCESS = ["jpeg", "png", "webp", "tiff", "svg", "gif", "avif"];
1107
+ const FORMATS_TO_OPTIMIZE = ["jpeg", "png", "webp", "tiff", "avif"];
1108
+ const isOptimizableFormat = (format) => format !== void 0 && FORMATS_TO_OPTIMIZE.includes(format);
1109
+ const writeStreamToFile = (stream, path2) => new Promise((resolve, reject) => {
1110
+ const writeStream = fs__default.default.createWriteStream(path2);
1111
+ stream.on("error", reject);
1112
+ stream.pipe(writeStream);
1113
+ writeStream.on("close", resolve);
1114
+ writeStream.on("error", reject);
1115
+ });
1116
+ const getMetadata = (file2) => {
1117
+ if (!file2.filepath) {
1118
+ return new Promise((resolve, reject) => {
1119
+ const pipeline = sharp__default.default();
1120
+ pipeline.metadata().then(resolve).catch(reject);
1121
+ file2.getStream().pipe(pipeline);
1122
+ });
1123
+ }
1124
+ return sharp__default.default(file2.filepath).metadata();
1125
+ };
1126
+ const getDimensions = async (file2) => {
1127
+ const { width = null, height = null } = await getMetadata(file2);
1128
+ return { width, height };
1129
+ };
1130
+ const THUMBNAIL_RESIZE_OPTIONS = {
1131
+ width: 245,
1132
+ height: 156,
1133
+ fit: "inside"
1134
+ };
1135
+ const resizeFileTo = async (file2, options, {
1136
+ name,
1137
+ hash
1138
+ }) => {
1139
+ const filePath = file2.tmpWorkingDirectory ? path.join(file2.tmpWorkingDirectory, hash) : hash;
1140
+ let newInfo;
1141
+ if (!file2.filepath) {
1142
+ const transform = sharp__default.default().resize(options).on("info", (info) => {
1143
+ newInfo = info;
1144
+ });
1145
+ await writeStreamToFile(file2.getStream().pipe(transform), filePath);
1146
+ } else {
1147
+ newInfo = await sharp__default.default(file2.filepath).resize(options).toFile(filePath);
1148
+ }
1149
+ const { width, height, size } = newInfo ?? {};
1150
+ const newFile = {
1151
+ name,
1152
+ hash,
1153
+ ext: file2.ext,
1154
+ mime: file2.mime,
1155
+ filepath: filePath,
1156
+ path: file2.path || null,
1157
+ getStream: () => fs__default.default.createReadStream(filePath)
1158
+ };
1159
+ Object.assign(newFile, {
1160
+ width,
1161
+ height,
1162
+ size: size ? bytesToKbytes(size) : 0,
1163
+ sizeInBytes: size
1164
+ });
1165
+ return newFile;
1166
+ };
1167
+ const generateThumbnail = async (file2) => {
1168
+ if (file2.width && file2.height && (file2.width > THUMBNAIL_RESIZE_OPTIONS.width || file2.height > THUMBNAIL_RESIZE_OPTIONS.height)) {
1169
+ return resizeFileTo(file2, THUMBNAIL_RESIZE_OPTIONS, {
1170
+ name: `thumbnail_${file2.name}`,
1171
+ hash: `thumbnail_${file2.hash}`
1172
+ });
1173
+ }
1174
+ return null;
1175
+ };
1176
+ const optimize = async (file2) => {
1177
+ const { sizeOptimization = false, autoOrientation = false } = await getService("upload").getSettings() ?? {};
1178
+ const { format, size } = await getMetadata(file2);
1179
+ if ((sizeOptimization || autoOrientation) && isOptimizableFormat(format)) {
1180
+ let transformer;
1181
+ if (!file2.filepath) {
1182
+ transformer = sharp__default.default();
1183
+ } else {
1184
+ transformer = sharp__default.default(file2.filepath);
1185
+ }
1186
+ transformer[format]({ quality: sizeOptimization ? 80 : 100 });
1187
+ if (autoOrientation) {
1188
+ transformer.rotate();
1189
+ }
1190
+ const filePath = file2.tmpWorkingDirectory ? path.join(file2.tmpWorkingDirectory, `optimized-${file2.hash}`) : `optimized-${file2.hash}`;
1191
+ let newInfo;
1192
+ if (!file2.filepath) {
1193
+ transformer.on("info", (info) => {
1194
+ newInfo = info;
1195
+ });
1196
+ await writeStreamToFile(file2.getStream().pipe(transformer), filePath);
1197
+ } else {
1198
+ newInfo = await transformer.toFile(filePath);
1199
+ }
1200
+ const { width: newWidth, height: newHeight, size: newSize } = newInfo ?? {};
1201
+ const newFile = { ...file2 };
1202
+ newFile.getStream = () => fs__default.default.createReadStream(filePath);
1203
+ newFile.filepath = filePath;
1204
+ if (newSize && size && newSize > size) {
1205
+ return file2;
1206
+ }
1207
+ return Object.assign(newFile, {
1208
+ width: newWidth,
1209
+ height: newHeight,
1210
+ size: newSize ? bytesToKbytes(newSize) : 0,
1211
+ sizeInBytes: newSize
1212
+ });
1213
+ }
1214
+ return file2;
1215
+ };
1216
+ const DEFAULT_BREAKPOINTS = {
1217
+ large: 1e3,
1218
+ medium: 750,
1219
+ small: 500
1220
+ };
1221
+ const getBreakpoints = () => strapi.config.get("plugin::upload.breakpoints", DEFAULT_BREAKPOINTS);
1222
+ const generateResponsiveFormats = async (file2) => {
1223
+ const { responsiveDimensions = false } = await getService("upload").getSettings() ?? {};
1224
+ if (!responsiveDimensions)
1225
+ return [];
1226
+ const originalDimensions = await getDimensions(file2);
1227
+ const breakpoints = getBreakpoints();
1228
+ return Promise.all(
1229
+ Object.keys(breakpoints).map((key) => {
1230
+ const breakpoint = breakpoints[key];
1231
+ if (breakpointSmallerThan(breakpoint, originalDimensions)) {
1232
+ return generateBreakpoint(key, { file: file2, breakpoint });
1233
+ }
1234
+ return void 0;
1235
+ })
1236
+ );
1237
+ };
1238
+ const generateBreakpoint = async (key, { file: file2, breakpoint }) => {
1239
+ const newFile = await resizeFileTo(
1240
+ file2,
1241
+ {
1242
+ width: breakpoint,
1243
+ height: breakpoint,
1244
+ fit: "inside"
1245
+ },
1246
+ {
1247
+ name: `${key}_${file2.name}`,
1248
+ hash: `${key}_${file2.hash}`
1249
+ }
1250
+ );
1251
+ return {
1252
+ key,
1253
+ file: newFile
1254
+ };
1255
+ };
1256
+ const breakpointSmallerThan = (breakpoint, { width, height }) => {
1257
+ return breakpoint < (width ?? 0) || breakpoint < (height ?? 0);
1258
+ };
1259
+ const isFaultyImage = async (file2) => {
1260
+ if (!file2.filepath) {
1261
+ return new Promise((resolve, reject) => {
1262
+ const pipeline = sharp__default.default();
1263
+ pipeline.stats().then(resolve).catch(reject);
1264
+ file2.getStream().pipe(pipeline);
1265
+ });
1266
+ }
1267
+ try {
1268
+ await sharp__default.default(file2.filepath).stats();
1269
+ return false;
1270
+ } catch (e) {
1271
+ return true;
1272
+ }
1273
+ };
1274
+ const isOptimizableImage = async (file2) => {
1275
+ let format;
1276
+ try {
1277
+ const metadata = await getMetadata(file2);
1278
+ format = metadata.format;
1279
+ } catch (e) {
1280
+ return false;
1281
+ }
1282
+ return format && FORMATS_TO_OPTIMIZE.includes(format);
1283
+ };
1284
+ const isResizableImage = async (file2) => {
1285
+ let format;
1286
+ try {
1287
+ const metadata = await getMetadata(file2);
1288
+ format = metadata.format;
1289
+ } catch (e) {
1290
+ return false;
1291
+ }
1292
+ return format && FORMATS_TO_RESIZE.includes(format);
1293
+ };
1294
+ const isImage = async (file2) => {
1295
+ let format;
1296
+ try {
1297
+ const metadata = await getMetadata(file2);
1298
+ format = metadata.format;
1299
+ } catch (e) {
1300
+ return false;
1301
+ }
1302
+ return format && FORMATS_TO_PROCESS.includes(format);
1303
+ };
1304
+ const imageManipulation = {
1305
+ isFaultyImage,
1306
+ isOptimizableImage,
1307
+ isResizableImage,
1308
+ isImage,
1309
+ getDimensions,
1310
+ generateResponsiveFormats,
1311
+ generateThumbnail,
1312
+ optimize
1313
+ };
1314
+ const setPathIdAndPath = async (folder2) => {
1315
+ const { max } = await strapi.db.queryBuilder(FOLDER_MODEL_UID).max("pathId").first().execute();
1316
+ const pathId = max + 1;
1317
+ let parentPath = "/";
1318
+ if (folder2.parent) {
1319
+ const parentFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({ where: { id: folder2.parent } });
1320
+ parentPath = parentFolder.path;
1321
+ }
1322
+ return Object.assign(folder2, {
1323
+ pathId,
1324
+ path: utils.strings.joinBy("/", parentPath, `${pathId}`)
1325
+ });
1326
+ };
1327
+ const create = async (folderData, opts) => {
1328
+ const folderService = getService("folder");
1329
+ const { user } = opts || {};
1330
+ let enrichedFolder = await folderService.setPathIdAndPath(folderData);
1331
+ if (user) {
1332
+ enrichedFolder = await utils.setCreatorFields({ user })(enrichedFolder);
1333
+ }
1334
+ const folder2 = await strapi.db.query(FOLDER_MODEL_UID).create({ data: enrichedFolder });
1335
+ strapi.eventHub.emit("media-folder.create", { folder: folder2 });
1336
+ return folder2;
1337
+ };
1338
+ const deleteByIds$1 = async (ids = []) => {
1339
+ const folders = await strapi.db.query(FOLDER_MODEL_UID).findMany({ where: { id: { $in: ids } } });
1340
+ if (folders.length === 0) {
1341
+ return {
1342
+ folders: [],
1343
+ totalFolderNumber: 0,
1344
+ totalFileNumber: 0
1345
+ };
1346
+ }
1347
+ const pathsToDelete = fp.map("path", folders);
1348
+ const filesToDelete = await strapi.db.query(FILE_MODEL_UID).findMany({
1349
+ where: {
1350
+ $or: pathsToDelete.flatMap((path2) => [
1351
+ { folderPath: { $eq: path2 } },
1352
+ { folderPath: { $startsWith: `${path2}/` } }
1353
+ ])
1354
+ }
1355
+ });
1356
+ await Promise.all(filesToDelete.map((file2) => getService("upload").remove(file2)));
1357
+ const { count: totalFolderNumber } = await strapi.db.query(FOLDER_MODEL_UID).deleteMany({
1358
+ where: {
1359
+ $or: pathsToDelete.flatMap((path2) => [
1360
+ { path: { $eq: path2 } },
1361
+ { path: { $startsWith: `${path2}/` } }
1362
+ ])
1363
+ }
1364
+ });
1365
+ strapi.eventHub.emit("media-folder.delete", { folders });
1366
+ return {
1367
+ folders,
1368
+ totalFolderNumber,
1369
+ totalFileNumber: filesToDelete.length
1370
+ };
1371
+ };
1372
+ const update = async (id, {
1373
+ name,
1374
+ parent
1375
+ }, { user }) => {
1376
+ if (fp.isUndefined(parent)) {
1377
+ const existingFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({ where: { id } });
1378
+ if (!existingFolder) {
1379
+ return void 0;
1380
+ }
1381
+ const newFolder = utils.setCreatorFields({ user, isEdition: true })({ name, parent });
1382
+ if (fp.isUndefined(parent)) {
1383
+ const folder2 = await strapi.db.query(FOLDER_MODEL_UID).update({ where: { id }, data: newFolder });
1384
+ return folder2;
1385
+ }
1386
+ } else {
1387
+ const trx = await strapi.db.transaction();
1388
+ try {
1389
+ const existingFolder = await strapi.db.queryBuilder(FOLDER_MODEL_UID).select(["pathId", "path"]).where({ id }).transacting(trx.get()).forUpdate().first().execute();
1390
+ const { joinTable } = strapi.db.metadata.get(FOLDER_MODEL_UID).attributes.parent;
1391
+ await strapi.db.queryBuilder(joinTable.name).transacting(trx.get()).delete().where({ [joinTable.joinColumn.name]: id }).execute();
1392
+ if (parent !== null) {
1393
+ await strapi.db.queryBuilder(joinTable.name).transacting(trx.get()).insert({ [joinTable.inverseJoinColumn.name]: parent, [joinTable.joinColumn.name]: id }).where({ [joinTable.joinColumn.name]: id }).execute();
1394
+ }
1395
+ let destinationFolderPath = "/";
1396
+ if (parent !== null) {
1397
+ const destinationFolder = await strapi.db.queryBuilder(FOLDER_MODEL_UID).select("path").where({ id: parent }).transacting(trx.get()).first().execute();
1398
+ destinationFolderPath = destinationFolder.path;
1399
+ }
1400
+ const folderTable = strapi.getModel(FOLDER_MODEL_UID).collectionName;
1401
+ const fileTable = strapi.getModel(FILE_MODEL_UID).collectionName;
1402
+ const folderPathColumnName = (
1403
+ // @ts-expect-error - no dynamic types
1404
+ strapi.db.metadata.get(FILE_MODEL_UID).attributes.folderPath.columnName
1405
+ );
1406
+ const pathColumnName = strapi.db.metadata.get(FOLDER_MODEL_UID).attributes.path.columnName;
1407
+ await strapi.db.getConnection(folderTable).transacting(trx.get()).where(pathColumnName, existingFolder.path).orWhere(pathColumnName, "like", `${existingFolder.path}/%`).update(
1408
+ pathColumnName,
1409
+ strapi.db.connection.raw("REPLACE(??, ?, ?)", [
1410
+ pathColumnName,
1411
+ existingFolder.path,
1412
+ utils.strings.joinBy("/", destinationFolderPath, `${existingFolder.pathId}`)
1413
+ ])
1414
+ );
1415
+ await strapi.db.getConnection(fileTable).transacting(trx.get()).where(folderPathColumnName, existingFolder.path).orWhere(folderPathColumnName, "like", `${existingFolder.path}/%`).update(
1416
+ folderPathColumnName,
1417
+ strapi.db.connection.raw("REPLACE(??, ?, ?)", [
1418
+ folderPathColumnName,
1419
+ existingFolder.path,
1420
+ utils.strings.joinBy("/", destinationFolderPath, `${existingFolder.pathId}`)
1421
+ ])
1422
+ );
1423
+ await trx.commit();
1424
+ } catch (e) {
1425
+ await trx.rollback();
1426
+ throw e;
1427
+ }
1428
+ const newFolder = utils.setCreatorFields({ user, isEdition: true })({ name });
1429
+ const folder2 = await strapi.db.query(FOLDER_MODEL_UID).update({ where: { id }, data: newFolder });
1430
+ strapi.eventHub.emit("media-folder.update", { folder: folder2 });
1431
+ return folder2;
1432
+ }
1433
+ };
1434
+ const exists = async (params = {}) => {
1435
+ const count = await strapi.db.query(FOLDER_MODEL_UID).count({ where: params });
1436
+ return count > 0;
1437
+ };
1438
+ const getStructure = async () => {
1439
+ const { joinTable } = strapi.db.metadata.get(FOLDER_MODEL_UID).attributes.parent;
1440
+ const qb = strapi.db.queryBuilder(FOLDER_MODEL_UID);
1441
+ const alias = qb.getAlias();
1442
+ const folders = await qb.select(["id", "name", `${alias}.${joinTable.inverseJoinColumn.name} as parent`]).join({
1443
+ alias,
1444
+ referencedTable: joinTable.name,
1445
+ referencedColumn: joinTable.joinColumn.name,
1446
+ rootColumn: joinTable.joinColumn.referencedColumn,
1447
+ rootTable: qb.alias
1448
+ }).execute({ mapResults: false });
1449
+ const folderMap = {
1450
+ null: { children: [] }
1451
+ };
1452
+ folders.forEach((f) => {
1453
+ folderMap[f.id] = { ...f, children: [] };
1454
+ });
1455
+ folders.forEach((f) => {
1456
+ const parentId = f.parent || "null";
1457
+ if (!folderMap[parentId]) {
1458
+ folderMap[parentId] = { children: [] };
1459
+ }
1460
+ folderMap[parentId].children.push(folderMap[f.id]);
1461
+ folderMap[parentId].children = fp.sortBy("name", folderMap[parentId].children);
1462
+ delete folderMap[f.id].parent;
1463
+ });
1464
+ return folderMap.null.children;
1465
+ };
1466
+ const folder = {
1467
+ create,
1468
+ exists,
1469
+ deleteByIds: deleteByIds$1,
1470
+ update,
1471
+ setPathIdAndPath,
1472
+ getStructure
1473
+ };
1474
+ const getFolderPath = async (folderId) => {
1475
+ if (!folderId)
1476
+ return "/";
1477
+ const parentFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({ where: { id: folderId } });
1478
+ return parentFolder.path;
1479
+ };
1480
+ const deleteByIds = async (ids = []) => {
1481
+ const filesToDelete = await strapi.db.query(FILE_MODEL_UID).findMany({ where: { id: { $in: ids } } });
1482
+ await Promise.all(filesToDelete.map((file2) => getService("upload").remove(file2)));
1483
+ return filesToDelete;
1484
+ };
1485
+ const signFileUrls = async (file2) => {
1486
+ const { provider: provider2 } = strapi.plugins.upload;
1487
+ const { provider: providerConfig } = strapi.config.get("plugin::upload");
1488
+ const isPrivate = await provider2.isPrivate();
1489
+ file2.isUrlSigned = false;
1490
+ if (file2.provider !== providerConfig || !isPrivate) {
1491
+ return file2;
1492
+ }
1493
+ const signUrl = async (file22) => {
1494
+ const signedUrl = await provider2.getSignedUrl(file22);
1495
+ file22.url = signedUrl.url;
1496
+ file22.isUrlSigned = true;
1497
+ };
1498
+ const signedFile = fp.cloneDeep(file2);
1499
+ await signUrl(signedFile);
1500
+ if (file2.formats) {
1501
+ await utils.async.map(Object.values(signedFile.formats ?? {}), signUrl);
1502
+ }
1503
+ return signedFile;
1504
+ };
1505
+ const file = { getFolderPath, deleteByIds, signFileUrls };
1506
+ const getWeeklyCronScheduleAt = (date) => `${date.getSeconds()} ${date.getMinutes()} ${date.getHours()} * * ${date.getDay()}`;
1507
+ const ONE_WEEK = 7 * 24 * 60 * 60 * 1e3;
1508
+ const getMetricsStoreValue = async () => {
1509
+ const value = await strapi.store.get({ type: "plugin", name: "upload", key: "metrics" });
1510
+ return fp.defaultTo({}, value);
1511
+ };
1512
+ const setMetricsStoreValue = (value) => strapi.store.set({ type: "plugin", name: "upload", key: "metrics", value });
1513
+ const weeklyMetrics = ({ strapi: strapi2 }) => ({
1514
+ async computeMetrics() {
1515
+ const pathColName = strapi2.db.metadata.get(FOLDER_MODEL_UID).attributes.path.columnName;
1516
+ const folderTable = strapi2.getModel(FOLDER_MODEL_UID).collectionName;
1517
+ let keepOnlySlashesSQLString = "??";
1518
+ const queryParams = [pathColName];
1519
+ for (let i = 0; i < 10; i += 1) {
1520
+ keepOnlySlashesSQLString = `REPLACE(${keepOnlySlashesSQLString}, ?, ?)`;
1521
+ queryParams.push(String(i), "");
1522
+ }
1523
+ const res = await strapi2.db.getConnection(folderTable).select(
1524
+ strapi2.db.connection.raw(
1525
+ `LENGTH(${keepOnlySlashesSQLString}) AS depth, COUNT(*) AS occurence`,
1526
+ queryParams
1527
+ )
1528
+ ).groupBy("depth");
1529
+ const folderLevelsArray = res.map((map) => ({
1530
+ depth: Number(map.depth),
1531
+ occurence: Number(map.occurence)
1532
+ }));
1533
+ let product = 0;
1534
+ let folderNumber = 0;
1535
+ let maxDepth = 0;
1536
+ for (const folderLevel of folderLevelsArray) {
1537
+ product += folderLevel.depth * folderLevel.occurence;
1538
+ folderNumber += folderLevel.occurence;
1539
+ if (folderLevel.depth > maxDepth) {
1540
+ maxDepth = folderLevel.depth;
1541
+ }
1542
+ }
1543
+ const averageDepth = folderNumber !== 0 ? product / folderNumber : 0;
1544
+ let sumOfDeviation = 0;
1545
+ for (const folderLevel of folderLevelsArray) {
1546
+ sumOfDeviation += Math.abs(folderLevel.depth - averageDepth) * folderLevel.occurence;
1547
+ }
1548
+ const averageDeviationDepth = folderNumber !== 0 ? sumOfDeviation / folderNumber : 0;
1549
+ const assetNumber = await strapi2.db.query(FILE_MODEL_UID).count();
1550
+ return {
1551
+ assetNumber,
1552
+ folderNumber,
1553
+ averageDepth,
1554
+ maxDepth,
1555
+ averageDeviationDepth
1556
+ };
1557
+ },
1558
+ async sendMetrics() {
1559
+ const metrics2 = await this.computeMetrics();
1560
+ strapi2.telemetry.send("didSendUploadPropertiesOnceAWeek", {
1561
+ groupProperties: { metrics: metrics2 }
1562
+ });
1563
+ const metricsInfoStored = await getMetricsStoreValue();
1564
+ await setMetricsStoreValue({ ...metricsInfoStored, lastWeeklyUpdate: (/* @__PURE__ */ new Date()).getTime() });
1565
+ },
1566
+ async ensureWeeklyStoredCronSchedule() {
1567
+ const metricsInfoStored = await getMetricsStoreValue();
1568
+ const { weeklySchedule: currentSchedule, lastWeeklyUpdate } = metricsInfoStored;
1569
+ const now = /* @__PURE__ */ new Date();
1570
+ let weeklySchedule = currentSchedule;
1571
+ if (!weeklySchedule || !lastWeeklyUpdate || lastWeeklyUpdate + ONE_WEEK < now.getTime()) {
1572
+ weeklySchedule = getWeeklyCronScheduleAt(add__default.default(now, { minutes: 5 }));
1573
+ await setMetricsStoreValue({ ...metricsInfoStored, weeklySchedule });
1574
+ return weeklySchedule;
1575
+ }
1576
+ return weeklySchedule;
1577
+ },
1578
+ async registerCron() {
1579
+ const weeklySchedule = await this.ensureWeeklyStoredCronSchedule();
1580
+ strapi2.cron.add({ [weeklySchedule]: this.sendMetrics.bind(this) });
1581
+ }
1582
+ });
1583
+ const getProviderName = () => strapi.config.get("plugin::upload.provider", "local");
1584
+ const isProviderPrivate = async () => strapi.plugin("upload").provider.isPrivate();
1585
+ const metrics = ({ strapi: strapi2 }) => ({
1586
+ async sendUploadPluginMetrics() {
1587
+ const uploadProvider = getProviderName();
1588
+ const privateProvider = await isProviderPrivate();
1589
+ strapi2.telemetry.send("didInitializePluginUpload", {
1590
+ groupProperties: {
1591
+ uploadProvider,
1592
+ privateProvider
1593
+ }
1594
+ });
1595
+ }
1596
+ });
1597
+ const getStore = () => strapi.store({ type: "plugin", name: "upload", key: "api-folder" });
1598
+ const createApiUploadFolder = async () => {
1599
+ let name = API_UPLOAD_FOLDER_BASE_NAME;
1600
+ const folderService = getService("folder");
1601
+ let exists2 = true;
1602
+ let index2 = 1;
1603
+ while (exists2) {
1604
+ exists2 = await folderService.exists({ name, parent: null });
1605
+ if (exists2) {
1606
+ name = `${API_UPLOAD_FOLDER_BASE_NAME} (${index2})`;
1607
+ index2 += 1;
1608
+ }
1609
+ }
1610
+ const folder2 = await folderService.create({ name });
1611
+ await getStore().set({ value: { id: folder2.id } });
1612
+ return folder2;
1613
+ };
1614
+ const getAPIUploadFolder = async () => {
1615
+ const storeValue = await getStore().get({});
1616
+ const folderId = fp.get("id", storeValue);
1617
+ const folder2 = folderId ? await strapi.db.query(FOLDER_MODEL_UID).findOne({ where: { id: folderId } }) : null;
1618
+ return fp.isNil(folder2) ? createApiUploadFolder() : folder2;
1619
+ };
1620
+ const apiUploadFolder = {
1621
+ getAPIUploadFolder
1622
+ };
1623
+ function isFile(value, attribute) {
1624
+ if (!value || attribute.type !== "media") {
1625
+ return false;
1626
+ }
1627
+ return true;
1628
+ }
1629
+ const signEntityMediaVisitor = async ({ key, value, attribute }, { set }) => {
1630
+ const { signFileUrls: signFileUrls2 } = getService("file");
1631
+ if (!attribute) {
1632
+ return;
1633
+ }
1634
+ if (attribute.type !== "media") {
1635
+ return;
1636
+ }
1637
+ if (isFile(value, attribute)) {
1638
+ if (attribute.multiple) {
1639
+ const signedFiles = await utils.async.map(value, signFileUrls2);
1640
+ set(key, signedFiles);
1641
+ return;
1642
+ }
1643
+ const signedFile = await signFileUrls2(value);
1644
+ set(key, signedFile);
1645
+ }
1646
+ };
1647
+ const signEntityMedia = async (entity, uid) => {
1648
+ const model = strapi.getModel(uid);
1649
+ return utils.traverseEntity(
1650
+ // @ts-expect-error - FIXME: fix traverseEntity using wrong types
1651
+ signEntityMediaVisitor,
1652
+ { schema: model, getModel: strapi.getModel.bind(strapi) },
1653
+ entity
1654
+ );
1655
+ };
1656
+ const signFileUrlsOnDocumentService = async () => {
1657
+ const { provider: provider2 } = strapi.plugins.upload;
1658
+ const isPrivate = await provider2.isPrivate();
1659
+ if (!isPrivate) {
1660
+ return;
1661
+ }
1662
+ strapi.documents.use(async (ctx, next) => {
1663
+ const uid = ctx.uid;
1664
+ const result = await next();
1665
+ if (ctx.action === "findMany") {
1666
+ return utils.async.map(result, (entry) => signEntityMedia(entry, uid));
1667
+ }
1668
+ if (ctx.action === "findFirst" || ctx.action === "findOne" || ctx.action === "create" || ctx.action === "update") {
1669
+ return signEntityMedia(result, uid);
1670
+ }
1671
+ if (ctx.action === "delete" || ctx.action === "clone" || ctx.action === "publish" || ctx.action === "unpublish" || ctx.action === "discardDraft") {
1672
+ return {
1673
+ ...result,
1674
+ entries: await utils.async.map(result.entries, (entry) => signEntityMedia(entry, uid))
1675
+ };
1676
+ }
1677
+ return result;
1678
+ });
1679
+ };
1680
+ const extensions = {
1681
+ signFileUrlsOnDocumentService
1682
+ };
1683
+ const services = {
1684
+ provider,
1685
+ upload,
1686
+ folder,
1687
+ file,
1688
+ weeklyMetrics,
1689
+ metrics,
1690
+ "image-manipulation": imageManipulation,
1691
+ "api-upload-folder": apiUploadFolder,
1692
+ extensions
1693
+ };
1694
+ const routes$3 = {
1695
+ type: "admin",
1696
+ routes: [
1697
+ {
1698
+ method: "GET",
1699
+ path: "/settings",
1700
+ handler: "admin-settings.getSettings",
1701
+ config: {
1702
+ policies: [
1703
+ "admin::isAuthenticatedAdmin",
1704
+ {
1705
+ name: "admin::hasPermissions",
1706
+ config: {
1707
+ actions: ["plugin::upload.settings.read"]
1708
+ }
1709
+ }
1710
+ ]
1711
+ }
1712
+ },
1713
+ {
1714
+ method: "PUT",
1715
+ path: "/settings",
1716
+ handler: "admin-settings.updateSettings",
1717
+ config: {
1718
+ policies: [
1719
+ "admin::isAuthenticatedAdmin",
1720
+ {
1721
+ name: "admin::hasPermissions",
1722
+ config: {
1723
+ actions: ["plugin::upload.settings.read"]
1724
+ }
1725
+ }
1726
+ ]
1727
+ }
1728
+ },
1729
+ {
1730
+ method: "POST",
1731
+ path: "/",
1732
+ handler: "admin-upload.upload",
1733
+ config: {
1734
+ policies: ["admin::isAuthenticatedAdmin"]
1735
+ }
1736
+ },
1737
+ {
1738
+ method: "GET",
1739
+ path: "/files",
1740
+ handler: "admin-file.find",
1741
+ config: {
1742
+ policies: [
1743
+ "admin::isAuthenticatedAdmin",
1744
+ {
1745
+ name: "admin::hasPermissions",
1746
+ config: {
1747
+ actions: ["plugin::upload.read"]
1748
+ }
1749
+ }
1750
+ ]
1751
+ }
1752
+ },
1753
+ {
1754
+ method: "GET",
1755
+ path: "/files/:id",
1756
+ handler: "admin-file.findOne",
1757
+ config: {
1758
+ policies: [
1759
+ "admin::isAuthenticatedAdmin",
1760
+ {
1761
+ name: "admin::hasPermissions",
1762
+ config: {
1763
+ actions: ["plugin::upload.read"]
1764
+ }
1765
+ }
1766
+ ]
1767
+ }
1768
+ },
1769
+ {
1770
+ method: "DELETE",
1771
+ path: "/files/:id",
1772
+ handler: "admin-file.destroy",
1773
+ config: {
1774
+ policies: [
1775
+ "admin::isAuthenticatedAdmin",
1776
+ {
1777
+ name: "admin::hasPermissions",
1778
+ config: {
1779
+ actions: ["plugin::upload.assets.update"]
1780
+ }
1781
+ }
1782
+ ]
1783
+ }
1784
+ },
1785
+ {
1786
+ method: "GET",
1787
+ path: "/folders/:id",
1788
+ handler: "admin-folder.findOne",
1789
+ config: {
1790
+ policies: [
1791
+ "admin::isAuthenticatedAdmin",
1792
+ {
1793
+ name: "admin::hasPermissions",
1794
+ config: {
1795
+ actions: ["plugin::upload.read"]
1796
+ }
1797
+ }
1798
+ ]
1799
+ }
1800
+ },
1801
+ {
1802
+ method: "GET",
1803
+ path: "/folders",
1804
+ handler: "admin-folder.find",
1805
+ config: {
1806
+ policies: [
1807
+ "admin::isAuthenticatedAdmin",
1808
+ {
1809
+ name: "admin::hasPermissions",
1810
+ config: {
1811
+ actions: ["plugin::upload.read"]
1812
+ }
1813
+ }
1814
+ ]
1815
+ }
1816
+ },
1817
+ {
1818
+ method: "POST",
1819
+ path: "/folders",
1820
+ handler: "admin-folder.create",
1821
+ config: {
1822
+ policies: [
1823
+ "admin::isAuthenticatedAdmin",
1824
+ {
1825
+ name: "admin::hasPermissions",
1826
+ config: {
1827
+ actions: ["plugin::upload.assets.create"]
1828
+ }
1829
+ }
1830
+ ]
1831
+ }
1832
+ },
1833
+ {
1834
+ method: "PUT",
1835
+ path: "/folders/:id",
1836
+ handler: "admin-folder.update",
1837
+ config: {
1838
+ policies: [
1839
+ "admin::isAuthenticatedAdmin",
1840
+ {
1841
+ name: "admin::hasPermissions",
1842
+ config: {
1843
+ actions: ["plugin::upload.assets.update"]
1844
+ }
1845
+ }
1846
+ ]
1847
+ }
1848
+ },
1849
+ {
1850
+ method: "GET",
1851
+ path: "/folder-structure",
1852
+ handler: "admin-folder.getStructure",
1853
+ config: {
1854
+ policies: [
1855
+ "admin::isAuthenticatedAdmin",
1856
+ {
1857
+ name: "admin::hasPermissions",
1858
+ config: {
1859
+ actions: ["plugin::upload.read"]
1860
+ }
1861
+ }
1862
+ ]
1863
+ }
1864
+ },
1865
+ {
1866
+ method: "POST",
1867
+ path: "/actions/bulk-delete",
1868
+ handler: "admin-folder-file.deleteMany",
1869
+ config: {
1870
+ policies: [
1871
+ "admin::isAuthenticatedAdmin",
1872
+ {
1873
+ name: "admin::hasPermissions",
1874
+ config: {
1875
+ actions: ["plugin::upload.assets.update"]
1876
+ }
1877
+ }
1878
+ ]
1879
+ }
1880
+ },
1881
+ {
1882
+ method: "POST",
1883
+ path: "/actions/bulk-move",
1884
+ handler: "admin-folder-file.moveMany",
1885
+ config: {
1886
+ policies: [
1887
+ "admin::isAuthenticatedAdmin",
1888
+ {
1889
+ name: "admin::hasPermissions",
1890
+ config: {
1891
+ actions: ["plugin::upload.assets.update"]
1892
+ }
1893
+ }
1894
+ ]
1895
+ }
1896
+ }
1897
+ ]
1898
+ };
1899
+ const routes$2 = {
1900
+ type: "content-api",
1901
+ routes: [
1902
+ {
1903
+ method: "POST",
1904
+ path: "/",
1905
+ handler: "content-api.upload"
1906
+ },
1907
+ {
1908
+ method: "GET",
1909
+ path: "/files",
1910
+ handler: "content-api.find"
1911
+ },
1912
+ {
1913
+ method: "GET",
1914
+ path: "/files/:id",
1915
+ handler: "content-api.findOne"
1916
+ },
1917
+ {
1918
+ method: "DELETE",
1919
+ path: "/files/:id",
1920
+ handler: "content-api.destroy"
1921
+ }
1922
+ ]
1923
+ };
1924
+ const routes$1 = {
1925
+ type: "admin",
1926
+ routes: [
1927
+ {
1928
+ method: "GET",
1929
+ path: "/configuration",
1930
+ handler: "view-configuration.findViewConfiguration",
1931
+ config: {
1932
+ policies: ["admin::isAuthenticatedAdmin"]
1933
+ }
1934
+ },
1935
+ {
1936
+ method: "PUT",
1937
+ path: "/configuration",
1938
+ handler: "view-configuration.updateViewConfiguration",
1939
+ config: {
1940
+ policies: [
1941
+ "admin::isAuthenticatedAdmin",
1942
+ {
1943
+ name: "admin::hasPermissions",
1944
+ config: {
1945
+ actions: [ACTIONS.configureView]
1946
+ }
1947
+ }
1948
+ ]
1949
+ }
1950
+ }
1951
+ ]
1952
+ };
1953
+ const routes = {
1954
+ admin: routes$3,
1955
+ "content-api": routes$2,
1956
+ viewConfiguration: routes$1
1957
+ };
1958
+ const config = {
1959
+ default: {
1960
+ enabled: true,
1961
+ provider: "local",
1962
+ sizeLimit: 1e9,
1963
+ // 1GB
1964
+ actionOptions: {}
1965
+ },
1966
+ validator() {
1967
+ }
1968
+ };
1969
+ const findEntityAndCheckPermissions = async (ability, action, model, id) => {
1970
+ const file2 = await getService("upload").findOne(id, [
1971
+ utils.contentTypes.constants.CREATED_BY_ATTRIBUTE,
1972
+ "folder"
1973
+ ]);
1974
+ if (___default.default.isNil(file2)) {
1975
+ throw new utils.errors.NotFoundError();
1976
+ }
1977
+ const pm = strapi.service("admin::permission").createPermissionsManager({ ability, action, model });
1978
+ const creatorId = ___default.default.get(file2, [utils.contentTypes.constants.CREATED_BY_ATTRIBUTE, "id"]);
1979
+ const author = creatorId ? await strapi.service("admin::user").findOne(creatorId, ["roles"]) : null;
1980
+ const fileWithRoles = ___default.default.set(___default.default.cloneDeep(file2), "createdBy", author);
1981
+ if (pm.ability.cannot(pm.action, pm.toSubject(fileWithRoles))) {
1982
+ throw new utils.errors.ForbiddenError();
1983
+ }
1984
+ return { pm, file: file2 };
1985
+ };
1986
+ const adminFile = {
1987
+ async find(ctx) {
1988
+ const {
1989
+ state: { userAbility }
1990
+ } = ctx;
1991
+ const defaultQuery = { populate: { folder: true } };
1992
+ const pm = strapi.service("admin::permission").createPermissionsManager({
1993
+ ability: userAbility,
1994
+ action: ACTIONS.read,
1995
+ model: FILE_MODEL_UID
1996
+ });
1997
+ if (!pm.isAllowed) {
1998
+ return ctx.forbidden();
1999
+ }
2000
+ await pm.validateQuery(ctx.query);
2001
+ const query = await utils.async.pipe(
2002
+ // Start by sanitizing the incoming query
2003
+ (q) => pm.sanitizeQuery(q),
2004
+ // Add the default query which should not be validated or sanitized
2005
+ (q) => fp.merge(defaultQuery, q),
2006
+ // Add the dynamic filters based on permissions' conditions
2007
+ (q) => pm.addPermissionsQueryTo(q)
2008
+ )(ctx.query);
2009
+ const { results: files, pagination } = await getService("upload").findPage(query);
2010
+ const signedFiles = await utils.async.map(files, getService("file").signFileUrls);
2011
+ const sanitizedFiles = await pm.sanitizeOutput(signedFiles);
2012
+ return { results: sanitizedFiles, pagination };
2013
+ },
2014
+ async findOne(ctx) {
2015
+ const {
2016
+ state: { userAbility },
2017
+ params: { id }
2018
+ } = ctx;
2019
+ const { pm, file: file2 } = await findEntityAndCheckPermissions(
2020
+ userAbility,
2021
+ ACTIONS.read,
2022
+ FILE_MODEL_UID,
2023
+ id
2024
+ );
2025
+ const signedFile = await getService("file").signFileUrls(file2);
2026
+ ctx.body = await pm.sanitizeOutput(signedFile);
2027
+ },
2028
+ async destroy(ctx) {
2029
+ const { id } = ctx.params;
2030
+ const { userAbility } = ctx.state;
2031
+ const { pm, file: file2 } = await findEntityAndCheckPermissions(
2032
+ userAbility,
2033
+ ACTIONS.update,
2034
+ FILE_MODEL_UID,
2035
+ id
2036
+ );
2037
+ const [body] = await Promise.all([
2038
+ pm.sanitizeOutput(file2, { action: ACTIONS.read }),
2039
+ getService("upload").remove(file2)
2040
+ ]);
2041
+ ctx.body = body;
2042
+ }
2043
+ };
2044
+ const folderExists = async (folderId) => {
2045
+ if (fp.isNil(folderId)) {
2046
+ return true;
2047
+ }
2048
+ const exists2 = await getService("folder").exists({ id: folderId });
2049
+ return exists2;
2050
+ };
2051
+ const isFolderOrChild = (folderOrChild, folder2) => folderOrChild.path === folder2.path || folderOrChild.path.startsWith(`${folder2.path}/`);
2052
+ const NO_SLASH_REGEX = /^[^/]+$/;
2053
+ const NO_SPACES_AROUND = /^(?! ).+(?<! )$/;
2054
+ const isNameUniqueInFolder = (id) => {
2055
+ return async function test(name) {
2056
+ const { exists: exists2 } = getService("folder");
2057
+ const filters = { name, parent: this.parent.parent || null };
2058
+ if (id) {
2059
+ filters.id = { $ne: id };
2060
+ if (fp.isUndefined(name)) {
2061
+ const existingFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({ where: { id } });
2062
+ filters.name = fp.get("name", existingFolder);
2063
+ }
2064
+ }
2065
+ const doesExist = await exists2(filters);
2066
+ return !doesExist;
2067
+ };
2068
+ };
2069
+ const validateCreateFolderSchema = utils.yup.object().shape({
2070
+ name: utils.yup.string().min(1).matches(NO_SLASH_REGEX, "name cannot contain slashes").matches(NO_SPACES_AROUND, "name cannot start or end with a whitespace").required().test("is-folder-unique", "A folder with this name already exists", isNameUniqueInFolder()),
2071
+ parent: utils.yup.strapiID().nullable().test("folder-exists", "parent folder does not exist", folderExists)
2072
+ }).noUnknown().required();
2073
+ const validateUpdateFolderSchema = (id) => utils.yup.object().shape({
2074
+ name: utils.yup.string().min(1).matches(NO_SLASH_REGEX, "name cannot contain slashes").matches(NO_SPACES_AROUND, "name cannot start or end with a whitespace").test(
2075
+ "is-folder-unique",
2076
+ "A folder with this name already exists",
2077
+ isNameUniqueInFolder(id)
2078
+ ),
2079
+ parent: utils.yup.strapiID().nullable().test("folder-exists", "parent folder does not exist", folderExists).test(
2080
+ "dont-move-inside-self",
2081
+ "folder cannot be moved inside itself",
2082
+ async function test(parent) {
2083
+ if (fp.isNil(parent))
2084
+ return true;
2085
+ const destinationFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({
2086
+ select: ["path"],
2087
+ where: { id: parent }
2088
+ });
2089
+ const currentFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({
2090
+ select: ["path"],
2091
+ where: { id }
2092
+ });
2093
+ if (!destinationFolder || !currentFolder)
2094
+ return true;
2095
+ return !isFolderOrChild(destinationFolder, currentFolder);
2096
+ }
2097
+ )
2098
+ }).noUnknown().required();
2099
+ const validateCreateFolder = utils.validateYupSchema(validateCreateFolderSchema);
2100
+ const validateUpdateFolder = (id) => utils.validateYupSchema(validateUpdateFolderSchema(id));
2101
+ const adminFolder = {
2102
+ async findOne(ctx) {
2103
+ const { id } = ctx.params;
2104
+ const permissionsManager = strapi.service("admin::permission").createPermissionsManager({
2105
+ ability: ctx.state.userAbility,
2106
+ model: FOLDER_MODEL_UID
2107
+ });
2108
+ await permissionsManager.validateQuery(ctx.query);
2109
+ const query = await permissionsManager.sanitizeQuery(ctx.query);
2110
+ const { results } = await strapi.db.query(FOLDER_MODEL_UID).findPage(
2111
+ strapi.get("query-params").transform(
2112
+ FOLDER_MODEL_UID,
2113
+ fp.defaultsDeep(
2114
+ {
2115
+ filters: { id },
2116
+ populate: {
2117
+ children: {
2118
+ count: true
2119
+ },
2120
+ files: {
2121
+ count: true
2122
+ }
2123
+ }
2124
+ },
2125
+ query
2126
+ )
2127
+ )
2128
+ );
2129
+ if (results.length === 0) {
2130
+ return ctx.notFound("folder not found");
2131
+ }
2132
+ ctx.body = {
2133
+ data: await permissionsManager.sanitizeOutput(results[0])
2134
+ };
2135
+ },
2136
+ async find(ctx) {
2137
+ const permissionsManager = strapi.service("admin::permission").createPermissionsManager({
2138
+ ability: ctx.state.userAbility,
2139
+ model: FOLDER_MODEL_UID
2140
+ });
2141
+ await permissionsManager.validateQuery(ctx.query);
2142
+ const query = await permissionsManager.sanitizeQuery(ctx.query);
2143
+ const results = await strapi.db.query(FOLDER_MODEL_UID).findMany(
2144
+ strapi.get("query-params").transform(
2145
+ FOLDER_MODEL_UID,
2146
+ fp.defaultsDeep(
2147
+ {
2148
+ populate: {
2149
+ children: {
2150
+ count: true
2151
+ },
2152
+ files: {
2153
+ count: true
2154
+ }
2155
+ }
2156
+ },
2157
+ query
2158
+ )
2159
+ )
2160
+ );
2161
+ ctx.body = {
2162
+ data: await permissionsManager.sanitizeOutput(results)
2163
+ };
2164
+ },
2165
+ async create(ctx) {
2166
+ const { user } = ctx.state;
2167
+ const { body } = ctx.request;
2168
+ await validateCreateFolder(body);
2169
+ const folderService = getService("folder");
2170
+ const folder2 = await folderService.create(body, { user });
2171
+ const permissionsManager = strapi.service("admin::permission").createPermissionsManager({
2172
+ ability: ctx.state.userAbility,
2173
+ model: FOLDER_MODEL_UID
2174
+ });
2175
+ ctx.created({
2176
+ data: await permissionsManager.sanitizeOutput(folder2)
2177
+ });
2178
+ },
2179
+ async update(ctx) {
2180
+ const { id } = ctx.params;
2181
+ const { user } = ctx.state;
2182
+ const { body } = ctx.request;
2183
+ const permissionsManager = strapi.service("admin::permission").createPermissionsManager({
2184
+ ability: ctx.state.userAbility,
2185
+ model: FOLDER_MODEL_UID
2186
+ });
2187
+ await validateUpdateFolder(id)(body);
2188
+ const folderService = getService("folder");
2189
+ const updatedFolder = await folderService.update(id, body, { user });
2190
+ if (!updatedFolder) {
2191
+ return ctx.notFound("folder not found");
2192
+ }
2193
+ ctx.body = {
2194
+ data: await permissionsManager.sanitizeOutput(updatedFolder)
2195
+ };
2196
+ },
2197
+ async getStructure(ctx) {
2198
+ const { getStructure: getStructure2 } = getService("folder");
2199
+ const structure = await getStructure2();
2200
+ ctx.body = {
2201
+ data: structure
2202
+ };
2203
+ }
2204
+ };
2205
+ const validateDeleteManyFoldersFilesSchema = utils.yup.object().shape({
2206
+ fileIds: utils.yup.array().of(utils.yup.strapiID().required()),
2207
+ folderIds: utils.yup.array().of(utils.yup.strapiID().required())
2208
+ }).noUnknown().required();
2209
+ const validateStructureMoveManyFoldersFilesSchema = utils.yup.object().shape({
2210
+ destinationFolderId: utils.yup.strapiID().nullable().defined().test("folder-exists", "destination folder does not exist", folderExists),
2211
+ fileIds: utils.yup.array().of(utils.yup.strapiID().required()),
2212
+ folderIds: utils.yup.array().of(utils.yup.strapiID().required())
2213
+ }).noUnknown().required();
2214
+ const validateDuplicatesMoveManyFoldersFilesSchema = utils.yup.object().test("are-folders-unique", "some folders already exist", async function(value) {
2215
+ const { folderIds, destinationFolderId } = value;
2216
+ if (fp.isEmpty(folderIds))
2217
+ return true;
2218
+ const folders = await strapi.db.query(FOLDER_MODEL_UID).findMany({
2219
+ select: ["name"],
2220
+ where: { id: { $in: folderIds } }
2221
+ });
2222
+ const existingFolders = await strapi.db.query(FOLDER_MODEL_UID).findMany({
2223
+ select: ["name"],
2224
+ where: { parent: { id: destinationFolderId } }
2225
+ });
2226
+ const duplicatedNames = fp.intersection(fp.map("name", folders), fp.map("name", existingFolders));
2227
+ if (duplicatedNames.length > 0) {
2228
+ return this.createError({
2229
+ message: `some folders already exists: ${duplicatedNames.join(", ")}`
2230
+ });
2231
+ }
2232
+ return true;
2233
+ });
2234
+ const validateMoveFoldersNotInsideThemselvesSchema = utils.yup.object().test(
2235
+ "dont-move-inside-self",
2236
+ "folders cannot be moved inside themselves or one of its children",
2237
+ async function(value) {
2238
+ const { folderIds, destinationFolderId } = value;
2239
+ if (destinationFolderId === null || fp.isEmpty(folderIds))
2240
+ return true;
2241
+ const destinationFolder = await strapi.db.query(FOLDER_MODEL_UID).findOne({
2242
+ select: ["path"],
2243
+ where: { id: destinationFolderId }
2244
+ });
2245
+ const folders = await strapi.db.query(FOLDER_MODEL_UID).findMany({
2246
+ select: ["name", "path"],
2247
+ where: { id: { $in: folderIds } }
2248
+ });
2249
+ const unmovableFoldersNames = folders.filter((folder2) => isFolderOrChild(destinationFolder, folder2)).map((f) => f.name);
2250
+ if (unmovableFoldersNames.length > 0) {
2251
+ return this.createError({
2252
+ message: `folders cannot be moved inside themselves or one of its children: ${unmovableFoldersNames.join(
2253
+ ", "
2254
+ )}`
2255
+ });
2256
+ }
2257
+ return true;
2258
+ }
2259
+ );
2260
+ const validateDeleteManyFoldersFiles = utils.validateYupSchema(
2261
+ validateDeleteManyFoldersFilesSchema
2262
+ );
2263
+ async function validateMoveManyFoldersFiles(body) {
2264
+ await utils.validateYupSchema(validateStructureMoveManyFoldersFilesSchema)(body);
2265
+ await utils.validateYupSchema(validateDuplicatesMoveManyFoldersFilesSchema)(body);
2266
+ await utils.validateYupSchema(validateMoveFoldersNotInsideThemselvesSchema)(body);
2267
+ }
2268
+ const adminFolderFile = {
2269
+ async deleteMany(ctx) {
2270
+ const { body } = ctx.request;
2271
+ const {
2272
+ state: { userAbility }
2273
+ } = ctx;
2274
+ const pmFolder = strapi.service("admin::permission").createPermissionsManager({
2275
+ ability: ctx.state.userAbility,
2276
+ model: FOLDER_MODEL_UID
2277
+ });
2278
+ const pmFile = strapi.service("admin::permission").createPermissionsManager({
2279
+ ability: userAbility,
2280
+ action: ACTIONS.read,
2281
+ model: FILE_MODEL_UID
2282
+ });
2283
+ await validateDeleteManyFoldersFiles(body);
2284
+ const fileService = getService("file");
2285
+ const folderService = getService("folder");
2286
+ const deletedFiles = await fileService.deleteByIds(body.fileIds);
2287
+ const {
2288
+ folders: deletedFolders,
2289
+ totalFolderNumber,
2290
+ totalFileNumber
2291
+ } = await folderService.deleteByIds(body.folderIds);
2292
+ if (deletedFiles.length + deletedFolders.length > 1) {
2293
+ strapi.telemetry.send("didBulkDeleteMediaLibraryElements", {
2294
+ eventProperties: {
2295
+ rootFolderNumber: deletedFolders.length,
2296
+ rootAssetNumber: deletedFiles.length,
2297
+ totalFolderNumber,
2298
+ totalAssetNumber: totalFileNumber + deletedFiles.length
2299
+ }
2300
+ });
2301
+ }
2302
+ ctx.body = {
2303
+ data: {
2304
+ files: await pmFile.sanitizeOutput(deletedFiles),
2305
+ folders: await pmFolder.sanitizeOutput(deletedFolders)
2306
+ }
2307
+ };
2308
+ },
2309
+ async moveMany(ctx) {
2310
+ const { body } = ctx.request;
2311
+ const {
2312
+ state: { userAbility }
2313
+ } = ctx;
2314
+ const pmFolder = strapi.service("admin::permission").createPermissionsManager({
2315
+ ability: ctx.state.userAbility,
2316
+ model: FOLDER_MODEL_UID
2317
+ });
2318
+ const pmFile = strapi.service("admin::permission").createPermissionsManager({
2319
+ ability: userAbility,
2320
+ action: ACTIONS.read,
2321
+ model: FILE_MODEL_UID
2322
+ });
2323
+ await validateMoveManyFoldersFiles(body);
2324
+ const { folderIds = [], fileIds = [], destinationFolderId } = body;
2325
+ let totalFolderNumber = 0;
2326
+ let totalFileNumber = 0;
2327
+ const trx = await strapi.db.transaction();
2328
+ try {
2329
+ const existingFolders = await strapi.db.queryBuilder(FOLDER_MODEL_UID).select(["id", "pathId", "path"]).where({ id: { $in: folderIds } }).transacting(trx.get()).forUpdate().execute();
2330
+ const existingFiles = await strapi.db.queryBuilder(FILE_MODEL_UID).select(["id"]).where({ id: { $in: fileIds } }).transacting(trx.get()).forUpdate().execute();
2331
+ let destinationFolderPath = "/";
2332
+ if (destinationFolderId !== null) {
2333
+ const destinationFolder = await strapi.db.queryBuilder(FOLDER_MODEL_UID).select("path").where({ id: destinationFolderId }).transacting(trx.get()).first().execute();
2334
+ destinationFolderPath = destinationFolder.path;
2335
+ }
2336
+ const fileTable = strapi.getModel(FILE_MODEL_UID).collectionName;
2337
+ const folderTable = strapi.getModel(FOLDER_MODEL_UID).collectionName;
2338
+ const folderPathColName = (
2339
+ // @ts-expect-error - no dynamic typings for the models
2340
+ strapi.db.metadata.get(FILE_MODEL_UID).attributes.folderPath.columnName
2341
+ );
2342
+ const pathColName = strapi.db.metadata.get(FOLDER_MODEL_UID).attributes.path.columnName;
2343
+ if (existingFolders.length > 0) {
2344
+ const { joinTable } = strapi.db.metadata.get(FOLDER_MODEL_UID).attributes.parent;
2345
+ await strapi.db.queryBuilder(joinTable.name).transacting(trx.get()).delete().where({ [joinTable.joinColumn.name]: { $in: folderIds } }).execute();
2346
+ if (destinationFolderId !== null) {
2347
+ await strapi.db.queryBuilder(joinTable.name).transacting(trx.get()).insert(
2348
+ existingFolders.map((folder2) => ({
2349
+ [joinTable.inverseJoinColumn.name]: destinationFolderId,
2350
+ [joinTable.joinColumn.name]: folder2.id
2351
+ }))
2352
+ ).execute();
2353
+ }
2354
+ for (const existingFolder of existingFolders) {
2355
+ let replaceQuery;
2356
+ switch (strapi.db.dialect.client) {
2357
+ case "sqlite":
2358
+ replaceQuery = "? || SUBSTRING(??, ?)";
2359
+ break;
2360
+ case "postgres":
2361
+ replaceQuery = "CONCAT(?::TEXT, SUBSTRING(??, ?::INTEGER))";
2362
+ break;
2363
+ default:
2364
+ replaceQuery = "CONCAT(?, SUBSTRING(??, ?))";
2365
+ }
2366
+ totalFolderNumber = await strapi.db.getConnection(folderTable).transacting(trx.get()).where(pathColName, existingFolder.path).orWhere(pathColName, "like", `${existingFolder.path}/%`).update(
2367
+ pathColName,
2368
+ strapi.db.connection.raw(replaceQuery, [
2369
+ utils.strings.joinBy("/", destinationFolderPath, `${existingFolder.pathId}`),
2370
+ pathColName,
2371
+ existingFolder.path.length + 1
2372
+ ])
2373
+ );
2374
+ totalFileNumber = await strapi.db.getConnection(fileTable).transacting(trx.get()).where(folderPathColName, existingFolder.path).orWhere(folderPathColName, "like", `${existingFolder.path}/%`).update(
2375
+ folderPathColName,
2376
+ strapi.db.connection.raw(replaceQuery, [
2377
+ utils.strings.joinBy("/", destinationFolderPath, `${existingFolder.pathId}`),
2378
+ folderPathColName,
2379
+ existingFolder.path.length + 1
2380
+ ])
2381
+ );
2382
+ }
2383
+ }
2384
+ if (existingFiles.length > 0) {
2385
+ const fileJoinTable = strapi.db.metadata.get(FILE_MODEL_UID).attributes.folder.joinTable;
2386
+ await strapi.db.queryBuilder(fileJoinTable.name).transacting(trx.get()).delete().where({ [fileJoinTable.joinColumn.name]: { $in: fileIds } }).execute();
2387
+ if (destinationFolderId !== null) {
2388
+ await strapi.db.queryBuilder(fileJoinTable.name).transacting(trx.get()).insert(
2389
+ existingFiles.map((file2) => ({
2390
+ [fileJoinTable.inverseJoinColumn.name]: destinationFolderId,
2391
+ [fileJoinTable.joinColumn.name]: file2.id
2392
+ }))
2393
+ ).execute();
2394
+ }
2395
+ await strapi.db.getConnection(fileTable).transacting(trx.get()).whereIn("id", fileIds).update(folderPathColName, destinationFolderPath);
2396
+ }
2397
+ await trx.commit();
2398
+ } catch (e) {
2399
+ await trx.rollback();
2400
+ throw e;
2401
+ }
2402
+ const updatedFolders = await strapi.db.query(FOLDER_MODEL_UID).findMany({
2403
+ where: { id: { $in: folderIds } }
2404
+ });
2405
+ const updatedFiles = await strapi.db.query(FILE_MODEL_UID).findMany({
2406
+ where: { id: { $in: fileIds } }
2407
+ });
2408
+ strapi.telemetry.send("didBulkMoveMediaLibraryElements", {
2409
+ eventProperties: {
2410
+ rootFolderNumber: updatedFolders.length,
2411
+ rootAssetNumber: updatedFiles.length,
2412
+ totalFolderNumber,
2413
+ totalAssetNumber: totalFileNumber + updatedFiles.length
2414
+ }
2415
+ });
2416
+ ctx.body = {
2417
+ data: {
2418
+ files: await pmFile.sanitizeOutput(updatedFiles),
2419
+ folders: await pmFolder.sanitizeOutput(updatedFolders)
2420
+ }
2421
+ };
2422
+ }
2423
+ };
2424
+ const settingsSchema = utils.yup.object({
2425
+ sizeOptimization: utils.yup.boolean().required(),
2426
+ responsiveDimensions: utils.yup.boolean().required(),
2427
+ autoOrientation: utils.yup.boolean()
2428
+ });
2429
+ const validateSettings = utils.validateYupSchema(settingsSchema);
2430
+ const adminSettings = {
2431
+ async updateSettings(ctx) {
2432
+ const {
2433
+ request: { body },
2434
+ state: { userAbility }
2435
+ } = ctx;
2436
+ if (userAbility.cannot(ACTIONS.readSettings, FILE_MODEL_UID)) {
2437
+ return ctx.forbidden();
2438
+ }
2439
+ const data = await validateSettings(body);
2440
+ await getService("upload").setSettings(data);
2441
+ ctx.body = { data };
2442
+ },
2443
+ async getSettings(ctx) {
2444
+ const {
2445
+ state: { userAbility }
2446
+ } = ctx;
2447
+ if (userAbility.cannot(ACTIONS.readSettings, FILE_MODEL_UID)) {
2448
+ return ctx.forbidden();
2449
+ }
2450
+ const data = await getService("upload").getSettings();
2451
+ ctx.body = { data };
2452
+ }
2453
+ };
2454
+ const fileInfoSchema$1 = utils.yup.object({
2455
+ name: utils.yup.string().nullable(),
2456
+ alternativeText: utils.yup.string().nullable(),
2457
+ caption: utils.yup.string().nullable(),
2458
+ folder: utils.yup.strapiID().nullable().test("folder-exists", "the folder does not exist", async (folderId) => {
2459
+ if (fp.isNil(folderId)) {
2460
+ return true;
2461
+ }
2462
+ const exists2 = await getService("folder").exists({ id: folderId });
2463
+ return exists2;
2464
+ })
2465
+ });
2466
+ const uploadSchema$1 = utils.yup.object({
2467
+ fileInfo: fileInfoSchema$1
2468
+ });
2469
+ const multiUploadSchema$1 = utils.yup.object({
2470
+ fileInfo: utils.yup.array().of(fileInfoSchema$1)
2471
+ });
2472
+ const validateUploadBody$1 = (data = {}, isMulti = false) => {
2473
+ const schema = isMulti ? multiUploadSchema$1 : uploadSchema$1;
2474
+ return utils.validateYupSchema(schema, { strict: false })(data);
2475
+ };
2476
+ const adminUpload = {
2477
+ async updateFileInfo(ctx) {
2478
+ const {
2479
+ state: { userAbility, user },
2480
+ query: { id },
2481
+ request: { body }
2482
+ } = ctx;
2483
+ if (typeof id !== "string") {
2484
+ throw new utils.errors.ValidationError("File id is required");
2485
+ }
2486
+ const uploadService = getService("upload");
2487
+ const { pm } = await findEntityAndCheckPermissions(
2488
+ userAbility,
2489
+ ACTIONS.update,
2490
+ FILE_MODEL_UID,
2491
+ id
2492
+ );
2493
+ const data = await validateUploadBody$1(body);
2494
+ const file2 = await uploadService.updateFileInfo(id, data.fileInfo, { user });
2495
+ ctx.body = await pm.sanitizeOutput(file2, { action: ACTIONS.read });
2496
+ },
2497
+ async replaceFile(ctx) {
2498
+ const {
2499
+ state: { userAbility, user },
2500
+ query: { id },
2501
+ request: { body, files: { files } = {} }
2502
+ } = ctx;
2503
+ if (typeof id !== "string") {
2504
+ throw new utils.errors.ValidationError("File id is required");
2505
+ }
2506
+ const uploadService = getService("upload");
2507
+ const { pm } = await findEntityAndCheckPermissions(
2508
+ userAbility,
2509
+ ACTIONS.update,
2510
+ FILE_MODEL_UID,
2511
+ id
2512
+ );
2513
+ if (Array.isArray(files)) {
2514
+ throw new utils.errors.ApplicationError("Cannot replace a file with multiple ones");
2515
+ }
2516
+ const data = await validateUploadBody$1(body);
2517
+ const replacedFile = await uploadService.replace(id, { data, file: files }, { user });
2518
+ const signedFile = await getService("file").signFileUrls(replacedFile);
2519
+ ctx.body = await pm.sanitizeOutput(signedFile, { action: ACTIONS.read });
2520
+ },
2521
+ async uploadFiles(ctx) {
2522
+ const {
2523
+ state: { userAbility, user },
2524
+ request: { body, files: { files } = {} }
2525
+ } = ctx;
2526
+ const uploadService = getService("upload");
2527
+ const pm = strapi.service("admin::permission").createPermissionsManager({
2528
+ ability: userAbility,
2529
+ action: ACTIONS.create,
2530
+ model: FILE_MODEL_UID
2531
+ });
2532
+ if (!pm.isAllowed) {
2533
+ return ctx.forbidden();
2534
+ }
2535
+ const data = await validateUploadBody$1(body);
2536
+ const uploadedFiles = await uploadService.upload({ data, files }, { user });
2537
+ const signedFiles = await utils.async.map(uploadedFiles, getService("file").signFileUrls);
2538
+ ctx.body = await pm.sanitizeOutput(signedFiles, { action: ACTIONS.read });
2539
+ ctx.status = 201;
2540
+ },
2541
+ // TODO: split into multiple endpoints
2542
+ async upload(ctx) {
2543
+ const {
2544
+ query: { id },
2545
+ request: { files: { files } = {} }
2546
+ } = ctx;
2547
+ if (___default.default.isEmpty(files) || !Array.isArray(files) && files.size === 0) {
2548
+ if (id) {
2549
+ return this.updateFileInfo(ctx);
2550
+ }
2551
+ throw new utils.errors.ApplicationError("Files are empty");
2552
+ }
2553
+ await (id ? this.replaceFile : this.uploadFiles)(ctx);
2554
+ }
2555
+ };
2556
+ const fileInfoSchema = utils.yup.object({
2557
+ name: utils.yup.string().nullable(),
2558
+ alternativeText: utils.yup.string().nullable(),
2559
+ caption: utils.yup.string().nullable()
2560
+ }).noUnknown();
2561
+ const uploadSchema = utils.yup.object({
2562
+ fileInfo: fileInfoSchema
2563
+ });
2564
+ const multiUploadSchema = utils.yup.object({
2565
+ fileInfo: utils.yup.array().of(fileInfoSchema)
2566
+ });
2567
+ const validateUploadBody = (data = {}, isMulti = false) => {
2568
+ const schema = isMulti ? multiUploadSchema : uploadSchema;
2569
+ return utils.validateYupSchema(schema, { strict: false })(data);
2570
+ };
2571
+ const { ValidationError } = utils__default.default.errors;
2572
+ const contentApi = ({ strapi: strapi2 }) => {
2573
+ const sanitizeOutput = async (data, ctx) => {
2574
+ const schema = strapi2.getModel(FILE_MODEL_UID);
2575
+ const { auth } = ctx.state;
2576
+ return strapi2.contentAPI.sanitize.output(data, schema, { auth });
2577
+ };
2578
+ const validateQuery = async (data, ctx) => {
2579
+ const schema = strapi2.getModel(FILE_MODEL_UID);
2580
+ const { auth } = ctx.state;
2581
+ return strapi2.contentAPI.validate.query(data, schema, { auth });
2582
+ };
2583
+ const sanitizeQuery = async (data, ctx) => {
2584
+ const schema = strapi2.getModel(FILE_MODEL_UID);
2585
+ const { auth } = ctx.state;
2586
+ return strapi2.contentAPI.sanitize.query(data, schema, { auth });
2587
+ };
2588
+ return {
2589
+ async find(ctx) {
2590
+ await validateQuery(ctx.query, ctx);
2591
+ const sanitizedQuery = await sanitizeQuery(ctx.query, ctx);
2592
+ const files = await getService("upload").findMany(sanitizedQuery);
2593
+ ctx.body = await sanitizeOutput(files, ctx);
2594
+ },
2595
+ async findOne(ctx) {
2596
+ const {
2597
+ params: { id }
2598
+ } = ctx;
2599
+ await validateQuery(ctx.query, ctx);
2600
+ const sanitizedQuery = await sanitizeQuery(ctx.query, ctx);
2601
+ const file2 = await getService("upload").findOne(id, sanitizedQuery.populate);
2602
+ if (!file2) {
2603
+ return ctx.notFound("file.notFound");
2604
+ }
2605
+ ctx.body = await sanitizeOutput(file2, ctx);
2606
+ },
2607
+ async destroy(ctx) {
2608
+ const {
2609
+ params: { id }
2610
+ } = ctx;
2611
+ const file2 = await getService("upload").findOne(id);
2612
+ if (!file2) {
2613
+ return ctx.notFound("file.notFound");
2614
+ }
2615
+ await getService("upload").remove(file2);
2616
+ ctx.body = await sanitizeOutput(file2, ctx);
2617
+ },
2618
+ async updateFileInfo(ctx) {
2619
+ const {
2620
+ query: { id },
2621
+ request: { body }
2622
+ } = ctx;
2623
+ const data = await validateUploadBody(body);
2624
+ if (!id || typeof id !== "string" && typeof id !== "number") {
2625
+ throw new ValidationError("File id is required and must be a single value");
2626
+ }
2627
+ const result = await getService("upload").updateFileInfo(id, data.fileInfo);
2628
+ ctx.body = await sanitizeOutput(result, ctx);
2629
+ },
2630
+ async replaceFile(ctx) {
2631
+ const {
2632
+ query: { id },
2633
+ request: { body, files: { files } = {} }
2634
+ } = ctx;
2635
+ if (Array.isArray(files)) {
2636
+ throw new ValidationError("Cannot replace a file with multiple ones");
2637
+ }
2638
+ if (!id || typeof id !== "string" && typeof id !== "number") {
2639
+ throw new ValidationError("File id is required and must be a single value");
2640
+ }
2641
+ const data = await validateUploadBody(body);
2642
+ const replacedFiles = await getService("upload").replace(id, { data, file: files });
2643
+ ctx.body = await sanitizeOutput(replacedFiles, ctx);
2644
+ },
2645
+ async uploadFiles(ctx) {
2646
+ const {
2647
+ request: { body, files: { files } = {} }
2648
+ } = ctx;
2649
+ const data = await validateUploadBody(body, Array.isArray(files));
2650
+ const apiUploadFolderService = getService("api-upload-folder");
2651
+ const apiUploadFolder2 = await apiUploadFolderService.getAPIUploadFolder();
2652
+ if (Array.isArray(files)) {
2653
+ data.fileInfo = data.fileInfo || [];
2654
+ data.fileInfo = files.map((_f, i) => ({ ...data.fileInfo[i], folder: apiUploadFolder2.id }));
2655
+ } else {
2656
+ data.fileInfo = { ...data.fileInfo, folder: apiUploadFolder2.id };
2657
+ }
2658
+ const uploadedFiles = await getService("upload").upload({
2659
+ data,
2660
+ files
2661
+ });
2662
+ ctx.body = await sanitizeOutput(uploadedFiles, ctx);
2663
+ ctx.status = 201;
2664
+ },
2665
+ // TODO: split into multiple endpoints
2666
+ async upload(ctx) {
2667
+ const {
2668
+ query: { id },
2669
+ request: { files: { files } = {} }
2670
+ } = ctx;
2671
+ if (___default.default.isEmpty(files) || !Array.isArray(files) && files.size === 0) {
2672
+ if (id) {
2673
+ return this.updateFileInfo(ctx);
2674
+ }
2675
+ throw new ValidationError("Files are empty");
2676
+ }
2677
+ await (id ? this.replaceFile : this.uploadFiles)(ctx);
2678
+ }
2679
+ };
2680
+ };
2681
+ const configSchema = utils.yup.object({
2682
+ pageSize: utils.yup.number().required(),
2683
+ sort: utils.yup.mixed().oneOf(ALLOWED_SORT_STRINGS)
2684
+ });
2685
+ const validateViewConfiguration = utils.validateYupSchema(configSchema);
2686
+ const viewConfiguration = {
2687
+ async updateViewConfiguration(ctx) {
2688
+ const {
2689
+ request: { body },
2690
+ state: { userAbility }
2691
+ } = ctx;
2692
+ if (userAbility.cannot(ACTIONS.configureView)) {
2693
+ return ctx.forbidden();
2694
+ }
2695
+ const data = await validateViewConfiguration(body);
2696
+ await getService("upload").setConfiguration(data);
2697
+ ctx.body = { data };
2698
+ },
2699
+ async findViewConfiguration(ctx) {
2700
+ const data = await getService("upload").getConfiguration();
2701
+ ctx.body = { data };
2702
+ }
2703
+ };
2704
+ const controllers = {
2705
+ "admin-file": adminFile,
2706
+ "admin-folder": adminFolder,
2707
+ "admin-folder-file": adminFolderFile,
2708
+ "admin-settings": adminSettings,
2709
+ "admin-upload": adminUpload,
2710
+ "content-api": contentApi,
2711
+ "view-configuration": viewConfiguration
2712
+ };
2713
+ const index = () => ({
2714
+ register,
2715
+ bootstrap,
2716
+ config,
2717
+ routes,
2718
+ controllers,
2719
+ contentTypes,
2720
+ services
2721
+ });
2722
+ exports.FILE_MODEL_UID = FILE_MODEL_UID;
2723
+ exports.index = index;
2724
+ //# sourceMappingURL=index-CZA6-NdH.js.map