@seavideo/cli 0.0.0-stage → 0.3.1

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 (111) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +153 -2
  3. package/README.publish.md +154 -0
  4. package/dist/bin/seavideo.js +11 -0
  5. package/dist/src/atomic-write.js +14 -0
  6. package/dist/src/canvas/api.js +172 -0
  7. package/dist/src/canvas/browser.js +40 -0
  8. package/dist/src/canvas/chrome-binary.js +109 -0
  9. package/dist/src/canvas/daemon.js +264 -0
  10. package/dist/src/canvas/engine-install.js +46 -0
  11. package/dist/src/canvas/engine-log.js +9 -0
  12. package/dist/src/canvas/engine.js +99 -0
  13. package/dist/src/canvas/entry.js +16 -0
  14. package/dist/src/canvas/env-lock.js +164 -0
  15. package/dist/src/canvas/launch.js +97 -0
  16. package/dist/src/canvas/lifecycle.js +65 -0
  17. package/dist/src/canvas/names.js +61 -0
  18. package/dist/src/canvas/params.js +38 -0
  19. package/dist/src/canvas/puppeteer.js +153 -0
  20. package/dist/src/canvas/screenshot.js +23 -0
  21. package/dist/src/canvas/session-record.js +77 -0
  22. package/dist/src/canvas/team.js +97 -0
  23. package/dist/src/canvas/tool-args.js +47 -0
  24. package/dist/src/canvas/tool-session.js +165 -0
  25. package/dist/src/canvas/tool-specs.js +54 -0
  26. package/dist/src/canvas/url.js +38 -0
  27. package/dist/src/cli/args.js +16 -0
  28. package/dist/src/cli/commands/auth.js +51 -0
  29. package/dist/src/cli/commands/canvas/common.js +31 -0
  30. package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
  31. package/dist/src/cli/commands/canvas/index.js +5 -0
  32. package/dist/src/cli/commands/canvas/item.js +233 -0
  33. package/dist/src/cli/commands/canvas/list.js +168 -0
  34. package/dist/src/cli/commands/canvas/register.js +106 -0
  35. package/dist/src/cli/commands/canvas/render.js +229 -0
  36. package/dist/src/cli/commands/canvas/screenshot.js +52 -0
  37. package/dist/src/cli/commands/canvas/session.js +249 -0
  38. package/dist/src/cli/commands/canvas/teams.js +142 -0
  39. package/dist/src/cli/commands/config.js +74 -0
  40. package/dist/src/cli/commands/doctor.js +261 -0
  41. package/dist/src/cli/commands/engine.js +96 -0
  42. package/dist/src/cli/commands/env/create.js +160 -0
  43. package/dist/src/cli/commands/env/fields.js +26 -0
  44. package/dist/src/cli/commands/env/index.js +4 -0
  45. package/dist/src/cli/commands/env/list.js +44 -0
  46. package/dist/src/cli/commands/env/mutate.js +118 -0
  47. package/dist/src/cli/commands/login/flow-token.js +41 -0
  48. package/dist/src/cli/commands/login/index.js +12 -0
  49. package/dist/src/cli/commands/login/oauth.js +69 -0
  50. package/dist/src/cli/commands/login/save.js +26 -0
  51. package/dist/src/cli/commands/logout.js +92 -0
  52. package/dist/src/cli/commands/skill.js +185 -0
  53. package/dist/src/cli/commands/tool.js +279 -0
  54. package/dist/src/cli/commands/update.js +117 -0
  55. package/dist/src/cli/commands/wallet.js +69 -0
  56. package/dist/src/cli/commands/whoami.js +147 -0
  57. package/dist/src/cli/context.js +41 -0
  58. package/dist/src/cli/credential.js +93 -0
  59. package/dist/src/cli/elapsed.js +25 -0
  60. package/dist/src/cli/failure-screenshot.js +24 -0
  61. package/dist/src/cli/flags.js +1 -0
  62. package/dist/src/cli/hints.js +7 -0
  63. package/dist/src/cli/main.js +44 -0
  64. package/dist/src/cli/output-error.js +23 -0
  65. package/dist/src/cli/output.js +47 -0
  66. package/dist/src/cli/program.js +261 -0
  67. package/dist/src/cli/run.js +11 -0
  68. package/dist/src/cli/session.js +63 -0
  69. package/dist/src/config/base-url.js +26 -0
  70. package/dist/src/config/credential-vault.js +115 -0
  71. package/dist/src/config/dotenv.js +59 -0
  72. package/dist/src/config/envname.js +41 -0
  73. package/dist/src/config/paths.js +22 -0
  74. package/dist/src/config/preset-schema.js +67 -0
  75. package/dist/src/config/presets.js +132 -0
  76. package/dist/src/config/resolve.js +41 -0
  77. package/dist/src/config/secret-key.js +63 -0
  78. package/dist/src/config/store-schema.js +143 -0
  79. package/dist/src/config/store.js +273 -0
  80. package/dist/src/config/vault-crypto.js +44 -0
  81. package/dist/src/deps.js +191 -0
  82. package/dist/src/deps.types.js +1 -0
  83. package/dist/src/errors.js +24 -0
  84. package/dist/src/fs-retry.js +34 -0
  85. package/dist/src/i18n.js +1214 -0
  86. package/dist/src/loopback.js +134 -0
  87. package/dist/src/sdk/auth.js +20 -0
  88. package/dist/src/sdk/credential-expiry.js +67 -0
  89. package/dist/src/sdk/discovery.js +90 -0
  90. package/dist/src/sdk/http.js +98 -0
  91. package/dist/src/sdk/identity.js +17 -0
  92. package/dist/src/sdk/jwks.js +119 -0
  93. package/dist/src/sdk/oauth-protocol.js +226 -0
  94. package/dist/src/sdk/oauth.js +179 -0
  95. package/dist/src/sdk/provider/cn.js +34 -0
  96. package/dist/src/sdk/provider/index.js +16 -0
  97. package/dist/src/sdk/provider/oversea.js +41 -0
  98. package/dist/src/sdk/provider/types.js +1 -0
  99. package/dist/src/sdk/refresh.js +66 -0
  100. package/dist/src/semver.js +89 -0
  101. package/dist/src/skill/api.js +176 -0
  102. package/dist/src/text.js +3 -0
  103. package/dist/src/types.js +1 -0
  104. package/dist/src/update/check-cache.js +56 -0
  105. package/dist/src/update/install-layout.js +79 -0
  106. package/dist/src/update/notify.js +15 -0
  107. package/dist/src/update/npm-install.js +64 -0
  108. package/dist/src/update/passive.js +53 -0
  109. package/dist/src/update/registry.js +59 -0
  110. package/dist/src/wallet/api.js +107 -0
  111. package/package.json +59 -4
