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.
Files changed (115) hide show
  1. package/README.md +106 -6
  2. package/dist/{DefinedWorkflow-gpknV-5f.js → DefinedWorkflow-CqNE_kgR.js} +67 -14
  3. package/dist/DefinedWorkflow-CqNE_kgR.js.map +1 -0
  4. package/dist/{DraftsSt-DmA0jWGl.js → DraftsSt-Da4DZUP7.js} +2 -2
  5. package/dist/{DraftsSt-DmA0jWGl.js.map → DraftsSt-Da4DZUP7.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +548 -239
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +164 -116
  10. package/dist/index.d.ts +165 -117
  11. package/dist/index.js +540 -230
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-Bn6yIJB0.js → run-serve-BqeXtf8P.js} +9 -7
  14. package/dist/run-serve-BqeXtf8P.js.map +1 -0
  15. package/dist/{run-tui-BtjaOXRh.js → run-tui-CiB7TbYv.js} +18 -13
  16. package/dist/run-tui-CiB7TbYv.js.map +1 -0
  17. package/dist/{state-DKCPy105.js → state-C1g_B8zR.js} +398 -201
  18. package/dist/state-C1g_B8zR.js.map +1 -0
  19. package/dist/web.d.ts +17335 -0
  20. package/dist/web.js +5715 -0
  21. package/dist/web.js.map +1 -0
  22. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +1 -0
  23. package/examples/comfy-cloud/anima-t2i.cflow.ts +2 -3
  24. package/examples/comfy-cloud/boogu-i2i.cflow.ts +2 -5
  25. package/examples/comfy-cloud/capybara-i2i.cflow.ts +2 -2
  26. package/examples/comfy-cloud/capybara-i2v.cflow.ts +1 -0
  27. package/examples/comfy-cloud/capybara-t2i.cflow.ts +2 -2
  28. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +1 -0
  29. package/examples/comfy-cloud/chroma-t2i.cflow.ts +2 -5
  30. package/examples/comfy-cloud/ernie-t2i.cflow.ts +2 -3
  31. package/examples/comfy-cloud/firered-i2i.cflow.ts +2 -2
  32. package/examples/comfy-cloud/flux1-i2i.cflow.ts +2 -2
  33. package/examples/comfy-cloud/flux1-t2i.cflow.ts +2 -2
  34. package/examples/comfy-cloud/flux2-i2i.cflow.ts +2 -5
  35. package/examples/comfy-cloud/flux2-t2i.cflow.ts +2 -5
  36. package/examples/comfy-cloud/hidream-i2i.cflow.ts +2 -5
  37. package/examples/comfy-cloud/hidream-t2i.cflow.ts +2 -2
  38. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +1 -0
  39. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +1 -0
  40. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +2 -3
  41. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +1 -0
  42. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +2 -2
  43. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +1 -0
  44. package/examples/comfy-cloud/krea2-t2i.cflow.ts +2 -3
  45. package/examples/comfy-cloud/lens-t2i.cflow.ts +2 -3
  46. package/examples/comfy-cloud/longcat-i2i.cflow.ts +2 -2
  47. package/examples/comfy-cloud/longcat-t2i.cflow.ts +2 -5
  48. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +1 -0
  49. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +1 -0
  50. package/examples/comfy-cloud/newbie-t2i.cflow.ts +2 -5
  51. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +2 -5
  52. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +2 -5
  53. package/examples/comfy-cloud/ovis-t2i.cflow.ts +2 -5
  54. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +2 -5
  55. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +2 -2
  56. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +2 -2
  57. package/examples/comfy-cloud/sd35-t2i.cflow.ts +2 -2
  58. package/examples/comfy-cloud/sdk.d.ts +13251 -11458
  59. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +2 -2
  60. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +1 -0
  61. package/examples/comfy-cloud/svd-i2v.cflow.ts +1 -0
  62. package/examples/comfy-cloud/wan21-i2v.cflow.ts +1 -0
  63. package/examples/comfy-cloud/wan21-t2v.cflow.ts +1 -0
  64. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +1 -0
  65. package/examples/comfy-cloud/wan22-i2v.cflow.ts +1 -0
  66. package/examples/comfy-cloud/wan22-t2v.cflow.ts +1 -0
  67. package/examples/comfy-cloud/z-image-t2i.cflow.ts +2 -5
  68. package/examples/rvion/01-txt2img.cflow.ts +5 -3
  69. package/examples/rvion/02-img2img-upload.cflow.ts +5 -4
  70. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +6 -7
  71. package/examples/rvion/05-comfy-cloud.cflow.ts +4 -2
  72. package/examples/rvion/06-qwen-image-edit.cflow.ts +2 -3
  73. package/examples/web/example.ts +78 -0
  74. package/examples/web/index.html +77 -0
  75. package/examples/web/serve.ts +42 -0
  76. package/examples/web/tsconfig.json +15 -0
  77. package/package.json +8 -2
  78. package/src/cli/serve/ServeApp.ts +9 -6
  79. package/src/cli/tui/state/ExecSt.ts +14 -2
  80. package/src/coreExports.ts +118 -0
  81. package/src/host/ComfyHost.ts +56 -24
  82. package/src/host/ResilientWebsocket.ts +93 -47
  83. package/src/host/hostUrl.ts +2 -1
  84. package/src/host/loraManagerApi.ts +6 -7
  85. package/src/index.ts +8 -107
  86. package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
  87. package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
  88. package/src/manager/loaders/step4_model-list-loader.ts +7 -7
  89. package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
  90. package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
  91. package/src/runner/ComfyExecution.ts +168 -77
  92. package/src/runner/ComfyWorkflow.ts +25 -3
  93. package/src/runner/ComfyWsApi.ts +6 -0
  94. package/src/runner/MediaImage.ts +73 -38
  95. package/src/runner/ephemeral.ts +21 -0
  96. package/src/runner/outputPath.ts +2 -2
  97. package/src/sdk-generator/ComfySchema.ts +2 -2
  98. package/src/sdk-generator/_pythonModuleToNamespace.ts +3 -0
  99. package/src/state.ts +13 -9
  100. package/src/storage/ComfyStorage.ts +144 -0
  101. package/src/storage/nodeStorage.ts +9 -0
  102. package/src/types/index.ts +6 -2
  103. package/src/utils/downloadFile.ts +11 -69
  104. package/src/utils/hashArrayBuffer.ts +3 -4
  105. package/src/utils/lazySharp.ts +25 -0
  106. package/src/utils/sha1.ts +69 -0
  107. package/src/vars/ComfyVars.ts +5 -6
  108. package/src/vars/DefinedWorkflow.ts +3 -1
  109. package/src/vars/loraKeywords.ts +6 -6
  110. package/src/web.ts +13 -0
  111. package/dist/DefinedWorkflow-gpknV-5f.js.map +0 -1
  112. package/dist/run-serve-Bn6yIJB0.js.map +0 -1
  113. package/dist/run-tui-BtjaOXRh.js.map +0 -1
  114. package/dist/state-DKCPy105.js.map +0 -1
  115. package/src/utils/writeFile.ts +0 -16
@@ -1,14 +1,77 @@
1
- import { _ as logError, g as isQuiet, h as extractErrorMessage, t as DefinedWorkflow, v as logInfo, y as logSuccess } from "./DefinedWorkflow-gpknV-5f.js";
2
- import fs, { existsSync, mkdirSync, readFileSync, statSync, writeFile, writeFileSync } from "node:fs";
3
- import { basename, dirname, join } from "pathe";
4
- import crypto from "node:crypto";
1
+ import { _ as resolveComfyStorage, b as logInfo, g as getComfyStorage, h as extractErrorMessage, t as DefinedWorkflow, v as isQuiet, x as logSuccess, y as logError } from "./DefinedWorkflow-CqNE_kgR.js";
2
+ import { basename, join } from "pathe";
5
3
  import { scope, type } from "arktype";
