@appdirect/sfb-toolkit 4.0.20 → 4.0.24

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 (73) hide show
  1. package/bin/index.js +93 -4
  2. package/config/index.js +1 -1
  3. package/coverage/clover.xml +2 -2
  4. package/coverage/lcov-report/constants/customUserAttributesMock.js.html +1 -1
  5. package/coverage/lcov-report/constants/index.html +1 -1
  6. package/coverage/lcov-report/constants/pageUrls.js.html +1 -1
  7. package/coverage/lcov-report/constants/userMock.js.html +1 -1
  8. package/coverage/lcov-report/controllers/controllers-utils/assetsUtils.js.html +1 -1
  9. package/coverage/lcov-report/controllers/controllers-utils/index.html +1 -1
  10. package/coverage/lcov-report/controllers/data-filters/bootstrap-data-filter.js.html +1 -1
  11. package/coverage/lcov-report/controllers/data-filters/call-to-actions-filter.js.html +1 -1
  12. package/coverage/lcov-report/controllers/data-filters/index.html +1 -1
  13. package/coverage/lcov-report/controllers/index.html +1 -1
  14. package/coverage/lcov-report/controllers/index.js.html +1 -1
  15. package/coverage/lcov-report/front-end-utils/src/components/base/ResultItem.js.html +1 -1
  16. package/coverage/lcov-report/front-end-utils/src/components/base/SearchBar.js.html +1 -1
  17. package/coverage/lcov-report/front-end-utils/src/components/base/index.html +1 -1
  18. package/coverage/lcov-report/front-end-utils/src/components/base/item.js.html +1 -1
  19. package/coverage/lcov-report/front-end-utils/src/components/container.js.html +1 -1
  20. package/coverage/lcov-report/front-end-utils/src/components/data-view.js.html +1 -1
  21. package/coverage/lcov-report/front-end-utils/src/components/header-view.js.html +1 -1
  22. package/coverage/lcov-report/front-end-utils/src/components/index.html +1 -1
  23. package/coverage/lcov-report/front-end-utils/src/components/search.js.html +1 -1
  24. package/coverage/lcov-report/front-end-utils/src/constants/index.html +1 -1
  25. package/coverage/lcov-report/front-end-utils/src/constants/pageUrl.js.html +1 -1
  26. package/coverage/lcov-report/front-end-utils/src/constants/roleType.js.html +1 -1
  27. package/coverage/lcov-report/front-end-utils/src/constants/searchType.js.html +1 -1
  28. package/coverage/lcov-report/front-end-utils/src/utils/debounce.js.html +1 -1
  29. package/coverage/lcov-report/front-end-utils/src/utils/index.html +1 -1
  30. package/coverage/lcov-report/index.html +1 -1
  31. package/coverage/lcov-report/middlewares/config.js.html +1 -1
  32. package/coverage/lcov-report/middlewares/index.html +1 -1
  33. package/coverage/lcov-report/tools/index.html +1 -1
  34. package/coverage/lcov-report/tools/proxy-fetch.js.html +1 -1
  35. package/customComponents/index.js +10 -2
  36. package/npm-shrinkwrap.json +314 -128
  37. package/package.json +4 -4
  38. package/readme.md +9 -0
  39. package/src/boilerplates/AddComponent/AddComponent.jsx +234 -0
  40. package/src/boilerplates/AddComponent/styles/AddComponent.scss +47 -0
  41. package/src/tools/.sfbconfig +1 -1
  42. package/src/tools/package-fonts.js +1 -1
  43. package/src/tools/prompt-questions.js +109 -14
  44. package/src/tools/toolkit-common-fun.js +41 -15
  45. package/src/tools/toolkit-common-vars-namespace.js +106 -0
  46. package/src/tools/toolkit-common-vars.js +2 -2
  47. package/src/tools/toolkit-components-add.js +334 -0
  48. package/src/tools/toolkit-components-copy.js +390 -0
  49. package/src/tools/toolkit-components-delete.js +370 -0
  50. package/src/tools/toolkit-components-fun.js +126 -7
  51. package/src/tools/toolkit-components-info.js +6 -4
  52. package/src/tools/toolkit-components-vars.js +50 -0
  53. package/src/tools/toolkit-components.js +1 -1
  54. package/src/tools/toolkit-create-extension.js +1 -1
  55. package/src/tools/toolkit-create.js +2 -3
  56. package/src/tools/toolkit-import.js +182 -0
  57. package/src/tools/toolkit-install.js +6 -5
  58. package/src/tools/toolkit-mock.js +1 -1
  59. package/src/tools/toolkit-package.js +3 -0
  60. package/src/tools/toolkit-setup.js +1 -1
  61. package/src/tools/toolkit-start.js +4 -1
  62. package/src/tools/toolkit-storybook.js +136 -48
  63. package/src/tools/toolkit-zip-utils.js +35 -0
  64. package/src/tools/zip-theme.js +62 -50
  65. package/themes-config.json +0 -7
  66. package/customComponents/atoms/label/Label.jsx +0 -20
  67. package/customComponents/atoms/label/stories/Label.story.mdx +0 -20
  68. package/customComponents/atoms/label/styles/Label.scss +0 -4
  69. package/customComponents/components/atoms-showcase-custom/AtomsShowcaseCustom.jsx +0 -8
  70. package/customComponents/components/atoms-showcase-custom/stories/AtomsShowcaseCustom.story.mdx +0 -17
  71. package/customComponents/components/atoms-showcase-modules/AtomsShowcaseModules.jsx +0 -223
  72. package/customComponents/components/atoms-showcase-modules/stories/AtomsShowcaseModules.story.mdx +0 -49
  73. package/customComponents/components/index.js +0 -2
