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.
- package/LICENSE +21 -0
- package/README.md +363 -0
- package/dist/cli.js +764 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +4128 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +9862 -0
- package/dist/index.d.ts +9846 -58
- package/dist/index.js +4049 -2
- package/dist/index.js.map +1 -1
- package/dist/log-CdfgILde.js +10 -0
- package/dist/log-CdfgILde.js.map +1 -0
- package/dist/run-tui-Io8Xea0L.js +3340 -0
- package/dist/run-tui-Io8Xea0L.js.map +1 -0
- package/package.json +104 -75
- package/src/cli/comfy-ts-cli.ts +36 -0
- package/src/cli/gen.ts +47 -0
- package/src/cli/outline.ts +82 -0
- package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
- package/src/cli/tui/components/EditField.tsx +27 -0
- package/src/cli/tui/components/Header.tsx +51 -0
- package/src/cli/tui/components/HostPanel.tsx +37 -0
- package/src/cli/tui/components/LorasOverlay.tsx +49 -0
- package/src/cli/tui/components/OverlayList.tsx +25 -0
- package/src/cli/tui/components/PickerOverlays.tsx +66 -0
- package/src/cli/tui/components/PreviewPanel.tsx +33 -0
- package/src/cli/tui/components/PromptOverlay.tsx +16 -0
- package/src/cli/tui/components/StatusBar.tsx +165 -0
- package/src/cli/tui/components/TextOverlay.tsx +72 -0
- package/src/cli/tui/components/TreePanel.tsx +51 -0
- package/src/cli/tui/components/TuiApp.tsx +223 -0
- package/src/cli/tui/components/VarsPanel.tsx +86 -0
- package/src/cli/tui/findDefinedWorkflow.ts +16 -0
- package/src/cli/tui/keys.ts +20 -0
- package/src/cli/tui/protocolImagePainter.ts +59 -0
- package/src/cli/tui/run-tui.tsx +73 -0
- package/src/cli/tui/state/DraftsSt.ts +273 -0
- package/src/cli/tui/state/EditorSt.ts +289 -0
- package/src/cli/tui/state/ExecSt.ts +170 -0
- package/src/cli/tui/state/HostSt.ts +107 -0
- package/src/cli/tui/state/LorasSt.ts +185 -0
- package/src/cli/tui/state/PickerSt.ts +112 -0
- package/src/cli/tui/state/PreviewSt.ts +138 -0
- package/src/cli/tui/state/QueueSt.ts +59 -0
- package/src/cli/tui/state/SettingsSt.ts +73 -0
- package/src/cli/tui/state/TreeSt.ts +122 -0
- package/src/cli/tui/state/TuiSt.ts +169 -0
- package/src/cli/tui/state/WorkflowsSt.ts +92 -0
- package/src/cli/tui-env.ts +8 -0
- package/src/errors/InvalidPromptError.ts +12 -0
- package/src/graph/ComfyNode.ts +403 -0
- package/src/graph/ComfyNodeID.ts +28 -0
- package/src/graph/ComfyNodeOutput.ts +16 -0
- package/src/graph/NodeSlotSize.ts +4 -0
- package/src/graph/autoValue.ts +17 -0
- package/src/host/ComfyHost.ts +646 -0
- package/src/host/ComfyInstallType.ts +15 -0
- package/src/host/ComfyManager.ts +232 -0
- package/src/host/ComfyUploader.ts +110 -0
- package/src/host/ComfyWorkflowBuilder.ts +60 -0
- package/src/host/Requirements.ts +55 -0
- package/src/host/ResilientWebsocket.ts +147 -0
- package/src/host/loraManagerApi.ts +98 -0
- package/src/image-utils/_getPngMetadata.ts +53 -0
- package/src/image-utils/_getWebpMetadata.ts +38 -0
- package/src/image-utils/_parseExifData.ts +53 -0
- package/src/index.ts +89 -0
- package/src/litegraph/LiteGraphGroup.ts +22 -0
- package/src/litegraph/LiteGraphJSON.ts +46 -0
- package/src/litegraph/LiteGraphLink.ts +23 -0
- package/src/litegraph/LiteGraphLinkID.ts +6 -0
- package/src/litegraph/LiteGraphNode.ts +69 -0
- package/src/litegraph/LiteGraphNodeInput.ts +27 -0
- package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
- package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
- package/src/manager/ComfyRegistry.ts +124 -0
- package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
- package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
- package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
- package/src/manager/generated/KnownModel_Base.ts +126 -0
- package/src/manager/generated/KnownModel_FileName.ts +2287 -0
- package/src/manager/generated/KnownModel_Name.ts +2287 -0
- package/src/manager/generated/KnownModel_SavePath.ts +263 -0
- package/src/manager/generated/KnownModel_Type.ts +97 -0
- package/src/manager/json/alter-list.json +224 -0
- package/src/manager/json/custom-node-list.extra.ts +13 -0
- package/src/manager/json/custom-node-list.json +21948 -0
- package/src/manager/json/extension-node-map.json +31282 -0
- package/src/manager/json/github-stats.json +12602 -0
- package/src/manager/json/model-list.extra.ts +26 -0
- package/src/manager/json/model-list.json +5052 -0
- package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
- package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
- package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
- package/src/manager/loaders/step4_model-list-loader.ts +159 -0
- package/src/manager/script-update-manager.bun.ts +18 -0
- package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
- package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
- package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
- package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
- package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
- package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
- package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
- package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
- package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
- package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
- package/src/runner/ComfyExecution.ts +301 -0
- package/src/runner/ComfyExecutionStatus.ts +2 -0
- package/src/runner/ComfyWorkflow.ts +395 -0
- package/src/runner/ComfyWorkflowLayout.ts +96 -0
- package/src/runner/ComfyWsApi.ts +159 -0
- package/src/runner/MediaImage.ts +262 -0
- package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
- package/src/sdk-generator/ComfySchema.ts +369 -0
- package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
- package/src/sdk-generator/Primitives.ts +76 -0
- package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
- package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
- package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
- package/src/sdk-generator/comfy-api-json.ts +16 -0
- package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
- package/src/sdk-generator/comfyui-types.ts +56 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
- package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
- package/src/ssh-host-manager/ssh-config.windows.md +32 -0
- package/src/ssh-host-manager/ssh-manager.ts +129 -0
- package/src/state.ts +136 -0
- package/src/types/comfy-sdk.ts +106 -0
- package/src/types/index.ts +55 -0
- package/src/utils/CodeBuffer.ts +61 -0
- package/src/utils/ComfyColors.ts +38 -0
- package/src/utils/ansi.ts +26 -0
- package/src/utils/ansiImage.ts +36 -0
- package/src/utils/bang.ts +39 -0
- package/src/utils/deepCopyNaive.ts +1 -0
- package/src/utils/downloadFile.ts +77 -0
- package/src/utils/escapeJSKey.ts +32 -0
- package/src/utils/exhaust.ts +4 -0
- package/src/utils/extractErrorMessage.ts +11 -0
- package/src/utils/fuzzyMatch.ts +8 -0
- package/src/utils/githubRegexes.ts +2 -0
- package/src/utils/hashArrayBuffer.ts +6 -0
- package/src/utils/log.ts +9 -0
- package/src/utils/loraTag.ts +10 -0
- package/src/utils/printArkResultInConsole.ts +16 -0
- package/src/utils/softValidate.ts +8 -0
- package/src/utils/stringifyReadable.ts +32 -0
- package/src/utils/toposort.ts +59 -0
- package/src/utils/tryExtracting.ts +41 -0
- package/src/utils/writeFile.ts +16 -0
- package/src/vars/ComfyVars.ts +531 -0
- package/src/vars/DefinedWorkflow.ts +112 -0
- package/src/vars/loraKeywords.ts +56 -0
- package/dist/index.d.mts +0 -74
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
- package/readme.md +0 -40
package/dist/cli.js
ADDED
|
@@ -0,0 +1,764 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { n as logInfo } from "./log-CdfgILde.js";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "pathe";
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
//#region src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts
|
|
7
|
+
/** having a bunch of sensible default will help slightly */
|
|
8
|
+
function getUnionNameBasedOnFirstFoundEnumName(enumName, hash, hashContent) {
|
|
9
|
+
if (enumName === "KSampler.sampler_name") return "E_SamplerName";
|
|
10
|
+
if (enumName === "KSampler.scheduler") return "E_SchedulerName";
|
|
11
|
+
if (enumName === "CheckpointLoaderSimple.ckpt_name") return "E_CkptName";
|
|
12
|
+
if (enumName === "VAELoader.vae_name") return "E_VaeName";
|
|
13
|
+
if (enumName === "LoraLoader.lora_name") return "E_LoraName";
|
|
14
|
+
if (enumName === "LatentUpscale.upscale_method") return "E_LatentUpscaleMethod";
|
|
15
|
+
if (enumName === "ImageScale.upscale_method") return "E_ImageUpscaleMethod";
|
|
16
|
+
if (enumName === "LoadImage.image") return "E_Image";
|
|
17
|
+
if (enumName === "LoadImageMask.channel") return "E_Channel";
|
|
18
|
+
if (enumName === "KSamplerAdvanced.add_noise") return "E_EnableOrDisable";
|
|
19
|
+
if (enumName === "LatentRotate.rotation") return "E_Rotation";
|
|
20
|
+
if (enumName === "LatentFlip.flip_method") return "E_FlipMethod";
|
|
21
|
+
if (enumName === "CLIPLoader.type") return "E_ClipType";
|
|
22
|
+
if (enumName === "UNETLoader.weight_dtype") return "E_WeightDType";
|
|
23
|
+
if (enumName === "DualCLIPLoader.type") return "E_DualClipType";
|
|
24
|
+
if (enumName === "CheckpointLoader.config_name") return "E_CkptConfigName";
|
|
25
|
+
if (enumName === "civitai_comfy_nodes.CivitAI_Checkpoint_Loader.ckpt_name") return "E_CivitAICkptName";
|
|
26
|
+
if (enumName === "Impact-Pack.SAMDetectorCombined.detection_hint") return "E_ImpactDetectionHint";
|
|
27
|
+
if (hashContent === "false|true") return "E_TrueOrFalse";
|
|
28
|
+
if (hashContent === "CPU|GPU") return "E_CpuOrGpu";
|
|
29
|
+
return "E_" + hash;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/sdk-generator/_pythonModuleToNamespace.ts
|
|
33
|
+
function pythonModuleToPrefix(pythonModule) {
|
|
34
|
+
if (pythonModule === "nodes") return "";
|
|
35
|
+
if (pythonModule.startsWith("comfy_extras.")) return "";
|
|
36
|
+
if (pythonModule.startsWith("comfy_api_nodes.")) return pythonModule.replace("comfy_api_nodes.", "api.");
|
|
37
|
+
if (pythonModule.startsWith("custom_nodes.")) return pythonModule.replace(/^custom_nodes\./i, "").replace(/^comfyui[-_]/i, "").replace(/[-_]comfyui$/i, "").replace(/^comfy[-_]/i, "").replace(/[-_]comfy$/i, "").replace(/^nodes[-_]/i, "").replace(/[-_]node[-_]suite$/i, "") + ".";
|
|
38
|
+
console.warn(`[comfy-ts] unexpected pythonModule "${pythonModule}", using it as prefix as-is`);
|
|
39
|
+
return `${pythonModule}.`;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/sdk-generator/_toQualifiedNodeKey.ts
|
|
43
|
+
const toQualifiedNodeKey = (pythonModule, nameInComfy) => {
|
|
44
|
+
return `${pythonModuleToPrefix(pythonModule)}${nameInComfy}`;
|
|
45
|
+
};
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/utils/CodeBuffer.ts
|
|
48
|
+
/** this class is used to buffer text and then write it to a file */
|
|
49
|
+
var CodeBuffer = class {
|
|
50
|
+
constructor(_indent = 0, lines = []) {
|
|
51
|
+
this._indent = _indent;
|
|
52
|
+
this.tab = " ";
|
|
53
|
+
this.content = "";
|
|
54
|
+
this.newLine = () => this.content += "\n";
|
|
55
|
+
this.line = (...txts) => this.writeLine(txts.join(""));
|
|
56
|
+
this.append = (str) => this.content += str;
|
|
57
|
+
this.writeLine = (txt) => {
|
|
58
|
+
this.content += txt.split("\n").map((line) => repeatStr(this._indent, this.tab) + line).join("\n") + "\n";
|
|
59
|
+
return this;
|
|
60
|
+
};
|
|
61
|
+
this.w = (txt, opts = { if: true }) => {
|
|
62
|
+
if (opts.if) this.writeLine(txt);
|
|
63
|
+
};
|
|
64
|
+
this.indent = () => this._indent++;
|
|
65
|
+
this.deindent = () => this._indent--;
|
|
66
|
+
this.indented = (fn) => {
|
|
67
|
+
this._indent++;
|
|
68
|
+
fn();
|
|
69
|
+
this._indent--;
|
|
70
|
+
};
|
|
71
|
+
this.bar = (text) => this.w(renderBar(text, "// "));
|
|
72
|
+
for (const line of lines) this.writeLine(line);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const repeatStr = (x, str) => {
|
|
76
|
+
let out = "";
|
|
77
|
+
for (let i = 0; i < x; i++) out += str;
|
|
78
|
+
return out;
|
|
79
|
+
};
|
|
80
|
+
const renderBar = (text, prefix = "") => {
|
|
81
|
+
const ___bar___ = "=============================================================================";
|
|
82
|
+
return `${prefix}|${___bar___}|\n${prefix}| ${text} ${repeatStr(77 - text.length - 4, " ")} |\n${prefix}|${___bar___}|`;
|
|
83
|
+
};
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/utils/escapeJSKey.ts
|
|
86
|
+
const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
87
|
+
const isValidJSKey = (s) => {
|
|
88
|
+
return regex.test(s);
|
|
89
|
+
};
|
|
90
|
+
const escapeJSKey = (s) => {
|
|
91
|
+
if (typeof s !== "string") return "string";
|
|
92
|
+
if (!isValidJSKey(s)) return `"${s}"`;
|
|
93
|
+
return s;
|
|
94
|
+
};
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/sdk-generator/Primitives.ts
|
|
97
|
+
const ComfyPrimitiveMapping = {
|
|
98
|
+
BOOLEAN: "boolean",
|
|
99
|
+
FLOAT: "number",
|
|
100
|
+
INT: "number",
|
|
101
|
+
STRING: "string"
|
|
102
|
+
};
|
|
103
|
+
const ComfyPrimitives = Object.keys(ComfyPrimitiveMapping);
|
|
104
|
+
const ComfyDefaultNodeWhenUnknown_Name = "UnknownNodeXX";
|
|
105
|
+
const ComfyDefaultNodeWhenUnknown_Schema = {
|
|
106
|
+
category: "test",
|
|
107
|
+
input: {},
|
|
108
|
+
output: [],
|
|
109
|
+
description: "This is a test node",
|
|
110
|
+
output_name: [],
|
|
111
|
+
display_name: "UnknownNodeXX",
|
|
112
|
+
name: "UnknownNodeXX",
|
|
113
|
+
output_is_list: [],
|
|
114
|
+
output_node: false,
|
|
115
|
+
python_module: "nodes"
|
|
116
|
+
};
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/sdk-generator/ComfyNodeSchema.ts
|
|
119
|
+
var ComfyNodeSchema = class {
|
|
120
|
+
get singleOutputs() {
|
|
121
|
+
if (this._singleOutputs != null) return this._singleOutputs;
|
|
122
|
+
const x = {};
|
|
123
|
+
for (const i of this.outputs) x[i.typeName] = (x[i.typeName] ?? 0) + 1;
|
|
124
|
+
this._singleOutputs = this.outputs.filter((i) => x[i.typeName] === 1);
|
|
125
|
+
return this._singleOutputs;
|
|
126
|
+
}
|
|
127
|
+
constructor(raw, nameInComfy, nodeKey, category, inputs, outputs, pythonModule) {
|
|
128
|
+
this.raw = raw;
|
|
129
|
+
this.nameInComfy = nameInComfy;
|
|
130
|
+
this.nodeKey = nodeKey;
|
|
131
|
+
this.category = category;
|
|
132
|
+
this.inputs = inputs;
|
|
133
|
+
this.outputs = outputs;
|
|
134
|
+
this.pythonModule = pythonModule;
|
|
135
|
+
this._singleOutputs = null;
|
|
136
|
+
this.category = this.category.replaceAll("/", "_");
|
|
137
|
+
}
|
|
138
|
+
codegenUI() {
|
|
139
|
+
const b = new CodeBuffer();
|
|
140
|
+
const p = b.w;
|
|
141
|
+
p(` ${escapeJSKey(this.nodeKey)}: {`);
|
|
142
|
+
this.inputs.forEach((i, _ix) => {
|
|
143
|
+
if (i.isPrimitive) {
|
|
144
|
+
const tsType = ComfyPrimitiveMapping[i.typeName];
|
|
145
|
+
if (tsType == null) return console.log(`[🔶] invariant violation`);
|
|
146
|
+
p(` ${escapeJSKey(i.nameInComfy)}: { kind: '${tsType}', type: ${tsType} }`);
|
|
147
|
+
} else if (i.isEnum) p(` ${escapeJSKey(i.nameInComfy)}: { kind: 'enum', type: Union['${i.typeName}'] }`);
|
|
148
|
+
else p(` // ${escapeJSKey(i.nameInComfy)}: { kind: 'object', type: ${i.typeName} }`);
|
|
149
|
+
});
|
|
150
|
+
p(` }`);
|
|
151
|
+
return b.content;
|
|
152
|
+
}
|
|
153
|
+
renderOpts(opts) {
|
|
154
|
+
if (opts == null) return null;
|
|
155
|
+
if (typeof opts === "string") return null;
|
|
156
|
+
let out = "/**";
|
|
157
|
+
if (opts.default != null) out += ` default=${JSON.stringify(opts.default)}`;
|
|
158
|
+
if (opts.min != null) out += ` min=${JSON.stringify(opts.min)}`;
|
|
159
|
+
if (opts.max != null) out += ` max=${JSON.stringify(opts.max)}`;
|
|
160
|
+
if (opts.step != null) out += ` step=${JSON.stringify(opts.step)}`;
|
|
161
|
+
out += " */";
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
const wrapQuote = (s) => {
|
|
166
|
+
if (s.includes("'")) return `"${s}"`;
|
|
167
|
+
return `'${s}'`;
|
|
168
|
+
};
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/sdk-generator/comfyui-sdk-codegen.ts
|
|
171
|
+
/**
|
|
172
|
+
* convert a host id to the namespace name it gets inside the global `Comfy` namespace
|
|
173
|
+
* e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
|
|
174
|
+
*/
|
|
175
|
+
function hostIdToNamespace(hostId) {
|
|
176
|
+
const ns = hostId.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
177
|
+
if (ns.length === 0) throw new Error(`cannot derive a namespace from host id "${hostId}"`);
|
|
178
|
+
return /^[0-9]/.test(ns) ? `Host${ns}` : ns;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* emit the typed SDK for one host:
|
|
182
|
+
*
|
|
183
|
+
* declare global {
|
|
184
|
+
* namespace Comfy {
|
|
185
|
+
* namespace <HostNs> { IN / OUT / Node / Builder / Slots / Accepts / Union / ... }
|
|
186
|
+
* interface Hosts { '<host-id>': <HostNs>.Sdk }
|
|
187
|
+
* }
|
|
188
|
+
* }
|
|
189
|
+
*/
|
|
190
|
+
function codegenSDK(opts) {
|
|
191
|
+
const ns = hostIdToNamespace(opts.hostId);
|
|
192
|
+
const packageName = opts.packageName ?? "comfy-ts";
|
|
193
|
+
const b = new CodeBuffer();
|
|
194
|
+
const p = b.w;
|
|
195
|
+
p(`/** generated by comfy-ts for host "${opts.hostId}" — do not edit */`);
|
|
196
|
+
p(``);
|
|
197
|
+
p(`import type { ComfyNode, ComfyNodeOutput, ComfyNodeMetadata, ComfyNodeSchemaJSON } from '${packageName}'`);
|
|
198
|
+
p(``);
|
|
199
|
+
p(`declare global {`);
|
|
200
|
+
b.indent();
|
|
201
|
+
p(`namespace Comfy {`);
|
|
202
|
+
b.indent();
|
|
203
|
+
p(`namespace ${ns} {`);
|
|
204
|
+
b.indent();
|
|
205
|
+
p(`// #region PythonModules`);
|
|
206
|
+
p(`/** list of all python modules installed on this host */`);
|
|
207
|
+
p(`export type PythonModules =`);
|
|
208
|
+
b.indent();
|
|
209
|
+
const pythonModulesArr = Array.from(this.pythonModules.entries()).toSorted((a, b) => a[0].localeCompare(b[0]));
|
|
210
|
+
for (const [k, v] of pythonModulesArr) {
|
|
211
|
+
p(`/**`);
|
|
212
|
+
p(`* Nodes: ${v.join(", ")}`);
|
|
213
|
+
p(`*/`);
|
|
214
|
+
p(`| ${wrapQuote(k)}`);
|
|
215
|
+
}
|
|
216
|
+
b.deindent();
|
|
217
|
+
p(`// #endregion`);
|
|
218
|
+
const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
|
|
219
|
+
p(`interface IN {`);
|
|
220
|
+
b.indent();
|
|
221
|
+
for (const n of nodes) {
|
|
222
|
+
p(`${escapeJSKey(n.nodeKey)}: {`);
|
|
223
|
+
for (const i of n.inputs) {
|
|
224
|
+
const opts_ = typeof i.opts === "string" ? null : i.opts;
|
|
225
|
+
let type = `Accepts[${JSON.stringify(i.typeName)}]`;
|
|
226
|
+
const comboOptions = i.typeName === "COMBO" && Array.isArray(opts_?.options) ? opts_.options.filter((o) => typeof o === "string" || typeof o === "number" || typeof o === "boolean") : [];
|
|
227
|
+
if (comboOptions.length > 0) type = `${comboOptions.map((o) => JSON.stringify(o)).join(" | ")} | ${type}`;
|
|
228
|
+
else if (opts_ && !i.isPrimitive && !i.isEnum) {
|
|
229
|
+
if (typeof opts_.default === "string" || opts_.placeholder != null || opts_.multiline != null) type = `string | ${type}`;
|
|
230
|
+
else if (typeof opts_.default === "number") type = `number | ${type}`;
|
|
231
|
+
else if (typeof opts_.default === "boolean") type = `boolean | ${type}`;
|
|
232
|
+
}
|
|
233
|
+
if (opts_) {
|
|
234
|
+
const rendered = n.renderOpts(opts_);
|
|
235
|
+
if (rendered) p(` ${rendered}`);
|
|
236
|
+
}
|
|
237
|
+
const canBeOmmited = opts_?.default !== void 0 || !i.required;
|
|
238
|
+
p(` ${i.nameInComfyEscaped}${canBeOmmited ? "?" : ""}: ${type}`);
|
|
239
|
+
}
|
|
240
|
+
p(`},`);
|
|
241
|
+
}
|
|
242
|
+
b.deindent();
|
|
243
|
+
p("}");
|
|
244
|
+
p("");
|
|
245
|
+
p(`interface OUT {`);
|
|
246
|
+
b.indent();
|
|
247
|
+
for (const n of nodes) {
|
|
248
|
+
p(`${escapeJSKey(n.nodeKey)}: {`);
|
|
249
|
+
n.outputs.forEach((i, ix) => {
|
|
250
|
+
p(` ${escapeJSKey(i.outKey)}: ComfyNodeOutput<'${i.typeName}', ${ix}>,`);
|
|
251
|
+
});
|
|
252
|
+
p(`}`);
|
|
253
|
+
}
|
|
254
|
+
b.deindent();
|
|
255
|
+
p("}");
|
|
256
|
+
p(`interface Node {`);
|
|
257
|
+
for (const n of nodes) {
|
|
258
|
+
p(` ${escapeJSKey(n.nodeKey)}: ComfyNode<IN[${JSON.stringify(n.nodeKey)}], OUT[${JSON.stringify(n.nodeKey)}]> & {`);
|
|
259
|
+
for (const hassingle of n.singleOutputs) p(` ${escapeJSKey(`_${hassingle.typeName}`)}: ComfyNodeOutput<'${hassingle.typeName}'>`);
|
|
260
|
+
p(` }`);
|
|
261
|
+
}
|
|
262
|
+
p("}");
|
|
263
|
+
p(`interface Builder {`);
|
|
264
|
+
for (const n of nodes) {
|
|
265
|
+
const baseDescription = `displayName="${n.raw.display_name}" category="${n.category}" name="${n.nameInComfy}" output=[${n.outputs.map((o) => o.outKey).join(", ")}]`;
|
|
266
|
+
if (n.raw.description) {
|
|
267
|
+
p(` /**`);
|
|
268
|
+
p(n.raw.description.split("\n").map((i) => ` * ${i}`).join("\n"));
|
|
269
|
+
p(` * ${baseDescription}`);
|
|
270
|
+
p(` **/`);
|
|
271
|
+
} else p(` /** ${baseDescription} */`);
|
|
272
|
+
p(` ${escapeJSKey(n.nodeKey)}(p: IN[${JSON.stringify(n.nodeKey)}], meta?: ComfyNodeMetadata): Node[${JSON.stringify(n.nodeKey)}]`);
|
|
273
|
+
}
|
|
274
|
+
p(`}`);
|
|
275
|
+
p(`interface Slots {`);
|
|
276
|
+
for (const e of this.knownUnionByHash.values()) {
|
|
277
|
+
p(" // " + e.unionName);
|
|
278
|
+
for (const alias of e.enumNames) p(` ${escapeJSKey(alias)}: Union['${e.unionName}']`);
|
|
279
|
+
}
|
|
280
|
+
p(`}`);
|
|
281
|
+
p(`type Embeddings = ${this.data.embeddings.map((e) => wrapQuote(e)).join(" | ") || "\"\""}`);
|
|
282
|
+
const slotTypes = [...this.knownSlotTypes.values()].map((comfyType) => ({
|
|
283
|
+
comfyType,
|
|
284
|
+
tsType: this.toTSType(comfyType),
|
|
285
|
+
tsType2: this.toAcceptsType(comfyType)
|
|
286
|
+
})).sort((a, b) => b.tsType.length - a.tsType.length);
|
|
287
|
+
p("");
|
|
288
|
+
p("interface Producer {");
|
|
289
|
+
b.indent();
|
|
290
|
+
for (const tp of slotTypes) {
|
|
291
|
+
const allProducingNodes = this.nodesByProduction[tp.comfyType];
|
|
292
|
+
if (allProducingNodes) p(`${escapeJSKey(tp.comfyType)}: Pick<Builder, ${allProducingNodes.map((i) => `'${i.nodeKey}'`).join(" | ")}>`);
|
|
293
|
+
else p(`${escapeJSKey(tp.comfyType)}: {}, // no node can output this type.`);
|
|
294
|
+
}
|
|
295
|
+
b.deindent();
|
|
296
|
+
p("}");
|
|
297
|
+
p(`interface Accepts {`);
|
|
298
|
+
b.indent();
|
|
299
|
+
p("// injected bottom type (broken/null input specs land here)");
|
|
300
|
+
p(`INVALID_null: any`);
|
|
301
|
+
p("");
|
|
302
|
+
p("// named slot types: everything an input of that type accepts");
|
|
303
|
+
for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
|
|
304
|
+
p("");
|
|
305
|
+
p("// enum unions: literal values or an output carrying one");
|
|
306
|
+
for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
|
|
307
|
+
b.deindent();
|
|
308
|
+
p(`}\n`);
|
|
309
|
+
p("interface Union {");
|
|
310
|
+
for (const e of this.knownUnionByHash.values()) if (e.values.length > 0) {
|
|
311
|
+
p(` // ${JSON.stringify(e.enumNames)}`);
|
|
312
|
+
p(` ${e.unionName}: ${e.values.map((v) => `${JSON.stringify(v)}`).join(" | ")}`);
|
|
313
|
+
} else p(` ${e.unionName}: '🔴' // never`);
|
|
314
|
+
p("}");
|
|
315
|
+
p(`export interface HasSingle {`);
|
|
316
|
+
for (const t of slotTypes) p(` ${escapeJSKey(t.comfyType)}: { '_${t.comfyType}': ${t.tsType} }`);
|
|
317
|
+
p(`}`);
|
|
318
|
+
for (const t of this.enumsAppearingInOutput.values()) p(`export interface HasSingle_${t} { _${t}: Union['${t}'] }`);
|
|
319
|
+
p(`export type Schemas = { [k in NodeType]: ComfyNodeSchemaJSON }`);
|
|
320
|
+
p(`export type NodeType = ${this.nodes.map((i) => `'${i.nodeKey}'`).join(" | ")}`);
|
|
321
|
+
p(``);
|
|
322
|
+
p(`/** everything above, packaged for the Comfy.Hosts registry */`);
|
|
323
|
+
p(`interface Sdk {`);
|
|
324
|
+
p(` IN: IN`);
|
|
325
|
+
p(` OUT: OUT`);
|
|
326
|
+
p(` Node: Node`);
|
|
327
|
+
p(` Builder: Builder`);
|
|
328
|
+
p(` Slots: Slots`);
|
|
329
|
+
p(` Accepts: Accepts`);
|
|
330
|
+
p(` Union: Union`);
|
|
331
|
+
p(` Producer: Producer`);
|
|
332
|
+
p(` Embeddings: Embeddings`);
|
|
333
|
+
p(` Schemas: Schemas`);
|
|
334
|
+
p(` NodeType: NodeType`);
|
|
335
|
+
p(`}`);
|
|
336
|
+
b.deindent();
|
|
337
|
+
p(`}`);
|
|
338
|
+
p(``);
|
|
339
|
+
p(`interface Hosts {`);
|
|
340
|
+
p(` ${wrapQuote(opts.hostId)}: ${ns}.Sdk`);
|
|
341
|
+
p(`}`);
|
|
342
|
+
b.deindent();
|
|
343
|
+
p("}");
|
|
344
|
+
b.deindent();
|
|
345
|
+
p("}");
|
|
346
|
+
p(``);
|
|
347
|
+
p(`export {}`);
|
|
348
|
+
return b.content;
|
|
349
|
+
}
|
|
350
|
+
//#endregion
|
|
351
|
+
//#region src/sdk-generator/comfyui-types.ts
|
|
352
|
+
const asComfyNodeSlotTypeName = (x) => x;
|
|
353
|
+
const asComfyNodeSlotName = (x) => x;
|
|
354
|
+
//#endregion
|
|
355
|
+
//#region src/sdk-generator/ComfySchema.ts
|
|
356
|
+
/**
|
|
357
|
+
* ONE host's schema: the parsed view of its object_info.json + embeddings.
|
|
358
|
+
* Owns union dedup (by sha1 of values), node indexing, and the per-host
|
|
359
|
+
* sdk codegen (`codegenDTS`).
|
|
360
|
+
*/
|
|
361
|
+
var ComfySchema = class {
|
|
362
|
+
constructor(data) {
|
|
363
|
+
this.data = data;
|
|
364
|
+
this.codegenDTS = codegenSDK.bind(this);
|
|
365
|
+
this.isInvalid = false;
|
|
366
|
+
this.knownSlotTypes = /* @__PURE__ */ new Set();
|
|
367
|
+
this.knownUnionBySlotName = /* @__PURE__ */ new Map();
|
|
368
|
+
this.knownUnionByHash = /* @__PURE__ */ new Map();
|
|
369
|
+
this.knownUnionByName = /* @__PURE__ */ new Map();
|
|
370
|
+
this.nodes = [];
|
|
371
|
+
this.pythonModuleByNodeKey = /* @__PURE__ */ new Map();
|
|
372
|
+
this.pythonModuleByNodeNameInComfy = /* @__PURE__ */ new Map();
|
|
373
|
+
this.nodesByNameInComfy = {};
|
|
374
|
+
this.nodesByKey = {};
|
|
375
|
+
this.nodesByProduction = {};
|
|
376
|
+
this.enumsAppearingInOutput = /* @__PURE__ */ new Set();
|
|
377
|
+
this.pythonModules = /* @__PURE__ */ new Map();
|
|
378
|
+
this.processSlot = (p) => {
|
|
379
|
+
const enumValues = [];
|
|
380
|
+
for (const enumValue of p.comfyUnionDef) if (typeof enumValue === "string") enumValues.push(enumValue);
|
|
381
|
+
else if (typeof enumValue === "boolean") enumValues.push(enumValue);
|
|
382
|
+
else if (typeof enumValue === "number") enumValues.push(enumValue);
|
|
383
|
+
else enumValues.push(enumValue.content);
|
|
384
|
+
const hashContent = enumValues.length === 0 ? `[[empty]]` : enumValues.sort().join("|");
|
|
385
|
+
const hash = crypto.createHash("sha1").update(hashContent).digest("hex").slice(0, 8);
|
|
386
|
+
let unionInfo = this.knownUnionByHash.get(hash);
|
|
387
|
+
if (unionInfo == null) {
|
|
388
|
+
const unionName = getUnionNameBasedOnFirstFoundEnumName(p.slotName, hash, hashContent);
|
|
389
|
+
unionInfo = {
|
|
390
|
+
hash,
|
|
391
|
+
unionName,
|
|
392
|
+
values: enumValues,
|
|
393
|
+
enumNames: []
|
|
394
|
+
};
|
|
395
|
+
this.knownUnionByHash.set(hash, unionInfo);
|
|
396
|
+
this.knownUnionByName.set(unionName, unionInfo);
|
|
397
|
+
}
|
|
398
|
+
unionInfo.enumNames.push(p.slotName);
|
|
399
|
+
this.knownUnionBySlotName.set(p.slotName, unionInfo);
|
|
400
|
+
return unionInfo;
|
|
401
|
+
};
|
|
402
|
+
this.RUN_BASIC_CHECKS = () => {
|
|
403
|
+
const numNodesInSource = Object.keys(this.data.spec).length;
|
|
404
|
+
const numNodesInSchema = this.nodes.length - 1;
|
|
405
|
+
if (numNodesInSource !== numNodesInSchema) console.log(`🔴 parsed ${numNodesInSchema} nodes but object_info has ${numNodesInSource}`);
|
|
406
|
+
};
|
|
407
|
+
this.getLoras = (filter) => {
|
|
408
|
+
const all = this.stringValues("LoraLoader.lora_name");
|
|
409
|
+
return filter == null ? all : all.filter((n) => filter.test(n));
|
|
410
|
+
};
|
|
411
|
+
this.getImages = () => {
|
|
412
|
+
return this.stringValues("LoadImage.image");
|
|
413
|
+
};
|
|
414
|
+
this.unsafely_addImageInSchemaWithoutReloading = (imgName) => {
|
|
415
|
+
const enumInfo = this.knownUnionBySlotName.get(asComfyNodeSlotName("LoadImage.image"));
|
|
416
|
+
if (enumInfo == null) throw new Error(`LoadImage.image not found`);
|
|
417
|
+
enumInfo.values.push(imgName);
|
|
418
|
+
};
|
|
419
|
+
this.getCheckpoints = () => {
|
|
420
|
+
return this.stringValues("CheckpointLoaderSimple.ckpt_name");
|
|
421
|
+
};
|
|
422
|
+
this.parse();
|
|
423
|
+
}
|
|
424
|
+
update(data) {
|
|
425
|
+
const prev = {
|
|
426
|
+
spec: this.data.spec,
|
|
427
|
+
embeddings: this.data.embeddings
|
|
428
|
+
};
|
|
429
|
+
Object.assign(this.data, data);
|
|
430
|
+
try {
|
|
431
|
+
this.parse();
|
|
432
|
+
this.isInvalid = false;
|
|
433
|
+
} catch (error) {
|
|
434
|
+
console.error(`❌ [ComfySchema.update] bad schema — keeping the previous one`, error);
|
|
435
|
+
this.data = prev;
|
|
436
|
+
try {
|
|
437
|
+
this.parse();
|
|
438
|
+
} catch {}
|
|
439
|
+
this.isInvalid = true;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
/** number of nodes in the current schema (quick way to check your instance infos) */
|
|
443
|
+
get size() {
|
|
444
|
+
return Object.keys(this.data.spec).length;
|
|
445
|
+
}
|
|
446
|
+
parse() {
|
|
447
|
+
this.knownSlotTypes.clear();
|
|
448
|
+
this.knownUnionBySlotName.clear();
|
|
449
|
+
this.knownUnionByHash.clear();
|
|
450
|
+
this.knownUnionByName.clear();
|
|
451
|
+
this.nodes = [];
|
|
452
|
+
this.pythonModuleByNodeKey.clear();
|
|
453
|
+
this.pythonModuleByNodeNameInComfy.clear();
|
|
454
|
+
this.nodesByNameInComfy = {};
|
|
455
|
+
this.nodesByKey = {};
|
|
456
|
+
this.nodesByProduction = {};
|
|
457
|
+
this.enumsAppearingInOutput.clear();
|
|
458
|
+
this.pythonModules.clear();
|
|
459
|
+
if (this.data.embeddings.length > 0 || Object.keys(this.data.spec).length > 0) this.log(`parsing ComfyUI object_info.json`);
|
|
460
|
+
const entries = Object.entries(this.data.spec);
|
|
461
|
+
entries.push([ComfyDefaultNodeWhenUnknown_Name, ComfyDefaultNodeWhenUnknown_Schema]);
|
|
462
|
+
for (const [KK, VV] of entries) {
|
|
463
|
+
const pythonModule = VV.python_module;
|
|
464
|
+
const prev = this.pythonModules.get(pythonModule);
|
|
465
|
+
if (prev == null) this.pythonModules.set(pythonModule, [KK]);
|
|
466
|
+
else prev.push(KK);
|
|
467
|
+
const nodeNameInComfy = KK;
|
|
468
|
+
const nodeDef = VV;
|
|
469
|
+
const nodeKey = toQualifiedNodeKey(pythonModule, nodeNameInComfy);
|
|
470
|
+
if (typeof nodeDef.output === "string") {
|
|
471
|
+
console.log(`[❌ ERROR] nodeDef ${nodeDef.name} has an invalid output definition: ${JSON.stringify(nodeDef.output)}`);
|
|
472
|
+
nodeDef.output = [];
|
|
473
|
+
}
|
|
474
|
+
this.pythonModuleByNodeKey.set(nodeKey, pythonModule);
|
|
475
|
+
this.pythonModuleByNodeNameInComfy.set(nodeNameInComfy, pythonModule);
|
|
476
|
+
const inputs = [];
|
|
477
|
+
const outputs = [];
|
|
478
|
+
const node = new ComfyNodeSchema(VV, nodeNameInComfy, nodeKey, nodeDef.category, inputs, outputs, pythonModule);
|
|
479
|
+
this.nodesByNameInComfy[nodeNameInComfy] = node;
|
|
480
|
+
this.nodesByKey[nodeKey] = node;
|
|
481
|
+
this.nodes.push(node);
|
|
482
|
+
const nameCountDict = {};
|
|
483
|
+
for (const [ix, slotType] of nodeDef.output.entries()) {
|
|
484
|
+
const outputNameInComfy = nodeDef.output_name[ix] || (typeof slotType === "string" ? slotType : `input_${ix}`);
|
|
485
|
+
const at = nameCountDict[outputNameInComfy] ??= 0;
|
|
486
|
+
const outKeyValue = at === 0 ? outputNameInComfy : `${outputNameInComfy}_${at}`;
|
|
487
|
+
nameCountDict[outputNameInComfy]++;
|
|
488
|
+
let slotTypeName;
|
|
489
|
+
const outputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${outKeyValue}.OUT`);
|
|
490
|
+
if (typeof slotType === "string") {
|
|
491
|
+
slotTypeName = asComfyNodeSlotTypeName(slotType);
|
|
492
|
+
this.knownSlotTypes.add(slotTypeName);
|
|
493
|
+
} else if (Array.isArray(slotType)) {
|
|
494
|
+
slotTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
495
|
+
pythonModule,
|
|
496
|
+
slotName: outputSlotName,
|
|
497
|
+
comfyUnionDef: slotType
|
|
498
|
+
}).unionName);
|
|
499
|
+
this.enumsAppearingInOutput.add(slotTypeName);
|
|
500
|
+
} else throw new Error(`invalid output ${ix} "${slotType}" in node "${nodeNameInComfy}"`);
|
|
501
|
+
const arr = this.nodesByProduction[slotTypeName];
|
|
502
|
+
if (arr == null) this.nodesByProduction[slotTypeName] = [node];
|
|
503
|
+
else arr.push(node);
|
|
504
|
+
outputs.push({
|
|
505
|
+
slotName: outputSlotName,
|
|
506
|
+
typeName: slotTypeName,
|
|
507
|
+
nameInComfy: outputNameInComfy,
|
|
508
|
+
outKey: outKeyValue,
|
|
509
|
+
isPrimitive: false
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
const optionalInputs = Object.entries(nodeDef.input?.optional ?? {}).map(([name, spec]) => ({
|
|
513
|
+
required: false,
|
|
514
|
+
name,
|
|
515
|
+
spec
|
|
516
|
+
}));
|
|
517
|
+
const allInputs = [...Object.entries(nodeDef.input?.required ?? {}).map(([name, spec]) => ({
|
|
518
|
+
required: true,
|
|
519
|
+
name,
|
|
520
|
+
spec
|
|
521
|
+
})).filter((i) => optionalInputs.find((oi) => oi.name === i.name) == null), ...optionalInputs];
|
|
522
|
+
for (const ipt of allInputs) {
|
|
523
|
+
const inputNameInComfy = ipt.name;
|
|
524
|
+
const typeDef = ipt.spec;
|
|
525
|
+
const slotType = typeDef[0];
|
|
526
|
+
const slotOpts = typeDef[1];
|
|
527
|
+
let inputTypeName;
|
|
528
|
+
const inputSlotName = asComfyNodeSlotName(`${node.nodeKey}.${inputNameInComfy}`);
|
|
529
|
+
if (slotType == null) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
530
|
+
pythonModule,
|
|
531
|
+
slotName: inputSlotName,
|
|
532
|
+
comfyUnionDef: ["❌"]
|
|
533
|
+
}).unionName);
|
|
534
|
+
else if (typeof slotType === "string") {
|
|
535
|
+
inputTypeName = asComfyNodeSlotTypeName(slotType);
|
|
536
|
+
this.knownSlotTypes.add(inputTypeName);
|
|
537
|
+
} else if (Array.isArray(slotType)) inputTypeName = asComfyNodeSlotTypeName(this.processSlot({
|
|
538
|
+
pythonModule,
|
|
539
|
+
slotName: inputSlotName,
|
|
540
|
+
comfyUnionDef: slotType
|
|
541
|
+
}).unionName);
|
|
542
|
+
else throw new Error(`invalid schema (${JSON.stringify(slotType)}) for input "${ipt.name}" in node "${nodeNameInComfy}" (type: ${typeof slotType}; expected: Array | string)`);
|
|
543
|
+
node.inputs.push({
|
|
544
|
+
slotName: inputSlotName,
|
|
545
|
+
required: ipt.required,
|
|
546
|
+
nameInComfy: inputNameInComfy,
|
|
547
|
+
nameInComfyEscaped: escapeJSKey(inputNameInComfy),
|
|
548
|
+
typeName: inputTypeName,
|
|
549
|
+
opts: slotOpts,
|
|
550
|
+
isPrimitive: ComfyPrimitives.includes(inputTypeName),
|
|
551
|
+
isEnum: this.knownUnionByName.has(inputTypeName),
|
|
552
|
+
index: node.inputs.length
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
log(...args) {
|
|
558
|
+
logInfo(`[👅]: ${args.join(" ")}`);
|
|
559
|
+
}
|
|
560
|
+
toTSType(t) {
|
|
561
|
+
if (t === "*") return `string | number | boolean | ComfyNodeOutput<string, number>`;
|
|
562
|
+
return ComfyPrimitiveMapping[t] ? `${ComfyPrimitiveMapping[t]} | ComfyNodeOutput<'${t}'>` : `ComfyNodeOutput<'${t}'>`;
|
|
563
|
+
}
|
|
564
|
+
toAcceptsType(t) {
|
|
565
|
+
return `ComfyNodeOutput<'${t}'>`;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* every possible value for a given slot, straight from the live schema.
|
|
569
|
+
* e.g. schema.values('LoraLoader.lora_name') -> all loras on this host
|
|
570
|
+
*/
|
|
571
|
+
values(slotName) {
|
|
572
|
+
return this.knownUnionBySlotName.get(asComfyNodeSlotName(slotName))?.values ?? [];
|
|
573
|
+
}
|
|
574
|
+
/** string values only (most enums are), for quick discovery */
|
|
575
|
+
stringValues(slotName) {
|
|
576
|
+
return this.values(slotName).filter((v) => typeof v === "string");
|
|
577
|
+
}
|
|
578
|
+
hasEmbedding(embedding) {
|
|
579
|
+
return this.data.embeddings.includes(embedding);
|
|
580
|
+
}
|
|
581
|
+
hasLora(loraName) {
|
|
582
|
+
return this.getLoras().includes(loraName);
|
|
583
|
+
}
|
|
584
|
+
hasImage(imgName) {
|
|
585
|
+
return this.getImages().includes(imgName);
|
|
586
|
+
}
|
|
587
|
+
hasCheckpoint(ckptName) {
|
|
588
|
+
return this.getCheckpoints().includes(ckptName);
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
//#endregion
|
|
592
|
+
//#region src/utils/stringifyReadable.ts
|
|
593
|
+
const tab = " ";
|
|
594
|
+
function readableStringify(obj, maxLevel = 3, level = 0) {
|
|
595
|
+
if (level > maxLevel) return JSON.stringify(obj);
|
|
596
|
+
if (typeof obj !== "object" || obj === null) return JSON.stringify(obj);
|
|
597
|
+
const indent = " ".repeat(level + 1);
|
|
598
|
+
let result = "{\n";
|
|
599
|
+
const keys = Object.keys(obj);
|
|
600
|
+
for (let i = 0; i < keys.length; i++) {
|
|
601
|
+
const key = keys[i];
|
|
602
|
+
const value = obj[key];
|
|
603
|
+
if (value === void 0) continue;
|
|
604
|
+
const valueType = typeof value;
|
|
605
|
+
if (i > 0) result += ",";
|
|
606
|
+
const thisIndent = i > 0 ? indent.slice(1) : indent;
|
|
607
|
+
if (Array.isArray(value)) result += `${thisIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}`;
|
|
608
|
+
else if (valueType === "object" && value !== null) result += `${thisIndent}${JSON.stringify(key)}: ${readableStringify(value, maxLevel, level + 1)}`;
|
|
609
|
+
else {
|
|
610
|
+
const formattedValue = valueType === "string" ? JSON.stringify(value) : value;
|
|
611
|
+
result += `${thisIndent}${JSON.stringify(key)}: ${formattedValue}`;
|
|
612
|
+
}
|
|
613
|
+
result += "\n";
|
|
614
|
+
}
|
|
615
|
+
result += `${tab.repeat(Math.max(0, level))}}`;
|
|
616
|
+
return result;
|
|
617
|
+
}
|
|
618
|
+
//#endregion
|
|
619
|
+
//#region src/cli/gen.ts
|
|
620
|
+
async function runGen(args) {
|
|
621
|
+
const getFlag = (name) => {
|
|
622
|
+
const ix = args.indexOf(`--${name}`);
|
|
623
|
+
return ix >= 0 ? args[ix + 1] ?? null : null;
|
|
624
|
+
};
|
|
625
|
+
const hostUrl = getFlag("host") ?? "http://127.0.0.1:8188";
|
|
626
|
+
const id = getFlag("id");
|
|
627
|
+
if (id == null) {
|
|
628
|
+
console.error("[comfy-ts gen] 🔴 --id <host-id> is required (it names .comfy-ts/hosts/<id>/)");
|
|
629
|
+
return 1;
|
|
630
|
+
}
|
|
631
|
+
const fetchJSON = async (route) => {
|
|
632
|
+
for (const url of [`${hostUrl}/api${route}`, `${hostUrl}${route}`]) {
|
|
633
|
+
console.log(`[comfy-ts gen] fetching ${url} …`);
|
|
634
|
+
const res = await fetch(url);
|
|
635
|
+
if (!res.ok) continue;
|
|
636
|
+
if (!(res.headers.get("content-type") ?? "").includes("json")) continue;
|
|
637
|
+
return await res.json();
|
|
638
|
+
}
|
|
639
|
+
throw new Error(`GET ${route} failed on ${hostUrl} (tried /api${route} and ${route})`);
|
|
640
|
+
};
|
|
641
|
+
const spec = await fetchJSON("/object_info");
|
|
642
|
+
const embeddings = await fetchJSON("/embeddings").catch(() => []);
|
|
643
|
+
const dir = join(process.cwd(), ".comfy-ts", "hosts", id);
|
|
644
|
+
mkdirSync(dir, { recursive: true });
|
|
645
|
+
writeFileSync(join(dir, "object_info.json"), readableStringify(spec, 4), "utf8");
|
|
646
|
+
writeFileSync(join(dir, "embeddings.json"), JSON.stringify(embeddings), "utf8");
|
|
647
|
+
const parsed = new ComfySchema({
|
|
648
|
+
spec,
|
|
649
|
+
embeddings
|
|
650
|
+
});
|
|
651
|
+
const dts = parsed.codegenDTS({ hostId: id });
|
|
652
|
+
const outPath = join(dir, "sdk.d.ts");
|
|
653
|
+
writeFileSync(outPath, dts, "utf8");
|
|
654
|
+
console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`);
|
|
655
|
+
console.log(`[comfy-ts gen] add ".comfy-ts/hosts/**/sdk.d.ts" to your tsconfig "include" to activate the types`);
|
|
656
|
+
return 0;
|
|
657
|
+
}
|
|
658
|
+
//#endregion
|
|
659
|
+
//#region src/cli/outline.ts
|
|
660
|
+
function findDefaultSdk() {
|
|
661
|
+
const hostsDir = join(process.cwd(), ".comfy-ts", "hosts");
|
|
662
|
+
if (!existsSync(hostsDir)) return null;
|
|
663
|
+
for (const id of readdirSync(hostsDir)) {
|
|
664
|
+
const p = join(hostsDir, id, "sdk.d.ts");
|
|
665
|
+
if (existsSync(p)) return p;
|
|
666
|
+
}
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
function runOutline(args) {
|
|
670
|
+
const linesFlagIx = args.indexOf("--lines");
|
|
671
|
+
const maxLines = linesFlagIx >= 0 ? Number(args[linesFlagIx + 1] ?? 10) : null;
|
|
672
|
+
const sectionFlagIx = args.indexOf("--section");
|
|
673
|
+
const wantedSection = sectionFlagIx >= 0 ? args[sectionFlagIx + 1] : null;
|
|
674
|
+
const flagValueIxs = new Set([linesFlagIx + 1, sectionFlagIx + 1].filter((ix) => ix > 0));
|
|
675
|
+
const file = args.find((a, ix) => !a.startsWith("--") && !flagValueIxs.has(ix)) ?? findDefaultSdk();
|
|
676
|
+
if (file == null || !existsSync(file)) {
|
|
677
|
+
console.error("[sdk-outline] 🔴 no sdk.d.ts found; pass a path explicitly");
|
|
678
|
+
return 1;
|
|
679
|
+
}
|
|
680
|
+
const lines = readFileSync(file, "utf8").split("\n");
|
|
681
|
+
const sections = [];
|
|
682
|
+
const stack = [];
|
|
683
|
+
let depth = 0;
|
|
684
|
+
const declRe = /^\s*(?:export\s+)?(interface|namespace|type)\s+([A-Za-z0-9_$]+)/;
|
|
685
|
+
for (let i = 0; i < lines.length; i++) {
|
|
686
|
+
const line = lines[i] ?? "";
|
|
687
|
+
const m = depth <= 3 ? declRe.exec(line) : null;
|
|
688
|
+
const opens = (line.match(/{/g) ?? []).length;
|
|
689
|
+
const closes = (line.match(/}/g) ?? []).length;
|
|
690
|
+
if (m && (opens > 0 || m[1] === "type")) {
|
|
691
|
+
const sec = {
|
|
692
|
+
name: m[2] ?? "?",
|
|
693
|
+
kind: m[1] ?? "?",
|
|
694
|
+
start: i + 1,
|
|
695
|
+
end: i + 1,
|
|
696
|
+
depth
|
|
697
|
+
};
|
|
698
|
+
sections.push(sec);
|
|
699
|
+
if (opens > closes) stack.push(sec);
|
|
700
|
+
}
|
|
701
|
+
depth += opens - closes;
|
|
702
|
+
while (stack.length > 0 && depth <= (stack[stack.length - 1]?.depth ?? 0)) {
|
|
703
|
+
const closed = stack.pop();
|
|
704
|
+
if (closed) closed.end = i + 1;
|
|
705
|
+
}
|
|
706
|
+
const last = sections[sections.length - 1];
|
|
707
|
+
if (last && last.kind === "type" && stack[stack.length - 1] !== last) last.end = Math.max(last.end, i);
|
|
708
|
+
}
|
|
709
|
+
if (wantedSection) {
|
|
710
|
+
const sec = sections.find((s) => s.name === wantedSection);
|
|
711
|
+
if (sec == null) {
|
|
712
|
+
console.error(`[sdk-outline] 🔴 section "${wantedSection}" not found. Available: ${sections.map((s) => s.name).join(", ")}`);
|
|
713
|
+
return 1;
|
|
714
|
+
}
|
|
715
|
+
const body = lines.slice(sec.start - 1, maxLines ? Math.min(sec.end, sec.start - 1 + maxLines) : sec.end);
|
|
716
|
+
console.log(body.join("\n"));
|
|
717
|
+
if (maxLines && sec.end - sec.start + 1 > maxLines) console.log(`… (${sec.end - sec.start + 1 - maxLines} more lines, ends at line ${sec.end})`);
|
|
718
|
+
} else {
|
|
719
|
+
console.log(`${file} — ${lines.length} lines\n`);
|
|
720
|
+
for (const s of sections) {
|
|
721
|
+
const indent = " ".repeat(s.depth);
|
|
722
|
+
console.log(`${indent}${s.kind} ${s.name} [${s.start}-${s.end}] (${s.end - s.start + 1} lines)`);
|
|
723
|
+
if (maxLines) {
|
|
724
|
+
const body = lines.slice(s.start - 1, s.start - 1 + maxLines);
|
|
725
|
+
console.log(body.map((l) => `${indent} │ ${l.trim()}`).join("\n"));
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
return 0;
|
|
730
|
+
}
|
|
731
|
+
//#endregion
|
|
732
|
+
//#region src/cli/comfy-ts-cli.ts
|
|
733
|
+
const HELP = `comfy-ts — typed SDK codegen for ComfyUI
|
|
734
|
+
|
|
735
|
+
Usage:
|
|
736
|
+
comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188]
|
|
737
|
+
fetch object_info + embeddings from a live ComfyUI host and write
|
|
738
|
+
.comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}
|
|
739
|
+
|
|
740
|
+
comfy-ts outline [file] [--lines N] [--section Name]
|
|
741
|
+
outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)
|
|
742
|
+
|
|
743
|
+
comfy-ts tui [dir | workflow-module.ts]
|
|
744
|
+
interactive tweak & re-run over **/*.cflow.ts modules (exporting
|
|
745
|
+
host.defineWorkflow(...)); no arg scans cwd, a file arg preselects it
|
|
746
|
+
|
|
747
|
+
comfy-ts help
|
|
748
|
+
`;
|
|
749
|
+
async function main() {
|
|
750
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
751
|
+
if (cmd === "gen") return runGen(rest);
|
|
752
|
+
if (cmd === "outline") return runOutline(rest);
|
|
753
|
+
if (cmd === "tui") {
|
|
754
|
+
const { runTui } = await import("./run-tui-Io8Xea0L.js");
|
|
755
|
+
return runTui(rest);
|
|
756
|
+
}
|
|
757
|
+
console.log(HELP);
|
|
758
|
+
return cmd == null || cmd === "help" ? 0 : 1;
|
|
759
|
+
}
|
|
760
|
+
process.exitCode = await main();
|
|
761
|
+
//#endregion
|
|
762
|
+
export {};
|
|
763
|
+
|
|
764
|
+
//# sourceMappingURL=cli.js.map
|