comfy-ts 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +26 -0
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-C_QAxKr3.js} +64 -13
  3. package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-DcOTn0QR.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-DcOTn0QR.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +346 -183
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +93 -40
  10. package/dist/index.d.ts +94 -41
  11. package/dist/index.js +338 -174
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-CN0DhrsA.js} +3 -3
  14. package/dist/{run-serve-Bn6yIJB0.js.map → run-serve-CN0DhrsA.js.map} +1 -1
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-bN2hSD5i.js} +10 -11
  16. package/dist/{run-tui-BtjaOXRh.js.map → run-tui-bN2hSD5i.js.map} +1 -1
  17. package/dist/{state-DKCPy105.js → state-COlKYipO.js} +199 -146
  18. package/dist/state-COlKYipO.js.map +1 -0
  19. package/dist/web.d.ts +17340 -0
  20. package/dist/web.js +5569 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/web/example.ts +71 -0
  23. package/examples/web/index.html +77 -0
  24. package/examples/web/serve.ts +42 -0
  25. package/examples/web/tsconfig.json +15 -0
  26. package/package.json +8 -2
  27. package/src/coreExports.ts +118 -0
  28. package/src/host/ComfyHost.ts +23 -23
  29. package/src/host/ResilientWebsocket.ts +93 -47
  30. package/src/host/hostUrl.ts +2 -1
  31. package/src/host/loraManagerApi.ts +6 -7
  32. package/src/index.ts +8 -107
  33. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  34. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  35. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  36. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  37. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  38. package/src/runner/ComfyExecution.ts +14 -11
  39. package/src/runner/MediaImage.ts +18 -30
  40. package/src/sdk-generator/ComfySchema.ts +2 -2
  41. package/src/state.ts +13 -9
  42. package/src/storage/ComfyStorage.ts +144 -0
  43. package/src/storage/nodeStorage.ts +9 -0
  44. package/src/utils/downloadFile.ts +11 -69
  45. package/src/utils/hashArrayBuffer.ts +3 -4
  46. package/src/utils/lazySharp.ts +25 -0
  47. package/src/utils/sha1.ts +69 -0
  48. package/src/vars/ComfyVars.ts +5 -6
  49. package/src/vars/loraKeywords.ts +6 -6
  50. package/src/web.ts +13 -0
  51. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  52. package/dist/state-DKCPy105.js.map +0 -1
  53. package/src/utils/writeFile.ts +0 -16
package/dist/index.js CHANGED
@@ -1,18 +1,116 @@
1
- import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
1
+ import * as fs from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import * as os from "node:os";
2
4
  import { basename, dirname, isAbsolute, join, resolve } from "pathe";
3
5
  import { scope, type } from "arktype";
4
6
  import { nanoid } from "nanoid";
5
- import sharp from "sharp";
6
7
  import { imageMeta } from "image-meta";
7
- import crypto from "node:crypto";
8
- import WebSocket from "ws";
9
- import { homedir } from "node:os";
10
8
  import { action, makeObservable, observable, runInAction } from "mobx";
11
- import https from "node:https";
12
- import { stdout } from "node:process";
13
9
  import { fileURLToPath } from "node:url";
