@ixon-cdk/core 1.0.0-alpha.6 → 1.0.0-rc.0

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.
@@ -1,30 +1,31 @@
1
- const fs = require("fs");
2
- const axios = require("axios");
3
- const ApiBaseService = require("./base.service");
1
+ const fs = require('fs');
2
+ const ApiBaseService = require('./base.service');
3
+ const httpRequest = require('../http-request');
4
4
 
5
5
  module.exports = class AuthService extends ApiBaseService {
6
6
  logIn(credentials) {
7
7
  const c = credentials;
8
- return axios.post(
9
- `${this._getApiBaseUrl()}/access-tokens`,
10
- { expiresIn: 86400 },
11
- {
12
- headers: {
13
- ...this._getApiDefaultHeaders(),
14
- "User-Agent": "ComponentDevKit",
15
- Authorization: `Basic ${Buffer.from(
16
- c.email + ":" + (c.otp || "") + ":" + c.password,
17
- "utf-8"
18
- ).toString("base64")}`,
19
- },
20
- }
21
- );
8
+ return httpRequest({
9
+ method: 'POST',
10
+ url: `${this._getApiBaseUrl()}/access-tokens`,
11
+ data: { expiresIn: 86400 },
12
+ headers: {
13
+ ...this._getApiDefaultHeaders(),
14
+ 'User-Agent': 'ComponentDevKit',
15
+ Authorization: `Basic ${Buffer.from(
16
+ `${c.email}:${c.otp || ''}:${c.password}`,
17
+ 'utf-8',
18
+ ).toString('base64')}`,
19
+ },
20
+ });
22
21
  }
23
22
 
24
23
  logOut() {
25
24
  const secretId = this._getSecretId();
26
25
  if (secretId) {
27
- return axios.delete(`${this._getApiBaseUrl()}/access-tokens/me`, {
26
+ return httpRequest({
27
+ method: 'DELETE',
28
+ url: `${this._getApiBaseUrl()}/access-tokens/me`,
28
29
  headers: {
29
30
  ...this._getApiDefaultHeaders(),
30
31
  Authorization: this._getApiAuthHeaderValue(),
@@ -40,8 +41,8 @@ module.exports = class AuthService extends ApiBaseService {
40
41
 
41
42
  remember(secretId) {
42
43
  fs.writeFileSync(this._getAccessTokenFilePath(), secretId, {
43
- encoding: "utf8",
44
- flag: "w",
44
+ encoding: 'utf8',
45
+ flag: 'w',
45
46
  });
46
47
  }
47
48
 
@@ -1,12 +1,12 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const ConfigService = require("../config/config.service");
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const ConfigService = require('../config/config.service');
4
4
 
5
5
  module.exports = class ApiBaseService {
6
6
  _configSrv = new ConfigService();
7
7
 
8
8
  _getAccessTokenFilePath() {
9
- return path.join(require("../utils").getRootDir(), ".accesstoken");
9
+ return path.join(require('../utils').getRootDir(), '.accesstoken');
10
10
  }
11
11
 
12
12
  _getApiAuthHeaderValue() {
@@ -19,9 +19,9 @@ module.exports = class ApiBaseService {
19
19
 
20
20
  _getApiDefaultHeaders() {
21
21
  return {
22
- "Content-Type": "application/json",
23
- "Api-Application": this._configSrv.getApiApplication(),
24
- "Api-Version": this._configSrv.getApiVersion(),
22
+ 'Content-Type': 'application/json',
23
+ 'Api-Application': this._configSrv.getApiApplication(),
24
+ 'Api-Version': this._configSrv.getApiVersion(),
25
25
  };
26
26
  }
27
27
 
@@ -29,7 +29,7 @@ module.exports = class ApiBaseService {
29
29
  let secretId;
30
30
  try {
31
31
  secretId = fs.readFileSync(this._getAccessTokenFilePath(), {
32
- encoding: "utf-8",
32
+ encoding: 'utf-8',
33
33
  });
34
34
  } catch {
35
35
  // do nothing
@@ -1,38 +1,32 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const axios = require("axios");
4
- const ApiBaseService = require("./base.service");
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const ApiBaseService = require('./base.service');
4
+ const httpRequest = require('../http-request');
5
5
 
6
6
  module.exports = class DeployService extends ApiBaseService {
7
7
  deploy(companyId, templateId, file) {
8
8
  const url = `${this._getApiBaseUrl()}/page-component-templates/${templateId}/version-upload`;
9
- const body = fs.readFileSync(
10
- path.join(require("../utils").getRootDir(), file)
11
- );
9
+ const body = fs.readFileSync(path.join(require('../utils').getRootDir(), file));
12
10
  const headers = {
13
11
  ...this._getApiDefaultHeaders(),
14
- "Content-Type": "application/x-www-form-urlencoded",
15
- "Api-Company": companyId,
12
+ 'Content-Type': 'application/x-www-form-urlencoded',
13
+ 'Api-Company': companyId,
16
14
  Authorization: this._getApiAuthHeaderValue(),
17
15
  };
18
- return axios.post(url, body, { headers }).then((res) => res.data.data);
16
+ return httpRequest({ method: 'POST', url, data: body, headers }).then((res) => res.data.data);
19
17
  }
20
18
 
21
19
  deployAndPublish(companyId, templateId, file) {
22
20
  return this.deploy(companyId, templateId, file).then((data) =>
23
- this._publish(companyId, data.publicId)
21
+ this._publish(companyId, data.publicId),
24
22
  );
25
23
  }
26
24
 
27
25
  fetchPublishable(companyId, templateId) {
28
- return this._fetchDescTemplateVersions(companyId, templateId).then(
29
- (versions) => {
30
- const publishedIdx = versions.findIndex(
31
- (v) => typeof v.publishedOn === "string"
32
- );
33
- return publishedIdx !== -1 ? versions.slice(0, publishedIdx) : versions;
34
- }
35
- );
26
+ return this._fetchDescTemplateVersions(companyId, templateId).then((versions) => {
27
+ const publishedIdx = versions.findIndex((v) => typeof v.publishedOn === 'string');
28
+ return publishedIdx !== -1 ? versions.slice(0, publishedIdx) : versions;
29
+ });
36
30
  }
37
31
 
38
32
  generatePreviewLink(companyId, versionId) {
@@ -40,32 +34,32 @@ module.exports = class DeployService extends ApiBaseService {
40
34
  this._fetchBrandingFqdn(companyId),
41
35
  this._fetchTemplateVersion(companyId, versionId),
42
36
  ])
43
- .then(([fqdn, version]) => {
44
- return this._fetchTemplate(companyId, version.template.publicId).then(
45
- (template) => [fqdn, version, template]
46
- );
47
- })
37
+ .then(([fqdn, version]) =>
38
+ this._fetchTemplate(companyId, version.template.publicId).then((template) => [
39
+ fqdn,
40
+ version,
41
+ template,
42
+ ]),
43
+ )
48
44
  .then(([fqdn, version, template]) => {
49
- const hash = require("../utils").generatePreviewHash(
45
+ const hash = require('../utils').generatePreviewHash(
50
46
  template.publicId,
51
47
  template.name,
52
48
  version.publicId,
53
49
  version.number,
54
- version.mainPath
50
+ version.mainPath,
55
51
  );
56
52
  const search = `?pctpvw=${encodeURIComponent(hash)}`;
57
- return `https://${fqdn || "[YOUR-PLATFORM-DOMAIN]"}/portal/${search}`;
53
+ return `https://${fqdn || '[YOUR-PLATFORM-DOMAIN]'}/portal/${search}`;
58
54
  });
59
55
  }
60
56
 
61
57
  publishLatestVersion(companyId, templateId) {
62
58
  return this.fetchPublishable(companyId, templateId).then((data) => {
63
59
  if (!data.length) {
64
- return Promise.reject("Template has no publishable versions");
60
+ return Promise.reject('Template has no publishable versions');
65
61
  }
66
- const latest = data.sort(
67
- (v1, v2) => Number(v2.number) - Number(v1.number)
68
- )[0];
62
+ const latest = data.sort((v1, v2) => Number(v2.number) - Number(v1.number))[0];
69
63
  return this._publish(companyId, latest.publicId);
70
64
  });
71
65
  }
@@ -73,26 +67,26 @@ module.exports = class DeployService extends ApiBaseService {
73
67
  publishVersion(companyId, templateId, versionNumber) {
74
68
  return this.fetchPublishable(companyId, templateId).then((data) => {
75
69
  if (!data.length) {
76
- return Promise.reject("Template has no publishable versions");
70
+ return Promise.reject('Template has no publishable versions');
77
71
  }
78
72
  const _version = data.find((v) => v.number === String(versionNumber));
79
- if (!!_version) {
73
+ if (_version) {
80
74
  return this._publish(companyId, _version.publicId);
81
75
  }
82
- return Promise.reject("Could not match!");
76
+ return Promise.reject('Could not match!');
83
77
  });
84
78
  }
85
79
 
86
80
  _fetchBrandingFqdn(companyId) {
87
81
  const url = `${this._getApiBaseUrl()}/companies/me`;
88
- const params = { fields: "branding(fqdn)" };
82
+ const params = { fields: 'branding(fqdn)' };
89
83
  const headers = {
90
84
  ...this._getApiDefaultHeaders(),
91
- "Api-Company": companyId,
85
+ 'Api-Company': companyId,
92
86
  Authorization: this._getApiAuthHeaderValue(),
93
87
  };
94
88
  // Lookup company FQDN (premium branding)
95
- return axios.get(url, { params, headers }).then((res) => {
89
+ return httpRequest({ method: 'GET', url, params, headers }).then((res) => {
96
90
  const myCompany = res.data.data;
97
91
  if (myCompany.branding && myCompany.branding.fqdn) {
98
92
  return myCompany.branding.fqdn;
@@ -100,7 +94,7 @@ module.exports = class DeployService extends ApiBaseService {
100
94
  // Or fallback to sector FQDN
101
95
  const _url = `${this._getApiBaseUrl()}/sectors/me`;
102
96
  const _headers = { ...this._getApiDefaultHeaders() };
103
- return axios.get(_url, { params, headers: _headers }).then((res) => {
97
+ return httpRequest({ method: 'GET', url: _url, params, headers: _headers }).then((res) => {
104
98
  const mySector = res.data.data;
105
99
  if (mySector.branding && mySector.branding.fqdn) {
106
100
  return mySector.branding.fqdn;
@@ -113,42 +107,40 @@ module.exports = class DeployService extends ApiBaseService {
113
107
  _fetchDescTemplateVersions(companyId, templateId) {
114
108
  const url = `${this._getApiBaseUrl()}/page-component-template-versions`;
115
109
  const params = {
116
- fields: "*,template(*)",
110
+ fields: '*,template(*)',
117
111
  filters: `eq(template.publicId,"${templateId}")`,
118
- "page-size": "100",
112
+ 'page-size': '100',
119
113
  };
120
114
  const headers = {
121
115
  ...this._getApiDefaultHeaders(),
122
- "Api-Company": companyId,
116
+ 'Api-Company': companyId,
123
117
  Authorization: this._getApiAuthHeaderValue(),
124
118
  };
125
- return axios.get(url, { params, headers }).then((res) => {
126
- return res.data.data.sort(
127
- (v1, v2) => Number(v2.number) - Number(v1.number)
128
- );
129
- });
119
+ return httpRequest({ method: 'GET', url, params, headers }).then((res) =>
120
+ res.data.data.sort((v1, v2) => Number(v2.number) - Number(v1.number)),
121
+ );
130
122
  }
131
123
 
132
124
  _fetchTemplate(companyId, templateId) {
133
125
  const url = `${this._getApiBaseUrl()}/page-component-templates/${templateId}`;
134
- const params = { fields: "*" };
126
+ const params = { fields: '*' };
135
127
  const headers = {
136
128
  ...this._getApiDefaultHeaders(),
137
- "Api-Company": companyId,
129
+ 'Api-Company': companyId,
138
130
  Authorization: this._getApiAuthHeaderValue(),
139
131
  };
140
- return axios.get(url, { params, headers }).then((res) => res.data.data);
132
+ return httpRequest({ method: 'GET', url, params, headers }).then((res) => res.data.data);
141
133
  }
142
134
 
143
135
  _fetchTemplateVersion(companyId, versionId) {
144
136
  const url = `${this._getApiBaseUrl()}/page-component-template-versions/${versionId}`;
145
- const params = { fields: "*,template(*)" };
137
+ const params = { fields: '*,template(*)' };
146
138
  const headers = {
147
139
  ...this._getApiDefaultHeaders(),
148
- "Api-Company": companyId,
140
+ 'Api-Company': companyId,
149
141
  Authorization: this._getApiAuthHeaderValue(),
150
142
  };
151
- return axios.get(url, { params, headers }).then((res) => res.data.data);
143
+ return httpRequest({ method: 'GET', url, params, headers }).then((res) => res.data.data);
152
144
  }
153
145
 
154
146
  _publish(companyId, versionId) {
@@ -156,9 +148,9 @@ module.exports = class DeployService extends ApiBaseService {
156
148
  const body = { published: true };
157
149
  const headers = {
158
150
  ...this._getApiDefaultHeaders(),
159
- "Api-Company": companyId,
151
+ 'Api-Company': companyId,
160
152
  Authorization: this._getApiAuthHeaderValue(),
161
153
  };
162
- return axios.patch(url, body, { headers });
154
+ return httpRequest({ method: 'PATCH', url, data: body, headers });
163
155
  }
164
156
  };
@@ -1,25 +1,25 @@
1
- const fs = require("fs");
2
- const { merge } = require("lodash");
3
- const path = require("path");
4
- const { getRootDir, logFileCrudMessage, logErrorMessage } = require("../utils");
1
+ const fs = require('fs');
2
+ const { merge } = require('lodash');
3
+ const path = require('path');
4
+ const { getRootDir, logFileCrudMessage, logErrorMessage } = require('../utils');
5
5
 
6
6
  module.exports = class ConfigService {
7
7
  _config = { components: {} };
8
8
 
9
- _path = path.join(getRootDir(), "config.json");
9
+ _path = path.join(getRootDir(), 'config.json');
10
10
 
11
11
  constructor() {
12
12
  let config;
13
13
 
14
14
  if (!fs.existsSync(this._path)) {
15
- logErrorMessage(`No config file.`);
15
+ logErrorMessage('No config file.');
16
16
  process.exit();
17
17
  }
18
18
 
19
19
  try {
20
20
  config = require(this._path);
21
21
  } catch {
22
- logErrorMessage(`Couldn't parse config file.`);
22
+ logErrorMessage('Couldn\'t parse config file.');
23
23
  process.exit();
24
24
  }
25
25
 
@@ -35,7 +35,7 @@ module.exports = class ConfigService {
35
35
  }
36
36
 
37
37
  getNewComponentRoot() {
38
- return this._config.newComponentRoot || "components";
38
+ return this._config.newComponentRoot || 'components';
39
39
  }
40
40
 
41
41
  getPrefix() {
@@ -43,15 +43,15 @@ module.exports = class ConfigService {
43
43
  }
44
44
 
45
45
  getApiApplication() {
46
- return this._config.apiApplication || "LtDdZKEPa5lK";
46
+ return this._config.apiApplication || 'LtDdZKEPa5lK';
47
47
  }
48
48
 
49
49
  getApiBaseUrl() {
50
- return this._config.apiBaseUrl || "https://api.ayayot.com";
50
+ return this._config.apiBaseUrl || 'https://api.ayayot.com';
51
51
  }
52
52
 
53
53
  getApiVersion() {
54
- return this._config.apiVersion || "2";
54
+ return this._config.apiVersion || '2';
55
55
  }
56
56
 
57
57
  addComponent(name, config) {
@@ -63,16 +63,16 @@ module.exports = class ConfigService {
63
63
  this._config.components[name] = merge(
64
64
  {},
65
65
  this._config.components[name],
66
- config
66
+ config,
67
67
  );
68
68
  this._sync();
69
69
  }
70
70
 
71
71
  _sync() {
72
- fs.writeFileSync(this._path, JSON.stringify(this._config, null, 2) + "\n", {
73
- encoding: "utf8",
74
- flag: "w",
72
+ fs.writeFileSync(this._path, `${JSON.stringify(this._config, null, 2)}\n`, {
73
+ encoding: 'utf8',
74
+ flag: 'w',
75
75
  });
76
- logFileCrudMessage("UPDATE", "config.json");
76
+ logFileCrudMessage('UPDATE', 'config.json');
77
77
  }
78
78
  };
@@ -0,0 +1,28 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const axios = require('axios');
4
+ const { getRootDir, logErrorMessage } = require('./utils');
5
+
6
+ module.exports = function request(options) {
7
+ const customPath = path.join(getRootDir(), 'http-request.js');
8
+
9
+ if (fs.existsSync(customPath)) {
10
+ const customRequest = require(customPath);
11
+
12
+ if (typeof customRequest !== 'function') {
13
+ logErrorMessage('The custom "http-request.js" file must export a function.');
14
+ process.exit();
15
+ }
16
+
17
+ const promise = customRequest(options);
18
+
19
+ if (typeof promise !== 'object' || typeof promise.then !== 'function') {
20
+ logErrorMessage('The exported function in the custom "http-request.js" file must return a Promise.');
21
+ process.exit();
22
+ }
23
+
24
+ return promise;
25
+ }
26
+
27
+ return axios.request(options);
28
+ };
package/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  module.exports = {
2
- AuthService: require("./api/auth.service"),
3
- DeployService: require("./api/deploy.service"),
4
- ConfigService: require("./config/config.service"),
5
- Server: require("./server"),
6
- TemplateService: require("./template/template.service"),
7
- ...require("./meta-files"),
8
- ...require("./prompts"),
9
- ...require("./utils"),
2
+ AuthService: require('./api/auth.service'),
3
+ DeployService: require('./api/deploy.service'),
4
+ ConfigService: require('./config/config.service'),
5
+ Server: require('./server'),
6
+ TemplateService: require('./template/template.service'),
7
+ ...require('./meta-files'),
8
+ ...require('./prompts'),
9
+ ...require('./utils'),
10
10
  };
package/meta-files.js CHANGED
@@ -1,10 +1,14 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const { debounce, uniq } = require("lodash");
4
- const rimraf = require("rimraf");
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { debounce, uniq } = require('lodash');
4
+ const rimraf = require('rimraf');
5
5
 
6
- const ICON_FILE_NAME = "icon.svg";
7
- const MANIFEST_FILE_NAME = "manifest.json";
6
+ const ICON_FILE_NAME = 'icon.svg';
7
+ const MANIFEST_FILE_NAME = 'manifest.json';
8
+ const WATCH_OPTIONS = {
9
+ cwd: require('./utils').getRootDir(),
10
+ usePolling: process.platform !== 'darwin',
11
+ };
8
12
 
9
13
  module.exports = {
10
14
  cleanDir(dir) {
@@ -14,11 +18,11 @@ module.exports = {
14
18
  fs.mkdirSync(dir, { recursive: true });
15
19
  },
16
20
  copyAssets(assets, inputDir, outputDir) {
17
- const paths = uniq([MANIFEST_FILE_NAME, ICON_FILE_NAME, ...assets]).map(
18
- (asset) => path.join(inputDir, asset)
21
+ const paths = uniq([MANIFEST_FILE_NAME, ICON_FILE_NAME, ...assets]).map((asset) =>
22
+ path.join(inputDir, asset),
19
23
  );
20
24
  paths.forEach((_path) => {
21
- require("glob")
25
+ require('glob')
22
26
  .sync(_path)
23
27
  .forEach((file) => {
24
28
  const fileName = file.slice(inputDir.length + 1);
@@ -27,34 +31,36 @@ module.exports = {
27
31
  });
28
32
  },
29
33
  watchAssets(assets, inputDir, outputDir) {
30
- const root = require("./utils").getRootDir();
31
- return require("chokidar")
34
+ const root = require('./utils').getRootDir();
35
+ return require('chokidar')
32
36
  .watch(
33
37
  uniq([MANIFEST_FILE_NAME, ICON_FILE_NAME, ...assets]).map((asset) =>
34
- path.join(inputDir, asset)
38
+ path.join(inputDir, asset),
35
39
  ),
36
- { cwd: require("./utils").getRootDir(), ignoreInitial: true }
40
+ WATCH_OPTIONS,
37
41
  )
38
- .on("all", (type, file) => {
42
+ .on('all', (type, file) => {
39
43
  const fileName = path.join(root, file).slice(inputDir.length + 1);
40
44
  switch (type) {
41
- case "add":
42
- case "change":
45
+ case 'add':
46
+ case 'change':
43
47
  _copyFileNameFromToSync(fileName, inputDir, outputDir);
44
48
  break;
45
- case "unlink":
49
+ case 'unlink':
46
50
  if (fs.existsSync(path.join(outputDir, fileName))) {
47
51
  rimraf.sync(path.join(outputDir, fileName));
48
52
  }
49
53
  break;
54
+ default:
55
+ break;
50
56
  }
51
57
  });
52
58
  },
53
- watchInputDir: function (dir, watchCallback) {
59
+ watchInputDir(dir, watchCallback) {
54
60
  const _debouncedCallback = debounce(() => watchCallback(), 300);
55
- require("chokidar")
56
- .watch([`${dir}/**`], { ignoreInitial: true })
57
- .on("all", (_, _path) => {
61
+ require('chokidar')
62
+ .watch([`${dir}/**`], WATCH_OPTIONS)
63
+ .on('all', (_, _path) => {
58
64
  if (
59
65
  _path.endsWith(path.join(dir, MANIFEST_FILE_NAME)) ||
60
66
  _path.endsWith(path.join(dir, ICON_FILE_NAME))
@@ -67,11 +73,11 @@ module.exports = {
67
73
  },
68
74
  writeDemoFile: function writeDemoFile(tag, outputDir, outputFile) {
69
75
  const demoFileContent = `<meta charset="utf-8">\n<title>${tag} demo</title>\n<script src="./${path.basename(
70
- outputFile
76
+ outputFile,
71
77
  )}"></script>\n\n\n<${tag}></${tag}>\n\n`;
72
78
  fs.writeFileSync(`${outputDir}/demo.html`, demoFileContent, {
73
- encoding: "utf8",
74
- flag: "w",
79
+ encoding: 'utf8',
80
+ flag: 'w',
75
81
  });
76
82
  },
77
83
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ixon-cdk/core",
3
- "version": "1.0.0-alpha.6",
3
+ "version": "1.0.0-rc.0",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "author": "",
@@ -12,7 +12,6 @@
12
12
  "chalk": "^4.1.2",
13
13
  "chokidar": "^3.5.2",
14
14
  "crypto-js": "^4.1.1",
15
- "debounce": "^1.2.1",
16
15
  "express": "^4.17.1",
17
16
  "glob": "^7.2.0",
18
17
  "livereload": "^0.9.3",
package/prompts.js CHANGED
@@ -1,31 +1,31 @@
1
1
  module.exports = {
2
- promptCompanyId: function(name) {
2
+ promptCompanyId(name) {
3
3
  return {
4
- type: "text",
4
+ type: 'text',
5
5
  name,
6
- message: "What is the ID of your Company?",
6
+ message: 'What is the ID of your Company?',
7
7
  validate: (value) => {
8
8
  if (!value) {
9
- return "Company ID is required.";
9
+ return 'Company ID is required.';
10
10
  }
11
11
  if (!/^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$/.test(value)) {
12
- return "Invalid company ID.";
12
+ return 'Invalid company ID.';
13
13
  }
14
14
  return true;
15
15
  },
16
16
  };
17
17
  },
18
- promptPageComponentTemplateId: function(name) {
18
+ promptPageComponentTemplateId(name) {
19
19
  return {
20
- type: "text",
20
+ type: 'text',
21
21
  name,
22
- message: "What is the ID of the PageComponentTemplate?",
22
+ message: 'What is the ID of the PageComponentTemplate?',
23
23
  validate: (value) => {
24
24
  if (!value) {
25
- return "Template ID is required.";
25
+ return 'Template ID is required.';
26
26
  }
27
27
  if (!/^[a-zA-Z0-9]{12}$/.test(value)) {
28
- return "Invalid template ID.";
28
+ return 'Invalid template ID.';
29
29
  }
30
30
  return true;
31
31
  },
package/server/index.js CHANGED
@@ -1,31 +1,33 @@
1
- const path = require("path");
2
- const express = require("express");
3
- const ConfigService = require("../config/config.service");
1
+ const path = require('path');
2
+ const express = require('express');
3
+ const ConfigService = require('../config/config.service');
4
4
 
5
5
  module.exports = class Server {
6
6
  constructor(opts) {
7
7
  this._configSrv = new ConfigService();
8
- this._opts = Object.assign(
9
- { port: 8000, componentBasePath: "components" },
10
- opts
11
- );
8
+ this._rootDir = require('../utils').getRootDir();
9
+ this._opts = {
10
+ port: 8000,
11
+ componentBasePath: 'components',
12
+ ...opts,
13
+ };
12
14
  }
13
15
 
14
16
  serve(names) {
15
17
  const app = express();
16
18
 
17
19
  // Cache
18
- app.use(function (_, res, next) {
19
- res.header("Cache-Control", "no-store");
20
+ app.use((_, res, next) => {
21
+ res.header('Cache-Control', 'no-store');
20
22
  next();
21
23
  });
22
24
 
23
25
  // CORS
24
- app.use(function (_, res, next) {
25
- res.header("Access-Control-Allow-Origin", "*");
26
+ app.use((_, res, next) => {
27
+ res.header('Access-Control-Allow-Origin', '*');
26
28
  res.header(
27
- "Access-Control-Allow-Headers",
28
- "Origin, X-Requested-With, Content-Type, Accept"
29
+ 'Access-Control-Allow-Headers',
30
+ 'Origin, X-Requested-With, Content-Type, Accept',
29
31
  );
30
32
  next();
31
33
  });
@@ -35,36 +37,32 @@ module.exports = class Server {
35
37
  names.forEach((name) => {
36
38
  const outputDir = this._getOutputDir(name);
37
39
  if (outputDir) {
38
- const dir = path.resolve(require("../utils").getRootDir(), outputDir);
40
+ const dir = path.resolve(this._rootDir, outputDir);
39
41
  app.use(
40
42
  `/${this._opts.componentBasePath}/${name}`,
41
- express.static(dir)
43
+ express.static(dir),
42
44
  );
43
45
  }
44
46
  });
45
47
  }
46
48
 
47
49
  // Adds live reload watchers
48
- const lrServer = require("livereload").createServer();
49
- const watchHandler = () => lrServer.refresh("/");
50
- const outputs = names.flatMap((name) => [
51
- this._getOutput(name),
52
- `dist/${name}/manifest.json`,
53
- ]);
54
-
55
- const watcher = require("chokidar").watch(outputs, { ignoreInitial: true });
56
- watcher.on("change", require("debounce")(watchHandler, 500));
57
- process.on("exit", () => {
58
- lrServer.close();
59
- watcher.close();
60
- });
50
+ const lrServer = require('livereload').createServer();
51
+ const _refresh = () => lrServer.refresh('/');
52
+ const _debouncedRefresh = require('lodash/debounce')(_refresh, 250);
53
+ names
54
+ .flatMap((name) => [
55
+ [path.join(this._rootDir, this._getOutput(name)), 100],
56
+ [path.join(this._rootDir, `dist/${name}/manifest.json`), 500],
57
+ ])
58
+ .forEach(([filename, interval]) => require('fs').watchFile(filename, { interval }, _debouncedRefresh));
61
59
 
62
60
  // Simulator app
63
- const appDir = path.dirname(require.resolve("@ixon-cdk/simulator"));
64
- app.get(`/${this._opts.componentBasePath}/*`, function (req, res) {
61
+ const appDir = path.dirname(require.resolve('@ixon-cdk/simulator'));
62
+ app.get(`/${this._opts.componentBasePath}/*`, (req, res) => {
65
63
  res.sendStatus(404);
66
64
  });
67
- app.get(`/config.json`, (req, res) => {
65
+ app.get('/config.json', (req, res) => {
68
66
  res.send({
69
67
  api: {
70
68
  appId: this._configSrv.getApiApplication(),
@@ -73,9 +71,9 @@ module.exports = class Server {
73
71
  },
74
72
  });
75
73
  });
76
- app.get("*.*", express.static(appDir));
77
- app.all("*", function (req, res) {
78
- res.status(200).sendFile(`/index.html`, { root: appDir });
74
+ app.get('*.*', express.static(appDir));
75
+ app.all('*', (req, res) => {
76
+ res.status(200).sendFile('/index.html', { root: appDir });
79
77
  });
80
78
 
81
79
  app.listen(this._opts.port);
@@ -83,8 +81,8 @@ module.exports = class Server {
83
81
 
84
82
  openSimulator(name = null) {
85
83
  const url = this._getComponentUrl(name);
86
- const queryString = url ? `?pct-url=${encodeURIComponent(url)}` : "";
87
- require("opener")(`${this._getBaseUrl()}/${queryString}`);
84
+ const queryString = url ? `?pct-url=${encodeURIComponent(url)}` : '';
85
+ require('opener')(`${this._getBaseUrl()}/${queryString}`);
88
86
  }
89
87
 
90
88
  _getBaseUrl() {
@@ -1,14 +1,14 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const prompts = require("prompts");
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const prompts = require('prompts');
4
4
 
5
5
  const {
6
6
  getRootDir,
7
7
  ensureModule,
8
8
  logFileCrudMessage,
9
9
  pascalCase,
10
- } = require("../utils");
11
- const ConfigService = require("../config/config.service");
10
+ } = require('../utils');
11
+ const ConfigService = require('../config/config.service');
12
12
 
13
13
  module.exports = class TemplateService {
14
14
  _configSrv = new ConfigService();
@@ -23,9 +23,9 @@ module.exports = class TemplateService {
23
23
  let schema;
24
24
 
25
25
  const result = await prompts({
26
- type: "select",
27
- name: "templateName",
28
- message: "Pick a template",
26
+ type: 'select',
27
+ name: 'templateName',
28
+ message: 'Pick a template',
29
29
  choices: Object.keys(this._schemas).map((key) => ({
30
30
  title: this._schemas[key].name,
31
31
  value: key,
@@ -47,9 +47,9 @@ module.exports = class TemplateService {
47
47
 
48
48
  if (schema.variants) {
49
49
  const _result = await prompts({
50
- type: "select",
51
- name: "variantIdx",
52
- message: "Pick a variant",
50
+ type: 'select',
51
+ name: 'variantIdx',
52
+ message: 'Pick a variant',
53
53
  choices: schema.variants.map((variant, index) => ({
54
54
  title: variant.name,
55
55
  value: index,
@@ -68,14 +68,14 @@ module.exports = class TemplateService {
68
68
  const modulesNames = Object.keys(schema.config.runner).reduce(
69
69
  (names, cmd) => {
70
70
  if (schema.config.runner[cmd].builder) {
71
- const name = schema.config.runner[cmd].builder.split(":")[0];
71
+ const name = schema.config.runner[cmd].builder.split(':')[0];
72
72
  if (!names.includes(name)) {
73
73
  return [...names, name];
74
74
  }
75
75
  }
76
76
  return names;
77
77
  },
78
- []
78
+ [],
79
79
  );
80
80
  modulesNames.forEach((name) => ensureModule(name));
81
81
  }
@@ -106,36 +106,36 @@ module.exports = class TemplateService {
106
106
  if (file.interpolateContent) {
107
107
  const text = fs.readFileSync(
108
108
  path.join(
109
- path.dirname(require.resolve("@ixon-cdk/templates")),
110
- file.source
109
+ path.dirname(require.resolve('@ixon-cdk/templates')),
110
+ file.source,
111
111
  ),
112
- { encoding: "utf-8" }
112
+ { encoding: 'utf-8' },
113
113
  );
114
114
  const data = this._interpolateText(text, ctx);
115
115
  fs.writeFileSync(path.join(rootDir, file.dest), data, {
116
- encoding: "utf-8",
116
+ encoding: 'utf-8',
117
117
  });
118
118
  } else {
119
119
  fs.copyFileSync(
120
120
  path.join(
121
- path.dirname(require.resolve("@ixon-cdk/templates")),
122
- file.source
121
+ path.dirname(require.resolve('@ixon-cdk/templates')),
122
+ file.source,
123
123
  ),
124
- path.join(rootDir, file.dest)
124
+ path.join(rootDir, file.dest),
125
125
  );
126
126
  }
127
- logFileCrudMessage("CREATE", file.dest);
127
+ logFileCrudMessage('CREATE', file.dest);
128
128
  }
129
129
 
130
130
  _discover() {
131
- const dir = path.dirname(require.resolve("@ixon-cdk/templates"));
131
+ const dir = path.dirname(require.resolve('@ixon-cdk/templates'));
132
132
  const files = fs.readdirSync(dir);
133
133
  files.forEach((file) => {
134
134
  if (fs.lstatSync(path.join(dir, file)).isDirectory()) {
135
- const schemaFile = path.join(dir, file, "schema.json");
135
+ const schemaFile = path.join(dir, file, 'schema.json');
136
136
  if (fs.existsSync(schemaFile)) {
137
137
  const schema = JSON.parse(fs.readFileSync(schemaFile));
138
- this._schemas = Object.assign({}, this._schemas, { [file]: schema });
138
+ this._schemas = { ...this._schemas, [file]: schema };
139
139
  }
140
140
  }
141
141
  });
package/utils.js CHANGED
@@ -1,20 +1,18 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const chalk = require("chalk");
4
- const flow = require("lodash/flow");
5
- const camelCase = require("lodash/camelCase");
6
- const upperFirst = require("lodash/upperFirst");
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const chalk = require('chalk');
4
+ const flow = require('lodash/flow');
5
+ const camelCase = require('lodash/camelCase');
6
+ const upperFirst = require('lodash/upperFirst');
7
7
 
8
8
  function getArgv() {
9
9
  const remain = process.argv.slice(2);
10
- const argv = require("yargs/yargs")(remain).argv;
10
+ const { argv } = require('yargs/yargs')(remain);
11
11
 
12
12
  // version argument fix
13
- if ("version" in argv) {
14
- const versionArg = remain.find((arg) =>
15
- /^--version=("[0-9]+"|'[0-9]+'|[0-9]+)$/.test(arg)
16
- );
17
- if (!!versionArg) {
13
+ if ('version' in argv) {
14
+ const versionArg = remain.find((arg) => /^--version=("[0-9]+"|'[0-9]+'|[0-9]+)$/.test(arg));
15
+ if (versionArg) {
18
16
  const matches = versionArg.match(/^--version=['"]?([0-9]+)['"]?$/);
19
17
  argv.version = Number(matches[1]);
20
18
  }
@@ -24,7 +22,7 @@ function getArgv() {
24
22
  }
25
23
 
26
24
  function getRootDir() {
27
- return require("app-root-dir").get();
25
+ return require('app-root-dir').get();
28
26
  }
29
27
 
30
28
  function logErrorMessage(message) {
@@ -33,10 +31,12 @@ function logErrorMessage(message) {
33
31
 
34
32
  function logFileCrudMessage(crud, file) {
35
33
  switch (crud) {
36
- case "CREATE":
37
- case "UPDATE":
34
+ case 'CREATE':
35
+ case 'UPDATE':
38
36
  console.log(`${chalk.green(crud)} ${file}`);
39
37
  break;
38
+ default:
39
+ break;
40
40
  }
41
41
  }
42
42
 
@@ -55,24 +55,25 @@ function moduleExists(moduleName) {
55
55
  }
56
56
 
57
57
  function ensureModule(moduleName) {
58
- if (!moduleName.startsWith("@ixon-cdk/")) {
59
- return logErrorMessage("Cannot install this module.");
58
+ if (!moduleName.startsWith('@ixon-cdk/')) {
59
+ logErrorMessage('Cannot install this module.');
60
+ return;
60
61
  }
61
62
  if (!moduleExists(moduleName)) {
62
63
  console.log(`Installing package '${moduleName}'...`);
63
- require("child_process").execSync(`npm install --save-dev ${moduleName}`);
64
+ require('child_process').execSync(`npm install --save-dev ${moduleName}`);
64
65
  }
65
66
  }
66
67
 
67
68
  function zip(output, callback) {
68
69
  const outputDir = path.dirname(output);
69
- const zipFile = path.join(outputDir + ".zip");
70
+ const zipFile = path.join(`${outputDir}.zip`);
70
71
  const stream = fs.createWriteStream(zipFile);
71
- stream.on("close", () => {
72
- require("rimraf").sync(outputDir);
72
+ stream.on('close', () => {
73
+ require('rimraf').sync(outputDir);
73
74
  callback(zipFile);
74
75
  });
75
- const archive = require("archiver")("zip", { zlib: { level: 9 } });
76
+ const archive = require('archiver')('zip', { zlib: { level: 9 } });
76
77
  archive.pipe(stream);
77
78
  archive.directory(outputDir, path.basename(outputDir));
78
79
  archive.finalize();
@@ -81,7 +82,7 @@ function zip(output, callback) {
81
82
  const pascalCase = flow(camelCase, upperFirst);
82
83
 
83
84
  function apiHttpErrorToMessage(error) {
84
- if (typeof error === "string") {
85
+ if (typeof error === 'string') {
85
86
  logErrorMessage(error);
86
87
  process.exit();
87
88
  }
@@ -90,28 +91,18 @@ function apiHttpErrorToMessage(error) {
90
91
  if (errors) {
91
92
  logErrorMessage(
92
93
  errors
93
- .map((err) =>
94
- !!err.propertyName
95
- ? `${err.propertyName}: ${err.message}`
96
- : err.message
97
- )
98
- .join("\n")
94
+ .map((err) => (err.propertyName ? `${err.propertyName}: ${err.message}` : err.message))
95
+ .join('\n'),
99
96
  );
100
97
  process.exit();
101
98
  }
102
99
  }
103
- logErrorMessage("Unexpected error.");
100
+ logErrorMessage('Unexpected error.');
104
101
  console.log(error);
105
102
  process.exit();
106
103
  }
107
104
 
108
- function generatePreviewHash(
109
- templateId,
110
- templateName,
111
- versionId,
112
- versionNumber,
113
- versionMainPath
114
- ) {
105
+ function generatePreviewHash(templateId, templateName, versionId, versionNumber, versionMainPath) {
115
106
  const ref = {
116
107
  tid: templateId,
117
108
  tnm: templateName,
@@ -119,8 +110,8 @@ function generatePreviewHash(
119
110
  vnr: versionNumber,
120
111
  vmp: versionMainPath,
121
112
  };
122
- const salt = "A9qJ03jh";
123
- return require("crypto-js").AES.encrypt(JSON.stringify(ref), salt).toString();
113
+ const salt = 'A9qJ03jh';
114
+ return require('crypto-js').AES.encrypt(JSON.stringify(ref), salt).toString();
124
115
  }
125
116
 
126
117
  module.exports = {