comfy-ts 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +23 -0
  2. package/dist/{run-serve-B5PfIuhK.js → ServeApp-BSA5yzxZ.js} +28 -446
  3. package/dist/ServeApp-BSA5yzxZ.js.map +1 -0
  4. package/dist/cli.js +18 -5
  5. package/dist/cli.js.map +1 -1
  6. package/dist/exampleAssets-BfWzygoM.js +38 -0
  7. package/dist/exampleAssets-BfWzygoM.js.map +1 -0
  8. package/dist/{LogsSt-C3UIWR-o.js → findDefinedWorkflow-0lG-VTEd.js} +201 -201
  9. package/dist/findDefinedWorkflow-0lG-VTEd.js.map +1 -0
  10. package/dist/index.cjs +202 -62
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +115 -14
  13. package/dist/index.d.ts +115 -14
  14. package/dist/index.js +202 -62
  15. package/dist/index.js.map +1 -1
  16. package/dist/run-run-DnaMLCFn.js +450 -0
  17. package/dist/run-run-DnaMLCFn.js.map +1 -0
  18. package/dist/run-serve-CbKxIu6i.js +418 -0
  19. package/dist/run-serve-CbKxIu6i.js.map +1 -0
  20. package/dist/{run-tui-D-N4_yyX.js → run-tui-B0AQWbad.js} +6 -37
  21. package/dist/run-tui-B0AQWbad.js.map +1 -0
  22. package/dist/{schemaDrift-BkN8rLiZ.js → schemaDrift-CbsABBuk.js} +59 -5
  23. package/dist/schemaDrift-CbsABBuk.js.map +1 -0
  24. package/dist/serve-web.js +48 -48
  25. package/dist/{state-CZsYJqB6.js → state-C2oDiQ26.js} +146 -60
  26. package/dist/state-C2oDiQ26.js.map +1 -0
  27. package/dist/web.d.ts +115 -14
  28. package/dist/web.js +202 -62
  29. package/dist/web.js.map +1 -1
  30. package/examples/README.md +2 -0
  31. package/examples/media/README.md +6 -5
  32. package/examples/media/voice_en_6s.flac +0 -0
  33. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +9 -1
  34. package/examples/rvion/10-anima-t2i.cflow.ts +8 -1
  35. package/examples/rvion/15-tts-voice-clone.cflow.ts +111 -0
  36. package/examples/rvion/16-tts-voice-design.cflow.ts +71 -0
  37. package/guide-for-agents.md +5 -1
  38. package/package.json +2 -2
  39. package/src/cli/comfy-ts-cli.ts +14 -1
  40. package/src/cli/run/findModules.ts +36 -0
  41. package/src/cli/run/flagValue.ts +61 -0
  42. package/src/cli/run/outputPaths.ts +41 -0
  43. package/src/cli/run/pickModule.ts +41 -0
  44. package/src/cli/run/run-run.ts +250 -0
  45. package/src/cli/run/runArgs.ts +61 -0
  46. package/src/cli/run/sidecar.ts +27 -0
  47. package/src/cli/serve/ServeApp.ts +28 -42
  48. package/src/cli/serve/web/components/DraftTabs.tsx +10 -3
  49. package/src/cli/serve/web/components/Gallery.tsx +2 -1
  50. package/src/cli/serve/web/components/HistoryPicker.tsx +5 -3
  51. package/src/cli/serve/web/components/MenuButton.tsx +2 -4
  52. package/src/cli/serve/web/components/Omnibox.tsx +2 -1
  53. package/src/cli/serve/web/components/PromptEnhancer.tsx +4 -3
  54. package/src/cli/serve/web/components/ShortcutsModal.tsx +2 -1
  55. package/src/cli/serve/web/components/SideMenu.tsx +2 -1
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +4 -3
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +2 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +2 -1
  59. package/src/cli/serve/web/components/controls/SizeControl.tsx +2 -1
  60. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  61. package/src/cli/serve/web/state/escape.ts +16 -0
  62. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  63. package/src/coreExports.ts +12 -1
  64. package/src/host/ComfyHost.ts +73 -40
  65. package/src/host/previewMethod.ts +29 -0
  66. package/src/runner/ComfyExecution.ts +45 -1
  67. package/src/runner/ComfyWorkflow.ts +6 -1
  68. package/src/runner/ComfyWsApi.ts +1 -1
  69. package/src/runner/wsBinaryFrame.ts +48 -25
  70. package/src/vars/ComfyVars.ts +86 -13
  71. package/src/vars/DefinedWorkflow.ts +36 -2
  72. package/dist/LogsSt-C3UIWR-o.js.map +0 -1
  73. package/dist/run-serve-B5PfIuhK.js.map +0 -1
  74. package/dist/run-tui-D-N4_yyX.js.map +0 -1
  75. package/dist/schemaDrift-BkN8rLiZ.js.map +0 -1
  76. package/dist/state-CZsYJqB6.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-BkN8rLiZ.js";
3
- import { a as ComfySchema, r as readableStringify, t as ComfyTS } from "./state-CZsYJqB6.js";
2
+ import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-CbsABBuk.js";
3
+ import { a as ComfySchema, r as readableStringify, t as ComfyTS } from "./state-C2oDiQ26.js";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmdirSync, writeFileSync } from "node:fs";
@@ -260,6 +260,15 @@ Usage:
260
260
  panel. No bundled examples, no auth, and any origin may call it: use
261
261
  --host beyond localhost only on a network you trust.
262
262
 
