@rainyun/cli 0.0.0-stage → 1.0.0

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 (68) hide show
  1. package/README.md +132 -2
  2. package/bin/postinstall.mjs +13 -0
  3. package/bin/rainyun-cli.mjs +13 -0
  4. package/catalog/human-names.json +340 -0
  5. package/catalog/list.openapi.json +354 -0
  6. package/catalog/openapi.json +34531 -0
  7. package/catalog/product-commands.json +332 -0
  8. package/catalog/public.openapi.json +1895 -0
  9. package/docs/AGENT_GUIDE.md +64 -0
  10. package/docs/install.md +44 -0
  11. package/docs/product-lists.md +48 -0
  12. package/docs/rgp.md +77 -0
  13. package/docs/terminal-exec.md +111 -0
  14. package/examples/public-panel.json +1 -0
  15. package/examples/public-rcs-price.json +1 -0
  16. package/examples/rca-terminal-input.json +1 -0
  17. package/examples/rcs-get.json +1 -0
  18. package/examples/rcs-list.json +1 -0
  19. package/examples/rcs-reboot.json +1 -0
  20. package/examples/terminal-controls.ndjson +3 -0
  21. package/examples/terminal-input.json +1 -0
  22. package/node_modules/ws/LICENSE +20 -0
  23. package/node_modules/ws/README.md +539 -0
  24. package/node_modules/ws/browser.js +8 -0
  25. package/node_modules/ws/index.js +22 -0
  26. package/node_modules/ws/lib/buffer-util.js +142 -0
  27. package/node_modules/ws/lib/constants.js +19 -0
  28. package/node_modules/ws/lib/event-target.js +292 -0
  29. package/node_modules/ws/lib/extension.js +203 -0
  30. package/node_modules/ws/lib/limiter.js +55 -0
  31. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  32. package/node_modules/ws/lib/receiver.js +751 -0
  33. package/node_modules/ws/lib/sender.js +610 -0
  34. package/node_modules/ws/lib/stream.js +161 -0
  35. package/node_modules/ws/lib/subprotocol.js +62 -0
  36. package/node_modules/ws/lib/validation.js +152 -0
  37. package/node_modules/ws/lib/websocket-server.js +565 -0
  38. package/node_modules/ws/lib/websocket.js +1471 -0
  39. package/node_modules/ws/package.json +74 -0
  40. package/node_modules/ws/wrapper.mjs +21 -0
  41. package/package.json +29 -4
  42. package/skills/rainyun-cli/SKILL.md +46 -0
  43. package/src/api/catalog.mjs +230 -0
  44. package/src/api/http.mjs +222 -0
  45. package/src/api/request.mjs +178 -0
  46. package/src/api/titles.mjs +9 -0
  47. package/src/auth/commands.mjs +192 -0
  48. package/src/auth/store.mjs +162 -0
  49. package/src/cli.mjs +154 -0
  50. package/src/commands/dispatch.mjs +128 -0
  51. package/src/commands/fields.mjs +77 -0
  52. package/src/commands/products.mjs +209 -0
  53. package/src/commands/rgs.mjs +44 -0
  54. package/src/json.mjs +81 -0
  55. package/src/output/business.mjs +188 -0
  56. package/src/output/discovery.mjs +197 -0
  57. package/src/output/examples.mjs +71 -0
  58. package/src/output/format.mjs +164 -0
  59. package/src/output/help.json +181 -0
  60. package/src/output/help.mjs +334 -0
  61. package/src/rgp/commands.mjs +251 -0
  62. package/src/rgp/input.mjs +144 -0
  63. package/src/rgp/operations.json +625 -0
  64. package/src/rgp/result.mjs +103 -0
  65. package/src/rgp/transfer.mjs +213 -0
  66. package/src/terminal/commands.mjs +155 -0
  67. package/src/terminal/session.mjs +233 -0
  68. package/src/terminal/target.mjs +155 -0
