dsh-sendcomfy 0.0.0-stage → 0.5.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.
@@ -0,0 +1,1572 @@
1
+ /**
2
+ * dsh-sendcomfy — ComfyUI 工作流解析 / UI→API 转换 / 参数推导
3
+ *
4
+ * 契约见 CONTRACT.md §4。本模块是纯 ESM、零第三方依赖的纯函数集合:
5
+ * parseWorkflowJson / uiToApiGraph / buildParamSpecs / applyParamOverrides
6
+ * / applyPrompts / mergeImport / summarizeGraph
7
+ *
8
+ * 关于 ComfyUI 真实格式的两个关键事实(以本机 0.44 导出的工作流核对过):
9
+ * 1) UI 导出里 `widgets_values` 是「小部件值数组」,顺序 = 节点类 INPUT_TYPES
10
+ * 里 required→optional 的小部件输入顺序;seed/noise_seed 后通常紧跟一个
11
+ * 'fixed'|'increment'|'decrement'|'randomize' 控制值(也占一个数组槽)。
12
+ * 被「转成输入」的小部件(inputs[].widget.name)在旧导出里仍占 widgets_values
13
+ * 的槽位,因此必须按名字/顺序对位读取,不能把 link 输入算进去。
14
+ * 2) object_info 的输入描述有两种形态:老式 combo 是 `[[选项...], {opts}]`,
15
+ * 新式(io.Combo)是 `["COMBO", {options:[...], image_upload:true, ...}]`。
16
+ * 两者都要支持。
17
+ */
18
+
19
+ const CONTROL_VALUES = new Set(['fixed', 'increment', 'decrement', 'randomize'])
20
+ const NOTE_TYPES = new Set(['Note', 'MarkdownNote', 'NoteNode'])
21
+ const REROUTE_TYPE = 'Reroute'
22
+ const PRIMITIVE_NODE_TYPE = 'PrimitiveNode'
23
+ const MAX_WARNINGS = 200
24
+
25
+ /** 输入名命中这些(且值是字符串)即视为提示词候选。 */
26
+ const PROMPT_INPUT_NAMES = new Set(['text', 'text_g', 'text_l', 'prompt'])
27
+
28
+ /** object_info 类型名 -> ParamSpec.type */
29
+ const WIDGET_KIND_BY_TYPE = {
30
+ INT: 'integer',
31
+ FLOAT: 'number',
32
+ STRING: 'string',
33
+ BOOLEAN: 'boolean',
34
+ COMBO: 'enum',
35
+ }
36
+
37
+ /**
38
+ * objectInfo 缺失时的内置小部件顺序表(只覆盖官方常用节点,尽力而为)。
39
+ * 每项: { name, control?: true(后面可能跟一个生成控制值), upload?: true(后面可能跟一个上传按钮值) }
40
+ */
41
+ const BUILTIN_WIDGET_SCHEMAS = {
42
+ KSampler: [
43
+ { name: 'seed', control: true },
44
+ { name: 'steps' },
45
+ { name: 'cfg' },
46
+ { name: 'sampler_name' },
47
+ { name: 'scheduler' },
48
+ { name: 'denoise' },
49
+ ],
50
+ KSamplerAdvanced: [
51
+ { name: 'add_noise' },
52
+ { name: 'noise_seed', control: true },
53
+ { name: 'steps' },
54
+ { name: 'cfg' },
55
+ { name: 'sampler_name' },
56
+ { name: 'scheduler' },
57
+ { name: 'start_at_step' },
58
+ { name: 'end_at_step' },
59
+ { name: 'return_with_leftover_noise' },
60
+ ],
61
+ CLIPTextEncode: [{ name: 'text' }],
62
+ CheckpointLoaderSimple: [{ name: 'ckpt_name' }],
63
+ EmptyLatentImage: [{ name: 'width' }, { name: 'height' }, { name: 'batch_size' }],
64
+ EmptySD3LatentImage: [{ name: 'width' }, { name: 'height' }, { name: 'batch_size' }],
65
+ VAEDecode: [],
66
+ VAEEncode: [],
67
+ SaveImage: [{ name: 'filename_prefix' }],
68
+ PreviewImage: [],
69
+ LoadImage: [{ name: 'image', upload: true }],
70
+ LoadImageMask: [{ name: 'image', upload: true }, { name: 'channel' }],
71
+ LoraLoader: [{ name: 'lora_name' }, { name: 'strength_model' }, { name: 'strength_clip' }],
72
+ LoraLoaderModelOnly: [{ name: 'lora_name' }, { name: 'strength_model' }],
73
+ UNETLoader: [{ name: 'unet_name' }, { name: 'weight_dtype' }],
74
+ CLIPLoader: [{ name: 'clip_name' }, { name: 'type' }, { name: 'device' }],
75
+ VAELoader: [{ name: 'vae_name' }],
76
+ CLIPSetLastLayer: [{ name: 'stop_at_clip_layer' }],
77
+ LatentUpscale: [{ name: 'upscale_method' }, { name: 'width' }, { name: 'height' }, { name: 'crop' }],
78
+ LatentUpscaleBy: [{ name: 'upscale_method' }, { name: 'scale_by' }],
79
+ ImageScale: [{ name: 'upscale_method' }, { name: 'width' }, { name: 'height' }, { name: 'crop' }],
80
+ ImageScaleBy: [{ name: 'upscale_method' }, { name: 'scale_by' }],
81
+ ControlNetLoader: [{ name: 'control_net_name' }],
82
+ UpscaleModelLoader: [{ name: 'model_name' }],
83
+ ModelSamplingAuraFlow: [{ name: 'shift' }],
84
+ // ComfyUI 0.4x 起的新版核心节点(io.ComfyNode,现代模板常用)
85
+ PrimitiveInt: [{ name: 'value', control: true }],
86
+ PrimitiveFloat: [{ name: 'value' }],
87
+ PrimitiveString: [{ name: 'value' }],
88
+ PrimitiveStringMultiline: [{ name: 'value' }],
89
+ PrimitiveBoolean: [{ name: 'value' }],
90
+ RandomNoise: [{ name: 'noise_seed', control: true }],
91
+ SamplerCustom: [{ name: 'add_noise' }, { name: 'noise_seed', control: true }, { name: 'cfg' }],
92
+ SamplerCustomAdvanced: [],
93
+ KSamplerSelect: [{ name: 'sampler_name' }],
94
+ BasicScheduler: [{ name: 'scheduler' }, { name: 'steps' }, { name: 'denoise' }],
95
+ SplitSigmas: [{ name: 'step' }],
96
+ SplitSigmasDenoise: [{ name: 'denoise' }],
97
+ CFGGuider: [{ name: 'cfg' }],
98
+ BasicGuider: [],
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // 小工具
103
+ // ---------------------------------------------------------------------------
104
+
105
+ function fail(message) {
106
+ const err = new Error(message)
107
+ err.code = 'EBAD_WORKFLOW'
108
+ return err
109
+ }
110
+
111
+ function isPlainObject(value) {
112
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
113
+ }
114
+
115
+ function isPrimitiveValue(value) {
116
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
117
+ }
118
+
119
+ /** API 格式里的链路值:[String(源节点id), 输出槽号] */
120
+ function isLinkValue(value) {
121
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'number'
122
+ }
123
+
124
+ /** ComfyUI 槽位类型可能是 'IMAGE' / 'IMAGE,MASK' / '*' 等,按集合比较兼容性。 */
125
+ function normalizeSlotType(type) {
126
+ if (typeof type !== 'string') return []
127
+ return type
128
+ .split(/[,|]/)
129
+ .map((part) => part.trim().toLowerCase())
130
+ .filter(Boolean)
131
+ }
132
+
133
+ function slotTypesCompatible(a, b) {
134
+ const left = normalizeSlotType(a)
135
+ const right = normalizeSlotType(b)
136
+ if (left.length === 0 || right.length === 0) return false
137
+ if (left.includes('*') || right.includes('*')) return true
138
+ return left.some((type) => right.includes(type))
139
+ }
140
+
141
+ function isSeedLikeName(name) {
142
+ return /(^|_)seed$/.test(name)
143
+ }
144
+
145
+ function cloneValue(value) {
146
+ try {
147
+ return structuredClone(value)
148
+ } catch {
149
+ try {
150
+ return JSON.parse(JSON.stringify(value))
151
+ } catch {
152
+ return value
153
+ }
154
+ }
155
+ }
156
+
157
+ function compareNodeIds(a, b) {
158
+ const sa = String(a)
159
+ const sb = String(b)
160
+ const na = Number(sa)
161
+ const nb = Number(sb)
162
+ const aNum = sa !== '' && Number.isFinite(na)
163
+ const bNum = sb !== '' && Number.isFinite(nb)
164
+ if (aNum && bNum) return na - nb
165
+ if (aNum) return -1
166
+ if (bNum) return 1
167
+ return sa < sb ? -1 : sa > sb ? 1 : 0
168
+ }
169
+
170
+ /** 有序节点 id 列表(数值序优先)。 */
171
+ function orderedNodeIds(graph) {
172
+ if (!isPlainObject(graph)) return []
173
+ return Object.keys(graph).sort(compareNodeIds)
174
+ }
175
+
176
+ /** 按插入顺序遍历「所有可迭代字符串」并附加未列出的键(兼容 input_order 缺项)。 */
177
+ function orderedNames(specs, listed) {
178
+ const own = Object.keys(specs)
179
+ if (!Array.isArray(listed)) return own
180
+ const seen = new Set()
181
+ const out = []
182
+ for (const name of listed) {
183
+ if (typeof name === 'string' && Object.prototype.hasOwnProperty.call(specs, name) && !seen.has(name)) {
184
+ out.push(name)
185
+ seen.add(name)
186
+ }
187
+ }
188
+ for (const name of own) if (!seen.has(name)) out.push(name)
189
+ return out
190
+ }
191
+
192
+ /** 收集 warnings:去重 + 上限。 */
193
+ function createWarningCollector() {
194
+ const warnings = []
195
+ const seen = new Set()
196
+ return {
197
+ warnings,
198
+ add(message) {
199
+ if (!message || seen.has(message)) return
200
+ if (warnings.length >= MAX_WARNINGS) {
201
+ const note = `警告过多,已省略后续 ${MAX_WARNINGS} 条之后的提示`
202
+ if (!seen.has(note)) {
203
+ seen.add(note)
204
+ warnings.push(note)
205
+ }
206
+ return
207
+ }
208
+ seen.add(message)
209
+ warnings.push(message)
210
+ },
211
+ }
212
+ }
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // object_info 解析
216
+ // ---------------------------------------------------------------------------
217
+
218
+ /**
219
+ * 解析 object_info 里单个输入声明。
220
+ * @returns null | { kind:'integer'|'number'|'string'|'boolean'|'enum'|'link',
221
+ * typeName:string, options?:unknown[], min?:number, max?:number,
222
+ * step?:number, multiline?:boolean, controlFlag?:boolean,
223
+ * upload?:boolean }
224
+ */
225
+ function parseInputSpec(spec) {
226
+ let type
227
+ let opts = {}
228
+ if (Array.isArray(spec)) {
229
+ type = spec[0]
230
+ if (spec.length > 1) {
231
+ if (isPlainObject(spec[1])) opts = spec[1]
232
+ else if (Array.isArray(spec[1])) opts = { options: spec[1] }
233
+ }
234
+ } else if (typeof spec === 'string') {
235
+ type = spec
236
+ } else {
237
+ return null
238
+ }
239
+
240
+ let kind
241
+ let options
242
+ if (Array.isArray(type)) {
243
+ kind = 'enum'
244
+ options = type
245
+ } else if (type === 'COMBO') {
246
+ kind = 'enum'
247
+ options = Array.isArray(opts.options) ? opts.options : Array.isArray(opts.values) ? opts.values : undefined
248
+ } else if (typeof type === 'string' && WIDGET_KIND_BY_TYPE[type]) {
249
+ kind = WIDGET_KIND_BY_TYPE[type]
250
+ } else {
251
+ kind = 'link'
252
+ }
253
+ if (opts.forceInput || opts.force_input) kind = 'link'
254
+
255
+ const numberOpt = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)
256
+
257
+ return {
258
+ kind,
259
+ typeName: typeof type === 'string' ? type : 'COMBO',
260
+ options,
261
+ min: numberOpt(opts.min),
262
+ max: numberOpt(opts.max),
263
+ step: numberOpt(opts.step),
264
+ multiline: opts.multiline === true,
265
+ controlFlag: opts.control_after_generate,
266
+ upload:
267
+ opts.image_upload === true || opts.video_upload === true || opts.audio_upload === true || opts.upload === true,
268
+ }
269
+ }
270
+
271
+ /** 从 object_info[class] 提取有序的小部件输入定义;无法识别返回 null。 */
272
+ function widgetDefsFromObjectInfo(nodeDef) {
273
+ if (!isPlainObject(nodeDef) || !isPlainObject(nodeDef.input)) return null
274
+ const input = nodeDef.input
275
+ const order = isPlainObject(nodeDef.input_order) ? nodeDef.input_order : {}
276
+ const defs = []
277
+ for (const group of ['required', 'optional']) {
278
+ const specs = input[group]
279
+ if (!isPlainObject(specs)) continue
280
+ for (const name of orderedNames(specs, order[group])) {
281
+ const spec = parseInputSpec(specs[name])
282
+ if (!spec || spec.kind === 'link') continue
283
+ const control =
284
+ spec.controlFlag === true || (spec.controlFlag === undefined && isSeedLikeName(name))
285
+ defs.push({
286
+ name,
287
+ control,
288
+ upload: spec.upload === true,
289
+ spec,
290
+ })
291
+ }
292
+ }
293
+ return defs
294
+ }
295
+
296
+ /** 取某个节点类的小部件顺序表(object_info 优先,其次内置,最后启发式)。 */
297
+ function widgetSchemaFor(nodeClass, objectInfo, warn) {
298
+ const nodeDef = isPlainObject(objectInfo) ? objectInfo[nodeClass] : undefined
299
+ const hasObjectInfo = isPlainObject(objectInfo) && Object.keys(objectInfo).length > 0
300
+ if (isPlainObject(nodeDef)) {
301
+ const defs = widgetDefsFromObjectInfo(nodeDef)
302
+ if (defs) return { defs, source: 'object_info' }
303
+ }
304
+ const builtin = BUILTIN_WIDGET_SCHEMAS[nodeClass]
305
+ if (builtin) {
306
+ if (isPlainObject(nodeDef)) {
307
+ warn(`object_info 中节点类型 ${nodeClass} 的输入描述不可用,改用内置 schema 转换小部件`)
308
+ } else if (hasObjectInfo) {
309
+ warn(`object_info 缺少节点类型 ${nodeClass},改用内置 schema 转换小部件`)
310
+ } else {
311
+ warn(`未提供 object_info:节点类型 ${nodeClass} 使用内置 schema 映射小部件(结果可能不完整)`)
312
+ }
313
+ return { defs: builtin, source: 'builtin' }
314
+ }
315
+ if (isPlainObject(nodeDef)) {
316
+ warn(`object_info 中节点类型 ${nodeClass} 的输入描述不可用,且没有内置 schema,只能启发式映射小部件`)
317
+ } else if (hasObjectInfo) {
318
+ warn(`object_info 缺少节点类型 ${nodeClass},且没有内置 schema,只能按 inputs[].widget.name 启发式映射小部件`)
319
+ } else {
320
+ warn(
321
+ `未提供 object_info:节点类型 ${nodeClass} 没有内置 schema,按 inputs[].widget.name 启发式映射小部件(结果可能不完整)`,
322
+ )
323
+ }
324
+ return { defs: null, source: 'none' }
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // parseWorkflowJson
329
+ // ---------------------------------------------------------------------------
330
+
331
+ function detectFormat(value) {
332
+ if (!isPlainObject(value)) return null
333
+ for (const item of Object.values(value)) {
334
+ if (isPlainObject(item) && typeof item.class_type === 'string') return 'api'
335
+ }
336
+ if (Array.isArray(value.nodes) && value.nodes.some((n) => isPlainObject(n) && typeof n.type === 'string')) {
337
+ return 'ui'
338
+ }
339
+ return null
340
+ }
341
+
342
+ function decodeWorkflowText(input) {
343
+ if (typeof input === 'string') return input
344
+ if (input instanceof Uint8Array) return new TextDecoder('utf-8').decode(input)
345
+ return null
346
+ }
347
+
348
+ /**
349
+ * 解析工作流 JSON(字符串或已解析对象)。
350
+ * @returns {{format:'ui'|'api', raw:object}}
351
+ * @throws Error code='EBAD_WORKFLOW'
352
+ */
353
+ export function parseWorkflowJson(textOrObject) {
354
+ let value = textOrObject
355
+ const text = decodeWorkflowText(textOrObject)
356
+ if (text !== null) {
357
+ if (!text.trim()) throw fail('工作流内容为空')
358
+ try {
359
+ value = JSON.parse(text)
360
+ } catch (err) {
361
+ throw fail(`工作流不是合法 JSON:${err && err.message ? err.message : String(err)}`)
362
+ }
363
+ }
364
+ if (!isPlainObject(value)) {
365
+ throw fail('无法识别工作流格式:期望 JSON 对象(ComfyUI UI 导出或 API 格式)')
366
+ }
367
+
368
+ let format = detectFormat(value)
369
+ let raw = value
370
+ if (!format) {
371
+ // ComfyUI 新版/服务器保存的包装:{ workflow: UI 图 } 或 { prompt: API 图 }
372
+ for (const key of ['workflow', 'prompt']) {
373
+ const inner = value[key]
374
+ const innerFormat = detectFormat(inner)
375
+ if (innerFormat) {
376
+ format = innerFormat
377
+ raw = inner
378
+ break
379
+ }
380
+ }
381
+ }
382
+ if (!format || !raw) {
383
+ throw fail('无法识别工作流格式:既没有 UI 格式的 nodes/type,也没有 API 格式的 class_type')
384
+ }
385
+ return { format, raw }
386
+ }
387
+
388
+ // ---------------------------------------------------------------------------
389
+ // UI -> API 转换
390
+ // ---------------------------------------------------------------------------
391
+
392
+ function pickUiGraph(input) {
393
+ if (!isPlainObject(input)) return null
394
+ if (Array.isArray(input.nodes)) return input
395
+ for (const key of ['workflow', 'graph']) {
396
+ if (isPlainObject(input[key]) && Array.isArray(input[key].nodes)) return input[key]
397
+ }
398
+ return null
399
+ }
400
+
401
+ /** 兼容 links 的数组形态 [id, src, srcSlot, dst, dstSlot, type] 与对象形态。 */
402
+ function normalizeLinkEntry(entry) {
403
+ if (Array.isArray(entry)) {
404
+ if (entry.length < 5) return null
405
+ const [id, srcNode, srcSlot, dstNode, dstSlot, typeName] = entry
406
+ if (id == null || srcNode == null) return null
407
+ return {
408
+ id: String(id),
409
+ srcNode: String(srcNode),
410
+ srcSlot: Number(srcSlot) || 0,
411
+ dstNode: dstNode == null ? '' : String(dstNode),
412
+ dstSlot: Number(dstSlot) || 0,
413
+ typeName: typeof typeName === 'string' ? typeName : undefined,
414
+ }
415
+ }
416
+ if (isPlainObject(entry)) {
417
+ const id = entry.id ?? entry.linkId
418
+ const srcNode = entry.origin_id ?? entry.originId ?? entry.srcNode ?? entry.source
419
+ const srcSlot = entry.origin_slot ?? entry.originSlot ?? entry.srcSlot
420
+ if (id == null || srcNode == null) return null
421
+ return {
422
+ id: String(id),
423
+ srcNode: String(srcNode),
424
+ srcSlot: Number(srcSlot) || 0,
425
+ dstNode: entry.target_id == null ? '' : String(entry.target_id ?? entry.targetId ?? entry.dstNode ?? entry.target),
426
+ dstSlot: Number(entry.target_slot ?? entry.targetSlot ?? entry.dstSlot) || 0,
427
+ typeName: entry.type,
428
+ }
429
+ }
430
+ return null
431
+ }
432
+
433
+ /**
434
+ * 把 ComfyUI「UI 格式」工作流(nodes/links/widgets_values)转换成 /prompt 需要的 API 格式。
435
+ *
436
+ * 处理规则(见 CONTRACT.md §4):
437
+ * - Reroute 在连线上透明穿透(保持真实源的输出槽号)
438
+ * - PrimitiveNode 的 widgets_values[0] 作为字面量
439
+ * - Note/MarkdownNote/mode=2(静音) 跳过;mode=4(bypass) 按输入类型透传
440
+ * - 链路值 -> [String(源节点id), 源输出槽];字面量 -> 值本身
441
+ * - 转成输入的小部件(inputs[].widget.name)改由 link 提供值
442
+ * - 其余 widgets_values 按 object_info 的小部件输入顺序映射;seed 后跟生成控制值时跳过
443
+ * - objectInfo 缺失时用内置 schema / inputs[].widget.name 尽力映射并写 warnings
444
+ *
445
+ * @param {object} ui UI 格式工作流
446
+ * @param {object} [objectInfo] /object_info 结果(可缺省)
447
+ * @returns {{apiGraph:Record<string,{class_type:string,inputs:Record<string,unknown>,_meta?:{title?:string}}>, warnings:string[]}}
448
+ */
449
+ /** 新版 ComfyUI 子图的虚拟输入/输出节点 id。 */
450
+ const SUBGRAPH_INPUT_ID = -10
451
+ const SUBGRAPH_OUTPUT_ID = -20
452
+
453
+ /** 收集 definitions.subgraphs(id → 定义)。 */
454
+ function collectSubgraphDefinitions(graph) {
455
+ const definitions = new Map()
456
+ const raw = isPlainObject(graph) && isPlainObject(graph.definitions) && Array.isArray(graph.definitions.subgraphs)
457
+ ? graph.definitions.subgraphs
458
+ : []
459
+ for (const def of raw) {
460
+ if (!isPlainObject(def) || def.id == null) continue
461
+ definitions.set(String(def.id), def)
462
+ }
463
+ return definitions
464
+ }
465
+
466
+ function instanceWidgetValues(instance) {
467
+ const raw = instance && instance.widgets_values
468
+ if (Array.isArray(raw)) return raw
469
+ if (isPlainObject(raw)) return Object.values(raw)
470
+ return []
471
+ }
472
+
473
+ /** 取子图实例上「提升输入」的默认值(实例输入没有外链时使用)。 */
474
+ function promotedInputDefault(instance, def, slotIndex) {
475
+ const slots = def && Array.isArray(def.inputs) ? def.inputs : []
476
+ const slot = slots[slotIndex]
477
+ if (!slot) return { found: false }
478
+ const values = instanceWidgetValues(instance)
479
+ const proxy = isPlainObject(instance && instance.properties) && Array.isArray(instance.properties.proxyWidgets)
480
+ ? instance.properties.proxyWidgets
481
+ : null
482
+ if (proxy) {
483
+ const serializable = proxy.filter((entry) => Array.isArray(entry) && !String(entry[1] ?? '').startsWith('$$'))
484
+ const index = serializable.findIndex((entry) => String(entry[0]) === '-1' && String(entry[1]) === String(slot.name))
485
+ if (index >= 0 && index < values.length) return { found: true, value: values[index] }
486
+ }
487
+ // 优先用实例 inputs 上的 widget 元数据对齐(ComfyUI 只给可小部件化的提升输入带 widget)
488
+ const instanceInputs = instance && Array.isArray(instance.inputs) ? instance.inputs : []
489
+ if (instanceInputs.length > 0) {
490
+ let widgetIndex = -1
491
+ for (let i = 0; i <= slotIndex && i < instanceInputs.length; i += 1) {
492
+ if (instanceInputs[i] && instanceInputs[i].widget) widgetIndex += 1
493
+ }
494
+ if (widgetIndex >= 0 && widgetIndex < values.length) return { found: true, value: values[widgetIndex] }
495
+ }
496
+ // 再退一步:按「可小部件化的提升输入」类型启发式兜底(跳过纯连接型槽位)
497
+ const NON_WIDGET_TYPES = new Set([
498
+ 'MODEL', 'CLIP', 'VAE', 'CONDITIONING', 'LATENT', 'IMAGE', 'MASK', 'GUIDER', 'SAMPLER',
499
+ 'SIGMAS', 'NOISE', 'AUDIO', 'VIDEO', 'CONTROL_NET', 'UPSCALE_MODEL',
500
+ ])
501
+ let widgetIndex = -1
502
+ for (let i = 0; i <= slotIndex; i += 1) {
503
+ const item = slots[i]
504
+ if (!item) continue
505
+ if (NON_WIDGET_TYPES.has(String(item.type))) continue
506
+ widgetIndex += 1
507
+ }
508
+ if (widgetIndex >= 0 && widgetIndex < values.length) return { found: true, value: values[widgetIndex] }
509
+ return { found: false }
510
+ }
511
+
512
+ /**
513
+ * 展开新版 ComfyUI 子图(definitions.subgraphs):
514
+ * - 每个子图实例替换成定义内部的真实节点,节点 id 用 `实例路径:内部id`(与 ComfyUI 执行 id 一致);
515
+ * - 子图输入 -10 / 输出 -20 视为虚拟端口,跨边界连线解析成直连;
516
+ * - 未连接外链的提升输入用实例 widgets_values 的默认值(合成 PrimitiveNode 字面量);
517
+ * - bypass 的子图实例按「同类型输入透传」处理;
518
+ * - 支持嵌套子图(带环检测)。
519
+ * 返回 { nodes, links, instanceCount }。
520
+ */
521
+ function expandSubgraphs(graph, definitions, warn) {
522
+ function scopeOf(nodes, links, path, parent, instance, def, chain) {
523
+ const nodesById = new Map()
524
+ for (const node of nodes || []) {
525
+ if (node && node.id != null) nodesById.set(String(node.id), node)
526
+ }
527
+ const linksById = new Map()
528
+ for (const raw of links || []) {
529
+ const link = normalizeLinkEntry(raw)
530
+ if (link) linksById.set(link.id, link)
531
+ }
532
+ return { nodes: nodes || [], linksById, nodesById, path, parent, instance, def, chain: chain || [] }
533
+ }
534
+
535
+ const flatNodes = []
536
+ const flatLinks = []
537
+ let linkSeq = 0
538
+ let literalSeq = 0
539
+ let instanceCount = 0
540
+ const resolving = new Set()
541
+
542
+ function flatId(scope, nodeId) {
543
+ return [...scope.path, String(nodeId)].join(':')
544
+ }
545
+
546
+ function makeFlatLink(originId, originSlot, targetId, targetSlot, type) {
547
+ linkSeq += 1
548
+ const id = `sg-link-${linkSeq}`
549
+ flatLinks.push({
550
+ id,
551
+ origin_id: String(originId),
552
+ origin_slot: Number(originSlot) || 0,
553
+ target_id: String(targetId),
554
+ target_slot: Number(targetSlot) || 0,
555
+ type,
556
+ })
557
+ return id
558
+ }
559
+
560
+ function addLiteralNode(value) {
561
+ literalSeq += 1
562
+ const id = `sg-literal-${literalSeq}`
563
+ flatNodes.push({ id, type: 'PrimitiveNode', mode: 0, inputs: [], outputs: [], widgets_values: [value] })
564
+ return id
565
+ }
566
+
567
+ function isInstance(node) {
568
+ return Boolean(node && definitions.has(String(node.type)))
569
+ }
570
+
571
+ function missingSubgraphDefinition(node) {
572
+ return Boolean(node && definitions.size > 0 && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-/i.test(String(node.type)))
573
+ }
574
+
575
+ function resolveLink(scope, linkId, consumerType) {
576
+ const link = scope.linksById.get(String(linkId))
577
+ if (!link) return { kind: 'missing', reason: `连线 ${linkId} 在子图内部不存在` }
578
+ return resolveOrigin(scope, link.srcNode, link.srcSlot, consumerType)
579
+ }
580
+
581
+ function resolveOrigin(scope, originId, originSlot, consumerType) {
582
+ const rawId = String(originId)
583
+ if (rawId === String(SUBGRAPH_INPUT_ID)) {
584
+ if (!scope.parent) return { kind: 'missing', reason: '子图输入端口 -10 出现在根图上' }
585
+ const instance = scope.instance
586
+ const input = instance && Array.isArray(instance.inputs) ? instance.inputs[originSlot] : null
587
+ if (!input) return { kind: 'missing', reason: `子图输入槽 ${originSlot} 不存在` }
588
+ if (input.link != null) return resolveLink(scope.parent, input.link, consumerType)
589
+ const promoted = promotedInputDefault(scope.instance, scope.def, originSlot)
590
+ if (promoted.found) return { kind: 'literal', value: promoted.value }
591
+ return { kind: 'missing', reason: `子图输入「${input.name || originSlot}」没有连接,也没有默认值` }
592
+ }
593
+ const node = scope.nodesById.get(rawId)
594
+ if (!node) return { kind: 'missing', reason: `连线指向子图内不存在的节点 #${rawId}` }
595
+ if (isInstance(node)) {
596
+ if (node.mode === 2) return { kind: 'missing', reason: `子图节点 #${node.id} 已静音` }
597
+ if (node.mode === 4) return bypassInstance(scope, node, originSlot, consumerType)
598
+ return resolveSubgraphOutput(scope, node, originSlot, consumerType)
599
+ }
600
+ return { kind: 'link', nodeId: flatId(scope, node.id), slot: Number(originSlot) || 0 }
601
+ }
602
+
603
+ function resolveSubgraphOutput(scope, instanceNode, outSlot, consumerType) {
604
+ const def = definitions.get(String(instanceNode.type))
605
+ if (!def) return { kind: 'missing', reason: `缺少子图定义:${instanceNode.type}` }
606
+ const key = `${scope.path.join(':')}>${instanceNode.id}:${outSlot}`
607
+ if (resolving.has(key)) return { kind: 'missing', reason: `子图输出解析出现环(#${instanceNode.id} slot ${outSlot})` }
608
+ resolving.add(key)
609
+ try {
610
+ const links = Array.isArray(def.links) ? def.links : []
611
+ const outputId = def.outputNode && def.outputNode.id != null ? String(def.outputNode.id) : String(SUBGRAPH_OUTPUT_ID)
612
+ const inner = links
613
+ .map(normalizeLinkEntry)
614
+ .find((link) => link && String(link.dstNode) === outputId && link.dstSlot === Number(outSlot))
615
+ if (!inner) return { kind: 'missing', reason: `子图「${def.name || instanceNode.type}」的输出 ${outSlot} 没有内部连线` }
616
+ const innerScope = scopeOf(def.nodes, def.links, [...scope.path, String(instanceNode.id)], scope, instanceNode, def, scope.chain)
617
+ return resolveOrigin(innerScope, inner.srcNode, inner.srcSlot, consumerType)
618
+ } finally {
619
+ resolving.delete(key)
620
+ }
621
+ }
622
+
623
+ function bypassInstance(scope, instanceNode, outSlot, consumerType) {
624
+ const def = definitions.get(String(instanceNode.type))
625
+ const outputs = Array.isArray(instanceNode.outputs) ? instanceNode.outputs : []
626
+ const output = outputs[outSlot]
627
+ const outputType = output && typeof output.type === 'string' ? output.type : undefined
628
+ const inputs = Array.isArray(instanceNode.inputs) ? instanceNode.inputs : []
629
+ const candidates = inputs
630
+ .map((input, index) => ({ input, index }))
631
+ .filter((item) => item.input && item.input.link != null)
632
+ const pickByType = (type) => {
633
+ const found = candidates.find((item) => slotTypesCompatible(item.input.type, type))
634
+ return found
635
+ }
636
+ let picked = null
637
+ if (consumerType) picked = pickByType(consumerType)
638
+ if (!picked && outputType) picked = pickByType(outputType)
639
+ if (!picked) return { kind: 'missing', reason: `bypass 的子图节点 #${instanceNode.id} 找不到同类型输入可透传` }
640
+ return resolveLink(scope.parent, picked.input.link, consumerType)
641
+ }
642
+
643
+ function emitScope(scope) {
644
+ for (const node of scope.nodes) {
645
+ if (!node || node.id == null) continue
646
+ if (isInstance(node)) continue
647
+ if (missingSubgraphDefinition(node)) {
648
+ warn(`节点 #${node.id} 看起来是子图实例(${node.type}),但工作流里缺少它的子图定义,已跳过`)
649
+ continue
650
+ }
651
+ const id = flatId(scope, node.id)
652
+ const silentInputs = node.mode === 2 || node.mode === 4
653
+ const inputs = Array.isArray(node.inputs) ? node.inputs.map((input) => ({ ...input })) : []
654
+ const outputs = Array.isArray(node.outputs) ? node.outputs.map((output) => ({ ...output })) : []
655
+ flatNodes.push({ ...node, id, inputs, outputs })
656
+ for (let slot = 0; slot < inputs.length; slot += 1) {
657
+ const input = inputs[slot]
658
+ if (!input || input.link == null) continue
659
+ const resolved = resolveLink(scope, input.link, input.type)
660
+ if (!resolved || resolved.kind === 'missing') {
661
+ if (!silentInputs && resolved && resolved.reason) {
662
+ warn(`节点 #${node.id} (${node.type}) 的输入 "${input.name}" 展开子图后无法解析:${resolved.reason}`)
663
+ }
664
+ input.link = null
665
+ continue
666
+ }
667
+ if (resolved.kind === 'literal') {
668
+ const literalId = addLiteralNode(resolved.value)
669
+ input.link = makeFlatLink(literalId, 0, id, slot, input.type)
670
+ } else {
671
+ input.link = makeFlatLink(resolved.nodeId, resolved.slot, id, slot, input.type)
672
+ }
673
+ }
674
+ }
675
+ // 递归展开这一层里的子图实例
676
+ for (const node of scope.nodes) {
677
+ if (!node || !isInstance(node)) continue
678
+ instanceCount += 1
679
+ const def = definitions.get(String(node.type))
680
+ if (!def) {
681
+ warn(`子图实例 #${node.id} 缺少定义(${node.type}),已跳过`)
682
+ continue
683
+ }
684
+ if (node.mode === 2 || node.mode === 4) {
685
+ warn(`子图实例 #${node.id} 处于${node.mode === 2 ? '静音' : 'bypass'}模式,已按其输入透传(不展开内部节点)`)
686
+ continue
687
+ }
688
+ if (scope.chain.includes(String(node.type))) {
689
+ warn(`子图 #${node.id}(${def.name || node.type})出现循环引用,已跳过`)
690
+ continue
691
+ }
692
+ const innerScope = scopeOf(
693
+ def.nodes,
694
+ def.links,
695
+ [...scope.path, String(node.id)],
696
+ scope,
697
+ node,
698
+ def,
699
+ [...scope.chain, String(node.type)],
700
+ )
701
+ emitScope(innerScope)
702
+ }
703
+ }
704
+
705
+ const rootScope = scopeOf(graph.nodes, graph.links, [], null, null, null, [])
706
+ emitScope(rootScope)
707
+ return { nodes: flatNodes, links: flatLinks, instanceCount }
708
+ }
709
+
710
+ export function uiToApiGraph(ui, objectInfo) {
711
+ const graph = pickUiGraph(ui)
712
+ if (!graph) throw fail('不是 ComfyUI UI 格式工作流:缺少 nodes 数组')
713
+
714
+ const collector = createWarningCollector()
715
+ const warn = (message) => collector.add(message)
716
+
717
+ const definitions = collectSubgraphDefinitions(graph)
718
+ let rawNodes = Array.isArray(graph.nodes) ? graph.nodes : []
719
+ let rawLinks = Array.isArray(graph.links) ? graph.links : []
720
+ if (definitions.size > 0) {
721
+ const expanded = expandSubgraphs(graph, definitions, warn)
722
+ rawNodes = expanded.nodes
723
+ rawLinks = expanded.links
724
+ if (expanded.instanceCount > 0) {
725
+ warn(`工作流里有 ${expanded.instanceCount} 个子图实例,已展开为普通节点(id 形如「实例路径:内部id」)`)
726
+ }
727
+ }
728
+
729
+ const nodes = rawNodes.filter((node) => node != null)
730
+ const nodeMap = new Map()
731
+ for (const node of nodes) {
732
+ if (node.id == null) continue
733
+ const key = String(node.id)
734
+ if (nodeMap.has(key)) warn(`节点 id 重复:#${key},后出现的定义覆盖前者`)
735
+ nodeMap.set(key, node)
736
+ }
737
+
738
+ const linkMap = new Map()
739
+ if (Array.isArray(rawLinks)) {
740
+ for (const rawLink of rawLinks) {
741
+ const link = normalizeLinkEntry(rawLink)
742
+ if (!link) continue
743
+ linkMap.set(link.id, link)
744
+ }
745
+ }
746
+
747
+
748
+ // ---- 连线解析(递归处理 Reroute / PrimitiveNode / bypass) -----------------
749
+ const resolving = new Set()
750
+
751
+ function primitiveLiteral(node) {
752
+ const values = node.widgets_values
753
+ let value
754
+ if (Array.isArray(values)) value = values[0]
755
+ else if (isPlainObject(values)) value = values.value ?? Object.values(values)[0]
756
+ if (value === undefined) {
757
+ warn(`PrimitiveNode #${node.id} 没有可用的字面量值,已忽略其连线`)
758
+ return null
759
+ }
760
+ return { kind: 'literal', value }
761
+ }
762
+
763
+ /**
764
+ * 处理 bypass(mode=4)节点的输出透传(ComfyUI 语义:给输出找同类型的输入链路,把下游接到它上游)。
765
+ * - 优先按下游消费者的类型匹配(兼容 'IMAGE,MASK' 宽类型与 '*' 通配);
766
+ * - 其次按输出槽自身类型匹配;多个同类型输入时优先名字与输出槽一致的;
767
+ * - 信息不足且只有一条输入链路时兜底透传;
768
+ * - 找不到可透传输入 → 输出视为「无输出」,下游该输入被忽略(ComfyUI 同样会判缺失)。
769
+ */
770
+ function bypassOutput(node, outSlot, consumerType) {
771
+ const inputs = Array.isArray(node.inputs) ? node.inputs.filter((input) => input && input.link != null) : []
772
+ if (!inputs.length) {
773
+ return {
774
+ kind: 'missing',
775
+ reason: `节点 #${node.id} (${node.type}) 是 bypass 的源节点(没有输入),输出 ${outSlot} 没有数据`,
776
+ }
777
+ }
778
+ const output = Array.isArray(node.outputs) ? node.outputs[outSlot] : undefined
779
+ const outputType = output && typeof output.type === 'string' ? output.type : undefined
780
+ const outputName = output && typeof output.name === 'string' ? output.name : ''
781
+
782
+ const pickByType = (type) => {
783
+ const candidates = inputs.filter((input) => slotTypesCompatible(input.type, type))
784
+ if (candidates.length <= 1) return candidates[0]
785
+ return candidates.find((input) => outputName && String(input.name || '').toLowerCase() === outputName.toLowerCase()) || candidates[0]
786
+ }
787
+
788
+ let picked = null
789
+ if (consumerType) picked = pickByType(consumerType)
790
+ if (!picked && outputType) picked = pickByType(outputType)
791
+ if (!picked && !consumerType && !outputType && inputs.length === 1) picked = inputs[0]
792
+ if (!picked) {
793
+ return {
794
+ kind: 'missing',
795
+ reason: `bypass 节点 #${node.id} (${node.type}) 的输出 ${outSlot}`
796
+ + `${outputType ? ` (${outputType})` : ''} 找不到同类型输入可透传`,
797
+ }
798
+ }
799
+ return resolveLink(picked.link, consumerType)
800
+ }
801
+
802
+ function resolveFromSource(srcNodeId, srcSlot, expectedType) {
803
+ const source = nodeMap.get(String(srcNodeId))
804
+ if (!source) {
805
+ warn(`连线指向不存在的节点 #${srcNodeId},已忽略`)
806
+ return null
807
+ }
808
+ const type = source.type
809
+ if (typeof type !== 'string') {
810
+ warn(`节点 #${source.id} 缺少 type,无法解析连线`)
811
+ return null
812
+ }
813
+ if (type === REROUTE_TYPE) {
814
+ const upstream = Array.isArray(source.inputs) ? source.inputs.find((input) => input && input.link != null) : null
815
+ if (!upstream) {
816
+ warn(`Reroute #${source.id} 没有上游连线,已忽略`)
817
+ return null
818
+ }
819
+ return resolveLink(upstream.link, expectedType)
820
+ }
821
+ if (type === PRIMITIVE_NODE_TYPE) return primitiveLiteral(source)
822
+ if (NOTE_TYPES.has(type)) {
823
+ warn(`连线源节点 #${source.id} 是 ${type}(不产生数据),已忽略`)
824
+ return null
825
+ }
826
+ if (source.mode === 2) {
827
+ warn(`节点 #${source.id} (${type}) 已静音 (mode=2),其下游连线无法解析`)
828
+ return null
829
+ }
830
+ if (source.mode === 4) return bypassOutput(source, srcSlot, expectedType)
831
+ return { kind: 'link', nodeId: String(source.id), slot: Number.isFinite(srcSlot) ? srcSlot : 0 }
832
+ }
833
+
834
+ function resolveLink(linkId, expectedType) {
835
+ const key = String(linkId)
836
+ if (resolving.has(key)) {
837
+ warn(`检测到环形连线 (link ${key}),已忽略`)
838
+ return null
839
+ }
840
+ const link = linkMap.get(key)
841
+ if (!link) {
842
+ warn(`连线 ${key} 不存在,已忽略`)
843
+ return null
844
+ }
845
+ resolving.add(key)
846
+ try {
847
+ return resolveFromSource(link.srcNode, link.srcSlot, expectedType)
848
+ } finally {
849
+ resolving.delete(key)
850
+ }
851
+ }
852
+
853
+ /** 某个节点类的某输入是否 required(没有 object_info 时保守当作必填)。 */
854
+ function inputIsRequired(nodeType, inputName) {
855
+ if (!isPlainObject(objectInfo)) return true
856
+ const def = objectInfo[nodeType]
857
+ if (!isPlainObject(def) || !isPlainObject(def.input)) return true
858
+ if (isPlainObject(def.input.required) && Object.prototype.hasOwnProperty.call(def.input.required, inputName)) return true
859
+ if (isPlainObject(def.input.optional) && Object.prototype.hasOwnProperty.call(def.input.optional, inputName)) return false
860
+ return true
861
+ }
862
+
863
+ // ---- 小部件值映射 ---------------------------------------------------------
864
+ function widgetNamesFromInputs(node) {
865
+ const names = []
866
+ if (Array.isArray(node.inputs)) {
867
+ for (const input of node.inputs) {
868
+ if (input && isPlainObject(input.widget) && typeof input.widget.name === 'string') {
869
+ names.push(input.widget.name)
870
+ }
871
+ }
872
+ }
873
+ return names
874
+ }
875
+
876
+ function mapWidgetValues(node, schema) {
877
+ const nodeLabel = `节点 #${node.id} (${node.type})`
878
+ const values = new Map()
879
+ const named = isPlainObject(node.widgets_values_named)
880
+ ? node.widgets_values_named
881
+ : isPlainObject(node.widgets_values)
882
+ ? node.widgets_values
883
+ : null
884
+
885
+ // 新导出格式:widgets_values_named 直接按名字对位,不会错位。
886
+ if (named) {
887
+ if (schema.defs) {
888
+ for (const def of schema.defs) {
889
+ if (Object.prototype.hasOwnProperty.call(named, def.name) && named[def.name] != null) {
890
+ values.set(def.name, named[def.name])
891
+ }
892
+ }
893
+ } else {
894
+ // 没有 schema:只取能从 inputs[].widget.name 确认名字的那些值
895
+ const names = widgetNamesFromInputs(node).filter((name) =>
896
+ Object.prototype.hasOwnProperty.call(named, name),
897
+ )
898
+ if (!names.length) warn(`${nodeLabel}:缺少小部件定义,已忽略 widgets_values_named`)
899
+ for (const name of names) {
900
+ if (named[name] != null) values.set(name, named[name])
901
+ }
902
+ }
903
+ return values
904
+ }
905
+
906
+ const positional = Array.isArray(node.widgets_values) ? node.widgets_values : null
907
+ if (!positional) return values
908
+
909
+ if (schema.defs) {
910
+ const expected = schema.defs.reduce(
911
+ (total, def) => total + 1 + (def.control ? 1 : 0) + (def.upload ? 1 : 0),
912
+ 0,
913
+ )
914
+ if (positional.length !== expected) {
915
+ if (schema.source === 'object_info') {
916
+ warn(
917
+ `${nodeLabel}:widgets_values 数量 ${positional.length} 与 object_info 预期 ${expected} 不一致,参数可能错位`,
918
+ )
919
+ } else if (schema.source === 'builtin') {
920
+ warn(`${nodeLabel}:widgets_values 数量 ${positional.length} 与内置 schema 预期 ${expected} 不一致`)
921
+ }
922
+ }
923
+ let position = 0
924
+ for (let index = 0; index < schema.defs.length; index += 1) {
925
+ const def = schema.defs[index]
926
+ if (position >= positional.length) break
927
+ const value = positional[position]
928
+ position += 1
929
+ // seed 后面可能跟一个生成控制值(fixed/increment/decrement/randomize)
930
+ if (def.control && position < positional.length) {
931
+ const next = positional[position]
932
+ if (typeof next === 'string' && CONTROL_VALUES.has(next)) position += 1
933
+ }
934
+ // 上传按钮等 UI 专用小部件会多占一个值;只在“确实有多余值”时占用
935
+ if (def.upload) {
936
+ const remainingExpected = schema.defs
937
+ .slice(index + 1)
938
+ .reduce((total, rest) => total + 1 + (rest.control ? 1 : 0) + (rest.upload ? 1 : 0), 0)
939
+ const surplus = positional.length - position - remainingExpected
940
+ if (surplus > 0) position += 1
941
+ }
942
+ if (value !== undefined && value !== null) values.set(def.name, value)
943
+ }
944
+ return values
945
+ }
946
+
947
+ // 没有 object_info 也没有内置 schema:按 inputs[].widget.name 的顺序尽力对位。
948
+ const widgetNames = widgetNamesFromInputs(node)
949
+ if (!widgetNames.length) {
950
+ warn(`${nodeLabel}:缺少 object_info 且无法从 inputs 推断小部件名称,已跳过其小部件值`)
951
+ return values
952
+ }
953
+ if (positional.length !== widgetNames.length) {
954
+ warn(
955
+ `${nodeLabel}:按 inputs[].widget.name 顺序启发式映射 ${Math.min(
956
+ positional.length,
957
+ widgetNames.length,
958
+ )} 个小部件值,可能与真实顺序不一致`,
959
+ )
960
+ }
961
+ const count = Math.min(positional.length, widgetNames.length)
962
+ for (let index = 0; index < count; index += 1) {
963
+ const value = positional[index]
964
+ if (value !== undefined && value !== null) values.set(widgetNames[index], value)
965
+ }
966
+ return values
967
+ }
968
+
969
+ // ---- 主循环 ---------------------------------------------------------------
970
+ const apiGraph = {}
971
+ let bypassedCount = 0
972
+ for (const node of nodes) {
973
+ if (node.id == null) {
974
+ warn('跳过缺少 id 的节点')
975
+ continue
976
+ }
977
+ const type = node.type
978
+ if (typeof type !== 'string' || !type) {
979
+ warn(`节点 #${node.id} 缺少 type,已跳过`)
980
+ continue
981
+ }
982
+ if (type === REROUTE_TYPE || type === PRIMITIVE_NODE_TYPE || NOTE_TYPES.has(type)) continue
983
+ if (node.mode === 2) {
984
+ warn(`节点 #${node.id} (${type}) 已静音 (mode=2),已跳过`)
985
+ continue
986
+ }
987
+ if (node.mode === 4) {
988
+ bypassedCount += 1
989
+ continue
990
+ }
991
+
992
+ const nodeId = String(node.id)
993
+ if (apiGraph[nodeId]) {
994
+ warn(`节点 #${nodeId} 重复,后者覆盖前者`)
995
+ }
996
+
997
+ const inputs = {}
998
+ // 1) 链路输入(含被“转成输入”的小部件,此时 link 优先于 widgets_values)
999
+ if (Array.isArray(node.inputs)) {
1000
+ for (const input of node.inputs) {
1001
+ if (!input || typeof input.name !== 'string' || !input.name) continue
1002
+ if (input.link == null) continue
1003
+ const resolved = resolveLink(input.link, input.type)
1004
+ if (!resolved) continue
1005
+ if (resolved.kind === 'missing') {
1006
+ if (inputIsRequired(type, input.name)) {
1007
+ warn(`输入 "${input.name}" 依赖的链路没有数据:${resolved.reason}(ComfyUI 运行时可能报缺少输入)`)
1008
+ }
1009
+ continue
1010
+ }
1011
+ if (resolved.kind === 'literal') inputs[input.name] = resolved.value
1012
+ else inputs[input.name] = [resolved.nodeId, resolved.slot]
1013
+ }
1014
+ }
1015
+
1016
+ // 2) 小部件值
1017
+ const schema = widgetSchemaFor(type, objectInfo, warn)
1018
+ const widgetValues = mapWidgetValues(node, schema)
1019
+ for (const [name, value] of widgetValues) {
1020
+ if (Object.prototype.hasOwnProperty.call(inputs, name)) continue
1021
+ inputs[name] = value
1022
+ }
1023
+
1024
+ const apiNode = { class_type: type, inputs }
1025
+ if (typeof node.title === 'string' && node.title) apiNode._meta = { title: node.title }
1026
+ apiGraph[nodeId] = apiNode
1027
+ }
1028
+
1029
+ if (bypassedCount > 0) {
1030
+ warn(`工作流里有 ${bypassedCount} 个 bypass 节点,已按同类型输入自动透传(不写入 API 图)`)
1031
+ }
1032
+
1033
+ if (Object.keys(apiGraph).length === 0) {
1034
+ throw fail('工作流中没有可执行节点(全是 Note/Reroute/Primitive、子图实例或被静音/bypass 的节点)')
1035
+ }
1036
+ return { apiGraph, warnings: collector.warnings }
1037
+ }
1038
+
1039
+ // ---------------------------------------------------------------------------
1040
+ // buildParamSpecs
1041
+ // ---------------------------------------------------------------------------
1042
+
1043
+ /** 收集 objectInfo 里某个节点类的「输入名 -> 解析后的 spec」。 */
1044
+ function inputSpecMapForClass(objectInfo, nodeClass) {
1045
+ const map = new Map()
1046
+ const nodeDef = isPlainObject(objectInfo) ? objectInfo[nodeClass] : undefined
1047
+ if (!isPlainObject(nodeDef) || !isPlainObject(nodeDef.input)) return map
1048
+ for (const group of ['required', 'optional']) {
1049
+ const specs = nodeDef.input[group]
1050
+ if (!isPlainObject(specs)) continue
1051
+ for (const [name, rawSpec] of Object.entries(specs)) {
1052
+ const spec = parseInputSpec(rawSpec)
1053
+ if (spec) map.set(name, spec)
1054
+ }
1055
+ }
1056
+ return map
1057
+ }
1058
+
1059
+ function describeParamType(value, spec) {
1060
+ let type
1061
+ let options
1062
+ if (spec && spec.kind !== 'link') {
1063
+ if (spec.kind === 'enum') {
1064
+ type = 'enum'
1065
+ if (Array.isArray(spec.options) && spec.options.length) {
1066
+ options = spec.options.filter(isPrimitiveValue).map((option) => String(option))
1067
+ }
1068
+ } else {
1069
+ type = spec.kind
1070
+ }
1071
+ }
1072
+ if (!type || (type === 'enum' && !options)) {
1073
+ // objectInfo 缺失 / 枚举没有选项时按 JS 值推断
1074
+ if (typeof value === 'boolean') type = 'boolean'
1075
+ else if (typeof value === 'number') type = Number.isInteger(value) ? 'integer' : 'number'
1076
+ else if (typeof value === 'string') type = 'string'
1077
+ else return null
1078
+ options = undefined
1079
+ }
1080
+ return { type, options }
1081
+ }
1082
+
1083
+ function isPromptCandidate(inputName, value) {
1084
+ return typeof value === 'string' && PROMPT_INPUT_NAMES.has(inputName)
1085
+ }
1086
+
1087
+ function classifyPromptTitle(title) {
1088
+ const text = String(title || '').toLowerCase()
1089
+ if (/negative|负/.test(text)) return 'negative'
1090
+ if (/positive|正/.test(text)) return 'positive'
1091
+ return null
1092
+ }
1093
+
1094
+ /**
1095
+ * 按拓扑补充提示词归类:沿着其它节点的 `positive`/`negative` 输入反向追溯,
1096
+ * 把链路尽头的文本编码节点分别归到正/负。
1097
+ * ComfyUI 官方默认模板的两个 CLIPTextEncode 常常没有 title,标题规则会漏掉负面提示词,
1098
+ * 而 KSampler.positive/negative 的连线是最可靠的语义来源(此处只用于「标题未给出」的节点)。
1099
+ * @returns {Map<string,'positive'|'negative'>} nodeId -> category
1100
+ */
1101
+ function inferPromptCategoriesFromTopology(apiGraph, candidateNodeIds) {
1102
+ const categories = new Map()
1103
+ const candidateSet = new Set(candidateNodeIds)
1104
+ const visited = new Set()
1105
+ if (!candidateSet.size) return categories
1106
+
1107
+ const trace = (nodeId, category, depth) => {
1108
+ const key = `${category}|${nodeId}`
1109
+ if (depth > 16 || visited.has(key)) return
1110
+ visited.add(key)
1111
+ const node = apiGraph[nodeId]
1112
+ if (!isPlainObject(node)) return
1113
+ if (candidateSet.has(nodeId)) {
1114
+ if (!categories.has(nodeId)) categories.set(nodeId, category)
1115
+ return
1116
+ }
1117
+ const inputs = isPlainObject(node.inputs) ? node.inputs : {}
1118
+ for (const value of Object.values(inputs)) {
1119
+ if (isLinkValue(value)) trace(String(value[0]), category, depth + 1)
1120
+ }
1121
+ }
1122
+
1123
+ for (const node of Object.values(apiGraph)) {
1124
+ if (!isPlainObject(node) || !isPlainObject(node.inputs)) continue
1125
+ for (const [inputName, value] of Object.entries(node.inputs)) {
1126
+ if (!isLinkValue(value)) continue
1127
+ const lower = inputName.toLowerCase()
1128
+ if (lower !== 'positive' && lower !== 'negative') continue
1129
+ trace(String(value[0]), lower, 0)
1130
+ }
1131
+ }
1132
+ return categories
1133
+ }
1134
+
1135
+ /**
1136
+ * 从 API 图推导可调参数(ParamSpec[])与提示词注入目标。
1137
+ * @returns {{params:object[], promptTargets:{positive:string[],negative:string[]}}}
1138
+ */
1139
+ /**
1140
+ * 补充「提示词经过连线转接」的情况:例如子图展开后的 CLIPTextEncode.text 来自
1141
+ * 一个 PrimitiveStringMultiline 节点(value 是一个字符串参数),此时 text 输入没有
1142
+ * 对应参数,需要把上游字符串参数登记为正/负提示词目标。
1143
+ * 沿 guider/sampler 的 positive/negative 输入反向追到能提供字符串参数的节点。
1144
+ */
1145
+ function augmentLinkedPromptTargets(apiGraph, params, promptTargets) {
1146
+ if (!isPlainObject(apiGraph) || !Array.isArray(params)) return
1147
+ const paramsByNode = new Map()
1148
+ for (const param of params) {
1149
+ if (!param || param.type !== 'string') continue
1150
+ const list = paramsByNode.get(String(param.nodeId)) || []
1151
+ list.push(param)
1152
+ paramsByNode.set(String(param.nodeId), list)
1153
+ }
1154
+ const stringParamFor = (nodeId) => {
1155
+ const list = paramsByNode.get(String(nodeId)) || []
1156
+ return list.find((param) => /value|text|prompt|string|positive|negative/i.test(param.inputName)) || list[0]
1157
+ }
1158
+
1159
+ const additions = []
1160
+ for (const node of Object.values(apiGraph)) {
1161
+ if (!isPlainObject(node) || !isPlainObject(node.inputs)) continue
1162
+ for (const [name, value] of Object.entries(node.inputs)) {
1163
+ if (!isLinkValue(value)) continue
1164
+ const category = /positive|正向/.test(name)
1165
+ ? 'positive'
1166
+ : (/negative|负向/.test(name) ? 'negative' : null)
1167
+ if (!category) continue
1168
+ let cursor = String(value[0])
1169
+ const seen = new Set()
1170
+ for (let depth = 0; depth < 8 && cursor; depth += 1) {
1171
+ if (seen.has(cursor)) break
1172
+ seen.add(cursor)
1173
+ const param = stringParamFor(cursor)
1174
+ if (param) {
1175
+ additions.push({ category, path: param.path })
1176
+ break
1177
+ }
1178
+ const upstream = isPlainObject(apiGraph[cursor]) && isPlainObject(apiGraph[cursor].inputs)
1179
+ ? apiGraph[cursor].inputs
1180
+ : {}
1181
+ // 优先沿着「文本类」输入往上游走(text/prompt/value…),避免误跟 clip/model 这类连线
1182
+ const linkEntries = Object.entries(upstream).filter(([, item]) => isLinkValue(item))
1183
+ if (linkEntries.length === 0) break
1184
+ const preferred = linkEntries.find(([name]) => /text|prompt|string|value/i.test(name))
1185
+ const chosen = preferred || linkEntries[0]
1186
+ cursor = String(chosen[1][0])
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ for (const item of additions) {
1192
+ // 已经有明确归类(例如节点标题写了 Positive/Negative)的目标不再按连线改判
1193
+ const already = promptTargets.positive.includes(item.path) || promptTargets.negative.includes(item.path)
1194
+ if (already) continue
1195
+ const list = promptTargets[item.category]
1196
+ if (Array.isArray(list) && !list.includes(item.path)) list.push(item.path)
1197
+ const param = params.find((entry) => entry.path === item.path)
1198
+ if (param) param.isPrompt = true
1199
+ }
1200
+ }
1201
+
1202
+ export function buildParamSpecs(apiGraph, objectInfo) {
1203
+ const graph = isPlainObject(apiGraph) ? apiGraph : {}
1204
+ const entries = []
1205
+ const specMapCache = new Map()
1206
+
1207
+ for (const nodeId of orderedNodeIds(graph)) {
1208
+ const node = graph[nodeId]
1209
+ if (!isPlainObject(node) || typeof node.class_type !== 'string') continue
1210
+ const nodeClass = node.class_type
1211
+ const inputs = isPlainObject(node.inputs) ? node.inputs : {}
1212
+ if (!specMapCache.has(nodeClass)) specMapCache.set(nodeClass, inputSpecMapForClass(objectInfo, nodeClass))
1213
+ const specMap = specMapCache.get(nodeClass)
1214
+ const nodeTitle =
1215
+ isPlainObject(node._meta) && typeof node._meta.title === 'string' && node._meta.title
1216
+ ? node._meta.title
1217
+ : undefined
1218
+
1219
+ let inputIndex = 0
1220
+ for (const [inputName, value] of Object.entries(inputs)) {
1221
+ const index = inputIndex++
1222
+ if (isLinkValue(value)) continue
1223
+ if (!isPrimitiveValue(value)) continue // 数组/对象/空值不是可调参数
1224
+ const spec = specMap.get(inputName) || null
1225
+ const described = describeParamType(value, spec)
1226
+ if (!described) continue
1227
+ entries.push({
1228
+ nodeId,
1229
+ inputName,
1230
+ nodeClass,
1231
+ nodeTitle,
1232
+ index,
1233
+ value,
1234
+ spec,
1235
+ type: described.type,
1236
+ options: described.options,
1237
+ candidate: isPromptCandidate(inputName, value),
1238
+ category: null,
1239
+ })
1240
+ }
1241
+ }
1242
+
1243
+ // 提示词正负归类:标题 -> 图拓扑(KSampler.positive/negative 等连线反查)-> 兜底。
1244
+ const candidates = entries.filter((entry) => entry.candidate)
1245
+ for (const entry of candidates) {
1246
+ entry.category = classifyPromptTitle(entry.nodeTitle)
1247
+ }
1248
+ const topologyCategories = inferPromptCategoriesFromTopology(
1249
+ graph,
1250
+ [...new Set(candidates.map((entry) => entry.nodeId))],
1251
+ )
1252
+ for (const entry of candidates) {
1253
+ if (!entry.category && topologyCategories.has(entry.nodeId)) {
1254
+ entry.category = topologyCategories.get(entry.nodeId)
1255
+ }
1256
+ }
1257
+ // 兜底(契约 §4):没有显式 positive 时,第一个非 negative 的候选当 positive,其余不归类。
1258
+ if (!candidates.some((entry) => entry.category === 'positive')) {
1259
+ const first = candidates.find((entry) => entry.category !== 'negative')
1260
+ if (first) first.category = 'positive'
1261
+ }
1262
+
1263
+ const rank = (entry) => (entry.category === 'positive' ? 0 : entry.category === 'negative' ? 1 : 2)
1264
+ const sorted = entries.slice().sort((a, b) => {
1265
+ const byRank = rank(a) - rank(b)
1266
+ if (byRank !== 0) return byRank
1267
+ const byNode = compareNodeIds(a.nodeId, b.nodeId)
1268
+ if (byNode !== 0) return byNode
1269
+ return a.index - b.index
1270
+ })
1271
+
1272
+ const params = []
1273
+ const promptTargets = { positive: [], negative: [] }
1274
+ for (const entry of sorted) {
1275
+ const multiline =
1276
+ (entry.spec && entry.spec.kind === 'string' && entry.spec.multiline) ||
1277
+ (typeof entry.value === 'string' && (entry.value.includes('\n') || entry.value.length > 120))
1278
+ const param = {
1279
+ path: `${entry.nodeId}.${entry.inputName}`,
1280
+ nodeId: entry.nodeId,
1281
+ inputName: entry.inputName,
1282
+ nodeClass: entry.nodeClass,
1283
+ type: entry.type,
1284
+ value: entry.value,
1285
+ }
1286
+ if (entry.nodeTitle) param.nodeTitle = entry.nodeTitle
1287
+ if (entry.type === 'enum' && entry.options) param.options = entry.options
1288
+ if (entry.spec) {
1289
+ if (entry.spec.min !== undefined) param.min = entry.spec.min
1290
+ if (entry.spec.max !== undefined) param.max = entry.spec.max
1291
+ if (entry.spec.step !== undefined) param.step = entry.spec.step
1292
+ }
1293
+ if (multiline) param.multiline = true
1294
+ if (entry.category) {
1295
+ param.isPrompt = true
1296
+ promptTargets[entry.category].push(param.path)
1297
+ }
1298
+ params.push(param)
1299
+ }
1300
+ augmentLinkedPromptTargets(apiGraph, params, promptTargets)
1301
+ return { params, promptTargets }
1302
+ }
1303
+
1304
+ // ---------------------------------------------------------------------------
1305
+ // applyParamOverrides
1306
+ // ---------------------------------------------------------------------------
1307
+
1308
+ function inferTypeFromValue(value) {
1309
+ if (typeof value === 'boolean') return 'boolean'
1310
+ if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'number'
1311
+ if (typeof value === 'string') return 'string'
1312
+ return null
1313
+ }
1314
+
1315
+ function convertOverrideValue(rawValue, type, options, path, warnings) {
1316
+ const numeric = (value) => {
1317
+ if (typeof value === 'number' && Number.isFinite(value)) return value
1318
+ if (typeof value === 'string' && value.trim() !== '') {
1319
+ const parsed = Number(value)
1320
+ if (Number.isFinite(parsed)) return parsed
1321
+ }
1322
+ return undefined
1323
+ }
1324
+
1325
+ if (type === 'integer' || type === 'number') {
1326
+ const parsed = numeric(rawValue)
1327
+ if (parsed === undefined) {
1328
+ warnings.push(`参数 ${path} 需要${type === 'integer' ? '整数' : '数字'},收到:${JSON.stringify(rawValue)}`)
1329
+ return undefined
1330
+ }
1331
+ if (type === 'integer' && !Number.isInteger(parsed)) {
1332
+ const rounded = Math.round(parsed)
1333
+ warnings.push(`参数 ${path} 需要整数,已将 ${parsed} 取整为 ${rounded}`)
1334
+ return rounded
1335
+ }
1336
+ return parsed
1337
+ }
1338
+
1339
+ if (type === 'boolean') {
1340
+ if (typeof rawValue === 'boolean') return rawValue
1341
+ if (typeof rawValue === 'number' && (rawValue === 0 || rawValue === 1)) return rawValue === 1
1342
+ if (typeof rawValue === 'string') {
1343
+ const text = rawValue.trim().toLowerCase()
1344
+ if (['true', '1', 'yes', 'on'].includes(text)) return true
1345
+ if (['false', '0', 'no', 'off'].includes(text)) return false
1346
+ }
1347
+ warnings.push(`参数 ${path} 需要布尔值,收到:${JSON.stringify(rawValue)}`)
1348
+ return undefined
1349
+ }
1350
+
1351
+ if (type === 'enum') {
1352
+ if (Array.isArray(options) && options.length) {
1353
+ if (typeof rawValue === 'string' && options.includes(rawValue)) return rawValue
1354
+ const asText = String(rawValue)
1355
+ if (options.includes(asText)) return asText
1356
+ warnings.push(`参数 ${path} 的值 ${JSON.stringify(rawValue)} 不在枚举选项内(仍已写入)`)
1357
+ }
1358
+ return rawValue
1359
+ }
1360
+
1361
+ if (type === 'string') {
1362
+ if (typeof rawValue === 'string') return rawValue
1363
+ if (typeof rawValue === 'number' || typeof rawValue === 'boolean') return String(rawValue)
1364
+ warnings.push(`参数 ${path} 需要字符串,收到:${JSON.stringify(rawValue)}`)
1365
+ return undefined
1366
+ }
1367
+
1368
+ // 未知类型:按 JS 值原样写入
1369
+ return rawValue
1370
+ }
1371
+
1372
+ /**
1373
+ * 应用参数覆盖。path 形如 '3.seed' / '6.ckpt_name'(只支持两级)。
1374
+ * @param {object} apiGraph
1375
+ * @param {object[]} params buildParamSpecs 的结果
1376
+ * @param {Record<string,string|number|boolean>} overrides
1377
+ * @returns {{apiGraph:object, applied:{path:string,value:unknown}[], warnings:string[]}}
1378
+ */
1379
+ export function applyParamOverrides(apiGraph, params, overrides) {
1380
+ const graph = cloneValue(isPlainObject(apiGraph) ? apiGraph : {})
1381
+ const applied = []
1382
+ const warnings = []
1383
+ const paramByPath = new Map()
1384
+ for (const param of Array.isArray(params) ? params : []) {
1385
+ if (isPlainObject(param) && typeof param.path === 'string') paramByPath.set(param.path, param)
1386
+ }
1387
+
1388
+ if (overrides == null) return { apiGraph: graph, applied, warnings }
1389
+ if (!isPlainObject(overrides)) {
1390
+ warnings.push('params 必须是对象,形如 { "节点id.输入名": 值 }')
1391
+ return { apiGraph: graph, applied, warnings }
1392
+ }
1393
+
1394
+ for (const [path, rawValue] of Object.entries(overrides)) {
1395
+ if (typeof path !== 'string') continue
1396
+ const dot = path.indexOf('.')
1397
+ if (dot <= 0 || dot === path.length - 1 || path.indexOf('.', dot + 1) !== -1) {
1398
+ warnings.push(`不支持嵌套参数路径:${path}(只支持 "节点id.输入名" 两级)`)
1399
+ continue
1400
+ }
1401
+ const nodeId = path.slice(0, dot)
1402
+ const inputName = path.slice(dot + 1)
1403
+ const node = graph[nodeId]
1404
+ if (!isPlainObject(node) || !isPlainObject(node.inputs) || !Object.prototype.hasOwnProperty.call(node.inputs, inputName)) {
1405
+ warnings.push(`找不到参数路径:${path}`)
1406
+ continue
1407
+ }
1408
+ const existing = node.inputs[inputName]
1409
+ if (isLinkValue(existing)) {
1410
+ warnings.push(`参数 ${path} 当前是连线输入,不能直接覆盖`)
1411
+ continue
1412
+ }
1413
+ if (rawValue === undefined) {
1414
+ warnings.push(`参数 ${path} 的值为 undefined,已忽略`)
1415
+ continue
1416
+ }
1417
+ if (rawValue === null || typeof rawValue === 'object') {
1418
+ warnings.push(`参数 ${path} 只支持字符串/数字/布尔值`)
1419
+ continue
1420
+ }
1421
+ const param = paramByPath.get(path)
1422
+ const type = (param && param.type) || inferTypeFromValue(existing)
1423
+ const options = param && Array.isArray(param.options) ? param.options : undefined
1424
+ const converted = convertOverrideValue(rawValue, type, options, path, warnings)
1425
+ if (converted === undefined) continue
1426
+ node.inputs[inputName] = converted
1427
+ applied.push({ path, value: converted })
1428
+ }
1429
+ return { apiGraph: graph, applied, warnings }
1430
+ }
1431
+
1432
+ // ---------------------------------------------------------------------------
1433
+ // applyPrompts
1434
+ // ---------------------------------------------------------------------------
1435
+
1436
+ /**
1437
+ * 把提示词写入 buildParamSpecs 推导出的目标路径。
1438
+ * @param {object} apiGraph
1439
+ * @param {{positive:string[],negative:string[]}} promptTargets
1440
+ * @param {{prompt?:string,negativePrompt?:string}} prompts
1441
+ * @param {object[]} [params] 预留(路径中的 inputName 已足够定位字段)
1442
+ * @returns {{apiGraph:object, applied:{path:string,field:string,value:string}[], warnings:string[]}}
1443
+ */
1444
+ export function applyPrompts(apiGraph, promptTargets, { prompt, negativePrompt } = {}, params) {
1445
+ void params
1446
+ const graph = cloneValue(isPlainObject(apiGraph) ? apiGraph : {})
1447
+ const applied = []
1448
+ const warnings = []
1449
+ const hasPrompt = typeof prompt === 'string' && prompt.length > 0
1450
+ const hasNegativePrompt = typeof negativePrompt === 'string' && negativePrompt.length > 0
1451
+ if (!hasPrompt && !hasNegativePrompt) return { apiGraph: graph, applied, warnings }
1452
+
1453
+ const targets = isPlainObject(promptTargets) ? promptTargets : {}
1454
+ const positive = Array.isArray(targets.positive) ? targets.positive : []
1455
+ const negative = Array.isArray(targets.negative) ? targets.negative : []
1456
+
1457
+ const write = (path, value) => {
1458
+ if (typeof path !== 'string') return false
1459
+ const dot = path.indexOf('.')
1460
+ if (dot <= 0 || dot === path.length - 1) {
1461
+ warnings.push(`提示词目标路径不合法:${String(path)}`)
1462
+ return false
1463
+ }
1464
+ const nodeId = path.slice(0, dot)
1465
+ const inputName = path.slice(dot + 1)
1466
+ const node = graph[nodeId]
1467
+ if (!isPlainObject(node) || !isPlainObject(node.inputs) || !Object.prototype.hasOwnProperty.call(node.inputs, inputName)) {
1468
+ warnings.push(`提示词目标不存在:${path}`)
1469
+ return false
1470
+ }
1471
+ node.inputs[inputName] = value
1472
+ applied.push({ path, field: inputName, value })
1473
+ return true
1474
+ }
1475
+
1476
+ if (hasPrompt) {
1477
+ if (!positive.length) warnings.push('没有检测到正向提示词输入节点(text/positive),prompt 未写入')
1478
+ for (const path of positive) write(path, prompt)
1479
+ }
1480
+ if (hasNegativePrompt) {
1481
+ if (!negative.length) warnings.push('没有检测到负面提示词输入节点(negative),negativePrompt 未写入')
1482
+ for (const path of negative) write(path, negativePrompt)
1483
+ }
1484
+ return { apiGraph: graph, applied, warnings }
1485
+ }
1486
+
1487
+ // ---------------------------------------------------------------------------
1488
+ // mergeImport
1489
+ // ---------------------------------------------------------------------------
1490
+
1491
+ function listGraphNodes(apiGraph) {
1492
+ const nodes = []
1493
+ for (const nodeId of orderedNodeIds(apiGraph)) {
1494
+ const node = apiGraph[nodeId]
1495
+ if (!isPlainObject(node) || typeof node.class_type !== 'string') continue
1496
+ const item = { id: nodeId, class: node.class_type }
1497
+ if (isPlainObject(node._meta) && typeof node._meta.title === 'string' && node._meta.title) {
1498
+ item.title = node._meta.title
1499
+ }
1500
+ nodes.push(item)
1501
+ }
1502
+ return nodes
1503
+ }
1504
+
1505
+ function normalizeApiGraph(raw) {
1506
+ if (!isPlainObject(raw)) throw fail('不是 ComfyUI API 格式工作流:期望 { 节点id: { class_type, inputs } }')
1507
+ const apiGraph = {}
1508
+ for (const [nodeId, node] of Object.entries(raw)) {
1509
+ if (!isPlainObject(node) || typeof node.class_type !== 'string') continue
1510
+ const copy = cloneValue(node)
1511
+ if (!isPlainObject(copy.inputs)) copy.inputs = {}
1512
+ apiGraph[nodeId] = copy
1513
+ }
1514
+ if (!Object.keys(apiGraph).length) throw fail('工作流中没有可执行节点(API 格式为空)')
1515
+ return apiGraph
1516
+ }
1517
+
1518
+ /**
1519
+ * 一站式导入:parse -> (UI ? uiToApiGraph) -> buildParamSpecs。
1520
+ * @param {{name?:string, raw?:unknown, objectInfo?:object}} input
1521
+ * @returns {{name:string, format:'ui'|'api', source:'ui'|'api', apiGraph:object, uiGraph?:object,
1522
+ * nodes:{id:string,class:string,title?:string}[], params:object[],
1523
+ * promptTargets:{positive:string[],negative:string[]}, warnings:string[]}}
1524
+ */
1525
+ export function mergeImport({ name, raw, objectInfo } = {}) {
1526
+ const parsed = parseWorkflowJson(raw)
1527
+ let apiGraph
1528
+ let uiGraph
1529
+ let warnings = []
1530
+
1531
+ if (parsed.format === 'ui') {
1532
+ const converted = uiToApiGraph(parsed.raw, objectInfo)
1533
+ apiGraph = converted.apiGraph
1534
+ warnings = converted.warnings.slice()
1535
+ uiGraph = cloneValue(parsed.raw)
1536
+ } else {
1537
+ apiGraph = normalizeApiGraph(parsed.raw)
1538
+ }
1539
+
1540
+ const { params, promptTargets } = buildParamSpecs(apiGraph, objectInfo)
1541
+ const cleanName = typeof name === 'string' && name.trim() ? name.trim() : '未命名工作流'
1542
+ const result = {
1543
+ name: cleanName,
1544
+ format: parsed.format,
1545
+ source: parsed.format,
1546
+ apiGraph,
1547
+ nodes: listGraphNodes(apiGraph),
1548
+ params,
1549
+ promptTargets,
1550
+ warnings,
1551
+ }
1552
+ if (uiGraph !== undefined) result.uiGraph = uiGraph
1553
+ return result
1554
+ }
1555
+
1556
+ // ---------------------------------------------------------------------------
1557
+ // summarizeGraph
1558
+ // ---------------------------------------------------------------------------
1559
+
1560
+ /** 图摘要(可选辅助函数):{ nodeCount, classes: Record<string, number> } */
1561
+ export function summarizeGraph(apiGraph) {
1562
+ const classes = {}
1563
+ let nodeCount = 0
1564
+ if (isPlainObject(apiGraph)) {
1565
+ for (const node of Object.values(apiGraph)) {
1566
+ if (!isPlainObject(node) || typeof node.class_type !== 'string') continue
1567
+ nodeCount += 1
1568
+ classes[node.class_type] = (classes[node.class_type] || 0) + 1
1569
+ }
1570
+ }
1571
+ return { nodeCount, classes }
1572
+ }