@strapi/data-transfer 0.0.0-experimental.62ce06180fe9a772eaeb3d43d238b26644f39f7c → 0.0.0-experimental.6340da17068c3bed7fb006e7bcc554c71129e282

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 (395) hide show
  1. package/LICENSE +19 -4
  2. package/dist/directory/index.d.ts +2 -0
  3. package/dist/directory/index.d.ts.map +1 -0
  4. package/dist/directory/index.js +8 -0
  5. package/dist/directory/index.js.map +1 -0
  6. package/dist/directory/index.mjs +3 -0
  7. package/dist/directory/index.mjs.map +1 -0
  8. package/dist/directory/providers/destination/index.d.ts +38 -0
  9. package/dist/directory/providers/destination/index.d.ts.map +1 -0
  10. package/dist/directory/providers/destination/index.js +184 -0
  11. package/dist/directory/providers/destination/index.js.map +1 -0
  12. package/dist/directory/providers/destination/index.mjs +177 -0
  13. package/dist/directory/providers/destination/index.mjs.map +1 -0
  14. package/dist/directory/providers/destination/utils.d.ts +8 -0
  15. package/dist/directory/providers/destination/utils.d.ts.map +1 -0
  16. package/dist/directory/providers/destination/utils.js +62 -0
  17. package/dist/directory/providers/destination/utils.js.map +1 -0
  18. package/dist/directory/providers/destination/utils.mjs +56 -0
  19. package/dist/directory/providers/destination/utils.mjs.map +1 -0
  20. package/dist/directory/providers/index.d.ts +3 -0
  21. package/dist/directory/providers/index.d.ts.map +1 -0
  22. package/dist/directory/providers/index.js +10 -0
  23. package/dist/directory/providers/index.js.map +1 -0
  24. package/dist/directory/providers/index.mjs +3 -0
  25. package/dist/directory/providers/index.mjs.map +1 -0
  26. package/dist/directory/providers/source/index.d.ts +27 -0
  27. package/dist/directory/providers/source/index.d.ts.map +1 -0
  28. package/dist/directory/providers/source/index.js +266 -0
  29. package/dist/directory/providers/source/index.js.map +1 -0
  30. package/dist/directory/providers/source/index.mjs +259 -0
  31. package/dist/directory/providers/source/index.mjs.map +1 -0
  32. package/dist/engine/errors.js +39 -0
  33. package/dist/engine/errors.js.map +1 -0
  34. package/dist/engine/errors.mjs +34 -0
  35. package/dist/engine/errors.mjs.map +1 -0
  36. package/dist/engine/index.d.ts +2 -3
  37. package/dist/engine/index.d.ts.map +1 -1
  38. package/dist/engine/index.js +922 -0
  39. package/dist/engine/index.js.map +1 -0
  40. package/dist/engine/index.mjs +917 -0
  41. package/dist/engine/index.mjs.map +1 -0
  42. package/dist/engine/validation/provider.d.ts +2 -2
  43. package/dist/engine/validation/provider.d.ts.map +1 -1
  44. package/dist/engine/validation/provider.js +19 -0
  45. package/dist/engine/validation/provider.js.map +1 -0
  46. package/dist/engine/validation/provider.mjs +17 -0
  47. package/dist/engine/validation/provider.mjs.map +1 -0
  48. package/dist/engine/validation/schemas/index.d.ts.map +1 -1
  49. package/dist/engine/validation/schemas/index.js +59 -0
  50. package/dist/engine/validation/schemas/index.js.map +1 -0
  51. package/dist/engine/validation/schemas/index.mjs +57 -0
  52. package/dist/engine/validation/schemas/index.mjs.map +1 -0
  53. package/dist/errors/base.js +13 -0
  54. package/dist/errors/base.js.map +1 -0
  55. package/dist/errors/base.mjs +11 -0
  56. package/dist/errors/base.mjs.map +1 -0
  57. package/dist/errors/constants.d.ts +1 -1
  58. package/dist/errors/constants.d.ts.map +1 -1
  59. package/dist/errors/constants.js +9 -0
  60. package/dist/errors/constants.js.map +1 -0
  61. package/dist/errors/constants.mjs +7 -0
  62. package/dist/errors/constants.mjs.map +1 -0
  63. package/dist/errors/providers.d.ts +1 -1
  64. package/dist/errors/providers.d.ts.map +1 -1
  65. package/dist/errors/providers.js +41 -0
  66. package/dist/errors/providers.js.map +1 -0
  67. package/dist/errors/providers.mjs +36 -0
  68. package/dist/errors/providers.mjs.map +1 -0
  69. package/dist/file/index.js +8 -0
  70. package/dist/file/index.js.map +1 -0
  71. package/dist/file/index.mjs +3 -0
  72. package/dist/file/index.mjs.map +1 -0
  73. package/dist/file/providers/destination/index.d.ts +3 -5
  74. package/dist/file/providers/destination/index.d.ts.map +1 -1
  75. package/dist/file/providers/destination/index.js +254 -0
  76. package/dist/file/providers/destination/index.js.map +1 -0
  77. package/dist/file/providers/destination/index.mjs +246 -0
  78. package/dist/file/providers/destination/index.mjs.map +1 -0
  79. package/dist/file/providers/destination/utils.d.ts +0 -1
  80. package/dist/file/providers/destination/utils.d.ts.map +1 -1
  81. package/dist/file/providers/destination/utils.js +63 -0
  82. package/dist/file/providers/destination/utils.js.map +1 -0
  83. package/dist/file/providers/destination/utils.mjs +60 -0
  84. package/dist/file/providers/destination/utils.mjs.map +1 -0
  85. package/dist/file/providers/index.js +10 -0
  86. package/dist/file/providers/index.js.map +1 -0
  87. package/dist/file/providers/index.mjs +3 -0
  88. package/dist/file/providers/index.mjs.map +1 -0
  89. package/dist/file/providers/source/index.d.ts +3 -3
  90. package/dist/file/providers/source/index.d.ts.map +1 -1
  91. package/dist/file/providers/source/index.js +336 -0
  92. package/dist/file/providers/source/index.js.map +1 -0
  93. package/dist/file/providers/source/index.mjs +328 -0
  94. package/dist/file/providers/source/index.mjs.map +1 -0
  95. package/dist/file/providers/source/utils.d.ts.map +1 -1
  96. package/dist/file/providers/source/utils.js +60 -0
  97. package/dist/file/providers/source/utils.js.map +1 -0
  98. package/dist/file/providers/source/utils.mjs +52 -0
  99. package/dist/file/providers/source/utils.mjs.map +1 -0
  100. package/dist/index.d.ts +1 -0
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +15 -4408
  103. package/dist/index.js.map +1 -1
  104. package/dist/index.mjs +10 -4382
  105. package/dist/index.mjs.map +1 -1
  106. package/dist/strapi/index.js +12 -0
  107. package/dist/strapi/index.js.map +1 -0
  108. package/dist/strapi/index.mjs +7 -0
  109. package/dist/strapi/index.mjs.map +1 -0
  110. package/dist/strapi/providers/index.js +18 -0
  111. package/dist/strapi/providers/index.js.map +1 -0
  112. package/dist/strapi/providers/index.mjs +8 -0
  113. package/dist/strapi/providers/index.mjs.map +1 -0
  114. package/dist/strapi/providers/local-destination/assets-destination-writable.d.ts +26 -0
  115. package/dist/strapi/providers/local-destination/assets-destination-writable.d.ts.map +1 -0
  116. package/dist/strapi/providers/local-destination/assets-destination-writable.js +125 -0
  117. package/dist/strapi/providers/local-destination/assets-destination-writable.js.map +1 -0
  118. package/dist/strapi/providers/local-destination/assets-destination-writable.mjs +123 -0
  119. package/dist/strapi/providers/local-destination/assets-destination-writable.mjs.map +1 -0
  120. package/dist/strapi/providers/local-destination/index.d.ts +5 -3
  121. package/dist/strapi/providers/local-destination/index.d.ts.map +1 -1
  122. package/dist/strapi/providers/local-destination/index.js +362 -0
  123. package/dist/strapi/providers/local-destination/index.js.map +1 -0
  124. package/dist/strapi/providers/local-destination/index.mjs +335 -0
  125. package/dist/strapi/providers/local-destination/index.mjs.map +1 -0
  126. package/dist/strapi/providers/local-destination/strategies/restore/configuration.d.ts +1 -2
  127. package/dist/strapi/providers/local-destination/strategies/restore/configuration.d.ts.map +1 -1
  128. package/dist/strapi/providers/local-destination/strategies/restore/configuration.js +58 -0
  129. package/dist/strapi/providers/local-destination/strategies/restore/configuration.js.map +1 -0
  130. package/dist/strapi/providers/local-destination/strategies/restore/configuration.mjs +51 -0
  131. package/dist/strapi/providers/local-destination/strategies/restore/configuration.mjs.map +1 -0
  132. package/dist/strapi/providers/local-destination/strategies/restore/entities.d.ts +1 -2
  133. package/dist/strapi/providers/local-destination/strategies/restore/entities.d.ts.map +1 -1
  134. package/dist/strapi/providers/local-destination/strategies/restore/entities.js +54 -0
  135. package/dist/strapi/providers/local-destination/strategies/restore/entities.js.map +1 -0
  136. package/dist/strapi/providers/local-destination/strategies/restore/entities.mjs +52 -0
  137. package/dist/strapi/providers/local-destination/strategies/restore/entities.mjs.map +1 -0
  138. package/dist/strapi/providers/local-destination/strategies/restore/index.d.ts.map +1 -1
  139. package/dist/strapi/providers/local-destination/strategies/restore/index.js +124 -0
  140. package/dist/strapi/providers/local-destination/strategies/restore/index.js.map +1 -0
  141. package/dist/strapi/providers/local-destination/strategies/restore/index.mjs +120 -0
  142. package/dist/strapi/providers/local-destination/strategies/restore/index.mjs.map +1 -0
  143. package/dist/strapi/providers/local-destination/strategies/restore/links.d.ts +1 -2
  144. package/dist/strapi/providers/local-destination/strategies/restore/links.d.ts.map +1 -1
  145. package/dist/strapi/providers/local-destination/strategies/restore/links.js +79 -0
  146. package/dist/strapi/providers/local-destination/strategies/restore/links.js.map +1 -0
  147. package/dist/strapi/providers/local-destination/strategies/restore/links.mjs +77 -0
  148. package/dist/strapi/providers/local-destination/strategies/restore/links.mjs.map +1 -0
  149. package/dist/strapi/providers/local-source/assets.d.ts +8 -2
  150. package/dist/strapi/providers/local-source/assets.d.ts.map +1 -1
  151. package/dist/strapi/providers/local-source/assets.js +151 -0
  152. package/dist/strapi/providers/local-source/assets.js.map +1 -0
  153. package/dist/strapi/providers/local-source/assets.mjs +147 -0
  154. package/dist/strapi/providers/local-source/assets.mjs.map +1 -0
  155. package/dist/strapi/providers/local-source/configuration.d.ts +0 -1
  156. package/dist/strapi/providers/local-source/configuration.d.ts.map +1 -1
  157. package/dist/strapi/providers/local-source/configuration.js +47 -0
  158. package/dist/strapi/providers/local-source/configuration.js.map +1 -0
  159. package/dist/strapi/providers/local-source/configuration.mjs +45 -0
  160. package/dist/strapi/providers/local-source/configuration.mjs.map +1 -0
  161. package/dist/strapi/providers/local-source/entities.d.ts +3 -2
  162. package/dist/strapi/providers/local-source/entities.d.ts.map +1 -1
  163. package/dist/strapi/providers/local-source/entities.js +66 -0
  164. package/dist/strapi/providers/local-source/entities.js.map +1 -0
  165. package/dist/strapi/providers/local-source/entities.mjs +63 -0
  166. package/dist/strapi/providers/local-source/entities.mjs.map +1 -0
  167. package/dist/strapi/providers/local-source/estimate-asset-totals.d.ts +11 -0
  168. package/dist/strapi/providers/local-source/estimate-asset-totals.d.ts.map +1 -0
  169. package/dist/strapi/providers/local-source/estimate-asset-totals.js +130 -0
  170. package/dist/strapi/providers/local-source/estimate-asset-totals.js.map +1 -0
  171. package/dist/strapi/providers/local-source/estimate-asset-totals.mjs +128 -0
  172. package/dist/strapi/providers/local-source/estimate-asset-totals.mjs.map +1 -0
  173. package/dist/strapi/providers/local-source/index.d.ts +6 -4
  174. package/dist/strapi/providers/local-source/index.d.ts.map +1 -1
  175. package/dist/strapi/providers/local-source/index.js +186 -0
  176. package/dist/strapi/providers/local-source/index.js.map +1 -0
  177. package/dist/strapi/providers/local-source/index.mjs +183 -0
  178. package/dist/strapi/providers/local-source/index.mjs.map +1 -0
  179. package/dist/strapi/providers/local-source/links.d.ts +0 -1
  180. package/dist/strapi/providers/local-source/links.d.ts.map +1 -1
  181. package/dist/strapi/providers/local-source/links.js +26 -0
  182. package/dist/strapi/providers/local-source/links.js.map +1 -0
  183. package/dist/strapi/providers/local-source/links.mjs +24 -0
  184. package/dist/strapi/providers/local-source/links.mjs.map +1 -0
  185. package/dist/strapi/providers/remote-destination/index.d.ts +13 -5
  186. package/dist/strapi/providers/remote-destination/index.d.ts.map +1 -1
  187. package/dist/strapi/providers/remote-destination/index.js +482 -0
  188. package/dist/strapi/providers/remote-destination/index.js.map +1 -0
  189. package/dist/strapi/providers/remote-destination/index.mjs +480 -0
  190. package/dist/strapi/providers/remote-destination/index.mjs.map +1 -0
  191. package/dist/strapi/providers/remote-source/index.d.ts +11 -6
  192. package/dist/strapi/providers/remote-source/index.d.ts.map +1 -1
  193. package/dist/strapi/providers/remote-source/index.js +538 -0
  194. package/dist/strapi/providers/remote-source/index.js.map +1 -0
  195. package/dist/strapi/providers/remote-source/index.mjs +536 -0
  196. package/dist/strapi/providers/remote-source/index.mjs.map +1 -0
  197. package/dist/strapi/providers/utils.d.ts +22 -16
  198. package/dist/strapi/providers/utils.d.ts.map +1 -1
  199. package/dist/strapi/providers/utils.js +178 -0
  200. package/dist/strapi/providers/utils.js.map +1 -0
  201. package/dist/strapi/providers/utils.mjs +174 -0
  202. package/dist/strapi/providers/utils.mjs.map +1 -0
  203. package/dist/strapi/queries/entity.d.ts.map +1 -1
  204. package/dist/strapi/queries/entity.js +125 -0
  205. package/dist/strapi/queries/entity.js.map +1 -0
  206. package/dist/strapi/queries/entity.mjs +123 -0
  207. package/dist/strapi/queries/entity.mjs.map +1 -0
  208. package/dist/strapi/queries/index.js +10 -0
  209. package/dist/strapi/queries/index.js.map +1 -0
  210. package/dist/strapi/queries/index.mjs +5 -0
  211. package/dist/strapi/queries/index.mjs.map +1 -0
  212. package/dist/strapi/queries/link.d.ts +1 -1
  213. package/dist/strapi/queries/link.d.ts.map +1 -1
  214. package/dist/strapi/queries/link.js +298 -0
  215. package/dist/strapi/queries/link.js.map +1 -0
  216. package/dist/strapi/queries/link.mjs +295 -0
  217. package/dist/strapi/queries/link.mjs.map +1 -0
  218. package/dist/strapi/remote/constants.d.ts.map +1 -1
  219. package/dist/strapi/remote/constants.js +11 -0
  220. package/dist/strapi/remote/constants.js.map +1 -0
  221. package/dist/strapi/remote/constants.mjs +8 -0
  222. package/dist/strapi/remote/constants.mjs.map +1 -0
  223. package/dist/strapi/remote/flows/default.d.ts.map +1 -1
  224. package/dist/strapi/remote/flows/default.js +43 -0
  225. package/dist/strapi/remote/flows/default.js.map +1 -0
  226. package/dist/strapi/remote/flows/default.mjs +41 -0
  227. package/dist/strapi/remote/flows/default.mjs.map +1 -0
  228. package/dist/strapi/remote/flows/index.d.ts +1 -1
  229. package/dist/strapi/remote/flows/index.d.ts.map +1 -1
  230. package/dist/strapi/remote/flows/index.js +54 -0
  231. package/dist/strapi/remote/flows/index.js.map +1 -0
  232. package/dist/strapi/remote/flows/index.mjs +52 -0
  233. package/dist/strapi/remote/flows/index.mjs.map +1 -0
  234. package/dist/strapi/remote/handlers/abstract.d.ts +4 -1
  235. package/dist/strapi/remote/handlers/abstract.d.ts.map +1 -1
  236. package/dist/strapi/remote/handlers/constants.js +10 -0
  237. package/dist/strapi/remote/handlers/constants.js.map +1 -0
  238. package/dist/strapi/remote/handlers/constants.mjs +8 -0
  239. package/dist/strapi/remote/handlers/constants.mjs.map +1 -0
  240. package/dist/strapi/remote/handlers/index.js +12 -0
  241. package/dist/strapi/remote/handlers/index.js.map +1 -0
  242. package/dist/strapi/remote/handlers/index.mjs +4 -0
  243. package/dist/strapi/remote/handlers/index.mjs.map +1 -0
  244. package/dist/strapi/remote/handlers/pull.d.ts +2 -3
  245. package/dist/strapi/remote/handlers/pull.d.ts.map +1 -1
  246. package/dist/strapi/remote/handlers/pull.js +369 -0
  247. package/dist/strapi/remote/handlers/pull.js.map +1 -0
  248. package/dist/strapi/remote/handlers/pull.mjs +367 -0
  249. package/dist/strapi/remote/handlers/pull.mjs.map +1 -0
  250. package/dist/strapi/remote/handlers/push.d.ts +16 -5
  251. package/dist/strapi/remote/handlers/push.d.ts.map +1 -1
  252. package/dist/strapi/remote/handlers/push.js +454 -0
  253. package/dist/strapi/remote/handlers/push.js.map +1 -0
  254. package/dist/strapi/remote/handlers/push.mjs +452 -0
  255. package/dist/strapi/remote/handlers/push.mjs.map +1 -0
  256. package/dist/strapi/remote/handlers/utils.d.ts +1 -2
  257. package/dist/strapi/remote/handlers/utils.d.ts.map +1 -1
  258. package/dist/strapi/remote/handlers/utils.js +318 -0
  259. package/dist/strapi/remote/handlers/utils.js.map +1 -0
  260. package/dist/strapi/remote/handlers/utils.mjs +312 -0
  261. package/dist/strapi/remote/handlers/utils.mjs.map +1 -0
  262. package/dist/strapi/remote/index.js +10 -0
  263. package/dist/strapi/remote/index.js.map +1 -0
  264. package/dist/strapi/remote/index.mjs +5 -0
  265. package/dist/strapi/remote/index.mjs.map +1 -0
  266. package/dist/strapi/utils/project-settings-logos.d.ts +29 -0
  267. package/dist/strapi/utils/project-settings-logos.d.ts.map +1 -0
  268. package/dist/strapi/utils/project-settings-logos.js +174 -0
  269. package/dist/strapi/utils/project-settings-logos.js.map +1 -0
  270. package/dist/strapi/utils/project-settings-logos.mjs +169 -0
  271. package/dist/strapi/utils/project-settings-logos.mjs.map +1 -0
  272. package/dist/types/common-entities.d.ts +149 -0
  273. package/dist/types/common-entities.d.ts.map +1 -0
  274. package/dist/types/encryption.d.ts +13 -0
  275. package/dist/types/encryption.d.ts.map +1 -0
  276. package/dist/types/index.d.ts +7 -0
  277. package/dist/types/index.d.ts.map +1 -0
  278. package/dist/types/providers.d.ts +49 -0
  279. package/dist/types/providers.d.ts.map +1 -0
  280. package/dist/types/remote/index.d.ts +2 -0
  281. package/dist/types/remote/index.d.ts.map +1 -0
  282. package/dist/types/remote/protocol/auth.d.ts +5 -0
  283. package/dist/types/remote/protocol/auth.d.ts.map +1 -0
  284. package/dist/types/remote/protocol/client/commands.d.ts +37 -0
  285. package/dist/types/remote/protocol/client/commands.d.ts.map +1 -0
  286. package/dist/types/remote/protocol/client/index.d.ts +9 -0
  287. package/dist/types/remote/protocol/client/index.d.ts.map +1 -0
  288. package/dist/types/remote/protocol/client/transfer/action.d.ts +5 -0
  289. package/dist/types/remote/protocol/client/transfer/action.d.ts.map +1 -0
  290. package/dist/types/remote/protocol/client/transfer/index.d.ts +12 -0
  291. package/dist/types/remote/protocol/client/transfer/index.d.ts.map +1 -0
  292. package/dist/types/remote/protocol/client/transfer/pull.d.ts +25 -0
  293. package/dist/types/remote/protocol/client/transfer/pull.d.ts.map +1 -0
  294. package/dist/types/remote/protocol/client/transfer/push.d.ts +29 -0
  295. package/dist/types/remote/protocol/client/transfer/push.d.ts.map +1 -0
  296. package/dist/types/remote/protocol/client/transfer/utils.d.ts +47 -0
  297. package/dist/types/remote/protocol/client/transfer/utils.d.ts.map +1 -0
  298. package/dist/types/remote/protocol/index.d.ts +4 -0
  299. package/dist/types/remote/protocol/index.d.ts.map +1 -0
  300. package/dist/types/remote/protocol/server/error.d.ts +18 -0
  301. package/dist/types/remote/protocol/server/error.d.ts.map +1 -0
  302. package/dist/types/remote/protocol/server/index.d.ts +3 -0
  303. package/dist/types/remote/protocol/server/index.d.ts.map +1 -0
  304. package/dist/types/remote/protocol/server/messaging.d.ts +37 -0
  305. package/dist/types/remote/protocol/server/messaging.d.ts.map +1 -0
  306. package/dist/types/transfer-engine.d.ts +148 -0
  307. package/dist/types/transfer-engine.d.ts.map +1 -0
  308. package/dist/types/utils.d.ts +82 -0
  309. package/dist/types/utils.d.ts.map +1 -0
  310. package/dist/utils/components.d.ts +23 -3
  311. package/dist/utils/components.d.ts.map +1 -1
  312. package/dist/utils/components.js +230 -0
  313. package/dist/utils/components.js.map +1 -0
  314. package/dist/utils/components.mjs +219 -0
  315. package/dist/utils/components.mjs.map +1 -0
  316. package/dist/{engine → utils}/diagnostic.d.ts +1 -0
  317. package/dist/utils/diagnostic.d.ts.map +1 -0
  318. package/dist/utils/diagnostic.js +51 -0
  319. package/dist/utils/diagnostic.js.map +1 -0
  320. package/dist/utils/diagnostic.mjs +49 -0
  321. package/dist/utils/diagnostic.mjs.map +1 -0
  322. package/dist/utils/encryption/decrypt.d.ts +6 -5
  323. package/dist/utils/encryption/decrypt.d.ts.map +1 -1
  324. package/dist/utils/encryption/decrypt.js +47 -0
  325. package/dist/utils/encryption/decrypt.js.map +1 -0
  326. package/dist/utils/encryption/decrypt.mjs +45 -0
  327. package/dist/utils/encryption/decrypt.mjs.map +1 -0
  328. package/dist/utils/encryption/encrypt.d.ts +6 -5
  329. package/dist/utils/encryption/encrypt.d.ts.map +1 -1
  330. package/dist/utils/encryption/encrypt.js +47 -0
  331. package/dist/utils/encryption/encrypt.js.map +1 -0
  332. package/dist/utils/encryption/encrypt.mjs +45 -0
  333. package/dist/utils/encryption/encrypt.mjs.map +1 -0
  334. package/dist/utils/encryption/index.js +10 -0
  335. package/dist/utils/encryption/index.js.map +1 -0
  336. package/dist/utils/encryption/index.mjs +3 -0
  337. package/dist/utils/encryption/index.mjs.map +1 -0
  338. package/dist/utils/index.d.ts +3 -0
  339. package/dist/utils/index.d.ts.map +1 -1
  340. package/dist/utils/index.js +28 -0
  341. package/dist/utils/index.js.map +1 -0
  342. package/dist/utils/index.mjs +17 -0
  343. package/dist/utils/index.mjs.map +1 -0
  344. package/dist/utils/json.d.ts.map +1 -1
  345. package/dist/utils/json.js +96 -0
  346. package/dist/utils/json.js.map +1 -0
  347. package/dist/utils/json.mjs +94 -0
  348. package/dist/utils/json.mjs.map +1 -0
  349. package/dist/utils/middleware.d.ts +1 -1
  350. package/dist/utils/middleware.d.ts.map +1 -1
  351. package/dist/utils/middleware.js +14 -0
  352. package/dist/utils/middleware.js.map +1 -0
  353. package/dist/utils/middleware.mjs +12 -0
  354. package/dist/utils/middleware.mjs.map +1 -0
  355. package/dist/utils/providers.js +12 -0
  356. package/dist/utils/providers.js.map +1 -0
  357. package/dist/utils/providers.mjs +10 -0
  358. package/dist/utils/providers.mjs.map +1 -0
  359. package/dist/utils/schema.d.ts.map +1 -1
  360. package/dist/utils/schema.js +32 -0
  361. package/dist/utils/schema.js.map +1 -0
  362. package/dist/utils/schema.mjs +29 -0
  363. package/dist/utils/schema.mjs.map +1 -0
  364. package/dist/utils/stream.d.ts +0 -1
  365. package/dist/utils/stream.d.ts.map +1 -1
  366. package/dist/utils/stream.js +96 -0
  367. package/dist/utils/stream.js.map +1 -0
  368. package/dist/utils/stream.mjs +92 -0
  369. package/dist/utils/stream.mjs.map +1 -0
  370. package/dist/utils/transaction.d.ts +1 -1
  371. package/dist/utils/transaction.d.ts.map +1 -1
  372. package/dist/utils/transaction.js +93 -0
  373. package/dist/utils/transaction.js.map +1 -0
  374. package/dist/utils/transaction.mjs +91 -0
  375. package/dist/utils/transaction.mjs.map +1 -0
  376. package/dist/utils/transfer-asset-chunk.d.ts +61 -0
  377. package/dist/utils/transfer-asset-chunk.d.ts.map +1 -0
  378. package/dist/utils/transfer-asset-chunk.js +118 -0
  379. package/dist/utils/transfer-asset-chunk.js.map +1 -0
  380. package/dist/utils/transfer-asset-chunk.mjs +112 -0
  381. package/dist/utils/transfer-asset-chunk.mjs.map +1 -0
  382. package/dist/utils/transfer-websocket-json.d.ts +24 -0
  383. package/dist/utils/transfer-websocket-json.d.ts.map +1 -0
  384. package/dist/utils/transfer-websocket-json.js +67 -0
  385. package/dist/utils/transfer-websocket-json.js.map +1 -0
  386. package/dist/utils/transfer-websocket-json.mjs +63 -0
  387. package/dist/utils/transfer-websocket-json.mjs.map +1 -0
  388. package/dist/utils/writable-async-write.d.ts +16 -0
  389. package/dist/utils/writable-async-write.d.ts.map +1 -0
  390. package/dist/utils/writable-async-write.js +61 -0
  391. package/dist/utils/writable-async-write.js.map +1 -0
  392. package/dist/utils/writable-async-write.mjs +59 -0
  393. package/dist/utils/writable-async-write.mjs.map +1 -0
  394. package/package.json +40 -26
  395. package/dist/engine/diagnostic.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,4409 +1,16 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const stream$1 = require("stream");
