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
@@ -8,9 +8,10 @@ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
8
8
  import { ComfyNode } from 'src/graph/ComfyNode.ts'
9
9
  import type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
10
10
  import { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
11
+ import { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'
11
12
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
12
13
  import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
13
- import { type AbsolutePath, type ImageSaveFormat, type Maybe, type Tagged } from 'src/types/index.ts'
14
+ import { type AbsolutePath, type Maybe, type SaveOptions, type Tagged } from 'src/types/index.ts'
14
15
  import type { SdkForHost } from 'src/types/comfy-sdk.ts'
15
16
  import { bang } from 'src/utils/bang.ts'
16
17
  import { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'
@@ -35,7 +36,16 @@ export type ProgressReport = {
35
36
  export type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'
36
37
 
37
38
  export type RunSettings = {
38
- saveFormat?: ImageSaveFormat
39
+ /** local disk saving is OPT-IN: unset/false keeps outputs in memory only
40
+ * (`execution.images` buffers); `true` = raw save, an object re-encodes/relocates */
41
+ save?: boolean | SaveOptions
42
+ /** rewrite every SaveImage node to SaveImageWebsocket in the SENT prompt —
43
+ * outputs never touch the server disk. Implies `scrubHistory` unless that
44
+ * is explicitly false. (architecture.md item 14) */
45
+ ephemeral?: boolean
46
+ /** delete this run's server history entry (workflow JSON, prompts, filenames)
47
+ * after `done` — loud but non-fatal on failure */
48
+ scrubHistory?: boolean
39
49
  idMode?: ComfyNodeIdMode
40
50
  /** render a live single-line progress report to the console */
41
51
  log?: boolean
@@ -350,6 +360,15 @@ export class ComfyWorkflow<ID extends string = string> {
350
360
  apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),
351
361
  workflowJson: await this.toWorkflowJson(),
352
362
  }
363
+ // ephemeral: rewrite in the SNAPSHOT only — the live graph stays editable/exportable as authored
364
+ if (p.ephemeral) {
365
+ const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson)
366
+ const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === 'SaveImageWebsocket')
367
+ if (rewritten === 0 && !hasWsSaver)
368
+ console.warn(
369
+ `🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`,
370
+ )
371
+ }
353
372
  const out: ApiPromptInput = {
354
373
  client_id: this.host.comfySessionId,
355
374
  prompt: snapshot.apiJson,
@@ -385,7 +404,10 @@ export class ComfyWorkflow<ID extends string = string> {
385
404
  },
386
405
  {
387
406
  snapshot,
388
- saveFormat: p.saveFormat,
407
+ save: p.save,
408
+ ephemeral: p.ephemeral ?? false,
409
+ // ephemeral implies the scrub unless the caller explicitly opted out
410
+ scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
389
411
  onProgress: p.onProgress,
390
412
  logProgress: p.log ?? false,
391
413
  },
@@ -140,6 +140,12 @@ export type NodeProgress = typeof types.NodeProgress.infer
140
140
 
141
141
  // LIVE UPDATES ----------------------------------------------------
142
142
  export type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer
143
+
144
+ /** a binary preview-kind ws frame buffered IN ORDER with the json messages
145
+ * during the pre-registration window (ComfyHost._pendingMsgs) — replayed by
146
+ * ComfyExecution.onCreate, which decides output-vs-latent at replay time */
147
+ export type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string }
148
+ export type PendingWsItem = PromptRelated_WsMsg | PendingBinaryFrame
143
149
  export type WsMsg = typeof types.WsMsg.infer
144
150
  export type ComfyStatusData = typeof types.ComfyStatusData.infer
145
151
  export type WsMsgStatus = typeof types.WsMsgStatus.infer
@@ -1,12 +1,13 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
1
  import { type } from 'arktype'
3
2
  import { type ImageMeta, imageMeta } from 'image-meta'
4
- import { basename, dirname } from 'pathe'
5
- import sharp, { type Sharp } from 'sharp'
3
+ import { basename } from 'pathe'
4
+ import type { Sharp } from 'sharp'
5
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
6
+ import { importSharp } from 'src/utils/lazySharp.ts'
6
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
7
8
  import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
8
9
  import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
9
- import type { AbsolutePath, Maybe } from 'src/types/index.ts'
10
+ import { type AbsolutePath, asAbsolutePath, type Maybe } from 'src/types/index.ts'
10
11
  import type { NodeOf } from 'src/types/comfy-sdk.ts'
11
12
  import type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'
12
13
  import { bang } from 'src/utils/bang.ts'
@@ -14,9 +15,23 @@ import { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'
14
15
  import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
15
16
  import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
16
17
  import { type ComfyImageInfo, ComfyImageInfo_ark } from 'src/runner/ComfyWsApi.ts'
18
+ import { ComfyNode } from 'src/graph/ComfyNode.ts'
19
+
20
+ /** base64 image loader nodes we know how to wire, in preference order — each
21
+ * verified against a real object_info dump before entering the table */
22
+ export const BASE64_IMAGE_LOADERS: { nameInComfy: string; inputs: (b64: string) => ComfyApiNodeJson['inputs'] }[] = [
23
+ // comfyui-tooling-nodes: outputs IMAGE + MASK (alpha)
24
+ { nameInComfy: 'ETN_LoadImageBase64', inputs: (b64) => ({ image: b64 }) },
25
+ // ComfyUI-Easy-Use: image_output 'Hide' + empty prefix so the node itself saves nothing
26
+ {
27
+ nameInComfy: 'easy loadImageBase64',
28
+ inputs: (b64) => ({ base64_data: b64, image_output: 'Hide', save_prefix: '' }),
29
+ },
30
+ ]
17
31
 
18
32
  export type MediaImageData = {
19
- path: AbsolutePath
33
+ /** absent = in-memory image (ws output with local saving off) — the buffer is then required */
34
+ path?: Maybe<AbsolutePath>
20
35
 
21
36
  // to avoid having to read the file if we already have the buffer around
22
37
  buffer?: Uint8Array
@@ -39,7 +54,8 @@ export const ImageInfos_ComfyGenerated_ark = type({
39
54
  })
40
55
 
41
56
  export class MediaImage {
42
- absPath: AbsolutePath
57
+ /** null for in-memory images (local saving is opt-in — architecture.md item 14) */
58
+ absPath: AbsolutePath | null
43
59
 
44
60
  /** the execution this image came from (null when not generated via comfy-ts) */
45
61
  execution: Maybe<ComfyExecution>
@@ -52,9 +68,11 @@ export class MediaImage {
52
68
  promptNodeID: Maybe<string>
53
69
 
54
70
  constructor(data: MediaImageData) {
55
- this.absPath = data.path
71
+ this.absPath = data.path ?? null
56
72
  this.execution = data.execution
57
73
  this.promptNodeID = data.promptNodeID
74
+ if (data.path == null && data.buffer == null)
75
+ throw new Error('❌ MediaImage: an in-memory image (no path) requires a buffer')
58
76
  if (data.buffer != null) this.updateBuffer(data.buffer)
59
77
  }
60
78
 
@@ -66,9 +84,10 @@ export class MediaImage {
66
84
  return new Blob([this.buffer as Uint8Array<ArrayBuffer>], { type: `image/${this.metadata.type ?? 'png'}` })
67
85
  }
68
86
 
69
- /** return the image filename */
87
+ /** return the image filename (in-memory images get a stable hash-derived name) */
70
88
  get filename(): string {
71
- return basename(this.absPath)
89
+ if (this.absPath != null) return basename(this.absPath)
90
+ return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? 'png'}`
72
91
  }
73
92
 
74
93
  get baseNameWithoutExtension(): string {
@@ -124,6 +143,31 @@ export class MediaImage {
124
143
  return mask as NodeOf<WID, 'LoadImageMask'>
125
144
  }
126
145
 
146
+ /** load this image into the workflow WITHOUT any server-side file: the
147
+ * image rides base64 inside the prompt JSON (architecture.md item 14 —
148
+ * the prompt still enters server history; `scrubHistory` covers that).
149
+ * Feature-detected against the host schema; no supported node = loud throw. */
150
+ loadInWorkflow_viaBase64Node = <WID extends string>(workflow: ComfyWorkflow<WID>): NodeOf<WID, 'LoadImage'> => {
151
+ const schema = workflow.host.schema
152
+ const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy))
153
+ if (entry == null) {
154
+ throw new Error(
155
+ `❌ host '${workflow.host.data.id}' has no base64 image loader node ` +
156
+ `(looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(', ')}). ` +
157
+ `Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`,
158
+ )
159
+ }
160
+ const node = new ComfyNode(
161
+ workflow,
162
+ (workflow._uidNumber++).toString(),
163
+ { class_type: entry.nameInComfy, inputs: entry.inputs(this.getBase64Payload()) },
164
+ {},
165
+ )
166
+ // sanctioned cast (family 1, like the two sibling loaders): both table
167
+ // nodes output IMAGE+MASK, the LoadImage face is the shape consumers wire
168
+ return node as NodeOf<WID, 'LoadImage'>
169
+ }
170
+
127
171
  /** return the json of the ComfyNode that led to this image */
128
172
  get ComfyNode(): Maybe<ComfyApiNodeJson> {
129
173
  const nodeID = this.promptNodeID
@@ -170,8 +214,11 @@ export class MediaImage {
170
214
  * does not includes the prefix `data:image/png;base64,`
171
215
  */
172
216
  getBase64Payload(): string {
173
- const bin = Buffer.from(this.buffer)
174
- return bin.toString('base64')
217
+ const bytes = this.buffer
218
+ let bin = ''
219
+ const chunk = 0x8000 // String.fromCharCode arg-count limit
220
+ for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk))
221
+ return btoa(bin)
175
222
  }
176
223
 
177
224
  /** return the ArrayBuffer for this file, regardless it's exact representation */
@@ -180,12 +227,13 @@ export class MediaImage {
180
227
  private _buffer: Maybe<Uint8Array> = null
181
228
  get buffer(): Uint8Array {
182
229
  if (this._buffer != null) return this._buffer
183
- const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)
184
- const uint8arr = new Uint8Array(buff)
185
- this._buffer = uint8arr
230
+ this._buffer = getComfyStorage().readBytes(bang(this.absPath, 'in-memory MediaImage lost its buffer'))
186
231
  return this._buffer
187
232
  }
188
- freeBuffer = (): void => void (this._buffer = null)
233
+ /** no-op on in-memory images: the buffer is the only copy */
234
+ freeBuffer = (): void => {
235
+ if (this.absPath != null) this._buffer = null
236
+ }
189
237
  updateBuffer = (buff: Uint8Array): void => {
190
238
  this._buffer = buff
191
239
  this._metadata = null // expire metadata
@@ -202,17 +250,14 @@ export class MediaImage {
202
250
  private _metadata: Maybe<ImageMeta> = null
203
251
  get metadata(): ImageMeta {
204
252
  if (this._metadata != null) return this._metadata
205
- const buff = readFileSync(this.absPath)
206
- const uint8arr = new Uint8Array(buff)
207
- this._metadata = imageMeta(uint8arr)
253
+ this._metadata = imageMeta(this.buffer)
208
254
  return this._metadata
209
255
  }
210
256
 
211
257
  private _hash: Maybe<string> = null
212
258
  get hash(): string {
213
259
  if (this._hash != null) return this._hash
214
- const buff: Buffer | ArrayBuffer = readFileSync(this.absPath)
215
- this._hash = hashArrayBuffer(new Uint8Array(buff))
260
+ this._hash = hashArrayBuffer(this.buffer)
216
261
  return this._hash
217
262
  }
218
263
 
@@ -224,8 +269,9 @@ export class MediaImage {
224
269
  /** processing function */
225
270
  fn: (sharp: Sharp) => Sharp,
226
271
  ): Promise<this> => {
227
- const buff = await fn(sharp(this.absPath)).toBuffer()
228
- writeFileSync(this.absPath, buff)
272
+ const sharp = await importSharp('processWithSharp_inplace')
273
+ const buff = await fn(sharp(this.buffer)).toBuffer()
274
+ if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))
229
275
  this.updateBuffer(new Uint8Array(buff))
230
276
  return this
231
277
  }
@@ -241,22 +287,11 @@ export class MediaImage {
241
287
  /** where to save the resulting image */
242
288
  path?: AbsolutePath,
243
289
  ): Promise<MediaImage> => {
244
- const res: Sharp = fn(sharp(this.absPath))
245
- path ??= this.absPath + `.processed-${Date.now()}` + this.extension
246
- await res.toFile(path)
247
- const buffer = await res.toBuffer()
290
+ const sharp = await importSharp('processWithSharp')
291
+ path ??=
292
+ this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : undefined
293
+ const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())
294
+ if (path != null) getComfyStorage().writeBytes(path, buffer)
248
295
  return new MediaImage({ path, buffer })
249
296
  }
250
-
251
- generatePreview = async (targetPath: string): Promise<void> => {
252
- const img = sharp(this.absPath).rotate().resize(100).jpeg({ mozjpeg: true })
253
- mkdirSync(dirname(targetPath), { recursive: true })
254
- await img.toFile(targetPath)
255
- }
256
-
257
- generateMiniPreview = async (): Promise<string> => {
258
- const image2 = await sharp(this.absPath).resize(32, 32, { fit: 'inside' }).webp({ quality: 1 }).toBuffer()
259
- const x = image2.toString('base64')
260
- return x
261
- }
262
297
  }
@@ -0,0 +1,21 @@
1
+ import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
2
+
3
+ /**
4
+ * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
5
+ * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`
6
+ * input only), so outputs stream over the ws and never touch the server disk.
7
+ * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied
8
+ * snapshot, never the live graph. Returns how many nodes were rewritten so
9
+ * callers can warn when a graph had nothing to rewrite.
10
+ */
11
+ export function rewriteSaveNodesToWebsocket(apiJson: ComfyApiJson): number {
12
+ let rewritten = 0
13
+ for (const node of Object.values(apiJson)) {
14
+ if (node.class_type !== 'SaveImage') continue
15
+ const images = node.inputs['images']
16
+ node.class_type = 'SaveImageWebsocket'
17
+ node.inputs = images == null ? {} : { images }
18
+ rewritten++
19
+ }
20
+ return rewritten
21
+ }
@@ -4,12 +4,12 @@
4
4
  * `_00001_` counter every run, so trusting it overwrote the same file — and
5
5
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
6
6
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
7
- * (or an explicit saveFormat.prefix override), then
7
+ * (or an explicit save.prefix override), then
8
8
  * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
9
9
  * per stem and nothing ever collides.
10
10
  */
11
11
  export const localOutputPath = (p: {
12
- /** explicit local dir override (ImageSaveFormat.prefix) — wins when set */
12
+ /** explicit local dir override (SaveOptions.prefix) — wins when set */
13
13
  localDir?: string
14
14
  /** the SaveImage node's own filename_prefix as sent in the prompt */
15
15
  filenamePrefix?: string
@@ -1,4 +1,4 @@
1
- import crypto from 'node:crypto'
1
+ import { sha1HexOfString } from 'src/utils/sha1.ts'
2
2
  import { getUnionNameBasedOnFirstFoundEnumName } from 'src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts'
3
3
  import { toQualifiedNodeKey } from 'src/sdk-generator/_toQualifiedNodeKey.ts'
4
4
  import { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
@@ -280,7 +280,7 @@ export class ComfySchema {
280
280
  enumValues.length === 0 //
281
281
  ? `[[empty]]`
282
282
  : enumValues.sort().join('|')
283
- const hash = crypto.createHash('sha1').update(hashContent).digest('hex').slice(0, 8)
283
+ const hash = sha1HexOfString(hashContent).slice(0, 8)
284
284
 
285
285
  // 3. retrieve or create an EnumInfo
286
286
  let unionInfo: Maybe<ComfyUnionInfo> = this.knownUnionByHash.get(hash)
@@ -2,6 +2,9 @@ export function pythonModuleToPrefix(pythonModule: string): string {
2
2
  // if (pythonModule == null) console.error(`[🔴🔴🔴🔴🔴🔴] `, pythonModule)
3
3
  if (pythonModule === 'nodes') return ''
4
4
  if (pythonModule.startsWith('comfy_extras.')) return '' //''
5
+ // ships INSIDE the ComfyUI repo (upstream parks it under custom_nodes/):
6
+ // the ephemeral-outputs saver reads `b.SaveImageWebsocket` like the core node it is
7
+ if (pythonModule === 'custom_nodes.websocket_image_save') return ''
5
8
  if (pythonModule.startsWith('comfy_api_nodes.')) return pythonModule.replace('comfy_api_nodes.', 'api.')
6
9
  if (pythonModule.startsWith('custom_nodes.')) {
7
10
  // return `${pythonModuleToNamespace_(pythonModule.replace('custom_nodes.', ''))}.`
package/src/state.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { existsSync, readFileSync } from 'node:fs'
2
1
  import { join } from 'pathe'
3
2
  import pkgJson from '../package.json' with { type: 'json' }
4
3
  import { ComfyHost, type ComfyHostData } from 'src/host/ComfyHost.ts'
5
4
  import { parseHostBase, renderHttpBase } from 'src/host/hostUrl.ts'
6
5
  import { ComfyRegistry } from 'src/manager/ComfyRegistry.ts'
6
+ import { type ComfyStorage, resolveComfyStorage } from 'src/storage/ComfyStorage.ts'
7
7
  import { type AbsolutePath, asAbsolutePath, type RelativePath } from 'src/types/index.ts'
8
8
 
9
9
  /** the ONE settings-file location rule — run-tui reads it BEFORE any module
@@ -16,12 +16,17 @@ export function settingsPathFor(root: string): AbsolutePath {
16
16
  export class ComfyTS {
17
17
  version = pkgJson.version
18
18
 
19
- constructor(p: { rootPath?: string } = {}) {
19
+ /** the storage seam (architecture item 13): node fs by default, in-memory on web */
20
+ storage: ComfyStorage
21
+
22
+ constructor(p: { rootPath?: string; storage?: ComfyStorage } = {}) {
20
23
  // global registration: the rest of the lib resolves paths through `comfyts`
21
24
  const globalHack = globalThis as { comfyts?: ComfyTS }
22
25
  if (globalHack.comfyts != null) throw new Error('ComfyTS instance already created')
23
26
  globalHack.comfyts = this
24
- if (p.rootPath) this.rootPath = asAbsolutePath(p.rootPath)
27
+ // storage FIRST: the default rootPath comes from it (browser has no process.cwd)
28
+ this.storage = resolveComfyStorage(p.storage)
29
+ this.rootPath = asAbsolutePath(p.rootPath ?? this.storage.cwd())
25
30
  this.baseFolder = asAbsolutePath(join(this.rootPath, '.comfy-ts'))
26
31
  this.hostsFolder = asAbsolutePath(join(this.baseFolder, 'hosts'))
27
32
  this.outputPath = asAbsolutePath(join(this.baseFolder, 'outputs'))
@@ -32,7 +37,7 @@ export class ComfyTS {
32
37
  * it. Workflow modules MUST use this (the TUI imports many of them into one
33
38
  * process); `new ComfyTS()` still throws on a second instance.
34
39
  */
35
- static create(p: { rootPath?: string } = {}): ComfyTS {
40
+ static create(p: { rootPath?: string; storage?: ComfyStorage } = {}): ComfyTS {
36
41
  const globalHack = globalThis as { comfyts?: ComfyTS }
37
42
  const existing = globalHack.comfyts
38
43
  if (existing == null) return new ComfyTS(p)
@@ -82,8 +87,8 @@ export class ComfyTS {
82
87
  return this._registry
83
88
  }
84
89
 
85
- /** root path used to resolve things */
86
- rootPath: AbsolutePath = asAbsolutePath(process.cwd())
90
+ /** root path used to resolve things (set in the constructor, storage.cwd() default) */
91
+ rootPath: AbsolutePath
87
92
 
88
93
  /**
89
94
  * every repo using comfy-ts gets ONE `.comfy-ts/` folder:
@@ -126,12 +131,11 @@ export class ComfyTS {
126
131
  }
127
132
 
128
133
  readJSON_ = <T>(absPath: AbsolutePath, def?: T): T => {
129
- const exists = existsSync(absPath)
130
- if (!exists) {
134
+ const str = this.storage.readTextIfExists(absPath)
135
+ if (str == null) {
131
136
  if (def != null) return def
132
137
  throw new Error(`file does not exist ${absPath}`)
133
138
  }
134
- const str = readFileSync(absPath, 'utf8')
135
139
  const json = JSON.parse(str)
136
140
  return json
137
141
  }
@@ -0,0 +1,144 @@
1
+ // the storage seam (architecture item 13): ONE sync fs-subset interface the
2
+ // core path talks to. Node gets the real fs, the web entry an in-memory Map.
3
+ // This file must stay browser-safe: no node imports, ever.
4
+
5
+ export type ComfyStorage = {
6
+ /** backend name, for error messages */
7
+ kind: string
8
+ /** throws when missing */
9
+ readText(path: string): string
10
+ readTextIfExists(path: string): string | null
11
+ /** throws when missing */
12
+ readBytes(path: string): Uint8Array
13
+ /** parents are created (mkdirp implied) */
14
+ writeText(path: string, text: string): void
15
+ /** parents are created (mkdirp implied) */
16
+ writeBytes(path: string, bytes: Uint8Array): void
17
+ exists(path: string): boolean
18
+ mkdirp(path: string): void
19
+ /** file mtime in ms; null when missing */
20
+ mtimeMs(path: string): number | null
21
+ homedir(): string
22
+ cwd(): string
23
+ }
24
+
25
+ /** the fs/os surface createNodeStorageFrom needs — structural, so this file
26
+ * never imports node types into the web graph */
27
+ export type NodeFsLike = {
28
+ readFileSync(path: string, encoding?: 'utf8'): string | Uint8Array
29
+ writeFileSync(path: string, data: string | Uint8Array): void
30
+ existsSync(path: string): boolean
31
+ mkdirSync(path: string, opts: { recursive: boolean }): unknown
32
+ statSync(path: string): { mtimeMs: number; isFile(): boolean }
33
+ }
34
+ export type NodeOsLike = { homedir(): string }
35
+
36
+ function dirnameOf(path: string): string {
37
+ const ix = path.lastIndexOf('/')
38
+ return ix <= 0 ? '/' : path.slice(0, ix)
39
+ }
40
+
41
+ /** node backend built from INJECTED modules: nodeStorage.ts passes its static
42
+ * imports, the autodetect below passes process.getBuiltinModule results */
43
+ export function createNodeStorageFrom(fs: NodeFsLike, os: NodeOsLike): ComfyStorage {
44
+ return {
45
+ kind: 'node',
46
+ readText: (p) => fs.readFileSync(p, 'utf8') as string,
47
+ readTextIfExists: (p) => (fs.existsSync(p) ? (fs.readFileSync(p, 'utf8') as string) : null),
48
+ readBytes: (p) => new Uint8Array(fs.readFileSync(p) as Uint8Array),
49
+ writeText: (p, text) => {
50
+ fs.mkdirSync(dirnameOf(p), { recursive: true })
51
+ fs.writeFileSync(p, text)
52
+ },
53
+ writeBytes: (p, bytes) => {
54
+ fs.mkdirSync(dirnameOf(p), { recursive: true })
55
+ fs.writeFileSync(p, bytes)
56
+ },
57
+ exists: (p) => fs.existsSync(p),
58
+ mkdirp: (p) => void fs.mkdirSync(p, { recursive: true }),
59
+ mtimeMs: (p) => (fs.existsSync(p) ? fs.statSync(p).mtimeMs : null),
60
+ homedir: () => os.homedir(),
61
+ cwd: () => process.cwd(),
62
+ }
63
+ }
64
+
65
+ /** in-memory backend: the web default, also handy for hermetic tests.
66
+ * Paths are LITERAL keys (no normalization — core callers resolve through
67
+ * pathe/comfyts already). exists() knows written files and EXPLICIT mkdirp
68
+ * dirs only, never implicit parents. Bytes are copied in AND out so neither
69
+ * side can mutate the store. */
70
+ export function createMemoryStorage(p: { homedir?: string; cwd?: string } = {}): ComfyStorage {
71
+ const files = new Map<string, Uint8Array>()
72
+ const mtimes = new Map<string, number>()
73
+ const dirs = new Set<string>()
74
+ const td = new TextDecoder()
75
+ const te = new TextEncoder()
76
+ const write = (path: string, bytes: Uint8Array): void => {
77
+ files.set(path, bytes.slice())
78
+ mtimes.set(path, Date.now())
79
+ }
80
+ return {
81
+ kind: 'memory',
82
+ readText: (path) => {
83
+ const hit = files.get(path)
84
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)
85
+ return td.decode(hit)
86
+ },
87
+ readTextIfExists: (path) => {
88
+ const hit = files.get(path)
89
+ return hit == null ? null : td.decode(hit)
90
+ },
91
+ readBytes: (path) => {
92
+ const hit = files.get(path)
93
+ if (hit == null) throw new Error(`[memory storage] no such file: ${path}`)
94
+ return hit.slice()
95
+ },
96
+ writeText: (path, text) => write(path, te.encode(text)),
97
+ writeBytes: write,
98
+ exists: (path) => files.has(path) || dirs.has(path),
99
+ mkdirp: (path) => void dirs.add(path),
100
+ mtimeMs: (path) => mtimes.get(path) ?? null,
101
+ homedir: () => p.homedir ?? '/home/web',
102
+ cwd: () => p.cwd ?? '/',
103
+ }
104
+ }
105
+
106
+ // ---- default resolution (architecture item 13) ------------------------------
107
+ // explicit ComfyTS.create({storage}) → entry-installed default → node builtins
108
+ // autodetect (node 22+/bun: no static import needed) → loud throw.
109
+
110
+ let installedDefault: ComfyStorage | null = null
111
+
112
+ /** entries call this at import time: index.ts installs node, web.ts memory */
113
+ export function setDefaultComfyStorage(storage: ComfyStorage): void {
114
+ installedDefault = storage
115
+ }
116
+
117
+ function autodetectNodeStorage(): ComfyStorage | null {
118
+ const get = globalThis.process?.getBuiltinModule
119
+ if (typeof get !== 'function') return null
120
+ const fs = get('node:fs') as NodeFsLike | undefined
121
+ const os = get('node:os') as NodeOsLike | undefined
122
+ if (fs == null || os == null) return null
123
+ return createNodeStorageFrom(fs, os)
124
+ }
125
+
126
+ export function resolveComfyStorage(explicit?: ComfyStorage): ComfyStorage {
127
+ if (explicit != null) return explicit
128
+ if (installedDefault != null) return installedDefault
129
+ const detected = autodetectNodeStorage()
130
+ if (detected != null) {
131
+ installedDefault = detected
132
+ return detected
133
+ }
134
+ throw new Error(
135
+ `no ComfyStorage available — import 'comfy-ts' (node) or 'comfy-ts/web' (browser) before creating ComfyTS, or pass ComfyTS.create({ storage })`,
136
+ )
137
+ }
138
+
139
+ /** the ONE accessor call sites use: the instance's storage when the global
140
+ * exists, the resolved default otherwise (vars constructed before create()) */
141
+ export function getComfyStorage(): ComfyStorage {
142
+ const g = globalThis as { comfyts?: { storage?: ComfyStorage } }
143
+ return g.comfyts?.storage ?? resolveComfyStorage()
144
+ }
@@ -0,0 +1,9 @@
1
+ // the ONLY core-path module allowed to import node:fs statically
2
+ // (architecture item 13) — index.ts installs it; the web graph never sees it
3
+ import * as fs from 'node:fs'
4
+ import * as os from 'node:os'
5
+ import { type ComfyStorage, createNodeStorageFrom } from 'src/storage/ComfyStorage.ts'
6
+
7
+ export function createNodeStorage(): ComfyStorage {
8
+ return createNodeStorageFrom(fs, os)
9
+ }
@@ -24,9 +24,13 @@ export const asRelativePath = (path: string): RelativePath => path as RelativePa
24
24
 
25
25
  // #region Image
26
26
  export type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'
27
- export type ImageSaveFormat = {
28
- format: ConvertibleImageFormat
27
+ /** local disk saving is OPT-IN per run: `save: true` = raw bytes, an object re-encodes/relocates */
28
+ export type SaveOptions = {
29
+ /** 'raw' (default) writes the bytes untouched; an image/* mime re-encodes through sharp */
30
+ format?: ConvertibleImageFormat
31
+ /** local dir under `.comfy-ts/outputs/` (wins over the prompt's own filename_prefix) */
29
32
  prefix?: string
33
+ /** 0..1, re-encode only */
30
34
  quality?: number
31
35
  }
32
36
 
@@ -1,77 +1,19 @@
1
- import fs, { mkdirSync } from 'node:fs'
2
- import https from 'node:https'
3
- import { stdout } from 'node:process'
4
- import { dirname } from 'pathe'
1
+ // fetch-based (node:https replaced 2026-07-31, architecture item 13): the
2
+ // manager registry chain is in the web graph via ComfyRegistry, so this file
3
+ // must stay portable — fetch follows redirects itself, storage owns the write
4
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
5
5
  import type { AbsolutePath } from 'src/types/index.ts'
6
6
 
7
- /** Usage example
8
- * | ;(async () => {
9
- * | try {
10
- * | await downloadFile('https://example.com/file', 'folder/filename')
11
- * | console.log('Download completed successfully')
12
- * | } catch (error) {
13
- * | console.error('Download failed:', error)
14
- * | }
15
- * | })()
16
- * |
17
- */
18
- export function downloadFile(
7
+ export async function downloadFile(
19
8
  //
20
9
  url: string,
21
10
  outputPath: AbsolutePath | string,
22
11
  logPrefix = ' - ',
23
12
  ): Promise<true> {
24
- const baseDir = dirname(outputPath)
25
- mkdirSync(baseDir, { recursive: true })
26
-
27
- return new Promise<true>((resolve, reject) => {
28
- const request = https.get(url, (response) => {
29
- // initial response --------------------------------------------
30
- // Check for redirect
31
- if (response.statusCode === 302 || response.statusCode === 301) {
32
- // Follow the redirect and call downloadFile recursively
33
- const newUrl = response.headers.location!
34
- console.log(`Redirected to ${newUrl}`)
35
- resolve(downloadFile(newUrl, outputPath))
36
- return
37
- }
38
-
39
- if (response.statusCode !== 200) {
40
- reject(`Failed to download file: Status Code ${response.statusCode}`)
41
- return
42
- }
43
-
44
- // progress --------------------------------------------------
45
- const rawLen = response.headers['content-length']
46
- if (rawLen == null) {
47
- console.warn(`download file: progress not available because no content-length header in response.`)
48
- } else {
49
- const totalSize = parseInt(rawLen, 10)
50
- let downloaded = 0
51
- let lastLoggedPercentage = 0
52
-
53
- response.on('data', (chunk) => {
54
- downloaded += chunk.length
55
- const percentage = Math.round((downloaded / totalSize) * 100)
56
- if (percentage >= lastLoggedPercentage + 1) {
57
- // console.log(`${percentage}% downloaded`)
58
- stdout.write(`\r${logPrefix}${percentage}% downloaded`)
59
- lastLoggedPercentage = percentage
60
- }
61
- })
62
- }
63
-
64
- // file stream -------------------------------------------
65
- const fileStream = fs.createWriteStream(outputPath)
66
- response.pipe(fileStream)
67
-
68
- fileStream.on('finish', () => {
69
- console.log(` (DONE)`)
70
- fileStream.close()
71
- resolve(true)
72
- })
73
- })
74
-
75
- request.on('error', (err) => reject(err))
76
- })
13
+ const res = await fetch(url)
14
+ if (!res.ok) throw new Error(`Failed to download ${url}: HTTP ${res.status}`)
15
+ const bytes = new Uint8Array(await res.arrayBuffer())
16
+ getComfyStorage().writeBytes(outputPath, bytes)
17
+ console.log(`${logPrefix}${(bytes.length / 1024).toFixed(0)}kB (DONE)`)
18
+ return true
77
19
  }