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56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// @ts-check
/// <reference path="../../web/types/litegraph.d.ts" />

/**
 * @typedef { import("../../web/scripts/app")["app"] } app
 * @typedef { import("../../web/types/litegraph") } LG
 * @typedef { import("../../web/types/litegraph").IWidget } IWidget
 * @typedef { import("../../web/types/litegraph").ContextMenuItem } ContextMenuItem
 * @typedef { import("../../web/types/litegraph").INodeInputSlot } INodeInputSlot
 * @typedef { import("../../web/types/litegraph").INodeOutputSlot } INodeOutputSlot
 * @typedef { InstanceType<LG["LGraphNode"]> & { widgets?: Array<IWidget> } } LGNode
 * @typedef { (...args: EzOutput[] | [...EzOutput[], Record<string, unknown>]) => EzNode } EzNodeFactory
 */

export class EzConnection {
	/** @type { app } */
	app;
	/** @type { InstanceType<LG["LLink"]> } */
	link;

	get originNode() {
		return new EzNode(this.app, this.app.graph.getNodeById(this.link.origin_id));
	}

	get originOutput() {
		return this.originNode.outputs[this.link.origin_slot];
	}

	get targetNode() {
		return new EzNode(this.app, this.app.graph.getNodeById(this.link.target_id));
	}

	get targetInput() {
		return this.targetNode.inputs[this.link.target_slot];
	}

	/**
	 * @param { app } app
	 * @param { InstanceType<LG["LLink"]> } link
	 */
	constructor(app, link) {
		this.app = app;
		this.link = link;
	}

	disconnect() {
		this.targetInput.disconnect();
	}
}

export class EzSlot {
	/** @type { EzNode } */
	node;
	/** @type { number } */
	index;

	/**
	 * @param { EzNode } node
	 * @param { number } index
	 */
	constructor(node, index) {
		this.node = node;
		this.index = index;
	}
}

export class EzInput extends EzSlot {
	/** @type { INodeInputSlot } */
	input;

	/**
	 * @param { EzNode } node
	 * @param { number } index
	 * @param { INodeInputSlot } input
	 */
	constructor(node, index, input) {
		super(node, index);
		this.input = input;
	}

	get connection() {
		const link = this.node.node.inputs?.[this.index]?.link;
		if (link == null) {
			return null;
		}
		return new EzConnection(this.node.app, this.node.app.graph.links[link]);
	}

	disconnect() {
		this.node.node.disconnectInput(this.index);
	}
}

export class EzOutput extends EzSlot {
	/** @type { INodeOutputSlot } */
	output;

	/**
	 * @param { EzNode } node
	 * @param { number } index
	 * @param { INodeOutputSlot } output
	 */
	constructor(node, index, output) {
		super(node, index);
		this.output = output;
	}

	get connections() {
		return (this.node.node.outputs?.[this.index]?.links ?? []).map(
			(l) => new EzConnection(this.node.app, this.node.app.graph.links[l])
		);
	}

	/**
	 * @param { EzInput } input
	 */
	connectTo(input) {
		if (!input) throw new Error("Invalid input");

		/**
		 * @type { LG["LLink"] | null }
		 */
		const link = this.node.node.connect(this.index, input.node.node, input.index);
		if (!link) {
			const inp = input.input;
			const inName = inp.name || inp.label || inp.type;
			throw new Error(
				`Connecting from ${input.node.node.type}#${input.node.id}[${inName}#${input.index}] -> ${this.node.node.type}#${this.node.id}[${
					this.output.name ?? this.output.type
				}#${this.index}] failed.`
			);
		}
		return link;
	}
}

export class EzNodeMenuItem {
	/** @type { EzNode } */
	node;
	/** @type { number } */
	index;
	/** @type { ContextMenuItem } */
	item;

	/**
	 * @param { EzNode } node
	 * @param { number } index
	 * @param { ContextMenuItem } item
	 */
	constructor(node, index, item) {
		this.node = node;
		this.index = index;
		this.item = item;
	}

