zcatalyst-cli 1.18.0-beta.9 → 1.18.1

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 (129) hide show
  1. package/README.md +11 -6
  2. package/docs/commands/slate/unlink.toml +9 -0
  3. package/docs/endpoints/lib/env.toml +3 -1
  4. package/docs/endpoints/lib/slate.toml +3 -0
  5. package/docs/serve/server/lib/slate/index.toml +14 -0
  6. package/docs/slate-utils.toml +4 -0
  7. package/docs/util_modules/config/lib/slate.toml +4 -0
  8. package/lib/archiver.js +18 -9
  9. package/lib/authentication/login.js +6 -5
  10. package/lib/code-deck.js +5 -6
  11. package/lib/command_needs/auth.js +1 -1
  12. package/lib/command_needs/rc.js +40 -3
  13. package/lib/commands/codelib/install.js +1 -0
  14. package/lib/commands/deploy/index.js +4 -0
  15. package/lib/commands/deploy/slate.js +58 -0
  16. package/lib/commands/index.js +2 -3
  17. package/lib/commands/init.js +0 -10
  18. package/lib/commands/slate/create.js +59 -0
  19. package/lib/commands/slate/link.js +59 -0
  20. package/lib/commands/slate/unlink.js +75 -0
  21. package/lib/commands/zest/generate/index.js +1 -6
  22. package/lib/config-store.js +2 -1
  23. package/lib/deploy/features/index.js +3 -0
  24. package/lib/deploy/features/slate.js +123 -0
  25. package/lib/endpoints/index.js +8 -1
  26. package/lib/endpoints/lib/env.js +2 -1
  27. package/lib/endpoints/lib/sdk.js +2 -2
  28. package/lib/endpoints/lib/slate.js +107 -0
  29. package/lib/fn-utils/lib/common.js +1 -1
  30. package/lib/iac/status/deploy.js +1 -5
  31. package/lib/index.js +1 -1
  32. package/lib/init/features/appsail/index.js +2 -3
  33. package/lib/init/features/index.js +13 -1
  34. package/lib/init/features/project.js +1 -1
  35. package/lib/init/features/slate/index.js +313 -0
  36. package/lib/internal/api.js +1 -1
  37. package/lib/internal/command.js +10 -6
  38. package/lib/port-resolver.js +7 -0
  39. package/lib/prompt/index.js +22 -6
  40. package/lib/prompt/types/file-path.js +10 -7
  41. package/lib/serve/features/index.js +8 -1
  42. package/lib/serve/features/slate.js +47 -0
  43. package/lib/serve/server/index.js +61 -1
  44. package/lib/serve/server/lib/appsail/index.js +1 -1
  45. package/lib/serve/server/lib/master/index.js +25 -21
  46. package/lib/serve/server/lib/master/slate.js +45 -0
  47. package/lib/serve/server/lib/master/utils.js +9 -3
  48. package/lib/serve/server/lib/slate/index.js +115 -0
  49. package/lib/serve/server/lib/slate/static-server.js +194 -0
  50. package/lib/serve/server/lib/web_client/server.js +2 -1
  51. package/lib/slate-utils.js +212 -0
  52. package/lib/util_modules/config/index.js +3 -1
  53. package/lib/util_modules/config/lib/slate.js +98 -0
  54. package/lib/util_modules/constants/lib/cliq-handlers.js +18 -10
  55. package/lib/util_modules/constants/lib/dc-type.js +8 -0
  56. package/lib/util_modules/constants/lib/default.js +4 -0
  57. package/lib/util_modules/constants/lib/file-names.js +7 -1
  58. package/lib/util_modules/constants/lib/folder-names.js +1 -0
  59. package/lib/util_modules/constants/lib/placeholders.js +2 -1
  60. package/lib/util_modules/constants/lib/scopes.js +1 -6
  61. package/lib/util_modules/context-help.js +2 -2
  62. package/lib/util_modules/fs/lib/async.js +14 -3
  63. package/lib/util_modules/fs/lib/sync.js +6 -1
  64. package/lib/util_modules/parser/toml.js +20 -5
  65. package/package.json +3 -3
  66. package/templates/event/integ/cliq/bot/action_handler.json +13 -4
  67. package/templates/event/integ/cliq/bot/call_handler.json +41 -0
  68. package/templates/event/integ/cliq/bot/context_handler.json +11 -3
  69. package/templates/event/integ/cliq/bot/incomingwebhook_handler.json +11 -3
  70. package/templates/event/integ/cliq/bot/mention_handler.json +12 -4
  71. package/templates/event/integ/cliq/bot/message_handler.json +13 -4
  72. package/templates/event/integ/cliq/bot/participation_handler.json +13 -3
  73. package/templates/event/integ/cliq/bot/welcome_handler.json +12 -8
  74. package/templates/event/integ/cliq/command/execution_handler.json +12 -3
  75. package/templates/event/integ/cliq/command/suggestion_handler.json +18 -4
  76. package/templates/event/integ/cliq/{installation → extension}/installation_handler.json +13 -4
  77. package/templates/event/integ/cliq/{installation → extension}/installation_validator.json +13 -5
  78. package/templates/event/integ/cliq/extension/uninstallation_handler.json +37 -0
  79. package/templates/event/integ/cliq/function/button_handler.json +13 -5
  80. package/templates/event/integ/cliq/function/form_change_handler.json +9 -3
  81. package/templates/event/integ/cliq/function/form_handler.json +11 -3
  82. package/templates/event/integ/cliq/function/form_values_handler.json +9 -3
  83. package/templates/event/integ/cliq/function/form_view_handler.json +26 -0
  84. package/templates/event/integ/cliq/function/widget_button_handler.json +14 -5
  85. package/templates/event/integ/cliq/link_preview/action_handler.json +54 -0
  86. package/templates/event/integ/cliq/link_preview/after_send_handler.json +47 -0
  87. package/templates/event/integ/cliq/link_preview/menu_handler.json +47 -0
  88. package/templates/event/integ/cliq/link_preview/preview_handler.json +47 -0
  89. package/templates/event/integ/cliq/messageaction/execution_handler.json +11 -3
  90. package/templates/event/integ/cliq/widget/view_handler.json +12 -4
  91. package/templates/init/client/react/react_js/template/src/index.js +3 -3
  92. package/templates/init/client/react/react_ts/template/src/index.tsx +3 -3
  93. package/templates/init/client/react/react_ts/template.json +3 -3
  94. package/templates/init/functions/java/event/sample.java +4 -0
  95. package/templates/init/functions/java/integ/cliq/com/handlers/BotHandler.java +29 -23
  96. package/templates/init/functions/java/integ/cliq/com/handlers/CommandHandler.java +14 -17
  97. package/templates/init/functions/java/integ/cliq/com/handlers/ExtensionHandler.java +41 -0
  98. package/templates/init/functions/java/integ/cliq/com/handlers/FunctionHandler.java +74 -22
  99. package/templates/init/functions/java/integ/cliq/com/handlers/LinkPreviewHandler.java +108 -0
  100. package/templates/init/functions/java/integ/cliq/com/handlers/MessageActionHandler.java +6 -8
  101. package/templates/init/functions/java/integ/cliq/sample.java +10 -0
  102. package/templates/init/functions/node/aio/package.json +1 -1
  103. package/templates/init/functions/node/bio/package.json +1 -1
  104. package/templates/init/functions/node/cron/package.json +1 -1
  105. package/templates/init/functions/node/event/package.json +1 -1
  106. package/templates/init/functions/node/event/sample.js +1 -0
  107. package/templates/init/functions/node/event/types/event.d.ts +7 -0
  108. package/templates/init/functions/node/integ/cliq/handlers/bot-handler.js +4 -0
  109. package/templates/init/functions/node/integ/cliq/handlers/command-handler.js +3 -5
  110. package/templates/init/functions/node/integ/cliq/handlers/{installation-validator.js → extension-handler.js} +20 -3
  111. package/templates/init/functions/node/integ/cliq/handlers/function-handler.js +42 -0
  112. package/templates/init/functions/node/integ/cliq/handlers/link-preview-handler.js +73 -0
  113. package/templates/init/functions/node/integ/cliq/package.json +1 -1
  114. package/templates/init/functions/node/integ/convokraft/package.json +1 -1
  115. package/templates/init/functions/node/job/package.json +1 -1
  116. package/templates/init/functions/python/event/sample.py +9 -5
  117. package/templates/init/functions/python/integ/cliq/handlers/bot_handler.py +13 -3
  118. package/templates/init/functions/python/integ/cliq/handlers/command_handler.py +7 -7
  119. package/templates/init/functions/python/integ/cliq/handlers/extension_handler.py +25 -0
  120. package/templates/init/functions/python/integ/cliq/handlers/function_handler.py +54 -10
  121. package/templates/init/functions/python/integ/cliq/handlers/link_preview_handler.py +76 -0
  122. package/templates/init/functions/python/integ/cliq/handlers/widget_handler.py +10 -9
  123. package/templates/init/functions/python/integ/cliq/sample.py +2 -2
  124. package/templates/init.txt +2 -1
  125. package/templates/init/functions/java/integ/cliq/com/handlers/InstallationHandler.java +0 -20
  126. package/templates/init/functions/java/integ/cliq/com/handlers/InstallationValidator.java +0 -22
  127. package/templates/init/functions/node/integ/cliq/handlers/installation-handler.js +0 -15
  128. package/templates/init/functions/python/integ/cliq/handlers/installation_handler.py +0 -12
  129. package/templates/init/functions/python/integ/cliq/handlers/installation_validator.py +0 -16
