comfy-ts 0.2.0 → 0.3.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4128 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9862 -0
  8. package/dist/index.d.ts +9846 -58
  9. package/dist/index.js +4049 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-Io8Xea0L.js +3340 -0
  14. package/dist/run-tui-Io8Xea0L.js.map +1 -0
  15. package/package.json +104 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +51 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  24. package/src/cli/tui/components/OverlayList.tsx +25 -0
  25. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +33 -0
  27. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  28. package/src/cli/tui/components/StatusBar.tsx +165 -0
  29. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  30. package/src/cli/tui/components/TreePanel.tsx +51 -0
  31. package/src/cli/tui/components/TuiApp.tsx +223 -0
  32. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  33. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  34. package/src/cli/tui/keys.ts +20 -0
  35. package/src/cli/tui/protocolImagePainter.ts +59 -0
  36. package/src/cli/tui/run-tui.tsx +73 -0
  37. package/src/cli/tui/state/DraftsSt.ts +273 -0
  38. package/src/cli/tui/state/EditorSt.ts +289 -0
  39. package/src/cli/tui/state/ExecSt.ts +170 -0
  40. package/src/cli/tui/state/HostSt.ts +107 -0
  41. package/src/cli/tui/state/LorasSt.ts +185 -0
  42. package/src/cli/tui/state/PickerSt.ts +112 -0
  43. package/src/cli/tui/state/PreviewSt.ts +138 -0
  44. package/src/cli/tui/state/QueueSt.ts +59 -0
  45. package/src/cli/tui/state/SettingsSt.ts +73 -0
  46. package/src/cli/tui/state/TreeSt.ts +122 -0
  47. package/src/cli/tui/state/TuiSt.ts +169 -0
  48. package/src/cli/tui/state/WorkflowsSt.ts +92 -0
  49. package/src/cli/tui-env.ts +8 -0
  50. package/src/errors/InvalidPromptError.ts +12 -0
  51. package/src/graph/ComfyNode.ts +403 -0
  52. package/src/graph/ComfyNodeID.ts +28 -0
  53. package/src/graph/ComfyNodeOutput.ts +16 -0
  54. package/src/graph/NodeSlotSize.ts +4 -0
  55. package/src/graph/autoValue.ts +17 -0
  56. package/src/host/ComfyHost.ts +646 -0
  57. package/src/host/ComfyInstallType.ts +15 -0
  58. package/src/host/ComfyManager.ts +232 -0
  59. package/src/host/ComfyUploader.ts +110 -0
  60. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  61. package/src/host/Requirements.ts +55 -0
  62. package/src/host/ResilientWebsocket.ts +147 -0
  63. package/src/host/loraManagerApi.ts +98 -0
  64. package/src/image-utils/_getPngMetadata.ts +53 -0
  65. package/src/image-utils/_getWebpMetadata.ts +38 -0
  66. package/src/image-utils/_parseExifData.ts +53 -0
  67. package/src/index.ts +89 -0
  68. package/src/litegraph/LiteGraphGroup.ts +22 -0
  69. package/src/litegraph/LiteGraphJSON.ts +46 -0
  70. package/src/litegraph/LiteGraphLink.ts +23 -0
  71. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  72. package/src/litegraph/LiteGraphNode.ts +69 -0
  73. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  74. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  75. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  76. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  77. package/src/manager/ComfyRegistry.ts +124 -0
  78. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  79. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  80. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  81. package/src/manager/generated/KnownModel_Base.ts +126 -0
  82. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  83. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  84. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  85. package/src/manager/generated/KnownModel_Type.ts +97 -0
  86. package/src/manager/json/alter-list.json +224 -0
  87. package/src/manager/json/custom-node-list.extra.ts +13 -0
  88. package/src/manager/json/custom-node-list.json +21948 -0
  89. package/src/manager/json/extension-node-map.json +31282 -0
  90. package/src/manager/json/github-stats.json +12602 -0
  91. package/src/manager/json/model-list.extra.ts +26 -0
  92. package/src/manager/json/model-list.json +5052 -0
  93. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  94. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  95. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  96. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  97. package/src/manager/script-update-manager.bun.ts +18 -0
  98. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  99. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  100. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  101. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  102. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  103. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  104. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  105. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  106. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  107. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  108. package/src/runner/ComfyExecution.ts +301 -0
  109. package/src/runner/ComfyExecutionStatus.ts +2 -0
  110. package/src/runner/ComfyWorkflow.ts +395 -0
  111. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  112. package/src/runner/ComfyWsApi.ts +159 -0
  113. package/src/runner/MediaImage.ts +262 -0
  114. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  115. package/src/sdk-generator/ComfySchema.ts +369 -0
  116. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  117. package/src/sdk-generator/Primitives.ts +76 -0
  118. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  119. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  120. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  121. package/src/sdk-generator/comfy-api-json.ts +16 -0
  122. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  123. package/src/sdk-generator/comfyui-types.ts +56 -0
  124. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  125. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  126. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  127. package/src/ssh-host-manager/ssh-manager.ts +129 -0
  128. package/src/state.ts +136 -0
  129. package/src/types/comfy-sdk.ts +106 -0
  130. package/src/types/index.ts +55 -0
  131. package/src/utils/CodeBuffer.ts +61 -0
  132. package/src/utils/ComfyColors.ts +38 -0
  133. package/src/utils/ansi.ts +26 -0
  134. package/src/utils/ansiImage.ts +36 -0
  135. package/src/utils/bang.ts +39 -0
  136. package/src/utils/deepCopyNaive.ts +1 -0
  137. package/src/utils/downloadFile.ts +77 -0
  138. package/src/utils/escapeJSKey.ts +32 -0
  139. package/src/utils/exhaust.ts +4 -0
  140. package/src/utils/extractErrorMessage.ts +11 -0
  141. package/src/utils/fuzzyMatch.ts +8 -0
  142. package/src/utils/githubRegexes.ts +2 -0
  143. package/src/utils/hashArrayBuffer.ts +6 -0
  144. package/src/utils/log.ts +9 -0
  145. package/src/utils/loraTag.ts +10 -0
  146. package/src/utils/printArkResultInConsole.ts +16 -0
  147. package/src/utils/softValidate.ts +8 -0
  148. package/src/utils/stringifyReadable.ts +32 -0
  149. package/src/utils/toposort.ts +59 -0
  150. package/src/utils/tryExtracting.ts +41 -0
  151. package/src/utils/writeFile.ts +16 -0
  152. package/src/vars/ComfyVars.ts +531 -0
  153. package/src/vars/DefinedWorkflow.ts +112 -0
  154. package/src/vars/loraKeywords.ts +56 -0
  155. package/dist/index.d.mts +0 -74
  156. package/dist/index.mjs +0 -3
  157. package/dist/index.mjs.map +0 -1
  158. package/readme.md +0 -40