6
4
  import { nanoid } from "nanoid";
7
- import sharp from "sharp";
8
5
  import { imageMeta } from "image-meta";
9
- import WebSocket from "ws";
10
- import https from "node:https";
11
- import { stdout } from "node:process";
6
+ //#region src/utils/sha1.ts
7
+ function sha1Hex(data) {
8
+ const ml = data.length;
9
+ const total = Math.ceil((ml + 1 + 8) / 64) * 64;
10
+ const bytes = new Uint8Array(total);
11
+ bytes.set(data);
12
+ bytes[ml] = 128;
13
+ const dv = new DataView(bytes.buffer);
14
+ const bitLen = ml * 8;
15
+ dv.setUint32(total - 8, Math.floor(bitLen / 2 ** 32));
16
+ dv.setUint32(total - 4, bitLen >>> 0);
17
+ let h0 = 1732584193;
18
+ let h1 = 4023233417;
19
+ let h2 = 2562383102;
20
+ let h3 = 271733878;
21
+ let h4 = 3285377520;
22
+ const w = /* @__PURE__ */ new Uint32Array(80);
23
+ for (let i = 0; i < total; i += 64) {
24
+ for (let j = 0; j < 16; j++) w[j] = dv.getUint32(i + j * 4);
25
+ for (let j = 16; j < 80; j++) {
26
+ const n = (w[j - 3] ?? 0) ^ (w[j - 8] ?? 0) ^ (w[j - 14] ?? 0) ^ (w[j - 16] ?? 0);
27
+ w[j] = n << 1 | n >>> 31;
28
+ }
29
+ let a = h0;
30
+ let b = h1;
31
+ let c = h2;
32
+ let d = h3;
33
+ let e = h4;
34
+ for (let j = 0; j < 80; j++) {
35
+ let f;
36
+ let k;
37
+ if (j < 20) {
38
+ f = b & c | ~b & d;
39
+ k = 1518500249;
40
+ } else if (j < 40) {
41
+ f = b ^ c ^ d;
42
+ k = 1859775393;
43
+ } else if (j < 60) {
44
+ f = b & c | b & d | c & d;
45
+ k = 2400959708;
46
+ } else {
47
+ f = b ^ c ^ d;
48
+ k = 3395469782;
49
+ }
50
+ const temp = (a << 5 | a >>> 27) + f + e + k + (w[j] ?? 0) >>> 0;
51
+ e = d;
52
+ d = c;
53
+ c = b << 30 | b >>> 2;
54
+ b = a;
55
+ a = temp;
56
+ }
57
+ h0 = h0 + a >>> 0;
58
+ h1 = h1 + b >>> 0;
59
+ h2 = h2 + c >>> 0;
60
+ h3 = h3 + d >>> 0;
61
+ h4 = h4 + e >>> 0;
62
+ }
63
+ return [
64
+ h0,
65
+ h1,
66
+ h2,
67
+ h3,
68
+ h4
69
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
70
+ }
71
+ function sha1HexOfString(s) {
72
+ return sha1Hex(new TextEncoder().encode(s));
73
+ }
74
+ //#endregion
12
75
  //#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
13
76
  /** having a bunch of sensible default will help slightly */
14
77
  function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
@@ -39,6 +102,7 @@ function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
39
102
  function pythonModuleToPrefix(pythonModule) {
40
103
  if (pythonModule === "nodes") return "";
41
104
  if (pythonModule.startsWith("comfy_extras.")) return "";
105
+ if (pythonModule === "custom_nodes.websocket_image_save") return "";
42
106
  if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
43
107
  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, "") + ".";
44
108
  console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
@@ -603,7 +667,7 @@ var ComfySchema = class {
603
667
  else if (typeof enumValue === "number") enumValues.push(enumValue);
604
668
  else enumValues.push(enumValue.content);
605
669
  const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
606
- const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
670
+ const hash = sha1HexOfString(hashContent).slice(0, 8);
607
671
  let unionInfo = this.knownUnionByHash.get(hash);
608
672
  if (unionInfo == null) {
609
673
  const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
@@ -820,7 +884,7 @@ var ComfySchema = class {
820
884
  };
821
885
  //#endregion
822
886
  //#region package.json
823
- var version = "1.3.0";
887
+ var version = "2.0.0";
824
888
  //#endregion
825
889
  //#region src/litegraph/LiteGraphLinkID.ts
826
890
  const asLiteGraphLinkID = (id) => id;
@@ -2139,7 +2203,7 @@ var LiteGraphCtx = class {
2139
2203
  * `_00001_` counter every run, so trusting it overwrote the same file — and
2140
2204
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
2141
2205
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
2142
- * (or an explicit saveFormat.prefix override), then
2206
+ * (or an explicit save.prefix override), then
2143
2207
  * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
2144
2208
  * per stem and nothing ever collides.
2145
2209
  */
@@ -2191,6 +2255,19 @@ const runTimestamp = (d) => {
2191
2255
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
2192
2256
  };
2193
2257
  //#endregion
2258
+ //#region src/utils/lazySharp.ts
2259
+ let cached = null;
2260
+ async function importSharp(reason) {
2261
+ if (cached != null) return cached;
2262
+ const specifier = "sharp";
2263
+ try {
2264
+ cached = (await import(specifier)).default;
2265
+ return cached;
2266
+ } catch (e) {
2267
+ throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
2268
+ }
2269
+ }
2270
+ //#endregion
2194
2271
  //#region src/types/index.ts
2195
2272
  const asAbsolutePath = (path) => path;
2196
2273
  const resultSuccess = (value) => ({
@@ -2229,8 +2306,7 @@ function exhaust(x) {
2229
2306
  //#endregion
2230
2307
  //#region src/utils/hashArrayBuffer.ts
2231
2308
  const hashArrayBuffer = (buffer) => {
2232
- const data = Buffer.from(buffer);
2233
- return crypto.createHash("sha1").update(data).digest("hex");
2309
+ return sha1Hex(buffer);
2234
2310
  };
2235
2311
  //#endregion
2236
2312
  //#region src/graph/ComfyNodeID.ts
@@ -2362,6 +2438,21 @@ const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2362
2438
  const WsMsg_ark = types$1.WsMsg;
2363
2439
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2364
2440
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2441
+ //#endregion
2442
+ //#region src/runner/MediaImage.ts
2443
+ /** base64 image loader nodes we know how to wire, in preference order — each
2444
+ * verified against a real object_info dump before entering the table */
2445
+ const BASE64_IMAGE_LOADERS = [{
2446
+ nameInComfy: "ETN_LoadImageBase64",
2447
+ inputs: (b64) => ({ image: b64 })
2448
+ }, {
2449
+ nameInComfy: "easy loadImageBase64",
2450
+ inputs: (b64) => ({
2451
+ base64_data: b64,
2452
+ image_output: "Hide",
2453
+ save_prefix: ""
2454
+ })
2455
+ }];
2365
2456
  type({
2366
2457
  comfyHostHttpURL: "string",
2367
2458
  comfyImageInfo: ComfyImageInfo_ark
@@ -2390,8 +2481,19 @@ var MediaImage = class MediaImage {
2390
2481
  channel
2391
2482
  });
2392
2483
  };
2484
+ this.loadInWorkflow_viaBase64Node = (workflow) => {
2485
+ const schema = workflow.host.schema;
2486
+ const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy));
2487
+ 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).`);
2488
+ return new ComfyNode(workflow, (workflow._uidNumber++).toString(), {
2489
+ class_type: entry.nameInComfy,
2490
+ inputs: entry.inputs(this.getBase64Payload())
2491
+ }, {});
2492
+ };
2393
2493
  this._buffer = null;
2394
- this.freeBuffer = () => void (this._buffer = null);
2494
+ this.freeBuffer = () => {
2495
+ if (this.absPath != null) this._buffer = null;
2496
+ };
2395
2497
  this.updateBuffer = (buff) => {
2396
2498
  this._buffer = buff;
2397
2499
  this._metadata = null;
@@ -2406,41 +2508,35 @@ var MediaImage = class MediaImage {
2406
2508
  this._metadata = null;
2407
2509
  this._hash = null;
2408
2510
  this.processWithSharp_inplace = async (fn) => {
2409
- const buff = await fn(sharp(this.absPath)).toBuffer();
2410
- writeFileSync(this.absPath, buff);
2511
+ const buff = await fn((await importSharp("processWithSharp_inplace"))(this.buffer)).toBuffer();
2512
+ if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff));
2411
2513
  this.updateBuffer(new Uint8Array(buff));
2412
2514
  return this;
2413
2515
  };
2414
2516
  this.processWithSharp = async (fn, path) => {
2415
- const res = fn(sharp(this.absPath));
2416
- path ??= this.absPath + `.processed-${Date.now()}` + this.extension;
2417
- await res.toFile(path);
2418
- const buffer = await res.toBuffer();
2517
+ const sharp = await importSharp("processWithSharp");
2518
+ path ??= this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : void 0;
2519
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer());
2520
+ if (path != null) getComfyStorage().writeBytes(path, buffer);
2419
2521
  return new MediaImage({
2420
2522
  path,
2421
2523
  buffer
2422
2524
  });
2423
2525
  };
2424
- this.generatePreview = async (targetPath) => {
2425
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true });
2426
- mkdirSync(dirname(targetPath), { recursive: true });
2427
- await img.toFile(targetPath);
2428
- };
2429
- this.generateMiniPreview = async () => {
2430
- return (await sharp(this.absPath).resize(32, 32, { fit: "inside" }).webp({ quality: 1 }).toBuffer()).toString("base64");
2431
- };
2432
- this.absPath = data.path;
2526
+ this.absPath = data.path ?? null;
2433
2527
  this.execution = data.execution;
2434
2528
  this.promptNodeID = data.promptNodeID;
2529
+ if (data.path == null && data.buffer == null) throw new Error("❌ MediaImage: an in-memory image (no path) requires a buffer");
2435
2530
  if (data.buffer != null) this.updateBuffer(data.buffer);
2436
2531
  }
2437
2532
  /** the image as a Blob, e.g. to feed FormData uploads */
2438
2533
  getAsBlob() {
2439
2534
  return new Blob([this.buffer], { type: `image/${this.metadata.type ?? "png"}` });
2440
2535
  }
2441
- /** return the image filename */
2536
+ /** return the image filename (in-memory images get a stable hash-derived name) */
2442
2537
  get filename() {
2443
- return basename(this.absPath);
2538
+ if (this.absPath != null) return basename(this.absPath);
2539
+ return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? "png"}`;
2444
2540
  }
2445
2541
  get baseNameWithoutExtension() {
2446
2542
  const fname = this.filename;
@@ -2498,26 +2594,25 @@ var MediaImage = class MediaImage {
2498
2594
  * does not includes the prefix `data:image/png;base64,`
2499
2595
  */
2500
2596
  getBase64Payload() {
2501
- return Buffer.from(this.buffer).toString("base64");
2597
+ const bytes = this.buffer;
2598
+ let bin = "";
2599
+ const chunk = 32768;
2600
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
2601
+ return btoa(bin);
2502
2602
  }
2503
2603
  get buffer() {
2504
2604
  if (this._buffer != null) return this._buffer;
2505
- const buff = readFileSync(this.absPath);
2506
- const uint8arr = new Uint8Array(buff);
2507
- this._buffer = uint8arr;
2605
+ this._buffer = getComfyStorage().readBytes(bang(this.absPath, "in-memory MediaImage lost its buffer"));
2508
2606
  return this._buffer;
2509
2607
  }
2510
2608
  get metadata() {
2511
2609
  if (this._metadata != null) return this._metadata;
2512
- const buff = readFileSync(this.absPath);
2513
- const uint8arr = new Uint8Array(buff);
2514
- this._metadata = imageMeta(uint8arr);
2610
+ this._metadata = imageMeta(this.buffer);
2515
2611
  return this._metadata;
2516
2612
  }
2517
2613
  get hash() {
2518
2614
  if (this._hash != null) return this._hash;
2519
- const buff = readFileSync(this.absPath);
2520
- this._hash = hashArrayBuffer(new Uint8Array(buff));
2615
+ this._hash = hashArrayBuffer(this.buffer);
2521
2616
  return this._hash;
2522
2617
  }
2523
2618
  };
@@ -2533,7 +2628,9 @@ var ComfyExecution = class {
2533
2628
  constructor(workflow, data, init = {}) {
2534
2629
  this.workflow = workflow;
2535
2630
  this.data = data;
2536
- this.saveFormat = null;
2631
+ this.save = null;
2632
+ this.scrubHistory = false;
2633
+ this.ephemeral = false;
2537
2634
  this.snapshot = null;
2538
2635
  this.onProgress = null;
2539
2636
  this.logProgress = false;
@@ -2544,6 +2641,13 @@ var ComfyExecution = class {
2544
2641
  });
2545
2642
  this.onPromptRelatedMessage = (msg) => {
2546
2643
  const graph = this.workflow;
2644
+ if (msg.type === "binary_preview_frame") {
2645
+ if (this.wsOutputNodeExecuting) this.onWsImageOutput({
2646
+ bytes: msg.bytes,
2647
+ mime: msg.mime
2648
+ });
2649
+ return;
2650
+ }
2547
2651
  if (msg.type === "execution_start") return;
2548
2652
  else if (msg.type === "execution_cached") graph.onExecutionCached(msg);
2549
2653
  else if (msg.type === "executing") this.onExecuting(msg);
@@ -2587,70 +2691,104 @@ var ComfyExecution = class {
2587
2691
  this.imageErrors = [];
2588
2692
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
2589
2693
  const promptNode = this.workflow.data.apiJson?.[promptNodeID];
2590
- const promptMeta = this.workflow.data.metadata?.[promptNodeID];
2591
2694
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`);
2592
2695
  const imgRoute = "/view?" + new URLSearchParams(comfyImageInfo).toString();
2593
- const sf = this.saveFormat;
2696
+ const response = await this.host.fetchFile(imgRoute);
2697
+ const bytes = new Uint8Array(await response.arrayBuffer());
2698
+ const comfyUIInfos = {
2699
+ comfyImageInfo,
2700
+ comfyHostHttpURL: this.host.getServerHostHTTP()
2701
+ };
2702
+ const sf = this.save;
2703
+ if (sf == null) return this.pushImage(new MediaImage({
2704
+ buffer: bytes,
2705
+ execution: this,
2706
+ promptNodeID,
2707
+ comfyUIInfos
2708
+ }), promptNodeID);
2594
2709
  const promptPrefix = promptNode.inputs["filename_prefix"];
2595
- let absPath = comfyts.resolveFromOutput(localOutputPath({
2596
- localDir: sf?.prefix,
2710
+ const written = await this.encodeAndWrite({
2711
+ bytes,
2712
+ sf,
2597
2713
  filenamePrefix: typeof promptPrefix === "string" ? promptPrefix : void 0,
2598
2714
  subfolder: comfyImageInfo.subfolder,
2599
- filename: comfyImageInfo.filename,
2600
- timestamp: runTimestamp(new Date(this.startedAt))
2601
- }));
2602
- if (sf?.format && sf.format !== "raw") {
2603
- const extension = sf.format.split("/")[1];
2604
- absPath += "." + extension;
2605
- }
2606
- absPath = uniquifyOutputPath({
2607
- path: absPath,
2608
- exists: existsSync,
2609
- claimed: CLAIMED_OUTPUT_PATHS
2715
+ filename: comfyImageInfo.filename
2610
2716
  });
2611
- mkdirSync(dirname(absPath), { recursive: true });
2612
- let img;
2613
- if (sf && sf.format !== "raw") {
2614
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2717
+ this.pushImage(new MediaImage({
2718
+ path: written.path,
2719
+ buffer: written.bytes,
2720
+ execution: this,
2721
+ promptNodeID,
2722
+ comfyUIInfos
2723
+ }), promptNodeID);
2724
+ };
2725
+ this.encodeAndWrite = async (p) => {
2726
+ let bytes = p.bytes;
2727
+ const reencode = p.sf.format != null && p.sf.format !== "raw";
2728
+ if (reencode) {
2615
2729
  let textChunk = {};
2616
2730
  try {
2617
- const res = getPngMetadataFromUint8Array(new Uint8Array(buff));
2731
+ const res = getPngMetadataFromUint8Array(p.bytes);
2618
2732
  if (res.success) textChunk = res.value;
2619
2733
  } catch {}
2620
2734
  const format = (() => {
2621
- if (sf.format === "image/jpeg") return "jpeg";
2622
- if (sf.format === "image/png") return "png";
2623
- if (sf.format === "image/webp") return "webp";
2735
+ if (p.sf.format === "image/jpeg") return "jpeg";
2736
+ if (p.sf.format === "image/webp") return "webp";
2624
2737
  return "png";
2625
2738
  })();
2626
- await sharp(buff).withMetadata().withExif({ IFD0: textChunk }).toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : void 0).toFile(absPath);
2627
- img = new MediaImage({
2628
- path: asAbsolutePath(absPath),
2629
- execution: this,
2630
- promptNodeID,
2631
- comfyUIInfos: {
2632
- comfyImageInfo,
2633
- comfyHostHttpURL: this.host.getServerHostHTTP()
2634
- }
2635
- });
2636
- } else {
2637
- const buff = await (await this.host.fetchFile(imgRoute)).arrayBuffer();
2638
- const uint8arr = new Uint8Array(buff);
2639
- writeFileSync(absPath, uint8arr);
2640
- img = new MediaImage({
2641
- path: asAbsolutePath(absPath),
2642
- buffer: uint8arr,
2643
- execution: this,
2644
- promptNodeID,
2645
- comfyUIInfos: {
2646
- comfyImageInfo,
2647
- comfyHostHttpURL: this.host.getServerHostHTTP()
2648
- }
2649
- });
2739
+ 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();
2740
+ bytes = new Uint8Array(encoded);
2650
2741
  }
2651
- if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2652
- if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2653
- this.images.push(img);
2742
+ let absPath = comfyts.resolveFromOutput(localOutputPath({
2743
+ localDir: p.sf.prefix,
2744
+ filenamePrefix: p.filenamePrefix,
2745
+ subfolder: p.subfolder,
2746
+ filename: p.filename,
2747
+ timestamp: runTimestamp(new Date(this.startedAt))
2748
+ }));
2749
+ if (reencode) absPath += "." + bang(p.sf.format).split("/")[1];
2750
+ const storage = getComfyStorage();
2751
+ absPath = uniquifyOutputPath({
2752
+ path: absPath,
2753
+ exists: (x) => storage.exists(x),
2754
+ claimed: CLAIMED_OUTPUT_PATHS
2755
+ });
2756
+ storage.writeBytes(asAbsolutePath(absPath), bytes);
2757
+ return {
2758
+ path: asAbsolutePath(absPath),
2759
+ bytes
2760
+ };
2761
+ };
2762
+ this.onWsImageOutput = (p) => {
2763
+ const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
2764
+ this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
2765
+ console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
2766
+ this.imageErrors.push({
2767
+ image: null,
2768
+ error: e
2769
+ });
2770
+ }));
2771
+ };
2772
+ this.storeWsImage = async (p, promptNodeID) => {
2773
+ const sf = this.save;
2774
+ if (sf == null) return this.pushImage(new MediaImage({
2775
+ buffer: p.bytes,
2776
+ execution: this,
2777
+ promptNodeID
2778
+ }), promptNodeID);
2779
+ const ext = p.mime === "image/jpeg" ? "jpg" : p.mime.split("/")[1] ?? "png";
2780
+ const written = await this.encodeAndWrite({
2781
+ bytes: p.bytes,
2782
+ sf,
2783
+ subfolder: "",
2784
+ filename: `${this.workflow.id}.${ext}`
2785
+ });
2786
+ this.pushImage(new MediaImage({
2787
+ path: written.path,
2788
+ buffer: written.bytes,
2789
+ execution: this,
2790
+ promptNodeID
2791
+ }), promptNodeID);
2654
2792
  };
2655
2793
  this.images = [];
2656
2794
  this.alreadyDone = false;
@@ -2664,11 +2802,20 @@ var ComfyExecution = class {
2664
2802
  await Promise.all(this.pendingPromises);
2665
2803
  this.host.executions.delete(this.data.id);
2666
2804
  this.host._pendingMsgs.delete(this.data.id);
2805
+ if (this.ephemeral) {
2806
+ const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type);
2807
+ 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.`);
2808
+ }
2809
+ if (this.scrubHistory) await this.host.deleteHistory(this.data.id).catch((e) => {
2810
+ console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e);
2811
+ });
2667
2812
  this.finishProgressLine();
2668
2813
  this._resolve(this);
2669
2814
  };
2670
2815
  this.snapshot = init.snapshot ?? null;
2671
- this.saveFormat = init.saveFormat ?? null;
2816
+ this.save = init.save === true ? {} : init.save === false ? null : init.save ?? null;
2817
+ this.scrubHistory = init.scrubHistory ?? false;
2818
+ this.ephemeral = init.ephemeral ?? false;
2672
2819
  this.onProgress = init.onProgress ?? null;
2673
2820
  this.logProgress = init.logProgress ?? false;
2674
2821
  this.host.executions.set(data.id, this);
@@ -2693,14 +2840,14 @@ var ComfyExecution = class {
2693
2840
  const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1e3).toFixed(0)}s`;
2694
2841
  if (line === this._lastLoggedLine) return;
2695
2842
  this._lastLoggedLine = line;
2696
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2843
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}`);
2697
2844
  else console.log(line);
2698
2845
  }
2699
2846
  finishProgressLine() {
2700
2847
  if (!this.logProgress) return;
2701
2848
  const p = this.progress;
2702
2849
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${this.images.length} image(s)`;
2703
- if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2850
+ if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
2704
2851
  else console.log(line);
2705
2852
  }
2706
2853
  log(...args) {
@@ -2726,11 +2873,47 @@ var ComfyExecution = class {
2726
2873
  get status() {
2727
2874
  return this.data.status ?? "New";
2728
2875
  }
2876
+ /** accumulate an output on the prompt; tags from node metadata ride along */
2877
+ pushImage(img, promptNodeID) {
2878
+ const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
2879
+ if (promptMeta?.tag) img.tags.push(promptMeta.tag);
2880
+ if (promptMeta?.tags) img.tags.push(...promptMeta.tags);
2881
+ this.images.push(img);
2882
+ }
2883
+ /** true while the currently executing node is a SaveImageWebsocket in the
2884
+ * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
2885
+ * live graph may still say SaveImage) — binary frames are then OUTPUTS */
2886
+ get wsOutputNodeExecuting() {
2887
+ const uid = this.workflow.currentExecutingNode?.uid;
2888
+ if (uid == null) return false;
2889
+ return (this.snapshot?.apiJson ?? this.workflow.apiJson)[uid]?.class_type === "SaveImageWebsocket";
2890
+ }
2729
2891
  update(data) {
2730
2892
  Object.assign(this.data, data);
2731
2893
  }
2732
2894
  };
2733
2895
  //#endregion
2896
+ //#region src/runner/ephemeral.ts
2897
+ /**
2898
+ * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
2899
+ * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`
2900
+ * input only), so outputs stream over the ws and never touch the server disk.
2901
+ * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied
2902
+ * snapshot, never the live graph. Returns how many nodes were rewritten so
2903
+ * callers can warn when a graph had nothing to rewrite.
2904
+ */
2905
+ function rewriteSaveNodesToWebsocket(apiJson) {
2906
+ let rewritten = 0;
2907
+ for (const node of Object.values(apiJson)) {
2908
+ if (node.class_type !== "SaveImage") continue;
2909
+ const images = node.inputs["images"];
2910
+ node.class_type = "SaveImageWebsocket";
2911
+ node.inputs = images == null ? {} : { images };
2912
+ rewritten++;
2913
+ }
2914
+ return rewritten;
2915
+ }
2916
+ //#endregion
2734
2917
  //#region src/utils/deepCopyNaive.ts
2735
2918
  const deepCopyNaive = (x) => JSON.parse(JSON.stringify(x));
2736
2919
  //#endregion
@@ -2993,6 +3176,11 @@ var ComfyWorkflow = class {
2993
3176
  apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? "use_stringified_numbers_only")),