263
+ comfy-ts run <name | module.cflow.ts> [--draft <name>] [--<var> <value>…] [--out <path>] [--json]
264
+ ONE generation, headless, with live progress: the module is found in cwd,
265
+ then in the examples bundled with comfy-ts, by its key (10-anima-t2i), its
266
+ key without the number (anima-t2i) or a unique part (anima). Each var is a
267
+ flag (--prompt "…" --seed 7 --image in.png), --<var>-file reads a text var
268
+ from a file, --out writes the output there (several: a-1.png, a-2.png; a
269
+ dir keeps the server's names). \`comfy-ts run <name> --help\` lists the vars,
270
+ \`comfy-ts run\` lists the modules. --json prints one line with the paths
271
+
263
272
  comfy-ts help
264
273
  `;
265
274
  async function main() {
@@ -267,7 +276,7 @@ async function main() {
267
276
  if (cmd === "gen") return runGen(rest);
268
277
  if (cmd === "outline") return runOutline(rest);
269
278
  if (cmd === "loras") return runLoras(rest);
270
- if (cmd === "tui" || cmd === "serve") {
279
+ if (cmd === "tui" || cmd === "serve" || cmd === "run") {
271
280
  if (process.versions.bun == null) {
272
281
  const res = spawnSync("bun", [
273
282
  fileURLToPath(import.meta.url),
@@ -277,11 +286,15 @@ async function main() {
277
286
  if (res.error == null) return res.status ?? 1;
278
287
  console.error(`[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`);
279
288
  }
289
+ if (cmd === "run") {
290
+ const { runRun } = await import("./run-run-DnaMLCFn.js");
291
+ return runRun(rest);
292
+ }
280
293
  if (cmd === "serve") {
281
- const { runServe } = await import("./run-serve-B5PfIuhK.js");
294
+ const { runServe } = await import("./run-serve-CbKxIu6i.js");
282
295
  return runServe(rest);
283
296
  }
284
- const { runTui } = await import("./run-tui-D-N4_yyX.js");
297
+ const { runTui } = await import("./run-tui-B0AQWbad.js");
285
298
  return runTui(rest);
286
299
  }
287
300
  console.log(HELP);
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/flags.ts","../src/cli/gen.ts","../src/cli/loras.ts","../src/cli/outline.ts","../src/cli/comfy-ts-cli.ts"],"sourcesContent":["/**\n * the CLI's one flag reader: `--name value`.\n * A flag written with no value after it is a TYPO, never a request for the\n * default — silently falling back would run against the wrong host.\n */\nexport function flagReader(args: string[]): (name: string) => string | null {\n return (name: string): string | null => {\n const ix = args.indexOf(`--${name}`)\n if (ix < 0) return null\n const value = args[ix + 1]\n if (value == null || value.startsWith('--')) throw new Error(`--${name} needs a value`)\n return value\n }\n}\n","// fetch a live host's schema and generate its typed sdk\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { ComfyTS } from 'src/state.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\n\nexport async function runGen(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n const hostUrl = getFlag('host') ?? 'http://127.0.0.1:8188'\n const id = getFlag('id')\n if (id == null) {\n console.error('[comfy-ts gen] 🔴 --id <host-id> is required (it names .comfy-ts/hosts/<id>/)')\n return 1\n }\n\n // the lib's own authed host.fetch does the /api-first probing + X-API-Key\n const comfy = ComfyTS.create()\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n const fetchJSON = async <T>(route: string): Promise<T> => {\n console.log(`[comfy-ts gen] fetching ${hostUrl} ${route} …`)\n const res = await host.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${hostUrl}: ${res.status}`)\n if (!(res.headers.get('content-type') ?? '').includes('json'))\n throw new Error(`GET ${route} on ${hostUrl} did not answer json`)\n return (await res.json()) as T\n }\n\n const spec = await fetchJSON<ComfySchemaJSON>('/object_info')\n const embeddings = await fetchJSON<string[]>('/embeddings').catch(() => [] as string[])\n\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'object_info.json'), readableStringify(spec, 4), 'utf8')\n writeFileSync(join(dir, 'embeddings.json'), JSON.stringify(embeddings), 'utf8')\n\n const parsed = new ComfySchema({ spec, embeddings })\n const dts = parsed.codegenDTS({ hostId: id })\n // --out: explicit sdk home (the committed cloud catalog) — the json dumps\n // above still cache under .comfy-ts/hosts/<id>/, but the sdk must exist at\n // ONE tsconfig-visible path only, so it skips the hosts dir entirely\n const out = getFlag('out')\n const outPath = out != null ? resolve(process.cwd(), out) : join(dir, 'sdk.d.ts')\n if (out != null) mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, dts, 'utf8')\n console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`)\n if (out == null)\n console.log(`[comfy-ts gen] add \".comfy-ts/hosts/**/sdk.d.ts\" to your tsconfig \"include\" to activate the types`)\n return 0\n}\n","// refresh the local mirror of what ComfyUI-Lora-Manager knows about a host's loras\nimport { readdirSync, rmdirSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { buildLoraMirror, readLoraMirror, writeLoraMirror } from 'src/host/loraInfoCache.ts'\nimport { fetchLoraList, lmModelName, lmTrainedWords } from 'src/host/loraManagerApi.ts'\nimport { ComfyTS } from 'src/state.ts'\n\nconst DEFAULT_HOST_URL = 'http://127.0.0.1:8188'\n\n/** host ids already known on disk — `.comfy-ts/hosts/<id>/` is created by `comfy-ts gen` */\nfunction knownHostIds(): string[] {\n try {\n return readdirSync(join(process.cwd(), '.comfy-ts', 'hosts'), { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .sort()\n } catch {\n return []\n }\n}\n\nexport async function runLoras(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n\n // --id: explicit, else the only host folder on disk (unambiguous), else loud\n const known = knownHostIds()\n const explicitId = getFlag('id')\n const id = explicitId ?? (known.length === 1 ? known[0] : null)\n if (id == null) {\n const hint =\n known.length === 0 ? 'none yet — run `comfy-ts gen --id <host-id> --host <url>` first' : known.join(', ')\n console.error(`[comfy-ts loras] 🔴 --id <host-id> is required (known: ${hint})`)\n return 1\n }\n // registering a host MKDIRS .comfy-ts/hosts/<id>/, so a typo used to leave a\n // junk folder that broke the `--id` default (and outline's) for good. Rather\n // than refuse unknown ids — `loras` has no real dependency on `gen` — remember\n // whether the folder pre-existed and take it back if the sweep fails.\n const hostDirExisted = known.includes(id)\n\n // ComfyTS FIRST: every .comfy-ts path, the mirror's included, resolves through the global\n const comfy = ComfyTS.create()\n\n // --host: explicit, else the url the last sync remembered for this id\n const previous = readLoraMirror(id)\n const hostUrl = getFlag('host') ?? (previous?.hostUrl !== '' ? previous?.hostUrl : null) ?? DEFAULT_HOST_URL\n\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n /** a sweep that never produced a mirror must leave no trace of this run */\n const abandon = (): void => {\n if (hostDirExisted) return\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n try {\n if (readdirSync(dir).length === 0) rmdirSync(dir)\n } catch {\n // best effort: a non-empty or vanished dir is not this command's business\n }\n }\n\n console.log(`[comfy-ts loras] sweeping ${hostUrl} /api/lm/loras/list …`)\n const sweep = await fetchLoraList(host)\n if (sweep.status === 'absent') {\n console.error(\n `[comfy-ts loras] 🔴 ${hostUrl} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,\n )\n abandon()\n return 1\n }\n if (sweep.status === 'unreachable') {\n console.error(`[comfy-ts loras] 🔴 ${hostUrl} unreachable — ${sweep.reason}. Mirror left untouched.`)\n abandon()\n return 1\n }\n if (sweep.status === 'partial') {\n // writing this would DELETE loras from the mirror that are alive on the\n // host, and every surface would then quietly not know them\n console.error(\n `[comfy-ts loras] 🔴 the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched. Re-run when the host is healthy.`,\n )\n abandon()\n return 1\n }\n\n const mirror = buildLoraMirror({ hostId: id, hostUrl, fetchedAt: new Date().toISOString(), items: sweep.items })\n const path = writeLoraMirror(mirror)\n\n // what actually moved since the last sync — the whole point of running it again\n const before = previous?.loras ?? {}\n const added: string[] = []\n const changed: string[] = []\n let withWords = 0\n for (const [key, item] of Object.entries(mirror.loras)) {\n const words = lmTrainedWords(item)\n if (words.length > 0) withWords++\n const old = before[key]\n if (old == null) {\n if (words.length > 0) added.push(`${key} → ${words.join(', ')}`)\n else added.push(key)\n } else if (lmTrainedWords(old).join('\\0') !== words.join('\\0')) {\n changed.push(`${key} → ${words.length === 0 ? '(cleared)' : words.join(', ')}`)\n }\n }\n const removed = Object.keys(before).filter((k) => mirror.loras[k] == null)\n\n const sample = (label: string, lines: string[]): void => {\n if (lines.length === 0) return\n console.log(`[comfy-ts loras] ${label} (${lines.length}):`)\n for (const line of lines.slice(0, 10)) console.log(` ${line}`)\n if (lines.length > 10) console.log(` … +${lines.length - 10} more`)\n }\n sample('added', added)\n sample('trigger words changed', changed)\n sample('gone from the host', removed)\n\n const named = Object.values(mirror.loras).filter((i) => lmModelName(i) != null).length\n console.log(\n `[comfy-ts loras] 🟢 ${path} — ${mirror.count} loras, ${withWords} with trigger words, ${named} with a model name`,\n )\n if (previous == null) console.log(`[comfy-ts loras] next time: \\`comfy-ts loras --id ${id}\\` (url remembered)`)\n return 0\n}\n","// outline a generated sdk.d.ts without reading 2MB blind\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'pathe'\n\ntype Section = { name: string; kind: string; start: number; end: number; depth: number }\n\nfunction findDefaultSdk(): string | null {\n const hostsDir = join(process.cwd(), '.comfy-ts', 'hosts')\n if (!existsSync(hostsDir)) return null\n for (const id of readdirSync(hostsDir)) {\n const p = join(hostsDir, id, 'sdk.d.ts')\n if (existsSync(p)) return p\n }\n return null\n}\n\nexport function runOutline(args: string[]): number {\n const linesFlagIx = args.indexOf('--lines')\n const maxLines = linesFlagIx >= 0 ? Number(args[linesFlagIx + 1] ?? 10) : null\n const sectionFlagIx = args.indexOf('--section')\n const wantedSection = sectionFlagIx >= 0 ? args[sectionFlagIx + 1] : null\n const flagValueIxs = new Set([linesFlagIx + 1, sectionFlagIx + 1].filter((ix) => ix > 0))\n const fileArg = args.find((a, ix) => !a.startsWith('--') && !flagValueIxs.has(ix))\n\n const file = fileArg ?? findDefaultSdk()\n if (file == null || !existsSync(file)) {\n console.error('[sdk-outline] 🔴 no sdk.d.ts found; pass a path explicitly')\n return 1\n }\n\n const lines = readFileSync(file, 'utf8').split('\\n')\n\n // scan: track brace depth, record interface/type/namespace declarations up to depth 3\n const sections: Section[] = []\n const stack: Section[] = []\n let depth = 0\n const declRe = /^\\s*(?:export\\s+)?(interface|namespace|type)\\s+([A-Za-z0-9_$]+)/\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n const m = depth <= 3 ? declRe.exec(line) : null\n const opens = (line.match(/{/g) ?? []).length\n const closes = (line.match(/}/g) ?? []).length\n if (m && (opens > 0 || m[1] === 'type')) {\n const sec: Section = { name: m[2] ?? '?', kind: m[1] ?? '?', start: i + 1, end: i + 1, depth }\n sections.push(sec)\n if (opens > closes) stack.push(sec)\n }\n depth += opens - closes\n while (stack.length > 0 && depth <= (stack[stack.length - 1]?.depth ?? 0)) {\n const closed = stack.pop()\n if (closed) closed.end = i + 1\n }\n // type aliases (no braces): extend until next decl at same depth\n const last = sections[sections.length - 1]\n if (last && last.kind === 'type' && stack[stack.length - 1] !== last) last.end = Math.max(last.end, i)\n }\n\n if (wantedSection) {\n const sec = sections.find((s) => s.name === wantedSection)\n if (sec == null) {\n console.error(\n `[sdk-outline] 🔴 section \"${wantedSection}\" not found. Available: ${sections.map((s) => s.name).join(', ')}`,\n )\n return 1\n }\n const body = lines.slice(sec.start - 1, maxLines ? Math.min(sec.end, sec.start - 1 + maxLines) : sec.end)\n console.log(body.join('\\n'))\n if (maxLines && sec.end - sec.start + 1 > maxLines)\n console.log(`… (${sec.end - sec.start + 1 - maxLines} more lines, ends at line ${sec.end})`)\n } else {\n console.log(`${file} — ${lines.length} lines\\n`)\n for (const s of sections) {\n const indent = ' '.repeat(s.depth)\n console.log(`${indent}${s.kind} ${s.name} [${s.start}-${s.end}] (${s.end - s.start + 1} lines)`)\n if (maxLines) {\n const body = lines.slice(s.start - 1, s.start - 1 + maxLines)\n console.log(body.map((l) => `${indent} │ ${l.trim()}`).join('\\n'))\n }\n }\n }\n return 0\n}\n","#!/usr/bin/env node\n// sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code\nimport { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { runGen } from 'src/cli/gen.ts'\nimport { runLoras } from 'src/cli/loras.ts'\nimport { runOutline } from 'src/cli/outline.ts'\n\nconst HELP = `comfy-ts — typed SDK codegen for ComfyUI\n\nUsage:\n comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] [--api-key <key>] [--out <sdk-path>]\n fetch object_info + embeddings from a live ComfyUI host and write\n .comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}\n (--api-key or COMFY_CLOUD_API_KEY authenticates via X-API-Key;\n --out relocates ONLY the sdk.d.ts, e.g. a committed cloud catalog)\n\n comfy-ts outline [file] [--lines N] [--section Name]\n outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)\n\n comfy-ts loras [--id <host-id>] [--host http://…] [--api-key <key>]\n mirror what the optional ComfyUI-Lora-Manager extension knows about\n every lora into .comfy-ts/hosts/<id>/loras.json: real model names,\n civitai trigger words, tags, base model, preview urls. The TUI then\n fuzzy-matches loras by their human name and auto-injects their trigger\n words into v.prompt (⌃K still overrides, per lora). --id defaults to\n the only host folder on disk, --host to the url the last sync used\n\n comfy-ts tui [dir | workflow-module.ts]\n interactive tweak & re-run over **/*.cflow.ts modules (exporting\n host.defineWorkflow(...)); no arg scans cwd + the examples bundled\n with comfy-ts, an explicit dir/file limits to it (file preselected)\n\n comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--host 127.0.0.1]\n drafts as a local HTTP generation API: POST /generate/<module>/<draft>\n with { ...vars } overriding the draft's values (blocking; raw image\n bytes under Accept: image/*), GET /drafts self-describes every var,\n GET /outputs/... serves the results. Open / in a browser for the web\n panel. No bundled examples, no auth, and any origin may call it: use\n --host beyond localhost only on a network you trust.\n\n comfy-ts help\n`\n\nasync function main(): Promise<number> {\n const [cmd, ...rest] = process.argv.slice(2)\n if (cmd === 'gen') return runGen(rest)\n if (cmd === 'outline') return runOutline(rest)\n if (cmd === 'loras') return runLoras(rest)\n if (cmd === 'tui' || cmd === 'serve') {\n // .cflow.ts workflow modules need bun: node refuses to strip types under\n // node_modules, exactly where the packaged examples live — and the bin's\n // node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop\n // to bun when we are not already in it; without bun, degrade loudly.\n if (process.versions.bun == null) {\n const self = fileURLToPath(import.meta.url)\n const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })\n if (res.error == null) return res.status ?? 1\n console.error(\n `[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`,\n )\n }\n if (cmd === 'serve') {\n const { runServe } = await import('src/cli/serve/run-serve.ts')\n return runServe(rest)\n }\n // lazy import: keeps ink/react out of the codegen paths\n const { runTui } = await import('src/cli/tui/run-tui.tsx')\n return runTui(rest)\n }\n console.log(HELP)\n return cmd == null || cmd === 'help' ? 0 : 1\n}\n\n// a thrown command (a flag with no value, an unreadable path) must print ONE\n// clear line and exit non-zero, never a raw unhandled-rejection stack\nprocess.exitCode = await main().catch((e: unknown) => {\n console.error(`[comfy-ts] 🔴 ${e instanceof Error ? e.message : String(e)}`)\n return 1\n})\n"],"mappings":";;;;;;;;;;;;;AAKA,SAAgB,WAAW,MAAiD;CACzE,QAAQ,SAAgC;EACrC,MAAM,KAAK,KAAK,QAAQ,KAAK,MAAM;EACnC,IAAI,KAAK,GAAG,OAAO;EACnB,MAAM,QAAQ,KAAK,KAAK;EACxB,IAAI,SAAS,QAAQ,MAAM,WAAW,IAAI,GAAG,MAAM,IAAI,MAAM,KAAK,KAAK,eAAe;EACtF,OAAO;CACV;AACH;;;ACJA,eAAsB,OAAO,MAAiC;CAC3D,MAAM,UAAU,WAAW,IAAI;CAC/B,MAAM,UAAU,QAAQ,MAAM,KAAK;CACnC,MAAM,KAAK,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AM,CAAC;CAC3C,IAAI,QAAQ,OAAO,OAAO,OAAO,IAAI;CACrC,IAAI,QAAQ,WAAW,OAAO,WAAW,IAAI;CAC7C,IAAI,QAAQ,SAAS,OAAO,SAAS,IAAI;CACzC,IAAI,QAAQ,SAAS,QAAQ,SAAS;EAKnC,IAAI,QAAQ,SAAS,OAAO,MAAM;GAE/B,MAAM,MAAM,UAAU,OAAO;IADhB,cAAc,OAAO,KAAK,GACN;IAAG;IAAK,GAAG;GAAI,GAAG,EAAE,OAAO,UAAU,CAAC;GACvE,IAAI,IAAI,SAAS,MAAM,OAAO,IAAI,UAAU;GAC5C,QAAQ,MACL,aAAa,IAAI,mBAAmB,IAAI,MAAM,QAAQ,gJACzD;EACH;EACA,IAAI,QAAQ,SAAS;GAClB,MAAM,EAAE,aAAa,MAAM,OAAO;GAClC,OAAO,SAAS,IAAI;EACvB;EAEA,MAAM,EAAE,WAAW,MAAM,OAAO;EAChC,OAAO,OAAO,IAAI;CACrB;CACA,QAAQ,IAAI,IAAI;CAChB,OAAO,OAAO,QAAQ,QAAQ,SAAS,IAAI;AAC9C;AAIA,QAAQ,WAAW,MAAM,KAAK,CAAC,CAAC,OAAO,MAAe;CACnD,QAAQ,MAAM,iBAAiB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG;CAC3E,OAAO;AACV,CAAC"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/flags.ts","../src/cli/gen.ts","../src/cli/loras.ts","../src/cli/outline.ts","../src/cli/comfy-ts-cli.ts"],"sourcesContent":["/**\n * the CLI's one flag reader: `--name value`.\n * A flag written with no value after it is a TYPO, never a request for the\n * default — silently falling back would run against the wrong host.\n */\nexport function flagReader(args: string[]): (name: string) => string | null {\n return (name: string): string | null => {\n const ix = args.indexOf(`--${name}`)\n if (ix < 0) return null\n const value = args[ix + 1]\n if (value == null || value.startsWith('--')) throw new Error(`--${name} needs a value`)\n return value\n }\n}\n","// fetch a live host's schema and generate its typed sdk\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'\nimport type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'\nimport { ComfyTS } from 'src/state.ts'\nimport { readableStringify } from 'src/utils/stringifyReadable.ts'\n\nexport async function runGen(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n const hostUrl = getFlag('host') ?? 'http://127.0.0.1:8188'\n const id = getFlag('id')\n if (id == null) {\n console.error('[comfy-ts gen] 🔴 --id <host-id> is required (it names .comfy-ts/hosts/<id>/)')\n return 1\n }\n\n // the lib's own authed host.fetch does the /api-first probing + X-API-Key\n const comfy = ComfyTS.create()\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n const fetchJSON = async <T>(route: string): Promise<T> => {\n console.log(`[comfy-ts gen] fetching ${hostUrl} ${route} …`)\n const res = await host.fetch(route)\n if (!res.ok) throw new Error(`GET ${route} failed on ${hostUrl}: ${res.status}`)\n if (!(res.headers.get('content-type') ?? '').includes('json'))\n throw new Error(`GET ${route} on ${hostUrl} did not answer json`)\n return (await res.json()) as T\n }\n\n const spec = await fetchJSON<ComfySchemaJSON>('/object_info')\n const embeddings = await fetchJSON<string[]>('/embeddings').catch(() => [] as string[])\n\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n mkdirSync(dir, { recursive: true })\n writeFileSync(join(dir, 'object_info.json'), readableStringify(spec, 4), 'utf8')\n writeFileSync(join(dir, 'embeddings.json'), JSON.stringify(embeddings), 'utf8')\n\n const parsed = new ComfySchema({ spec, embeddings })\n const dts = parsed.codegenDTS({ hostId: id })\n // --out: explicit sdk home (the committed cloud catalog) — the json dumps\n // above still cache under .comfy-ts/hosts/<id>/, but the sdk must exist at\n // ONE tsconfig-visible path only, so it skips the hosts dir entirely\n const out = getFlag('out')\n const outPath = out != null ? resolve(process.cwd(), out) : join(dir, 'sdk.d.ts')\n if (out != null) mkdirSync(dirname(outPath), { recursive: true })\n writeFileSync(outPath, dts, 'utf8')\n console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`)\n if (out == null)\n console.log(`[comfy-ts gen] add \".comfy-ts/hosts/**/sdk.d.ts\" to your tsconfig \"include\" to activate the types`)\n return 0\n}\n","// refresh the local mirror of what ComfyUI-Lora-Manager knows about a host's loras\nimport { readdirSync, rmdirSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { flagReader } from 'src/cli/flags.ts'\nimport { buildLoraMirror, readLoraMirror, writeLoraMirror } from 'src/host/loraInfoCache.ts'\nimport { fetchLoraList, lmModelName, lmTrainedWords } from 'src/host/loraManagerApi.ts'\nimport { ComfyTS } from 'src/state.ts'\n\nconst DEFAULT_HOST_URL = 'http://127.0.0.1:8188'\n\n/** host ids already known on disk — `.comfy-ts/hosts/<id>/` is created by `comfy-ts gen` */\nfunction knownHostIds(): string[] {\n try {\n return readdirSync(join(process.cwd(), '.comfy-ts', 'hosts'), { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => e.name)\n .sort()\n } catch {\n return []\n }\n}\n\nexport async function runLoras(args: string[]): Promise<number> {\n const getFlag = flagReader(args)\n\n // --id: explicit, else the only host folder on disk (unambiguous), else loud\n const known = knownHostIds()\n const explicitId = getFlag('id')\n const id = explicitId ?? (known.length === 1 ? known[0] : null)\n if (id == null) {\n const hint =\n known.length === 0 ? 'none yet — run `comfy-ts gen --id <host-id> --host <url>` first' : known.join(', ')\n console.error(`[comfy-ts loras] 🔴 --id <host-id> is required (known: ${hint})`)\n return 1\n }\n // registering a host MKDIRS .comfy-ts/hosts/<id>/, so a typo used to leave a\n // junk folder that broke the `--id` default (and outline's) for good. Rather\n // than refuse unknown ids — `loras` has no real dependency on `gen` — remember\n // whether the folder pre-existed and take it back if the sweep fails.\n const hostDirExisted = known.includes(id)\n\n // ComfyTS FIRST: every .comfy-ts path, the mirror's included, resolves through the global\n const comfy = ComfyTS.create()\n\n // --host: explicit, else the url the last sync remembered for this id\n const previous = readLoraMirror(id)\n const hostUrl = getFlag('host') ?? (previous?.hostUrl !== '' ? previous?.hostUrl : null) ?? DEFAULT_HOST_URL\n\n const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY\n const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })\n\n /** a sweep that never produced a mirror must leave no trace of this run */\n const abandon = (): void => {\n if (hostDirExisted) return\n const dir = join(process.cwd(), '.comfy-ts', 'hosts', id)\n try {\n if (readdirSync(dir).length === 0) rmdirSync(dir)\n } catch {\n // best effort: a non-empty or vanished dir is not this command's business\n }\n }\n\n console.log(`[comfy-ts loras] sweeping ${hostUrl} /api/lm/loras/list …`)\n const sweep = await fetchLoraList(host)\n if (sweep.status === 'absent') {\n console.error(\n `[comfy-ts loras] 🔴 ${hostUrl} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,\n )\n abandon()\n return 1\n }\n if (sweep.status === 'unreachable') {\n console.error(`[comfy-ts loras] 🔴 ${hostUrl} unreachable — ${sweep.reason}. Mirror left untouched.`)\n abandon()\n return 1\n }\n if (sweep.status === 'partial') {\n // writing this would DELETE loras from the mirror that are alive on the\n // host, and every surface would then quietly not know them\n console.error(\n `[comfy-ts loras] 🔴 the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched. Re-run when the host is healthy.`,\n )\n abandon()\n return 1\n }\n\n const mirror = buildLoraMirror({ hostId: id, hostUrl, fetchedAt: new Date().toISOString(), items: sweep.items })\n const path = writeLoraMirror(mirror)\n\n // what actually moved since the last sync — the whole point of running it again\n const before = previous?.loras ?? {}\n const added: string[] = []\n const changed: string[] = []\n let withWords = 0\n for (const [key, item] of Object.entries(mirror.loras)) {\n const words = lmTrainedWords(item)\n if (words.length > 0) withWords++\n const old = before[key]\n if (old == null) {\n if (words.length > 0) added.push(`${key} → ${words.join(', ')}`)\n else added.push(key)\n } else if (lmTrainedWords(old).join('\\0') !== words.join('\\0')) {\n changed.push(`${key} → ${words.length === 0 ? '(cleared)' : words.join(', ')}`)\n }\n }\n const removed = Object.keys(before).filter((k) => mirror.loras[k] == null)\n\n const sample = (label: string, lines: string[]): void => {\n if (lines.length === 0) return\n console.log(`[comfy-ts loras] ${label} (${lines.length}):`)\n for (const line of lines.slice(0, 10)) console.log(` ${line}`)\n if (lines.length > 10) console.log(` … +${lines.length - 10} more`)\n }\n sample('added', added)\n sample('trigger words changed', changed)\n sample('gone from the host', removed)\n\n const named = Object.values(mirror.loras).filter((i) => lmModelName(i) != null).length\n console.log(\n `[comfy-ts loras] 🟢 ${path} — ${mirror.count} loras, ${withWords} with trigger words, ${named} with a model name`,\n )\n if (previous == null) console.log(`[comfy-ts loras] next time: \\`comfy-ts loras --id ${id}\\` (url remembered)`)\n return 0\n}\n","// outline a generated sdk.d.ts without reading 2MB blind\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'pathe'\n\ntype Section = { name: string; kind: string; start: number; end: number; depth: number }\n\nfunction findDefaultSdk(): string | null {\n const hostsDir = join(process.cwd(), '.comfy-ts', 'hosts')\n if (!existsSync(hostsDir)) return null\n for (const id of readdirSync(hostsDir)) {\n const p = join(hostsDir, id, 'sdk.d.ts')\n if (existsSync(p)) return p\n }\n return null\n}\n\nexport function runOutline(args: string[]): number {\n const linesFlagIx = args.indexOf('--lines')\n const maxLines = linesFlagIx >= 0 ? Number(args[linesFlagIx + 1] ?? 10) : null\n const sectionFlagIx = args.indexOf('--section')\n const wantedSection = sectionFlagIx >= 0 ? args[sectionFlagIx + 1] : null\n const flagValueIxs = new Set([linesFlagIx + 1, sectionFlagIx + 1].filter((ix) => ix > 0))\n const fileArg = args.find((a, ix) => !a.startsWith('--') && !flagValueIxs.has(ix))\n\n const file = fileArg ?? findDefaultSdk()\n if (file == null || !existsSync(file)) {\n console.error('[sdk-outline] 🔴 no sdk.d.ts found; pass a path explicitly')\n return 1\n }\n\n const lines = readFileSync(file, 'utf8').split('\\n')\n\n // scan: track brace depth, record interface/type/namespace declarations up to depth 3\n const sections: Section[] = []\n const stack: Section[] = []\n let depth = 0\n const declRe = /^\\s*(?:export\\s+)?(interface|namespace|type)\\s+([A-Za-z0-9_$]+)/\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n const m = depth <= 3 ? declRe.exec(line) : null\n const opens = (line.match(/{/g) ?? []).length\n const closes = (line.match(/}/g) ?? []).length\n if (m && (opens > 0 || m[1] === 'type')) {\n const sec: Section = { name: m[2] ?? '?', kind: m[1] ?? '?', start: i + 1, end: i + 1, depth }\n sections.push(sec)\n if (opens > closes) stack.push(sec)\n }\n depth += opens - closes\n while (stack.length > 0 && depth <= (stack[stack.length - 1]?.depth ?? 0)) {\n const closed = stack.pop()\n if (closed) closed.end = i + 1\n }\n // type aliases (no braces): extend until next decl at same depth\n const last = sections[sections.length - 1]\n if (last && last.kind === 'type' && stack[stack.length - 1] !== last) last.end = Math.max(last.end, i)\n }\n\n if (wantedSection) {\n const sec = sections.find((s) => s.name === wantedSection)\n if (sec == null) {\n console.error(\n `[sdk-outline] 🔴 section \"${wantedSection}\" not found. Available: ${sections.map((s) => s.name).join(', ')}`,\n )\n return 1\n }\n const body = lines.slice(sec.start - 1, maxLines ? Math.min(sec.end, sec.start - 1 + maxLines) : sec.end)\n console.log(body.join('\\n'))\n if (maxLines && sec.end - sec.start + 1 > maxLines)\n console.log(`… (${sec.end - sec.start + 1 - maxLines} more lines, ends at line ${sec.end})`)\n } else {\n console.log(`${file} — ${lines.length} lines\\n`)\n for (const s of sections) {\n const indent = ' '.repeat(s.depth)\n console.log(`${indent}${s.kind} ${s.name} [${s.start}-${s.end}] (${s.end - s.start + 1} lines)`)\n if (maxLines) {\n const body = lines.slice(s.start - 1, s.start - 1 + maxLines)\n console.log(body.map((l) => `${indent} │ ${l.trim()}`).join('\\n'))\n }\n }\n }\n return 0\n}\n","#!/usr/bin/env node\n// sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code\nimport { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { runGen } from 'src/cli/gen.ts'\nimport { runLoras } from 'src/cli/loras.ts'\nimport { runOutline } from 'src/cli/outline.ts'\n\nconst HELP = `comfy-ts — typed SDK codegen for ComfyUI\n\nUsage:\n comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] [--api-key <key>] [--out <sdk-path>]\n fetch object_info + embeddings from a live ComfyUI host and write\n .comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}\n (--api-key or COMFY_CLOUD_API_KEY authenticates via X-API-Key;\n --out relocates ONLY the sdk.d.ts, e.g. a committed cloud catalog)\n\n comfy-ts outline [file] [--lines N] [--section Name]\n outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)\n\n comfy-ts loras [--id <host-id>] [--host http://…] [--api-key <key>]\n mirror what the optional ComfyUI-Lora-Manager extension knows about\n every lora into .comfy-ts/hosts/<id>/loras.json: real model names,\n civitai trigger words, tags, base model, preview urls. The TUI then\n fuzzy-matches loras by their human name and auto-injects their trigger\n words into v.prompt (⌃K still overrides, per lora). --id defaults to\n the only host folder on disk, --host to the url the last sync used\n\n comfy-ts tui [dir | workflow-module.ts]\n interactive tweak & re-run over **/*.cflow.ts modules (exporting\n host.defineWorkflow(...)); no arg scans cwd + the examples bundled\n with comfy-ts, an explicit dir/file limits to it (file preselected)\n\n comfy-ts serve [dir | workflow-module.ts] [--port 8288] [--host 127.0.0.1]\n drafts as a local HTTP generation API: POST /generate/<module>/<draft>\n with { ...vars } overriding the draft's values (blocking; raw image\n bytes under Accept: image/*), GET /drafts self-describes every var,\n GET /outputs/... serves the results. Open / in a browser for the web\n panel. No bundled examples, no auth, and any origin may call it: use\n --host beyond localhost only on a network you trust.\n\n comfy-ts run <name | module.cflow.ts> [--draft <name>] [--<var> <value>…] [--out <path>] [--json]\n ONE generation, headless, with live progress: the module is found in cwd,\n then in the examples bundled with comfy-ts, by its key (10-anima-t2i), its\n key without the number (anima-t2i) or a unique part (anima). Each var is a\n flag (--prompt \"…\" --seed 7 --image in.png), --<var>-file reads a text var\n from a file, --out writes the output there (several: a-1.png, a-2.png; a\n dir keeps the server's names). \\`comfy-ts run <name> --help\\` lists the vars,\n \\`comfy-ts run\\` lists the modules. --json prints one line with the paths\n\n comfy-ts help\n`\n\nasync function main(): Promise<number> {\n const [cmd, ...rest] = process.argv.slice(2)\n if (cmd === 'gen') return runGen(rest)\n if (cmd === 'outline') return runOutline(rest)\n if (cmd === 'loras') return runLoras(rest)\n if (cmd === 'tui' || cmd === 'serve' || cmd === 'run') {\n // .cflow.ts workflow modules need bun: node refuses to strip types under\n // node_modules, exactly where the packaged examples live — and the bin's\n // node shebang means `bunx comfy-ts tui|serve` lands here under NODE. Hop\n // to bun when we are not already in it; without bun, degrade loudly.\n if (process.versions.bun == null) {\n const self = fileURLToPath(import.meta.url)\n const res = spawnSync('bun', [self, cmd, ...rest], { stdio: 'inherit' })\n if (res.error == null) return res.status ?? 1\n console.error(\n `[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`,\n )\n }\n if (cmd === 'run') {\n const { runRun } = await import('src/cli/run/run-run.ts')\n return runRun(rest)\n }\n if (cmd === 'serve') {\n const { runServe } = await import('src/cli/serve/run-serve.ts')\n return runServe(rest)\n }\n // lazy import: keeps ink/react out of the codegen paths\n const { runTui } = await import('src/cli/tui/run-tui.tsx')\n return runTui(rest)\n }\n console.log(HELP)\n return cmd == null || cmd === 'help' ? 0 : 1\n}\n\n// a thrown command (a flag with no value, an unreadable path) must print ONE\n// clear line and exit non-zero, never a raw unhandled-rejection stack\nprocess.exitCode = await main().catch((e: unknown) => {\n console.error(`[comfy-ts] 🔴 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C9C;AAIA,QAAQ,WAAW,MAAM,KAAK,CAAC,CAAC,OAAO,MAAe;CACnD,QAAQ,MAAM,iBAAiB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG;CAC3E,OAAO;AACV,CAAC"}
@@ -0,0 +1,38 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, join } from "pathe";
4
+ //#region src/exampleAssets.ts
5
+ /**
6
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
7
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
8
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from
9
+ * this repo's src/. Returns null when the examples are absent (a consumer may
10
+ * prune the folder) or when the nearest named package is not comfy-ts (the lib
11
+ * was inlined into someone else's bundle — its examples are not on disk); no
12
+ * package.json all the way up is a broken install and throws.
13
+ */
14
+ function bundledExamplesDir(moduleUrl = import.meta.url) {
15
+ let dir = dirname(fileURLToPath(moduleUrl));
16
+ let prev = "";
17
+ while (dir !== prev) {
18
+ const pkgPath = join(dir, "package.json");
19
+ if (existsSync(pkgPath)) {
20
+ let pkg = {};
21
+ try {
22
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
23
+ } catch {}
24
+ if (pkg.name === "comfy-ts") {
25
+ const examples = join(dir, "examples");
26
+ return existsSync(examples) ? examples : null;
27
+ }
28
+ if (pkg.name != null) return null;
29
+ }
30
+ prev = dir;
31
+ dir = dirname(dir);
32
+ }
33
+ throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
34
+ }
35
+ //#endregion
36
+ export { bundledExamplesDir as t };
37
+
38
+ //# sourceMappingURL=exampleAssets-BfWzygoM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exampleAssets-BfWzygoM.js","names":[],"sources":["../src/exampleAssets.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join } from 'pathe'\n\n/**\n * the examples/ folder shipped in the npm tarball, resolved from THIS module's\n * own location (NEVER cwd): walking up to the nearest NAMED package.json finds\n * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/ and from\n * this repo's src/. Returns null when the examples are absent (a consumer may\n * prune the folder) or when the nearest named package is not comfy-ts (the lib\n * was inlined into someone else's bundle — its examples are not on disk); no\n * package.json all the way up is a broken install and throws.\n */\nexport function bundledExamplesDir(moduleUrl: string = import.meta.url): string | null {\n let dir = dirname(fileURLToPath(moduleUrl))\n let prev = ''\n while (dir !== prev) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n let pkg: { name?: string } = {}\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))\n } catch {\n // a malformed package.json on the walk (someone's broken fixture\n // dir) must not take the whole TUI down; treat as unnamed\n }\n if (pkg.name === 'comfy-ts') {\n const examples = join(dir, 'examples')\n return existsSync(examples) ? examples : null\n }\n if (pkg.name != null) return null\n }\n prev = dir\n dir = dirname(dir)\n }\n throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`)\n}\n\n/**\n * absolute path of a bundled `examples/images/` input image, e.g.\n * `exampleImagePath('bear_1024x1024.jpg')` — the out-of-the-box default for\n * i2i/i2v example image vars, valid from this repo AND from a consumer's\n * node_modules/comfy-ts/. Loud throw naming the path when the file is missing\n * or the package's examples/ folder was pruned.\n */\nexport function exampleImagePath(name: string): string {\n return bundledExampleFile('images', name)\n}\n\n/** the same for a bundled `examples/media/` audio or video file, e.g.\n * `exampleMediaPath('sine_440hz_3s.flac')` — the default of audio and video example vars */\nexport function exampleMediaPath(name: string): string {\n return bundledExampleFile('media', name)\n}\n\nfunction bundledExampleFile(folder: 'images' | 'media', name: string): string {\n const examples = bundledExamplesDir()\n if (examples == null) {\n throw new Error(\n `[comfy-ts] cannot resolve bundled example file '${name}': the package's examples/ folder is not on disk`,\n )\n }\n const abs = join(examples, folder, name)\n if (!existsSync(abs)) throw new Error(`[comfy-ts] bundled example file not found: ${abs}`)\n return abs\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,YAAoB,OAAO,KAAK,KAAoB;CACpF,IAAI,MAAM,QAAQ,cAAc,SAAS,CAAC;CAC1C,IAAI,OAAO;CACX,OAAO,QAAQ,MAAM;EAClB,MAAM,UAAU,KAAK,KAAK,cAAc;EACxC,IAAI,WAAW,OAAO,GAAG;GACtB,IAAI,MAAyB,CAAC;GAC9B,IAAI;IACD,MAAM,KAAK,MAAM,aAAa,SAAS,MAAM,CAAC;GACjD,QAAQ,CAGR;GACA,IAAI,IAAI,SAAS,YAAY;IAC1B,MAAM,WAAW,KAAK,KAAK,UAAU;IACrC,OAAO,WAAW,QAAQ,IAAI,WAAW;GAC5C;GACA,IAAI,IAAI,QAAQ,MAAM,OAAO;EAChC;EACA,OAAO;EACP,MAAM,QAAQ,GAAG;CACpB;CACA,MAAM,IAAI,MAAM,oDAAoD,cAAc,SAAS,GAAG;AACjG"}
@@ -1,49 +1,7 @@
1
- import { Q as stripAnsi, a as DefinedWorkflow, at as extractErrorMessage } from "./schemaDrift-BkN8rLiZ.js";
1
+ import { Q as stripAnsi, a as DefinedWorkflow, at as extractErrorMessage } from "./schemaDrift-CbsABBuk.js";
2
2
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, join } from "pathe";
4
4
  import { makeAutoObservable, reaction, runInAction } from "mobx";
5
- //#region src/cli/tui/discoverWorkflows.ts
6
- /**
7
- * recursive scan for the workflow-module naming convention. Entries BELOW a
8
- * node_modules segment are skipped: packaged examples arrive via
9
- * bundledExamplesDir (src/exampleAssets.ts — symlinked layouts like pnpm would
10
- * otherwise list them twice, un-deduped, as the user's own files), and
11
- * third-party packages shipping *.cflow.ts are not this project's workflows. A
12
- * scan root that is ITSELF inside node_modules still works (the filter is
13
- * relative to the root).
14
- */
15
- function scanCflowFiles(dir) {
16
- return readdirSync(dir, { recursive: true }).map((f) => String(f)).filter((f) => !f.split("/").includes("node_modules")).map((f) => join(dir, f)).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
17
- }
18
- /**
19
- * PURE merge of the scan with the packaged examples (headless-tested). An
20
- * explicit target keeps its scope only. Bundled files ALWAYS group under the
21
- * bundled section, also when the scan already found them (repo dev: ./examples
22
- * is under cwd) — dedupe relies on the caller passing realpath-normalized
23
- * strings on both sides.
24
- */
25
- function mergeWorkflowSources(p) {
26
- if (p.explicitTarget) return {
27
- files: p.scanned,
28
- bundled: /* @__PURE__ */ new Set()
29
- };
30
- const bundled = new Set(p.bundledFiles);
31
- return {
32
- files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
33
- bundled
34
- };
35
- }
36
- //#endregion
37
- //#region src/cli/tui/findDefinedWorkflow.ts
38
- /**
39
- * instanceof first; duck-type fallback covers a second copy of the library in
40
- * the module graph (linked dev setups, npm dedupe misses)
41
- */
42
- function findDefinedWorkflow(mod) {
43
- const isDefined = (x) => x instanceof DefinedWorkflow || typeof x === "object" && x != null && "spec" in x && typeof x.run === "function" && typeof x.entries === "function";
44
- return [mod.default, ...Object.values(mod)].find(isDefined) ?? null;
45
- }
46
- //#endregion
47
5
  //#region src/cli/tui/treeRows.ts
48
6
  /** module display name — also the drafts folder key (DraftsSt delegates here) */
49
7
  function moduleName(file) {
@@ -217,20 +175,6 @@ function buildFileRows(p) {
217
175
  return out;
218
176
  }
219
177
  //#endregion
220
- //#region src/utils/copyName.ts
221
- /** the default name of a duplicate: a trailing number is incremented (`shot 007` → `shot 008`,
222
- * zero padding kept), anything else gets `-2`. Never returns a name in `taken` */
223
- function copyName(name, taken) {
224
- const m = /^(.*?)(\d+)$/.exec(name);
225
- if (m == null) return copyName(`${name}-1`, taken);
226
- const prefix = m[1] ?? "";
227
- const digits = m[2] ?? "";
228
- for (let n = Number(digits) + 1;; n++) {
229
- const candidate = `${prefix}${String(n).padStart(digits.length, "0")}`;
230
- if (!taken.includes(candidate)) return candidate;
231
- }
232
- }
233
- //#endregion
234
178
  //#region src/cli/draftMeta.ts
235
179
  const ENHANCE_KEY = "$enhance";
236
180
  /** a parsed draft file: a json object, never an array or a scalar */
@@ -248,6 +192,168 @@ function preserveDraftMeta(previous, next) {
248
192
  return out;
249
193
  }
250
194
  //#endregion
195
+ //#region src/utils/mojibake.ts
196
+ const CP1252_REVERSE = {
197
+ "€": 128,
198
+ "‚": 130,
199
+ ƒ: 131,
200
+ "„": 132,
201
+ "…": 133,
202
+ "†": 134,
203
+ "‡": 135,
204
+ ˆ: 136,
205
+ "‰": 137,
206
+ Š: 138,
207
+ "‹": 139,
208
+ Œ: 140,
209
+ Ž: 142,
210
+ "‘": 145,
211
+ "’": 146,
212
+ "“": 147,
213
+ "”": 148,
214
+ "•": 149,
215
+ "–": 150,
216
+ "—": 151,
217
+ "˜": 152,
218
+ "™": 153,
219
+ š: 154,
220
+ "›": 155,
221
+ œ: 156,
222
+ ž: 158,
223
+ Ÿ: 159
224
+ };
225
+ /**
226
+ * repair UTF-8 that was decoded as cp1252 (a Windows server re-reading its own
227
+ * output: `█` E2 96 88 arrives as `â–ˆ`). Reverses the cp1252 map back to
228
+ * bytes and re-decodes as UTF-8; any unmappable char or invalid byte sequence
229
+ * means the text was NOT mojibake — the original is returned untouched.
230
+ */
231
+ function repairMojibake(s) {
232
+ let suspicious = false;
233
+ for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 127) {
234
+ suspicious = true;
235
+ break;
236
+ }
237
+ if (!suspicious) return s;
238
+ const bytes = new Uint8Array(s.length);
239
+ for (let i = 0; i < s.length; i++) {
240
+ const code = s.charCodeAt(i);
241
+ if (code <= 255) {
242
+ bytes[i] = code;
243
+ continue;
244
+ }
245
+ const mapped = CP1252_REVERSE[s[i] ?? ""];
246
+ if (mapped == null) return s;
247
+ bytes[i] = mapped;
248
+ }
249
+ const decoded = Buffer.from(bytes).toString("utf8");
250
+ return decoded.includes("�") ? s : decoded;
251
+ }
252
+ //#endregion
253
+ //#region src/cli/tui/state/LogsSt.ts
254
+ const MAX_LINES = 400;
255
+ /** fold write chunks into p.lines (mutated), returns the new partial tail.
256
+ * `\n` commits a line, `\r` resets the partial (tqdm redraws collapse to
257
+ * their last state), ANSI stripped, blank lines dropped. */
258
+ function assembleLogChunks(p) {
259
+ let partial = p.partial;
260
+ for (const entry of p.entries) for (const piece of stripAnsi(repairMojibake(entry.m)).split(/(\r\n|\n|\r)/)) if (piece === "\n" || piece === "\r\n") {
261
+ if (partial.trim() !== "") p.lines.push(partial);
262
+ partial = "";
263
+ } else if (piece === "\r") partial = "";
264
+ else if (piece !== "") partial += piece;
265
+ return partial;
266
+ }
267
+ /** server console mirror: /internal/logs/raw backfill + ws 'logs' stream.
268
+ * Entries are write CHUNKS, not lines — assembled here (`\n` commits,
269
+ * `\r` resets the partial, so tqdm redraws collapse to their last state). */
270
+ var LogsSt = class {
271
+ constructor(st) {
272
+ this.st = st;
273
+ this.lines = [];
274
+ this.partial = "";
275
+ this.attached = null;
276
+ makeAutoObservable(this, { st: false });
277
+ this.attach(this.st.wf.host);
278
+ this.st.disposers.push(() => {
279
+ if (this.attached != null) {
280
+ this.attached.onLogs = null;
281
+ this.attached.onSession = null;
282
+ }
283
+ });
284
+ }
285
+ /** follow the CURRENT workflow's host (re-called on workflow switch) */
286
+ attach(host) {
287
+ if (this.attached === host) return;
288
+ if (this.attached != null) {
289
+ this.attached.onLogs = null;
290
+ this.attached.onSession = null;
291
+ if (this.attached.isConnected && this.attached.comfySessionId !== "temp") this.attached.subscribeLogs({
292
+ enabled: false,
293
+ clientId: this.attached.comfySessionId
294
+ }).catch(() => {});
295
+ }
296
+ this.attached = host;
297
+ this.lines = [];
298
+ this.partial = "";
299
+ host.onLogs = (p) => this.feed(p.entries);
300
+ host.onSession = (sid) => void this.hydrate(host, sid);
301
+ if (host.isConnected && host.comfySessionId !== "temp") this.hydrate(host, host.comfySessionId);
302
+ }
303
+ /** backfill BEFORE subscribe: entries emitted in the gap are lost, which is
304
+ * the right trade — the reverse order would clobber streamed entries at the
305
+ * reset, and the backfill re-covers the recent past anyway */
306
+ async hydrate(host, sid) {
307
+ try {
308
+ const raw = await host.fetchRawLogs();
309
+ if (this.attached !== host || host.comfySessionId !== sid) return;
310
+ runInAction(() => {
311
+ this.lines = [];
312
+ this.partial = "";
313
+ });
314
+ this.feed(raw.entries);
315
+ await host.subscribeLogs({
316
+ enabled: true,
317
+ clientId: sid
318
+ });
319
+ } catch (e) {
320
+ if (this.attached !== host) return;
321
+ this.feed([{
322
+ t: "",
323
+ m: `[comfy-ts] server log stream unavailable: ${extractErrorMessage(e)}\n`
324
+ }]);
325
+ }
326
+ }
327
+ feed(entries) {
328
+ runInAction(() => {
329
+ this.partial = assembleLogChunks({
330
+ lines: this.lines,
331
+ partial: this.partial,
332
+ entries
333
+ });
334
+ if (this.lines.length > MAX_LINES) this.lines.splice(0, this.lines.length - MAX_LINES);
335
+ });
336
+ }
337
+ /** last rows to render, live partial included */
338
+ tail(n) {
339
+ return (this.partial.trim() !== "" ? [...this.lines, this.partial] : this.lines).slice(-n);
340
+ }
341
+ };
342
+ //#endregion
343
+ //#region src/utils/copyName.ts
344
+ /** the default name of a duplicate: a trailing number is incremented (`shot 007` → `shot 008`,
345
+ * zero padding kept), anything else gets `-2`. Never returns a name in `taken` */
346
+ function copyName(name, taken) {
347
+ const m = /^(.*?)(\d+)$/.exec(name);
348
+ if (m == null) return copyName(`${name}-1`, taken);
349
+ const prefix = m[1] ?? "";
350
+ const digits = m[2] ?? "";
351
+ for (let n = Number(digits) + 1;; n++) {
352
+ const candidate = `${prefix}${String(n).padStart(digits.length, "0")}`;
353
+ if (!taken.includes(candidate)) return candidate;
354
+ }
355
+ }
356
+ //#endregion
251
357
  //#region src/cli/tui/state/DraftsSt.ts
252
358
  /** module basename (`01-txt2img`) keys the draft folder — knowable for EVERY tree file without importing it */
253
359
  function draftKeyForFile(file) {
@@ -472,154 +578,48 @@ function keepDraftMeta(path, json) {
472
578
  return JSON.stringify(preserveDraftMeta(previous, next), null, 2);
473
579
  }
474
580
  //#endregion
475
- //#region src/utils/mojibake.ts
476
- const CP1252_REVERSE = {
477
- "€": 128,
478
- "‚": 130,
479
- ƒ: 131,
480
- "„": 132,
481
- "…": 133,
482
- "†": 134,
483
- "‡": 135,
484
- ˆ: 136,
485
- "‰": 137,
486
- Š: 138,
487
- "‹": 139,
488
- Œ: 140,
489
- Ž: 142,
490
- "‘": 145,
491
- "’": 146,
492
- "“": 147,
493
- "”": 148,
494
- "•": 149,
495
- "–": 150,
496
- "—": 151,
497
- "˜": 152,
498
- "™": 153,
499
- š: 154,
500
- "›": 155,
501
- œ: 156,
502
- ž: 158,
503
- Ÿ: 159
504
- };
581
+ //#region src/cli/tui/discoverWorkflows.ts
505
582
  /**
506
- * repair UTF-8 that was decoded as cp1252 (a Windows server re-reading its own
507
- * output: `█` E2 96 88 arrives as `â–ˆ`). Reverses the cp1252 map back to
508
- * bytes and re-decodes as UTF-8; any unmappable char or invalid byte sequence
509
- * means the text was NOT mojibake — the original is returned untouched.
583
+ * recursive scan for the workflow-module naming convention. Entries BELOW a
584
+ * node_modules segment are skipped: packaged examples arrive via
585
+ * bundledExamplesDir (src/exampleAssets.ts — symlinked layouts like pnpm would
586
+ * otherwise list them twice, un-deduped, as the user's own files), and
587
+ * third-party packages shipping *.cflow.ts are not this project's workflows. A
588
+ * scan root that is ITSELF inside node_modules still works (the filter is
589
+ * relative to the root).
510
590
  */
511
- function repairMojibake(s) {
512
- let suspicious = false;
513
- for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 127) {
514
- suspicious = true;
515
- break;
516
- }
517
- if (!suspicious) return s;
518
- const bytes = new Uint8Array(s.length);
519
- for (let i = 0; i < s.length; i++) {
520
- const code = s.charCodeAt(i);
521
- if (code <= 255) {
522
- bytes[i] = code;
523
- continue;
524
- }
525
- const mapped = CP1252_REVERSE[s[i] ?? ""];
526
- if (mapped == null) return s;
527
- bytes[i] = mapped;
528
- }
529
- const decoded = Buffer.from(bytes).toString("utf8");
530
- return decoded.includes("�") ? s : decoded;
591
+ function scanCflowFiles(dir) {
592
+ return readdirSync(dir, { recursive: true }).map((f) => String(f)).filter((f) => !f.split("/").includes("node_modules")).map((f) => join(dir, f)).filter((f) => f.endsWith(".cflow.ts") || f.endsWith(".cflow.tsx")).sort();
593
+ }
594
+ /**
595
+ * PURE merge of the scan with the packaged examples (headless-tested). An
596
+ * explicit target keeps its scope only. Bundled files ALWAYS group under the
597
+ * bundled section, also when the scan already found them (repo dev: ./examples
598
+ * is under cwd) — dedupe relies on the caller passing realpath-normalized
599
+ * strings on both sides.
600
+ */
601
+ function mergeWorkflowSources(p) {
602
+ if (p.explicitTarget) return {
603
+ files: p.scanned,
604
+ bundled: /* @__PURE__ */ new Set()
605
+ };
606
+ const bundled = new Set(p.bundledFiles);
607
+ return {
608
+ files: [...p.scanned.filter((f) => !bundled.has(f)), ...p.bundledFiles],
609
+ bundled
610
+ };
531
611
  }
532
612
  //#endregion
533
- //#region src/cli/tui/state/LogsSt.ts
534
- const MAX_LINES = 400;
535
- /** fold write chunks into p.lines (mutated), returns the new partial tail.
536
- * `\n` commits a line, `\r` resets the partial (tqdm redraws collapse to
537
- * their last state), ANSI stripped, blank lines dropped. */
538
- function assembleLogChunks(p) {
539
- let partial = p.partial;
540
- for (const entry of p.entries) for (const piece of stripAnsi(repairMojibake(entry.m)).split(/(\r\n|\n|\r)/)) if (piece === "\n" || piece === "\r\n") {
541
- if (partial.trim() !== "") p.lines.push(partial);
542
- partial = "";
543
- } else if (piece === "\r") partial = "";
544
- else if (piece !== "") partial += piece;
545
- return partial;
613
+ //#region src/cli/tui/findDefinedWorkflow.ts
614
+ /**
615
+ * instanceof first; duck-type fallback covers a second copy of the library in
616
+ * the module graph (linked dev setups, npm dedupe misses)
617
+ */
618
+ function findDefinedWorkflow(mod) {
619
+ const isDefined = (x) => x instanceof DefinedWorkflow || typeof x === "object" && x != null && "spec" in x && typeof x.run === "function" && typeof x.entries === "function";
620
+ return [mod.default, ...Object.values(mod)].find(isDefined) ?? null;
546
621
  }
547
- /** server console mirror: /internal/logs/raw backfill + ws 'logs' stream.
548
- * Entries are write CHUNKS, not lines — assembled here (`\n` commits,
549
- * `\r` resets the partial, so tqdm redraws collapse to their last state). */
550
- var LogsSt = class {
551
- constructor(st) {
552
- this.st = st;
553
- this.lines = [];
554
- this.partial = "";
555
- this.attached = null;
556
- makeAutoObservable(this, { st: false });
557
- this.attach(this.st.wf.host);
558
- this.st.disposers.push(() => {
559
- if (this.attached != null) {
560
- this.attached.onLogs = null;
561
- this.attached.onSession = null;
562
- }
563
- });
564
- }
565
- /** follow the CURRENT workflow's host (re-called on workflow switch) */
566
- attach(host) {
567
- if (this.attached === host) return;
568
- if (this.attached != null) {
569
- this.attached.onLogs = null;
570
- this.attached.onSession = null;
571
- if (this.attached.isConnected && this.attached.comfySessionId !== "temp") this.attached.subscribeLogs({
572
- enabled: false,
573
- clientId: this.attached.comfySessionId
574
- }).catch(() => {});
575
- }
576
- this.attached = host;
577
- this.lines = [];
578
- this.partial = "";
579
- host.onLogs = (p) => this.feed(p.entries);
580
- host.onSession = (sid) => void this.hydrate(host, sid);
581
- if (host.isConnected && host.comfySessionId !== "temp") this.hydrate(host, host.comfySessionId);
582
- }
583
- /** backfill BEFORE subscribe: entries emitted in the gap are lost, which is
584
- * the right trade — the reverse order would clobber streamed entries at the
585
- * reset, and the backfill re-covers the recent past anyway */
586
- async hydrate(host, sid) {
587
- try {
588
- const raw = await host.fetchRawLogs();
589
- if (this.attached !== host || host.comfySessionId !== sid) return;
590
- runInAction(() => {
591
- this.lines = [];
592
- this.partial = "";
593
- });
594
- this.feed(raw.entries);
595
- await host.subscribeLogs({
596
- enabled: true,
597
- clientId: sid
598
- });
599
- } catch (e) {
600
- if (this.attached !== host) return;
601
- this.feed([{
602
- t: "",
603
- m: `[comfy-ts] server log stream unavailable: ${extractErrorMessage(e)}\n`
604
- }]);
605
- }
606
- }
607
- feed(entries) {
608
- runInAction(() => {
609
- this.partial = assembleLogChunks({
610
- lines: this.lines,
611
- partial: this.partial,
612
- entries
613
- });
614
- if (this.lines.length > MAX_LINES) this.lines.splice(0, this.lines.length - MAX_LINES);
615
- });
616
- }
617
- /** last rows to render, live partial included */
618
- tail(n) {
619
- return (this.partial.trim() !== "" ? [...this.lines, this.partial] : this.lines).slice(-n);
620
- }
621
- };
622
622
  //#endregion
623
- export { draftsDirForFile as a, isDraftMetaKey as c, familyOf as d, findDefinedWorkflow as f, draftKeyForFile as i, assignFamilyColors as l, scanCflowFiles as m, assembleLogChunks as n, listDraftsForFile as o, mergeWorkflowSources as p, DraftsSt as r, ENHANCE_KEY as s, LogsSt as t, buildFileRows as u };
623
+ export { draftKeyForFile as a, LogsSt as c, isDraftMetaKey as d, assignFamilyColors as f, moduleName as h, DraftsSt as i, assembleLogChunks as l, familyOf as m, mergeWorkflowSources as n, draftsDirForFile as o, buildFileRows as p, scanCflowFiles as r, listDraftsForFile as s, findDefinedWorkflow as t, ENHANCE_KEY as u };
624
624
 
625
- //# sourceMappingURL=LogsSt-C3UIWR-o.js.map
625
+ //# sourceMappingURL=findDefinedWorkflow-0lG-VTEd.js.map