@@ -0,0 +1,279 @@
1
+ import { CliError, errorMessage } from "../../errors.js";
2
+ import { DEFAULT_TOOL_TIMEOUT_MS, createCanvasToolSession, } from "../../canvas/tool-session.js";
3
+ import { readToolSpecs, writeToolSpecs } from "../../canvas/tool-specs.js";
4
+ import { validateToolArgs } from "../../canvas/tool-args.js";
5
+ import { resolveEnvName } from "../../config/resolve.js";
6
+ import { displayWidth, renderTable, style } from "../output.js";
7
+ import { cmdPrefix } from "../hints.js";
8
+ import { withScreenshot } from "../failure-screenshot.js";
9
+ import { connectSession, touchSession } from "../session.js";
10
+ import { sanitizeText } from "../../text.js";
11
+ import { t } from "../../i18n.js";
12
+ const CALL_FAILURE_SCREENSHOT_REASON = 'call-failed';
13
+ function toolSession(deps, browser) {
14
+ return createCanvasToolSession({ stderr: deps.stderr, env: deps.env }, (expression) => browser.evaluate(expression));
15
+ }
16
+ async function toolsOf(ctx, opened, env) {
17
+ const dir = ctx.paths.toolSpecsDir(env);
18
+ const cached = await readToolSpecs(ctx.deps.fs, dir);
19
+ let result;
20
+ if (cached !== null) {
21
+ result = { tools: cached, fromCache: true, dir };
22
+ }
23
+ else {
24
+ const tools = await toolSession(ctx.deps, opened.browser).listTools();
25
+ await writeToolSpecs(ctx.deps, dir, tools).catch(() => undefined);
26
+ result = { tools, fromCache: false, dir };
27
+ }
28
+ return result;
29
+ }
30
+ function printSpecsHint(deps, json, table) {
31
+ const line = `${style.dim(` ${t(table.fromCache ? 'tool.specsFromCache' : 'tool.specsFetched', { dir: table.dir }, deps.env)}`)}\n`;
32
+ if (json) {
33
+ deps.stderr(line);
34
+ }
35
+ else {
36
+ deps.stdout(line);
37
+ }
38
+ }
39
+ export async function toolListCommand(ctx, options) {
40
+ const { deps } = ctx;
41
+ const env = await resolveEnvName(ctx.envFlag, deps, ctx.paths);
42
+ const opened = await connectSession(ctx);
43
+ try {
44
+ const table = await toolsOf(ctx, opened, env);
45
+ const { tools } = table;
46
+ await touchSession(ctx, opened);
47
+ if (options.json === true) {
48
+ deps.stdout(`${JSON.stringify({ id: opened.id, tools }, null, 2)}\n`);
49
+ }
50
+ else if (tools.length === 0) {
51
+ deps.stdout(`${style.dim(t('tool.none', {}, deps.env))}\n`);
52
+ }
53
+ else {
54
+ deps.stdout(`${renderTable([
55
+ [style.bold('NAME'), style.bold(t('tool.col.description', {}, deps.env))],
56
+ ...tools.map((tool) => [tool.name, summarize(tool.description)]),
57
+ ])}\n`);
58
+ deps.stdout(`${style.dim(` ${t('tool.count', { count: tools.length }, deps.env)}`)}\n`);
59
+ deps.stdout(`${style.dim(` ${t('tool.callHint', {}, deps.env)}: ${cmdPrefix(ctx)}tool call <name>`)}\n`);
60
+ }
61
+ printSpecsHint(deps, options.json === true, table);
62
+ }
63
+ finally {
64
+ await opened.browser.close();
65
+ }
66
+ return 0;
67
+ }
68
+ export async function toolSpecCommand(ctx, names, options) {
69
+ const { deps } = ctx;
70
+ const env = await resolveEnvName(ctx.envFlag, deps, ctx.paths);
71
+ const opened = await connectSession(ctx);
72
+ try {
73
+ const table = await toolsOf(ctx, opened, env);
74
+ const { tools } = table;
75
+ await touchSession(ctx, opened);
76
+ if (tools.length === 0) {
77
+ deps.stdout(`${style.dim(t('tool.none', {}, deps.env))}\n`);
78
+ }
79
+ else {
80
+ const missing = names.filter((name) => !tools.some((tool) => tool.name === name));
81
+ if (missing.length > 0) {
82
+ throw new CliError('usage', t('tool.specMissing', { names: missing.join(', ') }, deps.env), {
83
+ detail: t('tool.specMissingDetail', {}, deps.env),
84
+ });
85
+ }
86
+ const wanted = names.length === 0 ? tools : tools.filter((tool) => names.includes(tool.name));
87
+ if (options.json === true) {
88
+ const byName = {};
89
+ for (const tool of wanted)
90
+ byName[tool.name] = tool;
91
+ deps.stdout(`${JSON.stringify(byName, null, 2)}\n`);
92
+ }
93
+ else {
94
+ wanted.forEach((tool, index) => {
95
+ if (index > 0)
96
+ deps.stdout('\n');
97
+ else {
98
+ }
99
+ deps.stdout(`${style.bold(tool.name)}\n`);
100
+ if (tool.description !== '')
101
+ deps.stdout(`${tool.description}\n`);
102
+ else {
103
+ }
104
+ deps.stdout(`${JSON.stringify(tool.inputSchema, null, 2)}\n`);
105
+ });
106
+ }
107
+ }
108
+ printSpecsHint(deps, options.json === true, table);
109
+ }
110
+ finally {
111
+ await opened.browser.close();
112
+ }
113
+ return 0;
114
+ }
115
+ export async function toolCallCommand(ctx, name, options) {
116
+ const { deps } = ctx;
117
+ if (options.args !== undefined && options.argsFile !== undefined) {
118
+ throw new CliError('usage', t('tool.argsExclusive', {}, deps.env));
119
+ }
120
+ const timeoutMs = resolveTimeout(options.timeout, deps.env);
121
+ const args = await resolveToolArgs(ctx, options);
122
+ const env = await resolveEnvName(ctx.envFlag, deps, ctx.paths);
123
+ const opened = await connectSession(ctx);
124
+ try {
125
+ const tool = (await toolsOf(ctx, opened, env)).tools.find((item) => item.name === name) ?? null;
126
+ if (tool !== null)
127
+ validateToolArgs(tool, args, deps.env);
128
+ else {
129
+ }
130
+ return await runInSession(ctx, opened, env, name, args, timeoutMs, options.json === true);
131
+ }
132
+ finally {
133
+ await opened.browser.close();
134
+ }
135
+ }
136
+ async function runInSession(ctx, opened, env, name, args, timeoutMs, json) {
137
+ try {
138
+ const session = toolSession(ctx.deps, opened.browser);
139
+ await touchSession(ctx, opened);
140
+ const result = await session.callTool(name, args, timeoutMs);
141
+ await touchSession(ctx, opened);
142
+ renderResult(ctx, result, json);
143
+ if (json) {
144
+ }
145
+ else {
146
+ reportError(ctx, result, name, args);
147
+ }
148
+ return result.isError ? 1 : 0;
149
+ }
150
+ catch (err) {
151
+ throw await withScreenshot(ctx, { browser: opened.browser, env, canvasId: opened.id, reason: CALL_FAILURE_SCREENSHOT_REASON }, err);
152
+ }
153
+ }
154
+ async function resolveToolArgs(ctx, options) {
155
+ let result;
156
+ if (options.argsFile === undefined) {
157
+ result = await resolveArgs(ctx, options.args);
158
+ }
159
+ else if (options.argsFile === '-') {
160
+ result = await resolveArgs(ctx, '-');
161
+ }
162
+ else {
163
+ let text;
164
+ try {
165
+ text = await ctx.deps.fs.readFile(options.argsFile, 'utf8');
166
+ }
167
+ catch (err) {
168
+ throw new CliError('usage', t('tool.argsFileUnreadable', { path: options.argsFile }, ctx.deps.env), { detail: err.code ?? errorMessage(err) });
169
+ }
170
+ result = await resolveArgs(ctx, text);
171
+ }
172
+ return result;
173
+ }
174
+ function resolveTimeout(raw, envMap) {
175
+ let timeoutMs;
176
+ if (raw === undefined) {
177
+ timeoutMs = DEFAULT_TOOL_TIMEOUT_MS;
178
+ }
179
+ else if (!/^\d+$/.test(raw) || raw === '0') {
180
+ throw new CliError('usage', t('tool.badTimeout', { value: raw }, envMap));
181
+ }
182
+ else {
183
+ timeoutMs = Number(raw) * 1000;
184
+ }
185
+ return timeoutMs;
186
+ }
187
+ async function resolveArgs(ctx, raw) {
188
+ let parsed;
189
+ if (raw === undefined) {
190
+ parsed = {};
191
+ }
192
+ else {
193
+ const text = raw === '-' ? (await ctx.deps.readStdin()).trim() : raw;
194
+ if (text === '') {
195
+ parsed = {};
196
+ }
197
+ else {
198
+ try {
199
+ parsed = JSON.parse(text);
200
+ }
201
+ catch {
202
+ throw new CliError('usage', t('tool.badArgs', {}, ctx.deps.env));
203
+ }
204
+ }
205
+ }
206
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
207
+ throw new CliError('usage', t('tool.argsNotObject', {}, ctx.deps.env));
208
+ }
209
+ return parsed;
210
+ }
211
+ function renderResult(ctx, result, json) {
212
+ const { deps } = ctx;
213
+ if (json) {
214
+ deps.stdout(`${JSON.stringify({
215
+ content: result.content,
216
+ ...(result.structuredContent === undefined
217
+ ? {}
218
+ : { structuredContent: result.structuredContent }),
219
+ isError: result.isError,
220
+ ...(result.errorSource === undefined ? {} : { errorSource: result.errorSource }),
221
+ }, null, 2)}\n`);
222
+ }
223
+ else {
224
+ printTextBlocks(ctx, result);
225
+ }
226
+ }
227
+ function printTextBlocks(ctx, result) {
228
+ const { deps } = ctx;
229
+ const texts = result.content
230
+ .map((block) => block['text'])
231
+ .filter((text) => typeof text === 'string');
232
+ let printed = false;
233
+ for (const text of texts) {
234
+ deps.stdout(`${text}\n`);
235
+ printed = true;
236
+ }
237
+ if (!printed && result.structuredContent !== undefined) {
238
+ deps.stdout(`${JSON.stringify(result.structuredContent, null, 2)}\n`);
239
+ }
240
+ else {
241
+ }
242
+ }
243
+ function reportError(ctx, result, name, args) {
244
+ const { deps } = ctx;
245
+ if (!result.isError)
246
+ return;
247
+ deps.stderr(`${style.fail('✗')} ${t('tool.isError', {}, deps.env)}\n`);
248
+ deps.stderr(`${style.dim(` ${t('tool.isErrorDetail', {}, deps.env)}`)}\n`);
249
+ deps.stderr(`${style.dim(` ${t('tool.callArgs', { name, args: summarizeArgs(args) }, deps.env)}`)}\n`);
250
+ }
251
+ const ARGS_SUMMARY_WIDTH = 200;
252
+ function summarizeArgs(args) {
253
+ const oneLine = JSON.stringify(args);
254
+ return oneLine.length <= ARGS_SUMMARY_WIDTH
255
+ ? oneLine
256
+ : `${oneLine.slice(0, ARGS_SUMMARY_WIDTH)}…`;
257
+ }
258
+ const SUMMARY_WIDTH = 72;
259
+ const ELLIPSIS = '…';
260
+ function summarize(text) {
261
+ const flat = sanitizeText(text.replace(/\s+/g, ' ').trim());
262
+ let result;
263
+ if (displayWidth(flat) <= SUMMARY_WIDTH) {
264
+ result = flat;
265
+ }
266
+ else {
267
+ let out = '';
268
+ let width = 0;
269
+ for (const ch of flat) {
270
+ const w = displayWidth(ch);
271
+ if (width + w > SUMMARY_WIDTH - 1)
272
+ break;
273
+ out += ch;
274
+ width += w;
275
+ }
276
+ result = `${out.trimEnd()}${ELLIPSIS}`;
277
+ }
278
+ return result;
279
+ }
@@ -0,0 +1,117 @@
1
+ import { CliError, errorMessage } from "../../errors.js";
2
+ import { compareVersions } from "../../semver.js";
3
+ import { style } from "../output.js";
4
+ import { t } from "../../i18n.js";
5
+ import { VERSION } from "../program.js";
6
+ import { DEFAULT_CHANNEL, EXPLICIT_TIMEOUT_MS, PACKAGE_NAME, registryOf, fetchVersionInfo, } from "../../update/registry.js";
7
+ import { assertRegistryUrl } from "../../update/registry.js";
8
+ import { detectInstallLayout } from "../../update/install-layout.js";
9
+ export async function updateCommand(ctx, options) {
10
+ const { deps } = ctx;
11
+ assertRegistryUrl(options.registry ?? '', deps.env);
12
+ const registry = registryOf(deps.env, options.registry);
13
+ const channel = options.channel ?? DEFAULT_CHANNEL;
14
+ const target = options.to;
15
+ let info;
16
+ try {
17
+ info = await fetchVersionInfo({ fetch: deps.fetch, env: deps.env }, PACKAGE_NAME, VERSION, channel, EXPLICIT_TIMEOUT_MS, registry);
18
+ }
19
+ catch (err) {
20
+ const hint = options.registry === undefined ? t('update.registryHint', {}, deps.env) : '';
21
+ throw new CliError('network', t('update.checkFailed', {}, deps.env), {
22
+ detail: [errorMessage(err), hint].filter(Boolean).join(' · '),
23
+ });
24
+ }
25
+ let code;
26
+ if (options.json === true) {
27
+ deps.stdout(`${JSON.stringify(info, null, 2)}\n`);
28
+ code = 0;
29
+ }
30
+ else {
31
+ deps.stdout(`${renderVersion(ctx, info)}\n`);
32
+ code = await maybeUpgrade(ctx, info, channel, options.dryRun === true, target, registry);
33
+ }
34
+ return code;
35
+ }
36
+ async function maybeUpgrade(ctx, info, channel, dryRun, target, registry) {
37
+ const explicit = target !== undefined && target !== '';
38
+ const upgradable = info.updateAvailable && info.latest !== null;
39
+ let code;
40
+ if (explicit) {
41
+ code = await upgradeTo(ctx, target, channel, dryRun, registry);
42
+ }
43
+ else if (upgradable) {
44
+ code = await upgradeTo(ctx, info.latest, channel, dryRun, registry);
45
+ }
46
+ else {
47
+ code = 0;
48
+ }
49
+ return code;
50
+ }
51
+ async function upgradeTo(ctx, target, channel, dryRun, registry) {
52
+ const { deps } = ctx;
53
+ const layout = await detectInstallLayout(deps, deps.scriptPath());
54
+ let code;
55
+ if (layout.kind !== 'global') {
56
+ deps.stdout(`${style.warn(t(unsupportedKeyOf(layout.reason), {}, deps.env))}\n`);
57
+ deps.stdout(`${style.dim(` ${installHint(ctx, registry, target)}`)}\n`);
58
+ code = 0;
59
+ }
60
+ else {
61
+ const spec = `${PACKAGE_NAME}@${target}`;
62
+ if (dryRun) {
63
+ deps.stdout(`${style.dim(t('update.dryRun', { command: `npm install -g ${spec} --prefix ${layout.prefix} --registry ${registry}` }, deps.env))}\n`);
64
+ code = 0;
65
+ }
66
+ else {
67
+ code = await runInstall(ctx, spec, layout, registry);
68
+ }
69
+ }
70
+ return code;
71
+ }
72
+ async function runInstall(ctx, spec, layout, registry) {
73
+ const { deps } = ctx;
74
+ deps.stderr(`${style.dim(t('update.installing', { spec, prefix: layout.prefix }, deps.env))}\n`);
75
+ const result = await deps.runNpmInstall(spec, layout.prefix, registry);
76
+ let code;
77
+ if (result.code === 0) {
78
+ deps.stdout(`${style.ok(t('update.installed', { spec }, deps.env))}\n`);
79
+ code = 0;
80
+ }
81
+ else {
82
+ deps.stderr(`${style.fail(t('update.installFailed', { code: result.code }, deps.env))}\n` +
83
+ `${style.dim(result.output)}\n`);
84
+ code = 1;
85
+ }
86
+ return code;
87
+ }
88
+ function unsupportedKeyOf(reason) {
89
+ const keys = {
90
+ 'not-installed': 'update.notGlobalNotInstalled',
91
+ 'local-dependency': 'update.notGlobalLocalDependency',
92
+ 'no-global-shim': 'update.notGlobalNoShim',
93
+ 'unknown-layout': 'update.notGlobalUnknown',
94
+ };
95
+ return keys[reason];
96
+ }
97
+ function renderVersion(ctx, info) {
98
+ const { deps } = ctx;
99
+ const channelLine = style.dim(` ${t('update.channelLine', { channel: info.channel, registry: info.registry }, deps.env)}`);
100
+ let head;
101
+ if (info.latest === null) {
102
+ head = style.warn(t('update.noChannel', { channel: info.channel }, deps.env));
103
+ }
104
+ else if (info.updateAvailable) {
105
+ head = style.ok(t('update.available', { current: info.current, latest: info.latest }, deps.env));
106
+ }
107
+ else if (compareVersions(info.current, info.latest) === 1) {
108
+ head = style.dim(t('update.ahead', { current: info.current, latest: info.latest }, deps.env));
109
+ }
110
+ else {
111
+ head = style.ok(t('update.upToDate', { version: info.current }, deps.env));
112
+ }
113
+ return `${head}\n${channelLine}`;
114
+ }
115
+ function installHint(ctx, registry, target) {
116
+ return t('update.installHint', { command: `npm install -g ${PACKAGE_NAME}@${target}`, registry }, ctx.deps.env);
117
+ }
@@ -0,0 +1,69 @@
1
+ import { style } from "../output.js";
2
+ import { loadEnv } from "../context.js";
3
+ import { resolveFlowCredential } from "../credential.js";
4
+ import { t } from "../../i18n.js";
5
+ import { availableTotal, fetchWallet, frozenTotal } from "../../wallet/api.js";
6
+ export async function walletCommand(ctx, options) {
7
+ const { deps } = ctx;
8
+ const loaded = await loadEnv(ctx);
9
+ const { config, token } = await resolveFlowCredential(ctx, loaded);
10
+ const wallet = await fetchWallet(deps, config, token);
11
+ if (options.json === true) {
12
+ deps.stdout(`${JSON.stringify(serialize(wallet), null, 2)}\n`);
13
+ }
14
+ else {
15
+ deps.stdout(`${renderWallet(wallet, deps.env)}\n`);
16
+ }
17
+ return 0;
18
+ }
19
+ function serialize(wallet) {
20
+ return {
21
+ available: availableTotal(wallet),
22
+ frozen: frozenTotal(wallet),
23
+ availablePaid: wallet.availablePaid,
24
+ availableBonus: wallet.availableBonus,
25
+ frozenPaid: wallet.frozenPaid,
26
+ frozenBonus: wallet.frozenBonus,
27
+ totalConsumed: wallet.totalConsumed,
28
+ totalRecharged: wallet.totalRecharged,
29
+ totalRefunded: wallet.totalRefunded,
30
+ totalExpired: wallet.totalExpired,
31
+ productClassBalances: wallet.productClassBalances,
32
+ lots: wallet.lots,
33
+ };
34
+ }
35
+ function renderWallet(wallet, envMap) {
36
+ const label = (key) => t(key, {}, envMap);
37
+ const lines = [];
38
+ lines.push(`${style.ok('✓')} ${label('wallet.heading')} ${style.bold(availableTotal(wallet))}`);
39
+ lines.push(` ${label('wallet.available')} ${t('wallet.breakdown', { paid: wallet.availablePaid, bonus: wallet.availableBonus }, envMap)}`);
40
+ lines.push(` ${label('wallet.frozen')} ${frozenTotal(wallet)}`);
41
+ lines.push('');
42
+ lines.push(` ${label('wallet.consumed')} ${wallet.totalConsumed}`);
43
+ lines.push(` ${label('wallet.recharged')} ${wallet.totalRecharged}`);
44
+ lines.push(` ${label('wallet.expired')} ${wallet.totalExpired}`);
45
+ lines.push(` ${label('wallet.refunded')} ${wallet.totalRefunded}`);
46
+ const classes = Object.entries(wallet.productClassBalances);
47
+ if (classes.length > 0) {
48
+ lines.push('');
49
+ lines.push(` ${label('wallet.byClass')}`);
50
+ for (const [key, value] of classes) {
51
+ lines.push(` ${key} ${value}`);
52
+ }
53
+ }
54
+ else {
55
+ }
56
+ if (wallet.lots.length > 0) {
57
+ lines.push('');
58
+ lines.push(` ${label('wallet.lots')}`);
59
+ for (const lot of wallet.lots) {
60
+ const expiry = lot.expireAt === ''
61
+ ? label('wallet.noExpiry')
62
+ : t('wallet.expiresAt', { at: lot.expireAt }, envMap);
63
+ lines.push(` ${lot.category || lot.productClass} ${lot.availableAmount} ${style.dim(expiry)}`);
64
+ }
65
+ }
66
+ else {
67
+ }
68
+ return lines.join('\n');
69
+ }
@@ -0,0 +1,147 @@
1
+ import { fetchProfile } from "../../sdk/auth.js";
2
+ import { fetchIdentity } from "../../sdk/identity.js";
3
+ import { getProvider } from "../../sdk/provider/index.js";
4
+ import { CliError } from "../../errors.js";
5
+ import { sanitizeText } from "../../text.js";
6
+ import { renderTable, style } from "../output.js";
7
+ import { loadEnv } from "../context.js";
8
+ import { REASON_CODE, t } from "../../i18n.js";
9
+ function showOrMask(value) {
10
+ let result;
11
+ if (value === null || value === '') {
12
+ result = '***';
13
+ }
14
+ else {
15
+ result = sanitizeText(value);
16
+ }
17
+ return result;
18
+ }
19
+ export function reasonCodeOf(err) {
20
+ let result;
21
+ if (!(err instanceof CliError)) {
22
+ result = REASON_CODE.unknown;
23
+ }
24
+ else {
25
+ switch (err.kind) {
26
+ case 'auth':
27
+ result = REASON_CODE.authFailed;
28
+ break;
29
+ case 'network':
30
+ result = REASON_CODE.networkError;
31
+ break;
32
+ case 'timeout':
33
+ result = REASON_CODE.timeout;
34
+ break;
35
+ case 'server':
36
+ result = REASON_CODE.serverError;
37
+ break;
38
+ case 'config':
39
+ case 'usage':
40
+ case 'unsupported':
41
+ result = REASON_CODE.invalidResponse;
42
+ break;
43
+ }
44
+ }
45
+ return result;
46
+ }
47
+ export async function whoamiCommand(ctx, options) {
48
+ const { deps } = ctx;
49
+ const config = await loadEnv(ctx);
50
+ const flowCredential = config.flowCredential;
51
+ const viaFlow = flowCredential !== null;
52
+ const credentialSource = viaFlow ? flowCredential.source : (config.credential?.source ?? '-');
53
+ let identity = null;
54
+ try {
55
+ identity = viaFlow
56
+ ? await identityViaFlowApi(ctx, config, flowCredential)
57
+ : await identityViaAccount(ctx, config);
58
+ if (identity === null) {
59
+ if (options.json === true) {
60
+ deps.stdout(`${JSON.stringify({ status: 'offline', reason: REASON_CODE.noCredential }, null, 2)}\n`);
61
+ }
62
+ else {
63
+ deps.stdout(`${style.fail('✗')} ${t('whoami.offline', {}, deps.env)}\n`);
64
+ deps.stderr(`${style.dim(` ${t('whoami.notLoggedIn', { env: config.env }, deps.env)}`)}\n`);
65
+ }
66
+ }
67
+ else {
68
+ }
69
+ }
70
+ catch (err) {
71
+ const reason = reasonCodeOf(err);
72
+ if (options.json === true) {
73
+ deps.stdout(`${JSON.stringify({ status: 'offline', reason }, null, 2)}\n`);
74
+ }
75
+ else {
76
+ const detail = err instanceof CliError ? err.message : String(err);
77
+ deps.stdout(`${style.fail('✗')} ${t('whoami.offline', {}, deps.env)}\n`);
78
+ deps.stderr(`${style.dim(` ${t('whoami.reason', { reason: detail }, deps.env)}`)}\n`);
79
+ }
80
+ }
81
+ let result;
82
+ if (identity === null) {
83
+ result = 1;
84
+ }
85
+ else {
86
+ try {
87
+ await ctx.store.writeUser(config.env, identity);
88
+ }
89
+ catch (err) {
90
+ deps.stderr(`${style.warn('!')} ${t('whoami.cacheWriteFailed', {}, deps.env)}\n` +
91
+ `${style.dim(` ${err.message}`)}\n`);
92
+ }
93
+ const server = config.flowCredential !== null ? config.flowApiBaseUrl : config.seavideoBaseUrl;
94
+ if (options.json === true) {
95
+ deps.stdout(`${JSON.stringify({ status: 'online', env: config.env, ...identity }, null, 2)}\n`);
96
+ }
97
+ else {
98
+ deps.stdout(`${style.ok('✓')} ${t('whoami.online', {}, deps.env)}\n`);
99
+ deps.stdout(`${renderTable([
100
+ [t('whoami.label.env', {}, deps.env), config.env],
101
+ [t('whoami.label.platform', {}, deps.env), config.platform],
102
+ [t('whoami.label.account', {}, deps.env), showOrMask(identity.id)],
103
+ [t('whoami.label.displayName', {}, deps.env), showOrMask(identity.displayName)],
104
+ [t('whoami.label.username', {}, deps.env), showOrMask(identity.username)],
105
+ [t('whoami.label.source', {}, deps.env), credentialSource],
106
+ [t('whoami.label.server', {}, deps.env), server],
107
+ ])}\n`);
108
+ }
109
+ result = 0;
110
+ }
111
+ return result;
112
+ }
113
+ async function identityViaFlowApi(ctx, config, credential) {
114
+ const { deps } = ctx;
115
+ const identity = await fetchIdentity({ fetch: deps.fetch, env: deps.env, baseUrl: config.flowApiBaseUrl }, credential.value);
116
+ return {
117
+ id: identity.userId,
118
+ displayName: identity.displayName,
119
+ username: null,
120
+ name: null,
121
+ raw: identity.raw,
122
+ };
123
+ }
124
+ async function identityViaAccount(ctx, config) {
125
+ const { deps } = ctx;
126
+ const credential = config.credential;
127
+ let result;
128
+ if (credential === null) {
129
+ result = null;
130
+ }
131
+ else {
132
+ const provider = getProvider(config.platform);
133
+ const profile = await fetchProfile(provider, credential, {
134
+ fetch: deps.fetch,
135
+ env: deps.env,
136
+ baseUrl: config.seavideoBaseUrl,
137
+ });
138
+ result = {
139
+ id: profile.id,
140
+ displayName: profile.displayName,
141
+ username: profile.username,
142
+ name: profile.name,
143
+ raw: profile.raw,
144
+ };
145
+ }
146
+ return result;
147
+ }
@@ -0,0 +1,41 @@
1
+ import { CliError } from "../errors.js";
2
+ import { resolveEnvName } from "../config/resolve.js";
3
+ import { t } from "../i18n.js";
4
+ import { writeFileAtomic } from "../atomic-write.js";
5
+ export async function loadEnv(ctx) {
6
+ const env = await resolveEnvName(ctx.envFlag, ctx.deps, ctx.paths);
7
+ const config = await ctx.store.read(env);
8
+ return config;
9
+ }
10
+ export async function hasNoCurrentEnv(ctx) {
11
+ let result;
12
+ if (ctx.envFlag !== undefined && ctx.envFlag !== '') {
13
+ result = false;
14
+ }
15
+ else {
16
+ try {
17
+ await ctx.deps.fs.stat(ctx.paths.currentFile);
18
+ result = false;
19
+ }
20
+ catch {
21
+ result = true;
22
+ }
23
+ }
24
+ return result;
25
+ }
26
+ export async function setCurrentEnv(ctx, env) {
27
+ try {
28
+ await ctx.deps.fs.mkdir(ctx.paths.root, { recursive: true, mode: 0o700 });
29
+ await writeFileAtomic(ctx.deps, ctx.paths.currentFile, `${JSON.stringify({ env }, null, 2)}\n`, 0o600);
30
+ }
31
+ catch (err) {
32
+ throw new CliError('config', t('store.setCurrentFailed', { env }, ctx.deps.env), {
33
+ detail: err.code ?? String(err),
34
+ });
35
+ }
36
+ }
37
+ export function parsePlatform(value, envMap = process.env) {
38
+ if (value === 'oversea' || value === 'cn')
39
+ return value;
40
+ throw new CliError('usage', t('error.platformInvalid', { value }, envMap));
41
+ }