@dainprotocol/cli 1.2.25 → 1.2.28

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.
@@ -60,12 +60,14 @@ var miniflare_1 = require("miniflare");
60
60
  var build_1 = __importDefault(require("./build"));
61
61
  var fs_extra_1 = __importDefault(require("fs-extra"));
62
62
  var net_1 = require("net");
63
+ // Module state
63
64
  var childProcess = null;
64
65
  var watcher = null;
65
66
  var mf = null;
66
67
  var tunnelUrl = null;
67
68
  var isFirstStart = true;
68
- var serverStarted = false;
69
+ var proxyServer = null;
70
+ var isCleaningUp = false;
69
71
  function isPortAvailable(port) {
70
72
  return new Promise(function (resolve) {
71
73
  var server = (0, net_1.createServer)()
@@ -78,58 +80,121 @@ function isPortAvailable(port) {
78
80
  });
79
81
  });
80
82
  }
81
- function startProcess(command, options, isRestart) {
83
+ function cleanup() {
84
+ if (isCleaningUp)
85
+ return;
86
+ isCleaningUp = true;
87
+ if (childProcess) {
88
+ childProcess.kill('SIGTERM');
89
+ childProcess = null;
90
+ }
91
+ if (watcher) {
92
+ watcher.close();
93
+ watcher = null;
94
+ }
95
+ if (mf) {
96
+ mf.dispose();
97
+ mf = null;
98
+ }
99
+ (0, utils_1.logInfo)('Development server and file watcher stopped.');
100
+ }
101
+ function gracefulShutdown() {
102
+ return __awaiter(this, arguments, void 0, function (exitCode) {
103
+ var _a;
104
+ if (exitCode === void 0) { exitCode = 0; }
105
+ return __generator(this, function (_b) {
106
+ switch (_b.label) {
107
+ case 0:
108
+ cleanup();
109
+ if (!proxyServer) return [3 /*break*/, 4];
110
+ _b.label = 1;
111
+ case 1:
112
+ _b.trys.push([1, 3, , 4]);
113
+ return [4 /*yield*/, proxyServer.stop()];
114
+ case 2:
115
+ _b.sent();
116
+ (0, utils_1.logInfo)('Proxy server closed.');
117
+ return [3 /*break*/, 4];
118
+ case 3:
119
+ _a = _b.sent();
120
+ return [3 /*break*/, 4];
121
+ case 4:
122
+ process.exit(exitCode);
123
+ return [2 /*return*/];
124
+ }
125
+ });
126
+ });
127
+ }
128
+ function startProcess(mainFile, envVars, isRestart) {
82
129
  var _a, _b;
83
130
  if (isRestart === void 0) { isRestart = false; }
84
131
  if (childProcess) {
85
- childProcess.kill();
132
+ childProcess.kill('SIGTERM');
133
+ childProcess = null;
86
134
  }
87
- serverStarted = false; // Reset for each new process
88
135
  var spinner = (0, ora_1.default)(isRestart ? 'Restarting development server...' : 'Starting development server...').start();
89
- childProcess = (0, child_process_1.exec)(command, options);
90
- (_a = childProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) {
91
- if (!serverStarted) {
136
+ var hasStarted = false;
137
+ // Use spawn with args array to prevent command injection
138
+ var tsNodePath = path_1.default.join(process.cwd(), 'node_modules', '.bin', 'ts-node');
139
+ // Check if ts-node exists
140
+ if (!fs_extra_1.default.existsSync(tsNodePath)) {
141
+ spinner.fail('ts-node not found. Run: npm install ts-node typescript');
142
+ return;
143
+ }
144
+ // Check if main file exists
145
+ if (!fs_extra_1.default.existsSync(mainFile)) {
146
+ spinner.fail("Main file not found: ".concat(mainFile));
147
+ return;
148
+ }
149
+ childProcess = (0, child_process_1.spawn)(tsNodePath, [mainFile], {
150
+ env: __assign(__assign({}, process.env), envVars),
151
+ stdio: ['inherit', 'pipe', 'pipe'],
152
+ shell: false, // Explicitly disable shell to prevent injection
153
+ });
154
+ var markStarted = function (success) {
155
+ if (hasStarted)
156
+ return;
157
+ hasStarted = true;
158
+ if (success) {
92
159
  spinner.succeed(isRestart ? 'Development server restarted.' : 'Development server started.');
93
160
  if (tunnelUrl && isFirstStart) {
94
161
  (0, utils_1.displayTunnelUrl)(tunnelUrl);
95
162
  isFirstStart = false;
96
163
  }
97
- serverStarted = true;
98
164
  }
99
- console.log(data);
165
+ else {
166
+ spinner.fail('Development server error.');
167
+ }
168
+ };
169
+ (_a = childProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) {
170
+ markStarted(true);
171
+ process.stdout.write(data.toString());
100
172
  });
101
173
  (_b = childProcess.stderr) === null || _b === void 0 ? void 0 : _b.on('data', function (data) {
102
- if (!serverStarted) {
103
- spinner.fail('Development server error.');
104
- serverStarted = true; // Prevent multiple error messages too
174
+ var output = data.toString();
175
+ // Don't fail on warnings, only on actual errors
176
+ if (output.includes('Error:') || output.includes('error:')) {
177
+ markStarted(false);
178
+ }
179
+ else {
180
+ markStarted(true);
105
181
  }
106
- (0, utils_1.logError)(data);
182
+ process.stderr.write(output);
107
183
  });
108
184
  childProcess.on('close', function (code) {
109
- if (code !== 0 && !serverStarted) {
185
+ if (code !== 0 && code !== null && !hasStarted) {
110
186
  spinner.fail("Development server exited with code ".concat(code));
111
187
  }
188
+ childProcess = null;
112
189
  });
113
- }
114
- function cleanup() {
115
- if (childProcess) {
116
- childProcess.kill();
190
+ childProcess.on('error', function (error) {
191
+ spinner.fail("Failed to start: ".concat(error.message));
117
192
  childProcess = null;
118
- }
119
- if (watcher) {
120
- watcher.close();
121
- watcher = null;
122
- }
123
- if (mf) {
124
- mf.dispose();
125
- mf = null;
126
- }
127
- (0, utils_1.logInfo)('Development server and file watcher stopped.');
128
- process.exit(0);
193
+ });
129
194
  }
130
195
  function dev(options) {
131
196
  return __awaiter(this, void 0, void 0, function () {
132
- var config, portSource, port, portNumber, runtime, tsNodePath, command, envVars, proxyServer, portNumber_1, proxySetup, watchPaths, dainDir, outFile, MFconfig_1, debounceTimer_1, watchDirs, error_1;
197
+ var config, port, portSource, portNumber, runtime, mainFile, resolvedMain, envVars, parsedPort, proxySetup, watchPaths, dainDir, outFile, MFconfig_1, debounceTimer_1, error_1;
133
198
  return __generator(this, function (_a) {
134
199
  switch (_a.label) {
135
200
  case 0:
@@ -146,43 +211,54 @@ function dev(options) {
146
211
  port = '2022';
147
212
  portSource = 'default value';
148
213
  }
149
- portNumber = parseInt(port);
150
- if (isNaN(portNumber) || portNumber < 0 || portNumber > 65535) {
151
- (0, utils_1.logError)('Invalid port number. Using default port 2022');
152
- options.port = '2022';
214
+ portNumber = parseInt(port, 10);
215
+ if (isNaN(portNumber) || portNumber < 1 || portNumber > 65535) {
216
+ (0, utils_1.logError)("Invalid port: ".concat(port, ". Must be 1-65535. Using default port 2022"));
217
+ port = '2022';
153
218
  portSource = 'default value (after invalid port)';
154
219
  }
155
- else {
156
- options.port = port;
157
- }
158
- (0, utils_1.logInfo)("Using port ".concat(options.port, " (from ").concat(portSource, ")"));
220
+ (0, utils_1.logInfo)("Using port ".concat(port, " (from ").concat(portSource, ")"));
159
221
  runtime = options.runtime || config.runtime || 'node';
160
- tsNodePath = path_1.default.join(process.cwd(), 'node_modules', '.bin', 'ts-node');
161
- command = "\"".concat(tsNodePath, "\" \"").concat(config['main-file'], "\"");
222
+ mainFile = config['main-file'];
223
+ resolvedMain = path_1.default.resolve(process.cwd(), mainFile);
224
+ if (!resolvedMain.startsWith(process.cwd())) {
225
+ (0, utils_1.logError)('Invalid main-file path: must be within project directory');
226
+ process.exit(1);
227
+ }
162
228
  envVars = {
163
- PORT: options.port,
229
+ PORT: port,
164
230
  DAIN_API_KEY: config['api-key'],
165
231
  DAIN_PROJECT_ID: config['project-id'],
166
232
  DAIN_ENVIRONMENT: config['environment'],
167
233
  DAIN_OUT_DIR: config['out-dir'],
168
234
  };
169
- proxyServer = null;
235
+ // Register signal handlers once
236
+ process.once('SIGINT', function () { return gracefulShutdown(0); });
237
+ process.once('SIGTERM', function () { return gracefulShutdown(0); });
238
+ process.once('uncaughtException', function (error) {
239
+ (0, utils_1.logError)('Uncaught Exception:', error);
240
+ gracefulShutdown(1);
241
+ });
242
+ process.once('unhandledRejection', function (reason) {
243
+ (0, utils_1.logError)('Unhandled Rejection:', reason);
244
+ gracefulShutdown(1);
245
+ });
170
246
  _a.label = 1;
171
247
  case 1:
172
248
  _a.trys.push([1, 9, , 10]);
173
- portNumber_1 = parseInt(options.port);
174
- return [4 /*yield*/, isPortAvailable(portNumber_1)];
249
+ parsedPort = parseInt(port, 10);
250
+ return [4 /*yield*/, isPortAvailable(parsedPort)];
175
251
  case 2:
176
252
  if (!(_a.sent())) {
177
- (0, utils_1.logError)("Port ".concat(portNumber_1, " is already in use. Please use a different port with --port option."));
253
+ (0, utils_1.logError)("Port ".concat(parsedPort, " is already in use. Use --port to specify a different port."));
178
254
  process.exit(1);
179
255
  }
180
- process.env.PORT = portNumber_1.toString();
256
+ process.env.PORT = port;
181
257
  if (!!options.noproxy) return [3 /*break*/, 4];
182
258
  if (!config['api-key']) {
183
259
  throw new Error("'api-key' is required when using development proxy");
184
260
  }
185
- return [4 /*yield*/, (0, utils_1.setupProxy)(options.port, config['api-key'], config)];
261
+ return [4 /*yield*/, (0, utils_1.setupProxy)(port, config['api-key'], config)];
186
262
  case 3:
187
263
  proxySetup = _a.sent();
188
264
  proxyServer = proxySetup.client;
@@ -190,106 +266,50 @@ function dev(options) {
190
266
  _a.label = 4;
191
267
  case 4:
192
268
  if (!(runtime === 'node')) return [3 /*break*/, 5];
193
- // Existing Node.js development process
194
- startProcess(command, { env: __assign(__assign({}, process.env), envVars) });
269
+ startProcess(mainFile, envVars);
195
270
  watchPaths = [
196
- path_1.default.dirname(config['main-file']),
271
+ path_1.default.dirname(mainFile),
197
272
  config['static-dir']
198
273
  ? path_1.default.join(process.cwd(), config['static-dir'])
199
274
  : (0, utils_1.getStaticFilesPath)(),
200
- ];
275
+ ].filter(function (p) { return fs_extra_1.default.existsSync(p); });
201
276
  watcher = chokidar_1.default.watch(watchPaths, {
202
- ignored: /(^|[\/\\])\../, // ignore dotfiles
277
+ ignored: /(^|[\/\\])\../,
203
278
  persistent: true,
279
+ ignoreInitial: true,
204
280
  });
205
- watcher.on('change', function (path) {
206
- (0, utils_1.logInfo)("File ".concat(path, " has been changed. Restarting..."));
207
- startProcess(command, { env: __assign(__assign({}, process.env), envVars) }, true);
281
+ watcher.on('change', function (changedPath) {
282
+ (0, utils_1.logInfo)("File ".concat(changedPath, " changed. Restarting..."));
283
+ startProcess(mainFile, envVars, true);
208
284
  });
209
285
  (0, utils_1.logInfo)('Watching for file changes...');
210
- // Add signal handlers for graceful shutdown
211
- process.on('SIGINT', function () {
212
- cleanup();
213
- if (proxyServer) {
214
- proxyServer.close(function () {
215
- (0, utils_1.logInfo)('Proxy server closed.');
216
- setTimeout(function () {
217
- process.exit(0);
218
- }, 500);
219
- });
220
- }
221
- else {
222
- setTimeout(function () {
223
- process.exit(0);
224
- }, 500);
225
- }
226
- });
227
- process.on('SIGTERM', function () {
228
- cleanup();
229
- if (proxyServer) {
230
- proxyServer.close(function () {
231
- (0, utils_1.logInfo)('Proxy server closed.');
232
- setTimeout(function () {
233
- process.exit(0);
234
- }, 500);
235
- });
236
- }
237
- else {
238
- setTimeout(function () {
239
- process.exit(0);
240
- }, 500);
241
- }
242
- });
243
- // Handle uncaught exceptions and unhandled rejections
244
- process.on('uncaughtException', function (error) {
245
- (0, utils_1.logError)('Uncaught Exception:', error);
246
- cleanup();
247
- if (proxyServer)
248
- proxyServer.close();
249
- setTimeout(function () {
250
- process.exit(1);
251
- }, 500);
252
- });
253
- process.on('unhandledRejection', function (reason, promise) {
254
- (0, utils_1.logError)('Unhandled Rejection at:', promise + '\n\nreason:' + reason);
255
- cleanup();
256
- if (proxyServer)
257
- proxyServer.close();
258
- setTimeout(function () {
259
- process.exit(1);
260
- }, 500);
261
- });
262
286
  return [3 /*break*/, 8];
263
287
  case 5:
264
288
  if (!(runtime === 'workers')) return [3 /*break*/, 7];
265
289
  dainDir = path_1.default.join(process.cwd(), '.dain');
266
290
  outFile = path_1.default.join(dainDir, path_1.default.basename(config['main-file'], '.ts') + '.mjs');
267
- // Start the build process in watch mode
268
291
  return [4 /*yield*/, (0, build_1.default)({ config: options.config, runtime: 'workers', watch: true })];
269
292
  case 6:
270
- // Start the build process in watch mode
271
293
  _a.sent();
272
294
  MFconfig_1 = {
273
295
  scriptPath: outFile,
274
296
  modules: true,
275
- port: parseInt(options.port),
297
+ port: parseInt(port, 10),
276
298
  log: new miniflare_1.Log(miniflare_1.LogLevel.DEBUG),
277
299
  liveReload: true,
278
300
  };
279
301
  mf = new miniflare_1.Miniflare(MFconfig_1);
280
- (0, utils_1.logSuccess)("Miniflare server started on port ".concat(options.port));
281
- watchDirs = [dainDir];
282
- watchDirs.forEach(function (dir) {
283
- fs_extra_1.default.watch(dir, { recursive: true }, function (eventType, filename) {
302
+ (0, utils_1.logSuccess)("Miniflare server started on port ".concat(port));
303
+ debounceTimer_1 = null;
304
+ fs_extra_1.default.watch(dainDir, { recursive: true }, function (_eventType, filename) {
305
+ if (debounceTimer_1)
284
306
  clearTimeout(debounceTimer_1);
285
- debounceTimer_1 = setTimeout(function () {
286
- if (mf) {
287
- // mf.setOptions({ scriptPath: outFile });
288
- mf.setOptions(MFconfig_1);
289
- (0, utils_1.logInfo)("Build updated (".concat(filename, ")"));
290
- }
291
- }, 300); // 300ms debounce time
292
- });
307
+ debounceTimer_1 = setTimeout(function () {
308
+ if (mf) {
309
+ mf.setOptions(MFconfig_1);
310
+ (0, utils_1.logInfo)("Build updated (".concat(filename, ")"));
311
+ }
312
+ }, 300);
293
313
  });
294
314
  (0, utils_1.logInfo)('Watching for file changes in source and build directories...');
295
315
  return [3 /*break*/, 8];
@@ -298,12 +318,7 @@ function dev(options) {
298
318
  case 9:
299
319
  error_1 = _a.sent();
300
320
  (0, utils_1.logError)("Error in dev process for ".concat(runtime, " runtime:"), error_1);
301
- cleanup();
302
- if (proxyServer)
303
- proxyServer.close();
304
- setTimeout(function () {
305
- process.exit(1);
306
- }, 500);
321
+ gracefulShutdown(1);
307
322
  return [3 /*break*/, 10];
308
323
  case 10: return [2 /*return*/];
309
324
  }
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -53,10 +64,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
53
64
  exports.default = logs;
54
65
  var ora_1 = __importDefault(require("ora"));
55
66
  var utils_1 = require("../utils");
56
- function logs(options_1) {
57
- return __awaiter(this, arguments, void 0, function (options, isWatching) {
58
- var config, orgId, _a, apiKey, deploymentId, logsUrl, spinner, result, formatLogs, error_1;
59
- if (isWatching === void 0) { isWatching = false; }
67
+ // Module state for cleanup
68
+ var watchInterval = null;
69
+ var isShuttingDown = false;
70
+ function cleanup() {
71
+ isShuttingDown = true;
72
+ if (watchInterval) {
73
+ clearInterval(watchInterval);
74
+ watchInterval = null;
75
+ }
76
+ }
77
+ function logs(options) {
78
+ return __awaiter(this, void 0, void 0, function () {
79
+ var config, orgId, _a, apiKey, deploymentId, logsUrl, spinner, result, formattedLogs, error_1;
80
+ var _this = this;
60
81
  return __generator(this, function (_b) {
61
82
  switch (_b.label) {
62
83
  case 0:
@@ -65,37 +86,65 @@ function logs(options_1) {
65
86
  _a = initializeConfig(config, orgId), apiKey = _a.apiKey, deploymentId = _a.deploymentId, logsUrl = _a.logsUrl;
66
87
  if (!orgId || !deploymentId) {
67
88
  (0, utils_1.logError)("Org ID or deployment ID not found");
68
- return [2 /*return*/];
89
+ process.exit(1);
69
90
  }
91
+ // Setup cleanup handlers
92
+ process.once("SIGINT", function () {
93
+ cleanup();
94
+ process.exit(0);
95
+ });
96
+ process.once("SIGTERM", function () {
97
+ cleanup();
98
+ process.exit(0);
99
+ });
70
100
  spinner = (0, ora_1.default)("Fetching logs for project ".concat(config["project-id"], "...")).start();
71
101
  _b.label = 1;
72
102
  case 1:
73
- _b.trys.push([1, 3, 4, 5]);
74
- result = null;
103
+ _b.trys.push([1, 3, , 4]);
75
104
  return [4 /*yield*/, fetchLogs(logsUrl, apiKey)];
76
105
  case 2:
77
106
  result = _b.sent();
78
- formatLogs = formatProjectLogs(result, deploymentId);
79
- if (isWatching) {
80
- // clear terminal before printing logs when watching
81
- process.stdout.write("\x1Bc");
82
- }
83
- (0, utils_1.logInfo)("Project logs: ".concat(formatLogs));
107
+ spinner.stop();
108
+ formattedLogs = formatProjectLogs(result, deploymentId);
109
+ (0, utils_1.logInfo)("Project logs: ".concat(formattedLogs));
84
110
  if (options.watch) {
85
- setTimeout(function () { return logs(options, true); }, 10000);
111
+ (0, utils_1.logInfo)("Watching for log updates (Ctrl+C to stop)...");
112
+ watchInterval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
113
+ var newResult, newFormattedLogs, error_2;
114
+ return __generator(this, function (_a) {
115
+ switch (_a.label) {
116
+ case 0:
117
+ if (isShuttingDown)
118
+ return [2 /*return*/];
119
+ _a.label = 1;
120
+ case 1:
121
+ _a.trys.push([1, 3, , 4]);
122
+ return [4 /*yield*/, fetchLogs(logsUrl, apiKey)];
123
+ case 2:
124
+ newResult = _a.sent();
125
+ process.stdout.write("\x1Bc"); // Clear terminal
126
+ newFormattedLogs = formatProjectLogs(newResult, deploymentId);
127
+ (0, utils_1.logInfo)("Project logs: ".concat(newFormattedLogs));
128
+ return [3 /*break*/, 4];
129
+ case 3:
130
+ error_2 = _a.sent();
131
+ (0, utils_1.logError)("Error fetching logs", error_2);
132
+ return [3 /*break*/, 4];
133
+ case 4: return [2 /*return*/];
134
+ }
135
+ });
136
+ }); }, 10000);
86
137
  }
87
- if (!options.watch) {
138
+ else {
88
139
  process.exit(0);
89
140
  }
90
- return [3 /*break*/, 5];
141
+ return [3 /*break*/, 4];
91
142
  case 3:
92
143
  error_1 = _b.sent();
93
144
  handleError(spinner, error_1);
94
- return [3 /*break*/, 5];
95
- case 4:
96
- spinner.stop();
97
- return [7 /*endfinally*/];
98
- case 5: return [2 /*return*/];
145
+ process.exit(1);
146
+ return [3 /*break*/, 4];
147
+ case 4: return [2 /*return*/];
99
148
  }
100
149
  });
101
150
  });
@@ -107,28 +156,50 @@ var initializeConfig = function (config, orgId) {
107
156
  var environment = config["environment"];
108
157
  var serviceId = config["service-id"];
109
158
  var logsUrl = "".concat(baseUrl, "/codegen-deploy/logs/").concat(orgId, "/").concat(serviceId, "/").concat(deploymentId, "/").concat(environment);
110
- return { baseUrl: baseUrl, apiKey: apiKey, orgId: orgId, deploymentId: deploymentId, logsUrl: logsUrl };
159
+ return { apiKey: apiKey, deploymentId: deploymentId, logsUrl: logsUrl };
111
160
  };
161
+ var FETCH_TIMEOUT_MS = 30000;
162
+ function fetchWithTimeout(url_1, options_1) {
163
+ return __awaiter(this, arguments, void 0, function (url, options, timeoutMs) {
164
+ var controller, timeoutId, response;
165
+ if (timeoutMs === void 0) { timeoutMs = FETCH_TIMEOUT_MS; }
166
+ return __generator(this, function (_a) {
167
+ switch (_a.label) {
168
+ case 0:
169
+ controller = new AbortController();
170
+ timeoutId = setTimeout(function () { return controller.abort(); }, timeoutMs);
171
+ _a.label = 1;
172
+ case 1:
173
+ _a.trys.push([1, , 3, 4]);
174
+ return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { signal: controller.signal }))];
175
+ case 2:
176
+ response = _a.sent();
177
+ return [2 /*return*/, response];
178
+ case 3:
179
+ clearTimeout(timeoutId);
180
+ return [7 /*endfinally*/];
181
+ case 4: return [2 /*return*/];
182
+ }
183
+ });
184
+ });
185
+ }
112
186
  var fetchLogs = function (logsUrl, apiKey) { return __awaiter(void 0, void 0, void 0, function () {
113
187
  var response;
114
188
  return __generator(this, function (_a) {
115
189
  switch (_a.label) {
116
- case 0: return [4 /*yield*/, fetch(logsUrl, {
190
+ case 0: return [4 /*yield*/, fetchWithTimeout(logsUrl, {
117
191
  method: "GET",
118
192
  headers: {
119
193
  "Content-Type": "application/json",
120
- "X-DAIN-SIGNATORY-ADDRESS": "TODO: X-DAIN-SIGNATORY-ADDRESS",
121
- "X-DAIN-SIGNATURE": "TODO: X-DAIN-SIGNATORY-SIGNATURE",
122
194
  Authorization: "Bearer ".concat(apiKey),
123
195
  },
124
196
  })];
125
197
  case 1:
126
198
  response = _a.sent();
127
199
  if (!response.ok) {
128
- throw new Error("Log fetch failed: ".concat(response.statusText));
200
+ throw new Error("Log fetch failed: ".concat(response.status, " ").concat(response.statusText));
129
201
  }
130
- return [4 /*yield*/, response.json()];
131
- case 2: return [2 /*return*/, _a.sent()];
202
+ return [2 /*return*/, response.json()];
132
203
  }
133
204
  });
134
205
  }); };
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -42,6 +53,31 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
53
  exports.default = status;
43
54
  var ora_1 = __importDefault(require("ora"));
44
55
  var utils_1 = require("../utils");
56
+ var FETCH_TIMEOUT_MS = 30000;
57
+ function fetchWithTimeout(url_1, options_1) {
58
+ return __awaiter(this, arguments, void 0, function (url, options, timeoutMs) {
59
+ var controller, timeoutId, response;
60
+ if (timeoutMs === void 0) { timeoutMs = FETCH_TIMEOUT_MS; }
61
+ return __generator(this, function (_a) {
62
+ switch (_a.label) {
63
+ case 0:
64
+ controller = new AbortController();
65
+ timeoutId = setTimeout(function () { return controller.abort(); }, timeoutMs);
66
+ _a.label = 1;
67
+ case 1:
68
+ _a.trys.push([1, , 3, 4]);
69
+ return [4 /*yield*/, fetch(url, __assign(__assign({}, options), { signal: controller.signal }))];
70
+ case 2:
71
+ response = _a.sent();
72
+ return [2 /*return*/, response];
73
+ case 3:
74
+ clearTimeout(timeoutId);
75
+ return [7 /*endfinally*/];
76
+ case 4: return [2 /*return*/];
77
+ }
78
+ });
79
+ });
80
+ }
45
81
  function status(options, preDefinedDeploymentId, preDefinedEnvironmentName, preDefinedServiceId) {
46
82
  return __awaiter(this, void 0, void 0, function () {
47
83
  var config, orgId, _a, apiKey, deploymentId, statusUrl, spinner, response, result, error_1;
@@ -51,27 +87,25 @@ function status(options, preDefinedDeploymentId, preDefinedEnvironmentName, preD
51
87
  config = (0, utils_1.getDainConfig)(options.config);
52
88
  orgId = "hackathon";
53
89
  _a = initializeConfig(config, orgId, preDefinedDeploymentId, preDefinedEnvironmentName, preDefinedServiceId), apiKey = _a.apiKey, deploymentId = _a.deploymentId, statusUrl = _a.statusUrl;
54
- if (!orgId || !deploymentId) {
55
- (0, utils_1.logError)("Org ID or deployment ID not found");
56
- return [2 /*return*/];
90
+ if (!deploymentId) {
91
+ (0, utils_1.logError)("Deployment ID not found");
92
+ process.exit(1);
57
93
  }
58
94
  spinner = (0, ora_1.default)("Checking status for project ".concat(config["project-id"], "...")).start();
59
95
  _b.label = 1;
60
96
  case 1:
61
97
  _b.trys.push([1, 4, , 5]);
62
- return [4 /*yield*/, fetch(statusUrl, {
98
+ return [4 /*yield*/, fetchWithTimeout(statusUrl, {
63
99
  method: "GET",
64
100
  headers: {
65
101
  "Content-Type": "application/json",
66
- "X-DAIN-SIGNATORY-ADDRESS": "TODO: X-DAIN-SIGNATORY-ADDRESS",
67
- "X-DAIN-SIGNATURE": "TODO: X-DAIN-SIGNATORY-SIGNATURE",
68
102
  Authorization: "Bearer ".concat(apiKey),
69
103
  },
70
104
  })];
71
105
  case 2:
72
106
  response = _b.sent();
73
107
  if (!response.ok) {
74
- throw new Error("Status check failed: ".concat(response.statusText));
108
+ throw new Error("Status check failed: ".concat(response.status, " ").concat(response.statusText));
75
109
  }
76
110
  return [4 /*yield*/, response.json()];
77
111
  case 3:
@@ -95,10 +129,9 @@ function status(options, preDefinedDeploymentId, preDefinedEnvironmentName, preD
95
129
  var initializeConfig = function (config, orgId, preDefinedDeploymentId, preDefinedEnvironment, preDefinedServiceId) {
96
130
  var baseUrl = config["platform-base-url"] || "https://codegen-deploy-service.dainapp.com/";
97
131
  var apiKey = config["api-key"];
98
- var orgIdToBeUsed = orgId || (0, utils_1.extractOrgId)(apiKey);
99
132
  var deploymentId = preDefinedDeploymentId || config["deployment-id"];
100
133
  var environment = preDefinedEnvironment || config["environment"];
101
134
  var serviceId = preDefinedServiceId || config["service-id"];
102
- var statusUrl = "".concat(baseUrl, "/codegen-deploy/status/").concat(orgIdToBeUsed, "/").concat(serviceId, "/").concat(deploymentId, "/").concat(environment);
103
- return { baseUrl: baseUrl, apiKey: apiKey, orgIdToBeUsed: orgIdToBeUsed, deploymentId: deploymentId, statusUrl: statusUrl };
135
+ var statusUrl = "".concat(baseUrl, "/codegen-deploy/status/").concat(orgId, "/").concat(serviceId, "/").concat(deploymentId, "/").concat(environment);
136
+ return { apiKey: apiKey, deploymentId: deploymentId, statusUrl: statusUrl };
104
137
  };