dsh-mo-image 0.5.1 → 0.6.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/CHANGELOG.md +7 -0
- package/README.md +428 -409
- package/lib/adapter-kit.js +318 -0
- package/lib/adapters/async.js +351 -0
- package/lib/adapters/cn.js +95 -0
- package/lib/adapters/openai.js +233 -0
- package/lib/adapters.js +273 -356
- package/lib/client.js +549 -21
- package/lib/comfy-workflow.js +524 -0
- package/lib/index.js +230 -33
- package/lib/localized-error.js +1 -0
- package/lib/prompt-profiles.js +21 -0
- package/locale/messages.csv +214 -180
- package/package.json +1 -1
package/lib/adapters.js
CHANGED
|
@@ -17,6 +17,20 @@ import { createRequire } from 'node:module';
|
|
|
17
17
|
import { decodePng, encodePng, resizeRgba } from './png-scale.js';
|
|
18
18
|
import { request } from './net.js';
|
|
19
19
|
import { localizedError } from './localized-error.js';
|
|
20
|
+
import {
|
|
21
|
+
ASPECT_CHOICES, aspectLabel, nearestAspect, resolutionFor, baseUrlOf, headersFor,
|
|
22
|
+
keyedHeaders, sleep, readJsonResponse, jsonRequest, getPath, sniffType, looksLikeImage,
|
|
23
|
+
base64ToImage, fetchImageUrl, decodeImagePayload, classifyFailure, extractMessage,
|
|
24
|
+
readResponseBytes, MAX_IMAGE_BYTES
|
|
25
|
+
} from './adapter-kit.js';
|
|
26
|
+
import { OPENAI_ADAPTERS } from './adapters/openai.js';
|
|
27
|
+
import { ASYNC_ADAPTERS } from './adapters/async.js';
|
|
28
|
+
import { CN_ADAPTERS } from './adapters/cn.js';
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
ASPECT_CHOICES, aspectLabel, nearestAspect, resolutionFor, sniffType, looksLikeImage,
|
|
32
|
+
fetchImageUrl, decodeImagePayload, classifyFailure, extractMessage, readResponseBytes, MAX_IMAGE_BYTES
|
|
33
|
+
};
|
|
20
34
|
|
|
21
35
|
const require = createRequire(import.meta.url);
|
|
22
36
|
const DEFAULT_SIZE = '1024x1024';
|
|
@@ -34,22 +48,6 @@ export function parseSize(raw) {
|
|
|
34
48
|
return { width: width, height: height, text: width + 'x' + height };
|
|
35
49
|
}
|
|
36
50
|
|
|
37
|
-
function gcd(a, b) {
|
|
38
|
-
let x = Math.abs(a);
|
|
39
|
-
let y = Math.abs(b);
|
|
40
|
-
while (y) {
|
|
41
|
-
const t = x % y;
|
|
42
|
-
x = y;
|
|
43
|
-
y = t;
|
|
44
|
-
}
|
|
45
|
-
return x || 1;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function aspectLabel(width, height) {
|
|
49
|
-
const g = gcd(width, height);
|
|
50
|
-
return width / g + ':' + height / g;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
51
|
function settle(size, adjusted, reason, requested) {
|
|
54
52
|
const text = size && size.text ? size.text : String(size || DEFAULT_SIZE);
|
|
55
53
|
const parsed = size && size.width ? size : parseSize(text);
|
|
@@ -178,6 +176,15 @@ function encodeSize(adapter, fitted) {
|
|
|
178
176
|
const field = policy.field || 'size';
|
|
179
177
|
const style = policy.style || 'string';
|
|
180
178
|
if (fitted.omit || fitted.size === 'none') return {};
|
|
179
|
+
// 少数平台只认固定档位(火山方舟的 2K/3K/4K);接近档位就发档位名,否则发像素。
|
|
180
|
+
if (Array.isArray(policy.presets)) {
|
|
181
|
+
const pixels = (fitted.width || 1024) * (fitted.height || 1024);
|
|
182
|
+
for (const preset of policy.presets) {
|
|
183
|
+
if (!preset || !preset.pixels) continue;
|
|
184
|
+
if (Math.abs(pixels - preset.pixels) / preset.pixels <= 0.12) return { [field]: preset.value };
|
|
185
|
+
}
|
|
186
|
+
return { [field]: fitted.size };
|
|
187
|
+
}
|
|
181
188
|
if (style === 'width-height') return { width: fitted.width, height: fitted.height };
|
|
182
189
|
if (style === 'aspect') {
|
|
183
190
|
const aspects = policy.aspects || ['1:1'];
|
|
@@ -217,8 +224,8 @@ export function qualityOptionsFor(adapter, model) {
|
|
|
217
224
|
return { label: spec.label || '质量', options, default: fallback };
|
|
218
225
|
}
|
|
219
226
|
|
|
220
|
-
export function qualityForAdapter(adapter, value) {
|
|
221
|
-
const spec = qualityOptionsFor(adapter);
|
|
227
|
+
export function qualityForAdapter(adapter, value, model) {
|
|
228
|
+
const spec = qualityOptionsFor(adapter, model);
|
|
222
229
|
if (!spec) return undefined;
|
|
223
230
|
const raw = String(value || '').trim().toLowerCase();
|
|
224
231
|
if (raw === 'off') return 'off';
|
|
@@ -253,6 +260,21 @@ const NON_IMAGE_MODEL_KEYWORDS = [
|
|
|
253
260
|
];
|
|
254
261
|
const EXACT_IMAGE_MODEL_IDS = new Set(['core']);
|
|
255
262
|
|
|
263
|
+
const ASPECT_CHOICES_14 = ['1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9', '1:4', '4:1', '1:8', '8:1'];
|
|
264
|
+
|
|
265
|
+
/** 这些主机有自己的适配器:模型名匹配不能抢在主机匹配前面。 */
|
|
266
|
+
const MAJOR_HOSTS = /(^|\.)openai\.azure\.com$|(^|\.)openrouter\.ai$|(^|\.)bfl\.ai$|(^|\.)queue\.fal\.run$|(^|\.)fal\.run$|(^|\.)falrun\.com$|(^|\.)api\.replicate\.com$/;
|
|
267
|
+
|
|
268
|
+
function hostOfBase(baseUrl) {
|
|
269
|
+
return String(baseUrl || '').replace(/^https?:\/\//i, '').split('/')[0].toLowerCase();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Ideogram 把模型写进路径:/v2/image/generate/{model}。 */
|
|
273
|
+
function ideogramPath(input) {
|
|
274
|
+
const model = String((input && input.model) || 'ideogram-3').trim().replace(/^\/+/, '') || 'ideogram-3';
|
|
275
|
+
return '/v2/image/generate/' + model;
|
|
276
|
+
}
|
|
277
|
+
|
|
256
278
|
function normalizeModelId(model) {
|
|
257
279
|
return String(model || '').trim().toLowerCase().replace(/[_\s./:]+/g, '-');
|
|
258
280
|
}
|
|
@@ -270,39 +292,28 @@ export function filterImageModels(models) {
|
|
|
270
292
|
return (Array.isArray(models) ? models : []).filter(isLikelyImageModel);
|
|
271
293
|
}
|
|
272
294
|
|
|
273
|
-
|
|
295
|
+
/* ------------------------------------------------------------ ComfyUI 工作流 */
|
|
274
296
|
|
|
275
|
-
|
|
276
|
-
const w = Number(width) || 1024;
|
|
277
|
-
const h = Number(height) || 1024;
|
|
278
|
-
const target = Math.log(w / h);
|
|
279
|
-
let best = choices[0];
|
|
280
|
-
let bestScore = Infinity;
|
|
281
|
-
for (const item of choices) {
|
|
282
|
-
const parts = String(item).split(':');
|
|
283
|
-
const a = Number(parts[0]);
|
|
284
|
-
const b = Number(parts[1]);
|
|
285
|
-
if (!a || !b) continue;
|
|
286
|
-
const score = Math.abs(Math.log(a / b) - target);
|
|
287
|
-
if (score < bestScore) { bestScore = score; best = item; }
|
|
288
|
-
}
|
|
289
|
-
return best;
|
|
290
|
-
}
|
|
297
|
+
import { parseWorkflow, uiToApi, analyzeWorkflow, injectByMapping, applyWorkflowParams } from './comfy-workflow.js';
|
|
291
298
|
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
if (pixels >= 2800 * 2800) return '4k';
|
|
295
|
-
if (pixels >= 1800 * 1800) return '2k';
|
|
296
|
-
return '1k';
|
|
297
|
-
}
|
|
299
|
+
const OBJECT_INFO_TTL = 5 * 60 * 1000;
|
|
300
|
+
const objectInfoCache = new Map();
|
|
298
301
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
+
/** 拉全量节点签名并缓存;UI 格式工作流和模型列表都靠它。 */
|
|
303
|
+
async function comfyObjectInfo(base, provider, signal) {
|
|
304
|
+
const hit = objectInfoCache.get(base);
|
|
305
|
+
const now = Date.now();
|
|
306
|
+
if (hit && now - hit.at < OBJECT_INFO_TTL) return hit.data;
|
|
307
|
+
const response = await request(base + '/object_info', { headers: headersFor(provider, false), signal });
|
|
308
|
+
if (!response.ok) {
|
|
309
|
+
try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
|
|
310
|
+
throw new Error('读不到 ComfyUI 的节点签名(/object_info),请确认服务在运行。');
|
|
311
|
+
}
|
|
312
|
+
const data = await readJsonResponse(response, 40 * 1024 * 1024);
|
|
313
|
+
objectInfoCache.set(base, { at: now, data });
|
|
314
|
+
return data;
|
|
302
315
|
}
|
|
303
316
|
|
|
304
|
-
/* ------------------------------------------------------------ ComfyUI 工作流 */
|
|
305
|
-
|
|
306
317
|
/**
|
|
307
318
|
* 读某个 loader 节点可选的模型名。优先只取单节点,避免自定义节点很多时
|
|
308
319
|
* /object_info 的 20MB+ 全量响应;节点级 404 时退回全量。
|
|
@@ -650,41 +661,86 @@ function comfyCustomWorkflow(provider, model) {
|
|
|
650
661
|
return typeof entry.workflow === 'string' ? entry.workflow.trim() : '';
|
|
651
662
|
}
|
|
652
663
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
664
|
+
/**
|
|
665
|
+
* 设置页解析用:把用户贴的工作流变成映射与候选。
|
|
666
|
+
* UI 格式缺签名的节点会导致悬空连线,所以这里当硬错误处理。
|
|
667
|
+
*/
|
|
668
|
+
export async function analyzeComfyWorkflow({ base, provider, workflow, signal }) {
|
|
669
|
+
const parsed = parseWorkflow(workflow);
|
|
670
|
+
const info = await comfyObjectInfo(base, provider, signal);
|
|
671
|
+
let graph = parsed.graph;
|
|
672
|
+
if (parsed.format === 'ui') {
|
|
673
|
+
const converted = uiToApi(parsed.ui, info);
|
|
674
|
+
if (converted.missing.length) {
|
|
675
|
+
throw new Error('工作流里的节点没有安装:' + converted.missing.join('、')
|
|
676
|
+
+ '。请在 ComfyUI 里装好它们,或改贴 API 格式的工作流。');
|
|
677
|
+
}
|
|
678
|
+
graph = converted.graph;
|
|
659
679
|
}
|
|
660
|
-
|
|
661
|
-
|
|
680
|
+
const analysis = analyzeWorkflow(graph, info);
|
|
681
|
+
return { format: parsed.format, ...analysis };
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
async function comfyCustomGraph(base, provider, { kind, input, model, width, height, seed, raw, signal }) {
|
|
685
|
+
const parsed = parseWorkflow(raw);
|
|
686
|
+
let graph = parsed.graph;
|
|
687
|
+
if (parsed.format === 'ui') {
|
|
688
|
+
const info = await comfyObjectInfo(base, provider, signal);
|
|
689
|
+
const converted = uiToApi(parsed.ui, info);
|
|
690
|
+
if (converted.missing.length) {
|
|
691
|
+
throw new Error('工作流里的节点没有安装:' + converted.missing.join('、')
|
|
692
|
+
+ '。请在 ComfyUI 里装好它们,或改贴 API 格式的工作流。');
|
|
693
|
+
}
|
|
694
|
+
graph = converted.graph;
|
|
662
695
|
}
|
|
696
|
+
|
|
697
|
+
const entry = provider && provider.modelOptions ? provider.modelOptions[model] : null;
|
|
698
|
+
const mapping = entry && entry.mapping ? entry.mapping : null;
|
|
699
|
+
const hasPlaceholder = /\{\{\s*[A-Za-z_][A-Za-z0-9_]*\s*\}\}/.test(raw);
|
|
663
700
|
const values = {
|
|
664
701
|
prompt: input.prompt || '',
|
|
665
702
|
negative_prompt: input.negativePrompt || '',
|
|
666
|
-
|
|
703
|
+
negativePrompt: input.negativePrompt || '',
|
|
704
|
+
width, height, seed, model
|
|
667
705
|
};
|
|
668
|
-
|
|
706
|
+
|
|
669
707
|
if (kind === 'edit') {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
708
|
+
const hasImageSlot = /\{\{\s*image\s*\}\}/.test(raw);
|
|
709
|
+
if (!hasImageSlot && !(mapping && mapping.image)) {
|
|
710
|
+
throw new Error('这个自定义工作流里既没有 {{image}} 占位符,也没有可用的参考图映射,不能用于图生图;'
|
|
711
|
+
+ '请把参考图节点的 image 字段写成 {{image}},或在模型选项里解析并确认映射。');
|
|
673
712
|
}
|
|
674
713
|
const reference = input.images && input.images[0];
|
|
675
714
|
if (!reference || !reference.buffer) throw new Error('ComfyUI 编辑需要一张参考图');
|
|
676
715
|
values.image = await comfyUploadImage(base, provider, reference, signal);
|
|
677
|
-
} else if (hasImageSlot) {
|
|
678
|
-
values.image = '';
|
|
679
716
|
}
|
|
680
|
-
|
|
717
|
+
|
|
718
|
+
let out;
|
|
719
|
+
if (hasPlaceholder) out = applyWorkflowTemplate(graph, values);
|
|
720
|
+
else if (mapping) out = injectByMapping(graph, mapping, values).graph;
|
|
721
|
+
else throw new Error('这个自定义工作流没有注入映射,请先在模型选项里解析并确认。');
|
|
722
|
+
|
|
723
|
+
// 对话模型塞进来的可调参数:认得的写进去,认不得的记下来告诉它。
|
|
724
|
+
const declared = entry && Array.isArray(entry.params) ? entry.params : [];
|
|
725
|
+
const overrides = input && input.params && typeof input.params === 'object' ? input.params : null;
|
|
726
|
+
if (overrides) {
|
|
727
|
+
if (!declared.length) {
|
|
728
|
+
return { graph: out, note: '当前模型没有暴露任何工作流参数,已忽略:' + Object.keys(overrides).join('、') };
|
|
729
|
+
}
|
|
730
|
+
const tuned = applyWorkflowParams(out, declared, overrides);
|
|
731
|
+
const note = tuned.ignored.length
|
|
732
|
+
? '这些参数当前模型不支持或取值无效,已忽略:' + tuned.ignored.join('、')
|
|
733
|
+
: '';
|
|
734
|
+
return { graph: tuned.graph, note };
|
|
735
|
+
}
|
|
736
|
+
return { graph: out, note: '' };
|
|
681
737
|
}
|
|
682
738
|
|
|
683
739
|
const ADAPTERS = [
|
|
684
740
|
{
|
|
685
741
|
id: 'dall-e-3',
|
|
686
742
|
label: 'OpenAI DALL·E 3',
|
|
687
|
-
match: (provider, model) => /dall-?e-?3/i.test(model),
|
|
743
|
+
match: (provider, model) => /dall-?e-?3/i.test(model) && !MAJOR_HOSTS.test(hostOfBase(baseUrlOf(provider))),
|
|
688
744
|
endpoints: { generate: '/images/generations', edit: '/images/edits' },
|
|
689
745
|
transport: { generate: 'json', edit: 'multipart' },
|
|
690
746
|
send: ['model', 'prompt', 'size', 'quality', 'response_format', 'n'],
|
|
@@ -705,21 +761,25 @@ const ADAPTERS = [
|
|
|
705
761
|
{
|
|
706
762
|
id: 'gpt-image',
|
|
707
763
|
label: 'OpenAI GPT-Image',
|
|
708
|
-
match: (provider, model) => /gpt-?image/i.test(model),
|
|
764
|
+
match: (provider, model) => /gpt-?image/i.test(model) && !MAJOR_HOSTS.test(hostOfBase(baseUrlOf(provider))),
|
|
709
765
|
endpoints: { generate: '/images/generations', edit: '/images/edits' },
|
|
710
766
|
transport: { generate: 'json', edit: 'multipart' },
|
|
711
767
|
send: ['model', 'prompt', 'size', 'quality', 'n'],
|
|
712
|
-
|
|
768
|
+
// gpt-image 2.x 起支持任意 W×H:16 的倍数、比例 1:3–3:1、像素 655360–8294400。
|
|
769
|
+
size: { style: 'string', field: 'size', multiple: 16, minPixels: 655360, maxPixels: 8294400, default: '1024x1024', onUnsupported: 'nearest' },
|
|
713
770
|
quality: {
|
|
714
771
|
label: '质量', default: 'high', fallback: 'high',
|
|
715
|
-
allowed: ['low', 'medium', 'high', 'auto'],
|
|
716
|
-
options:
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
772
|
+
allowed: ['low', 'medium', 'high', 'xhigh', 'max', 'auto'],
|
|
773
|
+
options: (model) => {
|
|
774
|
+
const maxed = /2\.5-(sunburst|flare)/i.test(String(model || ''));
|
|
775
|
+
return [
|
|
776
|
+
{ value: 'off', label: 'Off' },
|
|
777
|
+
{ value: 'low', label: 'Low' },
|
|
778
|
+
{ value: 'medium', label: 'Medium' },
|
|
779
|
+
{ value: 'high', label: 'High' }
|
|
780
|
+
].concat(maxed ? [{ value: 'xhigh', label: 'XHigh' }, { value: 'max', label: 'Max' }] : [])
|
|
781
|
+
.concat([{ value: 'auto', label: 'Auto' }]);
|
|
782
|
+
}
|
|
723
783
|
},
|
|
724
784
|
maxN: 10,
|
|
725
785
|
editFields: ['image[]', 'image']
|
|
@@ -745,7 +805,9 @@ const ADAPTERS = [
|
|
|
745
805
|
.filter((item) => {
|
|
746
806
|
const methods = item.supportedGenerationMethods;
|
|
747
807
|
if (Array.isArray(methods) && !methods.includes('generateContent')) return false;
|
|
748
|
-
return /gemini/i.test(String(item.name || ''))
|
|
808
|
+
return /gemini/i.test(String(item.name || ''))
|
|
809
|
+
&& (/image/i.test(String(item.name || '')) || /nano-banana/i.test(String(item.name || '')))
|
|
810
|
+
&& !/imagen/i.test(String(item.name || ''));
|
|
749
811
|
})
|
|
750
812
|
.map((item) => {
|
|
751
813
|
const id = String(item.name || '').replace(/^models\//, '');
|
|
@@ -759,7 +821,13 @@ const ADAPTERS = [
|
|
|
759
821
|
const model = String(input.model || '').replace(/^models\//, '').trim();
|
|
760
822
|
if (!model) throw new Error('Gemini 模型 ID 不能为空');
|
|
761
823
|
const images = input.images || [];
|
|
762
|
-
|
|
824
|
+
const is25 = /gemini-2\.5-flash-image/i.test(model);
|
|
825
|
+
const isFlash31 = /gemini-3\.1-flash-image/i.test(model);
|
|
826
|
+
const isLite = /gemini-3\.1-flash-lite-image/i.test(model);
|
|
827
|
+
const referenceLimit = is25 ? 3 : 14;
|
|
828
|
+
if (images.length > referenceLimit) {
|
|
829
|
+
throw new Error('Gemini 一次最多 ' + referenceLimit + ' 张参考图(该模型上限)');
|
|
830
|
+
}
|
|
763
831
|
const parts = [];
|
|
764
832
|
for (const image of images) {
|
|
765
833
|
if (!image || !image.buffer) continue;
|
|
@@ -777,9 +845,13 @@ const ADAPTERS = [
|
|
|
777
845
|
const height = input.fitted && !input.fitted.omit ? input.fitted.height : 1024;
|
|
778
846
|
const generationConfig = {
|
|
779
847
|
responseModalities: ['TEXT', 'IMAGE'],
|
|
780
|
-
imageConfig: { aspectRatio: nearestAspect(width, height) }
|
|
848
|
+
imageConfig: { aspectRatio: nearestAspect(width, height, is25 ? ASPECT_CHOICES : ASPECT_CHOICES_14) }
|
|
781
849
|
};
|
|
782
|
-
if (
|
|
850
|
+
if (!is25) {
|
|
851
|
+
if (isLite) generationConfig.imageConfig.imageSize = '1K';
|
|
852
|
+
else if (isFlash31 && width <= 768 && height <= 768) generationConfig.imageConfig.imageSize = '512';
|
|
853
|
+
else generationConfig.imageConfig.imageSize = resolutionFor(width, height).toUpperCase();
|
|
854
|
+
}
|
|
783
855
|
const response = await request(baseUrlOf(provider) + '/models/' + encodeURIComponent(model) + ':generateContent', {
|
|
784
856
|
method: 'POST',
|
|
785
857
|
headers: keyedHeaders(provider, 'x-goog-api-key', false),
|
|
@@ -788,8 +860,11 @@ const ADAPTERS = [
|
|
|
788
860
|
});
|
|
789
861
|
const payload = await readJsonResponse(response, 48 * 1024 * 1024);
|
|
790
862
|
const partsOut = payload && payload.candidates && payload.candidates[0] && payload.candidates[0].content && payload.candidates[0].content.parts;
|
|
791
|
-
|
|
792
|
-
|
|
863
|
+
// thinking 模型会先返回 thought 中间草图,结果取最后一张非 thought 图。
|
|
864
|
+
const ordered = Array.isArray(partsOut) ? partsOut.slice().reverse() : [];
|
|
865
|
+
for (const part of ordered) {
|
|
866
|
+
if (!part || part.thought === true) continue;
|
|
867
|
+
const inline = part.inlineData || part.inline_data;
|
|
793
868
|
if (!inline || !inline.data) continue;
|
|
794
869
|
const decoded = base64ToImage(inline.data);
|
|
795
870
|
if (!decoded) continue;
|
|
@@ -843,24 +918,38 @@ const ADAPTERS = [
|
|
|
843
918
|
label: 'Recraft',
|
|
844
919
|
match: (provider) => /external\.api\.recraft\.ai/i.test(String((provider && provider.baseUrl) || '')),
|
|
845
920
|
local: false,
|
|
846
|
-
endpoints: { generate: '/images/generations', edit: '' },
|
|
847
|
-
transport: { generate: 'json', edit: '
|
|
921
|
+
endpoints: { generate: '/images/generations', edit: '/images/imageToImage' },
|
|
922
|
+
transport: { generate: 'json', edit: 'multipart' },
|
|
923
|
+
editFields: ['image'],
|
|
924
|
+
editExtras: { strength: 0.5 },
|
|
848
925
|
size: { style: 'string', field: 'size', allowed: ['1024x1024', '1365x1024', '1024x1365', '1536x1024', '1024x1536', '2048x2048'], default: '1024x1024', onUnsupported: 'nearest' },
|
|
849
926
|
maxN: 1,
|
|
850
927
|
async listModels() {
|
|
851
928
|
return ['recraftv4_1', 'recraftv4', 'recraftv3', 'recraftv2'];
|
|
852
929
|
},
|
|
853
930
|
async execute(kind, provider, input, signal) {
|
|
854
|
-
if (kind === 'edit') throw new Error('Recraft 原生编辑暂未支持;请使用生成或换支持编辑的模型。');
|
|
855
931
|
let prompt = String(input.prompt || '');
|
|
856
932
|
if (input.negativePrompt) prompt += '\n\nAvoid: ' + String(input.negativePrompt);
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
933
|
+
let response;
|
|
934
|
+
if (kind === 'edit') {
|
|
935
|
+
const form = new FormData();
|
|
936
|
+
form.append('prompt', prompt);
|
|
937
|
+
form.append('strength', '0.5');
|
|
938
|
+
for (const image of input.images || []) {
|
|
939
|
+
form.append('image', new Blob([image.buffer], { type: image.contentType }), image.filename);
|
|
940
|
+
}
|
|
941
|
+
response = await request(baseUrlOf(provider) + '/images/imageToImage', {
|
|
942
|
+
method: 'POST', headers: headersFor(provider, true, null, this), body: form, signal: signal
|
|
943
|
+
});
|
|
944
|
+
} else {
|
|
945
|
+
const body = {
|
|
946
|
+
model: input.model, prompt: prompt, n: 1, response_format: 'url'
|
|
947
|
+
};
|
|
948
|
+
if (input.fitted && !input.fitted.omit && input.fitted.size) body.size = input.fitted.size;
|
|
949
|
+
response = await request(baseUrlOf(provider) + '/images/generations', {
|
|
950
|
+
method: 'POST', headers: headersFor(provider, false, null, this), body: JSON.stringify(body), signal: signal
|
|
951
|
+
});
|
|
952
|
+
}
|
|
864
953
|
const payload = await readJsonResponse(response, 32 * 1024 * 1024);
|
|
865
954
|
const decoded = decodeImagePayload(payload, null);
|
|
866
955
|
if (decoded.bytes) return decoded;
|
|
@@ -873,7 +962,7 @@ const ADAPTERS = [
|
|
|
873
962
|
label: 'Ideogram',
|
|
874
963
|
match: (provider) => /(^|\.)api\.ideogram\.ai$/i.test(String((provider && provider.baseUrl) || '').replace(/^https?:\/\//, '').split('/')[0]),
|
|
875
964
|
local: false,
|
|
876
|
-
endpoints: { generate:
|
|
965
|
+
endpoints: { generate: (input) => ideogramPath(input), edit: '' },
|
|
877
966
|
transport: { generate: 'multipart', edit: 'json' },
|
|
878
967
|
size: { style: 'aspect', field: 'aspect_ratio', aspects: ['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3'], default: '1024x1024', onUnsupported: 'nearest' },
|
|
879
968
|
quality: {
|
|
@@ -889,7 +978,7 @@ const ADAPTERS = [
|
|
|
889
978
|
},
|
|
890
979
|
maxN: 1,
|
|
891
980
|
async listModels() {
|
|
892
|
-
return ['ideogram-3'];
|
|
981
|
+
return ['ideogram-3', 'ideogram-4'];
|
|
893
982
|
},
|
|
894
983
|
async execute(kind, provider, input, signal) {
|
|
895
984
|
if (kind === 'edit') throw new Error('Ideogram 原生编辑暂未支持;请使用生成或换支持编辑的模型。');
|
|
@@ -902,7 +991,7 @@ const ADAPTERS = [
|
|
|
902
991
|
if (speed) form.append('rendering_speed', speed);
|
|
903
992
|
form.append('aspect_ratio', nearestAspect(input.fitted && input.fitted.width, input.fitted && input.fitted.height));
|
|
904
993
|
form.append('num_images', '1');
|
|
905
|
-
const response = await request(baseUrlOf(provider) +
|
|
994
|
+
const response = await request(baseUrlOf(provider) + ideogramPath(input), {
|
|
906
995
|
method: 'POST',
|
|
907
996
|
headers: keyedHeaders(provider, 'Api-Key', true),
|
|
908
997
|
body: form,
|
|
@@ -932,10 +1021,12 @@ const ADAPTERS = [
|
|
|
932
1021
|
match: (provider, model) => /siliconflow/i.test(provider.baseUrl || ''),
|
|
933
1022
|
endpoints: { generate: '/images/generations', edit: '/images/generations' },
|
|
934
1023
|
transport: { generate: 'json', edit: 'json' },
|
|
935
|
-
send: ['model', 'prompt', 'negative_prompt', 'image_size', '
|
|
1024
|
+
send: ['model', 'prompt', 'negative_prompt', 'image_size', 'num_inference_steps', 'guidance_scale', 'seed'],
|
|
936
1025
|
size: { style: 'string', field: 'image_size', allowed: ['1024x1024', '768x1024', '1024x768', '512x512'], default: '1024x1024', onUnsupported: 'nearest' },
|
|
937
1026
|
maxN: 1,
|
|
938
|
-
editFields: ['image']
|
|
1027
|
+
editFields: ['image'],
|
|
1028
|
+
// Qwen-Image-Edit 系列不接受 image_size,传了会 400。
|
|
1029
|
+
editDrops: (input) => (/qwen-image-edit/i.test(String((input && input.model) || '')) ? ['image_size'] : [])
|
|
939
1030
|
},
|
|
940
1031
|
{
|
|
941
1032
|
id: 'volcengine-ark',
|
|
@@ -943,8 +1034,11 @@ const ADAPTERS = [
|
|
|
943
1034
|
match: (provider, model) => /volces\.com/i.test(provider.baseUrl || ''),
|
|
944
1035
|
endpoints: { generate: '/images/generations', edit: '/images/generations' },
|
|
945
1036
|
transport: { generate: 'json', edit: 'json' },
|
|
946
|
-
send: ['model', 'prompt', 'size', 'response_format', 'watermark', 'n'],
|
|
947
|
-
size: {
|
|
1037
|
+
send: ['model', 'prompt', 'size', 'response_format', 'watermark', 'n', 'image'],
|
|
1038
|
+
size: {
|
|
1039
|
+
style: 'string', field: 'size', default: '1024x1024', onUnsupported: 'nearest',
|
|
1040
|
+
presets: [{ value: '2K', pixels: 2048 * 2048 }, { value: '3K', pixels: 3072 * 3072 }, { value: '4K', pixels: 4096 * 4096 }]
|
|
1041
|
+
},
|
|
948
1042
|
responseFormat: 'url',
|
|
949
1043
|
watermark: false,
|
|
950
1044
|
maxN: 1,
|
|
@@ -963,6 +1057,7 @@ const ADAPTERS = [
|
|
|
963
1057
|
maxN: 1,
|
|
964
1058
|
editFields: ['image']
|
|
965
1059
|
},
|
|
1060
|
+
...CN_ADAPTERS,
|
|
966
1061
|
{
|
|
967
1062
|
// 异步入队型:提交拿 task_id → 轮询到 SUCCEEDED → 下载结果。
|
|
968
1063
|
// body 是嵌套结构,用 compose 把白名单字段折叠进去。
|
|
@@ -1073,10 +1168,11 @@ const ADAPTERS = [
|
|
|
1073
1168
|
|
|
1074
1169
|
const custom = comfyCustomWorkflow(provider, model);
|
|
1075
1170
|
if (custom) {
|
|
1076
|
-
const
|
|
1171
|
+
const built = await comfyCustomGraph(base, provider, {
|
|
1077
1172
|
kind, input, model, width, height, seed, raw: custom, signal
|
|
1078
1173
|
});
|
|
1079
|
-
|
|
1174
|
+
const result = await comfySubmitAndWait(base, provider, built.graph, signal);
|
|
1175
|
+
return built.note ? Object.assign({}, result, { note: built.note }) : result;
|
|
1080
1176
|
}
|
|
1081
1177
|
const diffusionModels = await comfyNodeOptions(base, provider, 'UNETLoader', 'unet_name', signal);
|
|
1082
1178
|
let workflow;
|
|
@@ -1174,6 +1270,8 @@ const ADAPTERS = [
|
|
|
1174
1270
|
return openAiCompatibleEntries(payload);
|
|
1175
1271
|
}
|
|
1176
1272
|
},
|
|
1273
|
+
...ASYNC_ADAPTERS,
|
|
1274
|
+
...OPENAI_ADAPTERS,
|
|
1177
1275
|
{
|
|
1178
1276
|
id: 'openai-images',
|
|
1179
1277
|
label: 'OpenAI Images 兼容',
|
|
@@ -1262,7 +1360,7 @@ export const PROVIDER_PRESETS = [
|
|
|
1262
1360
|
id: 'gemini', name: 'Google Gemini / Nano Banana',
|
|
1263
1361
|
baseUrl: 'https://generativelanguage.googleapis.com/v1beta', adapter: 'google-gemini',
|
|
1264
1362
|
website: 'https://aistudio.google.com/app/apikey',
|
|
1265
|
-
models: ['gemini-2.
|
|
1363
|
+
models: ['gemini-nano-banana-2.1', 'gemini-3.1-flash-image', 'gemini-3-pro-image', 'gemini-2.5-flash-image']
|
|
1266
1364
|
},
|
|
1267
1365
|
{ id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', adapter: '', website: 'https://platform.openai.com/api-keys', models: [] },
|
|
1268
1366
|
{
|
|
@@ -1307,10 +1405,57 @@ export const PROVIDER_PRESETS = [
|
|
|
1307
1405
|
website: 'https://novita.ai/settings/key-management',
|
|
1308
1406
|
models: ['flux-1-schnell']
|
|
1309
1407
|
},
|
|
1408
|
+
{
|
|
1409
|
+
id: 'openrouter', name: 'OpenRouter',
|
|
1410
|
+
baseUrl: 'https://openrouter.ai/api/v1', adapter: 'openrouter-images',
|
|
1411
|
+
website: 'https://openrouter.ai/settings/keys',
|
|
1412
|
+
models: ['google/gemini-3.1-flash-image', 'openai/gpt-image-2.5-flare', 'black-forest-labs/flux-2-pro']
|
|
1413
|
+
},
|
|
1414
|
+
{
|
|
1415
|
+
id: 'azure', name: 'Azure OpenAI',
|
|
1416
|
+
baseUrl: 'https://YOUR-RESOURCE.openai.azure.com/openai/v1', adapter: 'azure-openai',
|
|
1417
|
+
website: 'https://portal.azure.com/',
|
|
1418
|
+
models: []
|
|
1419
|
+
},
|
|
1420
|
+
{
|
|
1421
|
+
id: 'bfl', name: 'Black Forest Labs (FLUX)',
|
|
1422
|
+
baseUrl: 'https://api.bfl.ai/v1', adapter: 'bfl',
|
|
1423
|
+
website: 'https://dashboard.bfl.ai/',
|
|
1424
|
+
models: ['flux-2-pro', 'flux-2-max', 'flux-3-image', 'flux-kontext-pro']
|
|
1425
|
+
},
|
|
1426
|
+
{
|
|
1427
|
+
id: 'fal', name: 'fal.ai',
|
|
1428
|
+
baseUrl: 'https://queue.fal.run', adapter: 'fal',
|
|
1429
|
+
website: 'https://fal.ai/dashboard/keys',
|
|
1430
|
+
models: ['fal-ai/flux-2-pro', 'fal-ai/flux-pro/kontext']
|
|
1431
|
+
},
|
|
1432
|
+
{
|
|
1433
|
+
id: 'replicate', name: 'Replicate',
|
|
1434
|
+
baseUrl: 'https://api.replicate.com/v1', adapter: 'replicate',
|
|
1435
|
+
website: 'https://replicate.com/account/api-tokens',
|
|
1436
|
+
models: ['black-forest-labs/flux-2-pro']
|
|
1437
|
+
},
|
|
1310
1438
|
{ id: 'volcengine', name: '火山方舟', baseUrl: 'https://ark.cn-beijing.volces.com/api/v3', adapter: '', website: 'https://console.volcengine.com/ark', models: [] },
|
|
1311
|
-
{
|
|
1439
|
+
{
|
|
1440
|
+
id: 'volcengine-plan', name: '火山方舟 Agent Plan',
|
|
1441
|
+
baseUrl: 'https://ark.cn-beijing.volces.com/api/plan/v3', adapter: '',
|
|
1442
|
+
website: 'https://console.volcengine.com/ark',
|
|
1443
|
+
models: []
|
|
1444
|
+
},
|
|
1445
|
+
{
|
|
1446
|
+
id: 'dashscope', name: '阿里云百炼 · Qwen-Image',
|
|
1447
|
+
baseUrl: 'https://dashscope.aliyuncs.com/api/v1', adapter: 'dashscope-qwen-image',
|
|
1448
|
+
website: 'https://bailian.console.aliyun.com/',
|
|
1449
|
+
models: ['qwen-image-3.0-pro', 'qwen-image-3.0']
|
|
1450
|
+
},
|
|
1451
|
+
{
|
|
1452
|
+
id: 'dashscope-wanx', name: '阿里云百炼 · 通义万相',
|
|
1453
|
+
baseUrl: 'https://dashscope.aliyuncs.com/api/v1', adapter: 'dashscope-wanx',
|
|
1454
|
+
website: 'https://bailian.console.aliyun.com/',
|
|
1455
|
+
models: ['wan2.6-t2i', 'wanx2.1-t2i-turbo']
|
|
1456
|
+
},
|
|
1312
1457
|
{ id: 'siliconflow', name: '硅基流动', baseUrl: 'https://api.siliconflow.cn/v1', adapter: '', website: 'https://cloud.siliconflow.cn/account/ak', models: [] },
|
|
1313
|
-
{ id: 'bigmodel', name: '智谱 BigModel', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', adapter: '', website: 'https://bigmodel.cn/usercenter/apikeys', models: [] }
|
|
1458
|
+
{ id: 'bigmodel', name: '智谱 BigModel', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', adapter: 'zhipu', website: 'https://bigmodel.cn/usercenter/apikeys', models: [] }
|
|
1314
1459
|
];
|
|
1315
1460
|
|
|
1316
1461
|
export const LOCAL_PRESETS = [
|
|
@@ -1405,47 +1550,6 @@ export function describeAdapter(adapter) {
|
|
|
1405
1550
|
|
|
1406
1551
|
/* -------------------------------------------------------------- requests */
|
|
1407
1552
|
|
|
1408
|
-
function baseUrlOf(provider) {
|
|
1409
|
-
return String((provider && provider.baseUrl) || '').replace(/\/+$/, '');
|
|
1410
|
-
}
|
|
1411
|
-
|
|
1412
|
-
function headersFor(provider, multipart, extra) {
|
|
1413
|
-
const headers = Object.assign({}, extra || {});
|
|
1414
|
-
const key = String((provider && provider.key) || '').trim();
|
|
1415
|
-
if (key) headers.Authorization = 'Bearer ' + key;
|
|
1416
|
-
if (!multipart && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
|
1417
|
-
return headers;
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
function sleep(ms) {
|
|
1421
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1422
|
-
}
|
|
1423
|
-
|
|
1424
|
-
async function readJsonResponse(response, maxBytes = 10 * 1024 * 1024) {
|
|
1425
|
-
const buffer = await readResponseBytes(response, maxBytes);
|
|
1426
|
-
const text = buffer.toString('utf8');
|
|
1427
|
-
if (!response.ok) {
|
|
1428
|
-
let detail = '';
|
|
1429
|
-
try {
|
|
1430
|
-
const parsed = JSON.parse(text);
|
|
1431
|
-
detail = parsed && (parsed.error && (parsed.error.message || parsed.error) || parsed.message || parsed.detail) || '';
|
|
1432
|
-
if (typeof detail !== 'string') detail = JSON.stringify(detail);
|
|
1433
|
-
} catch (_error) {
|
|
1434
|
-
detail = text.slice(0, 300);
|
|
1435
|
-
}
|
|
1436
|
-
throw localizedError(
|
|
1437
|
-
new Error('本地生图服务返回 HTTP ' + response.status + (detail ? ':' + detail : '')),
|
|
1438
|
-
detail ? 'upstream.http' : 'upstream.httpNoDetail',
|
|
1439
|
-
{ status: response.status, detail: detail }
|
|
1440
|
-
);
|
|
1441
|
-
}
|
|
1442
|
-
try {
|
|
1443
|
-
return JSON.parse(text);
|
|
1444
|
-
} catch (_error) {
|
|
1445
|
-
throw localizedError(new Error('本地生图服务返回的不是 JSON'), 'upstream.invalidJson');
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
1553
|
/** A1111 img2img 需要原图尺寸;PNG/JPEG 足够覆盖常见参考图。 */
|
|
1450
1554
|
function imageDimensions(buffer) {
|
|
1451
1555
|
if (!buffer || buffer.length < 24) return null;
|
|
@@ -1502,8 +1606,9 @@ function composeBody(adapter, input, drops) {
|
|
|
1502
1606
|
return adapter.compose ? adapter.compose(fields) : fields;
|
|
1503
1607
|
}
|
|
1504
1608
|
|
|
1505
|
-
|
|
1506
|
-
|
|
1609
|
+
/** 端点既可以是固定字符串,也可以是按模型拼路径的函数(Ideogram、fal 这类)。 */
|
|
1610
|
+
function endpointOf(value, input) {
|
|
1611
|
+
return typeof value === 'function' ? value(input || {}) : value;
|
|
1507
1612
|
}
|
|
1508
1613
|
|
|
1509
1614
|
export function prepareGenerate(adapter, provider, input, drops) {
|
|
@@ -1511,13 +1616,17 @@ export function prepareGenerate(adapter, provider, input, drops) {
|
|
|
1511
1616
|
if (adapter.transport.generate === 'multipart') {
|
|
1512
1617
|
const form = new FormData();
|
|
1513
1618
|
for (const key of Object.keys(body)) form.append(key, String(body[key]));
|
|
1514
|
-
return { path: adapter.endpoints.generate, headers: headersFor(provider, true, adapter.headers), body: form };
|
|
1619
|
+
return { path: endpointOf(adapter.endpoints.generate, input), headers: headersFor(provider, true, adapter.headers, adapter), body: form };
|
|
1515
1620
|
}
|
|
1516
|
-
return jsonRequest(adapter, provider, adapter.endpoints.generate, body);
|
|
1621
|
+
return jsonRequest(adapter, provider, endpointOf(adapter.endpoints.generate, input), body);
|
|
1517
1622
|
}
|
|
1518
1623
|
|
|
1519
1624
|
export function prepareEdit(adapter, provider, input, drops, fieldName) {
|
|
1520
1625
|
const body = composeBody(adapter, input, drops);
|
|
1626
|
+
// 有些编辑端点不收尺寸(如硅基流动 Qwen-Image-Edit),由适配器逐个模型声明。
|
|
1627
|
+
if (typeof adapter.editDrops === 'function') {
|
|
1628
|
+
for (const key of adapter.editDrops(input) || []) delete body[key];
|
|
1629
|
+
}
|
|
1521
1630
|
if (adapter.transport.edit !== 'multipart') {
|
|
1522
1631
|
// 非 multipart 的编辑接口(如 SiliconFlow / 火山方舟)用 image 字段承载
|
|
1523
1632
|
// 参考图;统一编码成 data URL,单张发字符串,多张发数组。
|
|
@@ -1529,15 +1638,16 @@ export function prepareEdit(adapter, provider, input, drops, fieldName) {
|
|
|
1529
1638
|
.map((image) => 'data:' + image.contentType + ';base64,' + image.buffer.toString('base64'));
|
|
1530
1639
|
if (encoded.length > 0) body[field] = encoded.length === 1 ? encoded[0] : encoded;
|
|
1531
1640
|
}
|
|
1532
|
-
return jsonRequest(adapter, provider, adapter.endpoints.edit, body);
|
|
1641
|
+
return jsonRequest(adapter, provider, endpointOf(adapter.endpoints.edit, input), body);
|
|
1533
1642
|
}
|
|
1534
1643
|
const form = new FormData();
|
|
1535
1644
|
for (const key of Object.keys(body)) form.append(key, String(body[key]));
|
|
1645
|
+
for (const [key, value] of Object.entries(adapter.editExtras || {})) form.append(key, String(value));
|
|
1536
1646
|
const field = fieldName || (adapter.editFields && adapter.editFields[0]) || 'image';
|
|
1537
1647
|
for (const image of input.images || []) {
|
|
1538
1648
|
form.append(field, new Blob([image.buffer], { type: image.contentType }), image.filename);
|
|
1539
1649
|
}
|
|
1540
|
-
return { path: adapter.endpoints.edit, headers: headersFor(provider, true, adapter.headers), body: form };
|
|
1650
|
+
return { path: endpointOf(adapter.endpoints.edit, input), headers: headersFor(provider, true, adapter.headers, adapter), body: form };
|
|
1541
1651
|
}
|
|
1542
1652
|
|
|
1543
1653
|
/** 异步任务:先提交拿 task_id。 */
|
|
@@ -1545,6 +1655,21 @@ export function prepareAsync(adapter, provider, input, drops) {
|
|
|
1545
1655
|
return jsonRequest(adapter, provider, adapter.submit, composeBody(adapter, input, drops));
|
|
1546
1656
|
}
|
|
1547
1657
|
|
|
1658
|
+
/** 新式异步描述符:提交体与提交路径都由适配器自己决定;build 可以是异步的。 */
|
|
1659
|
+
export async function preparePhaseAsync(adapter, provider, input, signal) {
|
|
1660
|
+
const phase = adapter.async || {};
|
|
1661
|
+
const path = String(phase.submitPath(input) || '');
|
|
1662
|
+
const built = await phase.build(input, provider, signal);
|
|
1663
|
+
const body = built && built.body ? built.body : (built || {});
|
|
1664
|
+
const note = built && built.note ? String(built.note) : '';
|
|
1665
|
+
return {
|
|
1666
|
+
path: path,
|
|
1667
|
+
headers: headersFor(provider, false, adapter.headers, adapter),
|
|
1668
|
+
body: JSON.stringify(body),
|
|
1669
|
+
note: note
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1548
1673
|
export function pollUrlFor(adapter, provider, taskId) {
|
|
1549
1674
|
const template = String((adapter.poll && adapter.poll.path) || '/tasks/{taskId}');
|
|
1550
1675
|
return baseUrlOf(provider) + template.replace('{taskId}', encodeURIComponent(taskId));
|
|
@@ -1554,16 +1679,6 @@ export function pollHeaders(provider) {
|
|
|
1554
1679
|
return { Authorization: 'Bearer ' + String((provider && provider.key) || '') };
|
|
1555
1680
|
}
|
|
1556
1681
|
|
|
1557
|
-
function getPath(node, path) {
|
|
1558
|
-
if (!path) return node;
|
|
1559
|
-
let current = node;
|
|
1560
|
-
for (const key of String(path).split('.')) {
|
|
1561
|
-
if (current === null || current === undefined) return null;
|
|
1562
|
-
current = current[key];
|
|
1563
|
-
}
|
|
1564
|
-
return current === undefined ? null : current;
|
|
1565
|
-
}
|
|
1566
|
-
|
|
1567
1682
|
export function readTaskId(adapter, payload) {
|
|
1568
1683
|
const value = getPath(payload, (adapter.poll && adapter.poll.idPath) || 'output.task_id');
|
|
1569
1684
|
return value ? String(value) : null;
|
|
@@ -1589,204 +1704,6 @@ export function adapterBase(provider) {
|
|
|
1589
1704
|
return baseUrlOf(provider);
|
|
1590
1705
|
}
|
|
1591
1706
|
|
|
1592
|
-
/* -------------------------------------------------------------- responses */
|
|
1593
|
-
|
|
1594
|
-
export function sniffType(buffer) {
|
|
1595
|
-
if (!buffer || buffer.length < 12) return 'image/png';
|
|
1596
|
-
if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) return 'image/png';
|
|
1597
|
-
if (buffer[0] === 0xff && buffer[1] === 0xd8) return 'image/jpeg';
|
|
1598
|
-
if (buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP') return 'image/webp';
|
|
1599
|
-
if (buffer.slice(0, 3).toString('ascii') === 'GIF') return 'image/gif';
|
|
1600
|
-
return 'image/png';
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
export function looksLikeImage(buffer) {
|
|
1604
|
-
if (!buffer || buffer.length < 8) return false;
|
|
1605
|
-
const type = sniffType(buffer);
|
|
1606
|
-
if (type === 'image/png') return buffer[0] === 0x89 && buffer[1] === 0x50;
|
|
1607
|
-
if (type === 'image/jpeg') return buffer[0] === 0xff && buffer[1] === 0xd8;
|
|
1608
|
-
if (type === 'image/webp') return buffer.slice(0, 4).toString('ascii') === 'RIFF' && buffer.slice(8, 12).toString('ascii') === 'WEBP';
|
|
1609
|
-
return buffer.slice(0, 3).toString('ascii') === 'GIF';
|
|
1610
|
-
}
|
|
1611
|
-
|
|
1612
|
-
function base64ToImage(text) {
|
|
1613
|
-
const raw = String(text || '');
|
|
1614
|
-
if (!raw || raw.length < 64) return null;
|
|
1615
|
-
const dataUrl = /^data:image\/([a-z+]+);base64,(.+)$/i.exec(raw);
|
|
1616
|
-
const payload = dataUrl ? dataUrl[2] : raw;
|
|
1617
|
-
if (!/^[A-Za-z0-9+/=\r\n]+$/.test(payload)) return null;
|
|
1618
|
-
let buffer;
|
|
1619
|
-
try {
|
|
1620
|
-
buffer = Buffer.from(payload, 'base64');
|
|
1621
|
-
} catch (_error) {
|
|
1622
|
-
return null;
|
|
1623
|
-
}
|
|
1624
|
-
if (!looksLikeImage(buffer)) return null;
|
|
1625
|
-
return { bytes: buffer, contentType: dataUrl ? 'image/' + dataUrl[1].toLowerCase() : sniffType(buffer) };
|
|
1626
|
-
}
|
|
1627
|
-
|
|
1628
|
-
function collectStrings(node, out, depth) {
|
|
1629
|
-
if (!node || depth > 6 || out.length > 80) return;
|
|
1630
|
-
if (typeof node === 'string') {
|
|
1631
|
-
out.push(node);
|
|
1632
|
-
return;
|
|
1633
|
-
}
|
|
1634
|
-
if (Array.isArray(node)) {
|
|
1635
|
-
for (const item of node) collectStrings(item, out, depth + 1);
|
|
1636
|
-
return;
|
|
1637
|
-
}
|
|
1638
|
-
if (typeof node === 'object') {
|
|
1639
|
-
for (const key of Object.keys(node)) collectStrings(node[key], out, depth + 1);
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
|
|
1643
|
-
/**
|
|
1644
|
-
* 从任意形状的回应里找出图片:二进制 / b64 / data-url / 外链,全都认。
|
|
1645
|
-
*/
|
|
1646
|
-
export function decodeImagePayload(payload, binary) {
|
|
1647
|
-
if (binary && looksLikeImage(binary)) return { bytes: binary, contentType: sniffType(binary) };
|
|
1648
|
-
if (!payload) throw new Error('生图接口没有返回图片');
|
|
1649
|
-
|
|
1650
|
-
const strings = [];
|
|
1651
|
-
collectStrings(payload, strings, 0);
|
|
1652
|
-
|
|
1653
|
-
for (const text of strings) {
|
|
1654
|
-
const image = base64ToImage(text);
|
|
1655
|
-
if (image) return image;
|
|
1656
|
-
}
|
|
1657
|
-
for (const text of strings) {
|
|
1658
|
-
if (!/^https?:\/\//i.test(text)) continue;
|
|
1659
|
-
if (/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(text)) return { url: text };
|
|
1660
|
-
}
|
|
1661
|
-
for (const text of strings) {
|
|
1662
|
-
if (/^https?:\/\//i.test(text)) return { url: text };
|
|
1663
|
-
}
|
|
1664
|
-
throw new Error('生图接口返回格式不认识');
|
|
1665
|
-
}
|
|
1666
|
-
|
|
1667
|
-
/** 按上限读取响应体;有 Content-Length 时先拒绝明显超限的响应。 */
|
|
1668
|
-
export async function readResponseBytes(response, maxBytes) {
|
|
1669
|
-
const limit = Number(maxBytes) > 0 ? Number(maxBytes) : Infinity;
|
|
1670
|
-
const declared = Number(response.headers.get('content-length'));
|
|
1671
|
-
if (Number.isFinite(declared) && declared > limit) {
|
|
1672
|
-
try { await response.body?.cancel(); } catch (_error) { /* ignore */ }
|
|
1673
|
-
throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
|
|
1674
|
-
}
|
|
1675
|
-
const body = response.body;
|
|
1676
|
-
if (!body) {
|
|
1677
|
-
const buffer = Buffer.from(await response.arrayBuffer());
|
|
1678
|
-
if (buffer.length > limit) throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
|
|
1679
|
-
return buffer;
|
|
1680
|
-
}
|
|
1681
|
-
// Content-Length 可信时直接写进预分配 buffer,避免 chunks + Buffer.concat 的 2 倍峰值。
|
|
1682
|
-
if (Number.isFinite(declared) && declared > 0) {
|
|
1683
|
-
const out = Buffer.allocUnsafe(Math.floor(declared));
|
|
1684
|
-
let offset = 0;
|
|
1685
|
-
let overflow = null;
|
|
1686
|
-
for await (const chunk of body) {
|
|
1687
|
-
const buffer = Buffer.from(chunk);
|
|
1688
|
-
if (offset + buffer.length > limit) {
|
|
1689
|
-
try { await body.cancel(); } catch (_error) { /* ignore */ }
|
|
1690
|
-
throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
|
|
1691
|
-
}
|
|
1692
|
-
if (!overflow && offset + buffer.length <= out.length) {
|
|
1693
|
-
buffer.copy(out, offset);
|
|
1694
|
-
} else {
|
|
1695
|
-
if (!overflow) overflow = [out.subarray(0, offset)];
|
|
1696
|
-
overflow.push(buffer);
|
|
1697
|
-
}
|
|
1698
|
-
offset += buffer.length;
|
|
1699
|
-
}
|
|
1700
|
-
if (overflow) return Buffer.concat(overflow, offset);
|
|
1701
|
-
return offset === out.length ? out : Buffer.from(out.subarray(0, offset));
|
|
1702
|
-
}
|
|
1703
|
-
const chunks = [];
|
|
1704
|
-
let total = 0;
|
|
1705
|
-
for await (const chunk of body) {
|
|
1706
|
-
const buffer = Buffer.from(chunk);
|
|
1707
|
-
total += buffer.length;
|
|
1708
|
-
if (total > limit) {
|
|
1709
|
-
try { await body.cancel(); } catch (_error) { /* ignore */ }
|
|
1710
|
-
throw localizedError(new Error('响应体超过大小限制'), 'upstream.tooLarge');
|
|
1711
|
-
}
|
|
1712
|
-
chunks.push(buffer);
|
|
1713
|
-
}
|
|
1714
|
-
return Buffer.concat(chunks);
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
export const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
|
|
1718
|
-
|
|
1719
|
-
export async function fetchImageUrl(url, signal, maxBytes = MAX_IMAGE_BYTES) {
|
|
1720
|
-
const response = await request(url, { signal: signal });
|
|
1721
|
-
if (!response.ok) throw new Error('下载生成图失败:HTTP ' + response.status);
|
|
1722
|
-
const bytes = await readResponseBytes(response, maxBytes);
|
|
1723
|
-
if (!looksLikeImage(bytes)) throw new Error('下载生成图失败:返回内容不是有效图片');
|
|
1724
|
-
return { bytes: bytes, contentType: sniffType(bytes) };
|
|
1725
|
-
}
|
|
1726
|
-
|
|
1727
|
-
/* ----------------------------------------------------------------- errors */
|
|
1728
|
-
|
|
1729
|
-
export function extractMessage(text) {
|
|
1730
|
-
const raw = String(text || '').trim();
|
|
1731
|
-
if (!raw) return '';
|
|
1732
|
-
try {
|
|
1733
|
-
const parsed = JSON.parse(raw);
|
|
1734
|
-
if (parsed && typeof parsed === 'object') {
|
|
1735
|
-
if (parsed.error && typeof parsed.error === 'object' && parsed.error.message) return String(parsed.error.message);
|
|
1736
|
-
if (typeof parsed.error === 'string') return parsed.error;
|
|
1737
|
-
if (parsed.message) return String(parsed.message);
|
|
1738
|
-
if (parsed.msg) return String(parsed.msg);
|
|
1739
|
-
}
|
|
1740
|
-
} catch (_error) {
|
|
1741
|
-
/* 不是 JSON,原样返回 */
|
|
1742
|
-
}
|
|
1743
|
-
return raw;
|
|
1744
|
-
}
|
|
1745
|
-
|
|
1746
|
-
function detectDroppableField(message) {
|
|
1747
|
-
const token = "['\"]?([A-Za-z_][A-Za-z0-9_.-]*)['\"]?";
|
|
1748
|
-
const patterns = [
|
|
1749
|
-
new RegExp('unknown parameter:\\s*' + token, 'i'),
|
|
1750
|
-
new RegExp('unrecognized request argument supplied:\\s*' + token, 'i'),
|
|
1751
|
-
new RegExp('unknown (?:field|parameter|property)\\s*' + token, 'i'),
|
|
1752
|
-
new RegExp('(?:extra|unexpected|unsupported|not supported) (?:field|parameter|property)[^A-Za-z0-9_]*' + token, 'i')
|
|
1753
|
-
];
|
|
1754
|
-
for (const pattern of patterns) {
|
|
1755
|
-
const hit = pattern.exec(message);
|
|
1756
|
-
if (hit && hit[1]) return hit[1].trim();
|
|
1757
|
-
}
|
|
1758
|
-
return null;
|
|
1759
|
-
}
|
|
1760
|
-
|
|
1761
|
-
/** 从结构化错误里取 param 字段;不少兼容网关只在 error.param 里给字段名。 */
|
|
1762
|
-
function extractErrorParam(text) {
|
|
1763
|
-
try {
|
|
1764
|
-
const parsed = JSON.parse(String(text || ''));
|
|
1765
|
-
const param = (parsed && parsed.error && parsed.error.param) || (parsed && parsed.param);
|
|
1766
|
-
return typeof param === 'string' && /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(param) ? param.trim() : null;
|
|
1767
|
-
} catch (_error) {
|
|
1768
|
-
return null;
|
|
1769
|
-
}
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
/**
|
|
1773
|
-
* 把各家的错误归结成几类,调用方只按 kind 决策。
|
|
1774
|
-
*/
|
|
1775
|
-
export function classifyFailure(status, text) {
|
|
1776
|
-
const message = extractMessage(text) || ('HTTP ' + status);
|
|
1777
|
-
const drop = detectDroppableField(message) || extractErrorParam(text);
|
|
1778
|
-
if (drop) return { kind: 'param', drop: drop, message: message };
|
|
1779
|
-
if (/size/i.test(message) && /(invalid|unsupported|below|minimum|maximum|too small|too large|budget)/i.test(message)) {
|
|
1780
|
-
return { kind: 'size', message: message };
|
|
1781
|
-
}
|
|
1782
|
-
if (status === 401 || status === 403) return { kind: 'auth', message: message };
|
|
1783
|
-
if (status === 404) return { kind: 'endpoint', message: message };
|
|
1784
|
-
if (status === 413) return { kind: 'payload', message: message };
|
|
1785
|
-
if (status === 429) return { kind: 'rate', message: message, retryable: true };
|
|
1786
|
-
if (status >= 500) return { kind: 'upstream', message: message, retryable: true };
|
|
1787
|
-
return { kind: 'unknown', message: message };
|
|
1788
|
-
}
|
|
1789
|
-
|
|
1790
1707
|
/* ----------------------------------------------------------------- resize */
|
|
1791
1708
|
|
|
1792
1709
|
/**
|