@webiny/api-page-builder-import-export 0.0.0-unstable.97a151f74d → 0.0.0-unstable.aad28a72ae

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 (98) hide show
  1. package/client.d.ts +2 -2
  2. package/client.js.map +1 -1
  3. package/export/combine/blocksHandler.d.ts +6 -0
  4. package/export/combine/blocksHandler.js +106 -0
  5. package/export/combine/blocksHandler.js.map +1 -0
  6. package/{exportPages → export}/combine/index.d.ts +3 -2
  7. package/export/combine/index.js +30 -0
  8. package/export/combine/index.js.map +1 -0
  9. package/export/combine/pagesHandler.d.ts +6 -0
  10. package/export/combine/pagesHandler.js +106 -0
  11. package/export/combine/pagesHandler.js.map +1 -0
  12. package/export/process/blocksHandler.d.ts +6 -0
  13. package/export/process/blocksHandler.js +176 -0
  14. package/export/process/blocksHandler.js.map +1 -0
  15. package/{exportPages → export}/process/index.d.ts +4 -6
  16. package/export/process/index.js +27 -0
  17. package/export/process/index.js.map +1 -0
  18. package/export/process/pagesHandler.d.ts +6 -0
  19. package/export/process/pagesHandler.js +204 -0
  20. package/export/process/pagesHandler.js.map +1 -0
  21. package/{exportPages → export}/s3Stream.d.ts +0 -0
  22. package/{exportPages → export}/s3Stream.js +0 -0
  23. package/{exportPages → export}/s3Stream.js.map +0 -0
  24. package/export/utils.d.ts +16 -0
  25. package/export/utils.js +135 -0
  26. package/export/utils.js.map +1 -0
  27. package/{exportPages → export}/zipper.d.ts +6 -5
  28. package/{exportPages → export}/zipper.js +8 -7
  29. package/export/zipper.js.map +1 -0
  30. package/graphql/crud/blocks.crud.d.ts +4 -0
  31. package/graphql/crud/blocks.crud.js +155 -0
  32. package/graphql/crud/blocks.crud.js.map +1 -0
  33. package/graphql/crud/importExportTasks.crud.d.ts +5 -0
  34. package/graphql/crud/{pageImportExportTasks.crud.js → importExportTasks.crud.js} +48 -48
  35. package/graphql/crud/importExportTasks.crud.js.map +1 -0
  36. package/graphql/crud/pages.crud.d.ts +2 -2
  37. package/graphql/crud/pages.crud.js +14 -12
  38. package/graphql/crud/pages.crud.js.map +1 -1
  39. package/graphql/crud.d.ts +2 -2
  40. package/graphql/crud.js +4 -2
  41. package/graphql/crud.js.map +1 -1
  42. package/graphql/graphql/blocks.gql.d.ts +4 -0
  43. package/graphql/graphql/blocks.gql.js +57 -0
  44. package/graphql/graphql/blocks.gql.js.map +1 -0
  45. package/graphql/graphql/importExportTasks.gql.d.ts +4 -0
  46. package/graphql/graphql/{pageImportExportTasks.gql.js → importExportTasks.gql.js} +17 -17
  47. package/graphql/graphql/importExportTasks.gql.js.map +1 -0
  48. package/graphql/graphql/pages.gql.d.ts +2 -2
  49. package/graphql/graphql/pages.gql.js +2 -8
  50. package/graphql/graphql/pages.gql.js.map +1 -1
  51. package/graphql/graphql.js +4 -2
  52. package/graphql/graphql.js.map +1 -1
  53. package/graphql/index.d.ts +2 -2
  54. package/graphql/index.js.map +1 -1
  55. package/graphql/types.d.ts +43 -23
  56. package/graphql/types.js.map +1 -1
  57. package/import/create/blocksHandler.d.ts +3 -0
  58. package/import/create/blocksHandler.js +110 -0
  59. package/import/create/blocksHandler.js.map +1 -0
  60. package/{importPages → import}/create/index.d.ts +5 -4
  61. package/import/create/index.js +30 -0
  62. package/import/create/index.js.map +1 -0
  63. package/import/create/pagesHandler.d.ts +3 -0
  64. package/import/create/pagesHandler.js +110 -0
  65. package/import/create/pagesHandler.js.map +1 -0
  66. package/import/process/blocksHandler.d.ts +3 -0
  67. package/import/process/blocksHandler.js +175 -0
  68. package/import/process/blocksHandler.js.map +1 -0
  69. package/{importPages → import}/process/index.d.ts +4 -3
  70. package/import/process/index.js +27 -0
  71. package/import/process/index.js.map +1 -0
  72. package/import/process/pagesHandler.d.ts +3 -0
  73. package/import/process/pagesHandler.js +180 -0
  74. package/import/process/pagesHandler.js.map +1 -0
  75. package/{importPages → import}/utils.d.ts +19 -20
  76. package/{importPages → import}/utils.js +107 -36
  77. package/import/utils.js.map +1 -0
  78. package/package.json +22 -22
  79. package/types.d.ts +62 -65
  80. package/types.js +17 -17
  81. package/types.js.map +1 -1
  82. package/exportPages/combine/index.js +0 -114
  83. package/exportPages/combine/index.js.map +0 -1
  84. package/exportPages/process/index.js +0 -208
  85. package/exportPages/process/index.js.map +0 -1
  86. package/exportPages/utils.d.ts +0 -13
  87. package/exportPages/utils.js +0 -113
  88. package/exportPages/utils.js.map +0 -1
  89. package/exportPages/zipper.js.map +0 -1
  90. package/graphql/crud/pageImportExportTasks.crud.d.ts +0 -5
  91. package/graphql/crud/pageImportExportTasks.crud.js.map +0 -1
  92. package/graphql/graphql/pageImportExportTasks.gql.d.ts +0 -4
  93. package/graphql/graphql/pageImportExportTasks.gql.js.map +0 -1
  94. package/importPages/create/index.js +0 -118
  95. package/importPages/create/index.js.map +0 -1
  96. package/importPages/process/index.js +0 -185
  97. package/importPages/process/index.js.map +0 -1
  98. package/importPages/utils.js.map +0 -1
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.pagesHandler = 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 pages process workflow.
22
+ */
23
+ const pagesHandler = 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 Pages 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
+ pageId,
70
+ exportPagesDataKey,
71
+ revisionType
72
+ } = input;
73
+ /**
74
+ * At the moment, we only export a single revision of the page.
75
+ * It could be "published" or "latest" depending upon user input.
76
+ *
77
+ * Note: In case of no "published" revision available, we use the latest revision.
78
+ */
79
+
80
+ let page;
81
+
82
+ try {
83
+ if (revisionType === _types.ExportRevisionType.PUBLISHED) {
84
+ // Get "published" page.
85
+ page = await pageBuilder.getPublishedPageById({
86
+ id: pageId
87
+ });
88
+ } else {
89
+ // Get "latest" page.
90
+ page = await pageBuilder.getPage(pageId);
91
+ }
92
+ } catch (e) {
93
+ // If we're looking for "published" page and doesn't found it, get latest page.
94
+ if (revisionType === _types.ExportRevisionType.PUBLISHED && e instanceof _handlerGraphql.NotFoundError) {
95
+ page = await pageBuilder.getPage(pageId);
96
+ } else {
97
+ throw e;
98
+ }
99
+ }
100
+
101
+ if (!page) {
102
+ log(`Unable to load page "${pageId}"`);
103
+ throw new _handlerGraphql.NotFoundError(`Unable to load page "${pageId}"`);
104
+ }
105
+
106
+ log(`Processing page key "${pageId}" | version ${page.version} | ${page.status}`); // Mark task status as PROCESSING
107
+
108
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
109
+ status: _types.ImportExportTaskStatus.PROCESSING
110
+ }); // Update stats in main task
111
+
112
+ await pageBuilder.importExportTask.updateStats(taskId, {
113
+ prevStatus: prevStatusOfSubTask,
114
+ nextStatus: _types.ImportExportTaskStatus.PROCESSING
115
+ });
116
+ prevStatusOfSubTask = subTask.status;
117
+ log(`Extracting page data and uploading to storage...`); // Extract Page
118
+
119
+ const pageDataZip = await (0, _utils.exportPage)(page, exportPagesDataKey, fileManager);
120
+ log(`Finish uploading zip...`); // Update task record in DB
121
+
122
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
123
+ status: _types.ImportExportTaskStatus.COMPLETED,
124
+ data: {
125
+ message: `Finish uploading data for page "${page.id}" v${page.version} (${page.status}).`,
126
+ key: pageDataZip.Key
127
+ }
128
+ }); // Update stats in main task
129
+
130
+ await pageBuilder.importExportTask.updateStats(taskId, {
131
+ prevStatus: prevStatusOfSubTask,
132
+ nextStatus: _types.ImportExportTaskStatus.COMPLETED
133
+ });
134
+ prevStatusOfSubTask = subTask.status;
135
+ } catch (e) {
136
+ log("[EXPORT_PAGES_PROCESS] Error => ", e);
137
+
138
+ if (subTask && subTask.id) {
139
+ /**
140
+ * In case of error, we'll update the task status to "failed",
141
+ * so that, client can show notify the user appropriately.
142
+ */
143
+ subTask = await pageBuilder.importExportTask.updateSubTask(taskId, subTask.id, {
144
+ status: _types.ImportExportTaskStatus.FAILED,
145
+ error: {
146
+ name: e.name,
147
+ message: e.message,
148
+ stack: e.stack,
149
+ code: "EXPORT_FAILED"
150
+ }
151
+ }); // Update stats in main task
152
+
153
+ await pageBuilder.importExportTask.updateStats(taskId, {
154
+ prevStatus: prevStatusOfSubTask,
155
+ nextStatus: _types.ImportExportTaskStatus.FAILED
156
+ });
157
+ prevStatusOfSubTask = subTask.status;
158
+ }
159
+
160
+ return {
161
+ data: null,
162
+ error: {
163
+ message: e.message
164
+ }
165
+ };
166
+ } finally {
167
+ // Base condition!
168
+ if (noPendingTask) {
169
+ log(`No pending sub-task for task ${taskId}`); // Combine individual page zip files.
170
+
171
+ await (0, _client.invokeHandlerClient)({
172
+ context,
173
+ name: configuration.handlers.combine,
174
+ payload: {
175
+ taskId,
176
+ type,
177
+ identity: context.security.getIdentity()
178
+ },
179
+ description: "Export pages - combine"
180
+ });
181
+ } else {
182
+ console.log(`Invoking PROCESS for task "${subTaskIndex + 1}"`); // We want to continue with Self invocation no matter if current page error out.
183
+
184
+ await (0, _client.invokeHandlerClient)({
185
+ context,
186
+ name: configuration.handlers.process,
187
+ payload: {
188
+ taskId,
189
+ type,
190
+ subTaskIndex: subTaskIndex + 1,
191
+ identity: context.security.getIdentity()
192
+ },
193
+ description: "Export pages - process - subtask"
194
+ });
195
+ }
196
+ }
197
+
198
+ return {
199
+ data: "",
200
+ error: null
201
+ };
202
+ };
203
+
204
+ exports.pagesHandler = pagesHandler;
@@ -0,0 +1 @@
1
+ {"version":3,"names":["pagesHandler","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","pageId","exportPagesDataKey","revisionType","page","ExportRevisionType","PUBLISHED","getPublishedPageById","getPage","e","NotFoundError","version","updateSubTask","PROCESSING","updateStats","prevStatus","nextStatus","pageDataZip","exportPage","COMPLETED","message","key","Key","FAILED","name","stack","code","invokeHandlerClient","handlers","combine","security","getIdentity","description","process"],"sources":["pagesHandler.ts"],"sourcesContent":["import { ExportRevisionType, ImportExportTaskStatus, PbImportExportContext } from \"~/types\";\nimport { invokeHandlerClient } from \"~/client\";\nimport { NotFoundError } from \"@webiny/handler-graphql\";\nimport { exportPage } 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 pages process workflow.\n */\nexport const pagesHandler = 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 Pages 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\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 { pageId, exportPagesDataKey, revisionType } = input;\n\n /**\n * At the moment, we only export a single revision of the page.\n * It could be \"published\" or \"latest\" depending upon user input.\n *\n * Note: In case of no \"published\" revision available, we use the latest revision.\n */\n let page;\n try {\n if (revisionType === ExportRevisionType.PUBLISHED) {\n // Get \"published\" page.\n page = await pageBuilder.getPublishedPageById({ id: pageId });\n } else {\n // Get \"latest\" page.\n page = await pageBuilder.getPage(pageId);\n }\n } catch (e) {\n // If we're looking for \"published\" page and doesn't found it, get latest page.\n if (revisionType === ExportRevisionType.PUBLISHED && e instanceof NotFoundError) {\n page = await pageBuilder.getPage(pageId);\n } else {\n throw e;\n }\n }\n\n if (!page) {\n log(`Unable to load page \"${pageId}\"`);\n throw new NotFoundError(`Unable to load page \"${pageId}\"`);\n }\n\n log(`Processing page key \"${pageId}\" | version ${page.version} | ${page.status}`);\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 page data and uploading to storage...`);\n // Extract Page\n const pageDataZip = await exportPage(page, exportPagesDataKey, 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 page \"${page.id}\" v${page.version} (${page.status}).`,\n key: pageDataZip.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_PAGES_PROCESS] Error => \", e);\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 stack: e.stack,\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 page 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 pages - 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 page error out.\n await invokeHandlerClient<Payload>({\n context,\n name: configuration.handlers.process,\n payload: {\n taskId,\n type,\n subTaskIndex: subTaskIndex + 1,\n identity: context.security.getIdentity()\n },\n description: \"Export pages - 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,YAAY,GAAG,OACxBC,aADwB,EAExBC,OAFwB,EAGxBC,OAHwB,KAIJ;EACpB,MAAMC,GAAG,GAAGC,OAAO,CAACD,GAApB;EACA,IAAIE,OAAJ;EACA,IAAIC,aAAa,GAAG,IAApB;EACA,IAAIC,mBAAmB,GAAGC,6BAAA,CAAuBC,OAAjD;EAEAN,GAAG,CAAC,sCAAD,CAAH;EACA,MAAM;IAAEO,WAAF;IAAeC;EAAf,IAA+BT,OAArC;EACA,MAAM;IAAEU,MAAF;IAAUC,YAAV;IAAwBC,IAAxB;IAA8BC;EAA9B,IAA2Cd,OAAjD,CARoB,CASpB;EACA;;EACA,IAAAe,0BAAA,EAAaD,QAAb,EAA2Cb,OAA3C;;EAEA,IAAI;IACA;AACR;AACA;AACA;IACQG,OAAO,GAAG,MAAMK,WAAW,CAACO,gBAAZ,CAA6BC,UAA7B,CAAwCN,MAAxC,EAAgD,IAAAO,eAAA,EAAQN,YAAR,EAAsB,CAAtB,CAAhD,CAAhB;IACA;AACR;AACA;AACA;;IACQ,IAAI,CAACR,OAAD,IAAYA,OAAO,CAACe,MAAR,KAAmBZ,6BAAA,CAAuBC,OAA1D,EAAmE;MAC/DH,aAAa,GAAG,IAAhB;MACA,OAAO;QACHe,IAAI,EAAE,EADH;QAEHC,KAAK,EAAE;MAFJ,CAAP;IAIH,CAND,MAMO;MACHhB,aAAa,GAAG,KAAhB;IACH;;IAEDH,GAAG,CAAE,uBAAsBE,OAAO,CAACkB,EAAG,EAAnC,CAAH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ATkB,CAA7B,CAAN;IAWH;EACJ;;EACD,OAAO;IACHnC,IAAI,EAAE,EADH;IAEHC,KAAK,EAAE;EAFJ,CAAP;AAIH,CAzKM"}
File without changes
File without changes
File without changes
@@ -0,0 +1,16 @@
1
+ import S3 from "aws-sdk/clients/s3";
2
+ import { Page, PageBlock } 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 interface ExportedPageData {
7
+ page: Pick<Page, "content" | "title" | "version" | "status" | "settings" | "path">;
8
+ files: File[];
9
+ }
10
+ export declare function exportPage(page: Page, exportPagesDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
11
+ export interface ExportedBlockData {
12
+ block: Pick<PageBlock, "name" | "content" | "preview">;
13
+ files: File[];
14
+ }
15
+ export declare function exportBlock(block: PageBlock, exportBlocksDataKey: string, fileManager: FileManagerContext["fileManager"]): Promise<S3.ManagedUpload.SendData>;
16
+ export declare function extractFilesFromData(data: Record<string, any>, files?: any[]): File[];
@@ -0,0 +1,135 @@
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_PAGES_FOLDER_KEY = exports.EXPORT_BLOCKS_FOLDER_KEY = void 0;
9
+ exports.exportBlock = exportBlock;
10
+ exports.exportPage = exportPage;
11
+ exports.extractFilesFromData = extractFilesFromData;
12
+
13
+ var _get = _interopRequireDefault(require("lodash/get"));
14
+
15
+ var _zipper = _interopRequireDefault(require("./zipper"));
16
+
17
+ const EXPORT_PAGES_FOLDER_KEY = "WEBINY_PB_EXPORT_PAGES";
18
+ exports.EXPORT_PAGES_FOLDER_KEY = EXPORT_PAGES_FOLDER_KEY;
19
+ const EXPORT_BLOCKS_FOLDER_KEY = "WEBINY_PB_EXPORT_BLOCK";
20
+ exports.EXPORT_BLOCKS_FOLDER_KEY = EXPORT_BLOCKS_FOLDER_KEY;
21
+
22
+ async function exportPage(page, exportPagesDataKey, fileManager) {
23
+ // Extract all files
24
+ const files = extractFilesFromData(page.content || {}); // Extract images from page settings
25
+
26
+ const pageSettingsImages = [(0, _get.default)(page, "settings.general.image"), (0, _get.default)(page, "settings.social.image")].filter(image => image && image.src);
27
+ const fileIds = [...files, ...pageSettingsImages].map(imageFile => imageFile.id); // Get file data for all images
28
+
29
+ const imageFilesData = [];
30
+
31
+ if (fileIds.length > 0) {
32
+ const [filesData] = await fileManager.files.listFiles({
33
+ ids: fileIds
34
+ });
35
+ imageFilesData.push(...filesData);
36
+ } // Extract the page data in a json file and upload it to S3
37
+
38
+
39
+ const pageData = {
40
+ page: {
41
+ content: page.content,
42
+ title: page.title,
43
+ path: page.path,
44
+ version: page.version,
45
+ status: page.status,
46
+ settings: page.settings
47
+ },
48
+ files: imageFilesData
49
+ };
50
+ const pageDataBuffer = Buffer.from(JSON.stringify(pageData));
51
+ const zipper = new _zipper.default({
52
+ exportInfo: {
53
+ files: imageFilesData,
54
+ name: page.title,
55
+ dataBuffer: pageDataBuffer
56
+ },
57
+ archiveFileKey: exportPagesDataKey
58
+ });
59
+ return zipper.process();
60
+ }
61
+
62
+ async function exportBlock(block, exportBlocksDataKey, fileManager) {
63
+ // Extract all files
64
+ const files = extractFilesFromData(block.content || {});
65
+ const fileIds = files.map(imageFile => imageFile.id); // Get file data for all images
66
+
67
+ const imageFilesData = [];
68
+
69
+ if (fileIds.length > 0) {
70
+ const [filesData] = await fileManager.files.listFiles({
71
+ ids: fileIds
72
+ });
73
+ imageFilesData.push(...filesData);
74
+ } // Add block preview image file data
75
+
76
+
77
+ if (block.preview.id) {
78
+ imageFilesData.push(await fileManager.files.getFile(block.preview.id));
79
+ } // Extract the block data in a json file and upload it to S3
80
+
81
+
82
+ const blockData = {
83
+ block: {
84
+ name: block.name,
85
+ content: block.content,
86
+ preview: block.preview
87
+ },
88
+ files: imageFilesData
89
+ };
90
+ const blockDataBuffer = Buffer.from(JSON.stringify(blockData));
91
+ const zipper = new _zipper.default({
92
+ exportInfo: {
93
+ files: imageFilesData,
94
+ name: block.name,
95
+ dataBuffer: blockDataBuffer
96
+ },
97
+ archiveFileKey: exportBlocksDataKey
98
+ });
99
+ return zipper.process();
100
+ }
101
+
102
+ function extractFilesFromData(data, files = []) {
103
+ // Base case: termination
104
+ if (!data || typeof data !== "object") {
105
+ return files;
106
+ } // Recursively call function for each element
107
+
108
+
109
+ if (Array.isArray(data)) {
110
+ for (let i = 0; i < data.length; i++) {
111
+ const element = data[i];
112
+ extractFilesFromData(element, files);
113
+ }
114
+
115
+ return files;
116
+ } // Main
117
+
118
+
119
+ const tuple = Object.entries(data);
120
+
121
+ for (let i = 0; i < tuple.length; i++) {
122
+ const [key, value] = tuple[i]; // TODO: @ashutosh extract it to plugins, so that, we can handle cases for other components too.
123
+
124
+ if (key === "file" && value) {
125
+ files.push(value);
126
+ } else if (key === "images" && Array.isArray(value)) {
127
+ // Handle case for "images-list" component
128
+ files.push(...value);
129
+ } else {
130
+ extractFilesFromData(value, files);
131
+ }
132
+ }
133
+
134
+ return files;
135
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"names":["EXPORT_PAGES_FOLDER_KEY","EXPORT_BLOCKS_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","data","Array","isArray","i","element","tuple","Object","entries","key","value"],"sources":["utils.ts"],"sourcesContent":["import S3 from \"aws-sdk/clients/s3\";\nimport { Page, PageBlock } 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\";\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 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 {\n extractFilesFromData(value, files);\n }\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;AAGA;;AACA;;AAEO,MAAMA,uBAAuB,GAAG,wBAAhC;;AACA,MAAMC,wBAAwB,GAAG,wBAAjC;;;AAOA,eAAeC,UAAf,CACHC,IADG,EAEHC,kBAFG,EAGHC,WAHG,EAI+B;EAClC;EACA,MAAMC,KAAK,GAAGC,oBAAoB,CAACJ,IAAI,CAACK,OAAL,IAAgB,EAAjB,CAAlC,CAFkC,CAGlC;;EACA,MAAMC,kBAAkB,GAAG,CACvB,IAAAC,YAAA,EAAIP,IAAJ,EAAU,wBAAV,CADuB,EAEvB,IAAA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AP,EAAP;AACH;;AAEM,SAASlC,oBAAT,CAA8B0C,IAA9B,EAAyD3C,KAAY,GAAG,EAAxE,EAAoF;EACvF;EACA,IAAI,CAAC2C,IAAD,IAAS,OAAOA,IAAP,KAAgB,QAA7B,EAAuC;IACnC,OAAO3C,KAAP;EACH,CAJsF,CAKvF;;;EACA,IAAI4C,KAAK,CAACC,OAAN,CAAcF,IAAd,CAAJ,EAAyB;IACrB,KAAK,IAAIG,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGH,IAAI,CAAC9B,MAAzB,EAAiCiC,CAAC,EAAlC,EAAsC;MAClC,MAAMC,OAAO,GAAGJ,IAAI,CAACG,CAAD,CAApB;MACA7C,oBAAoB,CAAC8C,OAAD,EAAU/C,KAAV,CAApB;IACH;;IACD,OAAOA,KAAP;EACH,CAZsF,CAcvF;;;EACA,MAAMgD,KAAK,GAAGC,MAAM,CAACC,OAAP,CAAeP,IAAf,CAAd;;EACA,KAAK,IAAIG,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGE,KAAK,CAACnC,MAA1B,EAAkCiC,CAAC,EAAnC,EAAuC;IACnC,MAAM,CAACK,GAAD,EAAMC,KAAN,IAAeJ,KAAK,CAACF,CAAD,CAA1B,CADmC,CAEnC;;IACA,IAAIK,GAAG,KAAK,MAAR,IAAkBC,KAAtB,EAA6B;MACzBpD,KAAK,CAACiB,IAAN,CAAWmC,KAAX;IACH,CAFD,MAEO,IAAID,GAAG,KAAK,QAAR,IAAoBP,KAAK,CAACC,OAAN,CAAcO,KAAd,CAAxB,EAA8C;MACjD;MACApD,KAAK,CAACiB,IAAN,CAAW,GAAGmC,KAAd;IACH,CAHM,MAGA;MACHnD,oBAAoB,CAACmD,KAAD,EAAQpD,KAAR,CAApB;IACH;EACJ;;EACD,OAAOA,KAAP;AACH"}
@@ -2,15 +2,15 @@
2
2
  /// <reference types="node" />
3
3
  import S3 from "aws-sdk/clients/s3";
4
4
  import { Readable } from "stream";
5
- import { ImageFile } from "./utils";
5
+ import { File } from "@webiny/api-file-manager/types";
6
6
  interface FileStreamDetails {
7
7
  stream: Readable;
8
8
  filename: string;
9
9
  }
10
10
  interface ExportInfo {
11
- files: ImageFile[];
12
- pageTitle: string;
13
- pageDataBuffer: Buffer;
11
+ files: File[];
12
+ name: string;
13
+ dataBuffer: Buffer;
14
14
  }
15
15
  export interface ZipperConfig {
16
16
  exportInfo: ExportInfo;
@@ -29,7 +29,8 @@ export declare class ZipOfZip {
29
29
  private readonly archiveFormat;
30
30
  private readonly archiveFileName;
31
31
  keys: string[];
32
- constructor(keys: string[]);
32
+ filename: string;
33
+ constructor(keys: string[], filename: string);
33
34
  getFileStreams(): FileStreamDetails[];
34
35
  process(): Promise<S3.ManagedUpload.SendData>;
35
36
  }
@@ -31,12 +31,12 @@ class Zipper {
31
31
  (0, _defineProperty2.default)(this, "archiveFileName", void 0);
32
32
  (0, _defineProperty2.default)(this, "config", void 0);
33
33
  this.config = config;
34
- 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`);
35
35
  }
36
36
 
37
37
  s3DownloadStreams() {
38
38
  const exportInfo = this.config.exportInfo;
39
- const prefix = (0, _uniqid.default)("", `-${(0, _kebabCase.default)(exportInfo.pageTitle)}`);
39
+ const prefix = (0, _uniqid.default)("", `-${(0, _kebabCase.default)(exportInfo.name)}`);
40
40
  const files = exportInfo.files.map(({
41
41
  key
42
42
  }) => {
@@ -46,8 +46,8 @@ class Zipper {
46
46
  };
47
47
  });
48
48
  return [...files, {
49
- stream: _stream.Readable.from(exportInfo.pageDataBuffer),
50
- filename: `${prefix}\\${exportInfo.pageTitle}.json`
49
+ stream: _stream.Readable.from(exportInfo.dataBuffer),
50
+ filename: `${prefix}\\${exportInfo.name}.json`
51
51
  }];
52
52
  }
53
53
 
@@ -82,15 +82,16 @@ class Zipper {
82
82
  }
83
83
 
84
84
  exports.default = Zipper;
85
- const PAGE_EXPORT_BASENAME = `WEBINY_PAGE_EXPORT.zip`;
86
85
 
87
86
  class ZipOfZip {
88
- constructor(keys) {
87
+ constructor(keys, filename) {
89
88
  (0, _defineProperty2.default)(this, "archiveFormat", "zip");
90
89
  (0, _defineProperty2.default)(this, "archiveFileName", void 0);
91
90
  (0, _defineProperty2.default)(this, "keys", void 0);
91
+ (0, _defineProperty2.default)(this, "filename", void 0);
92
92
  this.keys = keys;
93
- this.archiveFileName = (0, _uniqid.default)("", `-${PAGE_EXPORT_BASENAME}`);
93
+ this.filename = filename;
94
+ this.archiveFileName = (0, _uniqid.default)("", `-${filename}`);
94
95
  }
95
96
 
96
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,CAAYK,UAA/B;IACA,MAAMG,MAAM,GAAG,IAAAN,eAAA,EAAS,EAAT,EAAc,IAAG,IAAAE,kBAAA,EAA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AJD,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;
@@ -0,0 +1,155 @@
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.default = void 0;
9
+
10
+ var _error = _interopRequireDefault(require("@webiny/error"));
11
+
12
+ var _handlerGraphql = require("@webiny/handler-graphql");
13
+
14
+ var _api = require("@webiny/api");
15
+
16
+ var _checkBasePermissions = _interopRequireDefault(require("@webiny/api-page-builder/graphql/crud/utils/checkBasePermissions"));
17
+
18
+ var _types = require("../../types");
19
+
20
+ var _client = require("../../client");
21
+
22
+ var _utils = require("../../import/utils");
23
+
24
+ var _utils2 = require("../../export/utils");
25
+
26
+ var _utils3 = require("@webiny/utils");
27
+
28
+ const PERMISSION_NAME = "pb.block";
29
+ const EXPORT_BLOCKS_PROCESS_HANDLER = process.env.EXPORT_PROCESS_HANDLER;
30
+ const IMPORT_BLOCKS_CREATE_HANDLER = process.env.IMPORT_CREATE_HANDLER;
31
+
32
+ var _default = new _api.ContextPlugin(context => {
33
+ const importExportCrud = {
34
+ async importBlocks({
35
+ category: categorySlug,
36
+ zipFileUrl
37
+ }) {
38
+ await (0, _checkBasePermissions.default)(context, PERMISSION_NAME, {
39
+ rwd: "w"
40
+ }); // Bail out early if category not found
41
+
42
+ const category = await context.pageBuilder.getBlockCategory(categorySlug);
43
+
44
+ if (!category) {
45
+ throw new _handlerGraphql.NotFoundError(`Category with slug "${categorySlug}" not found.`);
46
+ } // Create a task for import block
47
+
48
+
49
+ const task = await context.pageBuilder.importExportTask.createTask({
50
+ status: _types.ImportExportTaskStatus.PENDING,
51
+ input: {
52
+ category: categorySlug,
53
+ zipFileUrl
54
+ }
55
+ });
56
+ /**
57
+ * Import Blocks
58
+ * ImportBlocks
59
+ * importBlocks
60
+ */
61
+
62
+ await (0, _client.invokeHandlerClient)({
63
+ context,
64
+ name: IMPORT_BLOCKS_CREATE_HANDLER,
65
+ payload: {
66
+ category: categorySlug,
67
+ zipFileUrl,
68
+ task,
69
+ type: "block",
70
+ identity: context.security.getIdentity()
71
+ },
72
+ description: "Import Blocks - create"
73
+ });
74
+ return {
75
+ task
76
+ };
77
+ },
78
+
79
+ async exportBlocks({
80
+ ids: initialBlockIds,
81
+ where
82
+ }) {
83
+ await (0, _checkBasePermissions.default)(context, PERMISSION_NAME, {
84
+ rwd: "w"
85
+ });
86
+ let blockIds = initialBlockIds || []; // If no ids are provided then it means we want to export all blocks
87
+
88
+ if (!initialBlockIds || Array.isArray(initialBlockIds) && initialBlockIds.length === 0) {
89
+ blockIds = [];
90
+ const blocks = await context.pageBuilder.listPageBlocks({
91
+ where
92
+ }); // Save block ids
93
+
94
+ blocks.forEach(block => blockIds.push(block.id));
95
+ }
96
+
97
+ if (blockIds.length === 0) {
98
+ throw new _error.default("Cannot export blocks - no blocks found for provided inputs.", "EMPTY_EXPORT_NO_BLOCKS_FOUND");
99
+ } // Create the main task for blocks export.
100
+
101
+
102
+ const task = await context.pageBuilder.importExportTask.createTask({
103
+ status: _types.ImportExportTaskStatus.PENDING
104
+ });
105
+ const exportBlocksDataKey = `${_utils2.EXPORT_BLOCKS_FOLDER_KEY}/${task.id}`; // For each block create a sub task and invoke the process handler.
106
+
107
+ for (let i = 0; i < blockIds.length; i++) {
108
+ const blockId = blockIds[i]; // Create sub task.
109
+
110
+ await context.pageBuilder.importExportTask.createSubTask(task.id, (0, _utils3.zeroPad)(i + 1, 5), {
111
+ status: _types.ImportExportTaskStatus.PENDING,
112
+ input: {
113
+ blockId,
114
+ exportBlocksDataKey
115
+ }
116
+ });
117
+ } // Update main task status.
118
+
119
+
120
+ await context.pageBuilder.importExportTask.updateTask(task.id, {
121
+ status: _types.ImportExportTaskStatus.PROCESSING,
122
+ stats: (0, _utils.initialStats)(blockIds.length),
123
+ input: {
124
+ exportBlocksDataKey
125
+ }
126
+ });
127
+ /**
128
+ * Export Blocks
129
+ * ExportBlocks
130
+ * exportBlocks
131
+ */
132
+ // Invoke handler.
133
+
134
+ await (0, _client.invokeHandlerClient)({
135
+ context,
136
+ name: EXPORT_BLOCKS_PROCESS_HANDLER,
137
+ payload: {
138
+ taskId: task.id,
139
+ subTaskIndex: 1,
140
+ type: "block",
141
+ identity: context.security.getIdentity()
142
+ },
143
+ description: "Export blocks - process"
144
+ });
145
+ return {
146
+ task
147
+ };
148
+ }
149
+
150
+ }; // Modify context
151
+
152
+ context.pageBuilder.blocks = importExportCrud;
153
+ });
154
+
155
+ exports.default = _default;