@@ -0,0 +1,370 @@
1
+ const fs = require("fs");
2
+ const _ = require("lodash");
3
+ const { ACTIVE_THEME_PATH } = require("./toolkit-common-vars");
4
+ const { SUCCESS, ERROR, PATH_TO_CUSTOM_COMPONENTS_INDEX, BASE_PATH_TO_COMPONENTS_INDEX,
5
+ COMPONENTS_DELETE_FLAG_SHORT, COMPONENTS_DELETE_FLAG_FULL, DELETED, NO_MATCH, INVALID_COMPONENT_NAME,
6
+ INVALID_VERSION, MISSING_COMPONENT_NAME, COMPONENTS_NOT_INSTALLED_ERROR } = require("./toolkit-components-vars");
7
+ const { customComponentsEnabled, constructPath } = require("./toolkit-components-fun");
8
+ const { shouldBeProjectFolder } = require("./toolkit-common-fun");
9
+ const chalk = require("chalk");
10
+ const inquirer = require("inquirer");
11
+
12
+ // check if user is in correct location
13
+ shouldBeProjectFolder(true);
14
+
15
+ const traverseFiles = (traverseList) => {
16
+ if(Object.keys(traverseList).length === 0) {
17
+ return [];
18
+ }
19
+
20
+ const dfsPathsToTraverse = [...Object.keys(traverseList)];
21
+ const dfsAllTraversedPaths = [...Object.keys(traverseList)];
22
+
23
+ while(dfsPathsToTraverse.length > 0) {
24
+ const path = dfsPathsToTraverse.pop();
25
+ let isScssFile = path.match(/.scss/);
26
+ let fileData;
27
+
28
+ if(fs.existsSync(path)) {
29
+ fileData = fs.readFileSync(path, 'utf8').replace(/^\/\/+.*\s*/g, '');
30
+ } else {
31
+ continue;
32
+ }
33
+
34
+ let imports;
35
+
36
+ if(isScssFile) {
37
+ imports = fileData.matchAll(/@import.*\s+['|"](.+)['|"]/g);
38
+ } else {
39
+ imports = fileData.matchAll(/import.*\s+['|"](\.+.+)['|"]|from\s+['|"](\.+.+)['|"]/g);
40
+ }
41
+
42
+ for(const importPaths of imports) {
43
+ const usePath = importPaths[1] || importPaths[2];
44
+ let fullPath = constructPath(path, usePath);
45
+ if(!dfsAllTraversedPaths.includes(fullPath)) {
46
+ dfsPathsToTraverse.push(fullPath);
47
+ dfsAllTraversedPaths.push(fullPath);
48
+ }
49
+ }
50
+ }
51
+
52
+ return dfsAllTraversedPaths;
53
+ }
54
+
55
+ const formattedDeleteStatus = ({ data = '', statusMessage, statusType, version, helperMessage = '', maxStringLength = 30 }) => {
56
+ const formattingOffset = (maxStringLength + 20) <= 50 ? 50 : maxStringLength + 20;
57
+ switch(statusType) {
58
+ case SUCCESS:
59
+ console.log(`[${chalk.dim(version.padStart(7, ' '))}] `
60
+ + chalk.green(`${data.padEnd(formattingOffset, ".")}${statusMessage}`)
61
+ + `(${helperMessage && chalk.dim(helperMessage)})`);
62
+ break;
63
+ case ERROR:
64
+ console.log(`[${chalk.dim(version.padStart(7, ' '))}] `
65
+ + chalk.red(`${data.padEnd(formattingOffset, ".")}${statusMessage}`)
66
+ + `${helperMessage && `(${chalk.dim(helperMessage)})`}`);
67
+ break;
68
+ }
69
+ }
70
+
71
+ const deleteEmptyFolders = (path) => {
72
+ const directoryPath = fs.lstatSync(path).isDirectory();
73
+ if(!directoryPath) return;
74
+
75
+ const dirContent = directoryPath && fs.readdirSync(path);
76
+
77
+ if(dirContent && dirContent.length > 0) {
78
+ dirContent.forEach(dirPath => {
79
+ if(fs.lstatSync(`${path}/${dirPath}`).isDirectory()) {
80
+ deleteEmptyFolders(`${path}/${dirPath}`);
81
+ if(fs.existsSync(`${path}/${dirPath}`) && fs.readdirSync(`${path}/${dirPath}`).length === 0) {
82
+ fs.rmdirSync(`${path}/${dirPath}`);
83
+ }
84
+ }
85
+ })
86
+ }
87
+
88
+ if(fs.lstatSync(path).isDirectory() && fs.readdirSync(path).length === 0) {
89
+ fs.rmdirSync(path);
90
+ }
91
+ }
92
+
93
+ const deleteExportsFromIndex = (componentName, componentIndexPath, indexFileData) => {
94
+ const nonCommentedOutExportsToDelete = new RegExp(`(?<!\/\/\\s*)export.*\\s${componentName}`
95
+ + `[\\s|}].*${componentIndexPath}[.jsx?]?.*\\r?\\n?`, 'g');
96
+ return indexFileData.replace(nonCommentedOutExportsToDelete, '');
97
+ }
98
+
99
+ const deleteCopiedComponents = (
100
+ componentsNotToBeDeleted = {},
101
+ componentsToBeDeleted = {},
102
+ version
103
+ ) => {
104
+ let indexFileData = fs.readFileSync(PATH_TO_CUSTOM_COMPONENTS_INDEX, 'utf8');
105
+ const copiedComponents = { ...componentsNotToBeDeleted, ...componentsToBeDeleted };
106
+ const componentDependencies = {};
107
+
108
+ Object.keys(copiedComponents).forEach((componentPath) => {
109
+ const componentRoot = componentPath.match(/\/components\/([A-Za-z0-9_-]+)\/|\/atoms\/([A-Za-z0-9_-]+)\//);
110
+ const fileData = fs.readFileSync(componentPath, 'utf8');
111
+ const hasChildrenComponents = fileData.includes("hasChildrenComponents");
112
+
113
+ const matchedRoot = componentRoot[1] || componentRoot[2];
114
+
115
+ if(hasChildrenComponents) {
116
+ _.set(componentDependencies, `${matchedRoot}.hasChildren`, componentPath);
117
+ }
118
+
119
+ if(componentsToBeDeleted[componentPath]) {
120
+ const compToDelete = _.get(componentDependencies, `${matchedRoot}.deleteComponents`);
121
+ if(compToDelete) {
122
+ compToDelete.push(componentPath);
123
+ } else {
124
+ _.set(componentDependencies, `${matchedRoot}.deleteComponents`, [componentPath])
125
+ }
126
+ }
127
+
128
+ });
129
+
130
+ const allPathsToFilesNotToDelete = traverseFiles(componentsNotToBeDeleted);
131
+ const allPathsToFilesPotentiallyToDelete = traverseFiles(componentsToBeDeleted);
132
+
133
+ const pathsToFilesToDelete = [];
134
+ allPathsToFilesPotentiallyToDelete.forEach(path => {
135
+ if(!allPathsToFilesNotToDelete.includes(path)) {
136
+ const pathsToDelete = path.replace('node_modules/@appdirect/sfb-theme-components',
137
+ `customComponents/sfb_theme_components_${version}`);
138
+ pathsToFilesToDelete.push(pathsToDelete);
139
+ try {
140
+ if(fs.existsSync(pathsToDelete)) {
141
+ fs.unlinkSync(pathsToDelete);
142
+ }
143
+ } catch (error) {
144
+ console.log(error);
145
+ }
146
+ }
147
+ })
148
+
149
+ deleteEmptyFolders(`${ACTIVE_THEME_PATH}/customComponents/sfb_theme_components_${version}`);
150
+
151
+ Object.values(componentDependencies).forEach((compObj) => {
152
+ if(compObj.deleteComponents) {
153
+ compObj.deleteComponents.forEach(compPath => {
154
+ const pathToComponents = compPath.replace('node_modules/@appdirect/sfb-theme-components',
155
+ `customComponents/sfb_theme_components_${version}`).replace(/\/\w+.jsx?/, '');
156
+ const componentIndexPath = pathToComponents.split('customComponents')[1];
157
+ if(compObj.hasChildren) {
158
+ if(compObj.hasChildren === compPath) {
159
+ formattedDeleteStatus({
160
+ data: copiedComponents[compPath],
161
+ statusMessage: `[${DELETED}]`,
162
+ statusType: SUCCESS,
163
+ version,
164
+ helperMessage: pathToComponents
165
+ });
166
+ indexFileData = deleteExportsFromIndex(copiedComponents[compPath], componentIndexPath, indexFileData);
167
+ } else {
168
+ if(compObj.deleteComponents.includes(compObj.hasChildren)) {
169
+ formattedDeleteStatus({
170
+ data: copiedComponents[compPath],
171
+ statusMessage: `[${DELETED}]`,
172
+ statusType: SUCCESS,
173
+ version,
174
+ helperMessage: pathToComponents
175
+ });
176
+ indexFileData = deleteExportsFromIndex(copiedComponents[compPath], componentIndexPath, indexFileData);
177
+ } else {
178
+ formattedDeleteStatus({
179
+ data: copiedComponents[compPath],
180
+ statusMessage: `[${ERROR}][DEPENDENCY_WITH_${copiedComponents[compObj.hasChildren].toUpperCase()}]`,
181
+ statusType: ERROR,
182
+ version
183
+ });
184
+ }
185
+ }
186
+ } else {
187
+ formattedDeleteStatus({
188
+ data: copiedComponents[compPath],
189
+ statusMessage: `[${DELETED}]`,
190
+ statusType: SUCCESS,
191
+ version,
192
+ helperMessage: pathToComponents
193
+ });
194
+ indexFileData = deleteExportsFromIndex(copiedComponents[compPath], componentIndexPath, indexFileData);
195
+ }
196
+ })
197
+ }
198
+ });
199
+
200
+ fs.writeFileSync(PATH_TO_CUSTOM_COMPONENTS_INDEX, `${indexFileData.trim()}\n`);
201
+ };
202
+
203
+
204
+ (async () => {
205
+ try {
206
+ const areCustomComponentsEnabled = await customComponentsEnabled();
207
+ if(areCustomComponentsEnabled) {
208
+ const componentMap = {};
209
+ const customComponentsIndexFileData = fs.readFileSync(PATH_TO_CUSTOM_COMPONENTS_INDEX, 'utf8');
210
+ const localComponentMatches = [
211
+ ...customComponentsIndexFileData
212
+ .matchAll(/(?<!\/\/\s*)export.*as\s+(\w+)\s+.*from\s+['|"](\.+\/sfb_theme_components_([0-9_]+)\/.+)['|"]/g)
213
+ ];
214
+
215
+ const sfbComponentsIndexFileData = fs.readFileSync(BASE_PATH_TO_COMPONENTS_INDEX, 'utf8').replace(/\/\/+.*\s*/g, '');
216
+ const sfbComponentMatches = [...sfbComponentsIndexFileData
217
+ .matchAll(/.*as\s+(\w+)\s+.*from\s+['|"](\.+\/.+)['|"]/g)]
218
+ .reduce((acc, value) => ({ ...acc, [value[1].toLowerCase()]: value[2] }), {});
219
+
220
+
221
+ let maxComponentStringLength = 0;
222
+ let selectedComponentsList;
223
+ const validVersions = new Set();
224
+
225
+ localComponentMatches.forEach(component => {
226
+ if(sfbComponentMatches[component[1].toLowerCase()]) {
227
+ maxComponentStringLength = maxComponentStringLength < component[1].length
228
+ ? component[1].length
229
+ : maxComponentStringLength;
230
+
231
+ componentMap[`${sfbComponentMatches[component[1].toLowerCase()]}_${component[3]}`] = {
232
+ path: sfbComponentMatches[component[1].toLowerCase()],
233
+ name: component[1],
234
+ version: component[3]
235
+ }
236
+ validVersions.add(component[3]);
237
+ }
238
+ })
239
+
240
+ if(Object.keys(componentMap).length === 0) {
241
+ return console.log(chalk.cyanBright('[INFO] No components that can be deleted have been found.'));
242
+ }
243
+
244
+ if(process.argv[2]) {
245
+ const deleteObj = new Set();
246
+ let deleteData;
247
+ if(process.argv[2]) {
248
+ const listOfFlags = [...process.argv[2].matchAll(/--?(\w+)/g)];
249
+
250
+ if(listOfFlags.length === 0) {
251
+ console.log(`${ERROR}: missing flag [${COMPONENTS_DELETE_FLAG_SHORT}] or [${COMPONENTS_DELETE_FLAG_FULL}].`);
252
+ process.exit(0);
253
+ }
254
+
255
+ listOfFlags.forEach(flag => {
256
+ if(!(flag[0] === COMPONENTS_DELETE_FLAG_SHORT || flag[0] === COMPONENTS_DELETE_FLAG_FULL)){
257
+ console.log(`${ERROR}: unknown option '${flag[0]}'.`);
258
+ process.exit(0);
259
+ }
260
+ })
261
+ const pattern = new RegExp(`,?${COMPONENTS_DELETE_FLAG_SHORT},?|,?${COMPONENTS_DELETE_FLAG_FULL},?`);
262
+ deleteData = [...process.argv[2].replaceAll('.', '_').split(pattern).filter(Boolean)];
263
+ }
264
+ const validVersionsList = [...validVersions];
265
+ if(deleteData && deleteData.length > 0) {
266
+ deleteData.forEach(arg => {
267
+ const arguments = arg.split(',');
268
+ const isArgumentVersionValid = validVersionsList.includes(arguments[0]);
269
+ if(arguments.length > 1) {
270
+ for(let i = 1; i < arguments.length; i++ ) {
271
+ const componentKey = `${sfbComponentMatches[arguments[i].toLowerCase()]}_${arguments[0]}`;
272
+ if(componentMap[componentKey]) {
273
+ deleteObj.add(`${sfbComponentMatches[arguments[i].toLowerCase()]}_${arguments[0]}`)
274
+ } else {
275
+ const isArgumentComponentValid = /^[A-Za-z]+\d*$/.test(arguments[i]);
276
+ const message = `${
277
+ isArgumentVersionValid
278
+ ? isArgumentComponentValid
279
+ ? `[${NO_MATCH}]`
280
+ : `[${INVALID_COMPONENT_NAME}]`
281
+ : isArgumentComponentValid
282
+ ? `[${NO_MATCH}][${INVALID_VERSION}]`
283
+ : `[${INVALID_COMPONENT_NAME}][${INVALID_VERSION}]`
284
+ }`;
285
+
286
+ formattedDeleteStatus({
287
+ data: arguments[i],
288
+ statusMessage: message,
289
+ statusType: ERROR,
290
+ version: arguments[0],
291
+ helperMessage: !isArgumentVersionValid ? `possible versions: ${validVersionsList}` : ''
292
+ })
293
+ }
294
+ }
295
+ } else {
296
+ const message = `${
297
+ isArgumentVersionValid
298
+ ? `[${MISSING_COMPONENT_NAME}]`
299
+ : `[${MISSING_COMPONENT_NAME}][${INVALID_VERSION}]`
300
+ }`;
301
+
302
+ formattedDeleteStatus({
303
+ statusMessage: message,
304
+ statusType: ERROR,
305
+ version: arguments[0],
306
+ helperMessage: !isArgumentVersionValid ? `possible versions: ${validVersionsList}` : ''
307
+ })
308
+ }
309
+ })
310
+ } else {
311
+ console.log(chalk.red(`[${ERROR}] missing CLI command arguments.`));
312
+ process.exit(0);
313
+ }
314
+ selectedComponentsList = [...deleteObj];
315
+ } else {
316
+ const selectedComponents = await inquirer.prompt([{
317
+ type: 'checkbox',
318
+ name: 'components',
319
+ message: 'Please select component(s) to delete:',
320
+ choices: Object.values(componentMap).map(({ version, path, name }) => {
321
+ return {
322
+ name: `[${chalk.dim(version)}] ${name}`,
323
+ value: `${path}_${version}`
324
+ }
325
+ }).sort((a, b) => a.value.localeCompare(b.value))
326
+ }]);
327
+
328
+ selectedComponentsList = selectedComponents.components;
329
+
330
+ if(selectedComponentsList.length === 0) {
331
+ console.log(chalk.cyanBright(`[INFO] No components were selected.`));
332
+ return;
333
+ }
334
+
335
+ if(selectedComponentsList.length > 0) {
336
+ const confirmComponentsDeletion = (await inquirer.prompt({
337
+ type: 'confirm',
338
+ name: 'choice',
339
+ message: `This action is irreversible, are you certain you wish to delete the components selected above?`
340
+ })).choice;
341
+
342
+ if(!confirmComponentsDeletion) {
343
+ process.exit(0);
344
+ }
345
+ }
346
+ }
347
+
348
+ const componentsNotToBeDeleted = {};
349
+ const componentsToBeDeleted = {};
350
+
351
+ Object.entries(componentMap).forEach(([componentKey, {version, path, name}]) => {
352
+ const componentPathSfb = constructPath(BASE_PATH_TO_COMPONENTS_INDEX, path)?.replaceAll("\\", "/");
353
+
354
+ if(selectedComponentsList.includes(componentKey)) {
355
+ _.set(componentsToBeDeleted, `${version}.['${componentPathSfb}']`, name);
356
+ } else {
357
+ _.set(componentsNotToBeDeleted, `${version}.['${componentPathSfb}']`, name);
358
+ }
359
+ });
360
+
361
+ Object.entries(componentsToBeDeleted).forEach(([version, pathsToDelete]) => {
362
+ deleteCopiedComponents(componentsNotToBeDeleted[version], pathsToDelete, version);
363
+ })
364
+ } else {
365
+ console.log(COMPONENTS_NOT_INSTALLED_ERROR);
366
+ }
367
+ } catch (err) {
368
+ console.error(chalk.red(`\n ERROR: Unable to delete components due to: ${err}.\n`));
369
+ }
370
+ })();
@@ -1,6 +1,9 @@
1
1
  const fs = require("fs-extra");
2
2
  const chalk = require("chalk");
3
+ const path = require("path");
4
+
3
5
  const { CURRENT_PATH, THEME_COMPONENT_MODULE, ACTIVE_THEME_PATH} = require("./toolkit-common-vars");
6
+ const { zipFolder, extractZip } = require("./toolkit-zip-utils");
4
7
 
5
8
  const removeCurrentFolderPathPrefix = (path) => {
6
9
  return path.replace(/^\.\//, '').trim();
@@ -10,7 +13,7 @@ const getExportList = (fileData, prefixPath = '') => {
10
13
  const exportList = [];
11
14
  const defaultExports = [];
12
15
  const pathPattern = /['|"|`](.+)['|"|`]/;
13
- const exportedComponentPattern = /default\s*as\s*(\w+).*['|"|`](.+)['|"|`]/;
16
+ const exportedComponentPattern = /(?<!:.*)export.*default\s*as\s*(\w+).*['|"|`](.+)['|"|`]/;
14
17
  const filterOutComments = fileData.replace(/\/\/+.*\s*/g, '');
15
18
  const filterOutNewlines = filterOutComments.replace(/\r?\n$/g, '');
16
19
  const dataList = filterOutNewlines.split(/\r?\n/);
@@ -65,10 +68,79 @@ const getPathToUse = (usePath) => {
65
68
  }
66
69
  }
67
70
 
68
- const customComponentsEnabled = () => {
69
- const customComponentsPath = `${ACTIVE_THEME_PATH}/customComponents`
71
+ const extractCustomComponentsZipToThemeRoot = async (themePath = ACTIVE_THEME_PATH) => {
72
+ const themeCustomComponentsPath = path.join(themePath, `/customComponents`);
73
+
74
+ const themeAssetsCustomComponentsZip = path.join(
75
+ themePath,
76
+ `/assets`,
77
+ "customComponents.zip"
78
+ );
79
+
80
+ try {
81
+ if (
82
+ fs.existsSync(themeAssetsCustomComponentsZip) &&
83
+ !fs.existsSync(themeCustomComponentsPath)
84
+ ) {
85
+ await extractZip(
86
+ themeAssetsCustomComponentsZip,
87
+ themeCustomComponentsPath
88
+ );
89
+ fs.removeSync(themeAssetsCustomComponentsZip);
90
+ }
91
+ } catch (err) {
92
+ console.error(
93
+ `ERROR: Unexpected error occurred while managing theme files due to ${err}`
94
+ );
95
+ process.exit(1);
96
+ }
97
+ };
98
+
99
+ const compressCustomComponentsToThemeAssets = async () => {
100
+ const themeCustomComponentsPath = path.join(
101
+ ACTIVE_THEME_PATH,
102
+ `/customComponents`
103
+ );
104
+
105
+ const themeAssetsCustomComponentsZip = path.join(
106
+ ACTIVE_THEME_PATH,
107
+ `/assets`,
108
+ "customComponents.zip"
109
+ );
110
+
111
+ try {
112
+ if (fs.existsSync(themeCustomComponentsPath)) {
113
+ await zipFolder(
114
+ themeCustomComponentsPath,
115
+ themeAssetsCustomComponentsZip
116
+ );
117
+ }
118
+ } catch (err) {
119
+ console.error(chalk.red(`ERROR preparing the zip due to ${err}`));
120
+ process.exit(1);
121
+ }
122
+ };
123
+
124
+ const removeCustomComponentsInThemeAssets = () => {
125
+ const themeAssetsCustomComponentsZip = path.join(
126
+ ACTIVE_THEME_PATH,
127
+ `/assets`,
128
+ "customComponents.zip"
129
+ );
130
+
131
+ try {
132
+ if (fs.existsSync(themeAssetsCustomComponentsZip)) {
133
+ fs.removeSync(themeAssetsCustomComponentsZip);
134
+ }
135
+ } catch (err) { }
136
+ };
137
+
138
+ const customComponentsEnabled = async () => {
139
+ await extractCustomComponentsZipToThemeRoot();
140
+
141
+ const customComponentsPath = `${ACTIVE_THEME_PATH}/customComponents`;
70
142
  return fs.existsSync(customComponentsPath);
71
- }
143
+ };
72
144
 
73
145
  const customComponentsExportsTraversal = (pathsToTraverse) => {
74
146
  let paths = [...pathsToTraverse];
@@ -85,7 +157,7 @@ const customComponentsExportsTraversal = (pathsToTraverse) => {
85
157
  const filterOutComments = fileData.replace(/\/\/+.*\s*/g, '');
86
158
 
87
159
  // check if file content is a component
88
- const component = filterOutComments.match(/export\s+default\s+(?:\w*\((\w+)\)|(\w+));?/);
160
+ const component = fileData.match(/(?<!\/\/\s*)export\s+default\s+(?:\w*\((\w+)\)|(\w+));?/);
89
161
 
90
162
  if(component) {
91
163
  foundComponent = component[1] || component[2];
@@ -248,7 +320,7 @@ const getSfbThemeComponentsVersion = () => {
248
320
  const hasPackageJson = fs.existsSync(`${ACTIVE_THEME_PATH}/package.json`);
249
321
  if (hasPackageJson) {
250
322
  const themePackageJson = JSON.parse(fs.readFileSync(`${ACTIVE_THEME_PATH}/package.json`));
251
- const sfbVersion = themePackageJson.dependencies['@appdirect/sfb-theme-components'];
323
+ const sfbVersion = themePackageJson.dependencies?.['@appdirect/sfb-theme-components'];
252
324
  const foundSfbVersion = sfbVersion && sfbVersion.match(/\d+\.\d+\.\d+/)[0];
253
325
  if(foundSfbVersion) {
254
326
  sfbThemeComponentsVersion = foundSfbVersion;
@@ -257,8 +329,55 @@ const getSfbThemeComponentsVersion = () => {
257
329
  return sfbThemeComponentsVersion;
258
330
  };
259
331
 
332
+ const getPathToFile = (path) => {
333
+ let fullPath = path;
334
+ const hasExtension = fullPath.match(/(.scss|.jsx?)/);
335
+ if(!hasExtension) {
336
+ const jsFile = `${fullPath}.js`;
337
+ const indexJsFile = `${fullPath}/index.js`;
338
+ const jsxFile = `${fullPath}.jsx`;
339
+ const scssFile = `${fullPath}.scss`;
340
+
341
+ if(fs.existsSync(jsFile)) {
342
+ fullPath = jsFile;
343
+ } else if(fs.existsSync(jsxFile)) {
344
+ fullPath = jsxFile;
345
+ } else if(fs.existsSync(scssFile)) {
346
+ fullPath = scssFile;
347
+ } else if(fs.existsSync(indexJsFile)) {
348
+ fullPath = indexJsFile;
349
+ } else {
350
+ const split = fullPath.split('/');
351
+ split[split.length - 1] = `_${split[split.length - 1]}.scss`;
352
+ const updatedPathToFile = split.join('/');
353
+ if(fs.existsSync(updatedPathToFile)) {
354
+ fullPath = updatedPathToFile;
355
+ }
356
+ }
357
+ }
358
+ return fullPath;
359
+ }
360
+
361
+ const constructPath = (currentPath, goToRelativePath) => {
362
+ const levelsToGoUp = (goToRelativePath && goToRelativePath.match(/\.\.\//g) || []).length + 1;
363
+ const currentPathDepthIndices = [];
364
+ for(let i=0; i < currentPath.length; i++) {
365
+ if (currentPath[i] === '/') {
366
+ currentPathDepthIndices.push(i);
367
+ }
368
+ }
369
+ const newCurrentPath = currentPath.slice(0, currentPathDepthIndices[currentPathDepthIndices.length - levelsToGoUp]);
370
+ const newGoToPath = goToRelativePath && goToRelativePath.replace(/\.+\//g, '');
371
+ return getPathToFile(`${newCurrentPath}/${newGoToPath}`);
372
+ }
373
+
260
374
  module.exports = {
261
375
  getCustomComponentsInfo,
262
376
  customComponentsEnabled,
263
- getSfbThemeComponentsVersion
377
+ getSfbThemeComponentsVersion,
378
+ getSfbThemeComponentsList,
379
+ removeCustomComponentsInThemeAssets,
380
+ extractCustomComponentsZipToThemeRoot,
381
+ compressCustomComponentsToThemeAssets,
382
+ constructPath
264
383
  }
@@ -1,21 +1,23 @@
1
1
  const chalk = require("chalk");
2
2
 
3
3
  const { shouldBeProjectFolder } = require("./toolkit-common-fun");
4
-
4
+ const { COMPONENTS_NOT_INSTALLED_ERROR } = require("./toolkit-components-vars");
5
5
  const { getCustomComponentsInfo, customComponentsEnabled } = require("./toolkit-components-fun");
6
6
 
7
7
  // check if user is in correct location
8
8
  shouldBeProjectFolder(true);
9
9
 
10
- (() => {
10
+ (async () => {
11
11
  try {
12
- if(customComponentsEnabled) {
12
+ const isCustomComponentsEnabled = await customComponentsEnabled();
13
+
14
+ if(isCustomComponentsEnabled) {
13
15
  const { overridesJavaScript, overridesSass, userDefinedCustomComponents } = getCustomComponentsInfo();
14
16
  console.log('Overrides Components JS:', overridesJavaScript);
15
17
  console.log('Overrides Components SCSS:', overridesSass);
16
18
  console.log('User Defined Components/Atoms:', userDefinedCustomComponents);
17
19
  } else {
18
- console.log('Custom components are not enabled for this theme.');
20
+ console.log(COMPONENTS_NOT_INSTALLED_ERROR);
19
21
  }
20
22
 
21
23
  } catch ( err ) {
@@ -0,0 +1,50 @@
1
+
2
+ const { ACTIVE_THEME_PATH } = require("./toolkit-common-vars");
3
+ const chalk = require("chalk");
4
+
5
+ const COPIED = 'COPIED';
6
+ const NO_MATCH = 'NO_MATCH';
7
+ const SUCCESS = 'SUCCESS';
8
+ const FOUND = 'FOUND';
9
+ const ERROR = 'ERROR';
10
+ const SKIP = 'SKIP';
11
+ const DELETED = 'DELETED';
12
+ const INVALID_VERSION = 'INVALID_VERSION';
13
+ const INDEX_EXPORT_NO_CHANGE = 'skipComponentExport';
14
+ const INDEX_EXPORT_COMMENT_OUT = 'commentOutExistingExports';
15
+ const INDEX_EXPORT_REPLACE = 'replaceExistingExports';
16
+ const INVALID_COMPONENT_NAME = 'INVALID_COMPONENT_NAME';
17
+ const MISSING_COMPONENT_NAME = 'MISSING_COMPONENT_NAME';
18
+ const FEATURE_AVAILABLE_SINCE_TOOLKIT_VERSION = '4.0.22';
19
+ const FEATURE_AVAILABLE_SINCE_SFB_THEME_VERSION = '0.0.352';
20
+ const BLACKLISTED_COMPONENTS = ["PageOrderableContainer"];
21
+ const PATH_TO_CUSTOM_COMPONENTS_INDEX = `${ACTIVE_THEME_PATH}/customComponents/index.js`;
22
+ const BASE_PATH_TO_COMPONENTS_INDEX = `${ACTIVE_THEME_PATH}/node_modules/@appdirect/sfb-theme-components/src/components/index.js`;
23
+ const COMPONENTS_DELETE_FLAG_SHORT = '-d';
24
+ const COMPONENTS_DELETE_FLAG_FULL = '--delete';
25
+ const COMPONENTS_NOT_INSTALLED_ERROR = chalk.red('ERROR: Custom components are not enabled for this theme.'
26
+ +`\nTo install custom components please execute the following command: ${chalk.green('sfb-toolkit components')}`);
27
+
28
+ module.exports = {
29
+ COPIED,
30
+ NO_MATCH,
31
+ SUCCESS,
32
+ FOUND,
33
+ ERROR,
34
+ SKIP,
35
+ DELETED,
36
+ INVALID_VERSION,
37
+ INDEX_EXPORT_NO_CHANGE,
38
+ INDEX_EXPORT_COMMENT_OUT,
39
+ INDEX_EXPORT_REPLACE,
40
+ INVALID_COMPONENT_NAME,
41
+ MISSING_COMPONENT_NAME,
42
+ FEATURE_AVAILABLE_SINCE_TOOLKIT_VERSION,
43
+ FEATURE_AVAILABLE_SINCE_SFB_THEME_VERSION,
44
+ BLACKLISTED_COMPONENTS,
45
+ PATH_TO_CUSTOM_COMPONENTS_INDEX,
46
+ BASE_PATH_TO_COMPONENTS_INDEX,
47
+ COMPONENTS_DELETE_FLAG_SHORT,
48
+ COMPONENTS_DELETE_FLAG_FULL,
49
+ COMPONENTS_NOT_INSTALLED_ERROR
50
+ }
@@ -21,7 +21,7 @@ const settingsSchemaData = `{ "useComponents": true }`;
21
21
  (async () => {
22
22
  const baseFilePath = `${ACTIVE_THEME_PATH}/content/layout/base.html`;
23
23
  const customComponentsPath = `${ACTIVE_THEME_PATH}/customComponents`
24
- const areCustomComponentsEnabled = customComponentsEnabled();
24
+ const areCustomComponentsEnabled = await customComponentsEnabled();
25
25
 
26
26
  if(!areCustomComponentsEnabled) {
27
27
  const customComponents = await prompt.ask(["InstallCustomComponents"]);
@@ -40,7 +40,7 @@ shouldBeProjectFolder(true);
40
40
  }
41
41
 
42
42
  // Remove all special characters from the extension name
43
- ExtensionName = ExtensionName.replace(/[^a-zA-Z0-9 -]/g, "").replace(
43
+ ExtensionName = ExtensionName.replace(/[^a-zA-Z0-9 _-]/g, "").replace(
44
44
  /[- ]/g,
45
45
  "_"
46
46
  );
@@ -4,8 +4,7 @@ const { spawn } = require("child_process");
4
4
  const prompt = require("./prompt-questions");
5
5
  const chalk = require("chalk");
6
6
 
7
- const { CURRENT_PATH, TOOLKIT_PATH, COMMAND_PARAM, COMPILERCSS_PATH,
8
- PAGE_OBJECTS_SUFFIX, ACTIVE_THEME_PATH } = require("./toolkit-common-vars");
7
+ const { CURRENT_PATH, TOOLKIT_PATH, COMMAND_PARAM, COMPILERCSS_PATH, PAGE_OBJECTS_SUFFIX } = require("./toolkit-common-vars");
9
8
  const { shouldBeProjectFolder, getAvailableFolderWithPrompt, createCustomThemePacakgeJson, addMetadata } = require("./toolkit-common-fun");
10
9
  const { LOCAL_CONFIG } = require("./toolkit-config");
11
10
 
@@ -106,7 +105,7 @@ shouldBeProjectFolder(true);
106
105
 
107
106
  try {
108
107
  const toolkitPackageJson = JSON.parse(fs.readFileSync(`${TOOLKIT_PATH}/package.json`));
109
- const themeVersion = toolkitPackageJson.dependencies[`${userThemeAnswer.ThemeTemplates.dependency}`];
108
+ const themeVersion = toolkitPackageJson.dependencies?.[`${userThemeAnswer.ThemeTemplates.dependency}`];
110
109
  addMetadata({
111
110
  themeTemplate: userThemeAnswer.ThemeTemplates.dependency,
112
111
  themeVersion,