comfy-ts 0.4.0 → 1.0.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.
Files changed (59) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1167 -172
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +401 -115
  9. package/dist/index.d.ts +401 -115
  10. package/dist/index.js +1159 -173
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-SDSJo1Qf.js → run-tui-BFhba_oG.js} +132 -609
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +6 -1
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/TreePanel.tsx +15 -2
  25. package/src/cli/tui/discoverWorkflows.ts +79 -0
  26. package/src/cli/tui/run-tui.tsx +51 -23
  27. package/src/cli/tui/state/HostSt.ts +2 -3
  28. package/src/cli/tui/state/TreeSt.ts +30 -6
  29. package/src/cli/tui/state/TuiSt.ts +21 -3
  30. package/src/cli/tui/state/WorkflowsSt.ts +15 -1
  31. package/src/host/ComfyHost.ts +203 -77
  32. package/src/host/ComfyManager.ts +10 -9
  33. package/src/host/ComfyUploader.ts +1 -2
  34. package/src/host/ResilientWebsocket.ts +3 -1
  35. package/src/host/hostUrl.ts +59 -0
  36. package/src/host/loraManagerApi.ts +5 -4
  37. package/src/index.ts +20 -1
  38. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  39. package/src/litegraph/LiteGraphGroup.ts +9 -7
  40. package/src/litegraph/LiteGraphJSON.ts +34 -13
  41. package/src/litegraph/LiteGraphLink.ts +32 -2
  42. package/src/litegraph/LiteGraphNode.ts +18 -33
  43. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  44. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  45. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  46. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  47. package/src/litegraph/expandSubgraphs.ts +352 -0
  48. package/src/litegraph/normalizeWorkflow.ts +141 -0
  49. package/src/runner/ComfyExecution.ts +4 -5
  50. package/src/runner/ComfyWorkflow.ts +2 -2
  51. package/src/runner/wsBinaryFrame.ts +48 -0
  52. package/src/sdk-generator/Primitives.ts +6 -24
  53. package/src/sdk-generator/comfy-api-json.ts +3 -1
  54. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  55. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  56. package/src/state.ts +13 -2
  57. package/dist/log-CdfgILde.js +0 -10
  58. package/dist/log-CdfgILde.js.map +0 -1
  59. package/dist/run-tui-SDSJo1Qf.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -39,7 +39,597 @@ node_https = __toESM(node_https, 1);
39
39
  let node_process = require("node:process");
40
40
  let fs = require("fs");
41
41
  //#region package.json
