@ones-open/cli 1.0.1-29853.1886 → 1.0.1-4995.1947

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/index.cjs +750 -478
  2. package/dist/index.js +753 -481
  3. package/dist/types/actions/build/index.d.ts.map +1 -1
  4. package/dist/types/actions/dev/index.d.ts.map +1 -1
  5. package/dist/types/actions/disable/index.d.ts.map +1 -1
  6. package/dist/types/actions/enable/index.d.ts.map +1 -1
  7. package/dist/types/actions/install/index.d.ts.map +1 -1
  8. package/dist/types/actions/tunnel/consts.d.ts +3 -0
  9. package/dist/types/actions/tunnel/consts.d.ts.map +1 -1
  10. package/dist/types/actions/tunnel/index.d.ts +3 -1
  11. package/dist/types/actions/tunnel/index.d.ts.map +1 -1
  12. package/dist/types/actions/tunnel/tunnel-client.d.ts +9 -4
  13. package/dist/types/actions/tunnel/tunnel-client.d.ts.map +1 -1
  14. package/dist/types/actions/tunnel/tunnel.d.ts +2 -3
  15. package/dist/types/actions/tunnel/tunnel.d.ts.map +1 -1
  16. package/dist/types/actions/tunnel/types.d.ts +33 -0
  17. package/dist/types/actions/tunnel/types.d.ts.map +1 -0
  18. package/dist/types/actions/tunnel/utils.d.ts +7 -0
  19. package/dist/types/actions/tunnel/utils.d.ts.map +1 -0
  20. package/dist/types/actions/uninstall/index.d.ts.map +1 -1
  21. package/dist/types/actions/whoami/index.d.ts.map +1 -1
  22. package/dist/types/cli/index.d.ts.map +1 -1
  23. package/dist/types/common/error/enums.d.ts +12 -11
  24. package/dist/types/common/error/enums.d.ts.map +1 -1
  25. package/dist/types/common/locales/en/index.d.ts +28 -28
  26. package/dist/types/common/package/utils.d.ts +2 -0
  27. package/dist/types/common/package/utils.d.ts.map +1 -1
  28. package/dist/types/common/request/fetch.d.ts.map +1 -1
  29. package/dist/types/common/request/types.d.ts +15 -5
  30. package/dist/types/common/request/types.d.ts.map +1 -1
  31. package/dist/types/common/request/utils.d.ts +3 -2
  32. package/dist/types/common/request/utils.d.ts.map +1 -1
  33. package/package.json +3 -3
  34. package/dist/types/actions/tunnel/hosted-token.d.ts +0 -5
  35. package/dist/types/actions/tunnel/hosted-token.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -6,18 +6,17 @@ const createOnesApp = require("create-ones-app");
6
6
  const node_path = require("node:path");
7
7
  const node_child_process = require("node:child_process");
8
8
  const node_fs = require("node:fs");
9
+ const fse = require("fs-extra");
9
10
  const archiver = require("archiver");
10
11
  const lodashEs = require("lodash-es");
11
12
  const process$1 = require("node:process");
12
13
  const node_url = require("node:url");
13
14
  const cosmiconfig = require("cosmiconfig");
14
- const fse = require("fs-extra");
15
15
  const envPaths = require("env-paths");
16
16
  const zod = require("zod");
17
- const _defineProperty = require("@babel/runtime-corejs3/helpers/defineProperty");
18
- const WebSocket = require("ws");
19
17
  const axios = require("axios");
20
18
  const _reduceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/reduce");
19
+ const WebSocket = require("ws");
21
20
  const http = require("node:http");
22
21
  const ora = require("ora");
23
22
  const open = require("open");
@@ -25,34 +24,34 @@ const getPort = require("get-port");
25
24
  const uuid = require("uuid");
26
25
  var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
27
26
  const en = {
28
- "desc.ones": "cli for ones",
29
- "desc.build": "build the application",
30
- "desc.build.output": "specify the output file path",
31
- "desc.dev": "develop the application",
32
- "desc.dev.install": "whether to install the application",
33
- "desc.tunnel": "start a tunnel to the application",
34
- "desc.tunnel.port": "specify the port number for serve",
35
- "desc.login": "login to the environment",
36
- "desc.login.baseUrl": "specify the environment url for login",
37
- "desc.logout": "logout from the environment",
38
- "desc.whoami": "show the current user",
39
- "desc.app": "app command",
40
- "desc.install": "install the application",
41
- "desc.enable": "enable the application",
42
- "desc.disable": "disable the application",
43
- "desc.uninstall": "uninstall the application",
44
- "desc.legacy": "legacy command",
45
- "error.login.missingBaseURL": "missing base url",
46
- "error.login.incorrectBaseURL": "incorrect base url",
47
- "error.tunnel.missingPort": "missing port",
48
- "error.tunnel.incorrectPort": "incorrect port",
49
- "error.schema.app.package.parseError": "app package json parse error",
50
- "error.schema.app.manifest.parseError": "app manifest json parse error",
51
- "error.build.scriptNotFound": "build script not found",
52
- "error.dev.scriptNotFound": "dev script not found",
53
- "error.store.permission": 'permission denied, please check the file permission with "{filePath}"',
54
- "error.hostedToken.requestFailed": "failed to request hosted token",
55
- "error.hostedToken.empty": "hosted token is empty"
27
+ "desc.ones": "ONES CLI/{env}",
28
+ "desc.build": "Build your ONES App",
29
+ "desc.build.output": "Specify the output file path",
30
+ "desc.dev": "Start your local development server and connect to ONES",
31
+ "desc.dev.install": "Install your ONES App after the server is ready",
32
+ "desc.tunnel": "Start a tunnel to connect your local server with ONES",
33
+ "desc.tunnel.port": "Specify the port number for tunnel",
34
+ "desc.login": "Log in to your ONES account",
35
+ "desc.login.baseUrl": "Specify the ONES URL for login",
36
+ "desc.logout": "Log out of your ONES account",
37
+ "desc.whoami": "Display the account information of the logged in user",
38
+ "desc.app": "Manage app installations",
39
+ "desc.install": "Install your ONES App",
40
+ "desc.enable": "Enable your ONES App",
41
+ "desc.disable": "Disable your ONES App",
42
+ "desc.uninstall": "Uninstall your ONES App",
43
+ "desc.legacy": "Legacy command",
44
+ "error.login.missingBaseURL": "Missing base URL",
45
+ "error.login.incorrectBaseURL": "Incorrect base URL",
46
+ "error.tunnel.missingPort": "Missing port",
47
+ "error.tunnel.incorrectPort": "Incorrect port",
48
+ "error.schema.app.package.parseError": "App package JSON parse error",
49
+ "error.schema.app.manifest.parseError": 'App "opkx.json" JSON parse error',
50
+ "error.build.scriptNotFound": 'Npm "build" script not found',
51
+ "error.dev.scriptNotFound": 'Npm "dev" script not found',
52
+ "error.store.permission": 'Permission denied, please check the file permission with "{filePath}"',
53
+ "error.hostedToken.requestFailed": "Failed to request hosted token",
54
+ "error.hostedToken.empty": "Hosted token is empty"
56
55
  };
