zentao-api 0.9.1 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +13 -5
  2. package/dist/browser/zentao-api.global.js +19 -19
  3. package/dist/client/index.js +19 -11
  4. package/dist/index.d.ts +5 -2
  5. package/dist/index.js +5 -2
  6. package/dist/misc/errors.d.ts +6 -0
  7. package/dist/misc/errors.js +11 -0
  8. package/dist/modules/override.js +46 -7
  9. package/dist/modules/resolve.d.ts +5 -1
  10. package/dist/modules/resolve.js +15 -10
  11. package/dist/request/html-file-request.d.ts +6 -6
  12. package/dist/request/html-file-request.js +35 -50
  13. package/dist/request/html-files.d.ts +6 -1
  14. package/dist/request/html-files.js +26 -13
  15. package/dist/request/index.d.ts +11 -3
  16. package/dist/request/index.js +137 -80
  17. package/dist/request/markdown.d.ts +3 -0
  18. package/dist/request/markdown.js +73 -0
  19. package/dist/request/pagination.d.ts +12 -0
  20. package/dist/request/pagination.js +56 -0
  21. package/dist/request/prepare-body.d.ts +2 -0
  22. package/dist/request/prepare-body.js +11 -0
  23. package/dist/request/read-image-file.d.ts +19 -0
  24. package/dist/request/read-image-file.js +45 -0
  25. package/dist/request/version.d.ts +12 -0
  26. package/dist/request/version.js +36 -0
  27. package/dist/request/write-outcome.d.ts +23 -0
  28. package/dist/request/write-outcome.js +79 -0
  29. package/dist/types/module.d.ts +3 -2
  30. package/dist/types/options.d.ts +20 -0
  31. package/dist/types/response.d.ts +24 -0
  32. package/dist/types/upload.d.ts +6 -4
  33. package/dist/url.d.ts +19 -0
  34. package/dist/url.js +22 -0
  35. package/dist/utils/file-url.d.ts +13 -0
  36. package/dist/utils/file-url.js +80 -0
  37. package/dist/utils/html.d.ts +1 -1
  38. package/dist/utils/html.js +3 -3
  39. package/dist/utils/url.d.ts +3 -10
  40. package/dist/utils/url.js +8 -64
  41. package/dist/version.js +2 -2
  42. package/package.json +5 -1
@@ -1,7 +1,8 @@
1
- import { isZentaoConfigFetchError, ZentaoError } from '../misc/errors.js';
1
+ import { asTransportError, isZentaoConfigFetchError, ZentaoError } from '../misc/errors.js';
2
2
  import { parseZentaoVersion } from '../misc/zentao-version.js';
3
3
  import { assertInsecureSupported, fetchWithInsecureTls } from '../misc/environment.js';
4
4
  import { getGlobalOptions, setGlobalOptions } from '../misc/global-options.js';
5
+ import { rejectionStatuses, writeAttempts } from '../request/write-outcome.js';
5
6
  import { getProfileOrThrow, saveLoginProfile, switchProfile, updateProfileServerConfig } from '../profiles/index.js';
6
7
  import { isRecord, normalizeSiteUrl } from '../utils/index.js';
7
8
  const DEFAULT_TIMEOUT = 10000;
@@ -344,7 +345,13 @@ export class ZentaoClient {
344
345
  };
345
346
  }
346
347
  async request(path, options = {}) {
347
- return this.fetch(buildUrl(this.baseUrl, path, options.query), options, this.token);
348
+ const write = writeAttempts.get(options);
349
+ if (write)
350
+ write.phase = 'preparing';
351
+ const url = buildUrl(this.baseUrl, path, options.query);
352
+ if (write)
353
+ write.phase = 'dispatching';
354
+ return this.fetch(url, options, this.token);
348
355
  }
349
356
  /**
350
357
  * 使用完整 URL 发起请求,复用 API 与站点配置的传输层。
@@ -357,6 +364,9 @@ export class ZentaoClient {
357
364
  * @throws {ZentaoError} 传输层失败时抛出,详见 {@link ZentaoClient.request}。
358
365
  */
