@dainprotocol/cli 1.2.26 → 1.2.30

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.
@@ -65,124 +65,156 @@ var watcher = null;
65
65
  var mf = null;
66
66
  var tunnelUrl = null;
67
67
  var isFirstStart = true;
68
- var serverStarted = false;
68
+ var proxyServer = null;
69
+ var isCleaningUp = false;
69
70
  function isPortAvailable(port) {
70
71
  return new Promise(function (resolve) {
71
72
  var server = (0, net_1.createServer)()
72
- .listen(port, function () {
73
- server.close();
74
- resolve(true);
75
- })
76
- .on('error', function () {
77
- resolve(false);
73
+ .listen(port, function () { server.close(); resolve(true); })
74
+ .on('error', function () { return resolve(false); });
75
+ });
76
+ }
77
+ function cleanup() {
78
+ if (isCleaningUp)
79
+ return;
80
+ isCleaningUp = true;
81
+ if (childProcess) {
82
+ childProcess.kill('SIGTERM');
83
+ childProcess = null;
84
+ }
85
+ if (watcher) {
86
+ watcher.close();
87
+ watcher = null;
88
+ }
89
+ if (mf) {
90
+ mf.dispose();
91
+ mf = null;
92
+ }
93
+ (0, utils_1.logInfo)('Development server and file watcher stopped.');
94
+ }
95
+ function gracefulShutdown() {
96
+ return __awaiter(this, arguments, void 0, function (exitCode) {
97
+ var _a;
98
+ if (exitCode === void 0) { exitCode = 0; }
99
+ return __generator(this, function (_b) {
100
+ switch (_b.label) {
101
+ case 0:
102
+ cleanup();
103
+ if (!proxyServer) return [3 /*break*/, 4];
104
+ _b.label = 1;
105
+ case 1:
106
+ _b.trys.push([1, 3, , 4]);
107
+ return [4 /*yield*/, proxyServer.stop()];
108
+ case 2:
109
+ _b.sent();
110
+ (0, utils_1.logInfo)('Proxy server closed.');
111
+ return [3 /*break*/, 4];
112
+ case 3:
113
+ _a = _b.sent();
114
+ return [3 /*break*/, 4];
115
+ case 4:
116
+ process.exit(exitCode);
117
+ return [2 /*return*/];
118
+ }
78
119
  });
79
120
  });
80
121
  }
81
- function startProcess(command, options, isRestart) {
122
+ function startProcess(mainFile, envVars, isRestart) {
82
123
  var _a, _b;
83
124
  if (isRestart === void 0) { isRestart = false; }
84
125
  if (childProcess) {
85
- childProcess.kill();
126
+ childProcess.kill('SIGTERM');
127
+ childProcess = null;
86
128
  }
87
- serverStarted = false; // Reset for each new process
88
129
  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) {
130
+ var hasStarted = false;
131
+ var tsNodePath = path_1.default.join(process.cwd(), 'node_modules', '.bin', 'ts-node');
132
+ if (!fs_extra_1.default.existsSync(tsNodePath)) {
133
+ spinner.fail('ts-node not found. Run: npm install ts-node typescript');
134
+ return;
135
+ }
136
+ if (!fs_extra_1.default.existsSync(mainFile)) {
137
+ spinner.fail("Main file not found: ".concat(mainFile));
138
+ return;
139
+ }
140
+ childProcess = (0, child_process_1.spawn)(tsNodePath, [mainFile], {
141
+ env: __assign(__assign({}, process.env), envVars),
142
+ stdio: ['inherit', 'pipe', 'pipe'],
143
+ shell: false,
144
+ });
145
+ var markStarted = function (success) {
146
+ if (hasStarted)
147
+ return;
148
+ hasStarted = true;
149
+ if (success) {
92
150
  spinner.succeed(isRestart ? 'Development server restarted.' : 'Development server started.');
93
151
  if (tunnelUrl && isFirstStart) {
94
152
  (0, utils_1.displayTunnelUrl)(tunnelUrl);
95
153
  isFirstStart = false;
96
154
  }
97
- serverStarted = true;
98
155
  }
99
- console.log(data);
100
- });
101
- (_b = childProcess.stderr) === null || _b === void 0 ? void 0 : _b.on('data', function (data) {
102
- if (!serverStarted) {
156
+ else {
103
157
  spinner.fail('Development server error.');
104
- serverStarted = true; // Prevent multiple error messages too
105
158
  }
106
- (0, utils_1.logError)(data);
159
+ };
160
+ (_a = childProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', function (data) { markStarted(true); process.stdout.write(data.toString()); });
161
+ (_b = childProcess.stderr) === null || _b === void 0 ? void 0 : _b.on('data', function (data) {
162
+ var output = data.toString();
163
+ markStarted(output.includes('Error:') || output.includes('error:') ? false : true);
164
+ process.stderr.write(output);
107
165
  });
108
166
  childProcess.on('close', function (code) {
109
- if (code !== 0 && !serverStarted) {
167
+ if (code !== 0 && code !== null && !hasStarted)
110
168
  spinner.fail("Development server exited with code ".concat(code));
111
- }
112
- });
113
- }
114
- function cleanup() {
115
- if (childProcess) {
116
- childProcess.kill();
117
169
  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);
170
+ });
171
+ childProcess.on('error', function (error) { spinner.fail("Failed to start: ".concat(error.message)); childProcess = null; });
129
172
  }
130
173
  function dev(options) {
131
174
  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;
175
+ var config, port, portNumber, runtime, mainFile, resolvedMain, envVars, proxySetup, watchPaths, dainDir, outFile, MFconfig_1, debounceTimer_1, error_1;
133
176
  return __generator(this, function (_a) {
134
177
  switch (_a.label) {
135
178
  case 0:
136
179
  config = (0, utils_1.getDainConfig)(options.config);
137
- if (process.env.PORT) {
138
- port = process.env.PORT;
139
- portSource = '.env file';
140
- }
141
- else if (options.port) {
142
- port = options.port;
143
- portSource = 'command line argument';
144
- }
145
- else {
180
+ port = process.env.PORT || options.port || '2022';
181
+ portNumber = parseInt(port, 10);
182
+ if (isNaN(portNumber) || portNumber < 1 || portNumber > 65535) {
183
+ (0, utils_1.logError)("Invalid port: ".concat(port, ". Must be 1-65535. Using default port 2022"));
146
184
  port = '2022';
147
- portSource = 'default value';
148
- }
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';
153
- portSource = 'default value (after invalid port)';
154
185
  }
155
- else {
156
- options.port = port;
157
- }
158
- (0, utils_1.logInfo)("Using port ".concat(options.port, " (from ").concat(portSource, ")"));
159
186
  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'], "\"");
187
+ mainFile = config['main-file'];
188
+ resolvedMain = path_1.default.resolve(process.cwd(), mainFile);
189
+ if (!resolvedMain.startsWith(process.cwd())) {
190
+ (0, utils_1.logError)('Invalid main-file path: must be within project directory');
191
+ process.exit(1);
192
+ }
162
193
  envVars = {
163
- PORT: options.port,
194
+ PORT: port,
164
195
  DAIN_API_KEY: config['api-key'],
165
196
  DAIN_PROJECT_ID: config['project-id'],
166
197
  DAIN_ENVIRONMENT: config['environment'],
167
198
  DAIN_OUT_DIR: config['out-dir'],
168
199
  };
169
- proxyServer = null;
200
+ process.once('SIGINT', function () { return gracefulShutdown(0); });
201
+ process.once('SIGTERM', function () { return gracefulShutdown(0); });
202
+ process.once('uncaughtException', function (error) { (0, utils_1.logError)('Uncaught Exception:', error); gracefulShutdown(1); });
203
+ process.once('unhandledRejection', function (reason) { (0, utils_1.logError)('Unhandled Rejection:', reason); gracefulShutdown(1); });
170
204
  _a.label = 1;
171
205
  case 1:
172
206
  _a.trys.push([1, 9, , 10]);
173
- portNumber_1 = parseInt(options.port);
174
- return [4 /*yield*/, isPortAvailable(portNumber_1)];
207
+ return [4 /*yield*/, isPortAvailable(portNumber)];
175
208
  case 2:
176
209
  if (!(_a.sent())) {
177
- (0, utils_1.logError)("Port ".concat(portNumber_1, " is already in use. Please use a different port with --port option."));
210
+ (0, utils_1.logError)("Port ".concat(portNumber, " is already in use. Use --port to specify a different port."));
178
211
  process.exit(1);
179
212
  }
180
- process.env.PORT = portNumber_1.toString();
213
+ process.env.PORT = port;
181
214
  if (!!options.noproxy) return [3 /*break*/, 4];
182
- if (!config['api-key']) {
215
+ if (!config['api-key'])
183
216
  throw new Error("'api-key' is required when using development proxy");
184
- }
185
- return [4 /*yield*/, (0, utils_1.setupProxy)(options.port, config['api-key'], config)];
217
+ return [4 /*yield*/, (0, utils_1.setupProxy)(port, config['api-key'], config)];
186
218
  case 3:
187
219
  proxySetup = _a.sent();
188
220
  proxyServer = proxySetup.client;
@@ -190,106 +222,33 @@ function dev(options) {
190
222
  _a.label = 4;
191
223
  case 4:
192
224
  if (!(runtime === 'node')) return [3 /*break*/, 5];
193
- // Existing Node.js development process
194
- startProcess(command, { env: __assign(__assign({}, process.env), envVars) });
225
+ startProcess(mainFile, envVars);
195
226
  watchPaths = [
196
- path_1.default.dirname(config['main-file']),
197
- config['static-dir']
198
- ? path_1.default.join(process.cwd(), config['static-dir'])
199
- : (0, utils_1.getStaticFilesPath)(),
200
- ];
201
- watcher = chokidar_1.default.watch(watchPaths, {
202
- ignored: /(^|[\/\\])\../, // ignore dotfiles
203
- persistent: true,
204
- });
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);
208
- });
227
+ path_1.default.dirname(mainFile),
228
+ config['static-dir'] ? path_1.default.join(process.cwd(), config['static-dir']) : (0, utils_1.getStaticFilesPath)(),
229
+ ].filter(function (p) { return fs_extra_1.default.existsSync(p); });
230
+ watcher = chokidar_1.default.watch(watchPaths, { ignored: /(^|[\/\\])\./, persistent: true, ignoreInitial: true });
231
+ watcher.on('change', function (changedPath) { (0, utils_1.logInfo)("File ".concat(changedPath, " changed. Restarting...")); startProcess(mainFile, envVars, true); });
209
232
  (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
233
  return [3 /*break*/, 8];
263
234
  case 5:
264
235
  if (!(runtime === 'workers')) return [3 /*break*/, 7];
265
236
  dainDir = path_1.default.join(process.cwd(), '.dain');
266
237
  outFile = path_1.default.join(dainDir, path_1.default.basename(config['main-file'], '.ts') + '.mjs');
267
- // Start the build process in watch mode
268
238
  return [4 /*yield*/, (0, build_1.default)({ config: options.config, runtime: 'workers', watch: true })];
269
239
  case 6:
270
- // Start the build process in watch mode
271
240
  _a.sent();
272
- MFconfig_1 = {
273
- scriptPath: outFile,
274
- modules: true,
275
- port: parseInt(options.port),
276
- log: new miniflare_1.Log(miniflare_1.LogLevel.DEBUG),
277
- liveReload: true,
278
- };
241
+ MFconfig_1 = { scriptPath: outFile, modules: true, port: parseInt(port, 10), log: new miniflare_1.Log(miniflare_1.LogLevel.DEBUG), liveReload: true };
279
242
  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) {
243
+ (0, utils_1.logSuccess)("Miniflare server started on port ".concat(port));
244
+ debounceTimer_1 = null;
245
+ fs_extra_1.default.watch(dainDir, { recursive: true }, function (_eventType, filename) {
246
+ if (debounceTimer_1)
284
247
  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
- });
248
+ debounceTimer_1 = setTimeout(function () { if (mf) {
249
+ mf.setOptions(MFconfig_1);
250
+ (0, utils_1.logInfo)("Build updated (".concat(filename, ")"));
251
+ } }, 300);
293
252
  });
294
253
  (0, utils_1.logInfo)('Watching for file changes in source and build directories...');
295
254
  return [3 /*break*/, 8];
@@ -298,12 +257,7 @@ function dev(options) {
298
257
  case 9:
299
258
  error_1 = _a.sent();
300
259
  (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);
260
+ gracefulShutdown(1);
307
261
  return [3 /*break*/, 10];
308
262
  case 10: return [2 /*return*/];
309
263
  }
@@ -13,25 +13,19 @@ function init(projectName) {
13
13
  var projectDir = path_1.default.join(process.cwd(), projectName);
14
14
  var templateDir = path_1.default.join(__dirname, '..', '..', 'templates', 'default');
15
15
  try {
16
- // Check Node.js version
17
- var nodeVersion = process.version;
18
- var versionNum = Number(nodeVersion.slice(1).split('.')[0]);
19
- if (versionNum < 20) {
16
+ var nodeVersion = Number(process.version.slice(1).split('.')[0]);
17
+ if (nodeVersion < 20) {
20
18
  spinner.fail('Node.js version 20.7 or higher is required');
21
19
  (0, utils_1.logError)('Please upgrade Node.js to version 20.7 or higher');
22
20
  (0, utils_1.logInfo)('You can download it from: https://nodejs.org/');
23
21
  process.exit(1);
24
22
  }
25
- // Check if directory already exists
26
23
  if (fs_extra_1.default.existsSync(projectDir)) {
27
24
  spinner.fail("Directory ".concat(projectName, " already exists"));
28
25
  process.exit(1);
29
26
  }
30
- // Create project directory
31
27
  fs_extra_1.default.ensureDirSync(projectDir);
32
- // Copy template files
33
28
  fs_extra_1.default.copySync(templateDir, projectDir);
34
- // Modify package.json
35
29
  var packageJsonPath = path_1.default.join(projectDir, 'package.json');
36
30
  var packageJson = fs_extra_1.default.readJsonSync(packageJsonPath);
37
31
  packageJson.name = projectName;
@@ -42,7 +36,6 @@ function init(projectName) {
42
36
  (0, utils_1.logInfo)(" cd ".concat(projectName));
43
37
  (0, utils_1.logInfo)(' npm install');
44
38
  (0, utils_1.logInfo)(' npm run dev');
45
- // Explicitly exit with success
46
39
  process.exit(0);
47
40
  }
48
41
  catch (error) {
@@ -53,123 +53,129 @@ Object.defineProperty(exports, "__esModule", { value: true });
53
53
  exports.default = logs;
54
54
  var ora_1 = __importDefault(require("ora"));
55
55
  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; }
60
- return __generator(this, function (_b) {
61
- switch (_b.label) {
56
+ var watchInterval = null;
57
+ var isShuttingDown = false;
58
+ function cleanup() {
59
+ isShuttingDown = true;
60
+ if (watchInterval) {
61
+ clearInterval(watchInterval);
62
+ watchInterval = null;
63
+ }
64
+ }
65
+ function logs(options) {
66
+ return __awaiter(this, void 0, void 0, function () {
67
+ var config, orgId, apiKey, deploymentId, serviceId, logsUrl, spinner, result, error_1;
68
+ var _this = this;
69
+ return __generator(this, function (_a) {
70
+ switch (_a.label) {
62
71
  case 0:
63
72
  config = (0, utils_1.getDainConfig)(options.config);
64
- orgId = "hackathon";
65
- _a = initializeConfig(config, orgId), apiKey = _a.apiKey, deploymentId = _a.deploymentId, logsUrl = _a.logsUrl;
66
- if (!orgId || !deploymentId) {
67
- (0, utils_1.logError)("Org ID or deployment ID not found");
68
- return [2 /*return*/];
73
+ orgId = (0, utils_1.resolveOrgId)(config);
74
+ apiKey = config["api-key"];
75
+ deploymentId = config["deployment-id"];
76
+ serviceId = config["service-id"];
77
+ if (!orgId) {
78
+ (0, utils_1.logError)("Org ID not found. Ensure your API key or DAIN_ORG_ID is set.");
79
+ process.exit(1);
80
+ }
81
+ if (!deploymentId || !serviceId) {
82
+ (0, utils_1.logError)("Deployment ID or service ID not found");
83
+ process.exit(1);
69
84
  }
85
+ if (!apiKey) {
86
+ (0, utils_1.logError)("API key not found");
87
+ process.exit(1);
88
+ }
89
+ process.once("SIGINT", function () { cleanup(); process.exit(0); });
90
+ process.once("SIGTERM", function () { cleanup(); process.exit(0); });
91
+ logsUrl = (0, utils_1.buildPlatformUrl)(config, orgId, "logs");
70
92
  spinner = (0, ora_1.default)("Fetching logs for project ".concat(config["project-id"], "...")).start();
71
- _b.label = 1;
93
+ _a.label = 1;
72
94
  case 1:
73
- _b.trys.push([1, 3, 4, 5]);
74
- result = null;
95
+ _a.trys.push([1, 3, , 4]);
75
96
  return [4 /*yield*/, fetchLogs(logsUrl, apiKey)];
76
97
  case 2:
77
- 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));
98
+ result = _a.sent();
99
+ spinner.stop();
100
+ (0, utils_1.logInfo)("Project logs: ".concat(formatProjectLogs(result, deploymentId)));
84
101
  if (options.watch) {
85
- setTimeout(function () { return logs(options, true); }, 10000);
102
+ (0, utils_1.logInfo)("Watching for log updates (Ctrl+C to stop)...");
103
+ watchInterval = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
104
+ var newResult, error_2;
105
+ return __generator(this, function (_a) {
106
+ switch (_a.label) {
107
+ case 0:
108
+ if (isShuttingDown)
109
+ return [2 /*return*/];
110
+ _a.label = 1;
111
+ case 1:
112
+ _a.trys.push([1, 3, , 4]);
113
+ return [4 /*yield*/, fetchLogs(logsUrl, apiKey)];
114
+ case 2:
115
+ newResult = _a.sent();
116
+ process.stdout.write("\x1Bc");
117
+ (0, utils_1.logInfo)("Project logs: ".concat(formatProjectLogs(newResult, deploymentId)));
118
+ return [3 /*break*/, 4];
119
+ case 3:
120
+ error_2 = _a.sent();
121
+ (0, utils_1.logError)("Error fetching logs", error_2);
122
+ return [3 /*break*/, 4];
123
+ case 4: return [2 /*return*/];
124
+ }
125
+ });
126
+ }); }, 10000);
86
127
  }
87
- if (!options.watch) {
128
+ else {
88
129
  process.exit(0);
89
130
  }
90
- return [3 /*break*/, 5];
131
+ return [3 /*break*/, 4];
91
132
  case 3:
92
- error_1 = _b.sent();
93
- 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*/];
133
+ error_1 = _a.sent();
134
+ spinner.fail("Failed to retrieve project logs.");
135
+ (0, utils_1.logError)("Error during log fetch", error_1);
136
+ process.exit(1);
137
+ return [3 /*break*/, 4];
138
+ case 4: return [2 /*return*/];
99
139
  }
100
140
  });
101
141
  });
102
142
  }
103
- var initializeConfig = function (config, orgId) {
104
- var baseUrl = config["platform-base-url"] || "https://codegen-deploy-service.dainapp.com/";
105
- var apiKey = config["api-key"];
106
- var deploymentId = config["deployment-id"];
107
- var environment = config["environment"];
108
- var serviceId = config["service-id"];
109
- 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 };
111
- };
112
- var fetchLogs = function (logsUrl, apiKey) { return __awaiter(void 0, void 0, void 0, function () {
113
- var response;
114
- return __generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0: return [4 /*yield*/, fetch(logsUrl, {
117
- method: "GET",
118
- headers: {
119
- "Content-Type": "application/json",
120
- "X-DAIN-SIGNATORY-ADDRESS": "TODO: X-DAIN-SIGNATORY-ADDRESS",
121
- "X-DAIN-SIGNATURE": "TODO: X-DAIN-SIGNATORY-SIGNATURE",
122
- Authorization: "Bearer ".concat(apiKey),
123
- },
124
- })];
125
- case 1:
126
- response = _a.sent();
127
- if (!response.ok) {
128
- throw new Error("Log fetch failed: ".concat(response.statusText));
129
- }
130
- return [4 /*yield*/, response.json()];
131
- case 2: return [2 /*return*/, _a.sent()];
132
- }
143
+ function fetchLogs(url, apiKey) {
144
+ return __awaiter(this, void 0, void 0, function () {
145
+ var response;
146
+ return __generator(this, function (_a) {
147
+ switch (_a.label) {
148
+ case 0: return [4 /*yield*/, (0, utils_1.fetchWithTimeout)(url, {
149
+ method: "GET",
150
+ headers: { "Content-Type": "application/json", Authorization: "Bearer ".concat(apiKey) },
151
+ })];
152
+ case 1:
153
+ response = _a.sent();
154
+ if (!response.ok) {
155
+ throw new Error("Log fetch failed: ".concat(response.status, " ").concat(response.statusText));
156
+ }
157
+ return [2 /*return*/, response.json()];
158
+ }
159
+ });
133
160
  });
134
- }); };
135
- var handleError = function (spinner, error) {
136
- spinner.fail("Failed to retrieve project logs.");
137
- (0, utils_1.logError)("Error during log fetch", error);
138
- };
139
- var formatProjectLogs = function (projectLogs, deploymentId) {
161
+ }
162
+ function formatProjectLogs(projectLogs, deploymentId) {
140
163
  try {
141
164
  var _a = projectLogs.logs, logs_1 = _a === void 0 ? "" : _a, metadata = __rest(projectLogs, ["logs"]);
142
- var formatDate_1 = function (dateString) {
143
- try {
144
- return new Date(dateString).toLocaleString();
145
- }
146
- catch (_a) {
147
- return dateString;
148
- }
149
- };
150
165
  var formattedMetadata = Object.entries(metadata)
151
166
  .map(function (_a) {
152
167
  var _b;
153
168
  var key = _a[0], value = _a[1];
154
169
  var formattedValue = ((_b = value === null || value === void 0 ? void 0 : value.includes) === null || _b === void 0 ? void 0 : _b.call(value, "T"))
155
- ? formatDate_1(value)
170
+ ? new Date(value).toLocaleString()
156
171
  : value;
157
- var formattedKey = key.replace(/([A-Z])/g, " $1").toLowerCase();
158
- return "\u001B[36m".concat(formattedKey, ":\u001B[0m ").concat(formattedValue);
172
+ return "\u001B[36m".concat(key.replace(/([A-Z])/g, " $1").toLowerCase(), ":\u001B[0m ").concat(formattedValue);
159
173
  })
160
174
  .join("\n");
161
175
  var projectUrl = "\nurl: https://".concat(deploymentId.replace("codegen-", ""), "-agent.dainapp.com");
162
- var output = [
163
- "\n",
164
- "\x1b[1m=== Project ===\x1b[0m",
165
- formattedMetadata,
166
- projectUrl,
167
- "\n\x1b[1m=== Logs ===\x1b[0m",
168
- logs_1,
169
- ];
170
- return output.join("\n");
176
+ return ["\n", "\x1b[1m=== Project ===\x1b[0m", formattedMetadata, projectUrl, "\n\x1b[1m=== Logs ===\x1b[0m", logs_1].join("\n");
171
177
  }
172
178
  catch (error) {
173
179
  return "Error formatting logs: ".concat(error.message);
174
180
  }
175
- };
181
+ }
@@ -1,14 +1,25 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.default = start;
4
7
  var child_process_1 = require("child_process");
8
+ var fs_1 = __importDefault(require("fs"));
9
+ var path_1 = __importDefault(require("path"));
5
10
  var utils_1 = require("../utils");
6
11
  function start(options) {
12
+ var config = (0, utils_1.getDainConfig)();
7
13
  process.env.PORT = options.port;
8
- var command = "node ".concat((0, utils_1.getDainConfig)()['main-file']);
9
- var child = (0, child_process_1.spawn)('node', [(0, utils_1.getDainConfig)()['main-file']], {
10
- stdio: 'inherit' // This pipes stdout/stderr directly to parent process
11
- });
14
+ var mainFile = config['main-file'];
15
+ var outDir = config['out-dir'] || 'dist';
16
+ var outputFile = path_1.default.join(process.cwd(), outDir, "".concat(path_1.default.basename(mainFile, path_1.default.extname(mainFile)), ".js"));
17
+ var entryFile = fs_1.default.existsSync(outputFile) ? outputFile : mainFile;
18
+ if (entryFile === mainFile && mainFile.endsWith('.ts')) {
19
+ (0, utils_1.logError)("Build output not found: ".concat(outputFile, ". Run \"dain build\" first."));
20
+ process.exit(1);
21
+ }
22
+ var child = (0, child_process_1.spawn)('node', [entryFile], { stdio: 'inherit' });
12
23
  child.on('error', function (error) {
13
24
  console.error("Error: ".concat(error.message));
14
25
  process.exit(1);