@ones-open/cli 1.0.1-5596.1908 → 1.0.1-8888.1931

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/dist/index.cjs CHANGED
@@ -14,10 +14,9 @@ const cosmiconfig = require("cosmiconfig");
14
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");
@@ -222,7 +221,11 @@ const build = async function() {
222
221
  if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
223
222
  node_child_process.spawnSync("npm", ["run", "build"], {
224
223
  cwd: getAppWorkspacePath(),
225
- stdio: "inherit"
224
+ stdio: "inherit",
225
+ env: {
226
+ ...process.env,
227
+ NODE_ENV: "production"
228
+ }
226
229
  });
227
230
  } else {
228
231
  return createOnesApp.throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
@@ -272,109 +275,6 @@ const config = {
272
275
  }
273
276
  };
274
277
  const getConfig = () => config;
275
- var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
276
- InstallOptions2["AUTO"] = "auto";
277
- InstallOptions2["TRUE"] = "true";
278
- InstallOptions2["FALSE"] = "false";
279
- return InstallOptions2;
280
- })(InstallOptions || {});
281
- const defaultInstall = InstallOptions.AUTO;
282
- const normalize$9 = async (options) => {
283
- var _options$install;
284
- let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
285
- switch (true) {
286
- case install2 === InstallOptions.AUTO:
287
- break;
288
- case Boolean(install2):
289
- install2 = InstallOptions.TRUE;
290
- break;
291
- default:
292
- install2 = InstallOptions.FALSE;
293
- break;
294
- }
295
- return {
296
- install: install2
297
- };
298
- };
299
- const dev = async function() {
300
- var _appPackageJSON$scrip;
301
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
302
- args[_key] = arguments[_key];
303
- }
304
- const {
305
- options
306
- } = createOnesApp.getCommandOptions(args, devCommandArguments);
307
- const normalizedOptions = await normalize$9(options);
308
- const appPackageJSON = getAppPackageJSON();
309
- const appManifestJSON = getAppManifestJSON();
310
- const appRcJSON = getAppRcJSON();
311
- lodashEs.noop(appManifestJSON);
312
- lodashEs.noop(appRcJSON);
313
- if (!((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev)) {
314
- return createOnesApp.throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
315
- }
316
- const port = getConfig().defaultPort.tunnel;
317
- const cwd = getAppWorkspacePath();
318
- const env = {
319
- ...process.env,
320
- ONES_HOSTED_PORT: `${port}`
321
- };
322
- const tunnelChild = node_child_process.spawn("ones", ["tunnel", String(port)], {
323
- cwd,
324
- stdio: "inherit"
325
- });
326
- const devChild = node_child_process.spawn("npm", ["run", "dev"], {
327
- cwd,
328
- stdio: "inherit",
329
- env
330
- });
331
- const cleanup = () => {
332
- tunnelChild.kill();
333
- devChild.kill();
334
- };
335
- const onSignal = () => {
336
- cleanup();
337
- process.exit(128 + 2);
338
- };
339
- process.on("SIGINT", onSignal);
340
- process.on("SIGTERM", onSignal);
341
- if (normalizedOptions.install) {
342
- lodashEs.noop(normalizedOptions.install);
343
- }
344
- await new Promise((resolve) => {
345
- devChild.on("exit", () => {
346
- cleanup();
347
- process.off("SIGINT", onSignal);
348
- process.off("SIGTERM", onSignal);
349
- resolve();
350
- });
351
- });
352
- };
353
- const isPortNumber = /^[1-9]\d{0,4}$/;
354
- const minPortNumber = 1;
355
- const maxPortNumber = 65535;
356
- const normalize$8 = async (options) => {
357
- const portInput = options.port;
358
- if (portInput)
359
- ;
360
- else {
361
- return createOnesApp.throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
362
- }
363
- const portString = String(portInput);
364
- const portNumber = Number(portString);
365
- if (isPortNumber.test(portString))
366
- ;
367
- else {
368
- return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
369
- }
370
- if (portNumber < minPortNumber || portNumber > maxPortNumber) {
371
- return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
372
- }
373
- const port = portString;
374
- return {
375
- port
376
- };
377
- };
378
278
  const StoreJSONSchema = zod.z.object({
379
279
  version: zod.z.string().optional(),
380
280
  timestamp: zod.z.number().optional(),
@@ -476,61 +376,234 @@ const setONESToken = async (token) => {
476
376
  ones_token: token
477
377
  });
478
378
  };
