@ones-open/cli 0.50.0 → 1.0.1-10001.1957

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 (188) hide show
  1. package/LICENSE +201 -674
  2. package/bin/ones.js +4 -0
  3. package/dist/index.cjs +1589 -0
  4. package/dist/index.js +1588 -0
  5. package/dist/types/actions/build/index.d.ts +4 -0
  6. package/dist/types/actions/build/index.d.ts.map +1 -0
  7. package/dist/types/actions/build/normalize.d.ts +6 -0
  8. package/dist/types/actions/build/normalize.d.ts.map +1 -0
  9. package/dist/types/actions/build/regexp.d.ts +2 -0
  10. package/dist/types/actions/build/regexp.d.ts.map +1 -0
  11. package/dist/types/actions/dev/enums.d.ts +6 -0
  12. package/dist/types/actions/dev/enums.d.ts.map +1 -0
  13. package/dist/types/actions/dev/index.d.ts +4 -0
  14. package/dist/types/actions/dev/index.d.ts.map +1 -0
  15. package/dist/types/actions/dev/normalize.d.ts +6 -0
  16. package/dist/types/actions/dev/normalize.d.ts.map +1 -0
  17. package/dist/types/actions/dev/types.d.ts +10 -0
  18. package/dist/types/actions/dev/types.d.ts.map +1 -0
  19. package/dist/types/actions/disable/index.d.ts +4 -0
  20. package/dist/types/actions/disable/index.d.ts.map +1 -0
  21. package/dist/types/actions/disable/normalize.d.ts +6 -0
  22. package/dist/types/actions/disable/normalize.d.ts.map +1 -0
  23. package/dist/types/actions/enable/index.d.ts +4 -0
  24. package/dist/types/actions/enable/index.d.ts.map +1 -0
  25. package/dist/types/actions/enable/normalize.d.ts +6 -0
  26. package/dist/types/actions/enable/normalize.d.ts.map +1 -0
  27. package/dist/types/actions/index.d.ts +15 -0
  28. package/dist/types/actions/index.d.ts.map +1 -0
  29. package/dist/types/actions/install/index.d.ts +5 -0
  30. package/dist/types/actions/install/index.d.ts.map +1 -0
  31. package/dist/types/actions/install/install.d.ts +3 -0
  32. package/dist/types/actions/install/install.d.ts.map +1 -0
  33. package/dist/types/actions/install/normalize.d.ts +6 -0
  34. package/dist/types/actions/install/normalize.d.ts.map +1 -0
  35. package/dist/types/actions/legacy/index.d.ts +4 -0
  36. package/dist/types/actions/legacy/index.d.ts.map +1 -0
  37. package/dist/types/actions/legacy/normalize.d.ts +6 -0
  38. package/dist/types/actions/legacy/normalize.d.ts.map +1 -0
  39. package/dist/types/actions/login/consts.d.ts +2 -0
  40. package/dist/types/actions/login/consts.d.ts.map +1 -0
  41. package/dist/types/actions/login/index.d.ts +4 -0
  42. package/dist/types/actions/login/index.d.ts.map +1 -0
  43. package/dist/types/actions/login/normalize.d.ts +6 -0
  44. package/dist/types/actions/login/normalize.d.ts.map +1 -0
  45. package/dist/types/actions/login/regexp.d.ts +2 -0
  46. package/dist/types/actions/login/regexp.d.ts.map +1 -0
  47. package/dist/types/actions/logout/index.d.ts +4 -0
  48. package/dist/types/actions/logout/index.d.ts.map +1 -0
  49. package/dist/types/actions/logout/normalize.d.ts +6 -0
  50. package/dist/types/actions/logout/normalize.d.ts.map +1 -0
  51. package/dist/types/actions/tunnel/consts.d.ts +6 -0
  52. package/dist/types/actions/tunnel/consts.d.ts.map +1 -0
  53. package/dist/types/actions/tunnel/index.d.ts +7 -0
  54. package/dist/types/actions/tunnel/index.d.ts.map +1 -0
  55. package/dist/types/actions/tunnel/normalize.d.ts +6 -0
  56. package/dist/types/actions/tunnel/normalize.d.ts.map +1 -0
  57. package/dist/types/actions/tunnel/regexp.d.ts +2 -0
  58. package/dist/types/actions/tunnel/regexp.d.ts.map +1 -0
  59. package/dist/types/actions/tunnel/tunnel-client.d.ts +25 -0
  60. package/dist/types/actions/tunnel/tunnel-client.d.ts.map +1 -0
  61. package/dist/types/actions/tunnel/tunnel.d.ts +3 -0
  62. package/dist/types/actions/tunnel/tunnel.d.ts.map +1 -0
  63. package/dist/types/actions/tunnel/types.d.ts +33 -0
  64. package/dist/types/actions/tunnel/types.d.ts.map +1 -0
  65. package/dist/types/actions/tunnel/utils.d.ts +7 -0
  66. package/dist/types/actions/tunnel/utils.d.ts.map +1 -0
  67. package/dist/types/actions/uninstall/index.d.ts +4 -0
  68. package/dist/types/actions/uninstall/index.d.ts.map +1 -0
  69. package/dist/types/actions/uninstall/normalize.d.ts +6 -0
  70. package/dist/types/actions/uninstall/normalize.d.ts.map +1 -0
  71. package/dist/types/actions/whoami/index.d.ts +4 -0
  72. package/dist/types/actions/whoami/index.d.ts.map +1 -0
  73. package/dist/types/actions/whoami/normalize.d.ts +6 -0
  74. package/dist/types/actions/whoami/normalize.d.ts.map +1 -0
  75. package/dist/types/cli/index.d.ts +2 -0
  76. package/dist/types/cli/index.d.ts.map +1 -0
  77. package/dist/types/command/app/index.d.ts +4 -0
  78. package/dist/types/command/app/index.d.ts.map +1 -0
  79. package/dist/types/command/build/index.d.ts +9 -0
  80. package/dist/types/command/build/index.d.ts.map +1 -0
  81. package/dist/types/command/dev/index.d.ts +10 -0
  82. package/dist/types/command/dev/index.d.ts.map +1 -0
  83. package/dist/types/command/disable/index.d.ts +8 -0
  84. package/dist/types/command/disable/index.d.ts.map +1 -0
  85. package/dist/types/command/enable/index.d.ts +8 -0
  86. package/dist/types/command/enable/index.d.ts.map +1 -0
  87. package/dist/types/command/index.d.ts +16 -0
  88. package/dist/types/command/index.d.ts.map +1 -0
  89. package/dist/types/command/install/index.d.ts +8 -0
  90. package/dist/types/command/install/index.d.ts.map +1 -0
  91. package/dist/types/command/legacy/index.d.ts +8 -0
  92. package/dist/types/command/legacy/index.d.ts.map +1 -0
  93. package/dist/types/command/login/index.d.ts +8 -0
  94. package/dist/types/command/login/index.d.ts.map +1 -0
  95. package/dist/types/command/logout/index.d.ts +8 -0
  96. package/dist/types/command/logout/index.d.ts.map +1 -0
  97. package/dist/types/command/tunnel/index.d.ts +8 -0
  98. package/dist/types/command/tunnel/index.d.ts.map +1 -0
  99. package/dist/types/command/uninstall/index.d.ts +8 -0
  100. package/dist/types/command/uninstall/index.d.ts.map +1 -0
  101. package/dist/types/command/whoami/index.d.ts +8 -0
  102. package/dist/types/command/whoami/index.d.ts.map +1 -0
  103. package/dist/types/common/base/index.d.ts +5 -0
  104. package/dist/types/common/base/index.d.ts.map +1 -0
  105. package/dist/types/common/base/utils.d.ts +7 -0
  106. package/dist/types/common/base/utils.d.ts.map +1 -0
  107. package/dist/types/common/command/index.d.ts +6 -0
  108. package/dist/types/common/command/index.d.ts.map +1 -0
  109. package/dist/types/common/command/types.d.ts +2 -0
  110. package/dist/types/common/command/types.d.ts.map +1 -0
  111. package/dist/types/common/command/utils.d.ts +2 -0
  112. package/dist/types/common/command/utils.d.ts.map +1 -0
  113. package/dist/types/common/config/index.d.ts +6 -0
  114. package/dist/types/common/config/index.d.ts.map +1 -0
  115. package/dist/types/common/config/types.d.ts +8 -0
  116. package/dist/types/common/config/types.d.ts.map +1 -0
  117. package/dist/types/common/config/utils.d.ts +3 -0
  118. package/dist/types/common/config/utils.d.ts.map +1 -0
  119. package/dist/types/common/context/index.d.ts +6 -0
  120. package/dist/types/common/context/index.d.ts.map +1 -0
  121. package/dist/types/common/context/types.d.ts +2 -0
  122. package/dist/types/common/context/types.d.ts.map +1 -0
  123. package/dist/types/common/context/utils.d.ts +2 -0
  124. package/dist/types/common/context/utils.d.ts.map +1 -0
  125. package/dist/types/common/error/enums.d.ts +19 -0
  126. package/dist/types/common/error/enums.d.ts.map +1 -0
  127. package/dist/types/common/error/index.d.ts +7 -0
  128. package/dist/types/common/error/index.d.ts.map +1 -0
  129. package/dist/types/common/error/types.d.ts +2 -0
  130. package/dist/types/common/error/types.d.ts.map +1 -0
  131. package/dist/types/common/error/utils.d.ts +2 -0
  132. package/dist/types/common/error/utils.d.ts.map +1 -0
  133. package/dist/types/common/locales/en/index.d.ts +34 -0
  134. package/dist/types/common/locales/en/index.d.ts.map +1 -0
  135. package/dist/types/common/locales/index.d.ts +6 -0
  136. package/dist/types/common/locales/index.d.ts.map +1 -0
  137. package/dist/types/common/locales/types.d.ts +4 -0
  138. package/dist/types/common/locales/types.d.ts.map +1 -0
  139. package/dist/types/common/locales/utils.d.ts +6 -0
  140. package/dist/types/common/locales/utils.d.ts.map +1 -0
  141. package/dist/types/common/package/index.d.ts +7 -0
  142. package/dist/types/common/package/index.d.ts.map +1 -0
  143. package/dist/types/common/package/schema.d.ts +3 -0
  144. package/dist/types/common/package/schema.d.ts.map +1 -0
  145. package/dist/types/common/package/types.d.ts +2 -0
  146. package/dist/types/common/package/types.d.ts.map +1 -0
  147. package/dist/types/common/package/utils.d.ts +14 -0
  148. package/dist/types/common/package/utils.d.ts.map +1 -0
  149. package/dist/types/common/public/consts.d.ts +2 -0
  150. package/dist/types/common/public/consts.d.ts.map +1 -0
  151. package/dist/types/common/public/index.d.ts +6 -0
  152. package/dist/types/common/public/index.d.ts.map +1 -0
  153. package/dist/types/common/public/utils.d.ts +2 -0
  154. package/dist/types/common/public/utils.d.ts.map +1 -0
  155. package/dist/types/common/request/consts.d.ts +13 -0
  156. package/dist/types/common/request/consts.d.ts.map +1 -0
  157. package/dist/types/common/request/fetch.d.ts +12 -0
  158. package/dist/types/common/request/fetch.d.ts.map +1 -0
  159. package/dist/types/common/request/index.d.ts +8 -0
  160. package/dist/types/common/request/index.d.ts.map +1 -0
  161. package/dist/types/common/request/types.d.ts +92 -0
  162. package/dist/types/common/request/types.d.ts.map +1 -0
  163. package/dist/types/common/request/utils.d.ts +8 -0
  164. package/dist/types/common/request/utils.d.ts.map +1 -0
  165. package/dist/types/common/store/index.d.ts +6 -0
  166. package/dist/types/common/store/index.d.ts.map +1 -0
  167. package/dist/types/common/store/schema.d.ts +25 -0
  168. package/dist/types/common/store/schema.d.ts.map +1 -0
  169. package/dist/types/common/store/utils.d.ts +13 -0
  170. package/dist/types/common/store/utils.d.ts.map +1 -0
  171. package/dist/types/index.d.ts +2 -0
  172. package/dist/types/index.d.ts.map +1 -0
  173. package/index.d.ts +2 -0
  174. package/index.js +2 -0
  175. package/package.json +57 -38
  176. package/public/callback.html +65 -0
  177. package/public/logo.svg +4 -0
  178. package/bin/index.es.js +0 -261
  179. package/bin/types/index.d.ts +0 -2
  180. package/bin/types/index.d.ts.map +0 -1
  181. package/bin/types/lib/create.d.ts +0 -4
  182. package/bin/types/lib/create.d.ts.map +0 -1
  183. package/bin/types/lib/env.d.ts +0 -6
  184. package/bin/types/lib/env.d.ts.map +0 -1
  185. package/template/_prettierignore +0 -13
  186. package/template/_prettierrc +0 -6
  187. package/template/browserslist +0 -4
  188. package/template/package.json +0 -5