359
366
  async fetch(url, options, token, fetchOptions = {}) {
367
+ const write = writeAttempts.get(options);
368
+ if (write)
369
+ write.phase = 'preparing';
360
370
  const globals = getGlobalOptions();
361
371
  const method = options.method ?? 'GET';
362
372
  const timeout = options.timeout ?? globals.timeout ?? this.timeout ?? DEFAULT_TIMEOUT;
@@ -392,8 +402,12 @@ export class ZentaoClient {
392
402
  init.signal = signal;
393
403
  let keepResponseSignal = false;
394
404
  try {
405
+ if (write && !signal.aborted)
406
+ write.phase = 'dispatching';
395
407
  const response = await fetchWithInsecureTls(insecure, url, init);
396
408
  if (!response.ok) {
409
+ if (write && rejectionStatuses.has(response.status))
410
+ write.outcome = 'rejected';
397
411
  throw new ZentaoError('E_HTTP_ERROR', {
398
412
  status: response.status,
399
413
  statusText: response.statusText,
@@ -406,20 +420,14 @@ export class ZentaoClient {
406
420
  }
407
421
  if (options.responseType === 'response') {
408
422
  keepResponseSignal = true;
423
+ if (write)
424
+ write.responseBodyError = cause => asTransportError(cause, signal, didTimeout);
409
425
  return keepResponseSignalUntilBodyEnds(response, cleanup);
410
426
  }
411
427
  return await parseResponse(response, options.responseType);
412
428
  }
413
429
  catch (error) {
414
- if (signal.aborted) {
415
- throw new ZentaoError(didTimeout() ? 'E_TIMEOUT' : 'E_ABORTED', undefined, error);
416
- }
417
- if (error instanceof ZentaoError)
418
- throw error;
419
- if (error instanceof DOMException && error.name === 'AbortError') {
420
- throw new ZentaoError('E_ABORTED', undefined, error);
421
- }
422
- throw new ZentaoError('E_NETWORK_ERROR', { message: error.message ?? String(error) }, error);
430
+ throw asTransportError(error, signal, didTimeout);
423
431
  }
424
432
  finally {
425
433
  if (!keepResponseSignal)
package/dist/index.d.ts CHANGED
@@ -3,7 +3,10 @@ export { ERRORS, ZentaoError, type ErrorCode } from './misc/errors.js';
3
3
  export { getGlobalOptions, setGlobalOptions } from './misc/global-options.js';
4
4
  export { ZENTAO_PROFILES_STORAGE_KEY, addProfile, deleteProfile, getAllProfiles, getProfile, getProfileKey, switchProfile, } from './profiles/index.js';
5
5
  export { defineModuleActions, defineModules, type DefineModulesOptions, type ExportRegistryOptions, type ExportedModuleAction, type ExportedModuleDefinition, exportRegistry, extendModuleAction, getModuleNames, isModuleName, getModule, getModuleAction, getModuleActionParams, getObjectProps, } from './modules/registry.js';
6
- export { request, type BuiltinRequestName, type RequestParamsFor, type RequestResultFor, } from './request/index.js';
7
- export { createLink, extractFileIdFromUrl, extractFileIdsFromHtml, parseLink, pickFields, pickFieldsSingle, filterData, searchData, sortData, processData, } from './utils/index.js';
6
+ export { iteratePages, request, type BuiltinRequestName, type RequestParamsFor, type RequestResultFor, } from './request/index.js';
7
+ export { readImageFile, type ImageFileContent } from './request/read-image-file.js';
8
+ export { supportsFileBinding } from './request/version.js';
9
+ export { extractFileIdFromUrl, parseFileUrl, type ParsedFileUrl } from './url.js';
10
+ export { createLink, extractFileIdsFromHtml, parseLink, pickFields, pickFieldsSingle, filterData, searchData, sortData, processData, } from './utils/index.js';
8
11
  export { BUILD, VERSION } from './version.js';
9
12
  export type * from './types/index.js';
package/dist/index.js CHANGED
@@ -3,6 +3,9 @@ export { ERRORS, ZentaoError } from './misc/errors.js';
3
3
  export { getGlobalOptions, setGlobalOptions } from './misc/global-options.js';
4
4
  export { ZENTAO_PROFILES_STORAGE_KEY, addProfile, deleteProfile, getAllProfiles, getProfile, getProfileKey, switchProfile, } from './profiles/index.js';
5
5
  export { defineModuleActions, defineModules, exportRegistry, extendModuleAction, getModuleNames, isModuleName, getModule, getModuleAction, getModuleActionParams, getObjectProps, } from './modules/registry.js';
6
- export { request, } from './request/index.js';
7
- export { createLink, extractFileIdFromUrl, extractFileIdsFromHtml, parseLink, pickFields, pickFieldsSingle, filterData, searchData, sortData, processData, } from './utils/index.js';
6
+ export { iteratePages, request, } from './request/index.js';
7
+ export { readImageFile } from './request/read-image-file.js';
8
+ export { supportsFileBinding } from './request/version.js';
9
+ export { extractFileIdFromUrl, parseFileUrl } from './url.js';
10
+ export { createLink, extractFileIdsFromHtml, parseLink, pickFields, pickFieldsSingle, filterData, searchData, sortData, processData, } from './utils/index.js';
8
11
  export { BUILD, VERSION } from './version.js';
@@ -1,3 +1,4 @@
1
+ import type { WriteOutcome } from '../types/response.js';
1
2
  /**
2
3
  * SDK 已知错误码到默认消息的映射表。
3
4
  *
@@ -31,6 +32,7 @@ export declare const ERRORS: {
31
32
  readonly E_INVALID_PARAM: "Invalid value for parameter {param}: {value}";
32
33
  readonly E_INVALID_REQUEST_NAME: "Request name must use the form \"moduleName\", \"moduleName/methodName\", or \"moduleName/<objectID>\".";
33
34
  readonly E_API_FAILED: "ZenTao API returned failure: {message}";
35
+ readonly E_PAGINATION_INCOMPLETE: "Incomplete pagination for {action} at page {page}: {reason}";
34
36
  readonly E_UPLOAD_PATH_UNSUPPORTED: "Local file paths are not supported in browser runtimes. Pass a File or Blob instead.";
35
37
  readonly E_UPLOAD_FILE_NOT_FOUND: "Upload file not found: {path}";
36
38
  readonly E_UPLOAD_FILE_READ_FAILED: "Failed to read upload file: {path}";
@@ -45,6 +47,8 @@ export declare const ERRORS: {
45
47
  export type ErrorCode = keyof typeof ERRORS;
46
48
  /** 仅配置获取失败可选择跳过;取消、版本错误和持久化错误仍须抛出。 @internal */
47
49
  export declare function isZentaoConfigFetchError(error: unknown): boolean;
50
+ /** @internal Normalize transport failures, including failures while consuming a response body. */
51
+ export declare function asTransportError(error: unknown, signal?: AbortSignal, didTimeout?: () => boolean): ZentaoError;
48
52
  /**
49
53
  * SDK 统一错误类型。
50
54
  *
@@ -59,6 +63,8 @@ export declare class ZentaoError extends Error {
59
63
  readonly params: Readonly<Record<string, string | number>>;
60
64
  /** 附加上下文,例如 HTTP 响应详情、原始异常或失败的禅道响应原文。 */
61
65
  readonly details?: unknown;
66
+ /** 高阶对象写请求失败时的写入判定,错误码和 details 保留其原有含义。 */
67
+ readonly writeOutcome?: WriteOutcome;
62
68
  /**
63
69
  * 构造 SDK 错误实例。
64
70
  *
@@ -31,6 +31,7 @@ export const ERRORS = {
31
31
  E_INVALID_PARAM: 'Invalid value for parameter {param}: {value}',
32
32
  E_INVALID_REQUEST_NAME: 'Request name must use the form "moduleName", "moduleName/methodName", or "moduleName/<objectID>".',
33
33
  E_API_FAILED: 'ZenTao API returned failure: {message}',
34
+ E_PAGINATION_INCOMPLETE: 'Incomplete pagination for {action} at page {page}: {reason}',
34
35
  E_UPLOAD_PATH_UNSUPPORTED: 'Local file paths are not supported in browser runtimes. Pass a File or Blob instead.',
35
36
  E_UPLOAD_FILE_NOT_FOUND: 'Upload file not found: {path}',
36
37
  E_UPLOAD_FILE_READ_FAILED: 'Failed to read upload file: {path}',
@@ -46,6 +47,16 @@ export function isZentaoConfigFetchError(error) {
46
47
  return error instanceof ZentaoError && (error.code === 'E_HTTP_ERROR' || error.code === 'E_NETWORK_ERROR'
47
48
  || error.code === 'E_TIMEOUT' || error.code === 'E_INVALID_ZENTAO_CONFIG');
48
49
  }
50
+ /** @internal Normalize transport failures, including failures while consuming a response body. */
51
+ export function asTransportError(error, signal, didTimeout) {
52
+ if (signal?.aborted)
53
+ return new ZentaoError(didTimeout?.() ? 'E_TIMEOUT' : 'E_ABORTED', undefined, error);
54
+ if (error instanceof ZentaoError)
55
+ return error;
56
+ if (error instanceof DOMException && error.name === 'AbortError')
57
+ return new ZentaoError('E_ABORTED', undefined, error);
58
+ return new ZentaoError('E_NETWORK_ERROR', { message: error?.message ?? String(error) }, error);
59
+ }
49
60
  /**
50
61
  * SDK 统一错误类型。
51
62
  *
@@ -3,16 +3,29 @@ import { extractResult } from './resolve.js';
3
3
  import { snapshotToMarkdown } from '../utils/doc-helper/markdown.js';
4
4
  import { isRecord } from '../utils/index.js';
5
5
  import { request } from '../request/index.js';
6
+ import { classifyWriteReceipt, trackWrite, writeAttempts } from '../request/write-outcome.js';
6
7
  import { captureFileSession } from '../client/index.js';
7
- import { ZentaoError } from '../misc/errors.js';
8
+ import { asTransportError, ZentaoError } from '../misc/errors.js';
8
9
  import { VERSION_23_MINIMUMS } from '../misc/zentao-version.js';
9
10
  /** 这些内置接口要求 JSON,不能把 HTTP 200 的 PHP/SQL 错误文本视为成功。 */
10
- const requestJSON = async ({ request: command, body, bodyType, client, timeout, insecure, actionAssistant }) => {
11
- const response = await client.request(command.path, {
11
+ const requestJSON = async (info) => {
12
+ const { request: command, body, bodyType, client, timeout, insecure, actionAssistant } = info;
13
+ const write = writeAttempts.get(info);
14
+ if (write)
15
+ write.phase = 'dispatching';
16
+ const response = await client.request(command.path, trackWrite({
12
17
  method: command.action.method.toUpperCase(),
13
18
  query: command.query, body, bodyType, timeout, insecure, actionAssistant, responseType: 'response',
14
- });
15
- const responseText = await response.text();
19
+ }, write));
20
+ let responseText;
21
+ try {
22
+ responseText = await response.text();
23
+ }
24
+ catch (error) {
25
+ if (!write)
26
+ throw error;
27
+ throw (write.responseBodyError ?? asTransportError)(error);
28
+ }
16
29
  try {
17
30
  return JSON.parse(responseText);
18
31
  }
@@ -28,6 +41,11 @@ const requestJSON = async ({ request: command, body, bodyType, client, timeout,
28
41
  /** 代码库接口只有 status=success 才成功,表单校验还可能返回 result=fail。 */
29
42
  const requestCoderJSON = async (info) => {
30
43
  const response = await requestJSON(info);
44
+ const write = writeAttempts.get(info);
45
+ if (write) {
46
+ const receipt = classifyWriteReceipt(response);
47
+ write.outcome = receipt === 'confirmed' && !(isRecord(response) && response.status === 'success') ? 'unknown' : receipt;
48
+ }
31
49
  if (info.options.raw || (isRecord(response) && response.status === 'success' && response.result !== 'fail'))
32
50
  return response;
33
51
  return isRecord(response)
@@ -96,6 +114,23 @@ const requestCoderJSON = async (info) => {
96
114
  * @internal
97
115
  */
98
116
  export function applyBuiltinOverrides() {
117
+ defineModules({
118
+ name: 'setting',
119
+ display: '系统设置',
120
+ actions: [{
121
+ name: 'workHours',
122
+ minVersion: VERSION_23_MINIMUMS,
123
+ display: '获取工时设置',
124
+ description: 'dailyWorkHours 是每日可用工时,单位为小时。effortUnit 是工时展示单位,day 表示日,hour 表示小时。',
125
+ type: 'get',
126
+ method: 'get',
127
+ path: '/settings/workhours',
128
+ resultType: 'object',
129
+ resultObjectType: null,
130
+ resultGetter: { dailyWorkHours: 'dailyWorkHours', effortUnit: 'effortUnit' },
131
+ request: requestJSON,
132
+ }],
133
+ });
99
134
  // 已纳入 OpenAPI 的接口仅保留 JSON 校验及兼容响应处理。
100
135
  for (const [moduleName, actionName] of [
101
136
  ['db', 'query'], ['db', 'tables'], ['db', 'table'],
@@ -353,7 +388,11 @@ export function applyBuiltinOverrides() {
353
388
  });
354
389
  // 确认表单会重置缺省字段;仅补齐可写字段,不回传详情中的其他属性。
355
390
  extendModuleAction('bug', 'confirm', {
356
- request: async ({ request: command, body, bodyType, client, timeout, insecure, actionAssistant, options }) => {
391
+ request: async (info) => {
392
+ const { request: command, body, client, timeout, insecure, actionAssistant, options } = info;
393
+ const write = writeAttempts.get(info);
394
+ if (write)
395
+ write.phase = 'preparing';
357
396
  const data = { ...body };
358
397
  const fields = ['status', 'assignedTo', 'type', 'pri', 'deadline', 'mailto'];
359
398
  const missing = fields.filter(field => data[field] === undefined);
@@ -382,7 +421,7 @@ export function applyBuiltinOverrides() {
382
421
  if (data.assignedTo === 'closed') {
383
422
  throw new ZentaoError('E_INVALID_PARAM', { param: 'assignedTo', value: 'closed' });
384
423
  }
385
- return requestJSON({ request: command, body: data, bodyType, client, timeout, insecure, actionAssistant, options });
424
+ return requestJSON(trackWrite({ ...info, body: data }, write));
386
425
  },
387
426
  });
388
427
  // 修改 acl 字段默认值为 open
@@ -1,7 +1,11 @@
1
1
  import type { ListPagerInfo, ModuleAction, ModuleActionRequest, ModuleDefinition, RequestProcessOptions } from '../types/index.js';
2
+ /** 支持用户通过 `params.data` 传入 JSON 字符串或对象作为请求体基础值。 */
3
+ export declare function parseRequestData(value: unknown): Record<string, unknown> | undefined;
4
+ /** 取显式字段所属的对象。请求体只复制 params.data 中自身可枚举的字段。 */
5
+ export declare function explicitBodyFieldSource(params: Record<string, unknown>, data: Record<string, unknown> | undefined, key: string): Record<string, unknown> | undefined;
2
6
  /** 将模块名、动作名和调用参数解析为实际 API 请求路径、查询参数和请求体。 */
3
7
  export declare function resolveActionRequest(module: ModuleDefinition, actionName: string, params?: Record<string, unknown>): ModuleActionRequest;
4
8
  /** 根据动作定义中的 resultGetter,从原始响应里提取业务数据。 */
5
9
  export declare function extractResult(action: ModuleAction, response: Record<string, unknown>, params?: Record<string, unknown>, options?: RequestProcessOptions): unknown;
6
10
  /** 根据动作定义中的 pagerGetter,从原始响应里提取分页信息。 */
7
- export declare function extractPager(action: ModuleAction, response: Record<string, unknown>, params?: Record<string, unknown>, options?: RequestProcessOptions): ListPagerInfo | undefined;
11
+ export declare function extractPager(action: ModuleAction, response: Record<string, unknown>, params?: Record<string, unknown>, options?: RequestProcessOptions, toNumber?: (value: unknown) => number): ListPagerInfo | undefined;
@@ -50,7 +50,7 @@ function resolvePath(action, values) {
50
50
  });
51
51
  }
52
52
  /** 支持用户通过 `params.data` 传入 JSON 字符串或对象作为请求体基础值。 */
53
- function parseData(value) {
53
+ export function parseRequestData(value) {
54
54
  if (value === undefined)
55
55
  return undefined;
56
56
  if (typeof value === 'string') {
@@ -64,6 +64,12 @@ function parseData(value) {
64
64
  }
65
65
  return isRecord(value) ? value : undefined;
66
66
  }
67
+ /** 取显式字段所属的对象。请求体只复制 params.data 中自身可枚举的字段。 */
68
+ export function explicitBodyFieldSource(params, data, key) {
69
+ if (data && Object.prototype.propertyIsEnumerable.call(data, key))
70
+ return data;
71
+ return Object.hasOwn(params, key) ? params : undefined;
72
+ }
67
73
  const TRUTHY_STRINGS = new Set(['true', '1', 'yes', 'on']);
68
74
  const FALSY_STRINGS = new Set(['false', '0', 'no', 'off']);
69
75
  /**
@@ -175,7 +181,7 @@ function buildQuery(action, params) {
175
181
  }
176
182
  /** 按 requestBody schema 组装请求体,并对各字段做取值优先级解析与类型转换。 */
177
183
  function buildRequestBody(action, params) {
178
- const base = parseData(params.data);
184
+ const base = parseRequestData(params.data);
179
185
  if (action.requestBody?.schema?.type !== 'object')
180
186
  return base;
181
187
  const data = base ? { ...base } : {};
@@ -183,13 +189,12 @@ function buildRequestBody(action, params) {
183
189
  const required = new Set(schema.required ?? []);
184
190
  for (const [key, property] of Object.entries(schema.properties ?? {})) {
185
191
  // body 字段优先级:params.data 中的字段 > 平铺 params 字段 > schema 默认值。
186
- const hasDataValue = Object.prototype.hasOwnProperty.call(data, key);
187
- const hasParamValue = Object.prototype.hasOwnProperty.call(params, key);
188
- const raw = hasDataValue ? data[key] : hasParamValue ? params[key] : property.defaultValue;
192
+ const source = explicitBodyFieldSource(params, data, key);
193
+ const raw = source ? source[key] : property.defaultValue;
189
194
  if (raw === undefined && (property.required || required.has(key))) {
190
195
  throw new ZentaoError('E_MISSING_PARAM', { param: key });
191
196
  }
192
- const value = coerceValue(raw, property.type, key, hasDataValue);
197
+ const value = coerceValue(raw, property.type, key, source === data);
193
198
  if (value !== undefined) {
194
199
  data[key] = value;
195
200
  }
@@ -229,7 +234,7 @@ export function extractResult(action, response, params = {}, options = {}) {
229
234
  return result;
230
235
  }
231
236
  /** 根据动作定义中的 pagerGetter,从原始响应里提取分页信息。 */
232
- export function extractPager(action, response, params = {}, options = {}) {
237
+ export function extractPager(action, response, params = {}, options = {}, toNumber = Number) {
233
238
  const getter = action.pagerGetter;
234
239
  if (!getter)
235
240
  return response.pager;
@@ -243,8 +248,8 @@ export function extractPager(action, response, params = {}, options = {}) {
243
248
  if (page === undefined || recPerPage === undefined || recTotal === undefined)
244
249
  return undefined;
245
250
  return {
246
- pageID: Number(page),
247
- recPerPage: Number(recPerPage),
248
- recTotal: Number(recTotal),
251
+ pageID: toNumber(page),
252
+ recPerPage: toNumber(recPerPage),
253
+ recTotal: toNumber(recTotal),
249
254
  };
250
255
  }
@@ -1,6 +1,7 @@
1
1
  import { type ZentaoClient } from '../client/index.js';
2
- import type { FileHandlingOptions, FileWarning, ModuleActionRequest } from '../types/index.js';
3
- type FileRequest = (action: 'create' | 'delete', params: Record<string, unknown>, checkSession?: () => void) => Promise<Record<string, unknown>>;
2
+ import type { FileHandlingOptions, FileWarning, ModuleActionRequest, WriteOutcome } from '../types/index.js';
3
+ import { type FileReceipt } from './write-outcome.js';
4
+ type FileRequest = (action: 'create' | 'delete', params: Record<string, unknown>, checkSession?: () => void) => Promise<FileReceipt>;
4
5
  interface Context extends FileHandlingOptions {
5
6
  client: ZentaoClient;
6
7
  version: string | null;
@@ -10,7 +11,6 @@ interface Context extends FileHandlingOptions {
10
11
  }
11
12
  /** Put the batch identifier in the upload query or the object's JSON body. */
12
13
  export declare function setFileUid(command: ModuleActionRequest, value: unknown, version: string | null): string;
13
- export declare function isFileWriteFailure(raw: Record<string, unknown>): boolean;
14
14
  /** Owns only the images uploaded during this object save. */
15
15
  export declare class HtmlFileRequest {
16
16
  private readonly command;
@@ -24,11 +24,11 @@ export declare class HtmlFileRequest {
24
24
  private profile;
25
25
  private fileLink;
26
26
  private warn;
27
- prepare(): Promise<void>;
27
+ prepare(markdownField?: string): Promise<void>;
28
28
  cleanup(): Promise<void>;
29
29
  /** Preserve the primary error and attach enough context to reconcile uncertain writes. */
30
30
  errorWithFiles(error: unknown): unknown;
31
- saveError(error: unknown): Promise<unknown>;
32
- complete(raw: unknown): Promise<void>;
31
+ saveError(error: unknown, outcome: WriteOutcome): Promise<unknown>;
32
+ complete(raw: unknown, outcome: WriteOutcome, rawMode: boolean): Promise<void>;
33
33
  }
34
34
  export {};
@@ -1,18 +1,14 @@
1
1
  import { captureFileSession } from '../client/index.js';
2
2
  import { ZentaoError } from '../misc/errors.js';
3
3
  import { isNodeRuntime } from '../misc/environment.js';
4
- import { assertSupportedVersion, VERSION_23_MINIMUMS } from '../misc/zentao-version.js';
4
+ import { assertSupportedVersion } from '../misc/zentao-version.js';
5
5
  import { resolveResultObjectType } from '../modules/result-object-type.js';
6
6
  import { isRecord } from '../utils/object.js';
7
7
  import { createLink, parseLink } from '../utils/link.js';
8
8
  import { parseHtmlFiles, rewriteHtmlFiles } from './html-files.js';
9
9
  import { inferExtension, normalizeFilename } from './prepare-body.js';
10
- function positiveID(value) {
11
- if (typeof value !== 'number' && typeof value !== 'string')
12
- return undefined;
13
- const id = Number(value);
14
- return Number.isSafeInteger(id) && id > 0 ? id : undefined;
15
- }
10
+ import { FILE_BINDING_MINIMUMS } from './version.js';
11
+ import { positiveID } from './write-outcome.js';
16
12
  function directURL(path) {
17
13
  return /^(?:https?:\/\/|\/\/|#)/i.test(path)
18
14
  || (/^[a-z][a-z\d+.-]*:/i.test(path) && !/^file:/i.test(path));
@@ -43,7 +39,7 @@ export function setFileUid(command, value, version) {
43
39
  if (typeof value !== 'string' || !value || /[^A-Za-z0-9_-]/.test(value) || ['0', '1', 'used', 'apiv2'].includes(value)) {
44
40
  throw new ZentaoError('E_INVALID_PARAM', { param: 'uid', value: typeof value === 'string' ? value : typeof value });
45
41
  }
46
- assertSupportedVersion(version, VERSION_23_MINIMUMS, `${command.module}/${command.action.name}`);
42
+ assertSupportedVersion(version, FILE_BINDING_MINIMUMS, `${command.module}/${command.action.name}`);
47
43
  if (command.module === 'file' && command.action.name === 'create') {
48
44
  const { uid: _uid, extra, ...form } = command.data ?? {};
49
45
  command.data = form;
@@ -54,9 +50,6 @@ export function setFileUid(command, value, version) {
54
50
  }
55
51
  return value;
56
52
  }
57
- export function isFileWriteFailure(raw) {
58
- return raw.status === 'fail' || raw.status === 'error' || raw.result === 'fail' || raw.result === 'error';
59
- }
60
53
  async function localPath(path) {
61
54
  if (!isNodeRuntime())
62
55
  return path;
@@ -174,12 +167,17 @@ export class HtmlFileRequest {
174
167
  stage,
175
168
  code: error instanceof ZentaoError ? error.code : 'E_FILE_OPERATION_FAILED',
176
169
  message: error instanceof Error ? error.message : String(error),
177
- ...(reference ? { field: reference.field, path: reference.path, name: reference.name } : {}),
170
+ field: reference.field, path: reference.path, name: reference.name,
178
171
  ...(fileID !== undefined ? { fileID } : {}),
179
172
  ...(this.uid ? { uid: this.uid } : {}),
180
173
  ...(objectType ? { objectType } : {}),
181
174
  ...(!creating && this.command.id ? { objectID: this.command.id } : {}),
182
175
  };
176
+ if (stage === 'resolve' && error instanceof ZentaoError) {
177
+ const reason = error.details instanceof Error ? error.details.message : error.details;
178
+ if (typeof reason === 'string' && reason)
179
+ warning.message += ` (${reason})`;
180
+ }
183
181
  this.warnings.push(warning);
184
182
  // Notifications must not turn a completed write into a reported failure.
185
183
  try {
@@ -187,12 +185,13 @@ export class HtmlFileRequest {
187
185
  }
188
186
  catch { /* notification only */ }
189
187
  }
190
- async prepare() {
191
- const documents = parseHtmlFiles(this.command.data, this.command.action);
188
+ async prepare(markdownField) {
189
+ const documents = parseHtmlFiles(this.command.data, this.command.action, markdownField);
192
190
  const references = documents.flatMap(document => document.references);
193
191
  if (!references.length)
194
192
  return;
195
193
  const sources = new Map();
194
+ const replacements = new Map();
196
195
  const resolver = this.context.fileResolver;
197
196
  // Finish all user resolution before the first upload, including later fields.
198
197
  for (const reference of references) {
@@ -231,16 +230,17 @@ export class HtmlFileRequest {
231
230
  catch (cause) {
232
231
  const error = new ZentaoError('E_FILE_RESOLVE_FAILED', { path: reference.path }, cause);
233
232
  await this.warn('resolve', error, reference);
234
- throw error;
233
+ if (this.context.continueOnFileResolveError !== true)
234
+ throw error;
235
+ replacements.set(reference, { text: reference.alt?.trim() ? reference.alt : reference.path });
235
236
  }
236
237
  }
237
- if (!sources.size)
238
+ if (!sources.size && !replacements.size)
238
239
  return;
239
240
  if (!this.uid && [...sources.values()].some(source => source.kind === 'upload')) {
240
241
  this.uid = setFileUid(this.command, await newFileUid(), this.context.version);
241
242
  this.checkSession = this.context.client[captureFileSession]();
242
243
  }
243
- const replacements = new Map();
244
244
  const uploaded = new Map();
245
245
  for (const [reference, source] of sources) {
246
246
  if (source.kind === 'url') {
@@ -265,12 +265,9 @@ export class HtmlFileRequest {
265
265
  const file = source.blob
266
266
  ? { data: source.blob, filename: source.name }
267
267
  : { path: source.path, filename: source.name };
268
- const response = await this.context.requestFile('create', { file, uid: this.uid, extra: 'editor' }, this.checkSession);
269
- const data = isRecord(response.data) ? response.data : {};
270
- outcome.id = positiveID(response.id) ?? positiveID(data.id) ?? positiveID(response.data);
271
- const url = typeof response.url === 'string' && response.url.trim() ? response.url : data.url;
272
- if (typeof url === 'string' && url.trim())
273
- outcome.url = url;
268
+ const receipt = await this.context.requestFile('create', { file, uid: this.uid, extra: 'editor' }, this.checkSession);
269
+ outcome.id = receipt.id;
270
+ outcome.url = receipt.url;
274
271
  if (!outcome.id && !outcome.url)
275
272
  throw new ZentaoError('E_FILE_UPLOAD_FAILED');
276
273
  this.uploads.push({ id: outcome.id, url: outcome.url, reference });
@@ -326,41 +323,29 @@ export class HtmlFileRequest {
326
323
  const fileIDs = this.uploads.flatMap(upload => upload.id === undefined ? [] : [upload.id]);
327
324
  const extra = { uid: this.uid, fileIDs, fileWarnings: [...this.warnings] };
328
325
  if (error instanceof ZentaoError) {
329
- return new ZentaoError(error.code, error.params, {
326
+ const failure = new ZentaoError(error.code, error.params, {
330
327
  ...(plainRecord(error.details) ? error.details : { cause: error.details }), ...extra,
331
328
  });
329
+ return Object.defineProperty(failure, 'cause', { value: error, configurable: true });
332
330
  }
333
- if (error instanceof Error && Object.isExtensible(error)) {
334
- const descriptor = Object.getOwnPropertyDescriptor(error, 'details');
335
- if (!descriptor || descriptor.configurable) {
336
- Object.defineProperty(error, 'details', { value: { cause: descriptor?.value, ...extra }, configurable: true });
337
- return error;
338
- }
339
- }
340
- return Object.assign(new Error(error instanceof Error ? error.message : String(error), { cause: error }), { details: extra });
331
+ const failure = new Error(error instanceof Error ? error.message : String(error), { cause: error });
332
+ if (error instanceof Error)
333
+ failure.name = error.name;
334
+ const previousDetails = error instanceof Error ? Object.getOwnPropertyDescriptor(error, 'details')?.value : undefined;
335
+ return Object.assign(failure, { details: previousDetails === undefined ? extra : { cause: previousDetails, ...extra } });
341
336
  }
342
- async saveError(error) {
343
- if (this.uploads.length && error instanceof ZentaoError) {
344
- // Network failures, HTTP 408 and 5xx can follow a successful save.
345
- const status = error.code === 'E_HTTP_ERROR' && isRecord(error.details) ? Number(error.details.status) : 0;
346
- const rejected = [400, 401, 403, 404, 405, 409, 412, 413, 415, 422, 429].includes(status);
347
- if (rejected || ['E_API_FAILED', 'E_INVALID_PARAM', 'E_FILE_SESSION_CHANGED'].includes(error.code)) {
348
- await this.cleanup();
349
- }
350
- }
337
+ async saveError(error, outcome) {
338
+ if (this.uploads.length && (outcome === 'rejected' || outcome === 'not-sent'))
339
+ await this.cleanup();
351
340
  return this.errorWithFiles(error);
352
341
  }
353
- async complete(raw) {
342
+ async complete(raw, outcome, rawMode) {
354
343
  if (!this.uid)
355
344
  return;
356
- if (isRecord(raw) && !(raw.status === 'fail' && typeof raw.httpStatus === 'number' && typeof raw.responseText === 'string')) {
357
- if (isFileWriteFailure(raw))
358
- return this.cleanup();
359
- if (raw.status === 'success' || raw.result === 'success' || positiveID(raw.id) || (isRecord(raw.data) && positiveID(raw.data.id)))
360
- return;
345
+ if (outcome === 'rejected')
346
+ return this.cleanup();
347
+ if (outcome === 'unknown' && !rawMode) {
348
+ throw this.errorWithFiles(new ZentaoError('E_FILE_SAVE_UNCONFIRMED', undefined, raw));
361
349
  }
362
- if (positiveID(raw))
363
- return;
364
- throw this.errorWithFiles(new ZentaoError('E_FILE_SAVE_UNCONFIRMED', undefined, raw));
365
350
  }
366
351
  }
@@ -8,6 +8,8 @@ export interface HtmlFileReference {
8
8
  field: string;
9
9
  path: string;
10
10
  name?: string;
11
+ alt?: string;
12
+ startTag: SourceRange;
11
13
  attributes: Readonly<Record<string, SourceRange>>;
12
14
  insertOffset: number;
13
15
  }
@@ -20,9 +22,12 @@ export interface HtmlFileDocument {
20
22
  export interface HtmlFileReplacement {
21
23
  url?: string;
22
24
  error?: string;
25
+ text?: string;
23
26
  }
27
+ /** 请求体 schema 声明的顶层富文本字段,兼容旧注册表的 (HTML) 说明。 */
28
+ export declare function getHtmlFields(action: ModuleAction): string[];
24
29
  /** 只扫描最终请求体里声明为 HTML 的顶层字符串字段,不创建浏览器 DOM。 */
25
- export declare function parseHtmlFiles(data: Record<string, unknown> | undefined, action: ModuleAction): HtmlFileDocument[];
30
+ export declare function parseHtmlFiles(data: Record<string, unknown> | undefined, action: ModuleAction, markdownField?: string): HtmlFileDocument[];
26
31
  /** 按源码区间一次拼接,仅返回发生改写的字段;其余 HTML 字节保持原样。 */
27
32
  export declare function rewriteHtmlFiles(documents: HtmlFileDocument[], replacements: ReadonlyMap<HtmlFileReference, HtmlFileReplacement>): Record<string, string>;
28
33
  export {};
@@ -1,7 +1,5 @@
1
1
  import { findHtmlImages } from '../utils/html.js';
2
- function isRecord(value) {
3
- return value !== null && typeof value === 'object' && !Array.isArray(value);
4
- }
2
+ import { isRecord } from '../utils/object.js';
5
3
  function nonempty(value) {
6
4
  return value?.trim() || undefined;
7
5
  }
@@ -34,24 +32,34 @@ function sourceFilename(path) {
34
32
  }
35
33
  }
36
34
  function parseReferences(field, html) {
37
- return findHtmlImages(html).map(({ src, alt, attributes, endOffset }) => {
35
+ return findHtmlImages(html).map(({ src, alt, attributes, startTag }) => {
36
+ const { endOffset } = startTag;
38
37
  let insertOffset = endOffset - 1;
39
38
  // An unquoted value may itself end in '/', which is not a self-closing marker.
40
39
  const slash = insertOffset - 1;
41
40
  if (html[slash] === '/' && !Object.values(attributes).some(range => range.startOffset <= slash && range.endOffset > slash)) {
42
41
  insertOffset = slash;
43
42
  }
44
- return { field, path: src, name: nonempty(alt) || sourceFilename(src), attributes, insertOffset };
43
+ return { field, path: src, name: nonempty(alt) || sourceFilename(src), alt, startTag, attributes, insertOffset };
45
44
  });
46
45
  }
47
- /** 只扫描最终请求体里声明为 HTML 的顶层字符串字段,不创建浏览器 DOM。 */
48
- export function parseHtmlFiles(data, action) {
46
+ /** 请求体 schema 声明的顶层富文本字段,兼容旧注册表的 (HTML) 说明。 */
47
+ export function getHtmlFields(action) {
49
48
  const properties = action.requestBody?.schema.properties;
50
- if (!data || !isRecord(properties))
49
+ if (!isRecord(properties))
50
+ return [];
51
+ return Object.keys(properties).filter(field => {
52
+ const schema = properties[field];
53
+ return isRecord(schema) && (schema.textType === 'html' || (typeof schema.description === 'string' && schema.description.endsWith('(HTML)')));
54
+ });
55
+ }
56
+ /** 只扫描最终请求体里声明为 HTML 的顶层字符串字段,不创建浏览器 DOM。 */
57
+ export function parseHtmlFiles(data, action, markdownField) {
58
+ if (!data)
51
59
  return [];
52
60
  const documents = [];
53
- for (const [field, schema] of Object.entries(properties)) {
54
- if (!isRecord(schema) || (schema.textType !== 'html' && !(typeof schema.description === 'string' && schema.description.endsWith('(HTML)'))))
61
+ for (const field of getHtmlFields(action)) {
62
+ if (field === markdownField)
55
63
  continue;
56
64
  const html = data[field];
57
65
  if (typeof html !== 'string')
@@ -62,7 +70,7 @@ export function parseHtmlFiles(data, action) {
62
70
  }
63
71
  return documents;
64
72
  }
65
- function escapeAttribute(value) {
73
+ function escapeHtml(value) {
66
74
  return value.replace(/[&"<>]/g, char => ({ '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' })[char]);
67
75
  }
68
76
  /** 按源码区间一次拼接,仅返回发生改写的字段;其余 HTML 字节保持原样。 */
@@ -74,6 +82,11 @@ export function rewriteHtmlFiles(documents, replacements) {
74
82
  const replacement = replacements.get(reference);
75
83
  if (!replacement)
76
84
  continue;
85
+ if (replacement.text !== undefined) {
86
+ const { startOffset, endOffset } = reference.startTag;
87
+ edits.push({ start: startOffset, end: endOffset, value: escapeHtml(replacement.text) });
88
+ continue;
89
+ }
77
90
  const name = replacement.error === undefined ? 'src' : 'alt';
78
91
  const value = replacement.error ?? replacement.url;
79
92
  if (value === undefined)
@@ -81,10 +94,10 @@ export function rewriteHtmlFiles(documents, replacements) {
81
94
  const range = reference.attributes[name];
82
95
  if (range) {
83
96
  const spelling = document.html.slice(range.startOffset, range.endOffset).match(/^[^\t\n\f\r =/>]+/)?.[0] || name;
84
- edits.push({ start: range.startOffset, end: range.endOffset, value: `${spelling}="${escapeAttribute(value)}"` });
97
+ edits.push({ start: range.startOffset, end: range.endOffset, value: `${spelling}="${escapeHtml(value)}"` });
85
98
  }
86
99
  else {
87
- edits.push({ start: reference.insertOffset, end: reference.insertOffset, value: ` ${name}="${escapeAttribute(value)}"` });
100
+ edits.push({ start: reference.insertOffset, end: reference.insertOffset, value: ` ${name}="${escapeHtml(value)}"` });
88
101
  }
89
102
  }
90
103
  if (!edits.length)