bdy 1.16.16-dev → 1.16.18-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bdy",
3
3
  "preferGlobal": false,
4
- "version": "1.16.16-dev",
4
+ "version": "1.16.18-dev",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
7
7
  "scripts": {
@@ -51,7 +51,7 @@ class ApiClient {
51
51
  let responseBody;
52
52
  logger_1.default.debug(`API CLIENT: ${method} ${this.baseUrl.protocol}//${this.baseUrl.host}${path}`);
53
53
  logger_1.default.debug(headers);
54
- logger_1.default.debug(body);
54
+ logger_1.default.debug(bodyParsed);
55
55
  try {
56
56
  const r = await this.client.request(opts);
57
57
  status = r.statusCode;
@@ -107,7 +107,7 @@ class ApiClient {
107
107
  else
108
108
  throw new Error(texts_1.ERR_REST_API_GENERAL_ERROR);
109
109
  }
110
- if (status === 200 || status === 201) {
110
+ if ([200, 201].includes(status)) {
111
111
  if (parseResponseBody) {
112
112
  try {
113
113
  const b = await responseBody.json();
@@ -138,9 +138,6 @@ class ApiClient {
138
138
  throw new Error(texts_1.ERR_REST_API_GENERAL_ERROR);
139
139
  }
140
140
  }
141
- async getPipelineByIdentifier(workspace, project, identifier) {
142
- return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/identifiers?project=${encodeURIComponent(project)}&pipeline=${encodeURIComponent(identifier)}`, null, true);
143
- }
144
141
  async getPipelineRun(workspace, project, pipelineId, executionId) {
145
142
  return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/projects/${encodeURIComponent(project)}/pipelines/${encodeURIComponent(pipelineId)}/executions/${encodeURIComponent(executionId)}`, null, true);
146
143
  }
@@ -212,9 +209,6 @@ class ApiClient {
212
209
  async listSandboxCommands(workspace, sandboxId) {
213
210
  return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/sandboxes/${encodeURIComponent(sandboxId)}/commands`, null, true);
214
211
  }
215
- async getSandboxCommandLogsUrl(workspace, sandboxId, commandId) {
216
- return `${this.baseUrl.origin}/workspaces/${encodeURIComponent(workspace)}/sandboxes/${encodeURIComponent(sandboxId)}/commands/${encodeURIComponent(commandId)}/logs`;
217
- }
218
212
  async streamSandboxCommandLogs(workspace, sandboxId, commandId, follow = true) {
219
213
  let q = '';
220
214
  if (follow)
@@ -308,8 +302,79 @@ class ApiClient {
308
302
  async getWorkspaces() {
309
303
  return await this.request('GET', '/workspaces', null, true);
310
304
  }
305
+ async getPackages(workspace, project) {
306
+ let query = '';
307
+ if (project)
308
+ query += `?project_name=${encodeURIComponent(project)}`;
309
+ return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/packages${query}`, null, true);
310
+ }
311
311
  async getProjects(workspace) {
312
312
  return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/projects`, null, true);
313
313
  }
314
+ async getResourceByIdentifier(workspace, params) {
315
+ let query = '';
316
+ Object.keys(params).forEach((key) => {
317
+ if (!query)
318
+ query += '?';
319
+ else
320
+ query += '&';
321
+ query += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
322
+ });
323
+ return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/identifiers${query}`, null, true);
324
+ }
325
+ async getPipelineByIdentifier(workspace, project, identifier) {
326
+ return await this.getResourceByIdentifier(workspace, { project, pipeline: identifier });
327
+ }
328
+ async getPackageVersionByIdentifier(workspace, project, pkg, version) {
329
+ const opts = {
330
+ package: pkg,
331
+ };
332
+ if (project)
333
+ opts.project = project;
334
+ if (version)
335
+ opts.package_version = version;
336
+ return await this.getResourceByIdentifier(workspace, opts);
337
+ }
338
+ async getPackageVersion(workspace, pkgId, versionId) {
339
+ return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/packages/${encodeURIComponent(pkgId)}/versions/${encodeURIComponent(versionId)}`, null, true);
340
+ }
341
+ async getPackageLatest(workspace, pkgId) {
342
+ const res = await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/packages/${encodeURIComponent(pkgId)}/versions?page=1&per_page=1`, null, true);
343
+ if (res && res.versions && res.versions.length > 0) {
344
+ return res.versions[0];
345
+ }
346
+ return null;
347
+ }
348
+ async downloadPackageVersion(workspace, pkgId, versionId) {
349
+ return await this.request('GET', `/workspaces/${encodeURIComponent(workspace)}/packages/${encodeURIComponent(pkgId)}/versions/${encodeURIComponent(versionId)}/download`, null, false, true);
350
+ }
351
+ async postPackageVersion(workspace, pkgId, version) {
352
+ return await this.request('POST', `/workspaces/${encodeURIComponent(workspace)}/packages/${encodeURIComponent(pkgId)}/versions`, {
353
+ version
354
+ }, true);
355
+ }
356
+ async postPackageVersionZip(workspace, pkgId, versionId, file) {
357
+ const form = new undici_1.FormData();
358
+ form.append('file', file);
359
+ return await this.request('POST', `/workspaces/${encodeURIComponent(workspace)}/packages/${encodeURIComponent(pkgId)}/versions/${versionId}/upload`, form, true);
360
+ }
361
+ async postPackage(workspace, project, identifier) {
362
+ const body = {
363
+ name: identifier,
364
+ identifier,
365
+ type: 'FILE',
366
+ scope: 'WORKSPACE',
367
+ authorization: {
368
+ type: 'BUDDY'
369
+ }
370
+ };
371
+ if (project) {
372
+ body.project = {
373
+ name: project
374
+ };
375
+ body.scope = 'PROJECT';
376
+ }
377
+ return await this.request('POST', `/workspaces/${encodeURIComponent(workspace)}/packages`, body, true);
378
+ }
314
379
  }
315
380
  exports.default = ApiClient;
@@ -14,7 +14,7 @@ const input_1 = __importDefault(require("../input"));
14
14
  const OAUTH_CLIENT_APP_PORT = 7596;
15
15
  const OAUTH_CLIENT_APP_HOST = 'localhost';
16
16
  const OAUTH_CLIENT_APP_REDIRECT_URL = `http://localhost:${OAUTH_CLIENT_APP_PORT}`;
17
- const OAUTH_CLIENT_APP_SCOPES = 'WORKSPACE USER_INFO EXECUTION_MANAGE SANDBOX_MANAGE';
17
+ const OAUTH_CLIENT_APP_SCOPES = 'WORKSPACE USER_INFO EXECUTION_MANAGE SANDBOX_MANAGE PACKAGE_MANAGE';
18
18
  function normalizeBaseUrl(url) {
19
19
  let normalized = url.trim();
20
20
  normalized = normalized.replace(/^https?:\/\//i, '');
@@ -76,7 +76,8 @@ async function oauthServer(api, clientId, clientSecret) {
76
76
  reject(texts_1.ERR_LOGIN_HTTP_SERVER_PORT_TAKEN);
77
77
  });
78
78
  s.listen(OAUTH_CLIENT_APP_PORT, OAUTH_CLIENT_APP_HOST);
79
- (0, open_1.default)(`https://${api}/oauth2/authorize?type=web_server&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(OAUTH_CLIENT_APP_REDIRECT_URL)}&response_type=code&scope=${encodeURIComponent(OAUTH_CLIENT_APP_SCOPES)}`);
79
+ const url = `https://${api}/oauth2/authorize?type=web_server&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(OAUTH_CLIENT_APP_REDIRECT_URL)}&response_type=code&scope=${encodeURIComponent(OAUTH_CLIENT_APP_SCOPES)}`;
80
+ (0, open_1.default)(url);
80
81
  });
81
82
  }