	call(selectNode = true) {
		if (!this.item?.callback) throw new Error(`Menu Item ${this.item?.content ?? "[null]"} has no callback.`);
		if (selectNode) {
			this.node.select();
		}
		return this.item.callback.call(this.node.node, undefined, undefined, undefined, undefined, this.node.node);
	}
}

export class EzWidget {
	/** @type { EzNode } */
	node;
	/** @type { number } */
	index;
	/** @type { IWidget } */
	widget;

	/**
	 * @param { EzNode } node
	 * @param { number } index
	 * @param { IWidget } widget
	 */
	constructor(node, index, widget) {
		this.node = node;
		this.index = index;
		this.widget = widget;
	}

	get value() {
		return this.widget.value;
	}

	set value(v) {
		this.widget.value = v;
		this.widget.callback?.call?.(this.widget, v)
	}

	get isConvertedToInput() {
		// @ts-ignore : this type is valid for converted widgets
		return this.widget.type === "converted-widget";
	}

	getConvertedInput() {
		if (!this.isConvertedToInput) throw new Error(`Widget ${this.widget.name} is not converted to input.`);

		return this.node.inputs.find((inp) => inp.input["widget"]?.name === this.widget.name);
	}

	convertToWidget() {
		if (!this.isConvertedToInput)
			throw new Error(`Widget ${this.widget.name} cannot be converted as it is already a widget.`);
		this.node.menu[`Convert ${this.widget.name} to widget`].call();
	}

	convertToInput() {
		if (this.isConvertedToInput)
			throw new Error(`Widget ${this.widget.name} cannot be converted as it is already an input.`);
		this.node.menu[`Convert ${this.widget.name} to input`].call();
	}
}

export class EzNode {
	/** @type { app } */
	app;
	/** @type { LGNode } */
	node;

	/**
	 * @param { app } app
	 * @param { LGNode } node
	 */
	constructor(app, node) {
		this.app = app;
		this.node = node;
	}

	get id() {
		return this.node.id;
	}

	get inputs() {
		return this.#makeLookupArray("inputs", "name", EzInput);
	}

	get outputs() {
		return this.#makeLookupArray("outputs", "name", EzOutput);
	}

	get widgets() {
		return this.#makeLookupArray("widgets", "name", EzWidget);
	}

	get menu() {
		return this.#makeLookupArray(() => this.app.canvas.getNodeMenuOptions(this.node), "content", EzNodeMenuItem);
	}

	get isRemoved() {
		return !this.app.graph.getNodeById(this.id);
	}

	select(addToSelection = false) {
		this.app.canvas.selectNode(this.node, addToSelection);
	}

	// /**
	//  * @template { "inputs" | "outputs" } T
	//  * @param { T } type
	//  * @returns { Record<string, type extends "inputs" ? EzInput : EzOutput> & (type extends "inputs" ? EzInput [] : EzOutput[]) }
	//  */
	// #getSlotItems(type) {
	// 	// @ts-ignore : these items are correct
	// 	return (this.node[type] ?? []).reduce((p, s, i) => {
	// 		if (s.name in p) {
	// 			throw new Error(`Unable to store input ${s.name} on array as name conflicts.`);
	// 		}
	// 		// @ts-ignore
	// 		p.push((p[s.name] = new (type === "inputs" ? EzInput : EzOutput)(this, i, s)));
	// 		return p;
	// 	}, Object.assign([], { $: this }));
	// }

	/**
	 * @template { { new(node: EzNode, index: number, obj: any): any } } T
	 * @param { "inputs" | "outputs" | "widgets" | (() => Array<unknown>) } nodeProperty
	 * @param { string } nameProperty
	 * @param { T } ctor
	 * @returns { Record<string, InstanceType<T>> & Array<InstanceType<T>> }
	 */
	#makeLookupArray(nodeProperty, nameProperty, ctor) {
		const items = typeof nodeProperty === "function" ? nodeProperty() : this.node[nodeProperty];
		// @ts-ignore
		return (items ?? []).reduce((p, s, i) => {
			if (!s) return p;

			const name = s[nameProperty];
			const item = new ctor(this, i, s);
			// @ts-ignore
			p.push(item);
			if (name) {
				// @ts-ignore
				if (name in p) {
					throw new Error(`Unable to store ${nodeProperty} ${name} on array as name conflicts.`);
				}
			}
			// @ts-ignore
			p[name] = item;
			return p;
		}, Object.assign([], { $: this }));
	}
}

