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.
- package/README.md +13 -5
- package/dist/browser/zentao-api.global.js +19 -19
- package/dist/client/index.js +19 -11
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -2
- package/dist/misc/errors.d.ts +6 -0
- package/dist/misc/errors.js +11 -0
- package/dist/modules/override.js +46 -7
- package/dist/modules/resolve.d.ts +5 -1
- package/dist/modules/resolve.js +15 -10
- package/dist/request/html-file-request.d.ts +6 -6
- package/dist/request/html-file-request.js +35 -50
- package/dist/request/html-files.d.ts +6 -1
- package/dist/request/html-files.js +26 -13
- package/dist/request/index.d.ts +11 -3
- package/dist/request/index.js +137 -80
- package/dist/request/markdown.d.ts +3 -0
- package/dist/request/markdown.js +73 -0
- package/dist/request/pagination.d.ts +12 -0
- package/dist/request/pagination.js +56 -0
- package/dist/request/prepare-body.d.ts +2 -0
- package/dist/request/prepare-body.js +11 -0
- package/dist/request/read-image-file.d.ts +19 -0
- package/dist/request/read-image-file.js +45 -0
- package/dist/request/version.d.ts +12 -0
- package/dist/request/version.js +36 -0
- package/dist/request/write-outcome.d.ts +23 -0
- package/dist/request/write-outcome.js +79 -0
- package/dist/types/module.d.ts +3 -2
- package/dist/types/options.d.ts +20 -0
- package/dist/types/response.d.ts +24 -0
- package/dist/types/upload.d.ts +6 -4
- package/dist/url.d.ts +19 -0
- package/dist/url.js +22 -0
- package/dist/utils/file-url.d.ts +13 -0
- package/dist/utils/file-url.js +80 -0
- package/dist/utils/html.d.ts +1 -1
- package/dist/utils/html.js +3 -3
- package/dist/utils/url.d.ts +3 -10
- package/dist/utils/url.js +8 -64
- package/dist/version.js +2 -2
- package/package.json +5 -1
package/dist/request/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type { DataRecord, FileCreateParams, FileCreateResult, RequestOptions, ResponseData } from '../types/index.js';
|
|
1
|
+
import type { DataRecord, FileCreateParams, FileCreateResult, ListPage, RequestOptions, ResponseData, WorkHourSettings } from '../types/index.js';
|
|
2
2
|
import type { BuiltinActionMeta, BuiltinModuleName } from '../modules/generated.js';
|
|
3
3
|
type BuiltinActionName<M extends BuiltinModuleName> = Extract<keyof BuiltinActionMeta[M], string>;
|
|
4
4
|
type BuiltinListRequestName = BuiltinModuleName;
|
|
5
5
|
type BuiltinNamedRequestName = {
|
|
6
6
|
[M in BuiltinModuleName]: `${M}/${BuiltinActionName<M>}`;
|
|
7
|
-
}[BuiltinModuleName] | 'my/profile' | 'file/get' | 'file/read';
|
|
7
|
+
}[BuiltinModuleName] | 'my/profile' | 'file/get' | 'file/read' | 'setting/workHours';
|
|
8
8
|
type BuiltinIdRequestName = `${BuiltinModuleName}/${number}`;
|
|
9
9
|
/** 内置模块支持的请求名:`module`、`module/action` 或 `module/123`。 */
|
|
10
10
|
export type BuiltinRequestName = BuiltinListRequestName | BuiltinNamedRequestName | BuiltinIdRequestName;
|
|
@@ -16,7 +16,7 @@ type ActionMetaOf<Name extends BuiltinRequestName> = ModuleNameOf<Name> extends
|
|
|
16
16
|
/** 根据内置请求名推导出的参数类型。字段细节以运行时 registry 为准,这里保持可扩展。 */
|
|
17
17
|
export type RequestParamsFor<Name extends BuiltinRequestName> = Name extends 'file/create' ? FileCreateParams : Record<string, unknown>;
|
|
18
18
|
/** 根据内置请求名推导出的 `ResponseData.data` 类型。 */
|
|
19
|
-
export type RequestResultFor<Name extends BuiltinRequestName> = ActionMetaOf<Name> extends {
|
|
19
|
+
export type RequestResultFor<Name extends BuiltinRequestName> = Name extends 'setting/workHours' ? WorkHourSettings : ActionMetaOf<Name> extends {
|
|
20
20
|
resultType: 'list';
|
|
21
21
|
} ? DataRecord[] : Name extends 'file/create' ? FileCreateResult : Name extends 'file/read' ? ArrayBuffer | string : ActionMetaOf<Name> extends {
|
|
22
22
|
resultType: 'object';
|
|
@@ -34,6 +34,7 @@ export type RequestResultFor<Name extends BuiltinRequestName> = ActionMetaOf<Nam
|
|
|
34
34
|
*
|
|
35
35
|
* 对 `update` 动作,当 `options.autoFill` 或全局 `autoFill` 为真时,会先 GET 当前对象,
|
|
36
36
|
* 用现值补齐用户未显式传入的 body 字段后再 PUT,避免禅道覆盖未提交字段。详见 {@link RequestOptions#autoFill}。
|
|
37
|
+
* 若提供 {@link RequestOptions.renderMarkdown},在预读前渲染本次显式提交的富文本字段。
|
|
37
38
|
*
|
|
38
39
|
* @typeParam T 归一化响应中期望的 `data` 字段类型;不传时为 `unknown`,调用方需要自行收窄。
|
|
39
40
|
* @param name - 请求名,例如 `product`、`product/list` 或 `product/1`。
|
|
@@ -52,4 +53,11 @@ export declare function request<T = unknown>(name: string, params?: Record<strin
|
|
|
52
53
|
raw?: false;
|
|
53
54
|
}): Promise<ResponseData<T>>;
|
|
54
55
|
export declare function request(name: string, params?: Record<string, unknown>, options?: RequestOptions): Promise<unknown>;
|
|
56
|
+
/**
|
|
57
|
+
* 按需读取列表,从指定页码(默认 1)开始,每次迭代请求一页。退出循环即停止取页。
|
|
58
|
+
* 每页沿用 {@link request} 的本地处理选项,筛选后为空的页也会交付。是否翻页依据服务端 pager。
|
|
59
|
+
* @typeParam Row - 每条记录的类型。
|
|
60
|
+
* @throws {ZentaoError} 业务失败时抛出 E_API_FAILED。分页信息缺失、页码不匹配或服务端空页仍有后页时抛出 E_PAGINATION_INCOMPLETE。
|
|
61
|
+
*/
|
|
62
|
+
export declare function iteratePages<Row = DataRecord>(name: string, params?: Record<string, unknown>, options?: Omit<RequestOptions, 'raw' | 'throwOnFail'>): AsyncGenerator<ListPage<Row>, void, void>;
|
|
55
63
|
export {};
|
package/dist/request/index.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ZentaoError } from '../misc/errors.js';
|
|
2
2
|
import { assertSupportedVersion } from '../misc/zentao-version.js';
|
|
3
3
|
import { getGlobalOptions } from '../misc/global-options.js';
|
|
4
4
|
import { getModule, getModuleAction } from '../modules/registry.js';
|
|
5
|
-
import { extractPager, extractResult, resolveActionRequest } from '../modules/resolve.js';
|
|
5
|
+
import { explicitBodyFieldSource, extractPager, extractResult, parseRequestData, resolveActionRequest } from '../modules/resolve.js';
|
|
6
6
|
import { isRecord, processData } from '../utils/index.js';
|
|
7
7
|
import { prepareActionBody } from './prepare-body.js';
|
|
8
8
|
import { resolveResultObjectType } from '../modules/result-object-type.js';
|
|
9
|
-
import { HtmlFileRequest,
|
|
9
|
+
import { HtmlFileRequest, setFileUid } from './html-file-request.js';
|
|
10
|
+
import { renderExplicitMarkdown } from './markdown.js';
|
|
11
|
+
import { assertListPage, pagerNumber, setIterationPage } from './pagination.js';
|
|
12
|
+
import { resolveRequestVersion } from './version.js';
|
|
13
|
+
import { classifyWriteError, classifyWriteReceipt, readFileReceipt, trackWrite } from './write-outcome.js';
|
|
10
14
|
/** 将 `moduleName`、`moduleName/methodName` 或 `moduleName/<objectID>` 请求名拆成模块名、动作名和对象 ID。 */
|
|
11
15
|
function splitRequestName(name) {
|
|
12
16
|
const parts = name.split('/');
|
|
@@ -34,22 +38,6 @@ function splitRequestName(name) {
|
|
|
34
38
|
actionName,
|
|
35
39
|
};
|
|
36
40
|
}
|
|
37
|
-
/** 解析 `params.data` 中用户显式传入的 body 字段名,用于 autoFill 判断字段归属。 */
|
|
38
|
-
function getExplicitDataKeys(data) {
|
|
39
|
-
let value = data;
|
|
40
|
-
if (typeof value === 'string') {
|
|
41
|
-
try {
|
|
42
|
-
value = JSON.parse(value);
|
|
43
|
-
}
|
|
44
|
-
catch {
|
|
45
|
-
return new Set();
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
49
|
-
return new Set(Object.keys(value));
|
|
50
|
-
}
|
|
51
|
-
return new Set();
|
|
52
|
-
}
|
|
53
41
|
/**
|
|
54
42
|
* 在执行 `update` 动作前,用当前对象的现值填充用户未显式传入的 body 字段。
|
|
55
43
|
*
|
|
@@ -71,17 +59,16 @@ async function autoFillUpdateParams(module, action, params, options, version) {
|
|
|
71
59
|
insecure: options.insecure,
|
|
72
60
|
actionAssistant: options.actionAssistant,
|
|
73
61
|
throwOnFail: true,
|
|
74
|
-
}, version)).data;
|
|
62
|
+
}, { version })).data;
|
|
75
63
|
if (!isRecord(current))
|
|
76
64
|
return params;
|
|
77
|
-
const
|
|
65
|
+
const data = parseRequestData(params.data);
|
|
78
66
|
const filled = { ...params };
|
|
79
67
|
for (const key of Object.keys(properties)) {
|
|
80
68
|
// An upload uid identifies this save and must never be copied from a previous edit.
|
|
81
69
|
if (key === 'uid')
|
|
82
70
|
continue;
|
|
83
|
-
|
|
84
|
-
if (!userProvided && Object.prototype.hasOwnProperty.call(current, key)) {
|
|
71
|
+
if (!explicitBodyFieldSource(params, data, key) && Object.hasOwn(current, key)) {
|
|
85
72
|
filled[key] = current[key];
|
|
86
73
|
}
|
|
87
74
|
}
|
|
@@ -159,23 +146,36 @@ function attachResultObjectType(response, command) {
|
|
|
159
146
|
return response;
|
|
160
147
|
}
|
|
161
148
|
/** 将禅道原始响应归一化为稳定的 ResponseData 结构。 */
|
|
162
|
-
function normalizeResponse(command, raw, options,
|
|
163
|
-
|
|
149
|
+
function normalizeResponse(command, raw, options, rejected, cursor, fileReceipt) {
|
|
150
|
+
// A bare upload ID uses the same result processing as an object receipt.
|
|
151
|
+
if (fileReceipt?.id && !isRecord(raw) && !command.action.resultGetter)
|
|
152
|
+
raw = { id: fileReceipt.id };
|
|
153
|
+
if (!isRecord(raw)) {
|
|
164
154
|
return attachResultObjectType({ status: 'success', data: raw }, command);
|
|
165
155
|
}
|
|
166
156
|
const record = raw;
|
|
167
|
-
const status =
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
157
|
+
const status = rejected || record.status === 'fail' ? 'fail' : 'success';
|
|
158
|
+
let source = extractResult(command.action, record, command.params, options);
|
|
159
|
+
if (fileReceipt?.id && !command.action.resultGetter) {
|
|
160
|
+
const fields = isRecord(source) ? source : {};
|
|
161
|
+
if (fields.id !== fileReceipt.id || (fileReceipt.url && fields.url !== fileReceipt.url)) {
|
|
162
|
+
source = { ...fields, id: fileReceipt.id, ...(fileReceipt.url && { url: fileReceipt.url }) };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (cursor)
|
|
166
|
+
cursor.rowCount = Array.isArray(source) ? source.length : undefined;
|
|
167
|
+
const data = applyProcessing(source, options);
|
|
168
|
+
const rawMessage = fileReceipt ? fileReceipt.message : record.message;
|
|
169
|
+
const toNumber = cursor ? pagerNumber : Number;
|
|
170
|
+
const pager = extractPager(command.action, record, command.params, options, toNumber);
|
|
171
171
|
const response = {
|
|
172
172
|
status,
|
|
173
173
|
message: stringifyMessage(rawMessage),
|
|
174
174
|
data: data,
|
|
175
175
|
pager: pager ? {
|
|
176
|
-
total:
|
|
177
|
-
page:
|
|
178
|
-
recPerPage:
|
|
176
|
+
total: toNumber(pager.recTotal),
|
|
177
|
+
page: toNumber(pager.pageID),
|
|
178
|
+
recPerPage: toNumber(pager.recPerPage),
|
|
179
179
|
} : undefined,
|
|
180
180
|
};
|
|
181
181
|
if (rawMessage !== undefined && typeof rawMessage !== 'string') {
|
|
@@ -189,20 +189,67 @@ function normalizeResponse(command, raw, options, fileWrite) {
|
|
|
189
189
|
return attachResultObjectType(response, command);
|
|
190
190
|
}
|
|
191
191
|
export async function request(name, params = {}, options = {}) {
|
|
192
|
-
|
|
192
|
+
const attempt = {};
|
|
193
|
+
try {
|
|
194
|
+
return await requestInternal(name, params, options, { attempt });
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (!attempt.phase)
|
|
198
|
+
throw error;
|
|
199
|
+
attempt.outcome ??= classifyWriteError(attempt.phase, error);
|
|
200
|
+
if (!(error instanceof ZentaoError) || attempt.phase === 'before-hook' || attempt.phase === 'custom')
|
|
201
|
+
throw error;
|
|
202
|
+
// A config fetch can reject several concurrent requests with the same error.
|
|
203
|
+
const failure = new ZentaoError(error.code, error.params, error.details);
|
|
204
|
+
Object.defineProperty(failure, 'cause', { value: error, configurable: true });
|
|
205
|
+
throw Object.assign(failure, { writeOutcome: attempt.outcome });
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
if (attempt.outcome && options.onWriteOutcome) {
|
|
209
|
+
try {
|
|
210
|
+
await options.onWriteOutcome(attempt.outcome);
|
|
211
|
+
}
|
|
212
|
+
catch { /* notification only */ }
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* 按需读取列表,从指定页码(默认 1)开始,每次迭代请求一页。退出循环即停止取页。
|
|
218
|
+
* 每页沿用 {@link request} 的本地处理选项,筛选后为空的页也会交付。是否翻页依据服务端 pager。
|
|
219
|
+
* @typeParam Row - 每条记录的类型。
|
|
220
|
+
* @throws {ZentaoError} 业务失败时抛出 E_API_FAILED。分页信息缺失、页码不匹配或服务端空页仍有后页时抛出 E_PAGINATION_INCOMPLETE。
|
|
221
|
+
*/
|
|
222
|
+
export async function* iteratePages(name, params = {}, options = {}) {
|
|
223
|
+
const cursor = { globals: getGlobalOptions() };
|
|
224
|
+
const pageParams = { ...params };
|
|
225
|
+
const pageOptions = { ...options, raw: false, throwOnFail: true };
|
|
226
|
+
do {
|
|
227
|
+
const response = await requestInternal(name, pageParams, pageOptions, { cursor, version: cursor.version });
|
|
228
|
+
assertListPage(name, cursor, response);
|
|
229
|
+
const { page, recPerPage, total } = response.pager;
|
|
230
|
+
cursor.pageID = page * recPerPage < total ? page + 1 : undefined;
|
|
231
|
+
yield response;
|
|
232
|
+
} while (cursor.pageID !== undefined);
|
|
193
233
|
}
|
|
194
234
|
/** version 为 undefined 时解析一次,null 表示本次调用已选择跳过版本检查。 */
|
|
195
|
-
async function requestInternal(name, params, options, version,
|
|
196
|
-
const globals = getGlobalOptions();
|
|
235
|
+
async function requestInternal(name, params, options, { version, prepareRichText = true, checkSession, attempt, cursor }) {
|
|
236
|
+
const globals = cursor?.globals ?? getGlobalOptions();
|
|
197
237
|
const client = options.client ?? globals.client;
|
|
198
|
-
if (!client) {
|
|
199
|
-
throw new ZentaoError('E_NO_GLOBAL_CLIENT');
|
|
200
|
-
}
|
|
201
238
|
const { moduleName, actionName, id } = splitRequestName(name);
|
|
202
239
|
const module = getModule(moduleName);
|
|
240
|
+
const action = getModuleAction(moduleName, actionName);
|
|
241
|
+
const write = action && action.type !== 'get' && action.type !== 'list' && action.method?.toUpperCase() !== 'GET'
|
|
242
|
+
? attempt : undefined;
|
|
243
|
+
if (write)
|
|
244
|
+
write.phase = 'preparing';
|
|
245
|
+
if (!client)
|
|
246
|
+
throw new ZentaoError('E_NO_GLOBAL_CLIENT');
|
|
203
247
|
if (!module) {
|
|
204
248
|
throw new ZentaoError('E_INVALID_MODULE', { module: moduleName });
|
|
205
249
|
}
|
|
250
|
+
if (!action) {
|
|
251
|
+
throw new ZentaoError('E_INVALID_ACTION', { module: moduleName, action: actionName });
|
|
252
|
+
}
|
|
206
253
|
// recPerPage 是最常用的列表参数,允许在全局或本次调用中统一覆盖。
|
|
207
254
|
const recPerPage = params.recPerPage ?? options.recPerPage ?? globals.recPerPage;
|
|
208
255
|
const mergedParams = {
|
|
@@ -210,39 +257,30 @@ async function requestInternal(name, params, options, version, processHtmlFiles
|
|
|
210
257
|
...(id !== undefined ? { id } : {}),
|
|
211
258
|
...(recPerPage !== undefined ? { recPerPage } : {}),
|
|
212
259
|
};
|
|
213
|
-
|
|
214
|
-
// 避免禅道 PUT 把未提交字段覆盖为空。
|
|
215
|
-
const action = getModuleAction(moduleName, actionName);
|
|
216
|
-
if (!action) {
|
|
217
|
-
throw new ZentaoError('E_INVALID_ACTION', { module: moduleName, action: actionName });
|
|
218
|
-
}
|
|
260
|
+
const pageQuery = cursor && setIterationPage(action, mergedParams, cursor);
|
|
219
261
|
if (version === undefined) {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
else {
|
|
224
|
-
try {
|
|
225
|
-
version = (await client.getZentaoConfig({
|
|
226
|
-
forceRefresh: options.forceRefreshConfig,
|
|
227
|
-
timeout: options.timeout ?? globals.timeout,
|
|
228
|
-
insecure: options.insecure ?? globals.insecure,
|
|
229
|
-
})).version;
|
|
230
|
-
}
|
|
231
|
-
catch (error) {
|
|
232
|
-
if (!(options.skipVersionCheckOnConfigError ?? globals.skipVersionCheckOnConfigError)
|
|
233
|
-
|| !isZentaoConfigFetchError(error))
|
|
234
|
-
throw error;
|
|
235
|
-
version = null;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
262
|
+
version = await resolveRequestVersion(options, globals);
|
|
263
|
+
if (cursor)
|
|
264
|
+
cursor.version = version;
|
|
238
265
|
}
|
|
239
266
|
assertSupportedVersion(version, action.minVersion, `${module.name}/${action.name}`);
|
|
267
|
+
const renderMarkdown = prepareRichText && (options.renderMarkdown ?? globals.renderMarkdown);
|
|
268
|
+
const markdownField = renderMarkdown
|
|
269
|
+
? await renderExplicitMarkdown(module.name, action, mergedParams, renderMarkdown)
|
|
270
|
+
: undefined;
|
|
271
|
+
// autoFill completes its GET before the target object's write can start.
|
|
240
272
|
const finalParams = action.type === 'update' && (options.autoFill ?? globals.autoFill)
|
|
241
273
|
? await autoFillUpdateParams(module, action, mergedParams, { ...options, client }, version)
|
|
242
274
|
: mergedParams;
|
|
243
275
|
const command = resolveActionRequest(module, actionName, finalParams);
|
|
276
|
+
if (pageQuery)
|
|
277
|
+
Object.assign(command.query ??= {}, pageQuery);
|
|
244
278
|
if (command.action.beforeRequest) {
|
|
279
|
+
if (write)
|
|
280
|
+
write.phase = 'before-hook';
|
|
245
281
|
Object.assign(command, await command.action.beforeRequest(command));
|
|
282
|
+
if (write)
|
|
283
|
+
write.phase = 'preparing';
|
|
246
284
|
}
|
|
247
285
|
const transportOptions = {
|
|
248
286
|
timeout: options.timeout ?? globals.timeout,
|
|
@@ -251,34 +289,35 @@ async function requestInternal(name, params, options, version, processHtmlFiles
|
|
|
251
289
|
};
|
|
252
290
|
const method = String(command.action.method).toUpperCase();
|
|
253
291
|
const isWrite = method === 'POST' || method === 'PUT';
|
|
254
|
-
const
|
|
292
|
+
const fileAction = module.name === 'file' ? action.name : undefined;
|
|
293
|
+
const isUpload = fileAction === 'create';
|
|
255
294
|
const flatUid = isUpload && command.query?.uid !== undefined ? command.query.uid : command.params.uid;
|
|
256
295
|
const explicitUid = command.data?.uid !== undefined ? command.data.uid : flatUid;
|
|
257
296
|
const uid = isWrite && explicitUid !== undefined ? setFileUid(command, explicitUid, version) : undefined;
|
|
258
|
-
const files =
|
|
297
|
+
const files = prepareRichText && isWrite && !isUpload ? new HtmlFileRequest(command, {
|
|
259
298
|
client, version, ...transportOptions,
|
|
260
299
|
fileResolver: options.fileResolver ?? globals.fileResolver,
|
|
300
|
+
continueOnFileResolveError: options.continueOnFileResolveError ?? globals.continueOnFileResolveError,
|
|
261
301
|
continueOnFileUploadError: options.continueOnFileUploadError ?? globals.continueOnFileUploadError,
|
|
262
302
|
onFileError: options.onFileError ?? globals.onFileError,
|
|
263
303
|
requestFile: async (action, params, fileSession) => {
|
|
264
304
|
const raw = await requestInternal(`file/${action}`, params, {
|
|
265
305
|
client, ...transportOptions, maxUploadBytes: options.maxUploadBytes,
|
|
266
306
|
raw: true, autoFill: false,
|
|
267
|
-
}, version, false, fileSession);
|
|
307
|
+
}, { version, prepareRichText: false, checkSession: fileSession });
|
|
308
|
+
const receipt = readFileReceipt(action, raw);
|
|
268
309
|
if (action === 'create' && (typeof raw === 'number' || typeof raw === 'string'))
|
|
269
|
-
return
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
if (
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
}
|
|
276
|
-
return raw;
|
|
310
|
+
return receipt;
|
|
311
|
+
if (action === 'create' && isRecord(raw) && raw.status !== 'fail' && receipt.outcome !== 'rejected')
|
|
312
|
+
return receipt;
|
|
313
|
+
if (receipt.outcome === 'confirmed')
|
|
314
|
+
return receipt;
|
|
315
|
+
throw new ZentaoError('E_API_FAILED', { message: stringifyMessage(receipt.message) ?? `Invalid file/${action} response.` }, raw);
|
|
277
316
|
},
|
|
278
317
|
}, uid) : undefined;
|
|
279
318
|
let preparedBody;
|
|
280
319
|
try {
|
|
281
|
-
await files?.prepare();
|
|
320
|
+
await files?.prepare(markdownField);
|
|
282
321
|
preparedBody = await prepareActionBody(command, { maxUploadBytes: options.maxUploadBytes });
|
|
283
322
|
(checkSession ?? files?.checkSession)?.();
|
|
284
323
|
}
|
|
@@ -289,24 +328,42 @@ async function requestInternal(name, params, options, version, processHtmlFiles
|
|
|
289
328
|
const requestOptions = { ...preparedBody, ...transportOptions };
|
|
290
329
|
let raw;
|
|
291
330
|
try {
|
|
331
|
+
// A custom transport may send a write even when it throws without a receipt.
|
|
332
|
+
if (write)
|
|
333
|
+
write.phase = command.action.request ? 'custom' : 'dispatching';
|
|
292
334
|
raw = command.action.request
|
|
293
|
-
? await command.action.request({ request: command, ...requestOptions, client, options })
|
|
294
|
-
: await client.request(command.path, {
|
|
335
|
+
? await command.action.request(trackWrite({ request: command, ...requestOptions, client, options }, write))
|
|
336
|
+
: await client.request(command.path, trackWrite({
|
|
295
337
|
method,
|
|
296
338
|
query: command.query,
|
|
297
339
|
...requestOptions,
|
|
298
|
-
});
|
|
340
|
+
}, write));
|
|
299
341
|
}
|
|
300
342
|
catch (error) {
|
|
301
|
-
|
|
343
|
+
const outcome = write?.outcome ?? classifyWriteError(write?.phase, error);
|
|
344
|
+
if (write)
|
|
345
|
+
write.outcome = outcome;
|
|
346
|
+
throw files ? await files.saveError(error, outcome) : error;
|
|
347
|
+
}
|
|
348
|
+
const fileReceipt = write && (fileAction === 'create' || fileAction === 'delete') ? readFileReceipt(fileAction, raw) : undefined;
|
|
349
|
+
const receipt = write || (files && command.data?.uid !== undefined)
|
|
350
|
+
? write?.outcome ?? fileReceipt?.outcome ?? classifyWriteReceipt(raw)
|
|
351
|
+
: undefined;
|
|
352
|
+
if (receipt) {
|
|
353
|
+
if (write) {
|
|
354
|
+
write.phase = 'received';
|
|
355
|
+
write.outcome = receipt;
|
|
356
|
+
}
|
|
357
|
+
await files?.complete(raw, receipt, options.raw === true);
|
|
302
358
|
}
|
|
303
|
-
await files?.complete(raw);
|
|
304
359
|
if (options.raw) {
|
|
305
360
|
return raw;
|
|
306
361
|
}
|
|
307
362
|
// limit 现归入本地处理选项;本次调用优先,缺省回落到全局默认。
|
|
308
363
|
const processOptions = { ...options, limit: options.limit ?? globals.limit };
|
|
309
|
-
const response = normalizeResponse(command, raw, processOptions,
|
|
364
|
+
const response = normalizeResponse(command, raw, processOptions, receipt === 'rejected', cursor, fileReceipt);
|
|
365
|
+
if (write)
|
|
366
|
+
response.writeOutcome = write.outcome;
|
|
310
367
|
if (files?.warnings.length)
|
|
311
368
|
response.fileWarnings = files.warnings;
|
|
312
369
|
if (response.status === 'fail' && (options.throwOnFail ?? globals.throwOnFail)) {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { MarkdownRenderer, ModuleAction } from '../types/index.js';
|
|
2
|
+
/** Render into the request's private params. Return the native Markdown field to exclude from HTML image handling. */
|
|
3
|
+
export declare function renderExplicitMarkdown(module: string, action: ModuleAction, params: Record<string, unknown>, render: MarkdownRenderer): Promise<string | undefined>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { parseFragment } from 'parse5';
|
|
2
|
+
import { ZentaoError } from '../misc/errors.js';
|
|
3
|
+
import { explicitBodyFieldSource, parseRequestData } from '../modules/resolve.js';
|
|
4
|
+
import { getHtmlFields } from './html-files.js';
|
|
5
|
+
// Inspect only text outside HTML elements. Markdown-looking text inside an existing element is literal.
|
|
6
|
+
const blockMarkdown = /^ {0,3}(?:#{1,6}(?:\s|$)|>|(?:[-+*]|\d{1,9}[.)])\s|~{3,}|(?:-{3,}|={3,})\s*$)/m;
|
|
7
|
+
const inlineMarkdown = /`|\\<|\]\s*[(\[]|\*\*|~~|(?:^|\s)[*_](?=\S)/;
|
|
8
|
+
function isHtmlFragment(value) {
|
|
9
|
+
// Fragment parsing drops the document's outer html, head and body tags.
|
|
10
|
+
if (/^\s*<(?:!doctype\s+html|html|head|body)(?=[\s/>])/i.test(value))
|
|
11
|
+
return true;
|
|
12
|
+
// Also rules out Markdown autolinks such as <https://example.com> before parsing.
|
|
13
|
+
if (!/<(?:[a-z][\w-]*(?=[\s/>])|!--)/i.test(value))
|
|
14
|
+
return false;
|
|
15
|
+
const { childNodes } = parseFragment(value, { sourceCodeLocationInfo: true });
|
|
16
|
+
const outside = [];
|
|
17
|
+
let hasMarkup = false;
|
|
18
|
+
for (const node of childNodes) {
|
|
19
|
+
if ('value' in node && node.sourceCodeLocation) {
|
|
20
|
+
const { startOffset, endOffset } = node.sourceCodeLocation;
|
|
21
|
+
outside.push(value.slice(startOffset, endOffset));
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
// HTML error recovery treats Markdown autolinks as elements named "https:" or "a@example.test".
|
|
25
|
+
if ('tagName' in node && !/^[a-z][\w-]*$/i.test(node.tagName))
|
|
26
|
+
return false;
|
|
27
|
+
hasMarkup = true;
|
|
28
|
+
outside.push('<');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const text = outside.join('');
|
|
32
|
+
return hasMarkup && !blockMarkdown.test(text) && !inlineMarkdown.test(text);
|
|
33
|
+
}
|
|
34
|
+
/** Render into the request's private params. Return the native Markdown field to exclude from HTML image handling. */
|
|
35
|
+
export async function renderExplicitMarkdown(module, action, params, render) {
|
|
36
|
+
const method = action.method?.toUpperCase();
|
|
37
|
+
if ((method !== 'POST' && method !== 'PUT') || action.requestBody?.schema.type !== 'object')
|
|
38
|
+
return;
|
|
39
|
+
const fields = getHtmlFields(action);
|
|
40
|
+
if (!fields.length)
|
|
41
|
+
return;
|
|
42
|
+
const data = parseRequestData(params.data);
|
|
43
|
+
const nativeDoc = module.toLowerCase() === 'doc'
|
|
44
|
+
&& explicitBodyFieldSource(params, data, 'contentType')?.contentType !== 'html';
|
|
45
|
+
const markdownField = nativeDoc ? 'content' : undefined;
|
|
46
|
+
let updatedData;
|
|
47
|
+
for (const field of fields) {
|
|
48
|
+
if (field === markdownField)
|
|
49
|
+
continue;
|
|
50
|
+
const owner = explicitBodyFieldSource(params, data, field);
|
|
51
|
+
const value = owner?.[field];
|
|
52
|
+
if (typeof value !== 'string' || !value.trim())
|
|
53
|
+
continue;
|
|
54
|
+
if (isHtmlFragment(value))
|
|
55
|
+
continue;
|
|
56
|
+
const html = await render(value, { module, action: action.name, field });
|
|
57
|
+
if (typeof html !== 'string') {
|
|
58
|
+
throw new ZentaoError('E_INVALID_PARAM', { param: `renderMarkdown(${field})`, value: typeof html });
|
|
59
|
+
}
|
|
60
|
+
if (html === value)
|
|
61
|
+
continue;
|
|
62
|
+
if (owner === data) {
|
|
63
|
+
updatedData ??= { ...data };
|
|
64
|
+
updatedData[field] = html;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
params[field] = html;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (updatedData)
|
|
71
|
+
params.data = typeof params.data === 'string' ? JSON.stringify(updatedData) : updatedData;
|
|
72
|
+
return markdownField;
|
|
73
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { GlobalOptions, ListPage, ModuleAction, ResponseData } from '../types/index.js';
|
|
2
|
+
/** Private to one iterator. rowCount is captured before local conversion or filtering. */
|
|
3
|
+
export interface PageCursor {
|
|
4
|
+
globals: GlobalOptions;
|
|
5
|
+
version?: string | null;
|
|
6
|
+
pageID?: number;
|
|
7
|
+
rowCount?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function pagerNumber(value: unknown): number;
|
|
10
|
+
/** Set the page on the request's private params. Some workflow lists return a pager but omit its query fields from the schema. */
|
|
11
|
+
export declare function setIterationPage(action: ModuleAction, params: Record<string, unknown>, cursor: PageCursor): Record<string, unknown> | undefined;
|
|
12
|
+
export declare function assertListPage<Row>(name: string, cursor: PageCursor, response: ResponseData<Row[]>): asserts response is ListPage<Row>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ZentaoError } from '../misc/errors.js';
|
|
2
|
+
import { explicitBodyFieldSource, parseRequestData } from '../modules/resolve.js';
|
|
3
|
+
import { isRecord } from '../utils/object.js';
|
|
4
|
+
export function pagerNumber(value) {
|
|
5
|
+
if (typeof value === 'number')
|
|
6
|
+
return value;
|
|
7
|
+
return typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN;
|
|
8
|
+
}
|
|
9
|
+
/** Set the page on the request's private params. Some workflow lists return a pager but omit its query fields from the schema. */
|
|
10
|
+
export function setIterationPage(action, params, cursor) {
|
|
11
|
+
const method = action.method?.toUpperCase();
|
|
12
|
+
if (action.resultType !== 'list' || (method !== 'GET' && !(method === 'POST' && action.type === 'list'))) {
|
|
13
|
+
throw new ZentaoError('E_INVALID_PARAM', { param: 'list action', value: action.name });
|
|
14
|
+
}
|
|
15
|
+
const query = action.params?.find(param => param.name === 'pageID' || param.name === 'page');
|
|
16
|
+
const properties = action.requestBody?.schema.properties;
|
|
17
|
+
const bodyField = !query && isRecord(properties) ? ['pageID', 'page'].find(key => Object.hasOwn(properties, key)) : undefined;
|
|
18
|
+
const field = query?.name ?? bodyField ?? 'pageID';
|
|
19
|
+
const data = bodyField ? parseRequestData(params.data) : undefined;
|
|
20
|
+
const source = explicitBodyFieldSource(params, data, field);
|
|
21
|
+
const alias = field === 'pageID' ? params.page : params.pageID;
|
|
22
|
+
const start = source?.[field] === undefined ? alias ?? 1 : source[field];
|
|
23
|
+
const page = cursor.pageID ?? pagerNumber(start);
|
|
24
|
+
if (!Number.isSafeInteger(page) || page < 1) {
|
|
25
|
+
throw new ZentaoError('E_INVALID_PARAM', { param: field, value: String(start) });
|
|
26
|
+
}
|
|
27
|
+
cursor.pageID = page;
|
|
28
|
+
if (data && source === data) {
|
|
29
|
+
const updated = { ...data, [field]: page };
|
|
30
|
+
params.data = typeof params.data === 'string' ? JSON.stringify(updated) : updated;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
params[field] = page;
|
|
34
|
+
}
|
|
35
|
+
if (method === 'GET' && action.pagerGetter && !query && !bodyField) {
|
|
36
|
+
return { pageID: page, ...(params.recPerPage !== undefined ? { recPerPage: params.recPerPage } : {}) };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function assertListPage(name, cursor, response) {
|
|
40
|
+
const { pager } = response;
|
|
41
|
+
const invalid = (reason) => new ZentaoError('E_PAGINATION_INCOMPLETE', {
|
|
42
|
+
action: name, page: cursor.pageID ?? 1, reason,
|
|
43
|
+
}, pager);
|
|
44
|
+
if (!pager)
|
|
45
|
+
throw invalid('missing pager');
|
|
46
|
+
if (pager.page !== cursor.pageID)
|
|
47
|
+
throw invalid(`received page ${pager.page}`);
|
|
48
|
+
if (!Number.isSafeInteger(pager.recPerPage) || pager.recPerPage < 1 || !Number.isSafeInteger(pager.total) || pager.total < 0) {
|
|
49
|
+
throw invalid('invalid page size or total');
|
|
50
|
+
}
|
|
51
|
+
if (cursor.rowCount === undefined || !Array.isArray(response.data))
|
|
52
|
+
throw invalid('expected a list of records');
|
|
53
|
+
if (cursor.rowCount === 0 && pager.page * pager.recPerPage < pager.total) {
|
|
54
|
+
throw invalid('the server returned an empty list while the pager indicates more pages');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -8,6 +8,8 @@ export interface PreparedActionBody {
|
|
|
8
8
|
body: unknown;
|
|
9
9
|
bodyType?: ClientRequestBodyType;
|
|
10
10
|
}
|
|
11
|
+
/** @internal 图片读取支持的格式,保留上传时原有的 MIME 推断。 */
|
|
12
|
+
export declare function getImageContentType(extension: string): string | undefined;
|
|
11
13
|
export declare function inferExtension(contentType: string): string;
|
|
12
14
|
export declare function normalizeFilename(value: string | undefined, fallback: string, field: string): string;
|
|
13
15
|
/** 根据模块动作的媒体类型,把解析后的普通请求体转换为底层客户端可发送的请求体。 */
|
|
@@ -20,6 +20,17 @@ const MIME_TYPES = {
|
|
|
20
20
|
'.webp': 'image/webp',
|
|
21
21
|
'.zip': 'application/zip',
|
|
22
22
|
};
|
|
23
|
+
/** @internal 图片读取支持的格式,保留上传时原有的 MIME 推断。 */
|
|
24
|
+
export function getImageContentType(extension) {
|
|
25
|
+
if (extension === 'bmp')
|
|
26
|
+
return 'image/bmp';
|
|
27
|
+
if (extension === 'ico')
|
|
28
|
+
return 'image/x-icon';
|
|
29
|
+
if (extension === 'tif' || extension === 'tiff')
|
|
30
|
+
return 'image/tiff';
|
|
31
|
+
const mime = MIME_TYPES[`.${extension}`];
|
|
32
|
+
return mime?.startsWith('image/') ? mime : undefined;
|
|
33
|
+
}
|
|
23
34
|
// 与 environment.ts 相同:通过变量形式的动态 import 避免浏览器 bundle 静态拉入 node:*。
|
|
24
35
|
function importNodeModule(specifier) {
|
|
25
36
|
return import(specifier);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { RequestOptions } from '../types/options.js';
|
|
2
|
+
import { type ParsedFileUrl } from '../url.js';
|
|
3
|
+
/** 图片附件的原始内容及按附件 ID 生成的文件名。 */
|
|
4
|
+
export interface ImageFileContent {
|
|
5
|
+
fileID: number;
|
|
6
|
+
filename: string;
|
|
7
|
+
contentType: string;
|
|
8
|
+
data: ArrayBuffer;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 从当前禅道站点读取图片附件。路径中有图片后缀时直接调用 file/read。
|
|
12
|
+
* 无后缀的读取链接和数字 ID 先通过 file/get 取得扩展名,缺少扩展名时取文件标题的后缀。
|
|
13
|
+
*
|
|
14
|
+
* @param source - 附件 URL、{@link parseFileUrl} 的解析结果或数字 ID。带域名的 URL 按客户端站点和安装目录匹配。解析结果和 ID 均指当前站点。
|
|
15
|
+
* @param options - 客户端和传输选项,省略时使用 SDK 默认值。
|
|
16
|
+
* @returns 含二进制内容、文件名和 MIME 类型的图片。下载链接、无效地址、非图片或空内容返回 `undefined`。
|
|
17
|
+
* @throws {ZentaoError} 沿用附件请求的客户端、版本、传输或服务端错误。
|
|
18
|
+
*/
|
|
19
|
+
export declare function readImageFile(source: string | number | ParsedFileUrl, options?: Pick<RequestOptions, 'client' | 'timeout' | 'insecure' | 'actionAssistant'>): Promise<ImageFileContent | undefined>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { getGlobalOptions } from '../misc/global-options.js';
|
|
2
|
+
import { parseFileUrl } from '../url.js';
|
|
3
|
+
import { request } from './index.js';
|
|
4
|
+
import { getImageContentType } from './prepare-body.js';
|
|
5
|
+
/**
|
|
6
|
+
* 从当前禅道站点读取图片附件。路径中有图片后缀时直接调用 file/read。
|
|
7
|
+
* 无后缀的读取链接和数字 ID 先通过 file/get 取得扩展名,缺少扩展名时取文件标题的后缀。
|
|
8
|
+
*
|
|
9
|
+
* @param source - 附件 URL、{@link parseFileUrl} 的解析结果或数字 ID。带域名的 URL 按客户端站点和安装目录匹配。解析结果和 ID 均指当前站点。
|
|
10
|
+
* @param options - 客户端和传输选项,省略时使用 SDK 默认值。
|
|
11
|
+
* @returns 含二进制内容、文件名和 MIME 类型的图片。下载链接、无效地址、非图片或空内容返回 `undefined`。
|
|
12
|
+
* @throws {ZentaoError} 沿用附件请求的客户端、版本、传输或服务端错误。
|
|
13
|
+
*/
|
|
14
|
+
export async function readImageFile(source, options = {}) {
|
|
15
|
+
const { client = getGlobalOptions().client, timeout, insecure, actionAssistant } = options;
|
|
16
|
+
let route;
|
|
17
|
+
if (typeof source === 'string')
|
|
18
|
+
route = parseFileUrl(source, client?.siteUrl);
|
|
19
|
+
else if (typeof source === 'number')
|
|
20
|
+
route = { method: 'read', fileID: source };
|
|
21
|
+
else
|
|
22
|
+
route = source;
|
|
23
|
+
if (route?.method !== 'read' || !Number.isSafeInteger(route.fileID) || route.fileID <= 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
const { fileID } = route;
|
|
26
|
+
const requestOptions = { client, timeout, insecure, actionAssistant, throwOnFail: true };
|
|
27
|
+
let extension = route.extension;
|
|
28
|
+
if (!extension) {
|
|
29
|
+
const { data } = await request('file/get', { fileID }, requestOptions);
|
|
30
|
+
const declared = typeof data?.extension === 'string' ? data.extension.trim() : '';
|
|
31
|
+
if (declared)
|
|
32
|
+
extension = declared.replace(/^\./, '').toLowerCase();
|
|
33
|
+
else if (typeof data?.title === 'string')
|
|
34
|
+
extension = /\.([a-z0-9]+)$/i.exec(data.title.trim())?.[1].toLowerCase();
|
|
35
|
+
}
|
|
36
|
+
if (!extension)
|
|
37
|
+
return undefined;
|
|
38
|
+
const contentType = getImageContentType(extension);
|
|
39
|
+
if (!contentType)
|
|
40
|
+
return undefined;
|
|
41
|
+
const { data } = await request('file/read', { fileID, stream: 0 }, requestOptions);
|
|
42
|
+
if (!(data instanceof ArrayBuffer) || !data.byteLength)
|
|
43
|
+
return undefined;
|
|
44
|
+
return { fileID, filename: `${fileID}.${extension}`, contentType, data };
|
|
45
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { FileBindingOptions, GlobalOptions, RequestOptions } from '../types/options.js';
|
|
2
|
+
/** @internal 上传与对象保存通过同一 uid 绑定附件的最低版本。 */
|
|
3
|
+
export declare const FILE_BINDING_MINIMUMS: readonly string[];
|
|
4
|
+
/** @internal null 表示调用方明确允许配置获取失败后跳过版本检查。 */
|
|
5
|
+
export declare function resolveRequestVersion(options: RequestOptions, globals: GlobalOptions, version?: string | undefined): Promise<string | null>;
|
|
6
|
+
/**
|
|
7
|
+
* 判断当前禅道版本是否支持用 uid 将编辑器附件绑定到对象。版本门槛与实际保存共用。
|
|
8
|
+
* @param options - 可传已知版本或客户端。默认使用全局版本,缺省时读取客户端的站点配置。
|
|
9
|
+
* @returns 已知版本返回布尔值。配置获取失败且允许跳过版本检查时返回 `undefined`。
|
|
10
|
+
* @throws {ZentaoError} 版本格式非法或无法获取所需配置时抛出对应的 SDK 错误。
|
|
11
|
+
*/
|
|
12
|
+
export declare function supportsFileBinding(options?: FileBindingOptions): Promise<boolean | undefined>;
|