comfy-ts 1.2.0 → 1.4.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/README.md +66 -0
- package/dist/DefinedWorkflow-C_QAxKr3.js +737 -0
- package/dist/DefinedWorkflow-C_QAxKr3.js.map +1 -0
- package/dist/DraftsSt-DcOTn0QR.js +434 -0
- package/dist/DraftsSt-DcOTn0QR.js.map +1 -0
- package/dist/cli.js +15 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +476 -202
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +98 -40
- package/dist/index.d.ts +117 -59
- package/dist/index.js +468 -193
- package/dist/index.js.map +1 -1
- package/dist/run-serve-CN0DhrsA.js +638 -0
- package/dist/run-serve-CN0DhrsA.js.map +1 -0
- package/dist/{run-tui-BAdizWsO.js → run-tui-bN2hSD5i.js} +250 -447
- package/dist/run-tui-bN2hSD5i.js.map +1 -0
- package/dist/state-COlKYipO.js +4743 -0
- package/dist/state-COlKYipO.js.map +1 -0
- package/dist/web.d.ts +17340 -0
- package/dist/{state-BYbxDgfr.js → web.js} +1903 -1592
- package/dist/web.js.map +1 -0
- package/examples/web/example.ts +71 -0
- package/examples/web/index.html +77 -0
- package/examples/web/serve.ts +42 -0
- package/examples/web/tsconfig.json +15 -0
- package/package.json +10 -3
- package/src/cli/comfy-ts-cli.ts +15 -5
- package/src/cli/serve/ServeApp.ts +378 -0
- package/src/cli/serve/applyVarPayload.ts +119 -0
- package/src/cli/serve/describeVar.ts +74 -0
- package/src/cli/serve/run-serve.ts +169 -0
- package/src/cli/tui/components/StatusBar.tsx +1 -0
- package/src/cli/tui/components/TreePanel.tsx +17 -3
- package/src/cli/tui/components/TuiApp.tsx +7 -2
- package/src/cli/tui/components/VarsPanel.tsx +67 -34
- package/src/cli/tui/imageClipboard.ts +39 -0
- package/src/cli/tui/listWindow.ts +36 -0
- package/src/cli/tui/state/ExecSt.ts +48 -0
- package/src/cli/tui/state/TreeSt.ts +25 -0
- package/src/cli/tui/state/TuiSt.ts +34 -0
- package/src/coreExports.ts +118 -0
- package/src/host/ComfyHost.ts +23 -23
- package/src/host/ResilientWebsocket.ts +93 -47
- package/src/host/hostUrl.ts +2 -1
- package/src/host/loraManagerApi.ts +6 -7
- package/src/index.ts +8 -107
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
- package/src/manager/loaders/step2_custom-node-list-loader.ts +4 -4
- package/src/manager/loaders/step3_extension-node-map-loader.ts +3 -3
- package/src/manager/loaders/step4_model-list-loader.ts +7 -7
- package/src/manager/loaders/step5_alter-list-loader.ts +2 -2
- package/src/manager/loaders/step6_github-stats-loader.ts +2 -2
- package/src/runner/ComfyExecution.ts +32 -12
- package/src/runner/MediaImage.ts +18 -30
- package/src/runner/outputPath.ts +75 -0
- package/src/sdk-generator/ComfySchema.ts +2 -2
- package/src/sdk-generator/inputWidgetKind.ts +50 -11
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
- package/src/state.ts +13 -9
- package/src/storage/ComfyStorage.ts +144 -0
- package/src/storage/nodeStorage.ts +9 -0
- package/src/utils/downloadFile.ts +11 -69
- package/src/utils/hashArrayBuffer.ts +3 -4
- package/src/utils/lazySharp.ts +25 -0
- package/src/utils/sha1.ts +69 -0
- package/src/vars/ComfyVars.ts +13 -6
- package/src/vars/loraKeywords.ts +6 -6
- package/src/web.ts +13 -0
- package/dist/run-tui-BAdizWsO.js.map +0 -1
- package/dist/state-BYbxDgfr.js.map +0 -1
- package/src/utils/writeFile.ts +0 -16
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// comfy-ts/web in a real browser page: connect to a ComfyUI host, build a
|
|
2
|
+
// txt2img graph, run it, show the image — no server between the page and
|
|
3
|
+
// Comfy. The host must allow browser origins:
|
|
4
|
+
// python main.py --enable-cors-header '*'
|
|
5
|
+
// (Comfy Cloud sends no CORS headers today — cloud rides `comfy-ts serve`.)
|
|
6
|
+
import { ComfyTS } from 'comfy-ts/web'
|
|
7
|
+
|
|
8
|
+
const comfy = ComfyTS.create()
|
|
9
|
+
|
|
10
|
+
function el<T extends HTMLElement>(id: string): T {
|
|
11
|
+
const hit = document.getElementById(id)
|
|
12
|
+
if (hit == null) throw new Error(`missing #${id}`)
|
|
13
|
+
return hit as T
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** a LIVE host has whatever nodes it has — resolve or fail loud by name */
|
|
17
|
+
function node<T>(factory: T | undefined, name: string): T {
|
|
18
|
+
if (factory == null) throw new Error(`this host has no ${name} node`)
|
|
19
|
+
return factory
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const status = el<HTMLDivElement>('status')
|
|
23
|
+
const output = el<HTMLImageElement>('output')
|
|
24
|
+
|
|
25
|
+
async function generate(): Promise<void> {
|
|
26
|
+
const url = el<HTMLInputElement>('host').value.trim()
|
|
27
|
+
const prompt = el<HTMLTextAreaElement>('prompt').value
|
|
28
|
+
const ckptName = el<HTMLInputElement>('ckpt').value.trim()
|
|
29
|
+
status.textContent = 'connecting…'
|
|
30
|
+
try {
|
|
31
|
+
// one host per url; re-clicking with the same url reuses the connection
|
|
32
|
+
const host = comfy.host({ id: `web-${url}`, url })
|
|
33
|
+
await host.connect()
|
|
34
|
+
|
|
35
|
+
const wf = host.workflow()
|
|
36
|
+
const b = wf.builderBase
|
|
37
|
+
const ckpt = node(b.CheckpointLoaderSimple, 'CheckpointLoaderSimple')({ ckpt_name: ckptName })
|
|
38
|
+
const latent = node(b.EmptyLatentImage, 'EmptyLatentImage')({ width: 512, height: 512, batch_size: 1 })
|
|
39
|
+
const sampled = node(
|
|
40
|
+
b.KSampler,
|
|
41
|
+
'KSampler',
|
|
42
|
+
)({
|
|
43
|
+
model: ckpt,
|
|
44
|
+
positive: node(b.CLIPTextEncode, 'CLIPTextEncode')({ clip: ckpt, text: prompt }),
|
|
45
|
+
negative: node(b.CLIPTextEncode, 'CLIPTextEncode')({ clip: ckpt, text: 'blurry, low quality' }),
|
|
46
|
+
latent_image: latent,
|
|
47
|
+
sampler_name: 'euler',
|
|
48
|
+
scheduler: 'normal',
|
|
49
|
+
seed: Math.floor(Math.random() * 2 ** 32),
|
|
50
|
+
steps: 20,
|
|
51
|
+
cfg: 7,
|
|
52
|
+
denoise: 1,
|
|
53
|
+
})
|
|
54
|
+
node(b.SaveImage, 'SaveImage')({ images: node(b.VAEDecode, 'VAEDecode')({ samples: sampled, vae: ckpt }) })
|
|
55
|
+
|
|
56
|
+
const execution = await wf.run({
|
|
57
|
+
onProgress: (p) => {
|
|
58
|
+
status.textContent = `${p.percent.toFixed(0)}%${p.nodeName ? ` · ${p.nodeName}` : ''}`
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
const img = execution.images[0]
|
|
62
|
+
if (img == null) throw new Error(`no image came back (status: ${execution.status})`)
|
|
63
|
+
output.src = URL.createObjectURL(img.getAsBlob())
|
|
64
|
+
status.textContent = `done · ${img.filename}`
|
|
65
|
+
} catch (e) {
|
|
66
|
+
status.textContent = String(e)
|
|
67
|
+
throw e // loud in the console too
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
el<HTMLButtonElement>('generate').onclick = (): void => void generate()
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>comfy-ts/web — txt2img in the browser</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root {
|
|
9
|
+
color-scheme: dark;
|
|
10
|
+
}
|
|
11
|
+
body {
|
|
12
|
+
font-family: ui-monospace, monospace;
|
|
13
|
+
max-width: 640px;
|
|
14
|
+
margin: 2rem auto;
|
|
15
|
+
padding: 0 1rem;
|
|
16
|
+
background: #111;
|
|
17
|
+
color: #ddd;
|
|
18
|
+
}
|
|
19
|
+
label {
|
|
20
|
+
display: block;
|
|
21
|
+
margin-top: 0.8rem;
|
|
22
|
+
font-size: 0.8rem;
|
|
23
|
+
opacity: 0.7;
|
|
24
|
+
}
|
|
25
|
+
input,
|
|
26
|
+
textarea {
|
|
27
|
+
width: 100%;
|
|
28
|
+
box-sizing: border-box;
|
|
29
|
+
background: #1a1a1a;
|
|
30
|
+
color: #ddd;
|
|
31
|
+
border: 1px solid #333;
|
|
32
|
+
padding: 0.5rem;
|
|
33
|
+
font: inherit;
|
|
34
|
+
}
|
|
35
|
+
button {
|
|
36
|
+
margin-top: 1rem;
|
|
37
|
+
padding: 0.5rem 1.5rem;
|
|
38
|
+
background: #2a6;
|
|
39
|
+
color: #fff;
|
|
40
|
+
border: 0;
|
|
41
|
+
font: inherit;
|
|
42
|
+
cursor: pointer;
|
|
43
|
+
}
|
|
44
|
+
#status {
|
|
45
|
+
margin-top: 0.8rem;
|
|
46
|
+
min-height: 1.2em;
|
|
47
|
+
opacity: 0.8;
|
|
48
|
+
}
|
|
49
|
+
#output {
|
|
50
|
+
margin-top: 1rem;
|
|
51
|
+
max-width: 100%;
|
|
52
|
+
}
|
|
53
|
+
.note {
|
|
54
|
+
font-size: 0.75rem;
|
|
55
|
+
opacity: 0.5;
|
|
56
|
+
margin-top: 1.5rem;
|
|
57
|
+
}
|
|
58
|
+
</style>
|
|
59
|
+
</head>
|
|
60
|
+
<body>
|
|
61
|
+
<h1>comfy-ts/web</h1>
|
|
62
|
+
<label for="host">ComfyUI host (started with <code>--enable-cors-header '*'</code>)</label>
|
|
63
|
+
<input id="host" value="http://127.0.0.1:8188" />
|
|
64
|
+
<label for="ckpt">checkpoint name (as the host knows it)</label>
|
|
65
|
+
<input id="ckpt" value="v1-5-pruned-emaonly.ckpt" />
|
|
66
|
+
<label for="prompt">prompt</label>
|
|
67
|
+
<textarea id="prompt" rows="3">a lighthouse on a cliff, dramatic sky</textarea>
|
|
68
|
+
<button id="generate">generate</button>
|
|
69
|
+
<div id="status"></div>
|
|
70
|
+
<img id="output" alt="" />
|
|
71
|
+
<p class="note">
|
|
72
|
+
Everything runs in this page: comfy-ts/web talks to the host directly (schema fetch, websocket progress, image
|
|
73
|
+
download). Nothing touches disk — the library writes to an in-memory store.
|
|
74
|
+
</p>
|
|
75
|
+
<script type="module" src="./example.js"></script>
|
|
76
|
+
</body>
|
|
77
|
+
</html>
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// dev server for the browser example: bundles example.ts with the SAME
|
|
2
|
+
// browser target the guard test enforces, serves it with index.html.
|
|
3
|
+
// bun examples/web/serve.ts → http://127.0.0.1:8290
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { dirname, join } from 'pathe'
|
|
6
|
+
|
|
7
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
8
|
+
const repoRoot = join(here, '../..')
|
|
9
|
+
|
|
10
|
+
const result = await Bun.build({
|
|
11
|
+
entrypoints: [join(here, 'example.ts')],
|
|
12
|
+
target: 'browser',
|
|
13
|
+
minify: false,
|
|
14
|
+
plugins: [
|
|
15
|
+
{
|
|
16
|
+
name: 'repo-paths',
|
|
17
|
+
setup(build) {
|
|
18
|
+
build.onResolve({ filter: /^comfy-ts\/web$/ }, () => ({ path: join(repoRoot, 'src/web.ts') }))
|
|
19
|
+
build.onResolve({ filter: /^src\// }, (args) => ({ path: join(repoRoot, args.path) }))
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
],
|
|
23
|
+
})
|
|
24
|
+
if (!result.success) {
|
|
25
|
+
console.error(result.logs.join('\n'))
|
|
26
|
+
throw new Error('example bundle failed')
|
|
27
|
+
}
|
|
28
|
+
const first = result.outputs[0]
|
|
29
|
+
if (first == null) throw new Error('no bundle output')
|
|
30
|
+
const bundle = await first.text()
|
|
31
|
+
|
|
32
|
+
const server = Bun.serve({
|
|
33
|
+
port: 8290,
|
|
34
|
+
hostname: '127.0.0.1',
|
|
35
|
+
fetch: (req) => {
|
|
36
|
+
const path = new URL(req.url).pathname
|
|
37
|
+
if (path === '/example.js') return new Response(bundle, { headers: { 'content-type': 'text/javascript' } })
|
|
38
|
+
return new Response(Bun.file(join(here, 'index.html')))
|
|
39
|
+
},
|
|
40
|
+
})
|
|
41
|
+
console.log(`comfy-ts/web example → http://127.0.0.1:${server.port}/`)
|
|
42
|
+
console.log(`point it at a ComfyUI started with: --enable-cors-header '*'`)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
// the ONE dom-typed corner of the repo: the browser example needs document/
|
|
3
|
+
// URL.createObjectURL. src/ stays dom-free by machine (root + lib configs
|
|
4
|
+
// have no dom lib), so a dom global leaking into the library fails there.
|
|
5
|
+
"extends": "../../tsconfig.json",
|
|
6
|
+
"compilerOptions": {
|
|
7
|
+
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
|
8
|
+
"paths": {
|
|
9
|
+
"src/*": ["../../src/*"],
|
|
10
|
+
"comfy-ts": ["../../src/index.ts"],
|
|
11
|
+
"comfy-ts/web": ["../../src/web.ts"]
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"include": [".", "../../src"]
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "comfy-ts",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"comfyui",
|
|
@@ -48,6 +48,12 @@
|
|
|
48
48
|
"default": "./dist/index.cjs"
|
|
49
49
|
}
|
|
50
50
|
},
|
|
51
|
+
"./web": {
|
|
52
|
+
"import": {
|
|
53
|
+
"types": "./dist/web.d.ts",
|
|
54
|
+
"default": "./dist/web.js"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
51
57
|
"./src/*": "./src/*"
|
|
52
58
|
},
|
|
53
59
|
"files": [
|
|
@@ -63,7 +69,7 @@
|
|
|
63
69
|
"build:watch": "tsdown --watch",
|
|
64
70
|
"test": "bun test",
|
|
65
71
|
"test:watch": "bun test --watch",
|
|
66
|
-
"typecheck": "tsc --noEmit",
|
|
72
|
+
"typecheck": "tsc --noEmit && tsc -p examples/web/tsconfig.json",
|
|
67
73
|
"typecheck:lib": "tsc -p tsconfig.lib.json",
|
|
68
74
|
"lint": "oxlint src examples scripts tests",
|
|
69
75
|
"format": "oxfmt src examples scripts tests",
|
|
@@ -85,7 +91,8 @@
|
|
|
85
91
|
"release": "bun scripts/release.ts",
|
|
86
92
|
"release:dry": "bun scripts/release.ts --dry-run",
|
|
87
93
|
"prepublishOnly": "bun run ci && bun run build",
|
|
88
|
-
"tui": "bun src/cli/comfy-ts-cli.ts tui"
|
|
94
|
+
"tui": "bun src/cli/comfy-ts-cli.ts tui",
|
|
95
|
+
"serve": "bun src/cli/comfy-ts-cli.ts serve"
|
|
89
96
|
},
|
|
90
97
|
"rvt": {
|
|
91
98
|
"skip": [
|
package/src/cli/comfy-ts-cli.ts
CHANGED
|
@@ -22,6 +22,12 @@ Usage:
|
|
|
22
22
|
host.defineWorkflow(...)); no arg scans cwd + the examples bundled
|
|
23
23
|
with comfy-ts, an explicit dir/file limits to it (file preselected)
|
|
24
24
|
|
|
25
|
+
comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--bind 127.0.0.1]
|
|
26
|
+
drafts as a local HTTP generation API: POST /generate/<module>/<draft>
|
|
27
|
+
with { ...vars } overriding the draft's values (blocking; raw image
|
|
28
|
+
bytes under Accept: image/*), GET /drafts self-describes every var,
|
|
29
|
+
GET /outputs/... serves the results. No bundled examples, no auth.
|
|
30
|
+
|
|
25
31
|
comfy-ts help
|
|
26
32
|
`
|
|
27
33
|
|
|
@@ -29,19 +35,23 @@ async function main(): Promise<number> {
|
|
|
29
35
|
const [cmd, ...rest] = process.argv.slice(2)
|
|
30
36
|
if (cmd === 'gen') return runGen(rest)
|
|
31
37
|
if (cmd === 'outline') return runOutline(rest)
|
|
32
|
-
if (cmd === 'tui') {
|
|
38
|
+
if (cmd === 'tui' || cmd === 'serve') {
|
|
33
39
|
// .cflow.ts workflow modules need bun: node refuses to strip types under
|
|
34
40
|
// node_modules, exactly where the packaged examples live — and the bin's
|
|
35
|
-
// node shebang means `bunx comfy-ts tui` lands here under NODE. Hop
|
|
36
|
-
// bun when we are not already in it; without bun,
|
|
41
|
+
// node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop
|
|
42
|
+
// to bun when we are not already in it; without bun, degrade loudly.
|
|
37
43
|
if (process.versions.bun == null) {
|
|
38
44
|
const self = fileURLToPath(import.meta.url)
|
|
39
|
-
const res = spawnSync('bun', [self,
|
|
45
|
+
const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })
|
|
40
46
|
if (res.error == null) return res.status ?? 1
|
|
41
47
|
console.error(
|
|
42
|
-
`[comfy-ts
|
|
48
|
+
`[comfy-ts ${cmd}] bun not found (${res.error.message}) — continuing under node: the examples packaged in node_modules cannot load here, and your own .cflow.ts modules rely on node's type stripping`,
|
|
43
49
|
)
|
|
44
50
|
}
|
|
51
|
+
if (cmd === 'serve') {
|
|
52
|
+
const { runServe } = await import('src/cli/serve/run-serve.ts')
|
|
53
|
+
return runServe(rest)
|
|
54
|
+
}
|
|
45
55
|
// lazy import: keeps ink/react out of the codegen paths
|
|
46
56
|
const { runTui } = await import('src/cli/tui/run-tui.tsx')
|
|
47
57
|
return runTui(rest)
|
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,
|
|
2
|
+
// tests call handle() directly with an injected starter. Full contract:
|
|
3
|
+
// agent/architecture.md item 12.
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { nanoid } from 'nanoid'
|
|
6
|
+
import { basename, dirname, extname, join, resolve } from 'pathe'
|
|
7
|
+
import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
|
|
8
|
+
import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
|
|
9
|
+
import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
|
|
10
|
+
import { ImageVar, ImageVarEmptyError, SeedVar } from 'src/vars/ComfyVars.ts'
|
|
11
|
+
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
12
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
13
|
+
|
|
14
|
+
export type ServeModule = { key: string; file: string; dw: DefinedWorkflow }
|
|
15
|
+
|
|
16
|
+
/** structural face of ComfyExecution — tests inject a fake starter */
|
|
17
|
+
export type ServeExecution = {
|
|
18
|
+
done: Promise<unknown>
|
|
19
|
+
status: string
|
|
20
|
+
images: { absPath: string; filename: string }[]
|
|
21
|
+
data: { id: string; error?: unknown }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>
|
|
25
|
+
|
|
26
|
+
export type ServeRequest = { method: string; url: string; accept?: string; body?: string }
|
|
27
|
+
export type ServeReply = { status: number; contentType: string; body: string | Uint8Array }
|
|
28
|
+
|
|
29
|
+
/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex */
|
|
30
|
+
const realStarter: ServeStarter = async (mod) => {
|
|
31
|
+
await mod.dw.host.connect()
|
|
32
|
+
const wf = await mod.dw.build({ advance: true })
|
|
33
|
+
return await wf.start({})
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const CONTENT_TYPES: Record<string, string> = {
|
|
37
|
+
'.png': 'image/png',
|
|
38
|
+
'.jpg': 'image/jpeg',
|
|
39
|
+
'.jpeg': 'image/jpeg',
|
|
40
|
+
'.webp': 'image/webp',
|
|
41
|
+
'.gif': 'image/gif',
|
|
42
|
+
'.mp4': 'video/mp4',
|
|
43
|
+
'.webm': 'video/webm',
|
|
44
|
+
'.json': 'application/json',
|
|
45
|
+
'.txt': 'text/plain',
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function json(status: number, payload: unknown): ServeReply {
|
|
49
|
+
return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const USAGE = [
|
|
53
|
+
'GET /drafts — every served workflow, its drafts and var descriptors',
|
|
54
|
+
'GET /drafts/<module>/<draft> — one draft with its stored values',
|
|
55
|
+
'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
|
|
56
|
+
'POST /generate/<draft> — unqualified, when unambiguous',
|
|
57
|
+
'GET /outputs/<path> — generated files',
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
export class ServeApp {
|
|
61
|
+
private starter: ServeStarter
|
|
62
|
+
/** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it */
|
|
63
|
+
private seedState = new Map<string, number>()
|
|
64
|
+
/** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
|
|
65
|
+
private chains = new Map<string, Promise<unknown>>()
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
public modules: ServeModule[],
|
|
69
|
+
private opts: { starter?: ServeStarter; outputRoot?: string; loadErrors?: Record<string, string> } = {},
|
|
70
|
+
) {
|
|
71
|
+
this.starter = opts.starter ?? realStarter
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private get outputRoot(): string {
|
|
75
|
+
return this.opts.outputRoot ?? comfyts.outputPath
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// #region routing ----------------------------------------------------------
|
|
79
|
+
async handle(req: ServeRequest): Promise<ServeReply> {
|
|
80
|
+
try {
|
|
81
|
+
const path = (req.url.split('?')[0] ?? '/').split('#')[0] ?? '/'
|
|
82
|
+
let segs: string[]
|
|
83
|
+
try {
|
|
84
|
+
segs = path
|
|
85
|
+
.split('/')
|
|
86
|
+
.filter((s) => s !== '')
|
|
87
|
+
.map(decodeURIComponent)
|
|
88
|
+
} catch {
|
|
89
|
+
return json(400, { error: `bad url encoding: ${path}` })
|
|
90
|
+
}
|
|
91
|
+
if (req.method === 'GET') {
|
|
92
|
+
if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
|
|
93
|
+
if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
94
|
+
return this.replyDraft(segs[1], segs[2])
|
|
95
|
+
if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
|
|
96
|
+
return json(404, { error: `no route: GET ${path}`, usage: USAGE })
|
|
97
|
+
}
|
|
98
|
+
if (req.method === 'POST' && segs[0] === 'generate') {
|
|
99
|
+
const target = this.resolveDraft(segs.slice(1))
|
|
100
|
+
if ('error' in target) return json(target.status, { error: target.error })
|
|
101
|
+
return await this.generate(target.mod, target.draft, req)
|
|
102
|
+
}
|
|
103
|
+
return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
|
|
104
|
+
} catch (e) {
|
|
105
|
+
console.error('[serve] request crashed:', e)
|
|
106
|
+
return json(500, { error: extractErrorMessage(e) })
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
moduleByKey(key: string): ServeModule | null {
|
|
111
|
+
return this.modules.find((m) => m.key === key) ?? null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */
|
|
115
|
+
draftsFor(mod: ServeModule): string[] {
|
|
116
|
+
const onDisk = listDraftsForFile(mod.file)
|
|
117
|
+
return ['default', ...onDisk.filter((n) => n !== 'default')]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private draftExists(mod: ServeModule, draft: string): boolean {
|
|
121
|
+
return draft === 'default' || existsSync(join(draftsDirForFile(mod.file), `${draft}.json`))
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {
|
|
125
|
+
if (segs.length === 2 && segs[0] != null && segs[1] != null) {
|
|
126
|
+
const mod = this.moduleByKey(segs[0])
|
|
127
|
+
if (mod == null)
|
|
128
|
+
return {
|
|
129
|
+
status: 404,
|
|
130
|
+
error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(', ')}`,
|
|
131
|
+
}
|
|
132
|
+
if (!this.draftExists(mod, segs[1]))
|
|
133
|
+
return {
|
|
134
|
+
status: 404,
|
|
135
|
+
error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
136
|
+
}
|
|
137
|
+
return { mod, draft: segs[1] }
|
|
138
|
+
}
|
|
139
|
+
if (segs.length === 1 && segs[0] != null) {
|
|
140
|
+
const draft = segs[0]
|
|
141
|
+
if (this.modules.length === 1 && this.modules[0] != null) {
|
|
142
|
+
const mod = this.modules[0]
|
|
143
|
+
if (!this.draftExists(mod, draft))
|
|
144
|
+
return {
|
|
145
|
+
status: 404,
|
|
146
|
+
error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
147
|
+
}
|
|
148
|
+
return { mod, draft }
|
|
149
|
+
}
|
|
150
|
+
const hits = this.modules.filter((m) => this.draftExists(m, draft))
|
|
151
|
+
if (hits.length === 1 && hits[0] != null) return { mod: hits[0], draft }
|
|
152
|
+
if (hits.length === 0) return { status: 404, error: `no module has a draft '${draft}'` }
|
|
153
|
+
return {
|
|
154
|
+
status: 400,
|
|
155
|
+
error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(' or ')}`,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { status: 400, error: 'use POST /generate/<module>/<draft> or /generate/<draft>' }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// #region introspection ----------------------------------------------------
|
|
162
|
+
private describeModule(mod: ServeModule): Record<string, unknown> {
|
|
163
|
+
const vars: Record<string, VarDescriptor> = {}
|
|
164
|
+
for (const [name, varDef] of mod.dw.entries()) vars[name] = describeVar(varDef)
|
|
165
|
+
return {
|
|
166
|
+
module: mod.key,
|
|
167
|
+
file: mod.file,
|
|
168
|
+
host: mod.dw.host.data.id,
|
|
169
|
+
drafts: this.draftsFor(mod),
|
|
170
|
+
routes: this.draftsFor(mod).map(
|
|
171
|
+
(d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,
|
|
172
|
+
),
|
|
173
|
+
vars,
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private replyIndex(): ServeReply {
|
|
178
|
+
return json(200, {
|
|
179
|
+
server: 'comfy-ts serve',
|
|
180
|
+
usage: USAGE,
|
|
181
|
+
workflows: this.modules.map((m) => this.describeModule(m)),
|
|
182
|
+
...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0
|
|
183
|
+
? { loadErrors: this.opts.loadErrors }
|
|
184
|
+
: {}),
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private replyDraft(modKey: string, draft: string): ServeReply {
|
|
189
|
+
const mod = this.moduleByKey(modKey)
|
|
190
|
+
if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
|
|
191
|
+
if (!this.draftExists(mod, draft))
|
|
192
|
+
return json(404, {
|
|
193
|
+
error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,
|
|
194
|
+
})
|
|
195
|
+
return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
|
|
199
|
+
private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {
|
|
200
|
+
const path = join(draftsDirForFile(mod.file), `${draft}.json`)
|
|
201
|
+
if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>
|
|
202
|
+
const out: Record<string, unknown> = {}
|
|
203
|
+
for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default
|
|
204
|
+
return out
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// #region outputs ----------------------------------------------------------
|
|
208
|
+
private replyOutput(segs: string[]): ServeReply {
|
|
209
|
+
const abs = resolve(this.outputRoot, ...segs)
|
|
210
|
+
// traversal guard: the resolved path must stay under the output root
|
|
211
|
+
if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + '/'))
|
|
212
|
+
return json(400, { error: 'path escapes the outputs root' })
|
|
213
|
+
if (!existsSync(abs) || !statSync(abs).isFile())
|
|
214
|
+
return json(404, { error: `no such output file: /${segs.join('/')}` })
|
|
215
|
+
const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? 'application/octet-stream'
|
|
216
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private outputUrl(absPath: string): string | null {
|
|
220
|
+
if (!absPath.startsWith(this.outputRoot + '/')) return null
|
|
221
|
+
const rel = absPath.slice(this.outputRoot.length + 1)
|
|
222
|
+
return '/outputs/' + rel.split('/').map(encodeURIComponent).join('/')
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// #region generate ---------------------------------------------------------
|
|
226
|
+
private async generate(mod: ServeModule, draft: string, req: ServeRequest): Promise<ServeReply> {
|
|
227
|
+
let payload: Record<string, unknown> = {}
|
|
228
|
+
if (req.body != null && req.body.trim() !== '') {
|
|
229
|
+
let parsed: unknown
|
|
230
|
+
try {
|
|
231
|
+
parsed = JSON.parse(req.body)
|
|
232
|
+
} catch (e) {
|
|
233
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
|
|
234
|
+
}
|
|
235
|
+
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
236
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
|
|
237
|
+
payload = parsed as Record<string, unknown>
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const t0 = Date.now()
|
|
241
|
+
const seeds: Record<string, number> = {}
|
|
242
|
+
const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds))
|
|
243
|
+
if ('error' in started) return json(started.status, { error: started.error })
|
|
244
|
+
|
|
245
|
+
const execution = started.execution
|
|
246
|
+
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
|
|
247
|
+
await execution.done
|
|
248
|
+
const durationMs = Date.now() - t0
|
|
249
|
+
|
|
250
|
+
if (execution.status === 'Failure') {
|
|
251
|
+
console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)
|
|
252
|
+
return json(500, {
|
|
253
|
+
ok: false,
|
|
254
|
+
module: mod.key,
|
|
255
|
+
draft,
|
|
256
|
+
promptId: execution.data.id,
|
|
257
|
+
durationMs,
|
|
258
|
+
error: execution.data.error ?? 'execution failed',
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
console.log(
|
|
263
|
+
`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${execution.images.length} image(s)`,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
// Accept: image/* → first image's bytes directly (curl -o, <img src>)
|
|
267
|
+
const first = execution.images[0]
|
|
268
|
+
if (req.accept?.includes('image/') && first != null) {
|
|
269
|
+
const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
|
|
270
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return json(200, {
|
|
274
|
+
ok: true,
|
|
275
|
+
module: mod.key,
|
|
276
|
+
draft,
|
|
277
|
+
promptId: execution.data.id,
|
|
278
|
+
durationMs,
|
|
279
|
+
seeds,
|
|
280
|
+
images: execution.images.map((img) => ({
|
|
281
|
+
filename: img.filename,
|
|
282
|
+
url: this.outputUrl(img.absPath),
|
|
283
|
+
absPath: img.absPath,
|
|
284
|
+
})),
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** everything that touches the module's SHARED vars, under the module mutex */
|
|
289
|
+
private async prepareAndStart(
|
|
290
|
+
mod: ServeModule,
|
|
291
|
+
draft: string,
|
|
292
|
+
payload: Record<string, unknown>,
|
|
293
|
+
seeds: Record<string, number>,
|
|
294
|
+
): Promise<{ execution: ServeExecution } | { error: string; status: number }> {
|
|
295
|
+
// 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)
|
|
296
|
+
for (const [, varDef] of mod.dw.entries()) varDef.reset()
|
|
297
|
+
const draftPath = join(draftsDirForFile(mod.file), `${draft}.json`)
|
|
298
|
+
if (existsSync(draftPath)) {
|
|
299
|
+
try {
|
|
300
|
+
const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>
|
|
301
|
+
for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k])
|
|
302
|
+
} catch (e) {
|
|
303
|
+
return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` }
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// 2. payload overrides (image urls download first, so the var gets a local path)
|
|
308
|
+
const varMap = new Map(mod.dw.entries())
|
|
309
|
+
for (const [k, rawValue] of Object.entries(payload)) {
|
|
310
|
+
const varDef = varMap.get(k)
|
|
311
|
+
if (varDef == null)
|
|
312
|
+
return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }
|
|
313
|
+
let value = rawValue
|
|
314
|
+
if (varDef instanceof ImageVar && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
|
|
315
|
+
try {
|
|
316
|
+
value = await this.downloadInput(rawValue)
|
|
317
|
+
} catch (e) {
|
|
318
|
+
return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const err = applyVarPayload(varDef, value)
|
|
322
|
+
if (err != null) return { status: 400, error: err }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// 3. image vars must point at real files BEFORE anything is queued
|
|
326
|
+
for (const [k, varDef] of varMap) {
|
|
327
|
+
if (varDef instanceof ImageVar && varDef.isSet() && !existsSync(varDef.absPath()))
|
|
328
|
+
return { status: 400, error: `image var '${k}': file not found: ${varDef.absPath()}` }
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 4. seed policy (architecture item 12): payload wins; '?' rerolls;
|
|
332
|
+
// '+'/'-' continue from the last SERVED value; '=' keeps the draft value
|
|
333
|
+
for (const [k, varDef] of varMap) {
|
|
334
|
+
if (!(varDef instanceof SeedVar)) continue
|
|
335
|
+
const stateKey = `${mod.key}/${draft}/${k}`
|
|
336
|
+
if (!(k in payload)) {
|
|
337
|
+
if (varDef.mode === '?') varDef.randomize()
|
|
338
|
+
else if (varDef.mode === '+' || varDef.mode === '-') {
|
|
339
|
+
const last = this.seedState.get(stateKey)
|
|
340
|
+
if (last != null) varDef.set(last + (varDef.mode === '+' ? 1 : -1))
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
this.seedState.set(stateKey, varDef.value)
|
|
344
|
+
seeds[k] = varDef.value
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex
|
|
348
|
+
try {
|
|
349
|
+
return { execution: await this.starter(mod) }
|
|
350
|
+
} catch (e) {
|
|
351
|
+
if (e instanceof ImageVarEmptyError) return { status: 400, error: e.message }
|
|
352
|
+
return { status: 500, error: extractErrorMessage(e) }
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** serialize fn per module key; the stored chain never rejects */
|
|
357
|
+
private exclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
358
|
+
const prev = this.chains.get(key) ?? Promise.resolve()
|
|
359
|
+
const next = prev.then(fn)
|
|
360
|
+
this.chains.set(
|
|
361
|
+
key,
|
|
362
|
+
next.catch(() => {}),
|
|
363
|
+
)
|
|
364
|
+
return next
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** payload image urls land as local files under outputs/serve-inputs/ */
|
|
368
|
+
private async downloadInput(url: string): Promise<string> {
|
|
369
|
+
const res = await fetch(url)
|
|
370
|
+
if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`)
|
|
371
|
+
const bytes = new Uint8Array(await res.arrayBuffer())
|
|
372
|
+
const name = basename(new URL(url).pathname) || 'input'
|
|
373
|
+
const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${name}`)
|
|
374
|
+
mkdirSync(dirname(abs), { recursive: true })
|
|
375
|
+
writeFileSync(abs, bytes)
|
|
376
|
+
return abs
|
|
377
|
+
}
|
|
378
|
+
}
|