package/dist/index.js ADDED
@@ -0,0 +1,1588 @@
1
+ import _includesInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/includes";
2
+ import { Command } from "commander";
3
+ import { ErrorCode as ErrorCode$1, AppPackageJSONSchema, throwError, AppManifestJSONSchema, getPublicPath as getPublicPath$1, PUBLIC_FILENAME, AppRcJSONSchema, getCommandOptions, HostedTokenScope, addCommandUsage, addCommandOutput, $create, setContext } from "create-ones-app";
4
+ import { dirname, join, resolve, basename } from "node:path";
5
+ import { spawnSync, spawn } from "node:child_process";
6
+ import { readFileSync, createWriteStream } from "node:fs";
7
+ import fse from "fs-extra";
8
+ import archiver from "archiver";
9
+ import { get, merge, noop } from "lodash-es";
10
+ import process$1, { cwd } from "node:process";
11
+ import { fileURLToPath } from "node:url";
12
+ import { cosmiconfig } from "cosmiconfig";
13
+ import getPort from "get-port";
14
+ import envPaths from "env-paths";
15
+ import { z } from "zod";
16
+ import axios from "axios";
17
+ import _reduceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/reduce";
18
+ import WebSocket from "ws";
19
+ import http from "node:http";
20
+ import ora from "ora";
21
+ import open from "open";
22
+ import { v4 } from "uuid";
23
+ const en = {
24
+ "desc.ones": "ONES CLI/{env}",
25
+ "desc.build": "Build your ONES App",
26
+ "desc.build.output": "Specify the output file path",
27
+ "desc.dev": "Start your local development server and connect to ONES",
28
+ "desc.dev.install": "Install your ONES App after the server is ready",
29
+ "desc.dev.command": "Specify the dev command",
30
+ "desc.tunnel": "Start a tunnel to connect your local server with ONES",
31
+ "desc.tunnel.port": "Specify the port number for tunnel",
32
+ "desc.login": "Log in to your ONES account",
33
+ "desc.login.baseUrl": "Specify the ONES URL for login",
34
+ "desc.logout": "Log out of your ONES account",
35
+ "desc.whoami": "Display the account information of the logged in user",
36
+ "desc.app": "Manage app installations",
37
+ "desc.install": "Install your ONES App",
38
+ "desc.enable": "Enable your ONES App",
39
+ "desc.disable": "Disable your ONES App",
40
+ "desc.uninstall": "Uninstall your ONES App",
41
+ "desc.legacy": "Legacy command",
42
+ "error.login.missingBaseURL": "Missing base URL",
43
+ "error.login.incorrectBaseURL": "Incorrect base URL",
44
+ "error.tunnel.missingPort": "Missing port",
45
+ "error.tunnel.incorrectPort": "Incorrect port",
46
+ "error.schema.app.package.parseError": "App package JSON parse error",
47
+ "error.schema.app.manifest.parseError": 'App "opkx.json" JSON parse error',
48
+ "error.build.scriptNotFound": 'Npm "build" script not found',
49
+ "error.dev.scriptNotFound": 'Npm "dev" script not found',
50
+ "error.dev.incorrectCommand": "Incorrect dev command",
51
+ "error.store.permission": 'Permission denied, please check the file permission with "{filePath}"',
52
+ "error.hostedToken.requestFailed": "Failed to request hosted token",
53
+ "error.hostedToken.empty": "Hosted token is empty"
54
+ };
55
+ const map = {
56
+ en
57
+ };
58
+ const getCurrentLanguageList = () => {
59
+ return ["en"];
60
+ };
61
+ const translate = (key, params) => {
62
+ const list = getCurrentLanguageList();
63
+ for (let index = 0; index < list.length; index++) {
64
+ const language = list[index];
65
+ let value = get(map[language], key);
66
+ if (value) {
67
+ if (params && typeof value === "string") {
68
+ value = value.replace(/\{(\w+)\}/g, (match, paramKey) => {
69
+ var _params$paramKey;
70
+ const result = (_params$paramKey = params === null || params === void 0 ? void 0 : params[paramKey]) !== null && _params$paramKey !== void 0 ? _params$paramKey : match;
71
+ return String(result);
72
+ });
73
+ }
74
+ return value;
75
+ }
76
+ }
77
+ return key;
78
+ };
79
+ const i18n = {
80
+ t: translate
81
+ };
82
+ var ErrorCode = ((ErrorCode2) => {
83
+ ErrorCode2[ErrorCode2["UNKNOWN_ERROR"] = ErrorCode$1.UNKNOWN_ERROR] = "UNKNOWN_ERROR";
84
+ ErrorCode2[ErrorCode2["COMMAND_ERROR"] = ErrorCode$1.COMMAND_ERROR] = "COMMAND_ERROR";
85
+ ErrorCode2[ErrorCode2["TEMPLATE_NOT_FOUND"] = ErrorCode$1.TEMPLATE_NOT_FOUND] = "TEMPLATE_NOT_FOUND";
86
+ ErrorCode2[ErrorCode2["MISSING_PROJECT_PATH"] = ErrorCode$1.MISSING_PROJECT_PATH] = "MISSING_PROJECT_PATH";
87
+ ErrorCode2["MISSING_BASE_URL"] = "E04";
88
+ ErrorCode2["MISSING_PORT"] = "E05";
89
+ ErrorCode2["INCORRECT_BASE_URL"] = "E06";
90
+ ErrorCode2["INCORRECT_PORT"] = "E07";
91
+ ErrorCode2["APP_PACKAGE_JSON_PARSE_ERROR"] = "E08";
92
+ ErrorCode2["APP_MANIFEST_JSON_PARSE_ERROR"] = "E09";
93
+ ErrorCode2["BUILD_SCRIPT_NOT_FOUND"] = "E10";
94
+ ErrorCode2["DEV_SCRIPT_NOT_FOUND"] = "E11";
95
+ ErrorCode2["STORE_PERMISSION"] = "E12";
96
+ ErrorCode2["HOSTED_TOKEN_REQUEST_FAILED"] = "E13";
97
+ ErrorCode2["HOSTED_TOKEN_EMPTY"] = "E14";
98
+ ErrorCode2["INCORRECT_DEV_COMMAND"] = "E15";
99
+ return ErrorCode2;
100
+ })(ErrorCode || {});
101
+ const getPublicPath = () => {
102
+ const __dirname = dirname(fileURLToPath(import.meta.url));
103
+ return join(__dirname, "../public");
104
+ };
105
+ const getPackageJSONPath = () => {
106
+ const __dirname = dirname(fileURLToPath(import.meta.url));
107
+ return join(__dirname, "../package.json");
108
+ };
109
+ const getPackageJSON = () => {
110
+ const path = getPackageJSONPath();
111
+ try {
112
+ const string = readFileSync(path, {
113
+ encoding: "utf8"
114
+ });
115
+ return JSON.parse(string);
116
+ } catch (error) {
117
+ return {};
118
+ }
119
+ };
120
+ const getAppWorkspacePath = () => {
121
+ return join(cwd());
122
+ };
123
+ const getAppPackageJSONPath = () => {
124
+ return join(cwd(), "./package.json");
125
+ };
126
+ const getAppPackageJSON = () => {
127
+ const path = getAppPackageJSONPath();
128
+ try {
129
+ const string = readFileSync(path, {
130
+ encoding: "utf8"
131
+ });
132
+ const json = JSON.parse(string);
133
+ return AppPackageJSONSchema.parse(json);
134
+ } catch (error) {
135
+ const details = error instanceof Error ? error.message : String(error);
136
+ return throwError(ErrorCode.APP_PACKAGE_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.package.parseError")}: ${details}`);
137
+ }
138
+ };
139
+ const getAppManifestJSONPath = () => {
140
+ return join(cwd(), PUBLIC_FILENAME.MANIFEST);
141
+ };
142
+ const getAppManifestJSON = () => {
143
+ const path = getAppManifestJSONPath();
144
+ try {
145
+ const string = readFileSync(path, {
146
+ encoding: "utf8"
147
+ });
148
+ const json = JSON.parse(string);
149
+ return AppManifestJSONSchema.parse(json);
150
+ } catch (error) {
151
+ const details = error instanceof Error ? error.message : String(error);
152
+ return throwError(ErrorCode.APP_MANIFEST_JSON_PARSE_ERROR, `${i18n.t("error.schema.app.manifest.parseError")}: ${details}`);
153
+ }
154
+ };
155
+ const defaultDevCommand = ["npm", "run", "dev"];
156
+ const defaultAppRcJSON = {
157
+ dev: {
158
+ command: defaultDevCommand
159
+ }
160
+ };
161
+ let storeAppRcJSON = null;
162
+ const getAppRcJSON = async () => {
163
+ if (storeAppRcJSON)
164
+ ;
165
+ else {
166
+ try {
167
+ const path = join(getPublicPath$1(), PUBLIC_FILENAME.RC);
168
+ const string = readFileSync(path, {
169
+ encoding: "utf8"
170
+ });
171
+ const json = JSON.parse(string);
172
+ storeAppRcJSON = AppRcJSONSchema.parse(json);
173
+ } catch (error) {
174
+ storeAppRcJSON = {};
175
+ }
176
+ }
177
+ const templateAppRcJSON = storeAppRcJSON || {};
178
+ let currentAppRcJSON;
179
+ const explorer = cosmiconfig("ones");
180
+ try {
181
+ const result = await explorer.search();
182
+ const json = result === null || result === void 0 ? void 0 : result.config;
183
+ currentAppRcJSON = AppRcJSONSchema.parse(json);
184
+ } catch (error) {
185
+ currentAppRcJSON = {};
186
+ }
187
+ return {
188
+ ...defaultAppRcJSON,
189
+ ...templateAppRcJSON,
190
+ ...currentAppRcJSON
191
+ };
192
+ };
193
+ const isOPKXFilename = /\.opkx$/;
194
+ const defaultOutputPath = "";
195
+ const normalize$a = async (options) => {
196
+ var _options$output;
197
+ let output = resolve(cwd(), (_options$output = options.output) !== null && _options$output !== void 0 ? _options$output : defaultOutputPath);
198
+ if (isOPKXFilename.test(output))
199
+ ;
200
+ else {
201
+ const appManifestJSON = getAppManifestJSON();
202
+ const defaultOutputFilename = `${appManifestJSON.app.name}.opkx`;
203
+ output = resolve(output, defaultOutputFilename);
204
+ }
205
+ return {
206
+ output
207
+ };
208
+ };
209
+ const {
210
+ existsSync,
211
+ ensureDirSync
212
+ } = fse;
213
+ const build = async function() {
214
+ var _appRcJSON$build$comp, _appRcJSON$build;
215
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
216
+ args[_key] = arguments[_key];
217
+ }
218
+ const {
219
+ options
220
+ } = getCommandOptions(args, buildCommandArguments);
221
+ const normalizedOptions = await normalize$a(options);
222
+ const appManifestJSON = getAppManifestJSON();
223
+ const appRcJSON = await getAppRcJSON();
224
+ const appPackageJSONPath = getAppPackageJSONPath();
225
+ const isExists = existsSync(appPackageJSONPath);
226
+ if (isExists) {
227
+ var _appPackageJSON$scrip;
228
+ const appPackageJSON = getAppPackageJSON();
229
+ if ((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.build) {
230
+ const buildResult = spawnSync("npm", ["run", "build"], {
231
+ cwd: getAppWorkspacePath(),
232
+ stdio: "inherit",
233
+ env: {
234
+ ...process.env,
235
+ NODE_ENV: "production"
236
+ }
237
+ });
238
+ if (buildResult.status !== 0 || buildResult.signal) {
239
+ var _buildResult$status;
240
+ process.exit((_buildResult$status = buildResult.status) !== null && _buildResult$status !== void 0 ? _buildResult$status : 1);
241
+ }
242
+ } else {
243
+ return throwError(ErrorCode.BUILD_SCRIPT_NOT_FOUND, i18n.t("error.build.scriptNotFound"));
244
+ }
245
+ }
246
+ const appName = appManifestJSON.app.name;
247
+ const outputPath = normalizedOptions.output;
248
+ const outputDir = dirname(outputPath);
249
+ const outputFilename = basename(outputPath);
250
+ ensureDirSync(outputDir);
251
+ const outputStream = createWriteStream(outputPath);
252
+ 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 : [];
253
+ const archive = archiver("zip", {
254
+ zlib: {
255
+ level: 9
256
+ }
257
+ });
258
+ archive.on("error", (err) => {
259
+ throw err;
260
+ });
261
+ archive.on("warning", (err) => {
262
+ throw err;
263
+ });
264
+ archive.on("progress", (progress) => {
265
+ const {
266
+ entries,
267
+ fs
268
+ } = progress;
269
+ const entriesStr = entries.total > 0 ? ` ${entries.processed}/${entries.total} files` : "";
270
+ const bytesStr = fs.totalBytes > 0 ? ` ${(fs.processedBytes / 1024).toFixed(1)}/${(fs.totalBytes / 1024).toFixed(1)} KB` : "";
271
+ process.stdout.write(`\rCompressing:${entriesStr}${bytesStr} `);
272
+ });
273
+ archive.on("finish", () => {
274
+ process.stdout.write("\n");
275
+ console.log("");
276
+ console.log("Files in archive: ", PUBLIC_FILENAME.MANIFEST, files);
277
+ console.log(`App "${appName}" built successfully!`);
278
+ console.log(`OPKX "${outputFilename}" created successfully!`);
279
+ console.log(`Output file: ${outputPath}`);
280
+ });
281
+ archive.pipe(outputStream);
282
+ files.forEach((file) => {
283
+ archive.glob(file, {
284
+ cwd: getAppWorkspacePath()
285
+ });
286
+ });
287
+ archive.file(PUBLIC_FILENAME.MANIFEST, {
288
+ name: PUBLIC_FILENAME.MANIFEST
289
+ });
290
+ archive.finalize();
291
+ };
292
+ const config = {
293
+ defaultPort: {
294
+ login: 8200,
295
+ hosted: 8201,
296
+ devWebServer: 8202
297
+ }
298
+ };
299
+ const getConfig = () => config;
300
+ const StoreJSONSchema = z.object({
301
+ version: z.string().optional(),
302
+ timestamp: z.number().optional(),
303
+ base_url: z.string().optional(),
304
+ region_url: z.string().optional(),
305
+ ones_token: z.string().optional(),
306
+ host_token: z.string().optional()
307
+ });
308
+ const {
309
+ ensureFile,
310
+ readJSON,
311
+ writeJSON
312
+ } = fse;
313
+ const name = "@ones-open/cli";
314
+ const paths = envPaths(name);
315
+ const storeDir = paths.config;
316
+ const storePath = join(storeDir, "config.json");
317
+ const getStore = async () => {
318
+ let json = {};
319
+ try {
320
+ await ensureFile(storePath);
321
+ json = await readJSON(storePath, {
322
+ encoding: "utf8"
323
+ });
324
+ } catch (error) {
325
+ const $error = error;
326
+ if ($error.code === "EPERM" || $error.code === "EACCES") {
327
+ return throwError(ErrorCode.STORE_PERMISSION, i18n.t("error.store.permission", {
328
+ filePath: storePath
329
+ }));
330
+ }
331
+ if ($error instanceof SyntaxError) {
332
+ return {};
333
+ }
334
+ throw error;
335
+ }
336
+ try {
337
+ return StoreJSONSchema.parse(json);
338
+ } catch (error) {
339
+ return {};
340
+ }
341
+ };
342
+ const setStore = async (store) => {
343
+ try {
344
+ await ensureFile(storePath);
345
+ const version2 = `${getPackageJSON().version}`;
346
+ const timestamp = Date.now();
347
+ return await writeJSON(storePath, {
348
+ ...store,
349
+ version: version2,
350
+ timestamp
351
+ }, {
352
+ encoding: "utf8"
353
+ });
354
+ } catch (error) {
355
+ const $error = error;
356
+ if ($error.code === "EPERM" || $error.code === "EACCES") {
357
+ return throwError(ErrorCode.STORE_PERMISSION, i18n.t("error.store.permission", {
358
+ filePath: storePath
359
+ }));
360
+ }
361
+ throw error;
362
+ }
363
+ };
364
+ const mergeStore = async (store) => {
365
+ const currentStore = await getStore();
366
+ return setStore({
367
+ ...currentStore,
368
+ ...store
369
+ });
370
+ };
371
+ const getBaseURL = async () => {
372
+ var _store$base_url;
373
+ const store = await getStore();
374
+ return (_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "";
375
+ };
376
+ const setBaseURL = async (baseURL) => {
377
+ return mergeStore({
378
+ base_url: baseURL
379
+ });
380
+ };
381
+ const getRegionURL = async () => {
382
+ var _store$region_url;
383
+ const store = await getStore();
384
+ return (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
385
+ };
386
+ const setRegionURL = async (regionURL) => {
387
+ return mergeStore({
388
+ region_url: regionURL
389
+ });
390
+ };
391
+ const getONESToken = async () => {
392
+ var _store$ones_token;
393
+ const store = await getStore();
394
+ return (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
395
+ };
396
+ const setONESToken = async (token) => {
397
+ return mergeStore({
398
+ ones_token: token
399
+ });
400
+ };
401
+ const getHostToken = async () => {
402
+ var _store$host_token;
403
+ const store = await getStore();
404
+ return (_store$host_token = store.host_token) !== null && _store$host_token !== void 0 ? _store$host_token : "";
405
+ };
406
+ const setHostToken = async (token) => {
407
+ return mergeStore({
408
+ host_token: token
409
+ });
410
+ };
411
+ const API = {
412
+ TOKEN_INFO: "/project/api/project/auth/token_info",
413
+ HOSTED_TOKEN: "/platform/runtime_manager/hosted_token",
414
+ HOSTED_ABILITY_STORAGE_DEV_DECLARE: "/platform/runtime_manager/hosted_ability/storage/dev_declare",
415
+ APP_LIST: "/platform/api/app/list",
416
+ APP_INSTALL: "/platform/api/app/install",
417
+ APP_UPGRADE: "/platform/api/app/upgrade",
418
+ APP_UNINSTALL: "/platform/api/app/:installation_id/uninstall",
419
+ APP_ENABLE: "/platform/api/app/:installation_id/enable",
420
+ APP_DISABLE: "/platform/api/app/:installation_id/disable"
421
+ };
422
+ const REQUEST_TIMEOUT = 1e4;
423
+ const getPath = (path, map2) => {
424
+ var _context;
425
+ return _reduceInstanceProperty(_context = path.split("/")).call(_context, (base, part) => {
426
+ if (/^:/.test(part)) {
427
+ return `${base}/${map2[part.slice(1)]}`;
428
+ }
429
+ return `${base}/${part}`;
430
+ }, "").slice(1);
431
+ };
432
+ const consoleUnauthorizedMessage = () => {
433
+ console.log("Not logged in");
434
+ console.log('Login with "ones login" command');
435
+ process.exit(1);
436
+ };
437
+ const consoleAppNotInstalledMessage = () => {
438
+ console.log("App not installed");
439
+ process.exit(1);
440
+ };
441
+ const getURL = async (path, pathMap, queryMap) => {
442
+ const base = await getRegionURL();
443
+ if (base) {
444
+ const query = new URLSearchParams(queryMap !== null && queryMap !== void 0 ? queryMap : {}).toString();
445
+ return `${base}${getPath(path, pathMap !== null && pathMap !== void 0 ? pathMap : {})}${query ? `?${query}` : ""}`;
446
+ }
447
+ consoleUnauthorizedMessage();
448
+ };
449
+ const getHeaders = async (value) => {
450
+ const token = await getONESToken();
451
+ if (token) {
452
+ return merge({
453
+ Authorization: `Bearer ${token}`
454
+ }, value);
455
+ }
456
+ consoleUnauthorizedMessage();
457
+ process.exit(1);
458
+ };
459
+ const handleError = (error) => {
460
+ var _error$response, _error$response2;
461
+ if (((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) === 401) {
462
+ console.log(error.response.statusText);
463
+ consoleUnauthorizedMessage();
464
+ process.exit(1);
465
+ }
466
+ if ((_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
467
+ try {
468
+ const message = JSON.stringify(error.response.data, null, 2);
469
+ console.error(message);
470
+ process.exit(1);
471
+ } catch (error2) {
472
+ }
473
+ }
474
+ console.error(error);
475
+ return {};
476
+ };
477
+ const fetchAppBase = async (params) => {
478
+ var _params$url;
479
+ const url = await getURL((_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "", params.pathMap, params.queryMap);
480
+ const headers = await getHeaders(params.headers);
481
+ const response = await axios({
482
+ ...params,
483
+ url,
484
+ headers,
485
+ timeout: REQUEST_TIMEOUT
486
+ });
487
+ return response.data;
488
+ };
489
+ const fetchAppList = async (appID) => {
490
+ return await fetchAppBase({
491
+ url: API.APP_LIST,
492
+ method: "GET",
493
+ queryMap: {
494
+ app_id: appID
495
+ }
496
+ }).catch(handleError);
497
+ };
498
+ const fetchTokenInfo = async () => {
499
+ return await fetchAppBase({
500
+ url: API.TOKEN_INFO,
501
+ method: "GET"
502
+ }).catch(handleError);
503
+ };
504
+ const fetchHostedToken = async (data) => {
505
+ return await fetchAppBase({
506
+ url: API.HOSTED_TOKEN,
507
+ method: "POST",
508
+ data
509
+ }).catch(handleError);
510
+ };
511
+ const fetchHostedAbilityStorageDevDeclare = async (data) => {
512
+ return await fetchAppBase({
513
+ url: API.HOSTED_ABILITY_STORAGE_DEV_DECLARE,
514
+ method: "POST",
515
+ data
516
+ }).catch(handleError);
517
+ };
518
+ const fetchAppInstall = async (data) => {
519
+ var _appList$data$0$insta, _appList$data;
520
+ const appID = getAppManifestJSON().app.id;
521
+ const appList = await fetchAppList(appID);
522
+ 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 : "";
523
+ const url = installationID ? API.APP_UPGRADE : API.APP_INSTALL;
524
+ return await fetchAppBase({
525
+ url,
526
+ method: "POST",
527
+ data
528
+ }).catch(handleError);
529
+ };
530
+ const fetchAppUninstall = async () => {
531
+ var _appList$data$0$insta2, _appList$data2;
532
+ const appID = getAppManifestJSON().app.id;
533
+ const appList = await fetchAppList(appID);
534
+ 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 : "";
535
+ if (installationID) {
536
+ return await fetchAppBase({
537
+ url: API.APP_UNINSTALL,
538
+ method: "POST",
539
+ pathMap: {
540
+ installation_id: installationID
541
+ }
542
+ }).catch(handleError);
543
+ }
544
+ consoleAppNotInstalledMessage();
545
+ process.exit(1);
546
+ };
547
+ const fetchAppEnable = async () => {
548
+ var _appList$data$0$insta3, _appList$data3;
549
+ const appID = getAppManifestJSON().app.id;
550
+ const appList = await fetchAppList(appID);
551
+ 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 : "";
552
+ if (installationID) {
553
+ return await fetchAppBase({
554
+ url: API.APP_ENABLE,
555
+ method: "POST",
556
+ pathMap: {
557
+ installation_id: installationID
558
+ }
559
+ }).catch(handleError);
560
+ }
561
+ consoleAppNotInstalledMessage();
562
+ process.exit(1);
563
+ };
564
+ const fetchAppDisable = async () => {
565
+ var _appList$data$0$insta4, _appList$data4;
566
+ const appID = getAppManifestJSON().app.id;
567
+ const appList = await fetchAppList(appID);
568
+ 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 : "";
569
+ if (installationID) {
570
+ return await fetchAppBase({
571
+ url: API.APP_DISABLE,
572
+ method: "POST",
573
+ pathMap: {
574
+ installation_id: installationID
575
+ }
576
+ }).catch(handleError);
577
+ }
578
+ consoleAppNotInstalledMessage();
579
+ process.exit(1);
580
+ };
581
+ const checkTokenInfo = async () => {
582
+ var _store$ones_token, _store$region_url;
583
+ let boolean = true;
584
+ const store = await getStore();
585
+ const token = (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
586
+ const regionURL = (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
587
+ if (token && regionURL) {
588
+ await fetchAppBase({
589
+ url: API.TOKEN_INFO,
590
+ method: "GET"
591
+ }).catch(() => {
592
+ boolean = false;
593
+ });
594
+ } else {
595
+ boolean = false;
596
+ }
597
+ return boolean;
598
+ };
599
+ const isPortNumber = /^[1-9]\d{0,4}$/;
600
+ const minPortNumber = 1;
601
+ const maxPortNumber = 65535;
602
+ const MANIFEST_PATH = "/manifest";
603
+ const ONES_CLI_INTERNAL_MANIFEST_PATH = "/__ones_cli_internal_manifest__";
604
+ const MAX_RELAY_BODY_BYTES = 64 * 1024 * 1024;
605
+ const normalize$9 = async (options) => {
606
+ const portInput = options.port;
607
+ if (portInput)
608
+ ;
609
+ else {
610
+ return throwError(ErrorCode.MISSING_PORT, i18n.t("error.tunnel.missingPort"));
611
+ }
612
+ const portString = String(portInput);
613
+ const portNumber = Number(portString);
614
+ if (isPortNumber.test(portString))
615
+ ;
616
+ else {
617
+ return throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
618
+ }
619
+ if (portNumber < minPortNumber || portNumber > maxPortNumber) {
620
+ return throwError(ErrorCode.INCORRECT_PORT, i18n.t("error.tunnel.incorrectPort"));
621
+ }
622
+ const port = portString;
623
+ return {
624
+ port
625
+ };
626
+ };
627
+ const getTunnelContext = async () => {
628
+ var _appManifestJSON$app$, _appManifestJSON$app, _store$region_url, _store$ones_token;
629
+ const appManifestJSON = getAppManifestJSON();
630
+ 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$ : "";
631
+ const store = await getStore();
632
+ const regionURL = (_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "";
633
+ const onesToken = (_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "";
634
+ if (appID && regionURL && onesToken) {
635
+ return {
636
+ appID,
637
+ regionURL,
638
+ onesToken,
639
+ store,
640
+ appManifestJSON
641
+ };
642
+ }
643
+ consoleUnauthorizedMessage();
644
+ process.exit(1);
645
+ };
646
+ const getHostedTokenScopes = (ones2) => {
647
+ const storage = ones2 === null || ones2 === void 0 ? void 0 : ones2.storage;
648
+ if (!storage) {
649
+ return [];
650
+ }
651
+ const scopes = /* @__PURE__ */ new Set();
652
+ if (Array.isArray(storage.entities) && storage.entities.length > 0) {
653
+ scopes.add(HostedTokenScope.STORAGE_ENTITY);
654
+ }
655
+ if (storage.object !== void 0 && storage.object !== null && storage.object !== false) {
656
+ scopes.add(HostedTokenScope.STORAGE_OBJECT);
657
+ }
658
+ return Array.from(scopes);
659
+ };
660
+ const getRelayScope = () => {
661
+ return HostedTokenScope.RELAY;
662
+ };
663
+ const buildTunnelUrl = async () => {
664
+ const {
665
+ appID,
666
+ regionURL
667
+ } = await getTunnelContext();
668
+ const url = new URL(regionURL);
669
+ url.pathname = `/platform/app/relay/dispatch/${appID}`;
670
+ return url.toString();
671
+ };
672
+ class TunnelClient {
673
+ constructor(localPort, baseUrl, appID, hostedToken) {
674
+ let enableInternalManifestRoute = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
675
+ let replaceExisting = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : true;
676
+ this.ws = null;
677
+ this.localPort = localPort;
678
+ this.baseUrl = baseUrl;
679
+ this.appID = appID;
680
+ this.hostedToken = hostedToken;
681
+ this.enableInternalManifestRoute = enableInternalManifestRoute;
682
+ this.replaceExisting = replaceExisting;
683
+ }
684
+ async connect() {
685
+ const proxyUrl = this.buildProxyUrl();
686
+ this.ws = new WebSocket(proxyUrl, {
687
+ headers: {
688
+ Authorization: `Bearer ${this.hostedToken}`
689
+ },
690
+ maxPayload: MAX_RELAY_BODY_BYTES
691
+ });
692
+ this.ws.on("message", async (data) => {
693
+ const message = this.parseMessage(data);
694
+ if (!message) {
695
+ return;
696
+ }
697
+ await this.handleMessage(message);
698
+ });
699
+ this.ws.on("ping", (data) => {
700
+ var _this$ws;
701
+ (_this$ws = this.ws) === null || _this$ws === void 0 || _this$ws.pong(data);
702
+ });
703
+ this.ws.on("error", (error) => {
704
+ console.error("WebSocket error:", error);
705
+ });
706
+ return new Promise((resolve2, reject) => {
707
+ var _this$ws2, _this$ws3;
708
+ (_this$ws2 = this.ws) === null || _this$ws2 === void 0 || _this$ws2.on("open", () => resolve2());
709
+ (_this$ws3 = this.ws) === null || _this$ws3 === void 0 || _this$ws3.on("error", reject);
710
+ });
711
+ }
712
+ close() {
713
+ var _this$ws4;
714
+ (_this$ws4 = this.ws) === null || _this$ws4 === void 0 || _this$ws4.close();
715
+ }
716
+ buildProxyUrl() {
717
+ const url = new URL("/platform/app/relay/", this.baseUrl);
718
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
719
+ url.searchParams.set("app_id", this.appID);
720
+ url.searchParams.set("replace_existing", String(this.replaceExisting));
721
+ return url.toString();
722
+ }
723
+ parseMessage(data) {
724
+ const buffer = this.toBuffer(data);
725
+ if (!buffer) {
726
+ return null;
727
+ }
728
+ if (buffer.length >= 4) {
729
+ const binary = this.parseBinaryEnvelope(buffer);
730
+ if (binary) {
731
+ return binary;
732
+ }
733
+ }
734
+ return this.parseJSONEnvelope(buffer.toString());
735
+ }
736
+ async handleMessage(message) {
737
+ const request = this.getRequestPayload(message);
738
+ if (!request) {
739
+ return;
740
+ }
741
+ if (this.enableInternalManifestRoute && request.path === ONES_CLI_INTERNAL_MANIFEST_PATH) {
742
+ const appManifest = getAppManifestJSON().app;
743
+ const baseURL = await buildTunnelUrl();
744
+ const reply = {
745
+ id: message.id,
746
+ payload: {
747
+ status: 200,
748
+ headers: {
749
+ "content-type": ["application/json"]
750
+ },
751
+ body: {
752
+ ...appManifest,
753
+ base_url: baseURL
754
+ }
755
+ }
756
+ };
757
+ this.sendBinaryEnvelope(reply);
758
+ return;
759
+ }
760
+ try {
761
+ const response = await this.forwardRequest(request);
762
+ const reply = {
763
+ id: message.id,
764
+ payload: response
765
+ };
766
+ this.sendBinaryEnvelope(reply);
767
+ } catch (error) {
768
+ const reply = {
769
+ id: message.id,
770
+ payload: {
771
+ status: 500,
772
+ headers: {
773
+ "x-agent-error": [error instanceof Error ? error.message : "Unknown error"]
774
+ },
775
+ body: "agent request error"
776
+ }
777
+ };
778
+ this.sendBinaryEnvelope(reply);
779
+ }
780
+ }
781
+ getRequestPayload(message) {
782
+ const payload = message.payload;
783
+ if (!(payload !== null && payload !== void 0 && payload.method) || !(payload !== null && payload !== void 0 && payload.path)) {
784
+ return null;
785
+ }
786
+ return payload;
787
+ }
788
+ async forwardRequest(payload) {
789
+ const url = new URL(payload.path, `http://127.0.0.1:${this.localPort}`);
790
+ if (payload.query) {
791
+ Object.entries(payload.query).forEach((_ref) => {
792
+ let [key, value] = _ref;
793
+ if (Array.isArray(value)) {
794
+ value.forEach((item) => {
795
+ url.searchParams.append(key, item);
796
+ });
797
+ return;
798
+ }
799
+ url.searchParams.append(key, value);
800
+ });
801
+ }
802
+ const response = await axios.request({
803
+ url: url.toString(),
804
+ method: payload.method,
805
+ headers: payload.headers,
806
+ data: payload.body,
807
+ responseType: "arraybuffer",
808
+ validateStatus: () => true,
809
+ maxBodyLength: MAX_RELAY_BODY_BYTES,
810
+ maxContentLength: MAX_RELAY_BODY_BYTES
811
+ });
812
+ const responseBytes = Buffer.from(response.data);
813
+ return {
814
+ status: response.status,
815
+ headers: this.collectHeaders(response.headers),
816
+ body: responseBytes
817
+ };
818
+ }
819
+ collectHeaders(headers) {
820
+ const collected = {};
821
+ Object.entries(headers).forEach((_ref2) => {
822
+ let [key, value] = _ref2;
823
+ if (Array.isArray(value)) {
824
+ collected[key] = value.map((item) => String(item));
825
+ return;
826
+ }
827
+ if (value !== void 0 && value !== null) {
828
+ collected[key] = [String(value)];
829
+ }
830
+ });
831
+ return collected;
832
+ }
833
+ sendBinaryEnvelope(envelope) {
834
+ var _this$ws5;
835
+ const encoded = this.encodeBinaryEnvelope(envelope);
836
+ (_this$ws5 = this.ws) === null || _this$ws5 === void 0 || _this$ws5.send(encoded);
837
+ }
838
+ encodeBinaryEnvelope(envelope) {
839
+ var _envelope$payload;
840
+ const payload = (_envelope$payload = envelope.payload) !== null && _envelope$payload !== void 0 ? _envelope$payload : {};
841
+ const body = this.toBodyBuffer(payload.body);
842
+ if (body.length > MAX_RELAY_BODY_BYTES) {
843
+ throw new Error("relay body too large");
844
+ }
845
+ const metaPayload = {
846
+ ...payload
847
+ };
848
+ delete metaPayload.body;
849
+ const meta = Buffer.from(JSON.stringify({
850
+ id: envelope.id,
851
+ payload: metaPayload
852
+ }), "utf8");
853
+ const header = Buffer.allocUnsafe(4);
854
+ header.writeUInt32BE(meta.length, 0);
855
+ return Buffer.concat([header, meta, body]);
856
+ }
857
+ toBodyBuffer(body) {
858
+ if (body === void 0 || body === null) {
859
+ return Buffer.alloc(0);
860
+ }
861
+ if (Buffer.isBuffer(body)) {
862
+ return body;
863
+ }
864
+ if (body instanceof ArrayBuffer) {
865
+ return Buffer.from(body);
866
+ }
867
+ if (ArrayBuffer.isView(body)) {
868
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
869
+ }
870
+ if (typeof body === "string") {
871
+ return Buffer.from(body, "utf8");
872
+ }
873
+ return Buffer.from(JSON.stringify(body), "utf8");
874
+ }
875
+ parseBinaryEnvelope(buffer) {
876
+ const metaLength = buffer.readUInt32BE(0);
877
+ if (metaLength <= 0 || 4 + metaLength > buffer.length) {
878
+ return null;
879
+ }
880
+ const metaRaw = buffer.subarray(4, 4 + metaLength).toString("utf8");
881
+ try {
882
+ const envelope = JSON.parse(metaRaw);
883
+ if (!(envelope !== null && envelope !== void 0 && envelope.payload)) {
884
+ return envelope;
885
+ }
886
+ const body = buffer.subarray(4 + metaLength);
887
+ if (body.length > MAX_RELAY_BODY_BYTES) {
888
+ console.error("Binary tunnel body exceeds size limit");
889
+ return null;
890
+ }
891
+ const payload = envelope.payload;
892
+ payload.body = body;
893
+ return envelope;
894
+ } catch (error) {
895
+ console.error("Invalid binary tunnel message:", error);
896
+ return null;
897
+ }
898
+ }
899
+ parseJSONEnvelope(payload) {
900
+ try {
901
+ const message = JSON.parse(payload);
902
+ if (!message) {
903
+ return null;
904
+ }
905
+ return message;
906
+ } catch (error) {
907
+ console.error("Invalid tunnel message:", error);
908
+ return null;
909
+ }
910
+ }
911
+ toBuffer(data) {
912
+ if (Buffer.isBuffer(data)) {
913
+ return data;
914
+ }
915
+ if (Array.isArray(data)) {
916
+ return Buffer.concat(data);
917
+ }
918
+ if (data instanceof ArrayBuffer) {
919
+ return Buffer.from(data);
920
+ }
921
+ return null;
922
+ }
923
+ }
924
+ const invokeTunnel = async function(port) {
925
+ var _options$rebuildWhenE, _options$enableIntern, _hostedTokenResponse$;
926
+ let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
927
+ const {
928
+ appManifestJSON,
929
+ appID,
930
+ regionURL
931
+ } = await getTunnelContext();
932
+ const rebuildWhenExists = (_options$rebuildWhenE = options.rebuildWhenExists) !== null && _options$rebuildWhenE !== void 0 ? _options$rebuildWhenE : true;
933
+ const enableInternalManifestRoute = (_options$enableIntern = options.enableInternalManifestRoute) !== null && _options$enableIntern !== void 0 ? _options$enableIntern : true;
934
+ const storageScopes = getHostedTokenScopes(appManifestJSON.ones);
935
+ const scopes = Array.from(/* @__PURE__ */ new Set([...storageScopes, getRelayScope()]));
936
+ const hostedTokenResponse = await fetchHostedToken({
937
+ app_id: appID,
938
+ scopes
939
+ });
940
+ const hostedToken = hostedTokenResponse === null || hostedTokenResponse === void 0 || (_hostedTokenResponse$ = hostedTokenResponse.data) === null || _hostedTokenResponse$ === void 0 ? void 0 : _hostedTokenResponse$.hosted_token;
941
+ if (!hostedToken) {
942
+ return throwError(ErrorCode.HOSTED_TOKEN_EMPTY, i18n.t("error.hostedToken.empty"));
943
+ }
944
+ await setHostToken(hostedToken);
945
+ const client = new TunnelClient(port, regionURL, appID, hostedToken, enableInternalManifestRoute, rebuildWhenExists);
946
+ await client.connect();
947
+ };
948
+ const tunnel = async function() {
949
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
950
+ args[_key] = arguments[_key];
951
+ }
952
+ const {
953
+ options
954
+ } = getCommandOptions(args, tunnelCommandArguments);
955
+ const normalizedOptions = await normalize$9(options);
956
+ const port = Number(normalizedOptions.port);
957
+ await invokeTunnel(port, {
958
+ enableInternalManifestRoute: false,
959
+ rebuildWhenExists: true
960
+ });
961
+ const runnelUrl = await buildTunnelUrl();
962
+ console.log(`Relay endpoint: ${runnelUrl}`);
963
+ };
964
+ const normalize$8 = async (options) => {
965
+ noop(options);
966
+ return {};
967
+ };
968
+ const displayAppDetail = async (installationID) => {
969
+ var _tokenInfo$org$uuid, _tokenInfo$org, _tokenInfo$teams$0$uu, _tokenInfo$teams, _tokenInfo$org$visibi, _tokenInfo$org2;
970
+ const tokenInfo = await fetchTokenInfo();
971
+ 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 : "";
972
+ 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 : "";
973
+ 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;
974
+ const baseURL = await getBaseURL();
975
+ if (isOrgVisible && orgUUID) {
976
+ const url = `${baseURL}project/#/org/${orgUUID}/setting/app_manager/platform_app/${installationID}`;
977
+ console.log(`See App detail: ${url}`);
978
+ }
979
+ if (!isOrgVisible && teamUUID) {
980
+ const url = `${baseURL}project/#/team/${teamUUID}/team_setting/app_manager/platform_app/${installationID}`;
981
+ console.log(`See App detail: ${url}`);
982
+ }
983
+ };
984
+ const invokeInstall = async (manifestUrl) => {
985
+ const {
986
+ app
987
+ } = getAppManifestJSON();
988
+ const appName = app.name;
989
+ const appID = app.id;
990
+ const result = await fetchAppInstall({
991
+ manifest_url: manifestUrl,
992
+ options: {
993
+ enable: true
994
+ }
995
+ });
996
+ if (result.code === "OK") {
997
+ var _appList$data$0$insta, _appList$data;
998
+ console.log(`App "${appName}" installed successfully!`);
999
+ const appList = await fetchAppList(appID);
1000
+ 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 : "";
1001
+ if (installationID) {
1002
+ await displayAppDetail(installationID);
1003
+ }
1004
+ } else {
1005
+ console.log(`App "${appName}" installed failed!`);
1006
+ console.error(JSON.stringify(result, null, 2));
1007
+ }
1008
+ };
1009
+ const getManifestUrl = async () => {
1010
+ const runnelUrl = await buildTunnelUrl();
1011
+ const customManifestUrl = `${runnelUrl}${MANIFEST_PATH}`;
1012
+ const internalManifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1013
+ const internalResult = await axios.get(internalManifestUrl).then((response) => {
1014
+ if (response.status === 200) {
1015
+ return internalManifestUrl;
1016
+ }
1017
+ return null;
1018
+ }).catch(noop);
1019
+ if (internalResult) {
1020
+ return internalResult;
1021
+ }
1022
+ const customResult = await axios.get(customManifestUrl).then((response) => {
1023
+ if (response.status === 200) {
1024
+ return customManifestUrl;
1025
+ }
1026
+ return null;
1027
+ }).catch(noop);
1028
+ if (customResult) {
1029
+ return customResult;
1030
+ }
1031
+ return null;
1032
+ };
1033
+ const install = async function() {
1034
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1035
+ args[_key] = arguments[_key];
1036
+ }
1037
+ const {
1038
+ options
1039
+ } = getCommandOptions(args, installCommandArguments);
1040
+ const normalizedOptions = await normalize$8(options);
1041
+ noop(normalizedOptions);
1042
+ const {
1043
+ app
1044
+ } = getAppManifestJSON();
1045
+ const appName = app.name;
1046
+ const manifestUrl = await getManifestUrl();
1047
+ if (!manifestUrl) {
1048
+ console.log(`App "${appName}" server not available!`);
1049
+ console.log('Use "ones dev" command or "ones tunnel" command to start the server first');
1050
+ process.exit(1);
1051
+ }
1052
+ await invokeInstall(manifestUrl);
1053
+ };
1054
+ var InstallOptions = /* @__PURE__ */ ((InstallOptions2) => {
1055
+ InstallOptions2["AUTO"] = "auto";
1056
+ InstallOptions2["TRUE"] = "true";
1057
+ InstallOptions2["FALSE"] = "false";
1058
+ return InstallOptions2;
1059
+ })(InstallOptions || {});
1060
+ const defaultInstall = InstallOptions.AUTO;
1061
+ const normalize$7 = async (options) => {
1062
+ var _options$install, _options$command;
1063
+ let install2 = (_options$install = options.install) !== null && _options$install !== void 0 ? _options$install : defaultInstall;
1064
+ const command = (_options$command = options.command) !== null && _options$command !== void 0 ? _options$command : "";
1065
+ switch (true) {
1066
+ case install2 === InstallOptions.AUTO:
1067
+ break;
1068
+ case Boolean(install2):
1069
+ install2 = InstallOptions.TRUE;
1070
+ break;
1071
+ default:
1072
+ install2 = InstallOptions.FALSE;
1073
+ break;
1074
+ }
1075
+ return {
1076
+ install: install2,
1077
+ command
1078
+ };
1079
+ };
1080
+ const IDLE_MS = 2e3;
1081
+ function createReadyStatusPipes(onReady) {
1082
+ let readyTimer = null;
1083
+ let summaryPrinted = false;
1084
+ const scheduleReady = () => {
1085
+ if (summaryPrinted)
1086
+ return;
1087
+ if (readyTimer)
1088
+ clearTimeout(readyTimer);
1089
+ readyTimer = setTimeout(() => {
1090
+ readyTimer = null;
1091
+ if (!summaryPrinted) {
1092
+ summaryPrinted = true;
1093
+ onReady();
1094
+ }
1095
+ }, IDLE_MS);
1096
+ };
1097
+ const pipe = (stream, isStderr) => {
1098
+ const write = (chunk) => {
1099
+ if (isStderr)
1100
+ process.stderr.write(chunk);
1101
+ else
1102
+ process.stdout.write(chunk);
1103
+ };
1104
+ stream.on("data", (chunk) => {
1105
+ const str = typeof chunk === "string" ? chunk : chunk.toString();
1106
+ write(str);
1107
+ if (str.startsWith("[backend]") || str.startsWith("[web]")) {
1108
+ scheduleReady();
1109
+ }
1110
+ });
1111
+ };
1112
+ return pipe;
1113
+ }
1114
+ const dev = async function() {
1115
+ var _appRcJSON$dev, _defaultAppRcJSON$dev, _appRcJSON$dev$comman, _appRcJSON$dev2;
1116
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1117
+ args[_key] = arguments[_key];
1118
+ }
1119
+ const {
1120
+ options
1121
+ } = getCommandOptions(args, devCommandArguments);
1122
+ const normalizedOptions = await normalize$7(options);
1123
+ const appRcJSON = await getAppRcJSON();
1124
+ const appPackageJSON = getAppPackageJSON();
1125
+ const firstCommand = normalizedOptions.command || ((_appRcJSON$dev = appRcJSON.dev) === null || _appRcJSON$dev === void 0 || (_appRcJSON$dev = _appRcJSON$dev.command) === null || _appRcJSON$dev === void 0 ? void 0 : _appRcJSON$dev[0]) || ((_defaultAppRcJSON$dev = defaultAppRcJSON.dev) === null || _defaultAppRcJSON$dev === void 0 || (_defaultAppRcJSON$dev = _defaultAppRcJSON$dev.command) === null || _defaultAppRcJSON$dev === void 0 ? void 0 : _defaultAppRcJSON$dev[0]) || "";
1126
+ if (!firstCommand) {
1127
+ return throwError(ErrorCode.INCORRECT_DEV_COMMAND, i18n.t("error.dev.incorrectCommand"));
1128
+ }
1129
+ const currentCommand = normalizedOptions.command ? normalizedOptions.command.split(" ") : (_appRcJSON$dev$comman = (_appRcJSON$dev2 = appRcJSON.dev) === null || _appRcJSON$dev2 === void 0 ? void 0 : _appRcJSON$dev2.command) !== null && _appRcJSON$dev$comman !== void 0 ? _appRcJSON$dev$comman : [];
1130
+ const currentCommandString = currentCommand.join(" ");
1131
+ const defaultDevCommandString = defaultDevCommand.join(" ");
1132
+ if (currentCommandString === defaultDevCommandString) {
1133
+ var _appPackageJSON$scrip;
1134
+ if (!((_appPackageJSON$scrip = appPackageJSON.scripts) !== null && _appPackageJSON$scrip !== void 0 && _appPackageJSON$scrip.dev)) {
1135
+ return throwError(ErrorCode.DEV_SCRIPT_NOT_FOUND, i18n.t("error.dev.scriptNotFound"));
1136
+ }
1137
+ }
1138
+ let enableTunnel = true;
1139
+ if (normalizedOptions.install === InstallOptions.TRUE)
1140
+ ;
1141
+ else {
1142
+ enableTunnel = await checkTokenInfo();
1143
+ }
1144
+ const appManifestJSON = getAppManifestJSON();
1145
+ const {
1146
+ app,
1147
+ ones: ones2
1148
+ } = appManifestJSON;
1149
+ const appID = app.id;
1150
+ const config2 = getConfig();
1151
+ const ONES_HOSTED_PORT = await getPort({
1152
+ port: config2.defaultPort.hosted
1153
+ });
1154
+ const ONES_DEV_WEB_SERVER_PORT = await getPort({
1155
+ port: config2.defaultPort.devWebServer
1156
+ });
1157
+ const env2 = {
1158
+ ...process.env,
1159
+ NODE_ENV: "development",
1160
+ ONES_HOSTED_PORT: `${ONES_HOSTED_PORT}`,
1161
+ ONES_DEV_WEB_SERVER_PORT: `${ONES_DEV_WEB_SERVER_PORT}`,
1162
+ ONES_HOSTED_TOKEN: "",
1163
+ ONES_HOSTED_APP_ID: "",
1164
+ ONES_HOSTED_BASE_URL: ""
1165
+ };
1166
+ if (enableTunnel) {
1167
+ var _ones$storage$entitie, _ones$storage;
1168
+ await invokeTunnel(ONES_HOSTED_PORT, {
1169
+ enableInternalManifestRoute: true,
1170
+ rebuildWhenExists: true
1171
+ });
1172
+ const regionURL = await getRegionURL();
1173
+ const ONES_HOSTED_TOKEN = await getHostToken();
1174
+ const ONES_HOSTED_APP_ID = appID;
1175
+ const ONES_HOSTED_BASE_URL = `${regionURL}/platform/runtime_manager`;
1176
+ env2.ONES_HOSTED_TOKEN = ONES_HOSTED_TOKEN;
1177
+ env2.ONES_HOSTED_APP_ID = ONES_HOSTED_APP_ID;
1178
+ env2.ONES_HOSTED_BASE_URL = ONES_HOSTED_BASE_URL;
1179
+ const entities = (_ones$storage$entitie = ones2 === null || ones2 === void 0 || (_ones$storage = ones2.storage) === null || _ones$storage === void 0 ? void 0 : _ones$storage.entities) !== null && _ones$storage$entitie !== void 0 ? _ones$storage$entitie : [];
1180
+ if (entities.length > 0) {
1181
+ await fetchHostedAbilityStorageDevDeclare({
1182
+ app_id: appID,
1183
+ cleanup_legacy: false,
1184
+ opkx_content: appManifestJSON
1185
+ });
1186
+ }
1187
+ }
1188
+ const onReady = async () => {
1189
+ const appName = app.name;
1190
+ let manifestUrl = "";
1191
+ console.log("");
1192
+ console.log(`Local: http://localhost:${ONES_HOSTED_PORT}`);
1193
+ if (enableTunnel) {
1194
+ const runnelUrl = await buildTunnelUrl();
1195
+ console.log(`URL: ${runnelUrl}`);
1196
+ manifestUrl = `${runnelUrl}${ONES_CLI_INTERNAL_MANIFEST_PATH}`;
1197
+ }
1198
+ console.log("Docs site: https://open.ones.com/");
1199
+ console.log(`App "${appName}" server is ready!`);
1200
+ console.log("");
1201
+ if (enableTunnel) {
1202
+ switch (normalizedOptions.install) {
1203
+ case InstallOptions.TRUE:
1204
+ await invokeInstall(manifestUrl);
1205
+ break;
1206
+ case InstallOptions.AUTO:
1207
+ {
1208
+ var _appList$data$0$insta, _appList$data;
1209
+ const appList = await fetchAppList(appID);
1210
+ 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 : "";
1211
+ if (installationID) {
1212
+ await displayAppDetail(installationID);
1213
+ } else {
1214
+ await invokeInstall(manifestUrl);
1215
+ }
1216
+ }
1217
+ break;
1218
+ case InstallOptions.FALSE:
1219
+ break;
1220
+ }
1221
+ }
1222
+ };
1223
+ const cwd2 = getAppWorkspacePath();
1224
+ const child = spawn(firstCommand, currentCommand.slice(1), {
1225
+ cwd: cwd2,
1226
+ stdio: ["inherit", "pipe", "pipe"],
1227
+ env: env2,
1228
+ shell: true
1229
+ });
1230
+ const pipe = createReadyStatusPipes(onReady);
1231
+ if (child.stdout)
1232
+ pipe(child.stdout, false);
1233
+ if (child.stderr)
1234
+ pipe(child.stderr, true);
1235
+ const cleanup = () => {
1236
+ child.kill();
1237
+ };
1238
+ const onSignal = () => {
1239
+ cleanup();
1240
+ process.exit(128 + 2);
1241
+ };
1242
+ process.on("SIGINT", onSignal);
1243
+ process.on("SIGTERM", onSignal);
1244
+ await new Promise((resolve2) => {
1245
+ child.on("exit", () => {
1246
+ cleanup();
1247
+ process.off("SIGINT", onSignal);
1248
+ process.off("SIGTERM", onSignal);
1249
+ resolve2();
1250
+ });
1251
+ });
1252
+ };
1253
+ function createPromise() {
1254
+ let resolve2;
1255
+ let reject;
1256
+ const promise = new Promise((res, rej) => {
1257
+ resolve2 = res;
1258
+ reject = rej;
1259
+ });
1260
+ return {
1261
+ promise,
1262
+ resolve: resolve2,
1263
+ reject
1264
+ };
1265
+ }
1266
+ const sleep = (number) => {
1267
+ return new Promise((resolve2) => {
1268
+ setTimeout(resolve2, number);
1269
+ });
1270
+ };
1271
+ const isURL = /^https?:\/\//;
1272
+ const HostBlackList = ["ones.cn", "www.ones.cn", "ones.com", "www.ones.com"];
1273
+ const normalize$6 = async (options) => {
1274
+ const baseURLInput = options.baseURL;
1275
+ if (baseURLInput)
1276
+ ;
1277
+ else {
1278
+ return throwError(ErrorCode.MISSING_BASE_URL, i18n.t("error.login.missingBaseURL"));
1279
+ }
1280
+ if (isURL.test(baseURLInput))
1281
+ ;
1282
+ else {
1283
+ return throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1284
+ }
1285
+ let baseURL = "";
1286
+ try {
1287
+ const url = new URL(baseURLInput);
1288
+ const host = url.hostname;
1289
+ if (_includesInstanceProperty(HostBlackList).call(HostBlackList, host)) {
1290
+ return throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1291
+ }
1292
+ url.pathname = "";
1293
+ url.search = "";
1294
+ url.hash = "";
1295
+ baseURL = url.toString();
1296
+ } catch (error) {
1297
+ return throwError(ErrorCode.INCORRECT_BASE_URL, i18n.t("error.login.incorrectBaseURL"));
1298
+ }
1299
+ return {
1300
+ baseURL
1301
+ };
1302
+ };
1303
+ const login = async function() {
1304
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1305
+ args[_key] = arguments[_key];
1306
+ }
1307
+ const {
1308
+ options
1309
+ } = getCommandOptions(args, loginCommandArguments);
1310
+ const normalizedOptions = await normalize$6(options);
1311
+ const base = normalizedOptions.baseURL;
1312
+ const path = "project/oauth2.html";
1313
+ const config2 = getConfig();
1314
+ const port = await getPort({
1315
+ port: config2.defaultPort.login
1316
+ });
1317
+ const uuid = v4();
1318
+ const search = new URLSearchParams();
1319
+ search.set("redirect_path", "/developer/cli");
1320
+ search.set("redirect_url", `http://localhost:${port}`);
1321
+ search.set("state", uuid);
1322
+ const url = `${base}${path}?${search}`;
1323
+ const publicPath = getPublicPath();
1324
+ const htmlPath = join(publicPath, "callback.html");
1325
+ const html = readFileSync(htmlPath, {
1326
+ encoding: "utf-8"
1327
+ });
1328
+ const logoPath = join(publicPath, "logo.svg");
1329
+ const logo = readFileSync(logoPath, {
1330
+ encoding: "utf-8"
1331
+ });
1332
+ const {
1333
+ promise,
1334
+ resolve: resolve2
1335
+ } = createPromise();
1336
+ const server = http.createServer((req, res) => {
1337
+ var _req$url$split$, _req$url, _search2$get, _search2$get2;
1338
+ const search2 = new URLSearchParams((_req$url$split$ = (_req$url = req.url) === null || _req$url === void 0 ? void 0 : _req$url.split("?")[1]) !== null && _req$url$split$ !== void 0 ? _req$url$split$ : "");
1339
+ const state = search2.get("state");
1340
+ if (state === "logo") {
1341
+ res.writeHead(200, {
1342
+ "Content-Type": "image/svg+xml"
1343
+ });
1344
+ res.end(logo);
1345
+ return;
1346
+ }
1347
+ if (state === "cancel") {
1348
+ res.writeHead(200, {
1349
+ "Content-Type": "image/svg+xml"
1350
+ });
1351
+ res.end(logo);
1352
+ resolve2(null);
1353
+ return;
1354
+ }
1355
+ const token = (_search2$get = search2.get("access_token")) !== null && _search2$get !== void 0 ? _search2$get : "";
1356
+ const region = (_search2$get2 = search2.get("region_url")) !== null && _search2$get2 !== void 0 ? _search2$get2 : "";
1357
+ if (state === uuid && token && region) {
1358
+ resolve2({
1359
+ base_url: base,
1360
+ ones_token: token,
1361
+ region_url: region
1362
+ });
1363
+ res.writeHead(200, {
1364
+ "Content-Type": "text/html"
1365
+ });
1366
+ res.end(html);
1367
+ return;
1368
+ }
1369
+ res.writeHead(200, {
1370
+ "Content-Type": "text/html"
1371
+ });
1372
+ res.end("Invalid state error, please try again!");
1373
+ });
1374
+ server.listen(port);
1375
+ promise.then(async (store) => {
1376
+ await sleep(100);
1377
+ server.closeAllConnections();
1378
+ if (store) {
1379
+ var _store$base_url, _store$ones_token, _store$region_url;
1380
+ await setBaseURL((_store$base_url = store.base_url) !== null && _store$base_url !== void 0 ? _store$base_url : "");
1381
+ await setONESToken((_store$ones_token = store.ones_token) !== null && _store$ones_token !== void 0 ? _store$ones_token : "");
1382
+ await setRegionURL((_store$region_url = store.region_url) !== null && _store$region_url !== void 0 ? _store$region_url : "");
1383
+ console.log("Logged in successfully!");
1384
+ } else {
1385
+ console.log("Login canceled!");
1386
+ }
1387
+ process$1.exit(0);
1388
+ });
1389
+ console.log("Logging into your ONES account...");
1390
+ console.log(`Opening ${url}`);
1391
+ ora("Waiting for authorization...").start();
1392
+ await open(url);
1393
+ };
1394
+ const normalize$5 = async (options) => {
1395
+ noop(options);
1396
+ return {};
1397
+ };
1398
+ const logout = async function() {
1399
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1400
+ args[_key] = arguments[_key];
1401
+ }
1402
+ const {
1403
+ options
1404
+ } = getCommandOptions(args, logoutCommandArguments);
1405
+ const normalizedOptions = await normalize$5(options);
1406
+ noop(normalizedOptions);
1407
+ await setStore({});
1408
+ console.log("Logged out successfully!");
1409
+ };
1410
+ const normalize$4 = async (options) => {
1411
+ noop(options);
1412
+ return {};
1413
+ };
1414
+ const whoami = async function() {
1415
+ var _tokenInfo$user, _tokenInfo$user2;
1416
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1417
+ args[_key] = arguments[_key];
1418
+ }
1419
+ const {
1420
+ options
1421
+ } = getCommandOptions(args, whoamiCommandArguments);
1422
+ const normalizedOptions = await normalize$4(options);
1423
+ noop(normalizedOptions);
1424
+ const baseURL = await getBaseURL();
1425
+ const tokenInfo = await fetchTokenInfo();
1426
+ const name2 = (_tokenInfo$user = tokenInfo.user) === null || _tokenInfo$user === void 0 ? void 0 : _tokenInfo$user.name;
1427
+ const email = (_tokenInfo$user2 = tokenInfo.user) === null || _tokenInfo$user2 === void 0 ? void 0 : _tokenInfo$user2.email;
1428
+ if (name2 && email) {
1429
+ console.log(`User: ${name2}`);
1430
+ console.log(`Email: ${email}`);
1431
+ console.log(`ONES: ${baseURL}`);
1432
+ } else {
1433
+ consoleUnauthorizedMessage();
1434
+ }
1435
+ };
1436
+ const normalize$3 = async (options) => {
1437
+ noop(options);
1438
+ return {};
1439
+ };
1440
+ const enable = async function() {
1441
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1442
+ args[_key] = arguments[_key];
1443
+ }
1444
+ const {
1445
+ options
1446
+ } = getCommandOptions(args, enableCommandArguments);
1447
+ const normalizedOptions = await normalize$3(options);
1448
+ noop(normalizedOptions);
1449
+ const appName = getAppManifestJSON().app.name;
1450
+ const result = await fetchAppEnable();
1451
+ if (result.code === "OK") {
1452
+ console.log(`App "${appName}" enabled successfully!`);
1453
+ } else {
1454
+ console.log(`App "${appName}" enabled failed!`);
1455
+ console.error(JSON.stringify(result, null, 2));
1456
+ }
1457
+ };
1458
+ const normalize$2 = async (options) => {
1459
+ noop(options);
1460
+ return {};
1461
+ };
1462
+ const disable = async function() {
1463
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1464
+ args[_key] = arguments[_key];
1465
+ }
1466
+ const {
1467
+ options
1468
+ } = getCommandOptions(args, disableCommandArguments);
1469
+ const normalizedOptions = await normalize$2(options);
1470
+ noop(normalizedOptions);
1471
+ const appName = getAppManifestJSON().app.name;
1472
+ const result = await fetchAppDisable();
1473
+ if (result.code === "OK") {
1474
+ console.log(`App "${appName}" disabled successfully!`);
1475
+ } else {
1476
+ console.log(`App "${appName}" disabled failed!`);
1477
+ console.error(JSON.stringify(result, null, 2));
1478
+ }
1479
+ };
1480
+ const normalize$1 = async (options) => {
1481
+ noop(options);
1482
+ return {};
1483
+ };
1484
+ const uninstall = async function() {
1485
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1486
+ args[_key] = arguments[_key];
1487
+ }
1488
+ const {
1489
+ options
1490
+ } = getCommandOptions(args, uninstallCommandArguments);
1491
+ const normalizedOptions = await normalize$1(options);
1492
+ noop(normalizedOptions);
1493
+ const appName = getAppManifestJSON().app.name;
1494
+ const result = await fetchAppUninstall();
1495
+ if (result.code === "OK") {
1496
+ console.log(`App "${appName}" uninstalled successfully!`);
1497
+ } else {
1498
+ console.log(`App "${appName}" uninstalled failed!`);
1499
+ console.error(JSON.stringify(result, null, 2));
1500
+ }
1501
+ };
1502
+ const normalize = async (options) => {
1503
+ noop(options);
1504
+ return {};
1505
+ };
1506
+ const legacy = async function() {
1507
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1508
+ args[_key] = arguments[_key];
1509
+ }
1510
+ const {
1511
+ options
1512
+ } = getCommandOptions(args, legacyCommandArguments);
1513
+ const normalizedOptions = await normalize(options);
1514
+ console.log("legacy", normalizedOptions);
1515
+ };
1516
+ const buildCommandArguments = [];
1517
+ const $build = new Command("build").description(i18n.t("desc.build")).option("-o, --output [file-path]", i18n.t("desc.build.output")).action(build);
1518
+ addCommandUsage($build);
1519
+ addCommandOutput($build);
1520
+ const devCommandArguments = [];
1521
+ const $dev = new Command("dev").description(i18n.t("desc.dev")).option("-i, --install [boolean]", i18n.t("desc.dev.install")).option("-c, --command [string]", i18n.t("desc.dev.command")).action(dev);
1522
+ addCommandUsage($dev);
1523
+ addCommandOutput($dev);
1524
+ const tunnelCommandArguments = ["port"];
1525
+ const $tunnel = new Command("tunnel").description(i18n.t("desc.tunnel")).argument("<port>", i18n.t("desc.tunnel.port")).action(tunnel);
1526
+ addCommandUsage($tunnel);
1527
+ addCommandOutput($tunnel);
1528
+ const loginCommandArguments = ["baseURL"];
1529
+ const $login = new Command("login").description(i18n.t("desc.login")).argument("<base-url>", i18n.t("desc.login.baseUrl")).action(login);
1530
+ addCommandUsage($login);
1531
+ addCommandOutput($login);
1532
+ const logoutCommandArguments = [];
1533
+ const $logout = new Command("logout").description(i18n.t("desc.logout")).action(logout);
1534
+ addCommandUsage($logout);
1535
+ addCommandOutput($logout);
1536
+ const whoamiCommandArguments = [];
1537
+ const $whoami = new Command("whoami").description(i18n.t("desc.whoami")).action(whoami);
1538
+ addCommandUsage($whoami);
1539
+ addCommandOutput($whoami);
1540
+ const installCommandArguments = [];
1541
+ const $install = new Command("install").description(i18n.t("desc.install")).action(install);
1542
+ addCommandUsage($install);
1543
+ addCommandOutput($install);
1544
+ const enableCommandArguments = [];
1545
+ const $enable = new Command("enable").description(i18n.t("desc.enable")).action(enable);
1546
+ addCommandUsage($enable);
1547
+ addCommandOutput($enable);
1548
+ const disableCommandArguments = [];
1549
+ const $disable = new Command("disable").description(i18n.t("desc.disable")).action(disable);
1550
+ addCommandUsage($disable);
1551
+ addCommandOutput($disable);
1552
+ const uninstallCommandArguments = [];
1553
+ const $uninstall = new Command("uninstall").description(i18n.t("desc.uninstall")).action(uninstall);
1554
+ addCommandUsage($uninstall);
1555
+ addCommandOutput($uninstall);
1556
+ const $app = new Command("app").description(i18n.t("desc.app"));
1557
+ $app.addCommand($install).addCommand($enable).addCommand($disable).addCommand($uninstall);
1558
+ addCommandUsage($app);
1559
+ addCommandOutput($app);
1560
+ const legacyCommandArguments = [];
1561
+ const $legacy = new Command("legacy").description(i18n.t("desc.legacy")).action(legacy);
1562
+ addCommandUsage($legacy);
1563
+ addCommandOutput($legacy);
1564
+ const ones = new Command("ones");
1565
+ const version = `${getPackageJSON().version}`;
1566
+ const env = `${version} Node/${process.version}`;
1567
+ ones.description(i18n.t("desc.ones", {
1568
+ env
1569
+ })).addCommand($create).addCommand($build).addCommand($dev).addCommand($tunnel).addCommand($app).addCommand($login).addCommand($logout).addCommand($whoami).addCommand($legacy).configureHelp({
1570
+ visibleCommands: (cmd) => {
1571
+ const blackList = ["legacy"];
1572
+ return cmd.commands.filter((command) => !_includesInstanceProperty(blackList).call(blackList, command.name()));
1573
+ },
1574
+ subcommandTerm: (subcommand) => {
1575
+ return `${subcommand.name()} ${subcommand.usage()}`.trim();
1576
+ }
1577
+ });
1578
+ addCommandOutput(ones);
1579
+ const runCommandONES = async () => {
1580
+ const command = ones;
1581
+ setContext("command", command);
1582
+ const version2 = `${getPackageJSON().version}`;
1583
+ command.version(version2, "-v, --version");
1584
+ await command.parse();
1585
+ };
1586
+ export {
1587
+ runCommandONES
1588
+ };