42
- var version = "0.4.0";
42
+ var version = "1.0.0";
43
+ //#endregion
44
+ //#region src/litegraph/LiteGraphLinkID.ts
45
+ const asLiteGraphLinkID = (id) => id;
46
+ const LiteGraphLinkID_ = arktype.type.number.atLeast(0).as();
47
+ //#endregion
48
+ //#region src/utils/bang.ts
49
+ /** assertNotNull */
50
+ const bang = (x, msg = "") => {
51
+ if (x == null) {
52
+ console.error(`[🔴] BANG FAILED`, msg);
53
+ throw new Error("bang: " + (msg ?? "no message"));
54
+ }
55
+ return x;
56
+ };
57
+ //#endregion
58
+ //#region src/litegraph/expandSubgraphs.ts
59
+ /** boundary sentinel ids inside definition link tables */
60
+ const SUBGRAPH_INPUT_NODE_ID = -10;
61
+ const SUBGRAPH_OUTPUT_NODE_ID = -20;
62
+ /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
63
+ const MAX_EXPANSION_PASSES = 32;
64
+ /**
65
+ * widget-kind fallback when a def input slot has no boundary target carrying a
66
+ * widget marker: these litegraph slot types carry widget values. LOCAL copy on
67
+ * purpose — the sdk-generator's seed-consumes-2 arithmetic does not apply here
68
+ * (the io-widget era serializes exactly one value per exposed widget slot).
69
+ */
70
+ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
71
+ "INT",
72
+ "FLOAT",
73
+ "STRING",
74
+ "BOOLEAN",
75
+ "COMBO"
76
+ ]);
77
+ /**
78
+ * inline every subgraph instance (node whose `type` is a definition uuid) into
79
+ * the root graph: fresh numeric ids, boundary links rewired, instance widget
80
+ * values promoted into the inner nodes' `named` overrides. Iterative so nested
81
+ * definitions expand on the next pass. Muted instances are dropped (their
82
+ * consumers resolve unconnected); bypassed instances stay for the converter's
83
+ * passthrough walk, which needs no interior.
84
+ */
85
+ const expandSubgraphs = (wf, defs) => {
86
+ let passes = 0;
87
+ while (true) {
88
+ const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
89
+ if (expandable.length === 0) return wf;
90
+ if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
91
+ for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
92
+ else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
93
+ }
94
+ };
95
+ /** converter mute semantics applied early: after expansion there is no single node left to skip */
96
+ const dropMutedInstance = (wf, instance) => {
97
+ const dead = /* @__PURE__ */ new Set();
98
+ for (const link of wf.links) if (link.originId === instance.id || link.targetId === instance.id) dead.add(link.id);
99
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
100
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
101
+ pruneDeadLinkRefs(wf, dead);
102
+ };
103
+ const pruneDeadLinkRefs = (wf, dead) => {
104
+ if (dead.size === 0) return;
105
+ for (const node of wf.nodes) {
106
+ for (const input of node.inputs) if (input.link != null && dead.has(input.link)) input.link = null;
107
+ for (const output of node.outputs) output.links = output.links.filter((id) => !dead.has(id));
108
+ }
109
+ };
110
+ const expandOneInstance = (wf, instance, def) => {
111
+ let nextNodeId = Math.max(0, ...wf.nodes.map((n) => n.id));
112
+ let nextLinkId = Math.max(0, ...wf.links.map((l) => l.id));
113
+ const newNodeIds = /* @__PURE__ */ new Map();
114
+ for (const inner of def.nodes) newNodeIds.set(inner.id, ++nextNodeId);
115
+ const remapNodeId = (id) => newNodeIds.get(id) ?? null;
116
+ const defSlotOfInstanceSlot = /* @__PURE__ */ new Map();
117
+ for (const [k, input] of instance.inputs.entries()) {
118
+ const defSlot = def.inputs.findIndex((d) => d.name === input.name);
119
+ if (defSlot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): input "${input.name}" (slot ${k}) matches no definition input (defined: ${def.inputs.map((d) => d.name).join(", ")})`);
120
+ defSlotOfInstanceSlot.set(k, defSlot);
121
+ }
122
+ const outerLinkIntoDefSlot = /* @__PURE__ */ new Map();
123
+ for (const link of wf.links) {
124
+ if (link.targetId !== instance.id) continue;
125
+ const defSlot = defSlotOfInstanceSlot.get(link.targetSlot);
126
+ if (defSlot == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): link ${link.id} targets undeclared instance slot ${link.targetSlot}`);
127
+ outerLinkIntoDefSlot.set(defSlot, link);
128
+ }
129
+ const newLinkIds = /* @__PURE__ */ new Map();
130
+ const splicedLinks = [];
131
+ const producerByOutSlot = /* @__PURE__ */ new Map();
132
+ const passthroughOutSlot = /* @__PURE__ */ new Map();
133
+ const boundaryTargetsByInSlot = /* @__PURE__ */ new Map();
134
+ for (const link of def.links) {
135
+ const fromInputBoundary = link.originId === SUBGRAPH_INPUT_NODE_ID;
136
+ const toOutputBoundary = link.targetId === SUBGRAPH_OUTPUT_NODE_ID;
137
+ if (fromInputBoundary && toOutputBoundary) {
138
+ passthroughOutSlot.set(link.targetSlot, link.originSlot);
139
+ continue;
140
+ }
141
+ if (toOutputBoundary) {
142
+ const producerId = remapNodeId(link.originId);
143
+ if (producerId != null && !producerByOutSlot.has(link.targetSlot)) producerByOutSlot.set(link.targetSlot, {
144
+ nodeId: producerId,
145
+ slot: link.originSlot
146
+ });
147
+ continue;
148
+ }
149
+ if (fromInputBoundary) {
150
+ const targetId = remapNodeId(link.targetId);
151
+ if (targetId == null) continue;
152
+ const target = {
153
+ nodeId: targetId,
154
+ slot: link.targetSlot
155
+ };
156
+ const targets = boundaryTargetsByInSlot.get(link.originSlot) ?? [];
157
+ targets.push(target);
158
+ boundaryTargetsByInSlot.set(link.originSlot, targets);
159
+ const outer = outerLinkIntoDefSlot.get(link.originSlot);
160
+ if (outer == null) continue;
161
+ const fresh = asLiteGraphLinkID(++nextLinkId);
162
+ newLinkIds.set(link.id, fresh);
163
+ splicedLinks.push({
164
+ id: fresh,
165
+ originId: outer.originId,
166
+ originSlot: outer.originSlot,
167
+ targetId: target.nodeId,
168
+ targetSlot: target.slot,
169
+ type: link.type
170
+ });
171
+ wf.nodes.find((n) => n.id === outer.originId)?.outputs[outer.originSlot]?.links.push(fresh);
172
+ continue;
173
+ }
174
+ const interiorOrigin = remapNodeId(link.originId);
175
+ const interiorTarget = remapNodeId(link.targetId);
176
+ if (interiorOrigin == null || interiorTarget == null) continue;
177
+ const fresh = asLiteGraphLinkID(++nextLinkId);
178
+ newLinkIds.set(link.id, fresh);
179
+ splicedLinks.push({
180
+ id: fresh,
181
+ originId: interiorOrigin,
182
+ originSlot: link.originSlot,
183
+ targetId: interiorTarget,
184
+ targetSlot: link.targetSlot,
185
+ type: link.type
186
+ });
187
+ }
188
+ const splicedNodes = def.nodes.map((inner) => ({
189
+ id: bang(newNodeIds.get(inner.id)),
190
+ type: inner.type,
191
+ title: inner.title,
192
+ mode: inner.mode,
193
+ isVirtualNode: inner.isVirtualNode,
194
+ inputs: inner.inputs.map((i) => ({
195
+ name: i.name,
196
+ type: i.type,
197
+ link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
198
+ widgetName: i.widgetName
199
+ })),
200
+ outputs: inner.outputs.map((o) => ({
201
+ name: o.name,
202
+ type: o.type,
203
+ links: o.links.map((id) => newLinkIds.get(id)).filter((id) => id != null)
204
+ })),
205
+ widgets: {
206
+ positional: [...inner.widgets.positional],
207
+ named: { ...inner.widgets.named }
208
+ },
209
+ pos: [inner.pos[0], inner.pos[1]],
210
+ size: [inner.size[0], inner.size[1]],
211
+ properties: { ...inner.properties }
212
+ }));
213
+ const dead = /* @__PURE__ */ new Set();
214
+ for (const link of wf.links) {
215
+ if (link.targetId === instance.id) {
216
+ dead.add(link.id);
217
+ continue;
218
+ }
219
+ if (link.originId !== instance.id) continue;
220
+ const producer = producerByOutSlot.get(link.originSlot);
221
+ if (producer != null) {
222
+ link.originId = producer.nodeId;
223
+ link.originSlot = producer.slot;
224
+ splicedNodes.find((n) => n.id === producer.nodeId)?.outputs[producer.slot]?.links.push(link.id);
225
+ continue;
226
+ }
227
+ const passthroughInSlot = passthroughOutSlot.get(link.originSlot);
228
+ const outer = passthroughInSlot != null ? outerLinkIntoDefSlot.get(passthroughInSlot) : null;
229
+ if (outer != null) {
230
+ link.originId = outer.originId;
231
+ link.originSlot = outer.originSlot;
232
+ continue;
233
+ }
234
+ dead.add(link.id);
235
+ }
236
+ wf.links = wf.links.filter((l) => !dead.has(l.id));
237
+ pruneDeadLinkRefs(wf, dead);
238
+ promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
239
+ wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
240
+ wf.nodes.push(...splicedNodes);
241
+ wf.links.push(...splicedLinks);
242
+ };
243
+ /**
244
+ * instance widget values land in inner nodes' `named` overrides. TWO eras for
245
+ * the POSITIONAL values:
246
+ * - proxyWidgets era: `properties.proxyWidgets` pairs [innerNodeId, widgetName]
247
+ * zip against the instance's positional values (incl. `control_after_generate`
248
+ * phantom pairs — written to `named` and simply never read, no schema input
249
+ * has that name).
250
+ * - io-widget era (no proxyWidgets): positional values zip against the def's
251
+ * widget-kind input slots in def order, one value per slot (no phantom —
252
+ * corpus-verified). An outer link into the same slot wins in the converter;
253
+ * the named override is still written, matching ComfyUI.
254
+ * PLUS, in both eras, NAMED overrides on the instance keyed by def-input name:
255
+ * that is how a NESTED instance receives its outer values (the previous pass
256
+ * wrote them to `named`), so they must forward through THIS expansion too —
257
+ * named wins over positional, same precedence as the converter.
258
+ */
259
+ const promoteInstanceWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot) => {
260
+ const promoteToSlotTargets = (slot, value) => {
261
+ for (const t of boundaryTargetsByInSlot.get(slot) ?? []) {
262
+ const target = splicedNodes.find((n) => n.id === t.nodeId);
263
+ const input = innerInputAt(splicedNodes, t);
264
+ if (target == null || input == null) continue;
265
+ target.widgets.named[input.name] = value;
266
+ }
267
+ };
268
+ promotePositionalWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets);
269
+ for (const [slot, io] of def.inputs.entries()) {
270
+ if (!Object.hasOwn(instance.widgets.named, io.name)) continue;
271
+ promoteToSlotTargets(slot, instance.widgets.named[io.name]);
272
+ }
273
+ };
274
+ const promotePositionalWidgets = (instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot, promoteToSlotTargets) => {
275
+ const values = instance.widgets.positional;
276
+ if (values.length === 0) return;
277
+ const proxy = instance.properties["proxyWidgets"];
278
+ if (Array.isArray(proxy) && proxy.length > 0) {
279
+ const count = Math.min(values.length, proxy.length);
280
+ for (let k = 0; k < count; k++) {
281
+ const pair = proxy[k];
282
+ if (!Array.isArray(pair) || pair.length !== 2) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): malformed proxyWidgets entry ${JSON.stringify(pair)}`);
283
+ const innerId = Number(pair[0]);
284
+ const widgetName = String(pair[1]);
285
+ if (innerId < 0) {
286
+ const slot = def.inputs.findIndex((d) => d.name === widgetName);
287
+ if (slot < 0) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names io widget "${widgetName}" but no definition input matches`);
288
+ promoteToSlotTargets(slot, values[k]);
289
+ continue;
290
+ }
291
+ const target = splicedNodes.find((n) => n.id === newNodeIds.get(innerId));
292
+ if (target == null) throw new WorkflowNormalizeError("subgraph-io-mismatch", `subgraph instance ${instance.id}(${def.name}): proxyWidgets pair ${k} names unknown inner node ${String(pair[0])}`);
293
+ target.widgets.named[widgetName] = values[k];
294
+ }
295
+ return;
296
+ }
297
+ let valueIndex = 0;
298
+ for (const [slot, io] of def.inputs.entries()) {
299
+ const targets = boundaryTargetsByInSlot.get(slot) ?? [];
300
+ if (!(targets.length > 0 ? targets.some((t) => innerInputAt(splicedNodes, t)?.widgetName != null) : PRIMITIVE_WIDGET_TYPES.has(io.type))) continue;
301
+ if (valueIndex >= values.length) break;
302
+ promoteToSlotTargets(slot, values[valueIndex++]);
303
+ }
304
+ };
305
+ const innerInputAt = (splicedNodes, t) => {
306
+ return splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot] ?? null;
307
+ };
308
+ //#endregion
309
+ //#region src/litegraph/LiteGraphGroup.ts
310
+ const LiteGraphGroup_ark = (0, arktype.type)({
311
+ "id?": "number",
312
+ title: "string",
313
+ bounding: (0, arktype.type)([
314
+ "number",
315
+ "number",
316
+ "number",
317
+ "number"
318
+ ]),
319
+ "color?": "string",
320
+ "font_size?": "number",
321
+ "flags?": arktype.type.Record("string", "unknown").as()
322
+ });
323
+ //#endregion
324
+ //#region src/litegraph/LiteGraphLink.ts
325
+ const LiteGraphLinkTuple_ark = (0, arktype.type)([
326
+ LiteGraphLinkID_,
327
+ "number",
328
+ "number",
329
+ "number",
330
+ "number",
331
+ "string"
332
+ ]);
333
+ const LiteGraphLinkObject_ark = (0, arktype.type)({
334
+ id: LiteGraphLinkID_,
335
+ origin_id: "number",
336
+ origin_slot: "number",
337
+ target_id: "number",
338
+ target_slot: "number",
339
+ type: "string",
340
+ "parentId?": "number"
341
+ });
342
+ const LiteGraphLink_ark = LiteGraphLinkTuple_ark.or(LiteGraphLinkObject_ark);
343
+ //#endregion
344
+ //#region src/litegraph/LiteGraphNodeInput.ts
345
+ const LiteGraphNodeInput_ark = (0, arktype.type)({
346
+ name: "string",
347
+ type: "string",
348
+ "link?": LiteGraphLinkID_.or(arktype.type.null),
349
+ "shape?": "number",
350
+ "label?": "string",
351
+ "widget?": (0, arktype.type)({
352
+ name: "string",
353
+ "config?": "unknown"
354
+ })
355
+ });
356
+ //#endregion
357
+ //#region src/litegraph/LiteGraphSlotIndex.ts
358
+ const asLiteGraphSlotIndex = (id) => id;
359
+ const LiteGraphSlotIndex_ = arktype.type.number.atLeast(0).as();
360
+ //#endregion
361
+ //#region src/litegraph/LiteGraphNodeOutput.ts
362
+ const LiteGraphNodeOutput_ark = (0, arktype.type)({
363
+ name: "string",
364
+ type: "string",
365
+ "links?": LiteGraphLinkID_.array().or(arktype.type.null),
366
+ "shape?": "number",
367
+ "slot_index?": LiteGraphSlotIndex_
368
+ });
369
+ //#endregion
370
+ //#region src/litegraph/LiteGraphNode.ts
371
+ const LiteGraphNode_ark = (0, arktype.type)({
372
+ id: "number",
373
+ type: "string",
374
+ "title?": "string",
375
+ "color?": "string",
376
+ "bgcolor?": "string",
377
+ pos: {
378
+ "0": "number",
379
+ "1": "number"
380
+ },
381
+ size: {
382
+ "0": "number",
383
+ "1": "number"
384
+ },
385
+ "flags?": arktype.type.Record("string", "unknown"),
386
+ "order?": "number",
387
+ "mode?": "number",
388
+ "inputs?": LiteGraphNodeInput_ark.array(),
389
+ "outputs?": LiteGraphNodeOutput_ark.array(),
390
+ "isVirtualNode?": "boolean",
391
+ "properties?": arktype.type.Record("string", "unknown"),
392
+ "widgets_values?": (0, arktype.type)("unknown[]").or(arktype.type.Record("string", "unknown"))
393
+ });
394
+ //#endregion
395
+ //#region src/litegraph/LiteGraphSubgraphDef.ts
396
+ const LiteGraphSubgraphIO_ark = (0, arktype.type)({
397
+ id: "string",
398
+ name: "string",
399
+ type: "string",
400
+ "linkIds?": LiteGraphLinkID_.array(),
401
+ "label?": "string",
402
+ "localized_name?": "string",
403
+ "pos?": {
404
+ "0": "number",
405
+ "1": "number"
406
+ },
407
+ "shape?": "number"
408
+ });
409
+ const LiteGraphSubgraphDef_ark = (0, arktype.type)({
410
+ id: "string",
411
+ name: "string",
412
+ version: "number",
413
+ "state?": arktype.type.Record("string", "unknown"),
414
+ "revision?": "number",
415
+ "config?": arktype.type.Record("string", "unknown").as(),
416
+ "extra?": "unknown",
417
+ nodes: LiteGraphNode_ark.array(),
418
+ links: LiteGraphLinkObject_ark.array(),
419
+ "groups?": LiteGraphGroup_ark.array(),
420
+ inputNode: {
421
+ id: "number",
422
+ bounding: "number[]"
423
+ },
424
+ outputNode: {
425
+ id: "number",
426
+ bounding: "number[]"
427
+ },
428
+ inputs: LiteGraphSubgraphIO_ark.array(),
429
+ outputs: LiteGraphSubgraphIO_ark.array(),
430
+ widgets: "unknown[]"
431
+ });
432
+ //#endregion
433
+ //#region src/litegraph/LiteGraphJSON.ts
434
+ const LiteGraphJSON_ark = (0, arktype.type)({
435
+ "id?": "string",
436
+ "revision?": "number",
437
+ "last_node_id?": "number",
438
+ "last_link_id?": "number",
439
+ "state?": arktype.type.Record("string", "unknown"),
440
+ nodes: LiteGraphNode_ark.array(),
441
+ links: LiteGraphLink_ark.array(),
442
+ "groups?": LiteGraphGroup_ark.array(),
443
+ "config?": arktype.type.Record("never", "never"),
444
+ "extra?": { "ds?": {
445
+ scale: "number",
446
+ offset: {
447
+ "0": "number",
448
+ "1": "number"
449
+ }
450
+ } },
451
+ "models?": "unknown[]",
452
+ "definitions?": { subgraphs: LiteGraphSubgraphDef_ark.array() },
453
+ "reroutes?": "unknown[]",
454
+ "floatingLinks?": "unknown[]",
455
+ version: "0.4 | 1"
456
+ });
457
+ //#endregion
458
+ //#region src/litegraph/normalizeWorkflow.ts
459
+ /** a workflow JSON we cannot turn into a CanonicalWorkflow — loud, typed, never a cast */
460
+ var WorkflowNormalizeError = class extends Error {
461
+ constructor(code, message, detail) {
462
+ super(`[workflow ${code}] ${message}`);
463
+ this.code = code;
464
+ this.detail = detail;
465
+ this.name = "WorkflowNormalizeError";
466
+ }
467
+ };
468
+ /**
469
+ * THE one entry for foreign workflow JSON (files, clipboard, imports):
470
+ * tolerant ark validation, then normalization to the strict canonical shape.
471
+ */
472
+ const parseWorkflowJson = (json) => {
473
+ const out = LiteGraphJSON_ark(json);
474
+ if (out instanceof arktype.type.errors) throw new WorkflowNormalizeError("schema-reject", out.summary, out);
475
+ return normalizeWorkflow(out);
476
+ };
477
+ /**
478
+ * loose wire document → strict canonical document. Defaults filled, both link
479
+ * eras unified, cosmetic fields dropped, subgraph definitions expanded away
480
+ * (see expandSubgraphs.ts — def interiors go through the SAME per-shape
481
+ * normalizers, they are v1 bodies).
482
+ */
483
+ const normalizeWorkflow = (raw) => {
484
+ const wf = {
485
+ nodes: raw.nodes.map(normalizeNode),
486
+ links: raw.links.map(normalizeLink),
487
+ groups: (raw.groups ?? []).map(normalizeGroup)
488
+ };
489
+ const rawDefs = raw.definitions?.subgraphs ?? [];
490
+ if (rawDefs.length === 0) return wf;
491
+ const defs = /* @__PURE__ */ new Map();
492
+ for (const d of rawDefs) defs.set(d.id, normalizeSubgraphDef(d));
493
+ return expandSubgraphs(wf, defs);
494
+ };
495
+ const normalizeSubgraphDef = (d) => {
496
+ return {
497
+ id: d.id,
498
+ name: d.name,
499
+ inputs: d.inputs.map((io) => ({
500
+ name: io.name,
501
+ type: io.type
502
+ })),
503
+ outputs: d.outputs.map((io) => ({
504
+ name: io.name,
505
+ type: io.type
506
+ })),
507
+ nodes: d.nodes.map(normalizeNode),
508
+ links: d.links.map(normalizeLink)
509
+ };
510
+ };
511
+ const normalizeMode = (mode) => {
512
+ if (mode === 2) return "muted";
513
+ if (mode === 4) return "bypassed";
514
+ return "normal";
515
+ };
516
+ const normalizeNode = (n) => {
517
+ return {
518
+ id: n.id,
519
+ type: n.type,
520
+ title: n.title ?? null,
521
+ mode: normalizeMode(n.mode),
522
+ isVirtualNode: n.isVirtualNode ?? false,
523
+ inputs: (n.inputs ?? []).map(normalizeInput),
524
+ outputs: (n.outputs ?? []).map(normalizeOutput),
525
+ widgets: normalizeWidgetValues(n.widgets_values),
526
+ pos: [n.pos[0], n.pos[1]],
527
+ size: [n.size[0], n.size[1]],
528
+ properties: { ...n.properties }
529
+ };
530
+ };
531
+ const normalizeInput = (i) => {
532
+ return {
533
+ name: i.name,
534
+ type: i.type,
535
+ link: i.link ?? null,
536
+ widgetName: i.widget?.name ?? null
537
+ };
538
+ };
539
+ const normalizeOutput = (o) => {
540
+ return {
541
+ name: o.name,
542
+ type: o.type,
543
+ links: [...o.links ?? []]
544
+ };
545
+ };
546
+ const normalizeWidgetValues = (wv) => {
547
+ if (wv == null) return {
548
+ positional: [],
549
+ named: {}
550
+ };
551
+ if (Array.isArray(wv)) return {
552
+ positional: [...wv],
553
+ named: {}
554
+ };
555
+ return {
556
+ positional: [],
557
+ named: { ...wv }
558
+ };
559
+ };
560
+ const normalizeLink = (l) => {
561
+ if (Array.isArray(l)) return {
562
+ id: l[0],
563
+ originId: l[1],
564
+ originSlot: l[2],
565
+ targetId: l[3],
566
+ targetSlot: l[4],
567
+ type: l[5]
568
+ };
569
+ return {
570
+ id: l.id,
571
+ originId: l.origin_id,
572
+ originSlot: l.origin_slot,
573
+ targetId: l.target_id,
574
+ targetSlot: l.target_slot,
575
+ type: l.type
576
+ };
577
+ };
578
+ const normalizeGroup = (g) => {
579
+ return {
580
+ title: g.title,
581
+ bounding: [
582
+ g.bounding[0],
583
+ g.bounding[1],
584
+ g.bounding[2],
585
+ g.bounding[3]
586
+ ],
587
+ color: g.color ?? "#3f789e",
588
+ fontSize: g.font_size ?? 24
589
+ };
590
+ };
591
+ //#endregion
592
+ //#region src/runner/wsBinaryFrame.ts
593
+ function parseBinaryWsFrame(data) {
594
+ const view = new DataView(data);
595
+ const eventType = view.getUint32(0);
596
+ if (eventType === 1) {
597
+ const imageType = view.getUint32(4);
598
+ return {
599
+ kind: "preview",
600
+ bytes: new Uint8Array(data.slice(8)),
601
+ mime: imageType === 2 ? "image/png" : "image/jpeg",
602
+ metadata: null
603
+ };
604
+ }
605
+ if (eventType === 3) {
606
+ const nodeIdLen = view.getUint32(4);
607
+ const decoder = new TextDecoder();
608
+ return {
609
+ kind: "text",
610
+ nodeId: decoder.decode(data.slice(8, 8 + nodeIdLen)),
611
+ text: decoder.decode(data.slice(8 + nodeIdLen))
612
+ };
613
+ }
614
+ if (eventType === 4) {
615
+ const metadataLen = view.getUint32(4);
616
+ let metadata = null;
617
+ try {
618
+ metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)));
619
+ } catch {}
620
+ const bytes = new Uint8Array(data.slice(8 + metadataLen));
621
+ return {
622
+ kind: "preview",
623
+ bytes,
624
+ mime: bytes[0] === 137 && bytes[1] === 80 ? "image/png" : "image/jpeg",
625
+ metadata
626
+ };
627
+ }
628
+ return {
629
+ kind: "unknown",
630
+ eventType
631
+ };
632
+ }
43
633
  //#endregion
