zentao-api 0.9.3 → 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 +29 -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 +9 -1
  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 +2 -1
  30. package/dist/types/options.d.ts +20 -0
  31. package/dist/types/response.d.ts +17 -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 +2 -2
  39. package/dist/utils/url.d.ts +1 -8
  40. package/dist/utils/url.js +6 -64
  41. package/dist/version.js +2 -2
  42. package/package.json +5 -1
@@ -0,0 +1,36 @@
1
+ import { isZentaoConfigFetchError, ZentaoError } from '../misc/errors.js';
2
+ import { getGlobalOptions } from '../misc/global-options.js';
3
+ import { parseZentaoVersion, supportsZentaoVersion, VERSION_23_MINIMUMS } from '../misc/zentao-version.js';
4
+ /** @internal 上传与对象保存通过同一 uid 绑定附件的最低版本。 */
5
+ export const FILE_BINDING_MINIMUMS = VERSION_23_MINIMUMS;
6
+ /** @internal null 表示调用方明确允许配置获取失败后跳过版本检查。 */
7
+ export async function resolveRequestVersion(options, globals, version = globals.version) {
8
+ if (!options.forceRefreshConfig && version !== undefined)
9
+ return version;
10
+ const client = options.client ?? globals.client;
11
+ if (!client)
12
+ throw new ZentaoError('E_NO_GLOBAL_CLIENT');
13
+ try {
14
+ return (await client.getZentaoConfig({
15
+ forceRefresh: options.forceRefreshConfig,
16
+ timeout: options.timeout ?? globals.timeout,
17
+ insecure: options.insecure ?? globals.insecure,
18
+ })).version;
19
+ }
20
+ catch (error) {
21
+ if (!(options.skipVersionCheckOnConfigError ?? globals.skipVersionCheckOnConfigError)
22
+ || !isZentaoConfigFetchError(error))
23
+ throw error;
24
+ return null;
25
+ }
26
+ }
27
+ /**
28
+ * 判断当前禅道版本是否支持用 uid 将编辑器附件绑定到对象。版本门槛与实际保存共用。
29
+ * @param options - 可传已知版本或客户端。默认使用全局版本,缺省时读取客户端的站点配置。
30
+ * @returns 已知版本返回布尔值。配置获取失败且允许跳过版本检查时返回 `undefined`。
31
+ * @throws {ZentaoError} 版本格式非法或无法获取所需配置时抛出对应的 SDK 错误。
32
+ */
33
+ export async function supportsFileBinding(options = {}) {
34
+ const version = await resolveRequestVersion(options, getGlobalOptions(), options.version);
35
+ return version === null ? undefined : supportsZentaoVersion(parseZentaoVersion(version), FILE_BINDING_MINIMUMS);
36
+ }
@@ -0,0 +1,23 @@
1
+ import { ZentaoError } from '../misc/errors.js';
2
+ import type { WriteOutcome } from '../types/response.js';
3
+ export interface WriteAttempt {
4
+ phase?: 'preparing' | 'before-hook' | 'custom' | 'dispatching' | 'received';
5
+ outcome?: WriteOutcome;
6
+ /** A strict JSON action consumes its Response after client.fetch has returned the headers. */
7
+ responseBodyError?: (cause: unknown) => ZentaoError;
8
+ }
9
+ export declare const writeAttempts: WeakMap<object, WriteAttempt>;
10
+ export declare const rejectionStatuses: ReadonlySet<number>;
11
+ export declare function trackWrite<T extends object>(options: T, write: WriteAttempt | undefined): T;
12
+ export declare function positiveID(value: unknown): number | undefined;
13
+ type ReceiptOutcome = Exclude<WriteOutcome, 'not-sent'>;
14
+ export declare function classifyWriteReceipt(raw: unknown): ReceiptOutcome;
15
+ export interface FileReceipt {
16
+ outcome: ReceiptOutcome;
17
+ message?: unknown;
18
+ id?: number;
19
+ url?: string;
20
+ }
21
+ export declare function readFileReceipt(action: 'create' | 'delete', raw: unknown): FileReceipt;
22
+ export declare function classifyWriteError(phase: WriteAttempt['phase'], error: unknown): WriteOutcome;
23
+ export {};
@@ -0,0 +1,79 @@
1
+ import { ZentaoError } from '../misc/errors.js';
2
+ import { isBlank, isRecord } from '../utils/object.js';
3
+ // Associate only the primary transport's fresh options with this write. A shared
4
+ // client, a prefetch or an attachment request can run concurrently with it.
5
+ export const writeAttempts = new WeakMap();
6
+ // These HTTP responses explicitly reject the request. A 408 or 5xx can follow a successful save.
7
+ export const rejectionStatuses = new Set([400, 401, 403, 404, 405, 409, 412, 413, 415, 422, 429]);
8
+ export function trackWrite(options, write) {
9
+ if (write)
10
+ writeAttempts.set(options, write);
11
+ return options;
12
+ }
13
+ export function positiveID(value) {
14
+ if (typeof value !== 'number' && typeof value !== 'string')
15
+ return undefined;
16
+ const id = Number(value);
17
+ return Number.isSafeInteger(id) && id > 0 ? id : undefined;
18
+ }
19
+ function failed(value) {
20
+ return value === 'fail' || value === 'error' || value === 'failed';
21
+ }
22
+ function explicitOutcome(record) {
23
+ // The strict JSON adapter builds this diagnostic when it cannot read a valid receipt.
24
+ if (record.status === 'fail' && typeof record.httpStatus === 'number' && typeof record.responseText === 'string')
25
+ return 'unknown';
26
+ if (failed(record.status) || failed(record.result))
27
+ return 'rejected';
28
+ if (record.status === 'success' || record.result === 'success')
29
+ return 'confirmed';
30
+ }
31
+ export function classifyWriteReceipt(raw) {
32
+ if (isRecord(raw)) {
33
+ const outcome = explicitOutcome(raw);
34
+ if (outcome)
35
+ return outcome;
36
+ if (positiveID(raw.id))
37
+ return 'confirmed';
38
+ if (isRecord(raw.data) && positiveID(raw.data.id))
39
+ return 'confirmed';
40
+ }
41
+ return positiveID(raw) ? 'confirmed' : 'unknown';
42
+ }
43
+ function fileURL(value) {
44
+ return typeof value === 'string' && value.trim() ? value : undefined;
45
+ }
46
+ // Upload and deletion can wrap a second receipt in data. Other actions use data for business objects.
47
+ export function readFileReceipt(action, raw) {
48
+ const record = isRecord(raw) ? raw : undefined;
49
+ const data = record?.data;
50
+ const nested = isRecord(data) ? data : undefined;
51
+ const outcome = record && explicitOutcome(record);
52
+ const message = record?.message;
53
+ if (outcome === 'unknown')
54
+ return { outcome, message };
55
+ if (outcome === 'rejected') {
56
+ const fallback = nested && explicitOutcome(nested) !== 'confirmed' ? nested.message : undefined;
57
+ return { outcome, message: isBlank(message) ? fallback ?? message : message };
58
+ }
59
+ if (nested && (failed(nested.status) || failed(nested.result))) {
60
+ const reason = nested.message;
61
+ return { outcome: 'rejected', message: isBlank(reason) && !outcome ? message ?? reason : reason };
62
+ }
63
+ if (action === 'delete')
64
+ return { outcome: outcome ?? 'unknown', message };
65
+ const id = positiveID(record?.id) ?? positiveID(nested?.id) ?? positiveID(record ? data : raw);
66
+ const url = fileURL(record?.url) ?? fileURL(nested?.url);
67
+ return { outcome: outcome ?? (id ? 'confirmed' : 'unknown'), message, id, url };
68
+ }
69
+ export function classifyWriteError(phase, error) {
70
+ if (phase === 'preparing' || phase === 'before-hook')
71
+ return 'not-sent';
72
+ if (phase === 'dispatching' && error instanceof ZentaoError) {
73
+ if (error.code === 'E_API_FAILED')
74
+ return 'rejected';
75
+ if (error.code === 'E_HTTP_ERROR' && isRecord(error.details) && rejectionStatuses.has(Number(error.details.status)))
76
+ return 'rejected';
77
+ }
78
+ return 'unknown';
79
+ }
@@ -109,7 +109,8 @@ export type ModuleActionGetterFn<T, O = RequestProcessOptions> = (data: unknown,
109
109
  export type ModuleActionBeforeRequestCallback = (request: ModuleActionRequest) => Promise<Partial<Omit<ModuleActionRequest, 'module' | 'action'>>>;
110
110
  /**
111
111
  * 自定义动作的请求发送逻辑,在版本检查、参数解析和请求体准备完成后调用。
112
- * 返回原始响应数据,后续仍按动作定义提取结果、分页并应用请求选项;抛出的错误原样传递。
112
+ * 返回原始响应数据,后续按动作定义提取结果、分页并应用请求选项。
113
+ * 默认原样传递回调抛出的异常。需要附加附件批次或警告时,SDK 为当前请求创建异常,并通过 `cause` 保留原异常。
113
114
  */
114
115
  export type ModuleActionRequestCallback = (info: {
115
116
  /** 解析后的路径、查询参数、请求体数据及动作定义。 */
@@ -2,8 +2,17 @@ import type { ZentaoClient } from '../client/index.js';
2
2
  import type { ActionAssistant } from './client.js';
3
3
  import type { ProcessListOptions, ProcessSingleOptions } from './data.js';
4
4
  import type { FileHandlingOptions } from './upload.js';
5
+ import type { WriteOutcome } from './response.js';
6
+ /** 将一个显式提交的 Markdown 字段渲染为 HTML。上下文给出注册表中的模块、动作和字段名。 */
7
+ export type MarkdownRenderer = (markdown: string, context: {
8
+ module: string;
9
+ action: string;
10
+ field: string;
11
+ }) => string | Promise<string>;
5
12
  /** SDK 进程级全局默认选项,供请求和 {@link createLink} 等辅助方法复用。 */
6
13
  export interface GlobalOptions extends FileHandlingOptions {
14
+ /** 默认 Markdown 渲染回调,详见 {@link RequestOptions.renderMarkdown}。 */
15
+ renderMarkdown?: MarkdownRenderer;
7
16
  /** 当前禅道正式版本,例如 `biz13.5`;普通高阶请求直接使用,单次强制刷新时使用实际版本。不会自动写入 profile。 */
8
17
  version?: string;
9
18
  /** 配置网络或响应获取失败时,允许登录继续或高阶请求跳过版本检查,默认 false;不忽略版本不匹配、格式错误或存储错误。 */
@@ -35,6 +44,13 @@ export interface GlobalOptions extends FileHandlingOptions {
35
44
  }
36
45
  /** 高阶 `request("moduleName")` / `request("moduleName/methodName")` / `request("moduleName/<objectID>")` 的单次调用选项。 */
37
46
  export interface RequestOptions extends ProcessListOptions, FileHandlingOptions {
47
+ /**
48
+ * 在 autoFill 前把本次 POST / PUT 显式提交的富文本字段渲染为 HTML。
49
+ * `params.data` 的同名字段优先,空白字符串和已有 HTML 原样保留。
50
+ * `doc.content` 仅在本次显式指定 `contentType: 'html'` 时参与渲染。
51
+ * 默认使用全局回调,传 `false` 可关闭本次渲染。
52
+ */
53
+ renderMarkdown?: MarkdownRenderer | false;
38
54
  /** 强制刷新服务器配置并用实际版本校验本次请求,优先于全局 version;不会改写全局版本。 */
39
55
  forceRefreshConfig?: boolean;
40
56
  /** 配置网络或响应获取失败时跳过本次版本检查;优先于全局设置,默认 false,不忽略版本不匹配或格式错误。 */
@@ -71,5 +87,9 @@ export interface RequestOptions extends ProcessListOptions, FileHandlingOptions
71
87
  autoFill?: boolean;
72
88
  /** 是否返回原始响应体,默认 false。 */
73
89
  raw?: boolean;
90
+ /** 对象写操作结束时通知一次,包括抛错和 raw 模式。读取操作跳过通知,回调异常不影响请求结果。 */
91
+ onWriteOutcome?: (outcome: WriteOutcome) => void | Promise<void>;
74
92
  }
75
93
  export type RequestProcessOptions = ProcessListOptions & Pick<RequestOptions, 'convertSingle'>;
94
+ /** 附件绑定能力查询使用的版本和配置读取选项。显式 version 优先于全局版本,forceRefreshConfig 优先使用站点实际版本。 */
95
+ export type FileBindingOptions = Pick<GlobalOptions, 'version'> & Pick<RequestOptions, 'client' | 'forceRefreshConfig' | 'skipVersionCheckOnConfigError' | 'timeout' | 'insecure'>;
@@ -1,8 +1,19 @@
1
1
  import type { FileWarning } from './upload.js';
2
+ /**
3
+ * 目标对象的写入结果。
4
+ *
5
+ * - `not-sent` 表示目标写请求尚未发起,例如更新前读取旧值失败。
6
+ * - `rejected` 表示服务端明确拒绝目标写请求。
7
+ * - `unknown` 表示回执不足以判定结果,需要回读对象确认。
8
+ * - `confirmed` 表示收到了成功回执。
9
+ */
10
+ export type WriteOutcome = 'not-sent' | 'rejected' | 'unknown' | 'confirmed';
2
11
  /** 高阶 `request()` 归一化后的返回数据。 */
3
12
  export interface ResponseData<T = unknown> {
4
13
  /** 禅道服务端状态;非标准响应会按成功响应包装到 `data`。 */
5
14
  status: 'success' | 'fail';
15
+ /** 对象写操作的回执判定。读取操作省略此字段。 */
16
+ writeOutcome?: WriteOutcome;
6
17
  /** 禅道服务端返回的消息。 */
7
18
  message?: string;
8
19
  /** 原始消息字段;当服务端返回对象/数组等非字符串消息时保留在这里。 */
@@ -30,6 +41,12 @@ export interface ResponseData<T = unknown> {
30
41
  recPerPage: number;
31
42
  };
32
43
  }
44
+ /** {@link iteratePages} 交付的单页结果,包含本地处理后的记录和服务端分页信息。 */
45
+ export interface ListPage<Row> extends ResponseData<Row[]> {
46
+ status: 'success';
47
+ data: Row[];
48
+ pager: NonNullable<ResponseData['pager']>;
49
+ }
33
50
  /** 禅道 API 原始分页结构。 */
34
51
  export interface Pager {
35
52
  /** 总记录数。 */
@@ -60,7 +60,7 @@ export type ResolvedFile = string | {
60
60
  };
61
61
  /**
62
62
  * HTML 图片解析器。函数可异步执行;映射依次按路径和文件名查找自身属性。
63
- * 映射的字符串值以命中的 key 为文件名。未命中、抛错或返回无效来源时终止请求。
63
+ * 映射的字符串值以命中的 key 为文件名。未命中、抛错或返回无效来源时按 {@link FileHandlingOptions.continueOnFileResolveError} 处理。
64
64
  */
65
65
  export type FileResolver = ((reference: FileReference) => ResolvedFile | Promise<ResolvedFile>) | Record<string, ResolvedFile>;
66
66
  /** 富文本图片处理中的错误上下文。 */
@@ -71,9 +71,9 @@ export interface FileWarning {
71
71
  code: string;
72
72
  /** 可读错误消息。 */
73
73
  message: string;
74
- /** HTML body 字段名。 */
74
+ /** 原 HTML body 字段名。解析警告始终提供此字段。 */
75
75
  field?: string;
76
- /** 原始文件引用路径。 */
76
+ /** 原图片 src 的路径,已解码 HTML 实体。解析警告始终提供此字段。 */
77
77
  path?: string;
78
78
  /** 文件名。 */
79
79
  name?: string;
@@ -90,7 +90,9 @@ export interface FileWarning {
90
90
  export interface FileHandlingOptions {
91
91
  /** 解析本地及自定义文件引用;HTTP(S) 和已有禅道文件链接直接保留。 */
92
92
  fileResolver?: FileResolver;
93
- /** 上传或读取本地文件失败后是否标注 HTML 并继续主请求,默认 true;解析器失败始终终止。 */
93
+ /** 解析失败时,将该图片替换为原 alt 的纯文本,缺省时取原路径,记录警告并继续保存。默认 false,在上传前中止。 */
94
+ continueOnFileResolveError?: boolean;
95
+ /** 上传或读取本地文件失败后是否标注 HTML 并继续主请求,默认 true。 */
94
96
  continueOnFileUploadError?: boolean;
95
97
  /**
96
98
  * 文件错误通知;支持异步回调,回调异常不改变主请求结果。
package/dist/url.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type ParsedFileUrl } from './utils/file-url.js';
2
+ export type { ParsedFileUrl };
3
+ /**
4
+ * 从禅道图片或附件下载链接提取文件 ID,支持路径路由和 GET 查询路由。
5
+ *
6
+ * @param url - file/read 或 file/download 的相对路径或 HTTP(S) 地址。查询参数可使用 `&amp;` 分隔。
7
+ * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
8
+ * @returns 正的安全整数 ID。地址无效、站点或路由不匹配时返回 `undefined`。
9
+ */
10
+ export declare function extractFileIdFromUrl(url: string, siteUrl?: string): number | undefined;
11
+ /**
12
+ * 解析禅道附件的读取或下载路由。路径式链接可附带普通查询参数。
13
+ * 用查询参数指定路由时,模块、方法和文件 ID 必须唯一,且不能与路径路由混用。
14
+ *
15
+ * @param url - 附件路径或 URL,支持一次 HTML `&amp;` 转义。
16
+ * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
17
+ * @returns 路由信息。地址无效、站点不匹配或路由含糊时返回 `undefined`。
18
+ */
19
+ export declare function parseFileUrl(url: string, siteUrl?: string): ParsedFileUrl | undefined;
package/dist/url.js ADDED
@@ -0,0 +1,22 @@
1
+ import { parseFileRoute } from './utils/file-url.js';
2
+ /**
3
+ * 从禅道图片或附件下载链接提取文件 ID,支持路径路由和 GET 查询路由。
4
+ *
5
+ * @param url - file/read 或 file/download 的相对路径或 HTTP(S) 地址。查询参数可使用 `&amp;` 分隔。
6
+ * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
7
+ * @returns 正的安全整数 ID。地址无效、站点或路由不匹配时返回 `undefined`。
8
+ */
9
+ export function extractFileIdFromUrl(url, siteUrl) {
10
+ return parseFileRoute(url, siteUrl, 'fileUrl')?.fileID;
11
+ }
12
+ /**
13
+ * 解析禅道附件的读取或下载路由。路径式链接可附带普通查询参数。
14
+ * 用查询参数指定路由时,模块、方法和文件 ID 必须唯一,且不能与路径路由混用。
15
+ *
16
+ * @param url - 附件路径或 URL,支持一次 HTML `&amp;` 转义。
17
+ * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
18
+ * @returns 路由信息。地址无效、站点不匹配或路由含糊时返回 `undefined`。
19
+ */
20
+ export function parseFileUrl(url, siteUrl) {
21
+ return parseFileRoute(url, siteUrl, 'strict');
22
+ }
@@ -0,0 +1,13 @@
1
+ /** @internal 解析带安装目录的站点地址,兼容 API v2 根地址。 */
2
+ export declare function tryNormalizeSiteUrl(baseUrl: string): string | undefined;
3
+ /** 禅道附件页面路由。只有路径式 read 链接提供文件后缀。 */
4
+ export interface ParsedFileUrl {
5
+ fileID: number;
6
+ method: 'read' | 'download';
7
+ /** 小写后缀,不含点。查询路由的视图参数不代表文件格式。 */
8
+ extension?: string;
9
+ }
10
+ type FileUrlMode = 'fileUrl' | 'imageSrc' | 'strict';
11
+ /** @internal HTML src values are already entity-decoded and only identify read routes. */
12
+ export declare function parseFileRoute(url: string, siteUrl: string | undefined, source: FileUrlMode): ParsedFileUrl | undefined;
13
+ export {};
@@ -0,0 +1,80 @@
1
+ /** @internal 解析带安装目录的站点地址,兼容 API v2 根地址。 */
2
+ export function tryNormalizeSiteUrl(baseUrl) {
3
+ const trimmed = baseUrl.trim().replace(/\/+$/, '');
4
+ const siteUrl = trimmed.replace(/\/api\.php\/v2$/i, '');
5
+ let parsed;
6
+ try {
7
+ parsed = new URL(siteUrl);
8
+ }
9
+ catch {
10
+ return undefined;
11
+ }
12
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.search || parsed.hash) {
13
+ return undefined;
14
+ }
15
+ return parsed.toString().replace(/\/+$/, '');
16
+ }
17
+ function fileQueryParams(url, mode) {
18
+ if (mode === 'imageSrc')
19
+ return url.searchParams;
20
+ const search = url.search.replace(mode === 'strict' ? /&amp;/gi : /&amp;/g, '&');
21
+ return search === url.search ? url.searchParams : new URLSearchParams(search);
22
+ }
23
+ /** @internal HTML src values are already entity-decoded and only identify read routes. */
24
+ export function parseFileRoute(url, siteUrl, source) {
25
+ const src = typeof url === 'string' ? url.trim() : '';
26
+ if (!src || /[\\\u0000-\u001f]/.test(src))
27
+ return undefined;
28
+ let parsed;
29
+ try {
30
+ let base = 'https://zentao.invalid/';
31
+ if (/^(?:https?:)?\/\//i.test(src)) {
32
+ const site = siteUrl && tryNormalizeSiteUrl(siteUrl);
33
+ if (!site)
34
+ return undefined;
35
+ base = `${site}/`;
36
+ }
37
+ else if (/^[a-z][a-z\d+.-]*:/i.test(src)) {
38
+ return undefined;
39
+ }
40
+ parsed = new URL(src, base);
41
+ if (!parsed.href.startsWith(base))
42
+ return undefined;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ if (!parsed.pathname.endsWith('/') && !parsed.pathname.endsWith('/index.php')) {
48
+ if (source === 'strict' && parsed.search) {
49
+ const params = fileQueryParams(parsed, source);
50
+ if (['module', 'method', 'm', 'f', 'fileID'].some(key => params.has(key)))
51
+ return undefined;
52
+ }
53
+ const read = /\/file-read-(\d+)(?:\.([A-Za-z0-9]+))?$/.exec(parsed.pathname);
54
+ if (read && (read[2] || source === 'strict'))
55
+ return fileRoute(read[1], 'read', read[2]?.toLowerCase());
56
+ if (source === 'imageSrc')
57
+ return undefined;
58
+ const download = /\/file-download-(\d+)(?:-left)?\.html$/.exec(parsed.pathname);
59
+ return download ? fileRoute(download[1], 'download') : undefined;
60
+ }
61
+ const params = fileQueryParams(parsed, source);
62
+ if (source === 'strict' && (params.getAll('fileID').length !== 1
63
+ || params.getAll('module').length + params.getAll('m').length !== 1
64
+ || params.getAll('method').length + params.getAll('f').length !== 1))
65
+ return undefined;
66
+ for (const [moduleKey, methodKey] of [['module', 'method'], ['m', 'f']]) {
67
+ const method = params.get(methodKey);
68
+ if (params.get(moduleKey) === 'file' && (method === 'read' || (source !== 'imageSrc' && method === 'download'))) {
69
+ const digits = params.get('fileID');
70
+ if (digits && /^\d+$/.test(digits))
71
+ return fileRoute(digits, method);
72
+ }
73
+ }
74
+ }
75
+ function fileRoute(digits, method, extension) {
76
+ const fileID = Number(digits);
77
+ if (Number.isSafeInteger(fileID) && fileID > 0) {
78
+ return extension ? { fileID, method, extension } : { fileID, method };
79
+ }
80
+ }
@@ -3,7 +3,7 @@ interface HtmlImage {
3
3
  src: string;
4
4
  alt?: string;
5
5
  attributes: Record<string, Token.Location>;
6
- endOffset: number;
6
+ startTag: Token.Location;
7
7
  }
8
8
  /** @internal 按源码顺序收集图片属性和起始标签位置。 */
9
9
  export declare function findHtmlImages(html: string): HtmlImage[];
@@ -32,10 +32,10 @@ export function findHtmlImages(html) {
32
32
  if (!src || !attributes?.src || !startTag || html[startTag.endOffset - 1] !== '>' || seenOffsets.has(startTag.startOffset))
33
33
  continue;
34
34
  seenOffsets.add(startTag.startOffset);
35
- images.push({ src, alt: attribute(node, 'alt'), attributes, endOffset: startTag.endOffset });
35
+ images.push({ src, alt: attribute(node, 'alt'), attributes, startTag });
36
36
  }
37
37
  // HTML error recovery can move elements ahead of earlier source tags.
38
- return images.sort((a, b) => a.endOffset - b.endOffset);
38
+ return images.sort((a, b) => a.startTag.startOffset - b.startTag.startOffset);
39
39
  }
40
40
  /**
41
41
  * 按富文本 HTML 中 `<img>` 的出现顺序提取禅道图片引用,保留重复项。
@@ -1,12 +1,5 @@
1
+ export { extractFileIdFromUrl } from '../url.js';
1
2
  /** 将用户传入的站点根地址规范化,兼容误传入 `/api.php/v2` 的场景。 */
2
3
  export declare function normalizeSiteUrl(baseUrl: string): string;
3
- /**
4
- * 从禅道图片或附件下载链接提取文件 ID,支持路径路由和 GET 查询路由。
5
- *
6
- * @param url - file/read 或 file/download 的相对路径或 HTTP(S) 地址。查询参数可使用 `&amp;` 分隔。
7
- * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
8
- * @returns 正的安全整数 ID。地址无效、站点或路由不匹配时返回 `undefined`。
9
- */
10
- export declare function extractFileIdFromUrl(url: string, siteUrl?: string): number | undefined;
11
4
  /** @internal An HTML image src is already entity-decoded and identifies only a read route. */
12
5
  export declare function parseFileIdFromUrl(url: string, siteUrl: string | undefined, source: 'fileUrl' | 'imageSrc'): number | undefined;
package/dist/utils/url.js CHANGED
@@ -1,72 +1,14 @@
1
1
  import { ZentaoError } from '../misc/errors.js';
2
+ import { parseFileRoute, tryNormalizeSiteUrl } from './file-url.js';
3
+ export { extractFileIdFromUrl } from '../url.js';
2
4
  /** 将用户传入的站点根地址规范化,兼容误传入 `/api.php/v2` 的场景。 */
3
5
  export function normalizeSiteUrl(baseUrl) {
4
- const trimmed = baseUrl.trim().replace(/\/+$/, '');
5
- if (!trimmed)
6
+ const url = tryNormalizeSiteUrl(baseUrl);
7
+ if (!url)
6
8
  throw new ZentaoError('E_INVALID_BASE_URL');
7
- const siteUrl = trimmed.replace(/\/api\.php\/v2$/i, '');
8
- let parsed;
9
- try {
10
- parsed = new URL(siteUrl);
11
- }
12
- catch {
13
- throw new ZentaoError('E_INVALID_BASE_URL');
14
- }
15
- if (!['http:', 'https:'].includes(parsed.protocol) || parsed.search || parsed.hash) {
16
- throw new ZentaoError('E_INVALID_BASE_URL');
17
- }
18
- return parsed.toString().replace(/\/+$/, '');
19
- }
20
- /**
21
- * 从禅道图片或附件下载链接提取文件 ID,支持路径路由和 GET 查询路由。
22
- *
23
- * @param url - file/read 或 file/download 的相对路径或 HTTP(S) 地址。查询参数可使用 `&amp;` 分隔。
24
- * @param siteUrl - 禅道站点根地址,含安装目录。解析带域名的地址时必填。
25
- * @returns 正的安全整数 ID。地址无效、站点或路由不匹配时返回 `undefined`。
26
- */
27
- export function extractFileIdFromUrl(url, siteUrl) {
28
- return parseFileIdFromUrl(url, siteUrl, 'fileUrl');
9
+ return url;
29
10
  }
30
11
  /** @internal An HTML image src is already entity-decoded and identifies only a read route. */
31
12
  export function parseFileIdFromUrl(url, siteUrl, source) {
32
- const src = typeof url === 'string' ? url.trim() : '';
33
- if (!src || /[\\\u0000-\u001f]/.test(src))
34
- return undefined;
35
- let parsed;
36
- try {
37
- let base = 'https://zentao.invalid/';
38
- if (/^(?:https?:)?\/\//i.test(src)) {
39
- if (!siteUrl)
40
- return undefined;
41
- base = `${normalizeSiteUrl(siteUrl)}/`;
42
- }
43
- else if (/^[a-z][a-z\d+.-]*:/i.test(src)) {
44
- return undefined;
45
- }
46
- parsed = new URL(src, base);
47
- if (!parsed.href.startsWith(base))
48
- return undefined;
49
- }
50
- catch {
51
- return undefined;
52
- }
53
- let digits = /\/file-read-(\d+)\.[A-Za-z0-9]+$/.exec(parsed.pathname)?.[1];
54
- if (!digits && source === 'fileUrl')
55
- digits = /\/file-download-(\d+)(?:-left)?\.html$/.exec(parsed.pathname)?.[1];
56
- if (!digits) {
57
- if (!parsed.pathname.endsWith('/') && !parsed.pathname.endsWith('/index.php'))
58
- return undefined;
59
- const params = source === 'fileUrl' && parsed.search.includes('&amp;')
60
- ? new URLSearchParams(parsed.search.replaceAll('&amp;', '&'))
61
- : parsed.searchParams;
62
- const matchesMethod = (method) => method === 'read' || (source === 'fileUrl' && method === 'download');
63
- if (!(params.get('module') === 'file' && matchesMethod(params.get('method')))
64
- && !(params.get('m') === 'file' && matchesMethod(params.get('f'))))
65
- return undefined;
66
- digits = params.get('fileID') ?? '';
67
- if (!/^\d+$/.test(digits))
68
- return undefined;
69
- }
70
- const id = Number(digits);
71
- return Number.isSafeInteger(id) && id > 0 ? id : undefined;
13
+ return parseFileRoute(url, siteUrl, source)?.fileID;
72
14
  }
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
- const fallbackBuild = "2026-11-19T07:59:08.352Z";
2
- const fallbackVersion = "0.9.3";
1
+ const fallbackBuild = "2026-11-23T05:02:39.126Z";
2
+ const fallbackVersion = "0.9.4";
3
3
  /**
4
4
  * 构建标识,由构建脚本通过 `__ZENTAO_API_BUILD__` 注入。
5
5
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zentao-api",
3
- "version": "0.9.3",
3
+ "version": "0.9.4",
4
4
  "type": "module",
5
5
  "description": "Browser and Node.js SDK for ZenTao API",
6
6
  "license": "MIT",
@@ -33,6 +33,10 @@
33
33
  "import": "./dist/browser.js"
34
34
  },
35
35
  "./browser/global": "./dist/browser/zentao-api.global.js",
36
+ "./url": {
37
+ "types": "./dist/url.d.ts",
38
+ "import": "./dist/url.js"
39
+ },
36
40
  "./package.json": "./package.json"
37
41
  },
38
42
  "files": [