dsh-mo-image 0.5.1 → 0.7.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/icon.png ADDED
Binary file
@@ -0,0 +1,670 @@
1
+ /**
2
+ * 请求、解码与错误处理的公共工具。
3
+ *
4
+ * 原本长在 lib/adapters.js 里;协议变多以后拆出来,供 adapters.js 与
5
+ * lib/adapters/*.js 共用,避免循环依赖。
6
+ */
7
+ import { request } from './net.js';
8
+ import { localizedError } from './localized-error.js';
9
+ import { isPng, pngHeaderOf } from './png-scale.js';
10
+
11
+ export const ASPECT_CHOICES = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'];
12
+
13
+ function gcd(a, b) {
14
+ let x = Math.abs(a);
15
+ let y = Math.abs(b);
16
+ while (y) {
17
+ const t = x % y;
18
+ x = y;
19
+ y = t;
20
+ }
21
+ return x || 1;
22
+ }
23
+
24
+ export function aspectLabel(width, height) {
25
+ const g = gcd(width, height);
26
+ return width / g + ':' + height / g;
27
+ }
28
+
29
+ export function nearestAspect(width, height, choices = ASPECT_CHOICES) {
30
+ const w = Number(width) || 1024;
31
+ const h = Number(height) || 1024;
32
+ const target = Math.log(w / h);
33
+ let best = choices[0];
34
+ let bestScore = Infinity;
35
+ for (const item of choices) {
36
+ const parts = String(item).split(':');
37
+ const a = Number(parts[0]);
38
+ const b = Number(parts[1]);
39
+ if (!a || !b) continue;
40
+ const score = Math.abs(Math.log(a / b) - target);
41
+ if (score < bestScore) { bestScore = score; best = item; }
42
+ }
43
+ return best;
44
+ }
45
+
46
+ export function resolutionFor(width, height) {
47
+ const pixels = (Number(width) || 1024) * (Number(height) || 1024);
48
+ if (pixels >= 2800 * 2800) return '4k';
49
+ if (pixels >= 1800 * 1800) return '2k';
50
+ return '1k';
51
+ }
52
+
53
+ export function baseUrlOf(provider) {
54
+ return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
55
+ }
56
+
57
+ /** 按适配器声明的鉴权方式生成头;默认 Bearer。 */
58
+ export function authHeaders(provider, adapter) {
59
+ const key = String((provider && provider.key) || '').trim();
60
+ if (!key) return {};
61
+ const type = String((adapter && adapter.authHeader) || 'bearer');
62
+ if (type === 'api-key') return { 'api-key': key };
63
+ if (type === 'x-key') return { 'x-key': key };
64
+ if (type === 'fal-key') return { Authorization: 'Key ' + key };
65
+ return { Authorization: 'Bearer ' + key };
66
+ }
67
+
68
+ export function headersFor(provider, multipart, extra, adapter) {
69
+ const headers = Object.assign({}, extra || {}, authHeaders(provider, adapter));
70
+ if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
71
+ return headers;
72
+ }
73
+
74
+ export function keyedHeaders(provider, name, multipart) {
75
+ const key = String((provider && provider.key) || '').trim();
76
+ return headersFor(Object.assign({}, provider, { key: '' }), multipart, key ? { [name]: key } : {});
77
+ }
78
+
79
+ export function sleep(ms) {
80
+ return new Promise((resolve) => setTimeout(resolve, ms));
81
+ }
82
+
83
+ /** 把 provider 的一张图编码成 data URL(编辑接口通用)。 */
84
+ export function dataUrlOf(image) {
85
+ return 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64');
86
+ }
87
+
88
+ export async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
89
+ const buffer = await readResponseBytes(response, maxBytes);
90
+ const text = buffer.toString('utf8');
91
+ if (!response.ok) {
92
+ let detail = '';
93
+ try {
94
+ const parsed = JSON.parse(text);
95
+ detail = parsed && (parsed.error && (parsed.error.message || parsed.error) || parsed.message || parsed.detail) || '';
96
+ if (typeof detail !== 'string') detail = JSON.stringify(detail);
97
+ } catch (_error) {
98
+ detail = text.slice(0, 300);
99
+ }
100
+ throw localizedError(
101
+ new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
102
+ detail ? 'upstream.http' : 'upstream.httpNoDetail',
103
+ { status: response.status, detail: detail }
104
+ );
105
+ }
106
+ try {
107
+ return JSON.parse(text);
108
+ } catch (_error) {
109
+ throw localizedError(new Error('本地生图服务返回的不是 JSON'), 'upstream.invalidJson');
110
+ }
111
+ }
112
+
113
+ export function jsonRequest(adapter, provider, requestPath, body) {
114
+ return { path: requestPath, headers: headersFor(provider, false, adapter.headers, adapter), body: JSON.stringify(body) };
115
+ }
116
+
117
+ export function getPath(node, path) {
118
+ if (!path) return node;
119
+ let current = node;
120
+ for (const key of String(path).split('.')) {
121
+ if (current === null || current === undefined) return null;
122
+ current = current[key];
123
+ }
124
+ return current === undefined ? null : current;
125
+ }
126
+
127
+ /** 统一成可安全读写的 Buffer;其它类型(包括 Uint8Array 视图)也兼容。 */
128
+ function asBuffer(value) {
129
+ if (Buffer.isBuffer(value)) return value;
130
+ if (value instanceof Uint8Array) return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
131
+ return null;
132
+ }
133
+
134
+ function asciiAt(buffer, offset, text) {
135
+ return buffer.length >= offset + text.length
136
+ && buffer.toString('ascii', offset, offset + text.length) === text;
137
+ }
138
+
139
+ function pngSizeOf(buffer) {
140
+ if (!isPng(buffer)) return null;
141
+ const header = pngHeaderOf(buffer);
142
+ return header ? { width: header.width, height: header.height } : null;
143
+ }
144
+
145
+ function gifSizeOf(buffer) {
146
+ // 6 字节签名 + 7 字节逻辑屏幕描述符;不足就连宽高都读不到。
147
+ if (buffer.length < 13) return null;
148
+ if (!asciiAt(buffer, 0, 'GIF87a') && !asciiAt(buffer, 0, 'GIF89a')) return null;
149
+ const width = buffer.readUInt16LE(6);
150
+ const height = buffer.readUInt16LE(8);
151
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
152
+ }
153
+
154
+ function webpSizeOf(buffer) {
155
+ // RIFF 头 12 字节 + 首块头 8 字节。
156
+ if (buffer.length < 20) return null;
157
+ if (!asciiAt(buffer, 0, 'RIFF') || !asciiAt(buffer, 8, 'WEBP')) return null;
158
+ const riffSize = buffer.readUInt32LE(4);
159
+ // 有些来源只写首块头、把 riffSize 留成 0,按未声明处理;
160
+ // 一旦声明就必须让容器落在 buffer 内,截断的图不能再当有效图片。
161
+ if (riffSize !== 0 && (riffSize < 12 || riffSize > buffer.length - 8)) return null;
162
+ const chunkSize = buffer.readUInt32LE(16);
163
+ if (chunkSize !== 0 && chunkSize > buffer.length - 20) return null;
164
+ const chunk = buffer.toString('ascii', 12, 16);
165
+ if (chunk === 'VP8 ') {
166
+ if (buffer.length < 30) return null;
167
+ const width = buffer.readUInt16LE(26) & 0x3fff;
168
+ const height = buffer.readUInt16LE(28) & 0x3fff;
169
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
170
+ }
171
+ if (chunk === 'VP8L') {
172
+ if (buffer.length < 25) return null;
173
+ const bits = buffer.readUInt32LE(21);
174
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
175
+ }
176
+ if (chunk === 'VP8X') {
177
+ if (buffer.length < 30) return null;
178
+ const width = (buffer[24] | (buffer[25] << 8) | (buffer[26] << 16)) + 1;
179
+ const height = (buffer[27] | (buffer[28] << 8) | (buffer[29] << 16)) + 1;
180
+ return { width: width, height: height };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function isSofMarker(marker) {
186
+ return (marker >= 0xc0 && marker <= 0xc3)
187
+ || (marker >= 0xc5 && marker <= 0xc7)
188
+ || (marker >= 0xc9 && marker <= 0xcb)
189
+ || (marker >= 0xcd && marker <= 0xcf);
190
+ }
191
+
192
+ function jpegSizeOf(buffer) {
193
+ if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
194
+ let offset = 2;
195
+ while (offset + 4 <= buffer.length) {
196
+ if (buffer[offset] !== 0xff) { offset++; continue; }
197
+ const marker = buffer[offset + 1];
198
+ if (marker === 0xff) { offset++; continue; } // 填充字节
199
+ if (marker === 0x00) { offset += 2; continue; } // 扫描数据里的转义
200
+ if (marker === 0xd8 || marker === 0xd9 || marker === 0x01
201
+ || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
202
+ if (marker === 0xda) return null; // 都到扫描数据了还没见 SOF
203
+ const length = buffer.readUInt16BE(offset + 2);
204
+ if (length < 2) return null;
205
+ // 整段必须落在 buffer 内:只够读宽高、段尾却被截断的 JPEG 仍是坏图。
206
+ const next = offset + 2 + length;
207
+ if (next > buffer.length) return null;
208
+ if (isSofMarker(marker)) {
209
+ // SOF 段头至少要覆盖精度、高、宽和分量数;不足就当作截断。
210
+ if (length < 8 || offset + 9 > buffer.length) return null;
211
+ const height = buffer.readUInt16BE(offset + 5);
212
+ const width = buffer.readUInt16BE(offset + 7);
213
+ return width > 0 && height > 0 ? { width: width, height: height } : null;
214
+ }
215
+ offset = next;
216
+ }
217
+ return null;
218
+ }
219
+
220
+ /**
221
+ * 从文件头读出真实宽高(不解码整张图)。
222
+ * PNG / JPEG / WebP / GIF 足够覆盖各家回图;结构不完整或认不出返回 null。
223
+ */
224
+ export function imageSizeOf(buffer) {
225
+ const bytes = asBuffer(buffer);
226
+ if (!bytes) return null;
227
+ try {
228
+ if (isPng(bytes)) return pngSizeOf(bytes);
229
+ const gif = gifSizeOf(bytes);
230
+ if (gif) return gif;
231
+ const webp = webpSizeOf(bytes);
232
+ if (webp) return webp;
233
+ return jpegSizeOf(bytes);
234
+ } catch (_error) {
235
+ return null;
236
+ }
237
+ }
238
+
239
+ export function sniffType(buffer) {
240
+ const bytes = asBuffer(buffer);
241
+ if (!bytes) return 'image/png';
242
+ if (isPng(bytes)) return 'image/png';
243
+ if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg';
244
+ if (asciiAt(bytes, 0, 'RIFF') && asciiAt(bytes, 8, 'WEBP')) return 'image/webp';
245
+ if (asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a')) return 'image/gif';
246
+ return 'image/png';
247
+ }
248
+
249
+ /** 只有能读出合法宽高的文件头才算图片;截断内容不能混进参考图或下载结果。 */
250
+ export function looksLikeImage(buffer) {
251
+ return imageSizeOf(buffer) !== null;
252
+ }
253
+
254
+ export function base64ToImage(text) {
255
+ const raw = String(text || '');
256
+ if (!raw || raw.length < 64) return null;
257
+ const dataUrl = /^data:image\/([a-z+]+);base64,(.+)$/i.exec(raw);
258
+ const payload = dataUrl ? dataUrl[2] : raw;
259
+ if (!/^[A-Za-z0-9+/=\r\n]+$/.test(payload)) return null;
260
+ let buffer;
261
+ try {
262
+ buffer = Buffer.from(payload, 'base64');
263
+ } catch (_error) {
264
+ return null;
265
+ }
266
+ if (!looksLikeImage(buffer)) return null;
267
+ return { bytes: buffer, contentType: dataUrl ? 'image/' + dataUrl[1].toLowerCase() : sniffType(buffer) };
268
+ }
269
+
270
+ function collectStrings(node, out, depth) {
271
+ if (!node || depth > 6 || out.length > 80) return;
272
+ if (typeof node === 'string') {
273
+ out.push(node);
274
+ return;
275
+ }
276
+ if (Array.isArray(node)) {
277
+ for (const item of node) collectStrings(item, out, depth + 1);
278
+ return;
279
+ }
280
+ if (typeof node === 'object') {
281
+ for (const key of Object.keys(node)) collectStrings(node[key], out, depth + 1);
282
+ }
283
+ }
284
+
285
+ /**
286
+ * 从任意形状的回应里找出图片:二进制 / b64 / data-url / 外链,全都认。
287
+ */
288
+ export function decodeImagePayload(payload, binary) {
289
+ if (binary && looksLikeImage(binary)) return { bytes: binary, contentType: sniffType(binary) };
290
+ if (!payload) throw new Error('生图接口没有返回图片');
291
+
292
+ const strings = [];
293
+ collectStrings(payload, strings, 0);
294
+
295
+ for (const text of strings) {
296
+ const image = base64ToImage(text);
297
+ if (image) return image;
298
+ }
299
+ for (const text of strings) {
300
+ if (!/^https?:\/\//i.test(text)) continue;
301
+ if (/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(text)) return { url: text };
302
+ }
303
+ for (const text of strings) {
304
+ if (/^https?:\/\//i.test(text)) return { url: text };
305
+ }
306
+ throw new Error('生图接口返回格式不认识');
307
+ }
308
+
309
+ /** 按上限读取响应体;有 Content-Length 时先拒绝明显超限的响应。 */
310
+ export async function readResponseBytes(response, maxBytes) {
311
+ const limit = Number(maxBytes) > 0 ? Number(maxBytes) : Infinity;
312
+ const declared = Number(response.headers.get('content-length'));
313
+ if (Number.isFinite(declared) && declared > limit) {
314
+ try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
315
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
316
+ }
317
+ const body = response.body;
318
+ if (!body) {
319
+ const buffer = Buffer.from(await response.arrayBuffer());
320
+ if (buffer.length > limit) throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
321
+ return buffer;
322
+ }
323
+ // Content-Length 可信时直接写进预分配 buffer,避免 chunks + Buffer.concat 的 2 倍峰值。
324
+ if (Number.isFinite(declared) && declared > 0) {
325
+ const out = Buffer.allocUnsafe(Math.floor(declared));
326
+ let offset = 0;
327
+ let overflow = null;
328
+ for await (const chunk of body) {
329
+ const buffer = Buffer.from(chunk);
330
+ if (offset + buffer.length > limit) {
331
+ try { await body.cancel(); } catch (_error) { /* ignore */ }
332
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
333
+ }
334
+ if (!overflow && offset + buffer.length <= out.length) {
335
+ buffer.copy(out, offset);
336
+ } else {
337
+ if (!overflow) overflow = [out.subarray(0, offset)];
338
+ overflow.push(buffer);
339
+ }
340
+ offset += buffer.length;
341
+ }
342
+ if (overflow) return Buffer.concat(overflow, offset);
343
+ return offset === out.length ? out : Buffer.from(out.subarray(0, offset));
344
+ }
345
+ const chunks = [];
346
+ let total = 0;
347
+ for await (const chunk of body) {
348
+ const buffer = Buffer.from(chunk);
349
+ total += buffer.length;
350
+ if (total > limit) {
351
+ try { await body.cancel(); } catch (_error) { /* ignore */ }
352
+ throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
353
+ }
354
+ chunks.push(buffer);
355
+ }
356
+ return Buffer.concat(chunks);
357
+ }
358
+
359
+ export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
360
+
361
+ export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
362
+ const response = await request(url, { signal: signal });
363
+ if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
364
+ const bytes = await readResponseBytes(response, maxBytes);
365
+ if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
366
+ return { bytes: bytes, contentType: sniffType(bytes) };
367
+ }
368
+
369
+ /* ---------------------------------------------------------- 通用异步任务 */
370
+
371
+ /**
372
+ * 通用「提交拿任务 → 轮询拿图」形状的识别与轮询辅助,不绑定任何厂商。
373
+ *
374
+ * 覆盖的是 OpenAI 兼容网关里最常见的那套约定:
375
+ * - 任务 id:task_id / taskId / job_id / request_id / generation_id / prediction_id / id
376
+ * - 轮询地址:polling_url / status_url / task_url / get_url / urls.get ...
377
+ * - 状态词:SUCCEEDED / SUCCESS / COMPLETED / READY ...;FAILED / ERROR / CANCELED ...
378
+ * - 结果图:output_images / images / data / output / result 里的 url / b64_json
379
+ *
380
+ * 认不出来时不猜:调用方按同步响应处理,或者报「格式不认识」。
381
+ */
382
+ const TASK_ID_KEYS = [
383
+ 'task_id', 'taskId', 'job_id', 'jobId', 'request_id', 'requestId',
384
+ 'generation_id', 'generationId', 'prediction_id', 'predictionId', 'id'
385
+ ];
386
+ const TASK_URL_KEYS = [
387
+ 'polling_url', 'pollingUrl', 'poll_url', 'pollUrl', 'status_url', 'statusUrl',
388
+ 'task_url', 'taskUrl', 'get_url', 'getUrl', 'result_url', 'resultUrl'
389
+ ];
390
+ const TASK_IMAGE_KEYS = [
391
+ 'output_images', 'outputImages', 'images', 'image_urls', 'data', 'outputs', 'output',
392
+ 'result', 'results', 'artifacts', 'files', 'url', 'image_url', 'imageUrl', 'b64_json', 'base64', 'image'
393
+ ];
394
+ const TASK_SUCCESS = new Set([
395
+ 'SUCCEED', 'SUCCEEDED', 'SUCCESS', 'SUCCESSFUL', 'COMPLETED', 'COMPLETE', 'DONE', 'FINISHED', 'READY'
396
+ ]);
397
+ const TASK_FAILURE = new Set([
398
+ 'FAILED', 'FAILURE', 'ERROR', 'CANCELED', 'CANCELLED', 'ABORTED', 'REJECTED', 'EXPIRED', 'MODERATED'
399
+ ]);
400
+
401
+ /** 任务载荷的常见嵌套层:顶层、data、output、result(数组不算,避免把结果图当任务)。 */
402
+ function taskNodes(payload) {
403
+ const nodes = [];
404
+ const visit = (node, depth) => {
405
+ if (!node || typeof node !== 'object' || Array.isArray(node) || depth > 2) return;
406
+ nodes.push(node);
407
+ for (const key of ['data', 'output', 'result']) visit(node[key], depth + 1);
408
+ };
409
+ visit(payload, 0);
410
+ return nodes;
411
+ }
412
+
413
+ function firstTaskString(nodes, keys) {
414
+ // 字段名的优先级高于层级:嵌套的 task_id 应该压过顶层的通用 id。
415
+ for (const key of keys) {
416
+ for (const node of nodes) {
417
+ if (typeof node[key] === 'string' && node[key].trim()) return node[key].trim();
418
+ }
419
+ }
420
+ return '';
421
+ }
422
+
423
+ function urlsGetOf(nodes) {
424
+ for (const node of nodes) {
425
+ if (node.urls && typeof node.urls.get === 'string' && node.urls.get.trim()) return node.urls.get.trim();
426
+ }
427
+ return '';
428
+ }
429
+
430
+ /** 从提交响应里认任务:只要拿到任务 id 或轮询地址,就当异步任务。 */
431
+ export function readTaskEnvelope(payload) {
432
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
433
+ const nodes = taskNodes(payload);
434
+ const pollUrl = firstTaskString(nodes, TASK_URL_KEYS) || urlsGetOf(nodes);
435
+ const taskId = firstTaskString(nodes, TASK_ID_KEYS);
436
+ if (!pollUrl && !taskId) return null;
437
+ return { taskId: taskId, pollUrl: pollUrl };
438
+ }
439
+
440
+ function absoluteTaskUrl(value, base) {
441
+ const text = String(value || '').trim();
442
+ if (!text) return '';
443
+ if (/^https?:\/\//i.test(text)) return text;
444
+ try {
445
+ return new URL(text, base.endsWith('/') ? base : base + '/').toString();
446
+ } catch (_error) {
447
+ return '';
448
+ }
449
+ }
450
+
451
+ /**
452
+ * 轮询候选地址:响应里给的优先;没给就按常见约定推两个,最后再试提交地址 + 任务 id。
453
+ * base 以 /v1 结尾时是 /v1/tasks/{id},只有站点根时补 /v1。
454
+ */
455
+ export function taskPollUrls(provider, submission, submitUrl) {
456
+ const base = baseUrlOf(provider);
457
+ const nodes = taskNodes(submission || {});
458
+ const raw = [];
459
+ const direct = firstTaskString(nodes, TASK_URL_KEYS) || urlsGetOf(nodes);
460
+ if (direct) raw.push(direct);
461
+ const taskId = firstTaskString(nodes, TASK_ID_KEYS);
462
+ if (taskId) {
463
+ const id = encodeURIComponent(taskId);
464
+ const root = base.replace(/\/v\d+[a-z0-9]*$/i, '');
465
+ raw.push(root + '/v1/tasks/' + id);
466
+ raw.push(base + '/tasks/' + id);
467
+ if (submitUrl) raw.push(String(submitUrl).replace(/\/+$/, '') + '/' + id);
468
+ }
469
+ const urls = [];
470
+ for (const item of raw) {
471
+ const resolved = absoluteTaskUrl(item, base);
472
+ if (resolved && !urls.includes(resolved)) urls.push(resolved);
473
+ }
474
+ return urls;
475
+ }
476
+
477
+ function statusTextOf(nodes) {
478
+ // 任务专用状态词优先:顶层 status 可能只是「请求成功」,不能当成任务完成。
479
+ for (const key of ['task_status', 'taskStatus', 'status', 'state']) {
480
+ for (const node of nodes) {
481
+ const value = node[key];
482
+ if (typeof value === 'string' && value.trim()) return value.trim().toUpperCase();
483
+ if (value && typeof value === 'object') {
484
+ const nested = value.status || value.state;
485
+ if (typeof nested === 'string' && nested.trim()) return nested.trim().toUpperCase();
486
+ }
487
+ }
488
+ }
489
+ return '';
490
+ }
491
+
492
+ function errorTextOf(value, depth = 0) {
493
+ if (depth > 4 || value === null || value === undefined) return '';
494
+ if (typeof value === 'string') return value.trim();
495
+ if (Array.isArray(value)) {
496
+ for (const item of value) {
497
+ const text = errorTextOf(item, depth + 1);
498
+ if (text) return text;
499
+ }
500
+ return '';
501
+ }
502
+ if (typeof value !== 'object') return '';
503
+ for (const key of ['message', 'msg', 'detail', 'error', 'errors', 'reason', 'logs', 'fail_reason', 'error_message']) {
504
+ if (value[key] === undefined) continue;
505
+ const text = errorTextOf(value[key], depth + 1);
506
+ if (text) return text;
507
+ }
508
+ return '';
509
+ }
510
+
511
+ /** 明确的错误字段;没有状态词时用它判断任务失败,不去猜普通的 message。 */
512
+ export function taskErrorOf(payload) {
513
+ if (!payload || typeof payload !== 'object') return '';
514
+ for (const node of taskNodes(payload)) {
515
+ for (const key of ['error', 'errors', 'fail_reason', 'error_message']) {
516
+ if (node[key] === undefined || node[key] === null) continue;
517
+ const text = errorTextOf(node[key]);
518
+ if (text) return text;
519
+ }
520
+ }
521
+ return '';
522
+ }
523
+
524
+ /** 失败任务的人话原因:先找错误字段,再退到 message / detail / logs。 */
525
+ export function taskMessageOf(payload) {
526
+ if (!payload || typeof payload !== 'object') return '';
527
+ const error = taskErrorOf(payload);
528
+ if (error) return error;
529
+ for (const node of taskNodes(payload)) {
530
+ for (const key of ['message', 'msg', 'detail', 'logs', 'reason']) {
531
+ if (node[key] === undefined || node[key] === null) continue;
532
+ const text = errorTextOf(node[key]);
533
+ if (text) return text;
534
+ }
535
+ }
536
+ return '';
537
+ }
538
+
539
+ function imageFromValue(value, depth = 0) {
540
+ if (depth > 6 || value === null || value === undefined) return null;
541
+ if (typeof value === 'string') {
542
+ const text = value.trim();
543
+ if (!text) return null;
544
+ const decoded = base64ToImage(text);
545
+ if (decoded) return { bytes: decoded.bytes, contentType: decoded.contentType };
546
+ if (/^https?:\/\//i.test(text)) return { url: text };
547
+ return null;
548
+ }
549
+ if (Array.isArray(value)) {
550
+ for (const item of value) {
551
+ const hit = imageFromValue(item, depth + 1);
552
+ if (hit) return hit;
553
+ }
554
+ return null;
555
+ }
556
+ if (typeof value === 'object') {
557
+ for (const key of TASK_IMAGE_KEYS) {
558
+ if (value[key] === undefined) continue;
559
+ const hit = imageFromValue(value[key], depth + 1);
560
+ if (hit) return hit;
561
+ }
562
+ }
563
+ return null;
564
+ }
565
+
566
+ function containerImageOf(payload) {
567
+ for (const key of ['output_images', 'outputImages', 'images', 'image_urls', 'data', 'outputs', 'output', 'result', 'results', 'artifacts', 'files']) {
568
+ if (payload[key] === undefined) continue;
569
+ const hit = imageFromValue(payload[key], 1);
570
+ if (hit) return hit;
571
+ }
572
+ return null;
573
+ }
574
+
575
+ /**
576
+ * 只看约定的结果字段,避免把回显的参考图或状态地址当结果。
577
+ * containersOnly 用于「任务还在跑」的载荷:连顶层的 url / image 都不认,
578
+ * 免得把任务详情地址当成生成图去下载。
579
+ */
580
+ export function taskImageOf(payload, options) {
581
+ if (!payload || typeof payload !== 'object') return null;
582
+ if (options && options.containersOnly) return containerImageOf(payload);
583
+ return imageFromValue(payload);
584
+ }
585
+
586
+ /** 任务已成功但形状不常见时,再按「任意位置的图片」兜底扫一遍。 */
587
+ export function looseImageOf(payload) {
588
+ try {
589
+ return decodeImagePayload(payload, null) || null;
590
+ } catch (_error) {
591
+ return null;
592
+ }
593
+ }
594
+
595
+ /** 把任务载荷收敛成三态:成功词、失败词、其余都算进行中。 */
596
+ export function taskStatusOf(payload) {
597
+ const nodes = taskNodes(payload);
598
+ const status = statusTextOf(nodes);
599
+ if (status) {
600
+ if (TASK_SUCCESS.has(status)) return { state: 'success', status: status };
601
+ if (TASK_FAILURE.has(status)) {
602
+ return { state: 'failure', status: status, message: taskMessageOf(payload) || status };
603
+ }
604
+ return { state: 'pending', status: status };
605
+ }
606
+ const error = taskErrorOf(payload);
607
+ if (error) return { state: 'failure', status: '', message: error };
608
+ return { state: 'pending', status: '' };
609
+ }
610
+
611
+ export function extractMessage(text) {
612
+ const raw = String(text || '').trim();
613
+ if (!raw) return '';
614
+ try {
615
+ const parsed = JSON.parse(raw);
616
+ if (parsed && typeof parsed === 'object') {
617
+ if (parsed.error && typeof parsed.error === 'object' && parsed.error.message) return String(parsed.error.message);
618
+ if (typeof parsed.error === 'string') return parsed.error;
619
+ if (parsed.message) return String(parsed.message);
620
+ if (parsed.msg) return String(parsed.msg);
621
+ }
622
+ } catch (_error) {
623
+ /* 不是 JSON,原样返回 */
624
+ }
625
+ return raw;
626
+ }
627
+
628
+ function detectDroppableField(message) {
629
+ const token = "['\"]?([A-Za-z_][A-Za-z0-9_.-]*)['\"]?";
630
+ const patterns = [
631
+ new RegExp('unknown parameter:\\s*' + token, 'i'),
632
+ new RegExp('unrecognized request argument supplied:\\s*' + token, 'i'),
633
+ new RegExp('unknown (?:field|parameter|property)\\s*' + token, 'i'),
634
+ new RegExp('(?:extra|unexpected|unsupported|not supported) (?:field|parameter|property)[^A-Za-z0-9_]*' + token, 'i')
635
+ ];
636
+ for (const pattern of patterns) {
637
+ const hit = pattern.exec(message);
638
+ if (hit && hit[1]) return hit[1].trim();
639
+ }
640
+ return null;
641
+ }
642
+
643
+ /** 从结构化错误里取 param 字段;不少兼容网关只在 error.param 里给字段名。 */
644
+ function extractErrorParam(text) {
645
+ try {
646
+ const parsed = JSON.parse(String(text || ''));
647
+ const param = (parsed && parsed.error && parsed.error.param) || (parsed && parsed.param);
648
+ return typeof param === 'string' && /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(param) ? param.trim() : null;
649
+ } catch (_error) {
650
+ return null;
651
+ }
652
+ }
653
+
654
+ /**
655
+ * 把各家的错误归结成几类,调用方只按 kind 决策。
656
+ */
657
+ export function classifyFailure(status, text) {
658
+ const message = extractMessage(text) || ('HTTP ' + status);
659
+ const drop = detectDroppableField(message) || extractErrorParam(text);
660
+ if (drop) return { kind: 'param', drop: drop, message: message };
661
+ if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
662
+ return { kind: 'size', message: message };
663
+ }
664
+ if (status === 401 || status === 403) return { kind: 'auth', message: message };
665
+ if (status === 404) return { kind: 'endpoint', message: message };
666
+ if (status === 413) return { kind: 'payload', message: message };
667
+ if (status === 429) return { kind: 'rate', message: message, retryable: true };
668
+ if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
669
+ return { kind: 'unknown', message: message };
670
+ }