44
634
  //#region src/sdk-generator/Primitives.ts
45
635
  const ComfyPrimitiveMapping = {
@@ -50,20 +640,8 @@ const ComfyPrimitiveMapping = {
50
640
  };
51
641
  const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
52
642
  /**
53
- * when a litegraph node has no input for a given ComfyUI node input
54
- * (e.g. a seed or an enum that has not been turned into a primitive)
55
- */
56
- const howManyWidgetValuesForThisSchemaType = (input) => {
57
- if (input.typeName === "INT") {
58
- if (input.nameInComfy === "seed" || input.nameInComfy === "noise_seed") return 2;
59
- }
60
- if (input.isPrimitive) return 1;
61
- if (input.typeName.startsWith("E_")) return 1;
62
- return 0;
63
- };
64
- /**
65
- * then a litegraph node has an input entry, some convoluted logic seems to be necessary
66
- * to determine how many Field_values need to be consumed for this input
643
+ * when a litegraph node has an input entry with a widget marker, the
644
+ * serialized TYPE string decides how many widgets_values it consumed in that era
67
645
  */
68
646
  const howManyWidgetValuesForThisInputType = (type, nameInComfy) => {
69
647
  if (type === "INT") {
@@ -91,94 +669,433 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
91
669
  output_node: false,
92
670
  python_module: "nodes"
93
671
  };
94
- var UnknownCustomNode = class extends Error {
95
- constructor(node) {
96
- super(`❌ node ${node.id}(${node.type}) has no known schema; you probably need to install some custom node`);
97
- this.node = node;
672
+ //#endregion
673
+ //#region src/sdk-generator/inputWidgetKind.ts
674
+ const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
675
+ /**
676
+ * seed phantom: a TRUTHY `control_after_generate` adds one consumed value.
677
+ * The frontend creates the control widget on truthiness, and real 2026 hosts
678
+ * spell it as `true` OR as a string mode like `'fixed'` (PrimitiveInt.value,
679
+ * SeedNode.seed). When the KEY is absent (2024 era) the INT-named-seed
680
+ * heuristic applies.
681
+ */
682
+ const controlConsumes = (o, typeName, name) => {
683
+ if (o != null && "control_after_generate" in o) return o["control_after_generate"] ? 2 : 1;
684
+ if (typeName === "INT" && (name === "seed" || name === "noise_seed")) return 2;
685
+ return 1;
686
+ };
687
+ const flattenInputSections = (inputs) => {
688
+ const out = [];
689
+ for (const section of ["required", "optional"]) {
690
+ const sec = inputs[section];
691
+ if (!isRecord(sec)) continue;
692
+ for (const [name, spec] of Object.entries(sec)) {
693
+ if (!Array.isArray(spec) || spec.length === 0) continue;
694
+ const t = spec[0];
695
+ if (typeof t !== "string" && !Array.isArray(t)) continue;
696
+ out.push({
697
+ name,
698
+ type: t,
699
+ opts: spec[1],
700
+ required: section === "required"
701
+ });
702
+ }
703
+ }
704
+ return out;
705
+ };
706
+ /** null when the options array is NOT the dynamic `{key, inputs}` family (then it is a plain combo) */
707
+ const parseDynamicOptions = (options) => {
708
+ if (options.length === 0) return null;
709
+ const out = [];
710
+ for (const entry of options) {
711
+ if (!isRecord(entry)) return null;
712
+ const key = entry["key"];
713
+ const inputs = entry["inputs"];
714
+ if (typeof key !== "string" || !isRecord(inputs)) return null;
715
+ out.push({
716
+ key,
717
+ inputs: flattenInputSections(inputs)
718
+ });
719
+ }
720
+ return out;
721
+ };
722
+ /**
723
+ * autogrow (`template` WITH a nested `input` section): instances are always
724
+ * link slots named `decl.<name_i>` (the backend force-inputs widget
725
+ * templates), the first `min` of them required WHEN the template input
726
+ * section is `required` — mirrors `_io.py Autogrow._expand_schema_for_dynamic`.
727
+ */
728
+ const parseContainer = (template) => {
729
+ const input = template["input"];
730
+ const min = typeof template["min"] === "number" ? template["min"] : 1;
731
+ const prefix = typeof template["prefix"] === "string" ? template["prefix"] : "";
732
+ const max = typeof template["max"] === "number" ? template["max"] : 100;
733
+ const rawNames = template["names"];
734
+ const names = Array.isArray(rawNames) ? rawNames.filter((n) => typeof n === "string") : Array.from({ length: max }, (_, i) => `${prefix}${i}`);
735
+ return {
736
+ kind: "dynamic-container",
737
+ instanceNames: names,
738
+ requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
739
+ };
740
+ };
741
+ const classifyWidgetInput = (p) => {
742
+ const o = isRecord(p.opts) ? p.opts : null;
743
+ if (o?.["forceInput"] === true) return { kind: "slot" };
744
+ if (Array.isArray(p.type) || p.isEnumUnion === true) {
745
+ const tn = typeof p.type === "string" ? p.type : "COMBO";
746
+ return {
747
+ kind: "widget",
748
+ consumes: controlConsumes(o, tn, p.name),
749
+ strictValues: true
750
+ };
98
751
  }
752
+ if (typeof p.type !== "string") return { kind: "slot" };
753
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
754
+ if (ComfyPrimitiveMapping[widgetTypeName] != null) return {
755
+ kind: "widget",
756
+ consumes: controlConsumes(o, widgetTypeName, p.name),
757
+ strictValues: true
758
+ };
759
+ const options = o?.["options"];
760
+ if (Array.isArray(options)) {
761
+ const dynOptions = parseDynamicOptions(options);
762
+ if (dynOptions != null) {
763
+ const first = dynOptions[0];
764
+ if (first == null) return { kind: "slot" };
765
+ return {
766
+ kind: "dynamic-combo",
767
+ options: dynOptions,
768
+ defaultKey: typeof o?.["default"] === "string" ? o["default"] : first.key
769
+ };
770
+ }
771
+ return {
772
+ kind: "widget",
773
+ consumes: controlConsumes(o, p.type, p.name),
774
+ strictValues: true
775
+ };
776
+ }
777
+ const template = o?.["template"];
778
+ if (isRecord(template)) {
779
+ if (isRecord(template["input"])) return parseContainer(template);
780
+ return { kind: "slot" };
781
+ }
782
+ if (o?.["socketless"] === true) return {
783
+ kind: "widget",
784
+ consumes: 1,
785
+ strictValues: false
786
+ };
787
+ return { kind: "slot" };
788
+ };
789
+ const classifySchemaInput = (input) => classifyWidgetInput({
790
+ name: input.nameInComfy,
791
+ type: input.typeName,
792
+ opts: input.opts,
793
+ isEnumUnion: input.isEnum
794
+ });
795
+ /** how many widgets_values entries this schema input consumes (export path + positional walks) */
796
+ const howManyWidgetValuesForThisSchemaType = (input) => {
797
+ const kind = classifySchemaInput(input);
798
+ return kind.kind === "widget" ? kind.consumes : 0;
799
+ };
800
+ /**
801
+ * what ComfyUI's frontend gives a widget created with no serialized value
802
+ * (`getWidgetDefaultValue` semantics), used when a positional array is
803
+ * shorter than the schema's widget list. `null` for custom widgets — the
804
+ * backend accepts an explicit null but errors on an ABSENT required key.
805
+ */
806
+ const defaultValueForWidget = (p) => {
807
+ const o = isRecord(p.opts) ? p.opts : null;
808
+ if (o != null && o["default"] !== void 0) return o["default"];
809
+ const widgetTypeName = typeof o?.["widgetType"] === "string" ? o["widgetType"] : p.type;
810
+ if (widgetTypeName === "INT" || widgetTypeName === "FLOAT") return 0;
811
+ if (widgetTypeName === "BOOLEAN") return false;
812
+ if (widgetTypeName === "STRING") return "";
813
+ const options = o?.["options"];
814
+ if (Array.isArray(options) && options.length > 0) {
815
+ const first = options[0];
816
+ if (typeof first === "string" || typeof first === "number" || typeof first === "boolean") return first;
817
+ }
818
+ if (p.enumValues != null && p.enumValues.length > 0) return p.enumValues[0];
819
+ return null;
99
820
  };
100
821
  //#endregion
101
822
  //#region src/sdk-generator/litegraphToApiRequestPayload.ts
823
+ /** a canonical workflow the converter cannot turn into a prompt — the code NAMES the feature that failed */
824
+ var WorkflowConvertError = class extends Error {
825
+ constructor(code, message, node) {
826
+ super(`[workflow ${code}] ${message}`);
827
+ this.code = code;
828
+ this.node = node;
829
+ this.name = "WorkflowConvertError";
830
+ }
831
+ };
832
+ /**
833
+ * closed set: frontend-only node types that NEVER execute. PrimitiveString /
834
+ * PrimitiveInt / PrimitiveBoolean etc are REAL backend nodes — do not add them.
835
+ */
836
+ const VIRTUAL_NODE_TYPES = /* @__PURE__ */ new Set([
837
+ "Note",
838
+ "MarkdownNote",
839
+ "Reroute",
840
+ "PrimitiveNode"
841
+ ]);
842
+ const isNeverExecuted = (node) => node.isVirtualNode || VIRTUAL_NODE_TYPES.has(node.type);
843
+ /** exact match, or `*` wildcard on either side (Reroute-style slots) */
844
+ /** frontend isValidConnection parity: exact, `*` wildcard, or any member of a comma-separated multi-type */
845
+ const linkTypeMatches = (a, b) => {
846
+ if (a === b || a === "*" || b === "*") return true;
847
+ if (!a.includes(",") && !b.includes(",")) return false;
848
+ const as = a.split(",");
849
+ const bs = b.split(",");
850
+ return as.some((x) => bs.includes(x));
851
+ };
852
+ /** what an inlined PrimitiveNode may contribute: scalar widget values only */
853
+ const isPromptScalar = (v) => v === null || typeof v === "string" || typeof v === "number" || typeof v === "boolean";
102
854
  /**
103
- * convert a saved ComfyUI workflow.json (litegraph format) into the api.json
104
- * (prompt format) ComfyUI's POST /prompt takes.
105
- * Handles: muted nodes, Note/Reroute/PrimitiveNode virtual nodes (reroutes
106
- * unwrapped, primitives inlined into their consumers), widget-value offsets
107
- * (incl. the phantom `control_after_generate` value after seeds).
855
+ * convert a normalized workflow (CanonicalWorkflow — see parseWorkflowJson)
856
+ * into the api.json (prompt format) ComfyUI's POST /prompt takes.
857
+ * Handles: muted nodes (skipped, consumers resolve unconnected), bypassed
858
+ * nodes (mode 4: link resolution walks through to the first type-matching
859
+ * input), Note/MarkdownNote/Reroute/PrimitiveNode virtual nodes (reroutes
860
+ * unwrapped, primitives inlined into their consumers), widget values both
861
+ * positional (with the phantom `control_after_generate` offset after seeds)
862
+ * and named (object-form widgets_values + subgraph promotion overrides —
863
+ * named wins, but a live link wins over both). Widget-ness is decided from
864
+ * the input CONFIG (inputWidgetKind.ts): V3 string-spelled widget types
865
+ * (COMBO options, dynamic combos, autogrow containers, socketless customs)
866
+ * and 2024-era enums go through ONE classifier; a positional array shorter
867
+ * than the schema's widget list fills schema defaults, never throws
868
+ * (agent/architecture.md owns both decisions).
108
869
  */
109
870
  const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
110
871
  const prompt = {};
111
872
  const LOG = opts.verbose ? (...args) => console.log("[🔥] converter:", ...args) : () => {};
112
873
  const PRIMITIVE_VALUES = {};
113
- for (const node of workflow.nodes) if (node.type === "PrimitiveNode") {
114
- const widgetValues = node.widgets_values;
115
- if (widgetValues == null || widgetValues.length === 0) throw new Error(`PrimitiveNode#${node.id} has no widget values`);
116
- PRIMITIVE_VALUES[node.id] = widgetValues[0];
874
+ for (const node of workflow.nodes) {
875
+ if (node.type !== "PrimitiveNode") continue;
876
+ if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
877
+ else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
117
878
  }
118
879
  for (const node of workflow.nodes) {
119
- if (node.isVirtualNode) continue;
120
- if (node.mode === 2) continue;
121
- if (node.type === "Reroute") continue;
122
- if (node.type === "Note") continue;
123
- if (node.type === "PrimitiveNode") continue;
880
+ if (isNeverExecuted(node)) continue;
881
+ if (node.mode !== "normal") continue;
124
882
  const inputs = {};
125
- const fieldNamesWithLinks = new Set((node.inputs ?? []).map((i) => i.name));
883
+ const fieldNamesPresent = new Set(node.inputs.map((i) => i.name));
126
884
  const nodeSchema_ = schema.nodesByNameInComfy[node.type];
127
- if (nodeSchema_ == null) throw new UnknownCustomNode(node);
885
+ if (nodeSchema_ == null) throw new WorkflowConvertError("unknown-node", `node ${node.id}(${node.type}) has no schema on this host; a custom node is missing`, node);
128
886
  const nodeSchema = nodeSchema_;
129
887
  let offset = 0;
130
- const inputsInNodeJSON = node.inputs ?? [];
888
+ const positional = node.widgets.positional;
889
+ const named = node.widgets.named;
890
+ const widgetFallback = /* @__PURE__ */ new Map();
891
+ const inputsInNodeJSON = node.inputs;
131
892
  const inputsInNodeSchema = nodeSchema.inputs;
893
+ /** arrays ride wrapped (a bare 2-list is a link server-side); objects pass only in lax (custom-widget) domains */
894
+ const toPromptValue = (value, p) => {
895
+ if (value == null) return null;
896
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
897
+ if (Array.isArray(value)) return { __value__: value };
898
+ if (!p.strict && isRecord(value)) return value;
899
+ throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}) has an invalid widget value for "${p.promptName}": ${JSON.stringify(value)}`, node);
900
+ };
901
+ /** named wins, then positional cursor; filled=true when both miss (caller falls back to the schema default) */
902
+ const resolveWidgetValue = (p) => {
903
+ let value;
904
+ let has = false;
905
+ if (Object.hasOwn(named, p.promptName)) {
906
+ value = named[p.promptName];
907
+ has = true;
908
+ } else if (offset < positional.length) {
909
+ value = positional[offset];
910
+ has = true;
911
+ }
912
+ if (positional.length > 0) offset += p.consumes;
913
+ return {
914
+ value,
915
+ filled: !has
916
+ };
917
+ };
918
+ const consumePlainWidget = (p) => {
919
+ const r = resolveWidgetValue({
920
+ promptName: p.promptName,
921
+ consumes: p.consumes
922
+ });
923
+ const raw = r.filled ? defaultValueForWidget({
924
+ type: p.typeName,
925
+ opts: p.opts,
926
+ enumValues: p.enumValues ?? schema.knownUnionByName.get(p.typeName)?.values
927
+ }) : r.value;
928
+ const value = toPromptValue(raw, {
929
+ promptName: p.promptName,
930
+ strict: p.strict
931
+ });
932
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.promptName} = ${JSON.stringify(value)} (schema-default fill)`);
933
+ if (p.linkedInput?.link != null) widgetFallback.set(p.promptName, value);
934
+ else inputs[p.promptName] = value;
935
+ };
936
+ /** key consumed first, then the SELECTED branch inline, recursively (backend get_finalized_class_inputs) */
937
+ const consumeDynamicCombo = (p) => {
938
+ const r = resolveWidgetValue({
939
+ promptName: p.path,
940
+ consumes: 1
941
+ });
942
+ const key = r.filled ? p.defaultKey : r.value;
943
+ if (typeof key !== "string") throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic combo "${p.path}" key is not a string: ${JSON.stringify(key)}`, node);
944
+ const opt = p.options.find((o) => o.key === key);
945
+ if (opt == null) throw new WorkflowConvertError("unknown-dynamic-combo-option", `node ${node.id}(${node.type}): "${key}" is not an option of dynamic combo "${p.path}" (options: ${p.options.map((o) => o.key).join(", ")})`, node);
946
+ if (r.filled) LOG(`${node.type}#${node.id}.${p.path} = ${key} (schema-default fill)`);
947
+ inputs[p.path] = key;
948
+ for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
949
+ };
950
+ const consumeBranchInput = (subPath, sub) => {
951
+ const kind = classifyWidgetInput({
952
+ name: sub.name,
953
+ type: sub.type,
954
+ opts: sub.opts
955
+ });
956
+ if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
957
+ if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
958
+ path: subPath,
959
+ options: kind.options,
960
+ defaultKey: kind.defaultKey
961
+ });
962
+ const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
963
+ consumePlainWidget({
964
+ promptName: subPath,
965
+ typeName: typeof sub.type === "string" ? sub.type : "COMBO",
966
+ opts: sub.opts,
967
+ consumes: kind.consumes,
968
+ strict: kind.strictValues,
969
+ enumValues: inlineEnum,
970
+ linkedInput: inputsInNodeJSON.find((i) => i.name === subPath)
971
+ });
972
+ };
132
973
  for (const field of inputsInNodeSchema) {
133
974
  const input = inputsInNodeJSON.find((i) => i.name === field.nameInComfy);
134
- const MUST_CONSUME = input?.type ? howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) : howManyWidgetValuesForThisSchemaType(field);
135
- if (MUST_CONSUME > 0) {
136
- if (node.widgets_values == null) throw new Error(`node ${node.id}(${node.type}) has no widgets_values but "${field.nameInComfy}" needs one`);
137
- if (node.widgets_values.length < offset + 1) throw new Error(`node ${node.id}(${node.type}) has not enough widgets_values for "${field.nameInComfy}"`);
138
- const _value = node.widgets_values[offset];
139
- LOG(`${node.type}#${node.id}.${field.nameInComfy} = ${_value} (widget, consumes ${MUST_CONSUME})`);
140
- if (!isValidValue(_value)) throw new Error(`node ${node.id}(${node.type}) has an invalid widget value for "${field.nameInComfy}": ${JSON.stringify(_value)}`);
141
- inputs[field.nameInComfy] = _value;
142
- offset += MUST_CONSUME;
143
- } else if (!fieldNamesWithLinks.has(field.nameInComfy)) {
144
- if (field.required) throw new Error(`node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`);
975
+ let kind = classifySchemaInput(field);
976
+ if (kind.kind === "slot" && input?.widgetName != null) kind = {
977
+ kind: "widget",
978
+ consumes: howManyWidgetValuesForThisInputType(input.type, field.nameInComfy) === 2 ? 2 : 1,
979
+ strictValues: true
980
+ };
981
+ if (kind.kind === "widget") consumePlainWidget({
982
+ promptName: field.nameInComfy,
983
+ typeName: field.typeName,
984
+ opts: field.opts,
985
+ consumes: kind.consumes,
986
+ strict: kind.strictValues,
987
+ linkedInput: input
988
+ });
989
+ else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
990
+ path: field.nameInComfy,
991
+ options: kind.options,
992
+ defaultKey: kind.defaultKey
993
+ });
994
+ else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
995
+ const iname = `${field.nameInComfy}.${instName}`;
996
+ if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
997
+ }
998
+ else if (!fieldNamesPresent.has(field.nameInComfy)) {
999
+ if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
145
1000
  }
