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/README.md CHANGED
@@ -220,6 +220,27 @@ await txt2img.run({ log: true }) // fresh graph, fresh image
220
220
 
221
221
  `vars` can be a lambda receiving `v` so vars reference each other: `v.prompt('a cozy house', { loraKeywordsFrom: loras })` prefixes the active loras' trigger keywords. Name the file `*.cflow.ts` and the TUI finds it.
222
222
 
223
+ ## 👀 Live previews: watch the image form
224
+
225
+ Pass `onPreview` to any run and every sampling step hands you the image so far:
226
+
227
+ ```ts
228
+ const execution = await txt2img.run({
229
+ onPreview: (p) => {
230
+ // p.bytes: jpeg or png (p.mime) · p.nodeId / p.nodeName: 'KSampler' · p.step: { value: 7, max: 20 }
231
+ showImage(new Blob([p.bytes], { type: p.mime }))
232
+ },
233
+ })
234
+ ```
235
+
236
+ It works the same on `definedWorkflow.run()`, `workflow.run()` and `workflow.start()`. Without `onPreview`, no frame is decoded or copied for the run. A preview is never an output: `execution.images` holds only what the graph saved.
237
+
238
+ ComfyUI sends previews only when it was launched with `--preview-method auto` (or `latent2rgb`, `taesd`). Its default is `none`, and then no frame ever arrives. Ask the host:
239
+
240
+ ```ts
241
+ await host.fetchPreviewMethod() // 'auto' · 'none' = relaunch with --preview-method auto · null = the host does not say (cloud)
242
+ ```
243
+
223
244
  ## 🕶️ Ephemeral outputs: leave no traces
224
245
 
225
246
  Some images should not outlive the run — client work, private subjects, anything you would not leave in a shared server's `output/` folder. ComfyUI has three image savers, and they differ exactly there:
@@ -297,6 +318,8 @@ bunx comfy-ts loras # mirror your loras' names + trigger words (b
297
318
  bunx comfy-ts tui # your *.cflow.ts + bundled examples
298
319
  bunx comfy-ts tui [dir | module] # scan just that
299
320
  bunx comfy-ts serve [dir | module] # drafts as a local HTTP API (below)
