Line data Source code
1 : // JSONata-based pricing badge evaluation for API nodes.
2 : //
3 : // Pricing declarations are read from ComfyUI node definitions (price_badge field).
4 : // The Frontend evaluates these declarations locally using a JSONata engine.
5 : //
6 : // JSONata v2.x NOTE:
7 : // - jsonata(expression).evaluate(input) returns a Promise in JSONata 2.x.
8 : // - Therefore, pricing evaluation is async. This file implements:
9 : // - sync getter (returns cached label / last-known label),
10 : // - async evaluation + cache,
11 : // - reactive tick to update UI when async evaluation completes.
12 :
13 : import {
14 : formatPricingResult,
15 : getCompiledRuleForNodeType,
16 : normalizeWidgetValue
17 : } from '@comfyorg/shared-frontend-utils/nodePricing'
18 : import type {
19 : CompiledJsonataPricingRule,
20 : JsonataEvalContext,
21 : JsonataPricingRule,
22 : NormalizedWidgetValue
23 : } from '@comfyorg/shared-frontend-utils/nodePricing'
24 : import { readonly, ref } from 'vue'
25 : import type { Ref } from 'vue'
26 : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
27 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
28 : import type { INodeInputSlot } from '@comfyorg/graph-model/slots'
29 : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
30 : import type { PriceBadge } from '@comfyorg/object-info-parser'
31 : import { useNodeDefStore } from '@/stores/nodeDefStore'
32 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
33 :
34 2356 : const getNodeConstructorData = (node: LGraphNode) => node.constructor.nodeData
35 :
36 2356 : const buildJsonataContext = (
37 : node: LGraphNode,
38 : rule: JsonataPricingRule,
39 : widgetOverrides?: ReadonlyMap<string, unknown>
40 : ): JsonataEvalContext => {
41 98 : const widgets: Record<string, NormalizedWidgetValue> = {}
42 98 : for (const dep of rule.depends_on.widgets) {
43 180 : const raw = widgetOverrides?.has(dep.name)
44 : ? widgetOverrides.get(dep.name)
45 : : node.widgets?.find((x: IBaseWidget) => x.name === dep.name)?.value
46 180 : widgets[dep.name] = normalizeWidgetValue(raw, dep.type)
47 : }
48 :
49 98 : const inputs: Record<string, { connected: boolean }> = {}
50 98 : for (const name of rule.depends_on.inputs) {
51 0 : const index = node.inputs.findIndex((x: INodeInputSlot) => x.name === name)
52 0 : inputs[name] = { connected: index !== -1 && node.isInputConnected(index) }
53 : }
54 :
55 : // Count connected inputs per autogrow group
56 98 : const inputGroups: Record<string, number> = {}
57 98 : for (const groupName of rule.depends_on.input_groups) {
58 55 : const prefix = groupName + '.'
59 55 : inputGroups[groupName] = node.inputs.filter(
60 : (inp: INodeInputSlot, index: number) =>
61 : inp.name.startsWith(prefix) && node.isInputConnected(index)
62 : ).length
63 : }
64 :
65 98 : return { widgets, inputs, inputGroups }
66 : }
67 :
68 2356 : const safeValueForSig = (v: unknown): string => {
69 180 : if (v === null || v === undefined) return ''
70 180 : if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean')
71 180 : return `${typeof v}:${String(v)}`
72 0 : try {
73 0 : return `json:${JSON.stringify(v)}`
74 : } catch {
75 0 : return `fallback:${String(v)}`
76 : }
77 : }
78 :
79 : // Signature determines whether we need to re-evaluate when widgets/inputs change.
80 2356 : const buildSignature = (
81 : ctx: JsonataEvalContext,
82 : rule: JsonataPricingRule
83 : ): string => {
84 98 : const parts: string[] = []
85 98 : for (const dep of rule.depends_on.widgets) {
86 180 : parts.push(`w:${dep.name}=${safeValueForSig(ctx.widgets[dep.name])}`)
87 : }
88 98 : for (const name of rule.depends_on.inputs) {
89 0 : parts.push(`i:${name}=${ctx.inputs[name]?.connected ? '1' : '0'}`)
90 : }
91 98 : for (const name of rule.depends_on.input_groups) {
92 55 : parts.push(`g:${name}=${ctx.inputGroups[name] ?? 0}`)
93 : }
94 98 : return parts.join('|')
95 : }
96 :
97 : // -----------------------------
98 : // Async evaluation + cache (JSONata 2.x)
99 : // -----------------------------
100 :
101 : // Reactive tick to force UI updates when async evaluations resolve.
102 : // We purposely read pricingTick.value inside getNodeDisplayPrice to create a dependency.
103 2356 : const pricingTick = ref(0)
104 :
105 : // Per-node revision tracking for VueNodes mode (more efficient than global tick)
106 : // Uses plain Map with individual refs per node for fine-grained reactivity
107 : // Keys are stringified node IDs to handle both string and number ID types
108 2356 : const nodeRevisions = new Map<NodeId, Ref<number>>()
109 :
110 : /**
111 : * Get or create a revision ref for a specific node.
112 : * Each node has its own independent ref, so updates to one won't trigger others.
113 : */
114 2356 : const getNodeRevisionRef = (nodeId: NodeId): Ref<number> => {
115 126 : let rev = nodeRevisions.get(nodeId)
116 126 : if (!rev) {
117 29 : rev = ref(0)
118 29 : nodeRevisions.set(nodeId, rev)
119 : }
120 126 : return rev
121 : }
122 :
123 : // WeakMaps avoid memory leaks when nodes are removed.
124 : type InflightEntry = { sig: string; promise: Promise<void> }
125 :
126 2356 : const MAX_CACHED_SIGNATURES = 8
127 2356 : const cache = new WeakMap<LGraphNode, Map<string, string>>()
128 2356 : const inflight = new WeakMap<LGraphNode, InflightEntry>()
129 :
130 32 : function nodeSigCache(node: LGraphNode): Map<string, string> {
131 32 : const existing = cache.get(node)
132 32 : if (existing) return existing
133 28 : const next = new Map<string, string>()
134 28 : cache.set(node, next)
135 28 : return next
136 : }
137 :
138 32 : function cacheLabel(node: LGraphNode, sig: string, label: string): void {
139 32 : const sigCache = nodeSigCache(node)
140 32 : sigCache.delete(sig)
141 32 : sigCache.set(sig, label)
142 32 : for (const oldest of sigCache.keys()) {
143 32 : if (sigCache.size <= MAX_CACHED_SIGNATURES) break
144 0 : sigCache.delete(oldest)
145 : }
146 : }
147 :
148 2356 : const scheduleEvaluation = (
149 : node: LGraphNode,
150 : rule: CompiledJsonataPricingRule,
151 : ctx: JsonataEvalContext,
152 : sig: string
153 : ) => {
154 32 : const running = inflight.get(node)
155 32 : if (running && running.sig === sig) return
156 :
157 32 : if (!rule._compiled) return
158 :
159 32 : const promise = Promise.resolve(rule._compiled.evaluate(ctx))
160 : .then((res) => {
161 32 : cacheLabel(node, sig, formatPricingResult(res))
162 : })
163 : .catch(() => {
164 : // Cache empty to avoid retry-spam for same signature
165 0 : cacheLabel(node, sig, '')
166 : })
167 : .finally(() => {
168 32 : const cur = inflight.get(node)
169 32 : if (cur && cur.sig === sig) inflight.delete(node)
170 :
171 32 : if (LiteGraph.vueNodesMode) {
172 : // VueNodes mode: bump per-node revision (only this node re-renders)
173 23 : getNodeRevisionRef(node.id).value++
174 : }
175 32 : pricingTick.value++
176 : })
177 :
178 32 : inflight.set(node, { sig, promise })
179 : }
180 :
181 : /**
182 : * Get the pricing rule for a node from its nodeData.price_badge field.
183 : */
184 2356 : const getRuleForNode = (
185 : node: LGraphNode
186 : ): CompiledJsonataPricingRule | undefined => {
187 103 : const nodeData = getNodeConstructorData(node)
188 103 : if (!nodeData?.api_node) return undefined
189 :
190 103 : const nodeName = nodeData.name
191 103 : const priceBadge = nodeData.price_badge
192 :
193 103 : if (!priceBadge) return undefined
194 :
195 : const compiled = getCompiledRuleForNodeType(nodeName, priceBadge)
196 103 : return compiled ?? undefined
197 : }
198 :
199 : // -----------------------------
200 : // Helper to get price badge from node type
201 : // -----------------------------
202 2356 : const getNodePriceBadge = (nodeType: string): PriceBadge | undefined => {
203 : const nodeDefStore = useNodeDefStore()
204 313 : return nodeDefStore.nodeDefsByName[nodeType]?.price_badge
205 : }
206 :
207 : // -----------------------------
208 : // Public composable API
209 : // -----------------------------
210 2356 : export const useNodePricing = () => {
211 : /**
212 : * Sync getter:
213 : * - returns cached label for the current node signature when available
214 : * - schedules async evaluation when needed
215 : * - remains non-fatal on errors (returns safe fallback '')
216 : */
217 2992 : const getNodeDisplayPrice = (
218 : node: LGraphNode,
219 : widgetOverrides?: ReadonlyMap<string, unknown>
220 : ): string => {
221 : // Make this function reactive: when async evaluation completes, we bump pricingTick,
222 : // which causes this getter to recompute in Vue render/computed contexts.
223 103 : void pricingTick.value
224 :
225 : const nodeData = getNodeConstructorData(node)
226 103 : if (!nodeData?.api_node) return ''
227 :
228 103 : const rule = getRuleForNode(node)
229 103 : if (!rule) return ''
230 98 : if (!rule._compiled) return ''
231 :
232 98 : const ctx = buildJsonataContext(node, rule, widgetOverrides)
233 98 : const sig = buildSignature(ctx, rule)
234 :
235 98 : const sigCache = cache.get(node)
236 103 : const hit = sigCache?.get(sig)
237 103 : if (hit !== undefined) return hit
238 :
239 : // Cache miss: start async evaluation.
240 : // Return the last-known label (if any) to avoid flicker.
241 32 : scheduleEvaluation(node, rule, ctx, sig)
242 : const labels = [...(sigCache?.values() ?? [])]
243 103 : return labels.at(-1) ?? ''
244 : }
245 :
246 : /**
247 : * Caller compatibility helper:
248 : * returns union of widget dependencies + input dependencies for a node type.
249 : */
250 2992 : const getRelevantWidgetNames = (nodeType: string): string[] => {
251 70 : const priceBadge = getNodePriceBadge(nodeType)
252 70 : if (!priceBadge) return []
253 :
254 70 : const dependsOn = priceBadge.depends_on
255 70 : const widgetNames = dependsOn.widgets.map((w) => w.name)
256 :
257 : // Dedupe while preserving order
258 70 : const out: string[] = []
259 70 : for (const n of [
260 : ...widgetNames,
261 : ...dependsOn.inputs,
262 : ...dependsOn.input_groups
263 : ]) {
264 235 : if (!out.includes(n)) out.push(n)
265 : }
266 70 : return out
267 : }
268 :
269 : /**
270 : * Check if a node type has dynamic pricing (depends on widgets, inputs, or input_groups).
271 : */
272 2992 : const hasDynamicPricing = (nodeType: string): boolean => {
273 103 : const priceBadge = getNodePriceBadge(nodeType)
274 103 : if (!priceBadge) return false
275 :
276 98 : const dependsOn = priceBadge.depends_on
277 :
278 103 : return (
279 : dependsOn.widgets.length > 0 ||
280 : dependsOn.inputs.length > 0 ||
281 : dependsOn.input_groups.length > 0
282 : )
283 : }
284 :
285 : /**
286 : * Get input_groups prefixes for a node type (for watching connection changes).
287 : */
288 2992 : const getInputGroupPrefixes = (nodeType: string): string[] => {
289 : const priceBadge = getNodePriceBadge(nodeType)
290 70 : return priceBadge?.depends_on.input_groups ?? []
291 : }
292 :
293 : /**
294 : * Get regular input names for a node type (for watching connection changes).
295 : */
296 2992 : const getInputNames = (nodeType: string): string[] => {
297 : const priceBadge = getNodePriceBadge(nodeType)
298 70 : return priceBadge?.depends_on.inputs ?? []
299 : }
300 :
301 2992 : return {
302 : getNodeDisplayPrice,
303 : getRelevantWidgetNames,
304 : hasDynamicPricing,
305 : getInputGroupPrefixes,
306 : getInputNames,
307 : getNodeRevisionRef, // Each node has its own independent ref, so updates to one won't trigger others
308 : pricingRevision: readonly(pricingTick) // reactive invalidation signal
309 : }
310 : }
|