@@ -0,0 +1,16 @@
1
+ import { type } from 'arktype'
2
+
3
+ export type ComfyManagerPluginContentMetadata = typeof ComfyManagerPluginContentMetadata_ark.infer
4
+ export const ComfyManagerPluginContentMetadata_ark = type({
5
+ // optional because on damn validation on comfy manager! 😬
6
+ // should have been always present
7
+ title_aux: type.string.or(type.null), // "Jovimetrix Composition Nodes",
8
+
9
+ // optional
10
+ 'author?': 'string', // "amorano",
11
+ 'nickname?': 'string', // "Comfy Deploy",
12
+ 'description?': 'string', // "Webcams, GLSL shader, Media Streaming, Tick animation, Image manipulation,",
13
+ 'nodename_pattern?': 'string', // " \\(jov\\)$",
14
+ 'title?': 'string', // "Jovimetrix",
15
+ 'preemptions?': 'string[]', // ❓
16
+ })
@@ -0,0 +1,8 @@
1
+ import { type } from 'arktype'
2
+ import type { Tagged } from 'src/types/index.ts'
3
+
4
+ export type ComfyManagerPluginContentNodeName = Tagged<string, 'ComfyManagerPluginContentNodeName'>
5
+ export const ComfyManagerPluginContentNodeName_ark = type.string.as<ComfyManagerPluginContentNodeName>()
6
+
7
+ export type ComfyManagerPluginID = string
8
+ export const ComfyManagerPluginID_ark = type('string')
@@ -0,0 +1,50 @@
1
+ import { type } from 'arktype'
2
+ import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
3
+ import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
4
+ import type { ComfyManagerPluginID } from 'src/manager/types/ComfyManagerPluginEnums.ts'
5
+
6
+ export type ComfyManagerPluginInfo = typeof ComfyManagerPluginInfo_ark.infer
7
+ export const ComfyManagerPluginInfo_ark = type({
8
+ // required
9
+ author: 'string', // "Dr.Lt.Data",
10
+ title: type.string.as<KnownComfyPluginTitle>(), // "ComfyUI-Manager",
11
+ reference: 'string', // "https://github.com/ltdrdata/ComfyUI-Manager",
12
+ files: type.string.as<KnownComfyPluginURL>().array(), // ["https://github.com/ltdrdata/ComfyUI-Manager"],
13
+ install_type: 'string', // "git-clone",
14
+ description: 'string', // "ComfyUI-Manager itself is also a custom node."
15
+
16
+ // optional, but shouldn't, so they'll pre-emptively auto-fixed before validation
17
+ id: type.string.as<ComfyManagerPluginID>(), // on 2024-11-09, 579 fields are missing this
18
+
19
+ // optional
20
+ 'preemptions?': 'string[]',
21
+ 'pip?': 'string[]',
22
+ 'nodename_pattern?': 'string',
23
+ 'apt_dependency?': 'string[]',
24
+ 'js_path?': 'string',
25
+ 'version?': 'string',
26
+
27
+ // optional ?
28
+ // (probably not really well specified, sicne some of those only appear one or two times)
29
+ 'tags?': 'string[]', // 🔶 as of 2024-11-09, this shows only one time
30
+ })
31
+
32
+ // export type ComfyManagerPluginInfo = {
33
+ // // required
34
+ // author: string // "Dr.Lt.Data",
35
+ // title: KnownComfyPluginTitle // "ComfyUI-Manager",
36
+ // reference: string // "https://github.com/ltdrdata/ComfyUI-Manager",
37
+ // files: KnownComfyPluginURL[] // ["https://github.com/ltdrdata/ComfyUI-Manager"],
38
+ // install_type: string // "git-clone",
39
+ // description: string // "ComfyUI-Manager itself is also a custom node."
40
+
41
+ // // optional, but shouldn't
42
+ // // optional
43
+ // id?: ComfyManagerPluginID // Added in 2024-??
44
+ // preemptions?: string[] // ❓
45
+ // pip?: string[] // [ "ultralytics" ],
46
+ // nodename_pattern?: string // "Inspire$",
47
+ // apt_dependency?: string[] // [ "rustc", "cargo" ],
48
+ // js_path?: string // "strimmlarn",
49
+ // version?: string
50
+ // }
@@ -0,0 +1,301 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'pathe'
3
+ import sharp, { type FormatEnum } from 'sharp'
4
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
+ import { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'
6
+ import type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
7
+ import { asAbsolutePath, type ImageSaveFormat, type Maybe } from 'src/types/index.ts'
8
+ import { exhaust } from 'src/utils/exhaust.ts'
9
+ import type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
10
+ import type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport } from 'src/runner/ComfyWorkflow.ts'
11
+
12
+ import type {
13
+ ComfyImageInfo,
14
+ PromptID,
15
+ PromptRelated_WsMsg,
16
+ WsMsgExecuted,
17
+ WsMsgExecuting,
18
+ WsMsgExecutionError,
19
+ WsMsgExecutionSuccess,
20
+ } from 'src/runner/ComfyWsApi.ts'
21
+ import { MediaImage } from 'src/runner/MediaImage.ts'
22
+
23
+ export type ComfyExecutionData = {
24
+ id: PromptID
25
+ graphID: ComfyWorkflowID
26
+ executed: boolean
27
+ error?: WsMsgExecutionError | null
28
+ status?: ComfyExecutionStatus | null
29
+ }
30
+
31
+ export type ExecutionProgress = ProgressReport & {
32
+ promptId: PromptID
33
+ nodeName: string | null
34
+ elapsedMs: number
35
+ }
36
+
37
+ export class ComfyExecution {
38
+ get host(): ComfyHost {
39
+ return this.workflow.host
40
+ }
41
+
42
+ constructor(
43
+ public workflow: ComfyWorkflow,
44
+ public data: ComfyExecutionData,
45
+ init: {
46
+ snapshot?: ExecutionSnapshot
47
+ saveFormat?: Maybe<ImageSaveFormat>
48
+ onProgress?: Maybe<(p: ExecutionProgress) => void>
49
+ logProgress?: boolean
50
+ } = {},
51
+ ) {
52
+ // settings FIRST: onCreate flushes buffered ws messages whose handlers read them
53
+ this.snapshot = init.snapshot ?? null
54
+ this.saveFormat = init.saveFormat ?? null
55
+ this.onProgress = init.onProgress ?? null
56
+ this.logProgress = init.logProgress ?? false
57
+ // register with the host so websocket messages route here,
58
+ // then flush messages that arrived before we existed
59
+ this.host.executions.set(data.id, this)
60
+ this.onCreate()
61
+ }
62
+
63
+ // post-process
64
+ saveFormat: Maybe<ImageSaveFormat> = null
65
+
66
+ /** exactly what was sent to the host, frozen at send time (replayable) */
67
+ snapshot: Maybe<ExecutionSnapshot> = null
68
+
69
+ // ---- progress ----------------------------------------------------------
70
+ /** called on every progress-relevant websocket message */
71
+ onProgress: Maybe<(p: ExecutionProgress) => void> = null
72
+ /** render a live single-line progress report to the console */
73
+ logProgress: boolean = false
74
+ readonly startedAt: number = Date.now()
75
+
76
+ get progress(): ExecutionProgress {
77
+ const report = this.progressGlobal
78
+ return {
79
+ ...report,
80
+ promptId: this.data.id,
81
+ nodeName: this.workflow.currentExecutingNode?.$schema.nameInComfy ?? null,
82
+ elapsedMs: Date.now() - this.startedAt,
83
+ }
84
+ }
85
+
86
+ private _lastLoggedLine: string = ''
87
+ private emitProgress(): void {
88
+ const p = this.progress
89
+ this.onProgress?.(p)
90
+ if (!this.logProgress) return
91
+ const width = 12
92
+ const filled = Math.round((p.percent / 100) * width)
93
+ const bar = '█'.repeat(filled) + '░'.repeat(width - filled)
94
+ const node = p.nodeName ? ` · ${p.nodeName}` : ''
95
+ const line = `▶ [${bar}] ${p.percent.toFixed(0).padStart(3)}%${node} · ${(p.elapsedMs / 1000).toFixed(0)}s`
96
+ if (line === this._lastLoggedLine) return
97
+ this._lastLoggedLine = line
98
+ if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`)
99
+ else console.log(line)
100
+ }
101
+
102
+ private finishProgressLine(): void {
103
+ if (!this.logProgress) return
104
+ const p = this.progress
105
+ const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${this.images.length} image(s)`
106
+ if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
107
+ else console.log(line)
108
+ }
109
+
110
+ // promise handle so that we can wait for this execution to finish.
111
+ // resolves in BOTH success and failure — inspect `status` / `data.error`.
112
+ private _resolve!: (value: this) => void
113
+ done: Promise<this> = new Promise((resolve) => {
114
+ this._resolve = resolve
115
+ })
116
+
117
+ log(...args: unknown[]): void {
118
+ console.log(`[ComfyExecution#${this.data.id}]`, ...args)
119
+ }
120
+
121
+ onCreate(): void {
122
+ const data: ComfyExecutionData = this.data
123
+ const pending = this.host._pendingMsgs.get(data.id)
124
+ if (pending == null) return
125
+ this.log(`🟢 onCreate: ${pending.length} pending messages`)
126
+ this.host._pendingMsgs.delete(data.id) // buffered once, never again
127
+ for (const msg of pending) this.onPromptRelatedMessage(msg)
128
+ }
129
+
130
+ get progressGlobal(): ProgressReport {
131
+ if (this.data.status === 'Success') return { countDone: 1, countTotal: 1, isDone: true, percent: 100 }
132
+ return this.workflow.progressGlobal
133
+ }
134
+
135
+ get status(): 'New' | 'Scheduled' | 'Running' | 'Success' | 'Failure' {
136
+ return this.data.status ?? 'New'
137
+ }
138
+
139
+ onPromptRelatedMessage = (msg: PromptRelated_WsMsg): void => {
140
+ const graph = this.workflow
141
+ if (msg.type === 'execution_start') return
142
+ else if (msg.type === 'execution_cached') graph.onExecutionCached(msg)
143
+ else if (msg.type === 'executing') this.onExecuting(msg)
144
+ else if (msg.type === 'progress') graph.onProgress(msg)
145
+ else if (msg.type === 'progress_state') {
146
+ // per-node progress map; global progress is derived from the msgs above
147
+ } else if (msg.type === 'executed') this.onExecuted(msg)
148
+ else if (msg.type === 'execution_error') return void this.onError(msg)
149
+ else if (msg.type === 'execution_success') return void this.onExecutionSuccess(msg)
150
+ else {
151
+ console.log(`🔴 UNEXPECTED MESSAGE:`, msg)
152
+ return exhaust(msg)
153
+ }
154
+ this.emitProgress()
155
+ }
156
+
157
+ /** update pointer to the currently executing node */
158
+ private onExecuting = (msg: WsMsgExecuting): void => {
159
+ this.workflow.onExecuting(msg)
160
+ }
161
+
162
+ private onExecutionSuccess = async (_msg: WsMsgExecutionSuccess): Promise<void> => {
163
+ await Promise.all(this.pendingPromises)
164
+ return this._finish({ status: 'Success' })
165
+ }
166
+
167
+ private onError = async (msg: WsMsgExecutionError): Promise<void> => {
168
+ console.error('❌ Execution error:')
169
+ console.error(msg)
170
+ return this._finish({ status: 'Failure', error: msg })
171
+ }
172
+
173
+ /** update execution list */
174
+ private onExecuted = (msg: WsMsgExecuted): void => {
175
+ const promptNodeID = msg.data.node
176
+ const images = msg.data.output?.images
177
+ if (images) {
178
+ for (const img of images) {
179
+ // guard every retrieval: one failed download must not hang `done`
180
+ this.pendingPromises.push(
181
+ this.retrieveImage(img, promptNodeID).catch((e: unknown) => {
182
+ console.error(`🔴 failed to retrieve ${img.filename}:`, e)
183
+ this.imageErrors.push({ image: img, error: e })
184
+ }),
185
+ )
186
+ }
187
+ }
188
+ }
189
+ private pendingPromises: Promise<void>[] = []
190
+
191
+ /** image retrievals that failed (their images are missing from `images`) */
192
+ imageErrors: { image: ComfyImageInfo; error: unknown }[] = []
193
+
194
+ retrieveImage = async (
195
+ //
196
+ comfyImageInfo: ComfyImageInfo,
197
+ promptNodeID: ComfyNodeId,
198
+ ): Promise<void> => {
199
+ // retrieve the node
200
+ const promptNode = this.workflow.data.apiJson?.[promptNodeID]
201
+ const promptMeta = this.workflow.data.metadata?.[promptNodeID]
202
+ if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`)
203
+
204
+ // get image url from ComfyUI
205
+ const serverURL = this.host.getServerHostHTTP()
206
+ const imgUrl = serverURL + '/view?' + new URLSearchParams(comfyImageInfo).toString()
207
+
208
+ // target path on disk
209
+ const sf = this.saveFormat
210
+ let absPath: string = comfyts.resolveFromOutput(
211
+ join(sf?.prefix ?? comfyImageInfo.subfolder, comfyImageInfo.filename),
212
+ )
213
+ if (sf?.format && sf.format !== 'raw') {
214
+ const extension = sf.format.split('/')[1]
215
+ absPath += '.' + extension
216
+ }
217
+ const dir = dirname(absPath)
218
+ mkdirSync(dir, { recursive: true })
219
+
220
+ // ref
221
+ let img: MediaImage
222
+
223
+ // RE-ENCODE (COMPRESSED)
224
+ if (sf && sf.format !== 'raw') {
225
+ const response = await fetch(imgUrl, { headers: { 'Content-Type': 'image/png' }, method: 'GET' })
226
+ const buff = await response.arrayBuffer()
227
+ let textChunk = {}
228
+ try {
229
+ const res = getPngMetadataFromUint8Array(new Uint8Array(buff))
230
+ if (res.success) textChunk = res.value
231
+ } catch {}
232
+
233
+ const format = ((): keyof FormatEnum => {
234
+ if (sf.format === 'image/jpeg') return 'jpeg'
235
+ if (sf.format === 'image/png') return 'png'
236
+ if (sf.format === 'image/webp') return 'webp'
237
+ return 'png'
238
+ })()
239
+
240
+ await sharp(buff)
241
+ .withMetadata()
242
+ .withExif({ IFD0: textChunk })
243
+ // sharp expect quality between 1 and 100
244
+ .toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : undefined)
245
+ .toFile(absPath)
246
+
247
+ img = new MediaImage({
248
+ path: asAbsolutePath(absPath),
249
+ execution: this,
250
+ promptNodeID: promptNodeID,
251
+ comfyUIInfos: {
252
+ comfyImageInfo: comfyImageInfo,
253
+ comfyHostHttpURL: this.host.getServerHostHTTP(),
254
+ },
255
+ })
256
+ }
257
+
258
+ // SAVE RAW ------------------------------------------------------------------------------------------
259
+ else {
260
+ const response = await fetch(imgUrl, { headers: { 'Content-Type': 'image/png' }, method: 'GET' })
261
+ const buff = await response.arrayBuffer()
262
+ const uint8arr = new Uint8Array(buff)
263
+ writeFileSync(absPath, uint8arr)
264
+ img = new MediaImage({
265
+ path: asAbsolutePath(absPath),
266
+ buffer: uint8arr,
267
+ execution: this,
268
+ promptNodeID: promptNodeID,
269
+ comfyUIInfos: {
270
+ comfyImageInfo: comfyImageInfo,
271
+ comfyHostHttpURL: this.host.getServerHostHTTP(),
272
+ },
273
+ })
274
+ }
275
+
276
+ // accumulate outputs on the prompt; tags from node metadata ride along
277
+ if (promptMeta?.tag) img.tags.push(promptMeta.tag)
278
+ if (promptMeta?.tags) img.tags.push(...promptMeta.tags)
279
+ this.images.push(img)
280
+ }
281
+
282
+ /** images retrieved for this execution, in arrival order (final once `done` resolves) */
283
+ images: MediaImage[] = []
284
+
285
+ update(data: Partial<ComfyExecutionData>): void {
286
+ Object.assign(this.data, data)
287
+ }
288
+
289
+ private alreadyDone: boolean = false
290
+ private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error'>): Promise<void> => {
291
+ if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`)
292
+ this.alreadyDone = true
293
+ this.update({ ...p, executed: true })
294
+ await Promise.all(this.pendingPromises)
295
+ // finished executions receive no further messages — free the routing maps
296
+ this.host.executions.delete(this.data.id)
297
+ this.host._pendingMsgs.delete(this.data.id)
298
+ this.finishProgressLine()
299
+ this._resolve(this)
300
+ }
301
+ }
@@ -0,0 +1,2 @@
1
+ // biome-ignore format: misc
2
+ export type ComfyExecutionStatus = 'New' | 'Scheduled' | 'Running' | 'Success' | 'Failure'