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,98 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { type } from 'arktype'
4
+ import { dirname } from 'pathe'
5
+ import type { ComfyHost } from 'src/host/ComfyHost.ts'
6
+ import { logError } from 'src/utils/log.ts'
7
+
8
+ /**
9
+ * client for the OPTIONAL ComfyUI-Lora-Manager extension.
10
+ * absent extension = normal condition: callers get null/empty and degrade.
11
+ */
12
+
13
+ const lmLoraItem = type({
14
+ folder: 'string',
15
+ file_name: 'string',
16
+ preview_url: 'string',
17
+ })
18
+ const lmLoraPage = type({
19
+ items: lmLoraItem.array(),
20
+ total: 'number',
21
+ })
22
+
23
+ /** normalize an object_info lora name OR an lm folder/file pair to one key */
24
+ export function loraPreviewKey(name: string): string {
25
+ return name
26
+ .replaceAll('\\', '/')
27
+ .replace(/\.(safetensors|st|pt|ckpt)$/i, '')
28
+ .toLowerCase()
29
+ }
30
+
31
+ /**
32
+ * fetch every lora known to lora-manager, mapped `loraPreviewKey` → preview_url
33
+ * (server-relative). Returns null when the extension is absent (404/network).
34
+ */
35
+ export async function fetchLoraPreviewMap(host: ComfyHost): Promise<Map<string, string> | null> {
36
+ const base = host.getServerHostHTTP()
37
+ const map = new Map<string, string>()
38
+ const pageSize = 500
39
+ for (let page = 1; page <= 20; page++) {
40
+ let res: Response
41
+ try {
42
+ res = await fetch(`${base}/api/lm/loras/list?page=${page}&page_size=${pageSize}`)
43
+ } catch {
44
+ return null // host unreachable: previews off, not an error
45
+ }
46
+ if (!res.ok) return page === 1 ? null : map // 404 on page 1 = extension absent
47
+ const json: unknown = await res.json()
48
+ const parsed = lmLoraPage(json)
49
+ if (parsed instanceof type.errors) {
50
+ // wire tolerance (agent/coding.md): lm drifts faster than our schema — LOG then bail
51
+ logError(`[loraManagerApi] /api/lm/loras/list page ${page} shape mismatch: ${parsed.summary}`)
52
+ return map
53
+ }
54
+ for (const item of parsed.items) {
55
+ const rel = item.folder === '' ? item.file_name : `${item.folder}/${item.file_name}`
56
+ map.set(loraPreviewKey(rel), item.preview_url)
57
+ }
58
+ if (map.size >= parsed.total || parsed.items.length === 0) break
59
+ }
60
+ return map
61
+ }
62
+
63
+ /** the bytes look like an image (magic numbers) — guards against ComfyUI's SPA index.html fallback */
64
+ export function looksLikeImage(bytes: Uint8Array): boolean {
65
+ if (bytes.length < 3) return false // shortest signature (JPEG/GIF) is 3 bytes
66
+ const b = bytes
67
+ const is = (sig: number[], off = 0): boolean => sig.every((v, i) => b[off + i] === v)
68
+ return (
69
+ is([0x89, 0x50, 0x4e, 0x47]) || // PNG
70
+ is([0xff, 0xd8, 0xff]) || // JPEG
71
+ is([0x47, 0x49, 0x46]) || // GIF
72
+ (is([0x52, 0x49, 0x46, 0x46]) && is([0x57, 0x45, 0x42, 0x50], 8)) // RIFF…WEBP
73
+ )
74
+ }
75
+
76
+ /**
77
+ * fetch a preview image's bytes from its server-relative preview_url.
78
+ * cached on success at `.comfy-ts/cache/lora-previews/<sha1(url)>`. Returns null
79
+ * when the file is missing: lora-manager SPA-fallbacks to index.html (HTML), so
80
+ * a non-image content-type OR non-image magic bytes => no preview, not a crash.
81
+ */
82
+ export async function fetchLoraPreviewBytes(host: ComfyHost, previewUrl: string): Promise<Uint8Array | null> {
83
+ const cachePath = comfyts.resolveFromCache(`lora-previews/${createHash('sha1').update(previewUrl).digest('hex')}`)
84
+ if (existsSync(cachePath)) return new Uint8Array(readFileSync(cachePath))
85
+ try {
86
+ const res = await fetch(`${host.getServerHostHTTP()}${previewUrl}`)
87
+ if (!res.ok) return null
88
+ const ct = res.headers.get('content-type') ?? ''
89
+ if (ct !== '' && !ct.startsWith('image/')) return null // HTML fallback etc.
90
+ const bytes = new Uint8Array(await res.arrayBuffer())
91
+ if (!looksLikeImage(bytes)) return null
92
+ mkdirSync(dirname(cachePath), { recursive: true })
93
+ writeFileSync(cachePath, bytes)
94
+ return bytes
95
+ } catch {
96
+ return null
97
+ }
98
+ }
@@ -0,0 +1,53 @@
1
+ import { type Either, resultFailure, resultSuccess } from 'src/types/index.ts'
2
+
3
+ export type TextChunks = {
4
+ [key: string]: string
5
+ }
6
+
7
+ export const getPngMetadataFromUint8Array = (pngData: Uint8Array): Either<string, TextChunks> => {
8
+ const dataView = new DataView(
9
+ pngData.buffer,
10
+ pngData.byteOffset, // <-- it just doesn't work without this
11
+ pngData.byteLength, // <-- it just doesn't work without this
12
+ )
13
+
14
+ // console.log('🟢', dataView.getUint32(0))
15
+ // console.log('🟢', dataView)
16
+
17
+ // Check that the PNG signature is present
18
+ if (dataView.getUint32(0) !== 0x89504e47) {
19
+ // 🔴 showErrorMessage('Not a valid PNG file')
20
+ return resultFailure('Not a valid PNG file')
21
+ }
22
+
23
+ // Start searching for chunks after the PNG signature
24
+ let offset = 8
25
+
26
+ const txt_chunks: TextChunks = {}
27
+
28
+ // Loop through the chunks in the PNG file
29
+ while (offset < pngData.length) {
30
+ // Get the length of the chunk
31
+ const length = dataView.getUint32(offset)
32
+ // Get the chunk type
33
+ const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))
34
+ if (type === 'tEXt') {
35
+ // Get the keyword
36
+ let keyword_end = offset + 8
37
+ while (pngData[keyword_end] !== 0) {
38
+ keyword_end++
39
+ }
40
+ const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end))
41
+ // Get the text
42
+ const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length)
43
+ const contentJson = Array.from(contentArraySegment)
44
+ .map((s) => String.fromCharCode(s))
45
+ .join('')
46
+ txt_chunks[keyword] = contentJson
47
+ }
48
+
49
+ offset += 12 + length
50
+ }
51
+
52
+ return resultSuccess(txt_chunks)
53
+ }
@@ -0,0 +1,38 @@
1
+ import type { Maybe } from 'src/types/index.ts'
2
+ import { bong } from 'src/utils/bang.ts'
3
+ import { type ExifData, parseExifData } from 'src/image-utils/_parseExifData.ts'
4
+
5
+ export const getWebpMetadataFromUint8Array = (webp: Uint8Array): Maybe<ExifData> => {
6
+ const dataView = new DataView(webp.buffer)
7
+
8
+ // Check that the WEBP signature is present
9
+ if (dataView.getUint32(0) !== 0x52494646 || dataView.getUint32(8) !== 0x57454250) {
10
+ console.error('Not a valid WEBP file')
11
+ // r()
12
+ return null
13
+ }
14
+
15
+ // Start searching for chunks after the WEBP signature
16
+ let offset = 12
17
+ const txt_chunks: ExifData = {}
18
+ // Loop through the chunks in the WEBP file
19
+ while (offset < webp.length) {
20
+ const chunk_length = dataView.getUint32(offset + 4, true)
21
+ const chunk_type = String.fromCharCode(...webp.slice(offset, offset + 4))
22
+ if (chunk_type === 'EXIF') {
23
+ if (String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) === 'Exif\0\0') {
24
+ offset += 6
25
+ }
26
+ const data = parseExifData(webp.slice(offset + 8, offset + 8 + chunk_length))
27
+ for (const key in data) {
28
+ const value = bong(data[key])
29
+ const index = value.indexOf(':')
30
+ txt_chunks[value.slice(0, index)] = value.slice(index + 1)
31
+ }
32
+ }
33
+
34
+ offset += 8 + chunk_length
35
+ }
36
+
37
+ return txt_chunks
38
+ }
@@ -0,0 +1,53 @@
1
+ /** biome-ignore-all lint/style/noNonNullAssertion: fix later */
2
+ export type ExifData = { [key: string]: string }
3
+
4
+ // inspired from https://github.com/comfyanonymous/ComfyUI/blob/dccca1daa5af1954d55918f365e83a3331019549/web/scripts/pnginfo.js#L50C1-L96C1
5
+ export function parseExifData(arrData: Uint8Array): ExifData {
6
+ // Check for the correct TIFF header (0x4949 for little-endian or 0x4D4D for big-endian)
7
+ const isLittleEndian = new Uint16Array(arrData.slice(0, 2))[0] === 0x4949
8
+
9
+ // Function to read 16-bit and 32-bit integers from binary data
10
+ function readInt(offset: number, isLittleEndian: boolean, length: number): number | undefined {
11
+ const arr = arrData.slice(offset, offset + length)
12
+ if (length === 2) {
13
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(0, isLittleEndian)
14
+ } else if (length === 4) {
15
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(0, isLittleEndian)
16
+ }
17
+ return
18
+ }
19
+
20
+ // Read the offset to the first IFD (Image File Directory)
21
+ const ifdOffset = readInt(4, isLittleEndian, 4)!
22
+
23
+ function parseIFD(offset: number): ExifData {
24
+ const numEntries: number = readInt(offset, isLittleEndian, 2)!
25
+ const result: ExifData = {}
26
+
27
+ for (let i = 0; i < numEntries; i++) {
28
+ const entryOffset = offset + 2 + i * 12
29
+ const tag = readInt(entryOffset, isLittleEndian, 2)!
30
+ const type = readInt(entryOffset + 2, isLittleEndian, 2)!
31
+ const numValues = readInt(entryOffset + 4, isLittleEndian, 4)!
32
+ const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4)!
33
+
34
+ // Read the value(s) based on the data type
35
+ let value: string | undefined
36
+ if (type === 2) {
37
+ // ASCII string
38
+ value = String.fromCharCode(...arrData.slice(valueOffset, valueOffset + numValues - 1))
39
+ }
40
+
41
+ // 💬 2025-06-10 rvion: undefined check added
42
+ if (value !== undefined) {
43
+ result[tag] = value
44
+ }
45
+ }
46
+
47
+ return result
48
+ }
49
+
50
+ // Parse the first IFD
51
+ const ifdData: ExifData = parseIFD(ifdOffset)
52
+ return ifdData
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * comfy-ts — type-safe ComfyUI workflow creation and execution
3
+ * @packageDocumentation
4
+ */
5
+
6
+ // global Comfy.* base namespace + per-host sdk registry (side-effectful types)
7
+ export * from 'src/types/comfy-sdk.ts'
8
+
9
+ // entrypoint singleton
10
+ export { ComfyTS } from 'src/state.ts'
11
+
12
+ // host
13
+ export { ComfyHost, type ComfyHostData, type ComfyHostID, type ConnectOptions } from 'src/host/ComfyHost.ts'
14
+ export { ComfyManager } from 'src/host/ComfyManager.ts'
15
+ export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
16
+ export { ComfyWorkflowBuilder } from 'src/host/ComfyWorkflowBuilder.ts'
17
+ export type { Requirements, PluginInstallStatus, PluginSuggestion } from 'src/host/Requirements.ts'
18
+ export { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
19
+
20
+ // runner
21
+ export {
22
+ ComfyWorkflow,
23
+ type ComfyNodeIdMode,
24
+ type ComfyWorkflowData,
25
+ type ComfyWorkflowID,
26
+ type ExecutionSnapshot,
27
+ type ProgressReport,
28
+ type RunSettings,
29
+ } from 'src/runner/ComfyWorkflow.ts'
30
+ export { ComfyExecution, type ComfyExecutionData, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
31
+ export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
32
+ export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
33
+ export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
34
+ export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
35
+
36
+ // graph (programmatic node graph)
37
+ export { ComfyNode } from 'src/graph/ComfyNode.ts'
38
+ export { ComfyNodeOutput } from 'src/graph/ComfyNodeOutput.ts'
39
+ export type { ComfyNodeMetadata, ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
40
+ export { auto, auto_ } from 'src/graph/autoValue.ts'
41
+
42
+ // sdk generator (schema parsing + per-host codegen)
43
+ export { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
44
+ export { codegenSDK, hostIdToNamespace, type CodegenOptions } from 'src/sdk-generator/comfyui-sdk-codegen.ts'
45
+ export type { ComfyNodeSchemaJSON, ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
46
+ export type { ComfyImageName, ComfyUnionValue, QualifiedNodeKey } from 'src/sdk-generator/comfyui-types.ts'
47
+ export type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
48
+
49
+ // litegraph (ComfyUI saved-workflow JSON format)
50
+ export type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
51
+ export { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraphJSON.ts'
52
+
53
+ // vars + re-runnable workflows
54
+ export {
55
+ v,
56
+ ComfyVarBase,
57
+ ComfyVar,
58
+ TextVar,
59
+ PromptVar,
60
+ IntVar,
61
+ FloatVar,
62
+ SeedVar,
63
+ ToggleVar,
64
+ ChoiceVar,
65
+ LorasVar,
66
+ SizeVar,
67
+ DEFAULT_SIZE_PRESETS,
68
+ activeLoras,
69
+ } from 'src/vars/ComfyVars.ts'
70
+ export type {
71
+ AnyVar,
72
+ VarKind,
73
+ VarsSpec,
74
+ VarValues,
75
+ PromptValue,
76
+ ActiveLoraSource,
77
+ LorasHost,
78
+ LoraStrength,
79
+ ActiveLora,
80
+ SizeValue,
81
+ SizePreset,
82
+ } from 'src/vars/ComfyVars.ts'
83
+ export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
84
+ export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
85
+ export { isTuiActive } from 'src/cli/tui-env.ts'
86
+ export { loraTag } from 'src/utils/loraTag.ts'
87
+
88
+ // shared types
89
+ export * from 'src/types/index.ts'
@@ -0,0 +1,22 @@
1
+ import { type } from 'arktype'
2
+ import type { EmptyRecord, IsEqual } from 'src/types/index.ts'
3
+
4
+ // prettier-ignore
5
+ export type LiteGraphGroup = {
6
+ title: string // 'Create Mask'
7
+ bounding: [number, number, number, number] // [1078, -579, 1589, 614]
8
+ color: string // '#3f789e'
9
+ font_size: number // 24
10
+ flags: EmptyRecord // {}
11
+ }
12
+
13
+ export const LiteGraphGroup_ark = type({
14
+ title: 'string',
15
+ bounding: type(['number', 'number', 'number', 'number']),
16
+ color: 'string',
17
+ font_size: 'number',
18
+ // EmptyRecord: an object we don't read any key from
19
+ flags: type.Record('string', 'unknown').as<EmptyRecord>(),
20
+ })
21
+
22
+ true satisfies IsEqual<LiteGraphGroup, typeof LiteGraphGroup_ark.infer>
@@ -0,0 +1,46 @@
1
+ import { type } from 'arktype'
2
+ import type { EmptyRecord, IsEqual } from 'src/types/index.ts'
3
+ import { type LiteGraphGroup, LiteGraphGroup_ark } from 'src/litegraph/LiteGraphGroup.ts'
4
+ import { type LiteGraphLink, LiteGraphLink_ark } from 'src/litegraph/LiteGraphLink.ts'
5
+ import { type LiteGraphNode, LiteGraphNode_ark } from 'src/litegraph/LiteGraphNode.ts'
6
+
7
+ /** comfy workflows are simply LiteGraphs workflows */
8
+ export type ComfyWorkflowJSON = LiteGraphJSON
9
+
10
+ /** litegraph workflow are stored... in a very unpractical format */
11
+ export type LiteGraphJSON = {
12
+ last_node_id: number
13
+ last_link_id: number
14
+ nodes: LiteGraphNode[]
15
+ links: LiteGraphLink[]
16
+ groups: LiteGraphGroup[]
17
+ config: EmptyRecord
18
+ extra: {
19
+ ds?: {
20
+ scale: number
21
+ offset: { 0: number; 1: number }
22
+ }
23
+ }
24
+ version: 0.4
25
+ }
26
+
27
+ export const LiteGraphJSON_ark = type({
28
+ last_node_id: 'number',
29
+ last_link_id: 'number',
30
+ nodes: LiteGraphNode_ark.array(),
31
+ links: LiteGraphLink_ark.array(),
32
+ groups: LiteGraphGroup_ark.array(),
33
+ config: type.Record('never', 'never'),
34
+ extra: {
35
+ 'ds?': {
36
+ scale: 'number',
37
+ offset: {
38
+ '0': 'number',
39
+ '1': 'number',
40
+ },
41
+ },
42
+ },
43
+ version: '0.4',
44
+ })
45
+
46
+ true satisfies IsEqual<LiteGraphJSON, typeof LiteGraphJSON_ark.infer>
@@ -0,0 +1,23 @@
1
+ import { type } from 'arktype'
2
+ import type { IsEqual } from 'src/types/index.ts'
3
+ import { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'
4
+
5
+ export type LiteGraphLink = [
6
+ linkId: LiteGraphLinkID, // 9, - linkId
7
+ fromNodeId: number, // 8, - fromNodeId
8
+ fromNodeOutputIx: number, // 0, - fromNodeOutputIx
9
+ toNodeId: number, // 9, - toNodeId
10
+ toNodeInputIx: number, // 0, - toNodeInputIx
11
+ linkType: string, // "IMAGE" - type
12
+ ]
13
+
14
+ export const LiteGraphLink_ark = type([
15
+ LiteGraphLinkID_, // 9, - linkId
16
+ 'number', // 8, - fromNodeId
17
+ 'number', // 0, - fromNodeOutputIx
18
+ 'number', // 9, - toNodeId
19
+ 'number', // 0, - toNodeInputIx
20
+ 'string', // "IMAGE" - linkType
21
+ ])
22
+
23
+ true satisfies IsEqual<typeof LiteGraphLink_ark.infer, LiteGraphLink>
@@ -0,0 +1,6 @@
1
+ import { type } from 'arktype'
2
+ import type { Branded } from 'src/types/index.ts'
3
+
4
+ export const asLiteGraphLinkID = (id: number): LiteGraphLinkID => id as LiteGraphLinkID
5
+ export const LiteGraphLinkID_ = type.number.atLeast(0).as<Branded<number, { LiteGraphLinkID: true }>>()
6
+ export type LiteGraphLinkID = typeof LiteGraphLinkID_.infer
@@ -0,0 +1,69 @@
1
+ import { type } from 'arktype'
2
+ import type { EmptyRecord, IsEqual } from 'src/types/index.ts'
3
+ import { type LiteGraphNodeInput, LiteGraphNodeInput_ark } from 'src/litegraph/LiteGraphNodeInput.ts'
4
+ import { type LiteGraphNodeOutput, LiteGraphNodeOutput_ark } from 'src/litegraph/LiteGraphNodeOutput.ts'
5
+
6
+ // prettier-ignore
7
+ export type LiteGraphNode = {
8
+ id: number // 5
9
+ type: string // 'CLIPTextEncode'
10
+
11
+ // cosmetics
12
+ title?: string // "Inpaint (Positive)",
13
+ color?: string // "#222", or "#3f789e"
14
+ bgColor?: string // "#3f789e"
15
+ pos: { '0': number; '1': number } // was: [number, number]
16
+ size: { '0': number; '1': number }
17
+ flags?: EmptyRecord
18
+ order?: number
19
+ /**
20
+ * 0 = normal
21
+ * 1 = ?????
22
+ * 2 = muted
23
+ * */
24
+ mode?: number
25
+ inputs?: LiteGraphNodeInput[]
26
+ outputs: LiteGraphNodeOutput[]
27
+
28
+ isVirtualNode?: boolean // frontend only
29
+ properties?: {
30
+ /**
31
+ * S&R stands for search and replace
32
+ * // 💬 2024-11-13 rvion: do we want to populate taht someday soon
33
+ */
34
+ 'Node name for S&R'?: string
35
+
36
+ /** when set to true, it.... */
37
+ showOutputText?: boolean
38
+
39
+ /** no clue what it does */
40
+ horizontal?: boolean
41
+ }
42
+ widgets_values?: unknown[]
43
+ }
44
+
45
+ export const LiteGraphNode_ark = type({
46
+ id: 'number',
47
+ type: 'string',
48
+
49
+ // cospetics
50
+ 'title?': 'string',
51
+ 'color?': 'string',
52
+ 'bgcolor?': 'string',
53
+ pos: { '0': 'number', '1': 'number' },
54
+ size: { '0': 'number', '1': 'number' },
55
+ 'flags?': { '[never]': 'never' },
56
+ 'order?': 'number',
57
+ 'mode?': 'number',
58
+ 'inputs?': LiteGraphNodeInput_ark.array(),
59
+ outputs: LiteGraphNodeOutput_ark.array(),
60
+ 'isVirtualNode?': 'boolean',
61
+ 'properties?': {
62
+ 'Node name for S&R?': 'string',
63
+ 'showOutputText?': 'boolean',
64
+ 'horizontal?': 'boolean',
65
+ },
66
+ 'widgets_values?': `unknown[]`,
67
+ })
68
+
69
+ true satisfies IsEqual<LiteGraphNode, typeof LiteGraphNode_ark.infer>
@@ -0,0 +1,27 @@
1
+ import { type } from 'arktype'
2
+ import type { IsEqual } from 'src/types/index.ts'
3
+ import { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'
4
+
5
+ export type LiteGraphNodeInput = {
6
+ name: string // | 'clip'
7
+ type: string // | 'CLIP'
8
+ link: LiteGraphLinkID | null // | 5
9
+ shape?: number // | '2D'
10
+ widget?: {
11
+ name: string // | 'select'
12
+ config: unknown // | 🔴
13
+ }
14
+ }
15
+
16
+ export const LiteGraphNodeInput_ark = type({
17
+ name: 'string',
18
+ type: 'string',
19
+ link: LiteGraphLinkID_.or(type.null),
20
+ 'shape?': 'number',
21
+ 'widget?': type({
22
+ name: 'string',
23
+ config: type.unknown,
24
+ }),
25
+ })
26
+
27
+ true satisfies IsEqual<LiteGraphNodeInput, typeof LiteGraphNodeInput_ark.infer>
@@ -0,0 +1,23 @@
1
+ import { type } from 'arktype'
2
+ import type { IsEqual } from 'src/types/index.ts'
3
+ import { type LiteGraphLinkID, LiteGraphLinkID_ } from 'src/litegraph/LiteGraphLinkID.ts'
4
+ import { type LiteGraphSlotIndex, LiteGraphSlotIndex_ } from 'src/litegraph/LiteGraphSlotIndex.ts'
5
+
6
+ export type LiteGraphNodeOutput = {
7
+ // ❌9 name: string // 'CONDITIONING'
8
+ name: string
9
+ type: string // 'CONDITIONING'
10
+ links: LiteGraphLinkID[] | null
11
+ shape?: number // '2D'
12
+ slot_index?: LiteGraphSlotIndex
13
+ }
14
+
15
+ export const LiteGraphNodeOutput_ark = type({
16
+ name: 'string',
17
+ type: 'string',
18
+ links: LiteGraphLinkID_.array().or(type.null),
19
+ 'shape?': 'number',
20
+ 'slot_index?': LiteGraphSlotIndex_,
21
+ })
22
+
23
+ true satisfies IsEqual<LiteGraphNodeOutput, typeof LiteGraphNodeOutput_ark.infer>
@@ -0,0 +1,6 @@
1
+ import { type } from 'arktype'
2
+ import type { Branded } from 'src/types/index.ts'
3
+
4
+ export const asLiteGraphSlotIndex = (id: number): LiteGraphSlotIndex => id as LiteGraphSlotIndex
5
+ export const LiteGraphSlotIndex_ = type.number.atLeast(0).as<Branded<number, { LiteGraphSlotIndex: true }>>()
6
+ export type LiteGraphSlotIndex = typeof LiteGraphSlotIndex_.infer
@@ -0,0 +1,114 @@
1
+ import type { ComfyNode } from 'src/graph/ComfyNode.ts'
2
+ import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
3
+ import { bang } from 'src/utils/bang.ts'
4
+ import { howManyWidgetValuesForThisSchemaType } from 'src/sdk-generator/Primitives.ts'
5
+ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
6
+ import type { LiteGraphLink } from 'src/litegraph/LiteGraphLink.ts'
7
+ import { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
8
+ import type { LiteGraphNode } from 'src/litegraph/LiteGraphNode.ts'
9
+ import type { LiteGraphNodeInput } from 'src/litegraph/LiteGraphNodeInput.ts'
10
+ import type { LiteGraphNodeOutput } from 'src/litegraph/LiteGraphNodeOutput.ts'
11
+ import { asLiteGraphSlotIndex } from 'src/litegraph/LiteGraphSlotIndex.ts'
12
+
13
+ export const convertFlowToLiteGraphJSON = (graph: ComfyWorkflow): LiteGraphJSON => {
14
+ const ctx = new LiteGraphCtx(graph)
15
+ const last_node_id = Math.max(...graph.nodes.map((n) => n.uidNumber))
16
+ const xxx = graph.nodes.map((comfyNode) => ({
17
+ liteGraphNode: convertNodeToLiteGraphNode(ctx, comfyNode),
18
+ comfyNode,
19
+ }))
20
+ for (const xx of xxx) {
21
+ const n = xx.liteGraphNode
22
+ n.pos[0] = bang(xx.comfyNode.x)
23
+ n.pos[1] = bang(xx.comfyNode.y)
24
+ for (const o of n.outputs) {
25
+ o.links = ctx.links.filter((l) => l[3] === n.id && l[4] === o.slot_index).map((l) => l[0])
26
+ }
27
+ }
28
+ return {
29
+ last_node_id,
30
+ last_link_id: ctx.nextLinkId,
31
+ nodes: xxx.map((n) => n.liteGraphNode),
32
+ links: ctx.links,
33
+ config: {},
34
+ extra: {},
35
+ groups: [],
36
+ version: 0.4,
37
+ }
38
+ }
39
+
40
+ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): LiteGraphNode => {
41
+ const inputs: LiteGraphNodeInput[] = []
42
+ const widgets_values: unknown[] = []
43
+ for (const ipt of node.$schema.inputs) {
44
+ const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])
45
+ const isWidget = howManyWidgetValuesForThisSchemaType(ipt) > 0
46
+ if (_isLink(raw)) {
47
+ const nodeUidNumber = bang(
48
+ ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,
49
+ `link target node "${raw[0]}" not found in graph`,
50
+ )
51
+ inputs.push({
52
+ name: ipt.nameInComfy,
53
+ type: ipt.typeName,
54
+ // target_slot = index within THIS node's litegraph inputs array,
55
+ // not the schema input index (widget inputs are not litegraph slots)
56
+ link: ctx.allocateLink(
57
+ nodeUidNumber,
58
+ raw[1],
59
+ node.uidNumber,
60
+ asLiteGraphSlotIndex(inputs.length),
61
+ ipt.typeName,
62
+ ),
63
+ })
64
+ } else if (isWidget) {
65
+ widgets_values.push(raw)
66
+ // ComfyUI stores a phantom control_after_generate value after seeds
67
+ const isSeed = ipt.typeName === 'INT' && (ipt.nameInComfy === 'seed' || ipt.nameInComfy === 'noise_seed')
68
+ if (isSeed) widgets_values.push(false)
69
+ } else {
70
+ // unconnected link-kind input: a litegraph slot with no link —
71
+ // NEVER a widget value (that would misalign the round-trip import)
72
+ inputs.push({ name: ipt.nameInComfy, type: ipt.typeName, link: null })
73
+ }
74
+ }
75
+ const outputs = node.$schema.outputs.map(
76
+ (i, ix): LiteGraphNodeOutput => ({
77
+ // ❌9 name: i.nameInComfy,
78
+ type: i.typeName,
79
+ links: [], // empty links by default 🔴
80
+ slot_index: asLiteGraphSlotIndex(ix),
81
+ name: i.outKey,
82
+ }),
83
+ )
84
+ return {
85
+ type: node.$schema.nameInComfy,
86
+ id: node.uidNumber,
87
+ inputs,
88
+ outputs,
89
+ pos: [0, 0],
90
+ size: [node.width, node.height],
91
+ widgets_values,
92
+ }
93
+ }
94
+
95
+ const _isLink = (v: unknown): v is [string, number] => {
96
+ return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'
97
+ }
98
+
99
+ export class LiteGraphCtx {
100
+ constructor(public graph: ComfyWorkflow) {}
101
+ nextLinkId: number = 0
102
+ links: LiteGraphLink[] = []
103
+ allocateLink = (
104
+ fromNodeId: number,
105
+ fromNodeOutputIx: number,
106
+ toNodeId: number,
107
+ toNodeInputIx: number,
108
+ linkType: string,
109
+ ): LiteGraphLinkID => {
110
+ const linkId = asLiteGraphLinkID(++this.nextLinkId)
111
+ this.links.push([linkId, fromNodeId, fromNodeOutputIx, toNodeId, toNodeInputIx, linkType])
112
+ return linkId
113
+ }
114
+ }