zentao-api 0.8.4 → 0.9.0
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 +48 -2
- package/dist/browser/zentao-api.global.js +28 -28
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +10 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/misc/errors.d.ts +4 -0
- package/dist/misc/errors.js +4 -0
- package/dist/misc/zentao-version.d.ts +3 -0
- package/dist/misc/zentao-version.js +9 -0
- package/dist/modules/define.d.ts +1 -0
- package/dist/modules/define.js +3 -2
- package/dist/modules/generated.d.ts +402 -0
- package/dist/modules/generated.js +447 -55
- package/dist/modules/object-props.js +212 -36
- package/dist/modules/override.js +101 -9
- package/dist/modules/query.d.ts +2 -0
- package/dist/modules/query.js +6 -0
- package/dist/modules/registry-store.d.ts +4 -4
- package/dist/modules/registry-store.js +15 -8
- package/dist/modules/result-object-type.d.ts +7 -0
- package/dist/modules/result-object-type.js +35 -0
- package/dist/request/html-file-request.d.ts +34 -0
- package/dist/request/html-file-request.js +366 -0
- package/dist/request/html-files.d.ts +28 -0
- package/dist/request/html-files.js +139 -0
- package/dist/request/index.d.ts +3 -3
- package/dist/request/index.js +78 -26
- package/dist/request/prepare-body.d.ts +2 -0
- package/dist/request/prepare-body.js +2 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +2 -0
- package/dist/types/link.d.ts +52 -0
- package/dist/types/link.js +1 -0
- package/dist/types/module.d.ts +18 -0
- package/dist/types/options.d.ts +7 -4
- package/dist/types/response.d.ts +16 -0
- package/dist/types/upload.d.ts +64 -2
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +1 -0
- package/dist/utils/link.d.ts +30 -0
- package/dist/utils/link.js +225 -0
- package/dist/version.js +2 -2
- package/package.json +5 -2
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { captureFileSession } from '../client/index.js';
|
|
2
|
+
import { ZentaoError } from '../misc/errors.js';
|
|
3
|
+
import { isNodeRuntime } from '../misc/environment.js';
|
|
4
|
+
import { assertSupportedVersion, VERSION_23_MINIMUMS } from '../misc/zentao-version.js';
|
|
5
|
+
import { resolveResultObjectType } from '../modules/result-object-type.js';
|
|
6
|
+
import { isRecord } from '../utils/object.js';
|
|
7
|
+
import { createLink, parseLink } from '../utils/link.js';
|
|
8
|
+
import { parseHtmlFiles, rewriteHtmlFiles } from './html-files.js';
|
|
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
|
+
}
|
|
16
|
+
function directURL(path) {
|
|
17
|
+
return /^(?:https?:\/\/|\/\/|#)/i.test(path)
|
|
18
|
+
|| (/^[a-z][a-z\d+.-]*:/i.test(path) && !/^file:/i.test(path));
|
|
19
|
+
}
|
|
20
|
+
function mayBeFileLink(path) {
|
|
21
|
+
let decoded = path;
|
|
22
|
+
try {
|
|
23
|
+
decoded = decodeURIComponent(path);
|
|
24
|
+
}
|
|
25
|
+
catch { /* use the original path */ }
|
|
26
|
+
return /file.*read|read.*file/i.test(decoded);
|
|
27
|
+
}
|
|
28
|
+
function plainRecord(value) {
|
|
29
|
+
return isRecord(value) && [null, Object.prototype].includes(Object.getPrototypeOf(value));
|
|
30
|
+
}
|
|
31
|
+
async function importNode(specifier) {
|
|
32
|
+
return import(specifier);
|
|
33
|
+
}
|
|
34
|
+
async function newFileUid() {
|
|
35
|
+
if (!globalThis.crypto && isNodeRuntime())
|
|
36
|
+
return (await importNode('node:crypto')).randomUUID();
|
|
37
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
38
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
39
|
+
}
|
|
40
|
+
/** Put the batch identifier in the upload query or the object's JSON body. */
|
|
41
|
+
export function setFileUid(command, value, version) {
|
|
42
|
+
// PHP treats "0" as empty. "used" is an album key; "1" and "apiv2" are shared server defaults.
|
|
43
|
+
if (typeof value !== 'string' || !value || /[^A-Za-z0-9_-]/.test(value) || ['0', '1', 'used', 'apiv2'].includes(value)) {
|
|
44
|
+
throw new ZentaoError('E_INVALID_PARAM', { param: 'uid', value: typeof value === 'string' ? value : typeof value });
|
|
45
|
+
}
|
|
46
|
+
assertSupportedVersion(version, VERSION_23_MINIMUMS, `${command.module}/${command.action.name}`);
|
|
47
|
+
if (command.module === 'file' && command.action.name === 'create') {
|
|
48
|
+
const { uid: _uid, extra, ...form } = command.data ?? {};
|
|
49
|
+
command.data = form;
|
|
50
|
+
command.query = { ...command.query, uid: value, extra };
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
command.data = { ...command.data, uid: value };
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export function isFileWriteFailure(raw) {
|
|
58
|
+
return raw.status === 'fail' || raw.status === 'error' || raw.result === 'fail' || raw.result === 'error';
|
|
59
|
+
}
|
|
60
|
+
async function localPath(path) {
|
|
61
|
+
if (!isNodeRuntime())
|
|
62
|
+
return path;
|
|
63
|
+
const nodePath = await importNode('node:path');
|
|
64
|
+
if (/^file:\/\//i.test(path)) {
|
|
65
|
+
const tail = path.slice(7);
|
|
66
|
+
if (tail.startsWith('/') || /^localhost(?:\/|$)/i.test(tail)) {
|
|
67
|
+
const nodeURL = await importNode('node:url');
|
|
68
|
+
return nodeURL.fileURLToPath(path);
|
|
69
|
+
}
|
|
70
|
+
// Accept the documented file://path/to/file shorthand relative to cwd.
|
|
71
|
+
return nodePath.resolve(decodeURIComponent(tail));
|
|
72
|
+
}
|
|
73
|
+
return nodePath.resolve(path);
|
|
74
|
+
}
|
|
75
|
+
function filename(path) {
|
|
76
|
+
const last = path.replace(/[?#].*$/, '').split(/[\\/]/).at(-1) || 'file';
|
|
77
|
+
try {
|
|
78
|
+
return decodeURIComponent(last);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return last;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function sourceFor(value, fallbackName) {
|
|
85
|
+
const record = typeof value === 'string' ? { path: value } : value;
|
|
86
|
+
if (!isRecord(record))
|
|
87
|
+
throw new Error('Resolver must return a path, URL or Blob.');
|
|
88
|
+
const keys = ['path', 'url', 'blob'].filter(key => Object.hasOwn(record, key));
|
|
89
|
+
if (keys.length !== 1 || (record.name !== undefined && typeof record.name !== 'string')) {
|
|
90
|
+
throw new Error('Resolver must return exactly one file source and an optional string name.');
|
|
91
|
+
}
|
|
92
|
+
const name = (typeof record.name === 'string' ? record.name.trim() : undefined) || fallbackName;
|
|
93
|
+
if (keys[0] === 'blob') {
|
|
94
|
+
if (typeof Blob === 'undefined' || !(record.blob instanceof Blob))
|
|
95
|
+
throw new Error('Invalid Blob.');
|
|
96
|
+
const blob = record.blob;
|
|
97
|
+
const blobName = blob.name;
|
|
98
|
+
return { kind: 'upload', blob, name: normalizeFilename(name, blobName || `file${inferExtension(blob.type)}`, 'file') };
|
|
99
|
+
}
|
|
100
|
+
const path = keys[0] === 'url' ? record.url : record.path;
|
|
101
|
+
if (typeof path !== 'string' || !path.trim())
|
|
102
|
+
throw new Error('Empty file source.');
|
|
103
|
+
if (/^(?:https?:\/\/|\/\/)/i.test(path)) {
|
|
104
|
+
const url = new URL(path, 'https://zentao.invalid');
|
|
105
|
+
if (!['http:', 'https:'].includes(url.protocol))
|
|
106
|
+
throw new Error('Invalid file URL.');
|
|
107
|
+
return { kind: 'url', url: path, name };
|
|
108
|
+
}
|
|
109
|
+
if (keys[0] === 'url')
|
|
110
|
+
throw new Error('File URLs must use HTTP(S).');
|
|
111
|
+
if (/^file:(?!\/\/)/i.test(path)) {
|
|
112
|
+
const id = /^file:(\d+)$/i.exec(path)?.[1];
|
|
113
|
+
if (!positiveID(id))
|
|
114
|
+
throw new Error('Invalid ZenTao file ID.');
|
|
115
|
+
return { kind: 'id', id: positiveID(id), name };
|
|
116
|
+
}
|
|
117
|
+
if (/^[a-z][a-z\d+.-]*:/i.test(path) && !/^file:\/\//i.test(path) && !/^[a-z]:[\\/]/i.test(path)) {
|
|
118
|
+
throw new Error('Unsupported file path scheme.');
|
|
119
|
+
}
|
|
120
|
+
let normalized = path;
|
|
121
|
+
let error;
|
|
122
|
+
try {
|
|
123
|
+
normalized = await localPath(path);
|
|
124
|
+
}
|
|
125
|
+
catch (cause) {
|
|
126
|
+
error = cause;
|
|
127
|
+
}
|
|
128
|
+
return { kind: 'upload', path: normalized, name: normalizeFilename(name, filename(path), 'file'), error };
|
|
129
|
+
}
|
|
130
|
+
function extension(source, reference) {
|
|
131
|
+
for (const name of [source.name, source.kind === 'upload' ? source.path : undefined, reference.path]) {
|
|
132
|
+
const match = name && /\.([a-z\d]{1,16})$/i.exec(name.replace(/[?#].*$/, ''));
|
|
133
|
+
if (match)
|
|
134
|
+
return match[1].toLowerCase();
|
|
135
|
+
}
|
|
136
|
+
if (source.kind === 'upload' && source.blob?.type) {
|
|
137
|
+
const ext = inferExtension(source.blob.type);
|
|
138
|
+
if (ext !== '.bin')
|
|
139
|
+
return ext.slice(1);
|
|
140
|
+
}
|
|
141
|
+
return 'png';
|
|
142
|
+
}
|
|
143
|
+
/** Owns only the images uploaded during this object save. */
|
|
144
|
+
export class HtmlFileRequest {
|
|
145
|
+
command;
|
|
146
|
+
context;
|
|
147
|
+
uid;
|
|
148
|
+
warnings = [];
|
|
149
|
+
uploads = [];
|
|
150
|
+
linkProfile;
|
|
151
|
+
checkSession;
|
|
152
|
+
constructor(command, context, uid) {
|
|
153
|
+
this.command = command;
|
|
154
|
+
this.context = context;
|
|
155
|
+
this.uid = uid;
|
|
156
|
+
if (uid)
|
|
157
|
+
this.checkSession = context.client[captureFileSession]();
|
|
158
|
+
}
|
|
159
|
+
profile() {
|
|
160
|
+
return this.linkProfile ??= this.context.client.getZentaoConfig({
|
|
161
|
+
timeout: this.context.timeout, insecure: this.context.insecure,
|
|
162
|
+
}).then(serverConfig => ({ server: this.context.client.siteUrl, serverConfig }));
|
|
163
|
+
}
|
|
164
|
+
async fileLink(path) {
|
|
165
|
+
const profile = await this.profile();
|
|
166
|
+
const auto = profile.serverConfig?.moduleVar && profile.serverConfig.methodVar;
|
|
167
|
+
const link = parseLink(profile, path, auto ? { requestType: 'auto' } : {});
|
|
168
|
+
return !link.external && link.moduleName === 'file' && link.methodName === 'read' ? link : undefined;
|
|
169
|
+
}
|
|
170
|
+
async warn(stage, error, reference, fileID) {
|
|
171
|
+
const creating = this.command.action.type === 'create';
|
|
172
|
+
const objectType = creating ? resolveResultObjectType(this.command.action.resultObjectType, this.command.params, {}) : this.command.module;
|
|
173
|
+
const warning = {
|
|
174
|
+
stage,
|
|
175
|
+
code: error instanceof ZentaoError ? error.code : 'E_FILE_OPERATION_FAILED',
|
|
176
|
+
message: error instanceof Error ? error.message : String(error),
|
|
177
|
+
...(reference ? { field: reference.field, path: reference.path, name: reference.name } : {}),
|
|
178
|
+
...(fileID !== undefined ? { fileID } : {}),
|
|
179
|
+
...(this.uid ? { uid: this.uid } : {}),
|
|
180
|
+
...(objectType ? { objectType } : {}),
|
|
181
|
+
...(!creating && this.command.id ? { objectID: this.command.id } : {}),
|
|
182
|
+
};
|
|
183
|
+
this.warnings.push(warning);
|
|
184
|
+
// Notifications must not turn a completed write into a reported failure.
|
|
185
|
+
try {
|
|
186
|
+
await this.context.onFileError?.({ ...warning });
|
|
187
|
+
}
|
|
188
|
+
catch { /* notification only */ }
|
|
189
|
+
}
|
|
190
|
+
async prepare() {
|
|
191
|
+
const documents = parseHtmlFiles(this.command.data, this.command.action);
|
|
192
|
+
const references = documents.flatMap(document => document.references);
|
|
193
|
+
if (!references.length)
|
|
194
|
+
return;
|
|
195
|
+
const sources = new Map();
|
|
196
|
+
const resolver = this.context.fileResolver;
|
|
197
|
+
// Finish all user resolution before the first upload, including later fields.
|
|
198
|
+
for (const reference of references) {
|
|
199
|
+
if (!reference.path || directURL(reference.path))
|
|
200
|
+
continue;
|
|
201
|
+
const intrinsic = /^file:/i.test(reference.path);
|
|
202
|
+
if (!intrinsic && !resolver)
|
|
203
|
+
continue;
|
|
204
|
+
if (!intrinsic && mayBeFileLink(reference.path)) {
|
|
205
|
+
try {
|
|
206
|
+
if (await this.fileLink(reference.path))
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
// A resolver can still supply a network URL without working page routing.
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
let value = reference.path;
|
|
215
|
+
let name = reference.name;
|
|
216
|
+
if (resolver && !/^file:(?!\/\/)/i.test(reference.path)) {
|
|
217
|
+
if (typeof resolver === 'function')
|
|
218
|
+
value = await resolver({ path: reference.path, name });
|
|
219
|
+
else {
|
|
220
|
+
const key = Object.hasOwn(resolver, reference.path) ? reference.path
|
|
221
|
+
: name && Object.hasOwn(resolver, name) ? name : undefined;
|
|
222
|
+
if (key === undefined)
|
|
223
|
+
throw new Error('No matching file resolver entry.');
|
|
224
|
+
value = resolver[key];
|
|
225
|
+
if (typeof value === 'string')
|
|
226
|
+
name = key;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
sources.set(reference, await sourceFor(value, name));
|
|
230
|
+
}
|
|
231
|
+
catch (cause) {
|
|
232
|
+
const error = new ZentaoError('E_FILE_RESOLVE_FAILED', { path: reference.path }, cause);
|
|
233
|
+
await this.warn('resolve', error, reference);
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (!sources.size)
|
|
238
|
+
return;
|
|
239
|
+
if (!this.uid && [...sources.values()].some(source => source.kind === 'upload')) {
|
|
240
|
+
this.uid = setFileUid(this.command, await newFileUid(), this.context.version);
|
|
241
|
+
this.checkSession = this.context.client[captureFileSession]();
|
|
242
|
+
}
|
|
243
|
+
const replacements = new Map();
|
|
244
|
+
const uploaded = new Map();
|
|
245
|
+
for (const [reference, source] of sources) {
|
|
246
|
+
if (source.kind === 'url') {
|
|
247
|
+
replacements.set(reference, { url: source.url });
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
let id;
|
|
251
|
+
if (source.kind === 'id')
|
|
252
|
+
id = source.id;
|
|
253
|
+
else {
|
|
254
|
+
const key = source.blob ?? source.path;
|
|
255
|
+
let names = uploaded.get(key);
|
|
256
|
+
if (!names)
|
|
257
|
+
uploaded.set(key, names = new Map());
|
|
258
|
+
let outcome = names.get(source.name);
|
|
259
|
+
if (!outcome) {
|
|
260
|
+
outcome = {};
|
|
261
|
+
names.set(source.name, outcome);
|
|
262
|
+
try {
|
|
263
|
+
if (source.error)
|
|
264
|
+
throw source.error;
|
|
265
|
+
const file = source.blob
|
|
266
|
+
? { data: source.blob, filename: source.name }
|
|
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;
|
|
274
|
+
if (!outcome.id && !outcome.url)
|
|
275
|
+
throw new ZentaoError('E_FILE_UPLOAD_FAILED');
|
|
276
|
+
this.uploads.push({ id: outcome.id, url: outcome.url, reference });
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
outcome.error = error;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (Object.hasOwn(outcome, 'error')) {
|
|
283
|
+
await this.warn('upload', outcome.error, reference);
|
|
284
|
+
if (this.context.continueOnFileUploadError === false)
|
|
285
|
+
throw outcome.error;
|
|
286
|
+
replacements.set(reference, { error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error) });
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (outcome.url) {
|
|
290
|
+
replacements.set(reference, { url: outcome.url });
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
id = outcome.id;
|
|
294
|
+
}
|
|
295
|
+
const url = createLink(await this.profile(), {
|
|
296
|
+
moduleName: 'file', methodName: 'read', vars: `fileID=${id}`, viewType: extension(source, reference), relative: true,
|
|
297
|
+
});
|
|
298
|
+
replacements.set(reference, { url });
|
|
299
|
+
}
|
|
300
|
+
const changes = rewriteHtmlFiles(documents, replacements);
|
|
301
|
+
if (Object.keys(changes).length)
|
|
302
|
+
this.command.data = { ...this.command.data, ...changes };
|
|
303
|
+
}
|
|
304
|
+
async cleanup() {
|
|
305
|
+
const pending = this.uploads.splice(0);
|
|
306
|
+
for (const upload of pending) {
|
|
307
|
+
try {
|
|
308
|
+
if (upload.id === undefined && upload.url && mayBeFileLink(upload.url)) {
|
|
309
|
+
const route = await this.fileLink(upload.url);
|
|
310
|
+
upload.id = positiveID(route?.params?.fileID ?? route?.params?.$1);
|
|
311
|
+
}
|
|
312
|
+
if (upload.id === undefined)
|
|
313
|
+
throw new ZentaoError('E_FILE_UPLOAD_FAILED');
|
|
314
|
+
await this.context.requestFile('delete', { fileID: upload.id }, this.checkSession);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
this.uploads.push(upload);
|
|
318
|
+
await this.warn('cleanup', error, upload.reference, upload.id);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** Preserve the primary error and attach enough context to reconcile uncertain writes. */
|
|
323
|
+
errorWithFiles(error) {
|
|
324
|
+
if (!this.uid && !this.warnings.length)
|
|
325
|
+
return error;
|
|
326
|
+
const fileIDs = this.uploads.flatMap(upload => upload.id === undefined ? [] : [upload.id]);
|
|
327
|
+
const extra = { uid: this.uid, fileIDs, fileWarnings: [...this.warnings] };
|
|
328
|
+
if (error instanceof ZentaoError) {
|
|
329
|
+
return new ZentaoError(error.code, error.params, {
|
|
330
|
+
...(plainRecord(error.details) ? error.details : { cause: error.details }), ...extra,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
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 });
|
|
341
|
+
}
|
|
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
|
+
}
|
|
351
|
+
return this.errorWithFiles(error);
|
|
352
|
+
}
|
|
353
|
+
async complete(raw) {
|
|
354
|
+
if (!this.uid)
|
|
355
|
+
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;
|
|
361
|
+
}
|
|
362
|
+
if (positiveID(raw))
|
|
363
|
+
return;
|
|
364
|
+
throw this.errorWithFiles(new ZentaoError('E_FILE_SAVE_UNCONFIRMED', undefined, raw));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ModuleAction } from '../types/module.js';
|
|
2
|
+
type SourceRange = {
|
|
3
|
+
startOffset: number;
|
|
4
|
+
endOffset: number;
|
|
5
|
+
};
|
|
6
|
+
/** HTML 中的文件引用;源码位置仅供内部定点改写。 */
|
|
7
|
+
export interface HtmlFileReference {
|
|
8
|
+
field: string;
|
|
9
|
+
path: string;
|
|
10
|
+
name?: string;
|
|
11
|
+
attributes: Readonly<Record<string, SourceRange>>;
|
|
12
|
+
insertOffset: number;
|
|
13
|
+
}
|
|
14
|
+
/** 单个富文本字段及其中真实 HTML 元素的引用。 */
|
|
15
|
+
export interface HtmlFileDocument {
|
|
16
|
+
field: string;
|
|
17
|
+
html: string;
|
|
18
|
+
references: HtmlFileReference[];
|
|
19
|
+
}
|
|
20
|
+
export interface HtmlFileReplacement {
|
|
21
|
+
url?: string;
|
|
22
|
+
error?: string;
|
|
23
|
+
}
|
|
24
|
+
/** 只扫描最终请求体里声明为 HTML 的顶层字符串字段,不创建浏览器 DOM。 */
|
|
25
|
+
export declare function parseHtmlFiles(data: Record<string, unknown> | undefined, action: ModuleAction): HtmlFileDocument[];
|
|
26
|
+
/** 按源码区间一次拼接,仅返回发生改写的字段;其余 HTML 字节保持原样。 */
|
|
27
|
+
export declare function rewriteHtmlFiles(documents: HtmlFileDocument[], replacements: ReadonlyMap<HtmlFileReference, HtmlFileReplacement>): Record<string, string>;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { parseFragment } from 'parse5';
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function nonempty(value) {
|
|
6
|
+
return value?.trim() || undefined;
|
|
7
|
+
}
|
|
8
|
+
function attribute(element, name) {
|
|
9
|
+
return element.attrs.find(item => item.name === name && !item.namespace)?.value;
|
|
10
|
+
}
|
|
11
|
+
function sourceFilename(path) {
|
|
12
|
+
if (/^file:(?!\/\/)/i.test(path))
|
|
13
|
+
return undefined;
|
|
14
|
+
let pathname = path;
|
|
15
|
+
if (/^(?:https?:)?\/\//i.test(path)) {
|
|
16
|
+
try {
|
|
17
|
+
pathname = new URL(path, 'https://localhost').pathname;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
else if (/^[a-z][a-z\d+.-]*:/i.test(path) && !/^file:\/\//i.test(path) && !/^[a-z]:[\\/]/i.test(path)) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
pathname = path.replace(/^file:\/\//i, '').split(/[?#]/, 1)[0];
|
|
28
|
+
}
|
|
29
|
+
const name = pathname.split(/[\\/]/).at(-1);
|
|
30
|
+
if (!name)
|
|
31
|
+
return undefined;
|
|
32
|
+
try {
|
|
33
|
+
return nonempty(decodeURIComponent(name));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return nonempty(name);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function parseReferences(field, html) {
|
|
40
|
+
const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
|
|
41
|
+
const stack = [...fragment.childNodes].reverse();
|
|
42
|
+
const references = [];
|
|
43
|
+
const seenOffsets = new Set();
|
|
44
|
+
while (stack.length) {
|
|
45
|
+
const node = stack.pop();
|
|
46
|
+
if ('childNodes' in node) {
|
|
47
|
+
for (let i = node.childNodes.length - 1; i >= 0; i--)
|
|
48
|
+
stack.push(node.childNodes[i]);
|
|
49
|
+
}
|
|
50
|
+
if (!('tagName' in node))
|
|
51
|
+
continue;
|
|
52
|
+
if ('content' in node) {
|
|
53
|
+
const content = node.content;
|
|
54
|
+
for (let i = content.childNodes.length - 1; i >= 0; i--)
|
|
55
|
+
stack.push(content.childNodes[i]);
|
|
56
|
+
}
|
|
57
|
+
if (node.namespaceURI !== 'http://www.w3.org/1999/xhtml' || node.tagName !== 'img')
|
|
58
|
+
continue;
|
|
59
|
+
const path = attribute(node, 'src');
|
|
60
|
+
const location = node.sourceCodeLocation;
|
|
61
|
+
const source = location?.attrs?.src;
|
|
62
|
+
const startTag = location?.startTag;
|
|
63
|
+
if (!path || !source || !startTag || html[startTag.endOffset - 1] !== '>' || seenOffsets.has(source.startOffset))
|
|
64
|
+
continue;
|
|
65
|
+
seenOffsets.add(source.startOffset);
|
|
66
|
+
let insertOffset = startTag.endOffset - 1;
|
|
67
|
+
// An unquoted value may itself end in '/', which is not a self-closing marker.
|
|
68
|
+
const slash = insertOffset - 1;
|
|
69
|
+
if (html[slash] === '/' && !Object.values(location.attrs).some(range => range.startOffset <= slash && range.endOffset > slash)) {
|
|
70
|
+
insertOffset = slash;
|
|
71
|
+
}
|
|
72
|
+
references.push({
|
|
73
|
+
field,
|
|
74
|
+
path,
|
|
75
|
+
name: nonempty(attribute(node, 'alt')) || sourceFilename(path),
|
|
76
|
+
attributes: location.attrs,
|
|
77
|
+
insertOffset,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
// HTML error recovery can reorder nodes; resolver calls still follow source order.
|
|
81
|
+
return references.sort((a, b) => a.insertOffset - b.insertOffset);
|
|
82
|
+
}
|
|
83
|
+
/** 只扫描最终请求体里声明为 HTML 的顶层字符串字段,不创建浏览器 DOM。 */
|
|
84
|
+
export function parseHtmlFiles(data, action) {
|
|
85
|
+
const properties = action.requestBody?.schema.properties;
|
|
86
|
+
if (!data || !isRecord(properties))
|
|
87
|
+
return [];
|
|
88
|
+
const documents = [];
|
|
89
|
+
for (const [field, schema] of Object.entries(properties)) {
|
|
90
|
+
if (!isRecord(schema) || (schema.textType !== 'html' && !(typeof schema.description === 'string' && schema.description.endsWith('(HTML)'))))
|
|
91
|
+
continue;
|
|
92
|
+
const html = data[field];
|
|
93
|
+
if (typeof html !== 'string' || !/<img(?=[\t\n\f\r />])/i.test(html))
|
|
94
|
+
continue;
|
|
95
|
+
const references = parseReferences(field, html);
|
|
96
|
+
if (references.length)
|
|
97
|
+
documents.push({ field, html, references });
|
|
98
|
+
}
|
|
99
|
+
return documents;
|
|
100
|
+
}
|
|
101
|
+
function escapeAttribute(value) {
|
|
102
|
+
return value.replace(/[&"<>]/g, char => ({ '&': '&', '"': '"', '<': '<', '>': '>' })[char]);
|
|
103
|
+
}
|
|
104
|
+
/** 按源码区间一次拼接,仅返回发生改写的字段;其余 HTML 字节保持原样。 */
|
|
105
|
+
export function rewriteHtmlFiles(documents, replacements) {
|
|
106
|
+
const result = Object.create(null);
|
|
107
|
+
for (const document of documents) {
|
|
108
|
+
const edits = [];
|
|
109
|
+
for (const reference of document.references) {
|
|
110
|
+
const replacement = replacements.get(reference);
|
|
111
|
+
if (!replacement)
|
|
112
|
+
continue;
|
|
113
|
+
const name = replacement.error === undefined ? 'src' : 'alt';
|
|
114
|
+
const value = replacement.error ?? replacement.url;
|
|
115
|
+
if (value === undefined)
|
|
116
|
+
continue;
|
|
117
|
+
const range = reference.attributes[name];
|
|
118
|
+
if (range) {
|
|
119
|
+
const spelling = document.html.slice(range.startOffset, range.endOffset).match(/^[^\t\n\f\r =/>]+/)?.[0] || name;
|
|
120
|
+
edits.push({ start: range.startOffset, end: range.endOffset, value: `${spelling}="${escapeAttribute(value)}"` });
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
edits.push({ start: reference.insertOffset, end: reference.insertOffset, value: ` ${name}="${escapeAttribute(value)}"` });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (!edits.length)
|
|
127
|
+
continue;
|
|
128
|
+
edits.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
129
|
+
const parts = [];
|
|
130
|
+
let offset = 0;
|
|
131
|
+
for (const edit of edits) {
|
|
132
|
+
parts.push(document.html.slice(offset, edit.start), edit.value);
|
|
133
|
+
offset = edit.end;
|
|
134
|
+
}
|
|
135
|
+
parts.push(document.html.slice(offset));
|
|
136
|
+
result[document.field] = parts.join('');
|
|
137
|
+
}
|
|
138
|
+
return result;
|
|
139
|
+
}
|
package/dist/request/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ type BuiltinActionName<M extends BuiltinModuleName> = Extract<keyof BuiltinActio
|
|
|
4
4
|
type BuiltinListRequestName = BuiltinModuleName;
|
|
5
5
|
type BuiltinNamedRequestName = {
|
|
6
6
|
[M in BuiltinModuleName]: `${M}/${BuiltinActionName<M>}`;
|
|
7
|
-
}[BuiltinModuleName];
|
|
7
|
+
}[BuiltinModuleName] | 'my/info' | 'file/get' | 'file/read';
|
|
8
8
|
type BuiltinIdRequestName = `${BuiltinModuleName}/${number}`;
|
|
9
9
|
/** 内置模块支持的请求名:`module`、`module/action` 或 `module/123`。 */
|
|
10
10
|
export type BuiltinRequestName = BuiltinListRequestName | BuiltinNamedRequestName | BuiltinIdRequestName;
|
|
@@ -18,7 +18,7 @@ export type RequestParamsFor<Name extends BuiltinRequestName> = Name extends 'fi
|
|
|
18
18
|
/** 根据内置请求名推导出的 `ResponseData.data` 类型。 */
|
|
19
19
|
export type RequestResultFor<Name extends BuiltinRequestName> = ActionMetaOf<Name> extends {
|
|
20
20
|
resultType: 'list';
|
|
21
|
-
} ? DataRecord[] : Name extends 'file/create' ? FileCreateResult : ActionMetaOf<Name> extends {
|
|
21
|
+
} ? DataRecord[] : Name extends 'file/create' ? FileCreateResult : Name extends 'file/read' ? ArrayBuffer | string : ActionMetaOf<Name> extends {
|
|
22
22
|
resultType: 'object';
|
|
23
23
|
} ? DataRecord : unknown;
|
|
24
24
|
/**
|
|
@@ -33,7 +33,7 @@ export type RequestResultFor<Name extends BuiltinRequestName> = ActionMetaOf<Nam
|
|
|
33
33
|
* `skipVersionCheckOnConfigError` 可允许本次跳过检查,但不能忽略明确的版本不匹配。
|
|
34
34
|
*
|
|
35
35
|
* 对 `update` 动作,当 `options.autoFill` 或全局 `autoFill` 为真时,会先 GET 当前对象,
|
|
36
|
-
* 用现值补齐用户未显式传入的 body 字段后再 PUT,避免禅道覆盖未提交字段。详见 {@link RequestOptions
|
|
36
|
+
* 用现值补齐用户未显式传入的 body 字段后再 PUT,避免禅道覆盖未提交字段。详见 {@link RequestOptions#autoFill}。
|
|
37
37
|
*
|
|
38
38
|
* @typeParam T 归一化响应中期望的 `data` 字段类型;不传时为 `unknown`,调用方需要自行收窄。
|
|
39
39
|
* @param name - 请求名,例如 `product`、`product/list` 或 `product/1`。
|