146
1001
  }
147
1002
  const getParentNode = (linkId) => {
148
- const link = workflow.links.find((link) => link[0] === linkId);
149
- if (link == null) throw new Error(`Node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`);
150
- const parentId = link[1];
151
- const parentNode = workflow.nodes.find((n) => n.id === parentId);
152
- if (parentNode == null) throw new Error(`link ${linkId} references a non-existent parent node ${parentId}`);
1003
+ const link = workflow.links.find((link) => link.id === linkId);
1004
+ if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1005
+ const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1006
+ if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
153
1007
  return {
154
1008
  node: parentNode,
155
1009
  link
156
1010
  };
157
1011
  };
158
- INPT: for (const ipt of node.inputs ?? []) {
159
- if (howManyWidgetValuesForThisInputType(ipt.type, ipt.name) > 0) continue;
1012
+ const pickBypassInput = (p) => {
1013
+ const sameSlot = p.inputs[p.outSlot];
1014
+ if (p.consumerType === "*" || p.consumerType === "") return sameSlot ?? p.inputs[0] ?? null;
1015
+ if (sameSlot != null && linkTypeMatches(sameSlot.type, p.outputType) && linkTypeMatches(sameSlot.type, p.consumerType)) return sameSlot;
1016
+ const exact = p.inputs.find((i) => i.type === p.consumerType);
1017
+ if (exact != null) return exact;
1018
+ return p.inputs.find((i) => linkTypeMatches(i.type, p.outputType) && linkTypeMatches(i.type, p.consumerType)) ?? null;
1019
+ };
1020
+ const resolveThroughParents = (startLink, consumerType) => {
1021
+ const visited = /* @__PURE__ */ new Set();
1022
+ let linkId = startLink;
1023
+ let effectiveType = consumerType;
1024
+ while (true) {
1025
+ const parent = getParentNode(linkId);
1026
+ if (visited.has(parent.node.id)) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}): link resolution loops through node ${parent.node.id}`, node);
1027
+ visited.add(parent.node.id);
1028
+ if (parent.node.type === "Reroute") {
1029
+ const rerouteIn = parent.node.inputs[0]?.link;
1030
+ if (rerouteIn == null) return {
1031
+ kind: "unconnected",
1032
+ reason: "reroute chain ends on an empty slot"
1033
+ };
1034
+ linkId = rerouteIn;
1035
+ continue;
1036
+ }
1037
+ if (parent.node.mode === "muted") return {
1038
+ kind: "unconnected",
1039
+ reason: `parent ${parent.node.id}(${parent.node.type}) is muted`
1040
+ };
1041
+ if (parent.node.mode === "bypassed") {
1042
+ const outputType = parent.node.outputs[parent.link.originSlot]?.type ?? parent.link.type;
1043
+ const through = pickBypassInput({
1044
+ inputs: parent.node.inputs,
1045
+ outSlot: parent.link.originSlot,
1046
+ outputType,
1047
+ consumerType: effectiveType
1048
+ });
1049
+ if (through?.link == null) return {
1050
+ kind: "unconnected",
1051
+ reason: `bypassed parent ${parent.node.id}(${parent.node.type}) has no connected ${effectiveType} input to pass through`
1052
+ };
1053
+ linkId = through.link;
1054
+ effectiveType = through.type;
1055
+ continue;
1056
+ }
1057
+ if (parent.node.type === "PrimitiveNode") {
1058
+ if (!(parent.node.id in PRIMITIVE_VALUES)) return {
1059
+ kind: "unconnected",
1060
+ reason: `PrimitiveNode#${parent.node.id} has no widget value`
1061
+ };
1062
+ return {
1063
+ kind: "primitive",
1064
+ nodeId: parent.node.id
1065
+ };
1066
+ }
1067
+ return {
1068
+ kind: "link",
1069
+ nodeId: parent.node.id,
1070
+ slot: parent.link.originSlot
1071
+ };
1072
+ }
1073
+ };
1074
+ for (const ipt of node.inputs) {
160
1075
  if (ipt.link == null) {
161
- LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (fine when optional)`);
1076
+ LOG(`${node.type}#${node.id}.${ipt.name}: empty input slot (widget-backed or optional)`);
162
1077
  continue;
163
1078
  }
164
- let parent = getParentNode(ipt.link);
165
- let max = 100;
166
- while (parent != null && parent.node.type === "Reroute" && max-- > 0) {
167
- const firstParentInput = parent.node.inputs?.[0];
168
- if (firstParentInput?.link == null) {
169
- LOG(`${node.type}#${node.id}.${ipt.name}: reroute chain ends on an empty slot`);
170
- continue INPT;
171
- }
172
- parent = getParentNode(firstParentInput.link);
1079
+ const resolved = resolveThroughParents(ipt.link, ipt.type);
1080
+ if (resolved.kind === "primitive") {
1081
+ const pv = PRIMITIVE_VALUES[resolved.nodeId];
1082
+ if (!isPromptScalar(pv)) throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): PrimitiveNode#${resolved.nodeId} value is not a scalar: ${JSON.stringify(pv)}`, node);
1083
+ inputs[ipt.name] = pv;
1084
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${pv} (inlined primitive)`);
1085
+ continue;
1086
+ }
1087
+ if (resolved.kind === "link") {
1088
+ LOG(`${node.type}#${node.id}.${ipt.name} = [${resolved.nodeId}, ${resolved.slot}] (link)`);
1089
+ inputs[ipt.name] = [String(resolved.nodeId), resolved.slot];
1090
+ continue;
173
1091
  }
174
- if (parent == null) throw new Error(`no parent found for ${node.id}.${ipt.name}`);
175
- if (parent.node.type === "PrimitiveNode") {
176
- inputs[ipt.name] = PRIMITIVE_VALUES[parent.node.id];
177
- LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (inlined primitive)`);
1092
+ if (widgetFallback.has(ipt.name)) {
1093
+ inputs[ipt.name] = widgetFallback.get(ipt.name) ?? null;
1094
+ LOG(`${node.type}#${node.id}.${ipt.name} = ${inputs[ipt.name]} (widget fallback, ${resolved.reason})`);
178
1095
  continue;
179
1096
  }
180
- LOG(`${node.type}#${node.id}.${ipt.name} = [${parent.node.id}, ${parent.link[2]}] (link)`);
181
- inputs[ipt.name] = [String(parent.node.id), parent.link[2]];
1097
+ if (inputsInNodeSchema.find((f) => f.nameInComfy === ipt.name)?.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${ipt.name}" resolves unconnected (${resolved.reason}) and no widget value covers it`, node);
1098
+ LOG(`${node.type}#${node.id}.${ipt.name}: resolves unconnected (${resolved.reason})`);
182
1099
  }
183
1100
  prompt[String(node.id)] = {
184
1101
  inputs,
@@ -187,14 +1104,6 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
187
1104
  }
188
1105
  return prompt;
189
1106
  };