@@ -34,10 +34,12 @@ const utils_1 = require("./utils");
34
34
  const appsail_1 = require("./appsail");
35
35
  const web_client_1 = require("./web-client");
36
36
  const functions_1 = require("./functions");
37
- function spinUpMaster(listenPort, { otherServerDetails, appSailDetails }) {
37
+ const slate_1 = require("./slate");
38
+ function spinUpMaster(listenPort, { otherServerDetails, appSailDetails, slateDetails }) {
38
39
  var _a, _b;
39
40
  return __awaiter(this, void 0, void 0, function* () {
40
- if ((otherServerDetails && appSailDetails) || (!otherServerDetails && !appSailDetails)) {
41
+ if ((otherServerDetails && appSailDetails && slateDetails) ||
42
+ (!otherServerDetails && !appSailDetails && !slateDetails)) {
41
43
  throw new error_1.default('Either functions/client or AppSail is need to start the master server. But both cannot use the same master', { exit: 2 });
42
44
  }
43
45
  const projectDetails = {
@@ -56,12 +58,11 @@ function spinUpMaster(listenPort, { otherServerDetails, appSailDetails }) {
56
58
  app.use(cookie_parser_1.default);
57
59
  app.use((0, project_1.default)(projectDetails));
58
60
  app.use(authenticator_1.default);
59
- !appSailDetails &&
61
+ if (!appSailDetails && !slateDetails) {
60
62
  app.use(nonApigURL, (req, res) => {
61
63
  req.url = req.originalUrl;
62
64
  unknownProxy(req, res);
63
65
  });
64
- !appSailDetails &&
65
66
  app.use('*/.catalyst%2Freload-script.js', (req, res) => {
66
67
  var _a;
67
68
  req.url = '/.catalyst%2Freload-script.js';
@@ -73,33 +74,35 @@ function spinUpMaster(listenPort, { otherServerDetails, appSailDetails }) {
73
74
  });
74
75
  });
75
76
  });
76
- if (rules !== -1 && !appSailDetails) {
77
- for (const [sourceURL, methodByConfig] of Object.entries(rules)) {
78
- const router = app.route(sourceURL);
79
- for (const [method, config] of Object.entries(methodByConfig)) {
80
- if (config.system) {
81
- if (systemRoutes === undefined) {
82
- systemRoutes = {};
77
+ if (rules !== -1) {
78
+ for (const [sourceURL, methodByConfig] of Object.entries(rules)) {
79
+ const router = app.route(sourceURL);
80
+ for (const [method, config] of Object.entries(methodByConfig)) {
81
+ if (config.system) {
82
+ if (systemRoutes === undefined) {
83
+ systemRoutes = {};
84
+ }
85
+ js_1.JS.set(systemRoutes, [sourceURL, method], config);
83
86
  }
84
- js_1.JS.set(systemRoutes, [sourceURL, method], config);
87
+ router[method]((req, res, next) => {
88
+ if (res.locals.apigRules === undefined) {
89
+ res.locals.apigRules = [];
90
+ }
91
+ res.locals.apigRules.push(Object.assign({ source_endpoint: sourceURL, params: req.params }, config));
92
+ next();
93
+ });
85
94
  }
86
- router[method]((req, res, next) => {
87
- if (res.locals.apigRules === undefined) {
88
- res.locals.apigRules = [];
89
- }
90
- res.locals.apigRules.push(Object.assign({ source_endpoint: sourceURL, params: req.params }, config));
91
- next();
92
- });
93
95
  }
96
+ app.use('/', apig_matcher_1.default, auth_checker_1.default, url_rewriter_1.default);
94
97
  }
95
- app.use('/', apig_matcher_1.default, auth_checker_1.default, url_rewriter_1.default);
96
98
  }
97
99
  const proxy = (0, utils_1.createProxyServer)(listenPort);
100
+ const signRedirectUrl = slateDetails ? undefined : '/app/local-redirect';
98
101
  appSailDetails && ((_b = (_a = appSailDetails.target) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.catalyst_auth) === true
99
102
  ? proxy.on('proxyRes', (0, utils_1.proxyResponseHandler)({
100
103
  signInRedirect: appSailDetails.target.config.login_redirect || '/'
101
104
  }))
102
- : proxy.on('proxyRes', (0, utils_1.proxyResponseHandler)({ systemRoutes }));
105
+ : proxy.on('proxyRes', (0, utils_1.proxyResponseHandler)({ systemRoutes, signInRedirect: signRedirectUrl }));
103
106
  const proxyDestroyer = new server_js_1.ConnectionDestroyer(proxy);
104
107
  const unknownProxy = (0, unknown_req_proxy_1.default)(proxy, listenPort, customProxyUrl);
105
108
  otherServerDetails &&
@@ -132,6 +135,7 @@ function spinUpMaster(listenPort, { otherServerDetails, appSailDetails }) {
132
135
  }
133
136
  });
134
137
  appSailDetails && (0, appsail_1.addAppSailRoutes)(app, appSailDetails, proxy, unknownProxy);
138
+ slateDetails && (0, slate_1.addSlateRoutes)(app, slateDetails, proxy, unknownProxy);
135
139
  app.use('/', (0, unknown_req_proxy_1.default)(proxy, listenPort, customProxyUrl));
136
140
  app.use(error_handler_1.default);
137
141
  const expressServer = app.listen(listenPort, '127.0.0.1').on('error', (err) => {
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.addSlateRoutes = void 0;
13
+ function addSlateRoutes(app, details, proxy, unknownProxy) {
14
+ app.use('/__catalyst/sdk/init', (req, res) => __awaiter(this, void 0, void 0, function* () {
15
+ req.url = req.originalUrl;
16
+ unknownProxy(req, res);
17
+ }));
18
+ app.use(['/accounts', '/oauthorize'], (req, res) => {
19
+ req.url = req.originalUrl;
20
+ unknownProxy(req, res);
21
+ });
22
+ app.use('/__catalyst', (req, res) => {
23
+ req.url = req.originalUrl;
24
+ if (req.url.includes('redirect_url')) {
25
+ res.redirect(req.url.split('redirect_url=')[1]);
26
+ }
27
+ else if (req.url.includes('service_url')) {
28
+ res.redirect(req.url.split('service_url=')[1]);
29
+ }
30
+ else {
31
+ unknownProxy(req, res);
32
+ }
33
+ });
34
+ app.use('/', (req, res) => __awaiter(this, void 0, void 0, function* () {
35
+ if (req.header('catalyst-component') === 'true') {
36
+ unknownProxy(req, res);
37
+ return;
38
+ }
39
+ proxy.web(req, res, {
40
+ target: `http://localhost:${details.target.port.slate}`,
41
+ ws: true
42
+ });
43
+ }));
44
+ }
45
+ exports.addSlateRoutes = addSlateRoutes;
@@ -78,7 +78,7 @@ const createProxyServer = (port) => {
78
78
  return proxy;
79
79
  };
80
80
  exports.createProxyServer = createProxyServer;
81
- const proxyResponseHandler = ({ systemRoutes, signInRedirect = '/app/local-redirect' }) => (proxyRes, req, res) => {
81
+ const proxyResponseHandler = ({ systemRoutes, signInRedirect }) => (proxyRes, req, res) => {
82
82
  var _a, _b;
83
83
  if (!req.url) {
84
84
  return;
@@ -89,7 +89,7 @@ const proxyResponseHandler = ({ systemRoutes, signInRedirect = '/app/local-redir
89
89
  return cookie;
90
90
  });
91
91
  if (req.url.startsWith('/baas') || req.url.startsWith('/__catalyst')) {
92
- if (req.url.includes('/signin-redirect')) {
92
+ if (req.url.includes('/signin-redirect') && signInRedirect) {
93
93
  if (systemRoutes === undefined) {
94
94
  (0, exports.redirectByAuth)(req, res, signInRedirect);
95
95
  return;
@@ -127,7 +127,13 @@ const appsailInitJs = () => __awaiter(void 0, void 0, void 0, function* () {
127
127
  if (!initJsStr) {
128
128
  throw new error_1.default('Unable to read the init_js file', { exit: 2 });
129
129
  }
130
- const feed = [(0, project_1.getProjectId)(), (0, project_1.getDomainKey)(), constants_1.ORIGIN.iamPortal, (0, project_1.getEnvId)()];
130
+ const feed = [
131
+ (0, project_1.getProjectId)(),
132
+ (0, project_1.getDomainKey)(),
133
+ constants_1.ORIGIN.iamPortal,
134
+ (0, project_1.getEnvId)(),
135
+ `-development${constants_1.ORIGIN.stratusSuffix}`
136
+ ];
131
137
  Object.values(constants_1.PLACEHOLDER.init_js).forEach((holder, idx) => {
132
138
  initJsStr = initJsStr === null || initJsStr === void 0 ? void 0 : initJsStr.replace(new RegExp(holder, 'g'), feed[idx]);
133
139
  });
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const path_1 = require("path");
16
+ const error_1 = __importDefault(require("../../../../error"));
17
+ const fs_1 = require("../../../../util_modules/fs");
18
+ const logger_1 = require("../../../../util_modules/logger");
19
+ const shell_1 = require("../../../../util_modules/shell");
20
+ const master_1 = __importDefault(require("../master"));
21
+ const ansi_colors_1 = require("ansi-colors");
22
+ const file_names_1 = __importDefault(require("../../../../util_modules/constants/lib/file-names"));
23
+ const static_server_1 = __importDefault(require("./static-server"));
24
+ const open_1 = __importDefault(require("open"));
25
+ const async_1 = require("../../../../util_modules/fs/lib/async");
26
+ const startSlate = (port, opts) => {
27
+ const child = (0, shell_1.spawn)(opts.command, [], {
28
+ cwd: opts.target,
29
+ shell: true,
30
+ env: {
31
+ ZC_SLATE_PORT: port + ''
32
+ }
33
+ }).RAW();
34
+ return new Promise((_res, _rej) => {
35
+ child.on('spawn', () => _res(child));
36
+ child.on('error', (reason) => _rej(reason));
37
+ });
38
+ };
39
+ exports.default = (serverDetails) => __awaiter(void 0, void 0, void 0, function* () {
40
+ var _a;
41
+ const targetSlate = serverDetails.target;
42
+ if (!targetSlate || !targetSlate.config) {
43
+ throw new error_1.default('Slate details not found');
44
+ }
45
+ let child;
46
+ if (targetSlate.config.framework === 'static') {
47
+ child = yield (0, static_server_1.default)(targetSlate.port.slate, targetSlate.source, {
48
+ enableWatch: true
49
+ });
50
+ child.addListener('start', () => {
51
+ (0, open_1.default)('http://localhost:' + targetSlate.port.slate).catch();
52
+ });
53
+ }
54
+ else {
55
+ const configFile = (0, path_1.join)(targetSlate.source, file_names_1.default.cli_config);
56
+ if (!fs_1.ASYNC.fileExists(configFile)) {
57
+ throw new error_1.default('Unable to find the development command.', {
58
+ exit: 1,
59
+ errorId: 'SERVE-SLATE-1',
60
+ arg: ['catalyst slate:create']
61
+ });
62
+ }
63
+ if (!(yield fs_1.ASYNC.isPathExists(targetSlate.source))) {
64
+ throw new error_1.default('The given Slate source path does not exist', {
65
+ exit: 1,
66
+ errorId: 'SERVE-SLATE-2',
67
+ arg: [ansi_colors_1.italic.underline.red(targetSlate.source), (0, ansi_colors_1.bold)(targetSlate.name)]
68
+ });
69
+ }
70
+ const configJson = yield (0, async_1.readJSONFile)(configFile);
71
+ if (!configJson) {
72
+ throw new error_1.default('Development command not found', {
73
+ exit: 1,
74
+ errorId: 'SERVE-SLATE-3',
75
+ arg: ['catalyst slate:create']
76
+ });
77
+ }
78
+ child = yield startSlate(targetSlate.port.slate, {
79
+ target: targetSlate.source,
80
+ command: (_a = configJson === null || configJson === void 0 ? void 0 : configJson.slate) === null || _a === void 0 ? void 0 : _a.dev_command
81
+ });
82
+ }
83
+ const masterServe = yield (0, master_1.default)(targetSlate.port.proxy, {
84
+ slateDetails: serverDetails
85
+ });
86
+ child.once('exit', (code) => {
87
+ child.once('exit', () => {
88
+ masterServe.close((err) => {
89
+ if (err) {
90
+ (0, logger_1.debug)('Error stopping the Slate proxy server: ', err);
91
+ }
92
+ });
93
+ });
94
+ if (code === 150) {
95
+ targetSlate.validity = {
96
+ valid: false,
97
+ reason: 'Unable to start the Slate'
98
+ };
99
+ throw new error_1.default('Slate start failed', {
100
+ exit: 1,
101
+ errorId: 'SERVE-SLATE-5',
102
+ arg: [(0, ansi_colors_1.bold)(targetSlate.name)]
103
+ });
104
+ }
105
+ });
106
+ process.on('SIGINT', () => {
107
+ masterServe.close((err) => {
108
+ if (err) {
109
+ (0, logger_1.debug)('Error stopping the Slate proxy server: ', err);
110
+ }
111
+ });
112
+ targetSlate.trigger.kill = true;
113
+ });
114
+ return child;
115
+ });
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const express_1 = __importDefault(require("express"));
16
+ const events_1 = require("events");
17
+ const chokidar_1 = require("chokidar");
18
+ const logger_js_1 = require("../../../../util_modules/logger.js");
19
+ const index_js_1 = require("../../../../util_modules/constants/index.js");
20
+ const error_js_1 = __importDefault(require("../../../../error.js"));
21
+ const index_js_2 = require("../../../../util_modules/fs/index.js");
22
+ const path_1 = require("path");
23
+ const ws_1 = require("ws");
24
+ const port_resolver_js_1 = __importDefault(require("../../../../port-resolver.js"));
25
+ const ansi_colors_1 = require("ansi-colors");
26
+ const server_js_1 = require("../../../../util_modules/server.js");
27
+ function prepareScriptFile(dir, port) {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ const scriptFile = yield index_js_2.ASYNC.readFile(index_js_1.TEMPLATE.client.basic.socket);
30
+ if (!scriptFile) {
31
+ throw new error_js_1.default('Unable to read the script file', { exit: 2 });
32
+ }
33
+ const scriptReady = scriptFile.replace(new RegExp(index_js_1.PLACEHOLDER.client.port, 'g'), port + '');
34
+ yield index_js_2.ASYNC.ensureDir(dir);
35
+ const scriptFilePath = (0, path_1.join)(dir, 'reload-script.js');
36
+ yield index_js_2.ASYNC.writeFile(scriptFilePath, scriptReady);
37
+ return scriptFilePath;
38
+ });
39
+ }
40
+ function stringInjector(source, anchorIdx, marker, inject) {
41
+ const headLastIdx = anchorIdx + marker.length;
42
+ const scriptPrefix = source.slice(0, headLastIdx);
43
+ const scriptSuffix = source.slice(headLastIdx);
44
+ return scriptPrefix + inject + scriptSuffix;
45
+ }
46
+ function injectScript(scriptLocale, indexHtml) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ const headIdx = indexHtml.search(/<head>/gi);
49
+ const scriptTag = `\n<!-- Catalyst web client reload script -->\n<script type="text/javascript" src="${scriptLocale}"></script>\n`;
50
+ if (headIdx !== -1) {
51
+ return stringInjector(indexHtml, headIdx, '<head>', scriptTag);
52
+ }
53
+ const htmlIdx = indexHtml.search(/<html>/gi);
54
+ const headTag = `\n<head>${scriptTag}</head>\n`;
55
+ return stringInjector(indexHtml, htmlIdx, '<html>', headTag);
56
+ });
57
+ }
58
+ function reloadApp(event, path, liveSockets) {
59
+ (0, logger_js_1.info)((0, ansi_colors_1.cyan)(`${event} detected in ${path} of the Web-Client.`));
60
+ liveSockets.forEach((socket) => socket.send('reload'));
61
+ }
62
+ function slateServer(httpPort, source, { homepage = '/index.html', enableWatch = true, notFoundPage } = {}) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ const eventListener = new events_1.EventEmitter();
65
+ const catalystTempDir = (0, path_1.join)(source, '.catalyst');
66
+ const socketServerPort = yield port_resolver_js_1.default.getFreePort(httpPort, 20, true);
67
+ const reloadScriptSrc = enableWatch
68
+ ? (0, path_1.relative)(source, yield prepareScriptFile(catalystTempDir, socketServerPort))
69
+ : undefined;
70
+ if (reloadScriptSrc) {
71
+ const clientWatcher = (0, chokidar_1.watch)(source, {
72
+ ignoreInitial: true,
73
+ ignored: ['node_modules/**/*']
74
+ });
75
+ const liveSockets = [];
76
+ let watcherReady = false;
77
+ clientWatcher.on('error', (err) => {
78
+ watcherReady = false;
79
+ eventListener.emit('error', new error_js_1.default('client watcher error', {
80
+ original: err,
81
+ exit: 1,
82
+ skipHelp: true
83
+ }));
84
+ });
85
+ clientWatcher.on('ready', () => {
86
+ watcherReady = true;
87
+ const socketServer = new ws_1.WebSocketServer({
88
+ port: socketServerPort,
89
+ path: '/client-reload'
90
+ })
91
+ .on('connection', (clientSocket) => {
92
+ if (!watcherReady) {
93
+ clientSocket.send('watcher not ready');
94
+ clientSocket.close();
95
+ return;
96
+ }
97
+ clientSocket.on('close', () => {
98
+ const socketIdx = liveSockets.findIndex((socket) => socket === clientSocket);
99
+ liveSockets.splice(socketIdx, 1);
100
+ });
101
+ liveSockets.push(clientSocket);
102
+ clientSocket.send('connected');
103
+ })
104
+ .on('error', (err) => (0, logger_js_1.debug)(err));
105
+ setTimeout(() => {
106
+ clientWatcher.on('change', (path) => {
107
+ reloadApp('Change(s) is', (0, path_1.relative)(source, path), liveSockets);
108
+ });
109
+ clientWatcher.on('add', (path) => {
110
+ reloadApp('Addition of file(s) is', (0, path_1.relative)(source, path), liveSockets);
111
+ });
112
+ clientWatcher.on('unlink', (path) => {
113
+ reloadApp('Deletion of file(s) is', (0, path_1.relative)(source, path), liveSockets);
114
+ });
115
+ }, 1000);
116
+ eventListener.addListener('close', () => socketServer === null || socketServer === void 0 ? void 0 : socketServer.close());
117
+ });
118
+ eventListener.addListener('close', () => {
119
+ if (clientWatcher) {
120
+ clientWatcher.close();
121
+ }
122
+ liveSockets.forEach((socket) => socket.close());
123
+ index_js_2.SYNC.deleteDir(reloadScriptSrc);
124
+ });
125
+ }
126
+ const app = (0, express_1.default)();
127
+ app.use('/', (req, res) => __awaiter(this, void 0, void 0, function* () {
128
+ const requestedFile = req.url === '/' ? homepage : decodeURIComponent(req.path);
129
+ if (enableWatch && (requestedFile.includes('.html') || requestedFile.includes('.htm'))) {
130
+ const htmlFile = yield index_js_2.ASYNC.readFile((0, path_1.join)(source, requestedFile));
131
+ if (!htmlFile) {
132
+ res.contentType('text/html');
133
+ res.status(404);
134
+ res.end();
135
+ eventListener.emit('error', new error_js_1.default('Unable to read the html file', {
136
+ exit: 1,
137
+ errorId: 'SL-SERVER-1',
138
+ arg: [ansi_colors_1.red.italic(requestedFile)]
139
+ }));
140
+ return;
141
+ }
142
+ const injectedHtml = reloadScriptSrc
143
+ ? yield injectScript(encodeURIComponent(reloadScriptSrc), htmlFile)
144
+ : undefined;
145
+ res.contentType('text/html');
146
+ res.status(200);
147
+ res.send(injectedHtml || htmlFile);
148
+ return;
149
+ }
150
+ res.sendFile((0, path_1.join)(source, requestedFile), (err) => {
151
+ if (!err) {
152
+ return;
153
+ }
154
+ if (err.code &&
155
+ err.code === 'ENOENT') {
156
+ (0, logger_js_1.error)((0, ansi_colors_1.red)('[404 - Resource not found]: ') + (0, ansi_colors_1.bold)(requestedFile));
157
+ (0, logger_js_1.info)();
158
+ (0, logger_js_1.debug)(err.stack || err.message);
159
+ res.status(404);
160
+ notFoundPage
161
+ ? res.sendFile(notFoundPage, (e) => {
162
+ if (!e) {
163
+ return;
164
+ }
165
+ (0, logger_js_1.debug)('Unable to send the 404 page to server: ', e);
166
+ res.status(500);
167
+ res.send('Error sending 404 page to server: ' + e.stack);
168
+ })
169
+ : res.send('Resource not found');
170
+ return;
171
+ }
172
+ (0, logger_js_1.error)('Error fetching the resource: ' + err);
173
+ (0, logger_js_1.debug)(err.stack);
174
+ res.status(500);
175
+ res.send('Error fetching the resource');
176
+ });
177
+ }));
178
+ const server = app.listen(httpPort, '127.0.0.1').on('error', (err) => {
179
+ eventListener.emit('error', err);
180
+ });
181
+ const expressDestroyer = new server_js_1.ConnectionDestroyer(server);
182
+ eventListener.on('error', (err) => {
183
+ (0, logger_js_1.error)('Error when serving the web-client: ' + err.message);
184
+ (0, logger_js_1.info)('Please exit the command to get more info');
185
+ eventListener.emit('close');
186
+ });
187
+ eventListener.on('close', () => __awaiter(this, void 0, void 0, function* () {
188
+ yield expressDestroyer.destroy();
189
+ (0, logger_js_1.debug)('client server closed');
190
+ }));
191
+ return new Promise((res) => server.on('listening', () => res(eventListener)));
192
+ });
193
+ }
194
+ exports.default = slateServer;
@@ -151,7 +151,8 @@ function webClientServer(httpPort, source, { homepage = 'index.html', enableWatc
151
151
  if (!err) {
152
152
  return;
153
153
  }
154
- if (err.code && err.code === 'ENOENT') {
154
+ if (err.code &&
155
+ err.code === 'ENOENT') {
155
156
  (0, logger_js_1.error)((0, ansi_colors_1.red)('[404 - Resource not found]: ') + (0, ansi_colors_1.bold)(requestedFile));
156
157
  (0, logger_js_1.info)();
157
158
  (0, logger_js_1.debug)(err.stack || err.message);