comfy-ts 2.7.0 → 2.9.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.
- package/README.md +20 -13
- package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
- package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
- package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
- package/dist/LogsSt-DFxzQfDc.js.map +1 -0
- package/dist/cli.js +7 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +284 -35
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +125 -7
- package/dist/index.d.ts +125 -7
- package/dist/index.js +282 -37
- package/dist/index.js.map +1 -1
- package/dist/run-serve-_nrvJYyt.js +1948 -0
- package/dist/run-serve-_nrvJYyt.js.map +1 -0
- package/dist/{run-tui-JxlEbb_f.js → run-tui-BLEdTsOX.js} +106 -157
- package/dist/run-tui-BLEdTsOX.js.map +1 -0
- package/dist/serve-web.js +441 -72
- package/dist/{state-CaHeDL-0.js → state-BbgJeCe6.js} +180 -45
- package/dist/state-BbgJeCe6.js.map +1 -0
- package/dist/web.d.ts +185 -7
- package/dist/web.js +235 -36
- package/dist/web.js.map +1 -1
- package/examples/README.md +1 -0
- package/examples/comfy-cloud/sdk.d.ts +4066 -321
- package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
- package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
- package/examples/web/tsconfig.json +3 -0
- package/extra/README.md +32 -0
- package/extra/comfyui-textgen-stream/README.md +35 -0
- package/extra/comfyui-textgen-stream/__init__.py +166 -0
- package/extra/scripts/fetch_text_encoder.py +137 -0
- package/package.json +6 -3
- package/src/cli/comfy-ts-cli.ts +3 -1
- package/src/cli/serve/ServeApp.ts +754 -40
- package/src/cli/serve/applyVarPayload.ts +10 -3
- package/src/cli/serve/describeVar.ts +47 -7
- package/src/cli/serve/hostProtocol.ts +68 -0
- package/src/cli/serve/managerOnlyLoras.ts +27 -0
- package/src/cli/serve/run-serve.ts +35 -38
- package/src/cli/serve/serveSettings.ts +86 -0
- package/src/cli/serve/startupPrint.ts +111 -0
- package/src/cli/serve/web/api.ts +97 -1
- package/src/cli/serve/web/components/App.tsx +61 -22
- package/src/cli/serve/web/components/Gallery.tsx +306 -41
- package/src/cli/serve/web/components/Icon.tsx +160 -0
- package/src/cli/serve/web/components/PromptEnhancer.tsx +12 -9
- package/src/cli/serve/web/components/Sidebar.tsx +43 -19
- package/src/cli/serve/web/components/VarsForm.tsx +440 -91
- package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
- package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
- package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
- package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
- package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
- package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
- package/src/cli/serve/web/llm.ts +1 -1
- package/src/cli/serve/web/logWeb.ts +6 -0
- package/src/cli/serve/web/state/EnhancerSt.ts +8 -15
- package/src/cli/serve/web/state/FormSt.ts +74 -18
- package/src/cli/serve/web/state/RunSt.ts +22 -1
- package/src/cli/serve/web/state/WebSt.ts +814 -22
- package/src/cli/serve/web/state/host.ts +206 -0
- package/src/cli/serve/web/state/lightbox.ts +44 -0
- package/src/cli/serve/web/state/moduleTree.ts +52 -0
- package/src/cli/serve/web/state/payload.ts +44 -2
- package/src/cli/serve/web/state/urlSelection.ts +53 -0
- package/src/cli/serve/web/styles.ts +422 -57
- package/src/cli/serve/web/tsconfig.json +4 -0
- package/src/cli/tui/components/PickerOverlays.tsx +37 -0
- package/src/cli/tui/components/StatusBar.tsx +14 -1
- package/src/cli/tui/components/TuiApp.tsx +5 -2
- package/src/cli/tui/state/HostSt.ts +3 -2
- package/src/cli/tui/state/PickerSt.ts +48 -2
- package/src/cli/tui/state/TreeSt.ts +1 -1
- package/src/cli/tui/state/TuiSt.ts +2 -1
- package/src/coreExports.ts +8 -1
- package/src/graph/ComfyNode.ts +58 -1
- package/src/host/ComfyHost.ts +13 -2
- package/src/host/ComfyManager.ts +31 -13
- package/src/host/loraInfoCache.ts +35 -1
- package/src/host/loraManagerApi.ts +94 -0
- package/src/index.ts +2 -0
- package/src/promptEnhancers.ts +102 -0
- package/src/runner/ComfyExecution.ts +61 -6
- package/src/runner/ComfyWorkflow.ts +18 -4
- package/src/runner/ComfyWsApi.ts +3 -0
- package/src/runner/describePromptRejection.ts +34 -0
- package/src/sdk-generator/ComfySchema.ts +17 -4
- package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
- package/src/utils/ansi.ts +13 -0
- package/src/utils/matchesRegex.ts +13 -0
- package/src/utils/safeName.ts +29 -0
- package/src/utils/stringMap.ts +9 -0
- package/src/vars/ComfyVars.ts +61 -10
- package/src/vars/presets.ts +17 -0
- package/src/web.ts +12 -0
- package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
- package/dist/DraftsSt-dizp3VcC.js.map +0 -1
- package/dist/run-serve-D1Tsuru9.js +0 -1162
- package/dist/run-serve-D1Tsuru9.js.map +0 -1
- package/dist/run-tui-JxlEbb_f.js.map +0 -1
- package/dist/state-CaHeDL-0.js.map +0 -1
- package/src/cli/serve/promptEnhancers.ts +0 -69
- package/src/cli/serve/safeName.ts +0 -12
|
@@ -1,1162 +0,0 @@
|
|
|
1
|
-
import { C as loraPreviewMapFrom, S as loraKey, T as bang, _ as fetchLoraList, d as getLoraPreviewUrl, f as getLoraTriggerWords, h as refreshLoraInfoCacheIfChanged, u as getLoraDisplayName, v as fetchLoraPreviewBytes, w as extractErrorMessage } from "./DefinedWorkflow-BJgt5t0x.js";
|
|
2
|
-
import { c as findDefinedWorkflow, i as listDraftsForFile, n as draftKeyForFile, r as draftsDirForFile, u as scanCflowFiles } from "./DraftsSt-dizp3VcC.js";
|
|
3
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { basename, dirname, extname, join, resolve } from "pathe";
|
|
6
|
-
import { nanoid } from "nanoid";
|
|
7
|
-
import { createServer } from "node:http";
|
|
8
|
-
import { networkInterfaces } from "node:os";
|
|
9
|
-
//#region src/cli/serve/describeVar.ts
|
|
10
|
-
function rangeText(opts) {
|
|
11
|
-
if (opts.min == null && opts.max == null) return "";
|
|
12
|
-
return ` (${opts.min ?? "-∞"}..${opts.max ?? "∞"})`;
|
|
13
|
-
}
|
|
14
|
-
function describeVar(varDef) {
|
|
15
|
-
const base = {
|
|
16
|
-
kind: varDef.kind,
|
|
17
|
-
label: varDef.label,
|
|
18
|
-
default: varDef.defaultValue
|
|
19
|
-
};
|
|
20
|
-
switch (varDef.kind) {
|
|
21
|
-
case "prompt": return {
|
|
22
|
-
...base,
|
|
23
|
-
payload: "string (\"//\" lines = comments, \"- \" lines = negative)"
|
|
24
|
-
};
|
|
25
|
-
case "text": return {
|
|
26
|
-
...base,
|
|
27
|
-
payload: "string"
|
|
28
|
-
};
|
|
29
|
-
case "int": {
|
|
30
|
-
const v = varDef;
|
|
31
|
-
return {
|
|
32
|
-
...base,
|
|
33
|
-
payload: `integer${rangeText(v.opts)}`,
|
|
34
|
-
min: v.opts.min,
|
|
35
|
-
max: v.opts.max
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
case "float": {
|
|
39
|
-
const v = varDef;
|
|
40
|
-
return {
|
|
41
|
-
...base,
|
|
42
|
-
payload: `number${rangeText(v.opts)}`,
|
|
43
|
-
min: v.opts.min,
|
|
44
|
-
max: v.opts.max
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
case "seed": {
|
|
48
|
-
const v = varDef;
|
|
49
|
-
return {
|
|
50
|
-
...base,
|
|
51
|
-
default: {
|
|
52
|
-
mode: v.defaultMode,
|
|
53
|
-
value: v.defaultValue
|
|
54
|
-
},
|
|
55
|
-
payload: "number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}"
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
case "toggle": return {
|
|
59
|
-
...base,
|
|
60
|
-
payload: "true or false"
|
|
61
|
-
};
|
|
62
|
-
case "choice": {
|
|
63
|
-
const v = varDef;
|
|
64
|
-
return {
|
|
65
|
-
...base,
|
|
66
|
-
payload: `one of: ${v.choices.join(" | ")}`,
|
|
67
|
-
choices: v.choices
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
case "loras": {
|
|
71
|
-
const v = varDef;
|
|
72
|
-
return {
|
|
73
|
-
...base,
|
|
74
|
-
payload: "{\"<lora name>\": false | true | strength | [model, clip]}",
|
|
75
|
-
options: v.options
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
case "size": {
|
|
79
|
-
const v = varDef;
|
|
80
|
-
return {
|
|
81
|
-
...base,
|
|
82
|
-
payload: "{\"width\":W,\"height\":H} or \"WxH\" or a preset label",
|
|
83
|
-
presets: v.presets
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
case "image": {
|
|
87
|
-
const v = varDef;
|
|
88
|
-
return {
|
|
89
|
-
...base,
|
|
90
|
-
payload: "local file path or http(s) url",
|
|
91
|
-
extensions: v.extensions
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
default: {
|
|
95
|
-
const unknownKind = varDef.kind;
|
|
96
|
-
return {
|
|
97
|
-
...base,
|
|
98
|
-
payload: `string (unrecognised kind '${String(unknownKind)}')`
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
/** one aligned console line per var (startup print) */
|
|
104
|
-
function renderDescriptorLine(name, d, nameWidth) {
|
|
105
|
-
const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
|
|
106
|
-
return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? "null", 60)}`;
|
|
107
|
-
}
|
|
108
|
-
function truncate(s, n) {
|
|
109
|
-
return s.length <= n ? s : s.slice(0, n - 1) + "…";
|
|
110
|
-
}
|
|
111
|
-
//#endregion
|
|
112
|
-
//#region src/cli/serve/applyVarPayload.ts
|
|
113
|
-
function isFiniteNumber(x) {
|
|
114
|
-
return typeof x === "number" && Number.isFinite(x);
|
|
115
|
-
}
|
|
116
|
-
function isLoraStrength(x) {
|
|
117
|
-
if (typeof x === "boolean") return true;
|
|
118
|
-
if (isFiniteNumber(x)) return true;
|
|
119
|
-
return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1]);
|
|
120
|
-
}
|
|
121
|
-
/** cap long option lists in error messages */
|
|
122
|
-
function listSome(items, cap = 20) {
|
|
123
|
-
if (items.length <= cap) return items.join(", ");
|
|
124
|
-
return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
|
|
125
|
-
}
|
|
126
|
-
function applyVarPayload(varDef, raw) {
|
|
127
|
-
const name = varDef.name ?? varDef.label ?? varDef.kind;
|
|
128
|
-
switch (varDef.kind) {
|
|
129
|
-
case "text":
|
|
130
|
-
case "prompt":
|
|
131
|
-
if (typeof raw !== "string") return `var '${name}' expects a string`;
|
|
132
|
-
varDef.set(raw);
|
|
133
|
-
return null;
|
|
134
|
-
case "int":
|
|
135
|
-
case "float": {
|
|
136
|
-
const v = varDef;
|
|
137
|
-
if (isFiniteNumber(raw)) {
|
|
138
|
-
v.set(raw);
|
|
139
|
-
return null;
|
|
140
|
-
}
|
|
141
|
-
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
142
|
-
const o = v.opts;
|
|
143
|
-
return `var '${name}' expects a number${o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`}`;
|
|
144
|
-
}
|
|
145
|
-
case "seed": {
|
|
146
|
-
const v = varDef;
|
|
147
|
-
if (isFiniteNumber(raw)) {
|
|
148
|
-
v.setMode("=");
|
|
149
|
-
v.set(raw);
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
152
|
-
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
153
|
-
const o = raw;
|
|
154
|
-
const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
|
|
155
|
-
if (o.mode !== void 0 && mode == null) return `var '${name}': mode must be one of = + - ?`;
|
|
156
|
-
if (o.value !== void 0 && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`;
|
|
157
|
-
if (mode == null && o.value === void 0) return `var '${name}': give "mode" and/or "value"`;
|
|
158
|
-
if (mode != null) v.setMode(mode);
|
|
159
|
-
if (isFiniteNumber(o.value)) v.set(o.value);
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
|
|
163
|
-
}
|
|
164
|
-
case "toggle":
|
|
165
|
-
if (typeof raw !== "boolean") return `var '${name}' expects true or false`;
|
|
166
|
-
varDef.set(raw);
|
|
167
|
-
return null;
|
|
168
|
-
case "choice": {
|
|
169
|
-
const v = varDef;
|
|
170
|
-
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
171
|
-
return `var '${name}' expects one of: ${listSome(v.choices)}`;
|
|
172
|
-
}
|
|
173
|
-
case "loras": {
|
|
174
|
-
const v = varDef;
|
|
175
|
-
if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`;
|
|
176
|
-
const record = raw;
|
|
177
|
-
const known = new Set(v.options);
|
|
178
|
-
const unknownNames = Object.keys(record).filter((k) => !known.has(k));
|
|
179
|
-
if (unknownNames.length > 0) return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome(v.options)}`;
|
|
180
|
-
for (const [k, st] of Object.entries(record)) if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`;
|
|
181
|
-
v.set(record);
|
|
182
|
-
return null;
|
|
183
|
-
}
|
|
184
|
-
case "size": {
|
|
185
|
-
const v = varDef;
|
|
186
|
-
if (typeof raw === "string" && v.parse(raw)) return null;
|
|
187
|
-
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
188
|
-
const o = raw;
|
|
189
|
-
if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
|
|
190
|
-
v.set({
|
|
191
|
-
width: o.width,
|
|
192
|
-
height: o.height
|
|
193
|
-
});
|
|
194
|
-
return null;
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
|
|
198
|
-
}
|
|
199
|
-
case "image":
|
|
200
|
-
if (typeof raw !== "string") return `var '${name}' expects a file path or http(s) url string`;
|
|
201
|
-
varDef.set(raw);
|
|
202
|
-
return null;
|
|
203
|
-
default: {
|
|
204
|
-
const unknownKind = varDef.kind;
|
|
205
|
-
return `var '${name}' has unsupported kind '${String(unknownKind)}'`;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
//#endregion
|
|
210
|
-
//#region src/cli/serve/safeName.ts
|
|
211
|
-
/** the accepted name, or null. Rejects traversal, absolute paths, leading dots and empties */
|
|
212
|
-
function validStoreName(raw) {
|
|
213
|
-
const name = raw.trim();
|
|
214
|
-
if (name.length > 100) return null;
|
|
215
|
-
return /^[\w][\w .-]*$/.test(name) ? name : null;
|
|
216
|
-
}
|
|
217
|
-
//#endregion
|
|
218
|
-
//#region src/cli/serve/promptEnhancers.ts
|
|
219
|
-
const EXT = ".md";
|
|
220
|
-
function promptEnhancersDir() {
|
|
221
|
-
return comfyts.resolveFromPromptEnhancers("");
|
|
222
|
-
}
|
|
223
|
-
function promptEnhancerPath(name) {
|
|
224
|
-
const safe = validStoreName(name);
|
|
225
|
-
return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
|
|
226
|
-
}
|
|
227
|
-
/** the shipped starting point. It is a FILE from the first read on, so it can be edited
|
|
228
|
-
* on disk like everything else — the browser ships no copy of this text */
|
|
229
|
-
const SEED = {
|
|
230
|
-
name: "refine-krea2-prompt",
|
|
231
|
-
text: `You rewrite image prompts for krea2 turbo, a distilled 8 step text to image model whose text encoder reads flowing natural language, not tag soup, and which is steered by adjectives rather than by negatives.
|
|
232
|
-
|
|
233
|
-
Rewrite the user's prompt into ONE dense paragraph someone could picture with their eyes closed:
|
|
234
|
-
- keep every noun and every named subject the user wrote, they are the point
|
|
235
|
-
- add what is missing to make it fun to look at: lighting, palette, material, texture, camera angle, composition, mood
|
|
236
|
-
- prefer concrete visual nouns over praise, never write "masterpiece", "8k", "highly detailed", "award winning"
|
|
237
|
-
- stay under about 80 words, no lists, no headings, no quotes around the result
|
|
238
|
-
- keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line
|
|
239
|
-
|
|
240
|
-
Answer with the rewritten prompt and nothing else: no preamble, no explanation.
|
|
241
|
-
`
|
|
242
|
-
};
|
|
243
|
-
/** seeds ONCE, on an absent folder. A folder he emptied on purpose stays empty */
|
|
244
|
-
function listPromptEnhancers() {
|
|
245
|
-
const dir = promptEnhancersDir();
|
|
246
|
-
if (!existsSync(dir)) writePromptEnhancer(SEED.name, SEED.text);
|
|
247
|
-
if (!existsSync(dir)) return [];
|
|
248
|
-
const out = [];
|
|
249
|
-
for (const file of readdirSync(dir).sort()) {
|
|
250
|
-
if (!file.endsWith(EXT)) continue;
|
|
251
|
-
const name = file.slice(0, -3);
|
|
252
|
-
if (validStoreName(name) == null) continue;
|
|
253
|
-
out.push({
|
|
254
|
-
name,
|
|
255
|
-
text: readFileSync(join(dir, file), "utf8")
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
return out;
|
|
259
|
-
}
|
|
260
|
-
function writePromptEnhancer(name, text) {
|
|
261
|
-
const path = promptEnhancerPath(name);
|
|
262
|
-
if (path == null) return null;
|
|
263
|
-
mkdirSync(promptEnhancersDir(), { recursive: true });
|
|
264
|
-
writeFileSync(path, text);
|
|
265
|
-
return path;
|
|
266
|
-
}
|
|
267
|
-
/** a missing file is still a success: the caller asked for it to be gone, and it is */
|
|
268
|
-
function deletePromptEnhancer(name) {
|
|
269
|
-
const path = promptEnhancerPath(name);
|
|
270
|
-
if (path == null) return false;
|
|
271
|
-
if (existsSync(path)) rmSync(path);
|
|
272
|
-
return true;
|
|
273
|
-
}
|
|
274
|
-
//#endregion
|
|
275
|
-
//#region src/cli/serve/ServeApp.ts
|
|
276
|
-
/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
|
|
277
|
-
* serve OPTS INTO local saving (library default is memory-only, architecture.md
|
|
278
|
-
* item 14): the /outputs/ routes serve files, grouped per module */
|
|
279
|
-
const realStarter = async (mod) => {
|
|
280
|
-
await mod.dw.host.connect();
|
|
281
|
-
return await (await mod.dw.build({ advance: true })).start({ save: { prefix: mod.key } });
|
|
282
|
-
};
|
|
283
|
-
const CONTENT_TYPES = {
|
|
284
|
-
".png": "image/png",
|
|
285
|
-
".jpg": "image/jpeg",
|
|
286
|
-
".jpeg": "image/jpeg",
|
|
287
|
-
".webp": "image/webp",
|
|
288
|
-
".gif": "image/gif",
|
|
289
|
-
".mp4": "video/mp4",
|
|
290
|
-
".webm": "video/webm",
|
|
291
|
-
".json": "application/json",
|
|
292
|
-
".txt": "text/plain"
|
|
293
|
-
};
|
|
294
|
-
/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
|
|
295
|
-
function sniffImageContentType(bytes) {
|
|
296
|
-
if (bytes[0] === 137 && bytes[1] === 80) return "image/png";
|
|
297
|
-
if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
|
|
298
|
-
if (bytes[0] === 71 && bytes[1] === 73) return "image/gif";
|
|
299
|
-
if (bytes[0] === 82 && bytes[1] === 73) return "image/webp";
|
|
300
|
-
return "application/octet-stream";
|
|
301
|
-
}
|
|
302
|
-
function json(status, payload) {
|
|
303
|
-
return {
|
|
304
|
-
status,
|
|
305
|
-
contentType: "application/json",
|
|
306
|
-
body: JSON.stringify(payload, null, 2)
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
const USAGE = [
|
|
310
|
-
"GET / in a browser — web control panel (every var as a form control)",
|
|
311
|
-
"GET /drafts — every served workflow, its drafts and var descriptors",
|
|
312
|
-
"GET /drafts/<module>/<draft> — one draft with its stored values",
|
|
313
|
-
"POST /generate/<module>/<draft> with { ...vars } — run, blocking",
|
|
314
|
-
"POST /generate/<draft> — unqualified, when unambiguous",
|
|
315
|
-
"PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
|
|
316
|
-
"DELETE /drafts/<module>/<draft> — delete that draft file",
|
|
317
|
-
"GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
|
|
318
|
-
"POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image var",
|
|
319
|
-
"GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
|
|
320
|
-
"GET /lora-preview/<hostId>/<lora> — preview image bytes",
|
|
321
|
-
"GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
|
|
322
|
-
"PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it",
|
|
323
|
-
"GET /outputs/<path> — generated files"
|
|
324
|
-
];
|
|
325
|
-
/** the html shell; the app itself is ONE bundle at /web/app.js */
|
|
326
|
-
const WEB_SHELL = `<!doctype html>
|
|
327
|
-
<html lang="en">
|
|
328
|
-
<head>
|
|
329
|
-
<meta charset="utf-8">
|
|
330
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
331
|
-
<title>comfy-ts serve</title>
|
|
332
|
-
<style>html{background:#101217;color:#e8eaf0}</style>
|
|
333
|
-
</head>
|
|
334
|
-
<body>
|
|
335
|
-
<div id="root"></div>
|
|
336
|
-
<script type="module" src="/web/app.js"><\/script>
|
|
337
|
-
</body>
|
|
338
|
-
</html>
|
|
339
|
-
`;
|
|
340
|
-
var ServeApp = class {
|
|
341
|
-
constructor(modules, opts = {}) {
|
|
342
|
-
this.modules = modules;
|
|
343
|
-
this.opts = opts;
|
|
344
|
-
this.seedState = /* @__PURE__ */ new Map();
|
|
345
|
-
this.chains = /* @__PURE__ */ new Map();
|
|
346
|
-
this.webJsCache = null;
|
|
347
|
-
this.liveRuns = /* @__PURE__ */ new Map();
|
|
348
|
-
this.latentPreviews = /* @__PURE__ */ new Map();
|
|
349
|
-
this.latentSeq = 0;
|
|
350
|
-
this.promptOwner = /* @__PURE__ */ new Map();
|
|
351
|
-
this.latentHosts = /* @__PURE__ */ new Set();
|
|
352
|
-
this.previewSweeps = /* @__PURE__ */ new Map();
|
|
353
|
-
this.starter = opts.starter ?? realStarter;
|
|
354
|
-
}
|
|
355
|
-
get outputRoot() {
|
|
356
|
-
return this.opts.outputRoot ?? comfyts.outputPath;
|
|
357
|
-
}
|
|
358
|
-
async handle(req) {
|
|
359
|
-
try {
|
|
360
|
-
const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
|
|
361
|
-
let segs;
|
|
362
|
-
try {
|
|
363
|
-
segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
|
|
364
|
-
} catch {
|
|
365
|
-
return json(400, { error: `bad url encoding: ${path}` });
|
|
366
|
-
}
|
|
367
|
-
if (req.method === "GET") {
|
|
368
|
-
if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
|
|
369
|
-
this.webJsCache ??= this.opts.webJs();
|
|
370
|
-
if (await this.webJsCache != null) return {
|
|
371
|
-
status: 200,
|
|
372
|
-
contentType: "text/html; charset=utf-8",
|
|
373
|
-
body: WEB_SHELL
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1) return this.replyIndex();
|
|
377
|
-
if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2) return await this.replyWebJs();
|
|
378
|
-
if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyDraft(segs[1], segs[2]);
|
|
379
|
-
if (segs[0] === "run" && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1]);
|
|
380
|
-
if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview") return this.replyRunPreview(segs[1]);
|
|
381
|
-
if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null) return this.replyLoraInfo(segs[1], segs[2]);
|
|
382
|
-
if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyLoraPreview(segs[1], segs[2]);
|
|
383
|
-
if (segs[0] === "prompt-enhancers" && segs.length === 1) return this.replyPromptEnhancers();
|
|
384
|
-
if (segs[0] === "outputs") return this.replyOutput(segs.slice(1));
|
|
385
|
-
return json(404, {
|
|
386
|
-
error: `no route: GET ${path}`,
|
|
387
|
-
usage: USAGE
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
if (req.method === "POST" && segs[0] === "generate") {
|
|
391
|
-
const target = this.resolveDraft(segs.slice(1));
|
|
392
|
-
if ("error" in target) return json(target.status, { error: target.error });
|
|
393
|
-
return await this.generate(target.mod, target.draft, req);
|
|
394
|
-
}
|
|
395
|
-
if (req.method === "POST" && segs[0] === "upload" && segs.length === 1) return this.replyUpload(req);
|
|
396
|
-
if (req.method === "PUT" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replySaveDraft(segs[1], segs[2], req);
|
|
397
|
-
if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null) return await this.replyDeleteDraft(segs[1], segs[2]);
|
|
398
|
-
if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replySavePromptEnhancer(segs[1], req);
|
|
399
|
-
if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null) return this.replyDeletePromptEnhancer(segs[1]);
|
|
400
|
-
return json(404, {
|
|
401
|
-
error: `no route: ${req.method} ${path}`,
|
|
402
|
-
usage: USAGE
|
|
403
|
-
});
|
|
404
|
-
} catch (e) {
|
|
405
|
-
console.error("[serve] request crashed:", e);
|
|
406
|
-
return json(500, { error: extractErrorMessage(e) });
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
moduleByKey(key) {
|
|
410
|
-
return this.modules.find((m) => m.key === key) ?? null;
|
|
411
|
-
}
|
|
412
|
-
/** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
|
|
413
|
-
draftsFor(mod) {
|
|
414
|
-
return ["default", ...listDraftsForFile(mod.file).filter((n) => n !== "default")];
|
|
415
|
-
}
|
|
416
|
-
/** THE draft-name gate, shared by every route that turns a url segment into a path
|
|
417
|
-
* (safeName.ts owns the rule — the prompt-enhancer routes call the same function) */
|
|
418
|
-
validDraftName(raw) {
|
|
419
|
-
return validStoreName(raw);
|
|
420
|
-
}
|
|
421
|
-
/** absolute path of a draft file, or null when the name is not one we accept */
|
|
422
|
-
draftPath(mod, draft) {
|
|
423
|
-
const name = this.validDraftName(draft);
|
|
424
|
-
return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`);
|
|
425
|
-
}
|
|
426
|
-
draftExists(mod, draft) {
|
|
427
|
-
const path = this.draftPath(mod, draft);
|
|
428
|
-
if (path == null) return false;
|
|
429
|
-
return draft === "default" || existsSync(path);
|
|
430
|
-
}
|
|
431
|
-
resolveDraft(segs) {
|
|
432
|
-
if (segs.length === 2 && segs[0] != null && segs[1] != null) {
|
|
433
|
-
const mod = this.moduleByKey(segs[0]);
|
|
434
|
-
if (mod == null) return {
|
|
435
|
-
status: 404,
|
|
436
|
-
error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
|
|
437
|
-
};
|
|
438
|
-
if (!this.draftExists(mod, segs[1])) return {
|
|
439
|
-
status: 404,
|
|
440
|
-
error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
441
|
-
};
|
|
442
|
-
return {
|
|
443
|
-
mod,
|
|
444
|
-
draft: segs[1]
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
if (segs.length === 1 && segs[0] != null) {
|
|
448
|
-
const draft = segs[0];
|
|
449
|
-
if (this.modules.length === 1 && this.modules[0] != null) {
|
|
450
|
-
const mod = this.modules[0];
|
|
451
|
-
if (!this.draftExists(mod, draft)) return {
|
|
452
|
-
status: 404,
|
|
453
|
-
error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
454
|
-
};
|
|
455
|
-
return {
|
|
456
|
-
mod,
|
|
457
|
-
draft
|
|
458
|
-
};
|
|
459
|
-
}
|
|
460
|
-
const hits = this.modules.filter((m) => this.draftExists(m, draft));
|
|
461
|
-
if (hits.length === 1 && hits[0] != null) return {
|
|
462
|
-
mod: hits[0],
|
|
463
|
-
draft
|
|
464
|
-
};
|
|
465
|
-
if (hits.length === 0) return {
|
|
466
|
-
status: 404,
|
|
467
|
-
error: `no module has a draft '${draft}'`
|
|
468
|
-
};
|
|
469
|
-
return {
|
|
470
|
-
status: 400,
|
|
471
|
-
error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
|
|
472
|
-
};
|
|
473
|
-
}
|
|
474
|
-
return {
|
|
475
|
-
status: 400,
|
|
476
|
-
error: "use POST /generate/<module>/<draft> or /generate/<draft>"
|
|
477
|
-
};
|
|
478
|
-
}
|
|
479
|
-
describeModule(mod) {
|
|
480
|
-
refreshLoraInfoCacheIfChanged();
|
|
481
|
-
const hostId = mod.dw.host.data.id;
|
|
482
|
-
const vars = {};
|
|
483
|
-
for (const [name, varDef] of mod.dw.entries()) {
|
|
484
|
-
const desc = describeVar(varDef);
|
|
485
|
-
if (desc.kind === "loras" && desc.options != null) {
|
|
486
|
-
const labels = {};
|
|
487
|
-
for (const option of desc.options) {
|
|
488
|
-
const label = getLoraDisplayName(option, hostId);
|
|
489
|
-
if (label !== option) labels[option] = label;
|
|
490
|
-
}
|
|
491
|
-
if (Object.keys(labels).length > 0) desc.optionLabels = labels;
|
|
492
|
-
}
|
|
493
|
-
vars[name] = desc;
|
|
494
|
-
}
|
|
495
|
-
return {
|
|
496
|
-
module: mod.key,
|
|
497
|
-
file: mod.file,
|
|
498
|
-
host: mod.dw.host.data.id,
|
|
499
|
-
drafts: this.draftsFor(mod),
|
|
500
|
-
routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
|
|
501
|
-
vars
|
|
502
|
-
};
|
|
503
|
-
}
|
|
504
|
-
replyIndex() {
|
|
505
|
-
return json(200, {
|
|
506
|
-
server: "comfy-ts serve",
|
|
507
|
-
usage: USAGE,
|
|
508
|
-
workflows: this.modules.map((m) => this.describeModule(m)),
|
|
509
|
-
...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
replyDraft(modKey, draft) {
|
|
513
|
-
const mod = this.moduleByKey(modKey);
|
|
514
|
-
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
515
|
-
if (!this.draftExists(mod, draft)) return json(404, { error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}` });
|
|
516
|
-
return json(200, {
|
|
517
|
-
...this.describeModule(mod),
|
|
518
|
-
draft,
|
|
519
|
-
values: this.draftValues(mod, draft)
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
523
|
-
draftValues(mod, draft) {
|
|
524
|
-
const path = this.draftPath(mod, draft);
|
|
525
|
-
if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, "utf8"));
|
|
526
|
-
const out = {};
|
|
527
|
-
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default;
|
|
528
|
-
return out;
|
|
529
|
-
}
|
|
530
|
-
replyOutput(segs) {
|
|
531
|
-
const abs = resolve(this.outputRoot, ...segs);
|
|
532
|
-
if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/")) return json(400, { error: "path escapes the outputs root" });
|
|
533
|
-
if (!existsSync(abs) || !statSync(abs).isFile()) return json(404, { error: `no such output file: /${segs.join("/")}` });
|
|
534
|
-
return {
|
|
535
|
-
status: 200,
|
|
536
|
-
contentType: CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream",
|
|
537
|
-
body: new Uint8Array(readFileSync(abs))
|
|
538
|
-
};
|
|
539
|
-
}
|
|
540
|
-
async replyWebJs() {
|
|
541
|
-
if (this.opts.webJs == null) return json(404, { error: "web ui not enabled on this server" });
|
|
542
|
-
this.webJsCache ??= this.opts.webJs();
|
|
543
|
-
const js = await this.webJsCache;
|
|
544
|
-
if (js == null) return json(404, { error: "web ui bundle unavailable — see the server log" });
|
|
545
|
-
return {
|
|
546
|
-
status: 200,
|
|
547
|
-
contentType: "text/javascript; charset=utf-8",
|
|
548
|
-
body: js
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
/** browser file → local file an image var can point at (downloadInput family) */
|
|
552
|
-
replyUpload(req) {
|
|
553
|
-
let parsed;
|
|
554
|
-
try {
|
|
555
|
-
parsed = JSON.parse(req.body ?? "");
|
|
556
|
-
} catch (e) {
|
|
557
|
-
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
558
|
-
}
|
|
559
|
-
const o = parsed ?? {};
|
|
560
|
-
if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "") return json(400, { error: "upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}" });
|
|
561
|
-
const bytes = Buffer.from(o.dataBase64, "base64");
|
|
562
|
-
if (bytes.length === 0) return json(400, { error: "dataBase64 decoded to zero bytes" });
|
|
563
|
-
const safe = basename(o.name).replace(/[^\w.-]+/g, "_") || "upload";
|
|
564
|
-
const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
|
|
565
|
-
mkdirSync(dirname(abs), { recursive: true });
|
|
566
|
-
writeFileSync(abs, bytes);
|
|
567
|
-
console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
|
|
568
|
-
return json(200, {
|
|
569
|
-
ok: true,
|
|
570
|
-
path: abs,
|
|
571
|
-
url: this.outputUrl(abs)
|
|
572
|
-
});
|
|
573
|
-
}
|
|
574
|
-
async replySaveDraft(modKey, rawDraft, req) {
|
|
575
|
-
const mod = this.moduleByKey(modKey);
|
|
576
|
-
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
577
|
-
const draft = this.validDraftName(rawDraft);
|
|
578
|
-
if (draft == null) return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
|
|
579
|
-
let parsed;
|
|
580
|
-
try {
|
|
581
|
-
parsed = JSON.parse(req.body ?? "");
|
|
582
|
-
} catch (e) {
|
|
583
|
-
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
584
|
-
}
|
|
585
|
-
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
|
|
586
|
-
const values = parsed;
|
|
587
|
-
const known = new Set(mod.dw.entries().map(([k]) => k));
|
|
588
|
-
const unknown = Object.keys(values).filter((k) => !known.has(k));
|
|
589
|
-
if (unknown.length > 0) return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
|
|
590
|
-
const path = bang(this.draftPath(mod, draft), "draft name validated just above");
|
|
591
|
-
await this.exclusive(mod.key, () => {
|
|
592
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
593
|
-
writeFileSync(path, JSON.stringify(values, null, 2));
|
|
594
|
-
return Promise.resolve();
|
|
595
|
-
});
|
|
596
|
-
return json(200, {
|
|
597
|
-
ok: true,
|
|
598
|
-
module: mod.key,
|
|
599
|
-
draft,
|
|
600
|
-
drafts: this.draftsFor(mod)
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
/** delete the draft FILE. `default` is deletable like any other: the implicit `default`
|
|
604
|
-
* draft (spec values, no file) survives it, which is exactly the reset. Missing file is
|
|
605
|
-
* still a 200 — the caller asked for it to be gone, and it is */
|
|
606
|
-
async replyDeleteDraft(modKey, rawDraft) {
|
|
607
|
-
const mod = this.moduleByKey(modKey);
|
|
608
|
-
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
609
|
-
const path = this.draftPath(mod, rawDraft);
|
|
610
|
-
if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` });
|
|
611
|
-
await this.exclusive(mod.key, () => {
|
|
612
|
-
if (existsSync(path)) rmSync(path);
|
|
613
|
-
return Promise.resolve();
|
|
614
|
-
});
|
|
615
|
-
console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`);
|
|
616
|
-
return json(200, {
|
|
617
|
-
ok: true,
|
|
618
|
-
module: mod.key,
|
|
619
|
-
draft: rawDraft.trim(),
|
|
620
|
-
drafts: this.draftsFor(mod)
|
|
621
|
-
});
|
|
622
|
-
}
|
|
623
|
-
/** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
|
|
624
|
-
replyPromptEnhancers() {
|
|
625
|
-
try {
|
|
626
|
-
return json(200, { enhancers: listPromptEnhancers() });
|
|
627
|
-
} catch (e) {
|
|
628
|
-
return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` });
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
replySavePromptEnhancer(rawName, req) {
|
|
632
|
-
const name = validStoreName(rawName);
|
|
633
|
-
if (name == null) return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` });
|
|
634
|
-
let parsed;
|
|
635
|
-
try {
|
|
636
|
-
parsed = JSON.parse(req.body ?? "");
|
|
637
|
-
} catch (e) {
|
|
638
|
-
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
639
|
-
}
|
|
640
|
-
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
|
|
641
|
-
const text = parsed.text;
|
|
642
|
-
if (typeof text !== "string") return json(400, { error: "body must be { \"text\": \"<master prompt>\" }" });
|
|
643
|
-
try {
|
|
644
|
-
writePromptEnhancer(name, text);
|
|
645
|
-
} catch (e) {
|
|
646
|
-
return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
647
|
-
}
|
|
648
|
-
return json(200, {
|
|
649
|
-
ok: true,
|
|
650
|
-
name,
|
|
651
|
-
enhancers: listPromptEnhancers()
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
replyDeletePromptEnhancer(rawName) {
|
|
655
|
-
const name = validStoreName(rawName);
|
|
656
|
-
if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` });
|
|
657
|
-
try {
|
|
658
|
-
deletePromptEnhancer(name);
|
|
659
|
-
} catch (e) {
|
|
660
|
-
return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
661
|
-
}
|
|
662
|
-
console.log(`[serve] prompt enhancer deleted: ${name}`);
|
|
663
|
-
return json(200, {
|
|
664
|
-
ok: true,
|
|
665
|
-
name,
|
|
666
|
-
enhancers: listPromptEnhancers()
|
|
667
|
-
});
|
|
668
|
-
}
|
|
669
|
-
runningModules() {
|
|
670
|
-
return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
|
|
671
|
-
}
|
|
672
|
-
/** one dispatcher per host, installed once and left in place (idempotent) */
|
|
673
|
-
wireLatents(host) {
|
|
674
|
-
if (this.latentHosts.has(host)) return;
|
|
675
|
-
this.latentHosts.add(host);
|
|
676
|
-
host.onLatentPreview = (p) => {
|
|
677
|
-
const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : void 0;
|
|
678
|
-
const running = this.runningModules();
|
|
679
|
-
const key = owner ?? (running.length === 1 ? running[0] : void 0);
|
|
680
|
-
if (key == null) return;
|
|
681
|
-
this.latentPreviews.set(key, {
|
|
682
|
-
bytes: p.bytes,
|
|
683
|
-
mime: p.mime,
|
|
684
|
-
seq: ++this.latentSeq
|
|
685
|
-
});
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
replyRunStatus(modKey) {
|
|
689
|
-
const mod = this.moduleByKey(modKey);
|
|
690
|
-
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
691
|
-
const exec = this.liveRuns.get(mod.key);
|
|
692
|
-
const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
|
|
693
|
-
return json(200, {
|
|
694
|
-
running,
|
|
695
|
-
status: exec?.status ?? "idle",
|
|
696
|
-
percent: running ? exec.progressGlobal?.percent ?? null : null,
|
|
697
|
-
hasPreview: this.latentPreviews.has(mod.key),
|
|
698
|
-
previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
replyRunPreview(modKey) {
|
|
702
|
-
const mod = this.moduleByKey(modKey);
|
|
703
|
-
if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
|
|
704
|
-
const preview = this.latentPreviews.get(mod.key);
|
|
705
|
-
if (preview == null) return json(404, { error: "no latent preview yet" });
|
|
706
|
-
return {
|
|
707
|
-
status: 200,
|
|
708
|
-
contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
|
|
709
|
-
body: preview.bytes
|
|
710
|
-
};
|
|
711
|
-
}
|
|
712
|
-
hostById(hostId) {
|
|
713
|
-
return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
|
|
714
|
-
}
|
|
715
|
-
hostIds() {
|
|
716
|
-
return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
|
|
717
|
-
}
|
|
718
|
-
/** mirror-backed text for the hover pane, no network */
|
|
719
|
-
replyLoraInfo(hostId, lora) {
|
|
720
|
-
if (this.hostById(hostId) == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
721
|
-
refreshLoraInfoCacheIfChanged();
|
|
722
|
-
return json(200, {
|
|
723
|
-
name: lora,
|
|
724
|
-
displayName: getLoraDisplayName(lora, hostId),
|
|
725
|
-
triggerWords: getLoraTriggerWords(lora, hostId)
|
|
726
|
-
});
|
|
727
|
-
}
|
|
728
|
-
async replyLoraPreview(hostId, lora) {
|
|
729
|
-
const host = this.hostById(hostId);
|
|
730
|
-
if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
731
|
-
refreshLoraInfoCacheIfChanged();
|
|
732
|
-
let url = getLoraPreviewUrl(lora, hostId);
|
|
733
|
-
if (url == null) {
|
|
734
|
-
let sweep = this.previewSweeps.get(hostId);
|
|
735
|
-
if (sweep == null) {
|
|
736
|
-
sweep = fetchLoraList(host).then((r) => {
|
|
737
|
-
if (r.status === "unreachable") {
|
|
738
|
-
this.previewSweeps.delete(hostId);
|
|
739
|
-
return {
|
|
740
|
-
status: r.status,
|
|
741
|
-
map: null
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
status: r.status,
|
|
746
|
-
map: r.status === "absent" ? null : loraPreviewMapFrom(r.items)
|
|
747
|
-
};
|
|
748
|
-
});
|
|
749
|
-
this.previewSweeps.set(hostId, sweep);
|
|
750
|
-
}
|
|
751
|
-
const swept = await sweep;
|
|
752
|
-
url = swept.map?.get(loraKey(lora)) ?? null;
|
|
753
|
-
if (url == null && swept.status === "unreachable") return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
|
|
754
|
-
if (url == null && swept.status === "absent") return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
|
|
755
|
-
}
|
|
756
|
-
if (url == null) return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
|
|
757
|
-
const bytes = await fetchLoraPreviewBytes(host, url);
|
|
758
|
-
if (bytes == null) return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
|
|
759
|
-
return {
|
|
760
|
-
status: 200,
|
|
761
|
-
contentType: sniffImageContentType(bytes),
|
|
762
|
-
body: bytes
|
|
763
|
-
};
|
|
764
|
-
}
|
|
765
|
-
outputUrl(absPath) {
|
|
766
|
-
if (!absPath.startsWith(this.outputRoot + "/")) return null;
|
|
767
|
-
return "/outputs/" + absPath.slice(this.outputRoot.length + 1).split("/").map(encodeURIComponent).join("/");
|
|
768
|
-
}
|
|
769
|
-
async generate(mod, draft, req) {
|
|
770
|
-
let payload = {};
|
|
771
|
-
if (req.body != null && req.body.trim() !== "") {
|
|
772
|
-
let parsed;
|
|
773
|
-
try {
|
|
774
|
-
parsed = JSON.parse(req.body);
|
|
775
|
-
} catch (e) {
|
|
776
|
-
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
777
|
-
}
|
|
778
|
-
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return json(400, { error: "body must be a json object: { \"<var>\": value, … }" });
|
|
779
|
-
payload = parsed;
|
|
780
|
-
}
|
|
781
|
-
const t0 = Date.now();
|
|
782
|
-
const seeds = {};
|
|
783
|
-
const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
|
|
784
|
-
if ("error" in started) return json(started.status, { error: started.error });
|
|
785
|
-
const execution = started.execution;
|
|
786
|
-
this.liveRuns.set(mod.key, execution);
|
|
787
|
-
this.promptOwner.set(execution.data.id, mod.key);
|
|
788
|
-
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
|
|
789
|
-
try {
|
|
790
|
-
await execution.done;
|
|
791
|
-
} finally {
|
|
792
|
-
this.promptOwner.delete(execution.data.id);
|
|
793
|
-
}
|
|
794
|
-
const durationMs = Date.now() - t0;
|
|
795
|
-
if (execution.status === "Failure") {
|
|
796
|
-
console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`);
|
|
797
|
-
return json(500, {
|
|
798
|
-
ok: false,
|
|
799
|
-
module: mod.key,
|
|
800
|
-
draft,
|
|
801
|
-
promptId: execution.data.id,
|
|
802
|
-
durationMs,
|
|
803
|
-
error: execution.data.error ?? "execution failed"
|
|
804
|
-
});
|
|
805
|
-
}
|
|
806
|
-
console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1e3).toFixed(1)}s · ${execution.images.length} image(s)`);
|
|
807
|
-
const first = execution.images[0];
|
|
808
|
-
if (req.accept?.includes("image/") && first?.absPath != null) return {
|
|
809
|
-
status: 200,
|
|
810
|
-
contentType: CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream",
|
|
811
|
-
body: new Uint8Array(readFileSync(first.absPath))
|
|
812
|
-
};
|
|
813
|
-
return json(200, {
|
|
814
|
-
ok: true,
|
|
815
|
-
module: mod.key,
|
|
816
|
-
draft,
|
|
817
|
-
promptId: execution.data.id,
|
|
818
|
-
durationMs,
|
|
819
|
-
seeds,
|
|
820
|
-
images: execution.images.map((img) => ({
|
|
821
|
-
filename: img.filename,
|
|
822
|
-
url: img.absPath != null ? this.outputUrl(img.absPath) : null,
|
|
823
|
-
absPath: img.absPath
|
|
824
|
-
}))
|
|
825
|
-
});
|
|
826
|
-
}
|
|
827
|
-
/** everything that touches the module's SHARED vars, under the module mutex */
|
|
828
|
-
async prepareAndStart(mod, draft, payload, seeds) {
|
|
829
|
-
for (const [, varDef] of mod.dw.entries()) varDef.reset();
|
|
830
|
-
const draftPath = this.draftPath(mod, draft);
|
|
831
|
-
if (draftPath == null) return {
|
|
832
|
-
status: 404,
|
|
833
|
-
error: `no draft '${draft}'`
|
|
834
|
-
};
|
|
835
|
-
if (existsSync(draftPath)) try {
|
|
836
|
-
const values = JSON.parse(readFileSync(draftPath, "utf8"));
|
|
837
|
-
for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k]);
|
|
838
|
-
} catch (e) {
|
|
839
|
-
return {
|
|
840
|
-
status: 500,
|
|
841
|
-
error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}`
|
|
842
|
-
};
|
|
843
|
-
}
|
|
844
|
-
const draftSeedValues = /* @__PURE__ */ new Map();
|
|
845
|
-
for (const [k, varDef] of mod.dw.entries()) if (varDef.kind === "seed") draftSeedValues.set(k, varDef.value);
|
|
846
|
-
const varMap = new Map(mod.dw.entries());
|
|
847
|
-
for (const [k, rawValue] of Object.entries(payload)) {
|
|
848
|
-
const varDef = varMap.get(k);
|
|
849
|
-
if (varDef == null) return {
|
|
850
|
-
status: 400,
|
|
851
|
-
error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}`
|
|
852
|
-
};
|
|
853
|
-
let value = rawValue;
|
|
854
|
-
if (varDef.kind === "image" && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) try {
|
|
855
|
-
value = await this.downloadInput(rawValue);
|
|
856
|
-
} catch (e) {
|
|
857
|
-
return {
|
|
858
|
-
status: 400,
|
|
859
|
-
error: `var '${k}': ${extractErrorMessage(e)}`
|
|
860
|
-
};
|
|
861
|
-
}
|
|
862
|
-
const err = applyVarPayload(varDef, value);
|
|
863
|
-
if (err != null) return {
|
|
864
|
-
status: 400,
|
|
865
|
-
error: err
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
for (const [k, varDef] of varMap) {
|
|
869
|
-
if (varDef.kind !== "image") continue;
|
|
870
|
-
const img = varDef;
|
|
871
|
-
if (img.isSet() && !existsSync(img.absPath())) return {
|
|
872
|
-
status: 400,
|
|
873
|
-
error: `image var '${k}': file not found: ${img.absPath()}`
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
for (const [k, varDef] of varMap) {
|
|
877
|
-
if (varDef.kind !== "seed") continue;
|
|
878
|
-
const seedVar = varDef;
|
|
879
|
-
const stateKey = `${mod.key}/${draft}/${k}`;
|
|
880
|
-
const draftValue = draftSeedValues.get(k) ?? seedVar.value;
|
|
881
|
-
if (!(k in payload)) {
|
|
882
|
-
if (seedVar.mode === "?") seedVar.randomize();
|
|
883
|
-
else if (seedVar.mode === "+" || seedVar.mode === "-") {
|
|
884
|
-
const prev = this.seedState.get(stateKey);
|
|
885
|
-
if (prev != null && prev.draftBase === draftValue) seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
this.seedState.set(stateKey, {
|
|
889
|
-
last: seedVar.value,
|
|
890
|
-
draftBase: draftValue
|
|
891
|
-
});
|
|
892
|
-
seeds[k] = seedVar.value;
|
|
893
|
-
}
|
|
894
|
-
this.latentPreviews.delete(mod.key);
|
|
895
|
-
this.wireLatents(mod.dw.host);
|
|
896
|
-
try {
|
|
897
|
-
return { execution: await this.starter(mod) };
|
|
898
|
-
} catch (e) {
|
|
899
|
-
if (e instanceof Error && e.name === "ImageVarEmptyError") return {
|
|
900
|
-
status: 400,
|
|
901
|
-
error: e.message
|
|
902
|
-
};
|
|
903
|
-
if (e instanceof Error && e.name === "ComfyHostUnreachableError") return {
|
|
904
|
-
status: 502,
|
|
905
|
-
error: e.message
|
|
906
|
-
};
|
|
907
|
-
return {
|
|
908
|
-
status: 500,
|
|
909
|
-
error: extractErrorMessage(e)
|
|
910
|
-
};
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
/** serialize fn per module key; the stored chain never rejects */
|
|
914
|
-
exclusive(key, fn) {
|
|
915
|
-
const next = (this.chains.get(key) ?? Promise.resolve()).then(fn);
|
|
916
|
-
this.chains.set(key, next.catch(() => {}));
|
|
917
|
-
return next;
|
|
918
|
-
}
|
|
919
|
-
/** payload image urls land as local files under outputs/serve-inputs/ */
|
|
920
|
-
async downloadInput(url) {
|
|
921
|
-
const res = await fetch(url);
|
|
922
|
-
if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`);
|
|
923
|
-
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
924
|
-
const name = basename(new URL(url).pathname) || "input";
|
|
925
|
-
const abs = join(this.outputRoot, "serve-inputs", `${nanoid(6)}-${name}`);
|
|
926
|
-
mkdirSync(dirname(abs), { recursive: true });
|
|
927
|
-
writeFileSync(abs, bytes);
|
|
928
|
-
return abs;
|
|
929
|
-
}
|
|
930
|
-
};
|
|
931
|
-
//#endregion
|
|
932
|
-
//#region src/cli/serve/webBundle.ts
|
|
933
|
-
const WEB_ENTRY = "src/cli/serve/web/main.tsx";
|
|
934
|
-
/** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */
|
|
935
|
-
function packageRoot(fromDir) {
|
|
936
|
-
let dir = fromDir;
|
|
937
|
-
while (true) {
|
|
938
|
-
if (existsSync(join(dir, "package.json"))) return dir;
|
|
939
|
-
const parent = dirname(dir);
|
|
940
|
-
if (parent === dir) return null;
|
|
941
|
-
dir = parent;
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
/** bundle the web app to one browser file. Bun.build reads no tsconfig, so the
|
|
945
|
-
* house 'src/...' absolute imports resolve through the same plugin shape as
|
|
946
|
-
* tests/web-bundle.test.ts */
|
|
947
|
-
async function buildWebJsText(pkgRoot) {
|
|
948
|
-
const result = await Bun.build({
|
|
949
|
-
entrypoints: [join(pkgRoot, WEB_ENTRY)],
|
|
950
|
-
target: "browser",
|
|
951
|
-
minify: true,
|
|
952
|
-
throw: false,
|
|
953
|
-
define: { "process.env.NODE_ENV": "\"production\"" },
|
|
954
|
-
plugins: [{
|
|
955
|
-
name: "repo-src-paths",
|
|
956
|
-
setup(build) {
|
|
957
|
-
build.onResolve({ filter: /^src\// }, (args) => ({ path: join(pkgRoot, args.path) }));
|
|
958
|
-
}
|
|
959
|
-
}]
|
|
960
|
-
});
|
|
961
|
-
if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
|
|
962
|
-
return await result.outputs[0].text();
|
|
963
|
-
}
|
|
964
|
-
/** the runtime resolution chain; every miss logs loud and degrades to api-only */
|
|
965
|
-
async function loadOrBuildWebJs() {
|
|
966
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
967
|
-
const prebuilt = join(here, "serve-web.js");
|
|
968
|
-
if (existsSync(prebuilt)) return readFileSync(prebuilt, "utf8");
|
|
969
|
-
if (typeof Bun === "undefined") {
|
|
970
|
-
console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
|
|
971
|
-
return null;
|
|
972
|
-
}
|
|
973
|
-
const pkgRoot = packageRoot(here);
|
|
974
|
-
if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {
|
|
975
|
-
console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
|
|
976
|
-
return null;
|
|
977
|
-
}
|
|
978
|
-
try {
|
|
979
|
-
return await buildWebJsText(pkgRoot);
|
|
980
|
-
} catch (e) {
|
|
981
|
-
console.error("[serve] 🔴 web ui bundle failed — api only:", e);
|
|
982
|
-
return null;
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
//#endregion
|
|
986
|
-
//#region src/cli/serve/run-serve.ts
|
|
987
|
-
const DEFAULT_PORT = 8288;
|
|
988
|
-
const BODY_CAP = 1e7;
|
|
989
|
-
function parseArgs(args) {
|
|
990
|
-
let target;
|
|
991
|
-
let port = DEFAULT_PORT;
|
|
992
|
-
let bind = "127.0.0.1";
|
|
993
|
-
for (let i = 0; i < args.length; i++) {
|
|
994
|
-
const a = args[i];
|
|
995
|
-
if (a === "--port") {
|
|
996
|
-
const n = Number(args[++i]);
|
|
997
|
-
if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
|
|
998
|
-
port = n;
|
|
999
|
-
} else if (a === "--host" || a === "--bind") {
|
|
1000
|
-
const b = args[++i];
|
|
1001
|
-
if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` };
|
|
1002
|
-
bind = b;
|
|
1003
|
-
} else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
|
|
1004
|
-
else if (a != null) {
|
|
1005
|
-
if (target != null) return { error: `one target only (got '${target}' and '${a}')` };
|
|
1006
|
-
target = a;
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
return {
|
|
1010
|
-
target,
|
|
1011
|
-
port,
|
|
1012
|
-
bind
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
/** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
|
|
1016
|
-
function makeRequestListener(app) {
|
|
1017
|
-
return (req, res) => {
|
|
1018
|
-
const cors = {
|
|
1019
|
-
"access-control-allow-origin": "*",
|
|
1020
|
-
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
|
|
1021
|
-
"access-control-allow-headers": "content-type, accept"
|
|
1022
|
-
};
|
|
1023
|
-
const chunks = [];
|
|
1024
|
-
let size = 0;
|
|
1025
|
-
let overflow = false;
|
|
1026
|
-
req.on("error", (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`));
|
|
1027
|
-
req.on("data", (c) => {
|
|
1028
|
-
if (overflow) return;
|
|
1029
|
-
size += c.length;
|
|
1030
|
-
if (size > BODY_CAP) {
|
|
1031
|
-
overflow = true;
|
|
1032
|
-
res.writeHead(413, {
|
|
1033
|
-
"content-type": "application/json",
|
|
1034
|
-
...cors
|
|
1035
|
-
});
|
|
1036
|
-
res.end(JSON.stringify({ error: "payload too large" }), () => req.destroy());
|
|
1037
|
-
} else chunks.push(c);
|
|
1038
|
-
});
|
|
1039
|
-
req.on("end", () => {
|
|
1040
|
-
if (overflow) return;
|
|
1041
|
-
if (req.method === "OPTIONS") {
|
|
1042
|
-
res.writeHead(204, cors);
|
|
1043
|
-
res.end();
|
|
1044
|
-
return;
|
|
1045
|
-
}
|
|
1046
|
-
app.handle({
|
|
1047
|
-
method: req.method ?? "GET",
|
|
1048
|
-
url: req.url ?? "/",
|
|
1049
|
-
accept: req.headers.accept,
|
|
1050
|
-
body: Buffer.concat(chunks).toString("utf8")
|
|
1051
|
-
}).then((reply) => {
|
|
1052
|
-
res.writeHead(reply.status, {
|
|
1053
|
-
"content-type": reply.contentType,
|
|
1054
|
-
...cors
|
|
1055
|
-
});
|
|
1056
|
-
res.end(reply.body);
|
|
1057
|
-
}).catch((e) => {
|
|
1058
|
-
console.error(`[serve] response write failed: ${extractErrorMessage(e)}`);
|
|
1059
|
-
res.destroy();
|
|
1060
|
-
});
|
|
1061
|
-
});
|
|
1062
|
-
};
|
|
1063
|
-
}
|
|
1064
|
-
async function runServe(args) {
|
|
1065
|
-
const parsed = parseArgs(args);
|
|
1066
|
-
if ("error" in parsed) {
|
|
1067
|
-
console.error(`[comfy-ts serve] ${parsed.error}`);
|
|
1068
|
-
return 1;
|
|
1069
|
-
}
|
|
1070
|
-
const target = resolve(parsed.target ?? ".");
|
|
1071
|
-
let files;
|
|
1072
|
-
try {
|
|
1073
|
-
files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target];
|
|
1074
|
-
} catch {
|
|
1075
|
-
console.error(`[comfy-ts serve] no such file or directory: ${target}`);
|
|
1076
|
-
return 1;
|
|
1077
|
-
}
|
|
1078
|
-
if (files.length === 0) {
|
|
1079
|
-
console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`);
|
|
1080
|
-
return 1;
|
|
1081
|
-
}
|
|
1082
|
-
const modules = [];
|
|
1083
|
-
const loadErrors = {};
|
|
1084
|
-
for (const file of files) try {
|
|
1085
|
-
const dw = findDefinedWorkflow(await import(pathToFileURL(file).href));
|
|
1086
|
-
if (dw == null) throw new Error("exports no DefinedWorkflow");
|
|
1087
|
-
const key = draftKeyForFile(file);
|
|
1088
|
-
const clash = modules.find((m) => m.key === key);
|
|
1089
|
-
if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`);
|
|
1090
|
-
modules.push({
|
|
1091
|
-
key,
|
|
1092
|
-
file,
|
|
1093
|
-
dw
|
|
1094
|
-
});
|
|
1095
|
-
} catch (e) {
|
|
1096
|
-
loadErrors[file] = extractErrorMessage(e);
|
|
1097
|
-
console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`);
|
|
1098
|
-
}
|
|
1099
|
-
if (modules.length === 0) {
|
|
1100
|
-
console.error("[comfy-ts serve] every module failed to load — nothing to serve");
|
|
1101
|
-
return 1;
|
|
1102
|
-
}
|
|
1103
|
-
const app = new ServeApp(modules, {
|
|
1104
|
-
loadErrors,
|
|
1105
|
-
webJs: loadOrBuildWebJs
|
|
1106
|
-
});
|
|
1107
|
-
printStartup(app, parsed.bind, parsed.port);
|
|
1108
|
-
const server = createServer(makeRequestListener(app));
|
|
1109
|
-
server.on("error", (e) => {
|
|
1110
|
-
console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`);
|
|
1111
|
-
process.exitCode = 1;
|
|
1112
|
-
server.close();
|
|
1113
|
-
});
|
|
1114
|
-
server.listen(parsed.port, parsed.bind);
|
|
1115
|
-
return new Promise((resolveExit) => {
|
|
1116
|
-
server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
|
|
1117
|
-
});
|
|
1118
|
-
}
|
|
1119
|
-
/** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
|
|
1120
|
-
* only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
|
|
1121
|
-
function reachableAddresses(bind, nics) {
|
|
1122
|
-
if (bind !== "0.0.0.0" && bind !== "::") return [bind];
|
|
1123
|
-
const found = [];
|
|
1124
|
-
for (const list of Object.values(nics)) for (const nic of list ?? []) {
|
|
1125
|
-
if (nic.internal || nic.family !== "IPv4" && nic.family !== 4) continue;
|
|
1126
|
-
found.push(nic.address);
|
|
1127
|
-
}
|
|
1128
|
-
return ["127.0.0.1", ...found];
|
|
1129
|
-
}
|
|
1130
|
-
/** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one he wants */
|
|
1131
|
-
function addressNote(addr) {
|
|
1132
|
-
const octets = addr.split(".").map(Number);
|
|
1133
|
-
const second = octets[1] ?? 0;
|
|
1134
|
-
return octets[0] === 100 && second >= 64 && second <= 127 ? " (tailnet)" : "";
|
|
1135
|
-
}
|
|
1136
|
-
function printStartup(app, bind, port) {
|
|
1137
|
-
const base = `http://${bind}:${port}`;
|
|
1138
|
-
console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`);
|
|
1139
|
-
if (bind !== "127.0.0.1" && bind !== "localhost") {
|
|
1140
|
-
console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`);
|
|
1141
|
-
const urls = reachableAddresses(bind, networkInterfaces());
|
|
1142
|
-
if (urls.length > 1) {
|
|
1143
|
-
console.log("reachable at:");
|
|
1144
|
-
for (const addr of urls) console.log(` http://${addr}:${port}/${addressNote(addr)}`);
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
for (const mod of app.modules) {
|
|
1148
|
-
console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`);
|
|
1149
|
-
for (const draft of app.draftsFor(mod)) console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`);
|
|
1150
|
-
const entries = mod.dw.entries();
|
|
1151
|
-
const nameWidth = Math.max(...entries.map(([n]) => n.length), 4);
|
|
1152
|
-
for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth));
|
|
1153
|
-
}
|
|
1154
|
-
const firstMod = app.modules[0];
|
|
1155
|
-
if (firstMod != null) console.log(`\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`);
|
|
1156
|
-
console.log(`docs: GET ${base}/drafts (json index of everything above)`);
|
|
1157
|
-
console.log(`ui: open ${base}/ in a browser (every var as a form control)`);
|
|
1158
|
-
}
|
|
1159
|
-
//#endregion
|
|
1160
|
-
export { runServe };
|
|
1161
|
-
|
|
1162
|
-
//# sourceMappingURL=run-serve-D1Tsuru9.js.map
|