Line data Source code
1 : import { z } from 'zod'
2 : import { fromZodError } from 'zod-validation-error'
3 :
4 2356 : const CONTROL_OPTIONS = [
5 : 'fixed',
6 : 'increment',
7 : 'decrement',
8 : 'randomize'
9 : ] as const
10 2356 : const RESULT_ITEM_TYPE = z.enum(['input', 'output', 'temp'])
11 :
12 2356 : const zComboOption = z.union([z.string(), z.number()])
13 2356 : const zRemoteWidgetConfig = z.object({
14 : route: z.string().url().or(z.string().startsWith('/')),
15 : refresh: z.number().gte(128).safe().or(z.number().lte(0).safe()).optional(),
16 : response_key: z.string().optional(),
17 : query_params: z.record(z.string(), z.string()).optional(),
18 : refresh_button: z.boolean().optional(),
19 : control_after_refresh: z.enum(['first', 'last']).optional(),
20 : timeout: z.number().gte(0).optional(),
21 : max_retries: z.number().gte(0).optional()
22 : })
23 2356 : const zMultiSelectOption = z.object({
24 : placeholder: z.string().optional(),
25 : chip: z.boolean().optional()
26 : })
27 :
28 2356 : export const zBaseInputOptions = z
29 : .object({
30 : default: z.any().optional(),
31 : defaultInput: z.boolean().optional(),
32 : display_name: z.string().optional(),
33 : forceInput: z.boolean().optional(),
34 : tooltip: z.string().optional(),
35 : socketless: z.boolean().optional(),
36 : hidden: z.boolean().optional(),
37 : advanced: z.boolean().optional(),
38 : widgetType: z.string().optional(),
39 : /** Backend-only properties. */
40 : rawLink: z.boolean().optional(),
41 : lazy: z.boolean().optional()
42 : })
43 : .passthrough()
44 :
45 2356 : const zNumericInputOptions = zBaseInputOptions.extend({
46 : min: z.number().optional(),
47 : max: z.number().optional(),
48 : step: z.number().optional(),
49 : /** Note: Many node authors are using INT/FLOAT to pass list of INT/FLOAT. */
50 : default: z.union([z.number(), z.array(z.number())]).optional(),
51 : display: z.enum(['slider', 'number', 'knob', 'gradientslider']).optional()
52 : })
53 :
54 2356 : export const zIntInputOptions = zNumericInputOptions.extend({
55 : display: z
56 : .enum(['slider', 'number', 'knob', 'gradientslider', 'color'])
57 : .optional(),
58 : /**
59 : * If true, a linked widget will be added to the node to select the mode
60 : * of `control_after_generate`.
61 : */
62 : control_after_generate: z
63 : .union([z.boolean(), z.enum(CONTROL_OPTIONS)])
64 : .optional()
65 : })
66 :
67 2356 : export const zColorStop = z.object({
68 : offset: z.number(),
69 : color: z.tuple([z.number(), z.number(), z.number()])
70 : })
71 :
72 2356 : export const zFloatInputOptions = zNumericInputOptions.extend({
73 : round: z.union([z.number(), z.literal(false)]).optional(),
74 : gradient_stops: z.array(zColorStop).optional()
75 : })
76 :
77 2356 : export const zBooleanInputOptions = zBaseInputOptions.extend({
78 : label_on: z.string().optional(),
79 : label_off: z.string().optional(),
80 : default: z.boolean().optional()
81 : })
82 :
83 2356 : export const zStringInputOptions = zBaseInputOptions.extend({
84 : default: z.string().optional(),
85 : multiline: z.boolean().optional(),
86 : dynamicPrompts: z.boolean().optional(),
87 :
88 : // Multiline-only fields
89 : defaultVal: z.string().optional(),
90 : placeholder: z.string().optional()
91 : })
92 :
93 2356 : export const zComboInputOptions = zBaseInputOptions.extend({
94 : control_after_generate: z
95 : .union([z.boolean(), z.enum(CONTROL_OPTIONS)])
96 : .optional(),
97 : image_upload: z.boolean().optional(),
98 : image_folder: RESULT_ITEM_TYPE.optional(),
99 : allow_batch: z.boolean().optional(),
100 : video_upload: z.boolean().optional(),
101 : audio_upload: z.boolean().optional(),
102 : mesh_upload: z.boolean().optional(),
103 : upload_subfolder: z.string().optional(),
104 : animated_image_upload: z.boolean().optional(),
105 : options: z.array(zComboOption).optional(),
106 : remote: zRemoteWidgetConfig.optional(),
107 : /** Whether the widget is a multi-select widget. */
108 : multi_select: zMultiSelectOption.optional()
109 : })
110 :
111 : /** The backend serialises `("IMAGE",)` as `["IMAGE"]`, so options may be absent. */
112 16492 : function zInputSpecTuple<T extends z.ZodTypeAny, O extends z.ZodTypeAny>(
113 : type: T,
114 : options: O
115 : ) {
116 16492 : return z.union([z.tuple([type]), z.tuple([type, options.optional()])])
117 : }
118 :
119 2356 : const zIntInputSpec = zInputSpecTuple(z.literal('INT'), zIntInputOptions)
120 2356 : const zFloatInputSpec = zInputSpecTuple(z.literal('FLOAT'), zFloatInputOptions)
121 2356 : const zBooleanInputSpec = zInputSpecTuple(
122 : z.literal('BOOLEAN'),
123 : zBooleanInputOptions
124 : )
125 2356 : const zStringInputSpec = zInputSpecTuple(
126 : z.literal('STRING'),
127 : zStringInputOptions
128 : )
129 : /**
130 : * Legacy combo syntax.
131 : * @deprecated Use `zComboInputSpecV2` instead.
132 : */
133 2356 : const zComboInputSpec = zInputSpecTuple(
134 : z.array(zComboOption),
135 : zComboInputOptions
136 : )
137 2356 : const zComboInputSpecV2 = zInputSpecTuple(
138 : z.literal('COMBO'),
139 : zComboInputOptions
140 : )
141 :
142 60545805 : export function isComboInputSpecV1(
143 : inputSpec: InputSpec
144 : ): inputSpec is ComboInputSpec {
145 60545805 : return Array.isArray(inputSpec[0])
146 : }
147 :
148 11 : export function isIntInputSpec(
149 : inputSpec: InputSpec
150 : ): inputSpec is IntInputSpec {
151 11 : return inputSpec[0] === 'INT'
152 : }
153 :
154 1 : export function isFloatInputSpec(
155 : inputSpec: InputSpec
156 : ): inputSpec is FloatInputSpec {
157 1 : return inputSpec[0] === 'FLOAT'
158 : }
159 :
160 59480377 : export function isComboInputSpecV2(
161 : inputSpec: InputSpec
162 : ): inputSpec is ComboInputSpecV2 {
163 59480377 : return inputSpec[0] === 'COMBO'
164 : }
165 :
166 52403094 : export function isComboInputSpec(
167 : inputSpec: InputSpec
168 : ): inputSpec is ComboInputSpec | ComboInputSpecV2 {
169 52403094 : return isComboInputSpecV1(inputSpec) || isComboInputSpecV2(inputSpec)
170 : }
171 :
172 9868691 : export function isMediaUploadComboInput(inputSpec: InputSpec): boolean {
173 9868691 : const [inputName, inputOptions] = inputSpec
174 9868691 : if (!inputOptions) return false
175 :
176 : const isUploadInput =
177 : inputOptions['image_upload'] === true ||
178 : inputOptions['video_upload'] === true ||
179 : inputOptions['animated_image_upload'] === true
180 :
181 9868691 : return (
182 : isUploadInput && (isComboInputSpecV1(inputSpec) || inputName === 'COMBO')
183 : )
184 : }
185 :
186 : /**
187 : * Get the type of an input spec.
188 : *
189 : * @param inputSpec - The input spec to get the type of.
190 : * @returns The type of the input spec.
191 : */
192 246 : export function getInputSpecType(inputSpec: InputSpec): string {
193 246 : return isComboInputSpec(inputSpec) ? 'COMBO' : inputSpec[0]
194 : }
195 :
196 : /**
197 : * Get the combo options from a combo input spec.
198 : *
199 : * @param inputSpec - The input spec to get the combo options from.
200 : * @returns The combo options.
201 : */
202 7601692 : export function getComboSpecComboOptions(
203 : inputSpec: ComboInputSpec | ComboInputSpecV2
204 : ): (number | string)[] {
205 7601692 : return (
206 : (isComboInputSpecV2(inputSpec) ? inputSpec[1]?.options : inputSpec[0]) ?? []
207 : )
208 : }
209 :
210 2356 : const excludedLiterals = new Set([
211 : 'INT',
212 : 'FLOAT',
213 : 'BOOLEAN',
214 : 'STRING',
215 : 'COMBO',
216 : 'COMFY_DYNAMICGROUP_V3'
217 : ])
218 2356 : const zCustomInputSpec = zInputSpecTuple(
219 : z.string().refine((value) => !excludedLiterals.has(value)),
220 : zBaseInputOptions
221 : )
222 :
223 2356 : const zWidgetInputSpec = z.union([
224 : zIntInputSpec,
225 : zFloatInputSpec,
226 : zBooleanInputSpec,
227 : zStringInputSpec,
228 : zComboInputSpec,
229 : zComboInputSpecV2
230 : ])
231 :
232 2356 : const zDynamicGroupFields = z.record(
233 : z
234 : .string()
235 : .min(1)
236 : .refine(
237 : (name) => !name.includes('.'),
238 : 'DynamicGroup field names must not contain dots'
239 : ),
240 : z
241 : .union([zWidgetInputSpec, zCustomInputSpec])
242 : .refine(
243 : (spec) => typeof spec[0] !== 'string' || !isDynamicControlType(spec[0]),
244 : 'DynamicGroup fields must not contain dynamic inputs'
245 : )
246 : .refine(
247 : (spec) => !spec[1]?.forceInput,
248 : 'DynamicGroup fields must not force input sockets'
249 : )
250 : )
251 :
252 2356 : export const zDynamicGroupInputSpec = z.tuple([
253 : z.literal('COMFY_DYNAMICGROUP_V3'),
254 : zBaseInputOptions
255 : .extend({
256 : template: z
257 : .object({
258 : required: zDynamicGroupFields.optional(),
259 : optional: zDynamicGroupFields.optional()
260 : })
261 : .refine(
262 : (template) =>
263 : Object.keys({ ...template.required, ...template.optional }).length >
264 : 0,
265 : 'DynamicGroup template must contain a field'
266 : )
267 : .refine(
268 : (template) =>
269 : !Object.keys(template.required ?? {}).some((name) =>
270 : Object.hasOwn(template.optional ?? {}, name)
271 : ),
272 : 'DynamicGroup field names must be unique'
273 : ),
274 : min: z.number().int().nonnegative().default(0),
275 : max: z.number().int().positive().max(20).default(20),
276 : group_name: z.string().optional()
277 : })
278 : .refine(({ min, max }) => min <= max, {
279 : message: 'DynamicGroup min must not exceed max',
280 : path: ['min']
281 : })
282 : ])
283 :
284 2356 : const zInputSpec = z.union([
285 : zWidgetInputSpec,
286 : zDynamicGroupInputSpec,
287 : zCustomInputSpec
288 : ])
289 :
290 2356 : export const zComfyInputsSpec = z.object({
291 : required: z.record(z.string(), zInputSpec).optional(),
292 : optional: z.record(z.string(), zInputSpec).optional(),
293 : // Frontend repo is not using it, but some custom nodes are using the
294 : // hidden field to pass various values.
295 : hidden: z.record(z.string(), z.any()).optional()
296 : })
297 :
298 2356 : const zComfyNodeDataType = z.string()
299 2356 : const zComfyComboOutput = z.array(zComboOption)
300 2356 : export const zComfyOutputTypesSpec = z.array(
301 : z.union([zComfyNodeDataType, zComfyComboOutput])
302 : )
303 :
304 : /**
305 : * Widget dependency with type information.
306 : * Provides strong type enforcement for JSONata evaluation context.
307 : */
308 2356 : const zWidgetDependency = z.object({
309 : name: z.string(),
310 : type: z.string()
311 : })
312 :
313 : export type WidgetDependency = z.infer<typeof zWidgetDependency>
314 :
315 : /**
316 : * Schema for price badge depends_on field.
317 : * Specifies which widgets and inputs the pricing expression depends on.
318 : * Widgets must be specified as objects with name and type.
319 : */
320 2356 : const zPriceBadgeDepends = z.object({
321 : widgets: z.array(zWidgetDependency).optional().default([]),
322 : inputs: z.array(z.string()).optional().default([]),
323 : /**
324 : * Autogrow input group names to track.
325 : * For each group, the count of connected inputs will be available in the
326 : * JSONata context as `g.<groupName>`.
327 : * Example: `input_groups: ["reference_videos"]` makes `g.reference_videos`
328 : * available with the count of connected inputs like `reference_videos.character1`, etc.
329 : */
330 : input_groups: z.array(z.string()).optional().default([])
331 : })
332 :
333 : /**
334 : * Schema for price badge definition.
335 : * Used to calculate and display pricing information for API nodes.
336 : * The `expr` field contains a JSONata expression that returns a PricingResult.
337 : */
338 2356 : export const zPriceBadge = z.object({
339 : engine: z.literal('jsonata').optional().default('jsonata'),
340 : depends_on: zPriceBadgeDepends
341 : .optional()
342 : .default({ widgets: [], inputs: [], input_groups: [] }),
343 : expr: z.string()
344 : })
345 :
346 : export type PriceBadge = z.infer<typeof zPriceBadge>
347 :
348 2356 : export const zComfyNodeDef = z.object({
349 : input: zComfyInputsSpec.optional(),
350 : output: zComfyOutputTypesSpec.optional(),
351 : output_is_list: z.array(z.boolean()).optional(),
352 : output_name: z.array(z.string()).optional(),
353 : output_tooltips: z.array(z.string()).optional(),
354 : output_matchtypes: z.array(z.string().optional()).optional(),
355 : name: z.string(),
356 : display_name: z.string(),
357 : description: z.string(),
358 : help: z.string().optional(),
359 : category: z.string(),
360 : main_category: z.string().optional(),
361 : output_node: z.boolean(),
362 : python_module: z.string(),
363 : deprecated: z.boolean().optional(),
364 : experimental: z.boolean().optional(),
365 : dev_only: z.boolean().optional(),
366 : /**
367 : * Whether the node is an API node. Running API nodes requires login to
368 : * Comfy Org account.
369 : * https://docs.comfy.org/tutorials/api-nodes/overview
370 : */
371 : api_node: z.boolean().optional(),
372 : /**
373 : * Specifies the order of inputs for each input category.
374 : * Used to ensure consistent widget ordering regardless of JSON serialization.
375 : * Keys are 'required', 'optional', etc., values are arrays of input names.
376 : */
377 : input_order: z.record(z.string(), z.array(z.string())).optional(),
378 : /**
379 : * Alternative names for search. Useful for synonyms, abbreviations,
380 : * or old names after renaming a node.
381 : */
382 : search_aliases: z.array(z.string()).optional(),
383 : /**
384 : * Price badge definition for API nodes.
385 : * Contains a JSONata expression to calculate pricing based on widget values
386 : * and input connectivity.
387 : */
388 : price_badge: zPriceBadge.optional(),
389 : /** Category for the Essentials tab. If set, the node appears in Essentials. */
390 : essentials_category: z.string().optional(),
391 : /** Whether the blueprint is a global/installed blueprint (not user-created). */
392 : isGlobal: z.boolean().optional(),
393 : /**
394 : * An optional ordered list of widget names to be used when migrating a
395 : * workflow that lacks widgets_values_named. Only useful if the order of
396 : * widgets is changed after the introduction of widgets_values_named.
397 : */
398 : fallbackWidgetsValuesNames: z.array(z.string()).optional()
399 : })
400 :
401 2356 : export const zAutogrowOptions = z.object({
402 : ...zBaseInputOptions.shape,
403 : template: z.object({
404 : input: zComfyInputsSpec,
405 : names: z.array(z.string()).optional(),
406 : max: z.number().optional(),
407 : //Backend defines as mandatory with min 1, Frontend is more forgiving
408 : min: z.number().optional(),
409 : prefix: z.string().optional()
410 : })
411 : })
412 :
413 2356 : export const zDynamicComboOption = z.object({
414 : inputs: zComfyInputsSpec,
415 : key: z.string()
416 : })
417 :
418 2356 : const zDynamicComboBody = zBaseInputOptions.extend({
419 : options: z.array(zDynamicComboOption)
420 : })
421 :
422 2356 : export const zDynamicComboInputSpec = z.tuple([
423 : z.literal('COMFY_DYNAMICCOMBO_V3'),
424 : zDynamicComboBody
425 : ])
426 :
427 : /**
428 : * V2 object form of a DynamicCombo spec.
429 : *
430 : * `options` is deliberately left unvalidated here so that a single malformed
431 : * option does not discard its well-formed siblings. Consumers that need the
432 : * option bodies should validate each element with {@link zDynamicComboOption}.
433 : */
434 2356 : export const zDynamicComboSpecV2 = zBaseInputOptions.extend({
435 : type: z.literal('COMFY_DYNAMICCOMBO_V3'),
436 : options: z.array(z.unknown())
437 : })
438 :
439 2356 : export const zMatchTypeOptions = z.object({
440 : ...zBaseInputOptions.shape,
441 : type: z.literal('COMFY_MATCHTYPE_V3'),
442 : template: z.object({
443 : allowed_types: z.string(),
444 : template_id: z.string()
445 : })
446 : })
447 :
448 : /**
449 : * Input types whose spec is a container or constraint rather than a concrete
450 : * slot type. Every surface that resolves, renders or rewrites node inputs has
451 : * to special-case these, so they are enumerated once here; keying a registry
452 : * on {@link DynamicControlType} makes a missing entry a type error rather than
453 : * a silent gap.
454 : */
455 2356 : export const DYNAMIC_CONTROL_TYPES = [
456 : 'COMFY_DYNAMICGROUP_V3',
457 : 'COMFY_AUTOGROW_V3',
458 : 'COMFY_DYNAMICCOMBO_V3',
459 : 'COMFY_MATCHTYPE_V3'
460 : ] as const
461 :
462 : export type DynamicControlType = (typeof DYNAMIC_CONTROL_TYPES)[number]
463 :
464 100852100 : export function isDynamicControlType(type: string): type is DynamicControlType {
465 100852100 : return (DYNAMIC_CONTROL_TYPES as readonly string[]).includes(type)
466 : }
467 :
468 : // `/object_info`
469 : export type ComfyInputsSpec = z.infer<typeof zComfyInputsSpec>
470 : export type ComfyOutputTypesSpec = z.infer<typeof zComfyOutputTypesSpec>
471 : export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
472 :
473 : /** Full `/object_info` response: node definitions keyed by node type. */
474 : export type ObjectInfoResponse = Record<string, ComfyNodeDef>
475 : export type RemoteWidgetConfig = z.infer<typeof zRemoteWidgetConfig>
476 :
477 : export type ComboInputOptions = z.infer<typeof zComboInputOptions>
478 : export type NumericInputOptions = z.infer<typeof zNumericInputOptions>
479 :
480 : export type IntInputSpec = z.infer<typeof zIntInputSpec>
481 : export type FloatInputSpec = z.infer<typeof zFloatInputSpec>
482 : export type ComboInputSpec = z.infer<typeof zComboInputSpec>
483 : export type ComboInputSpecV2 = z.infer<typeof zComboInputSpecV2>
484 : export type InputSpec = z.infer<typeof zInputSpec>
485 :
486 : export function validateComfyNodeDef(
487 : data: unknown,
488 : onError: (error: string) => void = console.warn
489 : ): ComfyNodeDef | null {
490 : const result = zComfyNodeDef.safeParse(data)
491 : if (!result.success) {
492 : const zodError = fromZodError(result.error)
493 : onError(
494 : `Invalid ComfyNodeDef: ${JSON.stringify(data)}\n${zodError.message}`
495 : )
496 : return null
497 : }
498 : return result.data
499 : }
|