export class EzGraph {
	/** @type { app } */
	app;

	/**
	 * @param { app } app
	 */
	constructor(app) {
		this.app = app;
	}

	get nodes() {
		return this.app.graph._nodes.map((n) => new EzNode(this.app, n));
	}

	clear() {
		this.app.graph.clear();
	}

	arrange() {
		this.app.graph.arrange();
	}

	stringify() {
		return JSON.stringify(this.app.graph.serialize(), undefined);
	}

	/**
	 * @param { number | LGNode | EzNode } obj
	 * @returns { EzNode }
	 */
	find(obj) {
		let match;
		let id;
		if (typeof obj === "number") {
			id = obj;
		} else {
			id = obj.id;
		}

		match = this.app.graph.getNodeById(id);

		if (!match) {
			throw new Error(`Unable to find node with ID ${id}.`);
		}

		return new EzNode(this.app, match);
	}

	/**
	 * @returns { Promise<void> }
	 */
	reload() {
		const graph = JSON.parse(JSON.stringify(this.app.graph.serialize()));
		return new Promise((r) => {
			this.app.graph.clear();
			setTimeout(async () => {
				await this.app.loadGraphData(graph);
				r();
			}, 10);
		});
	}

	/**
	 * @returns { Promise<{
	 * 	workflow: {},
	 * 	output: Record<string, {
	 * 		class_name: string,
	 * 		inputs: Record<string, [string, number] | unknown>
	 * }>}> }
	 */
	toPrompt() {
		// @ts-ignore
		return this.app.graphToPrompt();
	}
}

export const Ez = {
	/**
	 * Quickly build and interact with a ComfyUI graph
	 * @example
	 * const { ez, graph } = Ez.graph(app);
	 * graph.clear();
	 * const [model, clip, vae] = ez.CheckpointLoaderSimple().outputs;
	 * const [pos] = ez.CLIPTextEncode(clip, { text: "positive" }).outputs;
	 * const [neg] = ez.CLIPTextEncode(clip, { text: "negative" }).outputs;
	 * const [latent] = ez.KSampler(model, pos, neg, ...ez.EmptyLatentImage().outputs).outputs;
	 * const [image] = ez.VAEDecode(latent, vae).outputs;
	 * const saveNode = ez.SaveImage(image);
	 * console.log(saveNode);
	 * graph.arrange();
	 * @param { app } app
	 * @param { LG["LiteGraph"] } LiteGraph
	 * @param { LG["LGraphCanvas"] } LGraphCanvas
	 * @param { boolean } clearGraph
	 * @returns { { graph: EzGraph, ez: Record<string, EzNodeFactory> } }
	 */
	graph(app, LiteGraph = window["LiteGraph"], LGraphCanvas = window["LGraphCanvas"], clearGraph = true) {
		// Always set the active canvas so things work
		LGraphCanvas.active_canvas = app.canvas;

		if (clearGraph) {
			app.graph.clear();
		}

		// @ts-ignore : this proxy handles utility methods & node creation
		const factory = new Proxy(
			{},
			{
				get(_, p) {
					if (typeof p !== "string") throw new Error("Invalid node");
					const node = LiteGraph.createNode(p);
					if (!node) throw new Error(`Unknown node "${p}"`);
					app.graph.add(node);

					/**
					 * @param {Parameters<EzNodeFactory>} args
					 */
					return function (...args) {
						const ezNode = new EzNode(app, node);
						const inputs = ezNode.inputs;

						let slot = 0;
						for (const arg of args) {
							if (arg instanceof EzOutput) {
								arg.connectTo(inputs[slot++]);
							} else {
								for (const k in arg) {
									ezNode.widgets[k].value = arg[k];
								}
							}
						}

						return ezNode;
					};
				},
			}
		);

		return { graph: new EzGraph(app), ez: factory };
	},
};