openyida 2026.11.10 → 2026.11.11

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 CHANGED
@@ -616,7 +616,7 @@ When preparing a PR that needs a personal Fork, or when you ask how to support t
616
616
  | `openyida connector delete-action <id> <operation-id>` | Delete an action |
617
617
  | `openyida connector test --connector-id <id> --action <actionId> [--path-json JSON] [--query-json JSON] [--header-json JSON] [--body-json JSON] [--account-id <id>] [--system-token-app <appType>] [--ignore-defaults]` | Test an action |
618
618
  | `openyida connector list-connections <id>` | List auth connections |
619
- | `openyida connector create-connection <id> <name> [--interactive]` | Create an auth connection |
619
+ | `openyida connector create-connection <id> <name> [--interactive] [--repair-api-key-scheme]` | Create an auth connection |
620
620
  | `openyida connector smart-create --curl "..."` | Generate a redacted action draft from cURL (no remote create) |
621
621
  | `openyida connector parse-api [options]` | Parse API information |
622
622
  | `openyida connector gen-template [output]` | Generate API document template |
package/bin/yida.js CHANGED
@@ -661,6 +661,11 @@ async function main() {
661
661
  return;
662
662
  }
663
663
 
664
+ const { runWithCommandContext } = require('../lib/core/command-context');
665
+ return runWithCommandContext(dispatchCommand);
666
+ }
667
+
668
+ async function dispatchCommand() {
664
669
  switch (command) {
665
670
  case 'commands': {
666
671
  if (args[0] === 'validate' || args[0] === 'build') {
@@ -4,6 +4,7 @@ const fs = require('fs');
4
4
  const path = require('path');
5
5
  const { createHash } = require('crypto');
6
6
  const { resolveBearerAuthHeaders } = require('../core/utils');
7
+ const { getCommandContextHeaders } = require('../core/command-context');
7
8
  const { readManagedContext, managedError } = require('../agent/managed-context');
8
9
  const { CliError } = require('../core/cli-error');
9
10
  const { t } = require('../core/i18n');
@@ -293,6 +294,7 @@ async function uploadCustomThemeFile(appType, filePath, authRef, options = {}) {
293
294
  headers: {
294
295
  Accept: 'application/json, text/plain, */*',
295
296
  ...auth.headers,
297
+ ...getCommandContextHeaders(endpoint),
296
298
  Origin: authRef.baseUrl,
297
299
  Referer: `${authRef.baseUrl}/`,
298
300
  'x-requested-with': 'XMLHttpRequest',
@@ -104,6 +104,7 @@ async function run(args) {
104
104
  if (schema) {
105
105
  exportedForms.push({
106
106
  formUuid: page.formUuid,
107
+ alias: page.formUuid,
107
108
  name: page.name,
108
109
  formType: page.formType,
109
110
  schema,
@@ -19,7 +19,9 @@ const {
19
19
  const { createAuthRef, isTokenAuthRef } = require('../core/yida-client');
20
20
  const { t } = require('../core/i18n');
21
21
  const { buildYidaI18n, resolveContentLocale } = require('../core/yida-i18n');
22
- const { banner, step, label, success, fail, warn, info, error, result, usage, hint } = require('../core/chalk');
22
+ const { banner, step, label, success, info, result, usage, hint } = require('../core/chalk');
23
+ const { CliError } = require('../core/cli-error');
24
+ const { redactString } = require('../core/redact');
23
25
  const { throwUsage } = require('../core/command-errors');
24
26
  const { isPermissionGuidanceError } = require('../core/permission-guidance');
25
27
  const { getSchemaServerRevision } = require('../core/server-revision');
@@ -29,31 +31,31 @@ const { resolveBuilderAiSource } = require('./builder-ai-source');
29
31
 
30
32
  async function createApp(appName, authRef) {
31
33
  const contentLocale = resolveContentLocale({ baseUrl: authRef.baseUrl });
32
- const result = await requestWithAutoLogin((auth) => {
33
- const postData = querystring.stringify({
34
- _csrf_token: auth.csrfToken,
35
- appName: JSON.stringify(buildYidaI18n(appName, { en_US: appName, ja_JP: appName })),
36
- description: JSON.stringify(buildYidaI18n(appName, { en_US: appName, ja_JP: appName })),
37
- icon: 'xian-yingyong%%#0089FF',
38
- iconUrl: 'xian-yingyong%%#0089FF',
39
- colour: 'blue',
40
- defaultLanguage: contentLocale,
41
- openExclusive: 'n',
42
- openPhysicColumn: 'n',
43
- openIsolationDatabase: 'n',
44
- openExclusiveUnit: 'n',
45
- group: 'ALL',
46
- fromBuilderAi: 'y',
47
- builderAiSource: resolveBuilderAiSource(),
48
- });
49
- return httpPost(auth.baseUrl, '/query/app/registerApp.json', postData);
50
- }, authRef);
34
+ const postData = querystring.stringify({
35
+ _csrf_token: authRef.csrfToken,
36
+ appName: JSON.stringify(buildYidaI18n(appName, { en_US: appName, ja_JP: appName })),
37
+ description: JSON.stringify(buildYidaI18n(appName, { en_US: appName, ja_JP: appName })),
38
+ icon: 'xian-yingyong%%#0089FF',
39
+ iconUrl: 'xian-yingyong%%#0089FF',
40
+ colour: 'blue',
41
+ defaultLanguage: contentLocale,
42
+ openExclusive: 'n',
43
+ openPhysicColumn: 'n',
44
+ openIsolationDatabase: 'n',
45
+ openExclusiveUnit: 'n',
46
+ group: 'ALL',
47
+ fromBuilderAi: 'y',
48
+ builderAiSource: resolveBuilderAiSource(),
49
+ });
50
+ const result = await httpPost(authRef.baseUrl, '/query/app/registerApp.json', postData, { projectRoot: authRef.projectRoot });
51
51
 
52
52
  if (!result || !result.success || !result.content) {
53
53
  throw new Error(t('import.create_app_error') + ': ' + (result ? result.errorMsg || t('common.unknown_error') : t('common.request_failed')));
54
54
  }
55
55
 
56
- return result.content; // appType
56
+ const appType = result.content.appType || result.content;
57
+ if (typeof appType !== 'string' || !/^[A-Za-z0-9_-]+$/.test(appType)) { throw invalidPackage('invalid_created_app_id'); }
58
+ return appType;
57
59
  }
58
60
 
59
61
  function normalizeImportFormType(formType) {
@@ -78,24 +80,25 @@ function buildCreateFormPostData(formTitle, formType = 'receipt') {
78
80
  // ── 创建空白表单/页面/报表 ──────────────────────────────
79
81
 
80
82
  async function createBlankForm(appType, formTitle, authRef, formType = 'receipt') {
81
- const result = await requestWithAutoLogin((auth) => {
82
- const postData = querystring.stringify({
83
- _csrf_token: auth.csrfToken,
84
- ...buildCreateFormPayload(formTitle, formType),
85
- });
86
- return httpPost(
87
- auth.baseUrl,
88
- `/dingtalk/web/${appType}/query/formdesign/saveFormSchemaInfo.json`,
89
- postData
90
- );
91
- }, authRef);
83
+ const postData = querystring.stringify({
84
+ _csrf_token: authRef.csrfToken,
85
+ ...buildCreateFormPayload(formTitle, formType),
86
+ });
87
+ const result = await httpPost(
88
+ authRef.baseUrl,
89
+ `/dingtalk/web/${appType}/query/formdesign/saveFormSchemaInfo.json`,
90
+ postData,
91
+ { projectRoot: authRef.projectRoot }
92
+ );
92
93
 
93
94
  if (!result || !result.success || !result.content) {
94
95
  throw new Error(t('import.create_form_error') + ': ' + (result ? result.errorMsg || t('common.unknown_error') : t('common.request_failed')));
95
96
  }
96
97
 
97
98
  const content = result.content;
98
- return content.formUuid || content;
99
+ const formUuid = content.formUuid || content;
100
+ if (typeof formUuid !== 'string' || !/^[A-Za-z0-9_-]+$/.test(formUuid)) { throw invalidPackage('invalid_created_form_id'); }
101
+ return formUuid;
99
102
  }
100
103
 
101
104
  async function fetchFormSchema(appType, formUuid, authRef) {
@@ -157,24 +160,43 @@ async function saveFormSchema(appType, formUuid, schema, authRef, formType = 're
157
160
  // 导入时需要把 Schema 里所有对旧 appType / formUuid 的引用(页面 id、组件
158
161
  // props.appType、actions.source、SerialNumberField 公式等)重映射为新值。
159
162
  //
160
- // 早期实现对整个 Schema JSON 做无约束的全局字符串替换,存在数据腐蚀风险:
161
- // 若某个字段的文本值、label、备注恰好包含旧 appType / formUuid 子串,会被
162
- // 误替换。这里改为「标识符边界」约束替换——appType / formUuid 都是由字母、
163
- // 数字、下划线、连字符构成的标识符,只有当匹配片段两侧不是同类标识符字符时
164
- // 才替换,从而避免误伤包含旧标识符子串的普通文本。
165
-
166
- function buildIdentifierBoundaryRegExp(identifier) {
167
- // 标识符字符集:字母、数字、下划线、连字符。
168
- // 使用 lookbehind / lookahead 保证匹配片段不是更长标识符的一部分。
169
- return new RegExp(`(?<![A-Za-z0-9_-])${escapeRegExp(identifier)}(?![A-Za-z0-9_-])`, 'g');
163
+ // 按完整映射一次替换,避免替换级联;保留 label 等文案与字段标识。
164
+ // 表达式中的标识符仍采用边界匹配,兼容已有迁移包。
165
+
166
+ function invalidPackage(reason, details = {}) {
167
+ return new CliError(t('issue_fixes.invalid_import'), { code: 'IMPORT_INVALID_PACKAGE', details: { reason, ...details } });
170
168
  }
171
169
 
172
- function adaptSchemaIdentifiers(schema, oldAppType, newAppType, oldFormUuid, newFormUuid) {
173
- const schemaStr = JSON.stringify(schema);
174
- const adapted = schemaStr
175
- .replace(buildIdentifierBoundaryRegExp(oldAppType), newAppType)
176
- .replace(buildIdentifierBoundaryRegExp(oldFormUuid), newFormUuid);
177
- return JSON.parse(adapted);
170
+ function adaptSchemaIdentifiers(schema, oldAppType, newAppType, oldFormUuid, newFormUuid, aliases = new Map()) {
171
+ const forms = oldFormUuid instanceof Map ? oldFormUuid : new Map([[oldFormUuid, newFormUuid]]);
172
+ const replacements = new Map([[oldAppType, newAppType], ...forms]);
173
+ // One pass prevents a newly allocated ID from being substituted a second time.
174
+ const pattern = new RegExp(`(?<![A-Za-z0-9_-])(?:${[...replacements.keys()].map(escapeRegExp).join('|')})(?![A-Za-z0-9_-])`, 'g');
175
+ const literalKeys = new Set(['label', 'title', 'description', 'placeholder', 'help', 'fieldId', 'mainFieldId']);
176
+ function adapt(value) {
177
+ if (typeof value === 'string') { return value.replace(pattern, match => replacements.get(match)); }
178
+ if (Array.isArray(value)) { return value.map(adapt); }
179
+ if (!value || typeof value !== 'object') { return value; }
180
+ // Explicit external references belong to a different application.
181
+ if (value.formUuid && value.appType && value.appType !== oldAppType && !Object.hasOwn(value, 'formAlias')) { return value; }
182
+ if (value.formUuid && !value.formAlias && !forms.has(value.formUuid)) {
183
+ throw invalidPackage('unknown_form_reference', { formUuid: value.formUuid });
184
+ }
185
+ const copy = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, literalKeys.has(key) ? item : adapt(item)]));
186
+ if (Object.hasOwn(value, 'formAlias')) {
187
+ const target = aliases.get(value.formAlias);
188
+ if (!target || !forms.has(target)) { throw invalidPackage('unknown_form_alias', { alias: value.formAlias }); }
189
+ if (value.formUuid && value.formUuid !== target && value.formUuid !== forms.get(target)) {
190
+ throw invalidPackage('conflicting_form_alias', { alias: value.formAlias });
191
+ }
192
+ if (value.appType && value.appType !== oldAppType) { throw invalidPackage('external_form_alias'); }
193
+ copy.appType = newAppType;
194
+ copy.formUuid = forms.get(target);
195
+ delete copy.formAlias;
196
+ }
197
+ return copy;
198
+ }
199
+ return adapt(schema);
178
200
  }
179
201
 
180
202
  function escapeRegExp(str) {
@@ -186,14 +208,51 @@ function escapeRegExp(str) {
186
208
  // getFormSchema 接口返回的结构可能是 { content: {...} } 或直接是 schema 对象。
187
209
 
188
210
  function extractSchemaContent(schemaResult) {
189
- if (!schemaResult) {return null;}
190
- if (schemaResult.content && typeof schemaResult.content === 'object') {
191
- return schemaResult.content;
211
+ if (!schemaResult || schemaResult.success === false) { return null; }
212
+ let schema = schemaResult.content || schemaResult;
213
+ if (typeof schema === 'string') {
214
+ try { schema = JSON.parse(schema); } catch { return null; }
215
+ }
216
+ return schema && Array.isArray(schema.pages) ? schema : null;
217
+ }
218
+
219
+ function preflightPackage(data) {
220
+ if (!data || typeof data.sourceAppType !== 'string' || !/^[A-Za-z0-9_-]+$/.test(data.sourceAppType)
221
+ || !Array.isArray(data.forms) || !data.forms.length) { throw invalidPackage('invalid_structure'); }
222
+ const forms = new Map();
223
+ const aliases = new Map();
224
+ for (const form of data.forms) {
225
+ if (!form || typeof form.formUuid !== 'string' || !/^[A-Za-z0-9_-]+$/.test(form.formUuid) || forms.has(form.formUuid)) {
226
+ throw invalidPackage('invalid_or_duplicate_form_uuid');
227
+ }
228
+ if (!extractSchemaContent(form.schema)) { throw invalidPackage('invalid_schema', { formUuid: form.formUuid }); }
229
+ forms.set(form.formUuid, form.formUuid);
230
+ if (form.alias !== undefined) {
231
+ if (typeof form.alias !== 'string' || !/^[A-Za-z][A-Za-z0-9_.-]*$/.test(form.alias) || aliases.has(form.alias)) {
232
+ throw invalidPackage('invalid_or_duplicate_alias');
233
+ }
234
+ aliases.set(form.alias, form.formUuid);
235
+ }
236
+ }
237
+ for (const form of data.forms) {
238
+ adaptSchemaIdentifiers(extractSchemaContent(form.schema), data.sourceAppType, data.sourceAppType, forms, undefined, aliases);
192
239
  }
193
- if (schemaResult.pages) {
194
- return schemaResult;
240
+ return aliases;
241
+ }
242
+
243
+ function verifyImportedReferences(expected, actual) {
244
+ if (!actual || !Array.isArray(actual.pages)) { throw new Error('IMPORT_SCHEMA_READBACK_FAILED'); }
245
+ const keys = new Set(['id', 'appType', 'formUuid', 'mainFieldId', 'fieldId']);
246
+ function compare(left, right) {
247
+ if (!left || typeof left !== 'object') { return; }
248
+ for (const [key, value] of Object.entries(left)) {
249
+ if (keys.has(key) && typeof value === 'string' && value !== right?.[key]) {
250
+ throw new Error('IMPORT_REFERENCE_READBACK_MISMATCH');
251
+ }
252
+ compare(value, right?.[key]);
253
+ }
195
254
  }
196
- return null;
255
+ compare(expected, actual);
197
256
  }
198
257
 
199
258
  // ── 主逻辑 ────────────────────────────────────────────
@@ -215,19 +274,27 @@ async function run(args) {
215
274
 
216
275
  step(1, t('import.step_read_file'));
217
276
  if (!fs.existsSync(exportFilePath)) {
218
- error(t('import.file_not_found', exportFilePath));
277
+ throw new CliError(t('import.file_not_found', exportFilePath), { code: 'IMPORT_FILE_NOT_FOUND' });
219
278
  }
220
279
 
221
280
  let exportData;
222
281
  try {
223
282
  exportData = JSON.parse(fs.readFileSync(exportFilePath, 'utf-8'));
224
283
  } catch (err) {
225
- error(t('import.parse_failed', err.message));
284
+ throw invalidPackage('invalid_json');
226
285
  }
227
286
 
287
+ const aliases = preflightPackage(exportData);
228
288
  const { sourceAppType, forms } = exportData;
229
- if (!sourceAppType || !Array.isArray(forms) || forms.length === 0) {
230
- error(t('import.invalid_format'));
289
+ const reportPath = path.join(process.cwd(), 'yida-migration-report.json');
290
+ if (fs.existsSync(reportPath)) {
291
+ let previous;
292
+ try { previous = JSON.parse(fs.readFileSync(reportPath, 'utf8')); } catch { previous = null; }
293
+ const legacyComplete = previous && previous.status === undefined && Array.isArray(previous.forms)
294
+ && previous.forms.length > 0 && previous.forms.every(form => form.status === 'success');
295
+ if (!previous || (previous.status !== 'complete' && !legacyComplete)) {
296
+ throw new CliError(t('issue_fixes.partial_import'), { code: 'IMPORT_RECOVERY_REQUIRED', details: { reportPath, retrySafe: false } });
297
+ }
231
298
  }
232
299
 
233
300
  const appName = targetAppName || (sourceAppType + t('import.migration_suffix'));
@@ -239,113 +306,106 @@ async function run(args) {
239
306
  const authRef = createAuthRef();
240
307
  success(t('common.login_ready', authRef.baseUrl));
241
308
 
242
- step(3, t('import.step_create_app'));
243
- let newAppType;
244
- try {
245
- newAppType = await createApp(appName, authRef);
246
- } catch (err) {
247
- if (isPermissionGuidanceError(err)) { throw err; }
248
- error(err.message);
249
- }
250
- success(t('import.app_created', newAppType));
251
-
252
- step(4, t('import.step_rebuild_forms'));
253
309
  const migrationReport = {
254
310
  version: '1.0',
255
311
  migratedAt: new Date().toISOString(),
256
312
  sourceAppType,
257
- targetAppType: newAppType,
313
+ targetAppType: null,
258
314
  targetAppName: appName,
259
315
  baseUrl: authRef.baseUrl,
260
- forms: [],
316
+ status: 'app_create_pending',
317
+ forms: forms.map(form => ({ oldFormUuid: form.formUuid, newFormUuid: null, alias: form.alias,
318
+ name: form.name, formType: normalizeImportFormType(form.formType), status: 'pending' })),
261
319
  };
262
-
263
- let successCount = 0;
264
- let failCount = 0;
265
-
266
- for (const form of forms) {
267
- const { formUuid: oldFormUuid, name: formName, schema: formSchemaResult } = form;
268
- const formType = normalizeImportFormType(form.formType);
269
- info(t('import.migrating', formName, oldFormUuid));
270
-
271
- // 4.1 创建空白表单
272
- let newFormUuid;
320
+ const persist = () => {
321
+ fs.writeFileSync(reportPath + '.tmp', JSON.stringify(migrationReport, null, 2), 'utf-8');
322
+ fs.renameSync(reportPath + '.tmp', reportPath);
323
+ };
324
+ persist();
325
+ step(3, t('import.step_create_app'));
326
+ let newAppType;
327
+ try { newAppType = await createApp(appName, authRef); }
328
+ catch (err) {
329
+ migrationReport.status = 'app_create_unknown';
330
+ migrationReport.errorCode = err.code || 'UNEXPECTED_ERROR';
331
+ migrationReport.error = redactString(String(err.message || '')).slice(0, 500);
332
+ persist();
333
+ if (isPermissionGuidanceError(err)) { throw err; }
334
+ throw new CliError(t('issue_fixes.partial_import'), { code: 'IMPORT_PARTIAL_FAILURE', details: {
335
+ reportPath, stage: 'create_app', retrySafe: false, sideEffectState: 'unknown', causeCode: err.code || 'UNEXPECTED_ERROR',
336
+ } });
337
+ }
338
+ migrationReport.targetAppType = newAppType;
339
+ migrationReport.status = 'creating';
340
+ persist();
341
+ success(t('import.app_created', newAppType));
342
+ step(4, t('import.step_rebuild_forms'));
343
+ const abort = (entry, err) => {
344
+ entry.errorCode = err.code || (/^[A-Z_]+$/.test(err.message) ? err.message : 'UNEXPECTED_ERROR');
345
+ entry.error = redactString(String(err.message || '')).slice(0, 500);
346
+ migrationReport.status = 'partial';
347
+ persist();
348
+ if (isPermissionGuidanceError(err)) {
349
+ err.details = { ...err.details, targetAppType: newAppType, reportPath, partial: true, retrySafe: false };
350
+ throw err;
351
+ }
352
+ throw new CliError(t('issue_fixes.partial_import'), { code: 'IMPORT_PARTIAL_FAILURE', details: {
353
+ targetAppType: newAppType, reportPath, partial: true, retrySafe: false, sideEffectState: 'unknown',
354
+ failedFormUuid: entry.oldFormUuid, status: entry.status, causeCode: entry.errorCode,
355
+ } });
356
+ };
357
+ persist();
358
+ // Allocate every target before adapting any Schema, including cyclic references.
359
+ const mapping = new Map();
360
+ for (const entry of migrationReport.forms) {
361
+ entry.status = 'create_pending';
362
+ persist();
273
363
  try {
274
- newFormUuid = await createBlankForm(newAppType, formName, authRef, formType);
275
- success(t('import.blank_form_created', newFormUuid));
364
+ entry.newFormUuid = await createBlankForm(newAppType, entry.name, authRef, entry.formType);
365
+ mapping.set(entry.oldFormUuid, entry.newFormUuid);
366
+ entry.status = 'created';
276
367
  } catch (err) {
277
- if (isPermissionGuidanceError(err)) { throw err; }
278
- fail(t('import.create_form_failed', err.message));
279
- migrationReport.forms.push({
280
- oldFormUuid,
281
- newFormUuid: null,
282
- name: formName,
283
- formType,
284
- status: 'failed',
285
- error: err.message,
286
- });
287
- failCount++;
288
- continue;
368
+ entry.status = 'create_unknown';
369
+ abort(entry, err);
289
370
  }
290
-
291
- // 4.2 提取并适配 Schema
292
- const originalSchema = extractSchemaContent(formSchemaResult);
293
- if (!originalSchema) {
294
- warn(t('import.schema_empty'));
295
- migrationReport.forms.push({
296
- oldFormUuid,
297
- newFormUuid,
298
- name: formName,
299
- formType,
300
- status: 'skipped',
301
- error: t('import.schema_empty_msg'),
302
- });
303
- failCount++;
304
- continue;
305
- }
306
-
307
- // 将 Schema 中所有旧 appType / formUuid 引用重映射为新值(标识符边界约束,避免误伤普通文本)
308
- const adaptedSchema = adaptSchemaIdentifiers(
309
- originalSchema,
310
- sourceAppType,
311
- newAppType,
312
- oldFormUuid,
313
- newFormUuid
314
- );
315
- const targetSchemaResult = await fetchFormSchema(newAppType, newFormUuid, authRef);
316
- const serverRevision = getSchemaServerRevision(targetSchemaResult);
317
-
318
- // 4.3 保存 Schema
319
- const saveResult = await saveFormSchema(newAppType, newFormUuid, adaptedSchema, authRef, formType, serverRevision);
320
- if (!saveResult || !saveResult.success) {
321
- const errorMsg = saveResult ? saveResult.errorMsg || t('common.unknown_error') : t('common.request_failed');
322
- fail(t('import.save_schema_failed', errorMsg));
323
- migrationReport.forms.push({
324
- oldFormUuid,
325
- newFormUuid,
326
- name: formName,
327
- formType,
328
- status: 'failed',
329
- error: t('import.save_schema_failed', errorMsg),
330
- });
331
- failCount++;
332
- continue;
371
+ persist();
372
+ }
373
+ migrationReport.status = 'saving';
374
+ for (let index = 0; index < forms.length; index++) {
375
+ const entry = migrationReport.forms[index];
376
+ const adapted = adaptSchemaIdentifiers(extractSchemaContent(forms[index].schema), sourceAppType, newAppType, mapping, undefined, aliases);
377
+ info(t('import.migrating', entry.name, entry.oldFormUuid));
378
+ let writeAttempted = false;
379
+ try {
380
+ const target = await fetchFormSchema(newAppType, entry.newFormUuid, authRef);
381
+ const revision = getSchemaServerRevision(target);
382
+ if (!target || target.success === false || !Number.isFinite(revision)) { throw new Error('SCHEMA_REMOTE_READ_FAILED'); }
383
+ entry.status = 'save_pending';
384
+ persist();
385
+ writeAttempted = true;
386
+ const saved = await saveFormSchema(newAppType, entry.newFormUuid, adapted, authRef, entry.formType, revision);
387
+ if (!saved || !saved.success) {
388
+ entry.status = 'save_failed';
389
+ throw new CliError(saved?.errorMsg || t('common.request_failed'), { code: 'SCHEMA_WRITE_REJECTED' });
390
+ }
391
+ entry.status = 'verify_pending';
392
+ persist();
393
+ const readback = await fetchFormSchema(newAppType, entry.newFormUuid, authRef);
394
+ verifyImportedReferences(adapted, extractSchemaContent(readback));
395
+ entry.readbackVerified = true;
396
+ entry.status = 'success';
397
+ } catch (err) {
398
+ if (entry.status === 'verify_pending') { entry.status = 'verify_failed'; }
399
+ else if (entry.status !== 'save_failed') { entry.status = writeAttempted ? 'save_unknown' : 'read_failed'; }
400
+ abort(entry, err);
333
401
  }
402
+ persist();
334
403
  success(t('import.schema_saved'));
335
-
336
- migrationReport.forms.push({
337
- oldFormUuid,
338
- newFormUuid,
339
- name: formName,
340
- formType,
341
- status: 'success',
342
- });
343
- successCount++;
344
404
  }
345
-
346
- step(5, t('import.step_write_report'));
347
- const reportPath = path.join(process.cwd(), 'yida-migration-report.json');
348
- fs.writeFileSync(reportPath, JSON.stringify(migrationReport, null, 2), 'utf-8');
405
+ migrationReport.status = 'complete';
406
+ persist();
407
+ const successCount = forms.length;
408
+ const failCount = 0;
349
409
  success(t('import.report_written', reportPath));
350
410
 
351
411
  // 输出结果
@@ -361,11 +421,6 @@ async function run(args) {
361
421
  resultDetails.push(['Failed', String(failCount)]);
362
422
  }
363
423
  result(failCount === 0, t('import.done'), resultDetails);
364
- if (failCount > 0) {
365
- warn(t('import.notice_label'));
366
- hint(t('import.notice_association'));
367
- hint(t('import.notice_custom_page'));
368
- }
369
424
 
370
425
  console.log(
371
426
  JSON.stringify({
@@ -392,5 +447,6 @@ module.exports = {
392
447
  saveFormSchema,
393
448
  adaptSchemaIdentifiers,
394
449
  extractSchemaContent,
450
+ preflightPackage,
395
451
  },
396
452
  };
@@ -9,6 +9,7 @@
9
9
 
10
10
  const { createAuthRef, createYidaClient } = require('../core/yida-client');
11
11
  const { t } = require('../core/i18n');
12
+ const { CliError } = require('../core/cli-error');
12
13
  const {
13
14
  HTTP_CONNECTOR_MODE,
14
15
  assertConnectorReadback,
@@ -279,12 +280,14 @@ async function saveConnector(params, authRef) {
279
280
  faasTemplateId: valueOr(params.faasTemplateId, '0'),
280
281
  securitySchemes: valueOr(params.securitySchemes, '{}'),
281
282
  connectorMode: valueOr(params.connectorMode, String(HTTP_CONNECTOR_MODE)),
282
- connectorName: params.connectorName,
283
- category: valueOr(params.category, 'http'),
283
+ // The detail endpoint can omit the HTTP category as an empty string.
284
+ // Sending that sentinel back on an edit removes it from the HTTP list.
285
+ category: params.category || 'http',
284
286
  };
285
287
 
286
288
  if (params.id) {
287
289
  bodyParams.id = params.id;
290
+ bodyParams.connectorName = params.connectorName;
288
291
  }
289
292
 
290
293
  const result = await connectorPostOnce(
@@ -294,8 +297,10 @@ async function saveConnector(params, authRef) {
294
297
  );
295
298
 
296
299
  if (result.hasError || !result.success) {
297
- const error = new Error(result.errorMsg || result.message || t('connector_api.save_failed'));
298
- error.code = 'CONNECTOR_WRITE_REJECTED';
300
+ const error = new CliError(result.errorMsg || result.message || t('connector_api.save_failed'), {
301
+ code: 'CONNECTOR_WRITE_REJECTED',
302
+ details: { retrySafe: false, sideEffectState: 'unknown', platformErrorCode: result.errorCode },
303
+ });
299
304
  error.writeAttempted = true;
300
305
  error.outcome = 'rejected';
301
306
  throw error;
@@ -314,20 +319,24 @@ async function saveConnector(params, authRef) {
314
319
  throw error;
315
320
  }
316
321
 
317
- const connectorName = responseConnectorName || params.connectorName;
322
+ const connectorName = responseConnectorName || (params.id ? params.connectorName : undefined);
318
323
  const detail = await getConnectorDetail({
319
324
  id: connectorId,
320
325
  connectorName,
321
326
  connectorMode: params.connectorMode || String(HTTP_CONNECTOR_MODE),
322
327
  }, authRef);
323
- assertConnectorReadback(params, detail);
328
+ // Creation may allocate a different internal name. Updates must retain their
329
+ // existing identity; all other definition fields still require an exact match.
330
+ const allocatedName = responseConnectorName || detail.connectorName;
331
+ assertConnectorReadback(!params.id && allocatedName
332
+ ? { ...params, connectorName: allocatedName } : params, detail);
324
333
 
325
334
  const detailConnectorId = detail && (detail.id || detail.connectorId);
326
335
 
327
336
  return {
328
337
  ...result,
329
338
  connectorId: detailConnectorId || connectorId,
330
- connectorName,
339
+ connectorName: detail.connectorName || connectorName,
331
340
  detail,
332
341
  readbackVerified: true,
333
342
  };
@@ -16,12 +16,14 @@ const { fail } = require('../core/chalk');
16
16
  const { safeJsonStringify } = require('../core/redact');
17
17
  const { CliError } = require('../core/cli-error');
18
18
  const { t } = require('../core/i18n');
19
+ const { isDeepStrictEqual } = require('util');
19
20
 
20
21
  const {
21
22
  getAuthRef,
22
23
  findConnectorById,
23
24
  getConnectorDetail,
24
25
  createConnection,
26
+ saveConnector,
25
27
  } = require('./api');
26
28
  const { AUTH_TYPE_CODES } = require('./contract');
27
29
 
@@ -46,9 +48,22 @@ function showUsage() {
46
48
  openyida connector create-connection 910244 "钉钉账号" --interactive
47
49
  openyida connector create-connection 910264 "阿里云账号" --app-code "your-app-code"
48
50
  `);
51
+ console.log(t('issue_fixes.repair_required'));
49
52
  }
50
53
 
51
- function buildSecurityValue(options, authType) {
54
+ function apiKeyScheme(schemes) {
55
+ const scheme = schemes && schemes.ApiKeyAuth;
56
+ const location = scheme && (scheme.in || scheme.location);
57
+ if (!scheme || typeof scheme.name !== 'string' || !scheme.name.trim()
58
+ || !['header', 'query'].includes(location)
59
+ || (scheme.type !== undefined && scheme.type !== 'apiKey')
60
+ || (scheme.location !== undefined && scheme.location !== location)) {
61
+ throw new CliError(t('issue_fixes.invalid_api_key'), { code: 'CONNECTOR_API_KEY_SCHEME_INVALID' });
62
+ }
63
+ return { ...scheme, type: 'apiKey', in: location, location };
64
+ }
65
+
66
+ function buildSecurityValue(options, authType, schemes) {
52
67
  switch (authType) {
53
68
  case 'BasicAuth':
54
69
  if (!options.username || !options.password) {
@@ -60,7 +75,7 @@ function buildSecurityValue(options, authType) {
60
75
  if (!options.apiKey) {
61
76
  throw new Error('API 密钥需要提供 --api-key');
62
77
  }
63
- return JSON.stringify({ token: options.apiKey });
78
+ return JSON.stringify({ [apiKeyScheme(schemes).name]: options.apiKey });
64
79
 
65
80
  case 'DingAuth':
66
81
  if (!options.appKey || !options.appSecret) {
@@ -206,6 +221,9 @@ function parseArgs(args) {
206
221
  case '--interactive':
207
222
  options.interactive = true;
208
223
  break;
224
+ case '--repair-api-key-scheme':
225
+ options.repairApiKeyScheme = true;
226
+ break;
209
227
  case '--json':
210
228
  options.json = true;
211
229
  break;
@@ -250,13 +268,29 @@ async function run(args, deps = {}) {
250
268
  log(`鉴权类型: ${authType}\n`);
251
269
 
252
270
  const credentialOptions = await collectInteractiveCredentials(options, authType, deps);
253
- const securityValue = buildSecurityValue(credentialOptions, authType);
271
+ const securityValue = buildSecurityValue(credentialOptions, authType, securitySchemes);
272
+ let accountSchemes = securitySchemes;
273
+ let schemeRepaired = false;
274
+ if (authType === 'ApiKeyAuth') {
275
+ accountSchemes = { ...securitySchemes, ApiKeyAuth: apiKeyScheme(securitySchemes) };
276
+ if (!isDeepStrictEqual(accountSchemes, securitySchemes)) {
277
+ if (!options.repairApiKeyScheme) {
278
+ throw new CliError(t('issue_fixes.repair_required'), { code: 'CONNECTOR_API_KEY_REPAIR_REQUIRED' });
279
+ }
280
+ await saveConnector({ ...detail, id: connector.id, connectorName: connector.connectorName,
281
+ operations: typeof detail.operations === 'string' ? detail.operations : JSON.stringify(detail.operations),
282
+ securitySchemes: JSON.stringify(accountSchemes) }, authRef);
283
+ schemeRepaired = true;
284
+ }
285
+ } else if (options.repairApiKeyScheme) {
286
+ throw new CliError(t('issue_fixes.invalid_api_key'), { code: 'CONNECTOR_API_KEY_SCHEME_INVALID' });
287
+ }
254
288
 
255
289
  const result = await createConnection({
256
290
  connectionName: options.connectionName,
257
291
  securityValue,
258
292
  connectorName: connector.connectorName,
259
- securitySchemes: detail.securitySchemes,
293
+ securitySchemes: JSON.stringify(accountSchemes),
260
294
  authType: AUTH_TYPE_CODES[authType] ?? AUTH_TYPE_CODES.NONE,
261
295
  }, authRef);
262
296
 
@@ -267,7 +301,10 @@ async function run(args, deps = {}) {
267
301
  connectionId: result.id || result.connectionId,
268
302
  connectionName: result.connectionName || options.connectionName,
269
303
  readbackVerified: result.readbackVerified === true,
304
+ ...(authType === 'ApiKeyAuth' ? { schemeRepaired, existingAccountsUnchanged: true,
305
+ notice: t('issue_fixes.replacement_notice') } : {}),
270
306
  };
307
+ if (authType === 'ApiKeyAuth') { log(output.notice); }
271
308
  if (options.json) {
272
309
  console.log(safeJsonStringify(output, 0));
273
310
  }
@@ -179,6 +179,8 @@ function buildSecuritySchemes(options) {
179
179
  label: options.apiKeyLabel || 'API Key',
180
180
  name: options.apiKeyName || 'X-API-Key',
181
181
  location: options.apiKeyLocation === 'QUERY' ? 'query' : 'header',
182
+ type: 'apiKey',
183
+ in: options.apiKeyLocation === 'QUERY' ? 'query' : 'header',
182
184
  },
183
185
  });
184
186
  case 'DINGTALK':
@@ -211,10 +213,6 @@ function parseBaseUrl(url) {
211
213
  }
212
214
  }
213
215
 
214
- function generateConnectorName() {
215
- return 'Http_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
216
- }
217
-
218
216
  async function run(args) {
219
217
  if (!args || args.length === 0 || args[0] === '--help' || args[0] === '-h') {
220
218
  showUsage();
@@ -288,7 +286,6 @@ async function run(args) {
288
286
 
289
287
  const urlInfo = parseBaseUrl(options.baseUrl);
290
288
  const securitySchemes = buildSecuritySchemes(options);
291
- const connectorName = generateConnectorName();
292
289
  const connectorDesc = buildConnectorDesc(options.description, null, authRef, operations);
293
290
 
294
291
  const saveResult = await saveConnector({
@@ -303,11 +300,11 @@ async function run(args) {
303
300
  faasTemplateId: '0',
304
301
  securitySchemes,
305
302
  connectorMode: String(HTTP_CONNECTOR_MODE),
306
- connectorName,
307
303
  category: 'http',
308
304
  }, authRef);
309
305
 
310
306
  const connectorId = saveResult.connectorId;
307
+ const connectorName = saveResult.connectorName;
311
308
  const detailUrl = connectorId
312
309
  ? `https://yidalogin.aliwork.com/platformManage/customConnectorFactory/update?id=${connectorId}&connectorName=${connectorName}&mode=http`
313
310
  : null;
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ const { AsyncLocalStorage } = require('async_hooks');
4
+ const { randomUUID } = require('crypto');
5
+
6
+ const commandContext = new AsyncLocalStorage();
7
+ const EMPTY_HEADERS = Object.freeze({});
8
+
9
+ function runWithCommandContext(run) {
10
+ const startedAtMs = Date.now();
11
+ const { resolveBuilderAiSource } = require('../app/builder-ai-source');
12
+ const headers = Object.freeze({
13
+ 'X-OpenYida-Agent-Source': resolveBuilderAiSource(),
14
+ 'X-OpenYida-Command-Id': randomUUID(),
15
+ 'X-OpenYida-Command-Started-At-Ms': String(startedAtMs),
16
+ });
17
+ return commandContext.run(headers, run);
18
+ }
19
+
20
+ function getCommandContextHeaders(url) {
21
+ const headers = commandContext.getStore();
22
+ if (!headers || url.protocol !== 'https:' || url.port) { return EMPTY_HEADERS; }
23
+
24
+ const { isYidaServiceHost } = require('./env-manager');
25
+ return isYidaServiceHost(url.hostname) ? headers : EMPTY_HEADERS;
26
+ }
27
+
28
+ module.exports = { runWithCommandContext, getCommandContextHeaders };
@@ -1466,7 +1466,9 @@ const COMMAND_GROUPS = [
1466
1466
  output: 'json',
1467
1467
  }),
1468
1468
  command('export', ['export'], 'export <appType> [output]', 'help.cmd_export', { managedRun: { scope: 'denied', reason: 'scope_not_audited' } }),
1469
- command('import', ['import'], 'import <file> [name]', 'help.cmd_import', { managedRun: { scope: 'denied', reason: 'scope_not_audited' } }),
1469
+ command('import', ['import'], 'import <file> [name]', 'help.cmd_import', { managedRun: { scope: 'denied', reason: 'scope_not_audited' },
1470
+ notes: ['Allocates all forms before saving schemas with the complete UUID mapping. Optional package form.alias and schema formAlias references resolve to real platform IDs; duplicate, missing or conflicting aliases fail before writes. See docs/guides/application-import.md. Interrupted imports retain yida-migration-report.json and block blind reruns until the existing resources have been inspected and the report archived.'],
1471
+ }),
1470
1472
  ],
1471
1473
  },
1472
1474
  {
@@ -2016,7 +2018,10 @@ const COMMAND_GROUPS = [
2016
2018
  command('connector.delete-action', ['connector', 'delete-action'], 'connector delete-action <id> <operation-id>', 'help.cmd_connector_delete_action', { managedRun: { scope: 'denied', reason: 'organization_scope_required' } }),
2017
2019
  command('connector.test', ['connector', 'test'], 'connector test --connector-id <id> --action <actionId> [--path-json JSON] [--query-json JSON] [--header-json JSON] [--body-json JSON] [--account-id <id>] [--system-token-app <appType>] [--ignore-defaults]', 'help.cmd_connector_test', { managedRun: { scope: 'denied', reason: 'organization_scope_required' } }),
2018
2020
  command('connector.list-connections', ['connector', 'list-connections'], 'connector list-connections <id>', 'help.cmd_connector_list_connections', { managedRun: { scope: 'denied', reason: 'organization_scope_required' } }),
2019
- command('connector.create-connection', ['connector', 'create-connection'], 'connector create-connection <id> <name> [--interactive]', 'help.cmd_connector_create_connection', { managedRun: { scope: 'denied', reason: 'organization_scope_required' } }),
2021
+ command('connector.create-connection', ['connector', 'create-connection'], 'connector create-connection <id> <name> [--interactive] [--repair-api-key-scheme]', 'help.cmd_connector_create_connection', { managedRun: { scope: 'denied', reason: 'organization_scope_required' },
2022
+ parameters: [{ name: 'repairApiKeyScheme', type: 'boolean', source: 'option', builder_options: ['--repair-api-key-scheme'], description: 'Explicitly repair missing API Key type/in/location on the existing connector before creating a replacement account; existing accounts are unchanged.' }],
2023
+ notes: ['API Key values use the configured scheme.name for header or query authentication. Legacy schemes require explicit --repair-api-key-scheme; inspect the connector first. Repair verifies the complete definition by readback, then creates a new account. Bind the returned account ID in callers; existing accounts retain their original scheme and values.'],
2024
+ }),
2020
2025
  command('connector.smart-create', ['connector', 'smart-create'], 'connector smart-create --curl "..."', 'help.cmd_connector_smart', { managedRun: { scope: 'denied', reason: 'organization_scope_required' } }),
2021
2026
  command('connector.parse-api', ['connector', 'parse-api'], 'connector parse-api [options]', 'help.cmd_connector_parse_api', { managedRun: { scope: 'local' } }),
2022
2027
  command('connector.gen-template', ['connector', 'gen-template'], 'connector gen-template [output]', 'help.cmd_connector_gen_template', { managedRun: { scope: 'local' } }),
@@ -4,6 +4,13 @@
4
4
  'use strict';
5
5
 
6
6
  module.exports = {
7
+ issue_fixes: {
8
+ invalid_api_key: 'API Key configuration requires a valid name and header/query location; inspect the connector definition first.',
9
+ repair_required: 'Legacy API Key configuration lacks type/in/location. Add --repair-api-key-scheme to explicitly repair the connector and create a new account.',
10
+ replacement_notice: 'Existing accounts are unchanged; rebind callers to the new account ID returned by this command.',
11
+ invalid_import: 'Invalid migration package; inspect the form identifiers, Schema or aliases in details.',
12
+ partial_import: 'Import is incomplete. Inspect existing resources in yida-migration-report.json before retrying; verify and archive the report before starting another import.',
13
+ },
7
14
  dingtalk_login: {
8
15
  select_version: 'Choose a DingTalk version for overseas YiDA:',
9
16
  domestic: 'Domestic DingTalk (overseas YiDA, default)',
@@ -4,6 +4,13 @@
4
4
  'use strict';
5
5
 
6
6
  module.exports = {
7
+ issue_fixes: {
8
+ invalid_api_key: 'API Key 配置必须包含有效的 name 和 header/query 位置;请先检查连接器定义。',
9
+ repair_required: '旧 API Key 配置缺少 type/in/location;确认后加 --repair-api-key-scheme 修补连接器并创建新账号。',
10
+ replacement_notice: '已有账号保持不变;请将调用方重新绑定到本次返回的新账号 ID。',
11
+ invalid_import: '迁移包无效;请检查 details 中的表单标识、Schema 或 alias。',
12
+ partial_import: '导入未完成。请先检查 yida-migration-report.json 中的已有应用和表单,不要直接重跑;核实并归档报告后再进行新的导入。',
13
+ },
7
14
  dingtalk_login: {
8
15
  select_version: '请选择用于登录宜搭海外站的钉钉版本:',
9
16
  domestic: '钉钉国内版(宜搭海外,默认)',
package/lib/core/utils.js CHANGED
@@ -18,6 +18,7 @@ const path = require('path');
18
18
  const os = require('os');
19
19
  const { t } = require('./i18n');
20
20
  const { warn } = require('./chalk');
21
+ const { getCommandContextHeaders } = require('./command-context');
21
22
 
22
23
  // ── 项目根目录查找 ────────────────────────────────────
23
24
 
@@ -1237,6 +1238,7 @@ async function httpPostMultipart(baseUrl, requestPath, fields, files, optionsOrL
1237
1238
  Referer: optionsOverride.referer || requestUrl.origin + '/',
1238
1239
  'x-requested-with': 'XMLHttpRequest',
1239
1240
  ...authHeaders,
1241
+ ...getCommandContextHeaders(requestUrl),
1240
1242
  },
1241
1243
  body: form,
1242
1244
  }, optionsOverride.timeout, response => parseJsonFetchResponse(response, { ...optionsOverride, baseUrl, requestPath }));
@@ -1403,6 +1405,7 @@ async function httpGetCodeBundleText(baseUrl, requestPath, queryParams, optionsO
1403
1405
  Referer: requestUrl.origin + '/',
1404
1406
  'x-requested-with': 'XMLHttpRequest',
1405
1407
  ...authHeaders,
1408
+ ...getCommandContextHeaders(requestUrl),
1406
1409
  },
1407
1410
  }, optionsOverride.timeout);
1408
1411
  const metadata = buildCodeBundleResponseMetadata(requestUrl, response);
@@ -1524,6 +1527,7 @@ async function httpPost(baseUrl, requestPath, postData, optionsOrLegacyCookies,
1524
1527
  Referer: optionsOverride.referer || baseUrl + '/',
1525
1528
  'x-requested-with': 'XMLHttpRequest',
1526
1529
  ...authHeaders,
1530
+ ...getCommandContextHeaders(parsedUrl),
1527
1531
  },
1528
1532
  timeout: optionsOverride.timeout || 30000,
1529
1533
  };
@@ -1603,6 +1607,7 @@ async function httpPostJson(baseUrl, requestPath, payload, optionsOrLegacyCookie
1603
1607
  Referer: optionsOverride.referer || baseUrl + '/',
1604
1608
  'x-requested-with': 'XMLHttpRequest',
1605
1609
  ...authHeaders,
1610
+ ...getCommandContextHeaders(parsedUrl),
1606
1611
  },
1607
1612
  timeout: optionsOverride.timeout || 30000,
1608
1613
  };
@@ -1707,6 +1712,7 @@ async function httpGet(baseUrl, requestPath, queryParams, optionsOrLegacyCookies
1707
1712
  Referer: baseUrl + '/',
1708
1713
  'x-requested-with': 'XMLHttpRequest',
1709
1714
  ...authHeaders,
1715
+ ...getCommandContextHeaders(parsedUrl),
1710
1716
  },
1711
1717
  timeout: optionsOverride.timeout || 30000,
1712
1718
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openyida",
3
- "version": "2026.11.10",
3
+ "version": "2026.11.11",
4
4
  "description": "OpenYida CLI - AI 宜搭应用开发工具(安装即用,零配置)",
5
5
  "bin": {
6
6
  "openyida": "bin/yida.js",