comfy-ts 1.2.0 → 1.3.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 (42) hide show
  1. package/README.md +40 -0
  2. package/dist/DefinedWorkflow-gpknV-5f.js +686 -0
  3. package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
  4. package/dist/DraftsSt-DmA0jWGl.js +434 -0
  5. package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
  6. package/dist/cli.js +15 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +132 -21
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +5 -0
  11. package/dist/index.d.ts +23 -18
  12. package/dist/index.js +132 -21
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-Bn6yIJB0.js +638 -0
  15. package/dist/run-serve-Bn6yIJB0.js.map +1 -0
  16. package/dist/{run-tui-BAdizWsO.js → run-tui-BtjaOXRh.js} +244 -440
  17. package/dist/run-tui-BtjaOXRh.js.map +1 -0
  18. package/dist/{state-BYbxDgfr.js → state-DKCPy105.js} +130 -698
  19. package/dist/state-DKCPy105.js.map +1 -0
  20. package/package.json +3 -2
  21. package/src/cli/comfy-ts-cli.ts +15 -5
  22. package/src/cli/serve/ServeApp.ts +378 -0
  23. package/src/cli/serve/applyVarPayload.ts +119 -0
  24. package/src/cli/serve/describeVar.ts +74 -0
  25. package/src/cli/serve/run-serve.ts +169 -0
  26. package/src/cli/tui/components/StatusBar.tsx +1 -0
  27. package/src/cli/tui/components/TreePanel.tsx +17 -3
  28. package/src/cli/tui/components/TuiApp.tsx +7 -2
  29. package/src/cli/tui/components/VarsPanel.tsx +67 -34
  30. package/src/cli/tui/imageClipboard.ts +39 -0
  31. package/src/cli/tui/listWindow.ts +36 -0
  32. package/src/cli/tui/state/ExecSt.ts +48 -0
  33. package/src/cli/tui/state/TreeSt.ts +25 -0
  34. package/src/cli/tui/state/TuiSt.ts +34 -0
  35. package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
  36. package/src/runner/ComfyExecution.ts +21 -4
  37. package/src/runner/outputPath.ts +75 -0
  38. package/src/sdk-generator/inputWidgetKind.ts +50 -11
  39. package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
  40. package/src/vars/ComfyVars.ts +8 -0
  41. package/dist/run-tui-BAdizWsO.js.map +0 -1
  42. package/dist/state-BYbxDgfr.js.map +0 -1