190
- function isValidValue(value) {
191
- if (value == null) return true;
192
- if (typeof value === "string") return true;
193
- if (typeof value === "number") return true;
194
- if (typeof value === "boolean") return true;
195
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number") return true;
196
- return false;
197
- }
198
1107
  //#endregion
199
1108
  //#region src/errors/InvalidPromptError.ts
200
1109
  var InvalidPromptError = class extends Error {
@@ -543,24 +1452,6 @@ var ComfyWorkflowBuilder = class {
543
1452
  }
544
1453
  };
545
1454
  //#endregion
546
- //#region src/utils/bang.ts
547
- /** assertNotNull */
548
- const bang = (x, msg = "") => {
549
- if (x == null) {
550
- console.error(`[🔴] BANG FAILED`, msg);
551
- throw new Error("bang: " + (msg ?? "no message"));
552
- }
553
- return x;
554
- };
555
- //#endregion
556
- //#region src/litegraph/LiteGraphLinkID.ts
557
- const asLiteGraphLinkID = (id) => id;
558
- arktype.type.number.atLeast(0).as();
559
- //#endregion
560
- //#region src/litegraph/LiteGraphSlotIndex.ts
561
- const asLiteGraphSlotIndex = (id) => id;
562
- arktype.type.number.atLeast(0).as();
563
- //#endregion
564
1455
  //#region src/litegraph/convertFlowToLiteGraphJSON.ts
