@webiny/api-page-builder-import-export 0.0.0-mt-3 → 0.0.0-unstable.3386f66516

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 (120) hide show
  1. package/client.d.ts +8 -0
  2. package/client.js +47 -0
  3. package/client.js.map +1 -0
  4. package/export/combine/blocksHandler.d.ts +6 -0
  5. package/export/combine/blocksHandler.js +106 -0
  6. package/export/combine/blocksHandler.js.map +1 -0
  7. package/export/combine/index.d.ts +16 -0
  8. package/export/combine/index.js +43 -0
  9. package/export/combine/index.js.map +1 -0
  10. package/export/combine/pagesHandler.d.ts +6 -0
  11. package/export/combine/pagesHandler.js +106 -0
  12. package/export/combine/pagesHandler.js.map +1 -0
  13. package/export/combine/templatesHandler.d.ts +6 -0
  14. package/export/combine/templatesHandler.js +106 -0
  15. package/export/combine/templatesHandler.js.map +1 -0
  16. package/export/process/blocksHandler.d.ts +6 -0
  17. package/export/process/blocksHandler.js +176 -0
  18. package/export/process/blocksHandler.js.map +1 -0
  19. package/export/process/index.d.ts +20 -0
  20. package/export/process/index.js +40 -0
  21. package/export/process/index.js.map +1 -0
  22. package/export/process/pagesHandler.d.ts +6 -0
  23. package/export/process/pagesHandler.js +204 -0
  24. package/export/process/pagesHandler.js.map +1 -0
  25. package/export/process/templatesHandler.d.ts +6 -0
  26. package/export/process/templatesHandler.js +176 -0
  27. package/export/process/templatesHandler.js.map +1 -0
  28. package/{exportPages → export}/s3Stream.d.ts +2 -0
  29. package/{exportPages → export}/s3Stream.js +14 -7
  30. package/export/s3Stream.js.map +1 -0
  31. package/export/utils.d.ts +22 -0
  32. package/export/utils.js +173 -0
  33. package/export/utils.js.map +1 -0
  34. package/{exportPages → export}/zipper.d.ts +7 -5
  35. package/{exportPages → export}/zipper.js +11 -12
  36. package/export/zipper.js.map +1 -0
  37. package/graphql/crud/blocks.crud.d.ts +4 -0
  38. package/graphql/crud/blocks.crud.js +155 -0
  39. package/graphql/crud/blocks.crud.js.map +1 -0
  40. package/graphql/crud/importExportTasks.crud.d.ts +5 -0
  41. package/graphql/crud/{pageImportExportTasks.crud.js → importExportTasks.crud.js} +82 -65
  42. package/graphql/crud/importExportTasks.crud.js.map +1 -0
  43. package/graphql/crud/pages.crud.d.ts +3 -3
  44. package/graphql/crud/pages.crud.js +46 -34
  45. package/graphql/crud/pages.crud.js.map +1 -0
  46. package/graphql/crud/templates.crud.d.ts +4 -0
  47. package/graphql/crud/templates.crud.js +140 -0
  48. package/graphql/crud/templates.crud.js.map +1 -0
  49. package/graphql/crud.d.ts +2 -2
  50. package/graphql/crud.js +7 -3
  51. package/graphql/crud.js.map +1 -0
  52. package/graphql/graphql/blocks.gql.d.ts +4 -0
  53. package/graphql/graphql/blocks.gql.js +57 -0
  54. package/graphql/graphql/blocks.gql.js.map +1 -0
  55. package/graphql/graphql/importExportTasks.gql.d.ts +4 -0
  56. package/graphql/graphql/{pageImportExportTasks.gql.js → importExportTasks.gql.js} +18 -18
  57. package/graphql/graphql/importExportTasks.gql.js.map +1 -0
  58. package/graphql/graphql/pages.gql.d.ts +2 -2
  59. package/graphql/graphql/pages.gql.js +4 -8
  60. package/graphql/graphql/pages.gql.js.map +1 -0
  61. package/graphql/graphql/templates.gql.d.ts +4 -0
  62. package/graphql/graphql/templates.gql.js +57 -0
  63. package/graphql/graphql/templates.gql.js.map +1 -0
  64. package/graphql/graphql/utils/resolve.d.ts +1 -1
  65. package/graphql/graphql/utils/resolve.js.map +1 -0
  66. package/graphql/graphql.d.ts +1 -1
  67. package/graphql/graphql.js +7 -3
  68. package/graphql/graphql.js.map +1 -0
  69. package/graphql/index.d.ts +2 -2
  70. package/graphql/index.js +1 -1
  71. package/graphql/index.js.map +1 -0
  72. package/graphql/types.d.ts +63 -27
  73. package/graphql/types.js.map +1 -0
  74. package/import/create/blocksHandler.d.ts +3 -0
  75. package/import/create/blocksHandler.js +110 -0
  76. package/import/create/blocksHandler.js.map +1 -0
  77. package/import/create/index.d.ts +24 -0
  78. package/import/create/index.js +43 -0
  79. package/import/create/index.js.map +1 -0
  80. package/import/create/pagesHandler.d.ts +3 -0
  81. package/import/create/pagesHandler.js +112 -0
  82. package/import/create/pagesHandler.js.map +1 -0
  83. package/import/create/templatesHandler.d.ts +3 -0
  84. package/import/create/templatesHandler.js +108 -0
  85. package/import/create/templatesHandler.js.map +1 -0
  86. package/import/process/blocksHandler.d.ts +3 -0
  87. package/import/process/blocksHandler.js +175 -0
  88. package/import/process/blocksHandler.js.map +1 -0
  89. package/import/process/index.d.ts +20 -0
  90. package/import/process/index.js +40 -0
  91. package/import/process/index.js.map +1 -0
  92. package/import/process/pagesHandler.d.ts +3 -0
  93. package/import/process/pagesHandler.js +181 -0
  94. package/import/process/pagesHandler.js.map +1 -0
  95. package/import/process/templatesHandler.d.ts +3 -0
  96. package/import/process/templatesHandler.js +172 -0
  97. package/import/process/templatesHandler.js.map +1 -0
  98. package/import/utils.d.ts +56 -0
  99. package/{importPages → import}/utils.js +246 -89
  100. package/import/utils.js.map +1 -0
  101. package/mockSecurity.js.map +1 -0
  102. package/package.json +36 -34
  103. package/types.d.ts +70 -72
  104. package/types.js +17 -17
  105. package/types.js.map +1 -0
  106. package/exportPages/combine/index.d.ts +0 -19
  107. package/exportPages/combine/index.js +0 -88
  108. package/exportPages/process/index.d.ts +0 -26
  109. package/exportPages/process/index.js +0 -204
  110. package/exportPages/utils.d.ts +0 -13
  111. package/exportPages/utils.js +0 -113
  112. package/graphql/crud/pageImportExportTasks.crud.d.ts +0 -5
  113. package/graphql/graphql/pageImportExportTasks.gql.d.ts +0 -4
  114. package/importPages/client.d.ts +0 -7
  115. package/importPages/client.js +0 -40
  116. package/importPages/create/index.d.ts +0 -27
  117. package/importPages/create/index.js +0 -109
  118. package/importPages/process/index.d.ts +0 -25
  119. package/importPages/process/index.js +0 -183
  120. package/importPages/utils.d.ts +0 -43
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.templatesHandler = void 0;
7
+
8
+ var _types = require("../../types");
9
+
10
+ var _client = require("../../client");
11
+
12
+ var _handlerGraphql = require("@webiny/handler-graphql");
13
+
14
+ var _utils = require("../utils");
15
+
16
+ var _mockSecurity = require("../../mockSecurity");
17
+
18
+ var _utils2 = require("@webiny/utils");
19
+
20
+ /**
21
+ * Handles the export templates process workflow.
22
+ */
23
+ const templatesHandler = async (configuration, payload, context) => {
24
+ const log = console.log;
25
+ let subTask;
26
+ let noPendingTask = true;
27
+ let prevStatusOfSubTask = _types.ImportExportTaskStatus.PENDING;
28
+ log("RUNNING Export Templates Process Handler");
29
+ const {
30
+ pageBuilder,
31
+ fileManager
32
+ } = context;
33
+ const {
34
+ taskId,
35
+ subTaskIndex,
36
+ type,
37
+ identity
38
+ } = payload; // Disable authorization; this is necessary because we call Page Builder CRUD methods which include authorization checks
39
+ // and this Lambda is invoked internally, without credentials.
40
+
41
+ (0, _mockSecurity.mockSecurity)(identity, context);
42
+
43
+ try {
44
+ /*
45
+ * Note: We're not going to DB for finding the next sub-task to process,
46
+ * because the data might be out of sync due to GSI eventual consistency.
47
+ */
48
+ subTask = await pageBuilder.importExportTask.getSubTask(taskId, (0, _utils2.zeroPad)(subTaskIndex, 5));
49
+ /**
50
+ * Base condition!!
51
+ * Bail out early, if task not found or task's status is not "pending".
52
+ */
53
+
54
+ if (!subTask || subTask.status !== _types.ImportExportTaskStatus.PENDING) {
55
+ noPendingTask = true;
56
+ return {
57
+ data: "",
58
+ error: null
59
+ };
60
+ } else {
61
+ noPendingTask = false;
62
+ }
63
+
64
+ log(`Fetched sub task => ${subTask.id}`);
65
+ const {
66
+ input
67
+ } = subTask;
68
+ const {
69
+ templateId,
70
+ exportTemplatesDataKey
71
+ } = input;
72
+ const template = await pageBuilder.getPageTemplate(templateId);
73
+
74
+ if (!template) {
75
+ log(`Unable to load template "${templateId}"`);
76
+ throw new _handlerGraphql.NotFoundError(`Unable to load template "${templateId}"`);
77
+ }
78
+
79
+ log(`Processing template key "${templateId}"`); // Mark task status as PROCESSING
80
+
81
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
82
+ status: _types.ImportExportTaskStatus.PROCESSING
83
+ }); // Update stats in main task
84
+
85
+ await pageBuilder.importExportTask.updateStats(taskId, {
86
+ prevStatus: prevStatusOfSubTask,
87
+ nextStatus: _types.ImportExportTaskStatus.PROCESSING
88
+ });
89
+ prevStatusOfSubTask = subTask.status;
90
+ log(`Extracting template data and uploading to storage...`); // Extract Template
91
+
92
+ const templateDataZip = await (0, _utils.exportTemplate)(template, exportTemplatesDataKey, fileManager);
93
+ log(`Finish uploading zip...`); // Update task record in DB
94
+
95
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
96
+ status: _types.ImportExportTaskStatus.COMPLETED,
97
+ data: {
98
+ message: `Finish uploading data for template "${template.id}"`,
99
+ key: templateDataZip.Key
100
+ }
101
+ }); // Update stats in main task
102
+
103
+ await pageBuilder.importExportTask.updateStats(taskId, {
104
+ prevStatus: prevStatusOfSubTask,
105
+ nextStatus: _types.ImportExportTaskStatus.COMPLETED
106
+ });
107
+ prevStatusOfSubTask = subTask.status;
108
+ } catch (e) {
109
+ log("[EXPORT_TEMPLATES_PROCESS] Error => ", e.message);
110
+
111
+ if (subTask && subTask.id) {
112
+ /**
113
+ * In case of error, we'll update the task status to "failed",
114
+ * so that, client can show notify the user appropriately.
115
+ */
116
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
117
+ status: _types.ImportExportTaskStatus.FAILED,
118
+ error: {
119
+ name: e.name,
120
+ message: e.message,
121
+ code: "EXPORT_FAILED"
122
+ }
123
+ }); // Update stats in main task
124
+
125
+ await pageBuilder.importExportTask.updateStats(taskId, {
126
+ prevStatus: prevStatusOfSubTask,
127
+ nextStatus: _types.ImportExportTaskStatus.FAILED
128
+ });
129
+ prevStatusOfSubTask = subTask.status;
130
+ }
131
+
132
+ return {
133
+ data: null,
134
+ error: {
135
+ message: e.message
136
+ }
137
+ };
138
+ } finally {
139
+ // Base condition!
140
+ if (noPendingTask) {
141
+ log(`No pending sub-task for task ${taskId}`); // Combine individual template zip files.
142
+
143
+ await (0, _client.invokeHandlerClient)({
144
+ context,
145
+ name: configuration.handlers.combine,
146
+ payload: {
147
+ taskId,
148
+ type,
149
+ identity: context.security.getIdentity()
150
+ },
151
+ description: "Export templates - combine"
152
+ });
153
+ } else {
154
+ console.log(`Invoking PROCESS for task "${subTaskIndex + 1}"`); // We want to continue with Self invocation no matter if current template error out.
155
+
156
+ await (0, _client.invokeHandlerClient)({
157
+ context,
158
+ name: configuration.handlers.process,
159
+ payload: {
160
+ taskId,
161
+ subTaskIndex: subTaskIndex + 1,
162
+ type,
163
+ identity: context.security.getIdentity()
164
+ },
165
+ description: "Export templates - process - subtask"
166
+ });
167
+ }
168
+ }
169
+
170
+ return {
171
+ data: "",
172
+ error: null
173
+ };
174
+ };
175
+
176
+ exports.templatesHandler = templatesHandler;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["templatesHandler","configuration","payload","context","log","console","subTask","noPendingTask","prevStatusOfSubTask","ImportExportTaskStatus","PENDING","pageBuilder","fileManager","taskId","subTaskIndex","type","identity","mockSecurity","importExportTask","getSubTask","zeroPad","status","data","error","id","input","templateId","exportTemplatesDataKey","template","getPageTemplate","NotFoundError","updateSubTask","PROCESSING","updateStats","prevStatus","nextStatus","templateDataZip","exportTemplate","COMPLETED","message","key","Key","e","FAILED","name","code","invokeHandlerClient","handlers","combine","security","getIdentity","description","process"],"sources":["templatesHandler.ts"],"sourcesContent":["import { ImportExportTaskStatus, PbImportExportContext } from \"~/types\";\nimport { invokeHandlerClient } from \"~/client\";\nimport { NotFoundError } from \"@webiny/handler-graphql\";\nimport { exportTemplate } from \"~/export/utils\";\nimport { Payload as ExtractPayload } from \"../combine\";\nimport { mockSecurity } from \"~/mockSecurity\";\nimport { SecurityIdentity } from \"@webiny/api-security/types\";\nimport { zeroPad } from \"@webiny/utils\";\nimport { Configuration, Payload, Response } from \"~/export/process\";\n\n/**\n * Handles the export templates process workflow.\n */\nexport const templatesHandler = async (\n configuration: Configuration,\n payload: Payload,\n context: PbImportExportContext\n): Promise<Response> => {\n const log = console.log;\n let subTask;\n let noPendingTask = true;\n let prevStatusOfSubTask = ImportExportTaskStatus.PENDING;\n\n log(\"RUNNING Export Templates Process Handler\");\n const { pageBuilder, fileManager } = context;\n const { taskId, subTaskIndex, type, identity } = payload;\n // Disable authorization; this is necessary because we call Page Builder CRUD methods which include authorization checks\n // and this Lambda is invoked internally, without credentials.\n mockSecurity(identity as SecurityIdentity, context);\n try {\n /*\n * Note: We're not going to DB for finding the next sub-task to process,\n * because the data might be out of sync due to GSI eventual consistency.\n */\n subTask = await pageBuilder.importExportTask.getSubTask(taskId, zeroPad(subTaskIndex, 5));\n /**\n * Base condition!!\n * Bail out early, if task not found or task's status is not \"pending\".\n */\n if (!subTask || subTask.status !== ImportExportTaskStatus.PENDING) {\n noPendingTask = true;\n return {\n data: \"\",\n error: null\n };\n } else {\n noPendingTask = false;\n }\n\n log(`Fetched sub task => ${subTask.id}`);\n\n const { input } = subTask;\n const { templateId, exportTemplatesDataKey } = input;\n\n const template = await pageBuilder.getPageTemplate(templateId);\n\n if (!template) {\n log(`Unable to load template \"${templateId}\"`);\n throw new NotFoundError(`Unable to load template \"${templateId}\"`);\n }\n\n log(`Processing template key \"${templateId}\"`);\n\n // Mark task status as PROCESSING\n subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {\n status: ImportExportTaskStatus.PROCESSING\n });\n // Update stats in main task\n await pageBuilder.importExportTask.updateStats(taskId, {\n prevStatus: prevStatusOfSubTask,\n nextStatus: ImportExportTaskStatus.PROCESSING\n });\n prevStatusOfSubTask = subTask.status;\n\n log(`Extracting template data and uploading to storage...`);\n // Extract Template\n const templateDataZip = await exportTemplate(template, exportTemplatesDataKey, fileManager);\n log(`Finish uploading zip...`);\n // Update task record in DB\n subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {\n status: ImportExportTaskStatus.COMPLETED,\n data: {\n message: `Finish uploading data for template \"${template.id}\"`,\n key: templateDataZip.Key\n }\n });\n // Update stats in main task\n await pageBuilder.importExportTask.updateStats(taskId, {\n prevStatus: prevStatusOfSubTask,\n nextStatus: ImportExportTaskStatus.COMPLETED\n });\n prevStatusOfSubTask = subTask.status;\n } catch (e) {\n log(\"[EXPORT_TEMPLATES_PROCESS] Error => \", e.message);\n\n if (subTask && subTask.id) {\n /**\n * In case of error, we'll update the task status to \"failed\",\n * so that, client can show notify the user appropriately.\n */\n subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {\n status: ImportExportTaskStatus.FAILED,\n error: {\n name: e.name,\n message: e.message,\n code: \"EXPORT_FAILED\"\n }\n });\n\n // Update stats in main task\n await pageBuilder.importExportTask.updateStats(taskId, {\n prevStatus: prevStatusOfSubTask,\n nextStatus: ImportExportTaskStatus.FAILED\n });\n prevStatusOfSubTask = subTask.status;\n }\n\n return {\n data: null,\n error: {\n message: e.message\n }\n };\n } finally {\n // Base condition!\n if (noPendingTask) {\n log(`No pending sub-task for task ${taskId}`);\n // Combine individual template zip files.\n await invokeHandlerClient<ExtractPayload>({\n context,\n name: configuration.handlers.combine,\n payload: {\n taskId,\n type,\n identity: context.security.getIdentity()\n },\n description: \"Export templates - combine\"\n });\n } else {\n console.log(`Invoking PROCESS for task \"${subTaskIndex + 1}\"`);\n // We want to continue with Self invocation no matter if current template error out.\n await invokeHandlerClient<Payload>({\n context,\n name: configuration.handlers.process,\n payload: {\n taskId,\n subTaskIndex: subTaskIndex + 1,\n type,\n identity: context.security.getIdentity()\n },\n description: \"Export templates - process - subtask\"\n });\n }\n }\n return {\n data: \"\",\n error: null\n };\n};\n"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AAEA;;AAEA;;AAGA;AACA;AACA;AACO,MAAMA,gBAAgB,GAAG,OAC5BC,aAD4B,EAE5BC,OA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A,MAAM,IAAAgC,2BAAA,EAA6B;QAC/B3C,OAD+B;QAE/ByC,IAAI,EAAE3C,aAAa,CAAC8C,QAAd,CAAuBK,OAFE;QAG/BlD,OAAO,EAAE;UACLW,MADK;UAELC,YAAY,EAAEA,YAAY,GAAG,CAFxB;UAGLC,IAHK;UAILC,QAAQ,EAAEb,OAAO,CAAC8C,QAAR,CAAiBC,WAAjB;QAJL,CAHsB;QAS/BC,WAAW,EAAE;MATkB,CAA7B,CAAN;IAWH;EACJ;;EACD,OAAO;IACH7B,IAAI,EAAE,EADH;IAEHC,KAAK,EAAE;EAFJ,CAAP;AAIH,CAjJM"}
@@ -1,10 +1,12 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import { PassThrough, Readable } from "stream";
3
4
  import S3 from "aws-sdk/clients/s3";
4
5
  declare class S3Stream {
5
6
  s3: S3;
6
7
  bucket: string;
7
8
  constructor();
9
+ getPresignedUrl(key: string): string;
8
10
  /**
9
11
  * We're checking if the file is accessible on S3 by getting object meta data.
10
12
  * It help us to filter files that we need to download as part of export data.
@@ -1,22 +1,20 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
4
 
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
8
  exports.s3Stream = void 0;
9
9
 
10
+ var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
11
+
10
12
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
11
13
 
12
14
  var _stream = require("stream");
13
15
 
14
16
  var _s = _interopRequireDefault(require("aws-sdk/clients/s3"));
15
17
 
16
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
17
-
18
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
19
-
20
18
  const ARCHIVE_CONTENT_TYPE = "application/zip";
21
19
 
22
20
  class S3Stream {
@@ -28,6 +26,15 @@ class S3Stream {
28
26
  });
29
27
  this.bucket = process.env.S3_BUCKET;
30
28
  }
29
+
30
+ getPresignedUrl(key) {
31
+ return this.s3.getSignedUrl("getObject", {
32
+ Bucket: this.bucket,
33
+ Key: key,
34
+ Expires: 604800 // 1 week
35
+
36
+ });
37
+ }
31
38
  /**
32
39
  * We're checking if the file is accessible on S3 by getting object meta data.
33
40
  * It help us to filter files that we need to download as part of export data.
@@ -63,7 +70,7 @@ class S3Stream {
63
70
  writeStream(Key, contentType = ARCHIVE_CONTENT_TYPE) {
64
71
  const streamPassThrough = new _stream.Stream.PassThrough();
65
72
  const params = {
66
- ACL: "public-read",
73
+ ACL: "private",
67
74
  Body: streamPassThrough,
68
75
  Bucket: this.bucket,
69
76
  ContentType: contentType,
@@ -80,7 +87,7 @@ class S3Stream {
80
87
  }
81
88
 
82
89
  upload(params) {
83
- return this.s3.upload(_objectSpread({
90
+ return this.s3.upload((0, _objectSpread2.default)({
84
91
  ACL: "private",
85
92
  Bucket: this.bucket
86
93
  }, params)).promise();
@@ -0,0 +1 @@
1
+ {"version":3,"names":["ARCHIVE_CONTENT_TYPE","S3Stream","constructor","s3","S3","region","process","env","AWS_REGION","bucket","S3_BUCKET","getPresignedUrl","key","getSignedUrl","Bucket","Key","Expires","isFileAccessible","getObjectHead","error","console","warn","log","headObject","promise","readStream","getObject","createReadStream","writeStream","contentType","streamPassThrough","Stream","PassThrough","params","ACL","Body","ContentType","streamPassThroughUploadPromise","upload","listObject","prefix","listObjects","Prefix","deleteObject","s3Stream"],"sources":["s3Stream.ts"],"sourcesContent":["import { Stream, PassThrough, Readable } from \"stream\";\nimport S3 from \"aws-sdk/clients/s3\";\n\nconst ARCHIVE_CONTENT_TYPE = \"application/zip\";\n\nclass S3Stream {\n s3: S3;\n bucket: string;\n\n constructor() {\n this.s3 = new S3({\n region: process.env.AWS_REGION as string\n });\n this.bucket = process.env.S3_BUCKET as string;\n }\n\n getPresignedUrl(key: string) {\n return this.s3.getSignedUrl(\"getObject\", {\n Bucket: this.bucket,\n Key: key,\n Expires: 604800 // 1 week\n });\n }\n\n /**\n * We're checking if the file is accessible on S3 by getting object meta data.\n * It help us to filter files that we need to download as part of export data.\n * @param Key {string}\n */\n async isFileAccessible(Key: string): Promise<boolean> {\n try {\n await this.getObjectHead(Key);\n return true;\n } catch (error) {\n console.warn(`Error while fetching meta data for file \"${Key}\"`);\n console.log(error);\n return false;\n }\n }\n\n getObjectHead(Key: string): Promise<S3.HeadObjectOutput> {\n return this.s3.headObject({ Bucket: this.bucket, Key }).promise();\n }\n\n readStream(Key: string): Readable {\n return this.s3.getObject({ Bucket: this.bucket, Key }).createReadStream();\n }\n\n writeStream(\n Key: string,\n contentType: string = ARCHIVE_CONTENT_TYPE\n ): {\n streamPassThrough: PassThrough;\n streamPassThroughUploadPromise: Promise<S3.ManagedUpload.SendData>;\n } {\n const streamPassThrough = new Stream.PassThrough();\n\n const params: S3.PutObjectRequest = {\n ACL: \"private\",\n Body: streamPassThrough,\n Bucket: this.bucket,\n ContentType: contentType,\n Key\n };\n\n return {\n streamPassThrough: streamPassThrough,\n /**\n * We're not using the `FileManager` storage plugin here because it currently doesn't support streams.\n */\n streamPassThroughUploadPromise: this.s3.upload(params).promise()\n };\n }\n\n upload(params: {\n Key: string;\n ContentType: string;\n Body: Buffer;\n }): Promise<S3.ManagedUpload.SendData> {\n return this.s3\n .upload({\n ACL: \"private\",\n Bucket: this.bucket,\n ...params\n })\n .promise();\n }\n\n listObject(prefix: string): Promise<S3.ListObjectsOutput> {\n return this.s3\n .listObjects({\n Bucket: this.bucket,\n Prefix: prefix\n })\n .promise();\n }\n\n deleteObject(key: string): Promise<S3.DeleteObjectOutput> {\n return this.s3.deleteObject({ Key: key, Bucket: this.bucket }).promise();\n }\n}\n\nexport const s3Stream = new S3Stream();\n"],"mappings":";;;;;;;;;;;;;AAAA;;AACA;;AAEA,MAAMA,oBAAoB,GAAG,iBAA7B;;AAEA,MAAMC,QAAN,CAAe;EAIXC,WAAW,GAAG;IAAA;IAAA;IACV,KAAKC,EAAL,GAAU,IAAIC,UAAJ,CAAO;MACbC,MAAM,EAAEC,OAAO,CAACC,GAAR,CAAYC;IADP,CAAP,CAAV;IAGA,KAAKC,MAAL,GAAcH,OAAO,CAACC,GAAR,CAAYG,SAA1B;EACH;;EAEDC,eAAe,CAACC,GAAD,EAAc;IACzB,OAAO,KAAKT,EAAL,CAAQU,YAAR,CAAqB,WAArB,EAAkC;MACrCC,MAAM,EAAE,KAAKL,MADwB;MAErCM,GAAG,EAAEH,GAFgC;MAGrCI,OAAO,EAAE,MAH4B,CAGrB;;IAHqB,CAAlC,CAAP;EAKH;EAED;AACJ;AACA;AACA;AACA;;;EAC0B,MAAhBC,gBAAgB,CAACF,GAAD,EAAgC;IAClD,IAAI;MACA,MAAM,KAAKG,aAAL,CAAmBH,GAAnB,CAAN;MACA,OAAO,IAAP;IACH,CAHD,CAGE,OAAOI,KAAP,EAAc;MACZC,OAAO,CAACC,IAAR,CAAc,4CAA2CN,GAAI,GAA7D;MACAK,OAAO,CAACE,GAAR,CAAYH,KAAZ;MACA,OAAO,KAAP;IACH;EACJ;;EAEDD,aAAa,CAACH,GAAD,EAA4C;IACrD,OAAO,KAAKZ,EAAL,CAAQoB,UAAR,CAAmB;MAAET,MAAM,EAAE,KAAKL,MAAf;MA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AAjB"}
@@ -0,0 +1,22 @@
1
+ import S3 from "aws-sdk/clients/s3";
2
+ import { Page, PageBlock, PageTemplate } from "@webiny/api-page-builder/types";
3
+ import { FileManagerContext, File } from "@webiny/api-file-manager/types";
4
+ export declare const EXPORT_PAGES_FOLDER_KEY = "WEBINY_PB_EXPORT_PAGES";
5
+ export declare const EXPORT_BLOCKS_FOLDER_KEY = "WEBINY_PB_EXPORT_BLOCK";
6
+ export declare const EXPORT_TEMPLATES_FOLDER_KEY = "WEBINY_PB_EXPORT_TEMPLATE";
7
+ export interface ExportedPageData {
8
+ page: Pick<Page, "content" | "title" | "version" | "status" | "settings" | "path">;
9
+ files: File[];
10
+ }
11
+ export declare function exportPage(page: Page, exportPagesDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
12
+ export interface ExportedBlockData {
13
+ block: Pick<PageBlock, "name" | "content" | "preview">;
14
+ files: File[];
15
+ }
16
+ export declare function exportBlock(block: PageBlock, exportBlocksDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
17
+ export interface ExportedTemplateData {
18
+ template: Pick<PageTemplate, "title" | "description" | "content">;
19
+ files: File[];
20
+ }
21
+ export declare function exportTemplate(template: PageTemplate, exportTemplatesDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
22
+ export declare function extractFilesFromData(data: Record<string, any>, files?: any[]): File[];
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.EXPORT_TEMPLATES_FOLDER_KEY = exports.EXPORT_PAGES_FOLDER_KEY = exports.EXPORT_BLOCKS_FOLDER_KEY = void 0;
9
+ exports.exportBlock = exportBlock;
10
+ exports.exportPage = exportPage;
11
+ exports.exportTemplate = exportTemplate;
12
+ exports.extractFilesFromData = extractFilesFromData;
13
+
14
+ var _get = _interopRequireDefault(require("lodash/get"));
15
+
16
+ var _zipper = _interopRequireDefault(require("./zipper"));
17
+
18
+ const EXPORT_PAGES_FOLDER_KEY = "WEBINY_PB_EXPORT_PAGES";
19
+ exports.EXPORT_PAGES_FOLDER_KEY = EXPORT_PAGES_FOLDER_KEY;
20
+ const EXPORT_BLOCKS_FOLDER_KEY = "WEBINY_PB_EXPORT_BLOCK";
21
+ exports.EXPORT_BLOCKS_FOLDER_KEY = EXPORT_BLOCKS_FOLDER_KEY;
22
+ const EXPORT_TEMPLATES_FOLDER_KEY = "WEBINY_PB_EXPORT_TEMPLATE";
23
+ exports.EXPORT_TEMPLATES_FOLDER_KEY = EXPORT_TEMPLATES_FOLDER_KEY;
24
+
25
+ async function exportPage(page, exportPagesDataKey, fileManager) {
26
+ // Extract all files
27
+ const files = extractFilesFromData(page.content || {}); // Extract images from page settings
28
+
29
+ const pageSettingsImages = [(0, _get.default)(page, "settings.general.image"), (0, _get.default)(page, "settings.social.image")].filter(image => image && image.src);
30
+ const fileIds = [...files, ...pageSettingsImages].map(imageFile => imageFile.id); // Get file data for all images
31
+
32
+ const imageFilesData = [];
33
+
34
+ if (fileIds.length > 0) {
35
+ const [filesData] = await fileManager.files.listFiles({
36
+ ids: fileIds
37
+ });
38
+ imageFilesData.push(...filesData);
39
+ } // Extract the page data in a json file and upload it to S3
40
+
41
+
42
+ const pageData = {
43
+ page: {
44
+ content: page.content,
45
+ title: page.title,
46
+ path: page.path,
47
+ version: page.version,
48
+ status: page.status,
49
+ settings: page.settings
50
+ },
51
+ files: imageFilesData
52
+ };
53
+ const pageDataBuffer = Buffer.from(JSON.stringify(pageData));
54
+ const zipper = new _zipper.default({
55
+ exportInfo: {
56
+ files: imageFilesData,
57
+ name: page.title,
58
+ dataBuffer: pageDataBuffer
59
+ },
60
+ archiveFileKey: exportPagesDataKey
61
+ });
62
+ return zipper.process();
63
+ }
64
+
65
+ async function exportBlock(block, exportBlocksDataKey, fileManager) {
66
+ // Extract all files
67
+ const files = extractFilesFromData(block.content || {});
68
+ const fileIds = files.map(imageFile => imageFile.id); // Get file data for all images
69
+
70
+ const imageFilesData = [];
71
+
72
+ if (fileIds.length > 0) {
73
+ const [filesData] = await fileManager.files.listFiles({
74
+ ids: fileIds
75
+ });
76
+ imageFilesData.push(...filesData);
77
+ } // Add block preview image file data
78
+
79
+
80
+ if (block.preview.id) {
81
+ imageFilesData.push(await fileManager.files.getFile(block.preview.id));
82
+ } // Extract the block data in a json file and upload it to S3
83
+
84
+
85
+ const blockData = {
86
+ block: {
87
+ name: block.name,
88
+ content: block.content,
89
+ preview: block.preview
90
+ },
91
+ files: imageFilesData
92
+ };
93
+ const blockDataBuffer = Buffer.from(JSON.stringify(blockData));
94
+ const zipper = new _zipper.default({
95
+ exportInfo: {
96
+ files: imageFilesData,
97
+ name: block.name,
98
+ dataBuffer: blockDataBuffer
99
+ },
100
+ archiveFileKey: exportBlocksDataKey
101
+ });
102
+ return zipper.process();
103
+ }
104
+
105
+ async function exportTemplate(template, exportTemplatesDataKey, fileManager) {
106
+ // Extract all files
107
+ const files = extractFilesFromData(template.content || {});
108
+ const fileIds = files.map(imageFile => imageFile.id); // Get file data for all images
109
+
110
+ const imageFilesData = [];
111
+
112
+ if (fileIds.length > 0) {
113
+ const [filesData] = await fileManager.files.listFiles({
114
+ ids: fileIds
115
+ });
116
+ imageFilesData.push(...filesData);
117
+ } // Extract the template data in a json file and upload it to S3
118
+
119
+
120
+ const templateData = {
121
+ template: {
122
+ title: template.title,
123
+ description: template.description,
124
+ content: template.content
125
+ },
126
+ files: imageFilesData
127
+ };
128
+ const templateDataBuffer = Buffer.from(JSON.stringify(templateData));
129
+ const zipper = new _zipper.default({
130
+ exportInfo: {
131
+ files: imageFilesData,
132
+ name: template.title,
133
+ dataBuffer: templateDataBuffer
134
+ },
135
+ archiveFileKey: exportTemplatesDataKey
136
+ });
137
+ return zipper.process();
138
+ }
139
+
140
+ function extractFilesFromData(data, files = []) {
141
+ // Base case: termination
142
+ if (!data || typeof data !== "object") {
143
+ return files;
144
+ } // Recursively call function for each element
145
+
146
+
147
+ if (Array.isArray(data)) {
148
+ for (let i = 0; i < data.length; i++) {
149
+ const element = data[i];
150
+ extractFilesFromData(element, files);
151
+ }
152
+
153
+ return files;
154
+ } // Main
155
+
156
+
157
+ const tuple = Object.entries(data);
158
+
159
+ for (let i = 0; i < tuple.length; i++) {
160
+ const [key, value] = tuple[i]; // TODO: @ashutosh extract it to plugins, so that, we can handle cases for other components too.
161
+
162
+ if (key === "file" && value) {
163
+ files.push(value);
164
+ } else if (key === "images" && Array.isArray(value)) {
165
+ // Handle case for "images-list" component
166
+ files.push(...value);
167
+ } else {
168
+ extractFilesFromData(value, files);
169
+ }
170
+ }
171
+
172
+ return files;
173
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["EXPORT_PAGES_FOLDER_KEY","EXPORT_BLOCKS_FOLDER_KEY","EXPORT_TEMPLATES_FOLDER_KEY","exportPage","page","exportPagesDataKey","fileManager","files","extractFilesFromData","content","pageSettingsImages","get","filter","image","src","fileIds","map","imageFile","id","imageFilesData","length","filesData","listFiles","ids","push","pageData","title","path","version","status","settings","pageDataBuffer","Buffer","from","JSON","stringify","zipper","Zipper","exportInfo","name","dataBuffer","archiveFileKey","process","exportBlock","block","exportBlocksDataKey","preview","getFile","blockData","blockDataBuffer","exportTemplate","template","exportTemplatesDataKey","templateData","description","templateDataBuffer","data","Array","isArray","i","element","tuple","Object","entries","key","value"],"sources":["utils.ts"],"sourcesContent":["import S3 from \"aws-sdk/clients/s3\";\nimport { Page, PageBlock, PageTemplate } from \"@webiny/api-page-builder/types\";\nimport { FileManagerContext, File } from \"@webiny/api-file-manager/types\";\nimport get from \"lodash/get\";\nimport Zipper from \"./zipper\";\n\nexport const EXPORT_PAGES_FOLDER_KEY = \"WEBINY_PB_EXPORT_PAGES\";\nexport const EXPORT_BLOCKS_FOLDER_KEY = \"WEBINY_PB_EXPORT_BLOCK\";\nexport const EXPORT_TEMPLATES_FOLDER_KEY = \"WEBINY_PB_EXPORT_TEMPLATE\";\n\nexport interface ExportedPageData {\n page: Pick<Page, \"content\" | \"title\" | \"version\" | \"status\" | \"settings\" | \"path\">;\n files: File[];\n}\n\nexport async function exportPage(\n page: Page,\n exportPagesDataKey: string,\n fileManager: FileManagerContext[\"fileManager\"]\n): Promise<S3.ManagedUpload.SendData> {\n // Extract all files\n const files = extractFilesFromData(page.content || {});\n // Extract images from page settings\n const pageSettingsImages = [\n get(page, \"settings.general.image\") as unknown as File,\n get(page, \"settings.social.image\") as unknown as File\n ].filter(image => image && image.src);\n\n const fileIds = [...files, ...pageSettingsImages].map(imageFile => imageFile.id);\n // Get file data for all images\n const imageFilesData = [];\n if (fileIds.length > 0) {\n const [filesData] = await fileManager.files.listFiles({ ids: fileIds });\n imageFilesData.push(...filesData);\n }\n\n // Extract the page data in a json file and upload it to S3\n const pageData = {\n page: {\n content: page.content,\n title: page.title,\n path: page.path,\n version: page.version,\n status: page.status,\n settings: page.settings\n },\n files: imageFilesData\n };\n const pageDataBuffer = Buffer.from(JSON.stringify(pageData));\n\n const zipper = new Zipper({\n exportInfo: {\n files: imageFilesData,\n name: page.title,\n dataBuffer: pageDataBuffer\n },\n archiveFileKey: exportPagesDataKey\n });\n\n return zipper.process();\n}\n\nexport interface ExportedBlockData {\n block: Pick<PageBlock, \"name\" | \"content\" | \"preview\">;\n files: File[];\n}\n\nexport async function exportBlock(\n block: PageBlock,\n exportBlocksDataKey: string,\n fileManager: FileManagerContext[\"fileManager\"]\n): Promise<S3.ManagedUpload.SendData> {\n // Extract all files\n const files = extractFilesFromData(block.content || {});\n const fileIds = files.map(imageFile => imageFile.id);\n // Get file data for all images\n const imageFilesData = [];\n if (fileIds.length > 0) {\n const [filesData] = await fileManager.files.listFiles({ ids: fileIds });\n imageFilesData.push(...filesData);\n }\n // Add block preview image file data\n if (block.preview.id) {\n imageFilesData.push(await fileManager.files.getFile(block.preview.id));\n }\n\n // Extract the block data in a json file and upload it to S3\n const blockData = {\n block: {\n name: block.name,\n content: block.content,\n preview: block.preview\n },\n files: imageFilesData\n };\n const blockDataBuffer = Buffer.from(JSON.stringify(blockData));\n\n const zipper = new Zipper({\n exportInfo: {\n files: imageFilesData,\n name: block.name,\n dataBuffer: blockDataBuffer\n },\n archiveFileKey: exportBlocksDataKey\n });\n\n return zipper.process();\n}\n\nexport interface ExportedTemplateData {\n template: Pick<PageTemplate, \"title\" | \"description\" | \"content\">;\n files: File[];\n}\n\nexport async function exportTemplate(\n template: PageTemplate,\n exportTemplatesDataKey: string,\n fileManager: FileManagerContext[\"fileManager\"]\n): Promise<S3.ManagedUpload.SendData> {\n // Extract all files\n const files = extractFilesFromData(template.content || {});\n const fileIds = files.map(imageFile => imageFile.id);\n // Get file data for all images\n const imageFilesData = [];\n if (fileIds.length > 0) {\n const [filesData] = await fileManager.files.listFiles({ ids: fileIds });\n imageFilesData.push(...filesData);\n }\n\n // Extract the template data in a json file and upload it to S3\n const templateData = {\n template: {\n title: template.title,\n description: template.description,\n content: template.content\n },\n files: imageFilesData\n };\n const templateDataBuffer = Buffer.from(JSON.stringify(templateData));\n\n const zipper = new Zipper({\n exportInfo: {\n files: imageFilesData,\n name: template.title,\n dataBuffer: templateDataBuffer\n },\n archiveFileKey: exportTemplatesDataKey\n });\n\n return zipper.process();\n}\n\nexport function extractFilesFromData(data: Record<string, any>, files: any[] = []): File[] {\n // Base case: termination\n if (!data || typeof data !== \"object\") {\n return files;\n }\n // Recursively call function for each element\n if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) {\n const element = data[i];\n extractFilesFromData(element, files);\n }\n return files;\n }\n\n // Main\n const tuple = Object.entries(data);\n for (let i = 0; i < tuple.length; i++) {\n const [key, value] = tuple[i];\n // TODO: @ashutosh extract it to plugins, so that, we can handle cases for other components too.\n if (key === \"file\" && value) {\n files.push(value);\n } else if (key === \"images\" && Array.isArray(value)) {\n // Handle case for \"images-list\" component\n files.push(...value);\n } else {\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ACC,OAAN,CAAcO,KAAd,CAAxB,EAA8C;MACjD;MACA1D,KAAK,CAACiB,IAAN,CAAW,GAAGyC,KAAd;IACH,CAHM,MAGA;MACHzD,oBAAoB,CAACyD,KAAD,EAAQ1D,KAAR,CAApB;IACH;EACJ;;EACD,OAAOA,KAAP;AACH"}
@@ -1,15 +1,16 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import S3 from "aws-sdk/clients/s3";
3
4
  import { Readable } from "stream";
4
- import { ImageFile } from "./utils";
5
+ import { File } from "@webiny/api-file-manager/types";
5
6
  interface FileStreamDetails {
6
7
  stream: Readable;
7
8
  filename: string;
8
9
  }
9
10
  interface ExportInfo {
10
- files: ImageFile[];
11
- pageTitle: string;
12
- pageDataBuffer: Buffer;
11
+ files: File[];
12
+ name: string;
13
+ dataBuffer: Buffer;
13
14
  }
14
15
  export interface ZipperConfig {
15
16
  exportInfo: ExportInfo;
@@ -28,7 +29,8 @@ export declare class ZipOfZip {
28
29
  private readonly archiveFormat;
29
30
  private readonly archiveFileName;
30
31
  keys: string[];
31
- constructor(keys: string[]);
32
+ filename: string;
33
+ constructor(keys: string[], filename: string);
32
34
  getFileStreams(): FileStreamDetails[];
33
35
  process(): Promise<S3.ManagedUpload.SendData>;
34
36
  }
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
+ var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4
+
5
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
6
 
5
7
  Object.defineProperty(exports, "__esModule", {
6
8
  value: true
@@ -21,10 +23,6 @@ var _uniqid = _interopRequireDefault(require("uniqid"));
21
23
 
22
24
  var _s3Stream = require("./s3Stream");
23
25
 
24
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
25
-
26
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
27
-
28
26
  // TODO: Move "archive" in layer
29
27
  class Zipper {
30
28
  constructor(config) {
@@ -33,12 +31,12 @@ class Zipper {
33
31
  (0, _defineProperty2.default)(this, "archiveFileName", void 0);
34
32
  (0, _defineProperty2.default)(this, "config", void 0);
35
33
  this.config = config;
36
- this.archiveFileName = (0, _uniqid.default)(`${this.config.archiveFileKey}/`, `-${(0, _kebabCase.default)(this.config.exportInfo.pageTitle)}.zip`);
34
+ this.archiveFileName = (0, _uniqid.default)(`${this.config.archiveFileKey}/`, `-${(0, _kebabCase.default)(this.config.exportInfo.name)}.zip`);
37
35
  }
38
36
 
39
37
  s3DownloadStreams() {
40
38
  const exportInfo = this.config.exportInfo;
41
- const prefix = (0, _uniqid.default)("", `-${(0, _kebabCase.default)(exportInfo.pageTitle)}`);
39
+ const prefix = (0, _uniqid.default)("", `-${(0, _kebabCase.default)(exportInfo.name)}`);
42
40
  const files = exportInfo.files.map(({
43
41
  key
44
42
  }) => {
@@ -48,8 +46,8 @@ class Zipper {
48
46
  };
49
47
  });
50
48
  return [...files, {
51
- stream: _stream.Readable.from(exportInfo.pageDataBuffer),
52
- filename: `${prefix}\\${exportInfo.pageTitle}.json`
49
+ stream: _stream.Readable.from(exportInfo.dataBuffer),
50
+ filename: `${prefix}\\${exportInfo.name}.json`
53
51
  }];
54
52
  }
55
53
 
@@ -84,15 +82,16 @@ class Zipper {
84
82
  }
85
83
 
86
84
  exports.default = Zipper;
87
- const PAGE_EXPORT_BASENAME = `WEBINY_PAGE_EXPORT.zip`;
88
85
 
89
86
  class ZipOfZip {
90
- constructor(keys) {
87
+ constructor(keys, filename) {
91
88
  (0, _defineProperty2.default)(this, "archiveFormat", "zip");
92
89
  (0, _defineProperty2.default)(this, "archiveFileName", void 0);
93
90
  (0, _defineProperty2.default)(this, "keys", void 0);
91
+ (0, _defineProperty2.default)(this, "filename", void 0);
94
92
  this.keys = keys;
95
- this.archiveFileName = (0, _uniqid.default)("", `-${PAGE_EXPORT_BASENAME}`);
93
+ this.filename = filename;
94
+ this.archiveFileName = (0, _uniqid.default)("", `-${filename}`);
96
95
  }
97
96
 
98
97
  getFileStreams() {
@@ -0,0 +1 @@
1
+ {"version":3,"names":["Zipper","constructor","config","archiveFileName","uniqueId","archiveFileKey","kebabCase","exportInfo","name","s3DownloadStreams","prefix","files","map","key","stream","s3Stream","readStream","filename","filesDirName","path","basename","Readable","from","dataBuffer","process","streamPassThrough","streamPassThroughUploadPromise","writeStream","s3FilesStreams","archive","vending","create","archiveFormat","on","error","Error","code","message","stack","forEach","streamDetails","append","pipe","finalize","ZipOfZip","keys","getFileStreams","fileStreamDetails"],"sources":["zipper.ts"],"sourcesContent":["// TODO: Move \"archive\" in layer\nimport vending, { ArchiverError } from \"archiver\";\nimport S3 from \"aws-sdk/clients/s3\";\nimport { Readable } from \"stream\";\nimport * as path from \"path\";\nimport kebabCase from \"lodash/kebabCase\";\nimport uniqueId from \"uniqid\";\nimport { s3Stream } from \"./s3Stream\";\nimport { File } from \"@webiny/api-file-manager/types\";\n\ninterface FileStreamDetails {\n stream: Readable;\n filename: string;\n}\n\ninterface ExportInfo {\n files: File[];\n name: string;\n dataBuffer: Buffer;\n}\n\nexport interface ZipperConfig {\n exportInfo: ExportInfo;\n archiveFileKey: string;\n}\n\nexport default class Zipper {\n private readonly archiveFormat = \"zip\";\n private readonly filesDirName = \"assets\";\n private readonly archiveFileName: string;\n config: ZipperConfig;\n\n constructor(config: ZipperConfig) {\n this.config = config;\n this.archiveFileName = uniqueId(\n `${this.config.archiveFileKey}/`,\n `-${kebabCase(this.config.exportInfo.name)}.zip`\n );\n }\n\n s3DownloadStreams(): FileStreamDetails[] {\n const exportInfo = this.config.exportInfo;\n const prefix = uniqueId(\"\", `-${kebabCase(exportInfo.name)}`);\n const files = exportInfo.files.map(({ key }) => {\n return {\n stream: s3Stream.readStream(key),\n filename: `${prefix}\\\\${this.filesDirName}\\\\${path.basename(key)}`\n };\n });\n\n return [\n ...files,\n {\n stream: Readable.from(exportInfo.dataBuffer),\n filename: `${prefix}\\\\${exportInfo.name}.json`\n }\n ];\n }\n\n process(): Promise<S3.ManagedUpload.SendData> {\n const { streamPassThrough, streamPassThroughUploadPromise } = s3Stream.writeStream(\n this.archiveFileName\n );\n\n // 1. Read all files from S3 using stream.\n const s3FilesStreams = this.s3DownloadStreams();\n\n // 2. Prepare zip from the file stream.\n const archive = vending.create(this.archiveFormat);\n // Handle archive events.\n archive.on(\"error\", (error: ArchiverError) => {\n throw new Error(\n `${error.name} ${error.code} ${error.message} ${error.path} ${error.stack}`\n );\n });\n\n // Append all file streams to archive.\n s3FilesStreams.forEach((streamDetails: FileStreamDetails) =>\n archive.append(streamDetails.stream, { name: streamDetails.filename })\n );\n\n // Pipe archive output to streamPassThrough (Transform Stream) which will be uploaded to S3.\n archive.pipe(streamPassThrough);\n // Finalize the archive (ie we are done appending files but streams have to finish yet)\n // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand\n archive.finalize();\n\n // 3. Return upload stream promise.\n return streamPassThroughUploadPromise;\n }\n}\n\nexport class ZipOfZip {\n private readonly archiveFormat = \"zip\";\n private readonly archiveFileName: string;\n keys: string[];\n filename: string;\n\n constructor(keys: string[], filename: string) {\n this.keys = keys;\n this.filename = filename;\n this.archiveFileName = uniqueId(\"\", `-${filename}`);\n }\n\n getFileStreams(): FileStreamDetails[] {\n return this.keys.map(key => {\n return {\n stream: s3Stream.readStream(key),\n filename: `${path.basename(key)}`\n };\n });\n }\n\n process(): Promise<S3.ManagedUpload.SendData> {\n const { streamPassThrough, streamPassThroughUploadPromise } = s3Stream.writeStream(\n this.archiveFileName\n );\n\n // 1. Read all files from S3 using stream.\n const fileStreamDetails = this.getFileStreams();\n\n // 2. Prepare zip from the file stream.\n const archive = vending.create(this.archiveFormat);\n // Handle archive events.\n archive.on(\"error\", (error: ArchiverError) => {\n throw new Error(\n `${error.name} ${error.code} ${error.message} ${error.path} ${error.stack}`\n );\n });\n\n // Append all file streams to archive.\n fileStreamDetails.forEach((streamDetails: FileStreamDetails) =>\n archive.append(streamDetails.stream, { name: streamDetails.filename })\n );\n\n // Pipe archive output to streamPassThrough (Transform Stream) which will be uploaded to S3.\n archive.pipe(streamPassThrough);\n // Finalize the archive (ie we are done appending files but streams have to finish yet)\n // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand\n archive.finalize();\n\n // 3. Return upload stream promise.\n return streamPassThroughUploadPromise;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AACA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AAPA;AA0Be,MAAMA,MAAN,CAAa;EAMxBC,WAAW,CAACC,MAAD,EAAuB;IAAA,qDALD,KAKC;IAAA,oDAJF,QAIE;IAAA;IAAA;IAC9B,KAAKA,MAAL,GAAcA,MAAd;IACA,KAAKC,eAAL,GAAuB,IAAAC,eAAA,EAClB,GAAE,KAAKF,MAAL,CAAYG,cAAe,GADX,EAElB,IAAG,IAAAC,kBAAA,EAAU,KAAKJ,MAAL,CAAYK,UAAZ,CAAuBC,IAAjC,CAAuC,MAFxB,CAAvB;EAIH;;EAEDC,iBAAiB,GAAwB;IACrC,MAAMF,UAAU,GAAG,KAAKL,MAAL,CA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F,KAAK,CAACG,OAAQ,IAAGH,KAAK,CAACf,IAAK,IAAGe,KAAK,CAACI,KAAM,EADxE,CAAN;IAGH,CAJD,EAX0C,CAiB1C;;IACAS,iBAAiB,CAACR,OAAlB,CAA2BC,aAAD,IACtBX,OAAO,CAACY,MAAR,CAAeD,aAAa,CAAC1B,MAA7B,EAAqC;MAAEN,IAAI,EAAEgC,aAAa,CAACvB;IAAtB,CAArC,CADJ,EAlB0C,CAsB1C;;IACAY,OAAO,CAACa,IAAR,CAAajB,iBAAb,EAvB0C,CAwB1C;IACA;;IACAI,OAAO,CAACc,QAAR,GA1B0C,CA4B1C;;IACA,OAAOjB,8BAAP;EACH;;AAnDiB"}
@@ -0,0 +1,4 @@
1
+ import { ContextPlugin } from "@webiny/api";
2
+ import { PbImportExportContext } from "../../types";
3
+ declare const _default: ContextPlugin<PbImportExportContext>;
4
+ export default _default;