82
83
  async function getOrCreateApp(api) {
@@ -84,10 +85,17 @@ async function getOrCreateApp(api) {
84
85
  let clientId = cfg_1.default.getApiClientId();
85
86
  let clientSecret = cfg_1.default.getApiClientSecret();
86
87
  if (clientId && clientSecret) {
88
+ let clear = false;
87
89
  try {
88
- await client.getApp(clientId);
90
+ const app = await client.getApp(clientId);
91
+ if (!app || !app.redirect_uris || !app.redirect_uris.includes(OAUTH_CLIENT_APP_REDIRECT_URL)) {
92
+ clear = true;
93
+ }
89
94
  }
90
95
  catch {
96
+ clear = true;
97
+ }
98
+ if (clear) {
91
99
  clientId = null;
92
100
  clientSecret = null;
93
101
  }
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const utils_1 = require("../../utils");
7
+ const texts_1 = require("../../texts");
8
+ const input_1 = __importDefault(require("../../input"));
9
+ const client_1 = __importDefault(require("../../api/client"));
10
+ const output_1 = __importDefault(require("../../output"));
11
+ const logger_1 = __importDefault(require("../../logger"));
12
+ const path_1 = require("path");
13
+ const uuid_1 = require("uuid");
14
+ const fs_1 = __importDefault(require("fs"));
15
+ const promises_1 = __importDefault(require("stream/promises"));
16
+ const fflate_1 = require("fflate");
17
+ const commandPackageDownload = (0, utils_1.newCommand)('download', texts_1.DESC_COMMAND_PACKAGE_DOWNLOAD);
18
+ commandPackageDownload.alias('dd');
19
+ commandPackageDownload.option('-t, --token <token>', texts_1.OPTION_REST_API_TOKEN);
20
+ commandPackageDownload.option('--api <url>', texts_1.OPTION_REST_API_ENDPOINT);
21
+ commandPackageDownload.option('--region <region>', texts_1.OPTION_REST_API_REGION);
22
+ commandPackageDownload.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
23
+ commandPackageDownload.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
24
+ commandPackageDownload.option('-m, --merge', texts_1.OPTION_PACKAGE_DOWNLOAD_MERGE);
25
+ commandPackageDownload.option('-r, --replace', texts_1.OPTION_PACKAGE_DOWNLOAD_REPLACE);
26
+ commandPackageDownload.argument('<identifier>', texts_1.OPTION_PACKAGE_ID);
27
+ commandPackageDownload.argument('<directory>', texts_1.OPTION_PACKAGE_DOWNLOAD_PATH);
28
+ commandPackageDownload.action(async (id, path, options) => {
29
+ const token = input_1.default.restApiToken(options.token);
30
+ const baseUrl = input_1.default.restApiBaseUrl(options.api, options.region);
31
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
32
+ const project = input_1.default.restApiProject(options.project, true);
33
+ const client = new client_1.default(baseUrl, token);
34
+ // eslint-disable-next-line prefer-const
35
+ let { identifier, version } = input_1.default.packageSplitIdentifier(id);
36
+ const data = await client.getPackageVersionByIdentifier(workspace, project, identifier, version);
37
+ if (!data || !data.domain) {
38
+ output_1.default.exitError(texts_1.ERR_WORKSPACE_NOT_FOUND);
39
+ }
40
+ if (project && !data.project_identifier) {
41
+ output_1.default.exitError(texts_1.ERR_PROJECT_NOT_FOUND);
42
+ }
43
+ const packageId = data.pkg_id;
44
+ if (!packageId) {
45
+ output_1.default.exitError(texts_1.ERR_PACKAGE_DOWNLOAD_NOT_FOUND);
46
+ }
47
+ let versionId = data.pkg_version_id;
48
+ if (version && !versionId) {
49
+ output_1.default.exitError(texts_1.ERR_PACKAGE_VERSION_NOT_FOUND);
50
+ }
51
+ if (!version || !versionId) {
52
+ const v = await client.getPackageLatest(workspace, packageId);
53
+ if (!v) {
54
+ output_1.default.exitError(texts_1.ERR_PACKAGE_VERSION_NOT_FOUND);
55
+ }
56
+ version = v.version;
57
+ versionId = v.id;
58
+ }
59
+ const dirPath = (0, path_1.resolve)(path);
60
+ const exists = fs_1.default.existsSync(dirPath);
61
+ if (!exists) {
62
+ try {
63
+ fs_1.default.mkdirSync(dirPath, {
64
+ recursive: true,
65
+ });
66
+ }
67
+ catch (err) {
68
+ logger_1.default.error(err);
69
+ output_1.default.exitError((0, texts_1.ERR_PACKAGE_DOWNLOAD_MKDIR)(dirPath));
70
+ }
71
+ }
72
+ else if (options.replace) {
73
+ try {
74
+ fs_1.default.rmSync(dirPath, {
75
+ recursive: true,
76
+ force: true,
77
+ });
78
+ fs_1.default.mkdirSync(dirPath, {
79
+ recursive: true,
80
+ });
81
+ }
82
+ catch (err) {
83
+ logger_1.default.error(err);
84
+ output_1.default.exitError((0, texts_1.ERR_PACKAGE_DOWNLOAD_REPLACE)(dirPath));
85
+ }
86
+ }
87
+ try {
88
+ const stat = fs_1.default.statSync(dirPath);
89
+ if (!stat.isDirectory()) {
90
+ output_1.default.exitError((0, texts_1.ERR_PACKAGE_DOWNLOAD_IS_FILE)(dirPath));
91
+ }
92
+ }
93
+ catch (err) {
94
+ logger_1.default.error(err);
95
+ output_1.default.exitError(texts_1.ERR_SWW);
96
+ }
97
+ let empty = true;
98
+ try {
99
+ const entries = fs_1.default.readdirSync(dirPath);
100
+ empty = !entries.length;
101
+ }
102
+ catch (err) {
103
+ logger_1.default.error(err);
104
+ output_1.default.exitError((0, texts_1.ERR_PACKAGE_DOWNLOAD_READDIR)(dirPath));
105
+ }
106
+ if (!empty && !options.merge) {
107
+ output_1.default.exitError((0, texts_1.ERR_PACKAGE_DOWNLOAD_NOT_EMPTY_DIR)(dirPath));
108
+ }
109
+ const zipPath = (0, path_1.join)((0, utils_1.getHomeDirectory)(), `${(0, uuid_1.v4)()}.zip`);
110
+ const clearZip = () => {
111
+ try {
112
+ fs_1.default.rmSync(zipPath);
113
+ }
114
+ catch {
115
+ // do nothing
116
+ }
117
+ };
118
+ output_1.default.normal(texts_1.TXT_PACKAGE_DOWNLOADING_ZIP);
119
+ const body = await client.downloadPackageVersion(workspace, packageId, versionId);
120
+ try {
121
+ await promises_1.default.pipeline(body, fs_1.default.createWriteStream(zipPath));
122
+ output_1.default.clearPreviousLine();
123
+ output_1.default.normal(texts_1.TXT_PACKAGE_DOWNLOADED_ZIP);
124
+ output_1.default.normal(texts_1.TXT_PACKAGE_UNZIPPING);
125
+ let count = 0;
126
+ await unzip(dirPath, zipPath, () => {
127
+ count += 1;
128
+ output_1.default.clearPreviousLine();
129
+ output_1.default.normal((0, texts_1.TXT_PACKAGE_UNZIPPING_COUNT)(count));
130
+ });
131
+ clearZip();
132
+ output_1.default.clearPreviousLine();
133
+ output_1.default.normal(texts_1.TXT_PACKAGE_UNZIPPED);
134
+ }
135
+ catch (err) {
136
+ logger_1.default.error(err);
137
+ clearZip();
138
+ output_1.default.exitError(texts_1.ERR_SWW);
139
+ }
140
+ output_1.default.exitSuccess((0, texts_1.TXT_PACKAGE_DOWNLOADED)(version, dirPath));
141
+ });
142
+ const unzip = (dirPath, zipPath, onFile) => {
143
+ return new Promise((resolve, reject) => {
144
+ let _startedFiles = 0;
145
+ let _finishedFiles = 0;
146
+ let _finishedStream = false;
147
+ let _finishedError = null;
148
+ let _calledResolve = false;
149
+ const rs = fs_1.default.createReadStream(zipPath);
150
+ const _finish = () => {
151
+ if (_finishedError || _finishedStream) {
152
+ try {
153
+ rs.removeAllListeners();
154
+ rs.close();
155
+ }
156
+ catch {
157
+ // do nothing
158
+ }
159
+ }
160
+ if (_calledResolve)
161
+ return;
162
+ if (_finishedError) {
163
+ _calledResolve = true;
164
+ reject(_finishedError);
165
+ return;
166
+ }
167
+ if (_finishedStream && _startedFiles === _finishedFiles) {
168
+ _calledResolve = true;
169
+ resolve();
170
+ }
171
+ };
172
+ const finishFile = (err, fws) => {
173
+ if (!_finishedError && err)
174
+ _finishedError = err;
175
+ _finishedFiles += 1;
176
+ if (fws) {
177
+ try {
178
+ fws.removeAllListeners();
179
+ fws.close();
180
+ }
181
+ catch {
182
+ // do nothing
183
+ }
184
+ }
185
+ onFile();
186
+ _finish();
187
+ };
188
+ const finishStream = (err) => {
189
+ if (!_finishedError && err)
190
+ _finishedError = err;
191
+ _finishedStream = true;
192
+ _finish();
193
+ };
194
+ const unzip = new fflate_1.Unzip(async (file) => {
195
+ if (_finishedError)
196
+ return;
197
+ _startedFiles += 1;
198
+ const fullPath = (0, path_1.join)(dirPath, file.name);
199
+ const parentPath = (0, path_1.dirname)(fullPath);
200
+ let fws;
201
+ try {
202
+ await fs_1.default.promises.rm(fullPath, {
203
+ recursive: true,
204
+ force: true,
205
+ });
206
+ }
207
+ catch {
208
+ // do nothing
209
+ }
210
+ try {
211
+ if (fullPath.endsWith('/')) {
212
+ await fs_1.default.promises.mkdir(fullPath, {
213
+ recursive: true,
214
+ });
215
+ finishFile();
216
+ return;
217
+ }
218
+ await fs_1.default.promises.mkdir(parentPath, {
219
+ recursive: true,
220
+ });
221
+ fws = fs_1.default.createWriteStream(fullPath, {
222
+ flags: 'w',
223
+ });
224
+ fws.on('error', (err) => {
225
+ finishFile(err, fws);
226
+ });
227
+ }
228
+ catch (err) {
229
+ finishFile(err, fws);
230
+ return;
231
+ }
232
+ file.ondata = (err, data, final) => {
233
+ if (_finishedError)
234
+ return;
235
+ if (err)
236
+ finishFile(err, fws);
237
+ else {
238
+ if (fws)
239
+ fws.write(data);
240
+ if (final)
241
+ finishFile(null, fws);
242
+ }
243
+ };
244
+ file.start();
245
+ });
246
+ unzip.register(fflate_1.AsyncUnzipInflate);
247
+ rs.on('data', (chunk) => {
248
+ unzip.push(chunk, false);
249
+ });
250
+ rs.on('error', (err) => {
251
+ finishStream(err);
252
+ });
253
+ rs.on('end', () => {
254
+ unzip.push(new Uint8Array(0), true);
255
+ finishStream();
256
+ });
257
+ });
258
+ };
259
+ exports.default = commandPackageDownload;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const output_1 = __importDefault(require("../../output"));
7
+ const client_1 = __importDefault(require("../../api/client"));
8
+ const texts_1 = require("../../texts");
9
+ const utils_1 = require("../../utils");
10
+ const input_1 = __importDefault(require("../../input"));
11
+ const commandPackageList = (0, utils_1.newCommand)('list', texts_1.DESC_COMMAND_PACKAGE_LIST);
12
+ commandPackageList.option('--token <token>', texts_1.OPTION_REST_API_TOKEN);
13
+ commandPackageList.option('--api <url>', texts_1.OPTION_REST_API_ENDPOINT);
14
+ commandPackageList.option('--region <region>', texts_1.OPTION_REST_API_REGION);
15
+ commandPackageList.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
16
+ commandPackageList.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
17
+ commandPackageList.alias('ls');
18
+ commandPackageList.action(async (options) => {
19
+ const token = input_1.default.restApiToken(options.token);
20
+ const baseUrl = input_1.default.restApiBaseUrl(options.api, options.region);
21
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
22
+ const project = input_1.default.restApiProject(options.project, true);
23
+ const client = new client_1.default(baseUrl, token);
24
+ const response = await client.getPackages(workspace, project);
25
+ if (!response.packages || response.packages.length === 0) {
26
+ output_1.default.exitError(texts_1.ERR_COMMAND_PACKAGE_NO_PROJECTS);
27
+ }
28
+ const data = [['NAME', 'IDENTIFIER']];
29
+ for (const pkg of response.packages) {
30
+ data.push([pkg.name, pkg.identifier]);
31
+ }
32
+ output_1.default.table(data);
33
+ output_1.default.exitNormal();
34
+ });
35
+ exports.default = commandPackageList;
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const utils_1 = require("../../utils");
7
+ const texts_1 = require("../../texts");
8
+ const input_1 = __importDefault(require("../../input"));
9
+ const client_1 = __importDefault(require("../../api/client"));
10
+ const output_1 = __importDefault(require("../../output"));
11
+ const logger_1 = __importDefault(require("../../logger"));
12
+ const fflate_1 = __importDefault(require("fflate"));
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const path_1 = require("path");
15
+ const uuid_1 = require("uuid");
16
+ const commandPackagePublish = (0, utils_1.newCommand)('publish', texts_1.DESC_COMMAND_PACKAGE_PUBLISH);
17
+ commandPackagePublish.alias('pub');
18
+ commandPackagePublish.option('-t, --token <token>', texts_1.OPTION_REST_API_TOKEN);
19
+ commandPackagePublish.option('--api <url>', texts_1.OPTION_REST_API_ENDPOINT);
20
+ commandPackagePublish.option('--region <region>', texts_1.OPTION_REST_API_REGION);
21
+ commandPackagePublish.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
22
+ commandPackagePublish.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
23
+ commandPackagePublish.option('-c, --create', texts_1.OPTION_PACKAGE_PUBLISH_CREATE);
24
+ commandPackagePublish.option('-f, --force', texts_1.OPTION_PACKAGE_PUBLISH_OVERWRITE_VERSION);
25
+ commandPackagePublish.argument('<identifier>', texts_1.OPTION_PACKAGE_ID);
26
+ commandPackagePublish.argument('<directory>', texts_1.OPTION_PACKAGE_PUBLISH_PATH);
27
+ commandPackagePublish.action(async (id, path, options) => {
28
+ let dirPath = input_1.default.resolvePath(path);
29
+ const token = input_1.default.restApiToken(options.token);
30
+ const baseUrl = input_1.default.restApiBaseUrl(options.api, options.region);
31
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
32
+ const project = input_1.default.restApiProject(options.project, true);
33
+ // eslint-disable-next-line prefer-const
34
+ let { identifier, version } = input_1.default.packageSplitIdentifier(id);
35
+ if (!version)
36
+ version = (0, uuid_1.v4)();
37
+ const client = new client_1.default(baseUrl, token);
38
+ const data = await client.getPackageVersionByIdentifier(workspace, project, identifier, version);
39
+ if (!data || !data.domain) {
40
+ output_1.default.exitError(texts_1.ERR_WORKSPACE_NOT_FOUND);
41
+ }
42
+ if (project && !data.project_identifier) {
43
+ output_1.default.exitError(texts_1.ERR_PROJECT_NOT_FOUND);
44
+ }
45
+ let packageId = data.pkg_id;
46
+ if (!packageId) {
47
+ if (options.create) {
48
+ const d = await client.postPackage(workspace, project, identifier);
49
+ packageId = d.id;
50
+ }
51
+ else {
52
+ output_1.default.exitError(texts_1.ERR_PACKAGE_PUBLISH_NOT_FOUND);
53
+ }
54
+ }
55
+ let packageVersionId = data.pkg_version_id;
56
+ let url;
57
+ if (packageVersionId && !options.force) {
58
+ output_1.default.exitError(texts_1.ERR_PACKAGE_VERSION_EXISTS);
59
+ }
60
+ if (!packageVersionId) {
61
+ const d = await client.postPackageVersion(workspace, packageId, version);
62
+ url = d.version_url;
63
+ packageVersionId = d.id;
64
+ }
65
+ else {
66
+ const d = await client.getPackageVersion(workspace, packageId, packageVersionId);
67
+ url = d.version_url;
68
+ }
69
+ output_1.default.normal(texts_1.TXT_PACKAGE_SCANNING_DIR, false);
70
+ const stat = fs_1.default.statSync(dirPath);
71
+ let entries;
72
+ if (stat.isDirectory()) {
73
+ entries = fs_1.default.readdirSync(dirPath, {
74
+ withFileTypes: true,
75
+ recursive: true,
76
+ });
77
+ }
78
+ else {
79
+ const parentPath = (0, path_1.dirname)(dirPath);
80
+ entries = [
81
+ {
82
+ isDirectory: () => stat.isDirectory(),
83
+ isFile: () => stat.isFile(),
84
+ isBlockDevice: () => stat.isBlockDevice(),
85
+ isCharacterDevice: () => stat.isCharacterDevice(),
86
+ isFIFO: () => stat.isFIFO(),
87
+ isSocket: () => stat.isSocket(),
88
+ isSymbolicLink: () => stat.isSymbolicLink(),
89
+ name: (0, path_1.basename)(dirPath),
90
+ parentPath,
91
+ path: parentPath,
92
+ },
93
+ ];
94
+ dirPath = parentPath;
95
+ }
96
+ if (!entries.length) {
97
+ output_1.default.normal(texts_1.TXT_PACKAGE_NO_ENTRIES_FOUND);
98
+ output_1.default.exitSuccess((0, texts_1.TXT_PACKAGE_PUBLISHED)(url));
99
+ }
100
+ else if (entries.length === 1) {
101
+ output_1.default.normal(texts_1.TXT_PACKAGE_ONE_ENTRY_FOUND);
102
+ }
103
+ else {
104
+ output_1.default.normal((0, texts_1.TXT_PACKAGE_ENTRIES_FOUND)(entries.length));
105
+ }
106
+ output_1.default.normal((0, texts_1.TXT_PACKAGE_ZIP_ENTRIES)(0));
107
+ const zipPath = (0, path_1.join)((0, utils_1.getHomeDirectory)(), `${(0, uuid_1.v4)()}.zip`);
108
+ const clearZip = () => {
109
+ try {
110
+ fs_1.default.rmSync(zipPath);
111
+ }
112
+ catch {
113
+ // do nothing
114
+ }
115
+ };
116
+ let blob;
117
+ try {
118
+ let proc = 0;
119
+ await createZip(dirPath, zipPath, entries, () => {
120
+ proc += 1;
121
+ output_1.default.clearPreviousLine();
122
+ output_1.default.normal((0, texts_1.TXT_PACKAGE_ZIP_ENTRIES)(proc));
123
+ });
124
+ output_1.default.clearPreviousLine();
125
+ output_1.default.normal(texts_1.TXT_PACKAGE_ZIPPED);
126
+ blob = await fs_1.default.openAsBlob(zipPath);
127
+ }
128
+ catch (err) {
129
+ logger_1.default.error(err);
130
+ clearZip();
131
+ output_1.default.exitError(texts_1.ERR_SWW);
132
+ }
133
+ try {
134
+ output_1.default.normal(texts_1.TXT_PACKAGE_UPLOADING);
135
+ await client.postPackageVersionZip(workspace, packageId, packageVersionId, blob);
136
+ output_1.default.clearPreviousLine();
137
+ output_1.default.normal(texts_1.TXT_PACKAGE_UPLOADED);
138
+ clearZip();
139
+ output_1.default.exitSuccess((0, texts_1.TXT_PACKAGE_PUBLISHED)(url));
140
+ }
141
+ catch (err) {
142
+ clearZip();
143
+ logger_1.default.error(err);
144
+ output_1.default.exitError(err);
145
+ }
146
+ });
147
+ const addEntryToZip = (dirPath, zip, entry) => {
148
+ return new Promise((resolve, reject) => {
149
+ const isDir = entry.isDirectory();
150
+ let name = (0, path_1.join)(entry.parentPath.replace(dirPath, ''), entry.name);
151
+ if (isDir)
152
+ name += '/';
153
+ const file = new fflate_1.default.AsyncZipDeflate(name, {
154
+ level: 9,
155
+ });
156
+ zip.add(file);
157
+ if (isDir) {
158
+ file.push(new Uint8Array(0), true);
159
+ resolve();
160
+ return;
161
+ }
162
+ const fullPath = (0, path_1.join)(entry.parentPath, entry.name);
163
+ const rs = fs_1.default.createReadStream(fullPath);
164
+ const finish = (err) => {
165
+ try {
166
+ rs.removeAllListeners();
167
+ rs.close();
168
+ }
169
+ catch {
170
+ // do nothing
171
+ }
172
+ if (err)
173
+ reject(err);
174
+ else
175
+ resolve();
176
+ };
177
+ rs.on('data', (chunk) => {
178
+ file.push(chunk, false);
179
+ });
180
+ rs.on('error', (err) => {
181
+ finish(err);
182
+ });
183
+ rs.on('end', () => {
184
+ file.push(new Uint8Array(0), true);
185
+ finish();
186
+ });
187
+ });
188
+ };
189
+ const addEntriesToZip = async (dirPath, zip, entries, onEntry) => {
190
+ for (let i = 0; i < entries.length; i += 1) {
191
+ await addEntryToZip(dirPath, zip, entries[i]);
192
+ onEntry();
193
+ }
194
+ };
195
+ const createZip = (dirPath, zipPath, entries, onEntry) => {
196
+ return new Promise((resolve, reject) => {
197
+ const ws = fs_1.default.createWriteStream(zipPath);
198
+ let wasError = false;
199
+ const zip = new fflate_1.default.Zip((err, data, final) => {
200
+ if (wasError) {
201
+ // do nothing
202
+ }
203
+ else if (err) {
204
+ wasError = true;
205
+ ws.close();
206
+ reject(err);
207
+ }
208
+ else {
209
+ ws.write(data);
210
+ if (final) {
211
+ ws.close((err) => {
212
+ if (err)
213
+ reject(err);
214
+ else
215
+ resolve();
216
+ });
217
+ }
218
+ }
219
+ });
220
+ addEntriesToZip(dirPath, zip, entries, onEntry)
221
+ .then(() => {
222
+ zip.end();
223
+ })
224
+ .catch((err) => {
225
+ ws.close(() => {
226
+ reject(err);
227
+ });
228
+ });
229
+ });
230
+ };
231
+ exports.default = commandPackagePublish;