Line data Source code
1 : import { z } from 'zod'
2 : import { fromZodError } from 'zod-validation-error'
3 : import type {
4 : ClipboardItems,
5 : ExportedSubgraph,
6 : RendererType
7 : } from './serialisation'
8 : import { isWidgetValue } from './widgets'
9 : import type { TWidgetValue } from './widgets'
10 : import { parseLinkId, toLinkId } from './linkId'
11 : import type { LinkPresentation } from './linkPresentation'
12 : import type { NodeProperty } from './nodeProperty'
13 : import { toRerouteId } from './rerouteId'
14 :
15 2356 : const zRendererType = z.enum([
16 : 'LG',
17 : 'Vue',
18 : 'Vue-corrected'
19 : ]) satisfies z.ZodType<RendererType>
20 :
21 : // GroupNode is hacking node id to be a string, so we need to allow that.
22 : // innerNode.id = `${this.node.id}:${i}`
23 : // Remove it after GroupNode is redesigned.
24 2356 : export const zNodeId = z.union([z.number().int(), z.string()])
25 2356 : const zNodeInputName = z.string()
26 :
27 : /**
28 : * UUID identifier for a saved workflow.
29 : *
30 : * Workflow files persist their identity as `id: z.guid()` on the
31 : * graph schema. This alias names that primitive at use sites (services,
32 : * stores, share types) without changing structural typing.
33 : */
34 : export type WorkflowId = string
35 2356 : const zSlotIndex = z.union([
36 : z.number().int(),
37 : z
38 : .string()
39 : .transform((val) => parseInt(val))
40 : .refine((val) => !isNaN(val), {
41 : message: 'Invalid number'
42 : })
43 : ])
44 :
45 : // TODO: Investigate usage of array and number as data type usage in custom nodes.
46 : // Known usage:
47 : // - https://github.com/rgthree/rgthree-comfy Context Big node is using array as type.
48 2356 : const zDataType = z.union([z.string(), z.array(z.string()), z.number()])
49 :
50 2356 : const zVector2 = z.union([
51 : z
52 : .object({ 0: z.number(), 1: z.number() })
53 : .passthrough()
54 : .transform((v) => [v[0], v[1]] as [number, number]),
55 : z.tuple([z.number(), z.number()])
56 : ])
57 :
58 : // Definition of an AI model file used in the workflow.
59 2356 : export const zModelFile = z.object({
60 : name: z.string(),
61 : url: z.string().url(),
62 : hash: z.string().optional(),
63 : hash_type: z.string().optional(),
64 : directory: z.string()
65 : })
66 :
67 : /**
68 : * A node's declared model entry. Only `name` is required - the shape a
69 : * workflow must declare to pass validation is `zModelFile`, and a workflow
70 : * that failed it still loads.
71 : */
72 2356 : export const zDeclaredModelFile = z.object({
73 : name: z.string(),
74 : url: z.string().optional(),
75 : hash: z.string().optional(),
76 : hash_type: z.string().optional(),
77 : directory: z.string().optional()
78 : })
79 :
80 2356 : const zGraphState = z
81 : .object({
82 : lastGroupId: z.number(),
83 : lastNodeId: z.number(),
84 : lastLinkId: z.number(),
85 : lastRerouteId: z.number()
86 : })
87 : .passthrough()
88 :
89 2356 : const zComfyLink = z.tuple([
90 : z.number(), // Link id
91 : zNodeId, // Node id of source node
92 : zSlotIndex, // Output slot# of source node
93 : zNodeId, // Node id of destination node
94 : zSlotIndex, // Input slot# of destination node
95 : zDataType // Data type
96 : ])
97 :
98 : /** Extension to 0.4 schema (links as arrays): parent reroute ID */
99 2356 : const zComfyLinkExtension = z
100 : .object({
101 : id: z.number(),
102 : parentId: z.number()
103 : })
104 : .passthrough()
105 :
106 2356 : const zLinkPresentationFields = {
107 : hidden: z.boolean().optional(),
108 : label: z.string().optional()
109 : } satisfies { [K in keyof LinkPresentation]-?: z.ZodType<LinkPresentation[K]> }
110 :
111 2356 : const zComfyLinkPresentation = z.object(zLinkPresentationFields).passthrough()
112 :
113 2356 : const zComfyLinkObject = z
114 : .object({
115 : id: z.number(),
116 : origin_id: zNodeId,
117 : origin_slot: zSlotIndex,
118 : target_id: zNodeId,
119 : target_slot: zSlotIndex,
120 : type: zDataType,
121 : parentId: z.number().optional(),
122 : ...zLinkPresentationFields
123 : })
124 : .passthrough()
125 :
126 2356 : const zReroute = z
127 : .object({
128 : id: z.number(),
129 : parentId: z.number().optional(),
130 : pos: zVector2,
131 : linkIds: z.array(z.number()).nullish(),
132 : floating: z
133 : .object({
134 : slotType: z.enum(['input', 'output'])
135 : })
136 : .optional()
137 : })
138 : .passthrough()
139 :
140 2356 : const zNodeOutput = z
141 : .object({
142 : name: z.string(),
143 : type: zDataType,
144 : links: z.array(z.number()).nullable().optional(),
145 : slot_index: zSlotIndex.optional()
146 : })
147 : .passthrough()
148 :
149 2356 : const zNodeInput = z
150 : .object({
151 : name: zNodeInputName,
152 : type: zDataType,
153 : link: z.number().nullable().optional(),
154 : slot_index: zSlotIndex.optional()
155 : })
156 : .passthrough()
157 :
158 2356 : const zFlags = z
159 : .object({
160 : collapsed: z.boolean().optional(),
161 : pinned: z.boolean().optional(),
162 : allow_interaction: z.boolean().optional(),
163 : horizontal: z.boolean().optional(),
164 : skip_repeated_outputs: z.boolean().optional(),
165 : fullResolutionPreview: z.boolean().optional()
166 : })
167 : .passthrough()
168 :
169 2356 : const repoLikeIdPattern = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/
170 2356 : const githubUsernamePattern = /^(?!-)(?!.*--)[a-zA-Z0-9-]+(?<!-)$/
171 2356 : const gitHashPattern = /^[0-9a-f]{4,40}$/i
172 2356 : const semverPattern =
173 : /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?(?:\+([\da-z-]+(?:\.[\da-z-]+)*))?$/
174 :
175 : // Shared schema for Comfy Node Registry IDs and GitHub repo names
176 2356 : const zRepoLikeId = z
177 : .string()
178 : .min(1)
179 : .max(100)
180 : .regex(repoLikeIdPattern, {
181 : message: "ID can only contain ASCII letters, digits, '_', '-', and '.'"
182 : })
183 : .refine((id) => !/^[_\-.]|[_\-.]$/.test(id), {
184 : message: "ID must not start or end with '_', '-', or '.'"
185 : })
186 :
187 2356 : const zCnrId = zRepoLikeId
188 2356 : const zGithubRepoName = zRepoLikeId
189 :
190 : // GitHub username/organization schema
191 2356 : const zGithubUsername = z
192 : .string()
193 : .min(1)
194 : .max(39)
195 : .regex(githubUsernamePattern, 'Invalid GitHub username/org')
196 :
197 : // Auxiliary ID identifies node packs not installed via the Comfy Node Registry
198 2356 : const zAuxId = z
199 : .string()
200 : .regex(/^[^/]+\/[^/]+$/, "Invalid format. Must be 'github-user/repo-name'")
201 : .transform((id) => id.split('/'))
202 : .refine(
203 : ([username, repo]) =>
204 : zGithubUsername.safeParse(username).success &&
205 : zGithubRepoName.safeParse(repo).success,
206 : "Invalid aux_id: Must be valid 'github-username/github-repo-name'"
207 : )
208 : .transform(([username, repo]) => `${username}/${repo}`)
209 :
210 2356 : const zGitHash = z.string().superRefine((val: string, ctx) => {
211 0 : if (!gitHashPattern.test(val)) {
212 0 : ctx.addIssue({
213 : code: z.ZodIssueCode.custom,
214 : message: `Node pack version has invalid Git commit hash: "${val}"`
215 : })
216 : }
217 : })
218 2356 : const zSemVer = z.string().superRefine((val: string, ctx) => {
219 94 : if (!semverPattern.test(val)) {
220 0 : ctx.addIssue({
221 : code: z.ZodIssueCode.custom,
222 : message: `Node pack version has invalid semantic version: "${val}"`
223 : })
224 : }
225 : })
226 2356 : const zVersion = z.union([
227 : z
228 : .string()
229 : .transform((ver) => ver.replace(/^v/, '')) // Strip leading 'v'
230 : .pipe(z.union([zSemVer, zGitHash])),
231 : z.literal('unknown')
232 : ])
233 :
234 2356 : const zNodeProperty = z.union([
235 : z.string(),
236 : z.number(),
237 : z.boolean(),
238 : z.null(),
239 : z.record(z.string(), z.unknown()),
240 : z.array(z.unknown())
241 : ]) satisfies z.ZodType<NodeProperty>
242 :
243 2356 : const zProperties = z
244 : .object({
245 : ['Node name for S&R']: z.string().optional(),
246 : cnr_id: zCnrId.optional(),
247 : aux_id: zAuxId.optional(),
248 : ver: zVersion.optional(),
249 : models: z.array(zModelFile).optional()
250 : })
251 : .catchall(zNodeProperty.optional())
252 :
253 2356 : const zWidgetValue = z.custom<TWidgetValue>(isWidgetValue)
254 2356 : const zWidgetValues: z.ZodType<TWidgetValue[] | Record<string, TWidgetValue>> =
255 : z.union([z.array(zWidgetValue), z.record(z.string(), zWidgetValue)])
256 2356 : const MAX_CLIPBOARD_WIDGET_VALUES = 10_000
257 :
258 57 : function hasSupportedClipboardWidgetValuesLength(
259 : values: z.output<typeof zWidgetValues> | undefined
260 : ): boolean {
261 57 : if (!values || Array.isArray(values)) return true
262 57 : return (
263 : typeof values.length !== 'number' ||
264 : values.length <= MAX_CLIPBOARD_WIDGET_VALUES
265 : )
266 : }
267 :
268 1 : function isArrayLikeLength(value: TWidgetValue): value is number {
269 1 : return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
270 : }
271 :
272 57 : function normalizeClipboardWidgetValues(
273 : values: z.output<typeof zWidgetValues> | undefined
274 : ): TWidgetValue[] | undefined {
275 57 : if (!values || Array.isArray(values)) return values
276 1 : const length = values.length
277 1 : if (!isArrayLikeLength(length)) return []
278 1 : const normalized: TWidgetValue[] = []
279 1 : normalized.length = length
280 1 : for (const [key, value] of Object.entries(values)) {
281 3 : const index = Number(key)
282 3 : if (Number.isInteger(index) && index >= 0 && index < length)
283 2 : normalized[index] = value
284 : }
285 1 : return normalized
286 : }
287 :
288 57 : function normalizeClipboardNodeWidgets<
289 : T extends { widgets_values?: z.output<typeof zWidgetValues> }
290 : >(node: T) {
291 57 : const values = node.widgets_values
292 57 : if (values && !Array.isArray(values) && typeof values.length !== 'number') {
293 0 : return {
294 : ...node,
295 : widgets_values: values as unknown as TWidgetValue[],
296 : widgets_values_named: { ...values }
297 : }
298 : }
299 57 : return { ...node, widgets_values: normalizeClipboardWidgetValues(values) }
300 : }
301 :
302 2356 : export const zComfyNode = z
303 : .object({
304 : id: zNodeId,
305 : type: z.string(),
306 : pos: zVector2,
307 : size: zVector2,
308 : flags: zFlags,
309 : order: z.number(),
310 : mode: z.number(),
311 : inputs: z.array(zNodeInput).optional(),
312 : outputs: z.array(zNodeOutput).optional(),
313 : properties: zProperties,
314 : widgets_values: zWidgetValues.optional(),
315 : color: z.string().optional(),
316 : bgcolor: z.string().optional()
317 : })
318 : .passthrough()
319 :
320 2356 : const zSubgraphIO = zNodeInput.extend({
321 : /** Slot ID (internal; never changes once instantiated). */
322 : id: z.guid(),
323 : /** The data type this slot uses. Unlike nodes, this does not support legacy numeric types. */
324 : type: z.string(),
325 : /** Links connected to this slot, or `undefined` if not connected. An output slot should only ever have one link. */
326 : linkIds: z.array(z.number()).optional()
327 : })
328 :
329 2356 : const zSubgraphInstance = z
330 : .object({
331 : id: zNodeId,
332 : type: z.guid(),
333 : pos: zVector2,
334 : size: zVector2,
335 : flags: zFlags,
336 : order: z.number(),
337 : mode: z.number(),
338 : inputs: z.array(zSubgraphIO).optional(),
339 : outputs: z.array(zSubgraphIO).optional(),
340 : widgets_values: zWidgetValues.optional(),
341 : color: z.string().optional(),
342 : bgcolor: z.string().optional()
343 : })
344 : .passthrough()
345 :
346 2356 : export const zGroup = z
347 : .object({
348 : id: z.number().optional(),
349 : title: z.string(),
350 : bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),
351 : color: z.string().optional(),
352 : font_size: z.number().optional(),
353 : locked: z.boolean().optional()
354 : })
355 : .passthrough()
356 :
357 2356 : const zDS = z
358 : .object({
359 : scale: z.number(),
360 : offset: zVector2
361 : })
362 : .passthrough()
363 :
364 2356 : const zConfig = z
365 : .object({
366 : links_ontop: z.boolean().optional(),
367 : align_to_grid: z.boolean().optional()
368 : })
369 : .passthrough()
370 :
371 2356 : const zExtra = z
372 : .object({
373 : ds: zDS.optional(),
374 : frontendVersion: z.string().optional(),
375 : linkExtensions: z.array(zComfyLinkExtension).optional(),
376 : linkPresentation: z
377 : .record(
378 : z.string().refine((value) => parseLinkId(value) !== undefined, {
379 : message: 'Expected a canonical integer link ID'
380 : }),
381 : zComfyLinkPresentation
382 : )
383 : .optional(),
384 : reroutes: z.array(zReroute).optional(),
385 : workflowRendererVersion: zRendererType.optional(),
386 : BlueprintDescription: z.string().optional(),
387 : BlueprintSearchAliases: z.array(z.string()).optional(),
388 : linearMode: z.boolean().optional(),
389 : linearData: z
390 : .object({
391 : inputs: z
392 : .array(
393 : z.union([
394 : z.tuple([
395 : zNodeId,
396 : z.string(),
397 : z.object({ height: z.number().optional() }).passthrough()
398 : ]),
399 : z.tuple([zNodeId, z.string()])
400 : ])
401 : )
402 : .optional(),
403 : outputs: z.array(zNodeId).optional()
404 : })
405 : .optional()
406 : })
407 : .passthrough()
408 :
409 2356 : const zGraphDefinitions = z.object({
410 : subgraphs: z.lazy(() => z.array(zSubgraphDefinition))
411 : })
412 :
413 2356 : const zBaseExportableGraph = z.object({
414 : /** Unique graph ID. Automatically generated if not provided. */
415 : id: z.guid().optional(),
416 : revision: z.number().optional(),
417 : config: zConfig.optional().nullable(),
418 : /** Details of the appearance and location of subgraphs shown in this graph. Similar to */
419 : subgraphs: z.array(zSubgraphInstance).optional()
420 : })
421 :
422 : /** Schema version 0.4 */
423 2356 : export const zComfyWorkflow = zBaseExportableGraph
424 : .extend({
425 : id: z.guid().optional(),
426 : revision: z.number().optional(),
427 : last_node_id: zNodeId,
428 : last_link_id: z.number(),
429 : nodes: z.array(zComfyNode),
430 : links: z.array(zComfyLink),
431 : floatingLinks: z.array(zComfyLinkObject).optional(),
432 : groups: z.array(zGroup).optional(),
433 : config: zConfig.optional().nullable(),
434 : extra: zExtra.optional().nullable(),
435 : version: z.number(),
436 : models: z.array(zModelFile).optional(),
437 : definitions: zGraphDefinitions.optional()
438 : })
439 : .passthrough()
440 :
441 : /** Required for recursive definition of subgraphs. */
442 : interface ComfyWorkflow1BaseType {
443 : id?: string
444 : revision?: number
445 : version: 1
446 : models?: z.infer<typeof zModelFile>[]
447 : state: z.infer<typeof zGraphState>
448 : }
449 :
450 : /** Required for recursive definition of subgraphs w/ZodEffects. */
451 : interface ComfyWorkflow1BaseInput extends ComfyWorkflow1BaseType {
452 : groups?: z.input<typeof zGroup>[]
453 : nodes: z.input<typeof zComfyNode>[]
454 : links?: z.input<typeof zComfyLinkObject>[]
455 : floatingLinks?: z.input<typeof zComfyLinkObject>[]
456 : reroutes?: z.input<typeof zReroute>[]
457 : definitions?: {
458 : subgraphs: SubgraphDefinitionBase<ComfyWorkflow1BaseInput>[]
459 : }
460 : }
461 :
462 : /** Required for recursive definition of subgraphs w/ZodEffects. */
463 : interface ComfyWorkflow1BaseOutput extends ComfyWorkflow1BaseType {
464 : groups?: z.output<typeof zGroup>[]
465 : nodes: z.output<typeof zComfyNode>[]
466 : links?: z.output<typeof zComfyLinkObject>[]
467 : floatingLinks?: z.output<typeof zComfyLinkObject>[]
468 : reroutes?: z.output<typeof zReroute>[]
469 : definitions?: {
470 : subgraphs: SubgraphDefinitionBase<ComfyWorkflow1BaseOutput>[]
471 : }
472 : }
473 :
474 : /** Schema version 1 */
475 2356 : export const zComfyWorkflow1 = zBaseExportableGraph
476 : .extend({
477 : id: z.guid().optional(),
478 : revision: z.number().optional(),
479 : version: z.literal(1),
480 : config: zConfig.optional().nullable(),
481 : state: zGraphState,
482 : groups: z.array(zGroup).optional(),
483 : nodes: z.array(zComfyNode),
484 : links: z.array(zComfyLinkObject).optional(),
485 : floatingLinks: z.array(zComfyLinkObject).optional(),
486 : reroutes: z.array(zReroute).optional(),
487 : extra: zExtra.optional().nullable(),
488 : models: z.array(zModelFile).optional(),
489 : definitions: z
490 : .object({
491 : subgraphs: z.lazy(
492 : (): z.ZodArray<
493 : z.ZodType<
494 : SubgraphDefinitionBase<ComfyWorkflow1BaseOutput>,
495 : SubgraphDefinitionBase<ComfyWorkflow1BaseInput>
496 : >
497 : > => z.array(zSubgraphDefinition)
498 : )
499 : })
500 : .optional()
501 : })
502 : .passthrough()
503 :
504 2356 : const zExportedSubgraphIONode = z.object({
505 : id: zNodeId,
506 : bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),
507 : pinned: z.boolean().optional()
508 : })
509 :
510 2356 : const zExposedWidget = z.object({
511 : id: z.string(),
512 : name: z.string()
513 : })
514 :
515 : interface SubgraphDefinitionBase<
516 : T extends ComfyWorkflow1BaseInput | ComfyWorkflow1BaseOutput
517 : > {
518 : /** Unique graph ID. Automatically generated if not provided. */
519 : id: string
520 : revision: number
521 : name: string
522 : /** Optional description shown as tooltip when hovering over the subgraph node. */
523 : description?: string
524 : category?: string
525 : essentials_category?: string
526 : /** Custom metadata for the subgraph (description, searchAliases, etc.) */
527 : extra?: T extends ComfyWorkflow1BaseInput
528 : ? z.input<typeof zExtra> | null
529 : : z.output<typeof zExtra> | null
530 :
531 : inputNode: T extends ComfyWorkflow1BaseInput
532 : ? z.input<typeof zExportedSubgraphIONode>
533 : : z.output<typeof zExportedSubgraphIONode>
534 : outputNode: T extends ComfyWorkflow1BaseInput
535 : ? z.input<typeof zExportedSubgraphIONode>
536 : : z.output<typeof zExportedSubgraphIONode>
537 : /** Ordered list of inputs to the subgraph itself. Similar to a reroute, with the input side in the graph, and the output side in the subgraph. */
538 : inputs?: T extends ComfyWorkflow1BaseInput
539 : ? z.input<typeof zSubgraphIO>[]
540 : : z.output<typeof zSubgraphIO>[]
541 : /** Ordered list of outputs from the subgraph itself. Similar to a reroute, with the input side in the subgraph, and the output side in the graph. */
542 : outputs?: T extends ComfyWorkflow1BaseInput
543 : ? z.input<typeof zSubgraphIO>[]
544 : : z.output<typeof zSubgraphIO>[]
545 : /** A list of node widgets displayed in the parent graph, on the subgraph object. */
546 : widgets?: T extends ComfyWorkflow1BaseInput
547 : ? z.input<typeof zExposedWidget>[]
548 : : z.output<typeof zExposedWidget>[]
549 : definitions?: {
550 : subgraphs: SubgraphDefinitionBase<T>[]
551 : }
552 : }
553 :
554 : /** A subgraph definition `worfklow.definitions.subgraphs` */
555 2356 : const zSubgraphDefinition = zComfyWorkflow1
556 : .extend({
557 : /** Unique graph ID. Automatically generated if not provided. */
558 : id: z.guid(),
559 : revision: z.number(),
560 : name: z.string(),
561 : /** Optional description shown as tooltip when hovering over the subgraph node. */
562 : description: z.string().optional(),
563 : category: z.string().optional(),
564 : essentials_category: z.string().optional(),
565 : inputNode: zExportedSubgraphIONode,
566 : outputNode: zExportedSubgraphIONode,
567 :
568 : /** Ordered list of inputs to the subgraph itself. Similar to a reroute, with the input side in the graph, and the output side in the subgraph. */
569 : inputs: z.array(zSubgraphIO).optional(),
570 : /** Ordered list of outputs from the subgraph itself. Similar to a reroute, with the input side in the subgraph, and the output side in the graph. */
571 : outputs: z.array(zSubgraphIO).optional(),
572 : /** A list of node widgets displayed in the parent graph, on the subgraph object. */
573 : widgets: z.array(zExposedWidget).optional(),
574 : definitions: z
575 : .object({
576 : subgraphs: z.lazy(
577 : (): z.ZodArray<
578 : z.ZodType<
579 : SubgraphDefinitionBase<ComfyWorkflow1BaseInput>,
580 : SubgraphDefinitionBase<ComfyWorkflow1BaseInput>
581 : >
582 : > => zSubgraphDefinition.array()
583 : )
584 : })
585 : .optional()
586 : })
587 : .passthrough()
588 :
589 2356 : const zClipboardNode = zComfyNode
590 : .refine(
591 : (node) => hasSupportedClipboardWidgetValuesLength(node.widgets_values),
592 : {
593 : path: ['widgets_values'],
594 : message: 'Clipboard widget values length is too large'
595 : }
596 : )
597 : .transform(normalizeClipboardNodeWidgets)
598 :
599 2356 : const zClipboardSubgraphInstance = zSubgraphInstance
600 : .refine(
601 : (node) => hasSupportedClipboardWidgetValuesLength(node.widgets_values),
602 : {
603 : path: ['widgets_values'],
604 : message: 'Clipboard widget values length is too large'
605 : }
606 : )
607 : .transform(normalizeClipboardNodeWidgets)
608 :
609 2356 : const zClipboardGroup = zGroup.transform((group) => ({
610 : ...group,
611 : id: group.id ?? -1
612 : }))
613 2356 : const zClipboardReroute = zReroute.transform((reroute) => ({
614 : ...reroute,
615 : linkIds: reroute.linkIds ?? []
616 : }))
617 :
618 : interface ClipboardSubgraphInput extends Omit<
619 : z.input<typeof zSubgraphDefinition>,
620 : 'groups' | 'nodes' | 'reroutes' | 'subgraphs' | 'definitions'
621 : > {
622 : groups?: z.input<typeof zClipboardGroup>[]
623 : nodes: z.input<typeof zClipboardNode>[]
624 : reroutes?: z.input<typeof zClipboardReroute>[]
625 : subgraphs?: z.input<typeof zClipboardSubgraphInstance>[]
626 : definitions?: { subgraphs: ClipboardSubgraphInput[] }
627 : }
628 :
629 2356 : const zClipboardSubgraphDefinition: z.ZodType<
630 : ExportedSubgraph,
631 : ClipboardSubgraphInput
632 : > = zSubgraphDefinition
633 : .extend({
634 : groups: z.array(zClipboardGroup).optional(),
635 : nodes: z.array(zClipboardNode),
636 : reroutes: z.array(zClipboardReroute).optional(),
637 : subgraphs: z.array(zClipboardSubgraphInstance).optional(),
638 : definitions: z
639 : .object({
640 : subgraphs: z.lazy(() => z.array(zClipboardSubgraphDefinition))
641 : })
642 : .optional()
643 : })
644 : .transform(({ config, extra, ...subgraph }) => {
645 2 : const normalizedExtra = extra
646 : ? {
647 : ...extra,
648 : reroutes: extra.reroutes?.map((reroute) => ({
649 : ...reroute,
650 : linkIds: reroute.linkIds ?? []
651 : })),
652 : linkExtensions: extra.linkExtensions?.map((link) => ({
653 : ...link,
654 : id: toLinkId(link.id),
655 : parentId: toRerouteId(link.parentId)
656 : }))
657 : }
658 : : undefined
659 2 : return {
660 : ...subgraph,
661 : config: config ?? undefined,
662 : extra: normalizedExtra
663 : }
664 : })
665 :
666 : const zClipboardItemsSchema = z
667 : .object({
668 : nodes: z.array(zClipboardNode).optional(),
669 : groups: z.array(zClipboardGroup).optional(),
670 : reroutes: z.array(zClipboardReroute).optional(),
671 : links: z.array(zComfyLinkObject).optional(),
672 : subgraphs: z.array(zClipboardSubgraphDefinition).optional()
673 : })
674 : .refine(
675 : (items) =>
676 : items.nodes !== undefined ||
677 : items.groups !== undefined ||
678 : items.reroutes !== undefined ||
679 : items.links !== undefined ||
680 : items.subgraphs !== undefined
681 : )
682 :
683 2356 : export const zClipboardItems: z.ZodType<
684 : ClipboardItems,
685 : z.input<typeof zClipboardItemsSchema>
686 : > = zClipboardItemsSchema
687 :
688 : export type ModelFile = z.infer<typeof zModelFile>
689 : export type DeclaredModelFile = z.infer<typeof zDeclaredModelFile>
690 : export type ComfyLinkObject = z.infer<typeof zComfyLinkObject>
691 : export type ComfyNode = z.infer<typeof zComfyNode>
692 : export type Reroute = z.infer<typeof zReroute>
693 : export type WorkflowJSON04 = z.infer<typeof zComfyWorkflow>
694 : export type ComfyWorkflowJSON = z.infer<
695 : typeof zComfyWorkflow | typeof zComfyWorkflow1
696 : >
697 :
698 : /**
699 : * The minimum a node must carry for `LGraph.configure` to instantiate it:
700 : * it calls `LiteGraph.createNode(type)` and assigns `id`.
701 : */
702 2356 : const zLegacyLoadableNode = z
703 : .object({
704 : id: zNodeId,
705 : type: z.string()
706 : })
707 : .passthrough()
708 :
709 2356 : export const zLegacyLoadableWorkflow = z
710 : .object({
711 : version: z.number(),
712 : nodes: z.array(zLegacyLoadableNode),
713 : links: z.array(z.unknown()).optional(),
714 : last_node_id: zNodeId.optional(),
715 : last_link_id: z.number().optional()
716 : })
717 : .passthrough()
718 : export type LegacyLoadableWorkflow = z.infer<typeof zLegacyLoadableWorkflow>
719 :
720 2356 : const zWorkflowVersion = z.object({
721 : version: z.number()
722 : })
723 :
724 12 : export async function validateComfyWorkflow(
725 : data: unknown,
726 : onError: (error: string) => void = console.warn
727 : ): Promise<ComfyWorkflowJSON | null> {
728 12 : const versionResult = zWorkflowVersion.safeParse(data)
729 :
730 12 : let result: z.ZodSafeParseResult<ComfyWorkflowJSON>
731 12 : if (!versionResult.success) {
732 : // Invalid workflow
733 : const error = fromZodError(versionResult.error)
734 0 : onError(`Workflow does not contain a valid version. Zod error:\n${error}`)
735 0 : return null
736 12 : } else if (versionResult.data.version === 1) {
737 : // Schema version 1
738 0 : result = await zComfyWorkflow1.safeParseAsync(data)
739 : } else {
740 : // Unknown or old version: 0.4
741 12 : result = await zComfyWorkflow.safeParseAsync(data)
742 : }
743 12 : if (result.success) return result.data
744 :
745 : const error = fromZodError(result.error)
746 0 : onError(`Invalid workflow against zod schema:\n${error}`)
747 0 : return null
748 : }
749 :
750 : /**
751 : * API format workflow for direct API usage.
752 : */
753 2356 : const zNodeInputValue = z.union([
754 : // For widget values (can be any type)
755 :
756 : z.any(),
757 : // For node links [nodeId, slotIndex]
758 : z.tuple([zNodeId, zSlotIndex])
759 : ])
760 :
761 2356 : export const zNodePackMetadata = zProperties
762 : .pick({ cnr_id: true, aux_id: true, ver: true })
763 : .strip()
764 :
765 2356 : const zNodeData = z.object({
766 : inputs: z.record(zNodeInputName, zNodeInputValue),
767 : class_type: z.string(),
768 : _meta: zNodePackMetadata.extend({ title: z.string() }).optional()
769 : })
770 :
771 2356 : export const zComfyApiWorkflow = z.record(zNodeId, zNodeData)
772 : export type ComfyApiWorkflow = z.infer<typeof zComfyApiWorkflow>
|