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,169 @@
1
+ import { makeAutoObservable, observable, runInAction } from 'mobx'
2
+ import type { SeedVar, ToggleVar, AnyVar } from 'src/vars/ComfyVars.ts'
3
+ import { DraftsSt } from 'src/cli/tui/state/DraftsSt.ts'
4
+ import { EditorSt } from 'src/cli/tui/state/EditorSt.ts'
5
+ import { ExecSt } from 'src/cli/tui/state/ExecSt.ts'
6
+ import { HostSt } from 'src/cli/tui/state/HostSt.ts'
7
+ import { LorasSt } from 'src/cli/tui/state/LorasSt.ts'
8
+ import { PickerSt } from 'src/cli/tui/state/PickerSt.ts'
9
+ import { PreviewSt } from 'src/cli/tui/state/PreviewSt.ts'
10
+ import { QueueSt } from 'src/cli/tui/state/QueueSt.ts'
11
+ import { SettingsSt } from 'src/cli/tui/state/SettingsSt.ts'
12
+ import { TreeSt } from 'src/cli/tui/state/TreeSt.ts'
13
+ import { WorkflowsSt } from 'src/cli/tui/state/WorkflowsSt.ts'
14
+ import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
15
+
16
+ // nav = vars list · tree = left workflow panel · host = host stats/actions ·
17
+ // edit = inline single-line (numbers + custom prompts) · overlay-* = modal popups
18
+ export type TuiMode =
19
+ | 'nav'
20
+ | 'tree'
21
+ | 'host'
22
+ | 'edit'
23
+ | 'overlay-text'
24
+ | 'overlay-choice'
25
+ | 'overlay-size'
26
+ | 'overlay-loras'
27
+ | 'overlay-drafts'
28
+
29
+ /**
30
+ * ROOT of the TUI state tree (one instance per run). Children are service
31
+ * classes with an `st` backref; components are stateless views over this.
32
+ */
33
+ export class TuiSt {
34
+ wf: DefinedWorkflow
35
+ mode: TuiMode = 'nav'
36
+ selIx: number = 0
37
+
38
+ editor: EditorSt
39
+ picker: PickerSt
40
+ loras: LorasSt
41
+ workflows: WorkflowsSt
42
+ tree: TreeSt
43
+ drafts: DraftsSt
44
+ exec: ExecSt
45
+ preview: PreviewSt
46
+ host: HostSt
47
+ queue: QueueSt
48
+ settings: SettingsSt
49
+
50
+ /** owned cleanups (reactions, listeners) — flushed by dispose() */
51
+ disposers: (() => void)[] = []
52
+ onExit: () => void = () => {}
53
+
54
+ constructor(wf: DefinedWorkflow, opts: { workflowFiles?: string[]; currentFile?: string } = {}) {
55
+ this.wf = wf
56
+ // wf: observable.ref so switching workflows re-renders without proxying
57
+ // the foreign object; children manage their own observability
58
+ makeAutoObservable(this, {
59
+ wf: observable.ref,
60
+ onExit: false,
61
+ editor: false,
62
+ picker: false,
63
+ loras: false,
64
+ workflows: false,
65
+ tree: false,
66
+ drafts: false,
67
+ exec: false,
68
+ preview: false,
69
+ host: false,
70
+ queue: false,
71
+ settings: false,
72
+ })
73
+ this.settings = new SettingsSt(this)
74
+ this.editor = new EditorSt(this)
75
+ this.picker = new PickerSt(this)
76
+ this.loras = new LorasSt(this)
77
+ this.workflows = new WorkflowsSt(this, opts.workflowFiles ?? [], opts.currentFile ?? null)
78
+ this.tree = new TreeSt(this)
79
+ this.drafts = new DraftsSt(this)
80
+ this.exec = new ExecSt(this)
81
+ this.preview = new PreviewSt(this)
82
+ this.host = new HostSt(this)
83
+ this.queue = new QueueSt(this)
84
+ // the TUI is ALWAYS in a draft from the very first frame: the one this
85
+ // workflow was last in (settings), else 'default'; the current workflow
86
+ // starts unfolded so its drafts are visible in the tree
87
+ this.drafts.activateRemembered()
88
+ if (opts.currentFile != null) this.tree.expandedFiles.add(opts.currentFile)
89
+ // full-terminal layout: track resizes (SIGWINCH surfaces as stdout resize)
90
+ const onResize = (): void => {
91
+ runInAction(() => {
92
+ this.termCols = process.stdout.columns ?? 80
93
+ this.termRows = (process.stdout.rows ?? 24) - 1
94
+ })
95
+ }
96
+ process.stdout.on?.('resize', onResize)
97
+ this.disposers.push(() => process.stdout.off?.('resize', onResize))
98
+ }
99
+
100
+ dispose(): void {
101
+ for (const d of this.disposers.splice(0)) d()
102
+ this.workflows.disconnectAllHosts()
103
+ }
104
+
105
+ // ---- terminal geometry (drives overlays + preview panel sizing) ----
106
+ // rows minus 1: vscode's terminal clips the first row when a frame uses them all
107
+ termCols: number = process.stdout.columns ?? 80
108
+ termRows: number = (process.stdout.rows ?? 24) - 1
109
+
110
+ /** rows available inside a modal overlay list */
111
+ get overlayLines(): number {
112
+ return Math.max(8, this.termRows - 12)
113
+ }
114
+
115
+ /** left tree panel width: longest row (workflow or indented draft), clamped */
116
+ get treeWidth(): number {
117
+ const longest = Math.max(
118
+ 8,
119
+ ...this.tree.rows.map((r) => (r.kind === 'workflow' ? r.name.length : r.draft.length + 3)),
120
+ )
121
+ return Math.min(32, longest + 7)
122
+ }
123
+
124
+ // ---- vars navigation ----
125
+ get entries(): [string, AnyVar][] {
126
+ return this.wf.entries()
127
+ }
128
+
129
+ get selected(): [string, AnyVar] | undefined {
130
+ return this.entries[this.selIx]
131
+ }
132
+
133
+ moveSel(delta: number): void {
134
+ const len = this.entries.length
135
+ if (len === 0) return
136
+ this.selIx = (this.selIx + delta + len) % len
137
+ }
138
+
139
+ // kind-discriminated narrowing casts below are sanctioned (agent/coding.md):
140
+ // ComfyVar<T> value-invariance blocks a clean union, `kind` is the tag.
141
+
142
+ /** enter/space on a var: toggle, open an overlay, or inline-edit */
143
+ activate(): void {
144
+ const sel = this.selected?.[1]
145
+ if (sel == null) return
146
+ if (sel.kind === 'toggle') (sel as ToggleVar).toggle()
147
+ else if (sel.kind === 'text') this.editor.beginMultiline()
148
+ else if (sel.kind === 'choice') this.picker.beginChoice()
149
+ else if (sel.kind === 'size') this.picker.beginSize()
150
+ else if (sel.kind === 'loras') this.loras.begin()
151
+ else this.editor.beginInline() // int / float / seed: type the number
152
+ }
153
+
154
+ /** kind-specific nav keys (documented in the keybar): seed `+`/`-`/`=`/`?` mode, `*` reroll */
155
+ navKey(input: string): boolean {
156
+ const sel = this.selected?.[1]
157
+ if (sel?.kind === 'seed') {
158
+ if (input === '+' || input === '-' || input === '=' || input === '?') {
159
+ ;(sel as SeedVar).setMode(input)
160
+ return true
161
+ }
162
+ if (input === '*') {
163
+ ;(sel as SeedVar).randomize()
164
+ return true
165
+ }
166
+ }
167
+ return false
168
+ }
169
+ }
@@ -0,0 +1,92 @@
1
+ import { pathToFileURL } from 'node:url'
2
+ import { makeAutoObservable, runInAction } from 'mobx'
3
+ import { basename, resolve } from 'pathe'
4
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
+ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
6
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
7
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
8
+
9
+ /** workflow-module data layer: scanned files, module loading, opened-host set (TreeSt is the UI over it) */
10
+ export class WorkflowsSt {
11
+ constructor(
12
+ private st: TuiSt,
13
+ public files: string[],
14
+ currentPath: string | null = null,
15
+ ) {
16
+ this.currentPath = currentPath
17
+ makeAutoObservable<WorkflowsSt, 'st'>(this, { st: false })
18
+ }
19
+
20
+ /** path of the currently loaded workflow module (display + selection) */
21
+ currentPath: string | null
22
+ loading: boolean = false
23
+
24
+ /**
25
+ * every host seen across switches. Modules are import-cached, so a
26
+ * switched-away host must stay connected (switching back reuses it) — exit
27
+ * disconnects them all.
28
+ */
29
+ loadedHosts: Set<ComfyHost> = new Set()
30
+
31
+ disconnectAllHosts(): void {
32
+ this.loadedHosts.add(this.st.wf.host)
33
+ for (const host of this.loadedHosts) host.disconnect()
34
+ }
35
+
36
+ /** load a workflow module; `draft` null => the remembered draft, else that exact draft */
37
+ async commit(path: string, draft: string | null = null): Promise<void> {
38
+ if (path === this.currentPath) {
39
+ // same module: only the draft changes
40
+ if (this.loading) return
41
+ if (draft == null) this.st.drafts.activateRemembered()
42
+ else this.st.drafts.activate(draft)
43
+ this.st.mode = 'nav'
44
+ return
45
+ }
46
+ return this.load(path, draft, false)
47
+ }
48
+
49
+ /** cache-busted re-import of the CURRENT module: defineWorkflow re-executes,
50
+ * so dynamic var option lists (v.loras over getLoras()…) pick up fresh schema values */
51
+ async reload(draft: string): Promise<void> {
52
+ const path = this.currentPath
53
+ if (path == null) return
54
+ return this.load(path, draft, true)
55
+ }
56
+
57
+ private async load(path: string, draft: string | null, bustCache: boolean): Promise<void> {
58
+ if (this.loading) return
59
+ runInAction(() => {
60
+ this.loading = true
61
+ })
62
+ try {
63
+ const url = pathToFileURL(resolve(path)).href + (bustCache ? `?v=${Date.now()}` : '')
64
+ const mod: Record<string, unknown> = await import(url)
65
+ const wf = findDefinedWorkflow(mod)
66
+ if (wf == null) throw new Error(`${path} exports no DefinedWorkflow`)
67
+ runInAction(() => {
68
+ this.loadedHosts.add(this.st.wf.host)
69
+ this.loadedHosts.add(wf.host)
70
+ this.st.wf = wf
71
+ this.st.queue.attach(wf.host)
72
+ this.currentPath = path
73
+ this.st.selIx = 0
74
+ this.st.mode = 'nav'
75
+ this.st.exec.resetForWorkflow(`${basename(path)}`)
76
+ // after the reset: a bad draft json must stay visible as exec.error
77
+ if (draft == null) this.st.drafts.activateRemembered()
78
+ else this.st.drafts.activate(draft)
79
+ this.st.preview.reset()
80
+ })
81
+ } catch (e) {
82
+ runInAction(() => {
83
+ this.st.mode = 'nav'
84
+ this.st.exec.error = extractErrorMessage(e)
85
+ })
86
+ } finally {
87
+ runInAction(() => {
88
+ this.loading = false
89
+ })
90
+ }
91
+ }
92
+ }
@@ -0,0 +1,8 @@
1
+ // contract between the TUI and workflow modules: the TUI sets this env var
2
+ // before importing a module; example files also use `import.meta.main` to
3
+ // only self-run when executed directly.
4
+ export const COMFY_TS_TUI_ENV = 'COMFY_TS_TUI'
5
+
6
+ export function isTuiActive(): boolean {
7
+ return process.env[COMFY_TS_TUI_ENV] === '1'
8
+ }
@@ -0,0 +1,12 @@
1
+ import type { ExecutionSnapshot } from 'src/runner/ComfyWorkflow.ts'
2
+
3
+ export class InvalidPromptError extends Error {
4
+ constructor(
5
+ public override message: string,
6
+ /** exactly what was sent to the host when the error happened */
7
+ public snapshot: ExecutionSnapshot,
8
+ public details: unknown,
9
+ ) {
10
+ super(message)
11
+ }
12
+ }
@@ -0,0 +1,403 @@
1
+ import type { ComfyWorkflow, ProgressReport } from 'src/runner/ComfyWorkflow.ts'
2
+ import type { NodeProgress } from 'src/runner/ComfyWsApi.ts'
3
+ import type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
4
+ import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
5
+ import type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'
6
+ import { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'
7
+ import type { Maybe } from 'src/types/index.ts'
8
+ import { comfyColors } from 'src/utils/ComfyColors.ts'
9
+ import { auto_ } from 'src/graph/autoValue.ts'
10
+ import type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
11
+ import { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
12
+ import { NodeSlotSize, NodeTitleHeight, nodeLineHeight } from 'src/graph/NodeSlotSize.ts'
13
+
14
+ type NodeExecutionStatus = 'executing' | 'done' | 'error' | 'waiting' | 'cached' | null
15
+
16
+ export type NodePort = {
17
+ id: string
18
+ label: string
19
+ width: number
20
+ height: number
21
+ type: string
22
+ x: number
23
+ y: number
24
+ toNode?: ComfyNode<object, object> | undefined
25
+ fromNode?: ComfyNode<object, object> | undefined
26
+ }
27
+
28
+ export type ComfyNodeUID = string
29
+
30
+ /** ComfyNode
31
+ * - correspond to a signal in the graph
32
+ * - belongs to a script
33
+ */
34
+ export class ComfyNode<
35
+ //
36
+ ComfyNode_input extends object = object,
37
+ ComfyNode_output extends object = object,
38
+ > {
39
+ storeAs(storeName: string): this {
40
+ this.meta.storeAs = storeName
41
+ return this
42
+ }
43
+
44
+ tag(tagName: string): this {
45
+ this.addTag(tagName)
46
+ return this
47
+ }
48
+
49
+ addTag(tag: string): this {
50
+ if (this.meta.tags == null) this.meta.tags = [tag]
51
+ else this.meta.tags.push(tag)
52
+ return this
53
+ }
54
+ // ---------------------------------------
55
+
56
+ /** reported though websocket by ComfyUI */
57
+ status: NodeExecutionStatus = null
58
+
59
+ /** last raw progress message reported by comfy */
60
+ progress: NodeProgress | null = null
61
+
62
+ /**
63
+ * updated on websocket progress report from the progress property just above
64
+ * between [0, 1]
65
+ * */
66
+ progressRatio: number = 0
67
+
68
+ get progressReport(): ProgressReport {
69
+ const percent = this.status === 'done' ? 100 : this.progressRatio * 100
70
+ const isDone = this.status === 'done'
71
+ return { percent, isDone, countDone: this.progressRatio * 100, countTotal: 100 }
72
+ }
73
+
74
+ $schema: ComfyNodeSchema
75
+ updatedAt: number = Date.now()
76
+ json: ComfyApiNodeJson
77
+
78
+ get isExecuting(): boolean {
79
+ return this.status === 'executing'
80
+ }
81
+
82
+ disabled: boolean = false
83
+
84
+ disable(): void {
85
+ this.disabled = true
86
+ }
87
+
88
+ get inputs(): ComfyNode_input {
89
+ // sanctioned cast (agent/coding.md): runtime graph json <-> generated
90
+ // static face; both derive from the same object_info
91
+ return this.json.inputs as ComfyNode_input
92
+ }
93
+
94
+ /** update a node */
95
+ set(p: Partial<ComfyNode_input>): this {
96
+ for (const [key, value] of Object.entries(p)) {
97
+ const next = this.serializeValue(key, value)
98
+ const prev = this.json.inputs[key]
99
+ if (next === prev) continue
100
+ this.json.inputs[key] = next as any // 🔴
101
+ }
102
+ return this
103
+ // 🔴 wrong resonsibility
104
+ // console.log('CHANGES', changes)
105
+ }
106
+
107
+ get color(): string {
108
+ return comfyColors[this.$schema.category] ?? '#aaa'
109
+ }
110
+
111
+ uidNumber: number
112
+ $outputs: ComfyNodeOutput<string>[] = []
113
+ outputs: ComfyNode_output
114
+ uidPrefixed: string
115
+
116
+ constructor(
117
+ public graph: ComfyWorkflow,
118
+ public uid: ComfyNodeUID, // = graph.getUID(),
119
+ jsonExt: ComfyApiNodeJson,
120
+ public meta: ComfyNodeMetadata = {},
121
+ ) {
122
+ // strictly-numeric uids keep uid === uidNumber (litegraph export must agree
123
+ // with prompt keys); anything else gets the next free number ('12abc' must
124
+ // NOT partial-parse to 12 — that collides with node '12')
125
+ const parsedUid = /^\d+$/.test(uid) ? Number(uid) : Number.NaN
126
+ this.uidNumber = Number.isNaN(parsedUid) ? this.graph._uidNumber++ : parsedUid
127
+ if (this.uidNumber >= this.graph._uidNumber) this.graph._uidNumber = this.uidNumber + 1
128
+ if (jsonExt == null) throw new Error('invariant violation: jsonExt is null')
129
+ // this.json = graph.data.apiJson[uid]
130
+ // if (this.json == null) graph.data.apiJson = {}
131
+ // console.log('CONSTRUCTING', xxx.class_type, uid)
132
+
133
+ // this.uidNumber = parseInt(uid) // 🔴 ugly
134
+ const exactSchema = graph.schema.nodesByNameInComfy[jsonExt.class_type]
135
+ if (exactSchema == null) {
136
+ // loud fallback: imported json referencing a node this host doesn't have
137
+ graph.recordProblem(
138
+ `unknown node type "${jsonExt.class_type}" — schema fallback to ${ComfyDefaultNodeWhenUnknown_Name}; install the missing custom node on the host`,
139
+ )
140
+ }
141
+ this.$schema = exactSchema ?? graph.schema.nodesByNameInComfy[ComfyDefaultNodeWhenUnknown_Name]!
142
+
143
+ if (this.$schema == null) {
144
+ console.log(`❌ available nodes:`, Object.keys(graph.schema.nodesByNameInComfy).join(','))
145
+ throw new Error(`❌ no schema found for node "${jsonExt.class_type}"`)
146
+ // throw new Error('')
147
+ }
148
+ this.uidPrefixed = `${this.$schema.nodeKey}_${this.uidNumber}`
149
+ let ix = 0
150
+
151
+ // 🔶 1 this declare the json locally,
152
+ // but Node are not live instances, they're local subinstances to a LiveGraph
153
+ this.json = this._convertPromptExtToPrompt(jsonExt)
154
+ // 🔶 2 so we need to ensure the json is properly synced with the LiveGraph data
155
+ // register node ensure this
156
+ this.graph.registerNode(this)
157
+
158
+ // dynamically add properties for every outputs
159
+ const outputs: { [key: string]: any } = {}
160
+ for (const x of this.$schema.outputs) {
161
+ const output = new ComfyNodeOutput(this, ix++, x.typeName, x.nameInComfy)
162
+ outputs[x.outKey] = output
163
+ this.$outputs.push(output)
164
+ // console.log(` - .${x.outKey} as ComfyNodeOutput(${ix})`)
165
+ }
166
+ this.outputs = outputs as ComfyNode_output
167
+
168
+ // implements the _<typeName> properties (HasSingle interfaces)
169
+ const extensions: { [key: string]: any } = {}
170
+ for (const x of this.$schema.singleOutputs) {
171
+ extensions[`_${x.typeName}`] = outputs[x.outKey]
172
+ }
173
+ Object.assign(this, extensions)
174
+ }
175
+
176
+ _convertPromptExtToPrompt(promptExt: ComfyApiNodeJson): ComfyApiNodeJson {
177
+ const inputs: { [inputName: string]: any } = {}
178
+ const _done = new Set<string>()
179
+ for (const i of this.$schema.inputs) {
180
+ _done.add(i.nameInComfy)
181
+ const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy])
182
+ inputs[i.nameInComfy] = value
183
+ }
184
+ for (const [nameInComfy, rawVal] of Object.entries(promptExt.inputs)) {
185
+ if (_done.has(nameInComfy)) continue
186
+ const value = this.serializeValue(nameInComfy, rawVal)
187
+ inputs[nameInComfy] = value
188
+ }
189
+ return { class_type: this.$schema.nameInComfy, inputs }
190
+ }
191
+
192
+ /** return the list of nodes piped into this node */
193
+ _incomingNodes(): ComfyNodeId[] {
194
+ const incomingNodes: ComfyNodeId[] = []
195
+ for (const [_name, val] of Object.entries(this.inputs)) {
196
+ if (Array.isArray(val)) {
197
+ const [from, _slotIx] = val
198
+ incomingNodes.push(from)
199
+ }
200
+ }
201
+ return incomingNodes
202
+ }
203
+
204
+ _primitives(): { inputName: string; value: string }[] {
205
+ const primitives: { inputName: string; value: string }[] = []
206
+ for (const [inputName, val] of Object.entries(this.inputs)) {
207
+ if (Array.isArray(val)) continue
208
+ primitives.push({ inputName: inputName, value: val?.toString() })
209
+ }
210
+ return primitives
211
+ }
212
+
213
+ /** return true if the given node is plugged into this one */
214
+ isChildrenOf(node: ComfyNode<any>): boolean {
215
+ return this._incomingNodes().includes(node.uid)
216
+ }
217
+
218
+ get parents(): ComfyNode<any>[] {
219
+ return this._incomingNodes().map((id) => this.graph.getNode(id)!)
220
+ }
221
+ // get children(): ComfyNode<any>[] {
222
+ // return this._incomingNodes().map((id) => this.graph.getNode(id)!)
223
+ // }
224
+
225
+ _visible: boolean = true
226
+ set visible(value: boolean) {
227
+ this._visible = value
228
+ } // biome-ignore format: misc
229
+ get visible(): boolean {
230
+ return this._visible
231
+ } // biome-ignore format: misc
232
+
233
+ _x: number = 0
234
+ get x(): number {
235
+ return this._x
236
+ } // biome-ignore format: misc
237
+ set x(value: number) {
238
+ this.isDirty = true
239
+ this._x = value
240
+ }
241
+
242
+ _y: number = 0
243
+ get y(): number {
244
+ return this._y
245
+ } // biome-ignore format: misc
246
+ set y(value: number) {
247
+ this.isDirty = true
248
+ this._y = value
249
+ }
250
+
251
+ isDirty = true
252
+
253
+ tagDirty(value: boolean): void {
254
+ this.isDirty = value
255
+ }
256
+
257
+ col: number = 0
258
+ selected: boolean = false
259
+ get outgoingPorts(): NodePort[] {
260
+ return this.$outputs.map(
261
+ (o, ix): NodePort => ({
262
+ id: this.uid + '#' + o.slotIx,
263
+ label: o.type,
264
+ width: NodeSlotSize,
265
+ height: NodeSlotSize,
266
+ fromNode: this,
267
+ toNode: o.node ?? undefined,
268
+ type: o.type,
269
+ x: this.x + this.width, // + NodeSlotSize / 2,
270
+ y:
271
+ this.y + // start
272
+ NodeTitleHeight + // title
273
+ ix * nodeLineHeight + // e.fromSlotIx * 10,
274
+ nodeLineHeight / 2, //
275
+ }),
276
+ )
277
+ }
278
+
279
+ get incomingPorts(): NodePort[] {
280
+ return this._incomingEdges().map(
281
+ (e, ix): NodePort => ({
282
+ id: this.uid + '<-' + e.from + '#' + e.fromSlotIx,
283
+ width: NodeSlotSize,
284
+ height: NodeSlotSize,
285
+ fromNode: this.graph.getNode(e.from) ?? undefined,
286
+ toNode: this,
287
+ label: e.inputName,
288
+ type: e.type,
289
+ x: this.x, // - NodeSlotSize / 2,
290
+ y:
291
+ this.y + // start
292
+ NodeTitleHeight + // title
293
+ ix * nodeLineHeight + // e.fromSlotIx * 10,
294
+ nodeLineHeight / 2,
295
+ }),
296
+ )
297
+ }
298
+
299
+ _incomingEdges(): {
300
+ from: ComfyNodeId
301
+ inputName: string
302
+ type: string
303
+ fromSlotIx: number
304
+ }[] {
305
+ const incomingEdges: {
306
+ from: ComfyNodeId
307
+ inputName: string
308
+ fromSlotIx: number
309
+ type: string
310
+ }[] = []
311
+
312
+ for (const [inputName, val] of Object.entries(this.inputs)) {
313
+ if (Array.isArray(val)) {
314
+ const [from, _slotIx] = val as [ComfyNodeId, number]
315
+ const type = this.graph.getNode(from)?.$outputs[_slotIx]?.type ?? 'UNKNOWN'
316
+ incomingEdges.push({ from, inputName, fromSlotIx: _slotIx, type })
317
+ }
318
+ }
319
+ return incomingEdges
320
+ }
321
+
322
+ /** number of primitive fields in this node */
323
+ primitivesCount(): number {
324
+ return Object.values(this.inputs).filter((val) => !Array.isArray(val)).length
325
+ }
326
+
327
+ /** width dimensions for autolayout algorithm */
328
+ get width(): number {
329
+ return 200
330
+ }
331
+
332
+ /** height dimensions for autolayout algorithm */
333
+ get height(): number {
334
+ const inputLen = this._incomingEdges().length
335
+ const outputLen = this.$schema.outputs.length
336
+ const headerCount = Math.max(inputLen, outputLen)
337
+
338
+ // max height since some nodes have many invisible inputs
339
+ return (this.primitivesCount() + headerCount + 1) * nodeLineHeight
340
+ }
341
+
342
+ serializeValue(field: string, value: unknown): unknown {
343
+ if (value == null) {
344
+ const schema = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === field)
345
+ if (schema == null) throw new Error(`❌ no schema for field "${field}" (of node ${this.$schema.nodeKey})`)
346
+ // console.log('def1=', field, schema.opts.default)
347
+ const opts = schema.opts == null || typeof schema.opts !== 'object' ? undefined : schema.opts
348
+ if (opts?.default != null) return opts.default
349
+ // console.log('def2=', field, schema.required)
350
+ if (!schema.required) return undefined
351
+ console.error(field, 'is required but value is ', value, this.json) //, this)
352
+ this.graph.recordProblem(
353
+ `🔴 [serializeValue] field "${field}" (of node ${this.$schema.nodeKey}#${this.uid}) value is null but field is not optional`,
354
+ )
355
+ return undefined
356
+ // throw new Error(
357
+ // `🔴 [serializeValue] field "${field}" (of node ${this.$schema.nodeKey}#${this.uid}) value is null`,
358
+ // )
359
+ }
360
+ if (typeof value === 'function') {
361
+ return this.serializeValue(field, value(this.graph.builder, this.graph))
362
+ }
363
+ if (value === auto_) {
364
+ const expectedType = this._getExpectedTypeForField(field)
365
+ console.info(`🔍 looking for type ${expectedType} for field ${field}`)
366
+ for (const node of this.graph.nodes.slice().reverse()) {
367
+ const output = node._getOutputForTypeOrNull(expectedType)
368
+ if (output != null) return [node.uid, output.slotIx]
369
+ }
370
+ throw new Error(`🔴 [AUTO failed] field "${field}" (of node ${this.$schema.nodeKey}) value is null`)
371
+ }
372
+ if (value instanceof ComfyNodeOutput) return [value.node.uid, value.slotIx]
373
+ if (value instanceof ComfyNode) {
374
+ const expectedType = this._getExpectedTypeForField(field)
375
+ const output = value._getOutputForTypeOrCrash(expectedType)
376
+ return [value.uid, output.slotIx]
377
+ }
378
+ return value
379
+ }
380
+
381
+ private _getExpectedTypeForField(name: string): string {
382
+ const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)
383
+ if (input == null) throw new Error('🔴 input not found asdf')
384
+ return input.typeName
385
+ }
386
+
387
+ private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {
388
+ const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!
389
+ const val = (this.outputs as any)[i.outKey]
390
+ // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)
391
+ if (val instanceof ComfyNodeOutput) return val
392
+ throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)
393
+ }
394
+
395
+ private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {
396
+ const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)
397
+ if (i == null) return null
398
+ const val = (this.outputs as any)[i.outKey]
399
+ if (val == null) return null
400
+ if (val instanceof ComfyNodeOutput) return val
401
+ throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)
402
+ }
403
+ }