comfy-ts 1.1.0 → 1.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/README.md +61 -8
- package/dist/{DefinedWorkflow-BYyu5dK9.js → DefinedWorkflow-gpknV-5f.js} +52 -35
- package/dist/DefinedWorkflow-gpknV-5f.js.map +1 -0
- package/dist/DraftsSt-DmA0jWGl.js +434 -0
- package/dist/DraftsSt-DmA0jWGl.js.map +1 -0
- package/dist/cli.js +17 -4555
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +184 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +54 -23
- package/dist/index.d.ts +36 -5
- package/dist/index.js +184 -32
- package/dist/index.js.map +1 -1
- package/dist/run-serve-Bn6yIJB0.js +638 -0
- package/dist/run-serve-Bn6yIJB0.js.map +1 -0
- package/dist/{run-tui-DZ22HDHI.js → run-tui-BtjaOXRh.js} +791 -395
- package/dist/run-tui-BtjaOXRh.js.map +1 -0
- package/dist/state-DKCPy105.js +4690 -0
- package/dist/state-DKCPy105.js.map +1 -0
- package/examples/README.md +6 -4
- package/examples/{01-txt2img.cflow.ts → rvion/01-txt2img.cflow.ts} +1 -1
- package/examples/{02-img2img-upload.cflow.ts → rvion/02-img2img-upload.cflow.ts} +1 -1
- package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts} +1 -1
- package/examples/{04-krea2-turbo-t2i.cflow.ts → rvion/04-krea2-turbo-t2i.cflow.ts} +2 -2
- package/examples/{05-comfy-cloud.cflow.ts → rvion/05-comfy-cloud.cflow.ts} +2 -2
- package/examples/rvion/06-qwen-image-edit.cflow.ts +89 -0
- package/package.json +6 -2
- 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/CopyOverlay.tsx +25 -0
- package/src/cli/tui/components/Header.tsx +9 -4
- package/src/cli/tui/components/HostPanel.tsx +3 -2
- package/src/cli/tui/components/HostsOverlay.tsx +33 -0
- package/src/cli/tui/components/StatusBar.tsx +29 -9
- package/src/cli/tui/components/TreePanel.tsx +33 -9
- package/src/cli/tui/components/TuiApp.tsx +54 -7
- package/src/cli/tui/components/VarsPanel.tsx +67 -34
- package/src/cli/tui/imageClipboard.ts +39 -0
- package/src/cli/tui/imagePicker/fsListing.ts +6 -4
- package/src/cli/tui/listWindow.ts +36 -0
- package/src/cli/tui/run-tui.tsx +47 -7
- package/src/cli/tui/state/DraftsSt.ts +3 -2
- package/src/cli/tui/state/ExecSt.ts +156 -12
- package/src/cli/tui/state/HostSt.ts +94 -10
- package/src/cli/tui/state/PickerSt.ts +8 -2
- package/src/cli/tui/state/QueueSt.ts +2 -2
- package/src/cli/tui/state/SettingsSt.ts +25 -7
- package/src/cli/tui/state/TreeSt.ts +164 -36
- package/src/cli/tui/state/TuiSt.ts +81 -6
- package/src/cli/tui/state/WorkflowsSt.ts +14 -2
- package/src/cli/tui/treeRows.ts +165 -0
- package/src/host/ComfyHost.ts +7 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +11 -7
- package/src/runner/ComfyExecution.ts +21 -4
- package/src/runner/ComfyWorkflowLayout.ts +6 -4
- package/src/runner/outputPath.ts +75 -0
- package/src/sdk-generator/inputWidgetKind.ts +50 -11
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +14 -7
- package/src/state.ts +7 -1
- package/src/vars/ComfyVars.ts +33 -4
- package/src/vars/DefinedWorkflow.ts +21 -8
- package/dist/DefinedWorkflow-BYyu5dK9.js.map +0 -1
- package/dist/run-tui-DZ22HDHI.js.map +0 -1
package/examples/README.md
CHANGED
|
@@ -6,12 +6,14 @@ with bun, or browse them all in the TUI (`bunx comfy-ts tui` lists them under
|
|
|
6
6
|
|
|
7
7
|
## Layout
|
|
8
8
|
|
|
9
|
-
- `01…04-*.cflow.ts` — the didactic sequence against a LOCAL ComfyUI
|
|
10
|
-
(edit the `comfy.host({...})` line to point at yours, then first run
|
|
9
|
+
- `rvion/01…04-*.cflow.ts` — the didactic sequence against a LOCAL ComfyUI
|
|
10
|
+
host (edit the `comfy.host({...})` line to point at yours, then first run
|
|
11
11
|
generates a typed SDK for it).
|
|
12
|
-
- `05-comfy-cloud.cflow.ts` — the same t2i against [Comfy Cloud]
|
|
12
|
+
- `rvion/05-comfy-cloud.cflow.ts` — the same t2i against [Comfy Cloud]
|
|
13
13
|
(https://cloud.comfy.org): no local GPU needed, the typed catalog ships
|
|
14
14
|
committed at `comfy-cloud/sdk.d.ts`.
|
|
15
|
+
- `rvion/06-qwen-image-edit.cflow.ts` — image editing (qwen image edit 2511)
|
|
16
|
+
against the same local host.
|
|
15
17
|
- `comfy-cloud/<family>-<mode>.cflow.ts` — the model zoo: one clean example
|
|
16
18
|
per model family × mode (`t2i`, `i2i`, `t2v`, `i2v`, `t2a`), each mirroring
|
|
17
19
|
an official ComfyUI template (flux, qwen-image, z-image, wan, hidream,
|
|
@@ -24,7 +26,7 @@ paid tiers). Without it everything still loads and typechecks — only `run()`
|
|
|
24
26
|
needs the key:
|
|
25
27
|
|
|
26
28
|
```sh
|
|
27
|
-
COMFY_CLOUD_API_KEY=… bun examples/05-comfy-cloud.cflow.ts "a fox in the snow" 42
|
|
29
|
+
COMFY_CLOUD_API_KEY=… bun examples/rvion/05-comfy-cloud.cflow.ts "a fox in the snow" 42
|
|
28
30
|
```
|
|
29
31
|
|
|
30
32
|
Cloud runs bill compute to your account — start with a small t2i.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// generate an image from text, fully typed against the 'windows-1' host sdk
|
|
2
|
-
// run directly: bun examples/01-txt2img.cflow.ts ["prompt"] [seed]
|
|
2
|
+
// run directly: bun examples/rvion/01-txt2img.cflow.ts ["prompt"] [seed]
|
|
3
3
|
// in the TUI: bun run tui (scans **/*.cflow.ts, tweak vars, r to run)
|
|
4
4
|
import { ComfyTS, v } from 'comfy-ts'
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// upload a local image (hash-named, deduped) and run img2img on it
|
|
2
|
-
// run directly: bun examples/02-img2img-upload.cflow.ts [path/to/image.png]
|
|
2
|
+
// run directly: bun examples/rvion/02-img2img-upload.cflow.ts [path/to/image.png]
|
|
3
3
|
// in the TUI: bun run tui — activate the `image` var to open the picker (browse, favorites, preview)
|
|
4
4
|
import { asAbsolutePath, ComfyTS, exampleImagePath, MediaImage, v } from 'comfy-ts'
|
|
5
5
|
|
package/examples/{03-export-workflow-json.cflow.ts → rvion/03-export-workflow-json.cflow.ts}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// build a graph OFFLINE (schema from .comfy-ts/ cache) and export both ComfyUI
|
|
2
2
|
// JSON formats: api.json (prompt) + workflow.json (readable litegraph, autolayouted)
|
|
3
|
-
// run directly: bun examples/03-export-workflow-json.cflow.ts (no server needed)
|
|
3
|
+
// run directly: bun examples/rvion/03-export-workflow-json.cflow.ts (no server needed)
|
|
4
4
|
// in the TUI: bun run tui — r runs it live (PreviewImage), c/C copy the JSONs
|
|
5
5
|
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
6
6
|
import { ComfyTS, v } from 'comfy-ts'
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// (rabbits-vs-sheeps "unified"). krea2 turbo UNET + standard LoraLoader chain
|
|
3
3
|
// → KSampler(8 steps, cfg 1) → RMBG cutout → transparent png game sprite.
|
|
4
4
|
//
|
|
5
|
-
// run directly: bun examples/04-krea2-turbo-t2i.cflow.ts ["prompt"] [seed]
|
|
6
|
-
// in the TUI: bun src/cli/comfy-ts-cli.ts tui examples/04-krea2-turbo-t2i.cflow.ts
|
|
5
|
+
// run directly: bun examples/rvion/04-krea2-turbo-t2i.cflow.ts ["prompt"] [seed]
|
|
6
|
+
// in the TUI: bun src/cli/comfy-ts-cli.ts tui examples/rvion/04-krea2-turbo-t2i.cflow.ts
|
|
7
7
|
// tui browser: bun src/cli/comfy-ts-cli.ts tui examples/ (scans **/*.cflow.ts)
|
|
8
8
|
import { activeLoras, ComfyTS } from 'comfy-ts'
|
|
9
9
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// sd15 t2i on Comfy Cloud — the reference zoo example (agent/examples.md)
|
|
2
2
|
// source template: default.json (official workflow-templates)
|
|
3
3
|
// needs COMFY_CLOUD_API_KEY (https://cloud.comfy.org, paid tiers) — loads fine without, run() needs it
|
|
4
|
-
// run directly: bun examples/05-comfy-cloud.cflow.ts ["prompt"] [seed]
|
|
4
|
+
// run directly: bun examples/rvion/05-comfy-cloud.cflow.ts ["prompt"] [seed]
|
|
5
5
|
import { v } from 'comfy-ts'
|
|
6
|
-
import { cloudHost, requireCloudKey } from '
|
|
6
|
+
import { cloudHost, requireCloudKey } from '../comfy-cloud/cloudHost.ts'
|
|
7
7
|
|
|
8
8
|
const host = await cloudHost()
|
|
9
9
|
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// qwen image edit 2511 on windows-1 — instruction-driven image editing
|
|
2
|
+
// mirrors the official image_qwen_image_edit_2511 template, single reference
|
|
3
|
+
// image; the lightning toggle switches the 4-step Lightning lora (cfg 1) vs
|
|
4
|
+
// full sampling (cfg 4 — raise steps to ~40 yourself when you flip it off)
|
|
5
|
+
// run directly: bun examples/rvion/06-qwen-image-edit.cflow.ts [path/to/image.png] ["edit instruction"]
|
|
6
|
+
import { asAbsolutePath, ComfyTS, exampleImagePath, MediaImage, v } from 'comfy-ts'
|
|
7
|
+
|
|
8
|
+
const comfy = ComfyTS.create()
|
|
9
|
+
const host = comfy.host({ id: 'windows-1', host: 'desktop-im18794', port: 8085 })
|
|
10
|
+
await host.loadSchemaFromCache() // offline import; run() connects lazily
|
|
11
|
+
|
|
12
|
+
// bundled default input (examples/images/, ships in the tarball) — the TUI picker or argv[2] swap it
|
|
13
|
+
const image = v.image(exampleImagePath('bear_1024x1024.jpg'))
|
|
14
|
+
|
|
15
|
+
export const qwenImageEdit = host.defineWorkflow({
|
|
16
|
+
id: 'qwen-image-edit',
|
|
17
|
+
vars: {
|
|
18
|
+
image,
|
|
19
|
+
// `- ` lines are the negative prompt (template default: empty negative encode)
|
|
20
|
+
prompt: v.prompt('turn this photo into a detailed watercolor painting'),
|
|
21
|
+
seed: v.seed(42),
|
|
22
|
+
steps: v.int(4, { min: 1, max: 60 }),
|
|
23
|
+
lightning: v.toggle(true, '4-step lightning lora'),
|
|
24
|
+
prefix: v.text('qwen-image-edit'),
|
|
25
|
+
},
|
|
26
|
+
// async build: the reference image is uploaded (hash-named, deduped) per run
|
|
27
|
+
build: async (b, vars, wf) => {
|
|
28
|
+
const img = new MediaImage({ path: asAbsolutePath(image.absPath()) })
|
|
29
|
+
const loaded = await img.loadInWorkflow_viaLoadImageNode(wf)
|
|
30
|
+
const scaled = b.FluxKontextImageScale({ image: loaded })
|
|
31
|
+
|
|
32
|
+
const unet = b.UNETLoader({ unet_name: 'qwen_image_edit_2511_bf16.safetensors', weight_dtype: 'default' })
|
|
33
|
+
const clip = b.CLIPLoader({
|
|
34
|
+
clip_name: 'qwen_2.5_vl_7b_fp8_scaled.safetensors',
|
|
35
|
+
type: 'qwen_image',
|
|
36
|
+
device: 'default',
|
|
37
|
+
})
|
|
38
|
+
const vae = b.VAELoader({ vae_name: 'qwen_image_vae.safetensors' })
|
|
39
|
+
|
|
40
|
+
let model = b.CFGNorm({
|
|
41
|
+
model: b.ModelSamplingAuraFlow({ model: unet, shift: 3.1 }),
|
|
42
|
+
strength: 1,
|
|
43
|
+
pre_cfg: false,
|
|
44
|
+
})._MODEL
|
|
45
|
+
if (vars.lightning) {
|
|
46
|
+
model = b.LoraLoaderModelOnly({
|
|
47
|
+
model,
|
|
48
|
+
lora_name: 'Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors',
|
|
49
|
+
strength_model: 1,
|
|
50
|
+
})._MODEL
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// both branches carry the reference through the kontext latent method (template shape)
|
|
54
|
+
const positive = b.FluxKontextMultiReferenceLatentMethod({
|
|
55
|
+
reference_latents_method: 'index_timestep_zero',
|
|
56
|
+
conditioning: b.TextEncodeQwenImageEditPlus({ clip, prompt: vars.prompt.positive, vae, image1: scaled }),
|
|
57
|
+
})
|
|
58
|
+
const negative = b.FluxKontextMultiReferenceLatentMethod({
|
|
59
|
+
reference_latents_method: 'index_timestep_zero',
|
|
60
|
+
conditioning: b.TextEncodeQwenImageEditPlus({ clip, prompt: vars.prompt.negative, vae, image1: scaled }),
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const samples = b.KSampler({
|
|
64
|
+
model,
|
|
65
|
+
positive,
|
|
66
|
+
negative,
|
|
67
|
+
latent_image: b.VAEEncode({ pixels: scaled, vae }),
|
|
68
|
+
seed: vars.seed,
|
|
69
|
+
steps: vars.steps,
|
|
70
|
+
cfg: vars.lightning ? 1 : 4,
|
|
71
|
+
sampler_name: 'euler',
|
|
72
|
+
scheduler: 'simple',
|
|
73
|
+
denoise: 1,
|
|
74
|
+
})
|
|
75
|
+
b.SaveImage({ images: b.VAEDecode({ samples, vae }), filename_prefix: vars.prefix })
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
export default qwenImageEdit
|
|
80
|
+
|
|
81
|
+
// standalone run (skipped when another driver — e.g. the TUI — imports this module)
|
|
82
|
+
if (import.meta.main) {
|
|
83
|
+
if (process.argv[2]) qwenImageEdit.vars.image.set(process.argv[2])
|
|
84
|
+
if (process.argv[3]) qwenImageEdit.vars.prompt.set(process.argv[3])
|
|
85
|
+
|
|
86
|
+
const execution = await qwenImageEdit.run({ log: true })
|
|
87
|
+
for (const img of execution.images) console.log(`🟢 ${img.absPath}`)
|
|
88
|
+
host.disconnect()
|
|
89
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "comfy-ts",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
],
|
|
22
22
|
"author": "Rémi Vion <vion.remi@gmail.com>",
|
|
23
23
|
"license": "MIT",
|
|
24
|
+
"funding": "https://github.com/sponsors/rvion",
|
|
24
25
|
"repository": {
|
|
25
26
|
"type": "git",
|
|
26
27
|
"url": "https://github.com/rvion/comfy-ts.git"
|
|
@@ -81,8 +82,11 @@
|
|
|
81
82
|
"templates:fetch": "bun scripts/fetch-templates.ts",
|
|
82
83
|
"templates:check": "bun scripts/check-templates.ts",
|
|
83
84
|
"hooks:install": "git config core.hooksPath .githooks",
|
|
85
|
+
"release": "bun scripts/release.ts",
|
|
86
|
+
"release:dry": "bun scripts/release.ts --dry-run",
|
|
84
87
|
"prepublishOnly": "bun run ci && bun run build",
|
|
85
|
-
"tui": "bun src/cli/comfy-ts-cli.ts tui"
|
|
88
|
+
"tui": "bun src/cli/comfy-ts-cli.ts tui",
|
|
89
|
+
"serve": "bun src/cli/comfy-ts-cli.ts serve"
|
|
86
90
|
},
|
|
87
91
|
"rvt": {
|
|
88
92
|
"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
|
+
}
|