57
56
  const map = {
58
57
  en
@@ -85,17 +84,18 @@ var ErrorCode = ((ErrorCode2) => {
85
84
  ErrorCode2[ErrorCode2["UNKNOWN_ERROR"] = createOnesApp.ErrorCode.UNKNOWN_ERROR] = "UNKNOWN_ERROR";
86
85
  ErrorCode2[ErrorCode2["COMMAND_ERROR"] = createOnesApp.ErrorCode.COMMAND_ERROR] = "COMMAND_ERROR";
87
86
  ErrorCode2[ErrorCode2["TEMPLATE_NOT_FOUND"] = createOnesApp.ErrorCode.TEMPLATE_NOT_FOUND] = "TEMPLATE_NOT_FOUND";
88
- ErrorCode2["MISSING_BASE_URL"] = "E03";
89
- ErrorCode2["MISSING_PORT"] = "E04";
90
- ErrorCode2["INCORRECT_BASE_URL"] = "E05";
91
- ErrorCode2["INCORRECT_PORT"] = "E06";
92
- ErrorCode2["APP_PACKAGE_JSON_PARSE_ERROR"] = "E07";
93
- ErrorCode2["APP_MANIFEST_JSON_PARSE_ERROR"] = "E08";
94
- ErrorCode2["BUILD_SCRIPT_NOT_FOUND"] = "E09";
95
- ErrorCode2["DEV_SCRIPT_NOT_FOUND"] = "E10";
96
- ErrorCode2["STORE_PERMISSION"] = "E11";
97
- ErrorCode2["HOSTED_TOKEN_REQUEST_FAILED"] = "E12";
98
- ErrorCode2["HOSTED_TOKEN_EMPTY"] = "E13";
87
+ ErrorCode2[ErrorCode2["MISSING_PROJECT_PATH"] = createOnesApp.ErrorCode.MISSING_PROJECT_PATH] = "MISSING_PROJECT_PATH";
88
+ ErrorCode2["MISSING_BASE_URL"] = "E04";
89
+ ErrorCode2["MISSING_PORT"] = "E05";
90
+ ErrorCode2["INCORRECT_BASE_URL"] = "E06";
91
+ ErrorCode2["INCORRECT_PORT"] = "E07";
92
+ ErrorCode2["APP_PACKAGE_JSON_PARSE_ERROR"] = "E08";
93
+ ErrorCode2["APP_MANIFEST_JSON_PARSE_ERROR"] = "E09";
94
+ ErrorCode2["BUILD_SCRIPT_NOT_FOUND"] = "E10";
95
+ ErrorCode2["DEV_SCRIPT_NOT_FOUND"] = "E11";
96
+ ErrorCode2["STORE_PERMISSION"] = "E12";
97
+ ErrorCode2["HOSTED_TOKEN_REQUEST_FAILED"] = "E13";
98
+ ErrorCode2["HOSTED_TOKEN_EMPTY"] = "E14";
99
99
  return ErrorCode2;
100
100
  })(ErrorCode || {});
101
101
  const getPublicPath = () => {
@@ -132,8 +132,8 @@ const getAppPackageJSON = () => {
132
132
  const json = JSON.parse(string);
133
133
  return createOnesApp.AppPackageJSONSchema.parse(json);
134
134
  } catch (error) {
135
- console.error(error);
136
- return createOnesApp.throwError(ErrorCode.APP_PACKAGE_JSON_PARSE_ERROR, i18n.t("error.schema.app.package.parseError"));
135
+ const details = error instanceof Error ? error.message : String(error);
136
+ return createOnesApp.throwError(ErrorCode.APP_PACKAGE_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.package.parseError")}: ${details}`);
137
137
  }
138
138
  };
139
139
  const getAppManifestJSONPath = () => {
@@ -148,13 +148,14 @@ const getAppManifestJSON = () => {
148
148
  const json = JSON.parse(string);
149
149
  return createOnesApp.AppManifestJSONSchema.parse(json);
150
150
  } catch (error) {
151
- console.error(error);
152
- return createOnesApp.throwError(ErrorCode.APP_MANIFEST_JSON_PARSE_ERROR, i18n.t("error.schema.app.manifest.parseError"));
151
+ const details = error instanceof Error ? error.message : String(error);
152
+ return createOnesApp.throwError(ErrorCode.APP_MANIFEST_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.manifest.parseError")}: ${details}`);
153
153
  }
154
154
  };
155
+ const defaultAppRcJSONDevCommand = "npm run dev";
155
156
  const defaultAppRcJSON = {
156
157
  dev: {
157
- command: ["npm run dev"]
158
+ command: [defaultAppRcJSONDevCommand]
158
159
  }
159
160
  };
160
161
  let storeAppRcJSON = null;
@@ -205,8 +206,11 @@ const normalize$a = async (options) => {
205
206
  output
206
207
  };
207
208
  };
209
+ const {
210
+ existsSync
211
+ } = fse;
208
212
  const build = async function() {
209
- var _appPackageJSON$scrip, _appRcJSON$build$comp, _appRcJSON$build;
213
+ var _appRcJSON$build$comp, _appRcJSON$build;
210
214
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
211
215
  args[_key] = arguments[_key];
212
216
  }
@@ -214,18 +218,35 @@ const build = async function() {
214
218
  options
215
219
  } = createOnesApp.getCommandOptions(args, buildCommandArguments);
216
220
  const normalizedOptions = await normalize$a(options);
217
- const appPackageJSON = getAppPackageJSON();
218
221
  const appManifestJSON = getAppManifestJSON();
219
222
  const appRcJSON = await getAppRcJSON();
220
- appManifestJSON.app.name;
221
- if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
222
- node_child_process.spawnSync("npm", ["run", "build"], {
223
- cwd: getAppWorkspacePath(),
224
- stdio: "inherit"
225
- });
226
- } else {
227
- return createOnesApp.throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
223
+ const appPackageJSONPath = getAppPackageJSONPath();
224
+ const isExists = existsSync(appPackageJSONPath);
225
+ if (isExists) {
226
+ var _appPackageJSON$scrip;
227
+ const appPackageJSON = getAppPackageJSON();
228
+ if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
229
+ const buildResult = node_child_process.spawnSync("npm", ["run", "build"], {
230
+ cwd: getAppWorkspacePath(),
231
+ stdio: "inherit",
232
+ env: {
233
+ ...process.env,
234
+ NODE_ENV: "production"
235
+ }
236
+ });
237
+ if (buildResult.status !== 0 || buildResult.signal) {
238
+ var _buildResult$status;
239
+ process.exit((_buildResult$status = buildResult.status) !== null && _buildResult$status !== void 0 ? _buildResult$status : 1);
240
+ }
241
+ } else {
242
+ return createOnesApp.throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
243
+ }
228
244
  }
245
+ const appName = appManifestJSON.app.name;
246
+ const outputPath = normalizedOptions.output;
247
+ const outputFilename = node_path.basename(outputPath);
248
+ const outputStream = node_fs.createWriteStream(normalizedOptions.output);
249
+ const files = (_appRcJSON$build$comp = (_appRcJSON$build = appRcJSON.build) === null || _appRcJSON$build === void 0 || (_appRcJSON$build = _appRcJSON$build.compress) === null || _appRcJSON$build === void 0 ? void 0 : _appRcJSON$build.files) !== null && _appRcJSON$build$comp !== void 0 ? _appRcJSON$build$comp : [];
229
250
  const archive = archiver("zip", {
230
251
  zlib: {
231
252
  level: 9
@@ -248,12 +269,13 @@ const build = async function() {
248
269
  });
249
270
  archive.on("finish", () => {
250
271
  process.stdout.write("\n");
251
- console.log(`Output file: ${normalizedOptions.output}`);
252
- console.log(`OPKX "${node_path.basename(normalizedOptions.output)}" created successfully!`);
272
+ console.log("");
273
+ console.log("Files in archive: ", createOnesApp.PUBLIC_FILENAME.MANIFEST, files);
274
+ console.log(`App "${appName}" built successfully!`);
275
+ console.log(`OPKX "${outputFilename}" created successfully!`);
276
+ console.log(`Output file: ${outputPath}`);
253
277
  });
254
- const outputStream = node_fs.createWriteStream(normalizedOptions.output);
255
278
  archive.pipe(outputStream);
256
- const files = (_appRcJSON$build$comp = (_appRcJSON$build = appRcJSON.build) === null || _appRcJSON$build === void 0 || (_appRcJSON$build = _appRcJSON$build.compress) === null || _appRcJSON$build === void 0 ? void 0 : _appRcJSON$build.files) !== null && _appRcJSON$build$comp !== void 0 ? _appRcJSON$build$comp : [];
257
279
  files.forEach((file) => {
258
280
  archive.glob(file, {
259
281
  cwd: getAppWorkspacePath()
@@ -264,76 +286,13 @@ const build = async function() {
264
286
  });
265
287
  archive.finalize();
266
288
  };
267
- var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
268
- InstallOptions2["AUTO"] = "auto";
269
- InstallOptions2["TRUE"] = "true";
270
- InstallOptions2["FALSE"] = "false";
271
- return InstallOptions2;
272
- })(InstallOptions || {});
273
- const defaultInstall = InstallOptions.AUTO;
274
- const normalize$9 = async (options) => {
275
- var _options$install;
276
- let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
277
- switch (true) {
278
- case install2 === InstallOptions.AUTO:
279
- break;
280
- case Boolean(install2):
281
- install2 = InstallOptions.TRUE;
282
- break;
283
- default:
284
- install2 = InstallOptions.FALSE;
285
- break;
286
- }
287
- return {
288
- install: install2
289
- };
290
- };
291
- const dev = async function() {
292
- var _appPackageJSON$scrip;
293
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
294
- args[_key] = arguments[_key];
295
- }
296
- const {
297
- options
298
- } = createOnesApp.getCommandOptions(args, devCommandArguments);
299
- const normalizedOptions = await normalize$9(options);
300
- console.log("dev", normalizedOptions);
301
- const appPackageJSON = getAppPackageJSON();
302
- console.log("appPackageJSON", appPackageJSON);
303
- const appManifestJSON = getAppManifestJSON();
304
- console.log("appManifestJSON", appManifestJSON);
305
- if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev) {
306
- if (normalizedOptions.install)
307
- ;
308
- } else {
309
- return createOnesApp.throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
310
- }
311
- };
312
- const isPortNumber = /^[1-9]\d{0,4}$/;
313
- const minPortNumber = 1;
314
- const maxPortNumber = 65535;
315
- const normalize$8 = async (options) => {
316
- const portInput = options.port;
317
- if (portInput)
318
- ;
319
- else {
320
- return createOnesApp.throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
321
- }
322
- const portString = String(portInput);
323
- const portNumber = Number(portString);
324
- if (isPortNumber.test(portString))
325
- ;
326
- else {
327
- return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
328
- }
329
- if (portNumber < minPortNumber || portNumber > maxPortNumber) {
330
- return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
289
+ const config = {
290
+ defaultPort: {
291
+ login: 8200,
292
+ tunnel: 8201
331
293
  }
332
- const port = portString;
333
- return {
334
- port
335
- };
336
294
  };
295
+ const getConfig = () => config;
337
296
  const StoreJSONSchema = zod.z.object({
338
297
  version: zod.z.string().optional(),
339
298
  timestamp: zod.z.number().optional(),
@@ -379,11 +338,11 @@ const getStore = async () => {
379
338
  const setStore = async (store) => {
380
339
  try {
381
340
  await ensureFile(storePath);
382
- const version = `${getPackageJSON().version}`;
341
+ const version2 = `${getPackageJSON().version}`;
383
342
  const timestamp = Date.now();
384
343
  return await writeJSON(storePath, {
385
344
  ...store,
386
- version,
345
+ version: version2,
387
346
  timestamp
388
347
  }, {
389
348
  encoding: "utf8"
@@ -435,293 +394,108 @@ const setONESToken = async (token) => {
435
394
  ones_token: token
436
395
  });
437
396
  };
438
- class TunnelClient {
439
- constructor(localPort, baseUrl, appID, hostedToken) {
440
- _defineProperty(this, "ws", null);
441
- this.localPort = localPort;
442
- this.baseUrl = baseUrl;
443
- this.appID = appID;
444
- this.hostedToken = hostedToken;
445
- }
446
- async connect() {
447
- const proxyUrl = this.buildProxyUrl();
448
- this.ws = new WebSocket(proxyUrl, {
449
- headers: {
450
- Authorization: `Bearer ${this.hostedToken}`
451
- }
452
- });
453
- this.ws.on("message", async (data) => {
454
- const message = this.parseMessage(data);
455
- if (!message) {
456
- return;
457
- }
458
- await this.handleMessage(message);
459
- });
460
- this.ws.on("ping", (data) => {
461
- var _this$ws;
462
- (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
463
- });
464
- this.ws.on("error", (error) => {
465
- console.error("WebSocket error:", error);
466
- });
467
- return new Promise((resolve, reject) => {
468
- var _this$ws2, _this$ws3;
469
- (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
470
- (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
471
- });
397
+ const getHostToken = async () => {
398
+ var _store$host_token;
399
+ const store = await getStore();
400
+ return (_store$host_token = store.host_token) !== null && _store$host_token !== void 0 ? _store$host_token : "";
401
+ };
402
+ const setHostToken = async (token) => {
403
+ return mergeStore({
404
+ host_token: token
405
+ });
406
+ };
407
+ const isPortNumber = /^[1-9]\d{0,4}$/;
408
+ const minPortNumber = 1;
409
+ const maxPortNumber = 65535;
410
+ const MANIFEST_PATH = "/manifest";
411
+ const ONES_CLI_INTERNAL_MANIFEST_PATH = "/__ones_cli_internal_manifest__";
412
+ const MAX_RELAY_BODY_BYTES = 64 * 1024 * 1024;
413
+ const normalize$9 = async (options) => {
414
+ const portInput = options.port;
415
+ if (portInput)
416
+ ;
417
+ else {
418
+ return createOnesApp.throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
472
419
  }
473
- close() {
474
- var _this$ws4;
475
- (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
420
+ const portString = String(portInput);
421
+ const portNumber = Number(portString);
422
+ if (isPortNumber.test(portString))
423
+ ;
424
+ else {
425
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
476
426
  }
477
- buildProxyUrl() {
478
- const url = new URL("/platform/app/relay/", this.baseUrl);
479
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
480
- url.searchParams.set("app_id", this.appID);
481
- return url.toString();
427
+ if (portNumber < minPortNumber || portNumber > maxPortNumber) {
428
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
482
429
  }
483
- parseMessage(data) {
484
- const payload = data.toString();
485
- try {
486
- const message = JSON.parse(payload);
487
- if (!message) {
488
- return null;
489
- }
490
- return message;
491
- } catch (error) {
492
- console.error("Invalid tunnel message:", error);
493
- return null;
430
+ const port = portString;
431
+ return {
432
+ port
433
+ };
434
+ };
435
+ const API = {
436
+ TOKEN_INFO: "/project/api/project/auth/token_info",
437
+ HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
438
+ APP_LIST: "/platform/api/app/list",
439
+ APP_INSTALL: "/platform/api/app/install",
440
+ APP_UPGRADE: "/platform/api/app/upgrade",
441
+ APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
442
+ APP_ENABLE: "/platform/api/app/:installation_id/enable",
443
+ APP_DISABLE: "/platform/api/app/:installation_id/disable"
444
+ };
445
+ const getPath = (path, map2) => {
446
+ var _context;
447
+ return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
448
+ if (/^:/.test(part)) {
449
+ return `${base}/${map2[part.slice(1)]}`;
494
450
  }
451
+ return `${base}/${part}`;
452
+ }, "").slice(1);
453
+ };
454
+ const consoleUnauthorizedMessage = () => {
455
+ console.log("Not logged in");
456
+ console.log('Login with "ones login" command');
457
+ process.exit(1);
458
+ };
459
+ const consoleAppNotInstalledMessage = () => {
460
+ console.log("App not installed");
461
+ process.exit(1);
462
+ };
463
+ const getURL = async (path, pathMap, queryMap) => {
464
+ const base = await getRegionURL();
465
+ if (base) {
466
+ const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
467
+ return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
495
468
  }
496
- async handleMessage(message) {
497
- const request = this.getRequestPayload(message);
498
- if (!request) {
499
- return;
500
- }
501
- if (request.path === ONES_CLI_MANIFEST_PATH) {
502
- var _this$ws5;
503
- const appManifest = getAppManifestJSON().app;
504
- const baseURL = await buildTunnelUrl();
505
- const reply = {
506
- id: message.id,
507
- payload: {
508
- status: 200,
509
- headers: {
510
- "content-type": ["application/json"]
511
- },
512
- body: {
513
- ...appManifest,
514
- base_url: baseURL
515
- }
516
- }
517
- };
518
- (_this$ws5 = this.ws) === null || _this$ws5 === void 0 || _this$ws5.send(JSON.stringify(reply));
519
- return;
520
- }
521
- try {
522
- var _this$ws6;
523
- const response = await this.forwardRequest(request);
524
- const reply = {
525
- id: message.id,
526
- payload: response
527
- };
528
- (_this$ws6 = this.ws) === null || _this$ws6 === void 0 || _this$ws6.send(JSON.stringify(reply));
529
- } catch (error) {
530
- var _this$ws7;
531
- const reply = {
532
- id: message.id,
533
- payload: {
534
- status: 500,
535
- headers: {
536
- "x-agent-error": [error instanceof Error ? error.message : "Unknown error"]
537
- },
538
- body: "agent request error"
539
- }
540
- };
541
- (_this$ws7 = this.ws) === null || _this$ws7 === void 0 || _this$ws7.send(JSON.stringify(reply));
542
- }
469
+ consoleUnauthorizedMessage();
470
+ };
471
+ const getHeaders = async (value) => {
472
+ const token = await getONESToken();
473
+ if (token) {
474
+ return lodashEs.merge({
475
+ Authorization: `Bearer ${token}`
476
+ }, value);
543
477
  }
544
- getRequestPayload(message) {
545
- const payload = message.payload;
546
- if (!(payload !== null && payload !== void 0 && payload.method) || !(payload !== null && payload !== void 0 && payload.path)) {
547
- return null;
548
- }
549
- return payload;
478
+ consoleUnauthorizedMessage();
479
+ process.exit(1);
480
+ };
481
+ const handleError = (error) => {
482
+ var _error$response, _error$response2;
483
+ if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
484
+ console.log(error.response.statusText);
485
+ consoleUnauthorizedMessage();
486
+ process.exit(1);
550
487
  }
551
- async forwardRequest(payload) {
552
- const url = new URL(payload.path, `http://127.0.0.1:${this.localPort}`);
553
- if (payload.query) {
554
- Object.entries(payload.query).forEach((_ref) => {
555
- let [key, value] = _ref;
556
- url.searchParams.set(key, value);
557
- });
488
+ if ((_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
489
+ try {
490
+ const message = JSON.stringify(error.response.data, null, 2);
491
+ console.error(message);
492
+ process.exit(1);
493
+ } catch (error2) {
558
494
  }
559
- const headers = this.normalizeHeaders(payload.headers);
560
- const body = this.normalizeBody(payload.body);
561
- const response = await axios.request({
562
- url: url.toString(),
563
- method: payload.method,
564
- headers,
565
- data: body,
566
- responseType: "text",
567
- validateStatus: () => true
568
- });
569
- return {
570
- status: response.status,
571
- headers: this.collectHeaders(response.headers),
572
- body: this.normalizeResponseBody(response.data)
573
- };
574
- }
575
- normalizeHeaders(headers) {
576
- if (!headers) {
577
- return void 0;
578
- }
579
- const normalized = {};
580
- Object.entries(headers).forEach((_ref2) => {
581
- let [key, values] = _ref2;
582
- if (!values || values.length === 0) {
583
- return;
584
- }
585
- normalized[key] = values.join(",");
586
- });
587
- return normalized;
588
- }
589
- collectHeaders(headers) {
590
- const collected = {};
591
- Object.entries(headers).forEach((_ref3) => {
592
- let [key, value] = _ref3;
593
- if (Array.isArray(value)) {
594
- collected[key] = value.map((item) => String(item));
595
- return;
596
- }
597
- if (value !== void 0 && value !== null) {
598
- collected[key] = [String(value)];
599
- }
600
- });
601
- return collected;
602
- }
603
- normalizeBody(body) {
604
- if (body === void 0 || body === null) {
605
- return void 0;
606
- }
607
- if (typeof body === "string") {
608
- return body;
609
- }
610
- return JSON.stringify(body);
611
- }
612
- normalizeResponseBody(body) {
613
- if (!body) {
614
- return void 0;
615
- }
616
- try {
617
- return JSON.parse(body);
618
- } catch {
619
- return body;
620
- }
621
- }
622
- }
623
- const getPath = (path, map2) => {
624
- var _context;
625
- return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
626
- if (/^:/.test(part)) {
627
- return `${base}/${map2[part.slice(1)]}`;
628
- }
629
- return `${base}/${part}`;
630
- }, "").slice(1);
631
- };
632
- const consoleUnauthorizedMessage = () => {
633
- console.log("Not logged in");
634
- console.log('Login with "ones login" command');
635
- };
636
- const getURL = async (path, pathMap, queryMap) => {
637
- const base = await getRegionURL();
638
- if (base) {
639
- const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
640
- return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
641
- }
642
- consoleUnauthorizedMessage();
643
- process$1.exit(1);
644
- };
645
- const getHeaders = async (value) => {
646
- const token = await getONESToken();
647
- if (token) {
648
- return lodashEs.merge({
649
- Authorization: `Bearer ${token}`
650
- }, value);
651
- }
652
- consoleUnauthorizedMessage();
653
- process$1.exit(1);
654
- };
655
- const handleError = (error) => {
656
- var _error$response;
657
- if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
658
- console.log(error.response.statusText);
659
- consoleUnauthorizedMessage();
660
- } else {
661
- console.error(error);
662
495
  }
496
+ console.error(error);
663
497
  return {};
664
498
  };
665
- const API = {
666
- TOKEN_INFO: "/project/api/project/auth/token_info",
667
- HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
668
- APP_LIST: "/platform/api/app/list",
669
- APP_INSTALL: "/platform/api/app/install",
670
- APP_UPGRADE: "/platform/api/app/upgrade",
671
- APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
672
- APP_ENABLE: "/platform/api/app/:installation_id/enable",
673
- APP_DISABLE: "/platform/api/app/:installation_id/disable"
674
- };
675
- const isRecord = (value) => {
676
- return typeof value === "object" && value !== null;
677
- };
678
- const getHostedTokenScopes = (ones2) => {
679
- const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
680
- if (!storage) {
681
- return [];
682
- }
683
- const scopes = /* @__PURE__ */ new Set();
684
- if (Array.isArray(storage.entities) && storage.entities.length > 0) {
685
- scopes.add(createOnesApp.HostedTokenScope.STORAGE_ENTITY);
686
- }
687
- if (storage.object !== void 0 && storage.object !== null && storage.object !== false) {
688
- scopes.add(createOnesApp.HostedTokenScope.STORAGE_OBJECT);
689
- }
690
- return Array.from(scopes);
691
- };
692
- const getRelayScope = () => {
693
- return createOnesApp.HostedTokenScope.RELAY;
694
- };
695
- const getHostToken = async (baseUrl, userToken, appID, scopes) => {
696
- const url = `${baseUrl.replace(/\/$/, "")}${API.HOSTED_TOKEN}`;
697
- return axios.post(url, {
698
- app_id: appID,
699
- scopes
700
- }, {
701
- headers: {
702
- Authorization: `Bearer ${userToken}`
703
- }
704
- }).then((resp) => {
705
- const data = resp === null || resp === void 0 ? void 0 : resp.data;
706
- const tokenFromData = (value) => {
707
- if (isRecord(value) && isRecord(value.data)) {
708
- const hosted_token = value.data.hosted_token;
709
- if (typeof hosted_token === "string" && hosted_token.length > 0) {
710
- return hosted_token;
711
- }
712
- }
713
- return null;
714
- };
715
- const token = tokenFromData(data);
716
- if (token) {
717
- return token;
718
- }
719
- return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
720
- }).catch((error) => {
721
- handleError(error);
722
- return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_REQUEST_FAILED, i18n.t("error.hostedToken.requestFailed"));
723
- });
724
- };
725
499
  const fetchAppBase = async (params) => {
726
500
  var _params$url;
727
501
  const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
@@ -748,6 +522,13 @@ const fetchTokenInfo = async () => {
748
522
  method: "GET"
749
523
  }).catch(handleError);
750
524
  };
525
+ const fetchHostedToken = async (data) => {
526
+ return await fetchAppBase({
527
+ url: API.HOSTED_TOKEN,
528
+ method: "POST",
529
+ data
530
+ }).catch(handleError);
531
+ };
751
532
  const fetchAppInstall = async (data) => {
752
533
  var _appList$data$0$insta, _appList$data;
753
534
  const appID = getAppManifestJSON().app.id;
@@ -765,85 +546,372 @@ const fetchAppUninstall = async () => {
765
546
  const appID = getAppManifestJSON().app.id;
766
547
  const appList = await fetchAppList(appID);
767
548
  const installationID = (_appList$data$0$insta2 = (_appList$data2 = appList.data) === null || _appList$data2 === void 0 || (_appList$data2 = _appList$data2[0]) === null || _appList$data2 === void 0 ? void 0 : _appList$data2.installation_id) !== null && _appList$data$0$insta2 !== void 0 ? _appList$data$0$insta2 : "";
768
- return await fetchAppBase({
769
- url: API.APP_UNINSTALL,
770
- method: "POST",
771
- pathMap: {
772
- installation_id: installationID
773
- }
774
- }).catch(handleError);
549
+ if (installationID) {
550
+ return await fetchAppBase({
551
+ url: API.APP_UNINSTALL,
552
+ method: "POST",
553
+ pathMap: {
554
+ installation_id: installationID
555
+ }
556
+ }).catch(handleError);
557
+ }
558
+ consoleAppNotInstalledMessage();
559
+ process.exit(1);
775
560
  };
776
561
  const fetchAppEnable = async () => {
777
562
  var _appList$data$0$insta3, _appList$data3;
778
563
  const appID = getAppManifestJSON().app.id;
779
564
  const appList = await fetchAppList(appID);
780
565
  const installationID = (_appList$data$0$insta3 = (_appList$data3 = appList.data) === null || _appList$data3 === void 0 || (_appList$data3 = _appList$data3[0]) === null || _appList$data3 === void 0 ? void 0 : _appList$data3.installation_id) !== null && _appList$data$0$insta3 !== void 0 ? _appList$data$0$insta3 : "";
781
- return await fetchAppBase({
782
- url: API.APP_ENABLE,
783
- method: "POST",
784
- pathMap: {
785
- installation_id: installationID
786
- }
787
- }).catch(handleError);
566
+ if (installationID) {
567
+ return await fetchAppBase({
568
+ url: API.APP_ENABLE,
569
+ method: "POST",
570
+ pathMap: {
571
+ installation_id: installationID
572
+ }
573
+ }).catch(handleError);
574
+ }
575
+ consoleAppNotInstalledMessage();
576
+ process.exit(1);
788
577
  };
789
578
  const fetchAppDisable = async () => {
790
579
  var _appList$data$0$insta4, _appList$data4;
791
580
  const appID = getAppManifestJSON().app.id;
792
581
  const appList = await fetchAppList(appID);
793
582
  const installationID = (_appList$data$0$insta4 = (_appList$data4 = appList.data) === null || _appList$data4 === void 0 || (_appList$data4 = _appList$data4[0]) === null || _appList$data4 === void 0 ? void 0 : _appList$data4.installation_id) !== null && _appList$data$0$insta4 !== void 0 ? _appList$data$0$insta4 : "";
794
- return await fetchAppBase({
795
- url: API.APP_DISABLE,
796
- method: "POST",
797
- pathMap: {
798
- installation_id: installationID
799
- }
800
- }).catch(handleError);
583
+ if (installationID) {
584
+ return await fetchAppBase({
585
+ url: API.APP_DISABLE,
586
+ method: "POST",
587
+ pathMap: {
588
+ installation_id: installationID
589
+ }
590
+ }).catch(handleError);
591
+ }
592
+ consoleAppNotInstalledMessage();
593
+ process.exit(1);
801
594
  };
802
- const ONES_CLI_MANIFEST_PATH = "/__ones_cli_manifest__";
803
- const buildTunnelContext = async () => {
804
- var _appManifestJSON$app$, _appManifestJSON$app;
595
+ const getTunnelContext = async () => {
596
+ var _appManifestJSON$app$, _appManifestJSON$app, _store$region_url, _store$ones_token;
805
597
  const appManifestJSON = getAppManifestJSON();
806
598
  const appID = (_appManifestJSON$app$ = (_appManifestJSON$app = appManifestJSON.app) === null || _appManifestJSON$app === void 0 ? void 0 : _appManifestJSON$app.id) !== null && _appManifestJSON$app$ !== void 0 ? _appManifestJSON$app$ : "";
807
- if (!appID) {
808
- throw new Error("app id is empty");
599
+ const store = await getStore();
600
+ const regionURL = (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
601
+ const onesToken = (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
602
+ if (appID && regionURL && onesToken) {
603
+ return {
604
+ appID,
605
+ regionURL,
606
+ onesToken,
607
+ store,
608
+ appManifestJSON
609
+ };
610
+ }
611
+ consoleUnauthorizedMessage();
612
+ process.exit(1);
613
+ };
614
+ const getHostedTokenScopes = (ones2) => {
615
+ const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
616
+ if (!storage) {
617
+ return [];
809
618
  }
810
- const regionURL = await getRegionURL();
811
- if (!regionURL) {
812
- throw new Error("region url is empty");
619
+ const scopes = /* @__PURE__ */ new Set();
620
+ if (Array.isArray(storage.entities) && storage.entities.length > 0) {
621
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_ENTITY);
813
622
  }
814
- return {
815
- appManifestJSON,
816
- appID,
817
- regionURL
818
- };
623
+ if (storage.object !== void 0 && storage.object !== null && storage.object !== false) {
624
+ scopes.add(createOnesApp.HostedTokenScope.STORAGE_OBJECT);
625
+ }
626
+ return Array.from(scopes);
627
+ };
628
+ const getRelayScope = () => {
629
+ return createOnesApp.HostedTokenScope.RELAY;
819
630
  };
820
631
  const buildTunnelUrl = async () => {
821
632
  const {
822
633
  appID,
823
634
  regionURL
824
- } = await buildTunnelContext();
635
+ } = await getTunnelContext();
825
636
  const url = new URL(regionURL);
826
- return `${url.protocol}//${url.host}/platform/app/relay/dispatch/${appID}`;
637
+ url.pathname = `/platform/app/relay/dispatch/${appID}`;
638
+ return url.toString();
827
639
  };
828
- const invokeTunnel = async (port) => {
640
+ class TunnelClient {
641
+ constructor(localPort, baseUrl, appID, hostedToken) {
642
+ let enableInternalManifestRoute = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
643
+ let replaceExisting = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : true;
644
+ this.ws = null;
645
+ this.localPort = localPort;
646
+ this.baseUrl = baseUrl;
647
+ this.appID = appID;
648
+ this.hostedToken = hostedToken;
649
+ this.enableInternalManifestRoute = enableInternalManifestRoute;
650
+ this.replaceExisting = replaceExisting;
651
+ }
652
+ async connect() {
653
+ const proxyUrl = this.buildProxyUrl();
654
+ this.ws = new WebSocket(proxyUrl, {
655
+ headers: {
656
+ Authorization: `Bearer ${this.hostedToken}`
657
+ },
658
+ maxPayload: MAX_RELAY_BODY_BYTES
659
+ });
660
+ this.ws.on("message", async (data) => {
661
+ const message = this.parseMessage(data);
662
+ if (!message) {
663
+ return;
664
+ }
665
+ await this.handleMessage(message);
666
+ });
667
+ this.ws.on("ping", (data) => {
668
+ var _this$ws;
669
+ (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
670
+ });
671
+ this.ws.on("error", (error) => {
672
+ console.error("WebSocket error:", error);
673
+ });
674
+ return new Promise((resolve, reject) => {
675
+ var _this$ws2, _this$ws3;
676
+ (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
677
+ (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
678
+ });
679
+ }
680
+ close() {
681
+ var _this$ws4;
682
+ (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
683
+ }
684
+ buildProxyUrl() {
685
+ const url = new URL("/platform/app/relay/", this.baseUrl);
686
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
687
+ url.searchParams.set("app_id", this.appID);
688
+ url.searchParams.set("replace_existing", String(this.replaceExisting));
689
+ return url.toString();
690
+ }
691
+ parseMessage(data) {
692
+ const buffer = this.toBuffer(data);
693
+ if (!buffer) {
694
+ return null;
695
+ }
696
+ if (buffer.length >= 4) {
697
+ const binary = this.parseBinaryEnvelope(buffer);
698
+ if (binary) {
699
+ return binary;
700
+ }
701
+ }
702
+ return this.parseJSONEnvelope(buffer.toString());
703
+ }
704
+ async handleMessage(message) {
705
+ const request = this.getRequestPayload(message);
706
+ if (!request) {
707
+ return;
708
+ }
709
+ if (this.enableInternalManifestRoute && request.path === ONES_CLI_INTERNAL_MANIFEST_PATH) {
710
+ const appManifest = getAppManifestJSON().app;
711
+ const baseURL = await buildTunnelUrl();
712
+ const reply = {
713
+ id: message.id,
714
+ payload: {
715
+ status: 200,
716
+ headers: {
717
+ "content-type": ["application/json"]
718
+ },
719
+ body: {
720
+ ...appManifest,
721
+ base_url: baseURL
722
+ }
723
+ }
724
+ };
725
+ this.sendBinaryEnvelope(reply);
726
+ return;
727
+ }
728
+ try {
729
+ const response = await this.forwardRequest(request);
730
+ const reply = {
731
+ id: message.id,
732
+ payload: response
733
+ };
734
+ this.sendBinaryEnvelope(reply);
735
+ } catch (error) {
736
+ const reply = {
737
+ id: message.id,
738
+ payload: {
739
+ status: 500,
740
+ headers: {
741
+ "x-agent-error": [error instanceof Error ? error.message : "Unknown error"]
742
+ },
743
+ body: "agent request error"
744
+ }
745
+ };
746
+ this.sendBinaryEnvelope(reply);
747
+ }
748
+ }
749
+ getRequestPayload(message) {
750
+ const payload = message.payload;
751
+ if (!(payload !== null && payload !== void 0 && payload.method) || !(payload !== null && payload !== void 0 && payload.path)) {
752
+ return null;
753
+ }
754
+ return payload;
755
+ }
756
+ async forwardRequest(payload) {
757
+ const url = new URL(payload.path, `http://127.0.0.1:${this.localPort}`);
758
+ if (payload.query) {
759
+ Object.entries(payload.query).forEach((_ref) => {
760
+ let [key, value] = _ref;
761
+ if (Array.isArray(value)) {
762
+ value.forEach((item) => {
763
+ url.searchParams.append(key, item);
764
+ });
765
+ return;
766
+ }
767
+ url.searchParams.append(key, value);
768
+ });
769
+ }
770
+ const response = await axios.request({
771
+ url: url.toString(),
772
+ method: payload.method,
773
+ headers: payload.headers,
774
+ data: payload.body,
775
+ responseType: "arraybuffer",
776
+ validateStatus: () => true,
777
+ maxBodyLength: MAX_RELAY_BODY_BYTES,
778
+ maxContentLength: MAX_RELAY_BODY_BYTES
779
+ });
780
+ const responseBytes = Buffer.from(response.data);
781
+ return {
782
+ status: response.status,
783
+ headers: this.collectHeaders(response.headers),
784
+ body: responseBytes
785
+ };
786
+ }
787
+ collectHeaders(headers) {
788
+ const collected = {};
789
+ Object.entries(headers).forEach((_ref2) => {
790
+ let [key, value] = _ref2;
791
+ if (Array.isArray(value)) {
792
+ collected[key] = value.map((item) => String(item));
793
+ return;
794
+ }
795
+ if (value !== void 0 && value !== null) {
796
+ collected[key] = [String(value)];
797
+ }
798
+ });
799
+ return collected;
800
+ }
801
+ sendBinaryEnvelope(envelope) {
802
+ var _this$ws5;
803
+ const encoded = this.encodeBinaryEnvelope(envelope);
804
+ (_this$ws5 = this.ws) === null || _this$ws5 === void 0 || _this$ws5.send(encoded);
805
+ }
806
+ encodeBinaryEnvelope(envelope) {
807
+ var _envelope$payload;
808
+ const payload = (_envelope$payload = envelope.payload) !== null && _envelope$payload !== void 0 ? _envelope$payload : {};
809
+ const body = this.toBodyBuffer(payload.body);
810
+ if (body.length > MAX_RELAY_BODY_BYTES) {
811
+ throw new Error("relay body too large");
812
+ }
813
+ const metaPayload = {
814
+ ...payload
815
+ };
816
+ delete metaPayload.body;
817
+ const meta = Buffer.from(JSON.stringify({
818
+ id: envelope.id,
819
+ payload: metaPayload
820
+ }), "utf8");
821
+ const header = Buffer.allocUnsafe(4);
822
+ header.writeUInt32BE(meta.length, 0);
823
+ return Buffer.concat([header, meta, body]);
824
+ }
825
+ toBodyBuffer(body) {
826
+ if (body === void 0 || body === null) {
827
+ return Buffer.alloc(0);
828
+ }
829
+ if (Buffer.isBuffer(body)) {
830
+ return body;
831
+ }
832
+ if (body instanceof ArrayBuffer) {
833
+ return Buffer.from(body);
834
+ }
835
+ if (ArrayBuffer.isView(body)) {
836
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
837
+ }
838
+ if (typeof body === "string") {
839
+ return Buffer.from(body, "utf8");
840
+ }
841
+ return Buffer.from(JSON.stringify(body), "utf8");
842
+ }
843
+ parseBinaryEnvelope(buffer) {
844
+ const metaLength = buffer.readUInt32BE(0);
845
+ if (metaLength <= 0 || 4 + metaLength > buffer.length) {
846
+ return null;
847
+ }
848
+ const metaRaw = buffer.subarray(4, 4 + metaLength).toString("utf8");
849
+ try {
850
+ const envelope = JSON.parse(metaRaw);
851
+ if (!(envelope !== null && envelope !== void 0 && envelope.payload)) {
852
+ return envelope;
853
+ }
854
+ const body = buffer.subarray(4 + metaLength);
855
+ if (body.length > MAX_RELAY_BODY_BYTES) {
856
+ console.error("Binary tunnel body exceeds size limit");
857
+ return null;
858
+ }
859
+ const payload = envelope.payload;
860
+ payload.body = body;
861
+ return envelope;
862
+ } catch (error) {
863
+ console.error("Invalid binary tunnel message:", error);
864
+ return null;
865
+ }
866
+ }
867
+ parseJSONEnvelope(payload) {
868
+ try {
869
+ const message = JSON.parse(payload);
870
+ if (!message) {
871
+ return null;
872
+ }
873
+ return message;
874
+ } catch (error) {
875
+ console.error("Invalid tunnel message:", error);
876
+ return null;
877
+ }
878
+ }
879
+ toBuffer(data) {
880
+ if (Buffer.isBuffer(data)) {
881
+ return data;
882
+ }
883
+ if (Array.isArray(data)) {
884
+ return Buffer.concat(data);
885
+ }
886
+ if (data instanceof ArrayBuffer) {
887
+ return Buffer.from(data);
888
+ }
889
+ return null;
890
+ }
891
+ }
892
+ const invokeTunnel = async function(port) {
893
+ var _options$rebuildWhenE, _options$enableIntern, _hostedTokenResponse$;
894
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
829
895
  const {
830
896
  appManifestJSON,
831
897
  appID,
832
898
  regionURL
833
- } = await buildTunnelContext();
834
- const onesToken = await getONESToken();
835
- if (!onesToken) {
836
- consoleUnauthorizedMessage();
837
- process$1.exit(1);
838
- }
899
+ } = await getTunnelContext();
900
+ const rebuildWhenExists = (_options$rebuildWhenE = options.rebuildWhenExists) !== null && _options$rebuildWhenE !== void 0 ? _options$rebuildWhenE : true;
901
+ const enableInternalManifestRoute = (_options$enableIntern = options.enableInternalManifestRoute) !== null && _options$enableIntern !== void 0 ? _options$enableIntern : true;
839
902
  const storageScopes = getHostedTokenScopes(appManifestJSON.ones);
840
903
  const scopes = Array.from(/* @__PURE__ */ new Set([...storageScopes, getRelayScope()]));
841
- const hostedToken = await getHostToken(regionURL, onesToken, appID, scopes);
842
- process.env.ONES_HOSTED_TOKEN = hostedToken;
843
- const client = new TunnelClient(port, regionURL, appID, hostedToken);
904
+ const hostedTokenResponse = await fetchHostedToken({
905
+ app_id: appID,
906
+ scopes
907
+ });
908
+ const hostedToken = hostedTokenResponse === null || hostedTokenResponse === void 0 || (_hostedTokenResponse$ = hostedTokenResponse.data) === null || _hostedTokenResponse$ === void 0 ? void 0 : _hostedTokenResponse$.hosted_token;
909
+ if (!hostedToken) {
910
+ return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
911
+ }
912
+ await setHostToken(hostedToken);
913
+ const client = new TunnelClient(port, regionURL, appID, hostedToken, enableInternalManifestRoute, rebuildWhenExists);
844
914
  await client.connect();
845
- const runnelUrl = await buildTunnelUrl();
846
- console.log(`Relay endpoint: ${runnelUrl}`);
847
915
  };
848
916
  const tunnel = async function() {
849
917
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
@@ -852,16 +920,156 @@ const tunnel = async function() {
852
920
  const {
853
921
  options
854
922
  } = createOnesApp.getCommandOptions(args, tunnelCommandArguments);
855
- const normalizedOptions = await normalize$8(options);
856
- await invokeTunnel(Number(normalizedOptions.port));
923
+ const normalizedOptions = await normalize$9(options);
924
+ await invokeTunnel(Number(normalizedOptions.port), {
925
+ enableInternalManifestRoute: false,
926
+ rebuildWhenExists: true
927
+ });
928
+ const runnelUrl = await buildTunnelUrl();
929
+ console.log(`Relay endpoint: ${runnelUrl}`);
857
930
  };
858
- const config = {
859
- defaultPort: {
860
- login: 8200,
861
- tunnel: 8201
931
+ var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
932
+ InstallOptions2["AUTO"] = "auto";
933
+ InstallOptions2["TRUE"] = "true";
934
+ InstallOptions2["FALSE"] = "false";
935
+ return InstallOptions2;
936
+ })(InstallOptions || {});
937
+ const defaultInstall = InstallOptions.AUTO;
938
+ const normalize$8 = async (options) => {
939
+ var _options$install;
940
+ let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
941
+ switch (true) {
942
+ case install2 === InstallOptions.AUTO:
943
+ break;
944
+ case Boolean(install2):
945
+ install2 = InstallOptions.TRUE;
946
+ break;
947
+ default:
948
+ install2 = InstallOptions.FALSE;
949
+ break;
862
950
  }
951
+ return {
952
+ install: install2
953
+ };
954
+ };
955
+ const IDLE_MS = 100;
956
+ function createReadyStatusPipes(onReady) {
957
+ let readyTimer = null;
958
+ let summaryPrinted = false;
959
+ const scheduleReady = () => {
960
+ if (summaryPrinted)
961
+ return;
962
+ if (readyTimer)
963
+ clearTimeout(readyTimer);
964
+ readyTimer = setTimeout(() => {
965
+ readyTimer = null;
966
+ if (!summaryPrinted) {
967
+ summaryPrinted = true;
968
+ onReady();
969
+ }
970
+ }, IDLE_MS);
971
+ };
972
+ const pipe = (stream, isStderr) => {
973
+ const write = (chunk) => {
974
+ if (isStderr)
975
+ process.stderr.write(chunk);
976
+ else
977
+ process.stdout.write(chunk);
978
+ };
979
+ stream.on("data", (chunk) => {
980
+ const str = typeof chunk === "string" ? chunk : chunk.toString();
981
+ write(str);
982
+ scheduleReady();
983
+ });
984
+ };
985
+ return pipe;
986
+ }
987
+ const dev = async function() {
988
+ var _ref, _appRcJSON$dev$comman, _appRcJSON$dev, _defaultAppRcJSON$dev;
989
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
990
+ args[_key] = arguments[_key];
991
+ }
992
+ const {
993
+ options
994
+ } = createOnesApp.getCommandOptions(args, devCommandArguments);
995
+ const normalizedOptions = await normalize$8(options);
996
+ const appRcJSON = await getAppRcJSON();
997
+ const appPackageJSON = getAppPackageJSON();
998
+ const currentCommand = (_ref = (_appRcJSON$dev$comman = (_appRcJSON$dev = appRcJSON.dev) === null || _appRcJSON$dev === void 0 || (_appRcJSON$dev = _appRcJSON$dev.command) === null || _appRcJSON$dev === void 0 ? void 0 : _appRcJSON$dev[0]) !== null && _appRcJSON$dev$comman !== void 0 ? _appRcJSON$dev$comman : (_defaultAppRcJSON$dev = defaultAppRcJSON.dev) === null || _defaultAppRcJSON$dev === void 0 || (_defaultAppRcJSON$dev = _defaultAppRcJSON$dev.command) === null || _defaultAppRcJSON$dev === void 0 ? void 0 : _defaultAppRcJSON$dev[0]) !== null && _ref !== void 0 ? _ref : "";
999
+ if (!currentCommand) {
1000
+ process.exit(1);
1001
+ }
1002
+ if (currentCommand === defaultAppRcJSONDevCommand) {
1003
+ var _appPackageJSON$scrip;
1004
+ if (!((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev)) {
1005
+ return createOnesApp.throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
1006
+ }
1007
+ }
1008
+ const port = getConfig().defaultPort.tunnel;
1009
+ await invokeTunnel(port, {
1010
+ enableInternalManifestRoute: true,
1011
+ rebuildWhenExists: true
1012
+ });
1013
+ const runnelUrl = await buildTunnelUrl();
1014
+ const manifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1015
+ const ONES_HOSTED_TOKEN = await getHostToken();
1016
+ const cwd = getAppWorkspacePath();
1017
+ const env2 = {
1018
+ ...process.env,
1019
+ NODE_ENV: "development",
1020
+ ONES_HOSTED_PORT: `${port}`,
1021
+ ONES_HOSTED_TOKEN
1022
+ };
1023
+ const {
1024
+ ones: ones2
1025
+ } = getAppManifestJSON();
1026
+ lodashEs.noop(ones2);
1027
+ const onReady = () => {
1028
+ console.log("");
1029
+ console.log(`Local: http://localhost:${port}`);
1030
+ console.log(`Relay endpoint: ${runnelUrl}`);
1031
+ console.log(`Manifest URL: ${manifestUrl}`);
1032
+ console.log("");
1033
+ switch (normalizedOptions.install) {
1034
+ case InstallOptions.TRUE:
1035
+ console.log("InstallOptions.TRUE");
1036
+ break;
1037
+ case InstallOptions.AUTO:
1038
+ console.log("InstallOptions.AUTO");
1039
+ break;
1040
+ case InstallOptions.FALSE:
1041
+ break;
1042
+ }
1043
+ };
1044
+ const child = node_child_process.spawn(currentCommand, [], {
1045
+ cwd,
1046
+ stdio: ["inherit", "pipe", "pipe"],
1047
+ env: env2,
1048
+ shell: true
1049
+ });
1050
+ const pipe = createReadyStatusPipes(onReady);
1051
+ if (child.stdout)
1052
+ pipe(child.stdout, false);
1053
+ if (child.stderr)
1054
+ pipe(child.stderr, true);
1055
+ const cleanup = () => {
1056
+ child.kill();
1057
+ };
1058
+ const onSignal = () => {
1059
+ cleanup();
1060
+ process.exit(128 + 2);
1061
+ };
1062
+ process.on("SIGINT", onSignal);
1063
+ process.on("SIGTERM", onSignal);
1064
+ await new Promise((resolve) => {
1065
+ child.on("exit", () => {
1066
+ cleanup();
1067
+ process.off("SIGINT", onSignal);
1068
+ process.off("SIGTERM", onSignal);
1069
+ resolve();
1070
+ });
1071
+ });
863
1072
  };
864
- const getConfig = () => config;
865
1073
  function createPromise() {
866
1074
  let resolve;
867
1075
  let reject;
@@ -926,7 +1134,7 @@ const login = async function() {
926
1134
  const port = await getPort({
927
1135
  port: config2.defaultPort.login
928
1136
  });
929
- const uuid$1 = uuid.v7();
1137
+ const uuid$1 = uuid.v4();
930
1138
  const search = new URLSearchParams();
931
1139
  search.set("redirect_path", "/developer/cli");
932
1140
  search.set("redirect_url", `http://localhost:${port}`);
@@ -1038,7 +1246,8 @@ const whoami = async function() {
1038
1246
  const name2 = (_tokenInfo$user = tokenInfo.user) === null || _tokenInfo$user === void 0 ? void 0 : _tokenInfo$user.name;
1039
1247
  const email = (_tokenInfo$user2 = tokenInfo.user) === null || _tokenInfo$user2 === void 0 ? void 0 : _tokenInfo$user2.email;
1040
1248
  if (name2 && email) {
1041
- console.log(`${name2} <${email}>`);
1249
+ console.log(`User: ${name2}`);
1250
+ console.log(`Email: ${email}`);
1042
1251
  console.log(`ONES: ${baseURL}`);
1043
1252
  } else {
1044
1253
  consoleUnauthorizedMessage();
@@ -1048,6 +1257,30 @@ const normalize$4 = async (options) => {
1048
1257
  lodashEs.noop(options);
1049
1258
  return {};
1050
1259
  };
1260
+ const getManifestUrl = async () => {
1261
+ const runnelUrl = await buildTunnelUrl();
1262
+ const customManifestUrl = `${runnelUrl}${MANIFEST_PATH}`;
1263
+ const internalManifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1264
+ const internalResult = await axios.get(internalManifestUrl).then((response) => {
1265
+ if (response.status === 200) {
1266
+ return internalManifestUrl;
1267
+ }
1268
+ return null;
1269
+ }).catch(lodashEs.noop);
1270
+ if (internalResult) {
1271
+ return internalResult;
1272
+ }
1273
+ const customResult = await axios.get(customManifestUrl).then((response) => {
1274
+ if (response.status === 200) {
1275
+ return customManifestUrl;
1276
+ }
1277
+ return null;
1278
+ }).catch(lodashEs.noop);
1279
+ if (customResult) {
1280
+ return customResult;
1281
+ }
1282
+ return null;
1283
+ };
1051
1284
  const install = async function() {
1052
1285
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1053
1286
  args[_key] = arguments[_key];
@@ -1057,15 +1290,44 @@ const install = async function() {
1057
1290
  } = createOnesApp.getCommandOptions(args, installCommandArguments);
1058
1291
  const normalizedOptions = await normalize$4(options);
1059
1292
  lodashEs.noop(normalizedOptions);
1060
- await invokeTunnel(getConfig().defaultPort.tunnel);
1061
- const runnelUrl = await buildTunnelUrl();
1293
+ const {
1294
+ app
1295
+ } = getAppManifestJSON();
1296
+ const appName = app.name;
1297
+ const appID = app.id;
1298
+ const manifestUrl = await getManifestUrl();
1299
+ if (!manifestUrl) {
1300
+ console.log(`App "${appName}" server not available!`);
1301
+ console.log('Use "ones dev" command or "ones tunnel" command to start the server first');
1302
+ process.exit(1);
1303
+ }
1062
1304
  const result = await fetchAppInstall({
1063
- manifest_url: `${runnelUrl}${ONES_CLI_MANIFEST_PATH}`
1305
+ manifest_url: manifestUrl
1064
1306
  });
1065
1307
  if (result.code === "OK") {
1066
- console.log("App installed successfully!");
1308
+ var _appList$data$0$insta, _appList$data;
1309
+ console.log(`App "${appName}" installed successfully!`);
1310
+ const appList = await fetchAppList(appID);
1311
+ const installationID = (_appList$data$0$insta = (_appList$data = appList.data) === null || _appList$data === void 0 || (_appList$data = _appList$data[0]) === null || _appList$data === void 0 ? void 0 : _appList$data.installation_id) !== null && _appList$data$0$insta !== void 0 ? _appList$data$0$insta : "";
1312
+ if (installationID) {
1313
+ var _tokenInfo$org$uuid, _tokenInfo$org, _tokenInfo$teams$0$uu, _tokenInfo$teams, _tokenInfo$org$visibi, _tokenInfo$org2;
1314
+ const tokenInfo = await fetchTokenInfo();
1315
+ const orgUUID = (_tokenInfo$org$uuid = (_tokenInfo$org = tokenInfo.org) === null || _tokenInfo$org === void 0 ? void 0 : _tokenInfo$org.uuid) !== null && _tokenInfo$org$uuid !== void 0 ? _tokenInfo$org$uuid : "";
1316
+ const teamUUID = (_tokenInfo$teams$0$uu = (_tokenInfo$teams = tokenInfo.teams) === null || _tokenInfo$teams === void 0 || (_tokenInfo$teams = _tokenInfo$teams[0]) === null || _tokenInfo$teams === void 0 ? void 0 : _tokenInfo$teams.uuid) !== null && _tokenInfo$teams$0$uu !== void 0 ? _tokenInfo$teams$0$uu : "";
1317
+ const isOrgVisible = (_tokenInfo$org$visibi = (_tokenInfo$org2 = tokenInfo.org) === null || _tokenInfo$org2 === void 0 ? void 0 : _tokenInfo$org2.visibility) !== null && _tokenInfo$org$visibi !== void 0 ? _tokenInfo$org$visibi : false;
1318
+ const baseURL = await getBaseURL();
1319
+ if (isOrgVisible && orgUUID) {
1320
+ const url = `${baseURL}/project/#/org/${orgUUID}/setting/app_manager/platform_app/${installationID}`;
1321
+ console.log(`See App detail: ${url}`);
1322
+ }
1323
+ if (!isOrgVisible && teamUUID) {
1324
+ const url = `${baseURL}/project/#/team/${teamUUID}/team_setting/app_manager/platform_app/${installationID}`;
1325
+ console.log(`See App detail: ${url}`);
1326
+ }
1327
+ }
1067
1328
  } else {
1068
- console.error(result);
1329
+ console.log(`App "${appName}" installed failed!`);
1330
+ console.error(JSON.stringify(result, null, 2));
1069
1331
  }
1070
1332
  };
1071
1333
  const normalize$3 = async (options) => {
@@ -1081,11 +1343,13 @@ const enable = async function() {
1081
1343
  } = createOnesApp.getCommandOptions(args, enableCommandArguments);
1082
1344
  const normalizedOptions = await normalize$3(options);
1083
1345
  lodashEs.noop(normalizedOptions);
1346
+ const appName = getAppManifestJSON().app.name;
1084
1347
  const result = await fetchAppEnable();
1085
1348
  if (result.code === "OK") {
1086
- console.log("App enabled successfully!");
1349
+ console.log(`App "${appName}" enabled successfully!`);
1087
1350
  } else {
1088
- console.error(result);
1351
+ console.log(`App "${appName}" enabled failed!`);
1352
+ console.error(JSON.stringify(result, null, 2));
1089
1353
  }
1090
1354
  };
1091
1355
  const normalize$2 = async (options) => {
@@ -1101,11 +1365,13 @@ const disable = async function() {
1101
1365
  } = createOnesApp.getCommandOptions(args, disableCommandArguments);
1102
1366
  const normalizedOptions = await normalize$2(options);
1103
1367
  lodashEs.noop(normalizedOptions);
1368
+ const appName = getAppManifestJSON().app.name;
1104
1369
  const result = await fetchAppDisable();
1105
1370
  if (result.code === "OK") {
1106
- console.log("App disabled successfully!");
1371
+ console.log(`App "${appName}" disabled successfully!`);
1107
1372
  } else {
1108
- console.error(result);
1373
+ console.log(`App "${appName}" disabled failed!`);
1374
+ console.error(JSON.stringify(result, null, 2));
1109
1375
  }
1110
1376
  };
1111
1377
  const normalize$1 = async (options) => {
@@ -1121,11 +1387,13 @@ const uninstall = async function() {
1121
1387
  } = createOnesApp.getCommandOptions(args, uninstallCommandArguments);
1122
1388
  const normalizedOptions = await normalize$1(options);
1123
1389
  lodashEs.noop(normalizedOptions);
1390
+ const appName = getAppManifestJSON().app.name;
1124
1391
  const result = await fetchAppUninstall();
1125
1392
  if (result.code === "OK") {
1126
- console.log("App uninstalled successfully!");
1393
+ console.log(`App "${appName}" uninstalled successfully!`);
1127
1394
  } else {
1128
- console.error(result);
1395
+ console.log(`App "${appName}" uninstalled failed!`);
1396
+ console.error(JSON.stringify(result, null, 2));
1129
1397
  }
1130
1398
  };
1131
1399
  const normalize = async (options) => {
@@ -1191,7 +1459,11 @@ const $legacy = new commander.Command("legacy").description(i18n.t("desc.legacy"
1191
1459
  createOnesApp.addCommandUsage($legacy);
1192
1460
  createOnesApp.addCommandOutput($legacy);
1193
1461
  const ones = new commander.Command("ones");
1194
- ones.description(i18n.t("desc.ones")).addCommand(createOnesApp.$create).addCommand($build).addCommand($dev).addCommand($tunnel).addCommand($app).addCommand($login).addCommand($logout).addCommand($whoami).addCommand($legacy).configureHelp({
1462
+ const version = `${getPackageJSON().version}`;
1463
+ const env = `${version} Node/${process.version}`;
1464
+ ones.description(i18n.t("desc.ones", {
1465
+ env
1466
+ })).addCommand(createOnesApp.$create).addCommand($build).addCommand($dev).addCommand($tunnel).addCommand($app).addCommand($login).addCommand($logout).addCommand($whoami).addCommand($legacy).configureHelp({
1195
1467
  visibleCommands: (cmd) => {
1196
1468
  const blackList = ["legacy"];
1197
1469
  return cmd.commands.filter((command) => !_includesInstanceProperty(blackList).call(blackList, command.name()));
@@ -1204,8 +1476,8 @@ createOnesApp.addCommandOutput(ones);
1204
1476
  const runCommandONES = async () => {
1205
1477
  const command = ones;
1206
1478
  createOnesApp.setContext("command", command);
1207
- const version = `${getPackageJSON().version}`;
1208
- command.version(version);
1479
+ const version2 = `${getPackageJSON().version}`;
1480
+ command.version(version2, "-v, --version");
1209
1481
  await command.parse();
1210
1482
  };
1211
1483
  exports.runCommandONES = runCommandONES;