2994
3177
  workflowJson: await this.toWorkflowJson()
2995
3178
  };
3179
+ if (p.ephemeral) {
3180
+ const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson);
3181
+ const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === "SaveImageWebsocket");
3182
+ if (rewritten === 0 && !hasWsSaver) console.warn(`🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`);
3183
+ }
2996
3184
  const out = {
2997
3185
  client_id: this.host.comfySessionId,
2998
3186
  prompt: snapshot.apiJson,
@@ -3015,7 +3203,9 @@ var ComfyWorkflow = class {
3015
3203
  graphID: this.id
3016
3204
  }, {
3017
3205
  snapshot,
3018
- saveFormat: p.saveFormat,
3206
+ save: p.save,
3207
+ ephemeral: p.ephemeral ?? false,
3208
+ scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
3019
3209
  onProgress: p.onProgress,
3020
3210
  logProgress: p.log ?? false
3021
3211
  });
@@ -3174,17 +3364,6 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3174
3364
  return result;
3175
3365
  }
3176
3366
  //#endregion
3177
- //#region src/utils/writeFile.ts
3178
- const writeFileAsync = async (path, data, fmt) => {
3179
- return new Promise((resolve, reject) => {
3180
- logInfo(`writing file: ${ansi.blue(path)}`);
3181
- writeFile(path, data, fmt, (err) => {
3182
- if (err) reject(err);
3183
- else resolve();
3184
- });
3185
- });
3186
- };
3187
- //#endregion
3188
3367
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3189
3368
  const ComfyManagerAPIModelList_ark = type({ models: type({
3190
3369
  name: type.string.as(),
@@ -3422,7 +3601,8 @@ function parseHostBase(p) {
3422
3601
  function renderHttpBase(p) {
3423
3602
  return `${p.scheme}://${p.host}${renderPort(p)}${p.basePath}`;
3424
3603
  }
3425
- /** ws(s) endpoint; auth NEVER rides the query string (headers own it) */
3604
+ /** ws(s) endpoint; auth rides the upgrade headers — EXCEPT headerless
3605
+ * transports (browser), where the ws client remaps X-API-Key to ?token= */
3426
3606
  function renderWsUrl(p) {
3427
3607
  return `${p.scheme === "https" ? "wss" : "ws"}://${p.host}${renderPort(p)}${p.basePath}/ws`;
3428
3608
  }
@@ -3432,6 +3612,27 @@ function renderPort(p) {
3432
3612
  }
3433
3613
  //#endregion
3434
3614
  //#region src/host/ResilientWebsocket.ts
3615
+ let transportPromise = null;
3616
+ /** node: the ws package (headers on the upgrade). browser: native WebSocket. */
3617
+ function resolveWsTransport() {
3618
+ transportPromise ??= (async () => {
3619
+ const specifier = "ws";
3620
+ try {
3621
+ return {
3622
+ ctor: (await import(specifier)).default,
3623
+ supportsHeaders: true
3624
+ };
3625
+ } catch {
3626
+ const native = globalThis.WebSocket;
3627
+ if (native != null) return {
3628
+ ctor: native,
3629
+ supportsHeaders: false
3630
+ };
3631
+ throw new Error(`no WebSocket transport: neither the 'ws' package nor a global WebSocket is available`);
3632
+ }
3633
+ })();
3634
+ return transportPromise;
3635
+ }
3435
3636
  var ResilientWebSocketClient = class {
3436
3637
  addInfo(msg) {
3437
3638
  this.debugMessages.push({
@@ -3466,7 +3667,17 @@ var ResilientWebSocketClient = class {
3466
3667
  this.currentWS = null;
3467
3668
  this.isOpen = false;
3468
3669
  }
3469
- connect() {
3670
+ /** headerless transports carry the api key as ?token= — everything else is refused loud */
3671
+ headerlessUrl(headers) {
3672
+ const rest = { ...headers };
3673
+ const apiKey = rest["X-API-Key"];
3674
+ delete rest["X-API-Key"];
3675
+ const extra = Object.keys(rest);
3676
+ if (extra.length > 0) throw new Error(`custom ws headers (${extra.join(", ")}) need the 'ws' package — a browser WebSocket cannot set upgrade headers`);
3677
+ if (apiKey == null) return this.url;
3678
+ return this.url + (this.url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(apiKey);
3679
+ }
3680
+ async connect() {
3470
3681
  this.isOpen = false;
3471
3682
  const prevWS = this.currentWS;
3472
3683
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
@@ -3475,13 +3686,24 @@ var ResilientWebSocketClient = class {
3475
3686
  this.addInfo("Previous WebSocket discarded");
3476
3687
  prevWS.close();
3477
3688
  }
3478
- const ws = new WebSocket(this.url, { headers: this.options.headers?.() });
3689
+ let ws;
3690
+ try {
3691
+ const transport = await resolveWsTransport();
3692
+ if (this.permanentlyClosed) return;
3693
+ const headers = this.options.headers?.() ?? {};
3694
+ ws = transport.supportsHeaders ? new transport.ctor(this.url, { headers }) : new transport.ctor(this.headerlessUrl(headers));
3695
+ } catch (e) {
3696
+ this.addError(`cannot open WebSocket: ${extractErrorMessage(e)}`);
3697
+ this.permanentlyClosed = true;
3698
+ this.options.onTransportDead?.(e);
3699
+ return;
3700
+ }
3479
3701
  ws.binaryType = "arraybuffer";
3480
3702
  this.currentWS = ws;
3481
- if (this.options.onMessage) ws.onmessage = (event) => {
3703
+ ws.onmessage = (event) => {
3482
3704
  this.options.onMessage(event);
3483
3705
  };
3484
- ws.onopen = (_event) => {
3706
+ ws.onopen = () => {
3485
3707
  if (ws !== this.currentWS) return;
3486
3708
  this.addInfo("✅ WebSocket connected to " + this.url);
3487
3709
  this.isOpen = true;
@@ -3495,7 +3717,7 @@ var ResilientWebSocketClient = class {
3495
3717
  if (this.permanentlyClosed) return;
3496
3718
  this.addError(`WebSocket closed (reason=${JSON.stringify(event.reason)}, code=${event.code})`);
3497
3719
  this.addInfo("⏱️ reconnecting in 2 seconds...");
3498
- this.reconnectTimeout = setTimeout(() => this.connect(), 2e3);
3720
+ this.reconnectTimeout = setTimeout(() => void this.connect(), 2e3);
3499
3721
  };
3500
3722
  ws.onerror = (event) => {
3501
3723
  if (ws !== this.currentWS) return;
@@ -3513,14 +3735,6 @@ var ResilientWebSocketClient = class {
3513
3735
  this.currentWS?.send(message);
3514
3736
  }
3515
3737
  }
3516
- /** forward WebSocket add event listeners to the current WebSocket instance */
3517
- addEventListener(type, listener, options) {
3518
- this.currentWS?.addEventListener(type, listener, options);
3519
- }
3520
- /** forward WebSocket remove event listeners to the current WebSocket instance */
3521
- removeEventListener(type, listener) {
3522
- this.currentWS?.removeEventListener(type, listener);
3523
- }
3524
3738
  };
3525
3739
  //#endregion
3526
3740
  //#region src/host/ComfyHost.ts
@@ -3701,6 +3915,12 @@ var ComfyHost = class {
3701
3915
  this.interrupt = () => {
3702
3916
  return this.postJSON_("/interrupt", {});
3703
3917
  };
3918
+ this.deleteHistory = (promptId) => {
3919
+ return this.postJSON_("/history", { delete: [promptId] });
3920
+ };
3921
+ this.clearHistory = () => {
3922
+ return this.postJSON_("/history", { clear: true });
3923
+ };
3704
3924
  this.fetchRawLogs = async () => {
3705
3925
  const res = await this.fetch("/internal/logs/raw", {}, { apiPrefix: false });
3706
3926
  if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`);
@@ -3736,11 +3956,11 @@ var ComfyHost = class {
3736
3956
  this.isUpdatingSchema = true;
3737
3957
  const object_info_json = await this.fetchJSON_("/object_info");
3738
3958
  const object_info_str = readableStringify(object_info_json, 4);
3739
- writeFileAsync(this.comfyJSONPath, object_info_str, "utf-8");
3959
+ getComfyStorage().writeText(this.comfyJSONPath, object_info_str);
3740
3960
  const res = ComfySchemaJSON_ark(object_info_json);
3741
3961
  if (res instanceof type.errors) printArkResultInConsole(res);
3742
3962
  const embeddings_json = await this.fetchJSON_("/embeddings").catch(() => []);
3743
- writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), "utf-8");
3963
+ getComfyStorage().writeText(this.embeddingsPath, JSON.stringify(embeddings_json));
3744
3964
  this.schema.update({
3745
3965
  spec: object_info_json,
3746
3966
  embeddings: embeddings_json
@@ -3757,7 +3977,7 @@ var ComfyHost = class {
3757
3977
  };
3758
3978
  console.error(error);
3759
3979
  console.error("🔴 FAILURE TO GENERATE the typed sdk", extractErrorMessage(error));
3760
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
3980
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
3761
3981
  this.markFailed(error);
3762
3982
  } finally {
3763
3983
  this.isUpdatingSchema = false;
@@ -3778,9 +3998,10 @@ var ComfyHost = class {
3778
3998
  this.base = parseHostBase(this.data);
3779
3999
  /** folder where file related to the host config will be cached */
3780
4000
  this.cacheFolder = comfyts.resolveFromHosts(this.data.id);
3781
- if (!existsSync(this.cacheFolder)) {
4001
+ const storage = getComfyStorage();
4002
+ if (!storage.exists(this.cacheFolder)) {
3782
4003
  console.log("🟢 creating folder", this.cacheFolder);
3783
- mkdirSync(this.cacheFolder, { recursive: true });
4004
+ storage.mkdirp(this.cacheFolder);
3784
4005
  }
3785
4006
  this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`);
3786
4007
  this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`);
@@ -3830,19 +4051,20 @@ var ComfyHost = class {
3830
4051
  }
3831
4052
  async writeSDKToDisk() {
3832
4053
  if (this.data.sdkAutoWrite === false) return;
4054
+ const storage = getComfyStorage();
3833
4055
  const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id });
3834
- if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, "utf-8") === comfySchemaTs) return;
3835
- await writeFileAsync(this.sdkDTSPath, comfySchemaTs, "utf-8");
4056
+ if (storage.readTextIfExists(this.sdkDTSPath) === comfySchemaTs) return;
4057
+ storage.writeText(this.sdkDTSPath, comfySchemaTs);
3836
4058
  }
3837
4059
  shouldUseSchemaCache() {
3838
4060
  if (this._schemaStrategy === "refresh") return false;
3839
- const exists = existsSync(this.comfyJSONPath);
4061
+ const mtimeMs = getComfyStorage().mtimeMs(this.comfyJSONPath);
3840
4062
  if (this._schemaStrategy === "cache") {
3841
- if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
4063
+ if (mtimeMs == null) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`);
3842
4064
  return true;
3843
4065
  }
3844
- if (!exists) return false;
3845
- return Date.now() - statSync(this.comfyJSONPath).mtimeMs < this._schemaMaxAgeMs;
4066
+ if (mtimeMs == null) return false;
4067
+ return Date.now() - mtimeMs < this._schemaMaxAgeMs;
3846
4068
  }
3847
4069
  waitForSession(timeoutMs = 5e3) {
3848
4070
  if (this.comfySessionId !== "temp") return Promise.resolve();
@@ -3877,6 +4099,7 @@ var ComfyHost = class {
3877
4099
  onMessage: (e) => this.onMessage(e),
3878
4100
  url: () => this.getWSUrl(),
3879
4101
  headers: () => this.authHeaders(),
4102
+ onTransportDead: (e) => this.markFailed(e),
3880
4103
  onClose: () => {
3881
4104
  logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`);
3882
4105
  }
@@ -3896,7 +4119,7 @@ var ComfyHost = class {
3896
4119
  * examples must still open in the TUI; run() fetches the real schema through
3897
4120
  * connect() anyway). Not memoized in that case, so a later gen/connect retries. */
3898
4121
  loadSchemaFromCache() {
3899
- if (this._schemaFromCache == null && !existsSync(this.comfyJSONPath)) {
4122
+ if (this._schemaFromCache == null && !getComfyStorage().exists(this.comfyJSONPath)) {
3900
4123
  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`);
3901
4124
  return Promise.resolve();
3902
4125
  }
@@ -3908,7 +4131,7 @@ var ComfyHost = class {
3908
4131
  embeddings: embeddings_json
3909
4132
  });
3910
4133
  this.schema.RUN_BASIC_CHECKS();
3911
- if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk();
4134
+ if (!getComfyStorage().exists(this.sdkDTSPath)) await this.writeSDKToDisk();
3912
4135
  })().catch((e) => {
3913
4136
  this._schemaFromCache = null;
3914
4137
  throw e;
@@ -3933,6 +4156,22 @@ var ComfyHost = class {
3933
4156
  if (e.data instanceof ArrayBuffer) {
3934
4157
  const frame = parseBinaryWsFrame(e.data);
3935
4158
  if (frame.kind === "preview") {
4159
+ const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null;
4160
+ if (activeExec?.wsOutputNodeExecuting) {
4161
+ activeExec.onWsImageOutput({
4162
+ bytes: frame.bytes,
4163
+ mime: frame.mime
4164
+ });
4165
+ return;
4166
+ }
4167
+ if (this.activePromptID != null) {
4168
+ const pending = this._pendingMsgs.get(this.activePromptID);
4169
+ if (pending != null) pending.push({
4170
+ type: "binary_preview_frame",
4171
+ bytes: frame.bytes,
4172
+ mime: frame.mime
4173
+ });
4174
+ }
3936
4175
  const imageBlob = new Blob([frame.bytes], { type: frame.mime });
3937
4176
  this.latentPreview = {
3938
4177
  blob: imageBlob,
@@ -4000,55 +4239,13 @@ var ComfyHost = class {
4000
4239
  };
4001
4240
  //#endregion
4002
4241
  //#region src/utils/downloadFile.ts
4003
- /** Usage example
4004
- * | ;(async () => {
4005
- * | try {
4006
- * | await downloadFile('https://example.com/file', 'folder/filename')
4007
- * | console.log('Download completed successfully')
4008
- * | } catch (error) {
4009
- * | console.error('Download failed:', error)
4010
- * | }
4011
- * | })()
4012
- * |
4013
- */
4014
- function downloadFile(url, outputPath, logPrefix = " - ") {
4015
- mkdirSync(dirname(outputPath), { recursive: true });
4016
- return new Promise((resolve, reject) => {
4017
- https.get(url, (response) => {
4018
- if (response.statusCode === 302 || response.statusCode === 301) {
4019
- const newUrl = response.headers.location;
4020
- console.log(`Redirected to ${newUrl}`);
4021
- resolve(downloadFile(newUrl, outputPath));
4022
- return;
4023
- }
4024
- if (response.statusCode !== 200) {
4025
- reject(`Failed to download file: Status Code ${response.statusCode}`);
4026
- return;
4027
- }
4028
- const rawLen = response.headers["content-length"];
4029
- if (rawLen == null) console.warn(`download file: progress not available because no content-length header in response.`);
4030
- else {
4031
- const totalSize = parseInt(rawLen, 10);
4032
- let downloaded = 0;
4033
- let lastLoggedPercentage = 0;
4034
- response.on("data", (chunk) => {
4035
- downloaded += chunk.length;
4036
- const percentage = Math.round(downloaded / totalSize * 100);
4037
- if (percentage >= lastLoggedPercentage + 1) {
4038
- stdout.write(`\r${logPrefix}${percentage}% downloaded`);
4039
- lastLoggedPercentage = percentage;
4040
- }
4041
- });
4042
- }
4043
- const fileStream = fs.createWriteStream(outputPath);
4044
- response.pipe(fileStream);
4045
- fileStream.on("finish", () => {
4046
- console.log(` (DONE)`);
4047
- fileStream.close();
4048
- resolve(true);
4049
- });
4050
- }).on("error", (err) => reject(err));
4051
- });
4242
+ async function downloadFile(url, outputPath, logPrefix = " - ") {
4243
+ const res = await fetch(url);
4244
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`);
4245
+ const bytes = new Uint8Array(await res.arrayBuffer());
4246
+ getComfyStorage().writeBytes(outputPath, bytes);
4247
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`);
4248
+ return true;
4052
4249
  }
4053
4250
  //#endregion
4054
4251
  //#region src/manager/loaders/step1_downloadComfyManagerJSONs.ts
@@ -4169,7 +4366,7 @@ const ComfyManagerRawPluginInfo_ark = type({
4169
4366
  const _getKnownPlugins = (DB) => {
4170
4367
  const counter = DB.report.file("custom-node-list.json");
4171
4368
  let totalFileSeen = 0;
4172
- const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(readFileSync("src/manager/json/custom-node-list.json", "utf8")));
4369
+ const root = ComfyManagerFilePluginListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/custom-node-list.json")));
4173
4370
  if (root instanceof type.errors) throw new ManagerParseError("custom-node-list.json", root.summary);
4174
4371
  const canonical = [];
4175
4372
  for (const row of root.custom_nodes) {
@@ -4207,7 +4404,7 @@ const _getKnownPlugins = (DB) => {
4207
4404
  }
4208
4405
  out1 += "\n";
4209
4406
  const out1Path = "src/manager/generated/KnownComfyPluginTitle.ts";
4210
- writeFileSync(out1Path, out1 + "\n", "utf-8");
4407
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4211
4408
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4212
4409
  let out2 = "";
4213
4410
  const sortedFileNames = [...DB.plugins_byFile.keys()].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
@@ -4215,7 +4412,7 @@ const _getKnownPlugins = (DB) => {
4215
4412
  out2 += "export type KnownComfyPluginURL =\n";
4216
4413
  for (const fileName of sortedFileNames) out2 += ` | ${JSON.stringify(fileName)}\n`;
4217
4414
  const out2Path = "src/manager/generated/KnownComfyPluginURL.ts";
4218
- writeFileSync(out2Path, out2, "utf-8");
4415
+ getComfyStorage().writeText(out2Path, out2);
4219
4416
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4220
4417
  }
4221
4418
  if (DB.opts.check) {
@@ -4261,7 +4458,7 @@ const ComfyManagerExtensionNodeMapEntry_ark = type([ComfyManagerPluginContentNod
4261
4458
  const _getCustomNodeRegistry = (DB) => {
4262
4459
  const counter = DB.report.file("extension-node-map.json");
4263
4460
  let totalCustomNodeSeen = 0;
4264
- const raw = JSON.parse(readFileSync("src/manager/json/extension-node-map.json", "utf8"));
4461
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/extension-node-map.json"));
4265
4462
  const root = type("Record<string, unknown>")(raw);
4266
4463
  if (root instanceof type.errors) throw new ManagerParseError("extension-node-map.json", root.summary);
4267
4464
  for (const [url, value] of Object.entries(root)) {
@@ -4297,7 +4494,7 @@ const _getCustomNodeRegistry = (DB) => {
4297
4494
  for (const nodeName of sortedNodeKeys) out += ` | ${JSON.stringify(nodeName)}\n`;
4298
4495
  out += "\n";
4299
4496
  const outPath = "src/manager/generated/KnownComfyCustomNodeName.ts";
4300
- writeFileSync(outPath, out + "\n", "utf-8");
4497
+ getComfyStorage().writeText(outPath, out + "\n");
4301
4498
  console.log(` > generated: ${ansi.blue.underline(outPath)}`);
4302
4499
  }
4303
4500
  if (DB.opts.check) {
@@ -4352,7 +4549,7 @@ const ComfyManagerModelInfo_ark = type({
4352
4549
  //#region src/manager/loaders/step4_model-list-loader.ts
4353
4550
  const _getKnownModels = (DB) => {
4354
4551
  const counter = DB.report.file("model-list.json");
4355
- const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(readFileSync("src/manager/json/model-list.json", "utf8")));
4552
+ const root = ComfyManagerFileModelInfoRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/model-list.json")));
4356
4553
  if (root instanceof type.errors) throw new ManagerParseError("model-list.json", root.summary);
4357
4554
  const canonical = [];
4358
4555
  for (const row of root.models) {
@@ -4381,7 +4578,7 @@ const _getKnownModels = (DB) => {
4381
4578
  for (const [cat, count] of Object.entries(uniqCategories)) out1 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4382
4579
  out1 += "]\n";
4383
4580
  const out1Path = "src/manager/generated/KnownModel_Type.ts";
4384
- writeFileSync(out1Path, out1 + "\n", "utf-8");
4581
+ getComfyStorage().writeText(out1Path, out1 + "\n");
4385
4582
  console.log(` > generated: ${ansi.blue.underline(out1Path)}`);
4386
4583
  let out4 = "";
4387
4584
  const uniqSavePath = knownModelList.reduce((acc, cur) => {
@@ -4397,7 +4594,7 @@ const _getKnownModels = (DB) => {
4397
4594
  for (const [cat, count] of Object.entries(uniqSavePath)) out4 += ` ${JSON.stringify(cat).padEnd(50)}, // x ${count.toString().padStart(3)}\n`;
4398
4595
  out4 += "]\n";
4399
4596
  const out4Path = "src/manager/generated/KnownModel_SavePath.ts";
4400
- writeFileSync(out4Path, out4 + "\n", "utf-8");
4597
+ getComfyStorage().writeText(out4Path, out4 + "\n");
4401
4598
  console.log(` > generated: ${ansi.blue.underline(out4Path)}`);
4402
4599
  let out2 = "";
4403
4600
  const uniqBases = knownModelList.reduce((acc, cur) => {
@@ -4414,7 +4611,7 @@ const _getKnownModels = (DB) => {
4414
4611
  for (const [cat, count] of Object.entries(uniqBases)) out2 += ` ${JSON.stringify(cat).padEnd(20)}, // x ${count.toString().padStart(3)}\n`;
4415
4612
  out2 += "]\n";
4416
4613
  const out2Path = "src/manager/generated/KnownModel_Base.ts";
4417
- writeFileSync(out2Path, out2 + "\n", "utf-8");
4614
+ getComfyStorage().writeText(out2Path, out2 + "\n");
4418
4615
  console.log(` > generated: ${ansi.blue.underline(out2Path)}`);
4419
4616
  let out3 = "";
4420
4617
  const sortedModels = knownModelList.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
@@ -4429,7 +4626,7 @@ const _getKnownModels = (DB) => {
4429
4626
  }
4430
4627
  out3 += "\n";
4431
4628
  const out3Path = "src/manager/generated/KnownModel_Name.ts";
4432
- writeFileSync(out3Path, out3 + "\n", "utf-8");
4629
+ getComfyStorage().writeText(out3Path, out3 + "\n");
4433
4630
  console.log(` > generated: ${ansi.blue.underline(out3Path)}`);
4434
4631
  let out99 = "";
4435
4632
  out99 += `// prettier-ignore\n`;
@@ -4443,7 +4640,7 @@ const _getKnownModels = (DB) => {
4443
4640
  }
4444
4641
  out99 += "\n";
4445
4642
  const out99Path = "src/manager/generated/KnownModel_FileName.ts";
4446
- writeFileSync(out99Path, out99 + "\n", "utf-8");
4643
+ getComfyStorage().writeText(out99Path, out99 + "\n");
4447
4644
  console.log(` > generated: ${ansi.blue.underline(out99Path)}`);
4448
4645
  }
4449
4646
  if (DB.opts.check) {
@@ -4464,7 +4661,7 @@ const ComfyManagerFileAlterListRoot_ark = type({ items: "unknown[]" });
4464
4661
  //#region src/manager/loaders/step5_alter-list-loader.ts
4465
4662
  const _getAlterList = (DB) => {
4466
4663
  const counter = DB.report.file("alter-list.json");
4467
- const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(readFileSync("src/manager/json/alter-list.json", "utf8")));
4664
+ const root = ComfyManagerFileAlterListRoot_ark(JSON.parse(getComfyStorage().readText("src/manager/json/alter-list.json")));
4468
4665
  if (root instanceof type.errors) throw new ManagerParseError("alter-list.json", root.summary);
4469
4666
  const canonical = [];
4470
4667
  for (const row of root.items) {
@@ -4489,7 +4686,7 @@ const ComfyManagerGithubStatEntry_ark = type({
4489
4686
  //#region src/manager/loaders/step6_github-stats-loader.ts
4490
4687
  const _getGithubStats = (DB) => {
4491
4688
  const counter = DB.report.file("github-stats.json");
4492
- const raw = JSON.parse(readFileSync("src/manager/json/github-stats.json", "utf8"));
4689
+ const raw = JSON.parse(getComfyStorage().readText("src/manager/json/github-stats.json"));
4493
4690
  const root = type("Record<string, unknown>")(raw);
4494
4691
  if (root instanceof type.errors) throw new ManagerParseError("github-stats.json", root.summary);
4495
4692
  for (const [url, value] of Object.entries(root)) {
@@ -4604,13 +4801,12 @@ var ComfyTS = class ComfyTS {
4604
4801
  this.version = version;
4605
4802
  this.hosts = /* @__PURE__ */ new Map();
4606
4803
  this._registry = null;
4607
- this.rootPath = asAbsolutePath(process.cwd());
4608
4804
  this.readJSON_ = (absPath, def) => {
4609
- if (!existsSync(absPath)) {
4805
+ const str = this.storage.readTextIfExists(absPath);
4806
+ if (str == null) {
4610
4807
  if (def != null) return def;
4611
4808
  throw new Error(`file does not exist ${absPath}`);
4612
4809
  }
4613
- const str = readFileSync(absPath, "utf8");
4614
4810
  return JSON.parse(str);
4615
4811
  };
4616
4812
  this.autolayoutOpts = {
@@ -4621,7 +4817,8 @@ var ComfyTS = class ComfyTS {
4621
4817
  const globalHack = globalThis;
4622
4818
  if (globalHack.comfyts != null) throw new Error("ComfyTS instance already created");
4623
4819
  globalHack.comfyts = this;
4624
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath);
4820
+ this.storage = resolveComfyStorage(p.storage);
4821
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd());
4625
4822
  this.baseFolder = asAbsolutePath(join(this.rootPath, ".comfy-ts"));
4626
4823
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, "hosts"));
4627
4824
  this.outputPath = asAbsolutePath(join(this.baseFolder, "outputs"));
@@ -4685,6 +4882,6 @@ var ComfyTS = class ComfyTS {
4685
4882
  }
4686
4883
  };
4687
4884
  //#endregion
4688
- export { ComfySchema as a, stripAnsi as i, settingsPathFor as n, readableStringify as r, ComfyTS as t };
4885
+ export { ComfySchema as a, stripAnsi as i, settingsPathFor as n, sha1HexOfString as o, readableStringify as r, ComfyTS as t };
4689
4886
 
4690
- //# sourceMappingURL=state-DKCPy105.js.map
4887
+ //# sourceMappingURL=state-C1g_B8zR.js.map