479
- class TunnelClient {
480
- constructor(localPort, baseUrl, appID, hostedToken) {
481
- _defineProperty(this, "ws", null);
482
- this.localPort = localPort;
483
- this.baseUrl = baseUrl;
484
- this.appID = appID;
485
- this.hostedToken = hostedToken;
486
- }
487
- async connect() {
488
- const proxyUrl = this.buildProxyUrl();
489
- this.ws = new WebSocket(proxyUrl, {
490
- headers: {
491
- Authorization: `Bearer ${this.hostedToken}`
492
- }
493
- });
494
- this.ws.on("message", async (data) => {
495
- const message = this.parseMessage(data);
496
- if (!message) {
497
- return;
498
- }
499
- await this.handleMessage(message);
500
- });
501
- this.ws.on("ping", (data) => {
502
- var _this$ws;
503
- (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
504
- });
505
- this.ws.on("error", (error) => {
506
- console.error("WebSocket error:", error);
507
- });
508
- return new Promise((resolve, reject) => {
509
- var _this$ws2, _this$ws3;
510
- (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
511
- (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
512
- });
379
+ const getHostToken = async () => {
380
+ var _store$host_token;
381
+ const store = await getStore();
382
+ return (_store$host_token = store.host_token) !== null && _store$host_token !== void 0 ? _store$host_token : "";
383
+ };
384
+ const API = {
385
+ TOKEN_INFO: "/project/api/project/auth/token_info",
386
+ HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
387
+ APP_LIST: "/platform/api/app/list",
388
+ APP_INSTALL: "/platform/api/app/install",
389
+ APP_UPGRADE: "/platform/api/app/upgrade",
390
+ APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
391
+ APP_ENABLE: "/platform/api/app/:installation_id/enable",
392
+ APP_DISABLE: "/platform/api/app/:installation_id/disable"
393
+ };
394
+ const getPath = (path, map2) => {
395
+ var _context;
396
+ return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
397
+ if (/^:/.test(part)) {
398
+ return `${base}/${map2[part.slice(1)]}`;
399
+ }
400
+ return `${base}/${part}`;
401
+ }, "").slice(1);
402
+ };
403
+ const consoleUnauthorizedMessage = () => {
404
+ console.log("Not logged in");
405
+ console.log('Login with "ones login" command');
406
+ };
407
+ const getURL = async (path, pathMap, queryMap) => {
408
+ const base = await getRegionURL();
409
+ if (base) {
410
+ const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
411
+ return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
513
412
  }
514
- close() {
515
- var _this$ws4;
516
- (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
413
+ consoleUnauthorizedMessage();
414
+ process$1.exit(1);
415
+ };
416
+ const getHeaders = async (value) => {
417
+ const token = await getONESToken();
418
+ if (token) {
419
+ return lodashEs.merge({
420
+ Authorization: `Bearer ${token}`
421
+ }, value);
517
422
  }
518
- buildProxyUrl() {
519
- const url = new URL("/platform/app/relay/", this.baseUrl);
520
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
521
- url.searchParams.set("app_id", this.appID);
522
- return url.toString();
423
+ consoleUnauthorizedMessage();
424
+ process$1.exit(1);
425
+ };
426
+ const handleError = (error) => {
427
+ var _error$response;
428
+ if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
429
+ console.log(error.response.statusText);
430
+ consoleUnauthorizedMessage();
431
+ } else {
432
+ console.error(error);
523
433
  }
524
- parseMessage(data) {
525
- const buffer = this.toBuffer(data);
526
- if (!buffer) {
527
- return null;
434
+ return {};
435
+ };
436
+ const fetchAppBase = async (params) => {
437
+ var _params$url;
438
+ const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
439
+ const headers = await getHeaders(params.headers);
440
+ const response = await axios({
441
+ ...params,
442
+ url,
443
+ headers
444
+ });
445
+ return response.data;
446
+ };
447
+ const fetchAppList = async (appID) => {
448
+ return await fetchAppBase({
449
+ url: API.APP_LIST,
450
+ method: "GET",
451
+ queryMap: {
452
+ app_id: appID
528
453
  }
529
- if (buffer.length >= 4) {
530
- const binary = this.parseBinaryEnvelope(buffer);
531
- if (binary) {
532
- return binary;
533
- }
454
+ }).catch(handleError);
455
+ };
456
+ const fetchTokenInfo = async () => {
457
+ return await fetchAppBase({
458
+ url: API.TOKEN_INFO,
459
+ method: "GET"
460
+ }).catch(handleError);
461
+ };
462
+ const fetchHostedToken = async (data) => {
463
+ return await fetchAppBase({
464
+ url: API.HOSTED_TOKEN,
465
+ method: "POST",
466
+ data
467
+ }).catch(handleError);
468
+ };
469
+ const fetchAppInstall = async (data) => {
470
+ var _appList$data$0$insta, _appList$data;
471
+ const appID = getAppManifestJSON().app.id;
472
+ const appList = await fetchAppList(appID);
473
+ 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 : "";
474
+ const url = installationID ? API.APP_UPGRADE : API.APP_INSTALL;
475
+ return await fetchAppBase({
476
+ url,
477
+ method: "POST",
478
+ data
479
+ }).catch(handleError);
480
+ };
481
+ const fetchAppUninstall = async () => {
482
+ var _appList$data$0$insta2, _appList$data2;
483
+ const appID = getAppManifestJSON().app.id;
484
+ const appList = await fetchAppList(appID);
485
+ 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 : "";
486
+ return await fetchAppBase({
487
+ url: API.APP_UNINSTALL,
488
+ method: "POST",
489
+ pathMap: {
490
+ installation_id: installationID
491
+ }
492
+ }).catch(handleError);
493
+ };
494
+ const fetchAppEnable = async () => {
495
+ var _appList$data$0$insta3, _appList$data3;
496
+ const appID = getAppManifestJSON().app.id;
497
+ const appList = await fetchAppList(appID);
498
+ 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 : "";
499
+ return await fetchAppBase({
500
+ url: API.APP_ENABLE,
501
+ method: "POST",
502
+ pathMap: {
503
+ installation_id: installationID
504
+ }
505
+ }).catch(handleError);
506
+ };
507
+ const fetchAppDisable = async () => {
508
+ var _appList$data$0$insta4, _appList$data4;
509
+ const appID = getAppManifestJSON().app.id;
510
+ const appList = await fetchAppList(appID);
511
+ 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 : "";
512
+ return await fetchAppBase({
513
+ url: API.APP_DISABLE,
514
+ method: "POST",
515
+ pathMap: {
516
+ installation_id: installationID
517
+ }
518
+ }).catch(handleError);
519
+ };
520
+ const isPortNumber = /^[1-9]\d{0,4}$/;
521
+ const minPortNumber = 1;
522
+ const maxPortNumber = 65535;
523
+ const normalize$9 = async (options) => {
524
+ const portInput = options.port;
525
+ if (portInput)
526
+ ;
527
+ else {
528
+ return createOnesApp.throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
529
+ }
530
+ const portString = String(portInput);
531
+ const portNumber = Number(portString);
532
+ if (isPortNumber.test(portString))
533
+ ;
534
+ else {
535
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
536
+ }
537
+ if (portNumber < minPortNumber || portNumber > maxPortNumber) {
538
+ return createOnesApp.throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
539
+ }
540
+ const port = portString;
541
+ return {
542
+ port
543
+ };
544
+ };
545
+ const MAX_RELAY_BODY_BYTES = 64 * 1024 * 1024;
546
+ class TunnelClient {
547
+ constructor(localPort, baseUrl, appID, hostedToken) {
548
+ let enableInternalManifestRoute = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
549
+ let replaceExisting = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : true;
550
+ this.ws = null;
551
+ this.localPort = localPort;
552
+ this.baseUrl = baseUrl;
553
+ this.appID = appID;
554
+ this.hostedToken = hostedToken;
555
+ this.enableInternalManifestRoute = enableInternalManifestRoute;
556
+ this.replaceExisting = replaceExisting;
557
+ }
558
+ async connect() {
559
+ const proxyUrl = this.buildProxyUrl();
560
+ this.ws = new WebSocket(proxyUrl, {
561
+ headers: {
562
+ Authorization: `Bearer ${this.hostedToken}`
563
+ },
564
+ maxPayload: MAX_RELAY_BODY_BYTES
565
+ });
566
+ this.ws.on("message", async (data) => {
567
+ const message = this.parseMessage(data);
568
+ if (!message) {
569
+ return;
570
+ }
571
+ await this.handleMessage(message);
572
+ });
573
+ this.ws.on("ping", (data) => {
574
+ var _this$ws;
575
+ (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
576
+ });
577
+ this.ws.on("error", (error) => {
578
+ console.error("WebSocket error:", error);
579
+ });
580
+ return new Promise((resolve, reject) => {
581
+ var _this$ws2, _this$ws3;
582
+ (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve());
583
+ (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
584
+ });
585
+ }
586
+ close() {
587
+ var _this$ws4;
588
+ (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
589
+ }
590
+ buildProxyUrl() {
591
+ const url = new URL("/platform/app/relay/", this.baseUrl);
592
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
593
+ url.searchParams.set("app_id", this.appID);
594
+ url.searchParams.set("replace_existing", String(this.replaceExisting));
595
+ return url.toString();
596
+ }
597
+ parseMessage(data) {
598
+ const buffer = this.toBuffer(data);
599
+ if (!buffer) {
600
+ return null;
601
+ }
602
+ if (buffer.length >= 4) {
603
+ const binary = this.parseBinaryEnvelope(buffer);
604
+ if (binary) {
605
+ return binary;
606
+ }
534
607
  }
535
608
  return this.parseJSONEnvelope(buffer.toString());
536
609
  }
@@ -539,7 +612,7 @@ class TunnelClient {
539
612
  if (!request) {
540
613
  return;
541
614
  }
542
- if (request.path === ONES_CLI_MANIFEST_PATH) {
615
+ if (this.enableInternalManifestRoute && request.path === ONES_CLI_INTERNAL_MANIFEST_PATH) {
543
616
  const appManifest = getAppManifestJSON().app;
544
617
  const baseURL = await buildTunnelUrl();
545
618
  const reply = {
@@ -591,7 +664,13 @@ class TunnelClient {
591
664
  if (payload.query) {
592
665
  Object.entries(payload.query).forEach((_ref) => {
593
666
  let [key, value] = _ref;
594
- url.searchParams.set(key, value);
667
+ if (Array.isArray(value)) {
668
+ value.forEach((item) => {
669
+ url.searchParams.append(key, item);
670
+ });
671
+ return;
672
+ }
673
+ url.searchParams.append(key, value);
595
674
  });
596
675
  }
597
676
  const response = await axios.request({
@@ -600,7 +679,9 @@ class TunnelClient {
600
679
  headers: payload.headers,
601
680
  data: payload.body,
602
681
  responseType: "arraybuffer",
603
- validateStatus: () => true
682
+ validateStatus: () => true,
683
+ maxBodyLength: MAX_RELAY_BODY_BYTES,
684
+ maxContentLength: MAX_RELAY_BODY_BYTES
604
685
  });
605
686
  const responseBytes = Buffer.from(response.data);
606
687
  return {
@@ -632,6 +713,9 @@ class TunnelClient {
632
713
  var _envelope$payload;
633
714
  const payload = (_envelope$payload = envelope.payload) !== null && _envelope$payload !== void 0 ? _envelope$payload : {};
634
715
  const body = this.toBodyBuffer(payload.body);
716
+ if (body.length > MAX_RELAY_BODY_BYTES) {
717
+ throw new Error("relay body too large");
718
+ }
635
719
  const metaPayload = {
636
720
  ...payload
637
721
  };
@@ -674,7 +758,12 @@ class TunnelClient {
674
758
  return envelope;
675
759
  }
676
760
  const body = buffer.subarray(4 + metaLength);
677
- envelope.payload.body = body;
761
+ if (body.length > MAX_RELAY_BODY_BYTES) {
762
+ console.error("Binary tunnel body exceeds size limit");
763
+ return null;
764
+ }
765
+ const payload = envelope.payload;
766
+ payload.body = body;
678
767
  return envelope;
679
768
  } catch (error) {
680
769
  console.error("Invalid binary tunnel message:", error);
@@ -706,60 +795,23 @@ class TunnelClient {
706
795
  return null;
707
796
  }
708
797
  }
709
- const getPath = (path, map2) => {
710
- var _context;
711
- return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
712
- if (/^:/.test(part)) {
713
- return `${base}/${map2[part.slice(1)]}`;
714
- }
715
- return `${base}/${part}`;
716
- }, "").slice(1);
717
- };
718
- const consoleUnauthorizedMessage = () => {
719
- console.log("Not logged in");
720
- console.log('Login with "ones login" command');
721
- };
722
- const getURL = async (path, pathMap, queryMap) => {
723
- const base = await getRegionURL();
724
- if (base) {
725
- const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
726
- return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
727
- }
728
- consoleUnauthorizedMessage();
729
- process$1.exit(1);
730
- };
731
- const getHeaders = async (value) => {
732
- const token = await getONESToken();
733
- if (token) {
734
- return lodashEs.merge({
735
- Authorization: `Bearer ${token}`
736
- }, value);
798
+ const ONES_CLI_INTERNAL_MANIFEST_PATH = "/__ones_cli_internal_manifest__";
799
+ const buildTunnelContext = async () => {
800
+ var _appManifestJSON$app$, _appManifestJSON$app;
801
+ const appManifestJSON = getAppManifestJSON();
802
+ 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$ : "";
803
+ if (!appID) {
804
+ throw new Error("app id is empty");
737
805
  }
738
- consoleUnauthorizedMessage();
739
- process$1.exit(1);
740
- };
741
- const handleError = (error) => {
742
- var _error$response;
743
- if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
744
- console.log(error.response.statusText);
745
- consoleUnauthorizedMessage();
746
- } else {
747
- console.error(error);
806
+ const regionURL = await getRegionURL();
807
+ if (!regionURL) {
808
+ throw new Error("region url is empty");
748
809
  }
749
- return {};
750
- };
751
- const API = {
752
- TOKEN_INFO: "/project/api/project/auth/token_info",
753
- HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
754
- APP_LIST: "/platform/api/app/list",
755
- APP_INSTALL: "/platform/api/app/install",
756
- APP_UPGRADE: "/platform/api/app/upgrade",
757
- APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
758
- APP_ENABLE: "/platform/api/app/:installation_id/enable",
759
- APP_DISABLE: "/platform/api/app/:installation_id/disable"
760
- };
761
- const isRecord = (value) => {
762
- return typeof value === "object" && value !== null;
810
+ return {
811
+ appManifestJSON,
812
+ appID,
813
+ regionURL
814
+ };
763
815
  };
764
816
  const getHostedTokenScopes = (ones2) => {
765
817
  const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
@@ -778,131 +830,6 @@ const getHostedTokenScopes = (ones2) => {
778
830
  const getRelayScope = () => {
779
831
  return createOnesApp.HostedTokenScope.RELAY;
780
832
  };
781
- const getHostToken = async (baseUrl, userToken, appID, scopes) => {
782
- const url = `${baseUrl.replace(/\/$/, "")}${API.HOSTED_TOKEN}`;
783
- return axios.post(url, {
784
- app_id: appID,
785
- scopes
786
- }, {
787
- headers: {
788
- Authorization: `Bearer ${userToken}`
789
- }
790
- }).then((resp) => {
791
- const data = resp === null || resp === void 0 ? void 0 : resp.data;
792
- const tokenFromData = (value) => {
793
- if (isRecord(value) && isRecord(value.data)) {
794
- const hosted_token = value.data.hosted_token;
795
- if (typeof hosted_token === "string" && hosted_token.length > 0) {
796
- return hosted_token;
797
- }
798
- }
799
- return null;
800
- };
801
- const token = tokenFromData(data);
802
- if (token) {
803
- return token;
804
- }
805
- return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
806
- }).catch((error) => {
807
- handleError(error);
808
- return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_REQUEST_FAILED, i18n.t("error.hostedToken.requestFailed"));
809
- });
810
- };
811
- const fetchAppBase = async (params) => {
812
- var _params$url;
813
- const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
814
- const headers = await getHeaders(params.headers);
815
- const response = await axios({
816
- ...params,
817
- url,
818
- headers
819
- });
820
- return response.data;
821
- };
822
- const fetchAppList = async (appID) => {
823
- return await fetchAppBase({
824
- url: API.APP_LIST,
825
- method: "GET",
826
- queryMap: {
827
- app_id: appID
828
- }
829
- }).catch(handleError);
830
- };
831
- const fetchTokenInfo = async () => {
832
- return await fetchAppBase({
833
- url: API.TOKEN_INFO,
834
- method: "GET"
835
- }).catch(handleError);
836
- };
837
- const fetchAppInstall = async (data) => {
838
- var _appList$data$0$insta, _appList$data;
839
- const appID = getAppManifestJSON().app.id;
840
- const appList = await fetchAppList(appID);
841
- 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 : "";
842
- const url = installationID ? API.APP_UPGRADE : API.APP_INSTALL;
843
- return await fetchAppBase({
844
- url,
845
- method: "POST",
846
- data
847
- }).catch(handleError);
848
- };
849
- const fetchAppUninstall = async () => {
850
- var _appList$data$0$insta2, _appList$data2;
851
- const appID = getAppManifestJSON().app.id;
852
- const appList = await fetchAppList(appID);
853
- 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 : "";
854
- return await fetchAppBase({
855
- url: API.APP_UNINSTALL,
856
- method: "POST",
857
- pathMap: {
858
- installation_id: installationID
859
- }
860
- }).catch(handleError);
861
- };
862
- const fetchAppEnable = async () => {
863
- var _appList$data$0$insta3, _appList$data3;
864
- const appID = getAppManifestJSON().app.id;
865
- const appList = await fetchAppList(appID);
866
- 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 : "";
867
- return await fetchAppBase({
868
- url: API.APP_ENABLE,
869
- method: "POST",
870
- pathMap: {
871
- installation_id: installationID
872
- }
873
- }).catch(handleError);
874
- };
875
- const fetchAppDisable = async () => {
876
- var _appList$data$0$insta4, _appList$data4;
877
- const appID = getAppManifestJSON().app.id;
878
- const appList = await fetchAppList(appID);
879
- 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 : "";
880
- return await fetchAppBase({
881
- url: API.APP_DISABLE,
882
- method: "POST",
883
- pathMap: {
884
- installation_id: installationID
885
- }
886
- }).catch(handleError);
887
- };
888
- const ONES_CLI_MANIFEST_PATH = "/__ones_cli_manifest__";
889
- const buildTunnelContext = async () => {
890
- var _appManifestJSON$app$, _appManifestJSON$app;
891
- const appManifestJSON = getAppManifestJSON();
892
- 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$ : "";
893
- if (!appID) {
894
- throw new Error("app id is empty");
895
- }
896
- const regionURL = await getRegionURL();
897
- if (!regionURL) {
898
- throw new Error("region url is empty");
899
- }
900
- return {
901
- appManifestJSON,
902
- appID,
903
- regionURL
904
- };
905
- };
906
833
  const buildTunnelUrl = async () => {
907
834
  const {
908
835
  appID,
@@ -911,12 +838,16 @@ const buildTunnelUrl = async () => {
911
838
  const url = new URL(regionURL);
912
839
  return `${url.protocol}//${url.host}/platform/app/relay/dispatch/${appID}`;
913
840
  };
914
- const invokeTunnel = async (port) => {
841
+ const invokeTunnel = async function(port) {
842
+ var _options$rebuildWhenE, _hostedTokenResponse$, _options$enableIntern;
843
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
915
844
  const {
916
845
  appManifestJSON,
917
846
  appID,
918
847
  regionURL
919
848
  } = await buildTunnelContext();
849
+ const runnelUrl = await buildTunnelUrl();
850
+ const rebuildWhenExists = (_options$rebuildWhenE = options.rebuildWhenExists) !== null && _options$rebuildWhenE !== void 0 ? _options$rebuildWhenE : true;
920
851
  const onesToken = await getONESToken();
921
852
  if (!onesToken) {
922
853
  consoleUnauthorizedMessage();
@@ -924,11 +855,17 @@ const invokeTunnel = async (port) => {
924
855
  }
925
856
  const storageScopes = getHostedTokenScopes(appManifestJSON.ones);
926
857
  const scopes = Array.from(/* @__PURE__ */ new Set([...storageScopes, getRelayScope()]));
927
- const hostedToken = await getHostToken(regionURL, onesToken, appID, scopes);
858
+ const hostedTokenResponse = await fetchHostedToken({
859
+ app_id: appID,
860
+ scopes
861
+ });
862
+ const hostedToken = hostedTokenResponse === null || hostedTokenResponse === void 0 || (_hostedTokenResponse$ = hostedTokenResponse.data) === null || _hostedTokenResponse$ === void 0 ? void 0 : _hostedTokenResponse$.hosted_token;
863
+ if (!hostedToken) {
864
+ return createOnesApp.throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
865
+ }
928
866
  process.env.ONES_HOSTED_TOKEN = hostedToken;
929
- const client = new TunnelClient(port, regionURL, appID, hostedToken);
867
+ const client = new TunnelClient(port, regionURL, appID, hostedToken, (_options$enableIntern = options.enableInternalManifestRoute) !== null && _options$enableIntern !== void 0 ? _options$enableIntern : true, rebuildWhenExists);
930
868
  await client.connect();
931
- const runnelUrl = await buildTunnelUrl();
932
869
  console.log(`Relay endpoint: ${runnelUrl}`);
933
870
  };
934
871
  const tunnel = async function() {
@@ -938,9 +875,143 @@ const tunnel = async function() {
938
875
  const {
939
876
  options
940
877
  } = createOnesApp.getCommandOptions(args, tunnelCommandArguments);
941
- const normalizedOptions = await normalize$8(options);
878
+ const normalizedOptions = await normalize$9(options);
942
879
  await invokeTunnel(Number(normalizedOptions.port));
943
880
  };
881
+ const normalize$8 = async (options) => {
882
+ lodashEs.noop(options);
883
+ return {};
884
+ };
885
+ const invokeInstall = async () => {
886
+ const runnelUrl = await buildTunnelUrl();
887
+ const result = await fetchAppInstall({
888
+ manifest_url: `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`
889
+ });
890
+ return result;
891
+ };
892
+ const install = async function() {
893
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
894
+ args[_key] = arguments[_key];
895
+ }
896
+ const {
897
+ options
898
+ } = createOnesApp.getCommandOptions(args, installCommandArguments);
899
+ const normalizedOptions = await normalize$8(options);
900
+ lodashEs.noop(normalizedOptions);
901
+ await invokeTunnel(getConfig().defaultPort.tunnel);
902
+ const result = await invokeInstall();
903
+ if (result.code === "OK") {
904
+ var _appList$data$0$insta, _appList$data;
905
+ console.log("App installed successfully!");
906
+ const appID = getAppManifestJSON().app.id;
907
+ const appList = await fetchAppList(appID);
908
+ 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 : "";
909
+ if (installationID) {
910
+ var _tokenInfo$org$uuid, _tokenInfo$org, _tokenInfo$teams$0$uu, _tokenInfo$teams, _tokenInfo$org$visibi, _tokenInfo$org2;
911
+ const tokenInfo = await fetchTokenInfo();
912
+ 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 : "";
913
+ 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 : "";
914
+ 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;
915
+ const baseURL = await getBaseURL();
916
+ if (isOrgVisible && orgUUID) {
917
+ const url = `${baseURL}/project/#/org/${orgUUID}/setting/app_manager/platform_app/${installationID}`;
918
+ console.log(`See App detail: ${url}`);
919
+ }
920
+ if (!isOrgVisible && teamUUID) {
921
+ const url = `${baseURL}/project/#/team/${teamUUID}/team_setting/app_manager/platform_app/${installationID}`;
922
+ console.log(`See App detail: ${url}`);
923
+ }
924
+ }
925
+ } else {
926
+ console.error(result);
927
+ }
928
+ };
929
+ var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
930
+ InstallOptions2["AUTO"] = "auto";
931
+ InstallOptions2["TRUE"] = "true";
932
+ InstallOptions2["FALSE"] = "false";
933
+ return InstallOptions2;
934
+ })(InstallOptions || {});
935
+ const defaultInstall = InstallOptions.AUTO;
936
+ const normalize$7 = async (options) => {
937
+ var _options$install;
938
+ let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
939
+ switch (true) {
940
+ case install2 === InstallOptions.AUTO:
941
+ break;
942
+ case Boolean(install2):
943
+ install2 = InstallOptions.TRUE;
944
+ break;
945
+ default:
946
+ install2 = InstallOptions.FALSE;
947
+ break;
948
+ }
949
+ return {
950
+ install: install2
951
+ };
952
+ };
953
+ const dev = async function() {
954
+ var _appPackageJSON$scrip;
955
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
956
+ args[_key] = arguments[_key];
957
+ }
958
+ const {
959
+ options
960
+ } = createOnesApp.getCommandOptions(args, devCommandArguments);
961
+ const normalizedOptions = await normalize$7(options);
962
+ const appPackageJSON = getAppPackageJSON();
963
+ const appManifestJSON = getAppManifestJSON();
964
+ const appRcJSON = getAppRcJSON();
965
+ lodashEs.noop(appManifestJSON);
966
+ lodashEs.noop(appRcJSON);
967
+ if (!((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev)) {
968
+ return createOnesApp.throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
969
+ }
970
+ const ONES_HOSTED_TOKEN = await getHostToken();
971
+ const port = getConfig().defaultPort.tunnel;
972
+ const cwd = getAppWorkspacePath();
973
+ const env = {
974
+ ...process.env,
975
+ NODE_ENV: "development",
976
+ ONES_HOSTED_PORT: `${port}`,
977
+ ONES_HOSTED_TOKEN
978
+ };
979
+ const tunnelChild = node_child_process.spawn("ones", ["tunnel", String(port)], {
980
+ cwd,
981
+ stdio: "inherit"
982
+ });
983
+ const devChild = node_child_process.spawn("npm", ["run", "dev"], {
984
+ cwd,
985
+ stdio: "inherit",
986
+ env
987
+ });
988
+ const cleanup = () => {
989
+ tunnelChild.kill();
990
+ devChild.kill();
991
+ };
992
+ const onSignal = () => {
993
+ cleanup();
994
+ process.exit(128 + 2);
995
+ };
996
+ process.on("SIGINT", onSignal);
997
+ process.on("SIGTERM", onSignal);
998
+ console.log(`Local: http://localhost:${port}`);
999
+ if (normalizedOptions.install === InstallOptions.TRUE) {
1000
+ setTimeout(() => {
1001
+ invokeInstall().catch((error) => {
1002
+ console.error(error);
1003
+ });
1004
+ }, 2e3);
1005
+ }
1006
+ await new Promise((resolve) => {
1007
+ devChild.on("exit", () => {
1008
+ cleanup();
1009
+ process.off("SIGINT", onSignal);
1010
+ process.off("SIGTERM", onSignal);
1011
+ resolve();
1012
+ });
1013
+ });
1014
+ };
944
1015
  function createPromise() {
945
1016
  let resolve;
946
1017
  let reject;
@@ -961,7 +1032,7 @@ const sleep = (number) => {
961
1032
  };
962
1033
  const isURL = /^https?:\/\//;
963
1034
  const HostBlackList = ["ones.cn", "www.ones.cn", "ones.com", "www.ones.com"];
964
- const normalize$7 = async (options) => {
1035
+ const normalize$6 = async (options) => {
965
1036
  const baseURLInput = options.baseURL;
966
1037
  if (baseURLInput)
967
1038
  ;
@@ -998,7 +1069,7 @@ const login = async function() {
998
1069
  const {
999
1070
  options
1000
1071
  } = createOnesApp.getCommandOptions(args, loginCommandArguments);
1001
- const normalizedOptions = await normalize$7(options);
1072
+ const normalizedOptions = await normalize$6(options);
1002
1073
  const base = normalizedOptions.baseURL;
1003
1074
  const path = "project/oauth2.html";
1004
1075
  const config2 = getConfig();
@@ -1082,7 +1153,7 @@ const login = async function() {
1082
1153
  ora("Waiting for authorization...").start();
1083
1154
  await open(url);
1084
1155
  };
1085
- const normalize$6 = async (options) => {
1156
+ const normalize$5 = async (options) => {
1086
1157
  lodashEs.noop(options);
1087
1158
  return {};
1088
1159
  };
@@ -1093,12 +1164,12 @@ const logout = async function() {
1093
1164
  const {
1094
1165
  options
1095
1166
  } = createOnesApp.getCommandOptions(args, logoutCommandArguments);
1096
- const normalizedOptions = await normalize$6(options);
1167
+ const normalizedOptions = await normalize$5(options);
1097
1168
  lodashEs.noop(normalizedOptions);
1098
1169
  await setStore({});
1099
1170
  console.log("Logged out successfully!");
1100
1171
  };
1101
- const normalize$5 = async (options) => {
1172
+ const normalize$4 = async (options) => {
1102
1173
  lodashEs.noop(options);
1103
1174
  return {};
1104
1175
  };
@@ -1110,7 +1181,7 @@ const whoami = async function() {
1110
1181
  const {
1111
1182
  options
1112
1183
  } = createOnesApp.getCommandOptions(args, whoamiCommandArguments);
1113
- const normalizedOptions = await normalize$5(options);
1184
+ const normalizedOptions = await normalize$4(options);
1114
1185
  lodashEs.noop(normalizedOptions);
1115
1186
  const baseURL = await getBaseURL();
1116
1187
  const tokenInfo = await fetchTokenInfo();
@@ -1123,54 +1194,6 @@ const whoami = async function() {
1123
1194
  consoleUnauthorizedMessage();
1124
1195
  }
1125
1196
  };
1126
- const normalize$4 = async (options) => {
1127
- lodashEs.noop(options);
1128
- return {};
1129
- };
1130
- const invokeInstall = async () => {
1131
- const runnelUrl = await buildTunnelUrl();
1132
- const result = await fetchAppInstall({
1133
- manifest_url: `${runnelUrl}${ONES_CLI_MANIFEST_PATH}`
1134
- });
1135
- return result;
1136
- };
1137
- const install = async function() {
1138
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1139
- args[_key] = arguments[_key];
1140
- }
1141
- const {
1142
- options
1143
- } = createOnesApp.getCommandOptions(args, installCommandArguments);
1144
- const normalizedOptions = await normalize$4(options);
1145
- lodashEs.noop(normalizedOptions);
1146
- await invokeTunnel(getConfig().defaultPort.tunnel);
1147
- const result = await invokeInstall();
1148
- if (result.code === "OK") {
1149
- var _appList$data$0$insta, _appList$data;
1150
- console.log("App installed successfully!");
1151
- const appID = getAppManifestJSON().app.id;
1152
- const appList = await fetchAppList(appID);
1153
- 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 : "";
1154
- if (installationID) {
1155
- var _tokenInfo$org$uuid, _tokenInfo$org, _tokenInfo$teams$0$uu, _tokenInfo$teams, _tokenInfo$org$visibi, _tokenInfo$org2;
1156
- const tokenInfo = await fetchTokenInfo();
1157
- 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 : "";
1158
- 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 : "";
1159
- 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;
1160
- const baseURL = await getBaseURL();
1161
- if (isOrgVisible && orgUUID) {
1162
- const url = `${baseURL}/project/#/org/${orgUUID}/setting/app_manager/platform_app/${installationID}`;
1163
- console.log(`See App detail: ${url}`);
1164
- }
1165
- if (!isOrgVisible && teamUUID) {
1166
- const url = `${baseURL}/project/#/team/${teamUUID}/team_setting/app_manager/platform_app/${installationID}`;
1167
- console.log(`See App detail: ${url}`);
1168
- }
1169
- }
1170
- } else {
1171
- console.error(result);
1172
- }
1173
- };
1174
1197
  const normalize$3 = async (options) => {
1175
1198
  lodashEs.noop(options);
1176
1199
  return {};
@@ -1308,7 +1331,7 @@ const runCommandONES = async () => {
1308
1331
  const command = ones;
1309
1332
  createOnesApp.setContext("command", command);
1310
1333
  const version = `${getPackageJSON().version}`;
1311
- command.version(version);
1334
+ command.version(version, "-v, --version");
1312
1335
  await command.parse();
1313
1336
  };
1314
1337
  exports.runCommandONES = runCommandONES;