@senguoyunnpm/producer-cli 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -2
- package/dist/config.d.ts +12 -0
- package/dist/config.js +105 -0
- package/dist/config.js.map +1 -0
- package/dist/download.d.ts +8 -0
- package/dist/download.js +88 -0
- package/dist/download.js.map +1 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +224 -0
- package/dist/errors.js.map +1 -0
- package/dist/generated/catalog-revision.d.ts +1 -0
- package/dist/generated/catalog-revision.js +2 -0
- package/dist/generated/catalog-revision.js.map +1 -0
- package/dist/main.d.ts +11 -0
- package/dist/main.js +1226 -0
- package/dist/main.js.map +1 -0
- package/dist/main.mjs +122 -0
- package/dist/next-step.d.ts +1 -0
- package/dist/next-step.js +34 -0
- package/dist/next-step.js.map +1 -0
- package/dist/output.d.ts +5 -0
- package/dist/output.js +126 -0
- package/dist/output.js.map +1 -0
- package/dist/parameters.d.ts +90 -0
- package/dist/parameters.js +502 -0
- package/dist/parameters.js.map +1 -0
- package/dist/schema.d.ts +11 -0
- package/dist/schema.js +158 -0
- package/dist/schema.js.map +1 -0
- package/dist/update/engine.d.ts +38 -0
- package/dist/update/engine.js +197 -0
- package/dist/update/engine.js.map +1 -0
- package/dist/update/launcher.d.ts +17 -0
- package/dist/update/launcher.js +121 -0
- package/dist/update/launcher.js.map +1 -0
- package/dist/update/layout.d.ts +10 -0
- package/dist/update/layout.js +84 -0
- package/dist/update/layout.js.map +1 -0
- package/dist/update/registry.d.ts +13 -0
- package/dist/update/registry.js +48 -0
- package/dist/update/registry.js.map +1 -0
- package/dist/update/tar.d.ts +5 -0
- package/dist/update/tar.js +94 -0
- package/dist/update/tar.js.map +1 -0
- package/dist/update/version.d.ts +8 -0
- package/dist/update/version.js +63 -0
- package/dist/update/version.js.map +1 -0
- package/dist/upgrade.d.ts +11 -0
- package/dist/upgrade.js +50 -0
- package/dist/upgrade.js.map +1 -0
- package/dist/upload.d.ts +23 -0
- package/dist/upload.js +57 -0
- package/dist/upload.js.map +1 -0
- package/package.json +27 -4
package/dist/main.js
ADDED
|
@@ -0,0 +1,1226 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command, Help } from 'commander';
|
|
3
|
+
import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { catalog, contractOf, createClient, getCommandExecutor, purchaseRefundHelp, refreshSalesOrderPackageMaterials, validateConstraints, validateInput, validatePurchaseRefundStock, } from '@senguoyunnpm/producersdk';
|
|
9
|
+
import { clientConfig, readShopRef, writeShopRef } from './config.js';
|
|
10
|
+
import { actionSupportsDraft, inputSchemaForAction, schemaValueWithOptions, resolveSchema, } from './schema.js';
|
|
11
|
+
import { applyFields, applyJq, formatOutput, parseOutputFormat } from './output.js';
|
|
12
|
+
import { CliError, errorExitCode, errorPayload } from './errors.js';
|
|
13
|
+
import { cliNextStep } from './next-step.js';
|
|
14
|
+
import { assertGlobalInstall, cliPackageRoot, npmExecutable, npmGlobalRoot, npmSpawn, } from './upgrade.js';
|
|
15
|
+
import { uploadAsset } from './upload.js';
|
|
16
|
+
import { downloadExportFile } from './download.js';
|
|
17
|
+
import { checkForUpdate, cleanupInstall, detectForm, installRelease, rollbackRelease, } from './update/engine.js';
|
|
18
|
+
import { bootstrapInstall } from './update/launcher.js';
|
|
19
|
+
import { installRoot, resolveRegistry } from './update/layout.js';
|
|
20
|
+
import { isValidVersion, compareVersions, resolveChannel } from './update/version.js';
|
|
21
|
+
import { CATALOG_REVISION } from './generated/catalog-revision.js';
|
|
22
|
+
import { cliType, coerceFlagValue, compileCommandParameters, enumValues, exampleCommand, exampleJson, flagName, isBooleanEnum, lastWindow, typeHint, } from './parameters.js';
|
|
23
|
+
const CLI_PACKAGE_NAME = '@senguoyunnpm/producer-cli';
|
|
24
|
+
const require = createRequire(import.meta.url);
|
|
25
|
+
// 自更新已开放:npmjs 正式版与应用内置 CLI 均可通过 `producer upgrade` 更新。
|
|
26
|
+
// 应用启动的 seed 使用 --bootstrap-only,只做本地安装;联网更新只由用户显式触发。
|
|
27
|
+
const SELF_UPDATE_ENABLED = true;
|
|
28
|
+
const UPGRADE_DISABLED_MESSAGE = '升级功能暂不可用,请检查并升级森果云AI助手;producer CLI 随应用一起更新。';
|
|
29
|
+
function currentCliVersion() {
|
|
30
|
+
try {
|
|
31
|
+
return String(require('../package.json').version);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return '0.0.0';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function globalRootOrUndefined() {
|
|
38
|
+
try {
|
|
39
|
+
return npmGlobalRoot();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** 已安装包自带的发布 registry;公开 npmjs 与私有 dev 包各自描述自己的来源。 */
|
|
46
|
+
function installedPackageRegistry() {
|
|
47
|
+
try {
|
|
48
|
+
const manifest = JSON.parse(readFileSync(join(cliPackageRoot(), 'package.json'), 'utf8'));
|
|
49
|
+
const registry = manifest.publishConfig?.registry;
|
|
50
|
+
return typeof registry === 'string' && registry.trim() ? registry.trim() : undefined;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function latestCliVersion(tag, registry) {
|
|
57
|
+
try {
|
|
58
|
+
const spawn = npmSpawn(npmExecutable(), [
|
|
59
|
+
'view',
|
|
60
|
+
CLI_PACKAGE_NAME,
|
|
61
|
+
'version',
|
|
62
|
+
'--registry',
|
|
63
|
+
registry,
|
|
64
|
+
'--tag',
|
|
65
|
+
tag,
|
|
66
|
+
]);
|
|
67
|
+
const raw = execFileSync(spawn.file, spawn.args, {
|
|
68
|
+
encoding: 'utf8',
|
|
69
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
70
|
+
shell: spawn.shell,
|
|
71
|
+
}).trim();
|
|
72
|
+
if (!isValidVersion(raw))
|
|
73
|
+
throw new CliError('registry 返回了非法版本号', 'internal', 'upgrade_payload_invalid');
|
|
74
|
+
return raw;
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (error instanceof CliError)
|
|
78
|
+
throw error;
|
|
79
|
+
throw new CliError('无法查询 npm 上的最新版本', 'internal', 'upgrade_npm_unavailable', '确认 npm 在 PATH 中可执行后重试;应用内置运行时不支持自动升级。');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// commander 驼峰 option key
|
|
83
|
+
const optionKey = (name) => name.replace(/[-_]([a-z0-9])/g, (_, c) => c.toUpperCase());
|
|
84
|
+
// 导出「触发 → 轮询 → 登记下载」的编排在 @senguoyunnpm/producersdk(createExportApi),CLI 只映射
|
|
85
|
+
// --wait/--key/--poll-interval/--wait-timeout 四个 flag 并渲染回执。
|
|
86
|
+
const EXPORT_RECORD_DOWNLOAD = 'producer.master_data.export-record.download';
|
|
87
|
+
const PURCHASE_REFUND_CREATE = 'producer.purchase.purchase-refund.create';
|
|
88
|
+
// 源预填 workflow:按 workflow_contract.planner 分发到 SDK 的预填实现(只读,不落库)。
|
|
89
|
+
const WORKFLOW_EXECUTORS = {
|
|
90
|
+
'purchase.purchase-refund.prefill': (sdk, params, options) => sdk.purchaseRefundIntent.prefill(params, options),
|
|
91
|
+
'stockin.document.prefill': (sdk, params, options) => sdk.sourcePrefill.stockin(params, options),
|
|
92
|
+
'purchase.material.prefill': (sdk, params, options) => sdk.sourcePrefill.purchase({ ...params, kind: 'material' }, options),
|
|
93
|
+
'purchase.auxiliary.prefill': (sdk, params, options) => sdk.sourcePrefill.purchase({ ...params, kind: 'auxiliary' }, options),
|
|
94
|
+
'purchase.product.prefill': (sdk, params, options) => sdk.sourcePrefill.purchase({ ...params, kind: 'product' }, options),
|
|
95
|
+
'outbound.document.prefill': (sdk, params, options) => sdk.sourcePrefill.outbound(params, options),
|
|
96
|
+
'sorting.order.prefill': (sdk, params, options) => sdk.sourcePrefill.sorting(params, options),
|
|
97
|
+
'processing.order.prefill': (sdk, params, options) => sdk.sourcePrefill.processing(params, options),
|
|
98
|
+
'transfer.document.prefill': (sdk, params, options) => sdk.sourcePrefill.transfer(params, options),
|
|
99
|
+
'sales.order.prefill': (sdk, params, options) => sdk.sourcePrefill.sales(params, options),
|
|
100
|
+
'production-plan.prefill': (sdk, params, options) => sdk.sourcePrefill.productionPlan(params, options),
|
|
101
|
+
'send-order.prefill': (sdk, params, options) => sdk.sourcePrefill.sendOrder(params, options),
|
|
102
|
+
'sketch-order.prefill': (sdk, params, options) => sdk.sourcePrefill.sketchOrder(params, options),
|
|
103
|
+
};
|
|
104
|
+
// workflow 分发到 SDK 预填实现的唯一查找入口;未知 planner 在这里 fail-closed,
|
|
105
|
+
// 避免 catalog 新增 workflow 而 CLI 忘记接线时静默漏掉命令。
|
|
106
|
+
export function workflowExecutor(planner) {
|
|
107
|
+
const executor = WORKFLOW_EXECUTORS[planner];
|
|
108
|
+
if (!executor)
|
|
109
|
+
throw new Error(`未实现 workflow: ${planner}`);
|
|
110
|
+
return executor;
|
|
111
|
+
}
|
|
112
|
+
// 示例命令:生成 schema-valid 的业务模板;实体引用使用来源占位符,调用前替换为真实查询结果。
|
|
113
|
+
function renderExamples(commandPath, action, isWrite) {
|
|
114
|
+
const input = inputSchemaForAction(action);
|
|
115
|
+
if (!isWrite)
|
|
116
|
+
return `Examples:\n ${exampleCommand(commandPath, input)}`;
|
|
117
|
+
const example = exampleJson(input, {
|
|
118
|
+
operationId: action.contract.operation_id,
|
|
119
|
+
planner: action.intent?.planner,
|
|
120
|
+
intent: Boolean(action.intent),
|
|
121
|
+
});
|
|
122
|
+
return `Examples:\n ${commandPath} --yes --params '${example}'`;
|
|
123
|
+
}
|
|
124
|
+
// 写命令 help:列出带 reference 的 ID 字段来源读命令(含 items[] 行内字段)。
|
|
125
|
+
// 来源命令若需要上下文参数(scopeArgument,如分仓必须按所选加工厂查),必须把它写出来——
|
|
126
|
+
// 否则调用方会从全量列表里随便挑一个,造成「工厂/分仓错配」,服务端只报「库存不足」或 500。
|
|
127
|
+
function renderIdSources(input) {
|
|
128
|
+
const lines = [];
|
|
129
|
+
const collect = (properties, prefix) => {
|
|
130
|
+
for (const [name, schema] of Object.entries(properties ?? {})) {
|
|
131
|
+
const reference = schema.reference;
|
|
132
|
+
if (reference) {
|
|
133
|
+
const scope = reference.scopeArgument;
|
|
134
|
+
const scopeFlag = scope?.replace(/_/g, '-');
|
|
135
|
+
lines.push(scopeFlag
|
|
136
|
+
? `${prefix}${name} 来自 \`${reference.command} --${scopeFlag} <本命令的 --${scopeFlag}>\`(取 \`${reference.resultPath}\`;必须与本命令的 ${scope} 一致)`
|
|
137
|
+
: `${prefix}${name} 来自 \`${reference.command}\`(取 \`${reference.resultPath}\`)`);
|
|
138
|
+
}
|
|
139
|
+
if (schema.type === 'array') {
|
|
140
|
+
const nested = schema.items
|
|
141
|
+
?.properties;
|
|
142
|
+
collect(nested, `${prefix}${name}[].`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
collect(input.properties, '');
|
|
147
|
+
return lines.length ? `ID 来源:\n ${lines.join('\n ')}` : '';
|
|
148
|
+
}
|
|
149
|
+
function renderContractHelp(action) {
|
|
150
|
+
const contract = action.contract;
|
|
151
|
+
const constraints = Array.isArray(contract.constraints) && contract.constraints.length
|
|
152
|
+
? `\nConstraints: ${JSON.stringify(contract.constraints)}`
|
|
153
|
+
: '';
|
|
154
|
+
return `\nSafety: effect=${contract.effect} risk=${contract.risk} confirmation=${contract.confirmation} idempotency=${contract.idempotency}\nWhen to use: ${(contract.use_when ?? []).join(';') || '未声明'}\nAvoid when: ${(contract.not_for ?? []).join(';') || '未声明'}${constraints}\n`;
|
|
155
|
+
}
|
|
156
|
+
function renderWorkflowHelp(action) {
|
|
157
|
+
const workflow = action.workflow_contract;
|
|
158
|
+
if (!workflow)
|
|
159
|
+
return '';
|
|
160
|
+
const input = action.contract.input;
|
|
161
|
+
const required = new Set(input.required ?? []);
|
|
162
|
+
const props = input.properties ?? {};
|
|
163
|
+
const describe = (schema) => {
|
|
164
|
+
if (schema.enum?.length)
|
|
165
|
+
return `(${schema.enum.map(String).join('|')})`;
|
|
166
|
+
const hint = typeHint(schema);
|
|
167
|
+
return hint ? `<${hint}>` : '';
|
|
168
|
+
};
|
|
169
|
+
const lines = Object.entries(props).map(([name, schema]) => {
|
|
170
|
+
const mark = required.has(name) ? '(必填)' : '(可选)';
|
|
171
|
+
const desc = schema.description ? `:${schema.description}` : '';
|
|
172
|
+
const hint = describe(schema);
|
|
173
|
+
return ` ${flagName(name)}${hint ? ` ${hint}` : ''}${mark}${desc}`;
|
|
174
|
+
});
|
|
175
|
+
return `\nWorkflow 输入:\n${lines.join('\n')}\n`;
|
|
176
|
+
}
|
|
177
|
+
function recordOf(value) {
|
|
178
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
179
|
+
? value
|
|
180
|
+
: undefined;
|
|
181
|
+
}
|
|
182
|
+
// contractOf 的公开声明只保留基线所需字段;catalog 索引里实际是完整 OperationContract。
|
|
183
|
+
function fullContractOf(operationId) {
|
|
184
|
+
return contractOf(operationId);
|
|
185
|
+
}
|
|
186
|
+
// Parameters:把写命令的 input schema 摘要成人类可读字段表;业务字段都在 --params JSON 里,
|
|
187
|
+
// help 不能只留下一个空对象示例。来源是 catalog 的 input_schema(意图命令用 intent_input)。
|
|
188
|
+
function renderParametersHelp(action) {
|
|
189
|
+
const input = inputSchemaForAction(action);
|
|
190
|
+
const entries = Object.entries(input.properties ?? {});
|
|
191
|
+
if (!entries.length)
|
|
192
|
+
return '';
|
|
193
|
+
const required = new Set(input.required ?? []);
|
|
194
|
+
const lines = entries.map(([name, schema]) => {
|
|
195
|
+
const type = cliType(schema) || 'string';
|
|
196
|
+
const mark = required.has(name) ? '(必填)' : '(可选)';
|
|
197
|
+
const values = enumValues(schema);
|
|
198
|
+
const enumText = values?.length ? `,取值:${values.map(String).join('|')}` : '';
|
|
199
|
+
const desc = schema.description ? `:${schema.description}` : '';
|
|
200
|
+
return ` ${name} (${type}${enumText})${mark}${desc}`;
|
|
201
|
+
});
|
|
202
|
+
return `\nParameters:\n${lines.join('\n')}\n`;
|
|
203
|
+
}
|
|
204
|
+
// Preflight:catalog 声明的执行前条件;意图命令同时读取目标 operation 的条件。
|
|
205
|
+
function renderPreflightHelp(action) {
|
|
206
|
+
const target = action.intent ? fullContractOf(action.intent.target_operation_id) : undefined;
|
|
207
|
+
const items = [...(action.contract.preconditions ?? []), ...(target?.preconditions ?? [])].filter((item, index, all) => item && all.indexOf(item) === index);
|
|
208
|
+
const workflow = recordOf(action.workflow_contract?.preflight);
|
|
209
|
+
const required = Array.isArray(workflow?.required)
|
|
210
|
+
? workflow.required.filter((item) => typeof item === 'string')
|
|
211
|
+
: [];
|
|
212
|
+
if (!items.length && !required.length)
|
|
213
|
+
return '';
|
|
214
|
+
const lines = [
|
|
215
|
+
...items.map((item) => ` - ${item}`),
|
|
216
|
+
...(required.length ? [` - 必须先取得:${required.join('、')}`] : []),
|
|
217
|
+
];
|
|
218
|
+
return `\nPreflight:\n${lines.join('\n')}\n`;
|
|
219
|
+
}
|
|
220
|
+
function cliPathOfOperation(operationId) {
|
|
221
|
+
const action = catalog.actionsForOperation(operationId)[0];
|
|
222
|
+
return action?.contract.cli_example;
|
|
223
|
+
}
|
|
224
|
+
// Readback:只渲染有可靠来源的内容——workflow 声明的回读要求,或编辑源的详情命令。
|
|
225
|
+
function renderReadbackHelp(action) {
|
|
226
|
+
const lines = [];
|
|
227
|
+
const readback = recordOf(action.workflow_contract?.readback);
|
|
228
|
+
const required = Array.isArray(readback?.required)
|
|
229
|
+
? readback.required.filter((item) => typeof item === 'string')
|
|
230
|
+
: [];
|
|
231
|
+
if (required.length)
|
|
232
|
+
lines.push(` - 回读要求:${required.join('、')}`);
|
|
233
|
+
const source = action.contract.edit_source;
|
|
234
|
+
if (source?.detail_operation_id) {
|
|
235
|
+
const cli = cliPathOfOperation(source.detail_operation_id);
|
|
236
|
+
const idArgument = source.id_argument ?? 'id';
|
|
237
|
+
if (cli)
|
|
238
|
+
lines.push(` - 回读详情:\`${cli} --${idArgument.replace(/_/g, '-')} <写入回执的 ${idArgument}>\``);
|
|
239
|
+
}
|
|
240
|
+
if (!lines.length)
|
|
241
|
+
return '';
|
|
242
|
+
return `\nReadback:\n${lines.join('\n')}\n`;
|
|
243
|
+
}
|
|
244
|
+
// Recovery:workflow 声明的恢复映射 + 由 idempotency=unknown 推导的写入超时处理。
|
|
245
|
+
function renderRecoveryHelp(action) {
|
|
246
|
+
const lines = [];
|
|
247
|
+
const recovery = recordOf(action.workflow_contract?.recovery);
|
|
248
|
+
for (const [stage, outcome] of Object.entries(recovery ?? {}))
|
|
249
|
+
lines.push(` - ${stage} → ${String(outcome)}`);
|
|
250
|
+
const contract = action.contract;
|
|
251
|
+
if (contract.effect === 'write' && contract.idempotency === 'unknown')
|
|
252
|
+
lines.push(' - 写入超时或连接中断:不要直接重放;先按 Readback 回读确认是否已提交,未提交再重试。');
|
|
253
|
+
if (!lines.length)
|
|
254
|
+
return '';
|
|
255
|
+
return `\nRecovery:\n${lines.join('\n')}\n`;
|
|
256
|
+
}
|
|
257
|
+
// 快捷路径:catalog 里声明的 from→to 预填(如订货单详情 → 采购单创建)。
|
|
258
|
+
// 目标命令若已从命令树隐藏(例如按业务类型拆成了意图命令),只说明意图,不给跑不通的命令行。
|
|
259
|
+
function renderShortcuts(action) {
|
|
260
|
+
const lines = [];
|
|
261
|
+
for (const shortcut of action.shortcuts ?? []) {
|
|
262
|
+
const prefilled = Object.entries(shortcut.argument_map)
|
|
263
|
+
.map(([from, to]) => `${to}=<${from}>`)
|
|
264
|
+
.join('、');
|
|
265
|
+
// 按业务类型分流:目标随来源记录的判别字段取值而不同(如订货单 order_type)。
|
|
266
|
+
if (shortcut.discriminator) {
|
|
267
|
+
const rows = Object.entries(shortcut.discriminator.values)
|
|
268
|
+
.map(([value, target]) => `${shortcut.discriminator.argument}=${value} → \`${target.cli_path}\``)
|
|
269
|
+
.join('\n ');
|
|
270
|
+
lines.push(`${shortcut.title}(按 ${shortcut.discriminator.argument} 分流${prefilled ? `,预填 ${prefilled}` : ''}):\n ${rows}`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (!shortcut.cli_path)
|
|
274
|
+
continue;
|
|
275
|
+
const parts = shortcut.cli_path.split(' ').slice(1);
|
|
276
|
+
let visible = false;
|
|
277
|
+
try {
|
|
278
|
+
const target = resolveSchema(parts);
|
|
279
|
+
visible = 'contract' in target && !target.hidden;
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
visible = false;
|
|
283
|
+
}
|
|
284
|
+
lines.push(visible
|
|
285
|
+
? `${shortcut.title} → \`${shortcut.cli_path}\`${prefilled ? `(预填 ${prefilled})` : ''}`
|
|
286
|
+
: `${shortcut.title}:目标命令 \`${shortcut.cli_path}\` 当前不在命令树中(可能已按业务类型拆分)`);
|
|
287
|
+
}
|
|
288
|
+
return lines.length ? `快捷:\n ${lines.join('\n ')}` : '';
|
|
289
|
+
}
|
|
290
|
+
// 是否有可见的叶子动作(用于跳过全隐藏的资源/能力包)
|
|
291
|
+
function hasVisible(node) {
|
|
292
|
+
return (node.actions ?? []).some((a) => !a.hidden) || (node.resources ?? []).some(hasVisible);
|
|
293
|
+
}
|
|
294
|
+
// --last 可展开的日期范围参数名(from/to 与 start/end 两档后端约定)
|
|
295
|
+
function dateRangeArgs(props) {
|
|
296
|
+
if ('from_date' in props && 'to_date' in props)
|
|
297
|
+
return ['from_date', 'to_date'];
|
|
298
|
+
if ('start_date' in props && 'end_date' in props)
|
|
299
|
+
return ['start_date', 'end_date'];
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
function getPath(value, path) {
|
|
303
|
+
let cursor = value;
|
|
304
|
+
for (const seg of path.split('.')) {
|
|
305
|
+
if (cursor === null || typeof cursor !== 'object')
|
|
306
|
+
return undefined;
|
|
307
|
+
cursor = cursor[seg];
|
|
308
|
+
}
|
|
309
|
+
return cursor;
|
|
310
|
+
}
|
|
311
|
+
function setPathValue(target, path, value) {
|
|
312
|
+
const segs = path.split('.').filter(Boolean);
|
|
313
|
+
if (!segs.length)
|
|
314
|
+
return;
|
|
315
|
+
let cursor = target;
|
|
316
|
+
for (let i = 0; i < segs.length - 1; i++) {
|
|
317
|
+
const next = cursor[segs[i]];
|
|
318
|
+
if (next === null || typeof next !== 'object' || Array.isArray(next))
|
|
319
|
+
cursor[segs[i]] = {};
|
|
320
|
+
cursor = cursor[segs[i]];
|
|
321
|
+
}
|
|
322
|
+
cursor[segs[segs.length - 1]] = value;
|
|
323
|
+
}
|
|
324
|
+
function parsePositiveNumber(value) {
|
|
325
|
+
const parsed = Number(value);
|
|
326
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
327
|
+
throw new CliError(`参数必须是大于 0 的有限数字: ${value}`, 'validation', 'flag_value_out_of_range');
|
|
328
|
+
return parsed;
|
|
329
|
+
}
|
|
330
|
+
function parsePositiveInteger(value) {
|
|
331
|
+
const parsed = Number(value);
|
|
332
|
+
if (!Number.isSafeInteger(parsed) || parsed < 1)
|
|
333
|
+
throw new CliError(`参数必须是大于 0 的整数: ${value}`, 'validation', 'flag_value_out_of_range');
|
|
334
|
+
return parsed;
|
|
335
|
+
}
|
|
336
|
+
function readParams(value, readStdin = () => readFileSync(0, 'utf8')) {
|
|
337
|
+
if (typeof value !== 'string' || !value)
|
|
338
|
+
throw new CliError('--params 需为 JSON 对象、JSON 文件路径或 -', 'validation', 'missing_required_parameter');
|
|
339
|
+
const source = value === '-' ? readStdin() : value;
|
|
340
|
+
let parsed;
|
|
341
|
+
try {
|
|
342
|
+
parsed = JSON.parse(source);
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
if (value === '-')
|
|
346
|
+
throw new CliError('--params - 需从 stdin 读取合法 JSON 对象', 'validation', 'invalid_parameter_json');
|
|
347
|
+
try {
|
|
348
|
+
parsed = JSON.parse(readFileSync(value, 'utf8'));
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
352
|
+
throw new CliError(`--params 需为合法 JSON,或可读取的 JSON 文件路径: ${reason}`, 'validation', 'invalid_parameter_json');
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
356
|
+
throw new CliError('--params 需为合法 JSON 对象', 'validation', 'invalid_parameter_json');
|
|
357
|
+
return parsed;
|
|
358
|
+
}
|
|
359
|
+
// 叶子执行前的可用性预检。区分两种失败:
|
|
360
|
+
// - 服务端明确返回 available=false:能力不可用,拒绝执行。
|
|
361
|
+
// - 预检调用本身失败:读取可以继续(避免假阴性);idempotency=unknown 的写入必须 fail-closed,
|
|
362
|
+
// 因为无法确认重复提交的后果。
|
|
363
|
+
async function assertCapabilityAvailable(client, operationId, shopRef, signal, contract) {
|
|
364
|
+
let result;
|
|
365
|
+
try {
|
|
366
|
+
result = await client.check(operationId, { shopRef, ...(signal ? { signal } : {}) });
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
if (contract?.effect === 'write' && contract.idempotency === 'unknown')
|
|
370
|
+
throw new CliError('能力预检不可用,已停止写入', 'api', 'preflight_unavailable', '无法确认预检结果,也无法确认写入是否幂等;请稍后重试预检或先回读确认,不要直接重放写入。');
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (result && result.available === false) {
|
|
374
|
+
throw new Error(result.reason ?? '当前账户无权限执行该操作');
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
function assertNotTruncated(result) {
|
|
378
|
+
if (result !== null &&
|
|
379
|
+
typeof result === 'object' &&
|
|
380
|
+
result.truncated === true)
|
|
381
|
+
throw new CliError('结果被投影截断:当前页超过合同上限;请将 --page-size 降到 100 以内或收窄筛选条件。', 'validation', 'projection_truncated');
|
|
382
|
+
}
|
|
383
|
+
// 分页执行:默认只取单页(page_size 用合同上限);--all 显式翻页取全部;--page/--page-size 指定单页。
|
|
384
|
+
const MAX_AUTO_PAGES = 10000;
|
|
385
|
+
async function executePaginated(executor, pagination, params, page, pageSize, all, pageBase, defaultPageSize, signal) {
|
|
386
|
+
const call = (p) => executor(p, signal ? { signal } : undefined);
|
|
387
|
+
const pageArg = pagination?.request_page_argument;
|
|
388
|
+
const sizeArg = pagination?.request_page_size_argument;
|
|
389
|
+
// 显式分页:--page(1 基)/ --page-size 只取单页;后端页码基准取自合同 page 参数的
|
|
390
|
+
// minimum(0 基合同减 1,1 基合同原样传),不假设所有后端都是 0 基。
|
|
391
|
+
if (all && page !== undefined)
|
|
392
|
+
throw new CliError('--all 与 --page 不能同时使用', 'validation', 'flag_conflict');
|
|
393
|
+
if (!all && (page !== undefined || pageSize !== undefined)) {
|
|
394
|
+
const p = { ...params };
|
|
395
|
+
if (pageArg && page !== undefined)
|
|
396
|
+
p[pageArg] = page - 1 + pageBase;
|
|
397
|
+
if (sizeArg && pageSize !== undefined)
|
|
398
|
+
p[sizeArg] = pageSize;
|
|
399
|
+
const result = await call(p);
|
|
400
|
+
assertNotTruncated(result);
|
|
401
|
+
return result;
|
|
402
|
+
}
|
|
403
|
+
// 无分页元数据:单次调用
|
|
404
|
+
if (!pageArg)
|
|
405
|
+
return call(params);
|
|
406
|
+
// --all:自动翻页直到 has_more=false;无记录数上限,仅保留页数保护防止后端异常死循环。
|
|
407
|
+
if (all) {
|
|
408
|
+
const hasMorePath = pagination.response_has_more_path ?? 'pagination.has_more';
|
|
409
|
+
const records = [];
|
|
410
|
+
let first;
|
|
411
|
+
let last;
|
|
412
|
+
let pageIndex = pageBase;
|
|
413
|
+
let hasMore = true;
|
|
414
|
+
for (let pages = 0; hasMore; pages += 1) {
|
|
415
|
+
if (pages >= MAX_AUTO_PAGES)
|
|
416
|
+
throw new CliError(`自动翻页超过 ${MAX_AUTO_PAGES} 页,已中止;请收窄筛选条件后重试`, 'validation', 'pagination_page_limit');
|
|
417
|
+
const pageParams = { ...params };
|
|
418
|
+
if (sizeArg && pageParams[sizeArg] === undefined)
|
|
419
|
+
pageParams[sizeArg] = pageSize ?? defaultPageSize;
|
|
420
|
+
pageParams[pageArg] = pageIndex;
|
|
421
|
+
const result = (await call(pageParams));
|
|
422
|
+
assertNotTruncated(result);
|
|
423
|
+
if (!first)
|
|
424
|
+
first = result;
|
|
425
|
+
last = result;
|
|
426
|
+
const pageRecords = getPath(result.data, 'records');
|
|
427
|
+
const batch = Array.isArray(pageRecords) ? pageRecords : [];
|
|
428
|
+
records.push(...batch);
|
|
429
|
+
hasMore = getPath(result.data, hasMorePath) === true;
|
|
430
|
+
if (batch.length === 0)
|
|
431
|
+
break;
|
|
432
|
+
pageIndex += 1;
|
|
433
|
+
}
|
|
434
|
+
const merged = { ...(first ?? {}) };
|
|
435
|
+
const data = {
|
|
436
|
+
...(first?.data ?? {}),
|
|
437
|
+
};
|
|
438
|
+
data.records = records;
|
|
439
|
+
// 聚合结果以最后一页为权威:单页 complete/has_more 只描述该页,沿用第一页
|
|
440
|
+
// 会留下 complete=false、has_more=true 与全量记录集矛盾的输出。
|
|
441
|
+
if (last) {
|
|
442
|
+
for (const field of ['complete', 'truncated', 'has_more']) {
|
|
443
|
+
if (typeof last[field] === 'boolean')
|
|
444
|
+
merged[field] = last[field];
|
|
445
|
+
else
|
|
446
|
+
delete merged[field];
|
|
447
|
+
}
|
|
448
|
+
const lastHasMore = getPath(last.data, hasMorePath);
|
|
449
|
+
setPathValue(data, hasMorePath, typeof lastHasMore === 'boolean' ? lastHasMore : false);
|
|
450
|
+
}
|
|
451
|
+
merged.data = data;
|
|
452
|
+
return merged;
|
|
453
|
+
}
|
|
454
|
+
// 默认单页:使用合同允许的最大页大小,原样返回后端 has_more。
|
|
455
|
+
const p = { ...params };
|
|
456
|
+
if (sizeArg && p[sizeArg] === undefined)
|
|
457
|
+
p[sizeArg] = pageSize ?? defaultPageSize;
|
|
458
|
+
if (pageArg && p[pageArg] === undefined)
|
|
459
|
+
p[pageArg] = pageBase;
|
|
460
|
+
const result = await call(p);
|
|
461
|
+
assertNotTruncated(result);
|
|
462
|
+
return result;
|
|
463
|
+
}
|
|
464
|
+
// Shared assembly for execution and offline development tools; actions run only after parsing.
|
|
465
|
+
export function buildProgram(ctx) {
|
|
466
|
+
const write = ctx.write ?? ((s) => process.stdout.write(s));
|
|
467
|
+
const program = new Command();
|
|
468
|
+
const writeCommands = new WeakSet();
|
|
469
|
+
const lastWindowCommands = new WeakSet();
|
|
470
|
+
program
|
|
471
|
+
.name('producer')
|
|
472
|
+
.description('产地业务开发 CLI')
|
|
473
|
+
.exitOverride()
|
|
474
|
+
.configureHelp({
|
|
475
|
+
showGlobalOptions: true,
|
|
476
|
+
// --yes 只对写操作有意义;--last 只对带日期范围参数的读命令有意义。
|
|
477
|
+
// 其余命令的 help 隐去它们,但全局前置写法仍然可用。
|
|
478
|
+
visibleGlobalOptions(command) {
|
|
479
|
+
const options = Help.prototype.visibleGlobalOptions.call(this, command);
|
|
480
|
+
if (command === program)
|
|
481
|
+
return options;
|
|
482
|
+
return options.filter((option) => {
|
|
483
|
+
if (option.long === '--yes')
|
|
484
|
+
return writeCommands.has(command);
|
|
485
|
+
if (option.long === '--last')
|
|
486
|
+
return lastWindowCommands.has(command);
|
|
487
|
+
return true;
|
|
488
|
+
});
|
|
489
|
+
},
|
|
490
|
+
})
|
|
491
|
+
.option('-f, --format <format>', '输出格式 json|table|raw|pretty|ndjson|csv', parseOutputFormat, 'json')
|
|
492
|
+
.option('--fields <fields>', '筛选输出字段 (逗号分隔, 如: name,id,status)')
|
|
493
|
+
.option('--jq <expr>', "jq 表达式过滤输出 (如: '.items[] | .name')")
|
|
494
|
+
.option('--timeout <seconds>', 'HTTP 请求超时时间(秒)', parsePositiveNumber)
|
|
495
|
+
.option('--shop-ref <ref>', '店铺引用(覆盖当前店铺)')
|
|
496
|
+
.option('--last <dur>', '相对时间窗(3m/7d/1y/this-month/this-week),展开为日期范围')
|
|
497
|
+
.option('-y, --yes', '确认执行写入操作(AI/非交互模式必须显式传入)');
|
|
498
|
+
const globals = () => program.opts();
|
|
499
|
+
const timeoutSignal = () => {
|
|
500
|
+
const timeout = globals().timeout;
|
|
501
|
+
return timeout && timeout > 0 ? AbortSignal.timeout(timeout * 1000) : undefined;
|
|
502
|
+
};
|
|
503
|
+
const resolveShopRef = () => globals().shopRef ?? readShopRef(ctx.shopFile) ?? ctx.shopRef;
|
|
504
|
+
const requireShopRef = (resolved) => {
|
|
505
|
+
const shopRef = resolved ?? resolveShopRef();
|
|
506
|
+
if (!shopRef)
|
|
507
|
+
throw new CliError('缺少店铺引用:请先 `producer shop use <ref>` 或传 `--shop-ref`', 'validation', 'shop_ref_required');
|
|
508
|
+
return shopRef;
|
|
509
|
+
};
|
|
510
|
+
const renderOutput = (value) => {
|
|
511
|
+
const opts = globals();
|
|
512
|
+
// 对齐 dws:--jq 作用于完整输出并独占输出,忽略 --fields 与 --format。
|
|
513
|
+
if (opts.jq) {
|
|
514
|
+
write(applyJq(value, opts.jq));
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
write(formatOutput(applyFields(value, opts.fields), opts.format ?? 'json'));
|
|
518
|
+
};
|
|
519
|
+
// 递归注册业务命令树:能力包 → 资源 → 动作(叶子用 argument schema 映射成 flag)
|
|
520
|
+
const registerNode = (parent, path, node) => {
|
|
521
|
+
for (const resource of node.resources ?? []) {
|
|
522
|
+
if (!hasVisible(resource))
|
|
523
|
+
continue;
|
|
524
|
+
const childPath = [...path, resource.id];
|
|
525
|
+
const child = parent
|
|
526
|
+
.command(resource.id)
|
|
527
|
+
.description(`${resource.title} — ${resource.summary}`);
|
|
528
|
+
registerNode(child, childPath, resource);
|
|
529
|
+
}
|
|
530
|
+
for (const action of node.actions ?? []) {
|
|
531
|
+
if (action.hidden)
|
|
532
|
+
continue;
|
|
533
|
+
const input = inputSchemaForAction(action);
|
|
534
|
+
const required = input.required ?? [];
|
|
535
|
+
const props = input.properties ?? {};
|
|
536
|
+
const pagination = action.contract.pagination;
|
|
537
|
+
const cliParameters = compileCommandParameters(input, pagination, action.contract.effect, actionSupportsDraft(action));
|
|
538
|
+
const pageArg = pagination?.request_page_argument;
|
|
539
|
+
const sizeArg = pagination?.request_page_size_argument;
|
|
540
|
+
// 后端页码基准由合同声明:page 的 minimum ≥ 1 即 1 基,否则按 0 基处理。
|
|
541
|
+
const pageBase = pageArg && (props[pageArg]?.minimum ?? 0) >= 1 ? 1 : 0;
|
|
542
|
+
// 分页参数不作为业务 flag 暴露(受控 --page / --page-size 另行注册)
|
|
543
|
+
const businessProps = Object.fromEntries(Object.entries(props).filter(([name]) => name !== pageArg && name !== sizeArg));
|
|
544
|
+
const commandPath = ['producer', ...path, action.id].join(' ');
|
|
545
|
+
const isWorkflow = action.workflow === true;
|
|
546
|
+
const isWrite = action.contract.effect === 'write';
|
|
547
|
+
const intent = action.intent;
|
|
548
|
+
const cmd = parent.command(action.id).description(`${action.title} — ${action.summary}`);
|
|
549
|
+
cmd.addHelpText('after', () => renderContractHelp(action));
|
|
550
|
+
if (isWrite)
|
|
551
|
+
cmd.addHelpText('after', () => renderParametersHelp(action));
|
|
552
|
+
cmd.addHelpText('after', () => renderWorkflowHelp(action));
|
|
553
|
+
cmd.addHelpText('after', () => purchaseRefundHelp(action.contract.operation_id, { intent: Boolean(action.intent) }));
|
|
554
|
+
if (action.shortcuts?.length)
|
|
555
|
+
cmd.addHelpText('after', () => renderShortcuts(action));
|
|
556
|
+
if (isWorkflow) {
|
|
557
|
+
for (const [name, schema] of Object.entries(businessProps)) {
|
|
558
|
+
const hint = typeHint(schema);
|
|
559
|
+
if (hint === '')
|
|
560
|
+
cmd.option(flagName(name), schema.description ?? '');
|
|
561
|
+
else
|
|
562
|
+
cmd.option(`${flagName(name)} <${hint}>`, schema.description ?? '');
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
else if (isWrite) {
|
|
566
|
+
writeCommands.add(cmd);
|
|
567
|
+
cmd.addHelpText('after', () => renderIdSources(input));
|
|
568
|
+
const paramsOption = action.contract.operation_id === EXPORT_RECORD_DOWNLOAD
|
|
569
|
+
? cmd.option.bind(cmd)
|
|
570
|
+
: cmd.requiredOption.bind(cmd);
|
|
571
|
+
paramsOption('--params <json|file|->', 'JSON 参数、JSON 文件路径或 -(从 stdin 读取)');
|
|
572
|
+
if (actionSupportsDraft(action)) {
|
|
573
|
+
cmd.option('--draft', '保存为草稿单');
|
|
574
|
+
}
|
|
575
|
+
if (action.contract.operation_id === EXPORT_RECORD_DOWNLOAD) {
|
|
576
|
+
cmd.option('--wait', '自动等待导出完成(--out 已默认等待)');
|
|
577
|
+
cmd.option('--key <int>', '触发导出返回的 data.export_key(与 record_id 二选一)', parsePositiveInteger);
|
|
578
|
+
cmd.option('--out <file>', '等待完成并下载到本地文件(不覆盖已有文件)');
|
|
579
|
+
cmd.option('--poll-interval <seconds>', '轮询间隔秒数(默认 3.3,与前端一致)', parsePositiveNumber);
|
|
580
|
+
cmd.option('--wait-timeout <seconds>', '等待导出完成的上限秒数(默认 120)', parsePositiveNumber);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
if (dateRangeArgs(businessProps))
|
|
585
|
+
lastWindowCommands.add(cmd);
|
|
586
|
+
for (const [name, schema] of Object.entries(businessProps)) {
|
|
587
|
+
const flag = flagName(name);
|
|
588
|
+
const parameter = cliParameters.find((item) => item.input_name === name);
|
|
589
|
+
const hint = parameter?.value_hint ?? typeHint(schema);
|
|
590
|
+
const desc = parameter?.help ?? schema.description ?? '';
|
|
591
|
+
if (hint === '')
|
|
592
|
+
cmd.option(flag, desc);
|
|
593
|
+
else
|
|
594
|
+
cmd.option(`${flag} <${hint}>`, desc);
|
|
595
|
+
}
|
|
596
|
+
if (pagination) {
|
|
597
|
+
const page = cliParameters.find((item) => item.flag === '--page');
|
|
598
|
+
const pageSize = cliParameters.find((item) => item.flag === '--page-size');
|
|
599
|
+
cmd.option('--all', '自动翻页获取全部数据(与 --page 互斥)', false);
|
|
600
|
+
cmd.option('--page <int>', page?.help ?? '指定页码(指定后只取单页)', parsePositiveInteger);
|
|
601
|
+
cmd.option('--page-size <int>', pageSize?.help ?? '每页条数(--all 时作为每页大小)', parsePositiveInteger);
|
|
602
|
+
}
|
|
603
|
+
// 编辑基线:详情命令声明了写 operation 时,输出可直接用于 update 的完整替换输入。
|
|
604
|
+
if (action.contract.edit_source?.write_operation_id) {
|
|
605
|
+
cmd.option('--editable', '输出可用于 update 的完整替换输入(整替换,非部分更新)', false);
|
|
606
|
+
cmd.option('--out <file>', '把可编辑基线写入文件而不是打印到 stdout');
|
|
607
|
+
// 详情除 id 之外还必填的上下文参数(如经营目标的期间、加工厂)——详情读不出来就没法给基线。
|
|
608
|
+
// 这些参数通常就是详情自身的入参,上面的 flag 已注册过,重复注册会被 commander 判为冲突。
|
|
609
|
+
for (const name of action.contract.edit_source?.detail_arguments ?? []) {
|
|
610
|
+
if (name in businessProps)
|
|
611
|
+
continue;
|
|
612
|
+
cmd.option(`${flagName(name)} <value>`, `读取编辑基线所需:${name}(用 --editable 时必填)`);
|
|
613
|
+
}
|
|
614
|
+
cmd.addHelpText('after', () => `\n编辑基线:\n 本命令是 ${action.contract.edit_source?.write_operation_id} 的编辑源;\n --editable 会按该写 operation 的参数 schema 裁剪详情,输出可直接提交的整替换输入。\n 基线缺少写 operation 的必填字段时失败关闭并列出缺失字段;写侧保持整替换语义,不做部分更新。\n`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
cmd.addHelpText('after', () => renderPreflightHelp(action));
|
|
618
|
+
cmd.addHelpText('after', () => renderExamples(commandPath, action, isWrite));
|
|
619
|
+
cmd.addHelpText('after', () => renderReadbackHelp(action));
|
|
620
|
+
cmd.addHelpText('after', () => renderRecoveryHelp(action));
|
|
621
|
+
cmd.action(async (options) => {
|
|
622
|
+
if (isWorkflow) {
|
|
623
|
+
const params = {};
|
|
624
|
+
for (const [name, schema] of Object.entries(businessProps)) {
|
|
625
|
+
const raw = options[optionKey(name)];
|
|
626
|
+
if (raw === undefined || raw === false)
|
|
627
|
+
continue;
|
|
628
|
+
if (isBooleanEnum(schema))
|
|
629
|
+
params[name] = 1;
|
|
630
|
+
else
|
|
631
|
+
params[name] =
|
|
632
|
+
schema.type === 'boolean' ? true : coerceFlagValue(schema, String(raw));
|
|
633
|
+
}
|
|
634
|
+
const planner = action.workflow_contract?.planner;
|
|
635
|
+
if (!planner)
|
|
636
|
+
throw new Error(`workflow 缺少 planner: ${commandPath}`);
|
|
637
|
+
const executor = workflowExecutor(planner);
|
|
638
|
+
const shopRef = resolveShopRef();
|
|
639
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef }));
|
|
640
|
+
const signal = timeoutSignal();
|
|
641
|
+
renderOutput(await executor(sdk, params, {
|
|
642
|
+
...(signal ? { signal } : {}),
|
|
643
|
+
...(shopRef !== undefined ? { shopRef } : {}),
|
|
644
|
+
}));
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
if (isWrite) {
|
|
648
|
+
// 写命令:--params 支持内联 JSON、JSON 文件路径或 stdin(-);--yes 是统一确认门。
|
|
649
|
+
const isExportDownload = action.contract.operation_id === EXPORT_RECORD_DOWNLOAD;
|
|
650
|
+
const params = readParams(options.params ?? (isExportDownload ? '{}' : undefined), ctx.readStdin);
|
|
651
|
+
const waitForDownload = isExportDownload && (options.wait === true || typeof options.out === 'string');
|
|
652
|
+
if (isExportDownload) {
|
|
653
|
+
const hasKey = options.key !== undefined;
|
|
654
|
+
const hasRecord = params.record_id !== undefined;
|
|
655
|
+
if (hasKey === hasRecord)
|
|
656
|
+
throw new CliError('record_id 与 --key 必须且只能提供一个', 'validation', 'export_target_required');
|
|
657
|
+
if (hasKey && !waitForDownload)
|
|
658
|
+
throw new CliError('--key 需搭配 --wait 或 --out', 'validation', 'export_wait_required');
|
|
659
|
+
if (hasKey && Object.keys(params).length)
|
|
660
|
+
throw new CliError('--key 不能与下载登记参数混用', 'validation', 'export_target_conflict');
|
|
661
|
+
}
|
|
662
|
+
if (actionSupportsDraft(action) && options.draft === true)
|
|
663
|
+
params.draft = true;
|
|
664
|
+
// 意图命令(purchase material/auxiliary/product create|edit)有两种提交形态:
|
|
665
|
+
// 1) 意图入参(category_id/supplier_id/items…)→ 走 planner 派生整单;
|
|
666
|
+
// 2) `<详情> --editable` 输出的整替换基线(目标 operation 的原始参数)→ 按 operation 直接提交。
|
|
667
|
+
// 这是「详情 --editable → 改 → 提交」这条路在采购单上唯一的可用形态:planner 是整单重写,
|
|
668
|
+
// 只带意图声明过的字段,会丢掉 remark_img、车牌、地址、批次、资金账户与手录费用。
|
|
669
|
+
// 形态按合同 schema 判定:先按意图合同校验,不通过再看是否满足目标 operation 合同。
|
|
670
|
+
const baseline = intent ? fullContractOf(intent.target_operation_id) : undefined;
|
|
671
|
+
// 原始 wire 回退只允许编辑基线场景(update 动作,或目标 operation 声明了 edit_source):
|
|
672
|
+
// 创建/预填意图收到原始 wire 时说明调用方拿错了入参形态,必须拒绝而不是静默按 operation 提交。
|
|
673
|
+
const wireFallbackAllowed = action.id === 'update' || Boolean(baseline?.edit_source);
|
|
674
|
+
const submitAsIntent = (() => {
|
|
675
|
+
if (!intent || !baseline?.input)
|
|
676
|
+
return true;
|
|
677
|
+
try {
|
|
678
|
+
validateInput(input, params, action.contract.operation_id);
|
|
679
|
+
return true;
|
|
680
|
+
}
|
|
681
|
+
catch (intentError) {
|
|
682
|
+
if (!baseline.input)
|
|
683
|
+
throw intentError;
|
|
684
|
+
try {
|
|
685
|
+
validateInput(baseline.input, params, intent.target_operation_id);
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
throw intentError;
|
|
689
|
+
}
|
|
690
|
+
if (!wireFallbackAllowed)
|
|
691
|
+
throw new CliError(`${commandPath} 只接受意图入参,不能提交目标 operation 的原始 wire;请按 \`producer schema ${path.join(' ')} ${action.id}\` 的 input_schema 传入业务意图参数。`, 'validation', 'intent_input_required');
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
})();
|
|
695
|
+
if (submitAsIntent && !(waitForDownload && options.key !== undefined)) {
|
|
696
|
+
const missing = required.filter((key) => !(key in params));
|
|
697
|
+
if (missing.length)
|
|
698
|
+
throw new CliError(`缺少必填参数: ${missing.map(flagName).join(', ')}。执行 \`${commandPath} --help\` 查看完整参数。`, 'validation', 'missing_required_parameter');
|
|
699
|
+
validateInput(input, params, action.contract.operation_id);
|
|
700
|
+
validateConstraints(action.contract.constraints, params, action.contract.operation_id);
|
|
701
|
+
}
|
|
702
|
+
else if (!submitAsIntent) {
|
|
703
|
+
validateConstraints(baseline?.constraints, params, intent?.target_operation_id ?? action.contract.operation_id);
|
|
704
|
+
}
|
|
705
|
+
if (globals().yes !== true)
|
|
706
|
+
throw CliError.confirmationRequired(commandPath);
|
|
707
|
+
if (intent && submitAsIntent) {
|
|
708
|
+
const intentShopRef = resolveShopRef();
|
|
709
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef: intentShopRef }));
|
|
710
|
+
const signal = timeoutSignal();
|
|
711
|
+
await assertCapabilityAvailable(sdk, intent.target_operation_id, requireShopRef(intentShopRef), signal, baseline);
|
|
712
|
+
renderOutput(await sdk.planner.run(intent.planner, params, {
|
|
713
|
+
...(signal ? { signal } : {}),
|
|
714
|
+
...(intentShopRef !== undefined ? { shopRef: intentShopRef } : {}),
|
|
715
|
+
}));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
const shopRef = resolveShopRef();
|
|
719
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef }));
|
|
720
|
+
const operationId = intent?.target_operation_id ?? action.contract.operation_id;
|
|
721
|
+
const executor = getCommandExecutor(sdk.commands, operationId);
|
|
722
|
+
if (!executor)
|
|
723
|
+
throw new Error(`no command executor for operation ${operationId}`);
|
|
724
|
+
const signal = timeoutSignal();
|
|
725
|
+
await assertCapabilityAvailable(sdk, operationId, requireShopRef(shopRef), signal, intent ? baseline : action.contract);
|
|
726
|
+
// SDK 拥有销售单辅料重算(含详情重读)与采退库存规则;CLI 只按 planner/operation 触发。
|
|
727
|
+
if (intent?.planner === 'sales.order.update')
|
|
728
|
+
await refreshSalesOrderPackageMaterials(sdk.commands, params, {
|
|
729
|
+
...(signal ? { signal } : {}),
|
|
730
|
+
...(shopRef !== undefined ? { shopRef } : {}),
|
|
731
|
+
});
|
|
732
|
+
if (operationId === PURCHASE_REFUND_CREATE)
|
|
733
|
+
await validatePurchaseRefundStock(sdk.commands, params, {
|
|
734
|
+
...(signal ? { signal } : {}),
|
|
735
|
+
});
|
|
736
|
+
if (waitForDownload) {
|
|
737
|
+
const waitOptions = {
|
|
738
|
+
...(typeof params.record_id === 'number' ? { recordId: params.record_id } : {}),
|
|
739
|
+
...(typeof options.key === 'number' ? { key: options.key } : {}),
|
|
740
|
+
...(typeof options.pollInterval === 'number'
|
|
741
|
+
? { pollIntervalMs: options.pollInterval * 1000 }
|
|
742
|
+
: {}),
|
|
743
|
+
...(typeof options.waitTimeout === 'number'
|
|
744
|
+
? { timeoutMs: options.waitTimeout * 1000 }
|
|
745
|
+
: {}),
|
|
746
|
+
...(signal ? { signal } : {}),
|
|
747
|
+
...(shopRef !== undefined ? { shopRef } : {}),
|
|
748
|
+
};
|
|
749
|
+
if (typeof options.out === 'string') {
|
|
750
|
+
const record = await sdk.exportRecord.waitForExportRecord({
|
|
751
|
+
...waitOptions,
|
|
752
|
+
requireDownloadUrl: true,
|
|
753
|
+
});
|
|
754
|
+
const file = await downloadExportFile(record.download_url, options.out, {
|
|
755
|
+
fetch: ctx.fetch,
|
|
756
|
+
signal: signal ?? AbortSignal.timeout(120_000),
|
|
757
|
+
});
|
|
758
|
+
try {
|
|
759
|
+
await executor({ record_id: record.id }, signal ? { signal } : undefined);
|
|
760
|
+
}
|
|
761
|
+
catch {
|
|
762
|
+
throw new CliError('文件已保存,但下载登记失败', 'api', 'export_registration_failed', undefined, undefined, { file });
|
|
763
|
+
}
|
|
764
|
+
renderOutput({ ok: true, file, record_id: record.id });
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const { record, download } = await sdk.exportRecord.waitAndDownload(waitOptions);
|
|
768
|
+
renderOutput({ ...download, export_record: record });
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
renderOutput(await executor(params, signal ? { signal } : undefined));
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
const params = {};
|
|
775
|
+
for (const [name, schema] of Object.entries(businessProps)) {
|
|
776
|
+
const raw = options[optionKey(name)];
|
|
777
|
+
if (raw === undefined || raw === false)
|
|
778
|
+
continue;
|
|
779
|
+
if (isBooleanEnum(schema))
|
|
780
|
+
params[name] = 1;
|
|
781
|
+
else
|
|
782
|
+
params[name] = schema.type === 'boolean' ? true : coerceFlagValue(schema, String(raw));
|
|
783
|
+
}
|
|
784
|
+
// --last 相对时间窗:展开为日期范围;与显式日期 flag 互斥
|
|
785
|
+
const lastSpec = globals().last;
|
|
786
|
+
if (lastSpec) {
|
|
787
|
+
const rangeArgs = dateRangeArgs(props);
|
|
788
|
+
if (!rangeArgs)
|
|
789
|
+
throw new CliError('当前命令没有日期范围参数,--last 不适用', 'validation', 'flag_value_invalid');
|
|
790
|
+
const [startName, endName] = rangeArgs;
|
|
791
|
+
if (options[optionKey(startName)] !== undefined ||
|
|
792
|
+
options[optionKey(endName)] !== undefined)
|
|
793
|
+
throw new CliError(`--last 与 --${startName.replace(/_/g, '-')}/--${endName.replace(/_/g, '-')} 互斥,二选一`, 'validation', 'flag_value_invalid');
|
|
794
|
+
const window = lastWindow(lastSpec);
|
|
795
|
+
params[startName] = window.from_date;
|
|
796
|
+
params[endName] = window.to_date;
|
|
797
|
+
}
|
|
798
|
+
const shopRef = resolveShopRef();
|
|
799
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef }));
|
|
800
|
+
const missing = required.filter((key) => !(key in params));
|
|
801
|
+
if (missing.length)
|
|
802
|
+
throw new CliError(`缺少必填参数: ${missing.map(flagName).join(', ')}。执行 \`${commandPath} --help\` 查看完整参数。`, 'validation', 'missing_required_parameter');
|
|
803
|
+
if (options.editable === true) {
|
|
804
|
+
const source = action.contract.edit_source;
|
|
805
|
+
if (!source?.write_operation_id || !source.id_argument)
|
|
806
|
+
throw new CliError(`${commandPath} 未声明编辑源,无法输出可编辑基线。`, 'validation', 'edit_source_missing');
|
|
807
|
+
const baselineSignal = timeoutSignal();
|
|
808
|
+
// 详情额外必填参数:数值型就地转成 number(flag 只能给字符串),其余原样透传。
|
|
809
|
+
const detailArguments = {};
|
|
810
|
+
for (const name of source.detail_arguments ?? []) {
|
|
811
|
+
const raw = options[optionKey(name)];
|
|
812
|
+
if (raw === undefined)
|
|
813
|
+
continue;
|
|
814
|
+
const text = String(raw);
|
|
815
|
+
detailArguments[name] = text !== '' && !Number.isNaN(Number(text)) ? Number(text) : raw;
|
|
816
|
+
}
|
|
817
|
+
const baseline = await sdk.editBaseline.editableBaseline(source.write_operation_id, params[source.id_argument], {
|
|
818
|
+
detailArguments,
|
|
819
|
+
...(baselineSignal ? { signal: baselineSignal } : {}),
|
|
820
|
+
...(shopRef !== undefined ? { shopRef } : {}),
|
|
821
|
+
});
|
|
822
|
+
const text = `${JSON.stringify(baseline, null, 2)}\n`;
|
|
823
|
+
if (typeof options.out === 'string')
|
|
824
|
+
writeFileSync(options.out, text, 'utf8');
|
|
825
|
+
else
|
|
826
|
+
renderOutput(baseline);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
validateConstraints(action.contract.constraints, params, action.contract.operation_id);
|
|
830
|
+
// 读命令不做能力预检,但店铺引用仍是业务查询的本地前置条件。
|
|
831
|
+
requireShopRef(shopRef);
|
|
832
|
+
const executor = getCommandExecutor(sdk.commands, action.contract.operation_id);
|
|
833
|
+
if (!executor)
|
|
834
|
+
throw new Error(`no command executor for operation ${action.contract.operation_id}`);
|
|
835
|
+
const signal = timeoutSignal();
|
|
836
|
+
renderOutput(await executePaginated(executor, pagination, params, options.page, options.pageSize, options.all === true, pageBase, props[sizeArg ?? '']?.maximum ?? 100, signal));
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
// 根 help 分组:业务能力包在前、工具命令在后。组顺序取自子命令注册顺序
|
|
841
|
+
//(commander 的 groupItems 按 program.commands 的出现顺序建组),故业务命令必须先注册。
|
|
842
|
+
program.commandsGroup('业务命令:');
|
|
843
|
+
const root = resolveSchema([]);
|
|
844
|
+
for (const capability of root.resources ?? []) {
|
|
845
|
+
const child = program
|
|
846
|
+
.command(capability.id)
|
|
847
|
+
.description(`${capability.title} — ${capability.summary}`);
|
|
848
|
+
registerNode(child, [capability.id], capability);
|
|
849
|
+
}
|
|
850
|
+
program.commandsGroup('工具命令:');
|
|
851
|
+
program
|
|
852
|
+
.command('version')
|
|
853
|
+
.description('显示 producer CLI 版本与发布通道')
|
|
854
|
+
.action(() => {
|
|
855
|
+
const version = currentCliVersion();
|
|
856
|
+
renderOutput({
|
|
857
|
+
package: CLI_PACKAGE_NAME,
|
|
858
|
+
version,
|
|
859
|
+
channel: resolveChannel(version, ctx.env ?? process.env),
|
|
860
|
+
catalog_revision: CATALOG_REVISION,
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
program
|
|
864
|
+
.command('upgrade')
|
|
865
|
+
.description('检查并升级 producer CLI 到当前发布通道最新版本')
|
|
866
|
+
.option('--check', '只检查版本,不执行安装', false)
|
|
867
|
+
.option('--rollback', '切回上一个版本', false)
|
|
868
|
+
.option('--bootstrap-only', '内部:仅把当前 bundle 安装到 launcher 根,不访问 registry', false)
|
|
869
|
+
.action(async (options) => {
|
|
870
|
+
const env = ctx.env ?? process.env;
|
|
871
|
+
const current = currentCliVersion();
|
|
872
|
+
const entryPath = realpathSync(process.argv[1] ?? '');
|
|
873
|
+
const root = env.PRODUCER_CLI_INSTALL_ROOT ?? installRoot(process.platform, env);
|
|
874
|
+
let form = detectForm({
|
|
875
|
+
env,
|
|
876
|
+
entryPath,
|
|
877
|
+
root: env.PRODUCER_CLI_INSTALL_ROOT,
|
|
878
|
+
globalRoot: globalRootOrUndefined(),
|
|
879
|
+
});
|
|
880
|
+
// 首次安装:运行单文件 bundle 时把自身落到安装根并写 current 指针。它只做本地拷贝,
|
|
881
|
+
// 不访问 registry,必须早于自更新开关;否则停用自更新会连带阻断应用内置 bundle 落盘。
|
|
882
|
+
let bootstrap;
|
|
883
|
+
if (!options.check && form !== 'launcher' && basename(entryPath) === 'main.mjs') {
|
|
884
|
+
bootstrap = bootstrapInstall({
|
|
885
|
+
root,
|
|
886
|
+
entryPath,
|
|
887
|
+
version: current,
|
|
888
|
+
runtime: process.execPath,
|
|
889
|
+
});
|
|
890
|
+
form = 'launcher';
|
|
891
|
+
}
|
|
892
|
+
// seed 可能因内置版本低于 current 而保留升级结果;后续判断与输出以实际生效版本为准。
|
|
893
|
+
const effectiveCurrent = bootstrap?.current ?? current;
|
|
894
|
+
if (options.bootstrapOnly) {
|
|
895
|
+
renderOutput({
|
|
896
|
+
package: CLI_PACKAGE_NAME,
|
|
897
|
+
current: effectiveCurrent,
|
|
898
|
+
channel: resolveChannel(effectiveCurrent, env),
|
|
899
|
+
bootstrap_only: true,
|
|
900
|
+
updated: false,
|
|
901
|
+
...(bootstrap?.skipped ? { skipped: true } : {}),
|
|
902
|
+
});
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (!SELF_UPDATE_ENABLED) {
|
|
906
|
+
renderOutput({
|
|
907
|
+
package: CLI_PACKAGE_NAME,
|
|
908
|
+
current: effectiveCurrent,
|
|
909
|
+
channel: resolveChannel(effectiveCurrent, env),
|
|
910
|
+
updated: false,
|
|
911
|
+
message: UPGRADE_DISABLED_MESSAGE,
|
|
912
|
+
});
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
const tag = resolveChannel(effectiveCurrent, env);
|
|
916
|
+
const managed = () => new CliError('当前为应用内置运行时,请通过应用升级', 'validation', 'upgrade_managed_runtime', '内置版本随 Desktop 安装包更新。');
|
|
917
|
+
const notGlobal = () => new CliError('producer 不是全局安装,无法自动升级', 'validation', 'upgrade_not_global', '源码或 npx 副本请手动更新。');
|
|
918
|
+
if (options.rollback && form !== 'launcher')
|
|
919
|
+
throw notGlobal();
|
|
920
|
+
if (options.rollback) {
|
|
921
|
+
const result = rollbackRelease(root);
|
|
922
|
+
renderOutput({
|
|
923
|
+
package: CLI_PACKAGE_NAME,
|
|
924
|
+
current: result.current,
|
|
925
|
+
previous: result.previous,
|
|
926
|
+
channel: resolveChannel(result.current, env),
|
|
927
|
+
updated: false,
|
|
928
|
+
});
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
if (form === 'embedded' && !options.check)
|
|
932
|
+
throw managed();
|
|
933
|
+
// 未显式选择环境时回退到安装 tarball 的 publishConfig.registry(npm 与 launcher 一致)。
|
|
934
|
+
const registry = resolveRegistry(root, env, installedPackageRegistry());
|
|
935
|
+
if (form === 'npm' || form === 'source') {
|
|
936
|
+
const latest = latestCliVersion(tag, registry);
|
|
937
|
+
if (options.check || latest === current) {
|
|
938
|
+
renderOutput({
|
|
939
|
+
package: CLI_PACKAGE_NAME,
|
|
940
|
+
current,
|
|
941
|
+
latest,
|
|
942
|
+
channel: tag,
|
|
943
|
+
updated: false,
|
|
944
|
+
catalog_revision: CATALOG_REVISION,
|
|
945
|
+
});
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
if (!isValidVersion(latest))
|
|
949
|
+
throw new CliError('registry 返回了非法版本号', 'internal', 'upgrade_payload_invalid');
|
|
950
|
+
// tag 落后于本地已装版本时不降级;降级需显式 --rollback。
|
|
951
|
+
if (compareVersions(latest, current) <= 0) {
|
|
952
|
+
renderOutput({
|
|
953
|
+
package: CLI_PACKAGE_NAME,
|
|
954
|
+
current,
|
|
955
|
+
latest,
|
|
956
|
+
channel: tag,
|
|
957
|
+
updated: false,
|
|
958
|
+
catalog_revision: CATALOG_REVISION,
|
|
959
|
+
});
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
assertGlobalInstall(CLI_PACKAGE_NAME, cliPackageRoot(), npmGlobalRoot());
|
|
963
|
+
const spawn = npmSpawn(npmExecutable(), [
|
|
964
|
+
'install',
|
|
965
|
+
'-g',
|
|
966
|
+
`${CLI_PACKAGE_NAME}@${latest}`,
|
|
967
|
+
'--registry',
|
|
968
|
+
registry,
|
|
969
|
+
]);
|
|
970
|
+
execFileSync(spawn.file, spawn.args, { stdio: 'inherit', shell: spawn.shell });
|
|
971
|
+
renderOutput({ package: CLI_PACKAGE_NAME, current, latest, channel: tag, updated: true });
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
if (options.check) {
|
|
975
|
+
const { latest } = await checkForUpdate({
|
|
976
|
+
root,
|
|
977
|
+
current: effectiveCurrent,
|
|
978
|
+
registry,
|
|
979
|
+
channel: tag,
|
|
980
|
+
});
|
|
981
|
+
renderOutput({
|
|
982
|
+
package: CLI_PACKAGE_NAME,
|
|
983
|
+
current: effectiveCurrent,
|
|
984
|
+
latest,
|
|
985
|
+
channel: tag,
|
|
986
|
+
updated: false,
|
|
987
|
+
catalog_revision: CATALOG_REVISION,
|
|
988
|
+
});
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
const result = await installRelease({
|
|
992
|
+
root,
|
|
993
|
+
current: effectiveCurrent,
|
|
994
|
+
registry,
|
|
995
|
+
channel: tag,
|
|
996
|
+
log: (line) => write(`${line}\n`),
|
|
997
|
+
});
|
|
998
|
+
renderOutput({
|
|
999
|
+
package: CLI_PACKAGE_NAME,
|
|
1000
|
+
current: result.updated ? effectiveCurrent : result.version,
|
|
1001
|
+
latest: result.version,
|
|
1002
|
+
channel: tag,
|
|
1003
|
+
updated: result.updated,
|
|
1004
|
+
});
|
|
1005
|
+
});
|
|
1006
|
+
program
|
|
1007
|
+
.command('schema')
|
|
1008
|
+
.description('渐进式查看 Producer 能力契约')
|
|
1009
|
+
.usage('[command path] [options]')
|
|
1010
|
+
.addHelpText('before', () => 'Examples:\n' +
|
|
1011
|
+
' producer schema --compact\n' +
|
|
1012
|
+
' producer schema fund --compact\n' +
|
|
1013
|
+
' producer schema sales order create --format json\n' +
|
|
1014
|
+
' producer schema --cli-path "sales order create" --compact\n')
|
|
1015
|
+
.argument('[command path...]', '能力包、资源或动作路径;不传路径查看能力包摘要')
|
|
1016
|
+
.option('--cli-path <path>', '按完整 CLI 路径查询叶子契约')
|
|
1017
|
+
.option('--compact', '只输出 Agent 选命令所需的稳定契约字段')
|
|
1018
|
+
.option('--all', '输出全部可见叶子契约,用于审计和基线')
|
|
1019
|
+
.addHelpText('after', () => '\n说明:\n' +
|
|
1020
|
+
' 不带路径时输出能力包摘要;指定能力包或资源时逐层展开。\n' +
|
|
1021
|
+
' --compact 只输出 Agent 选命令所需的稳定字段;--all 用于完整审计。\n' +
|
|
1022
|
+
' 升级 producer CLI 使用 `producer upgrade`;桌面内置版本随森果云AI助手更新。\n')
|
|
1023
|
+
.action((path, options) => {
|
|
1024
|
+
const selected = options.cliPath
|
|
1025
|
+
? options.cliPath.split(/\s+/).filter(Boolean)
|
|
1026
|
+
: (path ?? []);
|
|
1027
|
+
renderOutput(schemaValueWithOptions(selected, options));
|
|
1028
|
+
});
|
|
1029
|
+
const shop = program.command('shop').description('店铺');
|
|
1030
|
+
shop
|
|
1031
|
+
.command('list')
|
|
1032
|
+
.description('列出已授权店铺')
|
|
1033
|
+
.action(async () => {
|
|
1034
|
+
// producer_shops_list 只依赖凭据,不依赖当前店铺:首次使用(尚无 shop_ref)也必须可用。
|
|
1035
|
+
const sdk = createClient(clientConfig({ ...ctx }));
|
|
1036
|
+
const signal = timeoutSignal();
|
|
1037
|
+
renderOutput(await sdk.shop.list(signal ? { signal } : undefined));
|
|
1038
|
+
});
|
|
1039
|
+
shop
|
|
1040
|
+
.command('current')
|
|
1041
|
+
.description('查询当前店铺')
|
|
1042
|
+
.action(async () => {
|
|
1043
|
+
const sdk = createClient(clientConfig({ ...ctx }));
|
|
1044
|
+
const signal = timeoutSignal();
|
|
1045
|
+
const shops = (await sdk.shop.list(signal ? { signal } : undefined)).shops;
|
|
1046
|
+
const ref = readShopRef(ctx.shopFile);
|
|
1047
|
+
const shop = shops.find((item) => item.shop_ref === ref) ?? null;
|
|
1048
|
+
renderOutput(shop ? { shop_ref: shop.shop_ref, shop_name: shop.shop_name } : null);
|
|
1049
|
+
});
|
|
1050
|
+
shop
|
|
1051
|
+
.command('use')
|
|
1052
|
+
.description('设置当前店铺(持久化)')
|
|
1053
|
+
.argument('<ref>', '店铺引用')
|
|
1054
|
+
.action(async (ref) => {
|
|
1055
|
+
const sdk = createClient(clientConfig({ ...ctx }));
|
|
1056
|
+
const signal = timeoutSignal();
|
|
1057
|
+
const shops = (await sdk.shop.list(signal ? { signal } : undefined)).shops;
|
|
1058
|
+
const shop = shops.find((item) => item.shop_ref === ref);
|
|
1059
|
+
if (!shop)
|
|
1060
|
+
throw new CliError(`店铺引用不可用:${ref},请先执行 producer shop list`, 'validation', 'shop_ref_unavailable');
|
|
1061
|
+
writeShopRef(ref, ctx.shopFile);
|
|
1062
|
+
renderOutput(shop);
|
|
1063
|
+
});
|
|
1064
|
+
program
|
|
1065
|
+
.command('status')
|
|
1066
|
+
.description('查询当前用户、环境、店铺和业务上下文')
|
|
1067
|
+
.action(async () => {
|
|
1068
|
+
const config = clientConfig({ ...ctx });
|
|
1069
|
+
const sdk = createClient(config);
|
|
1070
|
+
const signal = timeoutSignal();
|
|
1071
|
+
const ref = readShopRef(ctx.shopFile);
|
|
1072
|
+
if (!ref)
|
|
1073
|
+
throw new CliError('未设置当前店铺,请先执行 `producer shop use <ref>`', 'validation', 'shop_ref_required');
|
|
1074
|
+
const available = (await sdk.shop.list(signal ? { signal } : undefined)).shops.some((shop) => shop.shop_ref === ref);
|
|
1075
|
+
if (!available)
|
|
1076
|
+
throw new CliError(`当前店铺不可用:${ref},请先执行 producer shop list`, 'validation', 'shop_ref_unavailable');
|
|
1077
|
+
const context = await sdk.context.current({ shopRef: ref, ...(signal ? { signal } : {}) });
|
|
1078
|
+
renderOutput({
|
|
1079
|
+
environment: { mcp_url: config.url },
|
|
1080
|
+
...context,
|
|
1081
|
+
});
|
|
1082
|
+
});
|
|
1083
|
+
const check = program.command('check').description('能力预检(权限+开关)');
|
|
1084
|
+
check
|
|
1085
|
+
.argument('<capability>', '能力包')
|
|
1086
|
+
.argument('<resource>', '资源')
|
|
1087
|
+
.argument('<action>', '动作')
|
|
1088
|
+
.action(async (capability, resource, action) => {
|
|
1089
|
+
const resolved = resolveSchema([capability, resource, action]);
|
|
1090
|
+
if (!('contract' in resolved))
|
|
1091
|
+
throw new Error('未找到该叶子动作,请检查路径');
|
|
1092
|
+
const operationId = resolved.contract.operation_id;
|
|
1093
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef: requireShopRef() }));
|
|
1094
|
+
const signal = timeoutSignal();
|
|
1095
|
+
renderOutput(await sdk.check(operationId, signal ? { signal } : undefined));
|
|
1096
|
+
});
|
|
1097
|
+
const contract = program
|
|
1098
|
+
.command('contract')
|
|
1099
|
+
.description('只读查询 ai-platform 当前 Operation 契约');
|
|
1100
|
+
contract
|
|
1101
|
+
.command('diagnose')
|
|
1102
|
+
.description('查询服务端当前字段、绑定与 contract revision;不会执行写入')
|
|
1103
|
+
.argument('<operation-id>', 'Operation ID,例如 producer.sales.order.create')
|
|
1104
|
+
.action(async (operationId) => {
|
|
1105
|
+
const sdk = createClient(clientConfig({ ...ctx }));
|
|
1106
|
+
const signal = timeoutSignal();
|
|
1107
|
+
const result = await sdk.describeContract(operationId, signal ? { signal } : undefined);
|
|
1108
|
+
renderOutput({
|
|
1109
|
+
...result,
|
|
1110
|
+
...(typeof result.next_step === 'string'
|
|
1111
|
+
? { next_step: cliNextStep(result.next_step, operationId) }
|
|
1112
|
+
: {}),
|
|
1113
|
+
});
|
|
1114
|
+
});
|
|
1115
|
+
// 通用上传:能力在 ProducersSDK(client.upload)——取 MCP 工具 producer_upload_prepare 的上传参数
|
|
1116
|
+
// (服务端决定 key/bucket/域名)→ 字节直传对象存储 → 返回可写进单据的 key(多图逗号拼接)。
|
|
1117
|
+
const upload = program
|
|
1118
|
+
.command('upload')
|
|
1119
|
+
.description('通用上传:图片/文件上传到对象存储,返回可写入单据的 key');
|
|
1120
|
+
for (const verb of ['image', 'file']) {
|
|
1121
|
+
upload
|
|
1122
|
+
.command(verb)
|
|
1123
|
+
.description(verb === 'image' ? '上传图片' : '上传文件')
|
|
1124
|
+
.requiredOption('--file <path>', '本地文件路径')
|
|
1125
|
+
.option('--upload-host <url>', '上传域名;默认使用服务端返回的 upload_url')
|
|
1126
|
+
.action(async (options) => {
|
|
1127
|
+
const shopRef = requireShopRef();
|
|
1128
|
+
const sdk = createClient(clientConfig({ ...ctx, shopRef }));
|
|
1129
|
+
const host = options.uploadHost ?? process.env.QINIU_UPLOAD_HOST;
|
|
1130
|
+
const asset = await uploadAsset({
|
|
1131
|
+
filePath: options.file,
|
|
1132
|
+
shopRef,
|
|
1133
|
+
api: sdk.upload,
|
|
1134
|
+
kind: verb,
|
|
1135
|
+
...(host !== undefined ? { uploadHost: host } : {}),
|
|
1136
|
+
});
|
|
1137
|
+
renderOutput({ ok: true, outcome: 'success', upload: asset });
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
// help 自动命令显式创建,归入当前默认组(工具命令)
|
|
1141
|
+
program.helpCommand('help [command]', 'display help for command');
|
|
1142
|
+
// 根 help 底部升级提示:仅在根 help 渲染,子命令 help 不重复。
|
|
1143
|
+
program.addHelpText('after', '\nNext: 使用 "producer <command> --help" 查看命令详情,使用 "producer schema --compact" 查看能力契约。\n\n' +
|
|
1144
|
+
'提示: 如果遇到能力缺失、命令报错、新功能未注册,或工具契约版本(contract_revision)与服务端不一致(报错 CATALOG_REVISION_MISMATCH),请先执行 `producer upgrade`;桌面内置版本请升级森果云AI助手。\n');
|
|
1145
|
+
return program;
|
|
1146
|
+
}
|
|
1147
|
+
export async function run(argv = process.argv.slice(2), ctx = {}) {
|
|
1148
|
+
const cleanupEnv = ctx.env ?? process.env;
|
|
1149
|
+
const first = argv[0];
|
|
1150
|
+
if (cleanupEnv.PRODUCER_CLI_INSTALL_ROOT && first !== 'install' && first !== 'upgrade') {
|
|
1151
|
+
try {
|
|
1152
|
+
cleanupInstall(cleanupEnv.PRODUCER_CLI_INSTALL_ROOT);
|
|
1153
|
+
}
|
|
1154
|
+
catch {
|
|
1155
|
+
// 清理失败不影响主命令
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
const program = buildProgram(ctx);
|
|
1159
|
+
const output = {
|
|
1160
|
+
writeOut: (str) => (ctx.write ?? ((s) => process.stdout.write(s)))(str),
|
|
1161
|
+
// Commander writes parse errors before throwing; suppress that unstructured copy so
|
|
1162
|
+
// the top-level handler can emit one stable error envelope.
|
|
1163
|
+
writeErr: () => { },
|
|
1164
|
+
outputError: () => { },
|
|
1165
|
+
};
|
|
1166
|
+
const configureOutput = (command) => {
|
|
1167
|
+
command.configureOutput(output);
|
|
1168
|
+
for (const child of command.commands)
|
|
1169
|
+
configureOutput(child);
|
|
1170
|
+
};
|
|
1171
|
+
configureOutput(program);
|
|
1172
|
+
// 兼容旧写法:--version 仍可用,但不再注册为全局选项,避免出现在每个子命令的 Global Options。
|
|
1173
|
+
if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-V')) {
|
|
1174
|
+
(ctx.write ?? ((value) => process.stdout.write(value)))(`${currentCliVersion()}\n`);
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
// 无参数回退到 --help:commander 对「有子命令但没给参数」走 help({ error: true }),写完 stderr
|
|
1178
|
+
// 再抛 commander.help;上面的 writeErr 已静默 stderr,不在此显式回退就会无任何输出。
|
|
1179
|
+
if (argv.length === 0) {
|
|
1180
|
+
program.outputHelp();
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
// Commander silently exits when a command group with children is given
|
|
1184
|
+
// without a subcommand. Treat `producer fund` / `producer fund --format json` /
|
|
1185
|
+
// `producer --format json` like the corresponding `--help` form.
|
|
1186
|
+
let command = program;
|
|
1187
|
+
let index = 0;
|
|
1188
|
+
while (index < argv.length && !argv[index].startsWith('-')) {
|
|
1189
|
+
const child = command.commands.find((candidate) => candidate.name() === argv[index]);
|
|
1190
|
+
if (!child)
|
|
1191
|
+
break;
|
|
1192
|
+
command = child;
|
|
1193
|
+
index += 1;
|
|
1194
|
+
}
|
|
1195
|
+
if (command.commands.length > 0 && onlyGlobalFlags(argv.slice(index))) {
|
|
1196
|
+
command.outputHelp();
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
await program.parseAsync(['node', 'producer', ...argv]);
|
|
1200
|
+
}
|
|
1201
|
+
// 命令组后面只剩全局 flag(没有子命令 token)时,commander 会静默退出且不输出。
|
|
1202
|
+
const BOOLEAN_GLOBAL_FLAGS = new Set(['-y', '--yes', '--version', '-V', '--help', '-h']);
|
|
1203
|
+
function onlyGlobalFlags(tokens) {
|
|
1204
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
1205
|
+
const token = tokens[index];
|
|
1206
|
+
if (!token.startsWith('-'))
|
|
1207
|
+
return false;
|
|
1208
|
+
if (BOOLEAN_GLOBAL_FLAGS.has(token))
|
|
1209
|
+
continue;
|
|
1210
|
+
// --flag=value 自带取值;其余 flag 跳过紧随其后的值。
|
|
1211
|
+
if (token.includes('='))
|
|
1212
|
+
continue;
|
|
1213
|
+
index += 1;
|
|
1214
|
+
}
|
|
1215
|
+
return true;
|
|
1216
|
+
}
|
|
1217
|
+
if (import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
1218
|
+
run().catch((error) => {
|
|
1219
|
+
const code = error?.code;
|
|
1220
|
+
if (code === 'commander.helpDisplayed' || code === 'commander.help')
|
|
1221
|
+
return;
|
|
1222
|
+
process.stdout.write(`${JSON.stringify(errorPayload(error), null, 2)}\n`);
|
|
1223
|
+
process.exitCode = errorExitCode(error);
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
//# sourceMappingURL=main.js.map
|