@dainprotocol/cli 1.0.43 → 1.0.45

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.
package/README.md CHANGED
@@ -15,3 +15,71 @@ npm install @dainprotocol/cli -g
15
15
  For detailed documentation, usage guides, and additional information, please visit:
16
16
  [https://docs.dain.org](https://docs.dain.org)
17
17
 
18
+ ## Usage
19
+
20
+ ```bash
21
+ dain --help
22
+ ```
23
+
24
+ ## Init
25
+
26
+ ```bash
27
+ dain init <project-name>
28
+ ```
29
+
30
+ The following commands require a dain.json file to be present in the root of the project with the following structure:
31
+
32
+ ```json
33
+ {
34
+ "out-dir": "your-build-output-directory(build/dist)",
35
+ "main-file": "your-main-file.(ts/js)",
36
+ "deployment-id": "your deploymentId that you will have after the deploy",
37
+ "api-key": "your-api-key"
38
+ }
39
+ ```
40
+
41
+ ## Build
42
+
43
+ ```bash
44
+ dain build
45
+ ```
46
+
47
+ ## Dev
48
+
49
+ ```bash
50
+ dain dev
51
+ ```
52
+
53
+ ### Deploy
54
+
55
+ An .env file must be present in the root of the project with the following variables:
56
+
57
+ ```bash
58
+ DAIN_API_KEY=your_api_key
59
+ ```
60
+
61
+ To deploy the project, run the following command:
62
+
63
+ ```bash
64
+ dain deploy
65
+ ```
66
+
67
+ ### Status
68
+
69
+ ```bash
70
+ dain status
71
+ ```
72
+
73
+ ### Logs
74
+
75
+ ```bash
76
+ dain logs [-w|--watch]
77
+ ```
78
+
79
+ The `-w` or `--watch` parameter allows you to monitor logs in real time.
80
+
81
+ ### Undeploy
82
+
83
+ ```bash
84
+ dain undeploy
85
+ ```
@@ -77,7 +77,7 @@ function build(options) {
77
77
  spinner = (0, ora_1.default)('Building project...').start();
78
78
  config = (0, utils_1.getDainConfig)(options.config);
79
79
  runtime = options.runtime || config.runtime || 'node';
80
- outDir = config['out-dir'] || 'build';
80
+ outDir = path_1.default.join(process.cwd(), config['out-dir'] || 'build');
81
81
  dainDir = path_1.default.join(process.cwd(), '.dain');
82
82
  _a.label = 1;
83
83
  case 1:
@@ -91,13 +91,13 @@ function build(options) {
91
91
  entryPoints: [config['main-file']],
92
92
  bundle: true,
93
93
  sourcemap: true,
94
- outdir: options.watch ? dainDir : outDir,
94
+ outdir: outDir,
95
95
  };
96
96
  if (runtime === 'node') {
97
97
  // Node.js build process
98
98
  Object.assign(buildOptions, {
99
99
  platform: 'node',
100
- target: 'node14',
100
+ target: 'es2020',
101
101
  minify: !options.watch,
102
102
  });
103
103
  }
@@ -140,16 +140,16 @@ function build(options) {
140
140
  return [4 /*yield*/, fs_extra_1.default.copy(staticDir, staticOutDir)];
141
141
  case 9:
142
142
  _a.sent();
143
- (0, utils_1.logInfo)("Static files copied to ".concat(staticOutDir));
143
+ spinner.info("Static files copied to ".concat(staticOutDir));
144
144
  return [3 /*break*/, 11];
145
145
  case 10:
146
- (0, utils_1.logInfo)('No static directory found. Skipping static file copy.');
146
+ spinner.info('No static directory found. Skipping static file copy.');
147
147
  _a.label = 11;
148
148
  case 11:
149
- spinner.succeed('Build completed successfully.');
150
- (0, utils_1.logSuccess)("Project built and ready for ".concat(runtime, " runtime in ").concat(options.watch ? dainDir : outDir, "."));
149
+ spinner.info('Build completed successfully.');
150
+ spinner.info("Project built and ready for ".concat(runtime, " runtime in ").concat(options.watch ? dainDir : outDir, "."));
151
151
  // Explicitly exit with success if not in watch mode
152
- if (!options.watch) {
152
+ if (!options.watch && !options.deploy) {
153
153
  process.exit(0);
154
154
  }
155
155
  return [3 /*break*/, 13];
@@ -40,89 +40,190 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.default = deploy;
43
- var build_1 = __importDefault(require("./build"));
44
43
  var utils_1 = require("../utils");
45
44
  var ora_1 = __importDefault(require("ora"));
46
45
  var fs_extra_1 = __importDefault(require("fs-extra"));
47
46
  var path_1 = __importDefault(require("path"));
47
+ var archiver_1 = __importDefault(require("archiver"));
48
+ var build_1 = __importDefault(require("./build"));
49
+ var status_1 = __importDefault(require("./status"));
50
+ var START_DEPLOY_URI = '/api/app/data/deployments/start-deploy';
48
51
  function deploy(options) {
49
52
  return __awaiter(this, void 0, void 0, function () {
50
- var config, spinner, outDir_1, platformBaseUrl, deployUrl, files, deployFiles, deployData, response, result, error_1;
51
- var _this = this;
53
+ var config, spinner, basePath, deployPath, envArray, result, deploymentId, error_1;
52
54
  return __generator(this, function (_a) {
53
55
  switch (_a.label) {
54
56
  case 0:
55
57
  config = (0, utils_1.getDainConfig)(options.config);
56
- // disable for now only availible for internal testing for now
57
- (0, utils_1.logError)("Deployment is not supported for now. Only available for internal testing.");
58
- return [2 /*return*/, process.exit(1)];
58
+ spinner = (0, ora_1.default)('Deploying project...').start();
59
+ basePath = config['api-base-url'] || 'https://dain-platform-ochre.vercel.app';
60
+ deployPath = "".concat(basePath).concat(START_DEPLOY_URI);
61
+ _a.label = 1;
59
62
  case 1:
60
- _a.trys.push([1, 7, , 8]);
61
- // First, build the project
62
- return [4 /*yield*/, (0, build_1.default)({ config: options.config })];
63
+ _a.trys.push([1, 6, , 7]);
64
+ return [4 /*yield*/, loadAndValidateEnvVariables()];
63
65
  case 2:
64
- // First, build the project
65
- _a.sent();
66
- outDir_1 = config['out-dir'] || 'build';
67
- platformBaseUrl = config['platform-base-url'] || 'https://platform.dain.org';
68
- deployUrl = "".concat(platformBaseUrl, "/api/platform-api/v1/service/deploy");
69
- return [4 /*yield*/, fs_extra_1.default.readdir(outDir_1)];
66
+ envArray = _a.sent();
67
+ return [4 /*yield*/, (0, build_1.default)({ config: options.config, deploy: true })];
70
68
  case 3:
71
- files = _a.sent();
72
- return [4 /*yield*/, Promise.all(files.map(function (file) { return __awaiter(_this, void 0, void 0, function () {
73
- var fileType, content;
74
- return __generator(this, function (_a) {
75
- switch (_a.label) {
76
- case 0:
77
- fileType = path_1.default.extname(file).slice(1);
78
- if (!['js', 'mjs', 'wasm'].includes(fileType)) return [3 /*break*/, 2];
79
- return [4 /*yield*/, fs_extra_1.default.readFile(path_1.default.join(outDir_1, file), 'utf-8')];
80
- case 1:
81
- content = _a.sent();
82
- return [2 /*return*/, {
83
- name: file,
84
- content: content,
85
- type: fileType,
86
- }];
87
- case 2: return [2 /*return*/, null];
88
- }
89
- });
90
- }); })).then(function (files) { return files.filter(Boolean); })];
69
+ _a.sent();
70
+ return [4 /*yield*/, deployAndPushFiles(deployPath, envArray)];
91
71
  case 4:
92
- deployFiles = _a.sent();
93
- deployData = {
94
- serviceIdentifer: config['project-id'],
95
- files: deployFiles,
96
- };
97
- return [4 /*yield*/, fetch(deployUrl, {
72
+ result = _a.sent();
73
+ deploymentId = result.deploymentId.replace('codegen-', '');
74
+ return [4 /*yield*/, recursiveStatusUntilRunning(JSON.stringify(config), deploymentId)];
75
+ case 5:
76
+ _a.sent();
77
+ console.log('\n-----------------------');
78
+ spinner.succeed("Deployment URL: ".concat(result.service.url));
79
+ spinner.succeed("Deployment ID: ".concat(result.deploymentId));
80
+ spinner.succeed('Deployment completed at: ' + new Date().toISOString());
81
+ spinner.succeed('Deployment completed successfully.');
82
+ spinner.info('You can access logs using `dain logs -w` command.');
83
+ console.log('-----------------------');
84
+ process.exit(0);
85
+ return [3 /*break*/, 7];
86
+ case 6:
87
+ error_1 = _a.sent();
88
+ spinner.fail('Deployment failed.');
89
+ (0, utils_1.logError)('Error during deployment: ', error_1);
90
+ process.exit(1);
91
+ return [3 /*break*/, 7];
92
+ case 7: return [2 /*return*/];
93
+ }
94
+ });
95
+ });
96
+ }
97
+ // Loads and validates environment variables
98
+ function loadAndValidateEnvVariables() {
99
+ return __awaiter(this, void 0, void 0, function () {
100
+ var envArray;
101
+ return __generator(this, function (_a) {
102
+ switch (_a.label) {
103
+ case 0: return [4 /*yield*/, loadEnvVariables()];
104
+ case 1:
105
+ envArray = _a.sent();
106
+ if (envArray.length === 0) {
107
+ (0, utils_1.logError)('No environment variables found. Please ensure your .env file is correctly set up.');
108
+ process.exit(1);
109
+ }
110
+ if (!envArray.some(function (env) { return env.name === 'DAIN_API_KEY'; })) {
111
+ (0, utils_1.logError)('DAIN_API_KEY not found in environment variables. Please check your .env file.');
112
+ process.exit(1);
113
+ }
114
+ return [2 /*return*/, envArray];
115
+ }
116
+ });
117
+ });
118
+ }
119
+ // Deploys and pushes files to the platform
120
+ function deployAndPushFiles(startDeployUrl, envArray) {
121
+ return __awaiter(this, void 0, void 0, function () {
122
+ var projectZip, projectZipBuffer, formData, response, errorText, result, error_2;
123
+ return __generator(this, function (_a) {
124
+ switch (_a.label) {
125
+ case 0: return [4 /*yield*/, zipDirectory('./', 'project.zip')];
126
+ case 1:
127
+ projectZip = _a.sent();
128
+ return [4 /*yield*/, fs_extra_1.default.readFile(projectZip)];
129
+ case 2:
130
+ projectZipBuffer = _a.sent();
131
+ formData = new FormData();
132
+ formData.append('array', JSON.stringify(envArray));
133
+ formData.append('file', new Blob([projectZipBuffer]), 'project.zip');
134
+ _a.label = 3;
135
+ case 3:
136
+ _a.trys.push([3, 8, , 9]);
137
+ return [4 /*yield*/, fetch(startDeployUrl, {
98
138
  method: 'POST',
99
- headers: {
100
- 'Content-Type': 'application/json',
101
- "X-DAIN-SIGNATORY-ADDRESS": "TODO: X-DAIN-SIGNATORY-ADDRESS",
102
- "X-DAIN-SIGNATURE": "TODO: X-DAIN-SIGNATORY-SIGNATURE",
103
- },
104
- body: JSON.stringify(deployData),
139
+ body: formData,
105
140
  })];
106
- case 5:
141
+ case 4:
107
142
  response = _a.sent();
108
- if (!response.ok) {
109
- throw new Error("Deployment failed: ".concat(response.statusText));
110
- }
111
- return [4 /*yield*/, response.json()];
112
- case 6:
113
- result = _a.sent();
114
- (0, utils_1.logSuccess)("Deployment completed successfully.");
115
- spinner.succeed("Deployment completed successfully.");
116
- (0, utils_1.logInfo)("Deployment result: ".concat(JSON.stringify(result, null, 2)));
117
- return [3 /*break*/, 8];
143
+ if (!!response.ok) return [3 /*break*/, 6];
144
+ return [4 /*yield*/, response.text()];
145
+ case 5:
146
+ errorText = _a.sent();
147
+ throw new Error("Deployment failed: ".concat(response.statusText, ". Response: ").concat(errorText));
148
+ case 6: return [4 /*yield*/, response.json()];
118
149
  case 7:
119
- error_1 = _a.sent();
120
- spinner.fail("Deployment failed.");
121
- (0, utils_1.logError)("Error during deployment", error_1);
150
+ result = _a.sent();
151
+ return [2 /*return*/, result];
152
+ case 8:
153
+ error_2 = _a.sent();
154
+ (0, utils_1.logError)('Error during deployment and push files: ', error_2.stack);
155
+ console.error('Detailed error:', error_2);
122
156
  process.exit(1);
123
- return [3 /*break*/, 8];
124
- case 8: return [2 /*return*/];
157
+ return [3 /*break*/, 9];
158
+ case 9: return [2 /*return*/];
159
+ }
160
+ });
161
+ });
162
+ }
163
+ // Reads the .env file and returns an array of key-value pairs
164
+ function loadEnvVariables() {
165
+ return __awaiter(this, void 0, void 0, function () {
166
+ var files, envFile, envContent;
167
+ return __generator(this, function (_a) {
168
+ switch (_a.label) {
169
+ case 0: return [4 /*yield*/, fs_extra_1.default.readdir('./')];
170
+ case 1:
171
+ files = _a.sent();
172
+ envFile = files.find(function (file) { return file === '.env'; });
173
+ if (!envFile) {
174
+ (0, utils_1.logError)('Environment file not found. Please create a .env file in the build directory.');
175
+ process.exit(1);
176
+ }
177
+ return [4 /*yield*/, fs_extra_1.default.readFile(path_1.default.join('./', envFile), 'utf-8')];
178
+ case 2:
179
+ envContent = _a.sent();
180
+ return [2 /*return*/, envContent
181
+ .split('\n')
182
+ .map(function (line) {
183
+ var _a = line.split('='), name = _a[0], value = _a[1];
184
+ return { name: name, value: value };
185
+ })
186
+ .filter(function (env) { return env.name && env.value; })];
125
187
  }
126
188
  });
127
189
  });
128
190
  }
191
+ // Zips the current directory and returns the path to the zip file
192
+ function zipDirectory(sourceDir, outputZip) {
193
+ return __awaiter(this, void 0, void 0, function () {
194
+ return __generator(this, function (_a) {
195
+ return [2 /*return*/, new Promise(function (resolve, reject) {
196
+ var output = fs_extra_1.default.createWriteStream(outputZip);
197
+ var archive = (0, archiver_1.default)('zip', { zlib: { level: 9 } });
198
+ output.on('close', function () { return resolve(outputZip); });
199
+ archive.on('error', function (err) {
200
+ (0, utils_1.logError)('Error during zipping the directory: ', err);
201
+ reject(err);
202
+ });
203
+ archive.pipe(output);
204
+ archive.glob('**/*', { ignore: ['node_modules/**', 'project.zip'] });
205
+ archive.finalize();
206
+ })];
207
+ });
208
+ });
209
+ }
210
+ var recursiveStatusUntilRunning = function (config, deploymentId) { return __awaiter(void 0, void 0, void 0, function () {
211
+ var statusResult;
212
+ return __generator(this, function (_a) {
213
+ switch (_a.label) {
214
+ case 0: return [4 /*yield*/, (0, status_1.default)({}, deploymentId)];
215
+ case 1:
216
+ statusResult = _a.sent();
217
+ if (statusResult.status === 'RUNNING') {
218
+ return [2 /*return*/];
219
+ }
220
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
221
+ case 2:
222
+ _a.sent();
223
+ return [4 /*yield*/, recursiveStatusUntilRunning(config, deploymentId)];
224
+ case 3:
225
+ _a.sent();
226
+ return [2 /*return*/];
227
+ }
228
+ });
229
+ }); };
@@ -106,16 +106,16 @@ function dev(options) {
106
106
  switch (_a.label) {
107
107
  case 0:
108
108
  config = (0, utils_1.getDainConfig)(options.config);
109
- console.log("Config: " + JSON.stringify(config));
109
+ console.log('Config: ' + JSON.stringify(config));
110
110
  runtime = options.runtime || config.runtime || 'node';
111
- console.log("Runtime: " + runtime);
112
- command = "ts-node ".concat(config['main-file']);
111
+ console.log('Runtime: ' + runtime);
112
+ command = "./node_modules/.bin/ts-node ".concat(config['main-file']);
113
113
  envVars = {
114
114
  PORT: options.port,
115
115
  DAIN_API_KEY: config['api-key'],
116
116
  DAIN_PROJECT_ID: config['project-id'],
117
117
  DAIN_ENVIRONMENT: config['environment'],
118
- DAIN_OUT_DIR: config['out-dir']
118
+ DAIN_OUT_DIR: config['out-dir'],
119
119
  };
120
120
  proxyServer = null;
121
121
  _a.label = 1;
@@ -135,11 +135,13 @@ function dev(options) {
135
135
  startProcess(command, envVars);
136
136
  watchPaths = [
137
137
  path_1.default.dirname(config['main-file']),
138
- config['static-dir'] ? path_1.default.join(process.cwd(), config['static-dir']) : (0, utils_1.getStaticFilesPath)()
138
+ config['static-dir']
139
+ ? path_1.default.join(process.cwd(), config['static-dir'])
140
+ : (0, utils_1.getStaticFilesPath)(),
139
141
  ];
140
142
  watcher = chokidar_1.default.watch(watchPaths, {
141
143
  ignored: /(^|[\/\\])\../, // ignore dotfiles
142
- persistent: true
144
+ persistent: true,
143
145
  });
144
146
  watcher.on('change', function (path) {
145
147
  (0, utils_1.logInfo)("File ".concat(path, " has been changed. Restarting..."));
@@ -204,7 +206,7 @@ function dev(options) {
204
206
  dainDir = path_1.default.join(process.cwd(), '.dain');
205
207
  outFile = path_1.default.join(dainDir, path_1.default.basename(config['main-file'], '.ts') + '.mjs');
206
208
  // Start the build process in watch mode
207
- return [4 /*yield*/, (0, build_1.default)({ config: options.config, runtime: 'workers', watch: true, })];
209
+ return [4 /*yield*/, (0, build_1.default)({ config: options.config, runtime: 'workers', watch: true })];
208
210
  case 5:
209
211
  // Start the build process in watch mode
210
212
  _a.sent();
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = help;
4
+ function help() {
5
+ console.log("\n Usage: dain [command] [options]\n\n Options:\n -w, --watch monitor logs in real time\n\n Commands:\n init initialize the project\n build build the project\n dev run the project in development mode\n deploy deploy the project\n status display the project status\n logs [-w|--watch] monitor logs in real time\n undeploy undeploy the project\n ");
6
+ process.exit(0);
7
+ }
@@ -0,0 +1,174 @@
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 __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __rest = (this && this.__rest) || function (s, e) {
39
+ var t = {};
40
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
41
+ t[p] = s[p];
42
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
43
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
44
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
45
+ t[p[i]] = s[p[i]];
46
+ }
47
+ return t;
48
+ };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
52
+ Object.defineProperty(exports, "__esModule", { value: true });
53
+ exports.default = logs;
54
+ var ora_1 = __importDefault(require("ora"));
55
+ var utils_1 = require("../utils");
56
+ function logs(options_1) {
57
+ return __awaiter(this, arguments, void 0, function (options, isWatching) {
58
+ var config, _a, apiKey, deploymentId, logsUrl, orgId, spinner, result, formatLogs, error_1;
59
+ if (isWatching === void 0) { isWatching = false; }
60
+ return __generator(this, function (_b) {
61
+ switch (_b.label) {
62
+ case 0:
63
+ config = (0, utils_1.getDainConfig)(options.config);
64
+ _a = initializeConfig(config), apiKey = _a.apiKey, deploymentId = _a.deploymentId, logsUrl = _a.logsUrl;
65
+ orgId = 'hackathon';
66
+ if (!orgId || !deploymentId) {
67
+ (0, utils_1.logError)('Org ID or deployment ID not found');
68
+ return [2 /*return*/];
69
+ }
70
+ spinner = (0, ora_1.default)("Fetching logs for project ".concat(config['project-id'], "...")).start();
71
+ _b.label = 1;
72
+ case 1:
73
+ _b.trys.push([1, 3, 4, 5]);
74
+ result = null;
75
+ return [4 /*yield*/, fetchLogs(logsUrl, apiKey)];
76
+ 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));
84
+ if (options.watch) {
85
+ setTimeout(function () { return logs(options, true); }, 10000);
86
+ }
87
+ if (!options.watch) {
88
+ process.exit(0);
89
+ }
90
+ return [3 /*break*/, 5];
91
+ 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*/];
99
+ }
100
+ });
101
+ });
102
+ }
103
+ var initializeConfig = function (config) {
104
+ var baseUrl = config['platform-base-url'] || 'https://codegen-deploy-service.dainapp.com/';
105
+ var apiKey = config['api-key'];
106
+ var orgId = (0, utils_1.extractOrgId)(apiKey);
107
+ var deploymentId = config['deployment-id'];
108
+ var logsUrl = "".concat(baseUrl, "/codegen-deploy/logs/").concat(orgId, "/").concat(deploymentId);
109
+ return { baseUrl: baseUrl, apiKey: apiKey, orgId: orgId, deploymentId: deploymentId, logsUrl: logsUrl };
110
+ };
111
+ var fetchLogs = function (logsUrl, apiKey) { return __awaiter(void 0, void 0, void 0, function () {
112
+ var response;
113
+ return __generator(this, function (_a) {
114
+ switch (_a.label) {
115
+ case 0: return [4 /*yield*/, fetch(logsUrl, {
116
+ method: 'GET',
117
+ headers: {
118
+ 'Content-Type': 'application/json',
119
+ 'X-DAIN-SIGNATORY-ADDRESS': 'TODO: X-DAIN-SIGNATORY-ADDRESS',
120
+ 'X-DAIN-SIGNATURE': 'TODO: X-DAIN-SIGNATORY-SIGNATURE',
121
+ Authorization: "Bearer ".concat(apiKey),
122
+ },
123
+ })];
124
+ case 1:
125
+ response = _a.sent();
126
+ if (!response.ok) {
127
+ throw new Error("Log fetch failed: ".concat(response.statusText));
128
+ }
129
+ return [4 /*yield*/, response.json()];
130
+ case 2: return [2 /*return*/, _a.sent()];
131
+ }
132
+ });
133
+ }); };
134
+ var handleError = function (spinner, error) {
135
+ spinner.fail('Failed to retrieve project logs.');
136
+ (0, utils_1.logError)('Error during log fetch', error);
137
+ };
138
+ var formatProjectLogs = function (projectLogs, deploymentId) {
139
+ try {
140
+ var _a = projectLogs.logs, logs_1 = _a === void 0 ? '' : _a, metadata = __rest(projectLogs, ["logs"]);
141
+ var formatDate_1 = function (dateString) {
142
+ try {
143
+ return new Date(dateString).toLocaleString();
144
+ }
145
+ catch (_a) {
146
+ return dateString;
147
+ }
148
+ };
149
+ var formattedMetadata = Object.entries(metadata)
150
+ .map(function (_a) {
151
+ var _b;
152
+ var key = _a[0], value = _a[1];
153
+ var formattedValue = ((_b = value === null || value === void 0 ? void 0 : value.includes) === null || _b === void 0 ? void 0 : _b.call(value, 'T'))
154
+ ? formatDate_1(value)
155
+ : value;
156
+ var formattedKey = key.replace(/([A-Z])/g, ' $1').toLowerCase();
157
+ return "\u001B[36m".concat(formattedKey, ":\u001B[0m ").concat(formattedValue);
158
+ })
159
+ .join('\n');
160
+ var projectUrl = "\nurl: https://".concat(deploymentId.replace('codegen-', ''), "-agent.dainapp.com");
161
+ var output = [
162
+ '\n',
163
+ '\x1b[1m=== Project ===\x1b[0m',
164
+ formattedMetadata,
165
+ projectUrl,
166
+ '\n\x1b[1m=== Logs ===\x1b[0m',
167
+ logs_1,
168
+ ];
169
+ return output.join('\n');
170
+ }
171
+ catch (error) {
172
+ return "Error formatting logs: ".concat(error.message);
173
+ }
174
+ };