10
+ //#region src/storage/ComfyStorage.ts
11
+ function dirnameOf(path) {
12
+ const ix = path.lastIndexOf("/");
13
+ return ix <= 0 ? "/" : path.slice(0, ix);
14
+ }
15
+ /** node backend built from INJECTED modules: nodeStorage.ts passes its static
16
+ * imports, the autodetect below passes process.getBuiltinModule results */
17
+ function createNodeStorageFrom(fs, os) {
18
+ return {
19
+ kind: "node",
20
+ readText: (p) => fs.readFileSync(p, "utf8"),
21
+ readTextIfExists: (p) => fs.existsSync(p) ? fs.readFileSync(p, "utf8") : null,
22
+ readBytes: (p) => new Uint8Array(fs.readFileSync(p)),
23
+ writeText: (p, text) => {
24
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
25
+ fs.writeFileSync(p, text);
26
+ },
27
+ writeBytes: (p, bytes) => {
28
+ fs.mkdirSync(dirnameOf(p), { recursive: true });
29
+ fs.writeFileSync(p, bytes);
30
+ },
31
+ exists: (p) => fs.existsSync(p),
32
+ mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
33
+ mtimeMs: (p) => fs.existsSync(p) ? fs.statSync(p).mtimeMs : null,
34
+ homedir: () => os.homedir(),
35
+ cwd: () => process.cwd()
36
+ };
37
+ }
38
+ /** in-memory backend: the web default, also handy for hermetic tests.
39
+ * Paths are LITERAL keys (no normalization — core callers resolve through
40
+ * pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
41
+ * dirs only, never implicit parents. Bytes are copied in AND out so neither
42
+ * side can mutate the store. */
43
+ function createMemoryStorage(p = {}) {
44
+ const files = /* @__PURE__ */ new Map();
45
+ const mtimes = /* @__PURE__ */ new Map();
46
+ const dirs = /* @__PURE__ */ new Set();
47
+ const td = new TextDecoder();
48
+ const te = new TextEncoder();
49
+ const write = (path, bytes) => {
50
+ files.set(path, bytes.slice());
51
+ mtimes.set(path, Date.now());
52
+ };
53
+ return {
54
+ kind: "memory",
55
+ readText: (path) => {
56
+ const hit = files.get(path);
57
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
58
+ return td.decode(hit);
59
+ },
60
+ readTextIfExists: (path) => {
61
+ const hit = files.get(path);
62
+ return hit == null ? null : td.decode(hit);
63
+ },
64
+ readBytes: (path) => {
65
+ const hit = files.get(path);
66
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`);
67
+ return hit.slice();
68
+ },
69
+ writeText: (path, text) => write(path, te.encode(text)),
70
+ writeBytes: write,
71
+ exists: (path) => files.has(path) || dirs.has(path),
72
+ mkdirp: (path) => void dirs.add(path),
73
+ mtimeMs: (path) => mtimes.get(path) ?? null,
74
+ homedir: () => p.homedir ?? "/home/web",
75
+ cwd: () => p.cwd ?? "/"
76
+ };
77
+ }
78
+ let installedDefault = null;
79
+ /** entries call this at import time: index.ts installs node, web.ts memory */
80
+ function setDefaultComfyStorage(storage) {
81
+ installedDefault = storage;
82
+ }
83
+ function autodetectNodeStorage() {
84
+ const get = globalThis.process?.getBuiltinModule;
85
+ if (typeof get !== "function") return null;
86
+ const fs = get("node:fs");
87
+ const os = get("node:os");
88
+ if (fs == null || os == null) return null;
89
+ return createNodeStorageFrom(fs, os);
90
+ }
91
+ function resolveComfyStorage(explicit) {
92
+ if (explicit != null) return explicit;
93
+ if (installedDefault != null) return installedDefault;
94
+ const detected = autodetectNodeStorage();
95
+ if (detected != null) {
96
+ installedDefault = detected;
97
+ return detected;
98
+ }
99
+ throw new Error(`no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`);
100
+ }
101
+ /** the ONE accessor call sites use: the instance's storage when the global
102
+ * exists, the resolved default otherwise (vars constructed before create()) */
103
+ function getComfyStorage() {
104
+ return globalThis.comfyts?.storage ?? resolveComfyStorage();
105
+ }
106
+ //#endregion
107
+ //#region src/storage/nodeStorage.ts
108
+ function createNodeStorage() {
109
+ return createNodeStorageFrom(fs, os);
110
+ }
111
+ //#endregion
14
112
  //#region package.json
15
- var version = "1.3.0";
113
+ var version = "1.4.0";
16
114
  //#endregion
17
115
  //#region src/litegraph/LiteGraphLinkID.ts
18
116
  const asLiteGraphLinkID = (id) => id;
@@ -1616,6 +1714,32 @@ const runTimestamp = (d) => {
1616
1714
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
1617
1715
  };
1618
1716
  //#endregion
1717
+ //#region src/utils/extractErrorMessage.ts
1718
+ /** Extracts an error message from an exception stuff. */
1719
+ const extractErrorMessage = (error) => {
1720
+ if (error instanceof Error) return error.message;
1721
+ if (error === null) return "null";
1722
+ if (typeof error === "string") return error;
1723
+ if (typeof error === "object") {
1724
+ if ("message" in error && typeof error.message === "string") return error.message;
1725
+ return JSON.stringify(error);
1726
+ }
1727
+ return String(error);
1728
+ };
1729
+ //#endregion
1730
+ //#region src/utils/lazySharp.ts
1731
+ let cached = null;
1732
+ async function importSharp(reason) {
1733
+ if (cached != null) return cached;
1734
+ const specifier = "sharp";
1735
+ try {
1736
+ cached = (await import(specifier)).default;
1737
+ return cached;
1738
+ } catch (e) {
1739
+ throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
1740
+ }
1741
+ }
1742
+ //#endregion
1619
1743
  //#region src/types/index.ts
1620
1744
  const asAbsolutePath = (path) => path;
1621
1745
  const asRelativePath = (path) => path;
@@ -1665,10 +1789,78 @@ function exhaust(x) {
1665
1789
  return x;
1666
1790
  }
1667
1791
  //#endregion
1792
+ //#region src/utils/sha1.ts
1793
+ function sha1Hex(data) {
1794
+ const ml = data.length;
1795
+ const total = Math.ceil((ml + 1 + 8) / 64) * 64;
1796
+ const bytes = new Uint8Array(total);
1797
+ bytes.set(data);
1798
+ bytes[ml] = 128;
1799
+ const dv = new DataView(bytes.buffer);
1800
+ const bitLen = ml * 8;
1801
+ dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
1802
+ dv.setUint32(total - 4, bitLen >>> 0);
1803
+ let h0 = 1732584193;
1804
+ let h1 = 4023233417;
1805
+ let h2 = 2562383102;
1806
+ let h3 = 271733878;
1807
+ let h4 = 3285377520;
1808
+ const w = /* @__PURE__ */ new Uint32Array(80);
1809
+ for (let i = 0; i < total; i += 64) {
1810
+ for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
1811
+ for (let j = 16; j < 80; j++) {
1812
+ const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
1813
+ w[j] = n << 1 | n >>> 31;
1814
+ }
1815
+ let a = h0;
1816
+ let b = h1;
1817
+ let c = h2;
1818
+ let d = h3;
1819
+ let e = h4;
1820
+ for (let j = 0; j < 80; j++) {
1821
+ let f;
1822
+ let k;
1823
+ if (j < 20) {
1824
+ f = b & c | ~b & d;
1825
+ k = 1518500249;
1826
+ } else if (j < 40) {
1827
+ f = b ^ c ^ d;
1828
+ k = 1859775393;
1829
+ } else if (j < 60) {
1830
+ f = b & c | b & d | c & d;
1831
+ k = 2400959708;
1832
+ } else {
1833
+ f = b ^ c ^ d;
1834
+ k = 3395469782;
1835
+ }
1836
+ const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
1837
+ e = d;
1838
+ d = c;
1839
+ c = b << 30 | b >>> 2;
1840
+ b = a;
1841
+ a = temp;
1842
+ }
1843
+ h0 = h0 + a >>> 0;
1844
+ h1 = h1 + b >>> 0;
1845
+ h2 = h2 + c >>> 0;
1846
+ h3 = h3 + d >>> 0;
1847
+ h4 = h4 + e >>> 0;
1848
+ }
1849
+ return [
1850
+ h0,
1851
+ h1,
1852
+ h2,
1853
+ h3,
1854
+ h4
1855
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
1856
+ }
1857
+ function sha1HexOfString(s) {
1858
+ return sha1Hex(new TextEncoder().encode(s));
1859
+ }
1860
+ //#endregion
1668
1861
  //#region src/utils/hashArrayBuffer.ts
1669
1862
  const hashArrayBuffer = (buffer) => {
1670
- const data = Buffer.from(buffer);
1671
- return crypto.createHash("sha1").update(data).digest("hex");
1863
+ return sha1Hex(buffer);
1672
1864
  };
1673
1865
  //#endregion
1674
1866
  //#region src/graph/ComfyNodeID.ts
@@ -1844,29 +2036,21 @@ var MediaImage = class MediaImage {
1844
2036
  this._metadata = null;
1845
2037
  this._hash = null;
1846
2038
  this.processWithSharp_inplace = async (fn) => {
1847
- const buff = await fn(sharp(this.absPath)).toBuffer();
1848
- writeFileSync(this.absPath, buff);
2039
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2040
+ getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
1849
2041
  this.updateBuffer(new Uint8Array(buff));
1850
2042
  return this;
1851
2043
  };
1852
2044
  this.processWithSharp = async (fn, path) => {
1853
- const res = fn(sharp(this.absPath));
2045
+ const sharp = await importSharp("processWithSharp");
1854
2046
  path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
1855
- await res.toFile(path);
1856
- const buffer = await res.toBuffer();
2047
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2048
+ getComfyStorage().writeBytes(path, buffer);
1857
2049
  return new MediaImage({
1858
2050
  path,
1859
2051
  buffer
1860
2052
  });
1861
2053
  };
1862
- this.generatePreview = async (targetPath) => {
1863
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
1864
- mkdirSync(dirname(targetPath), { recursive: true });
1865
- await img.toFile(targetPath);
1866
- };
1867
- this.generateMiniPreview = async () => {
1868
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
1869
- };
1870
2054
  this.absPath = data.path;
1871
2055
  this.execution = data.execution;
1872
2056
  this.promptNodeID = data.promptNodeID;
@@ -1936,26 +2120,25 @@ var MediaImage = class MediaImage {
1936
2120
  * does not includes the prefix `data:image/png;base64,`
1937
2121
  */
1938
2122
  getBase64Payload() {
1939
- return Buffer.from(this.buffer).toString("base64");
2123
+ const bytes = this.buffer;
2124
+ let bin = "";
2125
+ const chunk = 32768;
2126
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2127
+ return btoa(bin);
1940
2128
  }
1941
2129
  get buffer() {
1942
2130
  if (this._buffer != null) return this._buffer;
1943
- const buff = readFileSync(this.absPath);
1944
- const uint8arr = new Uint8Array(buff);
1945
- this._buffer = uint8arr;
2131
+ this._buffer = getComfyStorage().readBytes(this.absPath);
1946
2132
  return this._buffer;
1947
2133
  }
1948
2134
  get metadata() {
1949
2135
  if (this._metadata != null) return this._metadata;
1950
- const buff = readFileSync(this.absPath);
1951
- const uint8arr = new Uint8Array(buff);
1952
- this._metadata = imageMeta(uint8arr);
2136
+ this._metadata = imageMeta(this.buffer);
1953
2137
  return this._metadata;
1954
2138
  }
1955
2139
  get hash() {
1956
2140
  if (this._hash != null) return this._hash;
1957
- const buff = readFileSync(this.absPath);
1958
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2141
+ this._hash = hashArrayBuffer(this.buffer);
1959
2142
  return this._hash;
1960
2143
  }
1961
2144
  };
@@ -2041,12 +2224,12 @@ var ComfyExecution = class {
2041
2224
  const extension = sf.format.split("/")[1];
2042
2225
  absPath += "." + extension;
2043
2226
  }
2227
+ const storage = getComfyStorage();
2044
2228
  absPath = uniquifyOutputPath({
2045
2229
  path: absPath,
2046
- exists: existsSync,
2230
+ exists: (p) => storage.exists(p),
2047
2231
  claimed: CLAIMED_OUTPUT_PATHS
2048
2232
  });
2049
- mkdirSync(dirname(absPath), { recursive: true });
2050
2233
  let img;
2051
2234
  if (sf && sf.format !== "raw") {
2052
2235
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
@@ -2061,9 +2244,11 @@ var ComfyExecution = class {
2061
2244
  if (sf.format === "image/webp") return "webp";
2062
2245
  return "png";
2063
2246
  })();
2064
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2247
+ const encoded = await (await importSharp(`saveFormat '${sf.format}' re-encoding`))(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toBuffer();
2248
+ storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded));
2065
2249
  img = new MediaImage({
2066
2250
  path: asAbsolutePath(absPath),
2251
+ buffer: new Uint8Array(encoded),
2067
2252
  execution: this,
2068
2253
  promptNodeID,
2069
2254
  comfyUIInfos: {
@@ -2074,7 +2259,7 @@ var ComfyExecution = class {
2074
2259
  } else {
2075
2260
  const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2076
2261
  const uint8arr = new Uint8Array(buff);
2077
- writeFileSync(absPath, uint8arr);
2262
+ storage.writeBytes(asAbsolutePath(absPath), uint8arr);
2078
2263
  img = new MediaImage({
2079
2264
  path: asAbsolutePath(absPath),
2080
2265
  buffer: uint8arr,
@@ -2131,14 +2316,14 @@ var ComfyExecution = class {
2131
2316
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2132
2317
  if (line === this._lastLoggedLine) return;
2133
2318
  this._lastLoggedLine = line;
2134
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2319
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2135
2320
  else console.log(line);
2136
2321
  }
2137
2322
  finishProgressLine() {
2138
2323
  if (!this.logProgress) return;
2139
2324
  const p = this.progress;
2140
2325
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2141
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2326
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2142
2327
  else console.log(line);
2143
2328
  }
2144
2329
  log(...args) {
@@ -2887,7 +3072,7 @@ var ComfySchema = class {
2887
3072
  else if (typeof enumValue === "number") enumValues.push(enumValue);
2888
3073
  else enumValues.push(enumValue.content);
2889
3074
  const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
2890
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
3075
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
2891
3076
  let unionInfo = this.knownUnionByHash.get(hash);
2892
3077
  if (unionInfo == null) {
2893
3078
  const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
@@ -3171,19 +3356,6 @@ types.ComfyInputType;
3171
3356
  types.ComfyEnumDef;
3172
3357
  types.ComfyInputOpts;
3173
3358
  //#endregion
3174
- //#region src/utils/extractErrorMessage.ts
3175
- /** Extracts an error message from an exception stuff. */
3176
- const extractErrorMessage = (error) => {
3177
- if (error instanceof Error) return error.message;
3178
- if (error === null) return "null";
3179
- if (typeof error === "string") return error;
3180
- if (typeof error === "object") {
3181
- if ("message" in error && typeof error.message === "string") return error.message;
3182
- return JSON.stringify(error);
3183
- }
3184
- return String(error);
3185
- };
3186
- //#endregion
3187
3359
  //#region src/utils/stringifyReadable.ts
3188
3360
  const tab = " ";
3189
3361
  function readableStringify(obj, maxLevel = 3, level = 0) {
@@ -3211,17 +3383,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3211
3383
  return result;
3212
3384
  }
3213
3385
  //#endregion
3214
- //#region src/utils/writeFile.ts
3215
- const writeFileAsync = async (path, data, fmt) => {
3216
- return new Promise((resolve, reject) => {
3217
- logInfo(`writing file: ${ansi.blue(path)}`);
3218
- writeFile(path, data, fmt, (err) => {
3219
- if (err) reject(err);
3220
- else resolve();
3221
- });
3222
- });
3223
- };
3224
- //#endregion
3225
3386
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3226
3387
  const ComfyManagerAPIModelList_ark = type({ models: type({
3227
3388
  name: type.string.as(),
@@ -3459,7 +3620,8 @@ function parseHostBase(p) {
3459
3620
  function renderHttpBase(p) {
3460
3621
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3461
3622
  }
3462
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3623
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3624
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3463
3625
  function renderWsUrl(p) {
3464
3626
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3465
3627
  }
@@ -3469,6 +3631,27 @@ function renderPort(p) {
3469
3631
  }
3470
3632
  //#endregion
3471
3633
  //#region src/host/ResilientWebsocket.ts
3634
+ let transportPromise = null;
3635
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3636
+ function resolveWsTransport() {
3637
+ transportPromise ??= (async () => {
3638
+ const specifier = "ws";
3639
+ try {
3640
+ return {
3641
+ ctor: (await import(specifier)).default,
3642
+ supportsHeaders: true
3643
+ };
3644
+ } catch {
3645
+ const native = globalThis.WebSocket;
3646
+ if (native != null) return {
3647
+ ctor: native,
3648
+ supportsHeaders: false
3649
+ };
3650
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3651
+ }
3652
+ })();
3653
+ return transportPromise;
3654
+ }
3472
3655
  var ResilientWebSocketClient = class {
3473
3656
  addInfo(msg) {
3474
3657
  this.debugMessages.push({
@@ -3503,7 +3686,17 @@ var ResilientWebSocketClient = class {
3503
3686
  this.currentWS = null;
3504
3687
  this.isOpen = false;
3505
3688
  }
3506
- connect() {
3689
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3690
+ headerlessUrl(headers) {
3691
+ const rest = { ...headers };
3692
+ const apiKey = rest["X-API-Key"];
3693
+ delete rest["X-API-Key"];
3694
+ const extra = Object.keys(rest);
3695
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3696
+ if (apiKey == null) return this.url;
3697
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3698
+ }
3699
+ async connect() {
3507
3700
  this.isOpen = false;
3508
3701
  const prevWS = this.currentWS;
3509
3702
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3512,13 +3705,24 @@ var ResilientWebSocketClient = class {
3512
3705
  this.addInfo("Previous WebSocket discarded");
3513
3706
  prevWS.close();
3514
3707
  }
3515
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3708
+ let ws;
3709
+ try {
3710
+ const transport = await resolveWsTransport();
3711
+ if (this.permanentlyClosed) return;
3712
+ const headers = this.options.headers?.() ?? {};
3713
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3714
+ } catch (e) {
3715
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3716
+ this.permanentlyClosed = true;
3717
+ this.options.onTransportDead?.(e);
3718
+ return;
3719
+ }
3516
3720
  ws.binaryType = "arraybuffer";
3517
3721
  this.currentWS = ws;
3518
- if (this.options.onMessage) ws.onmessage = (event) => {
3722
+ ws.onmessage = (event) => {
3519
3723
  this.options.onMessage(event);
3520
3724
  };
3521
- ws.onopen = (_event) => {
3725
+ ws.onopen = () => {
3522
3726
  if (ws !== this.currentWS) return;
3523
3727
  this.addInfo("✅ WebSocket connected to " + this.url);
3524
3728
  this.isOpen = true;
@@ -3532,7 +3736,7 @@ var ResilientWebSocketClient = class {
3532
3736
  if (this.permanentlyClosed) return;
3533
3737
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3534
3738
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3535
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3739
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3536
3740
  };
3537
3741
  ws.onerror = (event) => {
3538
3742
  if (ws !== this.currentWS) return;
@@ -3550,14 +3754,6 @@ var ResilientWebSocketClient = class {
3550
3754
  this.currentWS?.send(message);
3551
3755
  }
3552
3756
  }
3553
- /** forward WebSocket add event listeners to the current WebSocket instance */
3554
- addEventListener(type, listener, options) {
3555
- this.currentWS?.addEventListener(type, listener, options);
3556
- }
3557
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3558
- removeEventListener(type, listener) {
3559
- this.currentWS?.removeEventListener(type, listener);
3560
- }
3561
3757
  };
3562
3758
  //#endregion
3563
3759
  //#region src/vars/loraKeywords.ts
@@ -3577,9 +3773,10 @@ function loadOnce() {
3577
3773
  if (loaded) return;
3578
3774
  loaded = true;
3579
3775
  const path = filePath();
3580
- if (!existsSync(path)) return;
3776
+ const text = getComfyStorage().readTextIfExists(path);
3777
+ if (text == null) return;
3581
3778
  try {
3582
- const raw = JSON.parse(readFileSync(path, "utf8"));
3779
+ const raw = JSON.parse(text);
3583
3780
  if (raw == null || typeof raw !== "object") return;
3584
3781
  runInAction(() => {
3585
3782
  for (const [name, kw] of Object.entries(raw)) if (typeof kw === "string") keywords.set(name, kw);
@@ -3602,8 +3799,7 @@ function setLoraKeyword(name, keyword) {
3602
3799
  });
3603
3800
  const path = filePath();
3604
3801
  try {
3605
- mkdirSync(dirname(path), { recursive: true });
3606
- writeFileSync(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3802
+ getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2));
3607
3803
  } catch (e) {
3608
3804
  logError(`[loraKeywords] write failed ${path}: ${String(e)}`);
3609
3805
  }
@@ -4047,7 +4243,7 @@ var SizeVar = class extends ComfyVar {
4047
4243
  if (iv == null || iv.value === "") return null;
4048
4244
  try {
4049
4245
  const abs = iv.absPath();
4050
- const meta = imageMeta(new Uint8Array(readFileSync(abs)));
4246
+ const meta = imageMeta(getComfyStorage().readBytes(abs));
4051
4247
  if (meta.width == null || meta.height == null) return null;
4052
4248
  return {
4053
4249
  width: meta.width,
@@ -4101,7 +4297,7 @@ var ImageVarEmptyError = class extends Error {
4101
4297
  /** trim + expand a leading `~/` — every ImageVar write funnels through this */
4102
4298
  function expandUserPath(raw) {
4103
4299
  const trimmed = raw.trim();
4104
- return trimmed.startsWith("~/") ? join(homedir(), trimmed.slice(2)) : trimmed;
4300
+ return trimmed.startsWith("~/") ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed;
4105
4301
  }
4106
4302
  /**
4107
4303
  * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
@@ -4137,7 +4333,7 @@ var ImageVar = class extends ComfyVar {
4137
4333
  absPath() {
4138
4334
  if (!this.isSet()) throw this.emptyError();
4139
4335
  if (isAbsolute(this.value)) return this.value;
4140
- return resolve(this.opts.folder ?? process.cwd(), this.value);
4336
+ return resolve(this.opts.folder ?? getComfyStorage().cwd(), this.value);
4141
4337
  }
4142
4338
  /** empty = unset: the build fails LOUD here (varValues calls outValue) */
4143
4339
  outValue() {
@@ -4146,7 +4342,7 @@ var ImageVar = class extends ComfyVar {
4146
4342
  }
4147
4343
  display() {
4148
4344
  if (!this.isSet()) return "(unset) pick a file";
4149
- const home = homedir();
4345
+ const home = getComfyStorage().homedir();
4150
4346
  return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value;
4151
4347
  }
4152
4348
  };
@@ -4444,11 +4640,11 @@ var ComfyHost = class {
4444
4640
  this.isUpdatingSchema = true;
4445
4641
  const object_info_json = await this.fetchJSON_("/object_info");
4446
4642
  const object_info_str = readableStringify(object_info_json, 4);
4447
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
4643
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
4448
4644
  const res = ComfySchemaJSON_ark(object_info_json);
4449
4645
  if (res instanceof type.errors) printArkResultInConsole(res);
4450
4646
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
4451
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
4647
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
4452
4648
  this.schema.update({
4453
4649
  spec: object_info_json,
4454
4650
  embeddings: embeddings_json
@@ -4465,7 +4661,7 @@ var ComfyHost = class {
4465
4661
  };
4466
4662
  console.error(error);
4467
4663
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
4468
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4664
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4469
4665
  this.markFailed(error);
4470
4666
  } finally {
4471
4667
  this.isUpdatingSchema = false;
@@ -4486,9 +4682,10 @@ var ComfyHost = class {
4486
4682
  this.base = parseHostBase(this.data);
4487
4683
  /** folder where file related to the host config will be cached */
4488
4684
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
4489
- if (!existsSync(this.cacheFolder)) {
4685
+ const storage = getComfyStorage();
4686
+ if (!storage.exists(this.cacheFolder)) {
4490
4687
  console.log("🟢 creating folder", this.cacheFolder);
4491
- mkdirSync(this.cacheFolder, { recursive: true });
4688
+ storage.mkdirp(this.cacheFolder);
4492
4689
  }
4493
4690
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
4494
4691
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -4538,19 +4735,20 @@ var ComfyHost = class {
4538
4735
  }
4539
4736
  async writeSDKToDisk() {
4540
4737
  if (this.data.sdkAutoWrite === false) return;
4738
+ const storage = getComfyStorage();
4541
4739
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
4542
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
4543
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
4740
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
4741
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
4544
4742
  }
4545
4743
  shouldUseSchemaCache() {
4546
4744
  if (this._schemaStrategy === "refresh") return false;
4547
- const exists = existsSync(this.comfyJSONPath);
4745
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
4548
4746
  if (this._schemaStrategy === "cache") {
4549
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4747
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4550
4748
  return true;
4551
4749
  }
4552
- if (!exists) return false;
4553
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
4750
+ if (mtimeMs == null) return false;
4751
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
4554
4752
  }
4555
4753
  waitForSession(timeoutMs = 5e3) {
4556
4754
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -4585,6 +4783,7 @@ var ComfyHost = class {
4585
4783
  onMessage: (e) => this.onMessage(e),
4586
4784
  url: () => this.getWSUrl(),
4587
4785
  headers: () => this.authHeaders(),
4786
+ onTransportDead: (e) => this.markFailed(e),
4588
4787
  onClose: () => {
4589
4788
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
4590
4789
  }
@@ -4604,7 +4803,7 @@ var ComfyHost = class {
4604
4803
  * examples must still open in the TUI; run() fetches the real schema through
4605
4804
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
4606
4805
  loadSchemaFromCache() {
4607
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4806
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
4608
4807
  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`);
4609
4808
  return Promise.resolve();
4610
4809
  }
@@ -4616,7 +4815,7 @@ var ComfyHost = class {
4616
4815
  embeddings: embeddings_json
4617
4816
  });