package/src/cli.mjs ADDED
@@ -0,0 +1,154 @@
1
+ import packageInfo from '../package.json' with { type: 'json' };
2
+ import { showHelp } from './output/help.mjs';
3
+ import { humanResult, humanError, safeDisplay } from './output/format.mjs';
4
+ import { auth, getKey } from './auth/commands.mjs';
5
+ import { createStore } from './auth/store.mjs';
6
+ import { core, getRGS } from './commands/dispatch.mjs';
7
+ import { jsonParse, jsonStringify } from './json.mjs';
8
+ import { terminal } from './terminal/commands.mjs';
9
+ import { rgp } from './rgp/commands.mjs';
10
+ import { rgsInstanceCommands } from './commands/rgs.mjs';
11
+ import { isProductOption, productNode } from './commands/products.mjs';
12
+
13
+ const booleanFlags = new Set(
14
+ 'help human json version responses yes dry-run stdin public authenticated stream logs'.split(' ')
15
+ );
16
+ const valuedFlags = new Set(
17
+ 'query scope limit offset input path body file base-url timeout max-response-bytes page per-page mode duration max-output-bytes cols rows tail-lines since-seconds source output max-file-bytes wait-timeout poll-interval project-id'.split(
18
+ ' '
19
+ )
20
+ );
21
+ for (const spec of rgsInstanceCommands.values()) {
22
+ for (const option of Object.keys(spec.options)) valuedFlags.add(option);
23
+ }
24
+ const exitCodes = { usage: 2, auth: 3, api: 4, network: 5, protocol: 6 };
25
+ const usage = (message) => Object.assign(new Error(message), { kind: 'usage' });
26
+
27
+ function parseArgs(argv) {
28
+ const flags = Object.create(null);
29
+ const args = [];
30
+ let literal = false;
31
+ for (let i = 0; i < argv.length; i++) {
32
+ let arg = argv[i];
33
+ if (literal || !arg.startsWith('-') || arg === '-') {
34
+ args.push(arg);
35
+ continue;
36
+ }
37
+ if (arg === '--') {
38
+ literal = true;
39
+ continue;
40
+ }
41
+ if (arg === '-h') arg = '--help';
42
+ const [head] = arg.split('=', 1);
43
+ const name = head.slice(2);
44
+ if (
45
+ !head.startsWith('--') ||
46
+ (!booleanFlags.has(name) && !valuedFlags.has(name) && !isProductOption(name))
47
+ )
48
+ throw usage('Unknown flag. Use --help.');
49
+ if (Object.hasOwn(flags, name) && name !== 'file') throw usage('Duplicate flag --' + name);
50
+ if (booleanFlags.has(name)) {
51
+ if (head !== arg) throw usage('--' + name + ' is a switch');
52
+ flags[name] = true;
53
+ continue;
54
+ }
55
+ let value;
56
+ if (head !== arg) value = arg.slice(head.length + 1);
57
+ else {
58
+ if (i + 1 === argv.length || argv[i + 1].startsWith('--'))
59
+ throw usage('--' + name + ' requires a value');
60
+ value = argv[++i];
61
+ }
62
+ if (name === 'file') (flags.file ??= []).push(value);
63
+ else flags[name] = value;
64
+ }
65
+ return { flags, args };
66
+ }
67
+
68
+ export async function run(argv, overrides = {}) {
69
+ const ctx = {
70
+ stdin: process.stdin,
71
+ stdout: process.stdout,
72
+ stderr: process.stderr,
73
+ env: process.env,
74
+ jsonParse,
75
+ jsonStringify,
76
+ redactionSecrets: [],
77
+ ...overrides,
78
+ };
79
+ ctx.store ??= createStore({ env: ctx.env });
80
+ ctx.getKey ??= (base) => getKey(base, ctx);
81
+ ctx.getRGS ??= (id, flags) => getRGS(id, flags, ctx);
82
+ const end = argv.indexOf('--');
83
+ const options = end === -1 ? argv : argv.slice(0, end);
84
+ const requested = options.includes('--json')
85
+ ? 'json'
86
+ : options.includes('--human')
87
+ ? 'human'
88
+ : ctx.env.RAIN_CLI_OUTPUT || 'auto';
89
+ const interactive = Boolean(ctx.stdin.isTTY && ctx.stdout.isTTY);
90
+ const human = requested === 'human' || (requested === 'auto' && interactive);
91
+ let humanFailure = human && (requested === 'human' || ctx.stderr.isTTY);
92
+ if (options.includes('--stream')) humanFailure = false;
93
+ try {
94
+ const { args, flags } = parseArgs(argv);
95
+ const [command, ...rest] = args;
96
+ if (flags.json && flags.human) throw usage('--json 和 --human 只能选择一个。');
97
+ if (!['auto', 'human', 'json'].includes(requested))
98
+ throw usage('RAIN_CLI_OUTPUT 可设为 auto、json 或 human。');
99
+ delete flags.json;
100
+ delete flags.human;
101
+ const streaming = command === 'terminal' && flags.stream && !flags['dry-run'];
102
+ if (!streaming) humanFailure = human && (requested === 'human' || ctx.stderr.isTTY);
103
+ let result;
104
+ const groupHelp =
105
+ human &&
106
+ !Object.keys(flags).length &&
107
+ ((args.length === 1 &&
108
+ ['auth', 'terminal', 'rgp', 'rcs', 'rgs', 'rbm', 'ros', 'rca'].includes(command)) ||
109
+ Boolean(productNode(args)?.children.size));
110
+ if ((!command && !Object.keys(flags).length) || flags.help || command === 'help' || groupHelp) {
111
+ await showHelp(command === 'help' ? rest : args, requested === 'json', ctx);
112
+ return 0;
113
+ }
114
+ if (streaming && options.includes('--human')) throw usage('持续终端使用逐行 JSON,请移除 --human。');
115
+ if (flags.version) {
116
+ if (args.length || Object.keys(flags).length !== 1) throw usage('Use --version alone');
117
+ result = { ok: true, data: { name: 'rainyun-cli', version: packageInfo.version } };
118
+ } else if (command === 'auth') result = await auth(rest, flags, ctx);
119
+ else if (command === 'terminal') result = await terminal(rest, flags, ctx);
120
+ else if (command === 'rgp') result = await rgp(rest, flags, ctx);
121
+ else result = await core(command, rest, flags, ctx);
122
+ if (result !== undefined) {
123
+ let output;
124
+ if (human && !streaming) {
125
+ // A completed write stays successful even if its response has an unfamiliar shape.
126
+ try {
127
+ output = humanResult(args, result, flags, ctx);
128
+ } catch {
129
+ output = safeDisplay(jsonStringify(result, 2)) + '\n';
130
+ }
131
+ } else output = jsonStringify(result) + '\n';
132
+ ctx.stdout.write(output);
133
+ }
134
+ return 0;
135
+ } catch (err) {
136
+ const known = Object.hasOwn(exitCodes, err?.kind);
137
+ const kind = known ? err.kind : 'protocol';
138
+ const error = { kind, message: known ? err.message : 'Unexpected CLI error.' };
139
+ if (known)
140
+ for (const field of [
141
+ 'operation',
142
+ 'http_status',
143
+ 'business_code',
144
+ 'outcome',
145
+ 'response',
146
+ 'response_text',
147
+ 'details',
148
+ ]) {
149
+ if (err[field] !== undefined) error[field] = err[field];
150
+ }
151
+ ctx.stderr.write(humanFailure ? humanError(error, ctx) : jsonStringify({ ok: false, error }) + '\n');
152
+ return exitCodes[kind];
153
+ }
154
+ }
@@ -0,0 +1,128 @@
1
+ import { allow, check, commands, describe, integer, lookup } from '../api/catalog.mjs';
2
+ import { titleOf } from '../api/titles.mjs';
3
+ import { callFlags, executionFlags as execution, readInput } from '../api/request.mjs';
4
+ import { execute } from '../api/http.mjs';
5
+ import { rgsInstanceCommands } from './rgs.mjs';
6
+ import { productNode, productOperation } from './products.mjs';
7
+ import { assignFields } from './fields.mjs';
8
+
9
+ const lists = [
10
+ 'rcs.list',
11
+ 'rgs.list',
12
+ 'rbm.list',
13
+ 'ros.list',
14
+ 'ros.bucket.list',
15
+ 'rca.app.list',
16
+ 'rca.project.list',
17
+ ];
18
+ function positiveID(raw, name) {
19
+ check(/^[1-9]\d*$/.test(raw), 'expected a positive integer for ' + name);
20
+ const n = BigInt(raw);
21
+ return n <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(n) : n;
22
+ }
23
+ async function run(op, input, flags, ctx) {
24
+ try {
25
+ return await execute(op, input, flags, ctx);
26
+ } catch (e) {
27
+ if (e.kind) e.operation = op.operation_id;
28
+ throw e;
29
+ }
30
+ }
31
+ async function runProduct(node, flags, ctx) {
32
+ const { op, fields, paged } = node;
33
+ allow(flags, [...callFlags, ...fields.keys(), ...(paged ? ['page', 'per-page'] : [])]);
34
+ const provided = [];
35
+ for (const [flag, field] of fields) {
36
+ if (Object.hasOwn(flags, flag)) provided.push(field.field + '=' + flags[flag]);
37
+ }
38
+ if (op.aliases?.includes('rca.app.list') && Object.hasOwn(flags, 'project-id')) {
39
+ positiveID(flags['project-id'], '--project-id');
40
+ }
41
+ const input = { ...(await readInput(flags, ctx)), ...assignFields(op, provided, flags, ctx) };
42
+ if (paged) {
43
+ if (Object.hasOwn(input.query ?? {}, 'options')) {
44
+ check(
45
+ !Object.hasOwn(flags, 'page') && !Object.hasOwn(flags, 'per-page'),
46
+ '--page and --per-page conflict with explicit options'
47
+ );
48
+ } else {
49
+ input.query = { ...input.query, ...pagination(flags) };
50
+ }
51
+ }
52
+ return run(op, input, flags, ctx);
53
+ }
54
+ function pagination(flags) {
55
+ const page = integer(flags.page, 1, 1, Number.MAX_SAFE_INTEGER, 'page');
56
+ const perPage = integer(flags['per-page'], 20, 1, 100, 'per-page');
57
+ return { options: { page, perPage } };
58
+ }
59
+
60
+ function runRGSInstance(positionals, flags, ctx) {
61
+ const [, action] = positionals;
62
+ const spec = rgsInstanceCommands.get(action);
63
+ check(
64
+ positionals.length === 2 && spec,
65
+ 'usage: rainyun-cli rgs instance <list|get|start|reboot|monitor> --help'
66
+ );
67
+ allow(flags, [...execution, ...Object.keys(spec.options)]);
68
+
69
+ if (action === 'list') return run(lookup(spec.operation), { query: pagination(flags) }, flags, ctx);
70
+ const input = { path: { id: positiveID(flags.id, '--id') } };
71
+ if (action === 'monitor') {
72
+ check(
73
+ flags['start-date'] !== undefined && flags['end-date'] !== undefined,
74
+ 'monitor requires --start-date and --end-date in Unix seconds'
75
+ );
76
+ const start = integer(flags['start-date'], undefined, 0, Number.MAX_SAFE_INTEGER, 'start-date');
77
+ const end = integer(flags['end-date'], undefined, start, Number.MAX_SAFE_INTEGER, 'end-date');
78
+ input.query = { start_date: start, end_date: end };
79
+ }
80
+ return run(lookup(spec.operation), input, flags, ctx);
81
+ }
82
+
83
+ export async function getRGS(id, flags, ctx) {
84
+ const readFlags = Object.fromEntries(
85
+ ['base-url', 'timeout', 'max-response-bytes']
86
+ .filter((k) => Object.hasOwn(flags, k))
87
+ .map((k) => [k, flags[k]])
88
+ );
89
+ return (await run(lookup('rgs.get'), { path: { id: positiveID(id, 'id') } }, readFlags, ctx)).response;
90
+ }
91
+ export async function core(command, positionals, flags, ctx) {
92
+ if (command === 'commands') {
93
+ check(!positionals.length, 'commands does not accept positional arguments');
94
+ return commands(flags, titleOf);
95
+ }
96
+ if (command === 'schema') {
97
+ allow(flags, ['responses']);
98
+ check(positionals.length === 1, 'usage: rainyun-cli schema OPERATION [--responses]');
99
+ const [name] = positionals;
100
+ return describe(productOperation(name) ?? name, flags.responses);
101
+ }
102
+ if (command === 'call') {
103
+ allow(flags, callFlags);
104
+ const [name, ...fields] = positionals;
105
+ check(name, 'usage: rainyun-cli call OPERATION [field=value ...] [--input FILE|-]');
106
+ const op = lookup(productOperation(name) ?? name);
107
+ const groups = assignFields(op, fields, flags, ctx);
108
+ return run(op, { ...(await readInput(flags, ctx)), ...groups }, flags, ctx);
109
+ }
110
+ if (command === 'rcs' && ['get', 'reboot'].includes(positionals[0])) {
111
+ allow(flags, execution);
112
+ check(positionals.length === 2, 'expected a positive instance ID');
113
+ return run(lookup('rcs.' + positionals[0]), { path: { id: positiveID(positionals[1], 'id') } }, flags, ctx);
114
+ }
115
+ const node = productNode([command, ...positionals]);
116
+ if (node?.pilot) return runRGSInstance(positionals, flags, ctx);
117
+ if (node?.op) return runProduct(node, flags, ctx);
118
+ const name = [command, ...positionals].join('.');
119
+ check(
120
+ lists.includes(name) && [command, ...positionals].every((s) => s && !s.includes('.')),
121
+ 'unknown command; use --help'
122
+ );
123
+ const projectRequired = name === 'rca.app.list';
124
+ allow(flags, [...execution, 'page', 'per-page', ...(projectRequired ? ['project-id'] : [])]);
125
+ const query = pagination(flags);
126
+ if (projectRequired) query.project_id = positiveID(flags['project-id'], '--project-id');
127
+ return run(lookup(name), { query }, flags, ctx);
128
+ }
@@ -0,0 +1,77 @@
1
+ import { check, fail, isObject, resolve } from '../api/catalog.mjs';
2
+
3
+ function fieldDefinitions(op) {
4
+ const fields = (op.parameters ?? []).map((p) => ({
5
+ group: p.in === 'header' ? 'headers' : p.in,
6
+ name: p.name,
7
+ schema: resolve(p.schema) ?? {},
8
+ }));
9
+ const body = resolve(op.request_body);
10
+ const shape = resolve(body?.content?.['application/json']?.schema);
11
+ for (const [name, schema] of Object.entries(shape?.properties ?? {})) {
12
+ fields.push({ group: 'body', name, schema: resolve(schema) ?? {} });
13
+ }
14
+ return fields;
15
+ }
16
+
17
+ function fieldValue({ schema, group, name }, raw, ctx) {
18
+ // String parameters stay literal (including "true", leading zeros and '=').
19
+ if (schema.type === 'string') return raw;
20
+ const label = group + '.' + name;
21
+ let value;
22
+ try {
23
+ value = ctx.jsonParse(raw);
24
+ } catch {
25
+ fail('usage', label + ' 需要有效的 JSON 值。');
26
+ }
27
+ if (value === null && schema.nullable) return value;
28
+ switch (schema.type) {
29
+ case 'integer':
30
+ check(/^-?(?:0|[1-9]\d*)$/.test(ctx.jsonStringify(value)), label + ' 需要整数。');
31
+ break;
32
+ case 'number':
33
+ check(
34
+ typeof value === 'number' || typeof value === 'bigint' || JSON.isRawJSON(value),
35
+ label + ' 需要数值。'
36
+ );
37
+ break;
38
+ case 'boolean':
39
+ check(typeof value === 'boolean', label + ' 需要 true 或 false。');
40
+ break;
41
+ case 'array':
42
+ check(Array.isArray(value), label + ' 需要 JSON 数组。');
43
+ break;
44
+ case 'object':
45
+ check(isObject(value), label + ' 需要 JSON 对象。');
46
+ break;
47
+ }
48
+ return value;
49
+ }
50
+
51
+ export function assignFields(op, tokens, flags, ctx) {
52
+ const groups = Object.create(null);
53
+ if (!tokens.length) return groups;
54
+ check(!Object.hasOwn(flags, 'input'), '--input 与 字段=值 不能同时使用。');
55
+ check(tokens.reduce((n, t) => n + Buffer.byteLength(t), 0) <= 8 * 1024 * 1024, '字段输入超过 8 MiB。');
56
+ const fields = fieldDefinitions(op);
57
+ for (const token of tokens) {
58
+ const equals = token.indexOf('=');
59
+ check(equals > 0, '请用 字段=值 传入参数。');
60
+ const key = token.slice(0, equals);
61
+ const matches = fields.filter((f) => key === f.name || key === f.group + '.' + f.name);
62
+ check(matches.length > 0, '此操作没有指定的字段;请查看参数说明。');
63
+ check(
64
+ matches.length === 1,
65
+ '同名字段需要指定位置:' + matches.map((f) => f.group + '.' + f.name).join('、')
66
+ );
67
+ const field = matches[0];
68
+ check(
69
+ !Object.hasOwn(flags, field.group),
70
+ '同一组字段不能重复通过 --' + field.group + ' 和 字段=值 提供。'
71
+ );
72
+ const group = (groups[field.group] ??= Object.create(null));
73
+ check(!Object.hasOwn(group, field.name), '重复字段 ' + field.group + '.' + field.name);
74
+ group[field.name] = fieldValue(field, token.slice(equals + 1), ctx);
75
+ }
76
+ return groups;
77
+ }
@@ -0,0 +1,209 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { check, isWrite, lookup, resolve } from '../api/catalog.mjs';
3
+ import { rgsInstanceCommands } from './rgs.mjs';
4
+
5
+ const catalog = JSON.parse(
6
+ readFileSync(new URL('../../catalog/product-commands.json', import.meta.url), 'utf8')
7
+ );
8
+ const reserved = new Set([
9
+ 'help',
10
+ 'human',
11
+ 'json',
12
+ 'version',
13
+ 'responses',
14
+ 'yes',
15
+ 'dry-run',
16
+ 'stdin',
17
+ 'public',
18
+ 'authenticated',
19
+ 'stream',
20
+ 'logs',
21
+ 'input',
22
+ 'path',
23
+ 'query',
24
+ 'body',
25
+ 'file',
26
+ 'base-url',
27
+ 'timeout',
28
+ 'max-response-bytes',
29
+ ]);
30
+ const pagedAliases = new Set([
31
+ 'rcs.list',
32
+ 'rgs.list',
33
+ 'rbm.list',
34
+ 'ros.list',
35
+ 'ros.bucket.list',
36
+ 'rca.project.list',
37
+ 'rca.app.list',
38
+ ]);
39
+ let registry;
40
+
41
+ function kebab(name) {
42
+ return name
43
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
44
+ .replaceAll('_', '-')
45
+ .toLowerCase();
46
+ }
47
+
48
+ function inputFlags(op) {
49
+ const fields = (op.parameters ?? []).map((parameter) => ({
50
+ parameter,
51
+ group: parameter.in === 'header' ? 'headers' : parameter.in,
52
+ name: kebab(parameter.name),
53
+ }));
54
+ return new Map(
55
+ fields.map(({ parameter, group, name }) => {
56
+ const ambiguous = fields.filter((other) => other.name === name).length > 1;
57
+ const flag = reserved.has(name) || ambiguous ? group + '-' + name : name;
58
+ return [
59
+ flag,
60
+ {
61
+ field: group + '.' + parameter.name,
62
+ type: resolve(parameter.schema)?.type ?? 'value',
63
+ required: parameter.required || group === 'path',
64
+ description: parameter.description,
65
+ },
66
+ ];
67
+ })
68
+ );
69
+ }
70
+
71
+ function loadRegistry() {
72
+ if (registry) return registry;
73
+ const nodes = new Map(),
74
+ options = new Set(),
75
+ namesByOperation = new Map();
76
+ for (const [domain, { title, commands }] of Object.entries(catalog)) {
77
+ nodes.set(domain, { children: new Map(), title });
78
+ for (const [name, operationID] of Object.entries(commands)) {
79
+ const parts = name.split('.');
80
+ check(
81
+ parts[0] === domain &&
82
+ parts.length >= 3 &&
83
+ parts.every((part) => /^[a-z0-9][a-z0-9-]*$/.test(part)),
84
+ 'invalid product command path: ' + name
85
+ );
86
+ const op = lookup(operationID);
87
+ check(
88
+ op.path === '/product/' + domain || op.path.startsWith('/product/' + domain + '/'),
89
+ 'product command refers to a different product: ' + name
90
+ );
91
+ for (let i = 1; i < parts.length; i++) {
92
+ const parent = nodes.get(parts.slice(0, i).join('.'));
93
+ const path = parts.slice(0, i + 1).join('.');
94
+ if (!nodes.has(path)) nodes.set(path, { children: new Map() });
95
+ parent.children.set(parts[i], nodes.get(path));
96
+ }
97
+ const node = nodes.get(name);
98
+ namesByOperation.set(operationID, name);
99
+ const fields = inputFlags(op);
100
+ check(fields.size === (op.parameters ?? []).length, 'duplicate product flags: ' + name);
101
+ for (const flag of fields.keys()) options.add(flag);
102
+ const pilot = parts[0] === 'rgs' && parts[1] === 'instance' && rgsInstanceCommands.get(parts[2]);
103
+ if (pilot)
104
+ check(lookup(pilot.operation).operation_id === operationID, 'RGS command mismatch: ' + name);
105
+ Object.assign(node, {
106
+ op,
107
+ fields,
108
+ paged: op.aliases?.some((alias) => pagedAliases.has(alias)) ?? false,
109
+ pilot: pilot || undefined,
110
+ });
111
+ }
112
+ }
113
+ for (const [name, node] of nodes) {
114
+ check(!node.op || !node.children.size, 'product command is both a method and a group: ' + name);
115
+ }
116
+ registry = { nodes, options, namesByOperation };
117
+ return registry;
118
+ }
119
+
120
+ export function isProductDomain(name) {
121
+ return Object.hasOwn(catalog, name);
122
+ }
123
+
124
+ export function productNode(parts) {
125
+ if (!isProductDomain(parts[0]) || parts.some((part) => part.includes('.'))) return;
126
+ return loadRegistry().nodes.get(parts.join('.'));
127
+ }
128
+
129
+ export function productOperation(name) {
130
+ return productNode(name.split('.'))?.op?.operation_id;
131
+ }
132
+
133
+ export function productName(operationID) {
134
+ return loadRegistry().namesByOperation.get(operationID);
135
+ }
136
+
137
+ export function isProductOption(name) {
138
+ return loadRegistry().options.has(name);
139
+ }
140
+
141
+ const fieldTypes = {
142
+ integer: '整数',
143
+ number: '数字',
144
+ string: '字符串',
145
+ boolean: 'true|false',
146
+ array: 'JSON 数组',
147
+ object: 'JSON 对象',
148
+ };
149
+
150
+ export function productHelp(parts) {
151
+ const node = productNode(parts);
152
+ if (!node) return;
153
+ const topic = parts.join(' ');
154
+ const command = 'rainyun-cli ' + topic;
155
+ const info = {
156
+ topic,
157
+ summary: node.title ?? node.op?.summary ?? '选择子命令。',
158
+ usage: [],
159
+ options: [],
160
+ examples: [],
161
+ };
162
+ if (node.children.size) {
163
+ info.usage.push(...[...node.children.keys()].map((child) => command + ' ' + child + ' --help'));
164
+ info.subcommands = [...node.children].map(([child, next]) => {
165
+ const names = [...next.children.keys()];
166
+ const preview = names.slice(0, 4).join('、') + (names.length > 4 ? ' 等' : '');
167
+ return [child, next.op?.summary ?? preview];
168
+ });
169
+ return info;
170
+ }
171
+ const op = node.op;
172
+ info.usage.push(command + ' [选项]');
173
+ if (node.pilot) {
174
+ for (const [name, [value, description]] of Object.entries(node.pilot.options)) {
175
+ info.options.push(['--' + name + ' ' + value, description]);
176
+ }
177
+ } else {
178
+ if (node.paged) {
179
+ info.options.push(['--page N', '页码,默认 1'], ['--per-page N', '每页 1 至 100 条,默认 20']);
180
+ }
181
+ for (const [name, field] of node.fields) {
182
+ const description = field.description?.split('\n')[0];
183
+ const details = [
184
+ field.required && !(node.paged && name === 'options') ? '必填' : '可选',
185
+ description && description.replace(/。$/, ''),
186
+ ]
187
+ .filter(Boolean)
188
+ .join('。');
189
+ info.options.push(['--' + name + ' <' + (fieldTypes[field.type] ?? '值') + '>', details]);
190
+ }
191
+ if (op.request_body) {
192
+ const content = resolve(op.request_body).content;
193
+ if (content['application/json']) info.options.push(['--body JSON', '请求体,字段见 schema']);
194
+ if (content['multipart/form-data']) info.options.push(['--file FIELD=PATH', '上传文件']);
195
+ }
196
+ info.options.push(['--input FILE|-', '从 JSON 文件或标准输入提供完整请求参数']);
197
+ if (op.authentication === 'none' && op.api_key_enabled)
198
+ info.options.push(['--authenticated', '以账号身份调用']);
199
+ }
200
+ info.options.push(['--dry-run', '仅离线预览。省略时执行命令']);
201
+ return {
202
+ ...info,
203
+ operation_id: op.operation_id,
204
+ method: op.method,
205
+ scopes: op.scopes,
206
+ is_write: isWrite(op.method),
207
+ requires_yes: false,
208
+ };
209
+ }
@@ -0,0 +1,44 @@
1
+ export const rgsInstanceCommands = new Map([
2
+ [
3
+ 'list',
4
+ {
5
+ operation: 'rgs.list',
6
+ options: {
7
+ page: ['N', '页码,默认 1'],
8
+ 'per-page': ['N', '每页 1 至 100 条,默认 20'],
9
+ },
10
+ },
11
+ ],
12
+ [
13
+ 'get',
14
+ {
15
+ operation: 'rgs.get',
16
+ options: { id: ['ID', '游戏云实例 ID,必填'] },
17
+ },
18
+ ],
19
+ [
20
+ 'start',
21
+ {
22
+ operation: 'post_product_rgs_id_start_016760b9',
23
+ options: { id: ['ID', '游戏云实例 ID,必填'] },
24
+ },
25
+ ],
26
+ [
27
+ 'reboot',
28
+ {
29
+ operation: 'post_product_rgs_id_reboot_ceeaea50',
30
+ options: { id: ['ID', '游戏云实例 ID,必填'] },
31
+ },
32
+ ],
33
+ [
34
+ 'monitor',
35
+ {
36
+ operation: 'get_product_rgs_id_monitor_cd687c27',
37
+ options: {
38
+ id: ['ID', '游戏云实例 ID,必填'],
39
+ 'start-date': ['UNIX_SECONDS', '起始时间,Unix 时间戳(秒),必填'],
40
+ 'end-date': ['UNIX_SECONDS', '结束时间,Unix 时间戳(秒),必填'],
41
+ },
42
+ },
43
+ ],
44
+ ]);
package/src/json.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // Parse JSON object keys before they are collapsed by JSON.parse. Preserve
2
+ // numeric lexemes which would otherwise be rounded by JavaScript Number.
3
+ export function jsonParse(text) {
4
+ if (typeof text !== 'string') throw new SyntaxError('expected JSON text');
5
+ let offset = 0;
6
+ const white = /[ \t\r\n]*/y;
7
+ const scalar = /true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y;
8
+ function skip() {
9
+ white.lastIndex = offset;
10
+ white.exec(text);
11
+ offset = white.lastIndex;
12
+ }
13
+ function invalid() {
14
+ throw new SyntaxError('invalid or ambiguous JSON');
15
+ }
16
+ function atom() {
17
+ if (text[offset] === '"') {
18
+ // Scan the delimiters linearly, then use the native decoder for escapes.
19
+ const start = offset++;
20
+ while (offset < text.length) {
21
+ const char = text[offset++];
22
+ if (char === '"') return JSON.parse(text.slice(start, offset));
23
+ if (char === '\\') offset++;
24
+ }
25
+ invalid();
26
+ }
27
+ scalar.lastIndex = offset;
28
+ const match = scalar.exec(text);
29
+ if (!match) invalid();
30
+ offset = scalar.lastIndex;
31
+ const raw = match[0];
32
+ const value = JSON.parse(raw);
33
+ if (typeof value !== 'number' || (JSON.stringify(value) === raw && Number.isSafeInteger(value)))
34
+ return value;
35
+ if (/^-?\d+$/.test(raw) && !Number.isSafeInteger(value)) return BigInt(raw);
36
+ return JSON.stringify(value) === raw ? value : JSON.rawJSON(raw);
37
+ }
38
+ function value(depth) {
39
+ if (depth > 512) invalid();
40
+ skip();
41
+ const lead = text[offset];
42
+ if (lead !== '{' && lead !== '[') return atom();
43
+ const object = lead === '{';
44
+ const result = object ? {} : [];
45
+ const end = object ? '}' : ']';
46
+ offset++;
47
+ skip();
48
+ if (text[offset] === end) {
49
+ offset++;
50
+ return result;
51
+ }
52
+ for (;;) {
53
+ if (object) {
54
+ skip();
55
+ if (text[offset] !== '"') invalid();
56
+ const key = atom();
57
+ if (Object.hasOwn(result, key)) invalid();
58
+ skip();
59
+ if (text[offset++] !== ':') invalid();
60
+ Object.defineProperty(result, key, {
61
+ value: value(depth + 1),
62
+ enumerable: true,
63
+ writable: true,
64
+ configurable: true,
65
+ });
66
+ } else result.push(value(depth + 1));
67
+ skip();
68
+ const separator = text[offset++];
69
+ if (separator === end) return result;
70
+ if (separator !== ',') invalid();
71
+ }
72
+ }
73
+ const result = value(0);
74
+ skip();
75
+ if (offset !== text.length) invalid();
76
+ return result;
77
+ }
78
+
79
+ export function jsonStringify(value, space) {
80
+ return JSON.stringify(value, (_, v) => (typeof v === 'bigint' ? JSON.rawJSON(String(v)) : v), space);
81
+ }