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