4618
4817
  this.schema.RUN_BASIC_CHECKS();
4619
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4818
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
4620
4819
  })().catch((e) => {
4621
4820
  this._schemaFromCache = null;
4622
4821
  throw e;
@@ -4708,55 +4907,13 @@ var ComfyHost = class {
4708
4907
  };
4709
4908
  //#endregion
4710
4909
  //#region src/utils/downloadFile.ts
4711
- /** Usage example
4712
- * | ;(async () => {
4713
- * | try {
4714
- * | await downloadFile('https://example.com/file', 'folder/filename')
4715
- * | console.log('Download completed successfully')
4716
- * | } catch (error) {
4717
- * | console.error('Download failed:', error)
4718
- * | }
4719
- * | })()
4720
- * |
4721
- */
4722
- function downloadFile(url, outputPath, logPrefix = " - ") {
4723
- mkdirSync(dirname(outputPath), { recursive: true });
4724
- return new Promise((resolve, reject) => {
4725
- https.get(url, (response) => {
4726
- if (response.statusCode === 302 || response.statusCode === 301) {
4727
- const newUrl = response.headers.location;
4728
- console.log(`Redirected to ${newUrl}`);
4729
- resolve(downloadFile(newUrl, outputPath));
4730
- return;
4731
- }
4732
- if (response.statusCode !== 200) {
4733
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4734
- return;
4735
- }
4736
- const rawLen = response.headers["content-length"];
4737
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4738
- else {
4739
- const totalSize = parseInt(rawLen, 10);
4740
- let downloaded = 0;
4741
- let lastLoggedPercentage = 0;
4742
- response.on("data", (chunk) => {
4743
- downloaded += chunk.length;
4744
- const percentage = Math.round(downloaded / totalSize * 100);
4745
- if (percentage >= lastLoggedPercentage + 1) {
4746
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4747
- lastLoggedPercentage = percentage;
4748
- }
4749
- });
4750
- }
4751
- const fileStream = fs.createWriteStream(outputPath);
4752
- response.pipe(fileStream);
4753
- fileStream.on("finish", () => {
4754
- console.log(` (DONE)`);
4755
- fileStream.close();
4756
- resolve(true);
4757
- });
4758
- }).on("error", (err) => reject(err));
4759
- });
4910
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
4911
+ const res = await fetch(url);
4912
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
4913
+ const bytes = new Uint8Array(await res.arrayBuffer());
4914
+ getComfyStorage().writeBytes(outputPath, bytes);
4915
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
4916
+ return true;
4760
4917
  }
4761
4918
  //#endregion
4762
4919
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4877,7 +5034,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4877
5034
  const _getKnownPlugins = (DB) => {
4878
5035
  const counter = DB.report.file("custom-node-list.json");
4879
5036
  let totalFileSeen = 0;
4880
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
5037
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4881
5038
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4882
5039
  const canonical = [];
4883
5040
  for (const row of root.custom_nodes) {
@@ -4915,7 +5072,7 @@ const _getKnownPlugins = (DB) => {
4915
5072
  }
4916
5073
  out1 += "\n";
4917
5074
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4918
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5075
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4919
5076
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4920
5077
  let out2 = "";
4921
5078
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4923,7 +5080,7 @@ const _getKnownPlugins = (DB) => {
4923
5080
  out2 += "export type KnownComfyPluginURL =\n";
4924
5081
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4925
5082
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4926
- writeFileSync(out2Path, out2, "utf-8");
5083
+ getComfyStorage().writeText(out2Path, out2);
4927
5084
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4928
5085
  }
4929
5086
  if (DB.opts.check) {
@@ -4969,7 +5126,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4969
5126
  const _getCustomNodeRegistry = (DB) => {
4970
5127
  const counter = DB.report.file("extension-node-map.json");
4971
5128
  let totalCustomNodeSeen = 0;
4972
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
5129
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4973
5130
  const root = type("Record<string, unknown>")(raw);
4974
5131
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4975
5132
  for (const [url, value] of Object.entries(root)) {
@@ -5005,7 +5162,7 @@ const _getCustomNodeRegistry = (DB) => {
5005
5162
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
5006
5163
  out += "\n";
5007
5164
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
5008
- writeFileSync(outPath, out + "\n", "utf-8");
5165
+ getComfyStorage().writeText(outPath, out + "\n");
5009
5166
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
5010
5167
  }
5011
5168
  if (DB.opts.check) {
@@ -5060,7 +5217,7 @@ const ComfyManagerModelInfo_ark = type({
5060
5217
  //#region src/manager/loaders/step4_model-list-loader.ts
5061
5218
  const _getKnownModels = (DB) => {
5062
5219
  const counter = DB.report.file("model-list.json");
5063
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
5220
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
5064
5221
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
5065
5222
  const canonical = [];
5066
5223
  for (const row of root.models) {
@@ -5089,7 +5246,7 @@ const _getKnownModels = (DB) => {
5089
5246
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
5090
5247
  out1 += "]\n";
5091
5248
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
5092
- writeFileSync(out1Path, out1 + "\n", "utf-8");
5249
+ getComfyStorage().writeText(out1Path, out1 + "\n");
5093
5250
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
5094
5251
  let out4 = "";
5095
5252
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -5105,7 +5262,7 @@ const _getKnownModels = (DB) => {
5105
5262
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
5106
5263
  out4 += "]\n";
5107
5264
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
5108
- writeFileSync(out4Path, out4 + "\n", "utf-8");
5265
+ getComfyStorage().writeText(out4Path, out4 + "\n");
5109
5266
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
5110
5267
  let out2 = "";
5111
5268
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -5122,7 +5279,7 @@ const _getKnownModels = (DB) => {
5122
5279
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
5123
5280
  out2 += "]\n";
5124
5281
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
5125
- writeFileSync(out2Path, out2 + "\n", "utf-8");
5282
+ getComfyStorage().writeText(out2Path, out2 + "\n");
5126
5283
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
5127
5284
  let out3 = "";
5128
5285
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -5137,7 +5294,7 @@ const _getKnownModels = (DB) => {
5137
5294
  }
5138
5295
  out3 += "\n";
5139
5296
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
5140
- writeFileSync(out3Path, out3 + "\n", "utf-8");
5297
+ getComfyStorage().writeText(out3Path, out3 + "\n");
5141
5298
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
5142
5299
  let out99 = "";
5143
5300
  out99 += `// prettier-ignore\n`;
@@ -5151,7 +5308,7 @@ const _getKnownModels = (DB) => {
5151
5308
  }
5152
5309
  out99 += "\n";
5153
5310
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
5154
- writeFileSync(out99Path, out99 + "\n", "utf-8");
5311
+ getComfyStorage().writeText(out99Path, out99 + "\n");
5155
5312
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
5156
5313
  }
5157
5314
  if (DB.opts.check) {
@@ -5172,7 +5329,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
5172
5329
  //#region src/manager/loaders/step5_alter-list-loader.ts
5173
5330
  const _getAlterList = (DB) => {
5174
5331
  const counter = DB.report.file("alter-list.json");
5175
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
5332
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
5176
5333
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
5177
5334
  const canonical = [];
5178
5335
  for (const row of root.items) {
@@ -5197,7 +5354,7 @@ const ComfyManagerGithubStatEntry_ark = type({
5197
5354
  //#region src/manager/loaders/step6_github-stats-loader.ts
5198
5355
  const _getGithubStats = (DB) => {
5199
5356
  const counter = DB.report.file("github-stats.json");
5200
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
5357
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
5201
5358
  const root = type("Record<string, unknown>")(raw);
5202
5359
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
5203
5360
  for (const [url, value] of Object.entries(root)) {
@@ -5312,13 +5469,12 @@ var ComfyTS = class ComfyTS {
5312
5469
  this.version = version;
5313
5470
  this.hosts = /* @__PURE__ */ new Map();
5314
5471
  this._registry = null;
5315
- this.rootPath = asAbsolutePath(process.cwd());
5316
5472
  this.readJSON_ = (absPath, def) => {
5317
- if (!existsSync(absPath)) {
5473
+ const str = this.storage.readTextIfExists(absPath);
5474
+ if (str == null) {
5318
5475
  if (def != null) return def;
5319
5476
  throw new Error(`file does not exist ${absPath}`);
5320
5477
  }
5321
- const str = readFileSync(absPath, "utf8");
5322
5478
  return JSON.parse(str);
5323
5479
  };
5324
5480
  this.autolayoutOpts = {
@@ -5329,7 +5485,8 @@ var ComfyTS = class ComfyTS {
5329
5485
  const globalHack = globalThis;
5330
5486
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
5331
5487
  globalHack.comfyts = this;
5332
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
5488
+ this.storage = resolveComfyStorage(p.storage);
5489
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
5333
5490
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
5334
5491
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
5335
5492
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -5393,6 +5550,18 @@ var ComfyTS = class ComfyTS {
5393
5550
  }
5394
5551
  };
5395
5552
  //#endregion
5553
+ //#region src/utils/loraTag.ts
5554
+ /**
5555
+ * build a LoraManager-style lora tag: `<lora:name:strength>` or
5556
+ * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5557
+ * autocomplete + validation:
5558
+ *
5559
+ * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5560
+ */
5561
+ function loraTag(name, strength = 1, clipStrength) {
5562
+ return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5563
+ }
5564
+ //#endregion
5396
5565
  //#region src/exampleAssets.ts
5397
5566
  /**
5398
5567
  * the examples/ folder shipped in the npm tarball, resolved from THIS module's
@@ -5445,18 +5614,13 @@ function isTuiActive() {
5445
5614
  return process.env[COMFY_TS_TUI_ENV] === "1";
5446
5615
  }
5447
5616
  //#endregion
5448
- //#region src/utils/loraTag.ts
5617
+ //#region src/index.ts
5449
5618
  /**
5450
- * build a LoraManager-style lora tag: `<lora:name:strength>` or
5451
- * `<lora:name:strength:clipStrength>`. Pin the name to a host union for
5452
- * autocomplete + validation:
5453
- *
5454
- * loraTag<Comfy.Windows1.Union['E_LoraName']>('myLora', 0.8)
5619
+ * comfy-ts — type-safe ComfyUI workflow creation and execution (NODE entry)
5620
+ * @packageDocumentation
5455
5621
  */
5456
- function loraTag(name, strength = 1, clipStrength) {
5457
- return clipStrength == null ? `<lora:${name}:${strength}>` : `<lora:${name}:${strength}:${clipStrength}>`;
5458
- }
5622
+ setDefaultComfyStorage(createNodeStorage());
5459
5623
  //#endregion
5460
- export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, exampleImagePath, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setLoraKeyword, v };
5624
+ export { ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, PromptVar, ResilientWebSocketClient, SeedVar, SizeVar, TextVar, ToggleVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, getComfyStorage, getLoraKeyword, hostIdToNamespace, isTuiActive, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, v };
5461
5625
 
5462
5626
  //# sourceMappingURL=index.js.map