comfy-ts 1.3.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -6
- package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-CqNE_kgR.js} +67 -14
- package/dist/DefinedWorkflow-CqNE_kgR.js.map +1 -0
- package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-Da4DZUP7.js} +2 -2
- package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-Da4DZUP7.js.map} +1 -1
- package/dist/cli.js +3 -3
- package/dist/index.cjs +548 -239
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +164 -116
- package/dist/index.d.ts +165 -117
- package/dist/index.js +540 -230
- package/dist/index.js.map +1 -1
- package/dist/{run-serve-Bn6yIJB0.js → run-serve-BqeXtf8P.js} +9 -7
- package/dist/run-serve-BqeXtf8P.js.map +1 -0
- package/dist/{run-tui-BtjaOXRh.js → run-tui-CiB7TbYv.js} +18 -13
- package/dist/run-tui-CiB7TbYv.js.map +1 -0
- package/dist/{state-DKCPy105.js → state-C1g_B8zR.js} +398 -201
- package/dist/state-C1g_B8zR.js.map +1 -0
- package/dist/web.d.ts +17335 -0
- package/dist/web.js +5715 -0
- package/dist/web.js.map +1 -0
- package/examples/comfy-cloud/ace-step-t2a.cflow.ts +1 -0
- package/examples/comfy-cloud/anima-t2i.cflow.ts +2 -3
- package/examples/comfy-cloud/boogu-i2i.cflow.ts +2 -5
- package/examples/comfy-cloud/capybara-i2i.cflow.ts +2 -2
- package/examples/comfy-cloud/capybara-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/capybara-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +1 -0
- package/examples/comfy-cloud/chroma-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/ernie-t2i.cflow.ts +2 -3
- package/examples/comfy-cloud/firered-i2i.cflow.ts +2 -2
- package/examples/comfy-cloud/flux1-i2i.cflow.ts +2 -2
- package/examples/comfy-cloud/flux1-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/flux2-i2i.cflow.ts +2 -5
- package/examples/comfy-cloud/flux2-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/hidream-i2i.cflow.ts +2 -5
- package/examples/comfy-cloud/hidream-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +2 -3
- package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/krea2-t2i.cflow.ts +2 -3
- package/examples/comfy-cloud/lens-t2i.cflow.ts +2 -3
- package/examples/comfy-cloud/longcat-i2i.cflow.ts +2 -2
- package/examples/comfy-cloud/longcat-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/ltxv-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/ltxv-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/newbie-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +2 -5
- package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/ovis-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +2 -5
- package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +2 -2
- package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/sd35-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/sdk.d.ts +13251 -11458
- package/examples/comfy-cloud/sdxl-t2i.cflow.ts +2 -2
- package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +1 -0
- package/examples/comfy-cloud/svd-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/wan21-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/wan21-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/wan22-i2v.cflow.ts +1 -0
- package/examples/comfy-cloud/wan22-t2v.cflow.ts +1 -0
- package/examples/comfy-cloud/z-image-t2i.cflow.ts +2 -5
- package/examples/rvion/01-txt2img.cflow.ts +5 -3
- package/examples/rvion/02-img2img-upload.cflow.ts +5 -4
- package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +6 -7
- package/examples/rvion/05-comfy-cloud.cflow.ts +4 -2
- package/examples/rvion/06-qwen-image-edit.cflow.ts +2 -3
- package/examples/web/example.ts +78 -0
- package/examples/web/index.html +77 -0
- package/examples/web/serve.ts +42 -0
- package/examples/web/tsconfig.json +15 -0
- package/package.json +8 -2
- package/src/cli/serve/ServeApp.ts +9 -6
- package/src/cli/tui/state/ExecSt.ts +14 -2
- package/src/coreExports.ts +118 -0
- package/src/host/ComfyHost.ts +56 -24
- package/src/host/ResilientWebsocket.ts +93 -47
- package/src/host/hostUrl.ts +2 -1
- package/src/host/loraManagerApi.ts +6 -7
- package/src/index.ts +8 -107
- package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
- package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
- package/src/manager/loaders/step4_model-list-loader.ts +7 -7
- package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
- package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
- package/src/runner/ComfyExecution.ts +168 -77
- package/src/runner/ComfyWorkflow.ts +25 -3
- package/src/runner/ComfyWsApi.ts +6 -0
- package/src/runner/MediaImage.ts +73 -38
- package/src/runner/ephemeral.ts +21 -0
- package/src/runner/outputPath.ts +2 -2
- package/src/sdk-generator/ComfySchema.ts +2 -2
- package/src/sdk-generator/_pythonModuleToNamespace.ts +3 -0
- package/src/state.ts +13 -9
- package/src/storage/ComfyStorage.ts +144 -0
- package/src/storage/nodeStorage.ts +9 -0
- package/src/types/index.ts +6 -2
- package/src/utils/downloadFile.ts +11 -69
- package/src/utils/hashArrayBuffer.ts +3 -4
- package/src/utils/lazySharp.ts +25 -0
- package/src/utils/sha1.ts +69 -0
- package/src/vars/ComfyVars.ts +5 -6
- package/src/vars/DefinedWorkflow.ts +3 -1
- package/src/vars/loraKeywords.ts +6 -6
- package/src/web.ts +13 -0
- package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
- package/dist/run-serve-Bn6yIJB0.js.map +0 -1
- package/dist/run-tui-BtjaOXRh.js.map +0 -1
- package/dist/state-DKCPy105.js.map +0 -1
- package/src/utils/writeFile.ts +0 -16
package/dist/index.cjs
CHANGED
|
@@ -23,24 +23,118 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
23
23
|
//#endregion
|
|
24
24
|
let node_fs = require("node:fs");
|
|
25
25
|
node_fs = __toESM(node_fs, 1);
|
|
26
|
+
let node_os = require("node:os");
|
|
27
|
+
node_os = __toESM(node_os, 1);
|
|
26
28
|
let pathe = require("pathe");
|
|
27
29
|
let arktype = require("arktype");
|
|
28
30
|
let nanoid = require("nanoid");
|
|
29
|
-
let sharp = require("sharp");
|
|
30
|
-
sharp = __toESM(sharp, 1);
|
|
31
31
|
let image_meta = require("image-meta");
|
|
32
|
-
let node_crypto = require("node:crypto");
|
|
33
|
-
node_crypto = __toESM(node_crypto, 1);
|
|
34
|
-
let ws = require("ws");
|
|
35
|
-
ws = __toESM(ws, 1);
|
|
36
|
-
let node_os = require("node:os");
|
|
37
32
|
let mobx = require("mobx");
|
|
38
|
-
let node_https = require("node:https");
|
|
39
|
-
node_https = __toESM(node_https, 1);
|
|
40
|
-
let node_process = require("node:process");
|
|
41
33
|
let node_url = require("node:url");
|
|
34
|
+
//#region src/storage/ComfyStorage.ts
|
|
35
|
+
function dirnameOf(path) {
|
|
36
|
+
const ix = path.lastIndexOf("/");
|
|
37
|
+
return ix <= 0 ? "/" : path.slice(0, ix);
|
|
38
|
+
}
|
|
39
|
+
/** node backend built from INJECTED modules: nodeStorage.ts passes its static
|
|
40
|
+
* imports, the autodetect below passes process.getBuiltinModule results */
|
|
41
|
+
function createNodeStorageFrom(fs, os) {
|
|
42
|
+
return {
|
|
43
|
+
kind: "node",
|
|
44
|
+
readText: (p) => fs.readFileSync(p, "utf8"),
|
|
45
|
+
readTextIfExists: (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null,
|
|
46
|
+
readBytes: (p) => new Uint8Array(fs.readFileSync(p)),
|
|
47
|
+
writeText: (p, text) => {
|
|
48
|
+
fs.mkdirSync(dirnameOf(p), { recursive: true });
|
|
49
|
+
fs.writeFileSync(p, text);
|
|
50
|
+
},
|
|
51
|
+
writeBytes: (p, bytes) => {
|
|
52
|
+
fs.mkdirSync(dirnameOf(p), { recursive: true });
|
|
53
|
+
fs.writeFileSync(p, bytes);
|
|
54
|
+
},
|
|
55
|
+
exists: (p) => fs.existsSync(p),
|
|
56
|
+
mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
|
|
57
|
+
mtimeMs: (p) => fs.existsSync(p) ? fs.statSync(p).mtimeMs : null,
|
|
58
|
+
homedir: () => os.homedir(),
|
|
59
|
+
cwd: () => process.cwd()
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** in-memory backend: the web default, also handy for hermetic tests.
|
|
63
|
+
* Paths are LITERAL keys (no normalization — core callers resolve through
|
|
64
|
+
* pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
|
|
65
|
+
* dirs only, never implicit parents. Bytes are copied in AND out so neither
|
|
66
|
+
* side can mutate the store. */
|
|
67
|
+
function createMemoryStorage(p = {}) {
|
|
68
|
+
const files = /* @__PURE__ */ new Map();
|
|
69
|
+
const mtimes = /* @__PURE__ */ new Map();
|
|
70
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
71
|
+
const td = new TextDecoder();
|
|
72
|
+
const te = new TextEncoder();
|
|
73
|
+
const write = (path, bytes) => {
|
|
74
|
+
files.set(path, bytes.slice());
|
|
75
|
+
mtimes.set(path, Date.now());
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
kind: "memory",
|
|
79
|
+
readText: (path) => {
|
|
80
|
+
const hit = files.get(path);
|
|
81
|
+
if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
|
|
82
|
+
return td.decode(hit);
|
|
83
|
+
},
|
|
84
|
+
readTextIfExists: (path) => {
|
|
85
|
+
const hit = files.get(path);
|
|
86
|
+
return hit == null ? null : td.decode(hit);
|
|
87
|
+
},
|
|
88
|
+
readBytes: (path) => {
|
|
89
|
+
const hit = files.get(path);
|
|
90
|
+
if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
|
|
91
|
+
return hit.slice();
|
|
92
|
+
},
|
|
93
|
+
writeText: (path, text) => write(path, te.encode(text)),
|
|
94
|
+
writeBytes: write,
|
|
95
|
+
exists: (path) => files.has(path) || dirs.has(path),
|
|
96
|
+
mkdirp: (path) => void dirs.add(path),
|
|
97
|
+
mtimeMs: (path) => mtimes.get(path) ?? null,
|
|
98
|
+
homedir: () => p.homedir ?? "/home/web",
|
|
99
|
+
cwd: () => p.cwd ?? "/"
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
let installedDefault = null;
|
|
103
|
+
/** entries call this at import time: index.ts installs node, web.ts memory */
|
|
104
|
+
function setDefaultComfyStorage(storage) {
|
|
105
|
+
installedDefault = storage;
|
|
106
|
+
}
|
|
107
|
+
function autodetectNodeStorage() {
|
|
108
|
+
const get = globalThis.process?.getBuiltinModule;
|
|
109
|
+
if (typeof get !== "function") return null;
|
|
110
|
+
const fs = get("node:fs");
|
|
111
|
+
const os = get("node:os");
|
|
112
|
+
if (fs == null || os == null) return null;
|
|
113
|
+
return createNodeStorageFrom(fs, os);
|
|
114
|
+
}
|
|
115
|
+
function resolveComfyStorage(explicit) {
|
|
116
|
+
if (explicit != null) return explicit;
|
|
117
|
+
if (installedDefault != null) return installedDefault;
|
|
118
|
+
const detected = autodetectNodeStorage();
|
|
119
|
+
if (detected != null) {
|
|
120
|
+
installedDefault = detected;
|
|
121
|
+
return detected;
|
|
122
|
+
}
|
|
123
|
+
throw new Error(`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`);
|
|
124
|
+
}
|
|
125
|
+
/** the ONE accessor call sites use: the instance's storage when the global
|
|
126
|
+
* exists, the resolved default otherwise (vars constructed before create()) */
|
|
127
|
+
function getComfyStorage() {
|
|
128
|
+
return globalThis.comfyts?.storage ?? resolveComfyStorage();
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region src/storage/nodeStorage.ts
|
|
132
|
+
function createNodeStorage() {
|
|
133
|
+
return createNodeStorageFrom(node_fs, node_os);
|
|
134
|
+
}
|
|
135
|
+
//#endregion
|
|
42
136
|
//#region package.json
|
|
43
|
-
var version = "
|
|
137
|
+
var version = "2.0.0";
|
|
44
138
|
//#endregion
|
|
45
139
|
//#region src/litegraph/LiteGraphLinkID.ts
|
|
46
140
|
const asLiteGraphLinkID = (id) => id;
|
|
@@ -1592,7 +1686,7 @@ var LiteGraphCtx = class {
|
|
|
1592
1686
|
* `_00001_` counter every run, so trusting it overwrote the same file — and
|
|
1593
1687
|
* a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
|
|
1594
1688
|
* prefix. Local names are ours: dir from the prompt's own filename_prefix
|
|
1595
|
-
* (or an explicit
|
|
1689
|
+
* (or an explicit save.prefix override), then
|
|
1596
1690
|
* `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
|
|
1597
1691
|
* per stem and nothing ever collides.
|
|
1598
1692
|
*/
|
|
@@ -1644,6 +1738,32 @@ const runTimestamp = (d) => {
|
|
|
1644
1738
|
return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
|
|
1645
1739
|
};
|
|
1646
1740
|
//#endregion
|
|
1741
|
+
//#region src/utils/extractErrorMessage.ts
|
|
1742
|
+
/** Extracts an error message from an exception stuff. */
|
|
1743
|
+
const extractErrorMessage = (error) => {
|
|
1744
|
+
if (error instanceof Error) return error.message;
|
|
1745
|
+
if (error === null) return "null";
|
|
1746
|
+
if (typeof error === "string") return error;
|
|
1747
|
+
if (typeof error === "object") {
|
|
1748
|
+
if ("message" in error && typeof error.message === "string") return error.message;
|
|
1749
|
+
return JSON.stringify(error);
|
|
1750
|
+
}
|
|
1751
|
+
return String(error);
|
|
1752
|
+
};
|
|
1753
|
+
//#endregion
|
|
1754
|
+
//#region src/utils/lazySharp.ts
|
|
1755
|
+
let cached = null;
|
|
1756
|
+
async function importSharp(reason) {
|
|
1757
|
+
if (cached != null) return cached;
|
|
1758
|
+
const specifier = "sharp";
|
|
1759
|
+
try {
|
|
1760
|
+
cached = (await import(specifier)).default;
|
|
1761
|
+
return cached;
|
|
1762
|
+
} catch (e) {
|
|
1763
|
+
throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
//#endregion
|
|
1647
1767
|
//#region src/types/index.ts
|
|
1648
1768
|
const asAbsolutePath = (path) => path;
|
|
1649
1769
|
const asRelativePath = (path) => path;
|
|
@@ -1693,10 +1813,78 @@ function exhaust(x) {
|
|
|
1693
1813
|
return x;
|
|
1694
1814
|
}
|
|
1695
1815
|
//#endregion
|
|
1816
|
+
//#region src/utils/sha1.ts
|
|
1817
|
+
function sha1Hex(data) {
|
|
1818
|
+
const ml = data.length;
|
|
1819
|
+
const total = Math.ceil((ml + 1 + 8) / 64) * 64;
|
|
1820
|
+
const bytes = new Uint8Array(total);
|
|
1821
|
+
bytes.set(data);
|
|
1822
|
+
bytes[ml] = 128;
|
|
1823
|
+
const dv = new DataView(bytes.buffer);
|
|
1824
|
+
const bitLen = ml * 8;
|
|
1825
|
+
dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
|
|
1826
|
+
dv.setUint32(total - 4, bitLen >>> 0);
|
|
1827
|
+
let h0 = 1732584193;
|
|
1828
|
+
let h1 = 4023233417;
|
|
1829
|
+
let h2 = 2562383102;
|
|
1830
|
+
let h3 = 271733878;
|
|
1831
|
+
let h4 = 3285377520;
|
|
1832
|
+
const w = /* @__PURE__ */ new Uint32Array(80);
|
|
1833
|
+
for (let i = 0; i < total; i += 64) {
|
|
1834
|
+
for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
|
|
1835
|
+
for (let j = 16; j < 80; j++) {
|
|
1836
|
+
const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
|
|
1837
|
+
w[j] = n << 1 | n >>> 31;
|
|
1838
|
+
}
|
|
1839
|
+
let a = h0;
|
|
1840
|
+
let b = h1;
|
|
1841
|
+
let c = h2;
|
|
1842
|
+
let d = h3;
|
|
1843
|
+
let e = h4;
|
|
1844
|
+
for (let j = 0; j < 80; j++) {
|
|
1845
|
+
let f;
|
|
1846
|
+
let k;
|
|
1847
|
+
if (j < 20) {
|
|
1848
|
+
f = b & c | ~b & d;
|
|
1849
|
+
k = 1518500249;
|
|
1850
|
+
} else if (j < 40) {
|
|
1851
|
+
f = b ^ c ^ d;
|
|
1852
|
+
k = 1859775393;
|
|
1853
|
+
} else if (j < 60) {
|
|
1854
|
+
f = b & c | b & d | c & d;
|
|
1855
|
+
k = 2400959708;
|
|
1856
|
+
} else {
|
|
1857
|
+
f = b ^ c ^ d;
|
|
1858
|
+
k = 3395469782;
|
|
1859
|
+
}
|
|
1860
|
+
const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
|
|
1861
|
+
e = d;
|
|
1862
|
+
d = c;
|
|
1863
|
+
c = b << 30 | b >>> 2;
|
|
1864
|
+
b = a;
|
|
1865
|
+
a = temp;
|
|
1866
|
+
}
|
|
1867
|
+
h0 = h0 + a >>> 0;
|
|
1868
|
+
h1 = h1 + b >>> 0;
|
|
1869
|
+
h2 = h2 + c >>> 0;
|
|
1870
|
+
h3 = h3 + d >>> 0;
|
|
1871
|
+
h4 = h4 + e >>> 0;
|
|
1872
|
+
}
|
|
1873
|
+
return [
|
|
1874
|
+
h0,
|
|
1875
|
+
h1,
|
|
1876
|
+
h2,
|
|
1877
|
+
h3,
|
|
1878
|
+
h4
|
|
1879
|
+
].map((x) => x.toString(16).padStart(8, "0")).join("");
|
|
1880
|
+
}
|
|
1881
|
+
function sha1HexOfString(s) {
|
|
1882
|
+
return sha1Hex(new TextEncoder().encode(s));
|
|
1883
|
+
}
|
|
1884
|
+
//#endregion
|
|
1696
1885
|
//#region src/utils/hashArrayBuffer.ts
|
|
1697
1886
|
const hashArrayBuffer = (buffer) => {
|
|
1698
|
-
|
|
1699
|
-
return node_crypto.default.createHash("sha1").update(data).digest("hex");
|
|
1887
|
+
return sha1Hex(buffer);
|
|
1700
1888
|
};
|
|
1701
1889
|
//#endregion
|
|
1702
1890
|
//#region src/graph/ComfyNodeID.ts
|
|
@@ -1831,6 +2019,21 @@ const PromptInfo_ark = (0, arktype.type)({ prompt_id: types$1.PromptID }).as();
|
|
|
1831
2019
|
const WsMsg_ark = types$1.WsMsg;
|
|
1832
2020
|
const ComfyImageInfo_ark = types$1.ComfyImageInfo;
|
|
1833
2021
|
const WsMsgLogsData_ark = types$1._WsMsgLogsData;
|
|
2022
|
+
//#endregion
|
|
2023
|
+
//#region src/runner/MediaImage.ts
|
|
2024
|
+
/** base64 image loader nodes we know how to wire, in preference order — each
|
|
2025
|
+
* verified against a real object_info dump before entering the table */
|
|
2026
|
+
const BASE64_IMAGE_LOADERS = [{
|
|
2027
|
+
nameInComfy: "ETN_LoadImageBase64",
|
|
2028
|
+
inputs: (b64) => ({ image: b64 })
|
|
2029
|
+
}, {
|
|
2030
|
+
nameInComfy: "easy loadImageBase64",
|
|
2031
|
+
inputs: (b64) => ({
|
|
2032
|
+
base64_data: b64,
|
|
2033
|
+
image_output: "Hide",
|
|
2034
|
+
save_prefix: ""
|
|
2035
|
+
})
|
|
2036
|
+
}];
|
|
1834
2037
|
(0, arktype.type)({
|
|
1835
2038
|
comfyHostHttpURL: "string",
|
|
1836
2039
|
comfyImageInfo: ComfyImageInfo_ark
|
|
@@ -1859,8 +2062,19 @@ var MediaImage = class MediaImage {
|
|
|
1859
2062
|
channel
|
|
1860
2063
|
});
|
|
1861
2064
|
};
|
|
2065
|
+
this.loadInWorkflow_viaBase64Node = (workflow) => {
|
|
2066
|
+
const schema = workflow.host.schema;
|
|
2067
|
+
const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy));
|
|
2068
|
+
if (entry == null) throw new Error(`❌ host '${workflow.host.data.id}' has no base64 image loader node (looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(", ")}). Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`);
|
|
2069
|
+
return new ComfyNode(workflow, (workflow._uidNumber++).toString(), {
|
|
2070
|
+
class_type: entry.nameInComfy,
|
|
2071
|
+
inputs: entry.inputs(this.getBase64Payload())
|
|
2072
|
+
}, {});
|
|
2073
|
+
};
|
|
1862
2074
|
this._buffer = null;
|
|
1863
|
-
this.freeBuffer = () =>
|
|
2075
|
+
this.freeBuffer = () => {
|
|
2076
|
+
if (this.absPath != null) this._buffer = null;
|
|
2077
|
+
};
|
|
1864
2078
|
this.updateBuffer = (buff) => {
|
|
1865
2079
|
this._buffer = buff;
|
|
1866
2080
|
this._metadata = null;
|
|
@@ -1875,41 +2089,35 @@ var MediaImage = class MediaImage {
|
|
|
1875
2089
|
this._metadata = null;
|
|
1876
2090
|
this._hash = null;
|
|
1877
2091
|
this.processWithSharp_inplace = async (fn) => {
|
|
1878
|
-
const buff = await fn((
|
|
1879
|
-
(
|
|
2092
|
+
const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
|
|
2093
|
+
if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
|
|
1880
2094
|
this.updateBuffer(new Uint8Array(buff));
|
|
1881
2095
|
return this;
|
|
1882
2096
|
};
|
|
1883
2097
|
this.processWithSharp = async (fn, path) => {
|
|
1884
|
-
const
|
|
1885
|
-
path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
|
|
1886
|
-
await
|
|
1887
|
-
|
|
2098
|
+
const sharp = await importSharp("processWithSharp");
|
|
2099
|
+
path ??= this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : void 0;
|
|
2100
|
+
const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
|
|
2101
|
+
if (path != null) getComfyStorage().writeBytes(path, buffer);
|
|
1888
2102
|
return new MediaImage({
|
|
1889
2103
|
path,
|
|
1890
2104
|
buffer
|
|
1891
2105
|
});
|
|
1892
2106
|
};
|
|
1893
|
-
this.
|
|
1894
|
-
const img = (0, sharp.default)(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
|
|
1895
|
-
(0, node_fs.mkdirSync)((0, pathe.dirname)(targetPath), { recursive: true });
|
|
1896
|
-
await img.toFile(targetPath);
|
|
1897
|
-
};
|
|
1898
|
-
this.generateMiniPreview = async () => {
|
|
1899
|
-
return (await (0, sharp.default)(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
|
|
1900
|
-
};
|
|
1901
|
-
this.absPath = data.path;
|
|
2107
|
+
this.absPath = data.path ?? null;
|
|
1902
2108
|
this.execution = data.execution;
|
|
1903
2109
|
this.promptNodeID = data.promptNodeID;
|
|
2110
|
+
if (data.path == null && data.buffer == null) throw new Error("❌ MediaImage: an in-memory image (no path) requires a buffer");
|
|
1904
2111
|
if (data.buffer != null) this.updateBuffer(data.buffer);
|
|
1905
2112
|
}
|
|
1906
2113
|
/** the image as a Blob, e.g. to feed FormData uploads */
|
|
1907
2114
|
getAsBlob() {
|
|
1908
2115
|
return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
|
|
1909
2116
|
}
|
|
1910
|
-
/** return the image filename */
|
|
2117
|
+
/** return the image filename (in-memory images get a stable hash-derived name) */
|
|
1911
2118
|
get filename() {
|
|
1912
|
-
return (0, pathe.basename)(this.absPath);
|
|
2119
|
+
if (this.absPath != null) return (0, pathe.basename)(this.absPath);
|
|
2120
|
+
return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? "png"}`;
|
|
1913
2121
|
}
|
|
1914
2122
|
get baseNameWithoutExtension() {
|
|
1915
2123
|
const fname = this.filename;
|
|
@@ -1967,26 +2175,25 @@ var MediaImage = class MediaImage {
|
|
|
1967
2175
|
* does not includes the prefix `data:image/png;base64,`
|
|
1968
2176
|
*/
|
|
1969
2177
|
getBase64Payload() {
|
|
1970
|
-
|
|
2178
|
+
const bytes = this.buffer;
|
|
2179
|
+
let bin = "";
|
|
2180
|
+
const chunk = 32768;
|
|
2181
|
+
for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
|
2182
|
+
return btoa(bin);
|
|
1971
2183
|
}
|
|
1972
2184
|
get buffer() {
|
|
1973
2185
|
if (this._buffer != null) return this._buffer;
|
|
1974
|
-
|
|
1975
|
-
const uint8arr = new Uint8Array(buff);
|
|
1976
|
-
this._buffer = uint8arr;
|
|
2186
|
+
this._buffer = getComfyStorage().readBytes(bang(this.absPath, "in-memory MediaImage lost its buffer"));
|
|
1977
2187
|
return this._buffer;
|
|
1978
2188
|
}
|
|
1979
2189
|
get metadata() {
|
|
1980
2190
|
if (this._metadata != null) return this._metadata;
|
|
1981
|
-
|
|
1982
|
-
const uint8arr = new Uint8Array(buff);
|
|
1983
|
-
this._metadata = (0, image_meta.imageMeta)(uint8arr);
|
|
2191
|
+
this._metadata = (0, image_meta.imageMeta)(this.buffer);
|
|
1984
2192
|
return this._metadata;
|
|
1985
2193
|
}
|
|
1986
2194
|
get hash() {
|
|
1987
2195
|
if (this._hash != null) return this._hash;
|
|
1988
|
-
|
|
1989
|
-
this._hash = hashArrayBuffer(new Uint8Array(buff));
|
|
2196
|
+
this._hash = hashArrayBuffer(this.buffer);
|
|
1990
2197
|
return this._hash;
|
|
1991
2198
|
}
|
|
1992
2199
|
};
|
|
@@ -2002,7 +2209,9 @@ var ComfyExecution = class {
|
|
|
2002
2209
|
constructor(workflow, data, init = {}) {
|
|
2003
2210
|
this.workflow = workflow;
|
|
2004
2211
|
this.data = data;
|
|
2005
|
-
this.
|
|
2212
|
+
this.save = null;
|
|
2213
|
+
this.scrubHistory = false;
|
|
2214
|
+
this.ephemeral = false;
|
|
2006
2215
|
this.snapshot = null;
|
|
2007
2216
|
this.onProgress = null;
|
|
2008
2217
|
this.logProgress = false;
|
|
@@ -2013,6 +2222,13 @@ var ComfyExecution = class {
|
|
|
2013
2222
|
});
|
|
2014
2223
|
this.onPromptRelatedMessage = (msg) => {
|
|
2015
2224
|
const graph = this.workflow;
|
|
2225
|
+
if (msg.type === "binary_preview_frame") {
|
|
2226
|
+
if (this.wsOutputNodeExecuting) this.onWsImageOutput({
|
|
2227
|
+
bytes: msg.bytes,
|
|
2228
|
+
mime: msg.mime
|
|
2229
|
+
});
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2016
2232
|
if (msg.type === "execution_start") return;
|
|
2017
2233
|
else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
|
|
2018
2234
|
else if (msg.type === "executing") this.onExecuting(msg);
|
|
@@ -2056,70 +2272,104 @@ var ComfyExecution = class {
|
|
|
2056
2272
|
this.imageErrors = [];
|
|
2057
2273
|
this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
|
|
2058
2274
|
const promptNode = this.workflow.data.apiJson?.[promptNodeID];
|
|
2059
|
-
const promptMeta = this.workflow.data.metadata?.[promptNodeID];
|
|
2060
2275
|
if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
|
|
2061
2276
|
const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
|
|
2062
|
-
const
|
|
2277
|
+
const response = await this.host.fetchFile(imgRoute);
|
|
2278
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
2279
|
+
const comfyUIInfos = {
|
|
2280
|
+
comfyImageInfo,
|
|
2281
|
+
comfyHostHttpURL: this.host.getServerHostHTTP()
|
|
2282
|
+
};
|
|
2283
|
+
const sf = this.save;
|
|
2284
|
+
if (sf == null) return this.pushImage(new MediaImage({
|
|
2285
|
+
buffer: bytes,
|
|
2286
|
+
execution: this,
|
|
2287
|
+
promptNodeID,
|
|
2288
|
+
comfyUIInfos
|
|
2289
|
+
}), promptNodeID);
|
|
2063
2290
|
const promptPrefix = promptNode.inputs["filename_prefix"];
|
|
2064
|
-
|
|
2065
|
-
|
|
2291
|
+
const written = await this.encodeAndWrite({
|
|
2292
|
+
bytes,
|
|
2293
|
+
sf,
|
|
2066
2294
|
filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
|
|
2067
2295
|
subfolder: comfyImageInfo.subfolder,
|
|
2068
|
-
filename: comfyImageInfo.filename
|
|
2069
|
-
timestamp: runTimestamp(new Date(this.startedAt))
|
|
2070
|
-
}));
|
|
2071
|
-
if (sf?.format && sf.format !== "raw") {
|
|
2072
|
-
const extension = sf.format.split("/")[1];
|
|
2073
|
-
absPath += "." + extension;
|
|
2074
|
-
}
|
|
2075
|
-
absPath = uniquifyOutputPath({
|
|
2076
|
-
path: absPath,
|
|
2077
|
-
exists: node_fs.existsSync,
|
|
2078
|
-
claimed: CLAIMED_OUTPUT_PATHS
|
|
2296
|
+
filename: comfyImageInfo.filename
|
|
2079
2297
|
});
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2298
|
+
this.pushImage(new MediaImage({
|
|
2299
|
+
path: written.path,
|
|
2300
|
+
buffer: written.bytes,
|
|
2301
|
+
execution: this,
|
|
2302
|
+
promptNodeID,
|
|
2303
|
+
comfyUIInfos
|
|
2304
|
+
}), promptNodeID);
|
|
2305
|
+
};
|
|
2306
|
+
this.encodeAndWrite = async (p) => {
|
|
2307
|
+
let bytes = p.bytes;
|
|
2308
|
+
const reencode = p.sf.format != null && p.sf.format !== "raw";
|
|
2309
|
+
if (reencode) {
|
|
2084
2310
|
let textChunk = {};
|
|
2085
2311
|
try {
|
|
2086
|
-
const res = getPngMetadataFromUint8Array(
|
|
2312
|
+
const res = getPngMetadataFromUint8Array(p.bytes);
|
|
2087
2313
|
if (res.success) textChunk = res.value;
|
|
2088
2314
|
} catch {}
|
|
2089
2315
|
const format = (() => {
|
|
2090
|
-
if (sf.format === "image/jpeg") return "jpeg";
|
|
2091
|
-
if (sf.format === "image/
|
|
2092
|
-
if (sf.format === "image/webp") return "webp";
|
|
2316
|
+
if (p.sf.format === "image/jpeg") return "jpeg";
|
|
2317
|
+
if (p.sf.format === "image/webp") return "webp";
|
|
2093
2318
|
return "png";
|
|
2094
2319
|
})();
|
|
2095
|
-
await (
|
|
2096
|
-
|
|
2097
|
-
path: asAbsolutePath(absPath),
|
|
2098
|
-
execution: this,
|
|
2099
|
-
promptNodeID,
|
|
2100
|
-
comfyUIInfos: {
|
|
2101
|
-
comfyImageInfo,
|
|
2102
|
-
comfyHostHttpURL: this.host.getServerHostHTTP()
|
|
2103
|
-
}
|
|
2104
|
-
});
|
|
2105
|
-
} else {
|
|
2106
|
-
const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
|
|
2107
|
-
const uint8arr = new Uint8Array(buff);
|
|
2108
|
-
(0, node_fs.writeFileSync)(absPath, uint8arr);
|
|
2109
|
-
img = new MediaImage({
|
|
2110
|
-
path: asAbsolutePath(absPath),
|
|
2111
|
-
buffer: uint8arr,
|
|
2112
|
-
execution: this,
|
|
2113
|
-
promptNodeID,
|
|
2114
|
-
comfyUIInfos: {
|
|
2115
|
-
comfyImageInfo,
|
|
2116
|
-
comfyHostHttpURL: this.host.getServerHostHTTP()
|
|
2117
|
-
}
|
|
2118
|
-
});
|
|
2320
|
+
const encoded = await (await importSharp(`save format '${p.sf.format}' re-encoding`))(p.bytes).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, p.sf.quality ? { quality: Math.round(p.sf.quality * 100) } : void 0).toBuffer();
|
|
2321
|
+
bytes = new Uint8Array(encoded);
|
|
2119
2322
|
}
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2323
|
+
let absPath = comfyts.resolveFromOutput(localOutputPath({
|
|
2324
|
+
localDir: p.sf.prefix,
|
|
2325
|
+
filenamePrefix: p.filenamePrefix,
|
|
2326
|
+
subfolder: p.subfolder,
|
|
2327
|
+
filename: p.filename,
|
|
2328
|
+
timestamp: runTimestamp(new Date(this.startedAt))
|
|
2329
|
+
}));
|
|
2330
|
+
if (reencode) absPath += "." + bang(p.sf.format).split("/")[1];
|
|
2331
|
+
const storage = getComfyStorage();
|
|
2332
|
+
absPath = uniquifyOutputPath({
|
|
2333
|
+
path: absPath,
|
|
2334
|
+
exists: (x) => storage.exists(x),
|
|
2335
|
+
claimed: CLAIMED_OUTPUT_PATHS
|
|
2336
|
+
});
|
|
2337
|
+
storage.writeBytes(asAbsolutePath(absPath), bytes);
|
|
2338
|
+
return {
|
|
2339
|
+
path: asAbsolutePath(absPath),
|
|
2340
|
+
bytes
|
|
2341
|
+
};
|
|
2342
|
+
};
|
|
2343
|
+
this.onWsImageOutput = (p) => {
|
|
2344
|
+
const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
|
|
2345
|
+
this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
|
|
2346
|
+
console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
|
|
2347
|
+
this.imageErrors.push({
|
|
2348
|
+
image: null,
|
|
2349
|
+
error: e
|
|
2350
|
+
});
|
|
2351
|
+
}));
|
|
2352
|
+
};
|
|
2353
|
+
this.storeWsImage = async (p, promptNodeID) => {
|
|
2354
|
+
const sf = this.save;
|
|
2355
|
+
if (sf == null) return this.pushImage(new MediaImage({
|
|
2356
|
+
buffer: p.bytes,
|
|
2357
|
+
execution: this,
|
|
2358
|
+
promptNodeID
|
|
2359
|
+
}), promptNodeID);
|
|
2360
|
+
const ext = p.mime === "image/jpeg" ? "jpg" : p.mime.split("/")[1] ?? "png";
|
|
2361
|
+
const written = await this.encodeAndWrite({
|
|
2362
|
+
bytes: p.bytes,
|
|
2363
|
+
sf,
|
|
2364
|
+
subfolder: "",
|
|
2365
|
+
filename: `${this.workflow.id}.${ext}`
|
|
2366
|
+
});
|
|
2367
|
+
this.pushImage(new MediaImage({
|
|
2368
|
+
path: written.path,
|
|
2369
|
+
buffer: written.bytes,
|
|
2370
|
+
execution: this,
|
|
2371
|
+
promptNodeID
|
|
2372
|
+
}), promptNodeID);
|
|
2123
2373
|
};
|
|
2124
2374
|
this.images = [];
|
|
2125
2375
|
this.alreadyDone = false;
|
|
@@ -2133,11 +2383,20 @@ var ComfyExecution = class {
|
|
|
2133
2383
|
await Promise.all(this.pendingPromises);
|
|
2134
2384
|
this.host.executions.delete(this.data.id);
|
|
2135
2385
|
this.host._pendingMsgs.delete(this.data.id);
|
|
2386
|
+
if (this.ephemeral) {
|
|
2387
|
+
const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type);
|
|
2388
|
+
if (classTypes.includes("LoadImage") || classTypes.includes("LoadImageMask")) console.warn(`🟡 ephemeral run ${this.data.id}: outputs never touched the server disk, but the graph's LoadImage nodes reference files in the host's input/ folder (uploads persist — ComfyUI has no delete API). Use MediaImage.loadInWorkflow_viaBase64Node to keep inputs off the server too.`);
|
|
2389
|
+
}
|
|
2390
|
+
if (this.scrubHistory) await this.host.deleteHistory(this.data.id).catch((e) => {
|
|
2391
|
+
console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e);
|
|
2392
|
+
});
|
|
2136
2393
|
this.finishProgressLine();
|
|
2137
2394
|
this._resolve(this);
|
|
2138
2395
|
};
|
|
2139
2396
|
this.snapshot = init.snapshot ?? null;
|
|
2140
|
-
this.
|
|
2397
|
+
this.save = init.save === true ? {} : init.save === false ? null : init.save ?? null;
|
|
2398
|
+
this.scrubHistory = init.scrubHistory ?? false;
|
|
2399
|
+
this.ephemeral = init.ephemeral ?? false;
|
|
2141
2400
|
this.onProgress = init.onProgress ?? null;
|
|
2142
2401
|
this.logProgress = init.logProgress ?? false;
|
|
2143
2402
|
this.host.executions.set(data.id, this);
|
|
@@ -2162,14 +2421,14 @@ var ComfyExecution = class {
|
|
|
2162
2421
|
const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
|
|
2163
2422
|
if (line === this._lastLoggedLine) return;
|
|
2164
2423
|
this._lastLoggedLine = line;
|
|
2165
|
-
if (process
|
|
2424
|
+
if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
|
|
2166
2425
|
else console.log(line);
|
|
2167
2426
|
}
|
|
2168
2427
|
finishProgressLine() {
|
|
2169
2428
|
if (!this.logProgress) return;
|
|
2170
2429
|
const p = this.progress;
|
|
2171
2430
|
const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
|
|
2172
|
-
if (process
|
|
2431
|
+
if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
|
|
2173
2432
|
else console.log(line);
|
|
2174
2433
|
}
|
|
2175
2434
|
log(...args) {
|
|
@@ -2195,11 +2454,47 @@ var ComfyExecution = class {
|
|
|
2195
2454
|
get status() {
|
|
2196
2455
|
return this.data.status ?? "New";
|
|
2197
2456
|
}
|
|
2457
|
+
/** accumulate an output on the prompt; tags from node metadata ride along */
|
|
2458
|
+
pushImage(img, promptNodeID) {
|
|
2459
|
+
const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
|
|
2460
|
+
if (promptMeta?.tag) img.tags.push(promptMeta.tag);
|
|
2461
|
+
if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
|
|
2462
|
+
this.images.push(img);
|
|
2463
|
+
}
|
|
2464
|
+
/** true while the currently executing node is a SaveImageWebsocket in the
|
|
2465
|
+
* SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
|
|
2466
|
+
* live graph may still say SaveImage) — binary frames are then OUTPUTS */
|
|
2467
|
+
get wsOutputNodeExecuting() {
|
|
2468
|
+
const uid = this.workflow.currentExecutingNode?.uid;
|
|
2469
|
+
if (uid == null) return false;
|
|
2470
|
+
return (this.snapshot?.apiJson ?? this.workflow.apiJson)[uid]?.class_type === "SaveImageWebsocket";
|
|
2471
|
+
}
|
|
2198
2472
|
update(data) {
|
|
2199
2473
|
Object.assign(this.data, data);
|
|
2200
2474
|
}
|
|
2201
2475
|
};
|
|
2202
2476
|
//#endregion
|
|
2477
|
+
//#region src/runner/ephemeral.ts
|
|
2478
|
+
/**
|
|
2479
|
+
* the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
|
|
2480
|
+
* node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`
|
|
2481
|
+
* input only), so outputs stream over the ws and never touch the server disk.
|
|
2482
|
+
* Mutates the given apiJson IN PLACE — callers pass the run's deep-copied
|
|
2483
|
+
* snapshot, never the live graph. Returns how many nodes were rewritten so
|
|
2484
|
+
* callers can warn when a graph had nothing to rewrite.
|
|
2485
|
+
*/
|
|
2486
|
+
function rewriteSaveNodesToWebsocket(apiJson) {
|
|
2487
|
+
let rewritten = 0;
|
|
2488
|
+
for (const node of Object.values(apiJson)) {
|
|
2489
|
+
if (node.class_type !== "SaveImage") continue;
|
|
2490
|
+
const images = node.inputs["images"];
|
|
2491
|
+
node.class_type = "SaveImageWebsocket";
|
|
2492
|
+
node.inputs = images == null ? {} : { images };
|
|
2493
|
+
rewritten++;
|
|
2494
|
+
}
|
|
2495
|
+
return rewritten;
|
|
2496
|
+
}
|
|
2497
|
+
//#endregion
|
|
2203
2498
|
//#region src/utils/deepCopyNaive.ts
|
|
2204
2499
|
const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
|
|
2205
2500
|
//#endregion
|
|
@@ -2466,6 +2761,11 @@ var ComfyWorkflow = class {
|
|
|
2466
2761
|
apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
|
|
2467
2762
|
workflowJson: await this.toWorkflowJson()
|
|
2468
2763
|
};
|
|
2764
|
+
if (p.ephemeral) {
|
|
2765
|
+
const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson);
|
|
2766
|
+
const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === "SaveImageWebsocket");
|
|
2767
|
+
if (rewritten === 0 && !hasWsSaver) console.warn(`🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`);
|
|
2768
|
+
}
|
|
2469
2769
|
const out = {
|
|
2470
2770
|
client_id: this.host.comfySessionId,
|
|
2471
2771
|
prompt: snapshot.apiJson,
|
|
@@ -2488,7 +2788,9 @@ var ComfyWorkflow = class {
|
|
|
2488
2788
|
graphID: this.id
|
|
2489
2789
|
}, {
|
|
2490
2790
|
snapshot,
|
|
2491
|
-
|
|
2791
|
+
save: p.save,
|
|
2792
|
+
ephemeral: p.ephemeral ?? false,
|
|
2793
|
+
scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
|
|
2492
2794
|
onProgress: p.onProgress,
|
|
2493
2795
|
logProgress: p.log ?? false
|
|
2494
2796
|
});
|
|
@@ -2582,6 +2884,7 @@ function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
|
|
|
2582
2884
|
function pythonModuleToPrefix(pythonModule) {
|
|
2583
2885
|
if (pythonModule === "nodes") return "";
|
|
2584
2886
|
if (pythonModule.startsWith("comfy_extras.")) return "";
|
|
2887
|
+
if (pythonModule === "custom_nodes.websocket_image_save") return "";
|
|
2585
2888
|
if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
|
|
2586
2889
|
if (pythonModule.startsWith("custom_nodes.")) return pythonModule.replace(/^custom_nodes\./i, "").replace(/^comfyui[-_]/i, "").replace(/[-_]comfyui$/i, "").replace(/^comfy[-_]/i, "").replace(/[-_]comfy$/i, "").replace(/^nodes[-_]/i, "").replace(/[-_]node[-_]suite$/i, "") + ".";
|
|
2587
2890
|
console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
|
|
@@ -2918,7 +3221,7 @@ var ComfySchema = class {
|
|
|
2918
3221
|
else if (typeof enumValue === "number") enumValues.push(enumValue);
|
|
2919
3222
|
else enumValues.push(enumValue.content);
|
|
2920
3223
|
const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
|
|
2921
|
-
const hash =
|
|
3224
|
+
const hash = sha1HexOfString(hashContent).slice(0, 8);
|
|
2922
3225
|
let unionInfo = this.knownUnionByHash.get(hash);
|
|
2923
3226
|
if (unionInfo == null) {
|
|
2924
3227
|
const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
|
|
@@ -3202,19 +3505,6 @@ types.ComfyInputType;
|
|
|
3202
3505
|
types.ComfyEnumDef;
|
|
3203
3506
|
types.ComfyInputOpts;
|
|
3204
3507
|
//#endregion
|
|
3205
|
-
//#region src/utils/extractErrorMessage.ts
|
|
3206
|
-
/** Extracts an error message from an exception stuff. */
|
|
3207
|
-
const extractErrorMessage = (error) => {
|
|
3208
|
-
if (error instanceof Error) return error.message;
|
|
3209
|
-
if (error === null) return "null";
|
|
3210
|
-
if (typeof error === "string") return error;
|
|
3211
|
-
if (typeof error === "object") {
|
|
3212
|
-
if ("message" in error && typeof error.message === "string") return error.message;
|
|
3213
|
-
return JSON.stringify(error);
|
|
3214
|
-
}
|
|
3215
|
-
return String(error);
|
|
3216
|
-
};
|
|
3217
|
-
//#endregion
|
|
3218
3508
|
//#region src/utils/stringifyReadable.ts
|
|
3219
3509
|
const tab = " ";
|
|
3220
3510
|
function readableStringify(obj, maxLevel = 3, level = 0) {
|
|
@@ -3242,17 +3532,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
|
|
|
3242
3532
|
return result;
|
|
3243
3533
|
}
|
|
3244
3534
|
//#endregion
|
|
3245
|
-
//#region src/utils/writeFile.ts
|
|
3246
|
-
const writeFileAsync = async (path, data, fmt) => {
|
|
3247
|
-
return new Promise((resolve, reject) => {
|
|
3248
|
-
logInfo(`writing file: ${ansi.blue(path)}`);
|
|
3249
|
-
(0, node_fs.writeFile)(path, data, fmt, (err) => {
|
|
3250
|
-
if (err) reject(err);
|
|
3251
|
-
else resolve();
|
|
3252
|
-
});
|
|
3253
|
-
});
|
|
3254
|
-
};
|
|
3255
|
-
//#endregion
|
|
3256
3535
|
//#region src/manager/types/ComfyManagerAPIModelList.ts
|
|
3257
3536
|
const ComfyManagerAPIModelList_ark = (0, arktype.type)({ models: (0, arktype.type)({
|
|
3258
3537
|
name: arktype.type.string.as(),
|
|
@@ -3490,7 +3769,8 @@ function parseHostBase(p) {
|
|
|
3490
3769
|
function renderHttpBase(p) {
|
|
3491
3770
|
return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
|
|
3492
3771
|
}
|
|
3493
|
-
/** ws(s) endpoint; auth
|
|
3772
|
+
/** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
|
|
3773
|
+
* transports (browser), where the ws client remaps X-API-Key to ?token= */
|
|
3494
3774
|
function renderWsUrl(p) {
|
|
3495
3775
|
return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
|
|
3496
3776
|
}
|
|
@@ -3500,6 +3780,27 @@ function renderPort(p) {
|
|
|
3500
3780
|
}
|
|
3501
3781
|
//#endregion
|
|
3502
3782
|
//#region src/host/ResilientWebsocket.ts
|
|
3783
|
+
let transportPromise = null;
|
|
3784
|
+
/** node: the ws package (headers on the upgrade). browser: native WebSocket. */
|
|
3785
|
+
function resolveWsTransport() {
|
|
3786
|
+
transportPromise ??= (async () => {
|
|
3787
|
+
const specifier = "ws";
|
|
3788
|
+
try {
|
|
3789
|
+
return {
|
|
3790
|
+
ctor: (await import(specifier)).default,
|
|
3791
|
+
supportsHeaders: true
|
|
3792
|
+
};
|
|
3793
|
+
} catch {
|
|
3794
|
+
const native = globalThis.WebSocket;
|
|
3795
|
+
if (native != null) return {
|
|
3796
|
+
ctor: native,
|
|
3797
|
+
supportsHeaders: false
|
|
3798
|
+
};
|
|
3799
|
+
throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
|
|
3800
|
+
}
|
|
3801
|
+
})();
|
|
3802
|
+
return transportPromise;
|
|
3803
|
+
}
|
|
3503
3804
|
var ResilientWebSocketClient = class {
|
|
3504
3805
|
addInfo(msg) {
|
|
3505
3806
|
this.debugMessages.push({
|
|
@@ -3534,7 +3835,17 @@ var ResilientWebSocketClient = class {
|
|
|
3534
3835
|
this.currentWS = null;
|
|
3535
3836
|
this.isOpen = false;
|
|
3536
3837
|
}
|
|
3537
|
-
|
|
3838
|
+
/** headerless transports carry the api key as ?token= — everything else is refused loud */
|
|
3839
|
+
headerlessUrl(headers) {
|
|
3840
|
+
const rest = { ...headers };
|
|
3841
|
+
const apiKey = rest["X-API-Key"];
|
|
3842
|
+
delete rest["X-API-Key"];
|
|
3843
|
+
const extra = Object.keys(rest);
|
|
3844
|
+
if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
|
|
3845
|
+
if (apiKey == null) return this.url;
|
|
3846
|
+
return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
|
|
3847
|
+
}
|
|
3848
|
+
async connect() {
|
|
3538
3849
|
this.isOpen = false;
|
|
3539
3850
|
const prevWS = this.currentWS;
|
|
3540
3851
|
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
|
|
@@ -3543,30 +3854,41 @@ var ResilientWebSocketClient = class {
|
|
|
3543
3854
|
this.addInfo("Previous WebSocket discarded");
|
|
3544
3855
|
prevWS.close();
|
|
3545
3856
|
}
|
|
3546
|
-
|
|
3547
|
-
|
|
3548
|
-
|
|
3549
|
-
|
|
3857
|
+
let ws;
|
|
3858
|
+
try {
|
|
3859
|
+
const transport = await resolveWsTransport();
|
|
3860
|
+
if (this.permanentlyClosed) return;
|
|
3861
|
+
const headers = this.options.headers?.() ?? {};
|
|
3862
|
+
ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
|
|
3863
|
+
} catch (e) {
|
|
3864
|
+
this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
|
|
3865
|
+
this.permanentlyClosed = true;
|
|
3866
|
+
this.options.onTransportDead?.(e);
|
|
3867
|
+
return;
|
|
3868
|
+
}
|
|
3869
|
+
ws.binaryType = "arraybuffer";
|
|
3870
|
+
this.currentWS = ws;
|
|
3871
|
+
ws.onmessage = (event) => {
|
|
3550
3872
|
this.options.onMessage(event);
|
|
3551
3873
|
};
|
|
3552
|
-
ws
|
|
3553
|
-
if (ws
|
|
3874
|
+
ws.onopen = () => {
|
|
3875
|
+
if (ws !== this.currentWS) return;
|
|
3554
3876
|
this.addInfo("✅ WebSocket connected to " + this.url);
|
|
3555
3877
|
this.isOpen = true;
|
|
3556
3878
|
this.options.onConnectOrReconnect();
|
|
3557
3879
|
this.flushMessageBuffer();
|
|
3558
3880
|
};
|
|
3559
|
-
ws
|
|
3560
|
-
if (ws
|
|
3881
|
+
ws.onclose = (event) => {
|
|
3882
|
+
if (ws !== this.currentWS) return;
|
|
3561
3883
|
this.isOpen = false;
|
|
3562
3884
|
this.options.onClose();
|
|
3563
3885
|
if (this.permanentlyClosed) return;
|
|
3564
3886
|
this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
|
|
3565
3887
|
this.addInfo("⏱️ reconnecting in 2 seconds...");
|
|
3566
|
-
this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
|
|
3888
|
+
this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
|
|
3567
3889
|
};
|
|
3568
|
-
ws
|
|
3569
|
-
if (ws
|
|
3890
|
+
ws.onerror = (event) => {
|
|
3891
|
+
if (ws !== this.currentWS) return;
|
|
3570
3892
|
this.addError(`WebSocket ERROR` + JSON.stringify(event));
|
|
3571
3893
|
console.error({ event });
|
|
3572
3894
|
};
|
|
@@ -3581,14 +3903,6 @@ var ResilientWebSocketClient = class {
|
|
|
3581
3903
|
this.currentWS?.send(message);
|
|
3582
3904
|
}
|
|
3583
3905
|
}
|
|
3584
|
-
/** forward WebSocket add event listeners to the current WebSocket instance */
|
|
3585
|
-
addEventListener(type, listener, options) {
|
|
3586
|
-
this.currentWS?.addEventListener(type, listener, options);
|
|
3587
|
-
}
|
|
3588
|
-
/** forward WebSocket remove event listeners to the current WebSocket instance */
|
|
3589
|
-
removeEventListener(type, listener) {
|
|
3590
|
-
this.currentWS?.removeEventListener(type, listener);
|
|
3591
|
-
}
|
|
3592
3906
|
};
|
|
3593
3907
|
//#endregion
|
|
3594
3908
|
//#region src/vars/loraKeywords.ts
|
|
@@ -3608,9 +3922,10 @@ function loadOnce() {
|
|
|
3608
3922
|
if (loaded) return;
|
|
3609
3923
|
loaded = true;
|
|
3610
3924
|
const path = filePath();
|
|
3611
|
-
|
|
3925
|
+
const text = getComfyStorage().readTextIfExists(path);
|
|
3926
|
+
if (text == null) return;
|
|
3612
3927
|
try {
|
|
3613
|
-
const raw = JSON.parse(
|
|
3928
|
+
const raw = JSON.parse(text);
|
|
3614
3929
|
if (raw == null || typeof raw !== "object") return;
|
|
3615
3930
|
(0, mobx.runInAction)(() => {
|
|
3616
3931
|
for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
|
|
@@ -3633,8 +3948,7 @@ function setLoraKeyword(name, keyword) {
|
|
|
3633
3948
|
});
|
|
3634
3949
|
const path = filePath();
|
|
3635
3950
|
try {
|
|
3636
|
-
(
|
|
3637
|
-
(0, node_fs.writeFileSync)(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
|
|
3951
|
+
getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
|
|
3638
3952
|
} catch (e) {
|
|
3639
3953
|
logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
|
|
3640
3954
|
}
|
|
@@ -4078,7 +4392,7 @@ var SizeVar = class extends ComfyVar {
|
|
|
4078
4392
|
if (iv == null || iv.value === "") return null;
|
|
4079
4393
|
try {
|
|
4080
4394
|
const abs = iv.absPath();
|
|
4081
|
-
const meta = (0, image_meta.imageMeta)(
|
|
4395
|
+
const meta = (0, image_meta.imageMeta)(getComfyStorage().readBytes(abs));
|
|
4082
4396
|
if (meta.width == null || meta.height == null) return null;
|
|
4083
4397
|
return {
|
|
4084
4398
|
width: meta.width,
|
|
@@ -4132,7 +4446,7 @@ var ImageVarEmptyError = class extends Error {
|
|
|
4132
4446
|
/** trim + expand a leading `~/` — every ImageVar write funnels through this */
|
|
4133
4447
|
function expandUserPath(raw) {
|
|
4134
4448
|
const trimmed = raw.trim();
|
|
4135
|
-
return trimmed.startsWith("~/") ? (0, pathe.join)((
|
|
4449
|
+
return trimmed.startsWith("~/") ? (0, pathe.join)(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
|
|
4136
4450
|
}
|
|
4137
4451
|
/**
|
|
4138
4452
|
* a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
|
|
@@ -4168,7 +4482,7 @@ var ImageVar = class extends ComfyVar {
|
|
|
4168
4482
|
absPath() {
|
|
4169
4483
|
if (!this.isSet()) throw this.emptyError();
|
|
4170
4484
|
if ((0, pathe.isAbsolute)(this.value)) return this.value;
|
|
4171
|
-
return (0, pathe.resolve)(this.opts.folder ??
|
|
4485
|
+
return (0, pathe.resolve)(this.opts.folder ?? getComfyStorage().cwd(), this.value);
|
|
4172
4486
|
}
|
|
4173
4487
|
/** empty = unset: the build fails LOUD here (varValues calls outValue) */
|
|
4174
4488
|
outValue() {
|
|
@@ -4177,7 +4491,7 @@ var ImageVar = class extends ComfyVar {
|
|
|
4177
4491
|
}
|
|
4178
4492
|
display() {
|
|
4179
4493
|
if (!this.isSet()) return "(unset) pick a file";
|
|
4180
|
-
const home = (
|
|
4494
|
+
const home = getComfyStorage().homedir();
|
|
4181
4495
|
return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
|
|
4182
4496
|
}
|
|
4183
4497
|
};
|
|
@@ -4252,7 +4566,9 @@ var DefinedWorkflow = class {
|
|
|
4252
4566
|
advance: true,
|
|
4253
4567
|
host
|
|
4254
4568
|
})).run({
|
|
4255
|
-
|
|
4569
|
+
save: settings.save,
|
|
4570
|
+
ephemeral: settings.ephemeral,
|
|
4571
|
+
scrubHistory: settings.scrubHistory,
|
|
4256
4572
|
idMode: settings.idMode,
|
|
4257
4573
|
log: settings.log,
|
|
4258
4574
|
onProgress: settings.onProgress
|
|
@@ -4440,6 +4756,12 @@ var ComfyHost = class {
|
|
|
4440
4756
|
this.interrupt = () => {
|
|
4441
4757
|
return this.postJSON_("/interrupt", {});
|
|
4442
4758
|
};
|
|
4759
|
+
this.deleteHistory = (promptId) => {
|
|
4760
|
+
return this.postJSON_("/history", { delete: [promptId] });
|
|
4761
|
+
};
|
|
4762
|
+
this.clearHistory = () => {
|
|
4763
|
+
return this.postJSON_("/history", { clear: true });
|
|
4764
|
+
};
|
|
4443
4765
|
this.fetchRawLogs = async () => {
|
|
4444
4766
|
const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
|
|
4445
4767
|
if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
|
|
@@ -4475,11 +4797,11 @@ var ComfyHost = class {
|
|
|
4475
4797
|
this.isUpdatingSchema = true;
|
|
4476
4798
|
const object_info_json = await this.fetchJSON_("/object_info");
|
|
4477
4799
|
const object_info_str = readableStringify(object_info_json, 4);
|
|
4478
|
-
|
|
4800
|
+
getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
|
|
4479
4801
|
const res = ComfySchemaJSON_ark(object_info_json);
|
|
4480
4802
|
if (res instanceof arktype.type.errors) printArkResultInConsole(res);
|
|
4481
4803
|
const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
|
|
4482
|
-
|
|
4804
|
+
getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
|
|
4483
4805
|
this.schema.update({
|
|
4484
4806
|
spec: object_info_json,
|
|
4485
4807
|
embeddings: embeddings_json
|
|
@@ -4496,7 +4818,7 @@ var ComfyHost = class {
|
|
|
4496
4818
|
};
|
|
4497
4819
|
console.error(error);
|
|
4498
4820
|
console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
|
|
4499
|
-
if (!(
|
|
4821
|
+
if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
|
|
4500
4822
|
this.markFailed(error);
|
|
4501
4823
|
} finally {
|
|
4502
4824
|
this.isUpdatingSchema = false;
|
|
@@ -4517,9 +4839,10 @@ var ComfyHost = class {
|
|
|
4517
4839
|
this.base = parseHostBase(this.data);
|
|
4518
4840
|
/** folder where file related to the host config will be cached */
|
|
4519
4841
|
this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
|
|
4520
|
-
|
|
4842
|
+
const storage = getComfyStorage();
|
|
4843
|
+
if (!storage.exists(this.cacheFolder)) {
|
|
4521
4844
|
console.log("🟢 creating folder", this.cacheFolder);
|
|
4522
|
-
|
|
4845
|
+
storage.mkdirp(this.cacheFolder);
|
|
4523
4846
|
}
|
|
4524
4847
|
this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
|
|
4525
4848
|
this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
|
|
@@ -4569,19 +4892,20 @@ var ComfyHost = class {
|
|
|
4569
4892
|
}
|
|
4570
4893
|
async writeSDKToDisk() {
|
|
4571
4894
|
if (this.data.sdkAutoWrite === false) return;
|
|
4895
|
+
const storage = getComfyStorage();
|
|
4572
4896
|
const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
|
|
4573
|
-
if (
|
|
4574
|
-
|
|
4897
|
+
if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
|
|
4898
|
+
storage.writeText(this.sdkDTSPath, comfySchemaTs);
|
|
4575
4899
|
}
|
|
4576
4900
|
shouldUseSchemaCache() {
|
|
4577
4901
|
if (this._schemaStrategy === "refresh") return false;
|
|
4578
|
-
const
|
|
4902
|
+
const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
|
|
4579
4903
|
if (this._schemaStrategy === "cache") {
|
|
4580
|
-
if (
|
|
4904
|
+
if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
|
|
4581
4905
|
return true;
|
|
4582
4906
|
}
|
|
4583
|
-
if (
|
|
4584
|
-
return Date.now() -
|
|
4907
|
+
if (mtimeMs == null) return false;
|
|
4908
|
+
return Date.now() - mtimeMs < this._schemaMaxAgeMs;
|
|
4585
4909
|
}
|
|
4586
4910
|
waitForSession(timeoutMs = 5e3) {
|
|
4587
4911
|
if (this.comfySessionId !== "temp") return Promise.resolve();
|
|
@@ -4616,6 +4940,7 @@ var ComfyHost = class {
|
|
|
4616
4940
|
onMessage: (e) => this.onMessage(e),
|
|
4617
4941
|
url: () => this.getWSUrl(),
|
|
4618
4942
|
headers: () => this.authHeaders(),
|
|
4943
|
+
onTransportDead: (e) => this.markFailed(e),
|
|
4619
4944
|
onClose: () => {
|
|
4620
4945
|
logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
|
|
4621
4946
|
}
|
|
@@ -4635,7 +4960,7 @@ var ComfyHost = class {
|
|
|
4635
4960
|
* examples must still open in the TUI; run() fetches the real schema through
|
|
4636
4961
|
* connect() anyway). Not memoized in that case, so a later gen/connect retries. */
|
|
4637
4962
|
loadSchemaFromCache() {
|
|
4638
|
-
if (this._schemaFromCache == null && !(
|
|
4963
|
+
if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
|
|
4639
4964
|
logError(`no schema cache for host '${this.data.id}' at ${this.comfyJSONPath} — continuing with base types (no node/model unions); run \`comfy-ts gen --id ${this.data.id} --host <url>\` or connect() once to create it`);
|
|
4640
4965
|
return Promise.resolve();
|
|
4641
4966
|
}
|
|
@@ -4647,7 +4972,7 @@ var ComfyHost = class {
|
|
|
4647
4972
|
embeddings: embeddings_json
|
|
4648
4973
|
});
|
|
4649
4974
|
this.schema.RUN_BASIC_CHECKS();
|
|
4650
|
-
if (!(
|
|
4975
|
+
if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
|
|
4651
4976
|
})().catch((e) => {
|
|
4652
4977
|
this._schemaFromCache = null;
|
|
4653
4978
|
throw e;
|
|
@@ -4672,6 +4997,22 @@ var ComfyHost = class {
|
|
|
4672
4997
|
if (e.data instanceof ArrayBuffer) {
|
|
4673
4998
|
const frame = parseBinaryWsFrame(e.data);
|
|
4674
4999
|
if (frame.kind === "preview") {
|
|
5000
|
+
const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null;
|
|
5001
|
+
if (activeExec?.wsOutputNodeExecuting) {
|
|
5002
|
+
activeExec.onWsImageOutput({
|
|
5003
|
+
bytes: frame.bytes,
|
|
5004
|
+
mime: frame.mime
|
|
5005
|
+
});
|
|
5006
|
+
return;
|
|
5007
|
+
}
|
|
5008
|
+
if (this.activePromptID != null) {
|
|
5009
|
+
const pending = this._pendingMsgs.get(this.activePromptID);
|
|
5010
|
+
if (pending != null) pending.push({
|
|
5011
|
+
type: "binary_preview_frame",
|
|
5012
|
+
bytes: frame.bytes,
|
|
5013
|
+
mime: frame.mime
|
|
5014
|
+
});
|
|
5015
|
+
}
|
|
4675
5016
|
const imageBlob = new Blob([frame.bytes], { type: frame.mime });
|
|
4676
5017
|
this.latentPreview = {
|
|
4677
5018
|
blob: imageBlob,
|
|
@@ -4739,55 +5080,13 @@ var ComfyHost = class {
|
|
|
4739
5080
|
};
|
|
4740
5081
|
//#endregion
|
|
4741
5082
|
//#region src/utils/downloadFile.ts
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
* | }
|
|
4750
|
-
* | })()
|
|
4751
|
-
* |
|
|
4752
|
-
*/
|
|
4753
|
-
function downloadFile(url, outputPath, logPrefix = " - ") {
|
|
4754
|
-
(0, node_fs.mkdirSync)((0, pathe.dirname)(outputPath), { recursive: true });
|
|
4755
|
-
return new Promise((resolve, reject) => {
|
|
4756
|
-
node_https.default.get(url, (response) => {
|
|
4757
|
-
if (response.statusCode === 302 || response.statusCode === 301) {
|
|
4758
|
-
const newUrl = response.headers.location;
|
|
4759
|
-
console.log(`Redirected to ${newUrl}`);
|
|
4760
|
-
resolve(downloadFile(newUrl, outputPath));
|
|
4761
|
-
return;
|
|
4762
|
-
}
|
|
4763
|
-
if (response.statusCode !== 200) {
|
|
4764
|
-
reject(`Failed to download file: Status Code ${response.statusCode}`);
|
|
4765
|
-
return;
|
|
4766
|
-
}
|
|
4767
|
-
const rawLen = response.headers["content-length"];
|
|
4768
|
-
if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
|
|
4769
|
-
else {
|
|
4770
|
-
const totalSize = parseInt(rawLen, 10);
|
|
4771
|
-
let downloaded = 0;
|
|
4772
|
-
let lastLoggedPercentage = 0;
|
|
4773
|
-
response.on("data", (chunk) => {
|
|
4774
|
-
downloaded += chunk.length;
|
|
4775
|
-
const percentage = Math.round(downloaded / totalSize * 100);
|
|
4776
|
-
if (percentage >= lastLoggedPercentage + 1) {
|
|
4777
|
-
node_process.stdout.write(`\r${logPrefix}${percentage}% downloaded`);
|
|
4778
|
-
lastLoggedPercentage = percentage;
|
|
4779
|
-
}
|
|
4780
|
-
});
|
|
4781
|
-
}
|
|
4782
|
-
const fileStream = node_fs.default.createWriteStream(outputPath);
|
|
4783
|
-
response.pipe(fileStream);
|
|
4784
|
-
fileStream.on("finish", () => {
|
|
4785
|
-
console.log(` (DONE)`);
|
|
4786
|
-
fileStream.close();
|
|
4787
|
-
resolve(true);
|
|
4788
|
-
});
|
|
4789
|
-
}).on("error", (err) => reject(err));
|
|
4790
|
-
});
|
|
5083
|
+
async function downloadFile(url, outputPath, logPrefix = " - ") {
|
|
5084
|
+
const res = await fetch(url);
|
|
5085
|
+
if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
|
|
5086
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
5087
|
+
getComfyStorage().writeBytes(outputPath, bytes);
|
|
5088
|
+
console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
|
|
5089
|
+
return true;
|
|
4791
5090
|
}
|
|
4792
5091
|
//#endregion
|
|
4793
5092
|
//#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
|
|
@@ -4908,7 +5207,7 @@ const ComfyManagerRawPluginInfo_ark = (0, arktype.type)({
|
|
|
4908
5207
|
const _getKnownPlugins = (DB) => {
|
|
4909
5208
|
const counter = DB.report.file("custom-node-list.json");
|
|
4910
5209
|
let totalFileSeen = 0;
|
|
4911
|
-
const root = ComfyManagerFilePluginListRoot_ark(JSON.parse((
|
|
5210
|
+
const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
|
|
4912
5211
|
if (root instanceof arktype.type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
|
|
4913
5212
|
const canonical = [];
|
|
4914
5213
|
for (const row of root.custom_nodes) {
|
|
@@ -4946,7 +5245,7 @@ const _getKnownPlugins = (DB) => {
|
|
|
4946
5245
|
}
|
|
4947
5246
|
out1 += "\n";
|
|
4948
5247
|
const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
|
|
4949
|
-
(
|
|
5248
|
+
getComfyStorage().writeText(out1Path, out1 + "\n");
|
|
4950
5249
|
console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
|
|
4951
5250
|
let out2 = "";
|
|
4952
5251
|
const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
|
@@ -4954,7 +5253,7 @@ const _getKnownPlugins = (DB) => {
|
|
|
4954
5253
|
out2 += "export type KnownComfyPluginURL =\n";
|
|
4955
5254
|
for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
|
|
4956
5255
|
const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
|
|
4957
|
-
(
|
|
5256
|
+
getComfyStorage().writeText(out2Path, out2);
|
|
4958
5257
|
console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
|
|
4959
5258
|
}
|
|
4960
5259
|
if (DB.opts.check) {
|
|
@@ -5000,7 +5299,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = (0, arktype.type)([ComfyManagerPlu
|
|
|
5000
5299
|
const _getCustomNodeRegistry = (DB) => {
|
|
5001
5300
|
const counter = DB.report.file("extension-node-map.json");
|
|
5002
5301
|
let totalCustomNodeSeen = 0;
|
|
5003
|
-
const raw = JSON.parse((
|
|
5302
|
+
const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
|
|
5004
5303
|
const root = (0, arktype.type)("Record<string, unknown>")(raw);
|
|
5005
5304
|
if (root instanceof arktype.type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
|
|
5006
5305
|
for (const [url, value] of Object.entries(root)) {
|
|
@@ -5036,7 +5335,7 @@ const _getCustomNodeRegistry = (DB) => {
|
|
|
5036
5335
|
for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
|
|
5037
5336
|
out += "\n";
|
|
5038
5337
|
const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
|
|
5039
|
-
(
|
|
5338
|
+
getComfyStorage().writeText(outPath, out + "\n");
|
|
5040
5339
|
console.log(` > generated: ${ansi.blue.underline(outPath)}`);
|
|
5041
5340
|
}
|
|
5042
5341
|
if (DB.opts.check) {
|
|
@@ -5091,7 +5390,7 @@ const ComfyManagerModelInfo_ark = (0, arktype.type)({
|
|
|
5091
5390
|
//#region src/manager/loaders/step4_model-list-loader.ts
|
|
5092
5391
|
const _getKnownModels = (DB) => {
|
|
5093
5392
|
const counter = DB.report.file("model-list.json");
|
|
5094
|
-
const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse((
|
|
5393
|
+
const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
|
|
5095
5394
|
if (root instanceof arktype.type.errors) throw new ManagerParseError("model-list.json", root.summary);
|
|
5096
5395
|
const canonical = [];
|
|
5097
5396
|
for (const row of root.models) {
|
|
@@ -5120,7 +5419,7 @@ const _getKnownModels = (DB) => {
|
|
|
5120
5419
|
for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
|
|
5121
5420
|
out1 += "]\n";
|
|
5122
5421
|
const out1Path = "src/manager/generated/KnownModel_Type.ts";
|
|
5123
|
-
(
|
|
5422
|
+
getComfyStorage().writeText(out1Path, out1 + "\n");
|
|
5124
5423
|
console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
|
|
5125
5424
|
let out4 = "";
|
|
5126
5425
|
const uniqSavePath = knownModelList.reduce((acc, cur) => {
|
|
@@ -5136,7 +5435,7 @@ const _getKnownModels = (DB) => {
|
|
|
5136
5435
|
for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
|
|
5137
5436
|
out4 += "]\n";
|
|
5138
5437
|
const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
|
|
5139
|
-
(
|
|
5438
|
+
getComfyStorage().writeText(out4Path, out4 + "\n");
|
|
5140
5439
|
console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
|
|
5141
5440
|
let out2 = "";
|
|
5142
5441
|
const uniqBases = knownModelList.reduce((acc, cur) => {
|
|
@@ -5153,7 +5452,7 @@ const _getKnownModels = (DB) => {
|
|
|
5153
5452
|
for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
|
|
5154
5453
|
out2 += "]\n";
|
|
5155
5454
|
const out2Path = "src/manager/generated/KnownModel_Base.ts";
|
|
5156
|
-
(
|
|
5455
|
+
getComfyStorage().writeText(out2Path, out2 + "\n");
|
|
5157
5456
|
console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
|
|
5158
5457
|
let out3 = "";
|
|
5159
5458
|
const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
|
|
@@ -5168,7 +5467,7 @@ const _getKnownModels = (DB) => {
|
|
|
5168
5467
|
}
|
|
5169
5468
|
out3 += "\n";
|
|
5170
5469
|
const out3Path = "src/manager/generated/KnownModel_Name.ts";
|
|
5171
|
-
(
|
|
5470
|
+
getComfyStorage().writeText(out3Path, out3 + "\n");
|
|
5172
5471
|
console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
|
|
5173
5472
|
let out99 = "";
|
|
5174
5473
|
out99 += `// prettier-ignore\n`;
|
|
@@ -5182,7 +5481,7 @@ const _getKnownModels = (DB) => {
|
|
|
5182
5481
|
}
|
|
5183
5482
|
out99 += "\n";
|
|
5184
5483
|
const out99Path = "src/manager/generated/KnownModel_FileName.ts";
|
|
5185
|
-
(
|
|
5484
|
+
getComfyStorage().writeText(out99Path, out99 + "\n");
|
|
5186
5485
|
console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
|
|
5187
5486
|
}
|
|
5188
5487
|
if (DB.opts.check) {
|
|
@@ -5203,7 +5502,7 @@ const ComfyManagerFileAlterListRoot_ark = (0, arktype.type)({ items: "unknown[]"
|
|
|
5203
5502
|
//#region src/manager/loaders/step5_alter-list-loader.ts
|
|
5204
5503
|
const _getAlterList = (DB) => {
|
|
5205
5504
|
const counter = DB.report.file("alter-list.json");
|
|
5206
|
-
const root = ComfyManagerFileAlterListRoot_ark(JSON.parse((
|
|
5505
|
+
const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
|
|
5207
5506
|
if (root instanceof arktype.type.errors) throw new ManagerParseError("alter-list.json", root.summary);
|
|
5208
5507
|
const canonical = [];
|
|
5209
5508
|
for (const row of root.items) {
|
|
@@ -5228,7 +5527,7 @@ const ComfyManagerGithubStatEntry_ark = (0, arktype.type)({
|
|
|
5228
5527
|
//#region src/manager/loaders/step6_github-stats-loader.ts
|
|
5229
5528
|
const _getGithubStats = (DB) => {
|
|
5230
5529
|
const counter = DB.report.file("github-stats.json");
|
|
5231
|
-
const raw = JSON.parse((
|
|
5530
|
+
const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
|
|
5232
5531
|
const root = (0, arktype.type)("Record<string, unknown>")(raw);
|
|
5233
5532
|
if (root instanceof arktype.type.errors) throw new ManagerParseError("github-stats.json", root.summary);
|
|
5234
5533
|
for (const [url, value] of Object.entries(root)) {
|
|
@@ -5343,13 +5642,12 @@ var ComfyTS = class ComfyTS {
|
|
|
5343
5642
|
this.version = version;
|
|
5344
5643
|
this.hosts = /* @__PURE__ */ new Map();
|
|
5345
5644
|
this._registry = null;
|
|
5346
|
-
this.rootPath = asAbsolutePath(process.cwd());
|
|
5347
5645
|
this.readJSON_ = (absPath, def) => {
|
|
5348
|
-
|
|
5646
|
+
const str = this.storage.readTextIfExists(absPath);
|
|
5647
|
+
if (str == null) {
|
|
5349
5648
|
if (def != null) return def;
|
|
5350
5649
|
throw new Error(`file does not exist ${absPath}`);
|
|
5351
5650
|
}
|
|
5352
|
-
const str = (0, node_fs.readFileSync)(absPath, "utf8");
|
|
5353
5651
|
return JSON.parse(str);
|
|
5354
5652
|
};
|
|
5355
5653
|
this.autolayoutOpts = {
|
|
@@ -5360,7 +5658,8 @@ var ComfyTS = class ComfyTS {
|
|
|
5360
5658
|
const globalHack = globalThis;
|
|
5361
5659
|
if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
|
|
5362
5660
|
globalHack.comfyts = this;
|
|
5363
|
-
|
|
5661
|
+
this.storage = resolveComfyStorage(p.storage);
|
|
5662
|
+
this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
|
|
5364
5663
|
this.baseFolder = asAbsolutePath((0, pathe.join)(this.rootPath, ".comfy-ts"));
|
|
5365
5664
|
this.hostsFolder = asAbsolutePath((0, pathe.join)(this.baseFolder, "hosts"));
|
|
5366
5665
|
this.outputPath = asAbsolutePath((0, pathe.join)(this.baseFolder, "outputs"));
|
|
@@ -5424,6 +5723,18 @@ var ComfyTS = class ComfyTS {
|
|
|
5424
5723
|
}
|
|
5425
5724
|
};
|
|
5426
5725
|
//#endregion
|
|
5726
|
+
//#region src/utils/loraTag.ts
|
|
5727
|
+
/**
|
|
5728
|
+
* build a LoraManager-style lora tag: `<lora:name:strength>` or
|
|
5729
|
+
* `<lora:name:strength:clipStrength>`. Pin the name to a host union for
|
|
5730
|
+
* autocomplete + validation:
|
|
5731
|
+
*
|
|
5732
|
+
* loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
|
|
5733
|
+
*/
|
|
5734
|
+
function loraTag(name, strength = 1, clipStrength) {
|
|
5735
|
+
return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
|
|
5736
|
+
}
|
|
5737
|
+
//#endregion
|
|
5427
5738
|
//#region src/exampleAssets.ts
|
|
5428
5739
|
/**
|
|
5429
5740
|
* the examples/ folder shipped in the npm tarball, resolved from THIS module's
|
|
@@ -5476,17 +5787,12 @@ function isTuiActive() {
|
|
|
5476
5787
|
return process.env[COMFY_TS_TUI_ENV] === "1";
|
|
5477
5788
|
}
|
|
5478
5789
|
//#endregion
|
|
5479
|
-
//#region src/
|
|
5790
|
+
//#region src/index.ts
|
|
5480
5791
|
/**
|
|
5481
|
-
*
|
|
5482
|
-
*
|
|
5483
|
-
* autocomplete + validation:
|
|
5484
|
-
*
|
|
5485
|
-
* loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
|
|
5792
|
+
* comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
|
|
5793
|
+
* @packageDocumentation
|
|
5486
5794
|
*/
|
|
5487
|
-
|
|
5488
|
-
return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
|
|
5489
|
-
}
|
|
5795
|
+
setDefaultComfyStorage(createNodeStorage());
|
|
5490
5796
|
//#endregion
|
|
5491
5797
|
exports.ChoiceVar = ChoiceVar;
|
|
5492
5798
|
exports.ComfyExecution = ComfyExecution;
|
|
@@ -5532,7 +5838,9 @@ exports.auto_ = auto_;
|
|
|
5532
5838
|
exports.codegenSDK = codegenSDK;
|
|
5533
5839
|
exports.convertFlowToLiteGraphJSON = convertFlowToLiteGraphJSON;
|
|
5534
5840
|
exports.convertLiteGraphToPrompt = convertLiteGraphToPrompt;
|
|
5841
|
+
exports.createMemoryStorage = createMemoryStorage;
|
|
5535
5842
|
exports.exampleImagePath = exampleImagePath;
|
|
5843
|
+
exports.getComfyStorage = getComfyStorage;
|
|
5536
5844
|
exports.getLoraKeyword = getLoraKeyword;
|
|
5537
5845
|
exports.hostIdToNamespace = hostIdToNamespace;
|
|
5538
5846
|
exports.isTuiActive = isTuiActive;
|
|
@@ -5544,6 +5852,7 @@ exports.renderHttpBase = renderHttpBase;
|
|
|
5544
5852
|
exports.renderWsUrl = renderWsUrl;
|
|
5545
5853
|
exports.resultFailure = resultFailure;
|
|
5546
5854
|
exports.resultSuccess = resultSuccess;
|
|
5855
|
+
exports.setDefaultComfyStorage = setDefaultComfyStorage;
|
|
5547
5856
|
exports.setLoraKeyword = setLoraKeyword;
|
|
5548
5857
|
exports.v = v;
|
|
5549
5858
|
|