565
1456
  const convertFlowToLiteGraphJSON = (graph) => {
566
1457
  const ctx = new LiteGraphCtx(graph);
@@ -573,7 +1464,7 @@ const convertFlowToLiteGraphJSON = (graph) => {
573
1464
  const n = xx.liteGraphNode;
574
1465
  n.pos[0] = bang(xx.comfyNode.x);
575
1466
  n.pos[1] = bang(xx.comfyNode.y);
576
- for (const o of n.outputs) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
1467
+ for (const o of n.outputs ?? []) o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0]);
577
1468
  }
578
1469
  return {
579
1470
  last_node_id,
@@ -1058,7 +1949,7 @@ var ComfyExecution = class {
1058
1949
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
1059
1950
  const promptMeta = this.workflow.data.metadata?.[promptNodeID];
1060
1951
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
1061
- const imgUrl = this.host.getServerHostHTTP() + "/view?" + new URLSearchParams(comfyImageInfo).toString();
1952
+ const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
1062
1953
  const sf = this.saveFormat;
1063
1954
  let absPath = comfyts.resolveFromOutput((0, pathe.join)(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename));
1064
1955
  if (sf?.format && sf.format !== "raw") {
@@ -1068,10 +1959,7 @@ var ComfyExecution = class {
1068
1959
  (0, node_fs.mkdirSync)((0, pathe.dirname)(absPath), { recursive: true });
1069
1960
  let img;
1070
1961
  if (sf && sf.format !== "raw") {
1071
- const buff = await (await fetch(imgUrl, {
1072
- headers: { "Content-Type": "image/png" },
1073
- method: "GET"
1074
- })).arrayBuffer();
1962
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1075
1963
  let textChunk = {};
1076
1964
  try {
1077
1965
  const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
@@ -1094,10 +1982,7 @@ var ComfyExecution = class {
1094
1982
  }
1095
1983
  });
1096
1984
  } else {
1097
- const buff = await (await fetch(imgUrl, {
1098
- headers: { "Content-Type": "image/png" },
1099
- method: "GET"
1100
- })).arrayBuffer();
1985
+ const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
1101
1986
  const uint8arr = new Uint8Array(buff);
1102
1987
  (0, node_fs.writeFileSync)(absPath, uint8arr);
1103
1988
  img = new MediaImage({
@@ -1469,9 +2354,9 @@ var ComfyWorkflow = class {
1469
2354
  comfy_ts_version: comfyts.version
1470
2355
  } }
1471
2356
  };
1472
- const promptEndpoint = `${this.host.getServerHostHTTP()}/prompt`;
1473
- const res = await fetch(promptEndpoint, {
2357
+ const res = await this.host.fetch("/prompt", {
1474
2358
  method: "POST",
2359
+ headers: { "Content-Type": "application/json" },
1475
2360
  body: JSON.stringify(out)
1476
2361
  });
1477
2362
  const promptInfo = softValidate(PromptInfo_ark, await res.json());
@@ -2337,8 +3222,7 @@ var ComfyManager = class {
2337
3222
  }
2338
3223
  };
2339
3224
  this.fetchPost = async (endpoint, body, validator) => {
2340
- const url = this.host.getServerHostHTTP() + endpoint;
2341
- const response = await fetch(url, {
3225
+ const response = await this.host.fetch(endpoint, {
2342
3226
  method: "POST",
2343
3227
  headers: { "Content-Type": "application/json" },
2344
3228
  body: JSON.stringify(body)
@@ -2349,16 +3233,14 @@ var ComfyManager = class {
2349
3233
  return status;
2350
3234
  };
2351
3235
  this.fetchGetJSON = async (endpoint, validator) => {
2352
- const url = this.host.getServerHostHTTP() + endpoint;
2353
- const response = await fetch(url);
3236
+ const response = await this.host.fetch(endpoint);
2354
3237
  if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
2355
3238
  const jsonResult = await response.json();
2356
3239
  if (validator) return softValidate(validator, jsonResult);
2357
3240
  return jsonResult;
2358
3241
  };
2359
3242
  this.fetchGetText = async (endopint) => {
2360
- const url = this.host.getServerHostHTTP() + endopint;
2361
- return await (await fetch(url)).text();
3243
+ return await (await this.host.fetch(endopint)).text();
2362
3244
  };
2363
3245
  }
2364
3246
  get registry() {
@@ -2376,11 +3258,10 @@ var ComfyManager = class {
2376
3258
  no();
2377
3259
  }
2378
3260
  if (abortCtrl) abortCtrl.abort();
2379
- const url = this.host.getServerHostHTTP();
2380
3261
  abortCtrl = new AbortController();
2381
3262
  try {
2382
3263
  console.log(` - trying...`);
2383
- await fetch(url, { signal: abortCtrl.signal });
3264
+ await this.host.fetch("/", { signal: abortCtrl.signal }, { apiPrefix: false });
2384
3265
  clearInterval(interval);
2385
3266
  yes(true);
2386
3267
  } catch {}
@@ -2418,8 +3299,7 @@ var ComfyUploader = class {
2418
3299
  if (p.type) form.set("type", p.type);
2419
3300
  if (p.override ?? true) form.set("override", "true");
2420
3301
  if (p.subfolder) form.set("subfolder", p.subfolder);
2421
- const uploadURL = this.host.getServerHostHTTP() + "/upload/image";
2422
- const resp = await fetch(uploadURL, {
3302
+ const resp = await this.host.fetch("/upload/image", {
2423
3303
  method: "POST",
2424
3304
  body: form
2425
3305
  });
@@ -2435,6 +3315,51 @@ var ComfyUploader = class {
2435
3315
  }
2436
3316
  };
2437
3317
  //#endregion
3318
+ //#region src/host/hostUrl.ts
3319
+ /** exactly ONE of `url` or the legacy `host`+`port` (+`https?`) spelling */
3320
+ function parseHostBase(p) {
3321
+ const hasLegacy = p.host != null || p.port != null || p.https != null;
3322
+ if (p.url != null && hasLegacy) throw new Error(`host '${p.id}': give either url OR host/port/https, not both spellings at once`);
3323
+ if (p.url == null) {
3324
+ if (p.host == null || p.port == null) throw new Error(`host '${p.id}': needs either url, or host AND port (got host=${p.host}, port=${p.port})`);
3325
+ return {
3326
+ scheme: p.https ? "https" : "http",
3327
+ host: p.host,
3328
+ port: p.port,
3329
+ basePath: ""
3330
+ };
3331
+ }
3332
+ let parsed;
3333
+ try {
3334
+ parsed = new URL(p.url);
3335
+ } catch {
3336
+ throw new Error(`host '${p.id}': unparseable url '${p.url}'`);
3337
+ }
3338
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`host '${p.id}': url scheme must be http or https, got '${parsed.protocol}' in '${p.url}'`);
3339
+ if (parsed.search !== "" || parsed.hash !== "") throw new Error(`host '${p.id}': url must be a plain base (no ?query or #hash), got '${p.url}'`);
3340
+ const scheme = parsed.protocol === "https:" ? "https" : "http";
3341
+ const port = parsed.port !== "" ? Number(parsed.port) : scheme === "https" ? 443 : 80;
3342
+ const basePath = parsed.pathname.replace(/\/+$/, "");
3343
+ return {
3344
+ scheme,
3345
+ host: parsed.hostname,
3346
+ port,
3347
+ basePath
3348
+ };
3349
+ }
3350
+ /** http(s) base, port omitted when it is the scheme default */
3351
+ function renderHttpBase(p) {
3352
+ return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3353
+ }
3354
+ /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3355
+ function renderWsUrl(p) {
3356
+ return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3357
+ }
3358
+ function renderPort(p) {
3359
+ const schemeDefault = p.scheme === "https" ? 443 : 80;
3360
+ return p.port === schemeDefault ? "" : `:${p.port}`;
3361
+ }
3362
+ //#endregion
2438
3363
  //#region src/host/ResilientWebsocket.ts
2439
3364
  var ResilientWebSocketClient = class {
2440
3365
  addInfo(msg) {
@@ -2479,7 +3404,7 @@ var ResilientWebSocketClient = class {
2479
3404
  this.addInfo("Previous WebSocket discarded");
2480
3405
  prevWS.close();
2481
3406
  }
2482
- const ws$1 = new ws.default(this.url);
3407
+ const ws$1 = new ws.default(this.url, { headers: this.options.headers?.() });
2483
3408
  ws$1.binaryType = "arraybuffer";
2484
3409
  this.currentWS = ws$1;
2485
3410
  if (this.options.onMessage) ws$1.onmessage = (event) => {
@@ -3089,6 +4014,17 @@ var DefinedWorkflow = class {
3089
4014
  };
3090
4015
  //#endregion
3091
4016
  //#region src/host/ComfyHost.ts
4017
+ /** auth failure with a SPECIFIC meaning (per the Comfy Cloud error table):
4018
+ * 401 invalid/missing key · 402 insufficient credits · 429 subscription inactive
4019
+ * (or plain rate limiting on non-cloud hosts). The key value never appears here. */
4020
+ var ComfyHostAuthError = class extends Error {
4021
+ constructor(code, hostId, message) {
4022
+ super(message);
4023
+ this.code = code;
4024
+ this.hostId = hostId;
4025
+ this.name = "ComfyHostAuthError";
4026
+ }
4027
+ };
3092
4028
  var ComfyHost = class {
3093
4029
  constructor(data) {
3094
4030
  this.data = data;
@@ -3144,7 +4080,48 @@ var ComfyHost = class {
3144
4080
  return this.manager.installPlugin(customNode);
3145
4081
  };
3146
4082
  this.getWSUrl = () => {
3147
- return `${this.data.https ? "wss" : "ws"}://${this.data.host}:${this.data.port}/ws`;
4083
+ return renderWsUrl(this.base);
4084
+ };
4085
+ this._apiPrefix = null;
4086
+ this.fetch = async (route, init = {}, p = {}) => {
4087
+ const base = this.getServerHostHTTP();
4088
+ const headers = new Headers(init.headers);
4089
+ for (const [k, v] of Object.entries(this.authHeaders())) headers.set(k, v);
4090
+ const send = (prefixed) => fetch(`${base}${prefixed ? "/api" : ""}${route}`, {
4091
+ ...init,
4092
+ headers
4093
+ });
4094
+ const missed = (res) => res.status === 404 || res.status === 405;
4095
+ let res;
4096
+ if (p.apiPrefix === false) res = await send(false);
4097
+ else if (this._apiPrefix != null) {
4098
+ res = await send(this._apiPrefix);
4099
+ if (missed(res)) {
4100
+ const alt = await send(!this._apiPrefix);
4101
+ if (!missed(alt)) res = alt;
4102
+ }
4103
+ } else {
4104
+ res = await send(true);
4105
+ if (missed(res)) {
4106
+ const bare = await send(false);
4107
+ if (!missed(bare)) {
4108
+ this._apiPrefix = false;
4109
+ res = bare;
4110
+ }
4111
+ } else this._apiPrefix = true;
4112
+ }
4113
+ this.throwOnAuthError(res, route);
4114
+ return res;
4115
+ };
4116
+ this.fetchFile = async (route) => {
4117
+ const res = await this.fetch(route, { redirect: "manual" });
4118
+ if (res.status >= 300 && res.status < 400) {
4119
+ const location = res.headers.get("location");
4120
+ if (location == null) throw new Error(`GET ${route} on host '${this.data.id}' redirected (${res.status}) without a Location`);
4121
+ res.body?.cancel();
4122
+ return fetch(new URL(location, this.getServerHostHTTP()));
4123
+ }
4124
+ return res;
3148
4125
  };
3149
4126
  this.schemaRetrievalLogs = [];
3150
4127
  this.resetLog = () => {
@@ -3160,7 +4137,8 @@ var ComfyHost = class {
3160
4137
  return new DefinedWorkflow(this, spec);
3161
4138
  };
3162
4139
  this.importWorkflowJson = (json, p = {}) => {
3163
- const apiJson = convertLiteGraphToPrompt(this.schema, json);
4140
+ const canonical = parseWorkflowJson(json);
4141
+ const apiJson = convertLiteGraphToPrompt(this.schema, canonical);
3164
4142
  return this.importApiJson(apiJson, p);
3165
4143
  };
3166
4144
  this.importApiJson = (json, p = {}) => {
@@ -3200,13 +4178,12 @@ var ComfyHost = class {
3200
4178
  this.schemaUpdateResult = null;
3201
4179
  this._schemaFromCache = null;
3202
4180
  this.postJSON_ = async (route, body) => {
3203
- const base = this.getServerHostHTTP();
3204
- for (const url of [`${base}/api${route}`, `${base}${route}`]) if ((await fetch(url, {
4181
+ const res = await this.fetch(route, {
3205
4182
  method: "POST",
3206
4183
  headers: { "Content-Type": "application/json" },
3207
4184
  body: JSON.stringify(body)
3208
- })).ok) return;
3209
- throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`);
4185
+ });
4186
+ if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
3210
4187
  };
3211
4188
  this.clearQueue = () => {
3212
4189
  return this.postJSON_("/queue", { clear: true });
@@ -3215,7 +4192,7 @@ var ComfyHost = class {
3215
4192
  return this.postJSON_("/interrupt", {});
3216
4193
  };
3217
4194
  this.fetchRawLogs = async () => {
3218
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`);
4195
+ const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
3219
4196
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
3220
4197
  const json = await res.json();
3221
4198
  const checked = WsMsgLogsData_ark(json);
@@ -3226,25 +4203,23 @@ var ComfyHost = class {
3226
4203
  return json;
3227
4204
  };
3228
4205
  this.subscribeLogs = async (p) => {
3229
- const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
4206
+ const res = await this.fetch("/internal/logs/subscribe", {
3230
4207
  method: "PATCH",
3231
4208
  headers: { "Content-Type": "application/json" },
3232
4209
  body: JSON.stringify({
3233
4210
  enabled: p.enabled,
3234
4211
  clientId: p.clientId
3235
4212
  })
3236
- });
4213
+ }, { apiPrefix: false });
3237
4214
  if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`);
3238
4215
  };
3239
4216
  this.fetchJSON_ = async (route) => {
3240
4217
  const base = this.getServerHostHTTP();
3241
- for (const url of [`${base}/api${route}`, `${base}${route}`]) {
3242
- const res = await fetch(url, { method: "GET" });
3243
- if (!res.ok) continue;
3244
- if (!(res.headers.get("content-type") ?? "").includes("json")) continue;
3245
- return await res.json();
3246
- }
3247
- throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`);
4218
+ const res = await this.fetch(route);
4219
+ if (!res.ok) throw new Error(`GET ${route} failed on ${base}: ${res.status}`);
4220
+ const contentType = res.headers.get("content-type") ?? "";
4221
+ if (!contentType.includes("json")) throw new Error(`GET ${route} on ${base} answered '${contentType || "no content-type"}' instead of json`);
4222
+ return await res.json();
3248
4223
  };
3249
4224
  this.fetchAndUpdateSchema = async () => {
3250
4225
  try {
@@ -3287,7 +4262,9 @@ var ComfyHost = class {
3287
4262
  this.onSession = null;
3288
4263
  this.onLogs = null;
3289
4264
  this.comfySessionId = "temp";
4265
+ this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
3290
4266
  this.status = null;
4267
+ this.base = parseHostBase(this.data);
3291
4268
  /** folder where file related to the host config will be cached */
3292
4269
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3293
4270
  if (!(0, node_fs.existsSync)(this.cacheFolder)) {
@@ -3313,7 +4290,19 @@ var ComfyHost = class {
3313
4290
  return value;
3314
4291
  }
3315
4292
  getServerHostHTTP() {
3316
- return `${this.data.https ? "https" : "http"}://${this.data.host}:${this.data.port}`;
4293
+ return renderHttpBase(this.base);
4294
+ }
4295
+ /** extra headers + X-API-Key, for every http request AND the ws upgrade */
4296
+ authHeaders() {
4297
+ const out = {};
4298
+ if (this.data.headers != null) Object.assign(out, this.data.headers);
4299
+ if (this.data.apiKey != null) out["X-API-Key"] = this.data.apiKey;
4300
+ return out;
4301
+ }
4302
+ throwOnAuthError(res, route) {
4303
+ if (res.status === 401) throw new ComfyHostAuthError(401, this.data.id, this.data.apiKey != null ? `host '${this.data.id}': 401 on ${route} — API key invalid or expired` : `host '${this.data.id}': 401 on ${route} — host requires authentication, no apiKey configured`);
4304
+ if (res.status === 402) throw new ComfyHostAuthError(402, this.data.id, `host '${this.data.id}': 402 on ${route} — insufficient credits`);
4305
+ if (res.status === 429) throw new ComfyHostAuthError(429, this.data.id, `host '${this.data.id}': 429 on ${route} — subscription inactive or rate limited`);
3317
4306
  }
3318
4307
  get isConnected() {
3319
4308
  return this.ws?.isOpen ?? false;
@@ -3329,6 +4318,7 @@ var ComfyHost = class {
3329
4318
  this._readyReject = null;
3330
4319
  }
3331
4320
  async writeSDKToDisk() {
4321
+ if (this.data.sdkAutoWrite === false) return;
3332
4322
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3333
4323
  if ((0, node_fs.existsSync)(this.sdkDTSPath) && (0, node_fs.readFileSync)(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3334
4324
  await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
@@ -3375,6 +4365,7 @@ var ComfyHost = class {
3375
4365
  },
3376
4366
  onMessage: (e) => this.onMessage(e),
3377
4367
  url: () => this.getWSUrl(),
4368
+ headers: () => this.authHeaders(),
3378
4369
  onClose: () => {
3379
4370
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3380
4371
  }
@@ -3388,8 +4379,16 @@ var ComfyHost = class {
3388
4379
  this._isUpdatingSchema = v;
3389
4380
  }
3390
4381
  /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
3391
- * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
4382
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once.
4383
+ * A MISSING cache degrades LOUDLY to the base types instead of failing the
4384
+ * module import (a fresh consumer project has no cache yet — the bundled
4385
+ * examples must still open in the TUI; run() fetches the real schema through
4386
+ * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3392
4387
  loadSchemaFromCache() {
4388
+ if (this._schemaFromCache == null && !(0, node_fs.existsSync)(this.comfyJSONPath)) {
4389
+ logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
4390
+ return Promise.resolve();
4391
+ }
3393
4392
  this._schemaFromCache ??= (async () => {
3394
4393
  const object_info_json = comfyts.readJSON_(this.comfyJSONPath);
3395
4394
  const embeddings_json = comfyts.readJSON_(this.embeddingsPath, []);
@@ -3420,40 +4419,23 @@ var ComfyHost = class {
3420
4419
  onMessage(e) {
3421
4420
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
3422
4421
  if (e.data instanceof ArrayBuffer) {
3423
- const eventType = new DataView(e.data).getUint32(0);
3424
- const buffer = e.data.slice(4);
3425
- switch (eventType) {
3426
- case 1: {
3427
- const imageType = new DataView(e.data).getUint32(4);
3428
- let imageMime;
3429
- switch (imageType) {
3430
- case 1:
3431
- imageMime = "image/jpeg";
3432
- break;
3433
- case 2:
3434
- imageMime = "image/png";
3435
- break;
3436
- default:
3437
- imageMime = "image/jpeg";
3438
- break;
3439
- }
3440
- const imageBytes = buffer.slice(4);
3441
- const imageBlob = new Blob([imageBytes], { type: imageMime });
3442
- const imagePreview = URL.createObjectURL(imageBlob);
3443
- this.latentPreview = {
3444
- blob: imageBlob,
3445
- url: imagePreview,
3446
- receivedAt: Date.now(),
3447
- promptID: this.activePromptID
3448
- };
3449
- this.onLatentPreview?.({
3450
- bytes: new Uint8Array(imageBytes),
3451
- mime: imageMime,
3452
- promptID: this.activePromptID
3453
- });
3454
- break;
3455
- }
3456
- default: throw new Error(`Unknown binary websocket message of type ${eventType}`);
4422
+ const frame = parseBinaryWsFrame(e.data);
4423
+ if (frame.kind === "preview") {
4424
+ const imageBlob = new Blob([frame.bytes], { type: frame.mime });
4425
+ this.latentPreview = {
4426
+ blob: imageBlob,
4427
+ url: URL.createObjectURL(imageBlob),
4428
+ receivedAt: Date.now(),
4429
+ promptID: this.activePromptID
4430
+ };
4431
+ this.onLatentPreview?.({
4432
+ bytes: frame.bytes,
4433
+ mime: frame.mime,
4434
+ promptID: this.activePromptID
4435
+ });
4436
+ } else if (frame.kind === "unknown" && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
4437
+ this._unknownBinaryFrameTypes.add(frame.eventType);
4438
+ console.error(`🔴 unknown binary ws frame type ${frame.eventType} from host ${this.data.id} — ignored`);
3457
4439
  }
3458
4440
  return;
3459
4441
  }
@@ -4063,7 +5045,11 @@ var ComfyTS = class ComfyTS {
4063
5045
  host(data) {
4064
5046
  const existing = this.hosts.get(data.id);
4065
5047
  if (existing != null) {
4066
- if (existing.data.host !== data.host || existing.data.port !== data.port || existing.data.https !== data.https) throw new Error(`host id '${data.id}' already registered at ${existing.data.host}:${existing.data.port} — refusing ${data.host}:${data.port}`);
5048
+ const incoming = parseHostBase(data);
5049
+ const cur = existing.base;
5050
+ const sameBase = cur.scheme === incoming.scheme && cur.host === incoming.host && cur.port === incoming.port && cur.basePath === incoming.basePath;
5051
+ const sameAuth = existing.data.apiKey == null === (data.apiKey == null);
5052
+ if (!sameBase || !sameAuth) throw new Error(`host id '${data.id}' already registered at ${renderHttpBase(cur)}${existing.data.apiKey != null ? " (authed)" : ""} — refusing ${renderHttpBase(incoming)}${data.apiKey != null ? " (authed)" : ""}`);
4067
5053
  return existing;
4068
5054
  }
4069
5055
  const created = new ComfyHost(data);
@@ -4125,6 +5111,7 @@ function loraTag(name, strength = 1, clipStrength) {
4125
5111
  exports.ChoiceVar = ChoiceVar;
4126
5112
  exports.ComfyExecution = ComfyExecution;
4127
5113
  exports.ComfyHost = ComfyHost;
5114
+ exports.ComfyHostAuthError = ComfyHostAuthError;
4128
5115
  exports.ComfyManager = ComfyManager;
4129
5116
  exports.ComfyNode = ComfyNode;
4130
5117
  exports.ComfyNodeOutput = ComfyNodeOutput;
@@ -4148,6 +5135,8 @@ exports.SeedVar = SeedVar;
4148
5135
  exports.SizeVar = SizeVar;
4149
5136
  exports.TextVar = TextVar;
4150
5137
  exports.ToggleVar = ToggleVar;
5138
+ exports.WorkflowConvertError = WorkflowConvertError;
5139
+ exports.WorkflowNormalizeError = WorkflowNormalizeError;
4151
5140
  exports.__FAIL = __FAIL;
4152
5141
  exports.__OK = __OK;
4153
5142
  exports.activeLoras = activeLoras;
@@ -4159,10 +5148,16 @@ exports.auto = auto;
4159
5148
  exports.auto_ = auto_;
4160
5149
  exports.codegenSDK = codegenSDK;
4161
5150
  exports.convertFlowToLiteGraphJSON = convertFlowToLiteGraphJSON;
5151
+ exports.convertLiteGraphToPrompt = convertLiteGraphToPrompt;
4162
5152
  exports.getLoraKeyword = getLoraKeyword;
4163
5153
  exports.hostIdToNamespace = hostIdToNamespace;
4164
5154
  exports.isTuiActive = isTuiActive;
4165
5155
  exports.loraTag = loraTag;
5156
+ exports.normalizeWorkflow = normalizeWorkflow;
5157
+ exports.parseHostBase = parseHostBase;
5158
+ exports.parseWorkflowJson = parseWorkflowJson;
5159
+ exports.renderHttpBase = renderHttpBase;
5160
+ exports.renderWsUrl = renderWsUrl;
4166
5161
  exports.resultFailure = resultFailure;
4167
5162
  exports.resultSuccess = resultSuccess;
4168
5163
  exports.setLoraKeyword = setLoraKeyword;