4
- const path = require("path");
5
- const os = require("os");
6
- const streamChain = require("stream-chain");
7
- const fp = require("lodash/fp");
8
- const semver = require("semver");
9
- const crypto = require("crypto");
10
- const events = require("events");
11
- const fse = require("fs-extra");
12
- const _ = require("lodash");
13
- const utils = require("@strapi/utils");
14
- const chalk = require("chalk");
15
- const webStream = require("stream/web");
16
- const ws = require("ws");
17
- const zip = require("zlib");
18
- const tar = require("tar");
19
- const Parser = require("stream-json/jsonl/Parser");
20
- const tar$1 = require("tar-stream");
21
- const Stringer = require("stream-json/jsonl/Stringer");
22
- const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
23
- function _interopNamespace(e) {
24
- if (e && e.__esModule)
25
- return e;
26
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
27
- if (e) {
28
- for (const k in e) {
29
- if (k !== "default") {
30
- const d = Object.getOwnPropertyDescriptor(e, k);
31
- Object.defineProperty(n, k, d.get ? d : {
32
- enumerable: true,
33
- get: () => e[k]
34
- });
35
- }
36
- }
37
- }
38
- n.default = e;
39
- return Object.freeze(n);
40
- }
41
- const path__default = /* @__PURE__ */ _interopDefault(path);
42
- const fse__namespace = /* @__PURE__ */ _interopNamespace(fse);
43
- const ___default = /* @__PURE__ */ _interopDefault(_);
44
- const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
45
- const webStream__namespace = /* @__PURE__ */ _interopNamespace(webStream);
46
- const zip__default = /* @__PURE__ */ _interopDefault(zip);
47
- const tar__default = /* @__PURE__ */ _interopDefault(tar);
48
- const tar__default$1 = /* @__PURE__ */ _interopDefault(tar$1);
49
- const getEncryptionStrategy = (algorithm) => {
50
- const strategies2 = {
51
- "aes-128-ecb"(key) {
52
- const hashedKey = crypto.scryptSync(key, "", 16);
53
- const initVector = null;
54
- const securityKey = hashedKey;
55
- return crypto.createCipheriv(algorithm, securityKey, initVector);
56
- },
57
- aes128(key) {
58
- const hashedKey = crypto.scryptSync(key, "", 32);
59
- const initVector = hashedKey.slice(16);
60
- const securityKey = hashedKey.slice(0, 16);
61
- return crypto.createCipheriv(algorithm, securityKey, initVector);
62
- },
63
- aes192(key) {
64
- const hashedKey = crypto.scryptSync(key, "", 40);
65
- const initVector = hashedKey.slice(24);
66
- const securityKey = hashedKey.slice(0, 24);
67
- return crypto.createCipheriv(algorithm, securityKey, initVector);
68
- },
69
- aes256(key) {
70
- const hashedKey = crypto.scryptSync(key, "", 48);
71
- const initVector = hashedKey.slice(32);
72
- const securityKey = hashedKey.slice(0, 32);
73
- return crypto.createCipheriv(algorithm, securityKey, initVector);
74
- }
75
- };
76
- return strategies2[algorithm];
77
- };
78
- const createEncryptionCipher = (key, algorithm = "aes-128-ecb") => {
79
- return getEncryptionStrategy(algorithm)(key);
80
- };
81
- const getDecryptionStrategy = (algorithm) => {
82
- const strategies2 = {
83
- "aes-128-ecb"(key) {
84
- const hashedKey = crypto.scryptSync(key, "", 16);
85
- const initVector = null;
86
- const securityKey = hashedKey;
87
- return crypto.createDecipheriv(algorithm, securityKey, initVector);
88
- },
89
- aes128(key) {
90
- const hashedKey = crypto.scryptSync(key, "", 32);
91
- const initVector = hashedKey.slice(16);
92
- const securityKey = hashedKey.slice(0, 16);
93
- return crypto.createDecipheriv(algorithm, securityKey, initVector);
94
- },
95
- aes192(key) {
96
- const hashedKey = crypto.scryptSync(key, "", 40);
97
- const initVector = hashedKey.slice(24);
98
- const securityKey = hashedKey.slice(0, 24);
99
- return crypto.createDecipheriv(algorithm, securityKey, initVector);
100
- },
101
- aes256(key) {
102
- const hashedKey = crypto.scryptSync(key, "", 48);
103
- const initVector = hashedKey.slice(32);
104
- const securityKey = hashedKey.slice(0, 32);
105
- return crypto.createDecipheriv(algorithm, securityKey, initVector);
106
- }
107
- };
108
- return strategies2[algorithm];
109
- };
110
- const createDecryptionCipher = (key, algorithm = "aes-128-ecb") => {
111
- return getDecryptionStrategy(algorithm)(key);
112
- };
113
- const index$9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
114
- __proto__: null,
115
- createDecryptionCipher,
116
- createEncryptionCipher
117
- }, Symbol.toStringTag, { value: "Module" }));
118
- const filter = (predicate, options = { objectMode: true }) => {
119
- return new stream$1.Transform({
120
- ...options,
121
- async transform(chunk, _encoding, callback) {
122
- const keep = await predicate(chunk);
123
- callback(null, keep ? chunk : void 0);
124
- }
125
- });
126
- };
127
- const map = (predicate, options = { objectMode: true }) => {
128
- return new stream$1.Transform({
129
- ...options,
130
- async transform(chunk, _encoding, callback) {
131
- const mappedValue = await predicate(chunk);
132
- callback(null, mappedValue);
133
- }
134
- });
135
- };
136
- const collect = (stream2, options = { destroy: true }) => {
137
- const chunks = [];
138
- return new Promise((resolve, reject2) => {
139
- stream2.on("close", () => resolve(chunks)).on("error", reject2).on("data", (chunk) => chunks.push(chunk)).on("end", () => {
140
- if (options.destroy) {
141
- stream2.destroy();
142
- }
143
- resolve(chunks);
144
- });
145
- });
146
- };
147
- const stream = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
148
- __proto__: null,
149
- collect,
150
- filter,
151
- map
152
- }, Symbol.toStringTag, { value: "Module" }));
153
- const createContext = () => ({ path: [] });
154
- const diff = (a, b, ctx = createContext()) => {
155
- const diffs = [];
156
- const { path: path2 } = ctx;
157
- const aType = typeof a;
158
- const bType = typeof b;
159
- const added = () => {
160
- diffs.push({ kind: "added", path: path2, type: bType, value: b });
161
- return diffs;
162
- };
163
- const deleted = () => {
164
- diffs.push({ kind: "deleted", path: path2, type: aType, value: a });
165
- return diffs;
166
- };
167
- const modified = () => {
168
- diffs.push({
169
- kind: "modified",
170
- path: path2,
171
- types: [aType, bType],
172
- values: [a, b]
173
- });
174
- return diffs;
175
- };
176
- if (fp.isArray(a) && fp.isArray(b)) {
177
- let k = 0;
178
- for (const [aItem, bItem] of fp.zip(a, b)) {
179
- const kCtx = { path: [...path2, k.toString()] };
180
- const kDiffs = diff(aItem, bItem, kCtx);
181
- diffs.push(...kDiffs);
182
- k += 1;
183
- }
184
- return diffs;
185
- }
186
- if (fp.isObject(a) && fp.isObject(b)) {
187
- const keys = fp.uniq(Object.keys(a).concat(Object.keys(b)));
188
- for (const key of keys) {
189
- const aValue = a[key];
190
- const bValue = b[key];
191
- const nestedDiffs = diff(aValue, bValue, { path: [...path2, key] });
192
- diffs.push(...nestedDiffs);
193
- }
194
- return diffs;
195
- }
196
- if (!fp.isEqual(a, b)) {
197
- if (aType === "undefined") {
198
- return added();
199
- }
200
- if (bType === "undefined") {
201
- return deleted();
202
- }
203
- return modified();
204
- }
205
- return diffs;
206
- };
207
- const json = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
208
- __proto__: null,
209
- diff
210
- }, Symbol.toStringTag, { value: "Module" }));
211
- const VALID_SCHEMA_PROPERTIES = [
212
- "collectionName",
213
- "info",
214
- "options",
215
- "pluginOptions",
216
- "attributes",
217
- "kind",
218
- "modelType",
219
- "modelName",
220
- "uid",
221
- "plugin",
222
- "globalId"
223
- ];
224
- const mapSchemasValues = (schemas) => {
225
- return fp.mapValues(fp.pick(VALID_SCHEMA_PROPERTIES), schemas);
226
- };
227
- const schemasToValidJSON = (schemas) => {
228
- return JSON.parse(JSON.stringify(schemas));
229
- };
230
- const schema = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
231
- __proto__: null,
232
- mapSchemasValues,
233
- schemasToValidJSON
234
- }, Symbol.toStringTag, { value: "Module" }));
235
- const createTransaction = (strapi2) => {
236
- const fns = [];
237
- let done = false;
238
- let resume = null;
239
- const e = new events.EventEmitter();
240
- e.on("spawn", (uuid, cb) => {
241
- fns.push({ fn: cb, uuid });
242
- resume?.();
243
- });
244
- e.on("close", () => {
245
- e.removeAllListeners("rollback");
246
- e.removeAllListeners("spawn");
247
- done = true;
248
- resume?.();
249
- });
250
- strapi2.db.transaction(async ({ trx, rollback }) => {
251
- e.once("rollback", async () => {
252
- e.removeAllListeners("close");
253
- e.removeAllListeners("spawn");
254
- try {
255
- await rollback();
256
- e.emit("rollback_completed");
257
- } catch {
258
- e.emit("rollback_failed");
259
- } finally {
260
- done = true;
261
- resume?.();
262
- }
263
- });
264
- while (!done) {
265
- while (fns.length) {
266
- const item = fns.shift();
267
- if (item) {
268
- const { fn, uuid } = item;
269
- try {
270
- const res = await fn(trx);
271
- e.emit(uuid, { data: res });
272
- } catch (error) {
273
- e.emit(uuid, { error });
274
- }
275
- }
276
- }
277
- if (!done && !fns.length) {
278
- await new Promise((resolve) => {
279
- resume = resolve;
280
- });
281
- }
282
- }
283
- });
284
- return {
285
- async attach(callback) {
286
- const uuid = crypto.randomUUID();
287
- e.emit("spawn", uuid, callback);
288
- return new Promise((resolve, reject2) => {
289
- e.on(uuid, ({ data, error }) => {
290
- if (data) {
291
- resolve(data);
292
- }
293
- if (error) {
294
- reject2(error);
295
- }
296
- resolve(void 0);
297
- });
298
- });
299
- },
300
- end() {
301
- return e.emit("close");
302
- },
303
- rollback() {
304
- return new Promise((resolve) => {
305
- e.emit("rollback");
306
- e.once("rollback_failed", () => resolve(false));
307
- e.once("rollback_completed", () => resolve(true));
308
- });
309
- }
310
- };
311
- };
312
- const transaction = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
313
- __proto__: null,
314
- createTransaction
315
- }, Symbol.toStringTag, { value: "Module" }));
316
- const runMiddleware = async (context, middlewares) => {
317
- if (!middlewares.length) {
318
- return;
319
- }
320
- const cb = middlewares[0];
321
- await cb(context, async (newContext) => {
322
- await runMiddleware(newContext, middlewares.slice(1));
323
- });
324
- };
325
- const middleware = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
326
- __proto__: null,
327
- runMiddleware
328
- }, Symbol.toStringTag, { value: "Module" }));
329
- const index$8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
330
- __proto__: null,
331
- encryption: index$9,
332
- json,
333
- middleware,
334
- schema,
335
- stream,
336
- transaction
337
- }, Symbol.toStringTag, { value: "Module" }));
338
- const OPTIONAL_CONTENT_TYPES = ["audit-log"];
339
- const isAttributeIgnorable = (diff2) => {
340
- return diff2.path.length === 3 && // Root property must be attributes
341
- diff2.path[0] === "attributes" && // Need a valid string attribute name
342
- typeof diff2.path[1] === "string" && // The diff must be on ignorable attribute properties
343
- ["private", "required", "configurable", "default"].includes(diff2.path[2]);
344
- };
345
- const isOptionalAdminType = (diff2) => {
346
- if ("value" in diff2 && fp.isObject(diff2.value)) {
347
- const name = diff2?.value?.info?.singularName;
348
- return OPTIONAL_CONTENT_TYPES.includes(name);
349
- }
350
- if ("values" in diff2 && fp.isArray(diff2.values) && fp.isObject(diff2.values[0])) {
351
- const name = diff2?.values[0]?.info?.singularName;
352
- return OPTIONAL_CONTENT_TYPES.includes(name);
353
- }
354
- return false;
355
- };
356
- const isIgnorableStrict = (diff2) => isAttributeIgnorable(diff2) || isOptionalAdminType(diff2);
357
- const strategies = {
358
- // No diffs
359
- exact(diffs) {
360
- return diffs;
361
- },
362
- // Strict: all content types must match except:
363
- // - the property within a content type is an ignorable one
364
- // - those that are (not transferrable and optionally available), for example EE features such as audit logs
365
- strict(diffs) {
366
- return fp.reject(isIgnorableStrict, diffs);
367
- }
368
- };
369
- const compareSchemas = (a, b, strategy) => {
370
- const diffs = diff(a, b);
371
- return strategies[strategy](diffs);
372
- };
373
- const SeverityKind = {
374
- FATAL: "fatal",
375
- ERROR: "error",
376
- SILLY: "silly"
377
- };
378
- class DataTransferError extends Error {
379
- origin;
380
- severity;
381
- details;
382
- constructor(origin2, severity, message, details) {
383
- super(message);
384
- this.origin = origin2;
385
- this.severity = severity;
386
- this.details = details ?? null;
387
- }
388
- }
389
- class TransferEngineError extends DataTransferError {
390
- constructor(severity, message, details) {
391
- super("engine", severity, message, details);
392
- }
393
- }
394
- class TransferEngineInitializationError extends TransferEngineError {
395
- constructor(message) {
396
- super(SeverityKind.FATAL, message, { step: "initialization" });
397
- }
398
- }
399
- class TransferEngineValidationError extends TransferEngineError {
400
- constructor(message, details) {
401
- super(SeverityKind.FATAL, message, { step: "validation", details });
402
- }
403
- }
404
- class TransferEngineTransferError extends TransferEngineError {
405
- constructor(message, details) {
406
- super(SeverityKind.FATAL, message, { step: "transfer", details });
407
- }
408
- }
409
- const errors = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
410
- __proto__: null,
411
- TransferEngineError,
412
- TransferEngineInitializationError,
413
- TransferEngineTransferError,
414
- TransferEngineValidationError
415
- }, Symbol.toStringTag, { value: "Module" }));
416
- const reject = (reason) => {
417
- throw new TransferEngineValidationError(`Invalid provider supplied. ${reason}`);
418
- };
419
- const validateProvider = (type, provider) => {
420
- if (!provider) {
421
- return reject(
422
- `Expected an instance of "${fp.capitalize(type)}Provider", but got "${typeof provider}" instead.`
423
- );
424
- }
425
- if (provider.type !== type) {
426
- return reject(
427
- `Expected the provider to be of type "${type}" but got "${provider.type}" instead.`
428
- );
429
- }
430
- };
431
- const createDiagnosticReporter = (options = {}) => {
432
- const { stackSize = -1 } = options;
433
- const emitter = new events.EventEmitter();
434
- const stack = [];
435
- const addListener = (event, listener) => {
436
- emitter.on(event, listener);
437
- };
438
- const isDiagnosticValid = (diagnostic) => {
439
- if (!diagnostic.kind || !diagnostic.details || !diagnostic.details.message) {
440
- return false;
441
- }
442
- return true;
443
- };
444
- return {
445
- stack: {
446
- get size() {
447
- return stack.length;
448
- },
449
- get items() {
450
- return stack;
451
- }
452
- },
453
- report(diagnostic) {
454
- if (!isDiagnosticValid(diagnostic)) {
455
- return this;
456
- }
457
- emitter.emit("diagnostic", diagnostic);
458
- emitter.emit(`diagnostic.${diagnostic.kind}`, diagnostic);
459
- if (stackSize !== -1 && stack.length >= stackSize) {
460
- stack.shift();
461
- }
462
- stack.push(diagnostic);
463
- return this;
464
- },
465
- onDiagnostic(listener) {
466
- addListener("diagnostic", listener);
467
- return this;
468
- },
469
- on(kind, listener) {
470
- addListener(`diagnostic.${kind}`, listener);
471
- return this;
472
- }
473
- };
474
- };
475
- class ProviderError extends DataTransferError {
476
- constructor(severity, message, details) {
477
- super("provider", severity, message, details);
478
- }
479
- }
480
- class ProviderInitializationError extends ProviderError {
481
- constructor(message) {
482
- super(SeverityKind.FATAL, message, { step: "initialization" });
483
- }
484
- }
485
- class ProviderValidationError extends ProviderError {
486
- constructor(message, details) {
487
- super(SeverityKind.SILLY, message, { step: "validation", details });
488
- }
489
- }
490
- class ProviderTransferError extends ProviderError {
491
- constructor(message, details) {
492
- super(SeverityKind.FATAL, message, { step: "transfer", details });
493
- }
494
- }
495
- const TRANSFER_STAGES = Object.freeze([
496
- "entities",
497
- "links",
498
- "assets",
499
- "schemas",
500
- "configuration"
501
- ]);
502
- const TransferGroupPresets = {
503
- content: {
504
- links: true,
505
- // Example: content includes the entire links stage
506
- entities: true
507
- // TODO: If we need to implement filtering on a running stage, it would be done like this, but we still need to implement it
508
- // [
509
- // // Example: content processes the entities stage, but filters individual entities
510
- // {
511
- // filter(data) {
512
- // return shouldIncludeThisData(data);
513
- // },
514
- // },
515
- // ],
516
- },
517
- files: {
518
- assets: true
519
- },
520
- config: {
521
- configuration: true
522
- }
523
- };
524
- const DEFAULT_VERSION_STRATEGY = "ignore";
525
- const DEFAULT_SCHEMA_STRATEGY = "strict";
526
- class TransferEngine {
527
- sourceProvider;
528
- destinationProvider;
529
- options;
530
- #metadata = {};
531
- #schema = {};
532
- // Progress of the current stage
533
- progress;
534
- diagnostics;
535
- #handlers = {
536
- schemaDiff: [],
537
- errors: {}
538
- };
539
- onSchemaDiff(handler) {
540
- this.#handlers?.schemaDiff?.push(handler);
541
- }
542
- addErrorHandler(handlerName, handler) {
543
- if (!this.#handlers.errors[handlerName]) {
544
- this.#handlers.errors[handlerName] = [];
545
- }
546
- this.#handlers.errors[handlerName]?.push(handler);
547
- }
548
- async attemptResolveError(error) {
549
- const context = {};
550
- if (error instanceof ProviderTransferError && error.details?.details.code) {
551
- const errorCode = error.details?.details.code;
552
- if (!this.#handlers.errors[errorCode]) {
553
- this.#handlers.errors[errorCode] = [];
554
- }
555
- await runMiddleware(context ?? {}, this.#handlers.errors[errorCode] ?? []);
556
- }
557
- return !!context.ignore;
558
- }
559
- // Save the currently open stream so that we can access it at any time
560
- #currentStream;
561
- constructor(sourceProvider, destinationProvider, options) {
562
- this.diagnostics = createDiagnosticReporter();
563
- validateProvider("source", sourceProvider);
564
- validateProvider("destination", destinationProvider);
565
- this.sourceProvider = sourceProvider;
566
- this.destinationProvider = destinationProvider;
567
- this.options = options;
568
- this.progress = { data: {}, stream: new stream$1.PassThrough({ objectMode: true }) };
569
- }
570
- /**
571
- * Report a fatal error and throw it
572
- */
573
- panic(error) {
574
- this.reportError(error, "fatal");
575
- throw error;
576
- }
577
- /**
578
- * Report an error diagnostic
579
- */
580
- reportError(error, severity) {
581
- this.diagnostics.report({
582
- kind: "error",
583
- details: {
584
- severity,
585
- createdAt: /* @__PURE__ */ new Date(),
586
- name: error.name,
587
- message: error.message,
588
- error
589
- }
590
- });
591
- }
592
- /**
593
- * Report a warning diagnostic
594
- */
595
- reportWarning(message, origin2) {
596
- this.diagnostics.report({
597
- kind: "warning",
598
- details: { createdAt: /* @__PURE__ */ new Date(), message, origin: origin2 }
599
- });
600
- }
601
- /**
602
- * Report an info diagnostic
603
- */
604
- reportInfo(message, params) {
605
- this.diagnostics.report({
606
- kind: "info",
607
- details: { createdAt: /* @__PURE__ */ new Date(), message, params }
608
- });
609
- }
610
- /**
611
- * Create and return a transform stream based on the given stage and options.
612
- *
613
- * Allowed transformations includes 'filter' and 'map'.
614
- */
615
- #createStageTransformStream(key, options = {}) {
616
- const { includeGlobal = true } = options;
617
- const { throttle } = this.options;
618
- const { global: globalTransforms, [key]: stageTransforms } = this.options?.transforms ?? {};
619
- let stream2 = new stream$1.PassThrough({ objectMode: true });
620
- const applyTransforms = (transforms = []) => {
621
- const chainTransforms = [];
622
- for (const transform of transforms) {
623
- if ("filter" in transform) {
624
- chainTransforms.push(filter(transform.filter));
625
- }
626
- if ("map" in transform) {
627
- chainTransforms.push(map(transform.map));
628
- }
629
- }
630
- if (chainTransforms.length) {
631
- stream2 = stream2.pipe(streamChain.chain(chainTransforms));
632
- }
633
- };
634
- if (includeGlobal) {
635
- applyTransforms(globalTransforms);
636
- }
637
- if (fp.isNumber(throttle) && throttle > 0) {
638
- stream2 = stream2.pipe(
639
- new stream$1.PassThrough({
640
- objectMode: true,
641
- async transform(data, _encoding, callback) {
642
- await new Promise((resolve) => {
643
- setTimeout(resolve, throttle);
644
- });
645
- callback(null, data);
646
- }
647
- })
648
- );
649
- }
650
- applyTransforms(stageTransforms);
651
- return stream2;
652
- }
653
- /**
654
- * Update the Engine's transfer progress data for a given stage.
655
- *
656
- * Providing aggregate options enable custom computation to get the size (bytes) or the aggregate key associated with the data
657
- */
658
- #updateTransferProgress(stage, data, aggregate) {
659
- if (!this.progress.data[stage]) {
660
- this.progress.data[stage] = { count: 0, bytes: 0, startTime: Date.now() };
661
- }
662
- const stageProgress = this.progress.data[stage];
663
- if (!stageProgress) {
664
- return;
665
- }
666
- const size = aggregate?.size?.(data) ?? JSON.stringify(data).length;
667
- const key = aggregate?.key?.(data);
668
- stageProgress.count += 1;
669
- stageProgress.bytes += size;
670
- if (key) {
671
- if (!stageProgress.aggregates) {
672
- stageProgress.aggregates = {};
673
- }
674
- const { aggregates } = stageProgress;
675
- if (!aggregates[key]) {
676
- aggregates[key] = { count: 0, bytes: 0 };
677
- }
678
- aggregates[key].count += 1;
679
- aggregates[key].bytes += size;
680
- }
681
- }
682
- /**
683
- * Create and return a PassThrough stream.
684
- *
685
- * Upon writing data into it, it'll update the Engine's transfer progress data and trigger stage update events.
686
- */
687
- #progressTracker(stage, aggregate) {
688
- return new stream$1.PassThrough({
689
- objectMode: true,
690
- transform: (data, _encoding, callback) => {
691
- this.#updateTransferProgress(stage, data, aggregate);
692
- this.#emitStageUpdate("progress", stage);
693
- callback(null, data);
694
- }
695
- });
696
- }
697
- /**
698
- * Shorthand method used to trigger transfer update events to every listeners
699
- */
700
- #emitTransferUpdate(type, payload) {
701
- this.progress.stream.emit(`transfer::${type}`, payload);
702
- }
703
- /**
704
- * Shorthand method used to trigger stage update events to every listeners
705
- */
706
- #emitStageUpdate(type, transferStage) {
707
- this.progress.stream.emit(`stage::${type}`, {
708
- data: this.progress.data,
709
- stage: transferStage
710
- });
711
- }
712
- /**
713
- * Run a version check between two strapi version (source and destination) using the strategy given to the engine during initialization.
714
- *
715
- * If there is a mismatch, throws a validation error.
716
- */
717
- #assertStrapiVersionIntegrity(sourceVersion, destinationVersion) {
718
- const strategy = this.options.versionStrategy || DEFAULT_VERSION_STRATEGY;
719
- const reject2 = () => {
720
- throw new TransferEngineValidationError(
721
- `The source and destination provide are targeting incompatible Strapi versions (using the "${strategy}" strategy). The source (${this.sourceProvider.name}) version is ${sourceVersion} and the destination (${this.destinationProvider.name}) version is ${destinationVersion}`,
722
- {
723
- check: "strapi.version",
724
- strategy,
725
- versions: { source: sourceVersion, destination: destinationVersion }
726
- }
727
- );
728
- };
729
- if (!sourceVersion || !destinationVersion || strategy === "ignore" || destinationVersion === sourceVersion) {
730
- return;
731
- }
732
- let diff2;
733
- try {
734
- diff2 = semver.diff(sourceVersion, destinationVersion);
735
- } catch {
736
- reject2();
737
- }
738
- if (!diff2) {
739
- return;
740
- }
741
- const validPatch = ["prelease", "build"];
742
- const validMinor = [...validPatch, "patch", "prepatch"];
743
- const validMajor = [...validMinor, "minor", "preminor"];
744
- if (strategy === "patch" && validPatch.includes(diff2)) {
745
- return;
746
- }
747
- if (strategy === "minor" && validMinor.includes(diff2)) {
748
- return;
749
- }
750
- if (strategy === "major" && validMajor.includes(diff2)) {
751
- return;
752
- }
753
- reject2();
754
- }
755
- /**
756
- * Run a check between two set of schemas (source and destination) using the strategy given to the engine during initialization.
757
- *
758
- * If there are differences and/or incompatibilities between source and destination schemas, then throw a validation error.
759
- */
760
- #assertSchemasMatching(sourceSchemas, destinationSchemas) {
761
- const strategy = this.options.schemaStrategy || DEFAULT_SCHEMA_STRATEGY;
762
- if (strategy === "ignore") {
763
- return;
764
- }
765
- const keys = fp.uniq(Object.keys(sourceSchemas).concat(Object.keys(destinationSchemas)));
766
- const diffs = {};
767
- keys.forEach((key) => {
768
- const sourceSchema = sourceSchemas[key];
769
- const destinationSchema = destinationSchemas[key];
770
- const schemaDiffs = compareSchemas(sourceSchema, destinationSchema, strategy);
771
- if (schemaDiffs.length) {
772
- diffs[key] = schemaDiffs;
773
- }
774
- });
775
- if (!fp.isEmpty(diffs)) {
776
- const formattedDiffs = Object.entries(diffs).map(([uid, ctDiffs]) => {
777
- let msg = `- ${uid}:${os.EOL}`;
778
- msg += ctDiffs.sort((a, b) => a.kind > b.kind ? -1 : 1).map((diff2) => {
779
- const path2 = diff2.path.join(".");
780
- if (diff2.kind === "added") {
781
- return `${path2} exists in destination schema but not in source schema and the data will not be transferred.`;
782
- }
783
- if (diff2.kind === "deleted") {
784
- return `${path2} exists in source schema but not in destination schema and the data will not be transferred.`;
785
- }
786
- if (diff2.kind === "modified") {
787
- if (diff2.types[0] === diff2.types[1]) {
788
- return `Schema value changed at "${path2}": "${diff2.values[0]}" (${diff2.types[0]}) => "${diff2.values[1]}" (${diff2.types[1]})`;
789
- }
790
- return `Schema has differing data types at "${path2}": "${diff2.values[0]}" (${diff2.types[0]}) => "${diff2.values[1]}" (${diff2.types[1]})`;
791
- }
792
- throw new TransferEngineValidationError(`Invalid diff found for "${uid}"`, {
793
- check: `schema on ${uid}`
794
- });
795
- }).map((line) => ` - ${line}`).join(os.EOL);
796
- return msg;
797
- }).join(os.EOL);
798
- throw new TransferEngineValidationError(
799
- `Invalid schema changes detected during integrity checks (using the ${strategy} strategy). Please find a summary of the changes below:
800
- ${formattedDiffs}`,
801
- {
802
- check: "schema.changes",
803
- strategy,
804
- diffs
805
- }
806
- );
807
- }
808
- }
809
- shouldSkipStage(stage) {
810
- const { exclude, only } = this.options;
811
- if (stage === "schemas") {
812
- return false;
813
- }
814
- let included = fp.isEmpty(only);
815
- if (only && only.length > 0) {
816
- included = only.some((transferGroup) => {
817
- return TransferGroupPresets[transferGroup][stage];
818
- });
819
- }
820
- if (exclude && exclude.length > 0) {
821
- if (included) {
822
- included = !exclude.some((transferGroup) => {
823
- return TransferGroupPresets[transferGroup][stage];
824
- });
825
- }
826
- }
827
- return !included;
828
- }
829
- async #transferStage(options) {
830
- const { stage, source, destination, transform, tracker } = options;
831
- const updateEndTime = () => {
832
- const stageData = this.progress.data[stage];
833
- if (stageData) {
834
- stageData.endTime = Date.now();
835
- }
836
- };
837
- if (!source || !destination || this.shouldSkipStage(stage)) {
838
- const results = await Promise.allSettled(
839
- [source, destination].map((stream2) => {
840
- if (!stream2 || stream2.destroyed) {
841
- return Promise.resolve();
842
- }
843
- return new Promise((resolve, reject2) => {
844
- stream2.on("close", resolve).on("error", reject2).destroy();
845
- });
846
- })
847
- );
848
- results.forEach((state) => {
849
- if (state.status === "rejected") {
850
- this.reportWarning(state.reason, `transfer(${stage})`);
851
- }
852
- });
853
- this.#emitStageUpdate("skip", stage);
854
- return;
855
- }
856
- this.#emitStageUpdate("start", stage);
857
- await new Promise((resolve, reject2) => {
858
- let stream2 = source;
859
- if (transform) {
860
- stream2 = stream2.pipe(transform);
861
- }
862
- if (tracker) {
863
- stream2 = stream2.pipe(tracker);
864
- }
865
- this.#currentStream = stream2.pipe(destination).on("error", (e) => {
866
- updateEndTime();
867
- this.#emitStageUpdate("error", stage);
868
- this.reportError(e, "error");
869
- destination.destroy(e);
870
- reject2(e);
871
- }).on("close", () => {
872
- this.#currentStream = void 0;
873
- updateEndTime();
874
- resolve();
875
- });
876
- });
877
- this.#emitStageUpdate("finish", stage);
878
- }
879
- // Cause an ongoing transfer to abort gracefully
880
- async abortTransfer() {
881
- const err = new TransferEngineError("fatal", "Transfer aborted.");
882
- if (!this.#currentStream) {
883
- throw err;
884
- }
885
- this.#currentStream.destroy(err);
886
- }
887
- async init() {
888
- await this.#resolveProviderResource();
889
- const { source: sourceMetadata } = this.#metadata;
890
- if (sourceMetadata) {
891
- this.destinationProvider.setMetadata?.("source", sourceMetadata);
892
- }
893
- }
894
- /**
895
- * Run the bootstrap method in both source and destination providers
896
- */
897
- async bootstrap() {
898
- const results = await Promise.allSettled([
899
- this.sourceProvider.bootstrap?.(),
900
- this.destinationProvider.bootstrap?.()
901
- ]);
902
- results.forEach((result) => {
903
- if (result.status === "rejected") {
904
- this.panic(result.reason);
905
- }
906
- });
907
- }
908
- /**
909
- * Run the close method in both source and destination providers
910
- */
911
- async close() {
912
- const results = await Promise.allSettled([
913
- this.sourceProvider.close?.(),
914
- this.destinationProvider.close?.()
915
- ]);
916
- results.forEach((result) => {
917
- if (result.status === "rejected") {
918
- this.panic(result.reason);
919
- }
920
- });
921
- }
922
- async #resolveProviderResource() {
923
- const sourceMetadata = await this.sourceProvider.getMetadata();
924
- const destinationMetadata = await this.destinationProvider.getMetadata();
925
- if (sourceMetadata) {
926
- this.#metadata.source = sourceMetadata;
927
- }
928
- if (destinationMetadata) {
929
- this.#metadata.destination = destinationMetadata;
930
- }
931
- }
932
- async #getSchemas() {
933
- if (!this.#schema.source) {
934
- this.#schema.source = await this.sourceProvider.getSchemas?.();
935
- }
936
- if (!this.#schema.destination) {
937
- this.#schema.destination = await this.destinationProvider.getSchemas?.();
938
- }
939
- return {
940
- sourceSchemas: this.#schema.source,
941
- destinationSchemas: this.#schema.destination
942
- };
943
- }
944
- async integrityCheck() {
945
- const sourceMetadata = await this.sourceProvider.getMetadata();
946
- const destinationMetadata = await this.destinationProvider.getMetadata();
947
- if (sourceMetadata && destinationMetadata) {
948
- this.#assertStrapiVersionIntegrity(
949
- sourceMetadata?.strapi?.version,
950
- destinationMetadata?.strapi?.version
951
- );
952
- }
953
- const { sourceSchemas, destinationSchemas } = await this.#getSchemas();
954
- try {
955
- if (sourceSchemas && destinationSchemas) {
956
- this.#assertSchemasMatching(sourceSchemas, destinationSchemas);
957
- }
958
- } catch (error) {
959
- if (error instanceof TransferEngineValidationError && error.details?.details?.diffs) {
960
- const schemaDiffs = error.details?.details?.diffs;
961
- const context = {
962
- ignoredDiffs: {},
963
- diffs: schemaDiffs,
964
- source: this.sourceProvider,
965
- destination: this.destinationProvider
966
- };
967
- if (fp.isEmpty(this.#handlers.schemaDiff)) {
968
- throw error;
969
- }
970
- await runMiddleware(
971
- context,
972
- this.#handlers.schemaDiff
973
- );
974
- const unresolvedDiffs = diff(context.diffs, context.ignoredDiffs);
975
- if (unresolvedDiffs.length) {
976
- this.panic(
977
- new TransferEngineValidationError("Unresolved differences in schema", {
978
- check: "schema.changes",
979
- unresolvedDiffs
980
- })
981
- );
982
- }
983
- return;
984
- }
985
- throw error;
986
- }
987
- }
988
- async transfer() {
989
- this.progress.data = {};
990
- try {
991
- this.#emitTransferUpdate("init");
992
- await this.bootstrap();
993
- await this.init();
994
- await this.integrityCheck();
995
- this.#emitTransferUpdate("start");
996
- await this.beforeTransfer();
997
- await this.transferSchemas();
998
- await this.transferEntities();
999
- await this.transferAssets();
1000
- await this.transferLinks();
1001
- await this.transferConfiguration();
1002
- await this.close();
1003
- this.#emitTransferUpdate("finish");
1004
- } catch (e) {
1005
- this.#emitTransferUpdate("error", { error: e });
1006
- const lastDiagnostic = fp.last(this.diagnostics.stack.items);
1007
- if (e instanceof Error && (!lastDiagnostic || lastDiagnostic.kind !== "error" || lastDiagnostic.details.error !== e)) {
1008
- this.reportError(e, e.severity || "fatal");
1009
- }
1010
- await this.destinationProvider.rollback?.(e);
1011
- throw e;
1012
- }
1013
- return {
1014
- source: this.sourceProvider.results,
1015
- destination: this.destinationProvider.results,
1016
- engine: this.progress.data
1017
- };
1018
- }
1019
- async beforeTransfer() {
1020
- const runWithDiagnostic = async (provider) => {
1021
- try {
1022
- await provider.beforeTransfer?.();
1023
- } catch (error) {
1024
- if (error instanceof Error) {
1025
- const resolved = await this.attemptResolveError(error);
1026
- if (resolved) {
1027
- return;
1028
- }
1029
- this.panic(error);
1030
- } else {
1031
- this.panic(
1032
- new Error(`Unknwon error when executing "beforeTransfer" on the ${origin} provider`)
1033
- );
1034
- }
1035
- }
1036
- };
1037
- await runWithDiagnostic(this.sourceProvider);
1038
- await runWithDiagnostic(this.destinationProvider);
1039
- }
1040
- async transferSchemas() {
1041
- const stage = "schemas";
1042
- if (this.shouldSkipStage(stage)) {
1043
- return;
1044
- }
1045
- const source = await this.sourceProvider.createSchemasReadStream?.();
1046
- const destination = await this.destinationProvider.createSchemasWriteStream?.();
1047
- const transform = this.#createStageTransformStream(stage);
1048
- const tracker = this.#progressTracker(stage, {
1049
- key: (value) => value.modelType
1050
- });
1051
- await this.#transferStage({ stage, source, destination, transform, tracker });
1052
- }
1053
- async transferEntities() {
1054
- const stage = "entities";
1055
- if (this.shouldSkipStage(stage)) {
1056
- return;
1057
- }
1058
- const source = await this.sourceProvider.createEntitiesReadStream?.();
1059
- const destination = await this.destinationProvider.createEntitiesWriteStream?.();
1060
- const transform = streamChain.chain([
1061
- this.#createStageTransformStream(stage),
1062
- new stream$1.Transform({
1063
- objectMode: true,
1064
- transform: async (entity2, _encoding, callback) => {
1065
- const { destinationSchemas: schemas } = await this.#getSchemas();
1066
- if (!schemas) {
1067
- return callback(null, entity2);
1068
- }
1069
- const availableContentTypes = Object.entries(schemas).filter(([, schema2]) => schema2.modelType === "contentType").map(([uid]) => uid);
1070
- if (!availableContentTypes.includes(entity2.type)) {
1071
- return callback(null, void 0);
1072
- }
1073
- const { type, data } = entity2;
1074
- const attributes = schemas[type].attributes;
1075
- const attributesToKeep = Object.keys(attributes).concat("documentId");
1076
- const updatedEntity = fp.set("data", fp.pick(attributesToKeep, data), entity2);
1077
- callback(null, updatedEntity);
1078
- }
1079
- })
1080
- ]);
1081
- const tracker = this.#progressTracker(stage, { key: (value) => value.type });
1082
- await this.#transferStage({ stage, source, destination, transform, tracker });
1083
- }
1084
- async transferLinks() {
1085
- const stage = "links";
1086
- if (this.shouldSkipStage(stage)) {
1087
- return;
1088
- }
1089
- const source = await this.sourceProvider.createLinksReadStream?.();
1090
- const destination = await this.destinationProvider.createLinksWriteStream?.();
1091
- const transform = streamChain.chain([
1092
- this.#createStageTransformStream(stage),
1093
- new stream$1.Transform({
1094
- objectMode: true,
1095
- transform: async (link2, _encoding, callback) => {
1096
- const { destinationSchemas: schemas } = await this.#getSchemas();
1097
- if (!schemas) {
1098
- return callback(null, link2);
1099
- }
1100
- const availableContentTypes = Object.keys(schemas);
1101
- const isValidType = (uid) => availableContentTypes.includes(uid);
1102
- if (!isValidType(link2.left.type) || !isValidType(link2.right.type)) {
1103
- return callback(null, void 0);
1104
- }
1105
- callback(null, link2);
1106
- }
1107
- })
1108
- ]);
1109
- const tracker = this.#progressTracker(stage);
1110
- await this.#transferStage({ stage, source, destination, transform, tracker });
1111
- }
1112
- async transferAssets() {
1113
- const stage = "assets";
1114
- if (this.shouldSkipStage(stage)) {
1115
- return;
1116
- }
1117
- const source = await this.sourceProvider.createAssetsReadStream?.();
1118
- const destination = await this.destinationProvider.createAssetsWriteStream?.();
1119
- const transform = this.#createStageTransformStream(stage);
1120
- const tracker = this.#progressTracker(stage, {
1121
- size: (value) => value.stats.size,
1122
- key: (value) => path.extname(value.filename) || "No extension"
1123
- });
1124
- await this.#transferStage({ stage, source, destination, transform, tracker });
1125
- }
1126
- async transferConfiguration() {
1127
- const stage = "configuration";
1128
- if (this.shouldSkipStage(stage)) {
1129
- return;
1130
- }
1131
- const source = await this.sourceProvider.createConfigurationReadStream?.();
1132
- const destination = await this.destinationProvider.createConfigurationWriteStream?.();
1133
- const transform = this.#createStageTransformStream(stage);
1134
- const tracker = this.#progressTracker(stage);
1135
- await this.#transferStage({ stage, source, destination, transform, tracker });
1136
- }
1137
- }
1138
- const createTransferEngine = (sourceProvider, destinationProvider, options) => {
1139
- return new TransferEngine(sourceProvider, destinationProvider, options);
1140
- };
1141
- const index$7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1142
- __proto__: null,
1143
- DEFAULT_SCHEMA_STRATEGY,
1144
- DEFAULT_VERSION_STRATEGY,
1145
- TRANSFER_STAGES,
1146
- TransferGroupPresets,
1147
- createTransferEngine,
1148
- errors
1149
- }, Symbol.toStringTag, { value: "Module" }));
1150
- const isDialectMySQL = () => strapi.db?.dialect.client === "mysql";
1151
- function omitComponentData(contentType, data) {
1152
- const { attributes } = contentType;
1153
- const componentAttributes = Object.keys(attributes).filter(
1154
- (attributeName) => utils.contentTypes.isComponentAttribute(attributes[attributeName])
1155
- );
1156
- return fp.omit(componentAttributes, data);
1157
- }
1158
- const createComponents = async (uid, data) => {
1159
- const { attributes = {} } = strapi.getModel(uid);
1160
- const componentBody = {};
1161
- const attributeNames = Object.keys(attributes);
1162
- for (const attributeName of attributeNames) {
1163
- const attribute = attributes[attributeName];
1164
- if (!fp.has(attributeName, data) || !utils.contentTypes.isComponentAttribute(attribute)) {
1165
- continue;
1166
- }
1167
- if (attribute.type === "component") {
1168
- const { component: componentUID, repeatable = false } = attribute;
1169
- const componentValue = data[attributeName];
1170
- if (componentValue === null) {
1171
- continue;
1172
- }
1173
- if (repeatable === true) {
1174
- if (!Array.isArray(componentValue)) {
1175
- throw new Error("Expected an array to create repeatable component");
1176
- }
1177
- const components = await utils.async.map(
1178
- componentValue,
1179
- (value) => createComponent(componentUID, value),
1180
- { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }
1181
- );
1182
- componentBody[attributeName] = components.map(({ id }) => {
1183
- return {
1184
- id,
1185
- __pivot: {
1186
- field: attributeName,
1187
- component_type: componentUID
1188
- }
1189
- };
1190
- });
1191
- } else {
1192
- const component = await createComponent(
1193
- componentUID,
1194
- componentValue
1195
- );
1196
- componentBody[attributeName] = {
1197
- id: component.id,
1198
- __pivot: {
1199
- field: attributeName,
1200
- component_type: componentUID
1201
- }
1202
- };
1203
- }
1204
- continue;
1205
- }
1206
- if (attribute.type === "dynamiczone") {
1207
- const dynamiczoneValues = data[attributeName];
1208
- if (!Array.isArray(dynamiczoneValues)) {
1209
- throw new Error("Expected an array to create repeatable component");
1210
- }
1211
- const createDynamicZoneComponents = async (value) => {
1212
- const { id } = await createComponent(value.__component, value);
1213
- return {
1214
- id,
1215
- __component: value.__component,
1216
- __pivot: {
1217
- field: attributeName
1218
- }
1219
- };
1220
- };
1221
- componentBody[attributeName] = await utils.async.map(
1222
- dynamiczoneValues,
1223
- createDynamicZoneComponents,
1224
- { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }
1225
- );
1226
- continue;
1227
- }
1228
- }
1229
- return componentBody;
1230
- };
1231
- const getComponents = async (uid, entity2) => {
1232
- const componentAttributes = utils.contentTypes.getComponentAttributes(strapi.getModel(uid));
1233
- if (___default.default.isEmpty(componentAttributes)) {
1234
- return {};
1235
- }
1236
- return strapi.db.query(uid).load(entity2, componentAttributes);
1237
- };
1238
- const deleteComponents = async (uid, entityToDelete, { loadComponents = true } = {}) => {
1239
- const { attributes = {} } = strapi.getModel(uid);
1240
- const attributeNames = Object.keys(attributes);
1241
- for (const attributeName of attributeNames) {
1242
- const attribute = attributes[attributeName];
1243
- if (attribute.type === "component" || attribute.type === "dynamiczone") {
1244
- let value;
1245
- if (loadComponents) {
1246
- value = await strapi.db.query(uid).load(entityToDelete, attributeName);
1247
- } else {
1248
- value = entityToDelete[attributeName];
1249
- }
1250
- if (!value) {
1251
- continue;
1252
- }
1253
- if (attribute.type === "component") {
1254
- const { component: componentUID } = attribute;
1255
- await utils.async.map(
1256
- ___default.default.castArray(value),
1257
- (subValue) => deleteComponent(componentUID, subValue),
1258
- {
1259
- concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity
1260
- }
1261
- );
1262
- } else {
1263
- await utils.async.map(
1264
- ___default.default.castArray(value),
1265
- (subValue) => deleteComponent(subValue.__component, subValue),
1266
- { concurrency: isDialectMySQL() && !strapi.db?.inTransaction() ? 1 : Infinity }
1267
- );
1268
- }
1269
- continue;
1270
- }
1271
- }
1272
- };
1273
- const createComponent = async (uid, data) => {
1274
- const model = strapi.getModel(uid);
1275
- const componentData = await createComponents(uid, data);
1276
- const transform = fp.pipe(
1277
- // Make sure we don't save the component with a pre-defined ID
1278
- fp.omit("id"),
1279
- // Remove the component data from the original data object ...
1280
- (payload) => omitComponentData(model, payload),
1281
- // ... and assign the newly created component instead
1282
- fp.assign(componentData)
1283
- );
1284
- return strapi.db.query(uid).create({ data: transform(data) });
1285
- };
1286
- const deleteComponent = async (uid, componentToDelete) => {
1287
- await deleteComponents(uid, componentToDelete);
1288
- await strapi.db.query(uid).delete({ where: { id: componentToDelete.id } });
1289
- };
1290
- const resolveComponentUID = ({
1291
- paths,
1292
- strapi: strapi2,
1293
- data,
1294
- contentType
1295
- }) => {
1296
- let value = data;
1297
- let cType = contentType;
1298
- for (const path2 of paths) {
1299
- value = fp.get(path2, value);
1300
- if (typeof cType === "function") {
1301
- cType = cType(value);
1302
- }
1303
- if (path2 in cType.attributes) {
1304
- const attribute = cType.attributes[path2];
1305
- if (attribute.type === "component") {
1306
- cType = strapi2.getModel(attribute.component);
1307
- }
1308
- if (attribute.type === "dynamiczone") {
1309
- cType = ({ __component }) => strapi2.getModel(__component);
1310
- }
1311
- }
1312
- }
1313
- if ("uid" in cType) {
1314
- return cType.uid;
1315
- }
1316
- return void 0;
1317
- };
1318
- const sanitizeComponentLikeAttributes = (model, data) => {
1319
- const { attributes } = model;
1320
- const componentLikeAttributesKey = Object.entries(attributes).filter(([, attribute]) => attribute.type === "component" || attribute.type === "dynamiczone").map(([key]) => key);
1321
- return fp.omit(componentLikeAttributesKey, data);
1322
- };
1323
- const omitInvalidCreationAttributes$1 = fp.omit(["id"]);
1324
- const createEntityQuery = (strapi2) => {
1325
- const components = {
1326
- async assignToEntity(uid, data) {
1327
- const model = strapi2.getModel(uid);
1328
- const entityComponents = await createComponents(uid, data);
1329
- const dataWithoutComponents = sanitizeComponentLikeAttributes(model, data);
1330
- return fp.assign(entityComponents, dataWithoutComponents);
1331
- },
1332
- async get(uid, entity2) {
1333
- return getComponents(uid, entity2);
1334
- },
1335
- delete(uid, componentsToDelete) {
1336
- return deleteComponents(uid, componentsToDelete, {
1337
- loadComponents: false
1338
- });
1339
- }
1340
- };
1341
- const query = (uid) => {
1342
- const create = async (params) => {
1343
- const dataWithComponents = await components.assignToEntity(uid, params.data);
1344
- const sanitizedData = omitInvalidCreationAttributes$1(dataWithComponents);
1345
- return strapi2.db.query(uid).create({ ...params, data: sanitizedData });
1346
- };
1347
- const createMany = async (params) => {
1348
- return Promise.resolve(params.data).then(fp.map((data) => components.assignToEntity(uid, data))).then(fp.map(omitInvalidCreationAttributes$1)).then((data) => strapi2.db.query(uid).createMany({ ...params, data }));
1349
- };
1350
- const deleteMany = async (params) => {
1351
- const entitiesToDelete = await strapi2.db.query(uid).findMany(params ?? {});
1352
- if (!entitiesToDelete.length) {
1353
- return null;
1354
- }
1355
- const componentsToDelete = await Promise.all(
1356
- entitiesToDelete.map((entityToDelete) => components.get(uid, entityToDelete))
1357
- );
1358
- const deletedEntities = await strapi2.db.query(uid).deleteMany(params);
1359
- await Promise.all(componentsToDelete.map((compos) => components.delete(uid, compos)));
1360
- return deletedEntities;
1361
- };
1362
- const getDeepPopulateComponentLikeQuery = (contentType, params = { select: "*" }) => {
1363
- const { attributes } = contentType;
1364
- const populate = {};
1365
- const entries = Object.entries(attributes);
1366
- for (const [key, attribute] of entries) {
1367
- if (attribute.type === "component") {
1368
- const component = strapi2.getModel(attribute.component);
1369
- const subPopulate = getDeepPopulateComponentLikeQuery(component, params);
1370
- if ((fp.isArray(subPopulate) || fp.isObject(subPopulate)) && fp.size(subPopulate) > 0) {
1371
- populate[key] = { ...params, populate: subPopulate };
1372
- }
1373
- if (fp.isArray(subPopulate) && fp.isEmpty(subPopulate)) {
1374
- populate[key] = { ...params };
1375
- }
1376
- }
1377
- if (attribute.type === "dynamiczone") {
1378
- const { components: componentsUID } = attribute;
1379
- const on = {};
1380
- for (const componentUID of componentsUID) {
1381
- const component = strapi2.getModel(componentUID);
1382
- const subPopulate = getDeepPopulateComponentLikeQuery(component, params);
1383
- if ((fp.isArray(subPopulate) || fp.isObject(subPopulate)) && fp.size(subPopulate) > 0) {
1384
- on[componentUID] = { ...params, populate: subPopulate };
1385
- }
1386
- if (fp.isArray(subPopulate) && fp.isEmpty(subPopulate)) {
1387
- on[componentUID] = { ...params };
1388
- }
1389
- }
1390
- populate[key] = fp.size(on) > 0 ? { on } : true;
1391
- }
1392
- }
1393
- const values = Object.values(populate);
1394
- if (values.every((value) => value === true)) {
1395
- return Object.keys(populate);
1396
- }
1397
- return populate;
1398
- };
1399
- return {
1400
- create,
1401
- createMany,
1402
- deleteMany,
1403
- getDeepPopulateComponentLikeQuery,
1404
- get deepPopulateComponentLikeQuery() {
1405
- const contentType = strapi2.getModel(uid);
1406
- return getDeepPopulateComponentLikeQuery(contentType);
1407
- }
1408
- };
1409
- };
1410
- return query;
1411
- };
1412
- const entity = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1413
- __proto__: null,
1414
- createEntityQuery
1415
- }, Symbol.toStringTag, { value: "Module" }));
1416
- const createLinkQuery = (strapi2, trx) => {
1417
- const query = () => {
1418
- const { connection } = strapi2.db;
1419
- const addSchema = (tableName) => {
1420
- const schemaName = connection.client.connectionSettings.schema;
1421
- return schemaName ? `${schemaName}.${tableName}` : tableName;
1422
- };
1423
- async function* generateAllForAttribute(uid, fieldName) {
1424
- const metadata = strapi2.db.metadata.get(uid);
1425
- if (!metadata) {
1426
- throw new Error(`No metadata found for ${uid}`);
1427
- }
1428
- const attributes = filterValidRelationalAttributes(metadata.attributes);
1429
- if (!(fieldName in attributes)) {
1430
- throw new Error(`${fieldName} is not a valid relational attribute name`);
1431
- }
1432
- const attribute = attributes[fieldName];
1433
- const kind = getLinkKind(attribute, uid);
1434
- const { relation, target } = attribute;
1435
- if (attribute.joinColumn) {
1436
- const joinColumnName = attribute.joinColumn.name;
1437
- const qb = connection.queryBuilder().select("id", joinColumnName).from(addSchema(metadata.tableName));
1438
- if (trx) {
1439
- qb.transacting(trx);
1440
- }
1441
- const entries = await qb;
1442
- for (const entry of entries) {
1443
- const ref = entry[joinColumnName];
1444
- if (ref !== null) {
1445
- yield {
1446
- kind,
1447
- relation,
1448
- left: { type: uid, ref: entry.id, field: fieldName },
1449
- right: { type: target, ref }
1450
- };
1451
- }
1452
- }
1453
- }
1454
- if (attribute.joinTable) {
1455
- const {
1456
- name,
1457
- joinColumn,
1458
- inverseJoinColumn,
1459
- orderColumnName,
1460
- morphColumn,
1461
- inverseOrderColumnName
1462
- } = attribute.joinTable;
1463
- const qb = connection.queryBuilder().from(addSchema(name));
1464
- const columns = {
1465
- left: { ref: null },
1466
- right: { ref: null }
1467
- };
1468
- const left = { type: uid, field: fieldName };
1469
- const right = {};
1470
- if (kind === "relation.basic" || kind === "relation.circular") {
1471
- right.type = attribute.target;
1472
- right.field = attribute.inversedBy;
1473
- columns.left.ref = joinColumn.name;
1474
- columns.right.ref = inverseJoinColumn.name;
1475
- if (orderColumnName) {
1476
- columns.left.order = orderColumnName;
1477
- }
1478
- if (inverseOrderColumnName) {
1479
- columns.right.order = inverseOrderColumnName;
1480
- }
1481
- }
1482
- if (kind === "relation.morph") {
1483
- columns.left.ref = joinColumn.name;
1484
- columns.right.ref = morphColumn.idColumn.name;
1485
- columns.right.type = morphColumn.typeColumn.name;
1486
- columns.right.field = "field";
1487
- columns.right.order = "order";
1488
- }
1489
- const validColumns = [
1490
- // Left
1491
- columns.left.ref,
1492
- columns.left.order,
1493
- // Right
1494
- columns.right.ref,
1495
- columns.right.type,
1496
- columns.right.field,
1497
- columns.right.order
1498
- ].filter((column) => !fp.isNil(column));
1499
- qb.select(validColumns);
1500
- if (trx) {
1501
- qb.transacting(trx);
1502
- }
1503
- const entries = await qb;
1504
- for (const entry of entries) {
1505
- if (columns.left.ref) {
1506
- left.ref = entry[columns.left.ref];
1507
- }
1508
- if (columns.right.ref) {
1509
- right.ref = entry[columns.right.ref];
1510
- }
1511
- if (columns.left.order) {
1512
- left.pos = entry[columns.left.order];
1513
- }
1514
- if (columns.right.order) {
1515
- right.pos = entry[columns.right.order];
1516
- }
1517
- if (columns.right.type) {
1518
- right.type = entry[columns.right.type];
1519
- }
1520
- if (columns.right.field) {
1521
- right.field = entry[columns.right.field];
1522
- }
1523
- const link2 = {
1524
- kind,
1525
- relation,
1526
- left: fp.clone(left),
1527
- right: fp.clone(right)
1528
- };
1529
- yield link2;
1530
- }
1531
- }
1532
- if (attribute.morphColumn) {
1533
- const { typeColumn, idColumn } = attribute.morphColumn;
1534
- const qb = connection.queryBuilder().select("id", typeColumn.name, idColumn.name).from(addSchema(metadata.tableName)).whereNotNull(typeColumn.name).whereNotNull(idColumn.name);
1535
- if (trx) {
1536
- qb.transacting(trx);
1537
- }
1538
- const entries = await qb;
1539
- for (const entry of entries) {
1540
- const ref = entry[idColumn.name];
1541
- yield {
1542
- kind,
1543
- relation,
1544
- left: { type: uid, ref: entry.id, field: fieldName },
1545
- right: { type: entry[typeColumn.name], ref }
1546
- };
1547
- }
1548
- }
1549
- }
1550
- async function* generateAll(uid) {
1551
- const metadata = strapi2.db.metadata.get(uid);
1552
- if (!metadata) {
1553
- throw new Error(`No metadata found for ${uid}`);
1554
- }
1555
- const attributes = filterValidRelationalAttributes(metadata.attributes);
1556
- for (const fieldName of Object.keys(attributes)) {
1557
- for await (const link2 of generateAllForAttribute(uid, fieldName)) {
1558
- yield link2;
1559
- }
1560
- }
1561
- }
1562
- const insert = async (link2) => {
1563
- const { kind, left, right } = link2;
1564
- const metadata = strapi2.db.metadata.get(left.type);
1565
- const attribute = metadata.attributes[left.field];
1566
- const payload = {};
1567
- if (!attribute) {
1568
- return;
1569
- }
1570
- if (attribute.type !== "relation") {
1571
- throw new Error(`Attribute ${left.field} is not a relation`);
1572
- }
1573
- if ("joinColumn" in attribute && attribute.joinColumn) {
1574
- const joinColumnName = attribute.joinColumn.name;
1575
- const qb = connection(addSchema(metadata.tableName)).where("id", left.ref).update({ [joinColumnName]: right.ref });
1576
- if (trx) {
1577
- qb.transacting(trx);
1578
- }
1579
- await qb;
1580
- }
1581
- if ("joinTable" in attribute && attribute.joinTable) {
1582
- const { joinTable } = attribute;
1583
- if (joinTable.joinColumn) {
1584
- Object.assign(payload, { [joinTable.joinColumn.name]: left.ref });
1585
- }
1586
- const assignInverseColumn = () => {
1587
- if ("inverseJoinColumn" in joinTable && joinTable.inverseJoinColumn) {
1588
- Object.assign(payload, {
1589
- [joinTable.inverseJoinColumn.name]: right.ref
1590
- });
1591
- }
1592
- };
1593
- const assignOrderColumns = () => {
1594
- if ("orderColumnName" in joinTable && joinTable.orderColumnName) {
1595
- Object.assign(payload, { [joinTable.orderColumnName]: left.pos ?? null });
1596
- }
1597
- if ("inverseOrderColumnName" in joinTable && joinTable.inverseOrderColumnName) {
1598
- Object.assign(payload, { [joinTable.inverseOrderColumnName]: right.pos ?? null });
1599
- }
1600
- };
1601
- const assignMorphColumns = () => {
1602
- if ("morphColumn" in joinTable && joinTable.morphColumn) {
1603
- const { idColumn, typeColumn } = joinTable.morphColumn ?? {};
1604
- if (idColumn) {
1605
- Object.assign(payload, { [idColumn.name]: right.ref });
1606
- }
1607
- if (typeColumn) {
1608
- Object.assign(payload, { [typeColumn.name]: right.type });
1609
- }
1610
- Object.assign(payload, { order: right.pos ?? null, field: right.field ?? null });
1611
- }
1612
- };
1613
- if (kind === "relation.basic" || kind === "relation.circular") {
1614
- assignInverseColumn();
1615
- }
1616
- if (kind === "relation.morph") {
1617
- assignMorphColumns();
1618
- }
1619
- assignOrderColumns();
1620
- const qb = connection.insert(payload).into(addSchema(joinTable.name));
1621
- if (trx) {
1622
- await trx.transaction(async (nestedTrx) => {
1623
- await qb.transacting(nestedTrx);
1624
- });
1625
- }
1626
- }
1627
- if ("morphColumn" in attribute && attribute.morphColumn) {
1628
- const { morphColumn } = attribute;
1629
- const qb = connection(addSchema(metadata.tableName)).where("id", left.ref).update({
1630
- [morphColumn.idColumn.name]: right.ref,
1631
- [morphColumn.typeColumn.name]: right.type
1632
- });
1633
- if (trx) {
1634
- qb.transacting(trx);
1635
- }
1636
- await qb;
1637
- }
1638
- };
1639
- return { generateAll, generateAllForAttribute, insert };
1640
- };
1641
- return query;
1642
- };
1643
- const filterValidRelationalAttributes = (attributes) => {
1644
- const isOwner = (attribute) => {
1645
- return attribute.owner || !attribute.mappedBy && !attribute.morphBy;
1646
- };
1647
- const isComponentLike = (attribute) => attribute.joinTable?.name.endsWith("_cmps");
1648
- return Object.entries(attributes).filter(([, attribute]) => {
1649
- return attribute.type === "relation" && isOwner(attribute) && !isComponentLike(attribute);
1650
- }).reduce((acc, [key, attribute]) => ({ ...acc, [key]: attribute }), {});
1651
- };
1652
- const getLinkKind = (attribute, uid) => {
1653
- if (attribute.relation.startsWith("morph")) {
1654
- return "relation.morph";
1655
- }
1656
- if (attribute.target === uid) {
1657
- return "relation.circular";
1658
- }
1659
- return "relation.basic";
1660
- };
1661
- const link = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1662
- __proto__: null,
1663
- createLinkQuery,
1664
- filterValidRelationalAttributes
1665
- }, Symbol.toStringTag, { value: "Module" }));
1666
- const index$6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
1667
- __proto__: null,
1668
- entity,
1669
- link
1670
- }, Symbol.toStringTag, { value: "Module" }));
1671
- const createEntitiesWriteStream = (options) => {
1672
- const { strapi: strapi2, updateMappingTable, transaction: transaction2 } = options;
1673
- const query = createEntityQuery(strapi2);
1674
- return new stream$1.Writable({
1675
- objectMode: true,
1676
- async write(entity2, _encoding, callback) {
1677
- await transaction2?.attach(async () => {
1678
- const { type, id, data } = entity2;
1679
- const { create, getDeepPopulateComponentLikeQuery } = query(type);
1680
- const contentType = strapi2.getModel(type);
1681
- try {
1682
- const created = await create({
1683
- data,
1684
- populate: getDeepPopulateComponentLikeQuery(contentType, { select: "id" }),
1685
- select: "id"
1686
- });
1687
- const diffs = diff(data, created);
1688
- updateMappingTable(type, id, created.id);
1689
- diffs.forEach((diff2) => {
1690
- if (diff2.kind === "modified" && fp.last(diff2.path) === "id" && "kind" in contentType) {
1691
- const target = resolveComponentUID({ paths: diff2.path, data, contentType, strapi: strapi2 });
1692
- if (!target) {
1693
- return;
1694
- }
1695
- const [oldID, newID] = diff2.values;
1696
- updateMappingTable(target, oldID, newID);
1697
- }
1698
- });
1699
- } catch (e) {
1700
- if (e instanceof Error) {
1701
- return callback(e);
1702
- }
1703
- return callback(new ProviderTransferError(`Failed to create "${type}" (${id})`));
1704
- }
1705
- return callback(null);
1706
- });
1707
- }
1708
- });
1709
- };
1710
- const omitInvalidCreationAttributes = fp.omit(["id"]);
1711
- const restoreCoreStore = async (strapi2, values) => {
1712
- const data = omitInvalidCreationAttributes(values);
1713
- return strapi2.db.query("strapi::core-store").create({
1714
- data: {
1715
- ...data,
1716
- value: JSON.stringify(data.value)
1717
- }
1718
- });
1719
- };
1720
- const restoreWebhooks = async (strapi2, values) => {
1721
- const data = omitInvalidCreationAttributes(values);
1722
- return strapi2.db.query("strapi::webhook").create({ data });
1723
- };
1724
- const restoreConfigs = async (strapi2, config) => {
1725
- if (config.type === "core-store") {
1726
- return restoreCoreStore(strapi2, config.value);
1727
- }
1728
- if (config.type === "webhook") {
1729
- return restoreWebhooks(strapi2, config.value);
1730
- }
1731
- };
1732
- const createConfigurationWriteStream = async (strapi2, transaction2) => {
1733
- return new stream$1.Writable({
1734
- objectMode: true,
1735
- async write(config, _encoding, callback) {
1736
- await transaction2?.attach(async () => {
1737
- try {
1738
- await restoreConfigs(strapi2, config);
1739
- } catch (error) {
1740
- return callback(
1741
- new ProviderTransferError(
1742
- `Failed to import ${chalk__default.default.yellowBright(config.type)} (${chalk__default.default.greenBright(
1743
- config.value.id
1744
- )}`
1745
- )
1746
- );
1747
- }
1748
- callback();
1749
- });
1750
- }
1751
- });
1752
- };
1753
- const isErrorWithCode = (error) => {
1754
- return error && typeof error.code === "string";
1755
- };
1756
- const isForeignKeyConstraintError = (e) => {
1757
- const MYSQL_FK_ERROR_CODES = ["1452", "1557", "1216", "1217", "1451"];
1758
- const POSTGRES_FK_ERROR_CODE = "23503";
1759
- const SQLITE_FK_ERROR_CODE = "SQLITE_CONSTRAINT_FOREIGNKEY";
1760
- if (isErrorWithCode(e) && e.code) {
1761
- return [SQLITE_FK_ERROR_CODE, POSTGRES_FK_ERROR_CODE, ...MYSQL_FK_ERROR_CODES].includes(e.code);
1762
- }
1763
- return e.message.toLowerCase().includes("foreign key constraint");
1764
- };
1765
- const createLinksWriteStream = (mapID, strapi2, transaction2, onWarning) => {
1766
- return new stream$1.Writable({
1767
- objectMode: true,
1768
- async write(link2, _encoding, callback) {
1769
- await transaction2?.attach(async (trx) => {
1770
- const { left, right } = link2;
1771
- const query = createLinkQuery(strapi2, trx);
1772
- const originalLeftRef = left.ref;
1773
- const originalRightRef = right.ref;
1774
- left.ref = mapID(left.type, originalLeftRef) ?? originalLeftRef;
1775
- right.ref = mapID(right.type, originalRightRef) ?? originalRightRef;
1776
- try {
1777
- await query().insert(link2);
1778
- } catch (e) {
1779
- if (e instanceof Error) {
1780
- if (isForeignKeyConstraintError(e)) {
1781
- onWarning?.(
1782
- `Skipping link ${left.type}:${originalLeftRef} -> ${right.type}:${originalRightRef} due to a foreign key constraint.`
1783
- );
1784
- return callback(null);
1785
- }
1786
- return callback(e);
1787
- }
1788
- return callback(
1789
- new ProviderTransferError(
1790
- `An error happened while trying to import a ${left.type} link.`
1791
- )
1792
- );
1793
- }
1794
- callback(null);
1795
- });
1796
- }
1797
- });
1798
- };
1799
- const deleteRecords = async (strapi2, options) => {
1800
- const entities = await deleteEntitiesRecords(strapi2, options);
1801
- const configuration = await deleteConfigurationRecords(strapi2, options);
1802
- return {
1803
- count: entities.count + configuration.count,
1804
- entities,
1805
- configuration
1806
- };
1807
- };
1808
- const deleteEntitiesRecords = async (strapi2, options = {}) => {
1809
- const { entities } = options;
1810
- const models = strapi2.get("models").get();
1811
- const contentTypes = Object.values(strapi2.contentTypes);
1812
- const contentTypesToClear = contentTypes.filter((contentType) => {
1813
- let removeThisContentType = true;
1814
- if (entities?.include) {
1815
- removeThisContentType = entities.include.includes(contentType.uid);
1816
- }
1817
- if (entities?.exclude && entities.exclude.includes(contentType.uid)) {
1818
- removeThisContentType = false;
1819
- }
1820
- if (entities?.filters) {
1821
- removeThisContentType = entities.filters.every((filter2) => filter2(contentType));
1822
- }
1823
- return removeThisContentType;
1824
- }).map((contentType) => contentType.uid);
1825
- const modelsToClear = models.filter((model) => {
1826
- if (contentTypesToClear.includes(model.uid)) {
1827
- return false;
1828
- }
1829
- let removeThisModel = true;
1830
- if (entities?.include) {
1831
- removeThisModel = entities.include.includes(model.uid);
1832
- }
1833
- if (entities?.exclude && entities.exclude.includes(model.uid)) {
1834
- removeThisModel = false;
1835
- }
1836
- return removeThisModel;
1837
- }).map((model) => model.uid);
1838
- const [results, updateResults] = useResults([...contentTypesToClear, ...modelsToClear]);
1839
- const contentTypeQuery = createEntityQuery(strapi2);
1840
- const contentTypePromises = contentTypesToClear.map(async (uid) => {
1841
- const result = await contentTypeQuery(uid).deleteMany(entities?.params);
1842
- if (result) {
1843
- updateResults(result.count || 0, uid);
1844
- }
1845
- });
1846
- const modelsPromises = modelsToClear.map(async (uid) => {
1847
- const result = await strapi2.db.query(uid).deleteMany({});
1848
- if (result) {
1849
- updateResults(result.count || 0, uid);
1850
- }
1851
- });
1852
- await Promise.all([...contentTypePromises, ...modelsPromises]);
1853
- return results;
1854
- };
1855
- const deleteConfigurationRecords = async (strapi2, options = {}) => {
1856
- const { coreStore = true, webhook = true } = options?.configuration ?? {};
1857
- const models = [];
1858
- if (coreStore) {
1859
- models.push("strapi::core-store");
1860
- }
1861
- if (webhook) {
1862
- models.push("strapi::webhook");
1863
- }
1864
- const [results, updateResults] = useResults(models);
1865
- const deletePromises = models.map(async (uid) => {
1866
- const result = await strapi2.db.query(uid).deleteMany({});
1867
- if (result) {
1868
- updateResults(result.count, uid);
1869
- }
1870
- });
1871
- await Promise.all(deletePromises);
1872
- return results;
1873
- };
1874
- const useResults = (keys) => {
1875
- const results = {
1876
- count: 0,
1877
- aggregate: keys.reduce((acc, key) => ({ ...acc, [key]: { count: 0 } }), {})
1878
- };
1879
- const update = (count, key) => {
1880
- if (key) {
1881
- if (!(key in results.aggregate)) {
1882
- throw new ProviderTransferError(`Unknown key "${key}" provided in results update`);
1883
- }
1884
- results.aggregate[key].count += count;
1885
- }
1886
- results.count += count;
1887
- };
1888
- return [results, update];
1889
- };
1890
- const assertValidStrapi = (strapi2, msg = "") => {
1891
- if (!strapi2) {
1892
- throw new ProviderInitializationError(`${msg}. Strapi instance not found.`);
1893
- }
1894
- };
1895
- const VALID_CONFLICT_STRATEGIES = ["restore"];
1896
- const DEFAULT_CONFLICT_STRATEGY = "restore";
1897
- class LocalStrapiDestinationProvider {
1898
- name = "destination::local-strapi";
1899
- type = "destination";
1900
- options;
1901
- strapi;
1902
- transaction;
1903
- uploadsBackupDirectoryName;
1904
- onWarning;
1905
- /**
1906
- * The entities mapper is used to map old entities to their new IDs
1907
- */
1908
- #entitiesMapper;
1909
- constructor(options) {
1910
- this.options = options;
1911
- this.#entitiesMapper = {};
1912
- this.uploadsBackupDirectoryName = `uploads_backup_${Date.now()}`;
1913
- }
1914
- async bootstrap() {
1915
- this.#validateOptions();
1916
- this.strapi = await this.options.getStrapi();
1917
- if (!this.strapi) {
1918
- throw new ProviderInitializationError("Could not access local strapi");
1919
- }
1920
- this.transaction = createTransaction(this.strapi);
1921
- }
1922
- // TODO: either move this to restore strategy, or restore strategy should given access to these instead of repeating the logic possibly in a different way
1923
- #areAssetsIncluded = () => {
1924
- return this.options.restore?.assets;
1925
- };
1926
- #isContentTypeIncluded = (type) => {
1927
- const notIncluded = this.options.restore?.entities?.include && !this.options.restore?.entities?.include?.includes(type);
1928
- const excluded = this.options.restore?.entities?.exclude && this.options.restore?.entities.exclude.includes(type);
1929
- return !excluded && !notIncluded;
1930
- };
1931
- async close() {
1932
- const { autoDestroy } = this.options;
1933
- this.transaction?.end();
1934
- if (autoDestroy === void 0 || autoDestroy === true) {
1935
- await this.strapi?.destroy();
1936
- }
1937
- }
1938
- #validateOptions() {
1939
- if (!VALID_CONFLICT_STRATEGIES.includes(this.options.strategy)) {
1940
- throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {
1941
- check: "strategy",
1942
- strategy: this.options.strategy,
1943
- validStrategies: VALID_CONFLICT_STRATEGIES
1944
- });
1945
- }
1946
- if (this.options.strategy === "restore" && !this.options.restore) {
1947
- throw new ProviderValidationError("Missing restore options");
1948
- }
1949
- }
1950
- async #deleteFromRestoreOptions() {
1951
- assertValidStrapi(this.strapi);
1952
- if (!this.options.restore) {
1953
- throw new ProviderValidationError("Missing restore options");
1954
- }
1955
- return deleteRecords(this.strapi, this.options.restore);
1956
- }
1957
- async #deleteAllAssets(trx) {
1958
- assertValidStrapi(this.strapi);
1959
- if (!this.#areAssetsIncluded()) {
1960
- return;
1961
- }
1962
- const stream2 = this.strapi.db.queryBuilder("plugin::upload.file").select("*").transacting(trx).stream();
1963
- for await (const file of stream2) {
1964
- await this.strapi.plugin("upload").provider.delete(file);
1965
- if (file.formats) {
1966
- for (const fileFormat of Object.values(file.formats)) {
1967
- await this.strapi.plugin("upload").provider.delete(fileFormat);
1968
- }
1969
- }
1970
- }
1971
- }
1972
- async rollback() {
1973
- await this.transaction?.rollback();
1974
- }
1975
- async beforeTransfer() {
1976
- if (!this.strapi) {
1977
- throw new Error("Strapi instance not found");
1978
- }
1979
- await this.transaction?.attach(async (trx) => {
1980
- try {
1981
- if (this.options.strategy === "restore") {
1982
- await this.#handleAssetsBackup();
1983
- await this.#deleteAllAssets(trx);
1984
- await this.#deleteFromRestoreOptions();
1985
- }
1986
- } catch (error) {
1987
- throw new Error(`restore failed ${error}`);
1988
- }
1989
- });
1990
- }
1991
- getMetadata() {
1992
- assertValidStrapi(this.strapi, "Not able to get Schemas");
1993
- const strapiVersion = this.strapi.config.get("info.strapi");
1994
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
1995
- return {
1996
- createdAt,
1997
- strapi: {
1998
- version: strapiVersion
1999
- }
2000
- };
2001
- }
2002
- getSchemas() {
2003
- assertValidStrapi(this.strapi, "Not able to get Schemas");
2004
- const schemas = schemasToValidJSON({
2005
- ...this.strapi.contentTypes,
2006
- ...this.strapi.components
2007
- });
2008
- return mapSchemasValues(schemas);
2009
- }
2010
- createEntitiesWriteStream() {
2011
- assertValidStrapi(this.strapi, "Not able to import entities");
2012
- const { strategy } = this.options;
2013
- const updateMappingTable = (type, oldID, newID) => {
2014
- if (!this.#entitiesMapper[type]) {
2015
- this.#entitiesMapper[type] = {};
2016
- }
2017
- Object.assign(this.#entitiesMapper[type], { [oldID]: newID });
2018
- };
2019
- if (strategy === "restore") {
2020
- return createEntitiesWriteStream({
2021
- strapi: this.strapi,
2022
- updateMappingTable,
2023
- transaction: this.transaction
2024
- });
2025
- }
2026
- throw new ProviderValidationError(`Invalid strategy ${this.options.strategy}`, {
2027
- check: "strategy",
2028
- strategy: this.options.strategy,
2029
- validStrategies: VALID_CONFLICT_STRATEGIES
2030
- });
2031
- }
2032
- async #handleAssetsBackup() {
2033
- assertValidStrapi(this.strapi, "Not able to create the assets backup");
2034
- if (!this.#areAssetsIncluded()) {
2035
- return;
2036
- }
2037
- if (this.strapi.config.get("plugin::upload").provider === "local") {
2038
- const assetsDirectory = path__default.default.join(this.strapi.dirs.static.public, "uploads");
2039
- const backupDirectory = path__default.default.join(
2040
- this.strapi.dirs.static.public,
2041
- this.uploadsBackupDirectoryName
2042
- );
2043
- try {
2044
- await fse__namespace.access(
2045
- assetsDirectory,
2046
- // eslint-disable-next-line no-bitwise
2047
- fse__namespace.constants.W_OK | fse__namespace.constants.R_OK | fse__namespace.constants.F_OK
2048
- );
2049
- await fse__namespace.access(path__default.default.join(assetsDirectory, ".."), fse__namespace.constants.W_OK | fse__namespace.constants.R_OK);
2050
- await fse__namespace.move(assetsDirectory, backupDirectory);
2051
- await fse__namespace.mkdir(assetsDirectory);
2052
- await fse__namespace.outputFile(path__default.default.join(assetsDirectory, ".gitkeep"), "");
2053
- } catch (err) {
2054
- throw new ProviderTransferError(
2055
- "The backup folder for the assets could not be created inside the public folder. Please ensure Strapi has write permissions on the public directory",
2056
- {
2057
- code: "ASSETS_DIRECTORY_ERR"
2058
- }
2059
- );
2060
- }
2061
- return backupDirectory;
2062
- }
2063
- }
2064
- async #removeAssetsBackup() {
2065
- assertValidStrapi(this.strapi, "Not able to remove Assets");
2066
- if (!this.#areAssetsIncluded()) {
2067
- return;
2068
- }
2069
- if (this.strapi.config.get("plugin::upload").provider === "local") {
2070
- assertValidStrapi(this.strapi);
2071
- const backupDirectory = path__default.default.join(
2072
- this.strapi.dirs.static.public,
2073
- this.uploadsBackupDirectoryName
2074
- );
2075
- await fse__namespace.rm(backupDirectory, { recursive: true, force: true });
2076
- }
2077
- }
2078
- // TODO: Move this logic to the restore strategy
2079
- async createAssetsWriteStream() {
2080
- assertValidStrapi(this.strapi, "Not able to stream Assets");
2081
- if (!this.#areAssetsIncluded()) {
2082
- throw new ProviderTransferError(
2083
- "Attempting to transfer assets when `assets` is not set in restore options"
2084
- );
2085
- }
2086
- const removeAssetsBackup = this.#removeAssetsBackup.bind(this);
2087
- const strapi2 = this.strapi;
2088
- const transaction2 = this.transaction;
2089
- const backupDirectory = this.uploadsBackupDirectoryName;
2090
- const fileEntitiesMapper = this.#entitiesMapper["plugin::upload.file"];
2091
- const restoreMediaEntitiesContent = this.#isContentTypeIncluded("plugin::upload.file");
2092
- return new stream$1.Writable({
2093
- objectMode: true,
2094
- async final(next) {
2095
- await removeAssetsBackup();
2096
- next();
2097
- },
2098
- async write(chunk, _encoding, callback) {
2099
- await transaction2?.attach(async () => {
2100
- if (!chunk.metadata) {
2101
- const assetsDirectory = path__default.default.join(strapi2.dirs.static.public, "uploads");
2102
- const entryPath = path__default.default.join(assetsDirectory, chunk.filename);
2103
- const writableStream = fse__namespace.createWriteStream(entryPath);
2104
- chunk.stream.pipe(writableStream).on("close", () => {
2105
- callback(null);
2106
- }).on("error", async (error) => {
2107
- const errorMessage = error.code === "ENOSPC" ? " Your server doesn't have space to proceed with the import. " : " ";
2108
- try {
2109
- await fse__namespace.rm(assetsDirectory, { recursive: true, force: true });
2110
- this.destroy(
2111
- new ProviderTransferError(
2112
- `There was an error during the transfer process.${errorMessage}The original files have been restored to ${assetsDirectory}`
2113
- )
2114
- );
2115
- } catch (err) {
2116
- throw new ProviderTransferError(
2117
- `There was an error doing the rollback process. The original files are in ${backupDirectory}, but we failed to restore them to ${assetsDirectory}`
2118
- );
2119
- } finally {
2120
- callback(error);
2121
- }
2122
- });
2123
- return;
2124
- }
2125
- const uploadData = {
2126
- ...chunk.metadata,
2127
- stream: stream$1.Readable.from(chunk.stream),
2128
- buffer: chunk?.buffer
2129
- };
2130
- const provider = strapi2.config.get("plugin::upload").provider;
2131
- try {
2132
- await strapi2.plugin("upload").provider.uploadStream(uploadData);
2133
- if (!restoreMediaEntitiesContent) {
2134
- return callback();
2135
- }
2136
- if (uploadData?.type) {
2137
- const condition = uploadData?.id ? { id: fileEntitiesMapper[uploadData.id] } : { hash: uploadData.mainHash };
2138
- const entry2 = await strapi2.db.query("plugin::upload.file").findOne({
2139
- where: condition
2140
- });
2141
- const specificFormat = entry2?.formats?.[uploadData.type];
2142
- if (specificFormat) {
2143
- specificFormat.url = uploadData.url;
2144
- }
2145
- await strapi2.db.query("plugin::upload.file").update({
2146
- where: { id: entry2.id },
2147
- data: {
2148
- formats: entry2.formats,
2149
- provider
2150
- }
2151
- });
2152
- return callback();
2153
- }
2154
- const entry = await strapi2.db.query("plugin::upload.file").findOne({
2155
- where: { id: fileEntitiesMapper[uploadData.id] }
2156
- });
2157
- entry.url = uploadData.url;
2158
- await strapi2.db.query("plugin::upload.file").update({
2159
- where: { id: entry.id },
2160
- data: {
2161
- url: entry.url,
2162
- provider
2163
- }
2164
- });
2165
- callback();
2166
- } catch (error) {
2167
- callback(new Error(`Error while uploading asset ${chunk.filename} ${error}`));
2168
- }
2169
- });
2170
- }
2171
- });
2172
- }
2173
- async createConfigurationWriteStream() {
2174
- assertValidStrapi(this.strapi, "Not able to stream Configurations");
2175
- const { strategy } = this.options;
2176
- if (strategy === "restore") {
2177
- return createConfigurationWriteStream(this.strapi, this.transaction);
2178
- }
2179
- throw new ProviderValidationError(`Invalid strategy ${strategy}`, {
2180
- check: "strategy",
2181
- strategy,
2182
- validStrategies: VALID_CONFLICT_STRATEGIES
2183
- });
2184
- }
2185
- async createLinksWriteStream() {
2186
- if (!this.strapi) {
2187
- throw new Error("Not able to stream links. Strapi instance not found");
2188
- }
2189
- const { strategy } = this.options;
2190
- const mapID = (uid, id) => this.#entitiesMapper[uid]?.[id];
2191
- if (strategy === "restore") {
2192
- return createLinksWriteStream(mapID, this.strapi, this.transaction, this.onWarning);
2193
- }
2194
- throw new ProviderValidationError(`Invalid strategy ${strategy}`, {
2195
- check: "strategy",
2196
- strategy,
2197
- validStrategies: VALID_CONFLICT_STRATEGIES
2198
- });
2199
- }
2200
- }
2201
- const createLocalStrapiDestinationProvider = (options) => {
2202
- return new LocalStrapiDestinationProvider(options);
2203
- };
2204
- const createEntitiesStream = (strapi2) => {
2205
- const contentTypes = Object.values(strapi2.contentTypes);
2206
- async function* contentTypeStreamGenerator() {
2207
- for (const contentType of contentTypes) {
2208
- const query = createEntityQuery(strapi2).call(null, contentType.uid);
2209
- const stream2 = strapi2.db.queryBuilder(contentType.uid).select("*").populate(query.deepPopulateComponentLikeQuery).stream();
2210
- yield { contentType, stream: stream2 };
2211
- }
2212
- }
2213
- return stream$1.Readable.from(
2214
- async function* entitiesGenerator() {
2215
- for await (const { stream: stream2, contentType } of contentTypeStreamGenerator()) {
2216
- try {
2217
- for await (const entity2 of stream2) {
2218
- yield { entity: entity2, contentType };
2219
- }
2220
- } catch {
2221
- } finally {
2222
- stream2.destroy();
2223
- }
2224
- }
2225
- }()
2226
- );
2227
- };
2228
- const createEntitiesTransformStream = () => {
2229
- return new stream$1.Transform({
2230
- objectMode: true,
2231
- transform(data, _encoding, callback) {
2232
- const { entity: entity2, contentType } = data;
2233
- const { id, ...attributes } = entity2;
2234
- callback(null, {
2235
- type: contentType.uid,
2236
- id,
2237
- data: attributes
2238
- });
2239
- }
2240
- });
2241
- };
2242
- const createLinksStream = (strapi2) => {
2243
- const uids = [...Object.keys(strapi2.contentTypes), ...Object.keys(strapi2.components)];
2244
- return stream$1.Readable.from(
2245
- async function* linkGenerator() {
2246
- const query = createLinkQuery(strapi2);
2247
- for (const uid of uids) {
2248
- const generator = query().generateAll(uid);
2249
- for await (const link2 of generator) {
2250
- yield link2;
2251
- }
2252
- }
2253
- }()
2254
- );
2255
- };
2256
- const createConfigurationStream = (strapi2) => {
2257
- return stream$1.Readable.from(
2258
- async function* configurationGenerator() {
2259
- const coreStoreStream = streamChain.chain([
2260
- strapi2.db.queryBuilder("strapi::core-store").stream(),
2261
- (data) => fp.set("value", JSON.parse(data.value), data),
2262
- wrapConfigurationItem("core-store")
2263
- ]);
2264
- const webhooksStream = streamChain.chain([
2265
- strapi2.db.queryBuilder("strapi::webhook").stream(),
2266
- wrapConfigurationItem("webhook")
2267
- ]);
2268
- const streams = [coreStoreStream, webhooksStream];
2269
- for (const stream2 of streams) {
2270
- for await (const item of stream2) {
2271
- yield item;
2272
- }
2273
- }
2274
- }()
2275
- );
2276
- };
2277
- const wrapConfigurationItem = (type) => (value) => ({
2278
- type,
2279
- value
2280
- });
2281
- function getFileStream(filepath, strapi2, isLocal = false) {
2282
- if (isLocal) {
2283
- return fse.createReadStream(filepath);
2284
- }
2285
- const readableStream = new stream$1.PassThrough();
2286
- strapi2.fetch(filepath).then((res) => {
2287
- if (res.status !== 200) {
2288
- readableStream.emit("error", new Error(`Request failed with status code ${res.status}`));
2289
- return;
2290
- }
2291
- if (res.body) {
2292
- stream$1.Readable.fromWeb(new webStream__namespace.ReadableStream(res.body)).pipe(readableStream);
2293
- } else {
2294
- readableStream.emit("error", new Error("Empty data found for file"));
2295
- }
2296
- }).catch((error) => {
2297
- readableStream.emit("error", error);
2298
- });
2299
- return readableStream;
2300
- }
2301
- function getFileStats(filepath, strapi2, isLocal = false) {
2302
- if (isLocal) {
2303
- return fse.stat(filepath);
2304
- }
2305
- return new Promise((resolve, reject2) => {
2306
- strapi2.fetch(filepath).then((res) => {
2307
- if (res.status !== 200) {
2308
- reject2(new Error(`Request failed with status code ${res.status}`));
2309
- return;
2310
- }
2311
- const contentLength = res.headers.get("content-length");
2312
- const stats = {
2313
- size: contentLength ? parseInt(contentLength, 10) : 0
2314
- };
2315
- resolve(stats);
2316
- }).catch((error) => {
2317
- reject2(error);
2318
- });
2319
- });
2320
- }
2321
- async function signFile(file) {
2322
- const { provider } = strapi.plugins.upload;
2323
- const { provider: providerName } = strapi.config.get("plugin.upload");
2324
- const isPrivate = await provider.isPrivate();
2325
- if (file?.provider === providerName && isPrivate) {
2326
- const signUrl = async (file2) => {
2327
- const signedUrl = await provider.getSignedUrl(file2);
2328
- file2.url = signedUrl.url;
2329
- };
2330
- await signUrl(file);
2331
- if (file.formats) {
2332
- for (const format of Object.keys(file.formats)) {
2333
- await signUrl(file.formats[format]);
2334
- }
2335
- }
2336
- }
2337
- }
2338
- const createAssetsStream = (strapi2) => {
2339
- const generator = async function* () {
2340
- const stream2 = strapi2.db.queryBuilder("plugin::upload.file").select("*").stream();
2341
- for await (const file of stream2) {
2342
- const isLocalProvider = file.provider === "local";
2343
- if (!isLocalProvider) {
2344
- await signFile(file);
2345
- }
2346
- const filepath = isLocalProvider ? path.join(strapi2.dirs.static.public, file.url) : file.url;
2347
- const stats = await getFileStats(filepath, strapi2, isLocalProvider);
2348
- const stream22 = getFileStream(filepath, strapi2, isLocalProvider);
2349
- yield {
2350
- metadata: file,
2351
- filepath,
2352
- filename: file.hash + file.ext,
2353
- stream: stream22,
2354
- stats: { size: stats.size }
2355
- };
2356
- if (file.formats) {
2357
- for (const format of Object.keys(file.formats)) {
2358
- const fileFormat = file.formats[format];
2359
- const fileFormatFilepath = isLocalProvider ? path.join(strapi2.dirs.static.public, fileFormat.url) : fileFormat.url;
2360
- const fileFormatStats = await getFileStats(fileFormatFilepath, strapi2, isLocalProvider);
2361
- const fileFormatStream = getFileStream(fileFormatFilepath, strapi2, isLocalProvider);
2362
- const metadata = { ...fileFormat, type: format, id: file.id, mainHash: file.hash };
2363
- yield {
2364
- metadata,
2365
- filepath: fileFormatFilepath,
2366
- filename: fileFormat.hash + fileFormat.ext,
2367
- stream: fileFormatStream,
2368
- stats: { size: fileFormatStats.size }
2369
- };
2370
- }
2371
- }
2372
- }
2373
- };
2374
- return stream$1.Duplex.from(generator());
2375
- };
2376
- const createLocalStrapiSourceProvider = (options) => {
2377
- return new LocalStrapiSourceProvider(options);
2378
- };
2379
- class LocalStrapiSourceProvider {
2380
- name = "source::local-strapi";
2381
- type = "source";
2382
- options;
2383
- strapi;
2384
- constructor(options) {
2385
- this.options = options;
2386
- }
2387
- async bootstrap() {
2388
- this.strapi = await this.options.getStrapi();
2389
- }
2390
- async close() {
2391
- const { autoDestroy } = this.options;
2392
- if (autoDestroy === void 0 || autoDestroy === true) {
2393
- await this.strapi?.destroy();
2394
- }
2395
- }
2396
- getMetadata() {
2397
- const strapiVersion = strapi.config.get("info.strapi");
2398
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
2399
- return {
2400
- createdAt,
2401
- strapi: {
2402
- version: strapiVersion
2403
- }
2404
- };
2405
- }
2406
- async createEntitiesReadStream() {
2407
- assertValidStrapi(this.strapi, "Not able to stream entities");
2408
- return streamChain.chain([
2409
- // Entities stream
2410
- createEntitiesStream(this.strapi),
2411
- // Transform stream
2412
- createEntitiesTransformStream()
2413
- ]);
2414
- }
2415
- createLinksReadStream() {
2416
- assertValidStrapi(this.strapi, "Not able to stream links");
2417
- return createLinksStream(this.strapi);
2418
- }
2419
- createConfigurationReadStream() {
2420
- assertValidStrapi(this.strapi, "Not able to stream configuration");
2421
- return createConfigurationStream(this.strapi);
2422
- }
2423
- getSchemas() {
2424
- assertValidStrapi(this.strapi, "Not able to get Schemas");
2425
- const schemas = schemasToValidJSON({
2426
- ...this.strapi.contentTypes,
2427
- ...this.strapi.components
2428
- });
2429
- return mapSchemasValues(schemas);
2430
- }
2431
- createSchemasReadStream() {
2432
- return stream$1.Readable.from(Object.values(this.getSchemas()));
2433
- }
2434
- createAssetsReadStream() {
2435
- assertValidStrapi(this.strapi, "Not able to stream assets");
2436
- return createAssetsStream(this.strapi);
2437
- }
2438
- }
2439
- const createDispatcher = (ws2, retryMessageOptions = {
2440
- retryMessageMaxRetries: 5,
2441
- retryMessageTimeout: 3e4
2442
- }) => {
2443
- const state = {};
2444
- const dispatch = async (message, options = {}) => {
2445
- if (!ws2) {
2446
- throw new Error("No websocket connection found");
2447
- }
2448
- return new Promise((resolve, reject2) => {
2449
- const uuid = crypto.randomUUID();
2450
- const payload = { ...message, uuid };
2451
- let numberOfTimesMessageWasSent = 0;
2452
- if (options.attachTransfer) {
2453
- Object.assign(payload, { transferID: state.transfer?.id });
2454
- }
2455
- const stringifiedPayload = JSON.stringify(payload);
2456
- ws2.send(stringifiedPayload, (error) => {
2457
- if (error) {
2458
- reject2(error);
2459
- }
2460
- });
2461
- const { retryMessageMaxRetries, retryMessageTimeout } = retryMessageOptions;
2462
- const sendPeriodically = () => {
2463
- if (numberOfTimesMessageWasSent <= retryMessageMaxRetries) {
2464
- numberOfTimesMessageWasSent += 1;
2465
- ws2.send(stringifiedPayload, (error) => {
2466
- if (error) {
2467
- reject2(error);
2468
- }
2469
- });
2470
- } else {
2471
- reject2(new ProviderError("error", "Request timed out"));
2472
- }
2473
- };
2474
- const interval = setInterval(sendPeriodically, retryMessageTimeout);
2475
- const onResponse = (raw) => {
2476
- const response = JSON.parse(raw.toString());
2477
- if (response.uuid === uuid) {
2478
- clearInterval(interval);
2479
- if (response.error) {
2480
- const message2 = response.error.message;
2481
- const details = response.error.details?.details;
2482
- const step = response.error.details?.step;
2483
- let error = new ProviderError("error", message2, details);
2484
- if (step === "transfer") {
2485
- error = new ProviderTransferError(message2, details);
2486
- } else if (step === "validation") {
2487
- error = new ProviderValidationError(message2, details);
2488
- } else if (step === "initialization") {
2489
- error = new ProviderInitializationError(message2);
2490
- }
2491
- return reject2(error);
2492
- }
2493
- resolve(response.data ?? null);
2494
- } else {
2495
- ws2.once("message", onResponse);
2496
- }
2497
- };
2498
- ws2.once("message", onResponse);
2499
- });
2500
- };
2501
- const dispatchCommand = (payload) => {
2502
- return dispatch({ type: "command", ...payload });
2503
- };
2504
- const dispatchTransferAction = async (action) => {
2505
- const payload = { type: "transfer", kind: "action", action };
2506
- return dispatch(payload, { attachTransfer: true }) ?? Promise.resolve(null);
2507
- };
2508
- const dispatchTransferStep = async (payload) => {
2509
- const message = {
2510
- type: "transfer",
2511
- kind: "step",
2512
- ...payload
2513
- };
2514
- return dispatch(message, { attachTransfer: true }) ?? Promise.resolve(null);
2515
- };
2516
- const setTransferProperties = (properties) => {
2517
- state.transfer = { ...properties };
2518
- };
2519
- return {
2520
- get transferID() {
2521
- return state.transfer?.id;
2522
- },
2523
- get transferKind() {
2524
- return state.transfer?.kind;
2525
- },
2526
- setTransferProperties,
2527
- dispatch,
2528
- dispatchCommand,
2529
- dispatchTransferAction,
2530
- dispatchTransferStep
2531
- };
2532
- };
2533
- const connectToWebsocket = (address, options) => {
2534
- return new Promise((resolve, reject2) => {
2535
- const server = new ws.WebSocket(address, options);
2536
- server.once("open", () => {
2537
- resolve(server);
2538
- });
2539
- server.on("unexpected-response", (_req, res) => {
2540
- if (res.statusCode === 401) {
2541
- return reject2(
2542
- new ProviderInitializationError(
2543
- "Failed to initialize the connection: Authentication Error"
2544
- )
2545
- );
2546
- }
2547
- if (res.statusCode === 403) {
2548
- return reject2(
2549
- new ProviderInitializationError(
2550
- "Failed to initialize the connection: Authorization Error"
2551
- )
2552
- );
2553
- }
2554
- if (res.statusCode === 404) {
2555
- return reject2(
2556
- new ProviderInitializationError(
2557
- "Failed to initialize the connection: Data transfer is not enabled on the remote host"
2558
- )
2559
- );
2560
- }
2561
- return reject2(
2562
- new ProviderInitializationError(
2563
- `Failed to initialize the connection: Unexpected server response ${res.statusCode}`
2564
- )
2565
- );
2566
- });
2567
- server.once("error", (err) => {
2568
- reject2(
2569
- new ProviderTransferError(err.message, {
2570
- details: {
2571
- error: err.message
2572
- }
2573
- })
2574
- );
2575
- });
2576
- });
2577
- };
2578
- const trimTrailingSlash = (input) => {
2579
- return input.replace(/\/$/, "");
2580
- };
2581
- const TRANSFER_PATH = "/transfer/runner";
2582
- const TRANSFER_METHODS = ["push", "pull"];
2583
- const constants = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2584
- __proto__: null,
2585
- TRANSFER_METHODS,
2586
- TRANSFER_PATH
2587
- }, Symbol.toStringTag, { value: "Module" }));
2588
- const jsonLength = (obj) => Buffer.byteLength(JSON.stringify(obj));
2589
- class RemoteStrapiDestinationProvider {
2590
- name = "destination::remote-strapi";
2591
- type = "destination";
2592
- options;
2593
- ws;
2594
- dispatcher;
2595
- transferID;
2596
- constructor(options) {
2597
- this.options = options;
2598
- this.ws = null;
2599
- this.dispatcher = null;
2600
- this.transferID = null;
2601
- }
2602
- async initTransfer() {
2603
- const { strategy, restore } = this.options;
2604
- const query = this.dispatcher?.dispatchCommand({
2605
- command: "init",
2606
- params: { options: { strategy, restore }, transfer: "push" }
2607
- });
2608
- const res = await query;
2609
- if (!res?.transferID) {
2610
- throw new ProviderTransferError("Init failed, invalid response from the server");
2611
- }
2612
- return res.transferID;
2613
- }
2614
- #startStepOnce(stage) {
2615
- return fp.once(() => this.#startStep(stage));
2616
- }
2617
- async #startStep(step) {
2618
- try {
2619
- await this.dispatcher?.dispatchTransferStep({ action: "start", step });
2620
- } catch (e) {
2621
- if (e instanceof Error) {
2622
- return e;
2623
- }
2624
- if (typeof e === "string") {
2625
- return new ProviderTransferError(e);
2626
- }
2627
- return new ProviderTransferError("Unexpected error");
2628
- }
2629
- return null;
2630
- }
2631
- async #endStep(step) {
2632
- try {
2633
- await this.dispatcher?.dispatchTransferStep({ action: "end", step });
2634
- } catch (e) {
2635
- if (e instanceof Error) {
2636
- return e;
2637
- }
2638
- if (typeof e === "string") {
2639
- return new ProviderTransferError(e);
2640
- }
2641
- return new ProviderTransferError("Unexpected error");
2642
- }
2643
- return null;
2644
- }
2645
- async #streamStep(step, data) {
2646
- try {
2647
- await this.dispatcher?.dispatchTransferStep({ action: "stream", step, data });
2648
- } catch (e) {
2649
- if (e instanceof Error) {
2650
- return e;
2651
- }
2652
- if (typeof e === "string") {
2653
- return new ProviderTransferError(e);
2654
- }
2655
- return new ProviderTransferError("Unexpected error");
2656
- }
2657
- return null;
2658
- }
2659
- #writeStream(step) {
2660
- const batchSize = 1024 * 1024;
2661
- const startTransferOnce = this.#startStepOnce(step);
2662
- let batch = [];
2663
- const batchLength = () => jsonLength(batch);
2664
- return new stream$1.Writable({
2665
- objectMode: true,
2666
- final: async (callback) => {
2667
- if (batch.length > 0) {
2668
- const streamError = await this.#streamStep(step, batch);
2669
- batch = [];
2670
- if (streamError) {
2671
- return callback(streamError);
2672
- }
2673
- }
2674
- const e = await this.#endStep(step);
2675
- callback(e);
2676
- },
2677
- write: async (chunk, _encoding, callback) => {
2678
- const startError = await startTransferOnce();
2679
- if (startError) {
2680
- return callback(startError);
2681
- }
2682
- batch.push(chunk);
2683
- if (batchLength() >= batchSize) {
2684
- const streamError = await this.#streamStep(step, batch);
2685
- batch = [];
2686
- if (streamError) {
2687
- return callback(streamError);
2688
- }
2689
- }
2690
- callback();
2691
- }
2692
- });
2693
- }
2694
- async bootstrap() {
2695
- const { url, auth } = this.options;
2696
- const validProtocols = ["https:", "http:"];
2697
- let ws2;
2698
- if (!validProtocols.includes(url.protocol)) {
2699
- throw new ProviderValidationError(`Invalid protocol "${url.protocol}"`, {
2700
- check: "url",
2701
- details: {
2702
- protocol: url.protocol,
2703
- validProtocols
2704
- }
2705
- });
2706
- }
2707
- const wsProtocol = url.protocol === "https:" ? "wss:" : "ws:";
2708
- const wsUrl = `${wsProtocol}//${url.host}${trimTrailingSlash(
2709
- url.pathname
2710
- )}${TRANSFER_PATH}/push`;
2711
- if (!auth) {
2712
- ws2 = await connectToWebsocket(wsUrl);
2713
- } else if (auth.type === "token") {
2714
- const headers = { Authorization: `Bearer ${auth.token}` };
2715
- ws2 = await connectToWebsocket(wsUrl, { headers });
2716
- } else {
2717
- throw new ProviderValidationError("Auth method not available", {
2718
- check: "auth.type",
2719
- details: {
2720
- auth: auth.type
2721
- }
2722
- });
2723
- }
2724
- this.ws = ws2;
2725
- const { retryMessageOptions } = this.options;
2726
- this.dispatcher = createDispatcher(this.ws, retryMessageOptions);
2727
- this.transferID = await this.initTransfer();
2728
- this.dispatcher.setTransferProperties({ id: this.transferID, kind: "push" });
2729
- await this.dispatcher.dispatchTransferAction("bootstrap");
2730
- }
2731
- async close() {
2732
- if (this.transferID && this.dispatcher) {
2733
- await this.dispatcher.dispatchTransferAction("close");
2734
- await this.dispatcher.dispatchCommand({
2735
- command: "end",
2736
- params: { transferID: this.transferID }
2737
- });
2738
- }
2739
- await new Promise((resolve) => {
2740
- const { ws: ws2 } = this;
2741
- if (!ws2 || ws2.CLOSED) {
2742
- resolve();
2743
- return;
2744
- }
2745
- ws2.on("close", () => resolve()).close();
2746
- });
2747
- }
2748
- getMetadata() {
2749
- return this.dispatcher?.dispatchTransferAction("getMetadata") ?? null;
2750
- }
2751
- async beforeTransfer() {
2752
- await this.dispatcher?.dispatchTransferAction("beforeTransfer");
2753
- }
2754
- async rollback() {
2755
- await this.dispatcher?.dispatchTransferAction("rollback");
2756
- }
2757
- getSchemas() {
2758
- if (!this.dispatcher) {
2759
- return Promise.resolve(null);
2760
- }
2761
- return this.dispatcher.dispatchTransferAction("getSchemas");
2762
- }
2763
- createEntitiesWriteStream() {
2764
- return this.#writeStream("entities");
2765
- }
2766
- createLinksWriteStream() {
2767
- return this.#writeStream("links");
2768
- }
2769
- createConfigurationWriteStream() {
2770
- return this.#writeStream("configuration");
2771
- }
2772
- createAssetsWriteStream() {
2773
- let batch = [];
2774
- let hasStarted = false;
2775
- const batchSize = 1024 * 1024;
2776
- const batchLength = () => {
2777
- return batch.reduce(
2778
- (acc, chunk) => chunk.action === "stream" ? acc + chunk.data.byteLength : acc,
2779
- 0
2780
- );
2781
- };
2782
- const startAssetsTransferOnce = this.#startStepOnce("assets");
2783
- const flush = async () => {
2784
- const streamError = await this.#streamStep("assets", batch);
2785
- batch = [];
2786
- return streamError;
2787
- };
2788
- const safePush = async (chunk) => {
2789
- batch.push(chunk);
2790
- if (batchLength() >= batchSize) {
2791
- const streamError = await flush();
2792
- if (streamError) {
2793
- throw streamError;
2794
- }
2795
- }
2796
- };
2797
- return new stream$1.Writable({
2798
- objectMode: true,
2799
- final: async (callback) => {
2800
- if (batch.length > 0) {
2801
- await flush();
2802
- }
2803
- if (hasStarted) {
2804
- const endStepError = await this.#endStep("assets");
2805
- if (endStepError) {
2806
- return callback(endStepError);
2807
- }
2808
- }
2809
- return callback(null);
2810
- },
2811
- async write(asset, _encoding, callback) {
2812
- const startError = await startAssetsTransferOnce();
2813
- if (startError) {
2814
- return callback(startError);
2815
- }
2816
- hasStarted = true;
2817
- const assetID = crypto.randomUUID();
2818
- const { filename, filepath, stats, stream: stream2, metadata } = asset;
2819
- try {
2820
- await safePush({
2821
- action: "start",
2822
- assetID,
2823
- data: { filename, filepath, stats, metadata }
2824
- });
2825
- for await (const chunk of stream2) {
2826
- await safePush({ action: "stream", assetID, data: chunk });
2827
- }
2828
- await safePush({ action: "end", assetID });
2829
- callback();
2830
- } catch (error) {
2831
- if (error instanceof Error) {
2832
- callback(error);
2833
- }
2834
- }
2835
- }
2836
- });
2837
- }
2838
- }
2839
- const createRemoteStrapiDestinationProvider = (options) => {
2840
- return new RemoteStrapiDestinationProvider(options);
2841
- };
2842
- class RemoteStrapiSourceProvider {
2843
- name = "source::remote-strapi";
2844
- type = "source";
2845
- options;
2846
- ws;
2847
- dispatcher;
2848
- constructor(options) {
2849
- this.options = options;
2850
- this.ws = null;
2851
- this.dispatcher = null;
2852
- }
2853
- results;
2854
- async #createStageReadStream(stage) {
2855
- const startResult = await this.#startStep(stage);
2856
- if (startResult instanceof Error) {
2857
- throw startResult;
2858
- }
2859
- const { id: processID } = startResult;
2860
- const stream2 = new stream$1.PassThrough({ objectMode: true });
2861
- const listener = async (raw) => {
2862
- const parsed = JSON.parse(raw.toString());
2863
- if (!parsed.uuid || parsed?.data?.type !== "transfer" || parsed?.data?.id !== processID) {
2864
- this.ws?.once("message", listener);
2865
- return;
2866
- }
2867
- const { uuid, data: message } = parsed;
2868
- const { ended, error, data } = message;
2869
- if (error) {
2870
- await this.#respond(uuid);
2871
- stream2.destroy(error);
2872
- return;
2873
- }
2874
- if (ended) {
2875
- await this.#respond(uuid);
2876
- await this.#endStep(stage);
2877
- stream2.end();
2878
- return;
2879
- }
2880
- for (const item of fp.castArray(data)) {
2881
- stream2.push(item);
2882
- }
2883
- this.ws?.once("message", listener);
2884
- await this.#respond(uuid);
2885
- };
2886
- this.ws?.once("message", listener);
2887
- return stream2;
2888
- }
2889
- createEntitiesReadStream() {
2890
- return this.#createStageReadStream("entities");
2891
- }
2892
- createLinksReadStream() {
2893
- return this.#createStageReadStream("links");
2894
- }
2895
- writeAsync = (stream2, data) => {
2896
- return new Promise((resolve, reject2) => {
2897
- stream2.write(data, (error) => {
2898
- if (error) {
2899
- reject2(error);
2900
- }
2901
- resolve();
2902
- });
2903
- });
2904
- };
2905
- async createAssetsReadStream() {
2906
- const assets = {};
2907
- const stream2 = await this.#createStageReadStream("assets");
2908
- const pass = new stream$1.PassThrough({ objectMode: true });
2909
- stream2.on("data", async (payload) => {
2910
- for (const item of payload) {
2911
- const { action } = item;
2912
- if (action === "start") {
2913
- assets[item.assetID] = { ...item.data, stream: new stream$1.PassThrough() };
2914
- await this.writeAsync(pass, assets[item.assetID]);
2915
- } else if (action === "stream") {
2916
- const rawBuffer = item.data;
2917
- const chunk = Buffer.from(rawBuffer.data);
2918
- await this.writeAsync(assets[item.assetID].stream, chunk);
2919
- } else if (action === "end") {
2920
- await new Promise((resolve, reject2) => {
2921
- const { stream: assetStream } = assets[item.assetID];
2922
- assetStream.on("close", () => {
2923
- delete assets[item.assetID];
2924
- resolve();
2925
- }).on("error", reject2).end();
2926
- });
2927
- }
2928
- }
2929
- }).on("close", () => {
2930
- pass.end();
2931
- });
2932
- return pass;
2933
- }
2934
- createConfigurationReadStream() {
2935
- return this.#createStageReadStream("configuration");
2936
- }
2937
- async getMetadata() {
2938
- const metadata = await this.dispatcher?.dispatchTransferAction("getMetadata");
2939
- return metadata ?? null;
2940
- }
2941
- assertValidProtocol(url) {
2942
- const validProtocols = ["https:", "http:"];
2943
- if (!validProtocols.includes(url.protocol)) {
2944
- throw new ProviderValidationError(`Invalid protocol "${url.protocol}"`, {
2945
- check: "url",
2946
- details: {
2947
- protocol: url.protocol,
2948
- validProtocols
2949
- }
2950
- });
2951
- }
2952
- }
2953
- async initTransfer() {
2954
- const query = this.dispatcher?.dispatchCommand({
2955
- command: "init"
2956
- });
2957
- const res = await query;
2958
- if (!res?.transferID) {
2959
- throw new ProviderTransferError("Init failed, invalid response from the server");
2960
- }
2961
- return res.transferID;
2962
- }
2963
- async bootstrap() {
2964
- const { url, auth } = this.options;
2965
- let ws2;
2966
- this.assertValidProtocol(url);
2967
- const wsProtocol = url.protocol === "https:" ? "wss:" : "ws:";
2968
- const wsUrl = `${wsProtocol}//${url.host}${trimTrailingSlash(
2969
- url.pathname
2970
- )}${TRANSFER_PATH}/pull`;
2971
- if (!auth) {
2972
- ws2 = await connectToWebsocket(wsUrl);
2973
- } else if (auth.type === "token") {
2974
- const headers = { Authorization: `Bearer ${auth.token}` };
2975
- ws2 = await connectToWebsocket(wsUrl, { headers });
2976
- } else {
2977
- throw new ProviderValidationError("Auth method not available", {
2978
- check: "auth.type",
2979
- details: {
2980
- auth: auth.type
2981
- }
2982
- });
2983
- }
2984
- this.ws = ws2;
2985
- const { retryMessageOptions } = this.options;
2986
- this.dispatcher = createDispatcher(this.ws, retryMessageOptions);
2987
- const transferID = await this.initTransfer();
2988
- this.dispatcher.setTransferProperties({ id: transferID, kind: "pull" });
2989
- await this.dispatcher.dispatchTransferAction("bootstrap");
2990
- }
2991
- async close() {
2992
- await this.dispatcher?.dispatchTransferAction("close");
2993
- await new Promise((resolve) => {
2994
- const { ws: ws2 } = this;
2995
- if (!ws2 || ws2.CLOSED) {
2996
- resolve();
2997
- return;
2998
- }
2999
- ws2.on("close", () => resolve()).close();
3000
- });
3001
- }
3002
- async getSchemas() {
3003
- const schemas = await this.dispatcher?.dispatchTransferAction("getSchemas");
3004
- return schemas ?? null;
3005
- }
3006
- async #startStep(step) {
3007
- try {
3008
- return await this.dispatcher?.dispatchTransferStep({ action: "start", step });
3009
- } catch (e) {
3010
- if (e instanceof Error) {
3011
- return e;
3012
- }
3013
- if (typeof e === "string") {
3014
- return new ProviderTransferError(e);
3015
- }
3016
- return new ProviderTransferError("Unexpected error");
3017
- }
3018
- }
3019
- async #respond(uuid) {
3020
- return new Promise((resolve, reject2) => {
3021
- this.ws?.send(JSON.stringify({ uuid }), (e) => {
3022
- if (e) {
3023
- reject2(e);
3024
- } else {
3025
- resolve(e);
3026
- }
3027
- });
3028
- });
3029
- }
3030
- async #endStep(step) {
3031
- try {
3032
- await this.dispatcher?.dispatchTransferStep({ action: "end", step });
3033
- } catch (e) {
3034
- if (e instanceof Error) {
3035
- return e;
3036
- }
3037
- if (typeof e === "string") {
3038
- return new ProviderTransferError(e);
3039
- }
3040
- return new ProviderTransferError("Unexpected error");
3041
- }
3042
- return null;
3043
- }
3044
- }
3045
- const createRemoteStrapiSourceProvider = (options) => {
3046
- return new RemoteStrapiSourceProvider(options);
3047
- };
3048
- const index$5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3049
- __proto__: null,
3050
- DEFAULT_CONFLICT_STRATEGY,
3051
- VALID_CONFLICT_STRATEGIES,
3052
- createLocalStrapiDestinationProvider,
3053
- createLocalStrapiSourceProvider,
3054
- createRemoteStrapiDestinationProvider,
3055
- createRemoteStrapiSourceProvider
3056
- }, Symbol.toStringTag, { value: "Module" }));
3057
- const DEFAULT_TRANSFER_FLOW = [
3058
- {
3059
- kind: "action",
3060
- action: "bootstrap"
3061
- },
3062
- {
3063
- kind: "action",
3064
- action: "init"
3065
- },
3066
- {
3067
- kind: "action",
3068
- action: "beforeTransfer"
3069
- },
3070
- {
3071
- kind: "transfer",
3072
- stage: "schemas"
3073
- },
3074
- {
3075
- kind: "transfer",
3076
- stage: "entities"
3077
- },
3078
- {
3079
- kind: "transfer",
3080
- stage: "assets"
3081
- },
3082
- {
3083
- kind: "transfer",
3084
- stage: "links"
3085
- },
3086
- {
3087
- kind: "transfer",
3088
- stage: "configuration"
3089
- },
3090
- {
3091
- kind: "action",
3092
- action: "close"
3093
- }
3094
- ];
3095
- const createFlow = (flow) => {
3096
- const state = { step: null };
3097
- const stepEqual = (stepA, stepB) => {
3098
- if (stepA.kind === "action" && stepB.kind === "action") {
3099
- return stepA.action === stepB.action;
3100
- }
3101
- if (stepA.kind === "transfer" && stepB.kind === "transfer") {
3102
- return stepA.stage === stepB.stage;
3103
- }
3104
- return false;
3105
- };
3106
- const findStepIndex = (step) => flow.findIndex((flowStep) => stepEqual(step, flowStep));
3107
- return {
3108
- has(step) {
3109
- return findStepIndex(step) !== -1;
3110
- },
3111
- can(step) {
3112
- if (state.step === null) {
3113
- return true;
3114
- }
3115
- const indexesDifference = findStepIndex(step) - findStepIndex(state.step);
3116
- if (indexesDifference === 0 && step.kind === "transfer") {
3117
- return true;
3118
- }
3119
- return indexesDifference > 0;
3120
- },
3121
- cannot(step) {
3122
- return !this.can(step);
3123
- },
3124
- set(step) {
3125
- const canSwitch = this.can(step);
3126
- if (!canSwitch) {
3127
- throw new Error("Impossible to proceed to the given step");
3128
- }
3129
- state.step = step;
3130
- return this;
3131
- },
3132
- get() {
3133
- return state.step;
3134
- }
3135
- };
3136
- };
3137
- const VALID_TRANSFER_COMMANDS = ["init", "end", "status"];
3138
- const transformUpgradeHeader = (header = "") => {
3139
- return header.split(",").map((s) => s.trim().toLowerCase());
3140
- };
3141
- let timeouts;
3142
- const hasHttpServer = () => {
3143
- return typeof strapi !== "undefined" && !!strapi?.server?.httpServer;
3144
- };
3145
- const disableTimeouts = () => {
3146
- if (!hasHttpServer()) {
3147
- return;
3148
- }
3149
- const { httpServer } = strapi.server;
3150
- if (!timeouts) {
3151
- timeouts = {
3152
- headersTimeout: httpServer.headersTimeout,
3153
- requestTimeout: httpServer.requestTimeout
3154
- };
3155
- }
3156
- httpServer.headersTimeout = 0;
3157
- httpServer.requestTimeout = 0;
3158
- strapi.log.info("[Data transfer] Disabling http timeouts");
3159
- };
3160
- const resetTimeouts = () => {
3161
- if (!hasHttpServer() || !timeouts) {
3162
- return;
3163
- }
3164
- const { httpServer } = strapi.server;
3165
- strapi.log.info("[Data transfer] Restoring http timeouts");
3166
- httpServer.headersTimeout = timeouts.headersTimeout;
3167
- httpServer.requestTimeout = timeouts.requestTimeout;
3168
- };
3169
- const assertValidHeader = (ctx) => {
3170
- if (ctx.headers.upgrade === "websocket") {
3171
- return;
3172
- }
3173
- const upgradeHeader = transformUpgradeHeader(ctx.headers.upgrade);
3174
- const logSafeUpgradeHeader = JSON.stringify(ctx.headers.upgrade)?.replace(/[^a-z0-9\s.,|]/gi, "").substring(0, 50);
3175
- if (!upgradeHeader.includes("websocket")) {
3176
- throw new Error(
3177
- `Transfer Upgrade header expected 'websocket', found '${logSafeUpgradeHeader}'. Please ensure that your server or proxy is not modifying the Upgrade header.`
3178
- );
3179
- }
3180
- strapi.log.info(
3181
- `Transfer Upgrade header expected only 'websocket', found unexpected values: ${logSafeUpgradeHeader}`
3182
- );
3183
- };
3184
- const isDataTransferMessage = (message) => {
3185
- if (!message || typeof message !== "object") {
3186
- return false;
3187
- }
3188
- const { uuid, type } = message;
3189
- if (typeof uuid !== "string" || typeof type !== "string") {
3190
- return false;
3191
- }
3192
- if (!["command", "transfer"].includes(type)) {
3193
- return false;
3194
- }
3195
- return true;
3196
- };
3197
- const handleWSUpgrade = (wss, ctx, callback) => {
3198
- assertValidHeader(ctx);
3199
- wss.handleUpgrade(ctx.req, ctx.request.socket, Buffer.alloc(0), (client, request) => {
3200
- if (!client) {
3201
- ctx.request.socket.destroy();
3202
- return;
3203
- }
3204
- disableTimeouts();
3205
- wss.emit("connection", client, ctx.req);
3206
- callback(client, request);
3207
- });
3208
- ctx.respond = false;
3209
- };
3210
- const handlerControllerFactory = (implementation) => (options) => {
3211
- const { verify, server: serverOptions } = options ?? {};
3212
- const wss = new ws.WebSocket.Server({ ...serverOptions, noServer: true });
3213
- return async (ctx) => {
3214
- const cb = (ws2) => {
3215
- const state = { id: void 0 };
3216
- const messageUUIDs = /* @__PURE__ */ new Set();
3217
- const cannotRespondHandler = (err) => {
3218
- strapi?.log?.error(
3219
- "[Data transfer] Cannot send error response to client, closing connection"
3220
- );
3221
- strapi?.log?.error(err);
3222
- try {
3223
- ws2.terminate();
3224
- ctx.req.socket.destroy();
3225
- } catch (err2) {
3226
- strapi?.log?.error("[Data transfer] Failed to close socket on error");
3227
- }
3228
- };
3229
- const prototype = {
3230
- // Transfer ID
3231
- get transferID() {
3232
- return state.id;
3233
- },
3234
- set transferID(id) {
3235
- state.id = id;
3236
- },
3237
- // Started at
3238
- get startedAt() {
3239
- return state.startedAt;
3240
- },
3241
- set startedAt(timestamp) {
3242
- state.startedAt = timestamp;
3243
- },
3244
- get response() {
3245
- return state.response;
3246
- },
3247
- set response(response) {
3248
- state.response = response;
3249
- },
3250
- addUUID(uuid) {
3251
- messageUUIDs.add(uuid);
3252
- },
3253
- hasUUID(uuid) {
3254
- return messageUUIDs.has(uuid);
3255
- },
3256
- isTransferStarted() {
3257
- return this.transferID !== void 0 && this.startedAt !== void 0;
3258
- },
3259
- assertValidTransfer() {
3260
- const isStarted = this.isTransferStarted();
3261
- if (!isStarted) {
3262
- throw new Error("Invalid Transfer Process");
3263
- }
3264
- },
3265
- assertValidTransferCommand(command) {
3266
- const isDefined = typeof this[command] === "function";
3267
- const isValidTransferCommand = VALID_TRANSFER_COMMANDS.includes(command);
3268
- if (!isDefined || !isValidTransferCommand) {
3269
- throw new Error("Invalid transfer command");
3270
- }
3271
- },
3272
- async respond(uuid, e, data) {
3273
- let details = {};
3274
- return new Promise((resolve, reject2) => {
3275
- if (!uuid && !e) {
3276
- reject2(new Error("Missing uuid for this message"));
3277
- return;
3278
- }
3279
- this.response = {
3280
- uuid,
3281
- data,
3282
- e
3283
- };
3284
- if (e instanceof ProviderError) {
3285
- details = e.details;
3286
- }
3287
- const payload = JSON.stringify({
3288
- uuid,
3289
- data: data ?? null,
3290
- error: e ? {
3291
- code: e?.name ?? "ERR",
3292
- message: e?.message,
3293
- details
3294
- } : null
3295
- });
3296
- this.send(payload, (error) => error ? reject2(error) : resolve());
3297
- });
3298
- },
3299
- send(message, cb2) {
3300
- ws2.send(message, cb2);
3301
- },
3302
- confirm(message) {
3303
- return new Promise((resolve, reject2) => {
3304
- const uuid = crypto.randomUUID();
3305
- const payload = JSON.stringify({ uuid, data: message });
3306
- this.send(payload, (error) => {
3307
- if (error) {
3308
- reject2(error);
3309
- }
3310
- });
3311
- const onResponse = (raw) => {
3312
- const response = JSON.parse(raw.toString());
3313
- if (response.uuid === uuid) {
3314
- resolve(response.data ?? null);
3315
- } else {
3316
- ws2.once("message", onResponse);
3317
- }
3318
- };
3319
- ws2.once("message", onResponse);
3320
- });
3321
- },
3322
- async executeAndRespond(uuid, fn) {
3323
- try {
3324
- const response = await fn();
3325
- await this.respond(uuid, null, response);
3326
- } catch (e) {
3327
- if (e instanceof Error) {
3328
- await this.respond(uuid, e).catch(cannotRespondHandler);
3329
- } else if (typeof e === "string") {
3330
- await this.respond(uuid, new ProviderTransferError(e)).catch(cannotRespondHandler);
3331
- } else {
3332
- await this.respond(
3333
- uuid,
3334
- new ProviderTransferError("Unexpected error", {
3335
- error: e
3336
- })
3337
- ).catch(cannotRespondHandler);
3338
- }
3339
- }
3340
- },
3341
- cleanup() {
3342
- this.transferID = void 0;
3343
- this.startedAt = void 0;
3344
- this.response = void 0;
3345
- },
3346
- teardown() {
3347
- this.cleanup();
3348
- },
3349
- verifyAuth(scope) {
3350
- return verify(ctx, scope);
3351
- },
3352
- // Transfer commands
3353
- init() {
3354
- },
3355
- end() {
3356
- },
3357
- status() {
3358
- },
3359
- // Default prototype implementation for events
3360
- onMessage() {
3361
- },
3362
- onError() {
3363
- },
3364
- onClose() {
3365
- }
3366
- };
3367
- const handler = Object.assign(Object.create(prototype), implementation(prototype));
3368
- ws2.on("close", async (...args) => {
3369
- try {
3370
- await handler.onClose(...args);
3371
- } catch (err) {
3372
- strapi?.log?.error("[Data transfer] Uncaught error closing connection");
3373
- strapi?.log?.error(err);
3374
- cannotRespondHandler(err);
3375
- } finally {
3376
- resetTimeouts();
3377
- }
3378
- });
3379
- ws2.on("error", async (...args) => {
3380
- try {
3381
- await handler.onError(...args);
3382
- } catch (err) {
3383
- strapi?.log?.error("[Data transfer] Uncaught error in error handling");
3384
- strapi?.log?.error(err);
3385
- cannotRespondHandler(err);
3386
- }
3387
- });
3388
- ws2.on("message", async (...args) => {
3389
- try {
3390
- await handler.onMessage(...args);
3391
- } catch (err) {
3392
- strapi?.log?.error("[Data transfer] Uncaught error in message handling");
3393
- strapi?.log?.error(err);
3394
- cannotRespondHandler(err);
3395
- }
3396
- });
3397
- };
3398
- try {
3399
- handleWSUpgrade(wss, ctx, cb);
3400
- } catch (err) {
3401
- strapi?.log?.error("[Data transfer] Error in websocket upgrade request");
3402
- strapi?.log?.error(err);
3403
- }
3404
- };
3405
- };
3406
- const VALID_TRANSFER_ACTIONS$1 = [
3407
- "bootstrap",
3408
- "close",
3409
- "rollback",
3410
- "beforeTransfer",
3411
- "getMetadata",
3412
- "getSchemas"
3413
- ];
3414
- const TRANSFER_KIND$1 = "push";
3415
- const writeAsync = (stream2, data) => {
3416
- return new Promise((resolve, reject2) => {
3417
- stream2.write(data, (error) => {
3418
- if (error) {
3419
- reject2(error);
3420
- }
3421
- resolve();
3422
- });
3423
- });
3424
- };
3425
- const createPushController = handlerControllerFactory((proto) => ({
3426
- isTransferStarted() {
3427
- return proto.isTransferStarted.call(this) && this.provider !== void 0;
3428
- },
3429
- verifyAuth() {
3430
- return proto.verifyAuth.call(this, TRANSFER_KIND$1);
3431
- },
3432
- cleanup() {
3433
- proto.cleanup.call(this);
3434
- this.streams = {};
3435
- this.assets = {};
3436
- delete this.flow;
3437
- delete this.provider;
3438
- },
3439
- teardown() {
3440
- if (this.provider) {
3441
- this.provider.rollback();
3442
- }
3443
- proto.teardown.call(this);
3444
- },
3445
- assertValidTransfer() {
3446
- proto.assertValidTransfer.call(this);
3447
- if (this.provider === void 0) {
3448
- throw new Error("Invalid Transfer Process");
3449
- }
3450
- },
3451
- assertValidTransferAction(action) {
3452
- if (VALID_TRANSFER_ACTIONS$1.includes(action)) {
3453
- return;
3454
- }
3455
- throw new ProviderTransferError(`Invalid action provided: "${action}"`, {
3456
- action,
3457
- validActions: Object.keys(VALID_TRANSFER_ACTIONS$1)
3458
- });
3459
- },
3460
- assertValidStreamTransferStep(stage) {
3461
- const currentStep = this.flow?.get();
3462
- const nextStep = { kind: "transfer", stage };
3463
- if (currentStep?.kind === "transfer" && !currentStep.locked) {
3464
- throw new ProviderTransferError(
3465
- `You need to initialize the transfer stage (${nextStep}) before starting to stream data`
3466
- );
3467
- }
3468
- if (this.flow?.cannot(nextStep)) {
3469
- throw new ProviderTransferError(`Invalid stage (${nextStep}) provided for the current flow`, {
3470
- step: nextStep
3471
- });
3472
- }
3473
- },
3474
- async createWritableStreamForStep(step) {
3475
- const mapper = {
3476
- entities: () => this.provider?.createEntitiesWriteStream(),
3477
- links: () => this.provider?.createLinksWriteStream(),
3478
- configuration: () => this.provider?.createConfigurationWriteStream(),
3479
- assets: () => this.provider?.createAssetsWriteStream()
3480
- };
3481
- if (!(step in mapper)) {
3482
- throw new Error("Invalid transfer step, impossible to create a stream");
3483
- }
3484
- if (!this.streams) {
3485
- throw new Error("Invalid transfer state");
3486
- }
3487
- this.streams[step] = await mapper[step]();
3488
- },
3489
- async onMessage(raw) {
3490
- const msg = JSON.parse(raw.toString());
3491
- if (!isDataTransferMessage(msg)) {
3492
- return;
3493
- }
3494
- if (!msg.uuid) {
3495
- await this.respond(void 0, new Error("Missing uuid in message"));
3496
- }
3497
- if (proto.hasUUID(msg.uuid)) {
3498
- const previousResponse = proto.response;
3499
- if (previousResponse?.uuid === msg.uuid) {
3500
- await this.respond(previousResponse?.uuid, previousResponse.e, previousResponse.data);
3501
- }
3502
- return;
3503
- }
3504
- const { uuid, type } = msg;
3505
- proto.addUUID(uuid);
3506
- if (type === "command") {
3507
- const { command } = msg;
3508
- await this.executeAndRespond(uuid, () => {
3509
- this.assertValidTransferCommand(command);
3510
- if (command === "status") {
3511
- return this.status();
3512
- }
3513
- return this[command](msg.params);
3514
- });
3515
- } else if (type === "transfer") {
3516
- await this.executeAndRespond(uuid, async () => {
3517
- await this.verifyAuth();
3518
- this.assertValidTransfer();
3519
- return this.onTransferMessage(msg);
3520
- });
3521
- } else {
3522
- await this.respond(uuid, new Error("Bad Request"));
3523
- }
3524
- },
3525
- async onTransferMessage(msg) {
3526
- const { kind } = msg;
3527
- if (kind === "action") {
3528
- return this.onTransferAction(msg);
3529
- }
3530
- if (kind === "step") {
3531
- return this.onTransferStep(msg);
3532
- }
3533
- },
3534
- lockTransferStep(stage) {
3535
- const currentStep = this.flow?.get();
3536
- const nextStep = { kind: "transfer", stage };
3537
- if (currentStep?.kind === "transfer" && currentStep.locked) {
3538
- throw new ProviderTransferError(
3539
- `It's not possible to start a new transfer stage (${stage}) while another one is in progress (${currentStep.stage})`
3540
- );
3541
- }
3542
- if (this.flow?.cannot(nextStep)) {
3543
- throw new ProviderTransferError(`Invalid stage (${stage}) provided for the current flow`, {
3544
- step: nextStep
3545
- });
3546
- }
3547
- this.flow?.set({ ...nextStep, locked: true });
3548
- },
3549
- unlockTransferStep(stage) {
3550
- const currentStep = this.flow?.get();
3551
- const nextStep = { kind: "transfer", stage };
3552
- if (currentStep?.kind === "transfer" && !currentStep.locked) {
3553
- throw new ProviderTransferError(
3554
- `You need to initialize the transfer stage (${stage}) before ending it`
3555
- );
3556
- }
3557
- if (this.flow?.cannot(nextStep)) {
3558
- throw new ProviderTransferError(`Invalid stage (${stage}) provided for the current flow`, {
3559
- step: nextStep
3560
- });
3561
- }
3562
- this.flow?.set({ ...nextStep, locked: false });
3563
- },
3564
- async onTransferStep(msg) {
3565
- const { step: stage } = msg;
3566
- if (msg.action === "start") {
3567
- this.lockTransferStep(stage);
3568
- if (this.streams?.[stage] instanceof stream$1.Writable) {
3569
- throw new Error("Stream already created, something went wrong");
3570
- }
3571
- await this.createWritableStreamForStep(stage);
3572
- return { ok: true };
3573
- }
3574
- if (msg.action === "stream") {
3575
- this.assertValidStreamTransferStep(stage);
3576
- const stream2 = this.streams?.[stage];
3577
- if (!stream2) {
3578
- throw new Error("You need to init first");
3579
- }
3580
- if (stage === "assets") {
3581
- return this.streamAsset(msg.data);
3582
- }
3583
- await Promise.all(msg.data.map((item) => writeAsync(stream2, item)));
3584
- }
3585
- if (msg.action === "end") {
3586
- this.unlockTransferStep(stage);
3587
- const stream2 = this.streams?.[stage];
3588
- if (stream2 && !stream2.closed) {
3589
- await new Promise((resolve, reject2) => {
3590
- stream2.on("close", resolve).on("error", reject2).end();
3591
- });
3592
- }
3593
- delete this.streams?.[stage];
3594
- return { ok: true };
3595
- }
3596
- },
3597
- async onTransferAction(msg) {
3598
- const { action } = msg;
3599
- this.assertValidTransferAction(action);
3600
- const step = { kind: "action", action };
3601
- const isStepRegistered = this.flow?.has(step);
3602
- if (isStepRegistered) {
3603
- if (this.flow?.cannot(step)) {
3604
- throw new ProviderTransferError(`Invalid action "${action}" found for the current flow `, {
3605
- action
3606
- });
3607
- }
3608
- this.flow?.set(step);
3609
- }
3610
- return this.provider?.[action]();
3611
- },
3612
- async streamAsset(payload) {
3613
- const assetsStream = this.streams?.assets;
3614
- if (payload === null) {
3615
- this.streams?.assets?.end();
3616
- return;
3617
- }
3618
- for (const item of payload) {
3619
- const { action, assetID } = item;
3620
- if (!assetsStream) {
3621
- throw new Error("Stream not defined");
3622
- }
3623
- if (action === "start") {
3624
- this.assets[assetID] = { ...item.data, stream: new stream$1.PassThrough() };
3625
- writeAsync(assetsStream, this.assets[assetID]);
3626
- }
3627
- if (action === "stream") {
3628
- const rawBuffer = item.data;
3629
- const chunk = Buffer.from(rawBuffer.data);
3630
- await writeAsync(this.assets[assetID].stream, chunk);
3631
- }
3632
- if (action === "end") {
3633
- await new Promise((resolve, reject2) => {
3634
- const { stream: assetStream } = this.assets[assetID];
3635
- assetStream.on("close", () => {
3636
- delete this.assets[assetID];
3637
- resolve();
3638
- }).on("error", reject2).end();
3639
- });
3640
- }
3641
- }
3642
- },
3643
- onClose() {
3644
- this.teardown();
3645
- },
3646
- onError(err) {
3647
- this.teardown();
3648
- strapi.log.error(err);
3649
- },
3650
- // Commands
3651
- async init(params) {
3652
- if (this.transferID || this.provider) {
3653
- throw new Error("Transfer already in progress");
3654
- }
3655
- await this.verifyAuth();
3656
- this.transferID = crypto.randomUUID();
3657
- this.startedAt = Date.now();
3658
- this.assets = {};
3659
- this.streams = {};
3660
- this.flow = createFlow(DEFAULT_TRANSFER_FLOW);
3661
- this.provider = createLocalStrapiDestinationProvider({
3662
- ...params.options,
3663
- autoDestroy: false,
3664
- getStrapi: () => strapi
3665
- });
3666
- this.provider.onWarning = (message) => {
3667
- strapi.log.warn(message);
3668
- };
3669
- return { transferID: this.transferID };
3670
- },
3671
- async status() {
3672
- const isStarted = this.isTransferStarted();
3673
- if (isStarted) {
3674
- const startedAt = this.startedAt;
3675
- return {
3676
- active: true,
3677
- kind: TRANSFER_KIND$1,
3678
- startedAt,
3679
- elapsed: Date.now() - startedAt
3680
- };
3681
- }
3682
- return { active: false, kind: null, elapsed: null, startedAt: null };
3683
- },
3684
- async end(params) {
3685
- await this.verifyAuth();
3686
- if (this.transferID !== params?.transferID) {
3687
- throw new ProviderTransferError("Bad transfer ID provided");
3688
- }
3689
- this.cleanup();
3690
- return { ok: true };
3691
- }
3692
- }));
3693
- const TRANSFER_KIND = "pull";
3694
- const VALID_TRANSFER_ACTIONS = ["bootstrap", "close", "getMetadata", "getSchemas"];
3695
- const createPullController = handlerControllerFactory((proto) => ({
3696
- isTransferStarted() {
3697
- return proto.isTransferStarted.call(this) && this.provider !== void 0;
3698
- },
3699
- verifyAuth() {
3700
- return proto.verifyAuth.call(this, TRANSFER_KIND);
3701
- },
3702
- cleanup() {
3703
- proto.cleanup.call(this);
3704
- this.streams = {};
3705
- delete this.provider;
3706
- },
3707
- assertValidTransferAction(action) {
3708
- const validActions = VALID_TRANSFER_ACTIONS;
3709
- if (validActions.includes(action)) {
3710
- return;
3711
- }
3712
- throw new ProviderTransferError(`Invalid action provided: "${action}"`, {
3713
- action,
3714
- validActions: Object.keys(VALID_TRANSFER_ACTIONS)
3715
- });
3716
- },
3717
- async onMessage(raw) {
3718
- const msg = JSON.parse(raw.toString());
3719
- if (!isDataTransferMessage(msg)) {
3720
- return;
3721
- }
3722
- if (!msg.uuid) {
3723
- await this.respond(void 0, new Error("Missing uuid in message"));
3724
- }
3725
- if (proto.hasUUID(msg.uuid)) {
3726
- const previousResponse = proto.response;
3727
- if (previousResponse?.uuid === msg.uuid) {
3728
- await this.respond(previousResponse?.uuid, previousResponse.e, previousResponse.data);
3729
- }
3730
- return;
3731
- }
3732
- const { uuid, type } = msg;
3733
- proto.addUUID(uuid);
3734
- if (type === "command") {
3735
- const { command } = msg;
3736
- await this.executeAndRespond(uuid, () => {
3737
- this.assertValidTransferCommand(command);
3738
- if (command === "status") {
3739
- return this.status();
3740
- }
3741
- return this[command](msg.params);
3742
- });
3743
- } else if (type === "transfer") {
3744
- await this.executeAndRespond(uuid, async () => {
3745
- await this.verifyAuth();
3746
- this.assertValidTransfer();
3747
- return this.onTransferMessage(msg);
3748
- });
3749
- } else {
3750
- await this.respond(uuid, new Error("Bad Request"));
3751
- }
3752
- },
3753
- async onTransferMessage(msg) {
3754
- const { kind } = msg;
3755
- if (kind === "action") {
3756
- return this.onTransferAction(msg);
3757
- }
3758
- if (kind === "step") {
3759
- return this.onTransferStep(msg);
3760
- }
3761
- },
3762
- async onTransferAction(msg) {
3763
- const { action } = msg;
3764
- this.assertValidTransferAction(action);
3765
- return this.provider?.[action]();
3766
- },
3767
- async flush(stage, id) {
3768
- const batchSize = 1024 * 1024;
3769
- let batch = [];
3770
- const stream2 = this.streams?.[stage];
3771
- const batchLength = () => Buffer.byteLength(JSON.stringify(batch));
3772
- const sendBatch = async () => {
3773
- await this.confirm({
3774
- type: "transfer",
3775
- data: batch,
3776
- ended: false,
3777
- error: null,
3778
- id
3779
- });
3780
- };
3781
- if (!stream2) {
3782
- throw new ProviderTransferError(`No available stream found for ${stage}`);
3783
- }
3784
- try {
3785
- for await (const chunk of stream2) {
3786
- if (stage !== "assets") {
3787
- batch.push(chunk);
3788
- if (batchLength() >= batchSize) {
3789
- await sendBatch();
3790
- batch = [];
3791
- }
3792
- } else {
3793
- await this.confirm({
3794
- type: "transfer",
3795
- data: [chunk],
3796
- ended: false,
3797
- error: null,
3798
- id
3799
- });
3800
- }
3801
- }
3802
- if (batch.length > 0 && stage !== "assets") {
3803
- await sendBatch();
3804
- batch = [];
3805
- }
3806
- await this.confirm({ type: "transfer", data: null, ended: true, error: null, id });
3807
- } catch (e) {
3808
- await this.confirm({ type: "transfer", data: null, ended: true, error: e, id });
3809
- }
3810
- },
3811
- async onTransferStep(msg) {
3812
- const { step, action } = msg;
3813
- if (action === "start") {
3814
- if (this.streams?.[step] instanceof stream$1.Readable) {
3815
- throw new Error("Stream already created, something went wrong");
3816
- }
3817
- const flushUUID = crypto.randomUUID();
3818
- await this.createReadableStreamForStep(step);
3819
- this.flush(step, flushUUID);
3820
- return { ok: true, id: flushUUID };
3821
- }
3822
- if (action === "end") {
3823
- const stream2 = this.streams?.[step];
3824
- if (stream2?.readableEnded === false) {
3825
- await new Promise((resolve) => {
3826
- stream2?.on("close", resolve).destroy();
3827
- });
3828
- }
3829
- delete this.streams?.[step];
3830
- return { ok: true };
3831
- }
3832
- },
3833
- async createReadableStreamForStep(step) {
3834
- const mapper = {
3835
- entities: () => this.provider?.createEntitiesReadStream(),
3836
- links: () => this.provider?.createLinksReadStream(),
3837
- configuration: () => this.provider?.createConfigurationReadStream(),
3838
- assets: () => {
3839
- const assets = this.provider?.createAssetsReadStream();
3840
- let batch = [];
3841
- const batchLength = () => {
3842
- return batch.reduce(
3843
- (acc, chunk) => chunk.action === "stream" ? acc + chunk.data.byteLength : acc,
3844
- 0
3845
- );
3846
- };
3847
- const BATCH_MAX_SIZE = 1024 * 1024;
3848
- if (!assets) {
3849
- throw new Error("bad");
3850
- }
3851
- async function* generator(stream2) {
3852
- let hasStarted = false;
3853
- let assetID = "";
3854
- for await (const chunk of stream2) {
3855
- const { stream: assetStream, ...assetData } = chunk;
3856
- if (!hasStarted) {
3857
- assetID = crypto.randomUUID();
3858
- batch.push({ action: "start", assetID, data: assetData });
3859
- hasStarted = true;
3860
- }
3861
- for await (const assetChunk of assetStream) {
3862
- batch.push({ action: "stream", assetID, data: assetChunk });
3863
- if (batchLength() >= BATCH_MAX_SIZE) {
3864
- yield batch;
3865
- batch = [];
3866
- }
3867
- }
3868
- hasStarted = false;
3869
- batch.push({ action: "end", assetID });
3870
- yield batch;
3871
- batch = [];
3872
- }
3873
- }
3874
- return stream$1.Readable.from(generator(assets));
3875
- }
3876
- };
3877
- if (!(step in mapper)) {
3878
- throw new Error("Invalid transfer step, impossible to create a stream");
3879
- }
3880
- if (!this.streams) {
3881
- throw new Error("Invalid transfer state");
3882
- }
3883
- this.streams[step] = await mapper[step]();
3884
- },
3885
- // Commands
3886
- async init() {
3887
- if (this.transferID || this.provider) {
3888
- throw new Error("Transfer already in progress");
3889
- }
3890
- await this.verifyAuth();
3891
- this.transferID = crypto.randomUUID();
3892
- this.startedAt = Date.now();
3893
- this.streams = {};
3894
- this.provider = createLocalStrapiSourceProvider({
3895
- autoDestroy: false,
3896
- getStrapi: () => strapi
3897
- });
3898
- return { transferID: this.transferID };
3899
- },
3900
- async end(params) {
3901
- await this.verifyAuth();
3902
- if (this.transferID !== params?.transferID) {
3903
- throw new ProviderTransferError("Bad transfer ID provided");
3904
- }
3905
- this.cleanup();
3906
- return { ok: true };
3907
- },
3908
- async status() {
3909
- const isStarted = this.isTransferStarted();
3910
- if (!isStarted) {
3911
- const startedAt = this.startedAt;
3912
- return {
3913
- active: true,
3914
- kind: TRANSFER_KIND,
3915
- startedAt,
3916
- elapsed: Date.now() - startedAt
3917
- };
3918
- }
3919
- return { active: false, kind: null, elapsed: null, startedAt: null };
3920
- }
3921
- }));
3922
- const index$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3923
- __proto__: null,
3924
- createPullController,
3925
- createPushController,
3926
- handlerControllerFactory
3927
- }, Symbol.toStringTag, { value: "Module" }));
3928
- const index$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3929
- __proto__: null,
3930
- constants,
3931
- handlers: index$4
3932
- }, Symbol.toStringTag, { value: "Module" }));
3933
- const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3934
- __proto__: null,
3935
- providers: index$5,
3936
- queries: index$6,
3937
- remote: index$3
3938
- }, Symbol.toStringTag, { value: "Module" }));
3939
- const isFilePathInDirname = (posixDirName, filePath) => {
3940
- const normalizedDir = path__default.default.posix.dirname(unknownPathToPosix(filePath));
3941
- return isPathEquivalent(posixDirName, normalizedDir);
3942
- };
3943
- const isPathEquivalent = (pathA, pathB) => {
3944
- const normalizedPathA = path__default.default.posix.normalize(unknownPathToPosix(pathA));
3945
- const normalizedPathB = path__default.default.posix.normalize(unknownPathToPosix(pathB));
3946
- return !path__default.default.posix.relative(normalizedPathB, normalizedPathA).length;
3947
- };
3948
- const unknownPathToPosix = (filePath) => {
3949
- if (filePath.includes(path__default.default.posix.sep)) {
3950
- return filePath;
3951
- }
3952
- return path__default.default.normalize(filePath).split(path__default.default.win32.sep).join(path__default.default.posix.sep);
3953
- };
3954
- const METADATA_FILE_PATH = "metadata.json";
3955
- const createLocalFileSourceProvider = (options) => {
3956
- return new LocalFileSourceProvider(options);
3957
- };
3958
- class LocalFileSourceProvider {
3959
- type = "source";
3960
- name = "source::local-file";
3961
- options;
3962
- #metadata;
3963
- constructor(options) {
3964
- this.options = options;
3965
- const { encryption } = this.options;
3966
- if (encryption.enabled && encryption.key === void 0) {
3967
- throw new Error("Missing encryption key");
3968
- }
3969
- }
3970
- /**
3971
- * Pre flight checks regarding the provided options, making sure that the file can be opened (decrypted, decompressed), etc.
3972
- */
3973
- async bootstrap() {
3974
- const { path: filePath } = this.options.file;
3975
- try {
3976
- await this.#loadMetadata();
3977
- } catch (e) {
3978
- if (this.options?.encryption?.enabled) {
3979
- throw new ProviderInitializationError(
3980
- `Key is incorrect or the file '${filePath}' is not a valid Strapi data file.`
3981
- );
3982
- }
3983
- throw new ProviderInitializationError(`File '${filePath}' is not a valid Strapi data file.`);
3984
- }
3985
- if (!this.#metadata) {
3986
- throw new ProviderInitializationError("Could not load metadata from Strapi data file.");
3987
- }
3988
- }
3989
- async #loadMetadata() {
3990
- const backupStream = this.#getBackupStream();
3991
- this.#metadata = await this.#parseJSONFile(backupStream, METADATA_FILE_PATH);
3992
- }
3993
- async #loadAssetMetadata(path2) {
3994
- const backupStream = this.#getBackupStream();
3995
- return this.#parseJSONFile(backupStream, path2);
3996
- }
3997
- async getMetadata() {
3998
- if (!this.#metadata) {
3999
- await this.#loadMetadata();
4000
- }
4001
- return this.#metadata ?? null;
4002
- }
4003
- async getSchemas() {
4004
- const schemaCollection = await collect(
4005
- this.createSchemasReadStream()
4006
- );
4007
- if (fp.isEmpty(schemaCollection)) {
4008
- throw new ProviderInitializationError("Could not load schemas from Strapi data file.");
4009
- }
4010
- const schemas = fp.keyBy("uid", schemaCollection);
4011
- return schemasToValidJSON(schemas);
4012
- }
4013
- createEntitiesReadStream() {
4014
- return this.#streamJsonlDirectory("entities");
4015
- }
4016
- createSchemasReadStream() {
4017
- return this.#streamJsonlDirectory("schemas");
4018
- }
4019
- createLinksReadStream() {
4020
- return this.#streamJsonlDirectory("links");
4021
- }
4022
- createConfigurationReadStream() {
4023
- return this.#streamJsonlDirectory("configuration");
4024
- }
4025
- createAssetsReadStream() {
4026
- const inStream = this.#getBackupStream();
4027
- const outStream = new stream$1.PassThrough({ objectMode: true });
4028
- const loadAssetMetadata = this.#loadAssetMetadata.bind(this);
4029
- stream$1.pipeline(
4030
- [
4031
- inStream,
4032
- new tar__default.default.Parse({
4033
- // find only files in the assets/uploads folder
4034
- filter(filePath, entry) {
4035
- if (entry.type !== "File") {
4036
- return false;
4037
- }
4038
- return isFilePathInDirname("assets/uploads", filePath);
4039
- },
4040
- async onentry(entry) {
4041
- const { path: filePath, size = 0 } = entry;
4042
- const normalizedPath = unknownPathToPosix(filePath);
4043
- const file = path__default.default.basename(normalizedPath);
4044
- let metadata;
4045
- try {
4046
- metadata = await loadAssetMetadata(`assets/metadata/${file}.json`);
4047
- } catch (error) {
4048
- console.warn(
4049
- ` Failed to read metadata for ${file}, Strapi will try to fix this issue automatically`
4050
- );
4051
- }
4052
- const asset = {
4053
- metadata,
4054
- filename: file,
4055
- filepath: normalizedPath,
4056
- stats: { size },
4057
- stream: entry
4058
- };
4059
- outStream.write(asset);
4060
- }
4061
- })
4062
- ],
4063
- () => outStream.end()
4064
- );
4065
- return outStream;
4066
- }
4067
- #getBackupStream() {
4068
- const { file, encryption, compression } = this.options;
4069
- const streams = [];
4070
- try {
4071
- streams.push(fse__namespace.default.createReadStream(file.path));
4072
- } catch (e) {
4073
- throw new Error(`Could not read backup file path provided at "${this.options.file.path}"`);
4074
- }
4075
- if (encryption.enabled && encryption.key) {
4076
- streams.push(createDecryptionCipher(encryption.key));
4077
- }
4078
- if (compression.enabled) {
4079
- streams.push(zip__default.default.createGunzip());
4080
- }
4081
- return streamChain.chain(streams);
4082
- }
4083
- // `directory` must be posix formatted path
4084
- #streamJsonlDirectory(directory) {
4085
- const inStream = this.#getBackupStream();
4086
- const outStream = new stream$1.PassThrough({ objectMode: true });
4087
- stream$1.pipeline(
4088
- [
4089
- inStream,
4090
- new tar__default.default.Parse({
4091
- filter(filePath, entry) {
4092
- if (entry.type !== "File") {
4093
- return false;
4094
- }
4095
- return isFilePathInDirname(directory, filePath);
4096
- },
4097
- async onentry(entry) {
4098
- const transforms = [
4099
- // JSONL parser to read the data chunks one by one (line by line)
4100
- Parser.parser({
4101
- checkErrors: true
4102
- }),
4103
- // The JSONL parser returns each line as key/value
4104
- (line) => line.value
4105
- ];
4106
- const stream2 = entry.pipe(streamChain.chain(transforms));
4107
- try {
4108
- for await (const chunk of stream2) {
4109
- outStream.write(chunk);
4110
- }
4111
- } catch (e) {
4112
- outStream.destroy(
4113
- new ProviderTransferError(
4114
- `Error parsing backup files from backup file ${entry.path}: ${e.message}`,
4115
- {
4116
- details: {
4117
- error: e
4118
- }
4119
- }
4120
- )
4121
- );
4122
- }
4123
- }
4124
- })
4125
- ],
4126
- async () => {
4127
- outStream.end();
4128
- }
4129
- );
4130
- return outStream;
4131
- }
4132
- // For collecting an entire JSON file then parsing it, not for streaming JSONL
4133
- async #parseJSONFile(fileStream, filePath) {
4134
- return new Promise((resolve, reject2) => {
4135
- stream$1.pipeline(
4136
- [
4137
- fileStream,
4138
- // Custom backup archive parsing
4139
- new tar__default.default.Parse({
4140
- /**
4141
- * Filter the parsed entries to only keep the one that matches the given filepath
4142
- */
4143
- filter(entryPath, entry) {
4144
- if (entry.type !== "File") {
4145
- return false;
4146
- }
4147
- return isPathEquivalent(entryPath, filePath);
4148
- },
4149
- async onentry(entry) {
4150
- const content = await entry.collect();
4151
- try {
4152
- const parsedContent = JSON.parse(Buffer.concat(content).toString());
4153
- resolve(parsedContent);
4154
- } catch (e) {
4155
- reject2(e);
4156
- } finally {
4157
- entry.destroy();
4158
- }
4159
- }
4160
- })
4161
- ],
4162
- () => {
4163
- reject2(new Error(`File "${filePath}" not found`));
4164
- }
4165
- );
4166
- });
4167
- }
4168
- }
4169
- const createFilePathFactory = (type) => (fileIndex = 0) => {
4170
- return path.posix.join(
4171
- // "{type}" directory
4172
- type,
4173
- // "${type}_XXXXX.jsonl" file
4174
- `${type}_${String(fileIndex).padStart(5, "0")}.jsonl`
4175
- );
4176
- };
4177
- const createTarEntryStream = (archive, pathFactory, maxSize = 256e6) => {
4178
- let fileIndex = 0;
4179
- let buffer = "";
4180
- const flush = async () => {
4181
- if (!buffer) {
4182
- return;
4183
- }
4184
- fileIndex += 1;
4185
- const name = pathFactory(fileIndex);
4186
- const size = buffer.length;
4187
- await new Promise((resolve, reject2) => {
4188
- archive.entry({ name, size }, buffer, (err) => {
4189
- if (err) {
4190
- reject2(err);
4191
- }
4192
- resolve();
4193
- });
4194
- });
4195
- buffer = "";
4196
- };
4197
- const push = (chunk) => {
4198
- buffer += chunk;
4199
- };
4200
- return new stream$1.Writable({
4201
- async destroy(err, callback) {
4202
- await flush();
4203
- callback(err);
4204
- },
4205
- async write(chunk, _encoding, callback) {
4206
- const size = chunk.length;
4207
- if (chunk.length > maxSize) {
4208
- callback(new Error(`payload too large: ${chunk.length}>${maxSize}`));
4209
- return;
4210
- }
4211
- if (buffer.length + size > maxSize) {
4212
- await flush();
4213
- }
4214
- push(chunk);
4215
- callback(null);
4216
- }
4217
- });
4218
- };
4219
- const createLocalFileDestinationProvider = (options) => {
4220
- return new LocalFileDestinationProvider(options);
4221
- };
4222
- class LocalFileDestinationProvider {
4223
- name = "destination::local-file";
4224
- type = "destination";
4225
- options;
4226
- results = {};
4227
- #providersMetadata = {};
4228
- #archive = {};
4229
- constructor(options) {
4230
- this.options = options;
4231
- }
4232
- get #archivePath() {
4233
- const { encryption, compression, file } = this.options;
4234
- let filePath = `${file.path}.tar`;
4235
- if (compression.enabled) {
4236
- filePath += ".gz";
4237
- }
4238
- if (encryption.enabled) {
4239
- filePath += ".enc";
4240
- }
4241
- return filePath;
4242
- }
4243
- setMetadata(target, metadata) {
4244
- this.#providersMetadata[target] = metadata;
4245
- return this;
4246
- }
4247
- createGzip() {
4248
- return zip__default.default.createGzip();
4249
- }
4250
- bootstrap() {
4251
- const { compression, encryption } = this.options;
4252
- if (encryption.enabled && !encryption.key) {
4253
- throw new Error("Can't encrypt without a key");
4254
- }
4255
- this.#archive.stream = tar__default$1.default.pack();
4256
- const outStream = fse.createWriteStream(this.#archivePath);
4257
- outStream.on("error", (err) => {
4258
- if (err.code === "ENOSPC") {
4259
- throw new ProviderTransferError(
4260
- "Your server doesn't have space to proceed with the import."
4261
- );
4262
- }
4263
- throw err;
4264
- });
4265
- const archiveTransforms = [];
4266
- if (compression.enabled) {
4267
- archiveTransforms.push(this.createGzip());
4268
- }
4269
- if (encryption.enabled && encryption.key) {
4270
- archiveTransforms.push(createEncryptionCipher(encryption.key));
4271
- }
4272
- this.#archive.pipeline = streamChain.chain([this.#archive.stream, ...archiveTransforms, outStream]);
4273
- this.results.file = { path: this.#archivePath };
4274
- }
4275
- async close() {
4276
- const { stream: stream2, pipeline } = this.#archive;
4277
- if (!stream2) {
4278
- return;
4279
- }
4280
- await this.#writeMetadata();
4281
- stream2.finalize();
4282
- if (pipeline && !pipeline.closed) {
4283
- await new Promise((resolve, reject2) => {
4284
- pipeline.on("close", resolve).on("error", reject2);
4285
- });
4286
- }
4287
- }
4288
- async rollback() {
4289
- await this.close();
4290
- await fse.rm(this.#archivePath, { force: true });
4291
- }
4292
- getMetadata() {
4293
- return null;
4294
- }
4295
- async #writeMetadata() {
4296
- const metadata = this.#providersMetadata.source;
4297
- if (metadata) {
4298
- await new Promise((resolve) => {
4299
- const outStream = this.#getMetadataStream();
4300
- const data = JSON.stringify(metadata, null, 2);
4301
- stream$1.Readable.from(data).pipe(outStream).on("close", resolve);
4302
- });
4303
- }
4304
- }
4305
- #getMetadataStream() {
4306
- const { stream: stream2 } = this.#archive;
4307
- if (!stream2) {
4308
- throw new Error("Archive stream is unavailable");
4309
- }
4310
- return createTarEntryStream(stream2, () => "metadata.json");
4311
- }
4312
- createSchemasWriteStream() {
4313
- if (!this.#archive.stream) {
4314
- throw new Error("Archive stream is unavailable");
4315
- }
4316
- const filePathFactory = createFilePathFactory("schemas");
4317
- const entryStream = createTarEntryStream(
4318
- this.#archive.stream,
4319
- filePathFactory,
4320
- this.options.file.maxSizeJsonl
4321
- );
4322
- return streamChain.chain([Stringer.stringer(), entryStream]);
4323
- }
4324
- createEntitiesWriteStream() {
4325
- if (!this.#archive.stream) {
4326
- throw new Error("Archive stream is unavailable");
4327
- }
4328
- const filePathFactory = createFilePathFactory("entities");
4329
- const entryStream = createTarEntryStream(
4330
- this.#archive.stream,
4331
- filePathFactory,
4332
- this.options.file.maxSizeJsonl
4333
- );
4334
- return streamChain.chain([Stringer.stringer(), entryStream]);
4335
- }
4336
- createLinksWriteStream() {
4337
- if (!this.#archive.stream) {
4338
- throw new Error("Archive stream is unavailable");
4339
- }
4340
- const filePathFactory = createFilePathFactory("links");
4341
- const entryStream = createTarEntryStream(
4342
- this.#archive.stream,
4343
- filePathFactory,
4344
- this.options.file.maxSizeJsonl
4345
- );
4346
- return streamChain.chain([Stringer.stringer(), entryStream]);
4347
- }
4348
- createConfigurationWriteStream() {
4349
- if (!this.#archive.stream) {
4350
- throw new Error("Archive stream is unavailable");
4351
- }
4352
- const filePathFactory = createFilePathFactory("configuration");
4353
- const entryStream = createTarEntryStream(
4354
- this.#archive.stream,
4355
- filePathFactory,
4356
- this.options.file.maxSizeJsonl
4357
- );
4358
- return streamChain.chain([Stringer.stringer(), entryStream]);
4359
- }
4360
- createAssetsWriteStream() {
4361
- const { stream: archiveStream } = this.#archive;
4362
- if (!archiveStream) {
4363
- throw new Error("Archive stream is unavailable");
4364
- }
4365
- return new stream$1.Writable({
4366
- objectMode: true,
4367
- write(data, _encoding, callback) {
4368
- const entryPath = path__default.default.posix.join("assets", "uploads", data.filename);
4369
- const entryMetadataPath = path__default.default.posix.join("assets", "metadata", `${data.filename}.json`);
4370
- const stringifiedMetadata = JSON.stringify(data.metadata);
4371
- archiveStream.entry(
4372
- {
4373
- name: entryMetadataPath,
4374
- size: stringifiedMetadata.length
4375
- },
4376
- stringifiedMetadata
4377
- );
4378
- const entry = archiveStream.entry({
4379
- name: entryPath,
4380
- size: data.stats.size
4381
- });
4382
- if (!entry) {
4383
- callback(new Error(`Failed to created an asset tar entry for ${entryPath}`));
4384
- return;
4385
- }
4386
- data.stream.pipe(entry);
4387
- entry.on("finish", () => {
4388
- callback(null);
4389
- }).on("error", (error) => {
4390
- callback(error);
4391
- });
4392
- }
4393
- });
4394
- }
4395
- }
4396
- const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4397
- __proto__: null,
4398
- createLocalFileDestinationProvider,
4399
- createLocalFileSourceProvider
4400
- }, Symbol.toStringTag, { value: "Module" }));
4401
- const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
4402
- __proto__: null,
4403
- providers: index$1
4404
- }, Symbol.toStringTag, { value: "Module" }));
4405
- exports.engine = index$7;
4406
- exports.file = index;
4407
- exports.strapi = index$2;
4408
- exports.utils = index$8;
1
+ 'use strict';
2
+
3
+ var index$1 = require('./engine/index.js');
4
+ var index$3 = require('./strapi/index.js');
5
+ var index$2 = require('./file/index.js');
6
+ var index = require('./directory/index.js');
7
+ var index$4 = require('./utils/index.js');
8
+
9
+
10
+
11
+ exports.engine = index$1;
12
+ exports.strapi = index$3;
13
+ exports.file = index$2;
14
+ exports.directory = index;
15
+ exports.utils = index$4;
4409
16
  //# sourceMappingURL=index.js.map