@@ -0,0 +1,686 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "pathe";
3
+ import { imageMeta } from "image-meta";
4
+ import { homedir } from "node:os";
5
+ import { action, makeObservable, observable, runInAction } from "mobx";
6
+ //#region src/utils/log.ts
7
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
8
+ const logInfo = (msg) => {
9
+ if (!isQuiet()) console.log(msg);
10
+ };
11
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
12
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
13
+ //#endregion
14
+ //#region src/utils/extractErrorMessage.ts
15
+ /** Extracts an error message from an exception stuff. */
16
+ const extractErrorMessage = (error) => {
17
+ if (error instanceof Error) return error.message;
18
+ if (error === null) return "null";
19
+ if (typeof error === "string") return error;
20
+ if (typeof error === "object") {
21
+ if ("message" in error && typeof error.message === "string") return error.message;
22
+ return JSON.stringify(error);
23
+ }
24
+ return String(error);
25
+ };
26
+ //#endregion
27
+ //#region src/vars/loraKeywords.ts
28
+ /**
29
+ * hand-assigned trigger keyword(s) per lora name — set via ⌃K in the TUI loras
30
+ * overlay, consumed by PromptVar's `loraKeywordsFrom` prefixing. Persisted at
31
+ * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
32
+ * and must survive a cache wipe). Observable map: overlay rows re-render on
33
+ * assignment. Keys are the RAW lora names (folder/file.safetensors).
34
+ */
35
+ const keywords = observable.map();
36
+ let loaded = false;
37
+ function filePath() {
38
+ return join(comfyts.baseFolder, "lora-keywords.json");
39
+ }
40
+ function loadOnce() {
41
+ if (loaded) return;
42
+ loaded = true;
43
+ const path = filePath();
44
+ if (!existsSync(path)) return;
45
+ try {
46
+ const raw = JSON.parse(readFileSync(path, "utf8"));
47
+ if (raw == null || typeof raw !== "object") return;
48
+ runInAction(() => {
49
+ for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
50
+ });
51
+ } catch (e) {
52
+ logError(`[loraKeywords] unreadable ${path}: ${String(e)}`);
53
+ }
54
+ }
55
+ function getLoraKeyword(name) {
56
+ loadOnce();
57
+ return keywords.get(name) ?? "";
58
+ }
59
+ /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
60
+ function setLoraKeyword(name, keyword) {
61
+ loadOnce();
62
+ const trimmed = keyword.trim();
63
+ runInAction(() => {
64
+ if (trimmed === "") keywords.delete(name);
65
+ else keywords.set(name, trimmed);
66
+ });
67
+ const path = filePath();
68
+ try {
69
+ mkdirSync(dirname(path), { recursive: true });
70
+ writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
71
+ } catch (e) {
72
+ logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
73
+ }
74
+ }
75
+ //#endregion
76
+ //#region src/vars/ComfyVars.ts
77
+ /**
78
+ * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
79
+ * time. They usually coincide — extend `ComfyVar<T>` for that. PromptVar is
80
+ * the one Out-specialized var (string in, PromptValue out); the split keeps
81
+ * outValue() cast-free.
82
+ */
83
+ var ComfyVarBase = class {
84
+ constructor(defaultValue, label) {
85
+ this.defaultValue = defaultValue;
86
+ this.label = label;
87
+ this.value = defaultValue;
88
+ makeObservable(this, {
89
+ value: observable,
90
+ set: action,
91
+ reset: action,
92
+ parse: action,
93
+ loadJSON: action
94
+ });
95
+ }
96
+ set(value) {
97
+ this.value = value;
98
+ return this;
99
+ }
100
+ /** what drafts persist for this var (subclasses may add fields, e.g. seed mode) */
101
+ toJSON() {
102
+ return this.value;
103
+ }
104
+ /**
105
+ * restore a value produced by toJSON() (drafts). The cast is sanctioned:
106
+ * drafts are our own round-trip, subclasses re-validate via set().
107
+ */
108
+ loadJSON(value) {
109
+ return this.set(value);
110
+ }
111
+ reset() {
112
+ this.value = this.defaultValue;
113
+ return this;
114
+ }
115
+ /** how the value renders in a var list */
116
+ display() {
117
+ return String(this.value);
118
+ }
119
+ /** the string the inline editor starts from (round-trips through parse) */
120
+ toEditBuffer() {
121
+ return String(this.value);
122
+ }
123
+ /** hook run after every DefinedWorkflow.run() (default no-op; SeedVar advances) */
124
+ afterRun() {}
125
+ };
126
+ /** the standard var: the graph consumes the stored value AS-IS (Out = T) */
127
+ var ComfyVar = class extends ComfyVarBase {
128
+ outValue() {
129
+ return this.value;
130
+ }
131
+ };
132
+ var TextVar = class extends ComfyVar {
133
+ constructor(..._args) {
134
+ super(..._args);
135
+ this.kind = "text";
136
+ }
137
+ parse(raw) {
138
+ this.set(raw);
139
+ return true;
140
+ }
141
+ };
142
+ const commentLineRe = /^\s*\/\//;
143
+ const negativeLineRe = /^\s*- (.*)$/;
144
+ /**
145
+ * prompt text with editor comforts, all resolved at BUILD time (the editor and
146
+ * drafts keep the raw text):
147
+ * - `//` lines are COMMENTS — stripped
148
+ * - `- ` lines are NEGATIVE prompt lines — removed from `.positive`,
149
+ * comma-joined into `.negative`
150
+ * - with `loraKeywordsFrom`, the ACTIVE loras' hand-assigned keywords
151
+ * (src/vars/loraKeywords.ts, ⌃K in the TUI) prefix `.positive` —
152
+ * `injectedKeywords()` is public so the TUI can PREVIEW the injection.
153
+ */
154
+ var PromptVar = class extends ComfyVarBase {
155
+ constructor(defaultValue, promptOpts = {}) {
156
+ super(defaultValue, promptOpts.label);
157
+ this.promptOpts = promptOpts;
158
+ this.kind = "text";
159
+ }
160
+ parse(raw) {
161
+ this.set(raw);
162
+ return true;
163
+ }
164
+ static isCommentLine(line) {
165
+ return commentLineRe.test(line);
166
+ }
167
+ static isNegativeLine(line) {
168
+ return negativeLineRe.test(line);
169
+ }
170
+ /** the keyword prefix the flag will inject (deduped, lora-list order) — the TUI previews this */
171
+ injectedKeywords() {
172
+ const src = this.promptOpts.loraKeywordsFrom;
173
+ if (src == null) return [];
174
+ return [...new Set(src.activeNames().map(getLoraKeyword).filter((k) => k !== ""))];
175
+ }
176
+ outValue() {
177
+ const pos = [];
178
+ const neg = [];
179
+ for (const line of this.value.split("\n")) {
180
+ if (commentLineRe.test(line)) continue;
181
+ const m = negativeLineRe.exec(line);
182
+ if (m != null) {
183
+ const text = (m[1] ?? "").trim();
184
+ if (text !== "") neg.push(text);
185
+ } else pos.push(line);
186
+ }
187
+ const body = pos.join("\n").trim();
188
+ const keywords = this.injectedKeywords();
189
+ return {
190
+ positive: keywords.length === 0 ? body : body === "" ? keywords.join(", ") : `${keywords.join(", ")}, ${body}`,
191
+ negative: neg.join(", ")
192
+ };
193
+ }
194
+ };
195
+ var IntVar = class extends ComfyVar {
196
+ constructor(defaultValue, opts = {}) {
197
+ super(defaultValue, opts.label);
198
+ this.opts = opts;
199
+ this.kind = "int";
200
+ }
201
+ set(value) {
202
+ const clamped = Math.round(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
203
+ return super.set(clamped);
204
+ }
205
+ parse(raw) {
206
+ const n = Number(raw);
207
+ if (Number.isNaN(n)) return false;
208
+ this.set(n);
209
+ return true;
210
+ }
211
+ };
212
+ var FloatVar = class extends ComfyVar {
213
+ constructor(defaultValue, opts = {}) {
214
+ super(defaultValue, opts.label);
215
+ this.opts = opts;
216
+ this.kind = "float";
217
+ }
218
+ set(value) {
219
+ return super.set(Math.min(this.opts.max ?? Infinity, Math.max(this.opts.min ?? -Infinity, value)));
220
+ }
221
+ parse(raw) {
222
+ const n = Number(raw);
223
+ if (Number.isNaN(n)) return false;
224
+ this.set(n);
225
+ return true;
226
+ }
227
+ };
228
+ /**
229
+ * a seed is a MODE + a number. `value` stays a plain number (what the graph
230
+ * consumes); `mode` decides how it advances after each run (afterRun()):
231
+ * `= 12` fixed · `+ 0` auto-increment · `- 0` auto-decrement · `? 0` random.
232
+ * The number shown is always the seed the NEXT run will use.
233
+ */
234
+ var SeedVar = class extends ComfyVar {
235
+ constructor(defaultValue = 0, label) {
236
+ super(defaultValue, label);
237
+ this.kind = "seed";
238
+ this.mode = "=";
239
+ makeObservable(this, {
240
+ mode: observable,
241
+ setMode: action,
242
+ randomize: action,
243
+ advance: action
244
+ });
245
+ }
246
+ setMode(mode) {
247
+ this.mode = mode;
248
+ return this;
249
+ }
250
+ randomize() {
251
+ return this.set(Math.floor(Math.random() * 2 ** 32));
252
+ }
253
+ set(value) {
254
+ return super.set(Math.max(0, Math.floor(value)));
255
+ }
256
+ /** move the seed to what the NEXT run should use, per mode */
257
+ advance() {
258
+ if (this.mode === "+") return this.set(this.value + 1);
259
+ if (this.mode === "-") return this.set(this.value - 1);
260
+ if (this.mode === "?") return this.randomize();
261
+ return this;
262
+ }
263
+ afterRun() {
264
+ this.advance();
265
+ }
266
+ /** mode is part of the seed's state: a reset must not keep a caller's `?`/`+` alive
267
+ * ('=' is the construction default; drafts restore their own mode via loadJSON) */
268
+ reset() {
269
+ this.setMode("=");
270
+ return super.reset();
271
+ }
272
+ /** parse `+` `- 12` `= 5` `?` or a bare number (=> fixed). Keeps the current number when none given */
273
+ parse(raw) {
274
+ const m = raw.trim().match(/^([+\-=?])?\s*(\d+)?$/);
275
+ if (m == null) return false;
276
+ const modeChar = m[1];
277
+ const numStr = m[2];
278
+ if (modeChar == null && numStr == null) return false;
279
+ this.setMode(modeChar == null ? "=" : modeChar);
280
+ if (numStr != null) this.set(Number(numStr));
281
+ return true;
282
+ }
283
+ display() {
284
+ return `${this.mode} ${this.value}`;
285
+ }
286
+ toEditBuffer() {
287
+ return `${this.mode} ${this.value}`;
288
+ }
289
+ toJSON() {
290
+ return {
291
+ mode: this.mode,
292
+ value: this.value
293
+ };
294
+ }
295
+ loadJSON(value) {
296
+ if (typeof value === "number") return this.set(value);
297
+ if (value != null && typeof value === "object") {
298
+ const o = value;
299
+ if (o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?") this.setMode(o.mode);
300
+ if (typeof o.value === "number") this.set(o.value);
301
+ }
302
+ return this;
303
+ }
304
+ };
305
+ var ToggleVar = class extends ComfyVar {
306
+ constructor(..._args2) {
307
+ super(..._args2);
308
+ this.kind = "toggle";
309
+ }
310
+ toggle() {
311
+ return this.set(!this.value);
312
+ }
313
+ parse(raw) {
314
+ if (raw !== "true" && raw !== "false") return false;
315
+ this.set(raw === "true");
316
+ return true;
317
+ }
318
+ display() {
319
+ return this.value ? "ON" : "OFF";
320
+ }
321
+ };
322
+ var ChoiceVar = class extends ComfyVar {
323
+ constructor(choices, defaultValue, label) {
324
+ super(defaultValue, label);
325
+ this.choices = choices;
326
+ this.kind = "choice";
327
+ }
328
+ next(delta = 1) {
329
+ const nextIx = (this.choices.indexOf(this.value) + delta + this.choices.length) % this.choices.length;
330
+ return this.set(this.choices[nextIx] ?? this.value);
331
+ }
332
+ parse(raw) {
333
+ const hit = this.choices.find((c) => c === raw);
334
+ if (hit == null) return false;
335
+ this.set(hit);
336
+ return true;
337
+ }
338
+ };
339
+ /**
340
+ * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
341
+ * against the host's loras at define time (DefinedWorkflow calls bindHost),
342
+ * or feed it host discovery (`host.schema.getLoras(regex?)`) directly; never
343
+ * a hardcoded inventory. Selection is empty by default.
344
+ */
345
+ var LorasVar = class LorasVar extends ComfyVar {
346
+ constructor(optionsSource, initial = {}, label) {
347
+ super(initial, label);
348
+ this.optionsSource = optionsSource;
349
+ this.kind = "loras";
350
+ this.prev = {};
351
+ this.resolvedOptions = null;
352
+ }
353
+ get options() {
354
+ if (!(this.optionsSource instanceof RegExp)) return this.optionsSource;
355
+ if (this.resolvedOptions == null) throw new Error(`v.loras(${String(this.optionsSource)}) is host-bound — it only works inside defineWorkflow({ vars }) (pass a name list otherwise)`);
356
+ return this.resolvedOptions;
357
+ }
358
+ /** DefinedWorkflow binds the host at define time: a RegExp source resolves here.
359
+ * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
360
+ * values of the SAME object_info enum the generated E_LoraName union comes from */
361
+ bindHost(host) {
362
+ if (!(this.optionsSource instanceof RegExp)) return;
363
+ this.resolvedOptions = host.schema.getLoras(this.optionsSource);
364
+ }
365
+ get names() {
366
+ return [...this.options];
367
+ }
368
+ /** loras currently ON (PromptVar keyword prefixing consumes this) */
369
+ activeNames() {
370
+ return this.names.filter((n) => this.isOn(n));
371
+ }
372
+ isOn(name) {
373
+ const s = this.value[name];
374
+ return s != null && s !== false;
375
+ }
376
+ toggleItem(name) {
377
+ const cur = this.value[name];
378
+ if (cur == null || cur === false) return this.set({
379
+ ...this.value,
380
+ [name]: this.prev[name] ?? true
381
+ });
382
+ this.prev[name] = cur;
383
+ return this.set({
384
+ ...this.value,
385
+ [name]: false
386
+ });
387
+ }
388
+ /** step both strengths by delta (true becomes 1 first); no-op when off */
389
+ adjustItem(name, delta) {
390
+ const cur = this.value[name];
391
+ if (cur == null || cur === false) return this;
392
+ const step = (n) => Math.max(0, Math.round((n + delta) * 100) / 100);
393
+ const next = Array.isArray(cur) ? [step(cur[0]), step(cur[1])] : step(cur === true ? 1 : cur);
394
+ return this.set({
395
+ ...this.value,
396
+ [name]: next
397
+ });
398
+ }
399
+ /** compact per-item strength label for lists */
400
+ strengthLabel(name) {
401
+ const s = this.value[name];
402
+ if (s == null || s === false) return "";
403
+ if (s === true) return "1.00";
404
+ if (Array.isArray(s)) return `m:${s[0].toFixed(2)} c:${s[1].toFixed(2)}`;
405
+ return s.toFixed(2);
406
+ }
407
+ parse(raw) {
408
+ try {
409
+ const parsed = JSON.parse(raw);
410
+ if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) return false;
411
+ this.set(parsed);
412
+ return true;
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
417
+ /** short human name: subfolder + extension stripped */
418
+ static shortName(name) {
419
+ return (name.split(/[\\/]/).pop() ?? name).replace(/\.safetensors$/, "");
420
+ }
421
+ /** tick (true) or untick (false) every lora in `names` (default: all options) */
422
+ setAll(on, names = this.options) {
423
+ const next = { ...this.value };
424
+ for (const name of names) {
425
+ const cur = next[name];
426
+ if (on) {
427
+ if (cur == null || cur === false) next[name] = this.prev[name] ?? true;
428
+ } else {
429
+ if (cur != null && cur !== false) this.prev[name] = cur;
430
+ next[name] = false;
431
+ }
432
+ }
433
+ return this.set(next);
434
+ }
435
+ display() {
436
+ const on = this.activeNames();
437
+ if (on.length === 0) return `(0/${this.options.length}) none`;
438
+ return `(${on.length}/${this.options.length}) ${on.map((n) => LorasVar.shortName(n)).join(", ")}`;
439
+ }
440
+ };
441
+ /** SDXL-style ~1MP buckets, multiples of 64 — safe for most latent models */
442
+ const DEFAULT_SIZE_PRESETS = [
443
+ {
444
+ label: "1:1 square",
445
+ width: 1024,
446
+ height: 1024
447
+ },
448
+ {
449
+ label: "4:3 landscape",
450
+ width: 1152,
451
+ height: 896
452
+ },
453
+ {
454
+ label: "3:4 portrait",
455
+ width: 896,
456
+ height: 1152
457
+ },
458
+ {
459
+ label: "3:2 landscape",
460
+ width: 1216,
461
+ height: 832
462
+ },
463
+ {
464
+ label: "2:3 portrait",
465
+ width: 832,
466
+ height: 1216
467
+ },
468
+ {
469
+ label: "16:9 widescreen",
470
+ width: 1344,
471
+ height: 768
472
+ },
473
+ {
474
+ label: "9:16 tall",
475
+ width: 768,
476
+ height: 1344
477
+ }
478
+ ];
479
+ /** width/height picker: presets + free `WxH` entry + optionally the LIVE
480
+ * size of a linked image var (his ask 2026-07-30: the widget shows
481
+ * `WxH size of image '<name>'` as a pickable row) */
482
+ var SizeVar = class extends ComfyVar {
483
+ constructor(defaultValue = {
484
+ width: 1024,
485
+ height: 1024
486
+ }, presets = DEFAULT_SIZE_PRESETS, label, imageVar) {
487
+ super(defaultValue, label);
488
+ this.presets = presets;
489
+ this.imageVar = imageVar;
490
+ this.kind = "size";
491
+ }
492
+ /** current dimensions of the linked image var — null when no link, unset
493
+ * path, or an unreadable/undecodable file (those errors belong to the
494
+ * image var itself, the size row simply disappears) */
495
+ imageSize() {
496
+ const iv = this.imageVar;
497
+ if (iv == null || iv.value === "") return null;
498
+ try {
499
+ const abs = iv.absPath();
500
+ const meta = imageMeta(new Uint8Array(readFileSync(abs)));
501
+ if (meta.width == null || meta.height == null) return null;
502
+ return {
503
+ width: meta.width,
504
+ height: meta.height,
505
+ name: basename(abs)
506
+ };
507
+ } catch {
508
+ return null;
509
+ }
510
+ }
511
+ /** accepts '1024x768' / '1024×768' / a preset label */
512
+ parse(raw) {
513
+ const m = raw.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/);
514
+ if (m != null) {
515
+ this.set({
516
+ width: Number(m[1]),
517
+ height: Number(m[2])
518
+ });
519
+ return true;
520
+ }
521
+ const preset = this.presets.find((p) => p.label === raw.trim());
522
+ if (preset != null) {
523
+ this.set({
524
+ width: preset.width,
525
+ height: preset.height
526
+ });
527
+ return true;
528
+ }
529
+ return false;
530
+ }
531
+ display() {
532
+ const { width, height } = this.value;
533
+ const hit = this.presets.find((p) => p.width === width && p.height === height);
534
+ return `${width}×${height}${hit ? ` (${hit.label})` : ""}`;
535
+ }
536
+ };
537
+ const DEFAULT_IMAGE_EXTENSIONS = [
538
+ "png",
539
+ "jpg",
540
+ "jpeg",
541
+ "webp",
542
+ "gif"
543
+ ];
544
+ /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
545
+ var ImageVarEmptyError = class extends Error {
546
+ constructor(varName) {
547
+ super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`);
548
+ this.varName = varName;
549
+ }
550
+ };
551
+ /** trim + expand a leading `~/` — every ImageVar write funnels through this */
552
+ function expandUserPath(raw) {
553
+ const trimmed = raw.trim();
554
+ return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
555
+ }
556
+ /**
557
+ * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
558
+ * drafts persist it verbatim (toJSON = the string), hand-editable in the
559
+ * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,
560
+ * so a build never runs on a silent placeholder. The TUI opens the image
561
+ * picker overlay for kind 'image'.
562
+ */
563
+ var ImageVar = class extends ComfyVar {
564
+ constructor(defaultValue, opts = {}) {
565
+ super(expandUserPath(defaultValue), opts.label);
566
+ this.opts = opts;
567
+ this.kind = "image";
568
+ }
569
+ /** what the picker lists (lowercase, no dots) */
570
+ get extensions() {
571
+ return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS;
572
+ }
573
+ set(value) {
574
+ return super.set(expandUserPath(value));
575
+ }
576
+ parse(raw) {
577
+ this.set(raw);
578
+ return true;
579
+ }
580
+ isSet() {
581
+ return this.value !== "";
582
+ }
583
+ emptyError() {
584
+ return new ImageVarEmptyError(this.name ?? this.label ?? "image");
585
+ }
586
+ /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */
587
+ absPath() {
588
+ if (!this.isSet()) throw this.emptyError();
589
+ if (isAbsolute(this.value)) return this.value;
590
+ return resolve(this.opts.folder ?? process.cwd(), this.value);
591
+ }
592
+ /** empty = unset: the build fails LOUD here (varValues calls outValue) */
593
+ outValue() {
594
+ if (!this.isSet()) throw this.emptyError();
595
+ return this.value;
596
+ }
597
+ display() {
598
+ if (!this.isSet()) return "(unset) pick a file";
599
+ const home = homedir();
600
+ return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
601
+ }
602
+ };
603
+ /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
604
+ const v = {
605
+ text: (defaultValue, label) => new TextVar(defaultValue, label),
606
+ prompt: (defaultValue, opts = {}) => new PromptVar(defaultValue, opts),
607
+ int: (defaultValue, opts = {}) => new IntVar(defaultValue, opts),
608
+ float: (defaultValue, opts = {}) => new FloatVar(defaultValue, opts),
609
+ seed: (defaultValue = 0, label) => new SeedVar(defaultValue, label),
610
+ toggle: (defaultValue, label) => new ToggleVar(defaultValue, label),
611
+ choice: (choices, defaultValue, label) => new ChoiceVar(choices, defaultValue, label),
612
+ loras: (options, initial = {}, label) => new LorasVar(options, initial, label),
613
+ size: (defaultValue, opts = {}) => new SizeVar(defaultValue, opts.presets, opts.label, opts.image),
614
+ image: (defaultValue, opts = {}) => new ImageVar(defaultValue, opts)
615
+ };
616
+ function varValues(vars) {
617
+ const out = {};
618
+ for (const [k, varDef] of Object.entries(vars)) out[k] = varDef.outValue();
619
+ return out;
620
+ }
621
+ //#endregion
622
+ //#region src/vars/DefinedWorkflow.ts
623
+ /** type predicate (not a cast): a VarsSpec is a plain record, never callable */
624
+ function isVarsThunk(vars) {
625
+ return typeof vars === "function";
626
+ }
627
+ /**
628
+ * a re-runnable workflow definition: `build` re-executes per run with the
629
+ * current var values, so every run gets a fresh, deterministic graph.
630
+ */
631
+ var DefinedWorkflow = class {
632
+ constructor(host, spec) {
633
+ this.host = host;
634
+ this.spec = spec;
635
+ this.lastWorkflow = null;
636
+ this.lastExecution = null;
637
+ this.vars = isVarsThunk(spec.vars) ? spec.vars(v) : spec.vars;
638
+ for (const [key, varDef] of this.entries()) {
639
+ varDef.name = key;
640
+ varDef.bindHost?.(this.host);
641
+ }
642
+ }
643
+ /** [name, var] pairs, for drivers that enumerate the knobs */
644
+ entries() {
645
+ return Object.entries(this.vars);
646
+ }
647
+ /**
648
+ * build a fresh graph from the CURRENT var values (no send). `p.advance`
649
+ * (set by run()) fires each var's afterRun() right after snapshotting the
650
+ * values — atomically, before any await — so the graph uses this run's seed
651
+ * while the var moves to the next (queued runs get distinct seeds; a bare
652
+ * build() for copy/export never advances). `p.host` substitutes the host
653
+ * the graph is built against (TUI host override): node/model availability
654
+ * there surfaces as workflow.problems / server validation, by design.
655
+ */
656
+ async build(p = {}) {
657
+ const wf = (p.host ?? this.host).workflow({ id: this.spec.id });
658
+ const values = varValues(this.vars);
659
+ if (p.advance) for (const varDef of Object.values(this.vars)) varDef.afterRun();
660
+ await this.spec.build(wf.builder, values, wf);
661
+ this.lastWorkflow = wf;
662
+ return wf;
663
+ }
664
+ /** build a fresh graph from the current var values, send it, wait for outputs.
665
+ * connects first (idempotent) — modules can import offline from the schema cache.
666
+ * `settings.host` runs against THAT host instead of the defining one. */
667
+ async run(settings = {}) {
668
+ const host = settings.host ?? this.host;
669
+ await host.connect();
670
+ const execution = await (await this.build({
671
+ advance: true,
672
+ host
673
+ })).run({
674
+ saveFormat: settings.saveFormat,
675
+ idMode: settings.idMode,
676
+ log: settings.log,
677
+ onProgress: settings.onProgress
678
+ });
679
+ this.lastExecution = execution;
680
+ return execution;
681
+ }
682
+ };
683
+ //#endregion
684
+ export { logError as _, ImageVarEmptyError as a, PromptVar as c, TextVar as d, ToggleVar as f, isQuiet as g, extractErrorMessage as h, ImageVar as i, SeedVar as l, setLoraKeyword as m, ChoiceVar as n, IntVar as o, getLoraKeyword as p, FloatVar as r, LorasVar as s, DefinedWorkflow as t, SizeVar as u, logInfo as v, logSuccess as y };
685
+
686
+ //# sourceMappingURL=DefinedWorkflow-gpknV-5f.js.map