321
+ bunx comfy-ts run anima-t2i --prompt "a knight in the rain" --out knight.png
322
+ # one generation, headless: every var a flag
300
323
  ```
301
324
 
302
325
  Any reachable host: the box under your desk or a GPU machine across the network, same command, same output.
@@ -1,11 +1,10 @@
1
- import { $ as DEFAULT_MEDIA_EXTENSIONS, A as reloadLoraInfoCache, B as lmFileSize, C as getLoraTriggers, E as lorasMissingFromMirror, F as fetchLoraList, G as lmTags, I as fetchLoraPreviewBytes, J as loraKey, L as lmBaseModel, M as fetchLoraCivitai, N as fetchLoraDescription, O as recordCivitaiMiss, P as fetchLoraExampleImages, Q as stripAnsi, R as lmCivitai, S as getLoraTriggerWords, T as loraMirrorEntries, U as lmNotes, V as lmFolder, W as lmSha256, X as ansi, Y as loraPreviewMapFrom, Z as colorsAvailable, _ as buildLoraMirror, at as extractErrorMessage, b as getLoraInfo, c as isLoraLanes, d as isLoraStrength, et as MEDIA_KINDS, ht as sha1HexOfString, i as summarizeDrift, j as writeLoraMirror, k as refreshLoraInfoCacheIfChanged, l as isLorasInput, mt as statelessRegex, p as getLoraKeyword, r as driftChanged, st as bang, u as isPromptInput, v as getLoraAddedAt, x as getLoraPreviewUrl, y as getLoraDisplayName, z as lmFilePath } from "./schemaDrift-BkN8rLiZ.js";
2
- import { a as draftsDirForFile, c as isDraftMetaKey, f as findDefinedWorkflow, i as draftKeyForFile, m as scanCflowFiles, n as assembleLogChunks, o as listDraftsForFile, s as ENHANCE_KEY } from "./LogsSt-C3UIWR-o.js";
3
- import { fileURLToPath, pathToFileURL } from "node:url";
1
+ import { $ as DEFAULT_MEDIA_EXTENSIONS, A as reloadLoraInfoCache, B as lmFileSize, C as getLoraTriggers, E as lorasMissingFromMirror, F as fetchLoraList, G as lmTags, I as fetchLoraPreviewBytes, J as loraKey, L as lmBaseModel, M as fetchLoraCivitai, N as fetchLoraDescription, O as recordCivitaiMiss, P as fetchLoraExampleImages, R as lmCivitai, S as getLoraTriggerWords, T as loraMirrorEntries, U as lmNotes, V as lmFolder, W as lmSha256, X as ansi, Y as loraPreviewMapFrom, _ as buildLoraMirror, at as extractErrorMessage, b as getLoraInfo, c as isLoraLanes, d as isLoraStrength, et as MEDIA_KINDS, ht as sha1HexOfString, i as summarizeDrift, j as writeLoraMirror, k as refreshLoraInfoCacheIfChanged, l as isLorasInput, mt as statelessRegex, p as getLoraKeyword, r as driftChanged, st as bang, u as isPromptInput, v as getLoraAddedAt, x as getLoraPreviewUrl, y as getLoraDisplayName, z as lmFilePath } from "./schemaDrift-CbsABBuk.js";
2
+ import { d as isDraftMetaKey, l as assembleLogChunks, o as draftsDirForFile, s as listDraftsForFile, u as ENHANCE_KEY } from "./findDefinedWorkflow-0lG-VTEd.js";
3
+ import { fileURLToPath } from "node:url";
4
4
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { basename, dirname, extname, isAbsolute, join, resolve } from "pathe";
6
6
  import { nanoid } from "nanoid";
7
- import { createServer } from "node:http";
8
- import { homedir, networkInterfaces } from "node:os";
7
+ import { homedir } from "node:os";
9
8
  //#region src/cli/serve/describeVar.ts
10
9
  /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
11
10
  function presetsOrUndefined(presets) {
@@ -999,7 +998,10 @@ const realStarter = async (mod, opts) => {
999
998
  return await (await mod.dw.build({
1000
999
  advance: true,
1001
1000
  host
1002
- })).start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false });
1001
+ })).start({
1002
+ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false,
1003
+ onPreview: opts.onPreview
1004
+ });
1003
1005
  };
1004
1006
  const CONTENT_TYPES = {
1005
1007
  ".png": "image/png",
@@ -1167,8 +1169,6 @@ var ServeApp = class {
1167
1169
  this.liveRuns = /* @__PURE__ */ new Map();
1168
1170
  this.latentPreviews = /* @__PURE__ */ new Map();
1169
1171
  this.latentSeq = 0;
1170
- this.promptOwner = /* @__PURE__ */ new Map();
1171
- this.latentHosts = /* @__PURE__ */ new Set();
1172
1172
  this.previewSweeps = /* @__PURE__ */ new Map();
1173
1173
  this.starter = opts.starter ?? realStarter;
1174
1174
  }
@@ -1630,13 +1630,13 @@ var ServeApp = class {
1630
1630
  const rebound = await this.rebindHostVars(hostId, host);
1631
1631
  const nodes = host.schema.nodes.length;
1632
1632
  const loras = host.schema.getLoras().length;
1633
- const dropped = rebound.stale.length === 0 ? "" : `. dropped ${rebound.stale.length} selection(s) this host no longer lists`;
1633
+ const dropped = rebound.stale.length === 0 ? "" : `. ${rebound.stale.length} selection(s) this host no longer lists (a lora is dropped, a model stays picked)`;
1634
1634
  return json(200, {
1635
1635
  ok: true,
1636
1636
  host: hostId,
1637
1637
  action,
1638
1638
  stale: rebound.stale,
1639
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`
1639
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora or model var(s) changed${dropped}${lorasNote}`
1640
1640
  });
1641
1641
  }
1642
1642
  if (action === "restart") {
@@ -1672,6 +1672,15 @@ var ServeApp = class {
1672
1672
  if (mod.dw.host.data.id !== hostId) continue;
1673
1673
  await this.exclusive(mod.key, () => {
1674
1674
  for (const [name, varDef] of mod.dw.entries()) {
1675
+ if (varDef.kind === "choice") {
1676
+ const choice = varDef;
1677
+ if (choice.hostSlot == null) continue;
1678
+ const before = choice.choices.length;
1679
+ choice.bindHost(host);
1680
+ if (choice.choices.length !== before) widened++;
1681
+ if (choice.value != null && !choice.choices.includes(choice.value)) stale.push(`${mod.key}/${name}: ${choice.value}`);
1682
+ continue;
1683
+ }
1675
1684
  if (varDef.kind !== "loras") continue;
1676
1685
  const lorasVar = varDef;
1677
1686
  if (lorasVar.optionsFilter == null) continue;
@@ -2102,25 +2111,6 @@ var ServeApp = class {
2102
2111
  configs: listLlmConfigs()
2103
2112
  });
2104
2113
  }
2105
- runningModules() {
2106
- return [...this.liveRuns.entries()].filter(([, e]) => e.status !== "Success" && e.status !== "Failure").map(([key]) => key);
2107
- }
2108
- /** one dispatcher per host, installed once and left in place (idempotent) */
2109
- wireLatents(host) {
2110
- if (this.latentHosts.has(host)) return;
2111
- this.latentHosts.add(host);
2112
- host.onLatentPreview = (p) => {
2113
- const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : void 0;
2114
- const running = this.runningModules();
2115
- const key = owner ?? (running.length === 1 ? running[0] : void 0);
2116
- if (key == null) return;
2117
- this.latentPreviews.set(key, {
2118
- bytes: p.bytes,
2119
- mime: p.mime,
2120
- seq: ++this.latentSeq
2121
- });
2122
- };
2123
- }
2124
2114
  replyRunStatus(modKey) {
2125
2115
  const mod = this.moduleByKey(modKey);
2126
2116
  if (mod == null) return json(404, { error: `unknown module '${modKey}'` });
@@ -2264,13 +2254,8 @@ var ServeApp = class {
2264
2254
  if ("error" in started) return json(started.status, { error: started.error });
2265
2255
  const execution = started.execution;
2266
2256
  this.liveRuns.set(mod.key, execution);
2267
- this.promptOwner.set(execution.data.id, mod.key);
2268
2257
  console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
2269
- try {
2270
- await execution.done;
2271
- } finally {
2272
- this.promptOwner.delete(execution.data.id);
2273
- }
2258
+ await execution.done;
2274
2259
  const durationMs = Date.now() - t0;
2275
2260
  if (execution.status === "Failure") {
2276
2261
  const error = describeRunError(execution.data.error);
@@ -2469,12 +2454,16 @@ var ServeApp = class {
2469
2454
  }
2470
2455
  this.latentPreviews.delete(mod.key);
2471
2456
  const runHost = this.runHostFor(mod);
2472
- this.wireLatents(runHost ?? mod.dw.host);
2473
2457
  try {
2474
2458
  return { execution: await this.starter(mod, {
2475
2459
  saveToDisk: this.settings.saveToDisk,
2476
2460
  savePrefix: this.savePrefixFor(mod.key),
2477
- host: runHost ?? void 0
2461
+ host: runHost ?? void 0,
2462
+ onPreview: (p) => this.latentPreviews.set(mod.key, {
2463
+ bytes: p.bytes,
2464
+ mime: p.mime,
2465
+ seq: ++this.latentSeq
2466
+ })
2478
2467
  }) };
2479
2468
  } catch (e) {
2480
2469
  if (e instanceof Error && (e.name === "MediaVarEmptyError" || e.name === "ImageVarEmptyError")) return {
@@ -2526,413 +2515,6 @@ var ServeApp = class {
2526
2515
  }
2527
2516
  };
2528
2517
  //#endregion
2529
- //#region src/cli/serve/byteRange.ts
2530
- /** one range, the only kind media players send: `bytes=a-b`, `bytes=a-`, `bytes=-n` */
2531
- function parseRange(header, size) {
2532
- const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
2533
- if (m == null) return null;
2534
- const a = m[1] ?? "";
2535
- const b = m[2] ?? "";
2536
- if (a === "" && b === "") return null;
2537
- if (a === "") {
2538
- const n = Number(b);
2539
- if (n === 0) return "unsatisfiable";
2540
- return {
2541
- start: Math.max(0, size - n),
2542
- end: size - 1
2543
- };
2544
- }
2545
- const start = Number(a);
2546
- const end = b === "" ? size - 1 : Math.min(Number(b), size - 1);
2547
- if (start >= size || start > end) return "unsatisfiable";
2548
- return {
2549
- start,
2550
- end
2551
- };
2552
- }
2553
- /** a whole 200 binary reply gets its length and `accept-ranges`; a range request gets 206 with
2554
- * those bytes, or 416 past the end. Text replies and errors pass through untouched */
2555
- function withByteRange(reply, req) {
2556
- if (req.method !== "GET" || reply.status !== 200 || typeof reply.body === "string") return reply;
2557
- const size = reply.body.length;
2558
- const base = {
2559
- ...reply.headers,
2560
- "accept-ranges": "bytes"
2561
- };
2562
- const range = req.range == null ? null : parseRange(req.range, size);
2563
- if (range == null) return {
2564
- ...reply,
2565
- headers: {
2566
- ...base,
2567
- "content-length": String(size)
2568
- }
2569
- };
2570
- if (range === "unsatisfiable") return {
2571
- status: 416,
2572
- contentType: reply.contentType,
2573
- body: /* @__PURE__ */ new Uint8Array(0),
2574
- headers: {
2575
- ...base,
2576
- "content-range": `bytes */${size}`
2577
- }
2578
- };
2579
- return {
2580
- status: 206,
2581
- contentType: reply.contentType,
2582
- body: reply.body.subarray(range.start, range.end + 1),
2583
- headers: {
2584
- ...base,
2585
- "content-range": `bytes ${range.start}-${range.end}/${size}`,
2586
- "content-length": String(range.end - range.start + 1)
2587
- }
2588
- };
2589
- }
2590
- //#endregion
2591
- //#region src/cli/serve/startupPrint.ts
2592
- const RULE_WIDTH = 64;
2593
- /** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one
2594
- * you want when the phone is not on the same wifi */
2595
- function addressNote(addr) {
2596
- const octets = addr.split(".").map(Number);
2597
- const second = octets[1] ?? 0;
2598
- if (octets[0] === 100 && second >= 64 && second <= 127) return "tailnet";
2599
- if (addr === "127.0.0.1" || addr === "localhost") return "this machine";
2600
- return "";
2601
- }
2602
- function paint(color) {
2603
- const id = (s) => s;
2604
- if (!color) return {
2605
- title: id,
2606
- name: id,
2607
- dim: id,
2608
- url: id,
2609
- warn: id
2610
- };
2611
- return {
2612
- title: (s) => ansi.bold(s),
2613
- name: (s) => ansi.bold.cyan(s),
2614
- dim: (s) => ansi.gray(s),
2615
- url: (s) => ansi.green(s),
2616
- warn: (s) => ansi.yellow(s)
2617
- };
2618
- }
2619
- /** a box that stays square whatever the colors do: padding measures the VISIBLE text */
2620
- function boxed(lines, p = { color: false }) {
2621
- const width = Math.max(...lines.map((l) => stripAnsi(l).length), 0);
2622
- const edge = (l, r) => `${l}${"─".repeat(width + 2)}${r}`;
2623
- const border = (s) => p.color ? ansi.gray(s) : s;
2624
- return [
2625
- border(edge("┌", "┐")),
2626
- ...lines.map((l) => `${border("│")} ${l}${" ".repeat(width - stripAnsi(l).length)} ${border("│")}`),
2627
- border(edge("└", "┘"))
2628
- ];
2629
- }
2630
- function renderStartupLines(p) {
2631
- const c = paint(p.color);
2632
- const loopback = p.bind === "127.0.0.1" || p.bind === "localhost" || p.bind === "::1";
2633
- const primary = `http://${p.urls[0] ?? p.bind}:${p.port}/`;
2634
- const out = [];
2635
- const count = `${p.modules.length} workflow${p.modules.length === 1 ? "" : "s"}`;
2636
- out.push(c.title(`comfy-ts serve · ${count} · ${primary}`));
2637
- out.push(c.warn(loopback ? "⚠️ no auth: this API runs workflows, and any page open in your browser can call it" : `⚠️ bound to ${p.bind}, no auth: anyone on this network can run workflows on your ComfyUI host`));
2638
- for (const mod of p.modules) {
2639
- out.push("", c.dim("─".repeat(RULE_WIDTH)));
2640
- out.push(`${c.name(mod.key)} ${c.dim(`host: ${mod.hostId}`)}`);
2641
- for (const route of mod.routes) out.push(c.dim(` POST ${route}`));
2642
- out.push(...mod.varLines);
2643
- }
2644
- out.push(c.dim("─".repeat(RULE_WIDTH)), "");
2645
- const box = [`${c.title("web ui")} ${c.url(primary)}`, `${c.dim("json api")} ${c.dim(`${primary}drafts`)}`];
2646
- if (p.urls.length > 1) {
2647
- box.push("", c.dim("also reachable at:"));
2648
- for (const url of p.urls.slice(1)) {
2649
- const note = addressNote(url);
2650
- box.push(` ${c.url(`http://${url}:${p.port}/`)}${note === "" ? "" : c.dim(` (${note})`)}`);
2651
- }
2652
- }
2653
- if (loopback) {
2654
- box.push("", c.dim("to open it from your phone or another machine:"));
2655
- box.push(c.dim(` comfy-ts serve --host 0.0.0.0 (--bind is the same flag)`));
2656
- box.push(c.dim(" every reachable url gets printed here, tailnet included"));
2657
- }
2658
- out.push(...boxed(box, { color: p.color }));
2659
- return out;
2660
- }
2661
- //#endregion
2662
- //#region src/cli/serve/webBundle.ts
2663
- const WEB_ENTRY = "src/cli/serve/web/main.tsx";
2664
- /** nearest dir upward holding a package.json — the comfy-ts package root, from dist/ and src/ alike */
2665
- function packageRoot(fromDir) {
2666
- let dir = fromDir;
2667
- while (true) {
2668
- if (existsSync(join(dir, "package.json"))) return dir;
2669
- const parent = dirname(dir);
2670
- if (parent === dir) return null;
2671
- dir = parent;
2672
- }
2673
- }
2674
- /** bundle the web app to one browser file. Bun.build reads no tsconfig, so the
2675
- * house 'src/...' absolute imports resolve through the same plugin shape as
2676
- * tests/web-bundle.test.ts */
2677
- async function buildWebJsText(pkgRoot) {
2678
- const result = await Bun.build({
2679
- entrypoints: [join(pkgRoot, WEB_ENTRY)],
2680
- target: "browser",
2681
- minify: true,
2682
- throw: false,
2683
- define: { "process.env.NODE_ENV": "\"production\"" },
2684
- plugins: [{
2685
- name: "repo-src-paths",
2686
- setup(build) {
2687
- build.onResolve({ filter: /^src\// }, (args) => ({ path: join(pkgRoot, args.path) }));
2688
- }
2689
- }]
2690
- });
2691
- if (!result.success || result.outputs[0] == null) throw new Error(`web ui bundle failed:\n${result.logs.map((l) => String(l)).join("\n")}`);
2692
- return await result.outputs[0].text();
2693
- }
2694
- /** changes whenever a file under `dir` is added, removed or rewritten. The web bundle reaches
2695
- * outside web/ (vars, protocol types), so the whole src/ tree is the input: ~300 stats, a few ms */
2696
- function sourceSignature(dir) {
2697
- let count = 0;
2698
- let newest = 0;
2699
- let bytes = 0;
2700
- const walk = (d) => {
2701
- for (const entry of readdirSync(d, { withFileTypes: true })) {
2702
- const abs = join(d, entry.name);
2703
- if (entry.isDirectory()) walk(abs);
2704
- else if (entry.isFile()) {
2705
- const st = statSync(abs);
2706
- count += 1;
2707
- bytes += st.size;
2708
- newest = Math.max(newest, st.mtimeMs);
2709
- }
2710
- }
2711
- };
2712
- walk(dir);
2713
- return `${count}:${bytes}:${newest}`;
2714
- }
2715
- let prebuiltJs = null;
2716
- let fromSource = null;
2717
- /** the runtime resolution chain; every miss logs loud and degrades to api-only. Called on every
2718
- * page load: a prebuilt file is read once, a source build is redone only when src/ changed, so
2719
- * an edited panel shows on refresh under `bun --watch`, which never sees the bundled files */
2720
- async function loadOrBuildWebJs() {
2721
- const here = dirname(fileURLToPath(import.meta.url));
2722
- const prebuilt = join(here, "serve-web.js");
2723
- if (prebuiltJs != null) return prebuiltJs;
2724
- if (existsSync(prebuilt)) {
2725
- prebuiltJs = readFileSync(prebuilt, "utf8");
2726
- return prebuiltJs;
2727
- }
2728
- if (typeof Bun === "undefined") {
2729
- console.error("[serve] 🔴 no serve-web.js next to the cli and not running under bun — api only, no web ui");
2730
- return null;
2731
- }
2732
- const pkgRoot = packageRoot(here);
2733
- if (pkgRoot == null || !existsSync(join(pkgRoot, WEB_ENTRY))) {
2734
- console.error(`[serve] 🔴 web ui source not found (looked for ${WEB_ENTRY} above ${here}) — api only, no web ui`);
2735
- return null;
2736
- }
2737
- const signature = sourceSignature(join(pkgRoot, "src"));
2738
- if (fromSource?.signature !== signature) {
2739
- const rebuilt = fromSource != null;
2740
- fromSource = {
2741
- signature,
2742
- js: buildWebJsText(pkgRoot).then((js) => {
2743
- if (rebuilt) console.log("[serve] web ui rebuilt from source");
2744
- return js;
2745
- }, (e) => {
2746
- console.error("[serve] 🔴 web ui bundle failed — api only until the next edit:", e);
2747
- return null;
2748
- })
2749
- };
2750
- }
2751
- return await fromSource.js;
2752
- }
2753
- //#endregion
2754
- //#region src/cli/serve/run-serve.ts
2755
- const DEFAULT_PORT = 8288;
2756
- const BODY_CAP = 1e7;
2757
- /** a video dropped on a media var rides POST /upload as base64 json: ~200 MB of file */
2758
- const UPLOAD_BODY_CAP = 28e7;
2759
- function parseArgs(args) {
2760
- let target;
2761
- let port = DEFAULT_PORT;
2762
- let bind = "127.0.0.1";
2763
- for (let i = 0; i < args.length; i++) {
2764
- const a = args[i];
2765
- if (a === "--port") {
2766
- const n = Number(args[++i]);
2767
- if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` };
2768
- port = n;
2769
- } else if (a === "--host" || a === "--bind") {
2770
- const b = args[++i];
2771
- if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` };
2772
- bind = b;
2773
- } else if (a != null && a.startsWith("--")) return { error: `unknown flag '${a}'` };
2774
- else if (a != null) {
2775
- if (target != null) return { error: `one target only (got '${target}' and '${a}')` };
2776
- target = a;
2777
- }
2778
- }
2779
- return {
2780
- target,
2781
- port,
2782
- bind
2783
- };
2784
- }
2785
- /** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
2786
- /** open CORS, because a browser page IS a first-class client here: the web entry runs the
2787
- * library in a tab and rides serve as its bridge to hosts that send no CORS headers
2788
- * (examples/web is on another port by construction). The cost is real and stated at launch:
2789
- * with no auth, any page you visit can drive this api. That is the same trade as the port
2790
- * being open at all, so it is said out loud rather than hidden behind a flag. */
2791
- function makeRequestListener(app) {
2792
- const cors = {
2793
- "access-control-allow-origin": "*",
2794
- "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
2795
- "access-control-allow-headers": "content-type, accept"
2796
- };
2797
- return (req, res) => {
2798
- const cap = req.method === "POST" && (req.url ?? "").split("?")[0] === "/upload" ? UPLOAD_BODY_CAP : BODY_CAP;
2799
- const chunks = [];
2800
- let size = 0;
2801
- let overflow = false;
2802
- req.on("error", (e) => console.error(`[serve] request stream error: ${extractErrorMessage(e)}`));
2803
- req.on("data", (c) => {
2804
- if (overflow) return;
2805
- size += c.length;
2806
- if (size > cap) {
2807
- overflow = true;
2808
- res.writeHead(413, {
2809
- "content-type": "application/json",
2810
- ...cors
2811
- });
2812
- res.end(JSON.stringify({ error: "payload too large" }), () => req.destroy());
2813
- } else chunks.push(c);
2814
- });
2815
- req.on("end", () => {
2816
- if (overflow) return;
2817
- if (req.method === "OPTIONS") {
2818
- res.writeHead(204, cors);
2819
- res.end();
2820
- return;
2821
- }
2822
- app.handle({
2823
- method: req.method ?? "GET",
2824
- url: req.url ?? "/",
2825
- accept: req.headers.accept,
2826
- body: Buffer.concat(chunks).toString("utf8")
2827
- }).then((whole) => {
2828
- const range = req.headers.range;
2829
- const reply = withByteRange(whole, {
2830
- method: req.method ?? "GET",
2831
- range
2832
- });
2833
- res.writeHead(reply.status, {
2834
- "content-type": reply.contentType,
2835
- ...reply.headers,
2836
- ...cors
2837
- });
2838
- res.end(reply.body);
2839
- }).catch((e) => {
2840
- console.error(`[serve] response write failed: ${extractErrorMessage(e)}`);
2841
- res.destroy();
2842
- });
2843
- });
2844
- };
2845
- }
2846
- async function runServe(args) {
2847
- const parsed = parseArgs(args);
2848
- if ("error" in parsed) {
2849
- console.error(`[comfy-ts serve] ${parsed.error}`);
2850
- return 1;
2851
- }
2852
- const target = resolve(parsed.target ?? ".");
2853
- let files;
2854
- try {
2855
- files = statSync(target).isDirectory() ? scanCflowFiles(target) : [target];
2856
- } catch {
2857
- console.error(`[comfy-ts serve] no such file or directory: ${target}`);
2858
- return 1;
2859
- }
2860
- if (files.length === 0) {
2861
- console.error(`[comfy-ts serve] no *.cflow.ts modules under ${target}`);
2862
- return 1;
2863
- }
2864
- const modules = [];
2865
- const loadErrors = {};
2866
- for (const file of files) try {
2867
- const dw = findDefinedWorkflow(await import(pathToFileURL(file).href));
2868
- if (dw == null) throw new Error("exports no DefinedWorkflow");
2869
- const key = draftKeyForFile(file);
2870
- const clash = modules.find((m) => m.key === key);
2871
- if (clash != null) throw new Error(`module key '${key}' already taken by ${clash.file}`);
2872
- modules.push({
2873
- key,
2874
- file,
2875
- dw
2876
- });
2877
- } catch (e) {
2878
- loadErrors[file] = extractErrorMessage(e);
2879
- console.error(`[comfy-ts serve] ✗ ${file}: ${loadErrors[file]}`);
2880
- }
2881
- if (modules.length === 0) {
2882
- console.error("[comfy-ts serve] every module failed to load — nothing to serve");
2883
- return 1;
2884
- }
2885
- const app = new ServeApp(modules, {
2886
- loadErrors,
2887
- webJs: loadOrBuildWebJs,
2888
- workspace: typeof comfyts === "undefined" ? process.cwd() : comfyts.rootPath,
2889
- root: statSync(target).isDirectory() ? target : dirname(target)
2890
- });
2891
- printStartup(app, parsed.bind, parsed.port);
2892
- const server = createServer(makeRequestListener(app));
2893
- server.on("error", (e) => {
2894
- console.error(`[comfy-ts serve] server error: ${extractErrorMessage(e)}`);
2895
- process.exitCode = 1;
2896
- server.close();
2897
- });
2898
- server.listen(parsed.port, parsed.bind);
2899
- return new Promise((resolveExit) => {
2900
- server.on("close", () => resolveExit(typeof process.exitCode === "number" ? process.exitCode : 0));
2901
- });
2902
- }
2903
- /** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
2904
- * only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
2905
- function reachableAddresses(bind, nics) {
2906
- if (bind !== "0.0.0.0" && bind !== "::") return [bind];
2907
- const found = [];
2908
- for (const list of Object.values(nics)) for (const nic of list ?? []) {
2909
- if (nic.internal || nic.family !== "IPv4" && nic.family !== 4) continue;
2910
- found.push(nic.address);
2911
- }
2912
- return ["127.0.0.1", ...found];
2913
- }
2914
- function printStartup(app, bind, port) {
2915
- const base = `http://${bind}:${port}`;
2916
- const color = colorsAvailable();
2917
- const lines = renderStartupLines({
2918
- bind,
2919
- port,
2920
- urls: reachableAddresses(bind, networkInterfaces()),
2921
- color,
2922
- modules: app.modules.map((mod) => {
2923
- const entries = mod.dw.entries();
2924
- const nameWidth = Math.max(...entries.map(([n]) => n.length), 4);
2925
- return {
2926
- key: mod.key,
2927
- hostId: mod.dw.host.data.id,
2928
- routes: app.draftsFor(mod).map((d) => `${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
2929
- varLines: entries.map(([name, varDef]) => renderDescriptorLine(name, describeVar(varDef), nameWidth, color))
2930
- };
2931
- })
2932
- });
2933
- for (const line of lines) console.log(line);
2934
- }
2935
- //#endregion
2936
- export { runServe };
2518
+ export { describeVar as n, renderDescriptorLine as r, ServeApp as t };
2937
2519
 
2938
- //# sourceMappingURL=run-serve-B5PfIuhK.js.map
2520
+ //# sourceMappingURL=ServeApp-BSA5yzxZ.js.map