PageSourceSearch

https://benjaminpittsley-dgg-comfyui.hf.space/assets/api-DzWNw5Ki.js

js benjaminpittsley-dgg-comfyui.hf.space collected 2026-10-03 16:43:42 UTC 457,590 bytes, 5 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./authStore-DFx0_RKO.js","./vendor-primevue-B5RSM0_L.js","./rolldown-runtime-DIIn1E2Q.js","./vendor-vue-core-YYGrZyUu.js","./dialogService-CVq-DX47.js","./_plugin-vue_export-helper-DFeget8G.js","./vendor-other-ifjiCTHW.js","./vendor-firebase-D7u00oy9.js","./vendor-three-WGQ9WPGE.js","./vendor-tiptap-AOzK4mYE.js","./vendor-zod-D4_SPtaA.js","./vendor-reka-ui-DCJH9-ga.js","./vendor-i18n-CnkrwQFe.js","./vendor-sentry-DDIxZ--H.js","./vendor-vueuse-B0E_utTN.js","./vendor-axios-CBXSxNK3.js","./vendor-markdown-CZQ8Ww3g.js","./formatUtil-HhX6KOOu.js","./src-CxUrk4NF.js","./downloadUtil-CFk34M5L.js","./i18n-Cao-Tg17.js","./commands-CM-jjkZ6.js","./main-D1dXkThe.js","./nodeDefs-B8Ivh7kD.js","./settings-JyxQt36L.js","./types-Btv0n5Jk.js","./toastStore-VTOcZeBz.js","./WaveAudioPlayer-CKgHSYyo.js","./Button-7zfaQ5So.js","./Slider-B54nPF3f.js","./Loader-D9QKHX9x.js","./Popover-CeaNMMzY.js","./DialogHeader-D2_3bxBd.js","./Input-C860XbUi.js","./SelectValue-BNESeFMt.js","./useCopyToClipboard-zuEs9ou5.js","./useErrorHandling-KYy6n8sm.js","./useExternalLink-CMNdQK0M.js","./envUtil-BMlCzY92.js","./useFeatureFlags-FMR1aaWr.js","./remoteConfig-CRr1Wqip.js","./devFeatureFlagOverride-JgCgZSMN.js","./widget-rWQfsHM3.js","./VideoPlayOverlay-BISdn8Ba.js","./assetMetadataUtils-BvOXgx9t.js","./useFeatureUsageTracker-B2pEnJte.js","./telemetry-B0ZwHBL8.js","./topupTracker-Bz8RZiER.js","./dialogStore-CawlP8vJ.js","./userStore-C4MxkVer.js","./widgetTypes-Cb7YnQDk.js","./colorUtil-_3GyXjLD.js","./markdownRendererUtil-CdS_PQqL.js","./vendor-other-CaaUC6Qe.css","./dialogService-lJepc2Rd.css"])))=>i.map(i=>d[i]);
2import{a as e,r as t}from"./rolldown-runtime-DIIn1E2Q.js";import{rt as n}from"./vendor-primevue-B5RSM0_L.js";import{At as r,Et as i,Lt as a,Ot as o,St as s,c,k as l,u}from"./vendor-vue-core-YYGrZyUu.js";import{H as d,P as f,Q as p,St as m,ct as h,dt as g,nt as _,ut as v}from"./vendor-other-ifjiCTHW.js";import{t as y}from"./types-Btv0n5Jk.js";import{L as ee,et as te,q as ne}from"./vendor-vueuse-B0E_utTN.js";import{t as b}from"./vendor-axios-CBXSxNK3.js";import{t as re}from"./devFeatureFlagOverride-JgCgZSMN.js";import{t as ie}from"./toastStore-VTOcZeBz.js";import{C as x,S,T as ae,_ as C,b as w,c as T,d as E,f as oe,g as D,m as se,o as O,p as k,s as A,t as ce,x as j,y as M}from"./vendor-zod-D4_SPtaA.js";import{r as le}from"./vendor-markdown-CZQ8Ww3g.js";import{i as ue,n as de,r as fe,t as pe}from"./vendor-yjs-twuETALr.js";import{t as me}from"./colorUtil-_3GyXjLD.js";import{c as he}from"./i18n-Cao-Tg17.js";import{n as ge,t as _e}from"./widget-rWQfsHM3.js";var ve={supports_preview_metadata:!0,supports_manager_v4_ui:!0,supports_progress_text_metadata:!0},ye=[`span`,`b`,`i`,`em`,`strong`],be=new Set([`display`,`color`,`background-color`,`padding-left`,`border-left`]);le.addHook(`uponSanitizeAttribute`,(e,t)=>{t.attrName===`style`&&(t.attrValue=t.attrValue.split(`;`).map(e=>e.trim()).filter(e=>{let t=e.indexOf(`:`);if(t===-1)return!1;let n=e.slice(0,t).trim().toLowerCase();return be.has(n)}).join(`; `))});function sanitizeMenuHTML(e){return le.sanitize(e,{ALLOWED_TAGS:ye,ALLOWED_ATTR:[`style`]})}var xe=class ContextMenu{options;parentMenu;root;current_submenu;lock;controller=new AbortController;constructor(e,t){t||={},this.options=t;let n=t.parentMenu;n&&(n instanceof ContextMenu?(this.parentMenu=n,this.parentMenu.lock=!0,this.parentMenu.current_submenu=this):(console.error(`parentMenu must be of class ContextMenu, ignoring it`),t.parentMenu=void 0),n.options?.className===`dark`&&(t.className=`dark`));let r=t.event?t.event.constructor.name:null;r!==`MouseEvent`&&r!==`CustomEvent`&&r!==`PointerEvent`&&(console.error(`Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (${r})`),t.event=void 0);let i=document.createElement(`div`),a=`litegraph litecontextmenu litemenubar-panel`;t.className&&(a+=` ${t.className}`),i.className=a,i.style.minWidth=`100`,i.style.minHeight=`100`;let{signal:o}=this.controller,s={capture:!0,signal:o};if(this.parentMenu||document.addEventListener(`pointerdown`,e=>{e.target instanceof Node&&!this.containsNode(e.target)&&this.close()},s),i.addEventListener(`pointerup`,e=>e.preventDefault(),s),i.addEventListener(`contextmenu`,e=>{e.button===2&&e.preventDefault()},s),i.addEventListener(`pointerdown`,e=>{e.button==2&&(this.close(),e.preventDefault())},s),this.root=i,t.title){let e=document.createElement(`div`);e.className=`litemenu-title`,e.textContent=t.title,i.append(e)}for(let n=0;n<e.length;n++){let r=e[n],i=Array.isArray(e)?r:String(n);typeof i!=`string`&&(i=i==null?i:i.content===void 0?String(i):i.content),this.addItem(i,r,t)}let c=t.event?.target?.ownerDocument||document;c.fullscreenElement?c.fullscreenElement.append(i):c.body.append(i);let l=t.left||0,u=t.top||0;if(t.event){if(l=t.event.clientX-10,u=t.event.clientY-10,t.title&&(u-=20),n){let e=n.root.getBoundingClientRect();l=e.left+e.width}
2let e=document.body.getBoundingClientRect(),r=i.getBoundingClientRect();e.height==0&&console.error(`document.body height is 0. That is dangerous, set html,body { height: 100%; }`),e.width&&l>e.width-r.width-10&&(l=e.width-r.width-10),e.height&&u>e.height-r.height-10&&(u=e.height-r.height-10)}i.style.left=`${l}px`,i.style.top=`${u}px`,Q.context_menu_scaling&&t.scale&&(i.style.transform=`scale(${Math.round(t.scale*4)*.25})`)}containsNode(e,t=new Set){return t.has(this)?!1:(t.add(this),this.current_submenu?.containsNode(e,t)||this.root.contains(e))}addItem(e,t,n){n||={};let r=document.createElement(`div`);r.className=`litemenu-entry submenu`;let i=!1;if(t===null)r.classList.add(`separator`);else{let n=e===null?``:String(e);typeof t==`string`?r.textContent=n:(t?.content!==void 0&&/<[a-z][\s\S]*>/i.test(t.content)?r.innerHTML=sanitizeMenuHTML(t.content):r.textContent=t?.title??n,t.disabled&&(i=!0,r.classList.add(`disabled`),r.setAttribute(`aria-disabled`,`true`)),(t.submenu||t.has_submenu)&&(r.classList.add(`has_submenu`),r.setAttribute(`aria-haspopup`,`true`),r.setAttribute(`aria-expanded`,`false`)),t.className&&(r.className+=` ${t.className}`)),r.value=t,r.setAttribute(`role`,`menuitem`),typeof t==`function`?(r.dataset.value=String(e),r.onclick_callback=t):r.dataset.value=String(t)}this.root.append(r),i||r.addEventListener(`click`,inner_onclick),!i&&n.autoopen&&r.addEventListener(`pointerenter`,inner_over);let setAriaExpanded=()=>{let e=this.root.querySelectorAll(`div.litemenu-entry.has_submenu`);if(e)for(let t of e)t.setAttribute(`aria-expanded`,`false`);r.setAttribute(`aria-expanded`,`true`)};function inner_over(e){let t=this.value;!t||!t.has_submenu||(inner_onclick.call(this,e),setAriaExpanded())}let a=this;function inner_onclick(e){let t=this.value,r=!0;if(a.current_submenu?.close(e),(t?.has_submenu||t?.submenu)&&setAriaExpanded(),n.callback&&n.callback.call(this,t,n,e,a,n.node)===!0&&(r=!1),typeof t==`object`&&(t.callback&&!n.ignore_item_callbacks&&t.disabled!==!0&&t.callback.call(this,t,n,e,a,n.extra)===!0&&(r=!1),t.submenu)){if(!t.submenu.options)throw`ContextMenu submenu needs options`;new a.constructor(t.submenu.options,{callback:t.submenu.callback,event:e,parentMenu:a,ignore_item_callbacks:t.submenu.ignore_item_callbacks,title:t.submenu.title,extra:t.submenu.extra,autoopen:n.autoopen}),r=!1}r&&!a.lock&&a.close()}return r}close(e,t){this.controller.abort(),this.root.remove(),this.parentMenu&&!t&&(this.parentMenu.lock=!1,this.parentMenu.current_submenu=void 0,e===void 0?this.parentMenu.close():e&&!ContextMenu.isCursorOverElement(e,this.parentMenu.root)&&ContextMenu.trigger(this.parentMenu.root,`${Q.pointerevents_method}leave`,e)),this.current_submenu?.close(e,!0)}static trigger(e,t,n){let r=document.createEvent(`CustomEvent`);return r.initCustomEvent(t,!0,!0,n),e.dispatchEvent&&e.dispatchEvent(r),r}getTopMenu(){return this.options.parentMenu?this.options.parentMenu.getTopMenu():this}getFirstEvent(){return this.options.parentMenu?this.options.parentMenu.getFirstEvent():this.options.event}static isCursorOverElement(e,t){let n=e.clientX,r=e.clientY,i=t.getBoundingClientRect();return i?r>i.top&&r<i.top+i.height&&n>i.left&&n<i.left+i.width:!1}},N=function(e){return e[e.INPUT=1]=`INPUT`,e[e.OUTPUT=2]=`OUTPUT`,e}({}),P=function(e){return e[e.BOX=1]=`BOX`,e[e.ROUND=2]=`ROUND`,e[e.CIRCLE=3]=`CIRCLE`,e[e.CARD=4]=`CARD`,e[e.ARROW=5]=`ARROW`,e[e.GRID=6]=`GRID`,e[e.HollowCircle=7]=`HollowCircle`,e}({}),F=function(e){return e[e.Nothing=0]=`Nothing`,e[e.Node=1]=`Node`,e[e.Group=2]=`Group`,e[e.Reroute=4]=`Reroute`,e[e.Link=8]=`Link`,e[e.RerouteSlot=32]=`RerouteSlot`,e[e.SubgraphIoNode=64]=`SubgraphIoNode`,e[e.SubgraphIoSlot=128]=`SubgraphIoSlot`,e}({}),I=function(e){return e[e.NONE=0]=`NONE`,e[e.UP=1]=`UP`,e[e.DOWN=2]=`DOWN`,e[e.LEFT=3]=`LEFT`,e[e.RIGHT=4]=`RIGHT`,e[e.CENTER=5]=`CENTER`,e}({}),L=function(e){return e[e.HIDDEN_LINK=-1]=`HIDDEN_LINK`,e[e.STRAIGHT_LINK=0]=`STRAIGHT_LINK`,e[e.LINEAR_LINK=1]=`LINEAR_LINK`,e[e.SPLINE_LINK=2]=`SPLINE_LINK`,e}({}),R=function(e){return e[e.None=0]=`None`,e[e.Circle=1]=`Circle`,e[e.Arrow=2]=`Arrow`,e}({}),z=function(e){return e[e.NORMAL_TITLE=0]=`NORMAL_TITLE`,e[e.NO_TITLE=1]=`NO_TITLE`,e[e.TRANSPARENT_TITLE=2]=`TRANSPARENT_TITLE`,e[e.AUTOHIDE_TITLE=3]=`AUTOHIDE_TITLE`,e}({}),B=function(e){return e[e.ALWAYS=0]=`ALWAYS`,e[e.ON_EVENT=1]=`ON_EVENT`,e[e.NEVER=2]=`NEVER`,e[e.ON_TRIGGER=3]=`ON_TRIGGER`,e[e.BYPASS=4]=`BYPASS`,e}({}
2),Se=function(e){return e.EASE_IN_OUT_QUAD=`easeInOutQuad`,e}({}),V=function(e){return e[e.None=0]=`None`,e[e.Top=1]=`Top`,e[e.Bottom=2]=`Bottom`,e[e.Middle=4]=`Middle`,e[e.Left=8]=`Left`,e[e.Right=16]=`Right`,e[e.Centre=32]=`Centre`,e[e.TopLeft=9]=`TopLeft`,e[e.TopCentre=33]=`TopCentre`,e[e.TopRight=17]=`TopRight`,e[e.MidLeft=12]=`MidLeft`,e[e.MidCentre=36]=`MidCentre`,e[e.MidRight=20]=`MidRight`,e[e.BottomLeft=10]=`BottomLeft`,e[e.BottomCentre=34]=`BottomCentre`,e[e.BottomRight=18]=`BottomRight`,e}({});function hasFlag(e,t){return(e&t)===t}function distance(e,t){return Math.sqrt((t[0]-e[0])*(t[0]-e[0])+(t[1]-e[1])*(t[1]-e[1]))}function dist2(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)}function isInRectangle(e,t,n,r,i,a){return e>=n&&e<n+i&&t>=r&&t<r+a}function isPointInRect(e,t){return e[0]>=t[0]&&e[0]<t[0]+t[2]&&e[1]>=t[1]&&e[1]<t[1]+t[3]}function isInRect(e,t,n){return e>=n[0]&&e<n[0]+n[2]&&t>=n[1]&&t<n[1]+n[3]}function isInsideRectangle(e,t,n,r,i,a){return n<e&&n+i>e&&r<t&&r+a>t}function overlapBounding(e,t){let n=e[0]+e[2],r=e[1]+e[3],i=t[0]+t[2],a=t[1]+t[3];return!(e[0]>i||e[1]>a||n<t[0]||r<t[1])}function getCentre(e){return[e[0]+e[2]*.5,e[1]+e[3]*.5]}function containsCentre(e,t){return isInRect(t[0]+t[2]*.5,t[1]+t[3]*.5,e)}function containsRect(e,t){let n=e[0]+e[2],r=e[1]+e[3],i=t[0]+t[2],a=t[1]+t[3];return!(e[0]===t[0]&&e[1]===t[1]&&n===i&&r===a)&&e[0]<=t[0]&&e[1]<=t[1]&&n>=i&&r>=a}function createBounds(e,t=10){let n=[1/0,1/0,-1/0,-1/0];for(let t of e){let e=t.boundingRect;n[0]=Math.min(n[0],e[0]),n[1]=Math.min(n[1],e[1]),n[2]=Math.max(n[2],e[0]+e[2]),n[3]=Math.max(n[3],e[1]+e[3])}return n.every(e=>isFinite(e))?[n[0]-t,n[1]-t,n[2]-n[0]+2*t,n[3]-n[1]+2*t]:null}function snapPoint(e,t,n=`round`){return t?(e[0]=t*Math[n](e[0]/t),e[1]=t*Math[n](e[1]/t),!0):!1}function alignToContainer(e,t,[n,r,i,a],[o,s]=[0,0]){return hasFlag(t,V.Left)?e[0]=n+o:hasFlag(t,V.Right)?e[0]=n+i-o-e[2]:hasFlag(t,V.Centre)&&(e[0]=n+i*.5-e[2]*.5),hasFlag(t,V.Top)?e[1]=r+s:hasFlag(t,V.Bottom)?e[1]=r+a-s-e[3]:hasFlag(t,V.Middle)&&(e[1]=r+a*.5-e[3]*.5),e}function alignOutsideContainer(e,t,[n,r,i,a],[o,s]=[0,0]){return hasFlag(t,V.Left)?e[0]=n-o-e[2]:hasFlag(t,V.Right)?e[0]=n+i+o:hasFlag(t,V.Centre)&&(e[0]=n+i*.5-e[2]*.5),hasFlag(t,V.Top)?e[1]=r-s-e[3]:hasFlag(t,V.Bottom)?e[1]=r+a+s:hasFlag(t,V.Middle)&&(e[1]=r+a*.5-e[3]*.5),e}var CurveEditor=class{points;selected;nearest;size;must_update;margin;_nearest;constructor(e){this.points=e,this.selected=-1,this.nearest=-1,this.size=null,this.must_update=!0,this.margin=5}static sampleCurve(e,t){if(t){for(let n=0;n<t.length-1;++n){let r=t[n],i=t[n+1];if(i[0]<e)continue;let a=i[0]-r[0];if(Math.abs(a)<1e-5)return r[1];let o=(e-r[0])/a;return r[1]*(1-o)+i[1]*o}return 0}}draw(e,t,n,r,i,a=!1){let o=this.points;if(!o)return;this.size=t;let s=t[0]-this.margin*2,c=t[1]-this.margin*2;i||=`#666`,e.save(),e.translate(this.margin,this.margin),r&&(e.fillStyle=`#111`,e.fillRect(0,0,s,c),e.fillStyle=`#222`,e.fillRect(s*.5,0,1,c),e.strokeStyle=`#333`,e.strokeRect(0,0,s,c)),e.strokeStyle=i,a&&(e.globalAlpha=.5),e.beginPath();for(let t of o)e.lineTo(t[0]*s,(1-t[1])*c);if(e.stroke(),e.globalAlpha=1,!a)for(let[t,n]of o.entries())e.fillStyle=this.selected==t?`#FFF`:this.nearest==t?`#DDD`:`#AAA`,e.beginPath(),e.arc(n[0]*s,(1-n[1])*c,2,0,Math.PI*2),e.fill();e.restore()}onMouseDown(e,t){let n=this.points;if(!n||e[1]<0)return;if(this.size==null)throw Error(`CurveEditor.size was null or undefined.`);let r=this.size[0]-this.margin*2,i=this.size[1]-this.margin*2,a=e[0]-this.margin,o=e[1]-this.margin,s=[a,o],c=30/t.ds.scale;if(this.selected=this.getCloserPoint(s,c),this.selected==-1){let e=[a/r,1-o/i];n.push(e),n.sort(function(e,t){return e[0]-t[0]}),this.selected=n.indexOf(e),this.must_update=!0}if(this.selected!=-1)return!0}onMouseMove(e,t){let n=this.points;if(!n)return;let r=this.selected;if(r<0)return;if(this.size==null)throw Error(`CurveEditor.size was null or undefined.`);let i=(e[0]-this.margin)/(this.size[0]-this.margin*2),a=(e[1]-this.margin)/(this.size[1]-this.margin*2),o=[e[0]-this.margin,e[1]-this.margin],s=30/t.ds.scale;this._nearest=this.getCloserPoint(o,s);let c=n[r];if(c){let t=r==0||r==n.length-1;if(!t&&(e[0]<-10||e[0]>this.size[0]+10||e[1]<-10||e[1]>this.size[1]+10)){n.splice(r,1),this.selected=-1;return}t?c[0]=r==0?0:1:c[0]=h(i,0,1),c[1]=1-h(a,0,1),n.sort(function(e,t){return e[0]-t[0]}),this.selected=n.indexOf(c),this.must_update=!0}}onMouseUp(){return this.selected=-1,!1}getCloserPoint(e,t){let n=this.points;if(!n)return-1;if(t||=30,this.size==null)throw Error(`CurveEditor.size was null or undefined.`);let r=this.size[0]-this.margin*2,i=this.size[1]-this.margin*2,a=n.length,o=[0,0],s=1e6,c=-1;for(let l=0;l<a;++l){let a=n[l];o[0]=a[0]*r,o[1]=(1-a[1])*i;let u=distance(e,o);u>s||u>t||(c=l,s=u)}return c}},DragAndScale=class{state;lastState={offset:[0,0],scale:0};max_scale;min_scale;enabled;last_mouse;element;visible_area;dragging;viewport;get offset(){return this.state.offset}set offset(e){this.state.offset[0]=e[0],this.state.offset[1]=e[1]}get scale(){return this.state.scale}set scale(e){this.state.scale=e}constructor(e){this.state={offset:[0,0],scale:1},this.max_scale=10,this.min_scale=.1,this.enabled=!0,this.last_mouse=[0,0],this.visible_area=new G,this.element=e}_stateHasChanged(){let e=this.state,t=this.lastState;return e.scale!==t.scale||e.offset[0]!==t.offset[0]||e.offset[1]!==t.offset[1]}computeVisibleArea(e){let{scale:t,offset:n,visible_area:r}=this;if(this._stateHasChanged()&&(this.onChanged?.(t,n),copyState(this.state,this.lastState)),!this.element){r[0]=r[1]=r[2]=r[3]=0;return}let{width:i,height:a}=this.element,o=-n[0],s=-n[1];e&&(o+=e[0]/t,s+=e[1]/t,i=e[2],a=e[3]);let c=o+i/t,l=s+a/t;r[0]=o,r[1]=s,r.resizeBottomRight(c,l)}toCanvasContext(e){e.scale(this.scale,this.scale),e.translate(this.offset[0],this.offset[1])}convertOffsetToCanvas(e){return[(e[0]+this.offset[0])*this.scale,(e[1]+this.offset[1])*this.scale]}convertCanvasToOffset(e,t){return t||=[0,0],t[0]=e[0]/this.scale-this.offset[0],t[1]=e[1]/this.scale-this.offset[1],t}mouseDrag(e,t){this.offset[0]+=e/this.scale,this.offset[1]+=t/this.scale,this.onredraw?.(this)}changeScale(e,t,n=!0){if(e<this.min_scale?e=this.min_scale:e>this.max_scale&&(e=this.max_scale),e==this.scale)return;let r=this.element.getBoundingClientRect();if(!r)return;t??=[r.width*.5,r.height*.5];let i=[t[0]-r.x,t[1]-r.y],a=this.convertCanvasToOffset(i);this.scale=e,n&&Math.abs(this.scale-1)<.01&&(this.scale=1);let o=this.convertCanvasToOffset(i),s=[o[0]-a[0],o[1]-a[1]];this.offset[0]+=s[0],this.offset[1]+=s[1],this.onredraw?.(this)}changeDeltaScale(e,t){this.changeScale(this.scale*e,t)}fitToBounds(e,{zoom:t=.75}={}){let[n,r]=this.element.width===300&&this.element.height===150?[1920,1080]:[this.element.width,this.element.height],i=n/window.devicePixelRatio,a=r/window.devicePixelRatio,o=this.scale;if(t>0){let n=t*i/Math.max(e[2],300),r=t*a/Math.max(e[3],300);o=Math.min(n,r,this.max_scale)}let s=i/o,c=a/o,l=-e[0]-e[2]*.5+s*.5,u=-e[1]-e[3]*.5+c*.5;this.offset[0]=l,this.offset[1]=u,this.scale=o}animateToBounds(e,t,{duration:n=350,zoom:r=.75,easing:i=Se.EASE_IN_O
2UT_QUAD}={}){if(!(n>0))throw RangeError(`Duration must be greater than 0`);let a={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:-1+(4-2*e)*e},o=a[i]??a.linear,s=performance.now(),c=this.element.width/window.devicePixelRatio,l=this.element.height/window.devicePixelRatio,u=this.offset[0],d=this.offset[1],f=u-c/this.scale,p=d-l/this.scale,m=this.scale;if(r>0){let t=r*c/Math.max(e[2],300),n=r*l/Math.max(e[3],300);m=Math.min(t,n,this.max_scale)}let h=c/m,g=l/m,_=-e[0]-e[2]*.5+h*.5,v=-e[1]-e[3]*.5+g*.5,y=_-h,ee=v-g,animate=e=>{let i=e-s,a=Math.min(i/n,1),m=o(a),h=u+(_-u)*m,g=d+(v-d)*m;if(this.offset[0]=h,this.offset[1]=g,r>0){let e=f+(y-f)*m,t=p+(ee-p)*m,n=Math.abs(e-h),r=Math.abs(t-g);this.scale=Math.min(c/n,l/r)}t(),a<1?te=requestAnimationFrame(animate):cancelAnimationFrame(te)},te=requestAnimationFrame(animate)}reset(){this.scale=1,this.offset[0]=0,this.offset[1]=0}};function copyState(e,t){t.scale=e.scale,t.offset[0]=e.offset[0],t.offset[1]=e.offset[1]}function toClass(e,...t){return t[0]instanceof e?t[0]:new e(...t)}function isColorable(e){return typeof e==`object`&&!!e&&`setColorOption`in e&&`getColorOption`in e}function isNodeBindable(e){return typeof e==`object`&&!!e&&`setNodeId`in e&&typeof e.setNodeId==`function`}function commonType(...e){if(!isStrings(e))return;let t=_(e,`*`);if(t.length===0)return`*`;let n=intersection(...t.map(e=>e.split(`,`)));if(n.length!==0)return n.join(`,`)}function intersection(...e){let t={};for(let n of e)for(let e of new Set(n))t[e]=(t[e]??0)+1;return Object.entries(t).filter(([,t])=>t===e.length).map(([e])=>e)}function isStrings(e){return e.every(e=>typeof e==`string`)}var Ce=`00000000-0000-0000-0000-000000000000`,we=new Uint32Array(31);function createUuidv4(){if(typeof crypto?.randomUUID==`function`)return crypto.randomUUID();if(typeof crypto?.getRandomValues==`function`){let e=crypto.getRandomValues(we),t=0;return`10000000-1000-4000-8000-100000000000`.replaceAll(/[018]/g,n=>(Number(n)^e[t++]*3.725290298461914e-9>>Number(n)*.25).toString(16))}return`10000000-1000-4000-8000-100000000000`.replaceAll(/[018]/g,e=>(Number(e)^Math.random()*16>>Number(e)*.25).toString(16))}var removeNodeTitleHeight=e=>Math.max(0,e-(Q.NODE_TITLE_HEIGHT||0)),H=function(e){return e.Canvas=`canvas`,e.Vue=`vue`,e.DOM=`dom`,e.External=`external`,e}({}),Te={DEFAULT_BOUNDS:{x:-1e4,y:-1e4,width:2e4,height:2e4},MAX_DEPTH:6,MAX_ITEMS_PER_NODE:4},Ee={CHANGE_DETECTION_INTERVAL:16,SPATIAL_CACHE_TTL:1e3,SPATIAL_CACHE_MAX_SIZE:100,BATCH_UPDATE_DELAY:4},De={USER_PREFIX:`user-`,ID_LENGTH:9,DEFAULT_SOURCE:H.External};function toPoint(e,t){return{x:e,y:t}}function isPointEqual(e,t){return e.x===t.x&&e.y===t.y}function isBoundsEqual(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function isSizeEqual(e,t){return e.width===t.width&&e.height===t.height}function pointInBounds(e,t){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}function boundsIntersect(e,t){return!(e.x+e.width<t.x||t.x+t.width<e.x||e.y+e.height<t.y||t.y+t.height<e.y)}function makeLinkSegmentKey(e,t){return`${e}:${t??`final`}`}var Oe={id:`unknown-node`,position:{x:0,y:0},size:{width:100,height:50},zIndex:0,visible:!0,bounds:{x:0,y:0,width:100,height:50}};function layoutToYNode(e){let t=new de;return t.set(`id`,e.id),t.set(`position`,e.position),t.set(`size`,e.size),t.set(`zIndex`,e.zIndex),t.set(`visible`,e.visible),t.set(`bounds`,e.boun
2ds),t}function getOr(e,t,n){return e.get(t)??n}function yNodeToLayout(e){return{id:getOr(e,`id`,Oe.id),position:getOr(e,`position`,Oe.position),size:getOr(e,`size`,Oe.size),zIndex:getOr(e,`zIndex`,Oe.zIndex),visible:getOr(e,`visible`,Oe.visible),bounds:getOr(e,`bounds`,Oe.bounds)}}var ke=class QuadNode{bounds;depth;maxDepth;maxItems;items=[];children=null;divided=!1;constructor(e,t=0,n=5,r=4){this.bounds=e,this.depth=t,this.maxDepth=n,this.maxItems=r}insert(e){if(!this.contains(e.bounds))return!1;if(this.items.length<this.maxItems&&!this.divided)return this.items.push(e),!0;if(!this.divided&&this.depth<this.maxDepth&&this.subdivide(),this.divided&&this.children){for(let t of this.children)if(t.insert(e))return!0}return this.items.push(e),!0}remove(e){let t=this.items.findIndex(t=>t.id===e.id);if(t!==-1)return this.items.splice(t,1),!0;if(this.divided&&this.children){for(let t of this.children)if(t.remove(e))return!0}return!1}query(e,t=[]){if(!this.intersects(e))return t;for(let n of this.items)this.boundsIntersect(n.bounds,e)&&t.push(n);if(this.divided&&this.children)for(let n of this.children)n.query(e,t);return t}subdivide(){let{x:e,y:t,width:n,height:r}=this.bounds,i=n/2,a=r/2;this.children=[new QuadNode({x:e,y:t,width:i,height:a},this.depth+1,this.maxDepth,this.maxItems),new QuadNode({x:e+i,y:t,width:i,height:a},this.depth+1,this.maxDepth,this.maxItems),new QuadNode({x:e,y:t+a,width:i,height:a},this.depth+1,this.maxDepth,this.maxItems),new QuadNode({x:e+i,y:t+a,width:i,height:a},this.depth+1,this.maxDepth,this.maxItems)],this.divided=!0;let o=[...this.items];this.items=[];for(let e of o){let t=!1;for(let n of this.children)if(n.insert(e)){t=!0;break}t||this.items.push(e)}}contains(e){return e.x>=this.bounds.x&&e.y>=this.bounds.y&&e.x+e.width<=this.bounds.x+this.bounds.width&&e.y+e.height<=this.bounds.y+this.bounds.height}intersects(e){return this.boundsIntersect(this.bounds,e)}boundsIntersect(e,t){return!(e.x+e.width<t.x||t.x+t.width<e.x||e.y+e.height<t.y||t.y+t.height<e.y)}getDebugInfo(){return{bounds:this.bounds,depth:this.depth,itemCount:this.items.length,divided:this.divided,children:this.children?.map(e=>e.getDebugInfo())}}},QuadTree=class{root;itemMap=new Map;options;constructor(e,t={}){this.options={maxDepth:t.maxDepth??5,maxItemsPerNode:t.maxItemsPerNode??4,minNodeSize:t.minNodeSize??50},this.root=new ke(e,0,this.options.maxDepth,this.options.maxItemsPerNode)}insert(e,t,n){let r={id:e,bounds:t,data:n};this.itemMap.has(e)&&this.remove(e);let i=this.root.insert(r);return i&&this.itemMap.set(e,r),i}remove(e){let t=this.itemMap.get(e);if(!t)return!1;let n=this.root.remove(t);return n&&this.itemMap.delete(e),n}update(e,t){let n=this.itemMap.get(e);if(!n)return!1;let r=n.data;return this.remove(e),this.insert(e,t,r)}query(e){return this.root.query(e).map(e=>e.data)}clear(){this.root=new ke(this.root.bounds,0,this.options.maxDepth,this.options.maxItemsPerNode),this.itemMap.clear()}get size(){return this.itemMap.size}getDebugInfo(){return{size:this.size,tree:this.root.getDebugInfo()}}},SpatialIndexManager=class{quadTree;queryCache;cacheSize=0;constructor(e){this.quadTree=new QuadTree(e??Te.DEFAULT_BOUNDS,{maxDepth:Te.MAX_DEPTH,maxItemsPerNode:Te.MAX_ITEMS_PER_NODE}),this.queryCache=new Map}insert(e,t){this.quadTree.insert(e,t,e),this.invalidateCache()}update(e,t){this.quadTree.update(e,t),this.invalidateCache()}batchUpdate(e){for(let{nodeId:t,bounds:n}of e)this.quadTree.update(t,n);this.invalidateCache()}remove(e){this.quadTree.remove(e),this.invalidateCache()}query(e){let t=this.getCacheKey(e),n=this.queryCache.get(t);if(n){if(Date.now()-n.timestamp<Ee.SPATIAL_CACHE_TTL)return n.result;this.queryCache.delete(t),this.cacheSize--}let r=this.quadTree.query(e);return this.addToCache(t,r),r}clear(){this.quadTree.clear(),this.invalidateCache()}get size(){return this.quadTree.size}getDebugInfo(){return{quadTreeInfo:this.quadTree.getDebugInfo(),cacheSize:this.cacheSize,cacheEntries:this.queryCache.size}}getCacheKey(e){return`${e.x},${e.y},${e.width},${e.height}`}addToCache(e,t){if(this.cacheSize>=Ee.SPATIAL_CACHE_MAX_SIZE){let e=this.findOldestCacheEntry();e&&(this.queryCache.delete(e),this.cacheSize--)}this.queryCache.set(e,{result:t,timestamp:Date.now()}),this.cacheSize++}findOldestCacheEntry(){let e=null,t=1/0;
2for(let[n,r]of this.queryCache)r.timestamp<t&&(t=r.timestamp,e=n);return e}invalidateCache(){this.queryCache.clear(),this.cacheSize=0}},Ae=e(f(),1),je=Ae.default.getLogger(`LayoutStore`);function asRerouteId(e){return Number(e)}function asLinkId(e){return Number(e)}var U=new class LayoutStoreImpl{static REROUTE_DEFAULTS={id:0,position:{x:0,y:0},parentId:0,linkIds:[]};ydoc=new pe;ynodes;ylinks;yreroutes;yoperations;version=0;currentSource=De.DEFAULT_SOURCE;currentActor=`${De.USER_PREFIX}${Math.random().toString(36).substring(2,2+De.ID_LENGTH)}`;changeListeners=new Set;nodeChangeListeners=new Map;pendingGlobalChanges=[];isGlobalDispatchQueued=!1;nodeRefs=new Map;nodeTriggers=new Map;linkLayouts=new Map;linkSegmentLayouts=new Map;slotLayouts=new Map;rerouteLayouts=new Map;spatialIndex;linkSegmentSpatialIndex;slotSpatialIndex;rerouteSpatialIndex;isDraggingVueNodes=r(!1);isResizingVueNodes=r(!1);_pendingSlotSync=!1;get pendingSlotSync(){return this._pendingSlotSync}get hasSlotLayouts(){return this.slotLayouts.size>0}setPendingSlotSync(e){this._pendingSlotSync=e}constructor(){this.ynodes=this.ydoc.getMap(`nodes`),this.ylinks=this.ydoc.getMap(`links`),this.yreroutes=this.ydoc.getMap(`reroutes`),this.yoperations=this.ydoc.getArray(`operations`),this.spatialIndex=new SpatialIndexManager,this.linkSegmentSpatialIndex=new SpatialIndexManager,this.slotSpatialIndex=new SpatialIndexManager,this.rerouteSpatialIndex=new SpatialIndexManager,this.ynodes.observe(e=>{this.version++,e.changes.keys.forEach((e,t)=>{let n=this.nodeTriggers.get(t);n&&n()})}),this.ylinks.observe(e=>{this.version++,e.changes.keys.forEach((e,t)=>{this.handleLinkChange(e,t)})}),this.yreroutes.observe(e=>{this.version++,e.changes.keys.forEach((e,t)=>{this.handleRerouteChange(e,t)})})}getLinkField(e,t){return e.get(t)}getRerouteField(e,t,n=LayoutStoreImpl.REROUTE_DEFAULTS[t]){return e.get(t)??n}getNodeLayoutRef(e){let t=this.nodeRefs.get(e);return t||(t=s((t,n)=>(this.nodeTriggers.set(e,n),{get:()=>{t();let n=this.ynodes.get(e);return n?yNodeToLayout(n):null},set:t=>{if(t===null){let t=this.ynodes.get(e);t&&this.applyOperation({type:`deleteNode`,entity:`node`,nodeId:e,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor,previousLayout:yNodeToLayout(t)})}else{let n=this.ynodes.get(e);if(!n)this.applyOperation({type:`createNode`,entity:`node`,nodeId:e,layout:t,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor});else{let r=yNodeToLayout(n);(r.position.x!==t.position.x||r.position.y!==t.position.y)&&this.applyOperation({type:`moveNode`,entity:`node`,nodeId:e,position:t.position,previousPosition:r.position,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor}),(r.size.width!==t.size.width||r.size.height!==t.size.height)&&this.applyOperation({type:`resizeNode`,entity:`node`,nodeId:e,size:t.size,previousSize:r.size,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor}),r.zIndex!==t.zIndex&&this.applyOperation({type:`setNodeZIndex`,entity:`node`,nodeId:e,zIndex:t.zIndex,previousZIndex:r.zIndex,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor})}}n()}})),this.nodeRefs.set(e,t)),t}getNodesInBounds(e){return l(()=>{this.version;let t=[];for(let[n]of this.ynodes){let r=this.ynodes.get(n);if(r){let i=yNodeToLayout(r);i&&boundsIntersect(i.bounds,e)&&t.push(n)}}return t})}getAllNodes(){return l(()=>{this.version;let e=new Map;for(let[t]of this.ynodes){let n=this.ynodes.get(t);if(n){let r=yNodeToLayout(n);r&&e.set(t,r)}}return e})}getVersion(){return l(()=>this.version)}queryNodeAtPoint(e){let t=[];for(let[e]of this.ynodes){let n=this.ynodes.get(e);if(n){let r=yNodeToLayout(n);r&&t.push([e,r])}}t.sort(([,e],[,t])=>t.zIndex-e.zIndex);for(let[n,r]of t)if(pointInBounds(e,r.bounds))return n;return null}queryNodesInBounds(e){return this.spatialIndex.query(e)}updateLinkLayout(e,t){let n=this.linkLayouts.get(e);if(n&&isBoundsEqual(n.bounds,t.bounds)&&isPointEqual(n.centerPos,t.centerPos)){t.path&&(n.path=t.path);return}this.linkLayouts.set(e,t)}deleteLinkLayout(e){if(this.linkLayouts.delete(e)){let t=[];for(let[n]of this.linkSegmentLayouts)n.startsWith(`${e}:`)&&t.push(n);for(let e of t)this.linkSegmentLayouts.delete(e),this.linkSegmentSpatialIndex.remove(e)}}updateSlotLayout(e,t){let n=this.slotLayouts.get(e);if(n){if(isPointEqual(n.position,t.position)&&isBoundsEqual(n.bounds,t.bounds))return;this.slotSpatialIndex.update(e,t.bounds)}else this.slotSpatialIndex.insert(e,t.bounds);this.slotLayouts.set(e,t)}batchUpdateSlotLayouts(e){if(e.length)for(let{key:t,layout:n}of e){let e=this.slotLayouts.get(t);if(e){if(isPointEqual(e.position,n.position)&&isBoundsEqual(e.bounds,n.bounds))continue;this.slotSpatialIndex.update(t,n.bounds)}else this.slotSpatialIndex.insert(t,n.bounds);this.slotLayouts.set(t,n)}}deleteSlotLayout(e){this.slotLayouts.delete(e)&&this.slotSpatialIndex.remove(e)}clearAllSlotLayouts(){this.slotLayouts.clear(),this.slotSpatialIndex.clear()}updateRerouteLayout(e,t){let n=this.rerouteLayouts.get(e);n||je.debug(`Adding reroute layout:`,{rerouteId:e,position:t.position,bounds:t.bounds}),n?this.rerouteSpatialIndex.update(String(e),t.bounds):this.rerouteSpatialIndex.insert(String(e),t.bounds),this.rerouteLayouts.set(e,t)}deleteRerouteLayout(e){this.rerouteLayouts.delete(e)&&this.rerouteSpatialIndex.remove(String(e))}getLinkLayout(e){return this.linkLayouts.get(e)||null}getSlotLayout(e){return this.slotLayouts.get(e)||null}getRerouteLayout(e){return this.rerouteLayouts.get(e)||null}getAllSlotKeys(){return Array.from(this.slotLayouts.keys())}updateLinkSegmentLayout(e,t,n){let r=makeLinkSegmentKey(e,t),i=this.linkSegmentLayouts.get(r);if(i&&isBoundsEqual(i.bounds,n.bounds)&&isPointEqual(i.centerPos,n.centerPos)){n.path&&(i.path=n.path);return}let a={...n,linkId:e,rerouteId:t};
2i||je.debug(`Adding link segment:`,{linkId:e,rerouteId:t,bounds:n.bounds,hasPath:!!n.path}),i?this.linkSegmentSpatialIndex.update(r,n.bounds):this.linkSegmentSpatialIndex.insert(r,n.bounds),this.linkSegmentLayouts.set(r,a)}deleteLinkSegmentLayout(e,t){let n=makeLinkSegmentKey(e,t);this.linkSegmentLayouts.delete(n)&&this.linkSegmentSpatialIndex.remove(n)}queryLinkSegmentAtPoint(e,t){let n=t?.lineWidth??10,r=Math.max(10,n),i={x:e.x-r,y:e.y-r,width:r*2,height:r*2},a=this.linkSegmentSpatialIndex.query(i);a.length>0&&je.debug(`Checking link segments at point:`,{point:e,candidateCount:a.length,tolerance:n});for(let n of a){let r=this.linkSegmentLayouts.get(n);if(r){if(t&&r.path){let n=typeof window<`u`&&window?.devicePixelRatio||1;if(t.isPointInStroke(r.path,e.x*n,e.y*n))return je.debug(`Link segment hit:`,{linkId:r.linkId,rerouteId:r.rerouteId,point:e}),{linkId:r.linkId,rerouteId:r.rerouteId}}else if(pointInBounds(e,r.bounds))return{linkId:r.linkId,rerouteId:r.rerouteId}}}return null}queryLinkAtPoint(e,t){let n=this.queryLinkSegmentAtPoint(e,t);return n?n.linkId:null}querySlotAtPoint(e){let t={x:e.x-10,y:e.y-10,width:20,height:20},n=this.slotSpatialIndex.query(t);for(let t of n){let n=this.slotLayouts.get(t);if(n&&pointInBounds(e,n.bounds))return n}return null}queryRerouteAtPoint(e){let t={x:e.x-20,y:e.y-20,width:40,height:40},n=this.rerouteSpatialIndex.query(t);n.length>0&&je.debug(`Checking reroutes at point:`,{point:e,candidateCount:n.length});for(let t of n){let n=asRerouteId(t),r=this.rerouteLayouts.get(n);if(r){let t=e.x-r.position.x,n=e.y-r.position.y,i=Math.sqrt(t*t+n*n);if(i<=r.radius)return je.debug(`Reroute hit:`,{rerouteId:r.id,position:r.position,distance:i}),r}}return null}queryItemsInBounds(e){let t=this.linkSegmentSpatialIndex.query(e),n=new Set;for(let e of t){let t=this.linkSegmentLayouts.get(e);t&&n.add(t.linkId)}return{nodes:this.queryNodesInBounds(e),links:Array.from(n),slots:this.slotSpatialIndex.query(e),reroutes:this.rerouteSpatialIndex.query(e).map(e=>asRerouteId(e))}}applyOperation(e){let t={type:`update`,nodeIds:[],timestamp:e.timestamp,source:e.source,operation:e};this.ydoc.transact(()=>{this.yoperations.push([e]),this.applyOperationInTransaction(e,t)},this.currentActor),this.finalizeOperation(t)}applyOperationInTransaction(e,t){switch(e.type){case`moveNode`:this.handleMoveNode(e,t);break;case`resizeNode`:this.handleResizeNode(e,t);break;case`setNodeZIndex`:this.handleSetNodeZIndex(e,t);break;case`createNode`:this.handleCreateNode(e,t);break;case`deleteNode`:this.handleDeleteNode(e,t);break;case`batchUpdateBounds`:this.handleBatchUpdateBounds(e,t);break;case`createLink`:this.handleCreateLink(e,t);break;case`deleteLink`:this.handleDeleteLink(e,t);break;case`createReroute`:this.handleCreateReroute(e,t);break;case`deleteReroute`:this.handleDeleteReroute(e,t);break;case`moveReroute`:this.handleMoveReroute(e,t);break}}finalizeOperation(e){this.version++,e.nodeIds.forEach(e=>{let t=this.nodeTriggers.get(e);t&&t()}),this.notifyNodeChange(e),this.queueGlobalChange(e)}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}onNodeChange(e,t){let n=this.nodeChangeListeners.get(e)??new Set;return n.add(t),this.nodeChangeListeners.set(e,n),()=>{let n=this.nodeChangeListeners.get(e);n&&(n.delete(t),n.size===0&&this.nodeChangeListeners.delete(e))}}setSource(e){this.currentSource=e}setActor(e){this.currentActor=e}getCurrentSource(){return this.currentSource}getCurrentActor(){return this.currentActor}cleanupNodeRef(e){this.nodeRefs.delete(e),this.nodeTriggers.delete(e)}initializeFromLiteGraph(e){this.ydoc.transact(()=>{this.ynodes.clear(),this.nodeChangeListeners.clear(),this.spatialIndex.clear(),this.linkSegmentSpatialIndex.clear(),this.slotSpatialIndex.clear(),this.rerouteSpatialIndex.clear(),this.linkLayouts.clear(),this.linkSegmentLayouts.clear(),this.slotLayouts.clear(),this.rerouteLayouts.clear(),this.pendingGlobalChanges=[],this.isGlobalDispatchQueued=!1,e.forEach((e,t)=>{let n={id:e.id.toString(),position:{x:e.pos[0],y:e.pos[1]},size:{width:e.size[0],height:e.size[1]},zIndex:t,visible:!0,bounds:{x:e.pos[0],y:e.pos[1],width:e.size[0],height:e.size[1]}};this.ynodes.set(n.id,layoutToYNode(n)),this.spatialIndex.insert(n.id,n.bounds)}
2),this.nodeTriggers.forEach(e=>e())},`initialization`)}handleMoveNode(e,t){let n=this.ynodes.get(e.nodeId);if(!n)return;let r=yNodeToLayout(n).size,i={x:e.position.x,y:e.position.y,width:r.width,height:r.height};this.spatialIndex.update(e.nodeId,i),n.set(`position`,e.position),this.updateNodeBounds(n,e.position,r),t.nodeIds.push(e.nodeId)}handleResizeNode(e,t){let n=this.ynodes.get(e.nodeId);if(!n)return;let r=yNodeToLayout(n).position,i={x:r.x,y:r.y,width:e.size.width,height:e.size.height};this.spatialIndex.update(e.nodeId,i),n.set(`size`,e.size),this.updateNodeBounds(n,r,e.size),t.nodeIds.push(e.nodeId)}handleSetNodeZIndex(e,t){let n=this.ynodes.get(e.nodeId);n&&(n.set(`zIndex`,e.zIndex),t.nodeIds.push(e.nodeId))}handleCreateNode(e,t){let n=layoutToYNode(e.layout);this.ynodes.set(e.nodeId,n),this.spatialIndex.insert(e.nodeId,e.layout.bounds),t.type=`create`,t.nodeIds.push(e.nodeId)}handleDeleteNode(e,t){if(!this.ynodes.has(e.nodeId))return;this.ynodes.delete(e.nodeId),this.spatialIndex.remove(e.nodeId);let n=this.findLinksConnectedToNode(e.nodeId);for(let e of n)this.ylinks.delete(String(e)),this.linkLayouts.delete(e),this.cleanupLinkSegments(e);t.type=`delete`,t.nodeIds.push(e.nodeId)}handleBatchUpdateBounds(e,t){let n=[];for(let r of e.nodeIds){let i=e.bounds[r],a=this.ynodes.get(r);!a||!i||(a.set(`position`,{x:i.bounds.x,y:i.bounds.y}),a.set(`size`,{width:i.bounds.width,height:i.bounds.height}),a.set(`bounds`,i.bounds),n.push({nodeId:r,bounds:i.bounds}),t.nodeIds.push(r))}n.length>0&&this.spatialIndex.batchUpdate(n),t.nodeIds.length&&(t.type=`update`)}handleCreateLink(e,t){let n=new de;n.set(`id`,e.linkId),n.set(`sourceNodeId`,e.sourceNodeId),n.set(`sourceSlot`,e.sourceSlot),n.set(`targetNodeId`,e.targetNodeId),n.set(`targetSlot`,e.targetSlot),this.ylinks.set(String(e.linkId),n),t.type=`create`}handleDeleteLink(e,t){this.ylinks.has(String(e.linkId))&&(this.ylinks.delete(String(e.linkId)),this.linkLayouts.delete(e.linkId),this.cleanupLinkSegments(e.linkId),t.type=`delete`)}handleCreateReroute(e,t){let n=new de;n.set(`id`,e.rerouteId),n.set(`position`,e.position),n.set(`parentId`,e.parentId),n.set(`linkIds`,e.linkIds),this.yreroutes.set(String(e.rerouteId),n),t.type=`create`}handleDeleteReroute(e,t){this.yreroutes.has(String(e.rerouteId))&&(this.yreroutes.delete(String(e.rerouteId)),this.rerouteLayouts.delete(e.rerouteId),this.rerouteSpatialIndex.remove(String(e.rerouteId)),t.type=`delete`)}handleMoveReroute(e,t){let n=this.yreroutes.get(String(e.rerouteId));if(!n)return;n.set(`position`,e.position);let r=e.position,i={id:e.rerouteId,position:r,radius:8,bounds:{x:r.x-8,y:r.y-8,width:16,height:16}};this.updateRerouteLayout(e.rerouteId,i),t.type=`update`}updateNodeBounds(e,t,n){e.set(`bounds`,{x:t.x,y:t.y,width:n.width,height:n.height})}findLinksConnectedToNode(e){let t=[];return this.ylinks.forEach((n,r)=>{let i=asLinkId(r),a=this.getLinkField(n,`sourceNodeId`),o=this.getLinkField(n,`targetNodeId`);(a===e||o===e)&&t.push(i)}),t}handleLinkChange(e,t){if(e.action===`delete`){let e=asLinkId(t);this.cleanupLinkData(e)}}cleanupLinkData(e){this.linkLayouts.delete(e),this.cleanupLinkSegments(e)}cleanupLinkSegments(e){let t=[];for(let[n]of this.linkSegmentLayouts)n.startsWith(`${e}:`)&&t.push(n);for(let e of t)this.linkSegmentLayouts.delete(e),this.linkSegmentSpatialIndex.remove(e)}handleRerouteChange(e,t){let n=asRerouteId(t);e.action===`delete`?this.handleRerouteDelete(n):this.handleRerouteUpsert(n)}handleRerouteDelete(e){this.rerouteLayouts.delete(e),this.rerouteSpatialIndex.remove(String(e))}handleRerouteUpsert(e){let t=this.yreroutes.get(String(e));if(!t)return;let n=this.getRerouteField(t,`position`);if(!n)return;let r=this.createRerouteLayout(e,n);this.updateRerouteLayout(e,r)}createRerouteLayout(e,t){return{id:e,position:t,radius:8,bounds:{x:t.x-8,y:t.y-8,width:16,height:16}}}queueGlobalChange(e){this.changeListeners.size!==0&&(this.pendingGlobalChanges.push(e),!this.isGlobalDispatchQueued&&(this.isGlobalDispatchQueued=!0,queueMicrotask(()=>{this.flushQueuedGlobalChanges()})))}flushQueuedGlobalChanges(){if(this.isGlobalDispatchQueued=!1,this.pendingGlobalChanges.length===0)return;let e=this.pendingGlobalChanges;
2this.pendingGlobalChanges=[],e.forEach(e=>{this.notifyChange(e)})}notifyChange(e){this.changeListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in layout change listener:`,e)}})}notifyNodeChange(e){for(let t of new Set(e.nodeIds)){let n=this.nodeChangeListeners.get(t);n&&n.forEach(t=>{try{t(e)}catch(e){console.error(`Error in node-scoped layout change listener:`,e)}})}}getOperationsSince(e){let t=[];return this.yoperations.forEach(n=>{n&&n.timestamp>e&&t.push(n)}),t}getOperationsByActor(e){let t=[];return this.yoperations.forEach(n=>{n&&n.actor===e&&t.push(n)}),t}getYDoc(){return this.ydoc}applyUpdate(e){fe(this.ydoc,e)}getStateAsUpdate(){return ue(this.ydoc)}batchUpdateNodeBounds(e){if(e.length===0)return;let t=this.currentSource,n=t===H.DOM;this.currentSource=H.Vue;let r=[],i={};for(let{nodeId:t,bounds:a}of e){let e=this.ynodes.get(t);if(!e)continue;let o=yNodeToLayout(e);i[t]={bounds:n?{...a,height:removeNodeTitleHeight(a.height)}:a,previousBounds:o.bounds},r.push(t)}if(!r.length){this.currentSource=t;return}let a={type:`batchUpdateBounds`,entity:`node`,nodeIds:r,bounds:i,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor};this.applyOperation(a),this.currentSource=t}},Me=Ae.default.getLogger(`LayoutMutations`);function useLayoutMutations(){let setSource=e=>{U.setSource(e)},setActor=e=>{U.setActor(e)},moveNode=(e,t)=>{let n=String(e),r=U.getNodeLayoutRef(n).value;r&&U.applyOperation({type:`moveNode`,entity:`node`,nodeId:n,position:t,previousPosition:r.position,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})};function batchMoveNodes(e){if(e.length===0)return;let t=e.flatMap(({nodeId:e,position:t})=>{let n=String(e),r=U.getNodeLayoutRef(n).value;return r?[{nodeId:n,bounds:{x:t.x,y:t.y,width:r.size.width,height:r.size.height}}]:[]});t.length!==0&&U.batchUpdateNodeBounds(t)}let resizeNode=(e,t)=>{let n=String(e),r=U.getNodeLayoutRef(n).value;r&&U.applyOperation({type:`resizeNode`,entity:`node`,nodeId:n,size:t,previousSize:r.size,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},setNodeZIndex=(e,t)=>{let n=String(e),r=U.getNodeLayoutRef(n).value;r&&U.applyOperation({type:`setNodeZIndex`,entity:`node`,nodeId:n,zIndex:t,previousZIndex:r.zIndex,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},createNode=(e,t)=>{let n=String(e),r={id:n,position:t.position??{x:0,y:0},size:t.size??{width:200,height:100},zIndex:t.zIndex??0,visible:t.visible??!0,bounds:{x:t.position?.x??0,y:t.position?.y??0,width:t.size?.width??200,height:t.size?.height??100}};U.applyOperation({type:`createNode`,entity:`node`,nodeId:n,layout:r,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},deleteNode=e=>{let t=String(e),n=U.getNodeLayoutRef(t).value;n&&U.applyOperation({type:`deleteNode`,entity:`node`,nodeId:t,previousLayout:n,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},bringNodeToFront=e=>{let t=U.getAllNodes().value,n=0;for(let[,e]of t)e.zIndex>n&&(n=e.zIndex);setNodeZIndex(e,n+1)},createLink=(e,t,n,r,i)=>{let a=String(t),o=String(r);Me.debug(`Creating link:`,{linkId:e,from:`${a}[${n}]`,to:`${o}[${i}]`}),U.applyOperation({type:`createLink`,entity:`link`,linkId:e,sourceNodeId:a,sourceSlot:n,targetNodeId:o,targetSlot:i,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},deleteLink=e=>{Me.debug(`Deleting link:`,e),U.applyOperation({type:`deleteLink`,entity:`link`,linkId:e,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},createReroute=(e,t,n,r=[])=>{Me.debug(`Creating reroute:`,{rerouteId:e,position:t,parentId:n,linkCount:r.length}),U.applyOperation({type:`createReroute`,entity:`reroute`,rerouteId:e,position:t,parentId:n,linkIds:r,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},deleteReroute=e=>{Me.debug(`Deleting reroute:`,e),U.applyOperation({type:`deleteReroute`,entity:`reroute`,rerouteId:e,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})},moveReroute=(e,t,n)=>{Me.debug(`Moving reroute:`,{rerouteId:e,from:n,to:t}),U.applyOperation({type:`moveReroute`,entity:`reroute`,rerouteId:e,position:t,previousPosition:n,timestamp:Date.now(),source:U.getCurrentSource(),actor:U.getCurrentActor()})};return{setSource,setActor,moveNode,batchMoveNodes,resizeNode,setNodeZIndex,createNode,deleteNode,bringNodeToFront,createLink,deleteLink,createReroute,deleteReroute,moveReroute}}var Ne=[];function makePromotionEntryKey(e){let t=`${e.sourceNodeId}
2:${e.sourceWidgetName}`;return e.disambiguatingSourceNodeId?`${t}:${e.disambiguatingSourceNodeId}`:t}var W=c(`promotion`,()=>{let e=r(new Map),t=r(new Map);function _getPromotionsForGraph(t){let n=e.value.get(t);if(n)return n;let r=new Map;return e.value.set(t,r),r}function _getRefCountsForGraph(e){let n=t.value.get(e);if(n)return n;let r=new Map;return t.value.set(e,r),r}function _incrementKeys(e,t){let n=_getRefCountsForGraph(e);for(let e of t){let t=makePromotionEntryKey(e);n.set(t,(n.get(t)??0)+1)}}function _decrementKeys(e,t){let n=_getRefCountsForGraph(e);for(let e of t){let t=makePromotionEntryKey(e),r=(n.get(t)??1)-1;r<=0?n.delete(t):n.set(t,r)}}function getPromotionsRef(e,t){return _getPromotionsForGraph(e).get(t)??Ne}function getPromotions(e,t){return[...getPromotionsRef(e,t)]}function isPromoted(e,t,n){return getPromotionsRef(e,t).some(e=>e.sourceNodeId===n.sourceNodeId&&e.sourceWidgetName===n.sourceWidgetName&&e.disambiguatingSourceNodeId===n.disambiguatingSourceNodeId)}function isPromotedByAny(e,t){return(_getRefCountsForGraph(e).get(makePromotionEntryKey(t))??0)>0}function setPromotions(e,t,n){let r=_getPromotionsForGraph(e);_decrementKeys(e,r.get(t)??[]),_incrementKeys(e,n),n.length===0?r.delete(t):r.set(t,[...n])}function promote(e,t,n){if(isPromoted(e,t,n))return;let r=getPromotionsRef(e,t),i={sourceNodeId:n.sourceNodeId,sourceWidgetName:n.sourceWidgetName};n.disambiguatingSourceNodeId&&(i.disambiguatingSourceNodeId=n.disambiguatingSourceNodeId),setPromotions(e,t,[...r,i])}function demote(e,t,n){setPromotions(e,t,getPromotionsRef(e,t).filter(e=>!(e.sourceNodeId===n.sourceNodeId&&e.sourceWidgetName===n.sourceWidgetName&&e.disambiguatingSourceNodeId===n.disambiguatingSourceNodeId)))}function movePromotion(e,t,n,r){let i=_getPromotionsForGraph(e),a=i.get(t);if(!a?.length)return;let o=[...a];if(n<0||n>=o.length||r<0||r>=o.length||n===r)return;let[s]=o.splice(n,1);o.splice(r,0,s),i.set(t,o)}function clearGraph(n){e.value.delete(n),t.value.delete(n)}return{getPromotionsRef,getPromotions,isPromoted,isPromotedByAny,setPromotions,promote,demote,movePromotion,clearGraph}});function stripGraphPrefix(e){return String(e).replace(/^(.*:)+/,``)}var Pe=c(`widgetValue`,()=>{let e=r(new Map);function getWidgetStateMap(t){let n=e.value.get(t);if(n)return n;let r=o(new Map);return e.value.set(t,r),r}function makeKey(e,t){return`${e}:${t}`}function registerWidget(e,t){let n=getWidgetStateMap(e),r=makeKey(t.nodeId,t.name);return n.set(r,t),n.get(r)}function getNodeWidgets(e,t){let n=getWidgetStateMap(e),r=`${t}:`;return[...n].filter(([e])=>e.startsWith(r)).map(([,e])=>e)}function getWidget(e,t,n){return getWidgetStateMap(e).get(makeKey(t,n))}function clearGraph(t){e.value.delete(t)}return{registerWidget,getWidget,getNodeWidgets,clearGraph}});function isNodeLocatorId(e){if(typeof e!=`string`)return!1;let t=e.split(`:`);return t.length===1?e.length>0:t.length!==2||!t[1]?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t[0])}function isNodeExecutionId(e){return typeof e==`string`?e.includes(`:`):!1}function parseNodeLocatorId(e){if(!isNodeLocatorId(e))return null;let t=e.split(`:`);if(t.length===1)return{subgraphUuid:null,localNodeId:isNaN(Number(e))?e:Number(e)};let[n,r]=t;return{subgraphUuid:n,localNodeId:isNaN(Number(r))?r:Number(r)}}function createNodeLocatorId(e,t){return`${e}:${t}`}function parseNodeExecutionId(e){return isNodeExecutionId(e)?e.split(`:`).map(e=>isNaN(Number(e))?e:Number(e)):null}function createNodeExecutionId(e){return e.join(`:`)}function getAncestorExecutionIds(e){let t=e.split(`:`);return Array.from({length:t.length},(e,n)=>t.slice(0,n+1).join(`:`))}function getParentExecutionIds(e){return getAncestorExecutionIds(e).slice(0,-1)}function compareExecutionId(e,t){let parse=e=>(e??``).split(`:`).map(Number),n=parse(e),r=parse(t);for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0,a=(Number.isNaN(t)?0:t)-(Number.isNaN(i)?0:i);if(a!==0)return a}return 0}var isAbortError=e=>e instanceof DOMException&&e.name===`AbortError`,isSubgraph=e=>e?.isRootGraph===!1,isNonNullish=e=>e!=null,isSubgraphIoNode=e=>{let t=e.constructor?.comfyClass;return t===`SubgraphInputNode`||t===`SubgraphOutputNode`},isSlotObject=e=>typeof e==`object`&&!!e&&`name`in e&&`type`in e&&`boundingRect`in e,isResultItemType=e=>e===`input`||e===`output`||e===`temp`;
2function getLocatorIdFromNodeData(e){return e.subgraphId?`${e.subgraphId}:${String(e.id)}`:String(e.id)}function parseExecutionId(e){return!e||typeof e!=`string`?null:e.split(`:`).filter(e=>e.length>0)}function getLocalNodeIdFromExecutionId(e){let t=parseExecutionId(e);return t?t[t.length-1]:null}function getSubgraphPathFromExecutionId(e){let t=parseExecutionId(e);return t?t.slice(0,-1):[]}function visitGraphNodes(e,t){for(let n of e.nodes)t(n)}function traverseSubgraphPath(e,t){let n=e;for(let e of t){let t=n.getNodeById(e);if(!t?.isSubgraphNode?.()||!t.subgraph)return null;n=t.subgraph}return n}function triggerCallbackOnAllNodes(e,t){forEachNode(e,e=>{let n=e[t];typeof n==`function`&&n.call(e)})}function mapAllNodes(e,t){let n=[];return visitGraphNodes(e,e=>{e.isSubgraphNode?.()&&e.subgraph&&n.push(...mapAllNodes(e.subgraph,t));let r=t(e);r!==void 0&&n.push(r)}),n}function forEachNode(e,t){visitGraphNodes(e,e=>{e.isSubgraphNode?.()&&e.subgraph&&forEachNode(e.subgraph,t),t(e)})}function collectAllNodes(e,t){return mapAllNodes(e,e=>{if(!t||t(e))return e})}function findSubgraphByUuid(e,t){if(`subgraphs`in e&&e.subgraphs instanceof Map)return e.subgraphs.get(t)??null;for(let n of e.nodes)if(n.isSubgraphNode?.()&&n.subgraph){if(n.subgraph.id===t)return n.subgraph;let e=findSubgraphByUuid(n.subgraph,t);if(e)return e}return null}function findSubgraphPathById(e,t){let n=[{graph:e,path:[]}];for(;n.length>0;){let{graph:e,path:r}=n.pop();if(!(!e||!e._nodes||!Array.isArray(e._nodes))){for(let i of e._nodes)if(i.isSubgraphNode?.()&&i.subgraph){let e=[...r,String(i.subgraph.id)];if(i.subgraph.id===t)return e;n.push({graph:i.subgraph,path:e})}}}return null}function getRootParentNode(e,t){let n=parseExecutionId(t);if(!n||n.length<2)return null;let r=n[0];return e&&e.getNodeById(Number(r))||null}function getNodeByExecutionId(e,t){if(!e)return null;let n=getLocalNodeIdFromExecutionId(t);if(!n)return null;let r=getSubgraphPathFromExecutionId(t);if(r.length===0)return e.getNodeById(n)||null;let i=traverseSubgraphPath(e,r);return i&&i.getNodeById(n)||null}function getExecutionIdByNode(e,t){if(!t.graph)return null;if(t.graph===e||t.graph.isRootGraph)return String(t.id);let n=findPartialExecutionPathToGraph(t.graph,e);return n===void 0?null:`${n}:${t.id}`}function isAncestorPathActive(e,t){if(!e)return!0;for(let n of getParentExecutionIds(t)){let t=getNodeByExecutionId(e,n);if(t&&(t.mode===B.NEVER||t.mode===B.BYPASS))return!1}return!0}function isMissingCandidateActive(e,t){return t.isMissing===!0?t.nodeId==null?!0:isAncestorPathActive(e,String(t.nodeId)):!1}function getExecutionIdForNodeInGraph(e,t,n){if(t===e||t.isRootGraph)return String(n);let r=findPartialExecutionPathToGraph(t,e);return r===void 0?String(n):`${r}:${n}`}function getExecutionIdFromNodeData(e,t){let n=getNodeByLocatorId(e,getLocatorIdFromNodeData(t));return n?getExecutionIdByNode(e,n)??String(t.id):String(t.id)}function getNodeByLocatorId(e,t){if(!e)return null;let n=parseNodeLocatorId(t);if(!n)return null;let{subgraphUuid:r,localNodeId:i}=n;if(!r)return e.getNodeById(i)||null;let a=findSubgraphByUuid(e,r);return a&&a.getNodeById(i)||null}function executionIdToNodeLocatorId(e,t){let n=String(t);if(!n.includes(`:`))return n;let r=n.split(`:`),i=r.at(-1),a=traverseSubgraphPath(e,r.slice(0,-1));if(a)return createNodeLocatorId(a.id,i)}function forEachSubgraphNode(e,t,n){!e||!t||forEachNode(e,e=>{e.type===t&&n(e)})}function getAllNonIoNodesInSubgraph(e){return e.nodes.filter(e=>!isSubgraphIoNode(e))}function traverseNodesDepthFirst(e,t){let{visitor=()=>void 0,initialContext:n=void 0,expandSubgraphs:r=!0}=t||{},i=[];for(let t of e)i.push({node:t,context:n});for(;i.length>0;){let{node:e,context:t}=i.pop(),n=visitor(e,t);if(r&&e.isSubgraphNode?.()&&e.subgraph){let t=e.subgraph.nodes;for(let e=t.length-1;e>=0;e--)i.push({node:t[e],context:n})}}}function reduceAllNodes(e,t,n){let r=n;return forEachNode(e,e=>{r=t(r,e)}),r}function collectFromNodes(e,t){let{collector=e=>e,contextBuilder=()=>void 0,initialContext:n=void 0,expandSubgraphs:r=!0}=t||{},i=[];return traverseNodesDepthFirst(e,{visitor:(e,t)=>
2{let n=collector(e,t);return n!==null&&i.push(n),contextBuilder(e,t)},initialContext:n,expandSubgraphs:r}),i}function getExecutionIdsForSelectedNodes(e,t=e[0]?.graph){if(!t)return[];let n=t.rootGraph,r=t.isRootGraph?``:findPartialExecutionPathToGraph(t,n);if(r===void 0)return[];let buildExecId=(e,t)=>{let n=String(e.id);return t?`${t}:${n}`:n};return collectFromNodes(e,{collector:buildExecId,contextBuilder:buildExecId,initialContext:r,expandSubgraphs:!0})}function getActiveGraphNodeIds(e,t,n){let r=new Set;for(let i of n){let n=getNodeByExecutionId(e,i);n?.graph===t&&r.add(String(n.id))}return r}function findPartialExecutionPathToGraph(e,t){for(let n of t.nodes){if(!n.isSubgraphNode())continue;if(n.subgraph===e)return`${n.id}`;let t=findPartialExecutionPathToGraph(e,n.subgraph);if(t!==void 0)return n.id+`:`+t}}function linkTupleKey(e){return`${e.origin_id}\0${e.origin_slot}\0${e.target_id}\0${e.target_slot}`}function groupLinksByTuple(e){let t=new Map;for(let[n,r]of e){let e=linkTupleKey(r);t.has(e)||t.set(e,[]),t.get(e).push(n)}return t}function selectSurvivorLink(e,t){if(!t)return e[0];for(let n of t.inputs??[]){if(!n)continue;let t=e.find(e=>n.link===e);if(t!=null)return t}return e[0]}function purgeOrphanedLinks(e,t,n,r){for(let i of e){if(i===t)continue;let e=n.get(i);if(!e)continue;let a=r(e.origin_id)?.outputs?.[e.origin_slot];if(a?.links)for(let e=a.links.length-1;e>=0;e--)a.links[e]===i&&a.links.splice(e,1);n.delete(i)}}function repairInputLinks(e,t,n){if(!n)return;let r=new Set(e);for(let e of n.inputs??[])e?.link==null||e.link===t||r.has(e.link)&&(e.link=t)}var MovingLinkBase=class{outputNodeId;outputNode;outputSlot;outputIndex;outputPos;inputNodeId;inputNode;inputSlot;inputIndex;inputPos;constructor(e,t,n,r,i=I.CENTER){this.network=e,this.link=t,this.toType=n,this.fromReroute=r,this.dragDirection=i;let{origin_id:a,target_id:o,origin_slot:s,target_slot:c}=t,l=e.getNodeById(a)??void 0;if(!l)throw Error(`Creating MovingRenderLink for link [${t.id}] failed: Output node [${a}] not found.`);let u=l.outputs.at(s);if(!u)throw Error(`Creating MovingRenderLink for link [${t.id}] failed: Output slot [${s}] not found.`);this.outputNodeId=a,this.outputNode=l,this.outputSlot=u,this.outputIndex=s,this.outputPos=l.getOutputPos(s);let d=e.getNodeById(o)??void 0;if(!d)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Input node [${o}] not found.`);let f=d.inputs.at(c);if(!f)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Input slot [${c}] not found.`);this.inputNodeId=o,this.inputNode=d,this.inputSlot=f,this.inputIndex=c,this.inputPos=d.getInputPos(c)}},MovingInputLink=class extends MovingLinkBase{toType=`input`;node;fromSlot;fromPos;fromDirection;fromSlotIndex;disconnectOnDrop;disconnectOrigin;constructor(e,t,n,r=I.CENTER,i){super(e,t,`input`,n,r),this.node=this.outputNode,this.fromSlot=this.outputSlot,this.fromPos=n?.pos??this.outputPos,this.fromDirection=I.NONE,this.fromSlotIndex=this.outputIndex,this.disconnectOnDrop=!0,this.disconnectOrigin=i??this.inputPos}canConnectToInput(e,t){return this.node.canConnectTo(e,t,this.outputSlot)}canConnectToOutput(){return!1}canConnectToReroute(e){return e.origin_id!==this.inputNode.id}connectToInput(e,t,n){if(t===this.inputSlot)return;this.inputNode.disconnectInput(this.inputIndex,!0);let r=this.outputNode.connectSlots(this.outputSlot,e,t,this.fromReroute?.id);return r&&n.dispatch(`input-moved`,this),r}connectToOutput(){throw Error(`MovingInputLink cannot connect to an output.`)}connectToSubgraphInput(){throw Error(`MovingInputLink cannot connect to a subgraph input.`)}connectToSubgraphOutput(e,t){let n=e.connect(this.fromSlot,this.node,this.fromReroute?.id);t?.dispatch(`link-created`,n)}connectToRerouteInput(e,{node:t,input:n,link:r},i,a){let{outputNode:o,outputSlot:s,fromReroute:c}=this;for(let e of a){if(e.id===this.link.parentId)break;e.totalLinks===1&&e.remove()}e.parentId=c?.id,o.connectSlots(s,t,n,r.parentId)&&i.dispatch(`input-moved`,this)}connectToRerouteOutput(){throw Error(`MovingInputLink cannot connect to an output.`)}disconnect(){return this.inputNode.disconnectInput(this.inputIndex,!0)}drawConnectionCircle(e,t){if(!this.disconnectOnDrop)return;let[n,r]=this.disconnectOrigin,i=(n-t[0])**2+(r-t[1])**2;e.save(),e.strokeStyle=Q.WIDGET_OUTLINE_COLOR,e.lineWidth=2,e.beginPath(),e.moveTo(n+35,r),e.arc(n,r,35,0,Math.PI*2),e.stroke(),e.restore(
2),this.disconnectOnDrop=i<35**2}},Fe=50;function calculateEdgePanSpeed(e,t,n,r,i){if(i<=0)return 0;let a=e-t,o=n-e;return a<0?-i/r:o<0?i/r:a<Fe?-i*(1-a/Fe)/r:o<Fe?i*(1-o/Fe)/r:0}var AutoPanController=class{pointerX=0;pointerY=0;canvas;ds;maxPanSpeed;onPan;raf;constructor(e){this.canvas=e.canvas,this.ds=e.ds,this.maxPanSpeed=e.maxPanSpeed,this.onPan=e.onPan,this.raf=ee(()=>this.tick(),{immediate:!1})}updatePointer(e,t){this.pointerX=e,this.pointerY=t}start(){this.raf.resume()}stop(){this.raf.pause()}tick(){let e=this.canvas.getBoundingClientRect(),t=this.ds.scale,n=calculateEdgePanSpeed(this.pointerX,e.left,e.right,t,this.maxPanSpeed),r=calculateEdgePanSpeed(this.pointerY,e.top,e.bottom,t,this.maxPanSpeed);n===0&&r===0||(this.ds.offset[0]-=n,this.ds.offset[1]-=r,this.onPan(n,r))}},CanvasPathRenderer=class{drawLink(e,t,n){let r=new Path2D,i=n.highlightedIds?.has(t.id)??!1,a=this.determineLinkColor(t,n,i);return e.save(),t.disabled&&n.patterns?.disabled?e.strokeStyle=n.patterns.disabled:e.strokeStyle=a,e.lineWidth=n.style.connectionWidth,e.lineJoin=`round`,n.style.borderWidth&&!n.style.lowQuality&&this.drawLinkPath(e,r,t,n,n.style.connectionWidth+n.style.borderWidth,`rgba(0,0,0,0.5)`),this.drawLinkPath(e,r,t,n,n.style.connectionWidth,a),this.calculateCenterPoint(t,n),n.style.showArrows&&this.drawArrows(e,t,n,a),n.style.showCenterMarker&&n.scale&&n.scale>=.6&&n.style.highQuality&&this.drawCenterMarker(e,t,n,a),t.flow&&n.animation&&this.drawFlowAnimation(e,r,t,n),e.restore(),r}determineLinkColor(e,t,n){return n?t.colors.highlighted:e.color?e.color:e.type&&t.colors.byType[e.type]?t.colors.byType[e.type]:t.colors.default}drawLinkPath(e,t,n,r,i,a){e.strokeStyle=a,e.lineWidth=i;let o=n.startPoint,s=n.endPoint;r.style.mode===`linear`?this.buildLinearPath(t,o,s,n.startDirection,n.endDirection):r.style.mode===`straight`?this.buildStraightPath(t,o,s,n.startDirection,n.endDirection):this.buildSplinePath(t,o,s,n.startDirection,n.endDirection,n.controlPoints),e.stroke(t)}buildLinearPath(e,t,n,r,i){let a={x:t.x,y:t.y},o={x:n.x,y:n.y};switch(r){case`left`:a.x-=15;break;case`right`:a.x+=15;break;case`up`:a.y-=15;break;case`down`:a.y+=15;break;case`none`:break}switch(i){case`left`:o.x-=15;break;case`right`:o.x+=15;break;case`up`:o.y-=15;break;case`down`:o.y+=15;break;case`none`:break}e.moveTo(t.x,t.y),e.lineTo(a.x,a.y),e.lineTo(o.x,o.y),e.lineTo(n.x,n.y)}buildStraightPath(e,t,n,r,i){let a={x:t.x,y:t.y},o={x:n.x,y:n.y};switch(r){case`left`:a.x-=10;break;case`right`:a.x+=10;break;case`up`:a.y-=10;break;case`down`:a.y+=10;break;case`none`:break}switch(i){case`left`:o.x-=10;break;case`right`:o.x+=10;break;case`up`:o.y-=10;break;case`down`:o.y+=10;break;case`none`:break}let s=(a.x+o.x)*.5;e.moveTo(t.x,t.y),e.lineTo(a.x,a.y),e.lineTo(s,a.y),e.lineTo(s,o.y),e.lineTo(o.x,o.y),e.lineTo(n.x,n.y)}buildSplinePath(e,t,n,r,i,a){e.moveTo(t.x,t.y);let o=a||this.calculateControlPoints(t,n,r,i);o.length>=2?e.bezierCurveTo(o[0].x,o[0].y,o[1].x,o[1].y,n.x,n.y):o.length===1?e.quadraticCurveTo(o[0].x,o[0].y,n.x,n.y):e.lineTo(n.x,n.y)}calculateControlPoints(e,t,n,r){let i=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),a=Math.max(30,i*.25),o=this.getDirectionOffset(n,a),s=this.getDirectionOffset(r,a);return[{x:e.x+o.x,y:e.y+o.y},{x:t.x+s.x,y:t.y+s.y}]}getDirectionOffset(e,t){switch(e){case`left`:return{x:-t,y:0};case`right`:return{x:t,y:0};case`up`:return{x:0,y:-t};case`down`:return{x:0,y:t};default:return{x:0,y:0}}}drawArrows(e,t,n,r){if(n.style.showArrows)for(let i of[.25,.75]){let a=this.computeConnectionPoint(t,i,n),o=this.computeConnectionPoint(t,i+.01,n),s=Math.atan2(o.y-a.y,o.x-a.x),c=e.getTransform();e.translate(a.x,a.y),e.rotate(s),e.fillStyle=r,e.beginPath(),e.moveTo(-5,-3),e.lineTo(0,7),e.lineTo(5,-3),e.fill(),e.setTransform(c)}}computeConnectionPoint(e,t,n){let{startPoint:r,endPoint:i,startDirection:a,endDirection:o}=e,s=Math.sqrt((i.x-r.x)**2+(i.y-r.y)**2),c=.25,l={x:r.x,y:r.y},u={x:i.x,y:i.y};switch(a){case`left`:l.x-=s*c;break;case`right`:l.x+=s*c;break;case`up`:l.y-=s*c;break;case`down`:l.y+=s*c;break;case`none`:break}switch(o){case`left`:u.x-=s*c;break;case`right`:u.x+=s*c;break;case`up`:u.y-=s*c;break;case`down`:u.y+=s*c;break;case`none`:break}let d=(1-t)*(1-t)*(1-t),f=3*((1-t)*(1-t))*t,p=3*(1-t)*(t*t),m=t*t*t;return{x:d*r.x+f*l.x+p*u.x+m*i.x,y:d*r.y+f*l.y+p*u.y+m*i.y}}drawFlowAnimation(e,t,n,r){if(!r.animation)return;let i=r.animation.time,a=this.determineLinkColor(n,r,!1);e.save(),e.fillStyle=a;for(let t=0;t<5;++t){let a=(i+t*.2)%1,o=this.computeConnectionPoint(n,a,r);e.beginPath(),e.arc(o.x,o.y,5,0,2*Math.PI),e.fill()}
2e.restore()}findPointOnBezier(e,t,n,r,i){let a=1-e,o=a*a,s=o*a,c=e*e,l=c*e;return{x:s*t.x+3*o*e*n.x+3*a*c*r.x+l*i.x,y:s*t.y+3*o*e*n.y+3*a*c*r.y+l*i.y}}drawDraggingLink(e,t,n){let r=t.fromInput?{id:`dragging`,startPoint:t.dragPoint,endPoint:t.fixedPoint,startDirection:t.dragDirection||this.getOppositeDirection(t.fixedDirection),endDirection:t.fixedDirection,color:t.color,type:t.type,disabled:t.disabled}:{id:`dragging`,startPoint:t.fixedPoint,endPoint:t.dragPoint,startDirection:t.fixedDirection,endDirection:t.dragDirection||this.getOppositeDirection(t.fixedDirection),color:t.color,type:t.type,disabled:t.disabled};return this.drawLink(e,r,n)}getOppositeDirection(e){switch(e){case`left`:return`right`;case`right`:return`left`;case`up`:return`down`;case`down`:return`up`;default:return`none`}}getLinkCenter(e){return{x:(e.startPoint.x+e.endPoint.x)/2,y:(e.startPoint.y+e.endPoint.y)/2}}calculateCenterPoint(e,t){let{startPoint:n,endPoint:r,controlPoints:i}=e;if(t.style.mode===`spline`&&i&&i.length>=2){let a=this.findPointOnBezier(.5,n,i[0],i[1],r);if(e.centerPos=a,t.style.centerMarkerShape===`arrow`){let t=this.findPointOnBezier(.51,n,i[0],i[1],r);e.centerAngle=Math.atan2(t.y-a.y,t.x-a.x)}}else if(t.style.mode===`linear`){let i={x:n.x,y:n.y},a={x:r.x,y:r.y};switch(e.startDirection){case`left`:i.x-=15;break;case`right`:i.x+=15;break;case`up`:i.y-=15;break;case`down`:i.y+=15;break}switch(e.endDirection){case`left`:a.x-=15;break;case`right`:a.x+=15;break;case`up`:a.y-=15;break;case`down`:a.y+=15;break}e.centerPos={x:(i.x+a.x)*.5,y:(i.y+a.y)*.5},t.style.centerMarkerShape===`arrow`&&(e.centerAngle=Math.atan2(a.y-i.y,a.x-i.x))}else if(t.style.mode===`straight`){let i={x:n.x,y:n.y},a={x:r.x,y:r.y};switch(e.startDirection){case`left`:i.x-=10;break;case`right`:i.x+=10;break;case`up`:i.y-=10;break;case`down`:i.y+=10;break}switch(e.endDirection){case`left`:a.x-=10;break;case`right`:a.x+=10;break;case`up`:a.y-=10;break;case`down`:a.y+=10;break}if(e.centerPos={x:(i.x+a.x)*.5,y:(i.y+a.y)*.5},t.style.centerMarkerShape===`arrow`){let t=a.y-i.y;Math.abs(t)<4?e.centerAngle=0:t>0?e.centerAngle=Math.PI*.5:e.centerAngle=-(Math.PI*.5)}}else e.centerPos=this.getLinkCenter(e),t.style.centerMarkerShape===`arrow`&&(e.centerAngle=Math.atan2(r.y-n.y,r.x-n.x))}drawCenterMarker(e,t,n,r){if(t.centerPos){if(e.beginPath(),n.style.centerMarkerShape===`arrow`&&t.centerAngle!==void 0){let n=e.getTransform();e.translate(t.centerPos.x,t.centerPos.y),e.rotate(t.centerAngle),e.moveTo(-3.2,-5),e.lineTo(7,0),e.lineTo(-3.2,5),e.setTransform(n)}else e.arc(t.centerPos.x,t.centerPos.y,5,0,Math.PI*2);if(t.disabled&&n.patterns?.disabled){let{fillStyle:t,globalAlpha:r}=e;e.fillStyle=n.patterns.disabled,e.globalAlpha=.75,e.fill(),e.globalAlpha=r,e.fillStyle=t}else e.fillStyle=r,e.fill()}}},LitegraphLinkAdapter=class{pathRenderer=new CanvasPathRenderer;constructor(e=!0){this.enableLayoutStoreWrites=e}convertDirection(e){switch(e){case I.LEFT:return`left`;case I.RIGHT:return`right`;case I.UP:return`up`;case I.DOWN:return`down`;case I.CENTER:case I.NONE:return`none`;default:return`right`}}convertToPathRenderContext(e){let t=e.scale>=.6&&e.highQualityRender&&e.renderConnectionArrows,n=e.linkMarkerShape!==R.None;return{style:{mode:this.convertRenderMode(e.renderMode),connectionWidth:e.connectionWidth,borderWidth:e.renderBorder?4:void 0,arrowShape:this.convertArrowShape(e.linkMarkerShape),showArrows:t,lowQuality:e.lowQuality,showCenterMarker:n,centerMarkerShape:e.linkMarkerShape===R.Arrow?`arrow`:`circle`,highQuality:e.highQualityRender},colors:{default:String(e.defaultLinkColor),byType:this.convertColorMap(e.linkTypeColors),highlighted:`#FFF`},patterns:{disabled:e.disabledPattern},animation:{time:Q.getTime()*.001},scale:e.scale,highlightedIds:new Set(Array.from(e.highlightedLinks).map(String))}}convertRenderMode(e){switch(e){case L.LINEAR_LINK:return`linear`;case L.STRAIGHT_LINK:return`straight`;case L.SPLINE_LINK:default:return`spline`}}convertArrowShape(e){switch(e){case R.Circle:return`circle`;case R.Arrow:default:return`triangle`}}convertColorMap(e){let t={};for(let[n,r]of Object.entries(e))t[n]=String(r);return t}applySplineOffset(e,t,n){switch(t){case I.LEFT:e.x-=n;break;case I.RIGHT:e.x+=n;break;case I.UP:e.y-=n;break;case I.DOWN:e.y+=n;break}}renderLinkDirect(e,t,n,r,i,a,o,s,c,l,u={}){let d=s||I.RIGHT,f=c||I.LEFT,p=a===!0||typeof a==`number`&&a>0,m={id:r?String(r.id):`temp`,startPoint:{x:t[0],y:t[1]},endPoint:{x:n[0],y:n[1]},startDirection:this.convertDirection(d),endDirection:this.convertDirection(f),color:o==null?void 0:String(o),type:r?.type===void 0?void 0:String(r.type),flow:p,disabled:u.disabled||!1};if(l.renderMode===L.SPLINE_LINK){let e=!!u.startControl,r=!!u.endControl,i=Math.sqrt((n[0]-t[0])*(n[0]-t[0])+(n[1]-t[1])*(n[1]-t[1])),a=.25,o=[];if(e&&r)o.push({x:t[0]+(u.startControl[0]||0),y:t[1]+(u.startControl[1]||0)},{x:n[0]+(u.endControl[0]||0),y:n[1]+(u.endControl[1]||0)}),m.controlPoints=o;else if(e&&!r){let e={x:t[0]+(u.startControl[0]||0),y:t[1]+(u.startControl[1]||0)},r={x:n[0],y:n[1]};this.applySplineOffset(r,f,i*a),o.push(e,r),m.controlPoints=o}else if(!e&&r){let e={x:t[0],y:t[1]};this.applySplineOffset(e,d,i*a);let r={x:n[0]+(u.endControl[0]||0),y:n[1]+(u.endControl[1]||0)};o.push(e,r),m.controlPoints=o}else{let e={x:t[0],y:t[1]},r={x:n[0],y:n[1]};this.applySplineOffset(e,d,i*a),this.applySplineOffset(r,f,i*a),o.push(e,r),m.controlPoints=o}}let h=this.convertToPathRenderContext(l);
2i&&(h.style.borderWidth=void 0);let g=this.pathRenderer.drawLink(e,m,h),_=u.reroute??r;if(_&&(_.path=g,m.centerPos&&(_._pos=_._pos||[0,0],_._pos[0]=m.centerPos.x,_._pos[1]=m.centerPos.y,m.centerAngle!==void 0&&(_._centreAngle=m.centerAngle)),this.enableLayoutStoreWrites&&r&&r.id!==-1)){let e=this.calculateLinkBounds([m.startPoint.x,m.startPoint.y],[m.endPoint.x,m.endPoint.y],m),t=m.centerPos||{x:(m.startPoint.x+m.endPoint.x)/2,y:(m.startPoint.y+m.endPoint.y)/2};u.reroute||U.updateLinkLayout(r.id,{id:r.id,path:g,bounds:e,centerPos:t,sourceNodeId:String(r.origin_id),targetNodeId:String(r.target_id),sourceSlot:r.origin_slot,targetSlot:r.target_slot});let n=u.reroute?u.reroute.id:null;U.updateLinkSegmentLayout(r.id,n,{path:g,bounds:e,centerPos:t})}}renderDraggingLink(e,t,n,r,i,a,o){this.renderLinkDirect(e,t,n,null,!1,null,r,i,a,{...o,linkMarkerShape:R.None},{disabled:!1})}calculateLinkBounds(e,t,n){let r=Math.min(e[0],t[0]),i=Math.max(e[0],t[0]),a=Math.min(e[1],t[1]),o=Math.max(e[1],t[1]);if(n.controlPoints)for(let e of n.controlPoints)r=Math.min(r,e.x),i=Math.max(i,e.x),a=Math.min(a,e.y),o=Math.max(o,e.y);return{x:r-20,y:a-20,width:i-r+40,height:o-a+40}}};function shallowCloneCommonProps(e){let{color_off:t,color_on:n,dir:r,label:i,localized_name:a,locked:o,name:s,nameLocked:c,removable:l,shape:u,type:d}=e;return{color_off:t,color_on:n,dir:r,label:i,localized_name:a,locked:o,name:s,nameLocked:c,removable:l,shape:u,type:d}}function inputAsSerialisable(e){let{link:t}=e,n=e.widget?{widget:{name:e.widget.name}}:{pos:e.pos};return{...shallowCloneCommonProps(e),...n,link:t}}function outputAsSerialisable(e){let{pos:t,slot_index:n,links:r,widget:i}=e,a=i?{widget:{name:i.name}}:null;return{...shallowCloneCommonProps(e),...a,pos:t,slot_index:n,links:r&&[...r]}}function isINodeInputSlot(e){return`link`in e}function isWidgetInputSlot(e){return!!e.widget}function getSlotKey(e,t,n){if(typeof e==`object`){let{nodeId:t,index:n,isInput:r}=e;return`${t}-${r?`in`:`out`}-${n}`}if(t===void 0||n===void 0)throw Error(`Missing required parameters for slot key generation`);return`${e}-${n?`in`:`out`}-${t}`}function calculateInputSlotPos(e,t){let n=e.inputs[t];return n?calculateInputSlotPosFromSlot(e,n):[e.nodeX,e.nodeY]}function calculateInputSlotPosFromSlot(e,t){let{nodeX:n,nodeY:r,collapsed:i}=e;if(i)return[n,r-Q.NODE_TITLE_HEIGHT*.5];let{pos:a}=t;if(a)return[n+a[0],r+a[1]];let o=Q.NODE_SLOT_HEIGHT*.5,s=e.slotStartY||0,c=(getDefaultVerticalInputs(e).indexOf(t)+.7)*Q.NODE_SLOT_HEIGHT;return[n+o,r+c+s]}function calculateOutputSlotPos(e,t){let{nodeX:n,nodeY:r,nodeWidth:i,collapsed:a,collapsedWidth:o,outputs:s}=e;if(a){let e=o||Q.NODE_COLLAPSED_WIDTH,t=Q.NODE_TITLE_HEIGHT*.5;return[n+e,r-t]}let c=s[t];if(!c)return[n+i,r];let l=c.pos;if(l)return[n+l[0],r+l[1]];let u=Q.NODE_SLOT_HEIGHT*.5,d=e.slotStartY||0,f=(getDefaultVerticalOutputs(e).indexOf(c)+.7)*Q.NODE_SLOT_HEIGHT;return[n+i+1-u,r+f+d]}function getSlotPosition(e,t,n){if(Q.vueNodesMode){let r=getSlotKey(String(e.id),t,n),i=U.getSlotLayout(r);if(i)return[i.position.x,i.position.y];let a=U.getNodeLayoutRef(String(e.id)).value;if(a){let r={nodeX:a.position.x,nodeY:a.position.y,nodeWidth:a.size.width,nodeHeight:a.size.height,collapsed:e.flags.collapsed||!1,collapsedWidth:e._collapsed_width,slotStartY:e.constructor.slot_start_y,inputs:e.inputs,outputs:e.outputs,widgets:e.widgets};return n?calculateInputSlotPos(r,t):calculateOutputSlotPos(r,t)}}let r={nodeX:e.pos[0],nodeY:e.pos[1],nodeWidth:e.size[0],nodeHeight:e.size[1],collapsed:e.flags.collapsed||!1,collapsedWidth:e._collapsed_width,slotStartY:e.constructor.slot_start_y,inputs:e.inputs,outputs:e.outputs,widgets:e.widgets};return n?calculateInputSlotPos(r,t):calculateOutputSlotPos(r,t)}function getDefaultVerticalInputs(e){return e.inputs.filter(t=>!t.pos&&!(e.widgets?.length&&isWidgetInputSlot(t)))}function getDefaultVerticalOutputs(e){return e.outputs.filter(e=>!e.pos)}var Ie=class CanvasPointer{static bufferTime=32;static doubleClickTime=300;static get maxClickDrift(){return this._maxClickDrift}static set maxClickDrift(e){this._maxClickDrift=e,this._maxClickDrift2=e*e}static _maxClickDrift=6;static _maxClickDrift2=this._maxClickDrift**2;static trackpadThreshold=60;static trackpadMaxGap=500;static maxHighResBufferTime=10;element;pointerId;dragStarted=!1;eLastDown;isDouble=!1;isDown=!1;resizeDirection;clearEventsOnReset=!0;eDown;eMove;eUp;detectedDevice=`mouse`;lastWheelEventTime=0;hasReceivedWheelEvent=!1;bufferedLinuxEvent;bufferedLinuxEventTime=0;linuxBufferTimeoutId;get finally(){return this._finally}set finally(e){try{this._finally?.()}finally{this._finally=e}}_finally;constructor(e){this.element=e}down(e){this.reset(),this.eDown=e,this.pointerId=e.pointerId,this.element.setPointerCapture(e.pointerId)}move(e){let{eDown:t}=this;if(t){if(!e.buttons){this.reset();return}if(!(e.buttons&t.buttons)){this._completeClick(e),this.reset();return}this.eMove=e,this.onDrag?.(e),!this.dragStarted&&(e.timeStamp-t.timeStamp>CanvasPointer.bufferTime||!this._hasSamePosition(e,t))&&this._setDragStarted(e)}}up(e){if(e.button!==this.eDown?.button)return!1;this._completeClick(e);let{dragStarted:t}=this;return this.reset(),!t}_completeClick(e){let{eDown:t}=this;t&&(this.eUp=e,this.dragStarted?this.onDragEnd?.(e):this._hasSamePosition(e,t)?this.onDoubleClick&&this._isDoubleClick()?(this.onDoubleClick(e),this.eLastDown=void 0):(this.onClick?.(e),this.eLastDown=t):(this._setDragStarted(),this.onDragEnd?.(e)))}_hasSamePosition(e,t,n=CanvasPointer._maxClickDrift2){return dist2(e.clientX,e.clientY,t.clientX,t.clientY)<=n}_isDoubleClick(){let{eDown:e,eLastDown:t}=this;if(!e||!t)return!1;let n=(3*CanvasPointer._maxClickDrift)**2,r=e.timeStamp-t.timeStamp;return r>0&&r<CanvasPointer.doubleClickTime&&this._hasSamePosition(e,t,n)}_setDragStarted(e){this.dragStarted=!0,this.onDragStart?.(this,e),delete this.onDragStart}isTrackpadGesture(e){let t=performance.now(),n=Math.max(0,t-this.lastWheelEventTime);return this.lastWheelEventTime=t,this._isHighResWheelEvent(e,t)?this.detectedDevice=`mouse`:this._isWithinCooldown(n)?this._shouldBufferLinuxEvent(e)&&this._bufferLinuxEvent(e,t):(this._updateDeviceMode(e,t),this.hasReceivedWheelEvent=!0),this.detectedDevice===`trackpad`}_isHighResWheelEvent(e,t){return!this.bufferedLinuxEvent||this.bufferedLinuxEventTime<=0?!1:t-this.bufferedLinuxEventTime>CanvasPointer.maxHighResBufferTime?(this._clearLinuxBuffer(),!1):e.deltaX===0&&this._isLinuxWheelPattern(this.bufferedLinuxEvent.deltaY,e.deltaY)?(this._clearLinuxBuffer(),!0):!1}_isWithinCooldown(e){let t=!this.hasReceivedWheelEvent,n=e>=CanvasPointer.trackpadMaxGap;return!t&&!n}_updateDeviceMode(e,t){this._isTrackpadPattern(e)?this.detectedDevice=`trackpad`:this._isMousePattern(e)?this.detectedDevice=`mouse`:this.detectedDevice===`trackpad`&&this._shouldBufferLinuxEvent(e)&&this._bufferLinuxEvent(e,t)}_clearLinuxBuffer(){this.bufferedLinuxEvent=void 0,this.bufferedLinuxEventTime=0,this.linuxBufferTimeoutId!==void 0&&(clearTimeout(this.linuxBufferTimeoutId),this.linuxBufferTimeoutId=void 0)}_isTrackpadPattern(e){return!!(e.deltaX!==0&&e.deltaY!==0||e.ctrlKey&&Math.abs(e.deltaY)<10)}_isMousePattern(e){let t=Math.abs(e.deltaY);return t>80?!0:t>=60&&e.deltaX===0&&this.detectedDevice===`mouse`}_shouldBufferLinuxEvent(e){let t=Math.abs(e.deltaY),n=t>=10&&t<60,r=e.deltaX===0,i=Number.isInteger(e.deltaY);return this.detectedDevice===`trackpad`&&n&&r&&i}_bufferLinuxEvent(e,t){this.linuxBufferTimeoutId!==void 0&&clearTimeout(this.linuxBufferTimeoutId),this.bufferedLinuxEvent=e,this.bufferedLinuxEventTime=t,this.linuxBufferTimeoutId=setTimeout(()=>{this._clearLinuxBuffer()},CanvasPointer.maxHighResBufferTime)}_isLinuxWheelPattern(e,t){let n=Math.abs(e),r=Math.abs(t);return n===0||r===0?!1:n===r?!0:n%r===0||r%n===0}reset(){this.finally=void 0,delete this.onClick,delete this.onDoubleClick,delete this.onDragStart,delete this.onDrag,delete this.onDragEnd,this.isDown=!1,this.isDouble=!1,this.dragStarted=!1,this.resizeDirection=void 0,this.clearEventsOnReset&&(this.eDown=void 0,this.eMove=void 0,this.eUp=void 0);let{element:e,pointerId:t}=this;this.pointerId=void 0,typeof t==`number`&&e.hasPointerCapture(t)&&e.releasePointerCapture(t)}};function createCursorCache(e){let t=``;return function setCursor(n){n!==t&&(t=n,e.style.cursor=n)}}
2var NullGraphError=class extends Error{constructor(e=`Attempted to access LGraph reference that was null or undefined.`,t){super(e,{cause:t}),this.name=`NullGraphError`}};function isRecord(e){return typeof e==`object`&&!!e}var Le=[`title`,`flags.collapsed`,`flags.pinned`,`mode`,`color`,`bgcolor`,`shape`,`showAdvanced`],LGraphNodeProperties=class{node;_instrumentedPaths=new Set;constructor(e){this.node=e,this._setupInstrumentation()}_setupInstrumentation(){for(let e of Le)this._instrumentProperty(e)}_resolveTargetObject(e){let t=this.node;if(e.length===1)return{targetObject:t,propertyName:e[0]};for(let n=0;n<e.length-1;n++){let r=e[n],i=t[r];isRecord(i)&&(t=i)}return{targetObject:t,propertyName:e[e.length-1]}}_instrumentProperty(e){let t=e.split(`.`);t.length>1&&this._ensureNestedPath(e);let{targetObject:n,propertyName:r}=this._resolveTargetObject(t),i=Object.prototype.hasOwnProperty.call(n,r),a=n[r];if(i)Object.defineProperty(n,r,this._createInstrumentedDescriptor(e,a));else{let t;Object.defineProperty(n,r,{get:()=>t,set:i=>{let a=t;t=i,this._emitPropertyChange(e,a,i);let o=i!==void 0,s=Object.getOwnPropertyDescriptor(n,r);s&&s.enumerable!==o&&Object.defineProperty(n,r,{...s,enumerable:o})},enumerable:!1,configurable:!0})}this._instrumentedPaths.add(e)}_createInstrumentedDescriptor(e,t){return this._createInstrumentedDescriptorTyped(e,t)}_createInstrumentedDescriptorTyped(e,t){let n=t;return{get:()=>n,set:t=>{let r=n;n=t,this._emitPropertyChange(e,r,t)},enumerable:!0,configurable:!0}}_emitPropertyChange(e,t,n){this._emitPropertyChangeTyped(e,t,n)}_emitPropertyChangeTyped(e,t,n){this.node.graph?.trigger(`node:property:changed`,{nodeId:this.node.id,property:e,oldValue:t,newValue:n})}_ensureNestedPath(e){let t=e.split(`.`),n=this.node;for(let e=0;e<t.length-1;e++){let r=t[e];n[r]||(n[r]={});let i=n[r];isRecord(i)&&(n=i)}}isTracked(e){return this._instrumentedPaths.has(e)}getTrackedProperties(){return[...Le]}toJSON(){}},Re=new Map;function cachedMeasureText(e,t){let n=`${e.font}\0${t}`,r=Re.get(n);if(r!==void 0)return r;let i=e.measureText(t).width;return Re.set(n,i),i}function clearTextMeasureCache(){Re.clear()}var LGraphIcon=class{unicode;fontFamily;image;color;bgColor;fontSize;size;circlePadding;xOffset;yOffset;constructor({unicode:e,fontFamily:t=`PrimeIcons`,image:n,color:r=`#e6c200`,bgColor:i,fontSize:a=16,size:o,circlePadding:s=2,xOffset:c=0,yOffset:l=0}){this.unicode=e,this.fontFamily=t,this.image=n,this.color=r,this.bgColor=i,this.fontSize=a,this.size=o??a,this.circlePadding=s,this.xOffset=c,this.yOffset=l}draw(e,t,n){if(t+=this.xOffset,n+=this.yOffset,this.image){let r=this.size,i=r/2+this.circlePadding;if(this.bgColor){let{fillStyle:r}=e;e.beginPath(),e.arc(t+i,n,i,0,2*Math.PI),e.fillStyle=this.bgColor,e.fill(),e.fillStyle=r}let a=t+this.circlePadding,o=n-r/2;e.drawImage(this.image,a,o,r,r)}else if(this.unicode){let{font:r,textBaseline:i,textAlign:a,fillStyle:o}=e;e.font=`${this.fontSize}px '${this.fontFamily}'`,e.textBaseline=`middle`,e.textAlign=`center`;let s=this.fontSize/2+this.circlePadding;this.bgColor&&(e.beginPath(),e.arc(t+s,n,s,0,2*Math.PI),e.fillStyle=this.bgColor,e.fill()),e.fillStyle=this.color,e.fillText(this.unicode,t+s,n),e.font=r,e.textBaseline=i,e.textAlign=a,e.fillStyle=o}}},ze=function(e){return e.TopLeft=`top-left`,e.TopRight=`top-right`,e}({}),LGraphBadge=class{text;fgColor;bgColor;fontSize;padding;height;cornerRadius;icon;onClick;xOffset;yOffset;_boundingRect=[0,0,0,0];get boundingRect(){return this._boundingRect}constructor({text:e,fgColor:t=`white`,bgColor:n=`#0F1F0F`,fontSize:r=12,padding:i=6,height:a=20,cornerRadius:o=5,iconOptions:s,onClick:c,xOffset:l=0,yOffset:u=0}){this.text=e,this.fgColor=t,this.bgColor=n,this.fontSize=r,this.padding=i,this.height=a,this.cornerRadius=o,s&&(this.icon=new LGraphIcon(s)),this.onClick=c,this.xOffset=l,this.yOffset=u}get visible(){return(this.text?.length??0)>0||!!this.icon}getWidth(e){if(!this.visible)return 0;let{font:t}=e,n=0;this.icon&&(this.icon.image?n=this.icon.size+this.padding:this.icon.unicode&&(e.font=`${this.icon.fontSize}px '${this.icon.fontFamily}'`,n=cachedMeasureText(e,this.icon.unicode)+this.padding)),e.font=`${this.fontSize}px sans-serif`;let r=this.text?cachedMeasureText(e,this.text):0;return e.font=t,n+r+this.padding*2}draw(e,t,n){if(!this.visible)return;t+=this.xOffset,n+=this.yOffset;let{font:r,fillStyle:i,textBaseline:a,textAlign:o}=e;e.font=`${this.fontSize}px sans-serif`;let s=this.getWidth(e);this._boundingRect.splice(0,4,t,n,s,this.height),e.fillStyle=this.bgColor,e.beginPath(),e.roundRect?e.roundRect(t+0,n,s,this.height,this.cornerRadius):e.rect(t+0,n,s,this.height),e.fill();let c=t+0+this.padding,l=n+this.height/2;if(this.icon){this.icon.draw(e,c,l);let t=this.icon.image?this.icon.size:this.icon.fontSize;c+=t+this.padding/2+4}this.text&&(e.fillStyle=this.fgColor,e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(this.text,c,l+1)),e.font=r,e.fillStyle=i,e.textBaseline=a,e.textAlign=o}},G=class Rectangle extends Float64Array{_pos;_size;constructor(e=0,t=0,n=0,r=0){super(4),this[0]=e,this[1]=t,this[2]=n,this[3]=r}static from([e,t,n,r]){return new Rectangle(e,t,n,r)}static fromCentre([e,t],n,r=n){return new Rectangle(e-n*.5,t-r*.5,n,r)}static ensureRect(e){return e instanceof Rectangle?e:new Rectangle(e[0],e[1],e[2],e[3])}subarray(e=0,t){let n=e<<3,r=t===void 0?t:t-e;return new Float64Array(this.buffer,n,r)}get pos(){return this._pos??=this.subarray(0,2),this._pos}set pos(e){this[0]=e[0],this[1]=e[1]}get size(){return this._size??=this.subarray(2,4),this._size}set size(e){this[2]=e[0],this[3]=e[1]}get x(){return this[0]}set x(e){this[0]=e}get y(){return this[1]}set y(e){this[1]=e}get width(){return this[2]}set width(e){this[2]=e}get height(){return this[3]}set height(e){this[3]=e}get left(){return this[0]}set left(e){this[0]=e}get top(){return this[1]}set top(e){this[1]=e}get right(){return this[0]+this[2]}set right(e){this[0]=e-this[2]}get bottom(){return this[1]+this[3]}set bottom(e){this[1]=e-this[3]}get centreX(){return this[0]+this[2]*.5}get centreY(){return this[1]+this[3]*.5}updateTo(e){this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3]}containsXy(e,t){let[n,r,i,a]=this;return e>=n&&e<n+i&&t>=r&&t<r+a}containsPoint([e,t]){let[n,r,i,a]=this;return e>=n&&e<n+i&&t>=r&&t<r+a}containsRect(e){let{right:t,bottom:n}=this,r=e[0]+e[2],i=e[1]+e[3];return!(this.x===e[0]&&this.y===e[1]&&t===r&&n===i)&&this.x<=e[0]&&this.y<=e[1]&&t>=r&&n>=i}overlaps(e){return this.x<e[0]+e[2]&&this.y<e[1]+e[3]&&this.x+this.width>e[0]&&this.y+this.height>e[1]}findContainingCorner(e,t,n){if(this.isInTopLeftCorner(e,t,n))return`NW`;if(this.isInTopRightCorner(e,t,n))return`NE`;if(this.isInBottomLeftCorner(e,t,n))return`SW`;if(this.isInBottomRightCorner(e,t,n))return`SE`}isInTopLeftCorner(e,t,n){return isInRectangle(e,t,this.x,this.y,n,n)}isInTopRightCorner(e,t,n){return isInRectangle(e,t,this.right-n,this.y,n,n)}isInBottomLeftCorner(e,t,n){return isInRectangle(e,t,this.x,this.bottom-n,n,n)}isInBottomRightCorner(e,t,n){return isInRectangle(e,t,this.right-n,this.bottom-n,n,n)}isInTopEdge(e,t,n){return isInRectangle(e,t,this.x,this.y,this.width,n)}isInBottomEdge(e,t,n){return isInRectangle(e,t,this.x,this.bottom-n,this.width,n)}isInLeftEdge(e,t,n){return isInRectangle(e,t,this.x,this.y,n,this.height)}isInRightEdge(e,t,n){return isInRectangle(e,t,this.right-n,this.y,n,this.height)}getCentre(){return[this.centreX,this.centreY]}getArea(){return this.width*this.height}getPerimeter(){return 2*(this.width+this.height)}getTopLeft(){return[this[0],this[1]]}getBottomRight(){return[this.right,this.bottom]}getSize(){return[this[2],this[3]]}getOffsetTo([e,t]){return[e-this[0],t-this[1]]}getOffsetFrom([e,t]){return[this[0]-e,this[1]-t]}resizeTopLeft(e,t){this[2]+=this[0]-e,this[3]+=this[1]-t,this[0]=e,this[1]=t}resizeBottomLeft(e,t){this[2]+=this[0]-e,this[3]=t-this[1],this[0]=e}resizeTopRight(e,t){this[2]=e-this[0],this[3]+=this[1]-t,this[1]=t}resizeBottomRight(e,t){this[2]=e-this[0],this[3]=t-this[1]}setWidthRightAnchored(e){let t=this[2];this[2]=e,this[0]+=t-e}setHeightBottomAnchored(e){let t=this[3];this[3]=e,this[1]+=t-e}clone(){return new Rectangle(this[0],this[1],this[2],this[3])}toArray(){return this.export()}export(){return[this[0],this[1],this[2],this[3]]}_drawDebug(e,t=`red`){let{strokeStyle:n,lineWidth:r}=e;try{e.strokeStyle=t,e.lineWidth=.5,e.beginPath(),e.strokeRect(this[0],this[1],this[2],this[3])}
2finally{e.strokeStyle=n,e.lineWidth=r}}},LGraphButton=class extends LGraphBadge{name;_last_area=new G;constructor(e){super(e),this.name=e.name}getWidth(e){if(!this.visible)return 0;let{font:t}=e;e.font=`${this.fontSize}px 'PrimeIcons'`;let n=this.text?cachedMeasureText(e,this.text):0;return e.font=t,n}draw(e,t,n){if(!this.visible)return;let r=this.getWidth(e);this._last_area[0]=t+this.xOffset,this._last_area[1]=n+this.yOffset,this._last_area[2]=r,this._last_area[3]=this.height;let i=t+this.xOffset,a=n+this.yOffset,{font:o,fillStyle:s,textBaseline:c,textAlign:l}=e,u=e.fillStyle||`white`;e.font=`${this.fontSize}px 'PrimeIcons'`,e.fillStyle=u,e.textBaseline=`middle`,e.textAlign=`center`;let d=i+r/2,f=a+this.height/2;this.text&&e.fillText(this.text,d,f),e.font=o,e.fillStyle=s,e.textBaseline=c,e.textAlign=l}isPointInside(e,t){return this._last_area.containsPoint([e,t])}},Be=useLayoutMutations(),K=class LLink{static _drawDebug=!1;id;parentId;type;origin_id;origin_slot;target_id;target_slot;data;_data;_pos;_last_time;path;_centreAngle;_dragging;_color;get color(){return this._color}set color(e){this._color=e===``?null:e}get isFloatingOutput(){return this.origin_id===-1&&this.origin_slot===-1}get isFloatingInput(){return this.target_id===-1&&this.target_slot===-1}get isFloating(){return this.isFloatingOutput||this.isFloatingInput}get originIsIoNode(){return this.origin_id===-10}get targetIsIoNode(){return this.target_id===-20}constructor(e,t,n,r,i,a,o){this.id=e,this.type=t,this.origin_id=n,this.origin_slot=r,this.target_id=i,this.target_slot=a,this.parentId=o,this._data=null,this._pos=[0,0]}static createFromArray(e){return new LLink(e[0],e[5],e[1],e[2],e[3],e[4])}static create(e){return new LLink(e.id,e.type,e.origin_id,e.origin_slot,e.target_id,e.target_slot,e.parentId)}static getReroutes(e,t){return t.parentId===void 0?[]:e.reroutes.get(t.parentId)?.getReroutes()??[]}static getFirstReroute(e,t){return LLink.getReroutes(e,t).at(0)}static findNextReroute(e,t,n){if(t.parentId!==void 0)return e.reroutes.get(t.parentId)?.findNextReroute(n)}static getOriginNode(e,t){let n=e.links.get(t)?.origin_id;return e.getNodeById(n)??void 0}static getTargetNode(e,t){let n=e.links.get(t)?.target_id;return e.getNodeById(n)??void 0}static resolve(e,t){return t.getLink(e)?.resolve(t)}static resolveMany(e,t){let n=[];for(let r of e){let e=t.getLink(r)?.resolve(t);e&&n.push(e)}return n}resolve(e){let t=this.target_id===-1?void 0:e.getNodeById(this.target_id)??void 0,n=t?.inputs[this.target_slot],r=this.originIsIoNode?e.inputNode?.slots[this.origin_slot]:void 0;if(r)return{inputNode:t,input:n,subgraphInput:r,link:this};let i=this.origin_id===-1?void 0:e.getNodeById(this.origin_id)??void 0,a=i?.outputs[this.origin_slot],o=this.targetIsIoNode?e.outputNode?.slots[this.target_slot]:void 0;return o?{outputNode:i,output:a,subgraphInput:void 0,subgraphOutput:o,link:this}:{inputNode:t,outputNode:i,input:n,output:a,subgraphInput:r,subgraphOutput:o,link:this}}configure(e){Array.isArray(e)?(this.id=e[0],this.origin_id=e[1],this.origin_slot=e[2],this.target_id=e[3],this.target_slot=e[4],this.type=e[5]):(this.id=e.id,this.type=e.type,this.origin_id=e.origin_id,this.origin_slot=e.origin_slot,this.target_id=e.target_id,this.target_slot=e.target_slot,this.parentId=e.parentId)}hasOrigin(e,t){return this.origin_id===e&&this.origin_slot===t}hasTarget(e,t){return this.target_id===e&&this.target_slot===t}toFloating(e,t){let n=this.asSerialisable();return n.id=-1,n.parentId=t,e===`input`?(n.origin_id=-1,n.origin_slot=-1):(n.target_id=-1,n.target_slot=-1),LLink.create(n)}disconnect(e,t){let n=LLink.getReroutes(e,this),r=n.at(-1);if(t===`output`&&r?.linkIds.size===1&&r.floatingLinkIds.size===0||t===`input`&&r){let n=LLink.create(this);n.id=-1,t===`input`?(n.origin_id=-1,n.origin_slot=-1,r.floating={slotType:`input`}):(n.target_id=-1,n.target_slot=-1,r.floating={slotType:`output`}),e.addFloatingLink(n)}for(let r of n)r.linkIds.delete(this.id),!t&&!r.totalLinks&&(e.reroutes.delete(r.id),Be.setSource(H.Canvas),Be.deleteReroute(r.id));e.links.delete(this.id),Be.setSource(H.Canvas),Be.deleteLink(this.id)}serialize(){return[this.id,this.origin_id,this.origin_slot,this.target_id,this.target_slot,this.type]}
2asSerialisable(){let e={id:this.id,origin_id:this.origin_id,origin_slot:this.origin_slot,target_id:this.target_id,target_slot:this.target_slot,type:this.type};return this.parentId!==void 0&&(e.parentId=this.parentId),e}};function getNodeInputOnPos(e,t,n){let{inputs:r}=e;if(r)for(let[i,a]of r.entries()){let r=e.getInputPos(i),o=20+((a.label?.length??a.localized_name?.length??a.name?.length)||3)*7;if(isInRectangle(t,n,r[0]-10,r[1]-10,o,20))return{index:i,input:a,pos:r}}}function getNodeOutputOnPos(e,t,n){let{outputs:r}=e;if(r)for(let[i,a]of r.entries()){let r=e.getOutputPos(i);if(isInRectangle(t,n,r[0]-10,r[1]-10,40,20))return{index:i,output:a,pos:r}}}function isOverNodeInput(e,t,n,r){let i=getNodeInputOnPos(e,t,n);return i?(r&&(r[0]=i.pos[0],r[1]=i.pos[1]),i.index):-1}function isOverNodeOutput(e,t,n,r){let i=getNodeOutputOnPos(e,t,n);return i?(r&&(r[0]=i.pos[0],r[1]=i.pos[1]),i.index):-1}var Ve=`…`,He=`‥`,Ue=`․`,We=function(e){return e.Array=`array`,e[e.Event=-1]=`Event`,e}({}),Ge=function(e){return e[e.Box=P.BOX]=`Box`,e[e.Arrow=P.ARROW]=`Arrow`,e[e.Grid=P.GRID]=`Grid`,e[e.Circle=P.CIRCLE]=`Circle`,e[e.HollowCircle=P.HollowCircle]=`HollowCircle`,e}({}),Ke=function(e){return e}({}),qe=function(e){return e.Left=`left`,e.Right=`right`,e}({});
2function strokeShape(e,t,{shape:n=P.BOX,round_radius:r,title_height:i,title_mode:a=z.NORMAL_TITLE,color:o,padding:s=6,collapsed:c=!1,lineWidth:l=1}={}){if(r??=Q.ROUND_RADIUS,o??=Q.NODE_BOX_OUTLINE_COLOR,a===z.TRANSPARENT_TITLE){let e=i??Q.NODE_TITLE_HEIGHT;t[1]-=e,t[3]+=e}let{lineWidth:u,strokeStyle:d}=e;e.lineWidth=l,e.globalAlpha=.8,e.strokeStyle=o,e.beginPath();let[f,p,m,h]=t;switch(n){case P.BOX:e.rect(f-s,p-s,m+2*s,h+2*s);break;case P.ROUND:case P.CARD:{let t=r+s,i=n===P.CARD&&c||n===P.ROUND?[t]:[t,2,t,2];e.roundRect(f-s,p-s,m+2*s,h+2*s,i);break}case P.CIRCLE:{let t=f+m/2,n=p+h/2,r=Math.max(m,h)/2+s;e.arc(t,n,r,0,Math.PI*2);break}}e.stroke(),e.lineWidth=u,e.strokeStyle=d,e.globalAlpha=1}function truncateTextToWidth(e,t,n){if(!(n>0))return``;if(cachedMeasureText(e,t)<=n)return t;let r=cachedMeasureText(e,Ve)*.75;if(r>n)return cachedMeasureText(e,He)*.75<n?He:cachedMeasureText(e,Ue)*.75<n?Ue:``;let i=0,a=t.length,o=0;for(;i<=a;){let s=Math.floor((i+a)*.5);if(s===0){i=s+1;continue}cachedMeasureText(e,t.substring(0,s))+r<=n?(o=s,i=s+1):a=s-1}return o===0?Ve:t.substring(0,o)+Ve}function drawTextInArea({ctx:e,text:t,area:n,align:r=`left`}){let{left:i,right:a,bottom:o,width:s,centreX:c}=n;if(cachedMeasureText(e,t)<=s){e.textAlign=r;let n=r===`left`?i:r===`right`?a:c;e.fillText(t,n,o);return}let l=truncateTextToWidth(e,t,s);if(l.length===0)return;e.textAlign=`left`,e.fillText(l.slice(0,-1),i,o),e.rect(i,o,s,1),e.textAlign=`right`;let u=l.at(-1);e.fillText(u,a,o,cachedMeasureText(e,u)*.75)}function getSlotColor(e){return e?`var(--color-datatype-${String(e).toUpperCase()}, #AAA)`:`#AAA`}var SlotBase=class{name;localized_name;label;type;dir;removable;shape;color_off;color_on;locked;nameLocked;widget;_floatingLinks;hasErrors;boundingRect;constructor(e,t,n){this.name=e,this.type=t,this.boundingRect=n??new G}renderingColor(e){return this.isConnected?this.color_on||e.getConnectedColor(this.type):this.color_off||e.getDisconnectedColor(this.type)}},Je=-Math.PI,NodeSlot=class extends SlotBase{pos;get _centreOffset(){let e=this.node.pos,{boundingRect:t}=this,n=t[3];return getCentre([t[0]-e[0],t[1]-e[1],n,n])}_node;get node(){return this._node}get highlightColor(){return Q.NODE_TEXT_HIGHLIGHT_COLOR??Q.NODE_SELECTED_TITLE_COLOR??Q.NODE_TEXT_COLOR}constructor(e,t){let{boundingRect:n,name:r,type:i,_listenerController:a,...o}=e,s=n?G.ensureRect(n):new G;super(r,i,s),Object.assign(this,o),this._node=t}get renderingLabel(){return this.label||this.localized_name||this.name||``}draw(e,{colorContext:t,labelPosition:n=qe.Right,lowQuality:r=!1,highlight:i=!1,doStroke:a=!1}){let o=e.fillStyle,s=e.strokeStyle,c=e.lineWidth,l=i?this.highlightColor:Q.NODE_TEXT_COLOR,u=this._centreOffset,d=this.type,f=d===We.Array?Ge.Grid:this.shape;e.save(),e.beginPath();let p=!0;if(e.fillStyle=this.renderingColor(t),e.lineWidth=1,d===We.Event||f===Ge.Box)e.rect(u[0]-6+.5,u[1]-5+.5,14,10);else if(f===Ge.Arrow)e.moveTo(u[0]+8,u[1]+.5),e.lineTo(u[0]-4,u[1]+6+.5),e.lineTo(u[0]-4,u[1]-6+.5),e.closePath();else if(f===Ge.Grid){for(let t=0;t<3;t++)for(let n=0;n<3;n++)e.rect(u[0]-4+t*3,u[1]-4+n*3,2,2);a=!1}else if(r)e.rect(u[0]-4,u[1]-4,8,8);else{if(f===Ge.HollowCircle){let t=new Path2D;t.arc(u[0],u[1],10,0,Math.PI*2),t.arc(u[0],u[1],i?2.5:1.5,0,Math.PI*2),e.clip(t,`evenodd`)}let n=i?5:4,r=this.isConnected?t.getConnectedColor:t.getDisconnectedColor,a=`${this.type}`.split(`,`).map(r).slice(0,3);if(a.length>1){p=!1;let t=Math.PI*2/a.length;a.forEach((r,i)=>{e.moveTo(u[0],u[1]),e.fillStyle=r,e.arc(u[0],u[1],n,t*i+Je,Math.PI*2+Je),e.fill(),e.beginPath()}),e.save(),e.strokeStyle=`black`,e.lineWidth=.5,a.forEach((r,i)=>{e.moveTo(u[0],u[1]);let a=Math.cos(t*i+Je)*n,o=Math.sin(t*i+Je)*n;e.lineTo(u[0]+a,u[1]+o)}),e.stroke(),e.restore(),e.beginPath()}e.arc(u[0],u[1],n,0,Math.PI*2)}if(p&&e.fill(),!r&&a&&e.stroke(),e.restore(),!(r||this.isWidgetInputSlot)){let t=this.renderingLabel;t&&(e.fillStyle=l,n===qe.Right?this.dir==I.UP?e.fillText(t,u[0],u[1]-10):e.fillText(t,u[0]+10,u[1]+5):this.dir==I.DOWN?e.fillText(t,u[0],u[1]-8):e.fillText(t,u[0]-10,u[1]+5))}this.hasErrors&&(e.lineWidth=2,e.strokeStyle=`red`,e.beginPath(),e.arc(u[0],u[1],12,0,Math.PI*2),e.stroke()),e.fillStyle=o,e.strokeStyle=s,e.lineWidth=c}
2toJSON(){return{name:this.name,type:this.type,label:this.label,color_on:this.color_on,color_off:this.color_off,shape:this.shape,dir:this.dir,localized_name:this.localized_name,pos:this.pos,boundingRect:[...this.boundingRect]}}drawCollapsed(e){let[t,n]=this.collapsedPos,{fillStyle:r}=e;e.fillStyle=`#686`,e.beginPath(),this.type===We.Event||this.shape===P.BOX?e.rect(t-7+.5,n-4,14,8):this.shape===P.ARROW?(this instanceof NodeInputSlot?(e.moveTo(t+8,n),e.lineTo(t-4,n-4),e.lineTo(t-4,n+4)):(e.moveTo(t+6,n),e.lineTo(t-6,n-4),e.lineTo(t-6,n+4)),e.closePath()):e.arc(t,n,4,0,Math.PI*2),e.fill(),e.fillStyle=r}},Ye=useLayoutMutations(),q=class Reroute{static radius=10;static maxSplineOffset=80;static drawIdBadge=!1;static slotRadius=5;static get slotOffset(){let e=Reroute.slotRadius*.33;return Reroute.radius+e+Reroute.slotRadius}network;parentIdInternal;get parentId(){return this.parentIdInternal}set parentId(e){e!==this.id&&this.getReroutes()!==null&&(this.parentIdInternal=e)}get parent(){return this.network.deref()?.getReroute(this.parentIdInternal)}floating;posInternal=[0,0];get pos(){return this.posInternal}set pos(e){if(!(e?.length>=2))throw TypeError(`Reroute.pos is an x,y point, and expects an indexable with at least two values.`);this.posInternal[0]=e[0],this.posInternal[1]=e[1]}get boundingRect(){let{radius:e}=Reroute,[t,n]=this.posInternal;return[t-e,n-e,2*e,2*e]}get hoverArea(){let e=2*Reroute.slotOffset,t=2*Math.max(Reroute.radius,Reroute.slotRadius),[n,r]=this.posInternal;return[n-e,r-t,2*e,2*t]}get totalLinks(){return this.linkIds.size+this.floatingLinkIds.size}selected;linkIds;floatingLinkIds;cos=0;sin=0;controlPoint=[0,0];path;_centreAngle;_pos=[0,0];_dragging;_colour;get colour(){return this._colour??`#18184d`}lastRenderTime=-1/0;inputSlot=new RerouteSlot(this,!0);outputSlot=new RerouteSlot(this,!1);get isSlotHovered(){return this.isInputHovered||this.isOutputHovered}get isInputHovered(){return this.inputSlot.hovering}get isOutputHovered(){return this.outputSlot.hovering}get firstLink(){let e=this.linkIds.values().next().value;return e===void 0?void 0:this.network.deref()?.links.get(e)}get firstFloatingLink(){let e=this.floatingLinkIds.values().next().value;return e===void 0?void 0:this.network.deref()?.floatingLinks.get(e)}get origin_id(){return this.firstLink?.origin_id}get origin_slot(){return this.firstLink?.origin_slot}constructor(e,t,n,r,i,a){this.id=e,this.network=new WeakRef(t),this.parentId=r,n&&(this.pos=n),this.linkIds=new Set(i),this.floatingLinkIds=new Set(a)}update(e,t,n,r){this.parentId=e,t&&(this.pos=t),n&&(this.linkIds=new Set(n)),this.floating=r}validateLinks(e,t){let{linkIds:n,floatingLinkIds:r}=this;for(let t of n)e.has(t)||n.delete(t);for(let e of r)t.has(e)||r.delete(e);return n.size>0||r.size>0}getReroutes(e=new Set){if(this.parentIdInternal===void 0)return[this];if(e.has(this))return null;e.add(this);let t=this.network.deref()?.reroutes.get(this.parentIdInternal);if(!t)return this.parentIdInternal=void 0,[this];let n=t.getReroutes(e);return n?.push(this),n}findNextReroute(e,t=new Set){if(this.parentIdInternal===e)return this;if(t.has(this))return null;if(t.add(this),this.parentIdInternal!==void 0)return this.network.deref()?.reroutes.get(this.parentIdInternal)?.findNextReroute(e,t)}findSourceOutput(){let e=this.firstLink??this.firstFloatingLink;if(!e)return;let t=this.network.deref()?.getNodeById(e.origin_id);if(t)return{node:t,output:t.outputs[e.origin_slot]}}findTargetInputs(){let e=this.network.deref();if(!e)return;let t=[];return addAllResults(e,this.linkIds,e.links),addAllResults(e,this.floatingLinkIds,e.floatingLinks),t;function addAllResults(e,n,r){for(let i of n){let n=r.get(i);if(!n)continue;let a=e.getNodeById(n.target_id),o=a?.inputs[n.target_slot];o&&t.push({node:a,input:o,link:n})}}}getFloatingLinks(e){let t=this.network.deref()?.floatingLinks;if(!t)return;let n=e===`input`?`origin_id`:`target_id`,r=[];for(let e of this.floatingLinkIds){let i=t.get(e);i?.[n]===-1&&r.push(i)}return r}setFloatingLinkOrigin(e,t,n){let r=this.network.deref(),i=this.getFloatingLinks(`output`);if(!i)throw Error(`[setFloatingLinkOrigin]: Invalid network.`);if(i.length){t._floatingLinks??=new Set;for(let a of i)t._floatingLinks.add(a),r?.getNodeById(a.origin_id)?.outputs[a.origin_slot]?._floatingLinks?.delete(a),a.origin_id=e.id,a.origin_slot=n}}move(e,t){let n={x:this.posInternal[0],y:this.posInternal[1]};this.posInternal[0]+=e,this.posInternal[1]+=t,Ye.setSource(H.Canvas),Ye.moveReroute(this.id,{x:this.posInternal[0],y:this.posInternal[1]},n)}
2snapToGrid(e){if(!e)return!1;let t=Q.NODE_SLOT_HEIGHT*.7,{pos:n}=this;return n[0]=e*Math.round(n[0]/e),n[1]=e*Math.round((n[1]-t)/e)+t,!0}removeAllFloatingLinks(){for(let e of this.floatingLinkIds)this.removeFloatingLink(e)}removeFloatingLink(e){let t=this.network.deref();if(!t)return;let n=t.floatingLinks.get(e);if(!n){console.warn(`[Reroute.removeFloatingLink] Floating link not found: ${e}, ignoring and discarding ID.`),this.floatingLinkIds.delete(e);return}t.removeFloatingLink(n)}removeLink(e){let t=this.network.deref();t&&(e===t.floatingLinks.get(e.id)?this.floatingLinkIds.delete(e.id):this.linkIds.delete(e.id))}remove(){let e=this.network.deref();e&&e.removeReroute(this.id)}calculateAngle(e,t,n){if(!(e>this.lastRenderTime))return;this.lastRenderTime=e;let{id:r,pos:i}=this,a=[],o=0;if(calculateAngles(this.linkIds,t.links),calculateAngles(this.floatingLinkIds,t.floatingLinks),!a.length){this.cos=0,this.sin=0,this.controlPoint[0]=0,this.controlPoint[1]=0;return}o/=a.length;let s=Math.atan2(this.posInternal[1]-n[1],this.posInternal[0]-n[0]),c=(s-o)*.5;Math.abs(c)>Math.PI*.5&&(c+=Math.PI);let l=Math.min(Reroute.maxSplineOffset,distance(n,this.posInternal)*.25),u=s-c,d=Math.cos(u),f=Math.sin(u);this.cos=d,this.sin=f,this.controlPoint[0]=l*-d,this.controlPoint[1]=l*-f;function calculateAngles(e,n){for(let s of e){let e=getNextPos(t,n.get(s),r);if(!e)continue;let c=getDirection(i,e);a.push(c),o+=c}}}draw(e,t){let{globalAlpha:n}=e,{pos:r}=this;if(e.beginPath(),e.arc(r[0],r[1],Reroute.radius,0,2*Math.PI),this.linkIds.size===0&&(e.fillStyle=t??`#797979`,e.fill(),e.globalAlpha=n*.33),e.fillStyle=this.colour,e.lineWidth=Reroute.radius*.1,e.strokeStyle=`rgb(0,0,0,0.5)`,e.fill(),e.stroke(),e.fillStyle=`#ffffff55`,e.strokeStyle=`rgb(0,0,0,0.3)`,e.beginPath(),e.arc(r[0],r[1],Reroute.radius*.8,0,2*Math.PI),e.fill(),e.stroke(),this.selected&&(e.strokeStyle=`#fff`,e.beginPath(),e.arc(r[0],r[1],Reroute.radius*1.2,0,2*Math.PI),e.stroke()),Reroute.drawIdBadge){let t=new LGraphBadge({text:this.id.toString()}),n=r[0]-t.getWidth(e)*.5,i=r[1]-t.height-Reroute.radius-2;t.draw(e,n,i)}e.globalAlpha=n}drawSlots(e){this.inputSlot.draw(e),this.outputSlot.draw(e)}drawHighlight(e,t){let{pos:n}=this,{strokeStyle:r,lineWidth:i}=e;e.strokeStyle=t,e.lineWidth=1,e.beginPath(),e.arc(n[0],n[1],Reroute.radius*1.5,0,2*Math.PI),e.stroke(),e.strokeStyle=r,e.lineWidth=i}updateVisibility(e){let t=this.inputSlot,n=this.outputSlot;t.dirty=!1,n.dirty=!1;let{firstFloatingLink:r}=this,i=!!this.firstLink,a=i||r?.isFloatingOutput,o=i||r?.isFloatingInput;if((a||o)&&isPointInRect(e,this.hoverArea)){let r=this.contains(e);a&&t.update(e,r),o&&n.update(e,r)}else this.hideSlots();return t.dirty||n.dirty}hideSlots(){this.inputSlot.hide(),this.outputSlot.hide()}containsPoint(e){return isPointInRect(e,this.hoverArea)&&this.contains(e)}contains(e){return distance(this.pos,e)<=Reroute.radius}asSerialisable(){let{id:e,parentId:t,pos:n,linkIds:r}=this;return{id:e,parentId:t,pos:[n[0],n[1]],linkIds:[...r],floating:this.floating?{slotType:this.floating.slotType}:void 0}}},RerouteSlot=class{reroute;offsetMultiplier;get pos(){let[e,t]=this.reroute.pos;return[e+q.slotOffset*this.offsetMultiplier,t]}dirty=!1;hoveringInternal=!1;get hovering(){return this.hoveringInternal}set hovering(e){Object.is(this.hoveringInternal,e)||(this.hoveringInternal=e,this.dirty=!0)}showOutlineInternal=!1;get showOutline(){return this.showOutlineInternal}set showOutline(e){Object.is(this.showOutlineInternal,e)||(this.showOutlineInternal=e,this.dirty=!0)}constructor(e,t){this.reroute=e,this.offsetMultiplier=t?-1:1}update(e,t){if(t)this.hovering=!1,this.showOutline=!0;else{let t=distance(this.pos,e);this.hovering=t<=2*q.slotRadius,this.showOutline=t<=5*q.slotRadius}}hide(){this.hovering=!1,this.showOutline=!1}draw(e){let{fillStyle:t,strokeStyle:n,lineWidth:r}=e,{showOutline:i,hovering:a,pos:[o,s]}=this;if(i)try{e.fillStyle=a?this.reroute.colour:`rgba(127,127,127,0.3)`,e.strokeStyle=`rgb(0,0,0,0.5)`,e.lineWidth=1,e.beginPath(),e.arc(o,s,q.slotRadius,0,2*Math.PI),e.fill(),e.stroke()}finally{e.fillStyle=t,e.strokeStyle=n,e.lineWidth=r}}};function getNextPos(e,t,n){if(!t)return;let r=K.findNextReroute(e,t,n)?.pos;if(r)return r;if(!(t.target_id===-1||t.target_slot===-1))return e.getNodeById(t.target_id)?.getInputPos(t.target_slot)}function getDirection(e,t){return Math.atan2(t[1]-e[1],t[0]-e[0])}function parseSlotTypes(e){return e==``||e==`0`?[`*`]:String(e).toLowerCase().split(`,`)}function nextUniqueName(e,t=[]){let n=1,r=e;for(;t.includes(e);)e=`${r}_${n++}`;return e}function getAllNestedItems(e){let t=new Set;if(e)for(let n of e)addRecursively(n,t);return t;function addRecursively(e,t){if(!(t.has(e)||e.pinned)&&(t.add(e),e.children))for(let n of e.children)addRecursively(n,t)}}function findFirstNode(e){for(let t of e)if(t instanceof Y)return t}function findFreeSlotOfType(e,t,n){if(!e?.length)return;let r,i,a,o=parseSlotTypes(t);for(let[t,s]of e.entries()){let e=parseSlotTypes(s.type);for(let c of o)for(let o of e)if(o===c){if(n(s))return{index:t,slot:s};r??={index:t,slot:s}}else !i&&(c===`*`||o===`*`)&&(n(s)?i={index:t,slot:s}:a??={index:t,slot:s})}return i??r??a}
2var CustomEventTarget=class extends EventTarget{dispatch(e,t){let n=new CustomEvent(e,{detail:t,cancelable:!0});return super.dispatchEvent(n)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}dispatchEvent(e){return super.dispatchEvent(e)}},Xe=class ConstrainedSize{_width=0;_height=0;_desiredWidth=0;_desiredHeight=0;minWidth=0;minHeight=0;maxWidth=1/0;maxHeight=1/0;get width(){return this._width}get height(){return this._height}get desiredWidth(){return this._desiredWidth}set desiredWidth(e){this._desiredWidth=e,this._width=h(e,this.minWidth,this.maxWidth)}get desiredHeight(){return this._desiredHeight}set desiredHeight(e){this._desiredHeight=e,this._height=h(e,this.minHeight,this.maxHeight)}constructor(e,t){this.desiredWidth=e,this.desiredHeight=t}static fromSize(e){return new ConstrainedSize(e[0],e[1])}static fromRect(e){return new ConstrainedSize(e[2],e[3])}setSize(e){this.desiredWidth=e[0],this.desiredHeight=e[1]}setValues(e,t){this.desiredWidth=e,this.desiredHeight=t}toSize(){return[this._width,this._height]}},Ze=class SubgraphSlot extends SlotBase{static get defaultHeight(){return Q.NODE_SLOT_HEIGHT}_pos=[0,0];measurement=new Xe(SubgraphSlot.defaultHeight,SubgraphSlot.defaultHeight);id;parent;type;linkIds=[];boundingRect=new G(0,0,0,SubgraphSlot.defaultHeight);get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get isConnected(){return this.linkIds.length>0}get displayName(){return this.label??this.localized_name??this.name}constructor(e,t){super(e.name,e.type),Object.assign(this,e),this.id=e.id??createUuidv4(),this.type=e.type,this.parent=t}isPointerOver=!1;containsPoint(e){return this.boundingRect.containsPoint(e)}onPointerMove(e){this.isPointerOver=this.boundingRect.containsXy(e.canvasX,e.canvasY)}getLinks(){let e=[],{subgraph:t}=this.parent;for(let n of this.linkIds){let r=t.getLink(n);r&&e.push(r)}return e}decrementSlots(e){let{links:t}=this.parent.subgraph,n=e===`inputs`?`origin_slot`:`target_slot`;for(let e of this.linkIds){let r=t.get(e);r?r[n]--:console.warn(`decrementSlots: link ID not found`,e)}}measure(){let e=Z._measureText?.(this.displayName)??0,{defaultHeight:t}=SubgraphSlot;return this.measurement.setValues(e+t,t),this.measurement.toSize()}disconnect(){let{subgraph:e}=this.parent;for(let t of this.linkIds)e.removeLink(t);this.linkIds.length=0}draw({ctx:e,colorContext:t,lowQuality:n,fromSlot:r,editorAlpha:i=1}){let a=this.shape,{isPointerOver:o,pos:[s,c]}=this,l=r?this.isValidTarget(r):!0,u=!r||l,d=u&&o,f=e.globalAlpha;e.globalAlpha=u?i:.4*i,e.beginPath();let p=this.renderingColor(t);if(n)e.fillStyle=p,e.rect(s-4,c-4,8,8),e.fill();else if(a===Ge.HollowCircle){e.lineWidth=3,e.strokeStyle=p;let t=d?4:3;e.arc(s,c,t,0,Math.PI*2),e.stroke()}else{e.fillStyle=p;let t=d?5:4;e.arc(s,c,t,0,Math.PI*2),e.fill()}if(this.displayName){let[t,n]=this.labelPos;e.fillStyle=d?`white`:Q.NODE_TEXT_COLOR||`#AAA`,e.fillText(this.displayName,t,n)}e.globalAlpha=f}asSerialisable(){let{id:e,name:t,type:n,linkIds:r,localized_name:i,label:a,dir:o,shape:s,color_off:c,color_on:l,pos:u}=this;return{id:e,name:t,type:n,linkIds:r,localized_name:i,label:a,dir:o,shape:s,color_off:c,color_on:l,pos:u}}},SubgraphInput=class extends Ze{events=new CustomEventTarget;_widgetRef;get _widget(){return this._widgetRef?.deref()}set _widget(e){this._widgetRef=e?new WeakRef(e):void 0}connect(e,t,n){let{subgraph:r}=this.parent,i=t.inputs.indexOf(e);if(t.onConnectInput?.(i,this.type,this,this.parent,-1)===!1)return;if(e.link!=null){r.beforeChange();let n=r.getLink(e.link);this.parent._disconnectNodeInput(t,e,n)}let a=t.getWidgetFromSlot(e);if(a){if(!this.matchesWidget(a)){console.warn(`Target input has invalid widget.`,e,t);return}this._widget=a,this.events.dispatch(`input-connected`,{input:e,widget:a,node:t})}else this.events.dispatch(`input-connected`,{input:e});let o=new K(++r.state.lastLinkId,e.type,this.parent.id,this.parent.slots.indexOf(this),t.id,i,n);r._links.set(o.id,o),this.linkIds.push(o.id),e.link=o.id;let s=K.getReroutes(r,o);for(let e of s)e.linkIds.add(o.id),e.floating&&delete e.floating,e._dragging=void 0;let c=s.at(-1);if(c)for(let e of c.floatingLinkIds){let t=r.floatingLinks.get(e);t?.parentId===c.id&&r.removeFloatingLink(t)}return r.incrementVersion(),r.trigger(`node:slot-links:changed`,{nodeId:t.id,slotType:N.INPUT,slotIndex:i,connected:!0,linkId:o.id}),t.onConnectionsChange?.(N.INPUT,i,!0,o,e),r.afterChange(),o}get labelPos(){let[e,t,,n]=this.boundingRect;return[e,t+n*.5]}getConnectedWidgets(){let{subgraph:e}=this.parent,t=[];for(let n of this.linkIds){let r=e.getLink(n);if(!r){console.error(`Link not found`,n);continue}let i=r.resolve(e);if(i.input&&i.inputNode?.widgets){let e=i.input.widget;if(!e)continue;if(!e.name){console.warn(`Invalid widget name`,e);continue}let n=i.inputNode.widgets.find(t=>t.name===e.name);if(!n){console.warn(`Widget not found`,e);continue}t.push(n)}}return t}matchesWidget(e){let t=this._widgetRef?.deref();return t?!(e.type!==t.type||e.options.min!==t.options.min||e.options.max!==t.options.max||e.options.step!==t.options.step||e.options.step2!==t.options.step2||e.options.precision!==t.options.precision):!0}disconnect(){super.disconnect(),this._widget=void 0,this.events.dispatch(`input-disconnected`,{input
2:this})}arrange(e){let[t,n,r,i]=e,{boundingRect:a,pos:o}=this;a[0]=t-r,a[1]=n,a[2]=r,a[3]=i,o[0]=t-i*.5,o[1]=n+i*.5}isValidTarget(e){return isNodeSlot(e)&&`link`in e||isSubgraphOutput(e)?Q.isValidConnection(this.type,e.type):!1}},EmptySubgraphInput=class extends SubgraphInput{constructor(e){super({id:Ce,name:``,type:``},e)}connect(e,t,n){let{subgraph:r}=this.parent,i=r.inputs.map(e=>e.name),a=nextUniqueName(e.name,i);return r.addInput(a,String(e.type)).connect(e,t,n)}get labelPos(){let[e,t,,n]=this.boundingRect;return[e,t+n*.5]}},Qe=class SubgraphIONodeBase{static margin=10;static minWidth=100;static roundedRadius=14;_boundingRect=new G;get boundingRect(){return this._boundingRect}selected=!1;pinned=!1;removable=!1;isPointerOver=!1;get pos(){return this.boundingRect.pos}set pos(e){this.boundingRect.pos=e}get size(){return this.boundingRect.size}set size(e){this.boundingRect.size=e}get sideLineWidth(){return this.isPointerOver?2.5:2}get sideStrokeStyle(){return this.isPointerOver?`white`:`#efefef`}constructor(e){this.subgraph=e}move(e,t){this.pos[0]+=e,this.pos[1]+=t}snapToGrid(e){return this.pinned?!1:snapPoint(this.pos,e)}containsPoint(e){return this.boundingRect.containsPoint(e)}onPointerMove(e){let t=this.boundingRect.containsXy(e.canvasX,e.canvasY),n=t?F.SubgraphIoNode:F.Nothing;if(t){this.isPointerOver||this.onPointerEnter();for(let t of this.allSlots)t.onPointerMove(e),t.isPointerOver&&(n|=F.SubgraphIoSlot)}else this.isPointerOver&&this.onPointerLeave();return n}onPointerEnter(){this.isPointerOver=!0}onPointerLeave(){this.isPointerOver=!1;for(let e of this.slots)e.isPointerOver=!1}getSlotInPosition(e,t){for(let n of this.allSlots)if(n.boundingRect.containsXy(e,t))return n}handleSlotDoubleClick(e,t){e!==this.emptySlot&&this._promptForSlotRename(e,t)}showSlotContextMenu(e,t){let n=this._getSlotMenuOptions(e);n.length>0&&new Q.ContextMenu(n,{event:t,title:e.name||`Subgraph Output`,callback:n=>{this._onSlotMenuAction(n,e,t)}})}_getSlotMenuOptions(e){let t=[];return e!==this.emptySlot&&e.linkIds.length>0&&t.push({content:`Disconnect Links`,value:`disconnect`}),e!==this.emptySlot&&t.push({content:`Rename Slot`,value:`rename`}),e!==this.emptySlot&&(t.push(null),t.push({content:`Remove Slot`,value:`remove`,className:`danger`})),t}_onSlotMenuAction(e,t,n){switch(e.value){case`disconnect`:t.disconnect();break;case`remove`:t!==this.emptySlot&&this.removeSlot(t);break;case`rename`:t!==this.emptySlot&&this._promptForSlotRename(t,n);break}this.subgraph.setDirtyCanvas(!0,!0)}_promptForSlotRename(e,t){this.subgraph.canvasAction(n=>n.prompt(`Slot name`,e.displayName,t=>{t&&this.renameSlot(e,t)},t))}arrange(){let{minWidth:e,roundedRadius:t}=SubgraphIONodeBase,[,n]=this.boundingRect,r=this.slotAnchorX,{size:i}=this,a=e,o=n+t;for(let e of this.allSlots){let[t,n]=e.measure();e.arrange([r,o,t,n]),o+=n,t>a&&(a=t)}i[0]=a+2*t,i[1]=o-n+t}draw(e,t,n,r){let{lineWidth:i,strokeStyle:a,fillStyle:o,font:s,textBaseline:c}=e;this.drawProtected(e,t,n,r),Object.assign(e,{lineWidth:i,strokeStyle:a,fillStyle:o,font:s,textBaseline:c})}drawSlots(e,t,n,r){e.fillStyle=`#AAA`,e.font=`12px Inter, sans-serif`,e.textBaseline=`middle`;for(let i of this.allSlots)i.draw({ctx:e,colorContext:t,fromSlot:n,editorAlpha:r})}configure(e){this._boundingRect.set(e.bounding),this.pinned=e.pinned??!1}asSerialisable(){return{id:this.id,bounding:this.boundingRect.export(),pinned:this.pinned?!0:void 0}}},SubgraphInputNode=class extends Qe{id=-10;emptySlot=new EmptySubgraphInput(this);get slots(){return this.subgraph.inputs}get allSlots(){return[...this.slots,this.emptySlot]}get slotAnchorX(){let[e,,t]=this.boundingRect;return e+t-Qe.roundedRadius}onPointerDown(e,t,n){if(e.button===0)for(let r of this.allSlots)r.boundingRect.containsXy(e.canvasX,e.canvasY)&&(t.onDragStart=()=>{n.dragNewFromSubgraphInput(this.subgraph,this,r)},t.onDragEnd=e=>{n.dropLinks(this.subgraph,e)},t.onDoubleClick=()=>{this.handleSlotDoubleClick(r,e)},t.finally=()=>{n.reset(!0)});else if(e.button===2){let t=this.getSlotInPosition(e.canvasX,e.canvasY);t&&this.showSlotContextMenu(t,e)}}renameSlot(e,t){this.subgraph.renameInput(e,t)}removeSlot(e){this.subgraph.removeInput(e)}canConnectTo(e,t,n){return e.canConnectTo(this,t,n)}connectSlots(e,t,n,r){let{subgraph:i}=this,a=this.slots.indexOf(e),o=t.inputs.indexOf(n);if(a===-1||o===-1)throw Error(`Invalid slot indices.`);return new K(++i.state.lastLinkId,n.type||e.type,this.id,a,t.id,o,r)}connectByType(e,t,n,r){let i=t.findInputByType(n);if(i){if(e===-1){let t=this.subgraph.inputs.map(e=>e.name),n=nextUniqueName(i.slot.name,t),r=this.subgraph.addInput(n,String(i.slot.type??``)),a=this.slots.indexOf(r);if(a===-1){console.error(`Could not find newly created subgraph input slot.`);return}e=a}return this.slots[e].connect(i.slot,t,r?.afterRerouteId)}}findOutputSlot(e){return this.slots.find(t=>t.name===e)}findOutputByType(e){return findFreeSlotOfType(this.slots,e,e=>e.linkIds.length>0)?.slot}_disconnectNodeInput(e,t,n){let{subgraph:r}=this;if(t._floatingLinks?.size)for(let e of t._floatingLinks)r.removeFloatingLink(e);if(t.link=null,r.setDirtyCanvas(!1,!0),!n)return;let i=n.origin_slot;n.disconnect(r,`output`),r.incrementVersion();let a=this.slots.at(i);if(!a){console.warn(`disconnectNodeInput: subgraphInput not found`,this,i);return}let o=a.linkIds.indexOf(n.id);o===-1?console.warn(`disconnectNodeInput: link ID not found in subgraphInput linkIds`,n.id):a.linkIds.splice(o,1),a.linkIds.length===0&&(a._widget=void 0),a.events.dispatch(`input-disconnected`,{input
2:a});let s=e.inputs.findIndex(e=>e===t);s!==-1&&(e.onConnectionsChange?.(N.INPUT,s,!1,n,a),r.trigger(`node:slot-links:changed`,{nodeId:e.id,slotType:N.INPUT,slotIndex:s,connected:!1,linkId:n.id}))}drawProtected(e,t,n,r){let{roundedRadius:i}=Qe,a=e.getTransform(),[o,s,c,l]=this.boundingRect;e.translate(o,s),e.strokeStyle=this.sideStrokeStyle,e.lineWidth=this.sideLineWidth,e.beginPath(),e.arc(c-i,i,i,Math.PI*1.5,0),e.moveTo(c,i),e.lineTo(c,l-i),e.arc(c-i,l-i,i,0,Math.PI*.5),e.stroke(),e.setTransform(a),this.drawSlots(e,t,n,r)}},SubgraphOutput=class extends Ze{connect(e,t,n){let{subgraph:r}=this.parent;if(!Q.isValidConnection(e.type,this.type))return;let i=t.outputs.indexOf(e);if(i===-1)throw Error(`Slot is not an output of the given node`);if(t.onConnectOutput?.(i,this.type,this,this.parent,-1)===!1)return;let a=this.getLinks().at(0);if(a!=null){r.beforeChange(),a.disconnect(r,`input`);let e=a.resolve(r).output?.links;e&&g(e,a.id)}let o=new K(++r.state.lastLinkId,e.type,t.id,i,this.parent.id,this.parent.slots.indexOf(this),n);r._links.set(o.id,o),this.linkIds[0]=o.id,e.links??=[],e.links.push(o.id);let s=K.getReroutes(r,o);for(let e of s)e.linkIds.add(o.id),e.floating&&delete e.floating,e._dragging=void 0;let c=s.at(-1);if(c)for(let e of c.floatingLinkIds){let t=r.floatingLinks.get(e);t?.parentId===c.id&&r.removeFloatingLink(t)}return r.incrementVersion(),t.onConnectionsChange?.(N.OUTPUT,i,!0,o,e),r.afterChange(),o}get labelPos(){let[e,t,,n]=this.boundingRect;return[e+n,t+n*.5]}arrange(e){let[t,n,r,i]=e,{boundingRect:a,pos:o}=this;a[0]=t,a[1]=n,a[2]=r,a[3]=i,o[0]=t+i*.5,o[1]=n+i*.5}isValidTarget(e){return isNodeSlot(e)&&`links`in e||isSubgraphInput(e)?Q.isValidConnection(e.type,this.type):!1}disconnect(){let{subgraph:e}=this.parent;for(let t of this.linkIds){let n=e.links[t];if(!n)continue;e.removeLink(t);let{output:r,outputNode:i}=n.resolve(e);r&&(r.links=r.links?.filter(e=>e!==t)??null),i?.onConnectionsChange?.(N.OUTPUT,n.origin_slot,!1,n,this)}this.linkIds.length=0}},EmptySubgraphOutput=class extends SubgraphOutput{constructor(e){super({id:Ce,name:``,type:``},e)}connect(e,t,n){let{subgraph:r}=this.parent,i=r.outputs.map(e=>e.name),a=nextUniqueName(e.name,i);return r.addOutput(a,String(e.type)).connect(e,t,n)}get labelPos(){let[e,t,,n]=this.boundingRect;return[e,t+n*.5]}},SubgraphOutputNode=class extends Qe{id=-20;emptySlot=new EmptySubgraphOutput(this);get slots(){return this.subgraph.outputs}get allSlots(){return[...this.slots,this.emptySlot]}get slotAnchorX(){let[e]=this.boundingRect;return e+Qe.roundedRadius}onPointerDown(e,t,n){if(e.button===0)for(let r of this.allSlots)r.boundingRect.containsXy(e.canvasX,e.canvasY)&&(t.onDragStart=()=>{n.dragNewFromSubgraphOutput(this.subgraph,this,r)},t.onDragEnd=e=>{n.dropLinks(this.subgraph,e)},t.onDoubleClick=()=>{this.handleSlotDoubleClick(r,e)},t.finally=()=>{n.reset(!0)});else if(e.button===2){let t=this.getSlotInPosition(e.canvasX,e.canvasY);t&&this.showSlotContextMenu(t,e)}}renameSlot(e,t){this.subgraph.renameOutput(e,t)}removeSlot(e){this.subgraph.removeOutput(e)}canConnectTo(e,t,n){return e.canConnectTo(this,t,n)}connectByTypeOutput(e,t,n,r){let i=t.findOutputByType(n);if(i)return this.slots[e].connect(i.slot,t,r?.afterRerouteId)}findInputByType(e){return findFreeSlotOfType(this.slots,e,e=>e.linkIds.length>0)?.slot}drawProtected(e,t,n,r){let{roundedRadius:i}=Qe,a=e.getTransform(),[o,s,,c]=this.boundingRect;e.translate(o,s),e.strokeStyle=this.sideStrokeStyle,e.lineWidth=this.sideLineWidth,e.beginPath(),e.arc(i,i,i,Math.PI,Math.PI*1.5),e.moveTo(0,i),e.lineTo(0,c-i),e.arc(i,c-i,i,Math.PI,Math.PI*.5,!0),e.stroke(),e.setTransform(a),this.drawSlots(e,t,n,r)}};function splitPositionables(e){let t=new Set,n=new Set,r=new Set,i=new Set,a=new Set,o=new Set;for(let s of e)switch(!0){case s instanceof Y:t.add(s);break;case s instanceof X:r.add(s);break;case s instanceof q:n.add(s);break;case s instanceof SubgraphInputNode:i.add(s);break;case s instanceof SubgraphOutputNode:a.add(s);break;default:o.add(s);break}return{nodes:t,reroutes:n,groups:r,subgraphInputNodes:i,subgraphOutputNodes:a,unknown:o}}function getBoundaryLinks(e,t){let n=[],r=[],i=[],a=[],o=[],s=new WeakSet;for(let o of t)if(!s.has(o)){if(s.add(o),o instanceof Y){let r=o;if(r.inputs)for(let a of r.inputs){if(addFloatingLinks(a._floatingLinks),a.link==null)continue;let r=K.resolve(a.link,e);if(!r){console.warn(`Failed to resolve link ID [${a.link}]`);continue}let{link:o,outputNode:s}=r;s?t.has(s)?n.push(o):i.push(o):o.origin_id===-10&&i.push(o)}if(r.outputs)for(let n of r.outputs){if(addFloatingLinks(n._floatingLinks),!n.links)continue;let r=K.resolveMany(n.links,e);for(let{link:e,inputNode:n}of r)(e.target_id===-20||n&&!t.has(n))&&a.push(e)}}else if(o instanceof q){let n=o,i=K.resolveMany(n.linkIds,e);for(let{link:n}of i){let i=K.getReroutes(e,n).filter(e=>!t.has(e)),{inputNode:a,outputNode:o}=n.resolve(e);(i.length||a&&!t.has(a)||o&&!t.has(o))&&r.push(n)}}}return{boundaryLinks:r,boundaryFloatingLinks:o,internalLinks:n,boundaryInputLinks:i,boundaryOutputLinks:a};function addFloatingLinks(n){if(n)for(let r of n)K.getReroutes(e,r).some(e=>!t.has(e))&&o.push(r)}}function multiClone(e){let t=[];for(let n of e){let e=Q.createNode(n.type);if(!e){console.warn(`Failed to create node`,n.type);let e=structuredClone(n.serialize());t.push(e);continue}let r=structuredClone(n.serialize());e.configure(r),t.push(e.serialize())}return t}function groupResolvedByOutput(e){let t=new Map;for(let n of e){let e=n.subgraphInput??n.output??{},r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function mapReroutes(e,t){let n=e,r=n.parentId===void 0?void 0:t.get(n.parentId);for(;n.parentId!==void 0&&r;)n=r,r=n.parentId===void 0?void 0:t.get(n.parentId);let i=n.parentId;return n.parentId=void 0,i}function mapSubgraphInputsAndLinks(e,t,n){let r=groupResolvedByOutput(e),i=[];for(let[,e]of r){let r=[];for(let a of e){let{link:e,input:o}=a;if(!o)continue;let s=e.asSerialisable();e.parentId=mapReroutes(e,n),s.origin_id=-10,s.origin_slot=i.length,t.push(s),r.push(s)}
2let{input:a}=e[0];if(!a)continue;let{color_off:o,color_on:s,dir:c,hasErrors:l,label:u,localized_name:d,name:f,shape:p,type:m}=a,h=nextUniqueName(f,i.map(e=>e.name)),g=d?nextUniqueName(d,i.map(e=>e.localized_name??``)):void 0,_={id:createUuidv4(),type:String(m),linkIds:r.map(e=>e.id),name:h,color_off:o,color_on:s,dir:c,label:u,localized_name:g,hasErrors:l,shape:p};i.push(_)}return i}function mapSubgraphOutputsAndLinks(e,t,n){let r=groupResolvedByOutput(e),i=[];for(let[,e]of r){let r=[];for(let a of e){let{link:e,output:o}=a;if(!o)continue;let s=e.asSerialisable();s.parentId=mapReroutes(e,n),s.target_id=-20,s.target_slot=i.length,t.push(s),r.push(s)}let{output:a}=e[0];if(!a)continue;let{color_off:o,color_on:s,dir:c,hasErrors:l,label:u,localized_name:d,name:f,shape:p,type:m}=a,h=nextUniqueName(f,i.map(e=>e.name)),g=d?nextUniqueName(d,i.map(e=>e.localized_name??``)):void 0,_={id:createUuidv4(),type:String(m),linkIds:r.map(e=>e.id),name:h,color_off:o,color_on:s,dir:c,label:u,localized_name:g,hasErrors:l,shape:p};i.push(structuredClone(_))}return i}function getDirectSubgraphIds(e){let t=new Set;for(let n of e._nodes)n.isSubgraphNode()&&t.add(n.type);return t}function findUsedSubgraphIds(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=getDirectSubgraphIds(r.shift());for(let i of e)if(!n.has(i)){n.add(i);let e=t.get(i);e&&r.push(e)}}return n}function isSubgraphInput(e){return typeof e==`object`&&!!e&&`parent`in e&&e.parent instanceof SubgraphInputNode}function isSubgraphOutput(e){return typeof e==`object`&&!!e&&`parent`in e&&e.parent instanceof SubgraphOutputNode}function isNodeSlot(e){return typeof e==`object`&&!!e&&(`link`in e||`links`in e)}var NodeInputSlot=class extends NodeSlot{link;alwaysVisible;get isWidgetInputSlot(){return!!this.widget}_widgetRef;get _widget(){return this._widgetRef?.deref()}set _widget(e){this._widgetRef=e?new WeakRef(e):void 0}get collapsedPos(){return[0,Q.NODE_TITLE_HEIGHT*-.5]}constructor(e,t){super(e,t),this.link=e.link}get isConnected(){return this.link!=null}isValidTarget(e){return`links`in e||isSubgraphInput(e)?Q.isValidConnection(e.type,this.type):!1}draw(e,t){let{textAlign:n}=e;e.textAlign=`left`,super.draw(e,{...t,labelPosition:qe.Right,doStroke:!1}),e.textAlign=n}toJSON(){return{...super.toJSON(),link:this.link,widget:this.widget}}},NodeOutputSlot=class extends NodeSlot{links;_data;slot_index;get isWidgetInputSlot(){return!1}get collapsedPos(){return[this._node._collapsed_width??Q.NODE_COLLAPSED_WIDTH,Q.NODE_TITLE_HEIGHT*-.5]}constructor(e,t){super(e,t),this.links=e.links,this._data=e._data,this.slot_index=e.slot_index}isValidTarget(e){return`link`in e||isSubgraphOutput(e)?Q.isValidConnection(this.type,e.type):!1}get isConnected(){return this.links!=null&&this.links.length>0}draw(e,t){let{textAlign:n,strokeStyle:r}=e;e.textAlign=`right`,e.strokeStyle=`black`,super.draw(e,{...t,labelPosition:qe.Left,doStroke:!0}),e.textAlign=n,e.strokeStyle=r}toJSON(){return{...super.toJSON(),links:this.links,slot_index:this.slot_index}}},$e=1e4,et=new Set;function warnDeprecated(e,t){if(!Q.alwaysRepeatWarnings){if(et.has(e)||et.size>$e)return;et.add(e)}for(let n of Q.onDeprecationWarning)n(e,t)}function defineDeprecatedProperty(e,t,n,r){Object.defineProperty(e,t,{get(){return warnDeprecated(r),this[n]},set(e){warnDeprecated(r),this[n]=e},configurable:!0,enumerable:!1})}function distributeSpace(e,t){if(t.length===0)return[];let n=t.reduce((e,t)=>e+t.minSize,0);if(e<n)return t.map(e=>e.minSize);let r=t.map(e=>({computedSize:e.minSize,maxSize:e.maxSize??1/0,remaining:(e.maxSize??1/0)-e.minSize})),i=e-n;for(;i>0&&r.some(e=>e.remaining>0);){let e=r.filter(e=>e.remaining>0).length;if(e===0)break;let t=i/e,n=0;if(r=r.map(e=>{if(e.remaining<=0)return e;let r=Math.min(t,e.remaining);return n+=r,{...e,computedSize:e.computedSize+r,remaining:e.remaining-r}}),i-=n,n===0)break}return r.map(({computedSize:e})=>e)}function truncateText(e,t,n,r=`...`){if(cachedMeasureText(e,t)<=n||n<=0)return t;let i=n-cachedMeasureText(e,r);if(i<=0)return r;let a=0,o=t.length,s=0;for(;a<=o;){let n=Math.floor((a+o)/2);cachedMeasureText(e,t.substring(0,n))<=i?(s=n,a=n+1):o=n-1}return t.substring(0,s)+r}var J=class BaseWidget{static margin=15;static arrowMargin=6;static arrowWidth=10;static minValueWidth=42;static labelValueGap=5;_node;get node(){return this._node}linkedWidgets;name;options;type;y=0;last_y;width;computedDisabled;tooltip;_state;get label(){return this._state.label}set label(e){this._state.label=e}hidden;advanced;get disabled(){return this._state.disabled}set disabled(e){this._state.disabled=e??!1}element;get value(){return this._state.value}set value(e){this._state.value=e}setNodeId(e){let t=this.node.graph?.rootGraph.id;t&&(this._state=Pe().registerWidget(t,{...this._state,value:this.value,
2nodeId:e}))}constructor(e,t){this._node=t??e.node,this.name=e.name,this.options=e.options,this.type=e.type;let{node:n,outline_color:r,background_color:i,height:a,text_color:o,secondary_text_color:s,disabledTextColor:c,displayName:l,displayValue:u,labelBaseline:d,label:f,disabled:p,value:m,linkedWidgets:h,...g}=e;Object.assign(this,g),this._state={name:this.name,type:this.type,value:m,label:f,disabled:p??!1,serialize:this.serialize,options:this.options}}getOutlineColor(e=!1){let t=this.node.graph?.rootGraph.id;return t&&!e&&W().isPromotedByAny(t,{sourceNodeId:String(this.node.id),sourceWidgetName:this.name})?Q.WIDGET_PROMOTED_OUTLINE_COLOR:this.advanced?Q.WIDGET_ADVANCED_OUTLINE_COLOR:Q.WIDGET_OUTLINE_COLOR}get outline_color(){return this.getOutlineColor()}get background_color(){return Q.WIDGET_BGCOLOR}get height(){return Q.NODE_WIDGET_HEIGHT}get text_color(){return Q.WIDGET_TEXT_COLOR}get secondary_text_color(){return Q.WIDGET_SECONDARY_TEXT_COLOR}get disabledTextColor(){return Q.WIDGET_DISABLED_TEXT_COLOR}get displayName(){return this.label||this.name}get _displayValue(){return this.computedDisabled?``:String(this.value)}get labelBaseline(){return this.y+this.height*.7}drawWidgetShape(e,{width:t,showText:n,suppressPromotedOutline:r}){let{height:i,y:a}=this,{margin:o}=BaseWidget;e.textAlign=`left`,e.strokeStyle=this.getOutlineColor(r),e.fillStyle=this.background_color,e.beginPath(),n?e.roundRect(o,a,t-o*2,i,[i*.5]):e.rect(o,a,t-o*2,i),e.fill(),n&&!this.computedDisabled&&e.stroke()}drawVueOnlyWarning(e,{width:t,suppressPromotedOutline:n},r){let{y:i,height:a}=this;e.save(),e.fillStyle=this.background_color,e.fillRect(15,i,t-30,a),e.strokeStyle=this.getOutlineColor(n),e.strokeRect(15,i,t-30,a),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${r}: ${he(`widgets.node2only`)}`,t/2,i+a/2),e.restore()}drawTruncatingText({ctx:e,width:t,leftPadding:n=5,rightPadding:r=20}){let{height:i,y:a}=this,{margin:o}=BaseWidget,{displayName:s,_displayValue:c}=this,l=cachedMeasureText(e,s),u=cachedMeasureText(e,c),d=BaseWidget.labelValueGap,f=o*2+n,p=t-f-2*o-r,m=l+d+u,h=new G(f,a,p,i*.7);if(e.fillStyle=this.secondary_text_color,m<=p)drawTextInArea({ctx:e,text:s,area:h,align:`left`});else if(Q.truncateWidgetTextEvenly){let t=(p-d)/(m-d);h.width=l*t,drawTextInArea({ctx:e,text:s,area:h,align:`left`}),h.right=f+p,h.setWidthRightAnchored(u*t)}else if(Q.truncateWidgetValuesFirst){let t=Math.min(l,p);h.width=t,drawTextInArea({ctx:e,text:s,area:h,align:`left`}),h.right=f+p,h.setWidthRightAnchored(Math.max(p-d-t,0))}else{let t=Math.min(u,p);h.width=Math.max(p-d-t,0),drawTextInArea({ctx:e,text:s,area:h,align:`left`}),h.right=f+p,h.setWidthRightAnchored(t)}e.fillStyle=this.text_color,drawTextInArea({ctx:e,text:c,area:h,align:`right`})}setValue(e,{e:t,node:n,canvas:r}){let i=this.value;if(e===this.value)return;let a=this.type===`number`?Number(e):e;this.value=a,this.options?.property&&n.properties[this.options.property]!==void 0&&n.setProperty(this.options.property,a);let o=r.graph_mouse;this.callback?.(this.value,r,n,o,t),n.onWidgetChanged?.(this.name??``,a,i,this),n.graph&&n.graph.incrementVersion()}createCopyForNode(e){let t=new this.constructor(this,e);return t.value=this.value,t}},AssetWidget=class extends J{constructor(e,t){super(e,t),this.type??=`asset`,this.value=e.value?.toString()??``}set value(e){let t=this.value;if(super.value=e,t!==e&&this.node.graph?.list_of_graphcanvas)for(let e of this.node.graph.list_of_graphcanvas)e.setDirty(!0)}get value(){return super.value}get _displayValue(){return String(this.value)}drawWidget(e,t){let{width:n,showText:r=!0}=t,{fillStyle:i,strokeStyle:a,textAlign:o}=e;this.drawWidgetShape(e,t),r&&this.drawTruncatingText({ctx:e,width:n,leftPadding:0,rightPadding:0}),Object.assign(e,{textAlign:o,strokeStyle:a,fillStyle:i})}onClick(){this.options.openModal(this)}},BooleanWidget=class extends J{type=`toggle`;drawWidget(e,t){let{width:n,showText:r=!0}=t,{height:i,y:a}=this,{margin:o}=J;this.drawWidgetShape(e,t),e.fillStyle=this.value?`#89A`:`#333`,e.beginPath(),e.arc(n-o*2,a+i*.5,i*.36,0,Math.PI*2),e.fill(),r&&(this.drawLabel(e,o*2),this.drawValue(e,n-40))}drawLabel(e,t){e.fillStyle=this.secondary_text_color;let{displayName:n}=this;n&&e.fillText(n,t,this.labelBaseline)}drawValue(e,t){e.fillStyle=this.value?this.text_color:this.secondary_text_color,e.textAlign=`right`;let n=this.value?this.options.on||`true`:this.options.off||`false`;e.fillText(n,t,this.labelBaseline)}onClick(e){this.setValue(!this.value,e)}},BoundingBoxWidget=class extends J{type=`boundingbox`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`BoundingBox`)}onClick(e){}},ButtonWidget=class extends J{type=`button`;clicked;constructor(e,t){super(e,t),this.clicked??=!1}drawWidget(e,{width:t,showText:n=!0,suppressPromotedOutline:r}){let{fillStyle:i,strokeStyle:a,textAlign:o}=e,{height:s,y:c}=this,{margin:l}=J;e.fillStyle=this.background_color,this.clicked&&=(e.fillStyle=`#AAA`,!1),e.fillRect(l,c,t-l*2,s),n&&!this.computedDisabled&&(e.strokeStyle=this.getOutlineColor(r),e.strokeRect(l,c,t-l*2,s)),n&&this.drawLabel(e,t*.5),Ob
2ject.assign(e,{textAlign:o,strokeStyle:a,fillStyle:i})}drawLabel(e,t){e.textAlign=`center`,e.fillStyle=this.text_color,e.fillText(this.displayName,t,this.y+this.height*.7)}onClick({e,node:t,canvas:n}){let r=n.graph_mouse;this.clicked=!0,n.setDirty(!0),this.callback?.(this.value,n,t,r,e)}},ChartWidget=class extends J{type=`chart`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`Chart: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},tt=null;function getColorInput(){return tt||(tt=document.createElement(`input`),tt.type=`color`,tt.style.position=`absolute`,tt.style.opacity=`0`,tt.style.pointerEvents=`none`,tt.style.zIndex=`-999`,document.body.appendChild(tt)),tt}var ColorWidget=class extends J{type=`color`;drawWidget(e,t){let{fillStyle:n,strokeStyle:r,textAlign:i}=e;this.drawWidgetShape(e,t);let{width:a}=t,{height:o,y:s}=this,{margin:c}=J,l=o-6,u=l/2,d=a-c-10-40,f=s+3;e.beginPath(),e.roundRect(d,f,40,l,u),e.fillStyle=this.value||`#000000`,e.fill(),e.fillStyle=this.secondary_text_color,e.textAlign=`left`,e.fillText(this.displayName,c*2+5,s+o*.7),e.fillStyle=this.text_color,e.textAlign=`right`,e.fillText(this.value||`#000000`,d-8,s+o*.7),Object.assign(e,{textAlign:i,strokeStyle:r,fillStyle:n})}onClick({e,node:t,canvas:n}){let r=getColorInput();r.value=this.value||`#000000`,r.style.left=`${e.clientX}px`,r.style.top=`${e.clientY}px`,r.addEventListener(`change`,()=>{this.setValue(r.value,{e,node:t,canvas:n}),n.setDirty(!0)},{once:!0}),requestAnimationFrame(()=>r.click())}},BaseSteppedWidget=class extends J{drawArrowButtons(e,t){let{height:n,text_color:r,disabledTextColor:i,y:a}=this,{arrowMargin:o,arrowWidth:s,margin:c}=J,l=c+o,u=l+s;e.fillStyle=this.canDecrement()?r:i,e.beginPath(),e.moveTo(u,a+5),e.lineTo(l,a+n*.5),e.lineTo(u,a+n-5),e.fill(),e.fillStyle=this.canIncrement()?r:i,e.beginPath(),e.moveTo(t-u,a+5),e.lineTo(t-l,a+n*.5),e.lineTo(t-u,a+n-5),e.fill()}drawWidget(e,t){let{fillStyle:n,strokeStyle:r,textAlign:i}=e;this.drawWidgetShape(e,t),t.showText&&(this.computedDisabled||this.drawArrowButtons(e,t.width),this.drawTruncatingText({ctx:e,width:t.width})),Object.assign(e,{textAlign:i,strokeStyle:r,fillStyle:n})}};function toArray(e){return Array.isArray(e)?e:Object.keys(e)}var ComboWidget=class extends BaseSteppedWidget{type=`combo`;get _displayValue(){if(this.computedDisabled)return``;let e=this.options.getOptionLabel;if(e)try{return e(this.value?String(this.value):null)}catch(e){return console.error(`Failed to map value:`,e),this.value?String(this.value):``}let{values:t}=this.options;if(t){let e=typeof t==`function`?t():t;if(e&&!Array.isArray(e))return e[this.value]}return typeof this.value==`number`?String(this.value):this.value}getValues(e){let{values:t}=this.options;if(t==null)throw Error(`[ComboWidget]: values is required`);return typeof t==`function`?t(this,e):t}canUseButton(e){let{values:t}=this.options;if(typeof t==`function`)return!1;let n=toArray(t);if(!(n.length>1))return!1;let r=n.at(0),i=n.at(-1);return r===i?!0:this.value!==(e?i:r)}canIncrement(){return this.canUseButton(!0)}canDecrement(){return this.canUseButton(!1)}incrementValue(e){this.tryChangeValue(1,e)}decrementValue(e){this.tryChangeValue(-1,e)}tryChangeValue(e,t){let n=this.getValues(t.node),r=toArray(n);t.canvas.last_mouseclick=0;let i=h(typeof n==`object`?r.indexOf(String(this.value))+e:r.indexOf(this.value)+e,0,r.length-1),a=Array.isArray(n)?n[i]:i;this.setValue(a,t)}onClick({e,node:t,canvas:n}){let r=e.canvasX-t.pos[0],i=this.width||t.size[0];if(typeof this.options.values==`function`&&warnDeprecated(`Using a function for values is deprecated. Use an array of unique values instead.`),r<40)return this.decrementValue({e,node:t,canvas:n});if(r>i-40)return this.incrementValue({e,node:t,canvas:n});let a=this.getValues(t),o=toArray(a);if(this.options.getOptionLabel){let r={scale:Math.max(1,n.ds.scale),event:e,className:`dark`,callback:r=>{this.setValue(r,{e,node:t,canvas:n})}},i=new Q.ContextMenu([],r),a=this.options.getOptionLabel;
2for(let e of o)try{let t=a?a(String(e)):String(e);i.addItem(t,e,r)}catch(t){console.error(`Failed to map value:`,t),i.addItem(String(e),e,r)}return}let s=a==o?a:Object.values(a);new Q.ContextMenu(s,{scale:Math.max(1,n.ds.scale),event:e,className:`dark`,callback:r=>{this.setValue(a==o?r:s.indexOf(r),{e,node:t,canvas:n})}})}},CurveWidget=class extends J{type=`curve`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Curve`)}onClick(e){}},FileUploadWidget=class extends J{type=`fileupload`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`Fileupload: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},GalleriaWidget=class extends J{type=`galleria`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`Galleria: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},GradientSliderWidget=class extends J{type=`gradientslider`;drawWidget(e,{width:t,showText:n=!0}){e.save();let{height:r,y:i}=this,{margin:a}=J;e.fillStyle=this.background_color,e.fillRect(a,i,t-a*2,r);let o=this.options.max-this.options.min,s=(this.value-this.options.min)/o;if(s=h(s,0,1),e.fillStyle=`#678`,e.fillRect(a,i,s*(t-a*2),r),n&&!this.computedDisabled&&(e.strokeStyle=this.outline_color,e.strokeRect(a,i,t-a*2,r)),n){e.textAlign=`center`,e.fillStyle=this.text_color;let n=Number(this.value).toFixed(this.options.precision??3);e.fillText(`${this.label||this.name}  ${n}`,t*.5,i+r*.7)}e.restore()}onClick(e){if(this.options.read_only)return;let{e:t,node:n}=e,r=this.width||n.size[0],i=t.canvasX-n.pos[0],{margin:a}=J,o=h((i-a)/(r-a*2),0,1),s=this.options.min+(this.options.max-this.options.min)*o;s!==this.value&&this.setValue(s,e)}onDrag(e){if(this.options.read_only)return!1;let{e:t,node:n}=e,r=this.width||n.size[0],i=t.canvasX-n.pos[0],{margin:a}=J,o=h((i-a)/(r-a*2),0,1),s=this.options.min+(this.options.max-this.options.min)*o;s!==this.value&&this.setValue(s,e)}},ImageCompareWidget=class extends J{type=`imagecompare`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`ImageCompare: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},BoundingBoxesWidget=class extends J{type=`boundingboxes`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Bounding Boxes`)}onClick(e){}},ColorsWidget=class extends J{type=`colors`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Colors`)}onClick(e){}},PainterWidget=class extends J{type=`painter`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Painter`)}onClick(e){}},RangeWidget=class extends J{type=`range`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Range`)}onClick(e){}},ImageCropWidget=class extends J{type=`imagecrop`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`ImageCrop`)}onClick(e){}},KnobWidget=class extends J{type=`knob`;computeLayoutSize(){return{minHeight:60,minWidth:20,maxHeight:1e6,maxWidth:1e6}}get height(){return this.computedHeight||super.height}drawWidget(e,{width:t,showText:n=!0,suppressPromotedOutline:r}){let{fillStyle:i,strokeStyle:a,textAlign:o}=e,{y:s}=this,{margin:c}=J,{gradient_stops:l=`rgb(14, 182, 201); rgb(0, 216, 72)`}=this.options,u=this.computedHeight||this.height,d=Math.min(this.computedHeight||this.height,this.width||20)/20,f={x:t/2,y:u/2+s};e.lineWidth=(Math.min(t,u)-c*d)/6;let p=(Math.min(t,u)-c*d-e.lineWidth)/2;{let t=e.createRadialGradient(f.x,f.y,p+e.lineWidth,0,0,p+e.lineWidth);t.addColorStop(0,`rgb(29, 29, 29)`),t.addColorStop(1,`rgb(116, 116, 116)`),e.fillStyle=t}e.beginPath(),e.arc(f.x,f.y,p+e.lineWidth/2,0,Math.PI*2,!1),e.fill(),e.closePath();let m={start_angle:Math.PI*.6,end_angle:Math.PI*2.4};e.beginPath();{let t=e.createRadialGradient(f.x,f.y,p+e.lineWidth,0,0,p+e.lineWidth);t.addColorStop(0,`rgb(99, 99, 99)`),t.addColorStop(1,`rgb(36, 36, 36)`),e.strokeStyle=t}e.arc(f.x,f.y,p,m.start_angle,m.end_angle,!1),e.stroke(),e.closePath();let g=this.options.max-this.options.min,_=(this.value-this.options.min)/g;_=h(_,0,1),e.beginPath();let v=e.createConicGradient(m.start_angle,f.x,f.y),y=l.split(`;`);for(let[e,t]of y.entries())v.addColorStop(e,t.trim());e.strokeStyle=v;let ee=(m.end_angle-m.start_angle)*_+m.start_angle;if(e.arc(f.x,f.y,p,m.start_angle,ee,!1),e.stroke(),e.closePath(),n&&!this.computedDisabled&&(e.strokeStyle=this.getOutlineColor(r),e.beginPath(),e.strokeStyle=this.getOutlineColor(r),e.arc(f.x,f.y,p+e.lineWidth/2,0,Math.PI*2,!1),e.lineWidth=1,e.stroke(),e.closePath()),n){e.textAlign=`center`,e.fillStyle=this.text_color;let n=Number(this.value).toFixed(this.options.precision??3);e.fillText(`${this.label||this.name}\n${n}`,t*.5,s+u*.5)}Object.assign(e,{textAlign:o,strokeStyle:a,fillStyle:i})}onClick(){this.current_drag_offset=0}current_drag_offset=0;onDrag(e){if(this.options.read_only)return;let{e:t}=e,n=ge(this.options),r=this.options.max-this.options.min,i=r/10,a=r/100,o={delta_x:n,shift:i>n?i-i%n:n,delta_y:a>n?a-a%n:n},s=Math.abs(t.movementY)>Math.abs(t.movementX),c=s?-t.movementY:t.movementX;this.current_drag_offset+=c;let l=0;this.current_drag_offset>15?(l+=1,this.current_drag_offset-=15):this.current_drag_offset<-15&&
2(--l,this.current_drag_offset+=15);let u=t.shiftKey?o.shift:s?o.delta_y:n,d=l*u,f=h(this.value+d,this.options.min,this.options.max);f!==this.value&&this.setValue(f,e)}},LegacyWidget=class extends J{drawWidget(e,t){let n=Q.NODE_WIDGET_HEIGHT;this.draw?.(e,this.node,t.width,this.y,n,!!t.showText)}onClick(){console.warn(`Custom widget wrapper onClick was just called. Handling for third party widgets is done via LGraphCanvas - the mouse callback.`)}},MarkdownWidget=class extends J{type=`markdown`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`Markdown: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},MultiSelectWidget=class extends J{type=`multiselect`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`MultiSelect: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},NumberWidget=class extends BaseSteppedWidget{type=`number`;get _displayValue(){return this.computedDisabled?``:Number(this.value).toFixed(this.options.precision===void 0?3:this.options.precision)}canIncrement(){let{max:e}=this.options;return e==null||this.value<e}canDecrement(){let{min:e}=this.options;return e==null||this.value>e}incrementValue(e){this.setValue(this.value+ge(this.options),e)}decrementValue(e){this.setValue(this.value-ge(this.options),e)}setValue(e,t){let n=e;this.options.min!=null&&n<this.options.min&&(n=this.options.min),this.options.max!=null&&n>this.options.max&&(n=this.options.max),super.setValue(n,t)}onClick({e,node:t,canvas:n}){let r=e.canvasX-t.pos[0],i=this.width||t.size[0],a=r<40?-1:r>i-40?1:0;if(a){this.setValue(this.value+a*ge(this.options),{e,node:t,canvas:n});return}n.prompt(`Value`,this.value,r=>{let i=_e(r);i!==void 0&&this.setValue(i,{e,node:t,canvas:n})},e)}onDrag({e,node:t,canvas:n}){let r=this.width||t.width,i=e.canvasX-t.pos[0];(i<40||i>r-40)&&i>-3&&i<r+3||this.setValue(this.value+(e.deltaX??0)*ge(this.options),{e,node:t,canvas:n})}},SelectButtonWidget=class extends J{type=`selectbutton`;drawWidget(e,t){let{width:n}=t,{y:r,height:i}=this,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l}=e;e.fillStyle=this.background_color,e.fillRect(15,r,n-30,i),e.strokeStyle=this.getOutlineColor(t.suppressPromotedOutline),e.strokeRect(15,r,n-30,i),e.fillStyle=this.text_color,e.font=`11px monospace`,e.textAlign=`center`,e.textBaseline=`middle`;let u=`SelectButton: ${he(`widgets.node2only`)}`;e.fillText(u,n/2,r+i/2),Object.assign(e,{fillStyle:a,strokeStyle:o,textAlign:s,textBaseline:c,font:l})}onClick(e){}},SliderWidget=class extends J{type=`slider`;marker;drawWidget(e,{width:t,showText:n=!0,suppressPromotedOutline:r}){let{fillStyle:i,strokeStyle:a,textAlign:o}=e,{height:s,y:c}=this,{margin:l}=J;e.fillStyle=this.background_color,e.fillRect(l,c,t-l*2,s);let u=this.options.max-this.options.min,d=(this.value-this.options.min)/u;if(d=h(d,0,1),e.fillStyle=this.options.slider_color??`#678`,e.fillRect(l,c,d*(t-l*2),s),n&&!this.computedDisabled&&(e.strokeStyle=this.getOutlineColor(r),e.strokeRect(l,c,t-l*2,s)),this.marker!=null){let n=(this.marker-this.options.min)/u;n=h(n,0,1),e.fillStyle=this.options.marker_color??`#AA9`,e.fillRect(l+n*(t-l*2),c,2,s)}if(n){e.textAlign=`center`,e.fillStyle=this.text_color;let n=Number(this.value).toFixed(this.options.precision??3);e.fillText(`${this.label||this.name}  ${n}`,t*.5,c+s*.7)}Object.assign(e,{textAlign:o,strokeStyle:a,fillStyle:i})}onClick(e){if(this.options.read_only)return;let{e:t,node:n}=e,r=this.width||n.size[0],i=h((t.canvasX-n.pos[0]-15)/(r-30),0,1),a=this.options.min+(this.options.max-this.options.min)*i;a!==this.value&&this.setValue(a,e)}onDrag(e){if(this.options.read_only)return!1;let{e:t,node:n}=e,r=this.width||n.size[0],i=h((t.canvasX-n.pos[0]-15)/(r-30),0,1),a=this.options.min+(this.options.max-this.options.min)*i;a!==this.value&&this.setValue(a,e)}},TextWidget=class extends J{constructor(e,t){super(e,t),this.type??=`string`,this.value=e.value?.toString()??``}drawWidget(e,t){let{width:n,showText:r=!0}=t,{fillStyle:i,strokeStyle:a,textAlign:o}=e;this.drawWidgetShape(e,t),r&&this.drawTruncatingText({ctx:e,width:n,leftPadding:0,r
2ightPadding:0}),Object.assign(e,{textAlign:o,strokeStyle:a,fillStyle:i})}onClick({e,node:t,canvas:n}){n.prompt(`Value`,this.value,r=>{r!==null&&this.setValue(r,{e,node:t,canvas:n})},e,this.options?.multiline??!1)}},TextareaWidget=class extends J{type=`textarea`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`Textarea`)}onClick(e){}},TreeSelectWidget=class extends J{type=`treeselect`;drawWidget(e,t){this.drawVueOnlyWarning(e,t,`TreeSelect`)}onClick(e){}};function toConcreteWidget(e,t,n=!0){if(e instanceof J)return e;let r=e;switch(r.type){case`button`:return toClass(ButtonWidget,r,t);case`toggle`:return toClass(BooleanWidget,r,t);case`slider`:return toClass(SliderWidget,r,t);case`gradientslider`:return toClass(GradientSliderWidget,r,t);case`knob`:return toClass(KnobWidget,r,t);case`combo`:return toClass(ComboWidget,r,t);case`number`:return toClass(NumberWidget,r,t);case`string`:return toClass(TextWidget,r,t);case`text`:return toClass(TextWidget,r,t);case`fileupload`:return toClass(FileUploadWidget,r,t);case`color`:return toClass(ColorWidget,r,t);case`markdown`:return toClass(MarkdownWidget,r,t);case`treeselect`:return toClass(TreeSelectWidget,r,t);case`multiselect`:return toClass(MultiSelectWidget,r,t);case`chart`:return toClass(ChartWidget,r,t);case`galleria`:return toClass(GalleriaWidget,r,t);case`imagecompare`:return toClass(ImageCompareWidget,r,t);case`selectbutton`:return toClass(SelectButtonWidget,r,t);case`textarea`:return toClass(TextareaWidget,r,t);case`asset`:return toClass(AssetWidget,r,t);case`imagecrop`:return toClass(ImageCropWidget,r,t);case`boundingbox`:return toClass(BoundingBoxWidget,r,t);case`curve`:return toClass(CurveWidget,r,t);case`painter`:return toClass(PainterWidget,r,t);case`range`:return toClass(RangeWidget,r,t);case`boundingboxes`:return toClass(BoundingBoxesWidget,r,t);case`colors`:return toClass(ColorsWidget,r,t);default:if(n)return toClass(LegacyWidget,e,t)}}function isComboWidget(e){return e.type===`combo`}var Y=class LGraphNode{static title;static MAX_CONSOLE;static type;static category;static description;static filter;static skip_list;static nodeData;static resizeHandleSize=15;static resizeEdgeSize=5;static keepAllLinksOnBypass=!1;title;get titleFontStyle(){return`${Q.NODE_TEXT_SIZE}px ${Q.NODE_FONT}`}get innerFontStyle(){return`normal ${Q.NODE_SUBTEXT_SIZE}px ${Q.NODE_FONT}`}get displayType(){return this.type}graph=null;id;type=``;inputs=[];outputs=[];_concreteInputs=[];_concreteOutputs=[];properties={};properties_info=[];flags={};widgets;changeTracker;freeWidgetSpace;_widgetSlotsDirty=!1;locked;order=0;mode=B.ALWAYS;last_serialization;serialize_widgets;color;bgcolor;boxcolor;get renderingColor(){return me(this.color||this.constructor.color||Q.NODE_DEFAULT_COLOR,{lightness:Q.nodeLightness})}get renderingBgColor(){let e=this.bgcolor||this.constructor.bgcolor||Q.NODE_DEFAULT_BGCOLOR,t={opacity:Q.nodeOpacity,lightness:Q.nodeLightness};return me(this.mode===B.BYPASS?Q.NODE_DEFAULT_BYPASS_COLOR:e,t)}get renderingBoxColor(){if(this.boxcolor)return this.boxcolor;if(Q.node_box_coloured_when_on){if(this.action_triggered)return`#FFF`;if(this.execute_triggered)return`#AAA`}if(Q.node_box_coloured_by_mode){let e=Q.NODE_MODES_COLORS[this.mode??B.ALWAYS];if(e)return e}return Q.NODE_DEFAULT_BOXCOLOR}setColorOption(e){e==null?(this.color=void 0,this.bgcolor=void 0):(this.color=e.color,this.bgcolor=e.bgcolor)}getColorOption(){return Object.values(Z.node_colors).find(e=>e.color===this.color&&e.bgcolor===this.bgcolor)??null}strokeStyles;progress;exec_version;action_call;execute_triggered;action_triggered;widgets_up;widgets_start_y;lostFocusAt;gotFocusAt;badges=[];title_buttons=[];badgePosition=ze.TopLeft;_collapsed_width;console;_level;_shape;mouseOver;redraw_on_mouse;resizable;clonable;_relative_id;clip_area;ignore_remove;has_errors;removable;block_delete;selected;showAdvanced;isSubgraphNode(){return!1}_renderArea=new G;get renderArea(){return this._renderArea}_boundingRect=new G;get boundingRect(){return this._boundingRect}get boundingOffset(){let{pos:[e,t],boundingRect:[n,r]}=this;return[e-n,t-r]}_posSize=new G;_pos=this._posSize.pos;_size=this._posSize.size;get pos(){return this._pos}set pos(e){if(!e||e.length<2)return;this._pos[0]=e[0],this._pos[1]=e[1];let t=useLayoutMutations();
2t.setSource(H.Canvas),t.moveNode(String(this.id),{x:e[0],y:e[1]})}setPos(e,t){this.pos=[e,t]}get size(){return this._size}set size(e){if(!e||e.length<2)return;this._size[0]=e[0],this._size[1]=e[1];let t=useLayoutMutations();t.setSource(H.Canvas),t.resizeNode(String(this.id),{width:e[0],height:e[1]})}get renderingSize(){return this.flags.collapsed?[this._collapsed_width??0,0]:this._size}get shape(){return this._shape}set shape(e){let t=this._shape;switch(e){case`default`:this._shape=void 0;break;case`box`:this._shape=P.BOX;break;case`round`:this._shape=P.ROUND;break;case`circle`:this._shape=P.CIRCLE;break;case`card`:this._shape=P.CARD;break;default:this._shape=e}t!==this._shape&&this.graph?.trigger(`node:property:changed`,{nodeId:this.id,property:`shape`,oldValue:t,newValue:this._shape})}get renderingShape(){return this._shape||this.constructor.shape||Q.NODE_DEFAULT_SHAPE}get is_selected(){return this.selected}set is_selected(e){this.selected=e}get title_mode(){return this.constructor.title_mode??z.NORMAL_TITLE}_getErrorStrokeStyle(){if(this.has_errors)return{padding:12,lineWidth:10,color:Q.NODE_ERROR_COLOUR}}_getSelectedStrokeStyle(){if(this.selected)return{padding:this.has_errors?20:void 0}}constructor(e,t){this.id=Q.use_uuids?Q.uuidv4():-1,this.title=e||`Unnamed`,this.type=t??``,this.size=[Q.NODE_WIDTH,60],this.pos=[10,10],this.strokeStyles={error:this._getErrorStrokeStyle,selected:this._getSelectedStrokeStyle},this.changeTracker=new LGraphNodeProperties(this)}configure(e){this.graph&&this.graph.incrementVersion(),e.id===-1&&(e.id=this.id);for(let t in e){if(t==`properties`){for(let t in e.properties)this.properties[t]=e.properties[t],this.onPropertyChanged?.(t,e.properties[t]);continue}e[t]!=null&&(typeof e[t]==`object`?this[t]?.configure?this[t]?.configure(e[t]):this[t]=Q.cloneObject(e[t],this[t]):this[t]=e[t])}e.title||(this.title=this.constructor.title),this.inputs??=[],this.inputs=this.inputs.map(e=>toClass(NodeInputSlot,e,this));for(let[e,t]of this.inputs.entries()){let n=this.graph&&t.link!=null?this.graph._links.get(t.link):null;this.onConnectionsChange?.(N.INPUT,e,!0,n,t),this.onInputAdded?.(t)}this.outputs??=[],this.outputs=this.outputs.map(e=>toClass(NodeOutputSlot,e,this));for(let[e,t]of this.outputs.entries())if(t.links){for(let n of t.links){let r=this.graph?this.graph._links.get(n):null;this.onConnectionsChange?.(N.OUTPUT,e,!0,r,t)}this.onOutputAdded?.(t)}if(this._internalConfigureAfterSlots?.(),this.widgets){for(let e of this.widgets){if(!e)continue;let t=this.inputs.find(t=>t.widget?.name===e.name);t?.label&&(e.label=t.label),e.options?.property&&this.properties[e.options.property]!=null&&(e.value=JSON.parse(JSON.stringify(this.properties[e.options.property])))}if(e.widgets_values){let t=0;for(let n of this.widgets??[])if(n.serialize!==!1){if(t>=e.widgets_values.length)break;n.value=e.widgets_values[t++]}}}this.pinned&&(this.resizable=!1),this.widgets_up&&console.warn(`[LiteGraph] Node type "${this.type}" uses deprecated property "widgets_up". This property is unsupported and will be removed. Use "widgets_start_y" or a custom arrange() override instead.`),this.onConfigure?.(e)}
2serialize(){let e={id:this.id,type:this.type,pos:[this.pos[0],this.pos[1]],size:[this.size[0],this.size[1]],flags:Q.cloneObject(this.flags),order:this.order,mode:this.mode,showAdvanced:this.showAdvanced};if(this.constructor===LGraphNode&&this.last_serialization)return{...this.last_serialization,mode:e.mode,pos:e.pos};this.inputs&&(e.inputs=this.inputs.map(e=>inputAsSerialisable(e))),this.outputs&&(e.outputs=this.outputs.map(e=>outputAsSerialisable(e))),this.title&&this.title!=this.constructor.title&&(e.title=this.title),this.properties&&(e.properties=Q.cloneObject(this.properties));let{widgets:t}=this;if(t&&this.serialize_widgets){e.widgets_values=[];for(let[n,r]of t.entries()){if(r.serialize===!1)continue;let t=r?.value;e.widgets_values[n]=typeof t==`object`&&t?JSON.parse(JSON.stringify(t)):t??null}}return!e.type&&this.constructor.type&&(e.type=this.constructor.type),this.color&&(e.color=this.color),this.bgcolor&&(e.bgcolor=this.bgcolor),this.boxcolor&&(e.boxcolor=this.boxcolor),this.shape&&(e.shape=this.shape),this.onSerialize?.(e)&&console.warn(`node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter`),e}clone(){if(this.type==null)return null;let e=Q.createNode(this.type);if(!e)return null;let t=Q.cloneObject(this.serialize()),{inputs:n,outputs:r}=t;if(n)for(let e of n)e.link=null;if(r)for(let{links:e}of r)e&&(e.length=0);return t.id=void 0,Q.use_uuids&&(t.id=Q.uuidv4()),e.configure(t),e}toString(){return JSON.stringify(this.serialize())}getTitle(){return this.title||this.constructor.title}setProperty(e,t){if(this.properties||={},t===this.properties[e])return;let n=this.properties[e];if(this.properties[e]=t,this.onPropertyChanged?.(e,t,n)===!1&&(this.properties[e]=n),this.widgets){for(let n of this.widgets)if(n&&n.options.property==e){n.value=t;break}}}setOutputData(e,t){let{outputs:n}=this;if(!n||e==-1||e>=n.length)return;let r=n[e];if(!r)return;if(r._data=t,!this.graph)throw new NullGraphError;let{links:i}=n[e];if(i)for(let e of i){let n=this.graph._links.get(e);n&&(n.data=t)}}setOutputDataType(e,t){let{outputs:n}=this;if(!n||e==-1||e>=n.length)return;let r=n[e];if(!r)return;if(r.type=t,!this.graph)throw new NullGraphError;let{links:i}=n[e];if(i)for(let e of i){let n=this.graph._links.get(e);n&&(n.type=t)}}getInputData(e,t){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return;if(!this.graph)throw new NullGraphError;let n=this.inputs[e].link,r=this.graph._links.get(n);if(!r)return null;if(!t)return r.data;let i=this.graph.getNodeById(r.origin_id);return i&&(i.updateOutputData?i.updateOutputData(r.origin_slot):i.onExecute?.()),r.data}getInputDataType(e){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return null;if(!this.graph)throw new NullGraphError;let t=this.inputs[e].link,n=this.graph._links.get(t);if(!n)return null;let r=this.graph.getNodeById(n.origin_id);if(!r)return n.type;let i=r.outputs[n.origin_slot];return i?i.type:null}getInputDataByName(e,t){let n=this.findInputSlot(e);return n==-1?null:this.getInputData(n,t)}isInputConnected(e){return this.inputs?e<this.inputs.length&&this.inputs[e].link!=null:!1}getInputInfo(e){return!this.inputs||!(e<this.inputs.length)?null:this.inputs[e]}getInputLink(e){if(!this.inputs)return null;if(e<this.inputs.length){if(!this.graph)throw new NullGraphError;let t=this.inputs[e];if(t.link!=null)return this.graph._links.get(t.link)??null}return null}getInputNode(e){if(!this.inputs||e>=this.inputs.length)return null;let t=this.inputs[e];if(!t||t.link===null)return null;if(!this.graph)throw new NullGraphError;let n=this.graph._links.get(t.link);return n?this.graph.getNodeById(n.origin_id):null}getInputOrProperty(e){let{inputs:t}=this;if(!t?.length)return this.properties?this.properties[e]:null;if(!this.graph)throw new NullGraphError;for(let n of t)if(e==n.name&&n.link!=null){let e=this.graph._links.get(n.link);if(e)return e.data}return this.properties[e]}getOutputData(e){return!this.outputs||e>=this.outputs.length?null:this.outputs[e]._data}getOutputInfo(e){return!this.outputs||!(e<this.outputs.length)?null:this.outputs[e]}isOutputConnected(e){return this.outputs?e<this.outputs.length&&Number(this.outputs[e].links?.length)>0:!1}isAnyOutputConnected(){let{outputs:e}=this;if(!e)return!1;for(let t of e)if(t.links?.length)return!0;return!1}getOutputNodes(e){let{outputs:t}=this;if(!t||t.length==0||e>=t.length)return null;let{links:n}=t[e];if(!n||n.length==0)return null;if(!this.graph)throw new NullGraphError;let r=[];for(let e of n){let t=this.graph._links.get(e);if(t){let e=this.graph.getNodeById(t.target_id);e&&r.push(e)}}return r}addOnTriggerInput(){let e=this.findInputSlot(`onTrigger`);return e==-1?(this.addInput(`onTrigger`,Q.EVENT,{nameLocked:!0}),this.findInputSlot(`onTrigger`)):e}addOnExecutedOutput(){let e=this.findOutputSlot(`onExecuted`);return e==-1?(this.addOutput(`onExecuted`,Q.ACTION,{nameLocked:!0}),this.findOutputSlot(`onExecuted`)):e}onAfterExecuteNode(e,t){let n=this.findOutputSlot(`onExecuted`);n!=-1&&this.triggerSlot(n,e,null,t)}changeMode(e){switch(e){case B.ON_EVENT:break;case B.ON_TRIGGER:this.addOnTriggerInput(),this.addOnExecutedOutput();break;case B.NEVER:break;case B.ALWAYS:break;case Q.ON_REQUEST:break;default:return!1}return this.mode=e,!0}doExecute(e,t){if(t||={},this.onExecute){if(t.action_call||=`${this.id}_exec_${Math.floor(Math.random()*9999)}`,!this.graph)throw new NullGraphError;this.graph.nodes_executing[this.id]=!0,this.onExecute(e,t),this.graph.nodes_executing[this.id]=!1,this.exec_version=this.graph.iteration,t?.action_call&&(this.action_call=t.action_call,this.graph.nodes_executedAction[this.id]=t.action_call)}this.execute_triggered=2,this.onAfterExecuteNode?.(e,t)}actionDo(e,t,n){if(n||={},this.onAction){if(n.action_call||=`${this.id}_${e||`action`}_${Math.floor(Math.random()*9999)}`,!this.graph)throw new NullGraphError;this.graph.nodes_actioning[this.id]=e||`actioning`,this.onAction(e,t,n),this.graph.nodes_actioning[this.id]=!1,n?.action_call&&(this.action_call=n.action_call,this.graph.nodes_executedAction[this.id]=n.action_call)}this.action_triggered=2,this.onAfterExecuteNode?.(t,n)}trigger(e,t,n){let{outputs:r}=this;if(!(!r||!r.length)){this.graph&&(this.graph._last_trigger_time=Q.getTime());for(let[i,a]of r.entries())!a||a.type!==Q.EVENT||e&&a.name!=e||this.triggerSlot(i,t,null,n)}}triggerSlot(e,t,n,r){if(r||={},!this.outputs)return;if(e==null){console.error(`slot must be a number`);return}typeof e!=`number`&&console.warn(`slot must be a number, use node.trigger('name') if you want to use a string`);let i=this.outputs[e];if(!i)return;let a=i.links;
2if(!(!a||!a.length)){if(!this.graph)throw new NullGraphError;this.graph._last_trigger_time=Q.getTime();for(let e of a){if(n!=null&&n!=e)continue;let i=this.graph._links.get(e);if(!i)continue;i._last_time=Q.getTime();let a=this.graph.getNodeById(i.target_id);if(a){if(a.mode===B.ON_TRIGGER)r.action_call||=`${this.id}_trigg_${Math.floor(Math.random()*9999)}`,a.doExecute?.(t,r);else if(a.onAction){r.action_call||=`${this.id}_act_${Math.floor(Math.random()*9999)}`;let e=a.inputs[i.target_slot];a.actionDo(e.name,t,r)}}}}}clearTriggeredSlot(e,t){if(!this.outputs)return;let n=this.outputs[e];if(!n)return;let r=n.links;if(!(!r||!r.length)){if(!this.graph)throw new NullGraphError;for(let e of r){if(t!=null&&t!=e)continue;let n=this.graph._links.get(e);n&&(n._last_time=0)}}}setSize(e){this.size=e,this.onResize?.(this.size)}expandToFitContent(){let e=this.computeSize();this.setSize([Math.max(this.size[0],e[0]),Math.max(this.size[1],e[1])])}addProperty(e,t,n,r){let i={name:e,type:n,default_value:t};return r&&Object.assign(i,r),this.properties_info||=[],this.properties_info.push(i),this.properties||={},this.properties[e]=t,i}addOutput(e,t,n){let r=Object.assign(new NodeOutputSlot({name:e,type:t,links:null},this),n);return this.outputs||=[],this.outputs.push(r),this.onOutputAdded?.(r),Q.auto_load_slot_types&&Q.registerNodeAndSlotType(this,t,!0),this.expandToFitContent(),this.setDirtyCanvas(!0,!0),r}removeOutput(e){this.graph&&this.disconnectOutput(e);let{outputs:t}=this;t.splice(e,1);for(let n=e;n<t.length;++n){let e=t[n];if(!(!e||!e.links)&&this.graph)for(let t of e.links){let e=this.graph._links.get(t);e&&e.origin_slot--}}this.onOutputRemoved?.(e),this.setDirtyCanvas(!0,!0)}addInput(e,t,n){t||=0;let r=Object.assign(new NodeInputSlot({name:e,type:t,link:null},this),n);return this.inputs||=[],this.inputs.push(r),this.expandToFitContent(),this.onInputAdded?.(r),Q.registerNodeAndSlotType(this,t),this.setDirtyCanvas(!0,!0),r}removeInput(e){this.graph&&this.disconnectInput(e,!0);let{inputs:t}=this,n=t.splice(e,1);for(let n=e;n<t.length;++n){let e=t[n];if(e?.link&&this.graph){let t=this.graph._links.get(e.link);t&&t.target_slot--}}this.onInputRemoved?.(e,n[0]),this.setDirtyCanvas(!0,!0)}computeSize(e){let t=this.constructor.size;if(t)return[t[0],t[1]];let{inputs:n,outputs:r,widgets:i}=this,a=Math.max(n?n.filter(e=>!isWidgetInputSlot(e)).length:1,r?r.length:1),o=e??[0,0];a=Math.max(a,1);let s=Q.NODE_TEXT_SIZE,c=Q.NODE_TITLE_HEIGHT,l=c*.33,u=c+compute_text_size(this.title,this.titleFontStyle)+l,d=0,f=0,p=0;if(n)for(let e of n){let t=compute_text_size(e.label||e.localized_name||e.name||``,this.innerFontStyle);if(isWidgetInputSlot(e)){let n=this.getWidgetFromSlot(e);if(n&&!this.isWidgetVisible(n))continue;t>f&&(f=t)}else t>d&&(d=t)}if(r)for(let e of r){let t=compute_text_size(e.label||e.localized_name||e.name||``,this.innerFontStyle);p<t&&(p=t)}let m=Q.NODE_WIDTH*(i?.length?1.5:1),h=d&&p?5:0,g=d+p+2*Q.NODE_SLOT_HEIGHT+h,_=J.margin+J.arrowMargin+J.arrowWidth,v=J.minValueWidth+2*_;f&&(f+=v),o[0]=Math.max(g,f,u,m),o[1]=(this.constructor.slot_start_y||0)+a*Q.NODE_SLOT_HEIGHT;let y=0;if(i?.length){for(let e of i){if(!this.isWidgetVisible(e))continue;let t=0;if(e.computeSize)t+=e.computeSize(o[0])[1];else if(e.computeLayoutSize){let{minHeight:n,minWidth:r}=e.computeLayoutSize(this),i=r+v;i>o[0]&&(o[0]=i),t+=n}else t+=Q.NODE_WIDGET_HEIGHT;y+=t+4}y+=8}this.widgets_up?o[1]=Math.max(o[1],y):this.widgets_start_y==null?o[1]+=y:o[1]=Math.max(o[1],y+this.widgets_start_y);function compute_text_size(e,t){return Z._measureText?.(e,t)??s*(e?.length??0)*.6}return this.constructor.min_height&&o[1]<this.constructor.min_height&&(o[1]=this.constructor.min_height),o[1]+=6,o}inResizeCorner(e,t){let n=this.outputs?this.outputs.length:1,r=(this.constructor.slot_start_y||0)+n*Q.NODE_SLOT_HEIGHT;return isInRectangle(e,t,this.pos[0]+this.size[0]-15,this.pos[1]+Math.max(this.size[1]-15,r),20,20)}findResizeDirection(e,t){if(this.resizable===!1)return;let{boundingRect:n}=this;if(n.containsXy(e,t))return n.findContainingCorner(e,t,LGraphNode.resizeHandleSize)}getPropertyInfo(e){let t=null,{properties_info:n}=this;if(n){for(let r of n)if(r.name==e){t=r;break}}return this.constructor[`@${e}`]&&(t=this.constructor[`@${e}`]),this.constructor.widgets_info?.[e]&&(t=this.constructor.widgets_info[e]),!t&&this.onGetPropertyInfo&&(t=this.onGetPropertyInfo(e)),t||={},t.type||=typeof this.properties[e],t.widget==`combo`&&(t.type=`enum`),t}addWidget(e,t,n,r,i){this.widgets||=[],!i&&r&&typeof r==`object`&&(i=r,r=null),i||={},typeof i==`string`&&(i={property:i}),r&&typeof r==`string`&&(i.property=r,r=null);let a={type:e.toLowerCase(),name:t,value:n,callback:typeof r==`function`?r:void 0,options:i,y:0};if(a.options.y!==void 0&&(a.y=a.options.y),!r&&!a.options.callback&&!a.options.property&&console.warn(`LiteGraph addWidget(...) without a callback or property assigned`),e==`combo`&&!a.options.values)throw`LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }`;let o=this.addCustomWidget(a);return this.expandToFitContent(),o}addCustomWidget(e){this.widgets||=[];let t=toConcreteWidget(e,this,!1)??e;
2return this.widgets.push(t),this._widgetSlotsDirty=!0,this.id!==-1&&isNodeBindable(t)&&t.setNodeId(this.id),t}addTitleButton(e){this.title_buttons||=[];let t=new LGraphButton(e);return this.title_buttons.push(t),t}onTitleButtonClick(e,t){t.dispatch(`litegraph:node-title-button-clicked`,{node:this,button:e})}removeWidget(e){if(!this.widgets)throw Error(`removeWidget called on node without widgets`);let t=this.widgets.indexOf(e);if(t===-1)throw Error(`Widget not found on this node`);if(this.inputs)for(let t of this.inputs)t._widget===e&&(t._widget=void 0,t.widget=void 0,t.pos=void 0);this._widgetSlotsDirty=!0,e.onRemove?.(),this.widgets.splice(t,1)}ensureWidgetRemoved(e){try{this.removeWidget(e)}catch(e){console.error(`Failed to remove widget`,e)}}move(e,t){this.pinned||Q.vueNodesMode||(this.pos=[this._pos[0]+e,this._pos[1]+t])}measure(e,t){let n=this.title_mode,r=n!=z.TRANSPARENT_TITLE&&n!=z.NO_TITLE?Q.NODE_TITLE_HEIGHT:0;e[0]=this.pos[0],e[1]=this.pos[1]+-r,!this.flags?.collapsed||Q.vueNodesMode?(e[2]=this.size[0],e[3]=this.size[1]+r):(t&&(t.font=this.innerFontStyle),this._collapsed_width=Math.min(this.size[0],t?cachedMeasureText(t,this.getTitle()??``)+Q.NODE_TITLE_HEIGHT*2:0),e[2]=this._collapsed_width||Q.NODE_COLLAPSED_WIDTH,e[3]=Q.NODE_TITLE_HEIGHT)}getBounding(e,t){e||=[0,0,0,0];let n=t?this.renderArea:this.boundingRect;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e}updateArea(e){let t=this._boundingRect;this.measure(t,e),this.onBounding?.(t);let n=this._renderArea;n.set(t),n[0]-=4,n[1]-=4,n[2]+=10,n[3]+=9}isPointInside(e,t){if(isInRect(e,t,this.boundingRect))return!0;for(let n of this.badges.map(a).filter(e=>e.onClick))if(isInRect(e-this.pos[0],t-this.pos[1],n.boundingRect))return!0;return!1}isPointInCollapse(e,t){let n=Q.NODE_TITLE_HEIGHT;return isInRectangle(e,t,this.pos[0],this.pos[1]-n,n,n)}getInputOnPos(e){return getNodeInputOnPos(this,e[0],e[1])?.input}getOutputOnPos(e){return getNodeOutputOnPos(this,e[0],e[1])?.output}getSlotOnPos(e){if(isPointInRect(e,this.boundingRect))return this.getInputOnPos(e)??this.getOutputOnPos(e)}getSlotInPosition(e,t){let{inputs:n,outputs:r}=this;if(n)for(let[r,i]of n.entries()){let n=this.getInputPos(r);if(isInRectangle(e,t,n[0]-10,n[1]-10,20,20))return{input:i,slot:r,link_pos:n}}if(r)for(let[n,i]of r.entries()){let r=this.getOutputPos(n);if(isInRectangle(e,t,r[0]-10,r[1]-10,20,20))return{output:i,slot:n,link_pos:r}}return null}getWidgetOnPos(e,t,n=!1){let{widgets:r,pos:i,size:a}=this;if(!r?.length)return;let o=e-i[0],s=t-i[1],c=a[0];for(let e of r){if(e.computedDisabled&&!n||!this.isWidgetVisible(e))continue;let t=e.computedHeight??e.computeSize?.(c)[1]??Q.NODE_WIDGET_HEIGHT,r=e,i=r.margin??-2,a=r.margin??2,l=r.margin??6,u=e.width||c;if(e.last_y!==void 0&&isInRectangle(o,s,l,e.last_y+i,u-2*l,t-i-a))return e}}findInputSlot(e,t=!1){let{inputs:n}=this;if(!n)return-1;for(let[r,i]of n.entries())if(e==i.name)return t?i:r;return-1}findOutputSlot(e,t=!1){let{outputs:n}=this;if(!n)return-1;for(let[r,i]of n.entries())if(e==i.name)return t?i:r;return-1}findInputSlotFree(e){return this._findFreeSlot(this.inputs,e)}findOutputSlotFree(e){return this._findFreeSlot(this.outputs,e)}_findFreeSlot(e,t){let n=Object.assign({returnObj:!1,typesNotAccepted:[]},t||{}),r=e?.length;if(!(r>0))return-1;for(let t=0;t<r;++t){let r=e[t];if(!(!r||r.link||r.links?.length)&&!n.typesNotAccepted?.includes?.(r.type))return n.returnObj?r:t}return-1}findInputSlotByType(e,t,n,r){return this._findSlotByType(this.inputs,e,t,n,r)}findOutputSlotByType(e,t,n,r){return this._findSlotByType(this.outputs,e,t,n,r)}findSlotByType(e,t,n,r,i){return e?this._findSlotByType(this.inputs,t,n,r,i):this._findSlotByType(this.outputs,t,n,r,i)}_findSlotByType(e,t,n,r,i){let a=e?.length;if(!a)return-1;(t==``||t==`*`)&&(t=0);let o=String(t).toLowerCase().split(`,`),s=null;for(let t=0;t<a;++t){let i=e[t],a=i.type==`0`||i.type==`*`?[`0`]:String(i.type).toLowerCase().split(`,`);for(let e of o){let o=e==`_event_`?Q.EVENT:e;for(let e of a){let a=e==`_event_`?Q.EVENT:e;if(o==a||o===`*`||a===`*`){if(r&&(i.links?.length||i.link!=null)){s??=n?i:t;continue}return n?i:t}}}}return i?-1:s??-1}findConnectByTypeSlot(e,t,n,r){r&&typeof r==`object`&&(`firstFreeIfInputGeneralInCase`in r&&(r.wildcardToTyped=!!r.firstFreeIfInputGeneralInCase),`firstFreeIfOutputGeneralInCase`in r&&(r.wildcardToTyped=!!r.firstFreeIfOutputGeneralInCase),`generalTypeInCase`in r&&(r.typedToWildcard=!!r.generalTypeInCase));let i=Object.assign({createEventInCase:!0,wildcardToTyped:!0,typedToWildcard:!0},r);if(!this.graph)throw new NullGraphError;if(t&&typeof t==`number`){let e=this.graph.getNodeById(t);if(!e)return;t=e}let a=t.findSlotByType(e,n,!1,!0);if(a>=0&&a!==null)return a;
2if(i.createEventInCase&&n==Q.EVENT){if(e)return-1;if(Q.do_add_triggers_slots)return t.addOnExecutedOutput()}if(i.typedToWildcard){let n=t.findSlotByType(e,0,!1,!0,!0);if(n>=0)return n}if(i.wildcardToTyped&&(n==0||n==`*`||n==``)){let n={typesNotAccepted:[Q.EVENT]},r=e?t.findInputSlotFree(n):t.findOutputSlotFree(n);if(r>=0)return r}}findOutputByType(e){return findFreeSlotOfType(this.outputs,e,e=>!e.links?.length)}findInputByType(e){return findFreeSlotOfType(this.inputs,e,e=>e.link==null||!!this.graph?.getLink(e.link)?._dragging)}connectByType(e,t,n,r){let i=this.findConnectByTypeSlot(!0,t,n,r);return i===void 0?null:this.connect(e,t,i,r?.afterRerouteId)}connectByTypeOutput(e,t,n,r){typeof r==`object`&&(`firstFreeIfInputGeneralInCase`in r&&(r.wildcardToTyped=!!r.firstFreeIfInputGeneralInCase),`generalTypeInCase`in r&&(r.typedToWildcard=!!r.generalTypeInCase));let i=this.findConnectByTypeSlot(!1,t,n,r);return i===void 0?(console.error(`[connectByType]: no way to connect type:`,n,`to node:`,t),null):t.connect(i,this,e,r?.afterRerouteId)}canConnectTo(e,t,n){return this.id!==e.id&&Q.isValidConnection(n.type,t.type)}connect(e,t,n,r){let i,{graph:a,outputs:o}=this;if(!a)return console.error(`Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them.`),null;if(typeof e==`string`){if(e=this.findOutputSlot(e),e==-1)return Q.debug&&console.error(`Connect: Error, no slot of name ${e}`),null}else if(!o||e>=o.length)return Q.debug&&console.error(`Connect: Error, slot number not found`),null;if(t&&typeof t==`number`){let e=a.getNodeById(t);if(!e)throw`target node is null`;t=e}if(!t)throw`target node is null`;if(t==this)return null;if(typeof n==`string`){if(i=t.findInputSlot(n),i==-1)return Q.debug&&console.error(`Connect: Error, no slot of name ${i}`),null}else if(n===Q.EVENT)if(Q.do_add_triggers_slots)t.changeMode(B.ON_TRIGGER),i=t.findInputSlot(`onTrigger`);else return null;else i=typeof n==`number`?n:0;if(t.onBeforeConnectInput){let e=t.onBeforeConnectInput(i,n);i=typeof e==`number`?e:null}if(i===null||!t.inputs||i>=t.inputs.length)return Q.debug&&console.error(`Connect: Error, slot number not found`),null;let s=t.inputs[i],c=o[e];return c?(c.links?.length&&c.type===Q.EVENT&&!Q.allow_multi_output_for_events&&(a.beforeChange(),this.disconnectOutput(e)),this.connectSlots(c,t,s,r)??null):null}connectSlots(e,t,n,r){let{graph:i}=this;if(!i)throw new NullGraphError;let a=useLayoutMutations(),o=this.outputs.indexOf(e);if(o===-1){console.warn(`connectSlots: output not found`);return}let s=t.inputs.indexOf(n);if(s===-1){console.warn(`connectSlots: input not found`);return}if(!Q.isValidConnection(e.type,n.type))return this.setDirtyCanvas(!1,!0),null;if(t.onConnectInput?.(s,e.type,e,this,o)===!1||this.onConnectOutput?.(o,n.type,n,t,s)===!1)return null;t.inputs[s]?.link!=null&&(i.beforeChange(),t.disconnectInput(s,!0));let c=n.type&&e.type&&commonType(n.type,e.type),l=new K(++i.state.lastLinkId,c||n.type||e.type,this.id,o,t.id,s,r);i._links.set(l.id,l),a.setSource(H.Canvas),a.createLink(l.id,this.id,o,t.id,s),e.links??=[],e.links.push(l.id);let u=t.inputs[s];u.link=l.id,u.widget&&i.trigger(`node:slot-links:changed`,{nodeId:t.id,slotType:N.INPUT,slotIndex:s,connected:!0,linkId:l.id});let d=K.getReroutes(i,l);for(let e of d)e.linkIds.add(l.id),e.floating&&=void 0,e._dragging=void 0;let f=d.at(-1);if(f)for(let e of f.floatingLinkIds){let t=i.floatingLinks.get(e);t?.parentId===f.id&&i.removeFloatingLink(t)}return i.incrementVersion(),this.onConnectionsChange?.(N.OUTPUT,o,!0,l,e),t.onConnectionsChange?.(N.INPUT,s,!0,l,n),this.setDirtyCanvas(!1,!0),i.afterChange(),l}connectFloatingReroute(e,t,n){let{graph:r,id:i}=this;if(!r)throw new NullGraphError;let a=this.inputs.indexOf(t),o=this.outputs.indexOf(t);if(a===-1&&o===-1)throw Error(`Invalid slot`);let s=o===-1?`input`:`output`,c=r.setReroute({pos:e,parentId:n,linkIds:[],floating:{slotType:s}}),l=r.getReroute(n),u=l?.floating?.slotType===`output`;if(n==null||!u){let e=new K(-1,t.type,o===-1?-1:i,o,a===-1?-1:i,a);return e.parentId=c.id,r.addFloatingLink(e),c}if(!l)throw Error(`[connectFloatingReroute] Parent reroute not found`);let d=l.getFloatingLinks(`output`)?.[0];if(!d)throw Error(`[connectFloatingReroute] Floating link not found`);return c.floatingLinkIds.add(d.id),d.parentId=c.id,l.floating=void 0,c}disconnectOutput(e,t){if(typeof e==`string`){if(e=this.findOutputSlot(e),e==-1)return Q.debug&&console.error(`Connect: Error, no slot of name ${e}
2`),!1}else if(!this.outputs||e>=this.outputs.length)return Q.debug&&console.error(`Connect: Error, slot number not found`),!1;let n=this.outputs[e];if(!n)return!1;if(n._floatingLinks)for(let t of n._floatingLinks)t.hasOrigin(this.id,e)&&this.graph?.removeFloatingLink(t);if(!n.links||n.links.length==0)return!1;let{links:r}=n,i=this.graph;if(!i)throw new NullGraphError;if(t){let a=typeof t==`number`?i.getNodeById(t):t;if(!a)throw`Target Node not found`;for(let[t,o]of r.entries()){let s=i._links.get(o);if(s?.target_id!=a.id)continue;r.splice(t,1);let c=a.inputs[s.target_slot];c.link=null,c.widget&&i.trigger(`node:slot-links:changed`,{nodeId:a.id,slotType:N.INPUT,slotIndex:s.target_slot,connected:!1,linkId:s.id}),s.disconnect(i,`input`),i.incrementVersion(),a.onConnectionsChange?.(N.INPUT,s.target_slot,!1,s,c),this.onConnectionsChange?.(N.OUTPUT,e,!1,s,n);break}}else{for(let t of r){let r=i._links.get(t);if(!r)continue;if(r.target_id===-20&&i instanceof bt){let e=i.outputNode.slots[r.target_slot];e?e.linkIds.length=0:console.error(`Missing subgraphOutput slot when disconnecting link`)}let a=i.getNodeById(r.target_id);if(i.incrementVersion(),a){let e=a.inputs[r.target_slot];e.link=null,e.widget&&i.trigger(`node:slot-links:changed`,{nodeId:a.id,slotType:N.INPUT,slotIndex:r.target_slot,connected:!1,linkId:r.id}),a.onConnectionsChange?.(N.INPUT,r.target_slot,!1,r,e)}r.disconnect(i,`input`),this.onConnectionsChange?.(N.OUTPUT,e,!1,r,n)}n.links=null}return this.setDirtyCanvas(!1,!0),!0}disconnectInput(e,t){if(typeof e==`string`){if(e=this.findInputSlot(e),e==-1)return Q.debug&&console.error(`Connect: Error, no slot of name ${e}`),!1}else if(!this.inputs||e>=this.inputs.length)return Q.debug&&console.error(`Connect: Error, slot number not found`),!1;let n=this.inputs[e];if(!n)return console.error(`disconnectInput: input not found`,e,this.inputs),!1;let{graph:r}=this;if(!r)throw new NullGraphError;if(n._floatingLinks?.size)for(let e of n._floatingLinks)r.removeFloatingLink(e);let i=this.inputs[e].link;if(i!=null){this.inputs[e].link=null,n.widget&&r.trigger(`node:slot-links:changed`,{nodeId:this.id,slotType:N.INPUT,slotIndex:e,connected:!1,linkId:i});let a=r._links.get(i);if(a){if(a.origin_id===-10&&`inputNode`in r)return r.inputNode._disconnectNodeInput(this,n,a),!0;let o=r.getNodeById(a.origin_id);if(!o)return console.error(`disconnectInput: output not found`,a.origin_slot),!1;let s=o.outputs[a.origin_slot];if(!s?.links?.length)return!1;let c=0;for(let e=s.links.length;c<e;c++)if(s.links[c]==i){s.links.splice(c,1);break}a.disconnect(r,t?`output`:void 0),r&&r.incrementVersion(),this.onConnectionsChange?.(N.INPUT,e,!1,a,n),o.onConnectionsChange?.(N.OUTPUT,c,!1,a,s)}}return this.setDirtyCanvas(!1,!0),!0}getConnectionPos(e,t,n){n||=[0,0];let{pos:[r,i],inputs:a,outputs:o}=this;if(this.flags.collapsed){let t=this._collapsed_width||Q.NODE_COLLAPSED_WIDTH;return n[0]=e?r:r+t,n[1]=i-Q.NODE_TITLE_HEIGHT*.5,n}if(e&&t==-1)return n[0]=r+Q.NODE_TITLE_HEIGHT*.5,n[1]=i+Q.NODE_TITLE_HEIGHT*.5,n;let s=a?.[t]?.pos,c=o?.[t]?.pos;if(e&&s)return n[0]=r+s[0],n[1]=i+s[1],n;if(!e&&c)return n[0]=r+c[0],n[1]=i+c[1],n;let l=Q.NODE_SLOT_HEIGHT*.5,u=e?this._defaultVerticalInputs.indexOf(this.inputs[t]):this._defaultVerticalOutputs.indexOf(this.outputs[t]);return n[0]=e?r+l:r+this.size[0]+1-l,n[1]=i+(u+.7)*Q.NODE_SLOT_HEIGHT+(this.constructor.slot_start_y||0),n}get _defaultVerticalInputs(){return this.inputs.filter(e=>!e.pos&&!(this.widgets?.length&&isWidgetInputSlot(e)))}get _defaultVerticalOutputs(){return this.outputs.filter(e=>!e.pos)}_getSlotPositionContext(){return{nodeX:this.pos[0],nodeY:this.pos[1],nodeWidth:this.size[0],nodeHeight:this.size[1],collapsed:this.flags.collapsed??!1,collapsedWidth:this._collapsed_width,slotStartY:this.constructor.slot_start_y,inputs:this.inputs,outputs:this.outputs,widgets:this.widgets}}getInputPos(e){return getSlotPosition(this,e,!0)}getInputSlotPos(e){return calculateInputSlotPosFromSlot(this._getSlotPositionContext(),e)}getOutputPos(e){return getSlotPosition(this,e,!1)}getSlotPosition(e,t){return getSlotPosition(this,e,t)}
2snapToGrid(e){return this.pinned?!1:snapPoint(this.pos,e)}alignToGrid(){this.snapToGrid(Q.CANVAS_GRID_SIZE)}trace(e){this.console||=[],this.console.push(e),this.console.length>LGraphNode.MAX_CONSOLE&&this.console.shift()}setDirtyCanvas(e,t){this.graph?.canvasAction(n=>n.setDirty(e,t))}loadImage(e){let t=new Image;t.src=Q.node_images_path+e,t.ready=!1;let dirty=()=>this.setDirtyCanvas(!0);return t.addEventListener(`load`,function(){this.ready=!0,dirty()}),t}captureInput(e){if(warnDeprecated(`[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.`),!this.graph||!this.graph.list_of_graphcanvas)return;let t=this.graph.list_of_graphcanvas;for(let n of t)!e&&n.node_capturing_input!=this||(n.node_capturing_input=e?this:null)}get collapsed(){return!!this.flags.collapsed}get collapsible(){return!this.pinned&&this.constructor.collapsable!==!1}collapse(e){if(!(!this.collapsible&&!e)){if(!this.graph)throw new NullGraphError;this.graph.incrementVersion(),this.flags.collapsed=!this.flags.collapsed,this.setDirtyCanvas(!0,!0)}}toggleAdvanced(){if(this.hasAdvancedWidgets()){if(!this.graph)throw new NullGraphError;this.graph.incrementVersion(),this.showAdvanced=!this.showAdvanced,this.expandToFitContent(),this.setDirtyCanvas(!0,!0)}}get pinned(){return!!this.flags.pinned}pin(e){if(!this.graph)throw new NullGraphError;this.graph.incrementVersion(),this.flags.pinned=e??!this.flags.pinned,this.resizable=!this.pinned,this.pinned||(this.flags.pinned=void 0)}unpin(){this.pin(!1)}localToScreen(e,t,n){return[(e+this.pos[0])*n.scale+n.offset[0],(t+this.pos[1])*n.scale+n.offset[1]]}get width(){return this.collapsed?this._collapsed_width||Q.NODE_COLLAPSED_WIDTH:this.size[0]}get height(){return Q.NODE_TITLE_HEIGHT+this.bodyHeight}get bodyHeight(){return this.collapsed?0:this.size[1]}drawBadges(e,{gap:t=2}={}){let n=this.badges.map(e=>e instanceof LGraphBadge?e:e()),r=this.badgePosition===ze.TopLeft?0:this.width-n.reduce((n,r)=>
2n+r.getWidth(e)+t,0),i=-(Q.NODE_TITLE_HEIGHT+t);for(let a of n)a.draw(e,r,i-a.height),r+=a.getWidth(e)+t}drawTitleBarBackground(e,{scale:t,title_height:n=Q.NODE_TITLE_HEIGHT,low_quality:r=!1}){let i=this.renderingColor,a=this.renderingShape,o=this.renderingSize;if(this.onDrawTitleBar){this.onDrawTitleBar(e,n,o,t,i);return}this.title_mode!==z.TRANSPARENT_TITLE&&(this.collapsed&&(e.shadowColor=Q.DEFAULT_SHADOW_COLOR),e.fillStyle=this.constructor.title_color||i,e.beginPath(),a==P.BOX||r?e.rect(0,-n,o[0],n):(a==P.ROUND||a==P.CARD)&&e.roundRect(0,-n,o[0],n,this.collapsed?[Q.ROUND_RADIUS]:[Q.ROUND_RADIUS,Q.ROUND_RADIUS,0,0]),e.fill(),e.shadowColor=`transparent`)}drawTitleBox(e,{scale:t,low_quality:n=!1,title_height:r=Q.NODE_TITLE_HEIGHT,box_size:i=10}){let a=this.renderingSize,o=this.renderingShape;if(this.onDrawTitleBox){this.onDrawTitleBox(e,r,a,t);return}[P.ROUND,P.CIRCLE,P.CARD].includes(o)?(n&&(e.fillStyle=`black`,e.beginPath(),e.arc(r*.5,r*-.5,i*.5+1,0,Math.PI*2),e.fill()),e.fillStyle=this.renderingBoxColor,n?e.fillRect(r*.5-i*.5,r*-.5-i*.5,i,i):(e.beginPath(),e.arc(r*.5,r*-.5,i*.5,0,Math.PI*2),e.fill())):(n&&(e.fillStyle=`black`,e.fillRect((r-i)*.5-1,(r+i)*-.5-1,i+2,i+2)),e.fillStyle=this.renderingBoxColor,e.fillRect((r-i)*.5,(r+i)*-.5,i,i))}drawTitleText(e,{scale:t,default_title_color:n,low_quality:r=!1,title_height:i=Q.NODE_TITLE_HEIGHT}){let a=this.renderingSize,o=this.selected;if(this.onDrawTitleText){this.onDrawTitleText(e,i,a,t,this.titleFontStyle,o);return}if(r)return;e.font=this.titleFontStyle;let s=this.getTitle()??`❌ ${this.type}`,c=String(s)+(this.pinned?`📌`:``);if(c){o?e.fillStyle=Q.NODE_SELECTED_TITLE_COLOR:e.fillStyle=this.constructor.title_text_color||n;let t=a[0]-i*2;if(this.title_buttons?.length>0){let n=0,r=e.font;for(let t of this.title_buttons)t.visible&&(n+=t.getWidth(e)+2);e.font=r,n>0&&(n-=20,t-=n)}let r=c;this.collapsed?r=c.substr(0,20):t>0&&(r=truncateText(e,c,t)),e.textAlign=`left`,e.fillText(r,i,Q.NODE_TITLE_TEXT_Y-i)}}connectInputToOutput(){let{inputs:e,outputs:t,graph:n}=this;if(!e||!t)return;if(!n)throw new NullGraphError;let{_links:r}=n,i=!1;for(let[i,a]of e.entries()){if(a.link==null)continue;let e=t[i];if(!e||!Q.isValidConnection(a.type,e.type))continue;let o=r.get(a.link);if(!o)continue;let s=n.getNodeById(o?.origin_id);s&&bypassAllLinks(e,s,o,n)}if(!(this.flags.keepAllLinksOnBypass??LGraphNode.keepAllLinksOnBypass))return i;for(let i of e){if(i.link==null)continue;let e=r.get(i.link);if(!e)continue;let a=n.getNodeById(e?.origin_id);if(a){for(let r of t)if(Q.isValidConnection(i.type,r.type)){bypassAllLinks(r,a,e,n);break}}}return i;function bypassAllLinks(e,t,n,a){let o=e.links?.map(e=>r.get(e)).filter(e=>!!e);if(o?.length)for(let e of o){let r=a.getNodeById(e.target_id);if(!r)continue;let o=t.connect(n.origin_slot,r,e.target_slot,n.parentId);i||=!!o}}}isWidgetVisible(e){return!(this.collapsed||e.hidden||e.advanced&&!this.showAdvanced)}getLayoutWidgets(){return this.widgets?.filter(e=>!e.hidden)??[]}hasAdvancedWidgets(){return this.widgets?.some(e=>e.advanced)??!1}updateComputedDisabled(){if(this.widgets)for(let e of this.widgets)e.computedDisabled=e.disabled||this.getSlotFromWidget(e)?.link!=null}drawWidgets(e,{lowQuality:t=!1,editorAlpha:n=1}){if(!this.widgets)return;let r=this.size[0],{widgets:i}=this,a=Q.NODE_WIDGET_HEIGHT,o=!t;e.save(),e.globalAlpha=n,this.updateComputedDisabled();for(let s of i){if(!this.isWidgetVisible(s))continue;let{y:i}=s,c=s.advanced?Q.WIDGET_ADVANCED_OUTLINE_COLOR:Q.WIDGET_OUTLINE_COLOR;s.last_y=i,e.strokeStyle=c,e.fillStyle=`#222`,e.textAlign=`left`,s.computedDisabled&&(e.globalAlpha*=.5);let l=s.width||r;typeof s.draw==`function`?s.draw(e,this,l,i,a,t):toConcreteWidget(s,this,!1)?.drawWidget(e,{width:l,showText:o}),e.globalAlpha=n}e.restore()}drawCollapsedSlots(e){for(let t of this._concreteInputs)if(t.link!=null){t.drawCollapsed(e);break}for(let t of this._concreteOutputs)if(t.links?.length){t.drawCollapsed(e);break}}get slots(){return[...this.inputs,...this.outputs]}_measureSlot(e,t,n){let r=n?this.getInputPos(t):this.getOutputPos(t);e.boundingRect[0]=r[0]-Q.NODE_SLOT_HEIGHT*.5,e.boundingRect[1]=r[1]-Q.NODE_SLOT_HEIGHT*.5,e.boundingRect[2]=e.isWidgetInputSlot?J.margin:Q.NODE_SLOT_HEIGHT,e.boun
2dingRect[3]=Q.NODE_SLOT_HEIGHT}_measureSlots(){let e=[];for(let[t,n]of this._concreteInputs.entries())this.widgets?.length&&isWidgetInputSlot(n)||(this._measureSlot(n,t,!0),e.push(n));for(let[t,n]of this._concreteOutputs.entries())this._measureSlot(n,t,!1),e.push(n);return e.length?createBounds(e,0):null}_getMouseOverSlot(e){let t=isINodeInputSlot(e),n=this.mouseOver?.[t?`inputId`:`outputId`]??-1;return n===-1?null:t?this.inputs[n]:this.outputs[n]}_isMouseOverSlot(e){return this._getMouseOverSlot(e)===e}_isMouseOverWidget(e){return e?this.mouseOver?.overWidget===e:!1}getSlotFromWidget(e){if(e)return this.inputs.find(t=>isWidgetInputSlot(t)&&t.widget.name===e.name)}getWidgetFromSlot(e){if(isWidgetInputSlot(e))return this.widgets?.find(t=>t.name===e.widget.name)}drawSlots(e,{fromSlot:t,colorContext:n,editorAlpha:r,lowQuality:i}){for(let a of[...this._concreteInputs,...this._concreteOutputs]){let o=t&&a.isValidTarget(t),s=this._isMouseOverSlot(a),c=!t||o,l=c&&s;(s||o||!a.isWidgetInputSlot||this._isMouseOverWidget(this.getWidgetFromSlot(a))||a.isConnected||a.alwaysVisible)&&(e.globalAlpha=c?r:.4*r,a.draw(e,{colorContext:n,lowQuality:i,highlight:l}))}}_arrangeWidgets(e){if(!this.widgets||!this.widgets.length)return;let t=this.bodyHeight,n=this.widgets_start_y??(this.widgets_up?0:e)+2,r=t-n,i=0,a=[],o=this.getLayoutWidgets();for(let e of o)if(e.computeSize){let t=e.computeSize()[1]+4;e.computedHeight=t,i+=t}else if(e.computeLayoutSize){let{minHeight:t,maxHeight:n}=e.computeLayoutSize(this);a.push({minHeight:t,prefHeight:n,w:e})}else{let t=Q.NODE_WIDGET_HEIGHT+4;e.computedHeight=t,i+=t}r-=i,this.freeWidgetSpace=r;let s=a.map(e=>({minSize:e.minHeight,maxSize:e.prefHeight})),c=distributeSpace(Math.max(0,r),s);for(let[e,t]of a.entries())t.w.computedHeight=c[e];let l=n;for(let e of o)e.y=l,l+=e.computedHeight??0;if(!this.graph)throw new NullGraphError;!Q.vueNodesMode&&l>t&&(this.setSize([this.size[0],l]),this.graph.setDirtyCanvas(!1,!0))}_arrangeWidgetInputSlots(){if(!this.widgets?.length)return;let e=new Map;for(let t of this.widgets)e.set(t.name,t);for(let[t,n]of this._concreteInputs.entries()){if(!isWidgetInputSlot(n))continue;let r=n._widget??e.get(n.widget.name);if(!r)continue;let i=Q.NODE_SLOT_HEIGHT*.5;n.pos=[i,r.y+i],this._measureSlot(n,t,!0)}}_setConcreteSlots(){this._concreteInputs=this.inputs.map(e=>toClass(NodeInputSlot,e,this)),this._concreteOutputs=this.outputs.map(e=>toClass(NodeOutputSlot,e,this))}arrange(){let e=this._measureSlots(),t=e?e[1]+e[3]-this.pos[1]:0;this._arrangeWidgets(t),this._arrangeWidgetInputSlots(),this._widgetSlotsDirty=!1}drawProgressBar(e){if(!this.progress)return;let t=e.fillStyle;e.fillStyle=`green`,e.fillRect(0,0,this.width*this.progress,6),e.fillStyle=t}},X=class LGraphGroup{static minWidth=140;static minHeight=80;static resizeLength=10;static padding=4;static defaultColour=`#335`;id;color;title;font;font_size=Q.GROUP_TEXT_SIZE;_bounding=new G(10,10,LGraphGroup.minWidth,LGraphGroup.minHeight);_pos=this._bounding.pos;_size=this._bounding.size;_nodes=[];_children=new Set;graph;flags={};selected;constructor(e,t){this.id=t??-1,this.title=e||`Group`;let{pale_blue:n}=Z.node_colors;this.color=n?n.groupcolor:`#AAA`}setColorOption(e){e==null?delete this.color:this.color=e.groupcolor}getColorOption(){return Object.values(Z.node_colors).find(e=>e.groupcolor===this.color)??null}get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get size(){return this._size}set size(e){!e||e.length<2||(this._size[0]=Math.max(LGraphGroup.minWidth,e[0]),this._size[1]=Math.max(LGraphGroup.minHeight,e[1]))}get boundingRect(){return this._bounding}getBounding(){return this._bounding}get nodes(){return this._nodes}get titleHeight(){return Q.NODE_TITLE_HEIGHT}get children(){return this._children}get pinned(){return!!this.flags.pinned}pin(e){(e===void 0?!this.pinned:e)?this.flags.pinned=!0:delete this.flags.pinned}unpin(){this.pin(!1)}configure(e){this.id=e.id,this.title=e.title,this._bounding.set(e.bounding),this.color=e.color,this.flags=e.flags||this.flags}serialize(){let e=this._bounding;
2return{id:this.id,title:this.title,bounding:[...e],color:this.color,flags:this.flags}}draw(e,t){let{padding:n,resizeLength:r,defaultColour:i}=LGraphGroup,a=Q.GROUP_TEXT_SIZE,[o,s]=this._pos,[c,l]=this._size,u=this.color||i;t.globalAlpha=.25*e.editor_alpha,t.fillStyle=u,t.strokeStyle=u,t.beginPath(),t.rect(o+.5,s+.5,c,Q.NODE_TITLE_HEIGHT),t.fill(),t.fillStyle=u,t.strokeStyle=u,t.beginPath(),t.rect(o+.5,s+.5,c,l),t.fill(),t.globalAlpha=e.editor_alpha,t.stroke(),t.beginPath(),t.moveTo(o+c,s+l),t.lineTo(o+c-r,s+l),t.lineTo(o+c,s+l-r),t.fill(),t.font=`${a}px ${Q.GROUP_FONT}`,t.textAlign=`left`,t.textBaseline=`middle`,t.fillText(this.title+(this.pinned?`📌`:``),o+a/2,s+Q.NODE_TITLE_HEIGHT/2+1),t.textBaseline=`alphabetic`,Q.highlight_selected_group&&this.selected&&strokeShape(t,this._bounding,{title_height:this.titleHeight,padding:n})}resize(e,t){return this.pinned?!1:(this._size[0]=Math.max(LGraphGroup.minWidth,e),this._size[1]=Math.max(LGraphGroup.minHeight,t),!0)}move(e,t,n=!1){if(!this.pinned&&(this._pos[0]+=e,this._pos[1]+=t,n!==!0))for(let n of this._children)n.move(e,t)}snapToGrid(e){return this.pinned?!1:snapPoint(this.pos,e)}recomputeInsideNodes(e=100,t=new Set){if(!this.graph)throw new NullGraphError;if(e<=0||t.has(this.id))return;t.add(this.id);let{nodes:n,reroutes:r,groups:i}=this.graph,a=this._children;this._nodes.length=0,a.clear();for(let e of n)containsCentre(this._bounding,e.boundingRect)&&(this._nodes.push(e),a.add(e));for(let e of r.values())isPointInRect(e.pos,this._bounding)&&a.add(e);let o=[];for(let e of i)e!==this&&containsRect(this._bounding,e._bounding)&&(a.add(e),o.push(e));for(let n of o)n.recomputeInsideNodes(e-1,t);i.sort((e,t)=>e===this?a.has(t)?-1:0:t===this&&a.has(e)?1:0)}resizeTo(e,t=10){let n=createBounds(e,t);n!==null&&(this.pos[0]=n[0],this.pos[1]=n[1]-this.titleHeight,this.size[0]=n[2],this.size[1]=n[3]+this.titleHeight)}addNodes(e,t=10){!this._nodes&&e.length===0||this.resizeTo([...this.children,...this._nodes,...e],t)}getMenuOptions(){return[{content:this.pinned?`Unpin`:`Pin`,callback:()=>{this.pinned?this.unpin():this.pin(),this.setDirtyCanvas(!1,!0)}},null,{content:`Title`,callback:Z.onShowPropertyEditor},{content:`Color`,has_submenu:!0,callback:Z.onMenuNodeColors},{content:`Font size`,property:`font_size`,type:`Number`,callback:Z.onShowPropertyEditor},null,{content:`Remove`,callback:Z.onMenuNodeRemove}]}isPointInTitlebar(e,t){let n=this.boundingRect;return isInRectangle(e,t,n[0],n[1],n[2],this.titleHeight)}isInResize(e,t){let n=this.boundingRect,r=n[0]+n[2],i=n[1]+n[3];return e<r&&t<i&&e-r+(t-i)>-LGraphGroup.resizeLength}isPointInside(e,t){return isInRect(e,t,this.boundingRect)}setDirtyCanvas=Y.prototype.setDirtyCanvas},FloatingRenderLink=class{node;fromSlot;fromPos;fromDirection;fromSlotIndex;outputNodeId=-1;outputNode;outputSlot;outputIndex=-1;outputPos;inputNodeId=-1;inputNode;inputSlot;inputIndex=-1;inputPos;constructor(e,t,n,r,i=I.CENTER){this.network=e,this.link=t,this.toType=n,this.fromReroute=r,this.dragDirection=i;let{origin_id:a,target_id:o,origin_slot:s,target_slot:c}=t;if(a!==-1){let n=e.getNodeById(a)??void 0;if(!n)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Output node [${a}] not found.`);let i=n?.outputs.at(s);if(!i)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Output slot [${s}] not found.`);this.outputNodeId=a,this.outputNode=n,this.outputSlot=i,this.outputIndex=s,this.outputPos=n.getOutputPos(s),this.node=n,this.fromSlot=i,this.fromPos=r?.pos??this.outputPos,this.fromDirection=I.LEFT,this.dragDirection=I.RIGHT,this.fromSlotIndex=s}else{let n=e.getNodeById(o)??void 0;if(!n)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Input node [${o}] not found.`);let r=n?.inputs.at(c);if(!r)throw Error(`Creating DraggingRenderLink for link [${t.id}] failed: Input slot [${c}] not found.`);this.inputNodeId=o,this.inputNode=n,this.inputSlot=r,this.inputIndex=c,this.inputPos=n.getInputPos(c),this.node=n,this.fromSlot=r,this.fromDirection=I.RIGHT,this.fromSlotIndex=c}this.fromPos=r.pos}canConnectToInput(){return this.toType===`input`}canConnectToOutput(){return this.toType===`output`}canConnectToReroute(e){if(this.toType===`input`){if(e.origin_id===this.inputNode?.id)return!1}else if(e.origin_id===this.outputNode?.id)return!1;return!0}canConnectToSubgraphInput(e){return this.toType===`output`&&e.isValidTarget(this.fromSlot)}connectToInput(e,t,n){let r=this.link;
2r.target_id=e.id,r.target_slot=e.inputs.indexOf(t),e.disconnectInput(e.inputs.indexOf(t)),this.fromSlot._floatingLinks?.delete(r),t._floatingLinks??=new Set,t._floatingLinks.add(r)}connectToOutput(e,t,n){let r=this.link;r.origin_id=e.id,r.origin_slot=e.outputs.indexOf(t),this.fromSlot._floatingLinks?.delete(r),t._floatingLinks??=new Set,t._floatingLinks.add(r)}connectToSubgraphInput(e,t){let n=this.link;n.origin_id=-10,n.origin_slot=e.parent.slots.indexOf(e),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToSubgraphOutput(e,t){let n=this.link;n.origin_id=-20,n.origin_slot=e.parent.slots.indexOf(e),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToRerouteInput(e,{node:t,input:n},r){let i=this.link;i.target_id=t.id,i.target_slot=t.inputs.indexOf(n),this.fromSlot._floatingLinks?.delete(i),n._floatingLinks??=new Set,n._floatingLinks.add(i),r.dispatch(`input-moved`,this)}connectToRerouteOutput(e,t,n,r){let i=this.link;i.origin_id=t.id,i.origin_slot=t.outputs.indexOf(n),this.fromSlot._floatingLinks?.delete(i),n._floatingLinks??=new Set,n._floatingLinks.add(i),r.dispatch(`output-moved`,this)}},MovingOutputLink=class extends MovingLinkBase{toType=`output`;node;fromSlot;fromPos;fromDirection;fromSlotIndex;constructor(e,t,n,r=I.CENTER){super(e,t,`output`,n,r),this.node=this.inputNode,this.fromSlot=this.inputSlot,this.fromPos=n?.pos??this.inputPos,this.fromDirection=I.LEFT,this.fromSlotIndex=this.inputIndex}canConnectToInput(){return!1}canConnectToOutput(e,t){return e.canConnectTo(this.node,this.inputSlot,t)}canConnectToReroute(e){return e.origin_id!==this.outputNode.id}canConnectToSubgraphInput(e){return e.isValidTarget(this.fromSlot)}connectToInput(){throw Error(`MovingOutputLink cannot connect to an input.`)}connectToOutput(e,t,n){if(t===this.outputSlot)return;let r=e.connectSlots(t,this.inputNode,this.inputSlot,this.link.parentId);return r&&n.dispatch(`output-moved`,this),r}connectToSubgraphInput(e,t){let n=e.connect(this.fromSlot,this.node,this.fromReroute?.id);t?.dispatch(`link-created`,n)}connectToSubgraphOutput(){throw Error(`MovingOutputLink cannot connect to a subgraph output.`)}connectToRerouteInput(){throw Error(`MovingOutputLink cannot connect to an input.`)}connectToRerouteOutput(e,t,n,r){let{inputNode:i,inputSlot:a,fromReroute:o}=this,s=e?.floating?.slotType===`output`;o?o.parentId=e.id:this.link.parentId=e.id,t.connectSlots(n,i,a,this.link.parentId),s&&e.removeAllFloatingLinks(),r.dispatch(`output-moved`,this)}disconnect(){return this.outputNode.disconnectOutput(this.outputIndex,this.inputNode)}},ToInputFromIoNodeLink=class{toType=`input`;fromSlotIndex;fromPos;fromDirection=I.RIGHT;existingLink;isIoNodeLink=!0;constructor(e,t,n,r,i=I.CENTER,a){this.network=e,this.node=t,this.fromSlot=n,this.fromReroute=r,this.dragDirection=i;let o=t.slots.indexOf(n);if(o===-1&&n!==t.emptySlot)throw Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=o,this.fromPos=r?r.pos:n.pos,this.existingLink=a}canConnectToInput(e,t){return this.node.canConnectTo(e,t,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(e,t,n){let{fromSlot:r,fromReroute:i,existingLink:a}=this;if(a&&e.id===a.target_id&&e.inputs[a.target_slot]===t)return;let o=r.connect(t,e,i?.id);if(a){let{input:e,inputNode:t}=a.resolve(this.network);t&&e&&this.node._disconnectNodeInput(t,e,a),n.dispatch(`input-moved`,this),r.events.dispatch(`input-disconnected`,{input:r})}else n.dispatch(`link-created`,o)}connectToSubgraphOutput(){throw Error(`Not implemented`)}connectToRerouteInput(e,{node:t,input:n,link:r},i,a){let{fromSlot:o,fromReroute:s}=this,c=s?.floating?.slotType===`output`;e.parentId=s?.id;let l=o.connect(n,t,r.parentId);c&&s.removeAllFloatingLinks();for(let e of a){if(e.id===s?.id)break;if(e.removeLink(r),e.totalLinks===0)if(r.isFloating)e.remove();else{let t=r.toFloating(`output`,e.id);this.network.addFloatingLink(t),e.floating={slotType:`output`}}}this.existingLink?i.dispatch(`input-moved`,this):i.dispatch(`link-created`,l)}connectToOutput(){throw Error(`ToInputRenderLink cannot connect to an output.`)}connectToSubgraphInput(){throw Error(`ToInputRenderLink cannot connect to a subgraph input.`)}connectToRerouteOutput(){throw Error(`ToInputRenderLink cannot connect to an output.`)}disconnect(){if(!this.existingLink)return!1;
2let{input:e,inputNode:t,subgraphInput:n}=this.existingLink.resolve(this.network);return!t||!e?!1:(this.node._disconnectNodeInput(t,e,this.existingLink),n&&n.events.dispatch(`input-disconnected`,{input:n}),!0)}},ToInputRenderLink=class{toType=`input`;fromPos;fromSlotIndex;fromDirection=I.RIGHT;constructor(e,t,n,r,i=I.CENTER){this.network=e,this.node=t,this.fromSlot=n,this.fromReroute=r,this.dragDirection=i;let a=t.outputs.indexOf(n);if(a===-1)throw Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=a,this.fromPos=r?r.pos:this.node.getOutputPos(a)}canConnectToInput(e,t){return this.node.canConnectTo(e,t,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(e,t,n){let{node:r,fromSlot:i,fromReroute:a}=this;if(e===r)return;let o=r.connectSlots(i,e,t,a?.id);n.dispatch(`link-created`,o)}connectToSubgraphOutput(e,t){let n=e.connect(this.fromSlot,this.node,this.fromReroute?.id);t.dispatch(`link-created`,n)}connectToRerouteInput(e,{node:t,input:n,link:r},i,a){let{node:o,fromSlot:s,fromReroute:c}=this,l=c?.floating?.slotType===`output`;e.parentId=c?.id;let u=o.connectSlots(s,t,n,r.parentId);l&&c.removeAllFloatingLinks();for(let e of a){if(e.id===c?.id)break;if(e.removeLink(r),e.totalLinks===0)if(r.isFloating)e.remove();else{let t=r.toFloating(`output`,e.id);this.network.addFloatingLink(t),e.floating={slotType:`output`}}}i.dispatch(`link-created`,u)}connectToOutput(){throw Error(`ToInputRenderLink cannot connect to an output.`)}connectToSubgraphInput(){throw Error(`ToInputRenderLink cannot connect to a subgraph input.`)}connectToRerouteOutput(){throw Error(`ToInputRenderLink cannot connect to an output.`)}},ToOutputFromIoNodeLink=class{toType=`output`;fromPos;fromSlotIndex;fromDirection=I.LEFT;isIoNodeLink=!0;constructor(e,t,n,r,i=I.CENTER){this.network=e,this.node=t,this.fromSlot=n,this.fromReroute=r,this.dragDirection=i;let a=t.slots.indexOf(n);if(a===-1&&n!==t.emptySlot)throw Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=a,this.fromPos=r?r.pos:n.pos}canConnectToInput(){return!1}canConnectToOutput(e,t){return this.node.canConnectTo(e,this.fromSlot,t)}canConnectToReroute(e){return e.origin_id!==this.node.id}connectToOutput(e,t,n){let{fromSlot:r,fromReroute:i}=this,a=r.connect(t,e,i?.id);n.dispatch(`link-created`,a)}connectToSubgraphInput(){throw Error(`Not implemented`)}connectToRerouteOutput(e,t,n,r){let{fromSlot:i}=this,a=i.connect(n,t,e?.id);r.dispatch(`link-created`,a)}connectToInput(){throw Error(`ToOutputRenderLink cannot connect to an input.`)}connectToSubgraphOutput(){throw Error(`ToOutputRenderLink cannot connect to a subgraph output.`)}connectToRerouteInput(){throw Error(`ToOutputRenderLink cannot connect to an input.`)}},ToOutputRenderLink=class{toType=`output`;fromPos;fromSlotIndex;fromDirection=I.LEFT;constructor(e,t,n,r,i=I.CENTER){this.network=e,this.node=t,this.fromSlot=n,this.fromReroute=r,this.dragDirection=i;let a=t.inputs.indexOf(n);if(a===-1)throw Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=a,this.fromPos=r?r.pos:this.node.getInputPos(a)}canConnectToInput(){return!1}canConnectToOutput(e,t){return this.node.canConnectTo(e,this.fromSlot,t)}canConnectToReroute(e){return e.origin_id!==this.node.id}canConnectToSubgraphInput(e){return e.isValidTarget(this.fromSlot)}connectToOutput(e,t,n){let{node:r,fromSlot:i,fromReroute:a}=this;if(!r)return;let o=e.connectSlots(t,r,i,a?.id);n.dispatch(`link-created`,o)}connectToSubgraphInput(e,t){let n=e.connect(this.fromSlot,this.node,this.fromReroute?.id);t?.dispatch(`link-created`,n)}connectToRerouteOutput(e,t,n,r){let{node:i,fromSlot:a}=this,o=t.connectSlots(n,i,a,e?.id);r.dispatch(`link-created`,o)}connectToInput(){throw Error(`ToOutputRenderLink cannot connect to an input.`)}connectToSubgraphOutput(){throw Error(`ToOutputRenderLink cannot connect to a subgraph output.`)}connectToRerouteInput(){throw Error(`ToOutputRenderLink cannot connect to an input.`)}},ToOutputFromRerouteLink=class extends ToOutputRenderLink{constructor(e,t,n,r,i){super(e,t,n,r),this.fromReroute=r,this.linkConnector=i}canConnectToReroute(){return!1}connectToOutput(e,t){let n=new ToInputRenderLink(this.network,e,t);this.linkConnector._connectOutputToReroute(this.fromReroute,n)}},LinkConnector=class{state={connectingTo:void 0,multi:!1,draggingExistingLinks:!1,snapLinksPos:void 0};events=new CustomEventTarget;renderLinks=[];inputLinks=[];outputLinks=[];floatingLinks=[];hiddenReroutes=new Set;overWidget;overWidgetType;overReroute;_setConnectingLinks;constructor(e){this._setConnectingLinks=e}get isConnecting(){return this.state.connectingTo!==void 0}get draggingExistingLinks(){return this.state.draggingExistingLinks}moveInputLink(e,t,n){if(this.isConnecting)throw Error(`Already dragging links.`);let{state:r,inputLinks:i,renderLinks:a}=this,o=t.link;if(o==null){let n=t._floatingLinks?.values().next().value;if(n?.parentId==null)return;try{let t=e.reroutes.get(n.parentId);if(!t)throw Error(`Invalid reroute id: [${n.parentId}] for floating link id: [${n.id}].`);let r=new FloatingRenderLink(e,n,`input`,t);if(this.events.dispatch(`before-move-input`,r)===!1)return;a.push(r)}catch(e){console.warn(`Could not create render link for link id: [${n.id}].`,n,e)}n._dragging=!0,this.floatingLinks.push(n)}else{let t=e.links.get(o);if(!t)return;if(t.origin_id===-10){let n=e.inputNode?.slots[t.origin_slot];if(!n){console.warn(`Could not find subgraph input for slot [${t.origin_slot}]`);return}try{let r=e.getReroute(t.parentId),i=new ToInputFromIoNodeLink(e,e.inputNode,n,r,I.CENTER,t);a.push(i),this.listenUntilReset(`input-moved`,()=>{t.disconnect(e,`input`)})}catch(e){console.warn(`Could not create render link for subgraph input link id: [${t.id}].`,t,e);return}t._dragging=!0,i.push(t)}else{try{let r=new MovingInputLink(e,t,e.getReroute(t.parentId),void 0,n?.startPoint);if(this.events.dispatch(`before-move-input`,r)===!1)return;a.push(r),this.listenUntilReset(`input-moved`,t=>{`link`in t.detail&&t.detail.link&&t.detail.link.disconnect(e,`output`)})}catch(e){console.warn(`Could not create render link for link id: [${t.id}].`,t,e);return}t._dragging=!0,i.push(t)}}r.connectingTo=`input`,r.draggingExistingLinks=!0,this._setLegacyLinks(!1)}moveOutputLink(e,t){if(this.isConnecting)throw Error(`Already dragging links.`);let{state:n,renderLinks:r}=this;if(t._floatingLinks?.size)for(let n of t._floatingLinks.values())try{let t=K.getFirstReroute(e,n);if(!t)throw Error(`Invalid reroute id: [${n.parentId}] for floating link id: [${n.id}].`);let i=new FloatingRenderLink(e,n,`output`,t);if(this.events.dispatch(`before-move-output`,i)===!1)continue;r.push(i),this.floatingLinks.push(n)}catch(e){console.warn(`Could not create render link for link id: [${n.id}].`,n,e)}if(t.links?.length)for(let n of t.links){let t=e.links.get(n);if(!t)continue;let i=K.getFirstReroute(e,t);i?(i._dragging=!0,this.hiddenReroutes.add(i)):t._dragging=!0,this.outputLinks.push(t);try{if(t.target_id===-20){if(!(e instanceof bt)){console.warn(`Subgraph output link found in non-subgraph network.`);continue}let n=e.outputs.at(t.target_slot);if(!n)throw Error(`No subgraph output found for link.`);let i=new ToOutputFromIoNodeLink(e,e.outputNode,n);i.fromDirection=I.NONE,r.push(i);continue}let n=new MovingOutputLink(e,t,i,I.RIGHT);if(this.events.dispatch(`before-move-output`,n)===!1)continue;r.push(n)}catch(e){console.warn(`Could not create render link for link id: [${t.id}].`,t,e);continue}}r.length!==0&&(n.draggingExistingLinks=!0,n.multi=!0,n.connectingTo=`output`,this._setLegacyLinks(!0))}dragNewFromOutput(e,t,n,r){if(this.isConnecting)throw Error(`Already dragging links.`);let{state:i}=this,a=new ToInputRenderLink(e,t,n,r);this.renderLinks.push(a),i.connectingTo=`input`,this._setLegacyLinks(!1)}dragNewFromInput(e,t,n,r){if(this.isConnecting)throw Error(`Already dragging links.`);let{state:i}=this,a=new ToOutputRenderLink(e,t,n,r);this.renderLinks.push(a),i.connectingTo=`output`,this._setLegacyLinks(!0)}dragNewFromSubgraphInput(e,t,n,r){if(this.isConnecting)throw Error(`Already dragging links.`);let i=new ToInputFromIoNodeLink(e,t,n,r);this.renderLinks.push(i),this.state.connectingTo=`input`,this._setLegacyLinks(!1)}dragNewFromSubgraphOutput(e,t,n,r){if(this.isConnecting)throw Error(`Already dragging links.`);let i=new ToOutputFromIoNodeLink(e,t,n,r);this.renderLinks.push(i),this.state.connectingTo=`output`,this._setLegacyLinks(!0)}dragFromReroute(e,t){if(this.isConnecting)throw Error(`Already dragging links.`);let n=t.firstLink??t.firstFloatingLink;if(!n){console.warn(`No link found for reroute.`);return}if(n.origin_id===-10){if(!(e instanceof bt)){console.warn(`Subgraph input link found in non-subgraph network.`);return}
2let r=e.inputs.at(n.origin_slot);if(!r)throw Error(`No subgraph input found for link.`);let i=new ToInputFromIoNodeLink(e,e.inputNode,r,t);i.fromDirection=I.NONE,this.renderLinks.push(i),this.state.connectingTo=`input`,this._setLegacyLinks(!1);return}let r=e.getNodeById(n.origin_id);if(!r){console.warn(`No output node found for link.`,n);return}let i=r.outputs.at(n.origin_slot);if(!i){console.warn(`No output slot found for link.`,n);return}let a=new ToInputRenderLink(e,r,i,t);a.fromDirection=I.NONE,this.renderLinks.push(a),this.state.connectingTo=`input`,this._setLegacyLinks(!1)}dragFromRerouteToOutput(e,t){if(this.isConnecting)throw Error(`Already dragging links.`);let n=t.firstLink??t.firstFloatingLink;if(!n){console.warn(`No link found for reroute.`);return}if(n.target_id===-20){if(!(e instanceof bt)){console.warn(`Subgraph output link found in non-subgraph network.`);return}let r=e.outputs.at(n.target_slot);if(!r)throw Error(`No subgraph output found for link.`);let i=new ToOutputFromIoNodeLink(e,e.outputNode,r,t);i.fromDirection=I.NONE,this.renderLinks.push(i),this.state.connectingTo=`output`,this._setLegacyLinks(!1);return}let r=e.getNodeById(n.target_id);if(!r){console.warn(`No input node found for link.`,n);return}let i=r.inputs.at(n.target_slot);if(!i){console.warn(`No input slot found for link.`,n);return}let a=new ToOutputFromRerouteLink(e,r,i,t,this);a.fromDirection=I.LEFT,this.renderLinks.push(a),this.state.connectingTo=`output`,this._setLegacyLinks(!0)}dragFromLinkSegment(e,t){if(this.isConnecting)throw Error(`Already dragging links.`);let{state:n}=this;if(t.origin_id==null||t.origin_slot==null)return;let r=e.getNodeById(t.origin_id);if(!r)return;let i=r.outputs.at(t.origin_slot);if(!i)return;let a=new ToInputRenderLink(e,r,i,e.getReroute(t.parentId));a.fromDirection=I.NONE,this.renderLinks.push(a),n.connectingTo=`input`,this._setLegacyLinks(!1)}dropLinks(e,t){if(!(!this.isConnecting&&this.events.dispatch(`before-drop-links`,{renderLinks:this.renderLinks,event:t})===!1))try{let{canvasX:n,canvasY:r}=t,i=e.getIoNodeOnPos?.(n,r);if(i){this.dropOnIoNode(i,t);return}let a=e.getNodeOnPos(n,r)??void 0;if(a)this.dropOnNode(a,t);else{let i=e.getRerouteOnPos(n,r);i&&this.isRerouteValidDrop(i)?this.dropOnReroute(i,t):this.dropOnNothing(t)}}finally{this.events.dispatch(`after-drop-links`,{renderLinks:this.renderLinks,event:t})}}dropOnIoNode(e,t){let{renderLinks:n,state:r}=this,{connectingTo:i}=r,{canvasX:a,canvasY:o}=t;if(i===`input`&&e instanceof SubgraphOutputNode){let r=e.getSlotInPosition(a,o);if(!r){this.dropOnNothing(t);return}let i=r;for(let t of n)if(t.connectToSubgraphOutput(i,this.events),r instanceof EmptySubgraphOutput&&e.slots.length>0){let a=e.slots[e.slots.length-1],o=n[n.indexOf(t)+1];i=o&&t.fromSlot.type===o.fromSlot.type?a:r}}else if(i===`output`&&e instanceof SubgraphInputNode){let r=e.getSlotInPosition(a,o);if(!r){this.dropOnNothing(t);return}let i=r;for(let t of n){if(`canConnectToSubgraphInput`in t&&!t.canConnectToSubgraphInput(i)){console.warn(`Invalid connection type`,t.fromSlot.type,`->`,i.type);continue}if(t.connectToSubgraphInput(i,this.events),r instanceof EmptySubgraphInput&&e.slots.length>0){let a=e.slots[e.slots.length-1],o=n[n.indexOf(t)+1];i=o&&t.fromSlot.type===o.fromSlot.type?a:r}}}else console.error(`Invalid connectingTo state &/ ioNode`,i,e)}dropOnNode(e,t){let{renderLinks:n,state:r}=this,{connectingTo:i}=r,{canvasX:a,canvasY:o}=t;if(!n.every(t=>t.node===e)){if(i===`output`){let n=e.getOutputOnPos([a,o]);n?this._dropOnOutput(e,n):this.connectToNode(e,t)}else if(i===`input`){let n=e.getInputOnPos([a,o])??e.getSlotFromWidget(this.overWidget);n?this._dropOnInput(e,n):this.connectToNode(e,t)}}}dropOnReroute(e,t){if(this.events.dispatch(`dropped-on-reroute`,{reroute:e,event:t})!==!1){if(this.state.connectingTo===`input`){if(this.renderLinks.length!==1)throw Error(`Attempted to connect ${this.renderLinks.length} input links to a reroute.`);let t=this.renderLinks[0];this._connectOutputToReroute(e,t);return}for(let t of this.renderLinks){if(t.toType!==`output`)continue;let n=e.findSourceOutput();if(!n)continue;let{node:r,output:i}=n;t.canConnectToOutput(r,i)&&t.connectToRerouteOutput(e,r,i,this.events)}}}_connectOutputToReroute(e,t){let n=e.findTargetInputs();if(!n?.length)return;let r=e.getReroutes();if(r===null)throw Error(`Reroute loop detected.`);let i=r.slice(0,-1).reverse();if(t instanceof ToInputRenderLink){let{node:n,fromSlot:r,fromSlotIndex:a,fromReroute:o}=t;if(e.setFloatingLinkOrigin(n,r,a),o!=null)for(let t of i){if(t.id===o.id)break;for(let n of e.floatingLinkIds)t.floatingLinkIds.delete(n)}}let a=n.filter(n=>t.toType===`input`&&canConnectInputLinkToReroute(t,n.node,n.input,e));for(let n of a)t.connectToRerouteInput(e,n,this.events,i)}dropOnNothing(e){v(this.renderLinks,e=>
2e instanceof MovingInputLink&&e.disconnectOnDrop).forEach(e=>e.disconnect()),this.renderLinks.length!==0&&this.events.dispatch(`dropped-on-canvas`,e)!==!1&&this.disconnectLinks()}disconnectLinks(){for(let e of this.renderLinks)(e instanceof MovingLinkBase||e instanceof ToInputFromIoNodeLink)&&e.disconnect()}connectToNode(e,t){let{state:{connectingTo:n}}=this;if(this.events.dispatch(`dropped-on-node`,{node:e,event:t})===!1)return;let r=this.renderLinks[0];if(r){if(n===`output`){let t=e.findOutputByType(r.fromSlot.type)?.slot;if(t===void 0){console.warn(`Could not find slot for link type: [${r.fromSlot.type}].`);return}this._dropOnOutput(e,t)}else if(n===`input`){let t=e.findInputByType(r.fromSlot.type)?.slot;if(t===void 0){console.warn(`Could not find slot for link type: [${r.fromSlot.type}].`);return}this._dropOnInput(e,t)}}}_dropOnInput(e,t){for(let n of this.renderLinks)n.canConnectToInput(e,t)&&n.connectToInput(e,t,this.events)}_dropOnOutput(e,t){for(let n of this.renderLinks){if(!n.canConnectToOutput(e,t)){n instanceof MovingOutputLink&&n.link.parentId!==void 0&&n.outputNode.connectSlots(n.outputSlot,n.inputNode,n.inputSlot,void 0);continue}n.connectToOutput(e,t,this.events)}}isInputValidDrop(e,t){return this.renderLinks.some(n=>n.canConnectToInput(e,t))}isNodeValidDrop(e){return this.state.connectingTo===`output`?e.outputs.some(t=>this.renderLinks.some(n=>n.canConnectToOutput(e,t))):e.inputs.some(t=>this.renderLinks.some(n=>n.canConnectToInput(e,t)))}isSubgraphInputValidDrop(e){return this.renderLinks.some(t=>`canConnectToSubgraphInput`in t&&t.canConnectToSubgraphInput(e))}isRerouteValidDrop(e){if(this.state.connectingTo===`input`){let t=e.findTargetInputs();if(!t?.length)return!1;for(let{node:n,input:r}of t)for(let t of this.renderLinks)if(t.toType===`input`&&canConnectInputLinkToReroute(t,n,r,e))return!0}else{let t=e.findSourceOutput();if(!t)return!1;let{node:n,output:r}=t;for(let t of this.renderLinks)if(t.toType===`output`&&t.canConnectToReroute(e)&&t.canConnectToOutput(n,r))return!0}return!1}_setLegacyLinks(e){let t=this.renderLinks.map(t=>{let n=e?t.fromSlot:null,r=e?null:t.fromSlot,i=t instanceof MovingLinkBase?t.link?.parentId:t.fromReroute?.id;return{node:t.node,slot:t.fromSlotIndex,input:n,output:r,pos:t.fromPos,afterRerouteId:i}});this._setConnectingLinks(t)}export(e){return{renderLinks:[...this.renderLinks],inputLinks:[...this.inputLinks],outputLinks:[...this.outputLinks],floatingLinks:[...this.floatingLinks],state:{...this.state},network:e}}listenUntilReset(e,t,n){this.events.addEventListener(e,t,n),this.events.addEventListener(`reset`,()=>this.events.removeEventListener(e,t),{once:!0})}reset(e=!1){if(this.events.dispatch(`reset`,e)===!1)return;let{state:t,outputLinks:n,inputLinks:r,hiddenReroutes:i,renderLinks:a,floatingLinks:o}=this;if(!(!e&&t.connectingTo===void 0)){t.connectingTo=void 0;for(let e of n)delete e._dragging;for(let e of r)delete e._dragging;for(let e of o)delete e._dragging;for(let e of i)delete e._dragging;a.length=0,r.length=0,n.length=0,o.length=0,i.clear(),t.multi=!1,t.draggingExistingLinks=!1,t.snapLinksPos=void 0}}};function canConnectInputLinkToReroute(e,t,n,r){let{fromReroute:i}=e;if(!e.canConnectToInput(t,n)||i?.id===r.id||i?.getReroutes()?.includes(r))return!1;if(e instanceof ToInputRenderLink){if(r.parentId==null){if(r.firstLink?.hasOrigin(e.node.id,e.fromSlotIndex))return!1}else if(e.fromReroute?.id===r.parentId)return!1}return!0}var RecursionError=class extends Error{constructor(e){super(e),this.name=`RecursionError`}},nt=c(`domWidget`,()=>{let e=r(new Map),t=l(()=>[...e.value.values()].filter(e=>e.active)),n=l(()=>[...e.value.values()].filter(e=>!e.active));function registerWidget(t){e.value.set(t.id,{widget:i(t),visible:!0,readonly:!1,zIndex:0,pos:[0,0],size:[0,0],active:!0})}function unregisterWidget(t){e.value.delete(t)}function activateWidget(t){let n=e.value.get(t);n&&(n.active=!0)}function deactivateWidget(t){let n=e.value.get(t);n&&(n.active=!1)}function setWidget(t){let n=e.value.get(t.id);n&&(n.active=!0,n.widget=t)}function setPositionOverride(t,n){let r=e.value.get(t);if(!r)return;let a=r.positionOverride;a&&a.node===n.node&&a.widget===n.widget||(r.positionOverride={node:i(n.node),widget:i(n.widget)}
2)}function clearPositionOverride(t){let n=e.value.get(t);n&&(n.positionOverride=void 0)}function clear(){e.value.clear()}return{widgetStates:e,activeWidgetStates:t,inactiveWidgetStates:n,registerWidget,unregisterWidget,activateWidget,deactivateWidget,setWidget,setPositionOverride,clearPositionOverride,clear}});function isPromotedWidgetView(e){return`sourceNodeId`in e&&`sourceWidgetName`in e}var rt=100;function traversePromotedWidgetChain(e,t,n,r){let i=new Set,a=new WeakMap,o=0,s=e,c=t,l=n,u=r;for(let e=0;e<rt;e++){let e=a.get(s);e===void 0&&(e=o,o+=1,a.set(s,e));let t=`${e}:${c}:${l}:${u??``}`;if(i.has(t))return{status:`failure`,failure:`cycle`};i.add(t);let n=s.subgraph.getNodeById(c);if(!n)return{status:`failure`,failure:`missing-node`};let r=findWidgetByIdentity(n.widgets,l,u);if(!r)return{status:`failure`,failure:`missing-widget`};if(!isPromotedWidgetView(r))return{status:`resolved`,resolved:{node:n,widget:r}};if(!r.node?.isSubgraphNode())return{status:`failure`,failure:`missing-node`};s=r.node,c=r.sourceNodeId,l=r.sourceW
2idgetName,u=void 0}return{status:`failure`,failure:`max-depth-exceeded`}}function findWidgetByIdentity(e,t,n){if(e)return n?e.find(e=>isPromotedWidgetView(e)&&(e.disambiguatingSourceNodeId??e.sourceNodeId)===n&&(e.sourceWidgetName===t||e.name===t)):e.find(e=>e.name===t)}function resolvePromotedWidgetAtHost(e,t,n,r){let i=e.subgraph.getNodeById(t);if(!i)return;let a=findWidgetByIdentity(i.widgets,n,r);if(a)return{node:i,widget:a}}function resolveConcretePromotedWidget(e,t,n,r){return e.isSubgraphNode()?traversePromotedWidgetChain(e,t,n,r):{status:`failure`,failure:`invalid-host`}}function matchPromotedInput(e,t){if(!e)return;let n=e.find(e=>e._widget===t);if(n)return n;let r=e.filter(e=>e.name===t.name);return r.length===1?r[0]:void 0}function hasWidgetNode(e){return`node`in e&&!!e.node}function isWidgetValue(e){return e===void 0||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?!0:typeof e==`object`&&!!e}function hasLegacyMouse(e){return`mouse`in e&&typeof e.mouse==`function`}var it=new Map;function createPromotedWidgetView(e,t,n,r,i,a){return new PromotedWidgetView(e,t,n,r,i,a)}var PromotedWidgetView=class{sourceNodeId;sourceWidgetName;serialize=!1;last_y;computedHeight;graphId;yValue=0;_computedDisabled=!1;projectedSourceNode;projectedSourceWidget;projectedSourceWidgetType;projectedWidget;cachedDeepestByFrame;cachedDeepestFrame=-1;_boundSlot;_boundSlotVersion=-1;constructor(e,t,n,r,i,a){this.subgraphNode=e,this.displayName=r,this.disambiguatingSourceNodeId=i,this.identityName=a,this.sourceNodeId=t,this.sourceWidgetName=n,this.graphId=e.rootGraph.id}get node(){return this.subgraphNode}get name(){return this.identityName??this.sourceWidgetName}get y(){return this.yValue}set y(e){this.yValue=e,this.syncDomOverride()}get computedDisabled(){return this._computedDisabled}set computedDisabled(e){this._computedDisabled=e??!1}get type(){return this.resolveDeepest()?.widget.type??`button`}get options(){return this.resolveDeepest()?.widget.options??{}}get tooltip(){return this.resolveDeepest()?.widget.tooltip}get linkedWidgets(){return this.resolveDeepest()?.widget.linkedWidgets}get value(){let e=this.getWidgetState();return e&&isWidgetValue(e.value)?e.value:this.resolveAtHost()?.widget.value}set value(e){let t=this.getLinkedInputWidgets();if(t.length>0){let n=Pe(),r=!1;for(let i of t){let t=n.getWidget(this.graphId,i.nodeId,i.widgetName);t&&(t.value=e,r=!0)}let i=this.resolveDeepest();if(i){let t=n.getWidget(this.graphId,stripGraphPrefix(String(i.node.id)),i.widget.name);t&&(t.value=e,r=!0)}if(r)return}let n=this.getWidgetState();if(n){n.value=e;return}let r=this.resolveAtHost();r&&isWidgetValue(e)&&(r.widget.value=e)}get label(){let e=this.getBoundSubgraphSlot();return e?e.label??e.displayName??e.name:this.getWidgetState()?.label??this.displayName}set label(e){let t=this.getBoundSubgraphSlot();t&&(t.label=e||void 0);let n=this.getWidgetState();n&&(n.label=e)}getBoundSubgraphSlot(){let e=this.subgraphNode.inputs?.length??0;return this._boundSlotVersion===e?this._boundSlot:(this._boundSlot=this.findBoundSubgraphSlot(),this._boundSlotVersion=e,this._boundSlot)}findBoundSubgraphSlot(){for(let e of this.subgraphNode.inputs??[]){let t=e._subgraphSlot;if(!t)continue;let n=e._widget;if(n&&isPromotedWidgetView(n)&&n.sourceNodeId===this.sourceNodeId&&n.sourceWidgetName===this.sourceWidgetName)return t}}get hidden(){return this.resolveDeepest()?.widget.hidden??!1}get computeLayoutSize(){let e=this.resolveDeepest(),t=e?.widget.computeLayoutSize;if(t)return n=>t.call(e.widget,n)}get computeSize(){let e=this.resolveDeepest(),t=e?.widget.computeSize;if(t)return n=>t.call(e.widget,n)}draw(e,t,n,r,i,a){let o=this.resolveDeepest();if(!o){drawDisconnectedPlaceholder(e,n,r,i);return}if(isBaseDOMWidget(o.widget))return this.syncDomOverride(o);let s=this.getProjectedWidget(o);if(!s||typeof s.drawWidget!=`function`)return;let c=s.y,l=s.computedHeight,u=s.computedDisabled,d=s.label;s.y=this.y,s.computedHeight=this.computedHeight,s.computedDisabled=this.computedDisabled,s.value=this.value,s.label=this.label;
2try{s.drawWidget(e,{width:n,showText:!a,suppressPromotedOutline:!0,previewImages:o.node.imgs})}finally{s.y=c,s.computedHeight=l,s.computedDisabled=u,s.label=d}}onPointerDown(e,t,n){let r=this.resolveAtHost();if(!r)return!1;let i=r.widget;if(typeof i.onPointerDown==`function`&&i.onPointerDown(e,this.subgraphNode,n))return!0;let a=toConcreteWidget(i,this.subgraphNode,!1);return a?this.bindConcretePointerHandlers(e,n,a):hasLegacyMouse(i)?this.handleLegacyMouse(e,i):!1}callback(e,t,n,r,i){this.resolveAtHost()?.widget.callback?.(e,t,n,r,i)}resolveAtHost(){return resolvePromotedWidgetAtHost(this.subgraphNode,this.sourceNodeId,this.sourceWidgetName,this.disambiguatingSourceNodeId)}resolveDeepest(){let e=this.subgraphNode.rootGraph.primaryCanvas?.frame;if(e!==void 0&&this.cachedDeepestFrame===e)return this.cachedDeepestByFrame;let t=resolveConcretePromotedWidget(this.subgraphNode,this.sourceNodeId,this.sourceWidgetName,this.disambiguatingSourceNodeId),n=t.status===`resolved`?t.resolved:void 0;return e!==void 0&&(this.cachedDeepestFrame=e,this.cachedDeepestByFrame=n),n}getWidgetState(){let e=this.getLinkedInputWidgetStates()[0];if(e)return e;let t=this.resolveDeepest();if(t)return Pe().getWidget(this.graphId,stripGraphPrefix(String(t.node.id)),t.widget.name)}getLinkedInputWidgets(){let e=this.subgraphNode.inputs.find(e=>{if(!e._subgraphSlot||matchPromotedInput([e],this)!==e)return!1;let t=e._widget;return t===this?!0:t&&isPromotedWidgetView(t)?t.sourceNodeId===this.sourceNodeId&&t.sourceWidgetName===this.sourceWidgetName&&t.disambiguatingSourceNodeId===this.disambiguatingSourceNodeId:e._subgraphSlot.getConnectedWidgets().filter(hasWidgetNode).some(e=>String(e.node.id)===this.sourceNodeId&&e.name===this.sourceWidgetName)})?._subgraphSlot;return e?e.getConnectedWidgets().filter(hasWidgetNode).map(e=>({nodeId:stripGraphPrefix(String(e.node.id)),widgetName:e.name,widget:e})):[]}getLinkedInputWidgetStates(){let e=Pe();return this.getLinkedInputWidgets().map(({nodeId:t,widgetName:n})=>e.getWidget(this.graphId,t,n)).filter(e=>e!==void 0)}getProjectedWidget(e){if(!(!this.projectedWidget||this.projectedSourceNode!==e.node||this.projectedSourceWidget!==e.widget||this.projectedSourceWidgetType!==e.widget.type))return this.projectedWidget;let t=toConcreteWidget(e.widget,e.node,!1);if(!t){this.projectedWidget=void 0,this.projectedSourceNode=void 0,this.projectedSourceWidget=void 0,this.projectedSourceWidgetType=void 0;return}return this.projectedWidget=t.createCopyForNode(this.subgraphNode),this.projectedSourceNode=e.node,this.projectedSourceWidget=e.widget,this.projectedSourceWidgetType=e.widget.type,this.projectedWidget}bindConcretePointerHandlers(e,t,n){let r=e.eDown;return r?(e.onClick=()=>n.onClick({e:r,node:this.subgraphNode,canvas:t}),e.onDrag=e=>n.onDrag?.({e,node:this.subgraphNode,canvas:t}),!0):!1}handleLegacyMouse(e,t){let n=e.eDown;if(!n)return!1;let r=[n.canvasX-this.subgraphNode.pos[0],n.canvasY-this.subgraphNode.pos[1]];return t.mouse(n,r,this.subgraphNode),e.finally=()=>{let n=e.eUp;if(!n)return;let r=[n.canvasX-this.subgraphNode.pos[0],n.canvasY-this.subgraphNode.pos[1]];t.mouse(n,r,this.subgraphNode)},!0}syncDomOverride(e=this.resolveAtHost()){!e||!isBaseDOMWidget(e.widget)||nt().setPositionOverride(e.widget.id,{node:this.subgraphNode,widget:this})}};function isBaseDOMWidget(e){return`id`in e&&(`element`in e||`component`in e)}function drawDisconnectedPlaceholder(e,t,n,r){let i=readDesignToken(`--color-secondary-background`,`#333`),a=readDesignToken(`--color-text-secondary`,`#999`),o=readDesignToken(`--text-2xs`,`11px`),s=readDesignToken(`--font-inter`,`sans-serif`);e.save(),e.fillStyle=i,e.fillRect(15,n,t-30,r),e.fillStyle=a,e.font=`${o} ${s}`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(he(`subgraphStore.disconnected`),t/2,n+r/2),e.restore()}function readDesignToken(e,t){if(typeof document>`u`)return t;let n=it.get(e);if(n)return n;let r=getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t;return it.set(e,r),r}var at=/^\s*(\d+)\s*:\s*(.+)$/;function canResolve(e,t,n,r){return resolveConcretePromotedWidget(e,t,n,r).status===`resolved`}function tryResolveCandidate(e,t,n,r){if(canResolve(e,t,n,r))return{sourceW
2idgetName:n,...r&&{disambiguatingSourceNodeId:r}}}function resolveLegacyPrefixedEntry(e,t,n,r){let i=n;for(;;){let n=at.exec(i);if(!n)return;let[,a,o]=n;i=o;let s=[a,...r?[r]:[],void 0];for(let n of s){let r=tryResolveCandidate(e,t,i,n);if(r)return r}}}function normalizeLegacyProxyWidgetEntry(e,t,n,r){if(canResolve(e,t,n,r))return{sourceNodeId:t,sourceWidgetName:n,...r&&{disambiguatingSourceNodeId:r}};let i=resolveLegacyPrefixedEntry(e,t,n,r),a=i?.disambiguatingSourceNodeId??r;return{sourceNodeId:t,sourceWidgetName:i?.sourceWidgetName??n,...a&&{disambiguatingSourceNodeId:a}}}function resolveSubgraphInputLink(e,t,n){if(!e.isSubgraphNode())return;let r=e.subgraph.inputNode.slots.find(e=>e.name===t);if(r)for(let t of r.linkIds){let r=e.subgraph.getLink(t);if(!r)continue;let{inputNode:i}=r.resolve(e.subgraph);if(!i||!Array.isArray(i.inputs))continue;let a=i.inputs.find(e=>e.link===t);if(!a)continue;let o,s=!1,c=n({inputNode:i,targetInput:a,getTargetWidget:()=>(s||=(o=i.getWidgetFromSlot(a),!0),o)});if(c!==void 0)return c}}function resolveSubgraphInputTarget(e,t){return resolveSubgraphInputLink(e,t,({inputNode:e,targetInput:t,getTargetWidget:n})=>{if(e.isSubgraphNode()){let r=n();return r?isPromotedWidgetView(r)?{nodeId:String(e.id),widgetName:r.sourceWidgetName,sourceNodeId:r.disambiguatingSourceNodeId??r.sourceNodeId}:{nodeId:String(e.id),widgetName:t.name}:void 0}let r=n();if(r)return{nodeId:String(e.id),widgetName:r.name}})}var ot=`$$canvas-image-preview`,st=new Set([`PreviewImage`,`SaveImage`,`GLSLShader`]);function supportsVirtualCanvasImagePreview(e){return st.has(e.type)}var ct=A(S([j([w(),w(),w()]),j([w(),w()])]));function parseProxyWidgets(e){try{typeof e==`string`&&(e=JSON.parse(e));let t=ct.safeParse(typeof e==`string`?JSON.parse(e):e);if(t.success)return t.data;let n=ce(t.error);console.warn(`Invalid assignment for properties.proxyWidgets:\n${n}`)}catch(e){console.warn(`Failed to parse properties.proxyWidgets:`,e)}return[]}var InvalidLinkError=class extends Error{constructor(e=`Attempted to access a link that was invali
2d.`,t){super(e,{cause:t}),this.name=`InvalidLinkError`}},SlotIndexError=class extends Error{constructor(e=`Attempted to access a slot that was out of bounds.`,t){super(e,{cause:t}),this.name=`SlotIndexError`}},lt=class ExecutableNodeDTO{graph;inputs;_id;get id(){return this._id}get type(){return this.node.type}get title(){return this.node.title}get mode(){return this.node.mode}get comfyClass(){return this.node.comfyClass}get isVirtualNode(){return this.node.isVirtualNode}get widgets(){return this.node.widgets}get subgraphId(){return this.subgraphNode?.subgraph.id}constructor(e,t,n,r){if(this.node=e,this.subgraphNodePath=t,this.nodesByExecutionId=n,this.subgraphNode=r,!e.graph)throw new NullGraphError;this._id=[...this.subgraphNodePath,this.node.id].join(`:`),this.graph=e.graph,this.inputs=this.node.inputs.map(e=>({linkId:e.link,name:e.name,type:e.type})),this.node.applyToGraph&&(this.applyToGraph=(...e)=>this.node.applyToGraph?.(...e))}getInnerNodes(){return this.node.isSubgraphNode()?this.node.getInnerNodes(this.nodesByExecutionId,this.subgraphNodePath):[this]}resolveInput(e,t=new Set,n){let r=`${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${e}`;if(t.has(r))throw new RecursionError(`Circular reference detected while resolving input ${e} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:``}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(`:`)}`:``}. This creates an infinite loop in link resolution. UniqueID: [${r}]`);t.add(r);let i=this.inputs.at(e);if(!i)throw new SlotIndexError(`No input found for flattened id [${this.id}] slot [${e}
2]`);if(i.linkId==null)return;let a=this.graph.getLink(i.linkId);if(!a)throw new InvalidLinkError(`No link found in parent graph for id [${this.id}] slot [${e}] ${i.name}`);let{subgraphNode:o}=this;if(o&&a.originIsIoNode){let e=o.inputs.at(a.origin_slot);if(!e)throw new SlotIndexError(`No input found for slot [${a.origin_slot}] ${i.name}`);let n=e.link;if(n==null){let t=o.getWidgetFromSlot(e);return t?{node:this,origin_id:this.id,origin_slot:-1,widgetInfo:{value:t.value}}:void 0}if(!o.graph)throw new NullGraphError(`SubgraphNode ${o.id} has no graph during input resolution`);let r=o.graph.getLink(n);if(!r)throw new InvalidLinkError(`No outer link found for slot [${a.origin_slot}] ${i.name}`);let s=this.subgraphNodePath.join(`:`),c=this.nodesByExecutionId.get(s);if(!c)throw Error(`No subgraph node DTO found for id [${s}]`);return c.resolveInput(r.target_slot,t)}let s=this.graph.getNodeById(a.origin_id);if(!s)throw new InvalidLinkError(`No input node found for id [${this.id}] slot [${e}] ${i.name}`);let c=[...this.subgraphNodePath,s.id].join(`:`),l=this.nodesByExecutionId.get(c);if(!l)throw Error(`No output node DTO found for id [${c}]`);return l.resolveOutput(a.origin_slot,n??i.type,t)}resolveOutput(e,t,n){let r=`${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${e}`;if(n.has(r))throw new RecursionError(`Circular reference detected while resolving output ${e} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:``}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(`:`)}`:``}. This creates an infinite loop in link resolution. UniqueID: [${r}]`);if(n.add(r),this.mode===B.NEVER)return;if(this.mode===B.BYPASS){let r=this._getBypassSlotIndex(e,t);if(r===-1){console.warn(`[ExecutableNodeDTO.resolveOutput] No input types match type [${t}] for id [${this.id}] slot [${e}
2]`,this);return}return this.resolveInput(r,n)}let{node:i}=this;if(i.isSubgraphNode())return this._resolveSubgraphOutput(e,t,n);if(i.isVirtualNode){let r=this.node.resolveVirtualOutput?.(e);if(r){let e=[...this.nodesByExecutionId.values()].find(e=>e instanceof ExecutableNodeDTO&&e.node===r.node);if(!e)throw Error(`No DTO found for virtual source node [${r.node.id}]`);return e.resolveOutput(r.slot,t,n)}let i=this.node.getInputLink(e);if(i){let{inputNode:r}=i.resolve(this.graph);if(!r)throw new InvalidLinkError(`Virtual node failed to resolve parent [${this.id}] slot [${e}]`);let a=[...this.subgraphNodePath,r.id].join(`:`),o=this.nodesByExecutionId.get(a);if(!o)throw Error(`No input node DTO found for id [${r.id}]`);return o.resolveInput(i.target_slot,n,t)}return}return{node:this,origin_id:this.id,origin_slot:e}}_getBypassSlotIndex(e,t){let{inputs:n}=this,r=n[e],i=this.node.outputs[e].type;if(t===`*`||t===``)return n.length>e?e:0;if(r&&Q.isValidConnection(r.type,i)&&Q.isValidConnection(r.type,t))return e;let a=n.findIndex(e=>e.type===t);return a===-1?n.findIndex(e=>Q.isValidConnection(e.type,i)&&Q.isValidConnection(e.type,t)):a}_resolveSubgraphOutput(e,t,n){let{node:r}=this,i=r.outputs.at(e);if(!i)throw new SlotIndexError(`No output found for flattened id [${this.id}] slot [${e}
2]`);if(!r.isSubgraphNode())throw TypeError(`Node is not a subgraph node: ${r.id}`);let a=r.resolveSubgraphOutputLink(e);if(!a)return;let o=a.outputNode;if(!o)throw Error(`No output node found for id [${this.id}] slot [${e}] ${i.name}`);let s=[...this.subgraphNodePath,r.id,o.id].join(`:`),c=this.nodesByExecutionId.get(s);if(!c)throw Error(`No inner node DTO found for id [${s}]`);return c.resolveOutput(a.link.origin_slot,t,n)}},PromotedWidgetViewManager=class{viewCache=new Map;cachedViews=null;cachedEntryKeys=null;reconcile(e,t){let n=e.map(e=>this.makeKey(e.sourceNodeId,e.sourceWidgetName,e.viewKey));if(this.cachedViews&&this.areEntryKeysEqual(n))return this.cachedViews;let r=[],i=new Set;for(let n of e){let e=this.makeKey(n.sourceNodeId,n.sourceWidgetName,n.viewKey);if(i.has(e))continue;i.add(e);let a=this.viewCache.get(e);if(a){r.push(a);continue}let o=t(n);this.viewCache.set(e,o),r.push(o)}for(let e of this.viewCache.keys())i.has(e)||this.viewCache.delete(e);return this.cachedViews=r,this.cachedEntryKeys=n,r}getOrCreate(e,t,n,r){let i=this.makeKey(e,t,r),a=this.viewCache.get(i);if(a)return a;let o=n();return this.viewCache.set(i,o),o}remove(e,t){this.viewCache.delete(this.makeKey(e,t)),this.invalidateMemoizedList()}removeByViewKey(e,t,n){this.viewCache.delete(this.makeKey(e,t,n)),this.invalidateMemoizedList()}clear(){this.viewCache.clear(),this.invalidateMemoizedList()}invalidateMemoizedList(){this.cachedViews=null,this.cachedEntryKeys=null}areEntryKeysEqual(e){if(!this.cachedEntryKeys||this.cachedEntryKeys.length!==e.length)return!1;for(let t=0;t<e.length;t+=1)if(this.cachedEntryKeys[t]!==e[t])return!1;return!0}makeKey(e,t,n){let r=`${e}:${t}`;return n?`${r}:${n}`:r}};function createBitmapCache(e,t){let n=null;return{get(){if(n)return n;if(!e.complete||e.naturalWidth===0)return e;let r=document.createElement(`canvas`);r.width=t,r.height=t;let i=r.getContext(`2d`);if(!i)return e;try{i.drawImage(e,0,0,t,t)}catch{return e}return n=r,n}}}var ut=new Image;ut.src=`data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath stroke='white' stroke-linecap='round' stroke-width='1.3' d='M9.18613 3.09999H6.81377M9.18613 12.9H7.55288c-3.08678 0-5.35171-2.99581-4.60305-6.08843l.3054-1.26158M14.7486 2.1721l-.5931 2.45c-.132.54533-.6065.92789-1.1508.92789h-2.2993c-.77173 0-1.33797-.74895-1.1508-1.5221l.5931-2.45c.132-.54533.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.74896 1.1508 1.52211Zm-8.3033 0-.59309 2.45c-.13201.54533-.60646.92789-1.15076.92789H2.4021c-.7717 0-1.33793-.74895-1.15077-1.5221l.59309-2.45c.13201-.54533.60647-.9279 1.15077-.9279h2.29935c.77169 0 1.33792.74896 1.15076 1.52211Zm8.3033 9.8-.5931 2.45c-.132.5453-.6065.9279-1.1508.9279h-2.2993c-.77173 0-1.33797-.749-1.1508-1.5221l.5931-2.45c.132-.5453.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.7489 1.1508 1.5221Z'/%3E%3C/svg%3E %3C/svg%3E`;var dt=createBitmapCache(ut,32),SubgraphNode=class extends Y{type;isVirtualNode=!0;graph;get rootGraph(){if(!this.graph)throw new NullGraphError(`SubgraphNode ${this.id} has no graph`);return this.graph.rootGraph}get displayType(){return`Subgraph node`}isSubgraphNode(){return!0}_promotedViewManager=new PromotedWidgetViewManager;_pendingPromotions=[];_cacheVersion=0;_linkedEntriesCache;_promotedViewsCache;_resolveLinkedPromotionBySubgraphInput(e){for(let t of e.linkIds){let e=this.subgraph.getLink(t);if(!e)continue;let{inputNode:n}=e.resolve(this.subgraph);if(!n||!Array.isArray(n.inputs))continue;let r=n.inputs.find(e=>e.link===t);if(!r)continue;let i=n.getWidgetFromSlot(r);if(i)return n.isSubgraphNode()?isPromotedWidgetView(i)?{sourceNodeId:String(n.id),sourceWidgetName:i.sourceWidgetName,disambiguatingSourceNodeId:i.disambiguatingSourceNodeId??i.sourceNodeId}:{sourceNodeId:String(n.id),sourceWidgetName:r.name}:{sourceNodeId:String(n.id),sourceWidgetName:i.name}}}_getLinkedPromotionEntries(e=!0){let t=this._hasMissingBoundSourceWidget(),n=this._linkedEntriesCache;if(e&&n?.version===this._cacheVersion&&n.hasMissingBoundSourceWidget===t)return n.entries;let r=[];for(let e of this.inputs){let t=e._subgraphSlot;if(!t)continue;let n=e._widget&&isPromotedWidgetView(e._widget)?e._widget:void 0;if(n&&this.subgraph.getNodeById(n.sourceNodeId)?.widgets?.some(e=>
2e.name===n.sourceWidgetName)===!0){r.push({inputName:e.label??e.name,inputKey:String(t.id),slotName:t.name,sourceNodeId:n.sourceNodeId,sourceWidgetName:n.sourceWidgetName});continue}let i=this._resolveLinkedPromotionBySubgraphInput(t);i&&r.push({inputName:e.label??e.name,inputKey:String(t.id),slotName:t.name,...i})}let i=new Set,a=r.filter(e=>{let t=this._makePromotionViewKey(e.inputKey,e.sourceNodeId,e.sourceWidgetName,e.inputName,e.disambiguatingSourceNodeId);return i.has(t)?!1:(i.add(t),!0)});return e&&(this._linkedEntriesCache={version:this._cacheVersion,hasMissingBoundSourceWidget:t,entries:a}),a}_hasMissingBoundSourceWidget(){return this.inputs.some(e=>{let t=e._widget&&isPromotedWidgetView(e._widget)?e._widget:void 0;return t?this.subgraph.getNodeById(t.sourceNodeId)?.widgets?.some(e=>e.name===t.sourceWidgetName)!==!0:!1})}_getPromotedViews(){let e=W().getPromotionsRef(this.rootGraph.id,this.id),t=this._hasMissingBoundSourceWidget(),n=this._promotedViewsCache;if(n?.version===this._cacheVersion&&n.entriesRef===e&&n.hasMissingBoundSourceWidget===t)return n.views;let r=this._getLinkedPromotionEntries(),{displayNameByViewKey:i,reconcileEntries:a}=this._buildPromotionReconcileState(e,r),o=this._promotedViewManager.reconcile(a,e=>createPromotedWidgetView(this,e.sourceNodeId,e.sourceWidgetName,e.viewKey?i.get(e.viewKey):void 0,e.disambiguatingSourceNodeId,e.slotName));return this._promotedViewsCache={version:this._cacheVersion,entriesRef:e,hasMissingBoundSourceWidget:t,views:o},o}_invalidatePromotedViewsCache(){this._cacheVersion++}_syncPromotions(){if(this.id===-1)return;let e=W(),t=e.getPromotionsRef(this.rootGraph.id,this.id),n=this._getLinkedPromotionEntries(!1),{mergedEntries:r}=this._buildPromotionPersistenceState(t,n);(r.length!==t.length||r.some((e,n)=>e.sourceNodeId!==t[n]?.sourceNodeId||e.sourceWidgetName!==t[n]?.sourceWidgetName||e.disambiguatingSourceNodeId!==t[n]?.disambiguatingSourceNodeId))&&e.setPromotions(this.rootGraph.id,this.id,r)}_buildPromotionReconcileState(e,t){let{fallbackStoredEntries:n}=this._collectLinkedAndFallbackEntries(e,t),r=this._buildLinkedReconcileEntries(t),i=this._shouldPersistLinkedOnly(t,n),a=n.map(e=>e.disambiguatingSourceNodeId?{sourceNodeId:e.sourceNodeId,sourceWidgetName:e.sourceWidgetName,disambiguatingSourceNodeId:e.disambiguatingSourceNodeId,viewKey:`src:${e.sourceNodeId}:${e.sourceWidgetName}:${e.disambiguatingSourceNodeId}`}:e),o=i?r:[...r,...a];return{displayNameByViewKey:this._buildDisplayNameByViewKey(t),reconcileEntries:o}}_buildPromotionPersistenceState(e,t){let{linkedPromotionEntries:n,fallbackStoredEntries:r}=this._collectLinkedAndFallbackEntries(e,t);return{mergedEntries:this._shouldPersistLinkedOnly(t,r)?n:[...n,...r]}}_collectLinkedAndFallbackEntries(e,t){let n=this._toPromotionEntries(t),r=new Set(n.map(e=>this._makePromotionEntryKey(e.sourceNodeId,e.sourceWidgetName,e.disambiguatingSourceNodeId))),i=this._getConnectedPromotionEntryKeys();for(let e of i)r.add(e);let a=this._getFallbackStoredEntries(e,r);return{linkedPromotionEntries:n,fallbackStoredEntries:this._pruneStaleAliasFallbackEntries(a,n)}}_shouldPersistLinkedOnly(e,t){if(!(this.inputs.length>0&&e.length===this.inputs.length))return!1;let n=new Set(e.map(e=>this._makePromotionEntryKey(e.sourceNodeId,e.sourceWidgetName))),r=new Set(e.map(e=>e.sourceWidgetName));return!t.some(e=>{let t=this.subgraph.getNodeById(e.sourceNodeId);return t?t.type===`PrimitiveNode`||t.widgets?.some(t=>t.name===e.sourceWidgetName)===!0?!0:n.has(this._makePromotionEntryKey(e.sourceNodeId,e.sourceWidgetName)):r.has(e.sourceWidgetName)})}_toPromotionEntries(e){return e.map(({sourceNodeId:e,sourceWidgetName:t,disambiguatingSourceNodeId:n})=>({sourceNodeId:e,sourceWidgetName:t,...n&&{disambiguatingSourceNodeId:n}}))}_getFallbackStoredEntries(e,t){return e.filter(e=>!t.has(this._makePromotionEntryKey(e.sourceNodeId,e.sourceWidgetName,e.disambiguatingSourceNodeId)))}_pruneStaleAliasFallbackEntries(e,t){if(e.length===0||t.length===0)return e;let n=new Set(t.map(e=>this._resolveConcretePromotionEntryKey(e)).filter(e=>e!==void 0));if(n.size===0)return e;let r=[];for(let t of e){if(!this.subgraph.getNodeById(t.sourceNodeId))continue;let e=this._resolveConcretePromotionEntryKey(t);e&&n.has(e)||r.push(t)}return r}
2_resolveConcretePromotionEntryKey(e){let t=resolveConcretePromotedWidget(this,e.sourceNodeId,e.sourceWidgetName,e.disambiguatingSourceNodeId);if(t.status===`resolved`)return this._makePromotionEntryKey(String(t.resolved.node.id),t.resolved.widget.name)}_getConnectedPromotionEntryKeys(){let e=new Set;for(let t of this.inputs){let n=t._subgraphSlot;if(!n)continue;let r=n.getConnectedWidgets();for(let t of r)hasWidgetNode(t)&&e.add(this._makePromotionEntryKey(String(t.node.id),t.name))}return e}_buildLinkedReconcileEntries(e){return e.map(({inputKey:e,inputName:t,slotName:n,sourceNodeId:r,sourceWidgetName:i,disambiguatingSourceNodeId:a})=>({sourceNodeId:r,sourceWidgetName:i,slotName:n,disambiguatingSourceNodeId:a,viewKey:this._makePromotionViewKey(e,r,i,t,a)}))}_buildDisplayNameByViewKey(e){return new Map(e.map(e=>[this._makePromotionViewKey(e.inputKey,e.sourceNodeId,e.sourceWidgetName,e.inputName,e.disambiguatingSourceNodeId),e.inputName]))}_makePromotionEntryKey(e,t,n){return makePromotionEntryKey({sourceNodeId:e,sourceWidgetName:t,disambiguatingSourceNodeId:n})}_makePromotionViewKey(e,t,n,r=``,i){return i?JSON.stringify([e,t,n,r,i]):JSON.stringify([e,t,n,r])}_serializeEntries(e){return e.map(e=>e.disambiguatingSourceNodeId?[e.sourceNodeId,e.sourceWidgetName,e.disambiguatingSourceNodeId]:[e.sourceNodeId,e.sourceWidgetName])}_resolveLegacyEntry(e){let t=this.inputs.find(t=>t.name===e);if(!t?._widget){let t=resolveSubgraphInputTarget(this,e);return t?[t.nodeId,t.widgetName]:void 0}let n=t._widget;if(isPromotedWidgetView(n))return[n.sourceNodeId,n.sourceWidgetName];let r=resolveSubgraphInputTarget(this,e);if(r)return[r.nodeId,r.widgetName]}_eventAbortController=new AbortController;constructor(e,t,n){super(t.name,t.id),this.subgraph=t,this.graph=e,Object.defineProperty(this,`widgets`,{get:()=>this._getPromotedViews(),set:()=>{},configurable:!0,enumerable:!0});let r=this.subgraph.events,{signal:i}=this._eventAbortController;r.addEventListener(`input-added`,e=>{let n=e.detail.input,{name:r,type:i}=n,a=this.inputs.find(e=>e._subgraphSlot===n||e._subgraphSlot&&e._subgraphSlot.id===n.id);if(a){this._addSubgraphInputListeners(n,a);let e=n.linkIds[0];if(e===void 0)return;let r=this.subgraph.getLink(e);if(!r)return;let{inputNode:i,input:o}=r.resolve(t);if(!i||!o)return;let s=i.getWidgetFromSlot(o);s&&this._setWidget(n,a,s,o.widget,i);return}let o=this.addInput(r,i,{_subgraphSlot:n});this._invalidatePromotedViewsCache(),this._addSubgraphInputListeners(n,o)},{signal:i}),r.addEventListener(`removing-input`,e=>{let t=e.detail.input._widget;t&&this.ensureWidgetRemoved(t),this.removeInput(e.detail.index),this._invalidatePromotedViewsCache(),this._syncPromotions(),this.setDirtyCanvas(!0,!0)},{signal:i}
2),r.addEventListener(`output-added`,e=>{let{name:t,type:n}=e.detail.output;this.addOutput(t,n)},{signal:i}),r.addEventListener(`removing-output`,e=>{this.removeOutput(e.detail.index),this.setDirtyCanvas(!0,!0)},{signal:i}),r.addEventListener(`renaming-input`,e=>{let{index:t,newName:n}=e.detail,r=this.inputs.at(t);if(!r)throw Error(`Subgraph input not found`);r.label=n,r._widget&&(r._widget.label=n),this._invalidatePromotedViewsCache(),this.graph?.trigger(`node:slot-label:changed`,{nodeId:this.id,slotType:N.INPUT})},{signal:i}),r.addEventListener(`renaming-output`,e=>{let{index:t,newName:n}=e.detail,r=this.outputs.at(t);if(!r)throw Error(`Subgraph output not found`);r.label=n,this.graph?.trigger(`node:slot-label:changed`,{nodeId:this.id,slotType:N.OUTPUT})},{signal:i}),this.type=t.id,this.configure(n),this.addTitleButton({name:`enter_subgraph`,text:``,yOffset:0,xOffset:-10,fontSize:16})}onTitleButtonClick(e,t){e.name===`enter_subgraph`?t.openSubgraph(this.subgraph,this):super.onTitleButtonClick(e,t)}_addSubgraphInputListeners(e,t){t._subgraphSlot=e,t._listenerController&&typeof t._listenerController.abort==`function`&&t._listenerController.abort(),t._listenerController=new AbortController;let{signal:n}=t._listenerController;e.events.addEventListener(`input-connected`,n=>{if(this._invalidatePromotedViewsCache(),t.shape=this.getSlotShape(e,n.detail.input),!n.detail.widget||!n.detail.node)return;let r={sourceNodeId:String(n.detail.node.id),sourceWidgetName:n.detail.widget.name};W().isPromoted(this.rootGraph.id,this.id,r)&&W().demote(this.rootGraph.id,this.id,r);let i=t._widget&&isPromotedWidgetView(t._widget)?t._widget:void 0,a=i&&this.subgraph.getNodeById(i.sourceNodeId)?.widgets?.some(e=>e.name===i.sourceWidgetName)!==!0;(!t._widget||a)&&this._setWidget(e,t,n.detail.widget,n.detail.input.widget,n.detail.node),this._syncPromotions()},{signal:n}),e.events.addEventListener(`input-disconnected`,()=>{if(this._invalidatePromotedViewsCache(),t.shape=this.getSlotShape(e),e.getConnectedWidgets().length>0){this._resolveInputWidget(e,t),this._syncPromotions();return}t._widget&&this.ensureWidgetRemoved(t._widget),delete t.pos,delete t.widget,t._widget=void 0,this._syncPromotions()},{signal:n})}_rebindInputSubgraphSlots(){this._invalidatePromotedViewsCache();let e=[...this.subgraph.inputNode.slots],t=new Map,n=new Map;for(let r of e){let e=`${r.name}:${String(r.type)}`,i=t.get(e);i?i.push(r):t.set(e,[r]);let a=n.get(r.name);a?a.push(r):n.set(r.name,[r])}let r=new Set,takeUnassignedSlot=e=>{if(e)return e.find(e=>!r.has(String(e.id)))};for(let e of this.inputs){let i=e._subgraphSlot;if(i&&this.subgraph.inputNode.slots.some(e=>e===i)){r.add(String(i.id));continue}let a=`${e.name}:${String(e.type)}`,o=takeUnassignedSlot(t.get(a))??takeUnassignedSlot(n.get(e.name));o?(e._subgraphSlot=o,r.add(String(o.id))):delete e._subgraphSlot}}configure(e){for(let e of this.inputs)e._listenerController&&typeof e._listenerController.abort==`function`&&e._listenerController.abort();this.inputs.length=0,this.inputs.push(...this.subgraph.inputNode.slots.map(e=>Object.assign(new NodeInputSlot({name:e.name,localized_name:e.localized_name,label:e.label,shape:this.getSlotShape(e),type:e.type,link:null},this),{_subgraphSlot:e}))),this.outputs.length=0,this.outputs.push(...this.subgraph.outputNode.slots.map(e=>new NodeOutputSlot({name:e.name,localized_name:e.localized_name,label:e.label,type:e.type,links:null},this))),super.configure(e)}_internalConfigureAfterSlots(){this._rebindInputSubgraphSlots(),this.inputs=this.inputs.filter(e=>e._subgraphSlot),this.properties.proxyWidgets??=[],this._promotedViewManager.clear(),this._invalidatePromotedViewsCache();let e=parseProxyWidgets(this.properties.proxyWidgets),t=W(),n=e.map(([e,t,n])=>{if(e===`-1`){let e=this._resolveLegacyEntry(t);return e?{sourceNodeId:e[0],sourceWidgetName:e[1]}:null}return this.subgraph.getNodeById(e)?normalizeLegacyProxyWidgetEntry(this,e,t,n):null}).filter(e=>e!==null);t.setPromotions(this.rootGraph.id,this.id,n);let r=this._serializeEntries(n);JSON.stringify(r)!==JSON.stringify(e)&&(this.properties.proxyWidgets=r);for(let e of this.inputs){let t=e._subgraphSlot;if(!t){console.warn(`[SubgraphNode.configure] No subgraph input found for input ${e.name}, skipping`);continue}this._addSubgraphInputListeners(t,e),this._resolveInputWidget(t,e)}this._syncPromotions();for(let e of this.subgraph.nodes){if(!supportsVirtualCanvasImagePreview(e))continue;
2let n={sourceNodeId:String(e.id),sourceWidgetName:ot};t.isPromoted(this.rootGraph.id,this.id,n)||t.promote(this.rootGraph.id,this.id,n)}}rebuildInputWidgetBindings(){this._promotedViewManager.clear(),this._invalidatePromotedViewsCache();for(let e of this.inputs){delete e.widget,delete e.pos,e._widget=void 0;let t=e._subgraphSlot;t&&this._resolveInputWidget(t,e)}this._syncPromotions()}_resolveInputWidget(e,t){for(let n of e.linkIds){let r=this.subgraph.getLink(n);if(!r){console.warn(`[SubgraphNode.configure] No link found for link ID ${n}`,this);continue}let{inputNode:i}=r.resolve(this.subgraph);if(!i){console.warn(`Failed to resolve inputNode`,r,this);continue}let a=i.inputs.find(e=>e.link===n);if(!a){console.warn(`Failed to find corresponding input`,r,i);continue}let o=i.getWidgetFromSlot(a);if(o){this._setWidget(e,t,o,a.widget,i);break}}}_setWidget(e,t,n,r,i){this._invalidatePromotedViewsCache(),this._flushPendingPromotions();let a=String(i.id),o=n.name,s=i.isSubgraphNode()&&isPromotedWidgetView(n)?n.sourceNodeId:void 0,c=t._widget;c&&isPromotedWidgetView(c)&&(c.sourceNodeId!==a||c.sourceWidgetName!==o)&&(W().demote(this.rootGraph.id,this.id,c),this._removePromotedView(c)),this.id===-1?this._pendingPromotions.some(e=>e.sourceNodeId===a&&e.sourceWidgetName===o&&e.disambiguatingSourceNodeId===s)||this._pendingPromotions.push({sourceNodeId:a,sourceWidgetName:o,...s&&{disambiguatingSourceNodeId:s}}):W().promote(this.rootGraph.id,this.id,{sourceNodeId:a,sourceWidgetName:o,disambiguatingSourceNodeId:s});let l=this._promotedViewManager.getOrCreate(a,o,()=>createPromotedWidgetView(this,a,o,t.label??e.name,s,e.name),this._makePromotionViewKey(String(e.id),a,o,t.label??t.name,s));t.widget??={name:e.name},t.widget.name=e.name,r&&Object.setPrototypeOf(t.widget,r),t._widget=l,this.subgraph.events.dispatch(`widget-promoted`,{widget:l,subgraphNode:this})}_flushPendingPromotions(){if(!(this.id===-1||this._pendingPromotions.length===0)){for(let e of this._pendingPromotions)W().promote(this.rootGraph.id,this.id,e);this._pendingPromotions=[]}}onAdded(e){this._flushPendingPromotions(),this._syncPromotions()}addInput(e,t,n={}){return super.addInput(e,t,n)}getSlotFromWidget(e){return!e||!isPromotedWidgetView(e)?super.getSlotFromWidget(e):this.inputs.find(t=>t._widget===e)}getWidgetFromSlot(e){return e._widget?e._widget:super.getWidgetFromSlot(e)}getInputLink(e){let t=this.subgraph.outputNode.slots[e].getLinks().at(0);if(!t)return console.warn(`SubgraphNode.getInputLink: no inner link found for slot ${e}`),null;let n=K.create(t);return n.origin_id=`${this.id}:${t.origin_id}`,n.origin_slot=t.origin_slot,n}resolveSubgraphInputLinks(e){let t=this.subgraph.inputNode.slots[e],n=t.getLinks();return n.length===0?(console.warn(`[SubgraphNode.resolveSubgraphInputLinks] No inner links found for input slot [${e}] ${t.name}`,this),[]):n.map(e=>e.resolve(this.subgraph))}resolveSubgraphOutputLink(e){let t=this.subgraph.outputNode.slots[e],n=t.getLinks().at(0);if(n)return n.resolve(this.subgraph);console.warn(`[SubgraphNode.resolveSubgraphOutputLink] No inner link found for output slot [${e}] ${t.name}`,this)}getInnerNodes(e,t=[],n=[],r=new Set){if(r.has(this)){let e=`${this.id}${this.title?` (${this.title})`:``}`,n=`'${this.subgraph.name||`Unnamed Subgraph`}'`,r=t.length;throw new RecursionError(`Circular reference detected at depth ${r} in node ${e} of subgraph ${n}. This creates an infinite loop in the subgraph hierarchy.`)}r.add(this);let i=[...t,this.id],a=this.rootGraph.resolveSubgraphIdPath(t).at(-1),o=new lt(this,t,e,a);e.set(o.id,o);for(let t of this.subgraph.nodes)if(`getInnerNodes`in t&&t.getInnerNodes)t.getInnerNodes(e,i,n,new Set(r));else{let r=new lt(t,i,e,this);e.set(r.id,r),n.push(r)}return n}_clearDomOverrideForView(e){let t=resolveConcretePromotedWidget(this,e.sourceNodeId,e.sourceWidgetName,e.disambiguatingSourceNodeId);if(t.status!==`resolved`)return;let n=t.resolved.widget;n&&`id`in n&&(`element`in n||`component`in n)&&nt().clearPositionOverride(String(n.id))}_removePromotedView(e){this._invalidatePromotedViewsCache(),this._promotedViewManager.remove(e.sourceNodeId,e.sourceW
2idgetName);for(let t of this.inputs){if(t._widget!==e||!t._subgraphSlot)continue;let n=t.label??t.name;this._promotedViewManager.removeByViewKey(e.sourceNodeId,e.sourceWidgetName,this._makePromotionViewKey(String(t._subgraphSlot.id),e.sourceNodeId,e.sourceWidgetName,n,e.disambiguatingSourceNodeId))}}removeWidget(e){this.ensureWidgetRemoved(e)}ensureWidgetRemoved(e){isPromotedWidgetView(e)&&(this._clearDomOverrideForView(e),W().demote(this.rootGraph.id,this.id,e),this._removePromotedView(e));for(let t of this.inputs)t._widget===e&&(t._widget=void 0,t.widget=void 0);this.subgraph.events.dispatch(`widget-demoted`,{widget:e,subgraphNode:this}),this._syncPromotions()}onRemoved(){this._eventAbortController.abort(),this._invalidatePromotedViewsCache();for(let e of this.widgets)isPromotedWidgetView(e)&&this._clearDomOverrideForView(e),this.subgraph.events.dispatch(`widget-demoted`,{widget:e,subgraphNode:this});W().setPromotions(this.rootGraph.id,this.id,[]),this._promotedViewManager.clear();for(let e of this.inputs)e._listenerController&&typeof e._listenerController.abort==`function`&&e._listenerController.abort()}drawTitleBox(e,{scale:t,low_quality:n=!1,title_height:r=Q.NODE_TITLE_HEIGHT,box_size:i=10}){if(this.onDrawTitleBox){this.onDrawTitleBox(e,r,this.renderingSize,t);return}e.save(),e.fillStyle=`#3b82f6`,e.beginPath(),e.roundRect(6,-24.5,22,20,5),e.fill(),n||(e.translate(25,23),e.scale(-1.5,1.5),e.drawImage(dt.get(),0,-r,i,i)),e.restore()}serialize(){for(let e of this.inputs){if(!e._widget)continue;let t=e._subgraphSlot??this.subgraph.inputNode.slots.find(t=>t.name===e.name);if(!t)continue;let n=t.getConnectedWidgets();for(let t of n)t.value=e._widget.value}let e=W().getPromotions(this.rootGraph.id,this.id);return this.properties.proxyWidgets=this._serializeEntries(e),super.serialize()}clone(){return super.clone()}getSlotShape(e,t){let n=e.linkIds.map(e=>this.subgraph.links[e]?.resolve(this.subgraph)?.input?.shape);return t&&n.push(t.shape),n.every(e=>e===n[0])?n[0]:void 0}};function getBoundaryNodes(e){let t=e?.find(e=>e);if(!t)return null;let n=t,r=t,i=t,a=t;for(let t of e){if(!t)continue;let[e,o]=t.pos,[s,c]=t.size;o<n.pos[1]&&(n=t),e+s>r.pos[0]+r.size[0]&&(r=t),o+c>i.pos[1]+i.size[1]&&(i=t),e<a.pos[0]&&(a=t)}return{top:n,right:r,bottom:i,left:a}}function distributeNodes(e,t){let n=e?.length;if(!(n>1))return[];let r=t?0:1,i=0,a=-1/0;for(let t of e){i+=t.size[r];let e=t.pos[r]+t.size[r];e>a&&(a=e)}let o=[...e].sort((e,t)=>e.pos[r]-t.pos[r]),s=o[0].pos[r],c=(a-s-i)/(n-1),l=s;for(let e=0;e<n;e++){let t=o[e];t.pos[r]=l+c*e,l+=t.size[r]}return o.map(e=>({node:e,newPos:{x:e.pos[0],y:e.pos[1]}}))}function alignNodes(e,t,n){if(!e)return[];let r=n===void 0?getBoundaryNodes(e):{top:n,right:n,bottom:n,left:n};if(r===null)return[];let i=e.map(e=>{switch(t){case`right`:return{node:e,newPos:{x:r.right.pos[0]+r.right.size[0]-e.size[0],y:e.pos[1]}};case`left`:return{node:e,newPos:{x:r.left.pos[0],y:e.pos[1]}};case`top`:return{node:e,newPos:{x:e.pos[0],y:r.top.pos[1]}};case`bottom`:return{node:e,newPos:{x:e.pos[0],y:r.bottom.pos[1]+r.bottom.size[1]-e.size[1]}}}});for(let{node:e,newPos:t}of i)e.setPos(t.x,t.y);return i}function resolveConnectingLinkColor(e){return e===Q.EVENT?Q.EVENT_LINK_COLOR:Q.CONNECTING_LINK_COLOR}var ft={NE:`nesw-resize`,SE:`nwse-resize`,SW:`nesw-resize`,NW:`nwse-resize`},pt=new G,mt=[0,0],ht=new G,gt=new G,_t=new G,Z=class LGraphCanvas{static DEFAULT_BACKGROUND_IMAGE=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=`;static DEFAULT_EVENT_LINK_COLOR=`#A86`;static link_type_colors={"-1":LGraphCanvas.DEFAULT_EVENT_LINK_COLOR,number:`#AAA`,node:`#DCA`};static gradients={};static search_limit=-1;
2static node_colors={red:{color:`#322`,bgcolor:`#533`,groupcolor:`#A88`},brown:{color:`#332922`,bgcolor:`#593930`,groupcolor:`#b06634`},green:{color:`#232`,bgcolor:`#353`,groupcolor:`#8A8`},blue:{color:`#223`,bgcolor:`#335`,groupcolor:`#88A`},pale_blue:{color:`#2a363b`,bgcolor:`#3f5159`,groupcolor:`#3f789e`},cyan:{color:`#233`,bgcolor:`#355`,groupcolor:`#8AA`},purple:{color:`#323`,bgcolor:`#535`,groupcolor:`#a1309b`},yellow:{color:`#432`,bgcolor:`#653`,groupcolor:`#b58b2a`},black:{color:`#222`,bgcolor:`#000`,groupcolor:`#444`}};static _measureText;state={draggingItems:!1,draggingCanvas:!1,readOnly:!1,hoveringOver:F.Nothing,shouldSetCursor:!0,selectionChanged:!1,ghostNodeId:null};_subgraph;get subgraph(){return this._subgraph}set subgraph(e){e!==this._subgraph&&(this._subgraph=e,e&&this.dispatch(`litegraph:set-graph`,{oldGraph:this._subgraph,newGraph:e}))}fpsInfoLocation;dispatch(e,t){let n=new CustomEvent(e,{detail:t,bubbles:!0});return this.canvas.dispatchEvent(n)}dispatchEvent(e,t){this.canvas.dispatchEvent(new CustomEvent(e,{detail:t}))}_setCursor;_updateCursorStyle(){if(!this.state.shouldSetCursor)return;let e=F.Node|F.RerouteSlot|F.SubgraphIoNode|F.SubgraphIoSlot,t=`default`;this.state.draggingCanvas?t=`grabbing`:this.state.readOnly?t=`grab`:this.pointer.resizeDirection?t=ft[this.pointer.resizeDirection]??ft.SE:this.state.hoveringOver&e?t=`crosshair`:this.state.hoveringOver&F.Reroute&&(t=`grab`),this._setCursor(t)}_previously_dragging_canvas=null;get read_only(){return this.state.readOnly}set read_only(e){this.state.readOnly=e,this._updateCursorStyle()}get isDragging(){return this.state.draggingItems}set isDragging(e){this.state.draggingItems=e}get hoveringOver(){return this.state.hoveringOver}set hoveringOver(e){this.state.hoveringOver=e,this._updateCursorStyle()}get pointer_is_down(){return this.pointer.isDown}get pointer_is_double(){return this.pointer.isDouble}get dragging_canvas(){return this.state.draggingCanvas}set dragging_canvas(e){this.state.draggingCanvas=e,this._updateCursorStyle()}get title_text_font(){return`${Q.NODE_TEXT_SIZE}px ${Q.NODE_FONT}`}get inner_text_font(){return`normal ${Q.NODE_SUBTEXT_SIZE}px ${Q.NODE_FONT}`}_maximumFrameGap=0;get maximumFps(){return this._maximumFrameGap>2**-52?this._maximumFrameGap/1e3:0}set maximumFps(e){this._maximumFrameGap=e>2**-52?1e3/e:0}
2get round_radius(){return Q.ROUND_RADIUS}set round_radius(e){Q.ROUND_RADIUS=e}_lowQualityZoomThreshold=0;_isLowQuality=!1;updateLowQualityThreshold(){if(this._min_font_size_for_lod===0){this._lowQualityZoomThreshold=0,this._isLowQuality=!1;return}let e=Q.NODE_TEXT_SIZE,t=Math.sqrt(window.devicePixelRatio||1);this._lowQualityZoomThreshold=this._min_font_size_for_lod/(e*t),this._isLowQuality=this.ds.scale<this._lowQualityZoomThreshold}get low_quality(){return this._isLowQuality}options;background_image;ds;pointer;zoom_modify_alpha;zoom_speed;auto_pan_speed;node_title_color;default_link_color;default_connection_color;default_connection_color_byType;default_connection_color_byTypeOff;colourGetter={getConnectedColor:e=>this.default_connection_color_byType[e]||this.default_connection_color.output_on,getDisconnectedColor:e=>this.default_connection_color_byTypeOff[e]||this.default_connection_color_byType[e]||this.default_connection_color.output_off};highquality_render;use_gradients;editor_alpha;pause_rendering;clear_background;clear_background_color;render_only_selected;show_info;info_text;allow_dragcanvas;allow_dragnodes;allow_interaction;multi_select;groupSelectChildren;allow_searchbox;allow_reconnect_links;align_to_grid;drag_mode;dragging_rectangle;filter;set_canvas_dirty_on_mouse_event;always_render_background;render_shadows;render_canvas_border;render_connections_shadows;render_connections_border;render_curved_connections;render_connection_arrows;render_collapsed_slots;render_execution_order;render_link_tooltip;linkMarkerShape=R.Circle;links_render_mode;_min_font_size_for_lod=8;get min_font_size_for_lod(){return this._min_font_size_for_lod}set min_font_size_for_lod(e){this._min_font_size_for_lod!==e&&(this._min_font_size_for_lod=e,this.updateLowQualityThreshold())}mouse;graph_mouse;canvas_mouse;onSearchBox;onSearchBoxSelection;onMouse;onDrawBackground;onDrawForeground;connections_width;current_node;node_widget;over_link_center;last_mouse_position;visible_area;renderedPaths=new Set;visible_links=[];connecting_links;linkConnector=new LinkConnector(e=>this.connecting_links=e);viewport;autoresize;static active_canvas;frame=0;last_draw_time=0;render_time=0;fps=0;selected_nodes={};selectedItems=new Set;resizingGroup=null;selected_group=null;visible_nodes=[];_visible_node_ids=new Set;node_over;node_capturing_input;highlighted_links={};_visibleReroutes=new Set;_autoPan=null;_ghostPointerHandler=null;_ghostKeyHandler=null;dirty_canvas=!0;dirty_bgcanvas=!0;dirty_nodes=new Map;dirty_area;node_in_panel;last_mouse=[0,0];last_mouseclick=0;graph;get _graph(){if(!this.graph)throw new NullGraphError;return this.graph}canvas;bgcanvas;overlayCanvas=null;overlayCtx=null;ctx;_events_binded;bgctx;is_rendering;block_click;last_click_position;resizing_node;selected_group_resizing;last_mouse_dragging;onMouseDown;_highlight_pos;_highlight_input;node_panel;options_panel;_bg_img;_pattern;_pattern_img;bg_tint;prompt_box;search_box;SELECTED_NODE;NODEPANEL_IS_OPEN;
2_snapToGrid;_shiftDown=!1;linkRenderer=null;dragZoomEnabled=!1;_dragZoomStart=null;liveSelection=!1;static active_node;onClear;onNodeMoved;onSelectionChange;onDrawLinkTooltip;onDrawOverlay;onRenderBackground;onNodeDblClicked;onShowNodePanel;onNodeSelected;onNodeDeselected;onRender;constructor(e,t,n){n||={},this.options=n,this.background_image=LGraphCanvas.DEFAULT_BACKGROUND_IMAGE,this.ds=new DragAndScale(e),this.pointer=new Ie(e),this.ds.onChanged=(e,t)=>{this._lowQualityZoomThreshold>0&&(this._isLowQuality=e<this._lowQualityZoomThreshold),this.setDirty(!0,!0)},t&&(this.linkRenderer=new LitegraphLinkAdapter(!1)),this.linkConnector.events.addEventListener(`link-created`,()=>this._dirty()),this.linkConnector.events.addEventListener(`reset`,()=>{this.state.ghostNodeId??(this._autoPan?.stop(),this._autoPan=null),this.connecting_links=null,this.dirty_bgcanvas=!0}),this.linkConnector.events.addEventListener(`dropped-on-canvas`,e=>{if(!this.connecting_links)return;let t=e.detail;this.emitEvent({subType:`empty-release`,originalEvent:t,linkReleaseContext:{links:this.connecting_links}});let n=this.linkConnector.renderLinks[0];if(Q.release_link_on_empty_shows_menu){let e=this.linkConnector.state.connectingTo===`input`?{node_from:n.node,slot_from:n.fromSlot,type_filter_in:n.fromSlot.type}:{node_to:n.node,slot_to:n.fromSlot,type_filter_out:n.fromSlot.type},r=n.fromReroute?.id;`shiftKey`in t&&t.shiftKey?this.allow_searchbox&&this.showSearchBox(t,e):this.linkConnector.state.connectingTo===`input`?this.showConnectionMenu({nodeFrom:n.node,slotFrom:n.fromSlot,e:t,afterRerouteId:r}):this.showConnectionMenu({nodeTo:n.node,slotTo:n.fromSlot,e:t,afterRerouteId:r})}}),this.zoom_modify_alpha=!0,this.zoom_speed=1.1,this.auto_pan_speed=15,this.node_title_color=Q.NODE_TITLE_COLOR,this.default_link_color=Q.LINK_COLOR,this.default_connection_color={input_off:`#778`,input_on:`#7F7`,output_off:`#778`,output_on:`#7F7`},this.default_connection_color_byType={},this.default_connection_color_byTypeOff={},this.highquality_render=!0,this.use_gradients=!1,this.editor_alpha=1,this.pause_rendering=!1,this.clear_background=!0,this.clear_background_color=`#222`,this.render_only_selected=!0,this.show_info=!0,this.allow_dragcanvas=!0,this.allow_dragnodes=!0,this.allow_interaction=!0,this.multi_select=!1,this.groupSelectChildren=!1,this.allow_searchbox=!0,this.allow_reconnect_links=!0,this.align_to_grid=!1,this.drag_mode=!1,this.dragging_rectangle=null,this.filter=null,this.set_canvas_dirty_on_mouse_event=!0,this.always_render_background=!1,this.render_shadows=!0,this.render_canvas_border=!0,this.render_connections_shadows=!1,this.render_connections_border=!0,this.render_curved_connections=!1,this.render_connection_arrows=!1,this.render_collapsed_slots=!0,this.render_execution_order=!1,this.render_link_tooltip=!0,this.links_render_mode=L.SPLINE_LINK,this.mouse=[0,0],this.graph_mouse=[0,0],this.canvas_mouse=this.graph_mouse,this.connections_width=3,this.current_node=null,this.node_widget=null,this.last_mouse_position=[0,0],this.visible_area=this.ds.visible_area,this.connecting_links=null,this.viewport=n.viewport,this.graph=t,t?.attachCanvas(this),this.canvas=void 0,this.bgcanvas=void 0,this.ctx=void 0,this.setCanvas(e,n.skip_events),this.clear(),LGraphCanvas._measureText=(e,t=this.inner_text_font)=>{let{ctx:n}=this,{font:r}=n;try{return n.font=t,n.measureText(e).width}finally{n.font=r}},n.skip_render||this.startRendering(),this.autoresize=n.autoresize??!1,this.updateLowQualityThreshold()}static onGroupAdd(e,t,n){let r=LGraphCanvas.active_canvas,i=new Q.LGraphGroup;if(i.pos=r.convertEventToCanvasOffset(n),!r.graph)throw new NullGraphError;r.graph.add(i)}static getBoundaryNodes(e){return getBoundaryNodes(Array.isArray(e)?e:Object.values(e))??{top:null,right:null,bottom:null,left:null}}static alignNodes(e,t,n){let r=alignNodes(Object.values(e),t,n);LGraphCanvas.active_canvas.repositionNodesVueMode(r),LGraphCanvas.active_canvas.setDirty(!0,!0)}static onNodeAlign(e,t,n,r,i){new Q.ContextMenu([`Top`,`Bottom`,`Left`,`Right`],{event:n,callback:inner_clicked,parentMenu:r});function inner_clicked(e){let t=alignNodes(Object.values(LGraphCanvas.active_canvas.selected_nodes),e.toLowerCase(),i);LGraphCanvas.active_canvas.repositionNodesVueMode(t),LGraphCanvas.active_canvas.setDirty(!0,!0)}}static onGroupAlign(e,t,n,r){new Q.ContextMenu([`Top`,`Bottom`,`Left`,`Right`],{event:n,callback:inner_clicked,parentMenu:r});function inner_clicked(e){let t=alignNodes(Object.values(LGraphCanvas.active_canvas.selected_nodes),e.toLowerCase());LGraphCanvas.active_canvas.repositionNodesVueMode(t),LGraphCanvas.active_canvas.setDirty(!0,!0)}}static createDistributeMenu(e,t,n,r){new Q.ContextMenu([`Vertically`,`Horizontally`],{event:n,callback:inner_clicked,parentMenu:r});function inner_clicked(e){let t=LGraphCanvas.active_canvas,n=distributeNodes(Object.values(t.selected_nodes),e===`Horizontally`);t.repositionNodesVueMode(n),t.setDirty(!0,!0)}}static onMenuAdd(e,t,n,r,i){let a=LGraphCanvas.active_canvas,{graph:o}=a;if(!o)return;return inner_onMenuAdded(``,r),!1;function inner_onMenuAdded(e,t){if(!o)return;let r=Q.getNodeTypesCategories(a.filter||o.filter).filter(t=>t.startsWith(e)),s=[];for(let t of r){if(!t)continue;let n=RegExp(`^(${e})`),r=t.replace(n,``).split(`/`,1)[0],i=e===``?`${r}/`:`${e}${r}/`,a=r;a.includes(`::`)&&(a=a.split(`::`,2)[1]),s.findIndex(e=>e.value===i)===-1&&s.push({value:i,content:a,has_submenu:!0,callback:function(e,t,n,r){inner_onMenuAdded(e.value,r)}})}let compareByContent=(e,t)=>
2(e.content??``).localeCompare(t.content??``,void 0,{numeric:!0,sensitivity:`base`});s.sort(compareByContent);let c=Q.getNodeTypesInCategory(e.slice(0,-1),a.filter||o.filter),l=[];for(let e of c){if(e.skip_list)continue;let t={value:e.type,content:e.title,has_submenu:!1,callback:function(e,t,n,r){if(!a.graph)throw new NullGraphError;let o=r.getFirstEvent();a.graph.beforeChange();let s=Q.createNode(e.value);if(s){if(!o)throw TypeError(`Context menu event was null. This should not occur in normal usage.`);s.pos=a.convertEventToCanvasOffset(o),a.graph.add(s)}else console.warn(`Failed to create node of type:`,e.value);i?.(s),a.graph.afterChange()}};l.push(t)}l.sort(compareByContent);let u=[...s,...l];new Q.ContextMenu(u,{event:n,parentMenu:t})}}static onMenuCollapseAll(){}static onMenuNodeEdit(){}static showMenuNodeOptionalOutputs(e,t,n,r,i){if(!i)return;let a=LGraphCanvas.active_canvas,o=[];Q.do_add_triggers_slots&&i.findOutputSlot(`onExecuted`)==-1&&o.push({content:`On Executed`,value:[`onExecuted`,Q.EVENT,{nameLocked:!0}],className:`event`});let s=i.onMenuNodeOutputs?.(o);if(s&&(o=s),!o.length)return;new Q.ContextMenu(o,{event:n,callback:inner_clicked,parentMenu:r,node:i});function inner_clicked(e,t,n,o){if(!i||!e||typeof e==`string`||(e.callback&&e.callback.call(this,i,e,n,o),!e.value))return;let s=e.value[1];if(s&&(typeof s==`object`||Array.isArray(s))){let e=[];for(let t in s)e.push({content:t,value:s[t]});return new Q.ContextMenu(e,{event:n,callback:inner_clicked,parentMenu:r,node:i}),!1}let{graph:c}=i;if(!c)throw new NullGraphError;c.beforeChange(),i.addOutput(e.value[0],e.value[1],e.value[2]),i.onNodeOutputAdd?.(e.value),a.setDirty(!0,!0),c.afterChange()}return!1}static onShowMenuNodeProperties(e,t,n,r,i){if(!i||!i.properties)return;let a=LGraphCanvas.active_canvas,o=[];for(let t in i.properties){e=i.properties[t]===void 0?` `:i.properties[t],typeof e==`object`&&(e=JSON.stringify(e));let n=i.getPropertyInfo(t);(n.type==`enum`||n.type==`combo`)&&(e=LGraphCanvas.getPropertyPrintableValue(e,n.values)),e=LGraphCanvas.decodeHTML(p(e)),o.push({content:`<span class='property_name'>${n.label||t}</span><span class='property_value'>${e}</span>`,value:t})}if(!o.length)return;new Q.ContextMenu(o,{event:n,callback:inner_clicked,parentMenu:r,node:i});function inner_clicked(e){if(!i||typeof e==`string`||!e?.value)return;let t=this.getBoundingClientRect();a.showEditPropertyValue(i,e.value,{position:[t.left,t.top]})}return!1}static decodeHTML(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}static onMenuResizeNode(e,t,n,r,i){if(!i)return;let fApplyMultiNode=function(e){e.setSize(e.computeSize())},a=LGraphCanvas.active_canvas;if(!a.selected_nodes||Object.keys(a.selected_nodes).length<=1)fApplyMultiNode(i);else for(let e in a.selected_nodes)fApplyMultiNode(a.selected_nodes[e]);a.setDirty(!0,!0)}static onShowPropertyEditor(e,t,n,r,i){let a=e.property||`title`,o=i[a],s=document.createElement(`span`);s.className=`name`,s.textContent=a;let c=document.createElement(`input`);Object.assign(c,{type:`text`,className:`value`,autofocus:!0});let l=document.createElement(`button`);l.textContent=`OK`;let u=Object.assign(document.createElement(`div`),{is_modified:!1,className:`graphdialog`,close:()=>u.remove()});u.append(s,c,l),c.value=String(o),c.addEventListener(`blur`,function(){this.focus()}),c.addEventListener(`keydown`,e=>{if(u.is_modified=!0,e.key==`Escape`)u.close();else if(e.key==`Enter`)inner();else if(!e.target||!(`localName`in e.target)||e.target.localName!=`textarea`)return;e.preventDefault(),e.stopPropagation()});let d=LGraphCanvas.active_canvas,f=d.canvas,p=f.getBoundingClientRect(),m=p?-20-p.left:-20,h=p?-20-p.top:-20;if(n?(u.style.left=`${n.clientX+m}px`,u.style.top=`${n.clientY+h}px`):(u.style.left=`${f.width*.5+m}px`,u.style.top=`${f.height*.5+h}px`),l.addEventListener(`click`,inner),f.parentNode==null)throw TypeError(`canvasEl.parentNode was null`);f.parentNode.append(u),c.focus();let g;u.addEventListener(`mouseleave`,function(){Q.dialog_close_on_mouse_leave&&!u.is_modified&&Q.dialog_close_on_mouse_leave&&(g=setTimeout(u.close,Q.dialog_close_on_mouse_leave_delay))}),u.addEventListener(`mouseenter`,function(){Q.dialog_close_on_mouse_leave&&g&&clearTimeout(g)});function inner(){c&&setValue(c.value)}function setValue(t){e.type==`Number`?t=Number(t):e.type==`Boolean`&&(t=!!t),i[a]=t,u.remove(),d.setDirty(!0,!0)}}static getPropertyPrintableValue(e,t){if(!t||Array.isArray(t))return String(e);if(typeof t==`object`){let n=``;for(let r in t)if(t[r]==e){n=r;break}return`${String(e)} (${n})`}}static onMenuNodeCollapse(e,t,n,r,i){if(!i.graph)throw new NullGraphError;i.graph.beforeChange();let fApplyMultiNode=function(e){e.collapse()},a=LGraphCanvas.active_canvas;if(!a.selected_nodes||Object.keys(a.selected_nodes).length<=1)fApplyMultiNode(i);else for(let e in a.selected_nodes)fApplyMultiNode(a.selected_nodes[e]);i.graph.afterChange()}static onMenuToggleAdvanced(e,t,n,r,i){if(!i.graph)throw new NullGraphError;i.graph.beforeChange();let fApplyMultiNode=function(e){e.toggleAdvanced()},a=LGraphCanvas.active_canvas;if(!a.selected_nodes||Object.keys(a.selected_nodes).length<=1)fApplyMultiNode(i);else for(let e in a.selected_nodes)fApplyMultiNode(a.selected_nodes[e]);i.graph.afterChange()}static onMenuNodeMode(e,t,n,r,i){new Q.ContextMenu(Q.NODE_MODES,{event:n,callback:inner_clicked,parentMenu:r,node:i});function inner_clicked(e){if(!i)return;let t=Object.values(Q.NODE_MODES).indexOf(e),fApplyMultiNode=function(n){t!==-1&&Q.NODE_MODES[t]?n.changeMode(t):(console.warn(`unexpected mode: ${e}`),n.changeMode(B.ALWAYS))},n=LGraphCanvas.active_canvas;if(!n.selected_nodes||Object.keys(n.selected_nodes).length<=1)fApplyMultiNode(i);else for(let e in n.selected_nodes)fApplyMultiNode(n.selected_nodes[e])}return!1}
2static onMenuNodeColors(e,t,n,r,i){if(!i)throw`no node for color`;let a=[];a.push({value:null,content:`<span style='display: block; padding-left: 4px;'>No color</span>`});for(let t in LGraphCanvas.node_colors){let n=LGraphCanvas.node_colors[t];e={value:t,content:`<span style='display: block; color: #999; padding-left: 4px; border-left: 8px solid ${n.color}; background-color:${n.bgcolor}'>${t}</span>`},a.push(e)}new Q.ContextMenu(a,{event:n,callback:inner_clicked,parentMenu:r,node:i});function inner_clicked(e){if(!i)return;let fApplyColor=function(t){let n=e.value?LGraphCanvas.node_colors[e.value]:null;t.setColorOption(n)},t=LGraphCanvas.active_canvas;if(!t.selected_nodes||Object.keys(t.selected_nodes).length<=1)fApplyColor(i);else for(let e in t.selected_nodes)fApplyColor(t.selected_nodes[e]);t.setDirty(!0,!0)}return!1}static onMenuNodeShapes(e,t,n,r,i){if(!i)throw`no node passed`;new Q.ContextMenu(Q.VALID_SHAPES,{event:n,callback:inner_clicked,parentMenu:r,node:i});function inner_clicked(e){if(!i)return;if(!i.graph)throw new NullGraphError;i.graph.beforeChange();let fApplyMultiNode=function(t){t.shape=e},t=LGraphCanvas.active_canvas;if(!t.selected_nodes||Object.keys(t.selected_nodes).length<=1)fApplyMultiNode(i);else for(let e in t.selected_nodes)fApplyMultiNode(t.selected_nodes[e]);i.graph.afterChange(),t.setDirty(!0)}return!1}static onMenuNodeRemove(){LGraphCanvas.active_canvas.deleteSelected()}static onMenuNodeClone(e,t,n,r,i){let a=LGraphCanvas.active_canvas,o=a.selectedItems.size?[...a.selectedItems]:[i];o.length&&LGraphCanvas.cloneNodes(o)}static cloneNodes(e){let t=LGraphCanvas.active_canvas,n=1/0,r=1/0;for(let t of e){if(t.pos==null)throw TypeError("Invalid node encountered on clone.  `pos` was null.");n=Math.min(n,t.pos[0]),r=Math.min(r,t.pos[1])}return t._deserializeItems(t._serializeItems(e),{position:[n+5,r+5]})}clear(){this.frame=0,this.last_draw_time=0,this.render_time=0,this.fps=0,this.dragging_rectangle=null;for(let e of this.selectedItems.keys())e.selected=void 0;this.selected_nodes={},this.selected_group=null,this.selectedItems.clear(),this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.visible_nodes=[],this.node_over=void 0,this.node_capturing_input=null,this.connecting_links=null,this.highlighted_links={},this.dragging_canvas=!1,this._dirty(),this.dirty_area=null,this.node_in_panel=null,this.node_widget=null,this.last_mouse=[0,0],this.last_mouseclick=0,this.pointer.reset(),this.visible_area.set([0,0,0,0]),this.onClear?.()}setGraph(e){let{graph:t}=this;e!==t&&(this.state.ghostNodeId!=null&&this.finalizeGhostPlacement(!0),this.clear(),e.attachCanvas(this),this.linkRenderer=new LitegraphLinkAdapter(!1),this.dispatch(`litegraph:set-graph`,{newGraph:e,oldGraph:t}),this._dirty())}openSubgraph(e,t){let{graph:n}=this;if(!n)throw new NullGraphError;let r={bubbles:!0,detail:{subgraph:e,closingGraph:n,fromNode:t},cancelable:!0};this.canvas.dispatchEvent(new CustomEvent(`subgraph-opening`,r))&&(this.clear(),this.subgraph=e,this.setGraph(e),this.canvas.dispatchEvent(new CustomEvent(`subgraph-opened`,r)))}getCurrentGraph(){return this.graph}_validateCanvas(e){if(typeof e==`string`){let t=document.getElementById(e);if(!(t instanceof HTMLCanvasElement))throw`Error validating LiteGraph canvas: Canvas element not found`;return t}return e}setCanvas(e,t){let n=this._validateCanvas(e);if(n===this.canvas||(!n&&this.canvas&&!t&&this.unbindEvents(),this.canvas=n,this.ds.element=n,this.pointer.element=n,!n))return;this._setCursor=createCursorCache(n),n.className+=` lgraphcanvas`,Object.defineProperty(n,`data`,{value:this,writable:!0,configurable:!0,enumerable:!1}),this.bgcanvas=document.createElement(`canvas`),this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height;let r=n.getContext?.(`2d`);if(r==null)throw n.localName==`canvas`?`This browser doesn't support Canvas`:`Element supplied for LGraphCanvas must be a <canvas> element, you passed a ${n.localName}`;this.ctx=r,t||this.bindEvents()}_doNothing(e){return e.preventDefault(),!1}_preventMiddleAuxClick(e){e.button===1&&e.preventDefault()}_doReturnTrue(e){return e.preventDefault(),!0}
2bindEvents(){if(this._events_binded){console.warn(`LGraphCanvas: events already bound`);return}let{canvas:e}=this,{document:t}=this.getCanvasWindow();this._mousedown_callback=this.processMouseDown.bind(this),this._mousewheel_callback=this.processMouseWheel.bind(this),this._mousemove_callback=this.processMouseMove.bind(this),this._mouseup_callback=this.processMouseUp.bind(this),this._mouseout_callback=this.processMouseOut.bind(this),this._mousecancel_callback=this.processMouseCancel.bind(this),e.addEventListener(`pointerdown`,this._mousedown_callback,!0),e.addEventListener(`wheel`,this._mousewheel_callback,!1),e.addEventListener(`pointerup`,this._mouseup_callback,!0),e.addEventListener(`pointermove`,this._mousemove_callback),e.addEventListener(`pointerout`,this._mouseout_callback),e.addEventListener(`pointercancel`,this._mousecancel_callback,!0),e.addEventListener(`contextmenu`,this._doNothing),e.addEventListener(`auxclick`,this._preventMiddleAuxClick),this._key_callback=this.processKey.bind(this),e.addEventListener(`keydown`,this._key_callback,!0),t.addEventListener(`keyup`,this._key_callback,!0),e.addEventListener(`dragover`,this._doNothing,!1),e.addEventListener(`dragend`,this._doNothing,!1),e.addEventListener(`dragenter`,this._doReturnTrue,!1),this._events_binded=!0}unbindEvents(){if(!this._events_binded){console.warn(`LGraphCanvas: no events bound`);return}let{document:e}=this.getCanvasWindow(),{canvas:t}=this;t.removeEventListener(`pointercancel`,this._mousecancel_callback),t.removeEventListener(`pointerout`,this._mouseout_callback),t.removeEventListener(`pointermove`,this._mousemove_callback),t.removeEventListener(`pointerup`,this._mouseup_callback),t.removeEventListener(`pointerdown`,this._mousedown_callback),t.removeEventListener(`wheel`,this._mousewheel_callback),t.removeEventListener(`keydown`,this._key_callback),e.removeEventListener(`keyup`,this._key_callback),t.removeEventListener(`contextmenu`,this._doNothing),t.removeEventListener(`auxclick`,this._preventMiddleAuxClick),t.removeEventListener(`dragenter`,this._doReturnTrue),this._mousedown_callback=void 0,this._mousewheel_callback=void 0,this._key_callback=void 0,this._events_binded=!1}setDirty(e,t){e&&(this.dirty_canvas=!0),t&&(this.dirty_bgcanvas=!0)}_dirty(){this.dirty_canvas=!0,this.dirty_bgcanvas=!0}_linkConnectorDrop(){let{graph:e,linkConnector:t,pointer:n}=this;if(!e)throw new NullGraphError;n.onDragEnd=n=>t.dropLinks(e,n),n.finally=()=>{this._autoPan?.stop(),this._autoPan=null,this.linkConnector.reset(!0)},this._autoPan=new AutoPanController({canvas:this.canvas,ds:this.ds,maxPanSpeed:this.auto_pan_speed,onPan:()=>{let e=this.canvas.getBoundingClientRect(),{scale:t}=this.ds;this.graph_mouse[0]=(this.mouse[0]-e.left)/t-this.ds.offset[0],this.graph_mouse[1]=(this.mouse[1]-e.top)/t-this.ds.offset[1],this._dirty()}}),this._autoPan.updatePointer(this.mouse[0],this.mouse[1]),this._autoPan.start()}getCanvasWindow(){if(!this.canvas)return window;let e=this.canvas.ownerDocument;return e.defaultView||e.parentWindow}startRendering(){if(this.is_rendering)return;this.is_rendering=!0,renderFrame.call(this);function renderFrame(){this.pause_rendering||this.draw();let e=this.getCanvasWindow();if(this.is_rendering)if(this._maximumFrameGap>0){let e=this._maximumFrameGap-(Q.getTime()-this.last_draw_time);setTimeout(renderFrame.bind(this),Math.max(1,e))}else e.requestAnimationFrame(renderFrame.bind(this))}}stopRendering(){this.is_rendering=!1}blockClick(){this.block_click=!0,this.last_mouseclick=0}getWidgetAtCursor(e){return e??=this.node_over,e?.getWidgetOnPos(this.graph_mouse[0],this.graph_mouse[1],!0)}updateMouseOverNodes(e,t){if(!this.graph)throw new NullGraphError;let{pointer:n}=this,r=this.graph._nodes;for(let i of r)i.mouseOver&&e!=i&&(n.eDown||(n.resizeDirection=void 0),i.mouseOver=void 0,this._highlight_input=void 0,this._highlight_pos=void 0,this.linkConnector.overWidget=void 0,i.lostFocusAt=Q.getTime(),this.node_over?.onMouseLeave?.(t),this.node_over=void 0,this.dirty_canvas=!0)}processMouseDown(e){if(this.state.ghostNodeId!=null){e.button===0&&this.finalizeGhostPlacement(!1),e.button===2&&this.finalizeGhostPlacement(!0),this.canvas.focus(),e.stopPropagation(),e.preventDefault();return}if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&!e.altKey&&e.buttons){this._dragZoomStart={pos:[e.x,e.y],scale:this.ds.scale,readOnly:this.read_only},this.read_only=!0;return}let{graph:t,pointer:n}=this;if(this.adjustMouseEvent(e),e.isPrimary&&n.down(e),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0),!t)return;let r=this.getCanvasWindow();LGraphCanvas.active_canvas=this;let i=e.clientX,a=e.clientY;if(this.ds.viewport=this.viewport,!(!this.viewport||isInRect(i,a,this.viewport)))return;let o=t.getNodeOnPos(e.canvasX,e.canvasY,this.visible_nodes)??void 0;if(!o&&Q.vueNodesMode){let n=U.querySlotAtPoint({x:e.canvasX,y:e.canvasY});n&&(o=t.getNodeById(n.nodeId)??void 0)}if(this.mouse[0]=i,this.mouse[1]=a,this.graph_mouse[0]=e.canvasX,this.graph_mouse[1]=e.canvasY,this.last_click_position=[this.mouse[0],this.mouse[1]],n.isDouble=n.isDown&&e.isPrimary,n.isDown=!0,this.canvas.focus(),Q.closeAllContextMenus(r),this.onMouse?.(e)!=1){if(e.button===0&&!n.isDouble)this._processPrimaryButton(e,o);else if(e.button===1)this._processMiddleButton(e,o);else if((e.button===2||n.isDouble)&&this.allow_interaction&&!this.read_only){let{linkConnector:r,subgraph:i}=this;if(i?.inputNode.containsPoint(this.graph_mouse))this.processSelect(i.inputNode,e,!0),i.inputNode.onPointerDown(e,n,r);else if(i?.outputNode.containsPoint(this.graph_mouse))this.processSelect(i.outputNode,e,!0),i.outputNode.onPointerDown(e,n,r);else{if(o)this.processSelect(o,e,!0);else if(this.links_render_mode!==L.HIDDEN_LINK){let r=U.queryRerouteAtPoint({x:e.canvasX,y:e.canvasY}),i;i=r?t.getReroute(r.id):t.getRerouteOnPos(e.canvasX,e.canvasY,this._visibleReroutes),i&&(e.altKey?n.onClick=e=>
2{e.altKey&&(i.selected&&(this.deselect(i),this.onSelectionChange?.(this.selected_nodes)),i.remove())}:this.processSelect(i,e,!0))}n.onClick??=()=>this.processContextMenu(o,e)}}this.last_mouse=[i,a],this.last_mouseclick=Q.getTime(),this.last_mouse_dragging=!0,t.change(),(!r.document.activeElement||r.document.activeElement.nodeName.toLowerCase()!=`input`&&r.document.activeElement.nodeName.toLowerCase()!=`textarea`)&&e.preventDefault(),e.stopPropagation(),this.onMouseDown?.(e)}}_getPositionableOnPos(e,t){let n=this.subgraph?.getIoNodeOnPos(e,t);if(n)return n;for(let n of this._visibleReroutes)if(n.containsPoint([e,t]))return n;return this.graph?.getGroupTitlebarOnPos(e,t)}_processPrimaryButton(e,t){let{pointer:n,graph:r,linkConnector:i,subgraph:a}=this;if(!r)throw new NullGraphError;let o=e.canvasX,s=e.canvasY,c=e.ctrlKey||e.metaKey;if(c&&!e.altKey&&Q.leftMouseClickBehavior===`panning`){this._setupNodeSelectionDrag(e,n,t);return}if(this.read_only){n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0;return}if(!Q.vueNodesMode&&Q.alt_drag_do_clone_nodes&&e.altKey&&!e.ctrlKey&&t&&this.allow_interaction){let e=this._deserializeItems(this._serializeItems([t]),{position:t.pos})?.created[0];if(!e)return;e.setPos(e.pos[0]+5,e.pos[1]+5),this.allow_dragnodes&&(n.onDragStart=t=>{this._startDraggingItems(e,t)},n.onDragEnd=e=>this._processDraggedItems(e));return}if(t&&(this.allow_interaction||t.flags.allow_interaction))this._processNodeClick(e,c,t);else{if(a){let{inputNode:t,outputNode:r}=a;if(processSubgraphIONode(this,t)||processSubgraphIONode(this,r))return;function processSubgraphIONode(t,r){return r.containsPoint([o,s])?(r.onPointerDown(e,n,i),n.onClick??=()=>t.processSelect(r,e),n.onDragStart??=()=>t._startDraggingItems(r,n,!0),n.onDragEnd??=e=>t._processDraggedItems(e),!0):!1}}if(this.links_render_mode!==L.HIDDEN_LINK){let t=U.queryRerouteAtPoint({x:o,y:s}
2),a;t&&(a=r.getReroute(t.id));for(let t of this._visibleReroutes){let c=a===t||t.containsPoint([o,s]);if(!(!t.isSlotHovered&&!c)){c&&(n.onClick=()=>this.processSelect(t,e),e.shiftKey||(n.onDragStart=e=>this._startDraggingItems(t,e,!0),n.onDragEnd=e=>this._processDraggedItems(e))),(t.isOutputHovered||c&&e.shiftKey)&&(i.dragFromReroute(r,t),this._linkConnectorDrop()),t.isInputHovered&&(i.dragFromRerouteToOutput(r,t),this._linkConnectorDrop()),t.hideSlots(),this.dirty_bgcanvas=!0;return}}}let{lineWidth:t}=this.ctx;this.ctx.lineWidth=this.connections_width+7;let c=Math.max(window?.devicePixelRatio??1,1),l=U.queryLinkSegmentAtPoint({x:o,y:s},this.ctx);for(let a of this.renderedPaths){let u=a._pos;if(!u)continue;let d=l&&a.id===(a instanceof q?l.rerouteId:l.linkId);if(!d&&a.path&&(d=this.ctx.isPointInStroke(a.path,o*c,s*c)),(e.shiftKey||e.altKey)&&d){if(this.ctx.lineWidth=t,e.shiftKey&&!e.altKey){i.dragFromLinkSegment(r,a),this._linkConnectorDrop();return}else if(e.altKey&&!e.shiftKey){let e=r.createReroute([o,s],a);n.onDragStart=t=>this._startDraggingItems(e,t),n.onDragEnd=e=>this._processDraggedItems(e);return}}else if(this.linkMarkerShape!==R.None&&isInRectangle(o,s,u[0]-4,u[1]-4,8,8)){this.ctx.lineWidth=t,n.onClick=()=>this.showLinkMenu(a,e),n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1,this.over_link_center=void 0;return}}this.ctx.lineWidth=t;let u=r.getGroupOnPos(o,s);if(this.selected_group=u??null,u){if(u.isInResize(o,s)){let e=u.boundingRect,t=o-(e[0]+e[2]),r=s-(e[1]+e[3]);n.onDragStart=()=>this.resizingGroup=u,n.onDrag=e=>{if(this.read_only)return;let n=[e.canvasX-u.pos[0]-t,e.canvasY-u.pos[1]-r];this._snapToGrid&&snapPoint(n,this._snapToGrid),u.resize(n[0],n[1])&&(this.dirty_bgcanvas=!0)},n.finally=()=>this.resizingGroup=null}else{let t=Q.NODE_TITLE_HEIGHT;isInRectangle(o,s,u.pos[0],u.pos[1],u.size[0],t)&&(n.onClick=()=>this.processSelect(u,e),n.onDragStart=e=>{u.recomputeInsideNodes(),this._startDraggingItems(u,e,!0)},n.onDragEnd=e=>this._processDraggedItems(e))}n.onDoubleClick=()=>{this.emitEvent({subType:`group-double-click`,originalEvent:e,group:u})}}else n.onDoubleClick=()=>{this.allow_searchbox&&(this.showSearchBox(e),e.preventDefault()),this.emitEvent({subType:`empty-double-click`,originalEvent:e})}}!n.onDragStart&&!n.onClick&&!n.onDrag&&this.allow_dragcanvas&&(Q.leftMouseClickBehavior===`panning`||this.read_only?(n.onClick=()=>this.processSelect(null,e),n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0):this._setupNodeSelectionDrag(e,n))}_setupNodeSelectionDrag(e,t,n){let r=[0,0,0,0];if(r[0]=e.canvasX,r[1]=e.canvasY,r[2]=1,r[3]=1,t.onClick=e=>{let t=n??this._getPositionableOnPos(e.canvasX,e.canvasY);this.processSelect(t,e)},t.onDragStart=()=>this.dragging_rectangle=r,this.liveSelection){let e=new Set(this.selectedItems);t.onDrag=t=>this.handleLiveSelect(t,r,e),t.onDragEnd=()=>this.finalizeLiveSelect()}else t.onDragEnd=e=>this._handleMultiSelect(e,r);t.finally=()=>this.dragging_rectangle=null}_processNodeClick(e,t,n){if(Q.vueNodesMode)return;let{pointer:r,graph:i,linkConnector:o}=this;if(!i)throw new NullGraphError;let s=e.canvasX,c=e.canvasY;r.onClick=()=>this.processSelect(n,e),n.flags.pinned||this.bringToFront(n);let l=n.isPointInCollapse(s,c);if(l)r.onClick=()=>{n.collapse(),this.setDirty(!0,!0)};else if(!n.flags.collapsed){let{inputs:a,outputs:l}=n;function hasRelevantOutputLinks(e,t){return[...e.links??[],...[...e._floatingLinks??new Set]].some(e=>typeof e==`number`&&t.getLink(e)!==void 0)}if(l)for(let[a,u]of l.entries()){let l=n.getOutputPos(a);if(isInRectangle(s,c,l[0]-15,l[1]-10,30,20)){if(e.shiftKey&&hasRelevantOutputLinks(u,i)){o.moveOutputLink(i,u),this._linkConnectorDrop();return}o.dragNewFromOutput(i,n,u),this._linkConnectorDrop(),Q.shift_click_do_break_link_from?e.shiftKey&&n.disconnectOutput(a):Q.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey&&n.disconnectOutput(a),r.onDoubleClick=()=>n.onOutputDblClick?.(a,e),r.onClick=()=>n.onOutputClick?.(a,e);return}}if(a)for(let[l,u]of a.entries()){let a=n.getInputPos(l);if(u instanceof NodeInputSlot?isInRect(s,c,u.boundingRect):isInRectangle(s,c,a[0]-15,a[1]-10,30,20)){r.onDoubleClick=()=>n.onInputDblClick?.(l,e),r.onClick=()=>n.onInputClick?.(l,e);let a=Q.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey;(u.link!==null||u._floatingLinks?.size)&&(a||Q.click_do_break_link_to?n.disconnectInput(l,!0):(e.shiftKey||this.allow_reconnect_links)&&o.moveInputLink(i,u)),o.isConnecting||o.dragNewFromInput(i,n,u),this._linkConnectorDrop(),this.dirty_bgcanvas=!0;return}}}let u=[s-n.pos[0],c-n.pos[1]],d=n.getWidgetOnPos(s,c);if(d)this.processWidgetClick(e,n,d),this.node_widget=[n,d];else{if(r.onDoubleClick=()=>{u[1]<0&&!l?n.onNodeTitleDblClick?.(e,u,this):n instanceof SubgraphNode&&this.openSubgraph(n.subgraph,n),n.onDblClick?.(e,u,this),this.emitEvent({subType:`node-double-click`,originalEvent:e,node:n}),this.processNodeDblClicked(n)},n.title_buttons?.length&&!n.flags.collapsed){let e=u[0],t=u[1];for(let i=0;i<n.title_buttons.length;i++){let a=n.title_buttons[i];if(a.visible&&a.isPointInside(e,t)){n.onTitleButtonClick(a,this),r.onClick=()=>{};return}}}for(let e of n.badges.map(a).filter(e=>e.onClick))if(isInRect(u[0],u[1],e.boundingRect)){r.onClick=e.onClick;return}if(n.onMouseDown?.(e,u,this)){r.onClick=()=>{};return}if(!this.allow_dragnodes)return;if(!n.flags.collapsed){let e=n.findResizeDirection(s,c);if(e){r.resizeDirection=e;let t=new G(n.pos[0],n.pos[1],n.size[0],n.size[1]);r.onDragStart=()=>{i.beforeChange(),this.resizing_node=n},r.onDrag=r=>{if(this.read_only)return;let i=r.canvasX-s,a=r.canvasY-c,o=new G(t.x,t.y,t.width,t.height);switch(e){case`NE`:o.y=t.y+a,o.width=t.width+i,o.height=t.height-a;break;case`SE`:o.width=t.width+i,o.height=t.height+a;break;case`SW`:o.x=t.x+i,o.width=t.width-i,o.height=t.height+a;break;case`NW`:o.x=t.x+i,o.y=t.y+a,o.width=t.width-i,o.height=t.height-a;break}
2if(this._snapToGrid){if(e.includes(`N`)||e.includes(`W`)){let t=o.x,n=o.y;snapPoint(o.pos,this._snapToGrid),e.includes(`N`)&&(o.height+=n-o.y),e.includes(`W`)&&(o.width+=t-o.x)}snapPoint(o.size,this._snapToGrid)}let l=n.computeSize();this._snapToGrid&&snapPoint(l,this._snapToGrid,`ceil`),o.width<l[0]&&(e.includes(`W`)&&(o.x=t.x+t.width-l[0]),o.width=l[0]),o.height<l[1]&&(e.includes(`N`)&&(o.y=t.y+t.height-l[1]),o.height=l[1]),n.pos=o.pos,n.setSize(o.size),this._dirty()},r.onDragEnd=()=>{this._dirty(),i.afterChange(n)},r.finally=()=>{this.resizing_node=null,r.resizeDirection=void 0},this._setCursor(ft[e]);return}}r.onDragStart=e=>this._startDraggingItems(n,e,!0),r.onDragEnd=e=>this._processDraggedItems(e)}this.dirty_canvas=!0}processWidgetClick(e,t,n,r=this.pointer){if(typeof n.onPointerDown==`function`&&n.onPointerDown(r,t,this))return;let i=n.value,a=this.graph_mouse,o=a[0]-t.pos[0],s=a[1]-t.pos[1],c=toConcreteWidget(n,t,!1);if(c)r.onClick=()=>c.onClick({e,node:t,canvas:this}),r.onDrag=e=>c.onDrag?.({e,node:t,canvas:this});else if(n.mouse){let r=n.mouse(e,[o,s],t);r!=null&&(this.dirty_canvas=r)}if(i!=n.value){if(t.onWidgetChanged?.(n.name,n.value,i,n),!t.graph)throw new NullGraphError;t.graph.incrementVersion()}r.finally=()=>
2{if(n.mouse){let{eUp:e}=r;if(!e)return;let{canvasX:i,canvasY:a}=e;n.mouse(e,[i-t.pos[0],a-t.pos[1]],t)}this.node_widget=null}}_processMiddleButton(e,t){let{pointer:n}=this;if(Q.middle_click_slot_add_default_node&&t&&this.allow_interaction&&!this.read_only&&!this.connecting_links&&!t.flags.collapsed){let r=!1,i=!1,a=!1,{inputs:o,outputs:s}=t;if(s)for(let[n,o]of s.entries()){let s=t.getOutputPos(n);if(isInRectangle(e.canvasX,e.canvasY,s[0]-15,s[1]-10,30,20)){r=o,i=n,a=!0;break}}if(o)for(let[n,s]of o.entries()){let o=t.getInputPos(n);if(isInRectangle(e.canvasX,e.canvasY,o[0]-15,o[1]-10,30,20)){r=s,i=n,a=!1;break}}if(r&&i!==!1){let r=.5-(i+1)/(a?s.length:o.length),c=t.getBounding(),l=[a?c[0]+c[2]:c[0],e.canvasY-80];n.onClick=()=>this.createDefaultNodeForSlot({nodeFrom:a?t:null,slotFrom:a?i:null,nodeTo:a?null:t,slotTo:a?null:i,position:l,nodeType:`AUTO`,posAdd:[a?30:-30,-r*130],posSizeFix:[a?0:-1,0]})}}this.allow_dragcanvas&&(n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1)}_processDragZoom(e){if(!e.buttons){this._finishDragZoom();return}let t=this._dragZoomStart;if(!t)throw TypeError(`Drag-zoom state object was null`);if(!this.graph)throw new NullGraphError;let n=e.y-t.pos[1],r=t.scale-n/100;this.ds.changeScale(r,t.pos),this.graph.change()}_finishDragZoom(){let e=this._dragZoomStart;e&&(this._dragZoomStart=null,this.read_only=e.readOnly)}processMouseMove(e){if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&this._dragZoomStart){this._processDragZoom(e);return}this.autoresize&&this.resize(),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);let{graph:t,resizingGroup:n,linkConnector:r,pointer:i,subgraph:a}=this;if(!t)return;LGraphCanvas.active_canvas=this,this.adjustMouseEvent(e);let o=[e.clientX,e.clientY];this.mouse[0]=o[0],this.mouse[1]=o[1];let s=[o[0]-this.last_mouse[0],o[1]-this.last_mouse[1]];this.last_mouse=o;let{canvasX:c,canvasY:l}=e;this.graph_mouse[0]=c,this.graph_mouse[1]=l,e.isPrimary&&i.move(e);let u=F.Nothing;if(a&&(u|=a.inputNode.onPointerMove(e),u|=a.outputNode.onPointerMove(e)),this.block_click){e.preventDefault();return}if(e.dragging=this.last_mouse_dragging,this.node_widget){let[t,n]=this.node_widget;if(n?.mouse){let r=c-t.pos[0],i=l-t.pos[1],a=n.mouse(e,[r,i],t);a!=null&&(this.dirty_canvas=a)}}let d=r.renderLinks.at(0),f=r.isConnecting&&d?.isIoNodeLink,p=Q.vueNodesMode&&!f?null:t.getNodeOnPos(c,l,this.visible_nodes),m=this.dragging_rectangle;if(m)m[2]=c-m[0],m[3]=l-m[1],this.dirty_canvas=!0;else if(n)u|=F.Group,i.resizeDirection=`SE`;else if(this.dragging_canvas)this.ds.offset[0]+=s[0]/this.ds.scale,this.ds.offset[1]+=s[1]/this.ds.scale,this._dirty();else if((this.allow_interaction||p?.flags.allow_interaction)&&!this.read_only){if(r.isConnecting&&(this._autoPan?.updatePointer(e.clientX,e.clientY),this.dirty_canvas=!0),this.updateMouseOverNodes(p,e),p){u|=F.Node,p.redraw_on_mouse&&(this.dirty_canvas=!0);let t=[0,0],n=-1,a=-1,o=U.querySlotAtPoint({x:c,y:l});o&&o.nodeId===String(p.id)?o.type===`input`?(n=o.index,t[0]=o.position.x,t[1]=o.position.y):(a=o.index,t[0]=o.position.x,t[1]=o.position.y):(n=isOverNodeInput(p,c,l,t),a=isOverNodeOutput(p,c,l,t));let s=p.getWidgetOnPos(c,l,!0)??void 0;if(!p.mouseOver){p.mouseOver={},this.node_over=p,this.dirty_canvas=!0;for(let e of this._visibleReroutes)e.hideSlots(),this.dirty_bgcanvas=!0;p.onMouseEnter?.(e)}p.onMouseMove?.(e,[c-p.pos[0],l-p.pos[1]],this);let{mouseOver:f}=p;if(f.inputId!==n||f.outputId!==a||f.overWidget!==s){if(f.inputId=n,f.outputId=a,f.overWidget=s,r.overWidget=void 0,r.isConnecting){let e,i;if(!(!d||!r.isNodeValidDrop(p))){if(r.state.connectingTo===`input`){if(s){let t=p.getSlotFromWidget(s);if(t&&r.isInputValidDrop(p,t)){if(i=t,Q.vueNodesMode){let n=p.inputs.indexOf(t);e=n===-1?p.getInputSlotPos(t):getSlotPosition(p,n,!0)}else e=p.getInputSlotPos(t);r.overWidget=s}}if(!r.overWidget){if(n===-1&&a===-1){let t=p.findInputByType(d.fromSlot.type);t&&(i=t.slot,e=Q.vueNodesMode?getSlotPosition(p,t.index,!0):p.getInputSlotPos(t.slot))}else n!=-1&&p.inputs[n]&&Q.isValidConnection(d.fromSlot.type,p.inputs[n].type)&&(e=t,i=p.inputs[n]);if(i&&!Q.vueNodesMode){let e=p.getWidgetFromSlot(i);e&&(r.overWidget=e)}}}else if(r.state.connectingTo===`output`)if(n===-1&&a===-1){let t=p.findOutputByType(d.fromSlot.type);t&&(e=Q.vueNodesMode?getSlotPosition(p,t.index,!1):p.getOutputPos(t.index))}else a!=-1&&p.outputs[a]&&Q.isValidConnection(d.fromSlot.type,p.outputs[a].type)&&(e=t)}this._highlight_pos=e,this._highlight_input=i}this.dirty_canvas=!0}i.eDown||(n===-1&&a===-1&&!s?i.resizeDirection=p.findResizeDirection(c,l):i.resizeDirection&&=void 0)}else{u=this._updateReroutes(u);let n=this._getLinkCentreOnPos(e);if(this.over_link_center!==n&&(u|=F.Link,this.over_link_center=n,this.dirty_bgcanvas=!0),this.canvas){let n=t.getGroupOnPos(c,l);n&&!e.ctrlKey&&!this.read_only&&n.isInResize(c,l)?i.resizeDirection=`SE`:i.resizeDirection&&=void 0}}if(this.node_capturing_input&&this.node_capturing_input!=p&&this.node_capturing_input.onMouseMove?.(e,[c-this.node_capturing_input.pos[0],l-this.node_capturing_input.pos[1]],this),this.isDragging){this._autoPan?.updatePointer(e.clientX,e.clientY);let t=this.selectedItems,n=e.ctrlKey?t:getAllNestedItems(t),r=s[0]/this.ds.scale,i=s[1]/this.ds.scale;if(Q.vueNodesMode)this.moveChildNodesInGroupVueMode(n,r,i);else for(let e of n)e.move(r,i,!0);this._dirty()}}this.hoveringOver=u,e.preventDefault()}_updateReroutes(e){let{graph:t,pointer:n,linkConnector:r}=this;if(!t)throw new NullGraphError;if(!n.isDown){let t=!1;for(let n of this._visibleReroutes)t||=n.updateVisibility(this.graph_mouse),n.isSlotHovered&&(e|=F.RerouteSlot);t&&(this.dirty_bgcanvas=!0)}else if(r.isConnecting){for(let t of this._visibleReroutes)if(t.containsPoint(this.graph_mouse))return r.isRerouteValidDrop(t)&&(r.overReroute=t,this._highlight_pos=t.pos),e|=F.RerouteSlot}return this._highlight_pos&&=void 0,r.overReroute&&=void 0,e}_startDraggingItems(e,t,n=!1){this.emitBeforeChange(),this.graph?.beforeChange(),t.finally=()=>{this.isDragging=!1,this._autoPan?.stop(),this._autoPan=null,this.graph?.afterChange(),this.emitAfterChange()},this.processSelect(e,t.eDown,n),this.isDragging=!0,this._startNodeAutoPan()}_startNodeAutoPan(){this._autoPan=new AutoPanController({canvas:this.canvas,ds:this.ds,maxPanSpeed:this.auto_pan_speed,onPan:(e,t)=>{let n=this.selectedItems,r=getAllNestedItems(n);if(Q.vueNodesMode)this.moveChildNodesInGroupVueMode(r,e,t);else for(let n of r)n.move(e,t,!0);this._dirty()}}),this._autoPan.updatePointer(this.mouse[0],this.mouse[1]),this._autoPan.start()}_processDraggedItems(e){let{graph:t}=this;
2(e.shiftKey||Q.alwaysSnapToGrid)&&t?.snapToGrid(this.selectedItems),this.dirty_canvas=!0,this.dirty_bgcanvas=!0,this.onNodeMoved?.(findFirstNode(this.selectedItems))}startGhostPlacement(e,t){if(this.state.ghostNodeId!=null&&this.finalizeGhostPlacement(!0),this.emitBeforeChange(),this.graph?.beforeChange(),t){this.adjustMouseEvent(t);let n=t;e.setPos(n.canvasX-e.size[0]/2,n.canvasY+10),this.last_mouse=[n.clientX,n.clientY]}else e.setPos(this.graph_mouse[0]-e.size[0]/2,this.graph_mouse[1]+10);this.state.ghostNodeId=e.id,this.dispatchEvent(`litegraph:ghost-placement`,{active:!0,nodeId:e.id}),this.deselectAll(),this.select(e),this.isDragging=!0,this._startNodeAutoPan(),this._ghostPointerHandler=e=>{this.processMouseMove(e)},document.addEventListener(`pointermove`,this._ghostPointerHandler),document.documentElement.addEventListener(`pointerleave`,this._ghostPointerHandler),this._ghostKeyHandler=e=>{e.key!==`Escape`&&e.key!==`Delete`&&e.key!==`Backspace`||(this.finalizeGhostPlacement(!0),e.stopPropagation(),e.preventDefault())},document.addEventListener(`keydown`,this._ghostKeyHandler,!0)}finalizeGhostPlacement(e){let t=this.state.ghostNodeId;if(t==null)return;this.state.ghostNodeId=null,this.isDragging=!1,this.dispatchEvent(`litegraph:ghost-placement`,{active:!1,nodeId:t}),this._autoPan?.stop(),this._autoPan=null,this._ghostPointerHandler&&=(document.removeEventListener(`pointermove`,this._ghostPointerHandler),document.documentElement.removeEventListener(`pointerleave`,this._ghostPointerHandler),null),this._ghostKeyHandler&&=(document.removeEventListener(`keydown`,this._ghostKeyHandler,!0),null);let n=this.graph?.getNodeById(t);n&&(e?(this.deselect(n),this.graph?.remove(n)):(delete n.flags.ghost,this.graph?.trigger(`node:property:changed`,{nodeId:n.id,property:`flags.ghost`,oldValue:!0,newValue:!1}),this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes)),this.dirty_canvas=!0,this.dirty_bgcanvas=!0,this.graph?.afterChange(),this.emitAfterChange())}processMouseUp(e){if(e.isPrimary===!1)return;let{graph:t,pointer:n}=this;if(t){if(this._finishDragZoom(),LGraphCanvas.active_canvas=this,this.adjustMouseEvent(e),e.click_time=Q.getTime()-this.last_mouseclick,n.up(e)===!0){n.isDown=!1,n.isDouble=!1,this.connecting_links=null,this.dragging_canvas=!1,t.change(),e.stopPropagation(),e.preventDefault();return}if(this.last_mouse_dragging=!1,this.last_click_position=null,this.block_click&&=!1,e.button===0){this.selected_group=null,this.isDragging=!1;let t=e.canvasX,n=e.canvasY;this.linkConnector.isConnecting||(this.dirty_canvas=!0,this.node_over?.onMouseUp?.(e,[t-this.node_over.pos[0],n-this.node_over.pos[1]],this),this.node_capturing_input?.onMouseUp?.(e,[t-this.node_capturing_input.pos[0],n-this.node_capturing_input.pos[1]],this))}else e.button===1?(this.dirty_canvas=!0,this.dragging_canvas=!1):e.button===2&&(this.dirty_canvas=!0);n.isDown=!1,n.isDouble=!1,t.change(),e.stopPropagation(),e.preventDefault()}}processMouseOut(e){this.adjustMouseEvent(e),this.updateMouseOverNodes(null,e)}processMouseCancel(){console.warn(`Pointer cancel!`),this.pointer.reset()}processMouseWheel(e){if(!this.graph||!this.allow_dragcanvas)return;this.adjustMouseEvent(e);let t=[e.clientX,e.clientY];if(this.viewport&&!isPointInRect(t,this.viewport))return;let{scale:n}=this.ds,r=this.pointer.isTrackpadGesture(e);if((e.ctrlKey||e.metaKey&&navigator.platform.includes(`Mac`))&&!e.altKey&&!e.shiftKey||Q.mouseWheelScroll===`zoom`)r?(n*=1+e.deltaY*(1-this.zoom_speed)*.18,this.ds.changeScale(n,[e.clientX,e.clientY],!1)):(e.deltaY<0?n*=this.zoom_speed:e.deltaY>0&&(n*=1/this.zoom_speed),this.ds.changeScale(n,[e.clientX,e.clientY]));else{let t=r?.18:.008333;!r&&e.shiftKey&&e.deltaX===0?this.ds.offset[0]-=e.deltaY*(1+t)*(1/n):(this.ds.offset[0]-=e.deltaX*(1+t)*(1/n),this.ds.offset[1]-=e.deltaY*(1+t)*(1/n))}this.graph.change(),e.preventDefault()}processKey(e){this._shiftDown=e.shiftKey;let{graph:t}=this;if(!t)return;let n=!1;if(e.target.localName!=`input`){if(e.type==`keydown`){if(e.key===` `)this.read_only=!0,this._previously_dragging_canvas===null&&(this._previously_dragging_canvas=this.dragging_canvas),this.dragging_canvas=this.pointer.isDown,n=!0;else if(e.key===`Escape`){if(this.linkConnector.isConnecting){this.linkConnector.reset(),e.preventDefault();return}this.node_panel?.close(),this.options_panel?.close(),(this.node_panel||this.options_panel)&&(n=!0)}for(let t of Object.values(this.selected_nodes))t.onKeyDown?.(e)}else if(e.type==`keyup`){e.key===` `&&(this.read_only=!1,this.dragging_canvas=(this._previously_dragging_canvas??!1)&&this.pointer.isDown,this._previously_dragging_canvas=null);for(let t of Object.values(this.selected_nodes))t.onKeyUp?.(e)}t.change(),n&&(e.preventDefault(),e.stopImmediatePropagation())}}_serializeItems(e){let t={nodes:[],groups:[],reroutes:[],links:[],subgraphs:[]},n=new Set;for(let r of e??this.selectedItems)if(r instanceof Y){if(r.clonable===!1)continue;let e=r.clone()?.serialize();if(!e)continue;if(e.id=r.id,t.nodes.push(e),r.inputs)for(let{link:e}of r.inputs){if(e==null)continue;let n=this.graph?._links.get(e)?.asSerialisable();n&&t.links.push(n)}r instanceof SubgraphNode&&n.add(r.subgraph)}else r instanceof X?t.groups.push(r.serialize()):r instanceof q&&t.reroutes.push(r.asSerialisable());for(let e of n){for(let t of e.nodes)t instanceof SubgraphNode&&n.add(t.subgraph);let r=e.clone(!0).asSerialisable();t.subgraphs.push(r)}return t}copyToClipboard(e){let t=JSON.stringify(this._serializeItems(e));return localStorage.setItem(`litegrapheditor_clipboard`,t),t}emitEvent(e){this.canvas.dispatchEvent(new CustomEvent(`litegraph:canvas`,{bubbles:!0,detail:e}))}emitBeforeChange(){this.emitEvent({subType:`before-change`})}emitAfterChange(){this.emitEvent({subType:`after-change`})}_pasteFromClipboard(e={}){let t=localStorage.getItem(`litegrapheditor_clipboard`);if(t)return this._deserializeItems(JSON.parse(t),e)}
2_deserializeItems(e,t){let{connectInputs:n=!1,position:r=this.graph_mouse}=t;if(!Q.ctrl_shift_v_paste_connect_unselected_outputs&&n)return;let{graph:i}=this;if(!i)throw new NullGraphError;i.beforeChange(),this.emitBeforeChange(),e.nodes??=[],e.groups??=[],e.reroutes??=[],e.links??=[],e.subgraphs??=[];let a=1/0,o=1/0;for(let t of[...e.nodes,...e.reroutes]){if(t.pos==null)throw TypeError("Invalid node encountered on paste.  `pos` was null.");t.pos[0]<a&&(a=t.pos[0]),t.pos[1]<o&&(o=t.pos[1])}if(e.groups)for(let t of e.groups)t.bounding[0]<a&&(a=t.bounding[0]),t.bounding[1]<o&&(o=t.bounding[1]);let s={created:[],nodes:new Map,links:new Map,reroutes:new Map,subgraphs:new Map},{created:c,nodes:l,links:u,reroutes:d}=s,f={};for(let t of e.subgraphs)t.id=f[t.id]=createUuidv4();let p=[e.nodes?[e.nodes]:[],e.subgraphs?e.subgraphs.map(e=>e.nodes??[]):[]].flat(2);for(let e of p)e.type in f&&(e.type=f[e.type]);remapClipboardSubgraphNodeIds(e,i.rootGraph);for(let t of e.subgraphs){let e=i.createSubgraph(t);s.subgraphs.set(t.id,e)}for(let t of e.subgraphs)s.subgraphs.get(t.id)?.configure(t);for(let t of e.groups){t.id=-1;let e=new X;e.configure(t),i.add(e),c.push(e)}for(let t of e.nodes){let e=t.type==null?null:Q.createNode(t.type);
2e&&(l.set(t.id,e),t.id=-1,i.add(e),e.configure(t),c.push(e))}for(let t of e.reroutes){let{id:e,...n}=t,r=i.setReroute(n);c.push(r),d.set(e,r)}for(let e of d.values()){if(e.parentId==null)continue;let t=d.get(e.parentId);t&&(e.parentId=t.id)}for(let t of e.links){let e=l.get(t.origin_id),r;t.parentId!=null&&(r=d.get(t.parentId)?.id),n&&Q.ctrl_shift_v_paste_connect_unselected_outputs&&(e??=i.getNodeById(t.origin_id),r??=t.parentId);let a=l.get(t.target_id);if(a){let n=e?.connect(t.origin_slot,a,t.target_slot,r);n&&u.set(t.id,n)}}for(let e of d.values()){let t=[...e.linkIds].map(e=>u.get(e)?.id??e);e.update(e.parentId,void 0,t,e.floating),e.validateLinks(i.links,i.floatingLinks)||i.removeReroute(e.id)}let m=r[0]-a,h=r[1]-o;for(let e of c)e instanceof Y?e.setPos(e.pos[0]+m,e.pos[1]+h):e instanceof q?e.move(m,h):e instanceof X&&e.move(m,h,!0);let g=c.filter(e=>e instanceof Y).map(e=>({nodeId:String(e.id),bounds:{x:e.pos[0],y:e.pos[1],width:e.size?.[0]??100,height:e.size?.[1]??200}}));g.length&&U.setSource(H.Canvas),U.batchUpdateNodeBounds(g);let _=U.getAllNodes().value,v=0;for(let[,e]of _)e.zIndex>v&&(v=e.zIndex);let{setNodeZIndex:y}=useLayoutMutations();for(let e=0;e<g.length;e++)y(g[e].nodeId,v+e+1);return this.selectItems(c),forEachNode(i,e=>e.onGraphConfigured?.()),forEachNode(i,e=>e.onAfterGraphConfigured?.()),i.afterChange(),this.emitAfterChange(),s}pasteFromClipboard(e={}){this.emitBeforeChange();try{this._pasteFromClipboard(e)}finally{this.emitAfterChange()}}processNodeDblClicked(e){this.onShowNodePanel?.(e),this.onNodeDblClicked?.(e),this.setDirty(!0)}_normalizeDragRect(e){let t=Math.abs(e[2]),n=Math.abs(e[3]);return e[2]<0&&(e[0]-=t),e[3]<0&&(e[1]-=n),e[2]=t,e[3]=n,e}_getItemsInRect(e){let{graph:t,subgraph:n}=this;if(!t)throw new NullGraphError;let r=new Set;if(n){let{inputNode:t,outputNode:i}=n;overlapBounding(e,t.boundingRect)&&r.add(t),overlapBounding(e,i.boundingRect)&&r.add(i)}for(let n of t._nodes)overlapBounding(e,n.boundingRect)&&r.add(n);for(let n of t.groups)containsRect(e,n._bounding)&&(n.recomputeInsideNodes(),r.add(n));for(let n of t.reroutes.values())isPointInRect(n.pos,e)&&r.add(n);return r}handleLiveSelect(e,t,n){t[2]=e.canvasX-t[0],t[3]=e.canvasY-t[1];let r=[t[0],t[1],t[2],t[3]];this._normalizeDragRect(r);let i=this._getItemsInRect(r),a=new Set;if(e.shiftKey&&!e.altKey){for(let e of n)a.add(e);for(let e of i)a.add(e)}else if(e.altKey&&!e.shiftKey)for(let e of n)i.has(e)||a.add(e);else for(let e of i)a.add(e);let o=!1;for(let e of[...this.selectedItems])a.has(e)||(this.deselect(e),o=!0);for(let e of a)this.selectedItems.has(e)||(this.select(e),o=!0);o&&(this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0))}finalizeLiveSelect(){this.onSelectionChange?.(this.selected_nodes)}_handleMultiSelect(e,t){let n=[t[0],t[1],t[2],t[3]];this._normalizeDragRect(n);let r=this._getItemsInRect(n),{selectedItems:i}=this;if(e.shiftKey)for(let e of r)this.select(e);else if(e.altKey)for(let e of r)this.deselect(e);else{for(let e of i.values())r.has(e)||this.deselect(e);for(let e of r)this.select(e)}this.onSelectionChange?.(this.selected_nodes)}processSelect(e,t,n=!1){let r=t?.shiftKey,i=t!=null&&(t.metaKey||t.ctrlKey),a=r||i,o=a||this.multi_select;if(!e)(!a||this.multi_select)&&this.deselectAll();else if(!e.selected||!this.selectedItems.has(e))o||this.deselectAll(e),this.select(e);else if(o&&!n)e instanceof X&&this.groupSelectChildren?(e.selected=!1,this.selectedItems.delete(e),this.state.selectionChanged=!0):this.deselect(e);else if(!n)this.deselectAll(e);else return;this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}select(e){if(!(e.selected&&this.selectedItems.has(e))){if(e.selected=!0,this.selectedItems.add(e),this.state.selectionChanged=!0,e instanceof X){e.recomputeInsideNodes(),this.groupSelectChildren&&this.#e(e,e=>{(!e.selected||!this.selectedItems.has(e))&&(e.selected=!0,this.selectedItems.add(e),this.state.selectionChanged=!0)},e=>this.select(e));return}if(e instanceof Y){if(e.onSelected?.(),this.selected_nodes[e.id]=e,this.onNodeSelected?.(e),e.inputs)for(let t of e.inputs)t.link!=null&&(this.highlighted_links[t.link]=!0);if(e.outputs)for(let t of e.outputs.flatMap(e=>e.links))t!=null&&(this.highlighted_links[t]=!0)}}}deselect(e){if(!e.selected&&!this.selectedItems.has(e))return;if(e.selected=!1,this.selectedItems.delete(e),this.state.selectionChanged=!0,e instanceof X&&this.groupSelectChildren){this.#e(e,e=>{(e.selected||this.selectedItems.has(e))&&(e.selected=!1,this.selectedItems.delete(e),this.state.selectionChanged=!0)},e=>this.deselect(e));return}if(!(e instanceof Y))return;e.onDeselected?.(),delete this.selected_nodes[e.id],this.onNodeDeselected?.(e);let{graph:t}=this;
2if(t){if(e.inputs)for(let n of e.inputs){if(n.link==null)continue;let e=K.getOriginNode(t,n.link);e&&this.selectedItems.has(e)||delete this.highlighted_links[n.link]}if(e.outputs)for(let n of e.outputs.flatMap(e=>e.links)){if(n==null)continue;let e=K.getTargetNode(t,n);e&&this.selectedItems.has(e)||delete this.highlighted_links[n]}}}#e(e,t,n){let r=[...e._children];for(;r.length>0;){let e=r.pop();if(e instanceof X){t(e);for(let t of e._children)r.push(t)}else n(e)}}processNodeSelected(e,t){this.processSelect(e,t,t&&(t.shiftKey||t.metaKey||t.ctrlKey||this.multi_select))}selectNode(e,t){e==null?this.deselectAll():this.selectNodes([e],t)}get empty(){if(!this.graph)throw new NullGraphError;return this.graph.empty}get positionableItems(){if(!this.graph)throw new NullGraphError;return this.graph.positionableItems()}selectItems(e,t){let n=e??this.positionableItems;t||this.deselectAll();for(let e of n)this.select(e);this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}selectNodes(e,t){this.selectItems(e,t)}deselectNode(e){this.deselect(e)}deselectAll(e){if(!this.graph)return;let t=this.selectedItems;if(!t.size)return;let n=t.size,r;for(let n of t){if(n===e){r=n;continue}n.onDeselected?.(),n.selected=!1}t.clear(),r&&t.add(r),this.setDirty(!0);let i=e?.id==null?null:this.selected_nodes[e.id];if(this.selected_nodes={},this.current_node=null,this.highlighted_links={},e instanceof Y){if(i&&(this.selected_nodes[i.id]=i),e.inputs)for(let t of e.inputs)t.link!=null&&(this.highlighted_links[t.link]=!0);if(e.outputs)for(let t of e.outputs.flatMap(e=>e.links))t!=null&&(this.highlighted_links[t]=!0)}n!==t.size&&(this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes))}deselectAllNodes(){this.deselectAll()}deleteSelected(){let{graph:e}=this;if(!e)throw new NullGraphError;this.emitBeforeChange(),e.beforeChange();let t=[...this.selectedItems];for(let n of t)if(n instanceof Y){let t=n;if(t.block_delete)continue;t.connectInputToOutput(),e.remove(t),this.onNodeDeselected?.(t)}else n instanceof X?e.remove(n):n instanceof q&&e.removeReroute(n.id);this.selected_nodes={},this.selectedItems.clear(),this.current_node=null,this.highlighted_links={},this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0),e.afterChange(),this.emitAfterChange()}deleteSelectedNodes(){this.deleteSelected()}centerOnNode(e){let t=window?.devicePixelRatio||1;this.ds.offset[0]=-e.pos[0]-e.size[0]*.5+this.canvas.width*.5/(this.ds.scale*t),this.ds.offset[1]=-e.pos[1]-e.size[1]*.5+this.canvas.height*.5/(this.ds.scale*t),this.setDirty(!0,!0)}adjustMouseEvent(e){let t=e.clientX,n=e.clientY;if(this.canvas){let e=this.canvas.getBoundingClientRect();t-=e.left,n-=e.top}e.safeOffsetX=t,e.safeOffsetY=n,e.deltaX===void 0&&(e.deltaX=t-this.last_mouse_position[0]),e.deltaY===void 0&&(e.deltaY=n-this.last_mouse_position[1]),this.last_mouse_position[0]=t,this.last_mouse_position[1]=n,e.canvasX=t/this.ds.scale-this.ds.offset[0],e.canvasY=n/this.ds.scale-this.ds.offset[1]}setZoom(e,t){this.ds.changeScale(e,t),this._dirty()}convertOffsetToCanvas(e,t){return this.ds.convertOffsetToCanvas(e)}convertCanvasToOffset(e,t){return this.ds.convertCanvasToOffset(e,t)}convertEventToCanvasOffset(e){let t=this.canvas.getBoundingClientRect();return this.convertCanvasToOffset([e.clientX-t.left,e.clientY-t.top])}bringToFront(e){let{graph:t}=this;if(!t)throw new NullGraphError;let n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.push(e))}sendToBack(e){let{graph:t}=this;if(!t)throw new NullGraphError;let n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.unshift(e))}computeVisibleNodes(e,t){let n=t||[];if(n.length=0,!this.graph)throw new NullGraphError;let r=e||this.graph._nodes;for(let e of r)e.updateArea(this.ctx),overlapBounding(this.visible_area,e.renderArea)&&n.push(e);return n}isNodeVisible(e){return this._visible_node_ids.has(e.id)}draw(e,t){if(!this.canvas||this.canvas.width==0||this.canvas.height==0)return;let n=Q.getTime();if(this.render_time=(n-this.last_draw_time)*.001,this.last_draw_time=n,this.graph&&this.ds.computeVisibleArea(this.viewport),this.dirty_canvas||e){this.computeVisibleNodes(void 0,this.visible_nodes),this._visible_node_ids=new Set(this.visible_nodes.map(e=>e.id));let{subgraph:e}=this;e&&(e.inputNode.arrange(),e.outputNode.arrange())}(this.dirty_bgcanvas||t||this.always_render_background||this.graph?._last_trigger_time&&n-this.graph._last_trigger_time<1e3)&&this.drawBackCanvas(),(this.dirty_canvas||e)&&this.drawFrontCanvas(),this.fps=this.render_time?1/this.render_time:0,this.frame++}drawFrontCanvas(){clearTextMeasureCache(),this.dirty_canvas=!1;let{ctx:e,canvas:t,graph:n}=this;
2e.start2D&&!this.viewport&&(e.start2D(),e.restore(),e.setTransform(1,0,0,1,0,0));let r=this.viewport||this.dirty_area;if(r&&(e.save(),e.beginPath(),e.rect(r[0],r[1],r[2],r[3]),e.clip()),this._snapToGrid=this._shiftDown||Q.alwaysSnapToGrid?this.graph?.getSnapToGridSize():void 0,this.clear_background&&(r?e.clearRect(r[0],r[1],r[2],r[3]):e.clearRect(0,0,t.width,t.height)),this.bgcanvas==this.canvas)this.drawBackCanvas();else{let t=window.devicePixelRatio;e.drawImage(this.bgcanvas,0,0,this.bgcanvas.width/t,this.bgcanvas.height/t)}if(this.onRender?.(t,e),this.show_info){let t=this.fpsInfoLocation??r;this.renderInfo(e,t?.[0]??0,t?.[1]??0)}if(n){e.save(),this.ds.toCanvasContext(e);let{visible_nodes:t}=this,r=this._snapToGrid&&(this.isDragging||U.isDraggingVueNodes.value);for(let n of t)e.save(),r&&this.selectedItems.has(n)&&this.drawSnapGuide(e,n),e.translate(n.pos[0],n.pos[1]),this.drawNode(n,e),e.restore();this.subgraph?.draw(e,this.colourGetter,this.linkConnector.renderLinks[0]?.fromSlot,this.editor_alpha),this.render_execution_order&&this.drawExecutionOrder(e),n.config.links_ontop&&this.drawConnections(e),!Q.vueNodesMode||!this.overlayCtx?this._drawConnectingLinks(e):this._drawOverlayLinks(),this._drawLinkTooltip(e),this.onDrawForeground?.(e,this.visible_area),e.restore()}this.onDrawOverlay?.(e),r&&e.restore()}_getLinkCentreOnPos(e){if(this.linkMarkerShape!==R.None)for(let t of this.renderedPaths){let n=t._pos;if(n&&isInRectangle(e.canvasX,e.canvasY,n[0]-4,n[1]-4,8,8))return t}}_drawConnectingLinks(e){let{linkConnector:t}=this;if(!t.isConnecting)return;let{renderLinks:n}=t,r=this._getHighlightPosition();e.lineWidth=this.connections_width;for(let t of n){let{fromSlot:n,fromPos:i,fromDirection:a,dragDirection:o}=t,s=n.shape,c=n.type,l=resolveConnectingLinkColor(c);this.linkRenderer&&this.linkRenderer.renderDraggingLink(e,i,r,l,a,o,{...this.buildLinkRenderContext(),linkMarkerShape:R.None}),t instanceof MovingInputLink&&this.setDirty(!1,!0),e.fillStyle=l,e.beginPath(),c===Q.EVENT||s===P.BOX?(e.rect(i[0]-6+.5,i[1]-5+.5,14,10),e.rect(r[0]-6+.5,r[1]-5+.5,14,10)):s===P.ARROW?(e.moveTo(i[0]+8,i[1]+.5),e.lineTo(i[0]-4,i[1]+6+.5),e.lineTo(i[0]-4,i[1]-6+.5),e.closePath()):(e.arc(i[0],i[1],4,0,Math.PI*2),e.arc(r[0],r[1],4,0,Math.PI*2)),e.fill()}this._renderSnapHighlight(e,r)}_drawLinkTooltip(e){!this.isDragging&&this.over_link_center&&this.render_link_tooltip?this.drawLinkTooltip(e,this.over_link_center):this.onDrawLinkTooltip?.(e,null)}_drawOverlayLinks(){let e=this.overlayCtx,t=this.overlayCanvas;if(!e||!t||(e.clearRect(0,0,t.width,t.height),!this.linkConnector.isConnecting))return;e.save();let n=t.width/(t.clientWidth||1);e.setTransform(n,0,0,n,0,0),this.ds.toCanvasContext(e),this._drawConnectingLinks(e),e.restore()}_getHighlightPosition(){return Q.snaps_for_comfy?this.linkConnector.state.snapLinksPos??this._highlight_pos??this.graph_mouse:this.graph_mouse}
2_renderSnapHighlight(e,t){let n=!!this.linkConnector.state.snapLinksPos;if(!this._highlight_pos&&!n)return;e.fillStyle=`#ffcc00`,e.beginPath(),this._highlight_input?.shape===P.ARROW?(e.moveTo(t[0]+8,t[1]+.5),e.lineTo(t[0]-4,t[1]+6+.5),e.lineTo(t[0]-4,t[1]-6+.5),e.closePath()):e.arc(t[0],t[1],6,0,Math.PI*2),e.fill();let{linkConnector:r}=this,{overReroute:i,overWidget:a}=r;if(!Q.snap_highlights_node||!r.isConnecting||n)return;i?.drawHighlight(e,`#ffcc00aa`);let o=this.node_over;if(!o)return;let{strokeStyle:s,lineWidth:c}=e,l=o.boundingRect,u=Q.ROUND_RADIUS+3,d=l[0]-3,f=l[1]-3,p=l[2]+6,m=l[3]+6;e.beginPath(),e.roundRect(d,f,p,m,u);let h=r.state.connectingTo===`output`?0:1,g=h?-1:1,_=t[0],v=t[1],y=p<m?p:p*Math.max(m/p,.5),ee=e.createRadialGradient(_,v,0,_,v,y);ee.addColorStop(1,`#00000000`),ee.addColorStop(0,`#ffcc00aa`);let te=e.createLinearGradient(d,f,d+p,f);if(te.addColorStop(.5,`#00000000`),te.addColorStop(h+.67*g,`#ddeeff33`),te.addColorStop(h+g,`#ffcc0055`),e.setLineDash([u,u*.001]),e.lineWidth=1,e.strokeStyle=te,e.stroke(),a){let{computedHeight:t}=a;e.beginPath();let{pos:[n,r]}=o,i=Q.NODE_WIDGET_HEIGHT;a.type.startsWith(`custom`)&&t!=null&&t>i*2?e.rect(n+9,r+a.y+9,(a.width??l[2])-18,t-18):e.roundRect(n+J.margin,r+a.y,a.width??l[2],i,i*.5),e.stroke()}e.strokeStyle=ee,e.stroke(),e.setLineDash([]),e.lineWidth=c,e.strokeStyle=s}renderInfo(e,t,n){let r=(this.graph?5:1)+(this.info_text?1:0);t||=10,n||=this.canvas.height/((this.canvas.ownerDocument.defaultView??window).devicePixelRatio||1)-(r+1)*13,e.save(),e.translate(t,n),e.font=`10px ${Q.DEFAULT_FONT}`,e.fillStyle=`#888`,e.textAlign=`left`;let i=1;this.graph?(e.fillText(`T: ${this.graph.globaltime.toFixed(2)}s`,5,13*i++),e.fillText(`I: ${this.graph.iteration}`,5,13*i++),e.fillText(`N: ${this.graph._nodes.length} [${this.visible_nodes.length}]`,5,13*i++),e.fillText(`V: ${this.graph._version}`,5,13*i++),e.fillText(`FPS:${this.fps.toFixed(2)}`,5,13*i++)):e.fillText(`No graph selected`,5,13*i++),this.info_text&&e.fillText(this.info_text,5,13*i++),e.restore()}drawBackCanvas(){let e=this.bgcanvas;(e.width!=this.canvas.width||e.height!=this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height),this.bgctx||=this.bgcanvas.getContext(`2d`);let t=this.bgctx;if(!t)throw TypeError(`Background canvas context was null.`);let n=this.viewport||[0,0,t.canvas.width,t.canvas.height];this.clear_background&&t.clearRect(n[0],n[1],n[2],n[3]);let r=this.onRenderBackground?this.onRenderBackground(e,t):!1;if(!this.viewport){let e=window.devicePixelRatio;t.restore(),t.setTransform(e,0,0,e,0,0)}if(this.graph){if(t.save(),this.ds.toCanvasContext(t),this.ds.scale<1.5&&!r&&this.clear_background_color&&(t.fillStyle=this.clear_background_color,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3])),this.background_image&&this.ds.scale>.5&&!r){this.zoom_modify_alpha?t.globalAlpha=(1-.5/this.ds.scale)*this.editor_alpha:t.globalAlpha=this.editor_alpha,t.imageSmoothingEnabled=!1,(!this._bg_img||this._bg_img.name!=this.background_image)&&(this._bg_img=new Image,this._bg_img.name=this.background_image,this._bg_img.src=this.background_image,this._bg_img.addEventListener(`load`,()=>{this.draw(!0,!0)}));let e=this._pattern;e==null&&this._bg_img.width>0&&(e=t.createPattern(this._bg_img,`repeat`)??void 0,this._pattern_img=this._bg_img,this._pattern=e),e&&(t.fillStyle=e,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle=`transparent`),t.globalAlpha=1,t.imageSmoothingEnabled=!0}this.bg_tint&&(t.fillStyle=this.bg_tint,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle=`transparent`),this.graph._groups.length&&this.drawGroups(e,t),this.onDrawBackground?.(t,this.visible_area),this.render_canvas_border&&(t.strokeStyle=`#235`,t.strokeRect(0,0,e.width,e.height)),this.render_connections_shadows?(t.shadowColor=`#000`,t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=6):t.shadowColor=`rgba(0,0,0,0)`,this.drawConnections(t),t.shadowColor=`rgba(0,0,0,0)`,t.restore(
2)}this.dirty_bgcanvas=!1,this.dirty_canvas=!0}drawNode(e,t){if(this.current_node=e,Q.vueNodesMode){e._setConcreteSlots(),e.collapsed||e.arrange();return}let n=e.renderingColor,r=e.renderingBgColor;if(t.globalAlpha=this.getNodeModeAlpha(e),this.render_shadows&&!this.low_quality?(t.shadowColor=Q.DEFAULT_SHADOW_COLOR,t.shadowOffsetX=2*this.ds.scale,t.shadowOffsetY=2*this.ds.scale,t.shadowBlur=3*this.ds.scale):t.shadowColor=`transparent`,e.flags.collapsed&&e.onDrawCollapsed?.(t,this)==1)return;let i=e._shape||P.BOX,a=mt;if(a[0]=e.renderingSize[0],a[1]=e.renderingSize[1],e.collapsed&&(t.font=this.inner_text_font),e.clip_area&&(t.save(),t.beginPath(),i==P.BOX?t.rect(0,0,a[0],a[1]):i==P.ROUND?t.roundRect(0,0,a[0],a[1],[10]):i==P.CIRCLE&&t.arc(a[0]*.5,a[1]*.5,a[0]*.5,0,Math.PI*2),t.clip()),this.drawNodeShape(e,t,a,n,r,!!e.selected),e.title_buttons&&!e.flags.collapsed){let n=Q.NODE_TITLE_HEIGHT,r=a[0];for(let i=0;i<e.title_buttons.length;i++){let a=e.title_buttons[i];if(!a.visible)continue;let o=a.getWidth(t);r-=o;let s=-n+(n-a.height)/2;a.draw(t,r,s),r-=2}}this.low_quality||e.drawBadges(t),t.shadowColor=`transparent`,t.strokeStyle=Q.NODE_BOX_OUTLINE_COLOR,e.onDrawForeground?.(t,this,this.canvas),t.font=this.inner_text_font,e._setConcreteSlots(),e.collapsed?this.render_collapsed_slots&&e.drawCollapsedSlots(t):(e.arrange(),e.drawSlots(t,{fromSlot:this.linkConnector.renderLinks[0]?.fromSlot,colorContext:this.colourGetter,editorAlpha:this.editor_alpha,lowQuality:this.low_quality}),t.textAlign=`left`,t.globalAlpha=1,this.drawNodeWidgets(e,null,t)),e.clip_area&&t.restore(),t.globalAlpha=1}drawLinkTooltip(e,t){let n=t._pos;if(e.fillStyle=`black`,e.beginPath(),this.linkMarkerShape===R.Arrow){let r=e.getTransform();e.translate(n[0],n[1]),Number.isFinite(t._centreAngle)&&e.rotate(t._centreAngle),e.moveTo(-2,-3),e.lineTo(4,0),e.lineTo(-2,3),e.setTransform(r)}else (this.linkMarkerShape==null||this.linkMarkerShape===R.Circle)&&e.arc(n[0],n[1],3,0,Math.PI*2);e.fill();let{data:r}=t;if(r==null||this.onDrawLinkTooltip?.(e,t,this)==1)return;let i=null;if(i=typeof r==`number`?r.toFixed(2):typeof r==`string`?`"${r}"`:typeof r==`boolean`?String(r):r.toToolTip?r.toToolTip():`[${r.constructor.name}]`,i==null)return;i=i.substring(0,30),e.font=`14px Courier New`;let a=cachedMeasureText(e,i)+20;e.shadowColor=`black`,e.shadowOffsetX=2,e.shadowOffsetY=2,e.shadowBlur=3,e.fillStyle=`#454`,e.beginPath(),e.roundRect(n[0]-a*.5,n[1]-15-24,a,24,[3]),e.moveTo(n[0]-10,n[1]-15),e.lineTo(n[0]+10,n[1]-15),e.lineTo(n[0],n[1]-5),e.fill(),e.shadowColor=`transparent`,e.textAlign=`center`,e.fillStyle=`#CEC`,e.fillText(i,n[0],n[1]-15-24*.3)}drawNodeShape(e,t,n,r,i,a){t.strokeStyle=r,t.fillStyle=i;let o=Q.NODE_TITLE_HEIGHT,{low_quality:s}=this,{collapsed:c}=e.flags,l=e.renderingShape,{title_mode:u}=e,d=!(u==z.TRANSPARENT_TITLE||u==z.NO_TITLE),f=ht;f.set(e.boundingRect),f[0]-=e.pos[0],f[1]-=e.pos[1];let p=t.globalAlpha;t.beginPath(),l==P.BOX||s?t.rect(f[0],f[1],f[2],f[3]):l==P.ROUND||l==P.CARD?t.roundRect(f[0],f[1],f[2],f[3],l==P.CARD?[Q.ROUND_RADIUS,Q.ROUND_RADIUS,0,0]:[Q.ROUND_RADIUS]):l==P.CIRCLE&&t.arc(n[0]*.5,n[1]*.5,n[0]*.5,0,Math.PI*2),t.fill(),!c&&d&&(t.shadowColor=`transparent`,t.fillStyle=`rgba(0,0,0,0.2)`,t.fillRect(0,-1,f[2],2)),t.shadowColor=`transparent`,e.onDrawBackground?.(t),(d||u==z.TRANSPARENT_TITLE)&&(e.drawTitleBarBackground(t,{scale:this.ds.scale,low_quality:s}),e.drawTitleBox(t,{scale:this.ds.scale,low_quality:s,box_size:10}),t.globalAlpha=p,e.drawTitleText(t,{scale:this.ds.scale,default_title_color:this.node_title_color,low_quality:s}),e.onDrawTitle?.(t));for(let n of Object.values(e.strokeStyles)){let r=n.call(e);r&&strokeShape(t,f,{shape:l,title_height:o,title_mode:u,collapsed:c,...r})}e.drawProgressBar(t),e.execute_triggered!=null&&e.execute_triggered>0&&e.execute_triggered--,e.action_triggered!=null&&e.action_triggered>0&&e.action_triggered--}drawSnapGuide(e,t,n=P.ROUND,{offsetToSlot:r}={}){let i=pt;i.set(t.boundingRect);let{pos:a}=t,o=a[0]-i[0],s=a[1]-i[1]-(r?Q.NODE_SLOT_HEIGHT*.7:0);i[0]+=o,i[1]+=s,this._snapToGrid&&snapPoint(i,this._snapToGrid),i[0]-=o,i[1]-=s;let{globalAlpha:c}=e;e.globalAlpha=1,e.beginPath();let[l,u,d,f]=i;if(n===P.CIRCLE){let t=l+d*.5,n=u+f*.5,r=Math.min(d*.5,f*.5);e.arc(t,n,r,0,Math.PI*2)}else e.rect(l,u,d,f);e.lineWidth=.5,e.strokeStyle=`#FFFFFF66`,e.fillStyle=`#FFFFFF22`,e.fill(),e.stroke(),e.globalAlpha=c}drawConnections(e){if(this.renderedPaths.clear(),this.links_render_mode===L.HIDDEN_LINK)return;if(Q.vueNodesMode&&U.pendingSlotSync){this._visibleReroutes.clear();return}let{graph:t,subgraph:n}=this;if(!t)throw new NullGraphError;let r=[],i=Q.getTime(),{visible_area:a}=this;gt[0]=a[0]-20,gt[1]=a[1]-20,gt[2]=a[2]+40,gt[3]=a[3]+40,e.lineWidth=this.connections_width,e.fillStyle=`#AAA`,e.strokeStyle=`#AAA`,e.globalAlpha=this.editor_alpha;let o=t._nodes;
2for(let e of o)e.flags.collapsed||!e._widgetSlotsDirty||(e._setConcreteSlots(),e.arrange());for(let n of o){let{inputs:a}=n;if(a?.length)for(let[o,s]of a.entries()){if(!s||s.link==null)continue;let a=s.link,c=t._links.get(a);if(!c)continue;let l=Q.vueNodesMode?getSlotPosition(n,o,!0):n.getInputPos(o),u=t.getNodeById(c.origin_id);if(u==null)continue;let d=c.origin_slot,f=d===-1?[u.pos[0]+10,u.pos[1]+10]:Q.vueNodesMode?getSlotPosition(u,d,!1):u.getOutputPos(d),p=u.outputs[d];p&&this._renderAllLinkSegments(e,c,f,l,r,i,p.dir,s.dir)}}if(n){for(let a of n.inputNode.slots)if(a.linkIds.length)for(let n of a.linkIds){let o=K.resolve(n,t);if(!o)continue;let{link:s,inputNode:c,input:l}=o;if(!c||!l)continue;let u=Q.vueNodesMode?getSlotPosition(c,s.target_slot,!0):c.getInputPos(s.target_slot);this._renderAllLinkSegments(e,s,a.pos,u,r,i,l.dir,l.dir)}for(let a of n.outputNode.slots){if(!a.linkIds.length)continue;let n=K.resolve(a.linkIds[0],t);if(!n)continue;let{link:o,outputNode:s,output:c}=n;if(!s||!c)continue;let l=Q.vueNodesMode?getSlotPosition(s,o.origin_slot,!1):s.getOutputPos(o.origin_slot);this._renderAllLinkSegments(e,o,l,a.pos,r,i,c.dir,a.dir)}}t.floatingLinks.size>0&&this._renderFloatingLinks(e,t,r,i);let s=this._visibleReroutes;s.clear(),r.sort((e,t)=>e.linkIds.size-t.linkIds.size);for(let t of r)s.add(t),this._snapToGrid&&this.isDragging&&this.selectedItems.has(t)&&this.drawSnapGuide(e,t,P.CIRCLE,{offsetToSlot:!0}),t.draw(e,this._pattern),this.pointer.isDown||t.drawSlots(e);let c=this._getHighlightPosition();this.linkConnector.renderLinks.filter(e=>e instanceof MovingInputLink).forEach(t=>t.drawConnectionCircle(e,c)),e.globalAlpha=1}getNodeModeAlpha(e){return e.flags.ghost?.3:e.mode===B.BYPASS?.2:e.mode===B.NEVER?.4:this.editor_alpha}_renderFloatingLinks(e,t,n,r){let{globalAlpha:i}=e;e.globalAlpha=i*.33;for(let i of t.floatingLinks.values()){let a=K.getReroutes(t,i),o=a[0],s=a.at(-1);if(!(!o||!s?.floating))if(s.floating.slotType===`input`){let a=t.getNodeById(i.target_id);if(!a)continue;let s=o.pos,c=Q.vueNodesMode?getSlotPosition(a,i.target_slot,!0):a.getInputPos(i.target_slot),l=a.inputs[i.target_slot]?.dir;o._dragging=!0,this._renderAllLinkSegments(e,i,s,c,n,r,I.CENTER,l,!0)}else{let a=t.getNodeById(i.origin_id);if(!a)continue;let o=Q.vueNodesMode?getSlotPosition(a,i.origin_slot,!1):a.getOutputPos(i.origin_slot),c=s.pos,l=a.outputs[i.origin_slot]?.dir;i._dragging=!0,this._renderAllLinkSegments(e,i,o,c,n,r,l,I.CENTER,!0)}}e.globalAlpha=i}_renderAllLinkSegments(e,t,n,r,i,a,o,s,c=!1){let{graph:l,renderedPaths:u}=this;if(!l)return;let d=K.getReroutes(l,t),f=[n,...d.map(e=>e.pos),r],p=f.map(e=>e[0]),m=f.map(e=>e[1]);if(_t[0]=Math.min(...p),_t[1]=Math.min(...m),_t[2]=Math.max(...p)-_t[0],_t[3]=Math.max(...m)-_t[1],!overlapBounding(_t,gt))return;let h=o||I.RIGHT,g=s||I.LEFT;if(d.length){let a,o=d.length;for(let s=0;s<o;s++){let o=d[s];if(!u.has(o)){u.add(o),i.push(o),o._colour=t.color||LGraphCanvas.link_type_colors[t.type]||this.default_link_color;let r=l.getReroute(o.parentId)?.pos??n;o.calculateAngle(this.last_draw_time,l,r),o._dragging||this.renderLink(e,r,o.pos,t,!1,0,null,a===void 0?h:I.CENTER,I.CENTER,{startControl:a,endControl:o.controlPoint,reroute:o,disabled:c})}if(!a&&d.at(-1)?.floating?.slotType===`input`)a=[0,0];else{let e=d[s+1]?.pos??r,t=Math.min(q.maxSplineOffset,distance(o.pos,e)*.25);a=[t*o.cos,t*o.sin]}}if(t._dragging)return;let s=f.at(-2)??n;this.renderLink(e,s,r,t,!1,0,null,I.CENTER,g,{startControl:a,disabled:c})}else t._dragging||this.renderLink(e,n,r,t,!1,0,null,h,g);if(u.add(t),t?._last_time&&a-t._last_time<1e3){let i=2-(a-t._last_time)*.002,o=e.globalAlpha;e.globalAlpha=o*i,this.renderLink(e,n,r,t,!0,i,`white`,h,g),e.globalAlpha=o}}buildLinkRenderContext(){return{renderMode:this.links_render_mode,connectionWidth:this.connections_width,renderBorder:this.render_connections_border,lowQuality:this.low_quality,highQualityRender:this.highquality_render,scale:this.ds.scale,linkMarkerShape:this.linkMarkerShape,renderConnectionArrows:this.render_connection_arrows,highlightedLinks:new Set(Object.keys(this.highlighted_links)),defaultLinkColor:this.default_link_color,linkTypeColors:LGraphCanvas.link_type_colors,disabledPattern:this._pattern}}renderLink(e,t,n,r,i,a,o,s,c,{startControl:l,endControl:u,reroute:d,num_sublines:f=1,disabled:p=!1}={}){if(this.linkRenderer){let m=this.buildLinkRenderContext();this.linkRenderer.renderLinkDirect(e,t,n,r,i,a,o,s,c,m,{reroute:d,startControl:l,endControl:u,num_sublines:f,disabled:p})}}drawExecutionOrder(e){e.shadowColor=`transparent`,e.globalAlpha=.25,e.textAlign=`center`,e.
2strokeStyle=`white`,e.globalAlpha=.75;let{visible_nodes:t}=this;for(let n of t)e.fillStyle=`black`,e.fillRect(n.pos[0]-Q.NODE_TITLE_HEIGHT,n.pos[1]-Q.NODE_TITLE_HEIGHT,Q.NODE_TITLE_HEIGHT,Q.NODE_TITLE_HEIGHT),n.order==0&&e.strokeRect(n.pos[0]-Q.NODE_TITLE_HEIGHT+.5,n.pos[1]-Q.NODE_TITLE_HEIGHT+.5,Q.NODE_TITLE_HEIGHT,Q.NODE_TITLE_HEIGHT),e.fillStyle=`#FFF`,e.fillText(p(n.order),n.pos[0]+Q.NODE_TITLE_HEIGHT*-.5,n.pos[1]-6);e.globalAlpha=1}drawNodeWidgets(e,t,n){e.drawWidgets(n,{lowQuality:this.low_quality,editorAlpha:this.getNodeModeAlpha(e)})}drawGroups(e,t){if(!this.graph)return;let n=this.graph._groups;t.save(),t.globalAlpha=.5*this.editor_alpha;let r=this._snapToGrid&&(this.isDragging||U.isDraggingVueNodes.value);for(let e of n)overlapBounding(this.visible_area,e._bounding)&&(r&&this.selectedItems.has(e)&&this.drawSnapGuide(t,e),e.draw(this,t));t.restore()}resize(e,t){if(!e&&!t){let n=this.canvas.parentElement;if(!n)throw TypeError(`Attempted to resize canvas, but parent element was null.`);e=n.offsetWidth,t=n.offsetHeight}this.canvas.width==e&&this.canvas.height==t||(this.canvas.width=e??0,this.canvas.height=t??0,this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height,this.setDirty(!0,!0))}onNodeSelectionChange(){}boundaryNodesForSelection(){return LGraphCanvas.getBoundaryNodes(this.selected_nodes)}showLinkMenu(e,t){let{graph:n}=this;if(!n)throw new NullGraphError;let r=`data`in e&&e.data!=null?e.data.constructor.name:void 0,{origin_id:i,origin_slot:a}=e;if(i==null||a==null)return new Q.ContextMenu([`Link has no origin`],{event:t,title:r}),!1;let o=n.getNodeById(i),s=o?.outputs?.[a]?.type,c=new Q.ContextMenu([`Add Node`,`Add Reroute`,null,`Delete`,null],{event:t,title:r,callback:inner_clicked.bind(this)});return!1;function inner_clicked(t,r,i){if(!n)throw new NullGraphError;switch(t){case`Add Node`:LGraphCanvas.onMenuAdd(null,null,i,c,t=>{if(!t?.inputs?.length||!t?.outputs?.length||a==null)return;let n={afterRerouteId:e.parentId};o?.connectByType(a,t,s??`*`,n)&&t.setPos(t.pos[0]-t.size[0]*.5,t.pos[1])});break;case`Add Reroute`:try{this.emitBeforeChange(),this.adjustMouseEvent(i),n.createReroute(e._pos,e),this.setDirty(!1,!0)}catch(e){console.error(e)}finally{this.emitAfterChange()}break;case`Delete`:{let t=e instanceof q?e.linkIds.values().next().value:e.id;t!==void 0&&(n.removeLink(t),U.deleteLinkLayout(t));break}default:}}}createDefaultNodeForSlot(e){let t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,position:[0,0],nodeType:void 0,posAdd:[0,0],posSizeFix:[0,0]},e),{afterRerouteId:n}=t,r=t.nodeFrom&&t.slotFrom!==null,i=!r&&t.nodeTo&&t.slotTo!==null;if(!r&&!i)return console.warn(`No data passed to createDefaultNodeForSlot`,t.nodeFrom,t.slotFrom,t.nodeTo,t.slotTo),!1;if(!t.nodeType)return console.warn(`No type to createDefaultNodeForSlot`),!1;let a=r?t.nodeFrom:t.nodeTo;if(!a)throw TypeError(`nodeX was null when creating default node for slot.`);let o=r?t.slotFrom:t.slotTo,s=!1;if(a instanceof Qe){if(typeof o!=`object`||!o)return console.warn(`Cant get slot information`,o),!1;let{name:e}=o;if(s=a.slots.findIndex(t=>t.name===e),o=a.slots[s],!o)return console.warn(`Cant get slot information`,o),!1}else switch(typeof o){case`string`:s=r?a.findOutputSlot(o,!1):a.findInputSlot(o,!1),o=r?a.outputs[o]:a.inputs[o];break;case`object`:if(o===null)return console.warn(`Cant get slot information`,o),!1;s=r?a.findOutputSlot(o.name):a.findInputSlot(o.name);break;case`number`:s=o,o=r?a.outputs[o]:a.inputs[o];break;default:return console.warn(`Cant get slot information`,o),!1}let c=o.type==Q.EVENT?`_event_`:o.type,l=r?Q.slot_types_default_out:Q.slot_types_default_in;if(l?.[c]){let e=!1;if(typeof l[c]==`object`){for(let n in l[c])if(t.nodeType==l[c][n]||t.nodeType==`AUTO`){e=l[c][n];break}}else (t.nodeType==l[c]||t.nodeType==`AUTO`)&&(e=l[c]);if(e){let i,a;typeof e==`object`?(i=e,a=i.node??``):a=e;let o=t.posSizeFix[0]*Q.NODE_WIDTH,l=t.posSizeFix[1]*Q.NODE_SLOT_HEIGHT,u=[t.position[0]+t.posAdd[0]+o,t.position[1]+t.posAdd[1]+l],d=Q.createNode(a,i?.title,{pos:u});if(d){if(i){if(i.properties)for(let e in i.properties)d.addProperty(e,i.properties[e]);if(i.inputs){d.inputs=[];for(let e of i.inputs)d.addInput(e[0],e[1])}if(i.outputs){d.outputs=[];
2for(let e of i.outputs)d.addOutput(e[0],e[1])}i.json&&d.configure(i.json)}if(!this.graph)throw new NullGraphError;this.graph.add(d);let e={node:d,opts:t};if(!this.canvas.dispatchEvent(new CustomEvent(`connect-new-default-node`,{detail:e,cancelable:!0})))return!0;if(r){if(!t.nodeFrom)throw TypeError(`createDefaultNodeForSlot - nodeFrom was null`);t.nodeFrom.connectByType(s,d,c,{afterRerouteId:n})}else{if(!t.nodeTo)throw TypeError(`createDefaultNodeForSlot - nodeTo was null`);t.nodeTo.connectByTypeOutput(s,d,c,{afterRerouteId:n})}return!0}console.error(`failed creating ${e}`)}}return!1}showConnectionMenu(e){let t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,e:void 0,allow_searchbox:this.allow_searchbox,showSearchBox:this.showSearchBox},e||{}),dirty=()=>this._dirty(),n=this,{graph:r}=this,{afterRerouteId:i}=t,a=t.nodeFrom&&t.slotFrom,o=!a&&t.nodeTo&&t.slotTo;if(!a&&!o){console.warn(`No data passed to showConnectionMenu`);return}let s=a?t.nodeFrom:t.nodeTo;if(!s)throw TypeError(`nodeX was null when creating default node for slot.`);let c=a?t.slotFrom:t.slotTo,l;if(s instanceof Qe){if(typeof c!=`object`||!c){console.warn(`Cant get slot information`,c);return}let{name:e}=c;if(l=s.slots.findIndex(t=>t.name===e),l!==-1&&(c=s.slots[l]),!c){console.warn(`Cant get slot information`,c);return}}else switch(typeof c){case`string`:l=a?s.findOutputSlot(c,!1):s.findInputSlot(c,!1),c=a?s.outputs[c]:s.inputs[c];break;case`object`:if(c===null){console.warn(`Cant get slot information`,c);return}l=a?s.findOutputSlot(c.name):s.findInputSlot(c.name);break;case`number`:l=c,c=a?s.outputs[c]:s.inputs[c];break;default:console.warn(`Cant get slot information`,c);return}let u=[`Add Node`,`Add Reroute`,null];t.allow_searchbox&&u.push(`Search`,null);let d=c.type==Q.EVENT?`_event_`:c.type,f=a?Q.slot_types_default_out:Q.slot_types_default_in;if(f?.[d])if(typeof f[d]==`object`)for(let e in f[d])u.push(f[d][e]);else u.push(f[d]);let p=new Q.ContextMenu(u,{event:t.e,extra:c,title:(c&&c.name!=``?c.name+(d?` | `:``):``)+(c&&d?d:``),callback:inner_clicked});return p;function inner_clicked(e,o,s){switch(e){case`Add Node`:LGraphCanvas.onMenuAdd(null,null,s,p,function(e){if(e)if(a){if(!t.nodeFrom)throw TypeError(`Cannot add node to SubgraphInputNode: nodeFrom was null`);t.nodeFrom.connectByType(l,e,d,{afterRerouteId:i})||console.warn(`Failed to make new connection.`)}else{if(!t.nodeTo)throw TypeError(`Cannot add node to SubgraphInputNode: nodeTo was null`);t.nodeTo.connectByTypeOutput(l,e,d,{afterRerouteId:i})}});break;case`Add Reroute`:{let e=a?t.nodeFrom:t.nodeTo,n=o.extra;if(!r)throw new NullGraphError;if(!e)throw TypeError(`Cannot add reroute: node was null`);if(!n)throw TypeError(`Cannot add reroute: slot was null`);if(!t.e)throw TypeError(`Cannot add reroute: CanvasPointerEvent was null`);if(e instanceof Qe)throw TypeError(`Cannot add floating reroute to Subgraph IO Nodes`);if(!e.connectFloatingReroute([t.e.canvasX,t.e.canvasY],n,i))throw Error(`Failed to create reroute`);dirty();break}case`Search`:a?t.showSearchBox(s,{node_from:t.nodeFrom,slot_from:c,type_filter_in:d}):t.showSearchBox(s,{node_to:t.nodeTo,slot_from:c,type_filter_out:d});break;default:{let r={position:[t.e?.canvasX??0,t.e?.canvasY??0],nodeType:e,afterRerouteId:i},a=Object.assign(t,r);if(!n.createDefaultNodeForSlot(a))break}}}}prompt(e,t,n,r,i){let a=this;e||=``;let o={is_modified:!1,className:`graphdialog rounded`,innerHTML:i?`<span class='name'></span> <textarea autofocus class='value'></textarea><button class='rounded'>OK</button>`:`<span class='name'></span> <input autofocus type='text' class='value'/><button class='rounded'>OK</button>`,close(){a.prompt_box=null,c.parentNode&&c.remove()}},s=document.createElement(`div`),c=Object.assign(s,o),{canvas:l}=LGraphCanvas.active_canvas;if(!l.parentNode)throw TypeError(`canvas element parentNode was null when opening a prompt.`);l.parentNode.append(c),this.ds.scale>1&&(c.style.transform=`scale(${this.ds.scale})`);let u,d=0;Q.pointerListenerAdd(c,`leave`,function(){d||Q.dialog_close_on_mouse_leave&&!c.is_modified&&Q.dialog_close_on_mouse_leave&&(u=setTimeout(c.close,Q.dialog_close_on_mouse_leave_delay))}),Q.pointerListenerAdd(c,`enter`,function(){Q.dialog_close_on_mouse_leave&&u&&clearTimeout(u)});let f=c.querySelectorAll(`select`);if(f)for(let e of f)e.addEventListener(`click`,function(){d++}),e.addEventListener(`blur`,function(){d=0}),e.addEventListener(`change`,function(){d=-1});this.prompt_box?.close(),this.prompt_box=c;let p=c.querySelector(`.name`);if(!p)throw TypeError(`name_element was null`);p.textContent=e;let m=c.querySelector(`.value`);if(!m)throw TypeError(`value_element was null`);m.value=String(t),m.select();let h=m;
2h.addEventListener(`keydown`,function(e){if(c.is_modified=!0,e.key==`Escape`)c.close();else if(e.key==`Enter`&&e.target.localName!=`textarea`)n&&n(this.value),c.close();else return;e.preventDefault(),e.stopPropagation()});let g=c.querySelector(`button`);if(!g)throw TypeError(`button was null when opening prompt`);g.addEventListener(`click`,function(){n?.(h.value),a.setDirty(!0),c.close()});let _=l.getBoundingClientRect(),v=-20,y=-20;return _&&(v-=_.left,y-=_.top),r?(c.style.left=`${r.clientX+v}px`,c.style.top=`${r.clientY+y}px`):(c.style.left=`${l.width*.5+v}px`,c.style.top=`${l.height*.5+y}px`),setTimeout(function(){h.focus();let e=Date.now();function handleOutsideClick(t){t.target===l&&Date.now()-e>256&&(c.close(),l.parentElement?.removeEventListener(`click`,handleOutsideClick),l.parentElement?.removeEventListener(`touchend`,handleOutsideClick))}l.parentElement?.addEventListener(`click`,handleOutsideClick),l.parentElement?.addEventListener(`touchend`,handleOutsideClick)},10),c}showSearchBox(e,t){let n={slot_from:null,node_from:null,node_to:null,do_type_filter:Q.search_filter_enabled,type_filter_in:!1,type_filter_out:!1,show_general_if_none_on_typefilter:!0,show_general_after_typefiltered:!0,hide_on_mouse_leave:Q.search_hide_on_mouse_leave,show_all_if_empty:!0,show_all_on_open:Q.search_show_all_on_open};Object.assign(n,t);let r=this,i=LGraphCanvas.active_canvas,{canvas:a}=i,o=a.ownerDocument||document,s=document.createElement(`div`),c=Object.assign(s,{close(){r.search_box=void 0,this.blur(),a.focus(),o.body.style.overflow=``,setTimeout(()=>a.focus(),20),c.remove()}});c.className=`litegraph litesearchbox graphdialog rounded`,c.innerHTML=`<span class='name'>Search</span> <input autofocus type='text' class='value rounded'/>`,n.do_type_filter&&(c.innerHTML+=`<select class='slot_in_type_filter'><option value=''></option></select>`,c.innerHTML+=`<select class='slot_out_type_filter'><option value=''></option></select>`);
2let l=document.createElement(`div`);l.className=`helper`,c.append(l),o.fullscreenElement?o.fullscreenElement.append(c):(o.body.append(c),o.body.style.overflow=`hidden`);let u,d;if(n.do_type_filter&&(u=c.querySelector(`.slot_in_type_filter`),d=c.querySelector(`.slot_out_type_filter`)),this.ds.scale>1&&(c.style.transform=`scale(${this.ds.scale})`),n.hide_on_mouse_leave){let e=0,t=null;if(Q.pointerListenerAdd(c,`enter`,function(){t&&=(clearTimeout(t),null)}),c.addEventListener(`pointerleave`,function(){if(e)return;let r=n.hide_on_mouse_leave,i=typeof r==`number`?r:500;t=setTimeout(c.close,i)}),n.do_type_filter){if(!u)throw TypeError(`selIn was null when showing search box`);if(!d)throw TypeError(`selOut was null when showing search box`);u.addEventListener(`click`,function(){e++}),u.addEventListener(`blur`,function(){e=0}),u.addEventListener(`change`,function(){e=-1}),d.addEventListener(`click`,function(){e++}),d.addEventListener(`blur`,function(){e=0}),d.addEventListener(`change`,function(){e=-1})}}r.search_box?.close(),r.search_box=c;let f=null,p=null,m=null,h=c.querySelector(`input`);if(!h)throw TypeError(`Could not create search input box.`);let g=h;if(g&&(g.addEventListener(`blur`,function(){this.focus()}),g.addEventListener(`keydown`,function(e){if(e.key==`ArrowUp`)changeSelection(!1);else if(e.key==`ArrowDown`)changeSelection(!0);else if(e.key==`Escape`)c.close();else if(e.key==`Enter`)m instanceof HTMLElement?select(unescape(String(m.dataset.type))):f?select(f):c.close();else{p&&clearInterval(p),p=setTimeout(refreshHelper,10);return}return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),!0})),n.do_type_filter){if(u){let e=Q.slot_types_in,t=e.length;(n.type_filter_in==Q.EVENT||n.type_filter_in==Q.ACTION)&&(n.type_filter_in=`_event_`);for(let r=0;r<t;r++){let t=document.createElement(`option`);t.value=e[r],t.innerHTML=e[r],u.append(t),n.type_filter_in!==!1&&String(n.type_filter_in).toLowerCase()==String(e[r]).toLowerCase()&&(t.selected=!0)}u.addEventListener(`change`,function(){refreshHelper()})}if(d){let e=Q.slot_types_out;(n.type_filter_out==Q.EVENT||n.type_filter_out==Q.ACTION)&&(n.type_filter_out=`_event_`);for(let t of e){let e=document.createElement(`option`);e.value=t,e.innerHTML=t,d.append(e),n.type_filter_out!==!1&&String(n.type_filter_out).toLowerCase()==String(t).toLowerCase()&&(e.selected=!0)}d.addEventListener(`change`,function(){refreshHelper()})}}let _=a.getBoundingClientRect(),v=e??new MouseEvent(`click`,{clientX:_.left+_.width*.5,clientY:_.top+_.height*.5,layerY:_.top+_.height*.5}),y=v.clientX-80,ee=v.clientY-20;c.style.left=`${y}px`,c.style.top=`${ee}px`,v.layerY>_.height-200&&(l.style.maxHeight=`${_.height-v.layerY-20}px`),requestAnimationFrame(function(){g.focus()}),n.show_all_on_open&&refreshHelper();function select(e){if(e)if(r.onSearchBoxSelection)r.onSearchBoxSelection(e,v,i);else{if(!i.graph)throw new NullGraphError;i.graph.beforeChange();let t=Q.createNode(e);if(t&&(t.pos=i.convertEventToCanvasOffset(v),i.graph.add(t,!1)),n.node_from){let e=!1;switch(typeof n.slot_from){case`string`:e=n.node_from.findOutputSlot(n.slot_from);break;case`object`:if(n.slot_from==null)throw TypeError(`options.slot_from was null when showing search box`);e=n.slot_from.name?n.node_from.findOutputSlot(n.slot_from.name):-1,e==-1&&n.slot_from.slot_index!==void 0&&(e=n.slot_from.slot_index);break;case`number`:e=n.slot_from;break;default:e=0}if(e!==!1&&n.node_from.outputs[e]!==void 0&&e>-1){if(t==null)throw TypeError(`options.slot_from was null when showing search box`);n.node_from.connectByType(e,t,n.node_from.outputs[e].type)}}if(n.node_to){let e=!1;switch(typeof n.slot_from){case`string`:e=n.node_to.findInputSlot(n.slot_from);break;case`object`:if(n.slot_from==null)throw TypeError(`options.slot_from was null when showing search box`);e=n.slot_from.name?n.node_to.findInputSlot(n.slot_from.name):-1,e==-1&&n.slot_from.slot_index!==void 0&&(e=n.slot_from.slot_index);break;case`number`:e=n.slot_from;break;default:e=0}if(e!==!1&&n.node_to.inputs[e]!==void 0&&e>-1){if(t==null)throw TypeError(`options.slot_from was null when showing search box`);
2n.node_to.connectByTypeOutput(e,t,n.node_to.inputs[e].type)}}i.graph.afterChange()}c.close()}function changeSelection(e){let t=m;m?m instanceof Element&&(m.classList.remove(`selected`),m=e?m.nextSibling:m.previousSibling,m||=t):m=e?l.childNodes[0]:l.childNodes[l.childNodes.length],m instanceof Element&&(m.classList.add(`selected`),m.scrollIntoView({block:`end`,behavior:`smooth`}))}function refreshHelper(){p=null;let e=g.value;if(f=null,l.innerHTML=``,!e&&!n.show_all_if_empty)return;if(r.onSearchBox){let t=r.onSearchBox(l,e,i);if(t)for(let e of t)addResult(e)}else{let t=0;if(e=e.toLowerCase(),!i.graph)throw new NullGraphError;let a=i.filter||i.graph.filter,o=null,s=null;n.do_type_filter&&r.search_box&&(o=r.search_box.querySelector(`.slot_in_type_filter`),s=r.search_box.querySelector(`.slot_out_type_filter`));let c=Object.keys(Q.registered_node_types).filter(e=>inner_test_filter(e));for(let e of c)if(addResult(e),LGraphCanvas.search_limit!==-1&&t++>LGraphCanvas.search_limit)break;if(n.show_general_after_typefiltered&&(o?.value||s?.value)){let e=[];for(let t in Q.registered_node_types)inner_test_filter(t,{inTypeOverride:o&&o.value?`*`:!1,outTypeOverride:s&&s.value?`*`:!1})&&e.push(t);for(let n of e)if(addResult(n,`generic_type`),LGraphCanvas.search_limit!==-1&&t++>LGraphCanvas.search_limit)break}if((o?.value||s?.value)&&l.childNodes.length==0&&n.show_general_if_none_on_typefilter){let e=[];for(let t in Q.registered_node_types)inner_test_filter(t,{skipFilter:!0})&&e.push(t);for(let n of e)if(addResult(n,`not_in_filter`),LGraphCanvas.search_limit!==-1&&t++>LGraphCanvas.search_limit)break}function inner_test_filter(t,r){r||={};let i=Object.assign({skipFilter:!1,inTypeOverride:!1,outTypeOverride:!1},r),c=Q.registered_node_types[t];if(a&&c.filter!=a||(!n.show_all_if_empty||e)&&!t.toLowerCase().includes(e)&&(!c.title||!c.title.toLowerCase().includes(e)))return!1;if(n.do_type_filter&&!i.skipFilter){let e=t,n=typeof i.inTypeOverride==`string`?i.inTypeOverride:o?.value;if(o&&n&&Q.registered_slot_in_types[n]?.nodes&&Q.registered_slot_in_types[n].nodes.includes(e)===!1||(n=s?.value,typeof i.outTypeOverride==`string`&&(n=i.outTypeOverride),s&&n&&Q.registered_slot_out_types[n]?.nodes&&Q.registered_slot_out_types[n].nodes.includes(e)===!1))return!1}return!0}}function addResult(e,t){let n=document.createElement(`div`);f||=e;let r=Q.registered_node_types[e];if(r?.title){n.textContent=r?.title;let t=document.createElement(`span`);t.className=`litegraph lite-search-item-type`,t.textContent=e,n.append(t)}else n.textContent=e;n.dataset.type=escape(e),n.className=`litegraph lite-search-item`,t&&(n.className+=` ${t}`),n.addEventListener(`click`,function(){select(unescape(String(this.dataset.type)))}),l.append(n)}}return c}showEditPropertyValue(e,t,n){if(!e||e.properties[t]===void 0)return;n||={};let r=e.getPropertyInfo(t),{type:i}=r,a=``;
2if(i==`string`||i==`number`||i==`array`||i==`object`)a=`<input autofocus type='text' class='value'/>`;else if((i==`enum`||i==`combo`)&&r.values){a=`<select autofocus type='text' class='value'>`;for(let n in r.values){let i=Array.isArray(r.values)?r.values[n]:n,o=i==e.properties[t]?`selected`:``;a+=`<option value='${i}' ${o}>${r.values[n]}</option>`}a+=`</select>`}else if(i==`boolean`||i==`toggle`)a=`<input autofocus type='checkbox' class='value' ${e.properties[t]?`checked`:``}/>`;else{console.warn(`unknown type: ${i}`);return}let o=this.createDialog(`<span class='name'>${r.label||t}</span>${a}<button>OK</button>`,n),s;if((i==`enum`||i==`combo`)&&r.values)s=o.querySelector(`select`),s?.addEventListener(`change`,function(e){o.modified(),setValue(e.target?.value)});else if(i==`boolean`||i==`toggle`)s=o.querySelector(`input`),s?.addEventListener(`click`,function(){o.modified(),setValue(!!s.checked)});else if(s=o.querySelector(`input`),s){s.addEventListener(`blur`,function(){this.focus()});let n=e.properties[t]===void 0?``:e.properties[t];i!==`string`&&(n=JSON.stringify(n)),s.value=n,s.addEventListener(`keydown`,function(e){if(e.key==`Escape`)o.close();else if(e.key==`Enter`)inner();else{o.modified();return}e.preventDefault(),e.stopPropagation()})}s?.focus();let c=o.querySelector(`button`);if(!c)throw TypeError(`Show edit property value button was null.`);c.addEventListener(`click`,inner);function inner(){setValue(s?.value)}let dirty=()=>this._dirty();function setValue(a){r?.values&&typeof r.values==`object`&&r.values[a]!=null&&(a=r.values[a]),typeof e.properties[t]==`number`&&(a=Number(a)),(i==`array`||i==`object`)&&(a=JSON.parse(a)),e.properties[t]=a,e.graph&&e.graph.incrementVersion(),e.onPropertyChanged?.(t,a),n.onclose?.(),o.close(),dirty()}return o}createDialog(e,t){t=Object.assign({checkForInput:!1,closeOnLeave:!0,closeOnLeave_checkModified:!0},t||{});let n={className:`graphdialog`,innerHTML:e,is_modified:!1,modified(){this.is_modified=!0},close(){this.remove()}},r=document.createElement(`div`),i=Object.assign(r,n),a=this.canvas.getBoundingClientRect(),o=-20,s=-20;if(a&&(o-=a.left,s-=a.top),t.position?(o+=t.position[0],s+=t.position[1]):t.event?(o+=t.event.clientX,s+=t.event.clientY):(o+=this.canvas.width*.5,s+=this.canvas.height*.5),i.style.left=`${o}px`,i.style.top=`${s}px`,!this.canvas.parentNode)throw TypeError(`Canvas parent element was null.`);if(this.canvas.parentNode.append(i),t.checkForInput){let e=i.querySelectorAll(`input`);if(e)for(let t of e)t.addEventListener(`keydown`,function(e){if(i.modified(),e.key==`Escape`)i.close();else if(e.key!=`Enter`)return;e.preventDefault(),e.stopPropagation()}),t.focus()}let c,l=0;i.addEventListener(`mouseleave`,function(){l||!i.is_modified&&Q.dialog_close_on_mouse_leave&&(c=setTimeout(i.close,Q.dialog_close_on_mouse_leave_delay))}),i.addEventListener(`mouseenter`,function(){(t.closeOnLeave||Q.dialog_close_on_mouse_leave)&&c&&clearTimeout(c)});let u=i.querySelectorAll(`select`);if(u)for(let e of u)e.addEventListener(`click`,function(){l++}
2),e.addEventListener(`blur`,function(){l=0}),e.addEventListener(`change`,function(){l=-1});return i}createPanel(e,t){t||={};let n=document.createElement(`div`);if(n.className=`litegraph dialog`,n.innerHTML=`<div class='dialog-header'><span class='dialog-title'></span></div><div class='dialog-content'></div><div style='display:none;' class='dialog-alt-content'></div><div class='dialog-footer'></div>`,n.header=n.querySelector(`.dialog-header`),t.width&&(n.style.width=t.width+(typeof t.width==`number`?`px`:``)),t.height&&(n.style.height=t.height+(typeof t.height==`number`?`px`:``)),t.closable){let e=document.createElement(`span`);e.innerHTML=`&#10005;`,e.classList.add(`close`),e.addEventListener(`click`,function(){n.close()}),n.header.append(e)}return n.title_element=n.querySelector(`.dialog-title`),n.title_element.textContent=e,n.content=n.querySelector(`.dialog-content`),n.alt_content=n.querySelector(`.dialog-alt-content`),n.footer=n.querySelector(`.dialog-footer`),n.footer.style.marginTop=`-96px`,n.close=function(){typeof n.onClose==`function`&&n.onClose(),n.remove(),this.remove()},n.toggleAltContent=function(e){let t,r;e===void 0?(t=n.alt_content.style.display==`block`?`none`:`block`,r=n.alt_content.style.display==`block`?`block`:`none`):(t=e?`block`:`none`,r=e?`none`:`block`),n.alt_content.style.display=t,n.content.style.display=r},n.toggleFooterVisibility=function(e){let t;t=e===void 0?n.footer.style.display==`block`?`none`:`block`:e?`block`:`none`,n.footer.style.display=t},n.clear=function(){this.content.innerHTML=``},n.addHTML=function(e,t,r){let i=document.createElement(`div`);return t&&(i.className=t),i.innerHTML=e,r?n.footer.append(i):n.content.append(i),i},n.addButton=function(e,t,r){let i=document.createElement(`button`);return i.textContent=e,i.options=r,i.classList.add(`btn`),i.addEventListener(`click`,t),n.footer.append(i),i},n.addSeparator=function(){let e=document.createElement(`div`);e.className=`separator`,n.content.append(e)},n.addWidget=function(e,t,r,i,a){i||={};let o=String(r);e=e.toLowerCase(),e==`number`&&typeof r==`number`&&(o=r.toFixed(3));let s=document.createElement(`div`);s.className=`property`,s.innerHTML=`<span class='property_name'></span><span class='property_value'></span>`;let c=s.querySelector(`.property_name`);if(!c)throw TypeError(`Property name element was null.`);c.textContent=i.label||t;let l=s.querySelector(`.property_value`);if(!l)throw TypeError(`Property name element was null.`);if(l.textContent=o,s.dataset.property=t,s.dataset.type=i.type||e,s.options=i,s.value=r,e==`code`)s.addEventListener(`click`,function(){let e=this.dataset.property;e&&n.inner_showCodePad?.(e)});else if(e==`boolean`)s.classList.add(`boolean`),r&&s.classList.add(`bool-on`),s.addEventListener(`click`,()=>{let e=s.dataset.property;if(s.value=!s.value,s.classList.toggle(`bool-on`),!l)throw TypeError(`Property name element was null.`);l.textContent=s.value?`true`:`false`,innerChange(e,s.value)});else if(e==`string`||e==`number`){if(!l)throw TypeError(`Property name element was null.`);l.setAttribute(`contenteditable`,`true`),l.addEventListener(`keydown`,function(t){t.code==`Enter`&&(e!=`string`||!t.shiftKey)&&(t.preventDefault(),this.blur())}),l.addEventListener(`blur`,function(){let e=this.textContent,t=this.parentElement?.dataset.property;this.parentElement?.dataset.type==`number`&&(e=Number(e)),innerChange(t,e)})}else if(e==`enum`||e==`combo`){let e=LGraphCanvas.getPropertyPrintableValue(r,i.values);if(!l)throw TypeError(`Property name element was null.`);l.textContent=e??``,l.addEventListener(`click`,function(e){let t=i?.values||[],n=this.parentElement?.dataset.property,inner_clicked=e=>(this.textContent=e??null,innerChange(n,e),!1);new Q.ContextMenu(t,{event:e,className:`dark`,callback:inner_clicked})})}n.content.append(s);function innerChange(e,t){let n=i||{};n.callback?.(e,t,n),a?.(e,t,n)}return s},typeof n.onOpen==`function`&&n.onOpen(),n}closePanels(){document.querySelector(`#node-panel`)?.close?.(),document.querySelector(`#option-panel`)?.close?.()}showShowNodePanel(e){this.SELECTED_NODE=e,this.closePanels();let t=this.getCanvasWindow(),n=this.createPanel(e.title||``,{closable:!0,window:t,onOpen:()=>{this.NODEPANEL_IS_OPEN=!0},onClose:()=>{this.NODEPANEL_IS_OPEN=!1,this.node_panel=void 0}});this.node_panel=n,n.id=`node-panel`,n.node=e,n.classList.add(`settings`),n.style.position=`absolute`,n.style.top=`96px`,n.style.left=`65px`;let inner_refresh=()=>{n.content.innerHTML=``,n.addHTML(`<span class='node_type'>${e.type}</span><span class='node_desc'>${e.constructor.desc||``}</span><span class='separator'></span>`),n.addHTML(`<h3>Properties</h3>`);
2let fUpdate=(t,n)=>{if(!this.graph)throw new NullGraphError;if(t){switch(this.graph.beforeChange(e),t){case`Title`:if(typeof n!=`string`)throw TypeError(`Attempting to set title to non-string value.`);e.title=n;break;case`Mode`:{if(typeof n!=`string`)throw TypeError(`Attempting to set mode to non-string value.`);let t=Object.values(Q.NODE_MODES).indexOf(n);t!==-1&&Q.NODE_MODES[t]?e.changeMode(t):console.warn(`unexpected mode: ${n}`);break}case`Color`:if(typeof n!=`string`)throw TypeError(`Attempting to set colour to non-string value.`);LGraphCanvas.node_colors[n]?(e.color=LGraphCanvas.node_colors[n].color,e.bgcolor=LGraphCanvas.node_colors[n].bgcolor):console.warn(`unexpected color: ${n}`);break;default:e.setProperty(t,n);break}this.graph.afterChange(),this.dirty_canvas=!0}};n.addWidget(`string`,`Title`,e.title,{},fUpdate);let t=e.mode==null?void 0:Q.NODE_MODES[e.mode];n.addWidget(`combo`,`Mode`,t,{values:Q.NODE_MODES},fUpdate);let r=e.color===void 0?``:Object.keys(LGraphCanvas.node_colors).filter(function(t){return LGraphCanvas.node_colors[t].color==e.color});n.addWidget(`combo`,`Color`,r,{values:Object.keys(LGraphCanvas.node_colors)},fUpdate);for(let t in e.properties){let r=e.properties[t],i=e.getPropertyInfo(t);e.onAddPropertyToPanel?.(t,n)||n.addWidget(i.widget||i.type,t,r,i,fUpdate)}n.addSeparator(),e.onShowCustomPanelInfo?.(n),n.footer.innerHTML=``,n.addButton(`Delete`,function(){if(!e.block_delete){if(!e.graph)throw new NullGraphError;e.graph.remove(e),n.close()}}).classList.add(`delete`)};if(n.inner_showCodePad=function(t){n.classList.remove(`settings`),n.classList.add(`centered`),n.alt_content.innerHTML=`<textarea class='code'></textarea>`;let r=n.alt_content.querySelector(`textarea`),fDoneWith=function(){n.toggleAltContent(!1),n.toggleFooterVisibility(!0),r.remove(),n.classList.add(`settings`),n.classList.remove(`centered`),inner_refresh()};r.value=String(e.properties[t]),r.addEventListener(`keydown`,function(n){n.code==`Enter`&&n.ctrlKey&&(e.setProperty(t,r.value),fDoneWith())}),n.toggleAltContent(!0),n.toggleFooterVisibility(!1),r.style.height=`calc(100% - 40px)`;let i=n.addButton(`Assign`,function(){e.setProperty(t,r.value),fDoneWith()});n.alt_content.append(i);let a=n.addButton(`Close`,fDoneWith);a.style.float=`right`,n.alt_content.append(a)},inner_refresh(),!this.canvas.parentNode)throw TypeError(`showNodePanel - this.canvas.parentNode was null`);this.canvas.parentNode.append(n)}checkPanels(){if(!this.canvas)return;if(!this.canvas.parentNode)throw TypeError(`checkPanels - this.canvas.parentNode was null`);let e=this.canvas.parentNode.querySelectorAll(`.litegraph.dialog`);for(let t of e)t.node&&(!t.node.graph||t.graph!=this.graph)&&t.close()}getCanvasMenuOptions(){let e;this.getMenuOptions?e=this.getMenuOptions():(e=[{content:`Add Node`,has_submenu:!0,callback:LGraphCanvas.onMenuAdd},{content:`Add Group`,callback:LGraphCanvas.onGroupAdd},{content:`Paste`,callback:()=>{this.pasteFromClipboard()}}],Object.keys(this.selected_nodes).length>1&&e.push({content:`Convert to Subgraph`,callback:()=>{if(!this.selectedItems.size)throw Error(`Convert to Subgraph: Nothing selected.`);this._graph.convertToSubgraph(this.selectedItems)}},{content:`Align`,has_submenu:!0,callback:LGraphCanvas.onGroupAlign}));let t=this.getExtraMenuOptions?.(this,e);return Array.isArray(t)?e.concat(t):e}getNodeMenuOptions(e){let t;e.getMenuOptions?t=e.getMenuOptions(this):(t=[{content:`Convert to Subgraph`,callback:()=>this._graph.convertToSubgraph(this.selectedItems)},{content:`Properties`,has_submenu:!0,callback:LGraphCanvas.onShowMenuNodeProperties},{content:`Properties Panel`,callback:function(e,t,n,r,i){LGraphCanvas.active_canvas.showShowNodePanel(i)}},null,{content:`Title`,callback:LGraphCanvas.onShowPropertyEditor},{content:`Mode`,has_submenu:!0,callback:LGraphCanvas.onMenuNodeMode}],e.resizable!==!1&&t.push({content:`Resize`,callback:LGraphCanvas.onMenuResizeNode}),e.collapsible&&t.push({content:e.collapsed?`Expand`:`Collapse`,callback:LGraphCanvas.onMenuNodeCollapse}),e.hasAdvancedWidgets()&&t.push({content:e.showAdvanced?`Hide Advanced`:`Show Advanced`,callback:LGraphCanvas.onMenuToggleAdvanced}),t.push({content:e.pinned?`Unpin`:`Pin`,callback:()=>{for(let e in this.selected_nodes)this.selected_nodes[e].pin();this.setDirty(!0,!0)}},{content:`Colors`,has_submenu:!0,callback:LGraphCanvas.onMenuNodeColors},{content:`Shapes`,has_submenu:!0,callback:LGraphCanvas.onMenuNodeShapes},null));let n=e.getExtraMenuOptions?.(this,t);return Array.isArray(n)&&n.length>0&&(n.push(null),t=n.concat(t)),e.clonable!==!1&&t.push({content:`Clone`,callback:LGraphCanvas.onMenuNodeClone}),Object.keys(this.selected_nodes).length>1&&t.push({content:`Align Selected To`,has_submenu:!0,callback:LGraphCanvas.onNodeAlign},{content:`Distribute Nodes`,has_submenu:!0,callback:LGraphCanvas.createDistributeMenu}),t.push(null,{content:`Remove`,disabled:!(e.removable!==!1&&!e.block_delete),callback:LGraphCanvas.onMenuNodeRemove}
2),e.graph?.onGetNodeMenuOptions?.(t,e),t}getGroupMenuOptions(e){return console.warn(`LGraphCanvas.getGroupMenuOptions is deprecated, use LGraphGroup.getMenuOptions instead`),e.getMenuOptions()}processContextMenu(e,t){let n,r={event:t,callback:inner_option_clicked,extra:e};if(e){r.title=e.displayType??e.type??void 0,LGraphCanvas.active_node=e;let i=e.getSlotInPosition(t.canvasX,t.canvasY);if(i){if(n=[],e.getSlotMenuOptions)n=e.getSlotMenuOptions(i);else{(i.output?.links?.length||i.input?.link!=null)&&n.push({content:`Disconnect Links`,slot:i});let t=i.input||i.output;if(!t)throw TypeError(`Both in put and output slots were null when processing context menu.`);!t.nameLocked&&!(`link`in t&&t.widget)&&n.push({content:`Rename Slot`,slot:i}),t.removable&&(n.push(null),n.push(t.locked?`Cannot remove`:{content:`Remove Slot`,slot:i,className:`danger`})),e.getExtraSlotMenuOptions&&n.push(...e.getExtraSlotMenuOptions(i))}r.title=(i.input?i.input.type:i.output.type)||`*`,i.input&&i.input.type==Q.ACTION&&(r.title=`Action`),i.output&&i.output.type==Q.EVENT&&(r.title=`Event`)}else n=this.getNodeMenuOptions(e)}else{if(n=this.getCanvasMenuOptions(),!this.graph)throw new NullGraphError;if(this.links_render_mode!==L.HIDDEN_LINK){let e=U.queryRerouteAtPoint({x:t.canvasX,y:t.canvasY}),r;r=e?this.graph.getReroute(e.id):this.graph.getRerouteOnPos(t.canvasX,t.canvasY,this._visibleReroutes),r&&n.unshift({content:`Delete Reroute`,callback:()=>{if(!this.graph)throw new NullGraphError;this.graph.removeReroute(r.id)}},null)}let e=this.graph.getGroupOnPos(t.canvasX,t.canvasY);e&&n.push(null,{content:`Edit Group`,has_submenu:!0,submenu:{title:`Group`,extra:e,options:e.getMenuOptions()}})}if(!n)return;new Q.ContextMenu(n,r);let createDialog=e=>this.createDialog(`<span class='name'>Name</span><input autofocus type='text'/><button>OK</button>`,e),setDirty=()=>this.setDirty(!0);function inner_option_clicked(t,n){if(t){if(t.content==`Remove Slot`){if(!e?.graph)throw new NullGraphError;let n=t.slot;if(!n)throw TypeError(`Found-slot info was null when processing context menu.`);e.graph.beforeChange(),n.input?e.removeInput(n.slot):n.output&&e.removeOutput(n.slot),e.graph.afterChange();return}else if(t.content==`Disconnect Links`){if(!e?.graph)throw new NullGraphError;let n=t.slot;if(!n)throw TypeError(`Found-slot info was null when processing context menu.`);e.graph.beforeChange(),n.output?e.disconnectOutput(n.slot):n.input&&e.disconnectInput(n.slot,!0),e.graph.afterChange();return}else if(t.content==`Rename Slot`){if(!e)throw TypeError("`node` was null when processing the context menu.");let r=t.slot;if(!r)throw TypeError(`Found-slot info was null when processing context menu.`);let i=r.input?e.getInputInfo(r.slot):e.getOutputInfo(r.slot),a=createDialog(n),o=a.querySelector(`input`);o&&i&&(o.value=i.label||``);let inner=function(){if(!e.graph)throw new NullGraphError;e.graph.beforeChange(),o?.value&&(i&&(i.label=o.value),setDirty()),a.close(),e.graph.afterChange()};if(a.querySelector(`button`)?.addEventListener(`click`,inner),!o)throw TypeError(`Input element was null when processing context menu.`);o.addEventListener(`keydown`,function(e){if(a.is_modified=!0,e.key==`Escape`)a.close();else if(e.key==`Enter`)inner();else if(e.target.localName!=`textarea`)return;e.preventDefault(),e.stopPropagation()}),o.focus()}}}}animateToBounds(e,t={}){let setDirty=()=>this.setDirty(!0,!0);this.ds.animateToBounds(e,setDirty,t)}fitViewToSelectionAnimated(e={}){let t=createBounds(this.selectedItems.size?Array.from(this.selectedItems):this.positionableItems);if(!t)throw TypeError(`Attempted to fit to view but could not calculate bounds.`);let setDirty=()=>this.setDirty(!0,!0);this.ds.animateToBounds(t,setDirty,e)}calculateNewPosition(e,t,n){return{x:e.pos[0]+t,y:e.pos[1]+n}}applyNodePositionUpdates(e){for(let{node:t,newPos:n}of e)t.setPos(n.x,n.y)}collectNodesInGroups(e){let t=new Set;for(let n of e)if(n instanceof X)for(let e of n._children)e instanceof Y&&t.add(e);return t}moveGroupChildren(e,t,n,r){for(let i of e._children)if(i instanceof Y){let e=i;r.push({node:e,newPos:this.calculateNewPosition(e,t,n)})}else i instanceof X||i.move(t,n,!0)}moveChildNodesInGroupVueMode(e,t,n){let r=this.collectNodesInGroups(e),i=[];for(let a of e)if(a instanceof Y){let e=a;if(r.has(e))continue;i.push({node:e,newPos:this.calculateNewPosition(e,t,n)})}else a instanceof X?(a.move(t,n,!0),this.moveGroupChildren(a,t,n,i)):a.move(t,n,!0);this.applyNodePositionUpdates(i)}repositionNodesVueMode(e){this.applyNodePositionUpdates(e)}toJSON(){return{ds:{scale:this.ds.scale,offset:[...this.ds.offset]}}}};function patchLinkNodeIds$1(e,t){if(e?.length)for(let n of e){let e=t.get(n.origin_id);e!==void 0&&(n.origin_id=e);let r=t.get(n.target_id);r!==void 0&&(n.target_id=r)}}t(patchLinkNodeIds$1,`patchLinkNodeIds`);function remapNodeId(e,t){let n=t.get(e);if(n!==void 0)return n;if(!/^-?\d+$/.test(e))return;let r=Number(e);if(Number.isSafeInteger(r))return t.get(r)}function remapProxyWidgets(e,t){if(!t||t.size===0)return;let n=e.properties?.proxyWidgets;if(Array.isArray(n))for(let e of n){if(!Array.isArray(e))continue;let[n]=e;if(typeof n!=`string`||n===`-1`)continue;let r=remapNodeId(n,t);r!==void 0&&(e[0]=String(r))}}function remapClipboardSubgraphNodeIds(e,t){let n=new Set;forEachNode(t,e=>{typeof e.id==`number`&&(n.add(e.id),t.state.lastNodeId<e.id&&(t.state.lastNodeId=e.id))});function nextUniqueNodeId(){for(;n.has(++t.state.lastNodeId););let e=t.state.lastNodeId;return n.add(e),e}let r=new Map;for(let i of e.subgraphs??[]){let e=new Map,a=i.nodes??[];for(let r of a)if(typeof r.id==`number`){if(n.has(r.id)){let t=r.id,n=nextUniqueNodeId();e.set(t,n),r.id=n;continue}n.add(r.id),t.state.lastNodeId<r.id&&(t.state.lastNodeId=r.id)}e.size>0&&(patchLinkNodeIds$1(i.links,e),r.set(i.id,e))}
2let i=[e.nodes?[e.nodes]:[],e.subgraphs?e.subgraphs.map(e=>e.nodes??[]):[]].flat(2);for(let e of i)typeof e.type==`string`&&remapProxyWidgets(e,r.get(e.type))}var MapProxyHandler=class{getOwnPropertyDescriptor(e,t){let n=this.get(e,t);if(n)return{configurable:!0,enumerable:!0,value:n}}has(e,t){if(typeof t==`symbol`)return!1;let n=parseInt(t,10);return e.has(isNaN(n)?t:n)}ownKeys(e){return[...e.keys()].map(String)}get(e,t){if(t in e)return Reflect.get(e,t,e);if(typeof t==`symbol`)return;let n=parseInt(t,10);return e.get(isNaN(n)?t:n)}set(e,t,n){if(typeof t==`symbol`)return!1;let r=parseInt(t,10);return e.set(isNaN(r)?t:r,n),!0}deleteProperty(e,t){return e.delete(t)}static bindAllMethods(e){e.clear=e.clear.bind(e),e.delete=e.delete.bind(e),e.forEach=e.forEach.bind(e),e.get=e.get.bind(e),e.has=e.has.bind(e),e.set=e.set.bind(e),e.entries=e.entries.bind(e),e.keys=e.keys.bind(e),e.values=e.values.bind(e),e[Symbol.iterator]=e[Symbol.iterator].bind(e)}},vt=1e8;function deduplicateSubgraphNodeIds(e,t,n,r){let i=structuredClone(e),a=r?structuredClone(r):void 0,o=new Set(t),s=new Set(i.map(e=>e.id)),c=new Map;for(let e of i){let t=remapNodeIds(e.nodes??[],o,n);t.size!==0&&(c.set(e.id,t),patchSerialisedLinks(e.links??[],t),patchPromotedWidgets(e.widgets??[],t))}for(let e of i)patchProxyWidgets(e.nodes??[],s,c);return a&&patchProxyWidgets(a,s,c),{subgraphs:i,rootNodes:a}}function remapNodeIds(e,t,n){let r=new Map;for(let i of e){let e=i.id;if(typeof e==`number`)if(t.has(e)){let a=findNextAvailableId(t,n);r.set(e,a),i.id=a,t.add(a),console.warn(`LiteGraph: duplicate subgraph node ID ${e} remapped to ${a}`)}else t.add(e),e>n.lastNodeId&&(n.lastNodeId=e)}return r}function findNextAvailableId(e,t){for(;;){let n=t.lastNodeId+1;if(n>vt)throw Error(`Node ID space exhausted`);if(t.lastNodeId=n,!e.has(n))return n}}function patchSerialisedLinks(e,t){for(let n of e){let e=t.get(n.origin_id);e!==void 0&&(n.origin_id=e);let r=t.get(n.target_id);r!==void 0&&(n.target_id=r)}}function patchPromotedWidgets(e,t){for(let n of e){let e=t.get(n.id);e!==void 0&&(n.id=e)}}function topologicalSortSubgraphs(e){let t=new Set(e.map(e=>e.id)),n=new Map(e.map(e=>[e.id,e])),r=new Map,i=new Map;for(let e of t)r.set(e,new Set),i.set(e,0);for(let n of e)for(let e of n.nodes??[])t.has(e.type)&&(r.get(e.type).add(n.id),i.set(n.id,(i.get(n.id)??0)+1));let a=[];for(let[e,t]of i)t===0&&a.push(e);let o=[];for(;a.length>0;){let e=a.shift();o.push(n.get(e));for(let t of r.get(e)??[]){let e=(i.get(t)??1)-1;i.set(t,e),e===0&&a.push(t)}}return o.length===e.length?o:e}function patchProxyWidgets(e,t,n){for(let r of e){if(!t.has(r.type))continue;let e=n.get(r.type);if(!e)continue;let i=r.properties?.proxyWidgets;if(Array.isArray(i))for(let t of i){if(!Array.isArray(t))continue;let n=Number(t[0]),r=e.get(n);r!==void 0&&(t[0]=String(r))}}}var yt=class LGraph{static serialisedSchemaVersion=1;static STATUS_STOPPED=1;static STATUS_RUNNING=2;static ConfigureProperties=new Set([`nodes`,`groups`,`links`,`state`,`reroutes`,`floatingLinks`,`id`,`subgraphs`,`definitions`,`inputs`,`outputs`,`widgets`,`inputNode`,`outputNode`,`extra`]);id=Ce;revision=0;_version=-1;_links=new Map;links;list_of_graphcanvas;status=LGraph.STATUS_STOPPED;_state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0};get state(){return this._state}set state(e){this._state=e}events=new CustomEventTarget;_subgraphs=new Map;_nodes=[];_nodes_by_id={};_nodes_in_order=[];_nodes_executable=null;_groups=[];iteration=0;globaltime=0;runningtime=0;fixedtime=0;fixedtime_lapse=.01;elapsed_time=.01;last_update_time=0;starttime=0;catch_errors=!0;execution_timer_id;errors_in_execution;execution_time;_last_trigger_time;filter;config={};vars={};nodes_executing=[];nodes_actioning=[];nodes_executedAction=[];extra={};version;get empty(){return this._nodes.length+this._groups.length+this.reroutes.size===0}*positionableItems(){for(let e of this._nodes)yield e;for(let e of this._groups)yield e;for(let e of this.reroutes.values())yield e}_lastFloatingLinkId=0;floatingLinksInternal=new Map;get floatingLinks(){return this.floatingLinksInternal}reroutesInternal=new Map;get reroutes(){return this.reroutesInternal}get rootGraph(){return this}get isRootGraph(){return this.rootGraph===this}get last_node_id(){return this.state.lastNodeId}set last_node_id(e){this.state.lastNodeId=e}get last_link_id(){return this.state.lastLinkId}set last_link_id(e){this.state.lastLinkId=e}onTrigger;_input_nodes;constructor(e){let t=this._links;MapProxyHandler.bindAllMethods(t);let n=new MapProxyHandler;this.links=new Proxy(t,n),this.list_of_graphcanvas=null,this.clear(),e&&this.configure(e)}clear(){this.stop(),this.status=LGraph.STATUS_STOPPED;let e=this.id;if(this.isRootGraph&&e!==`00000000-0000-0000-0000-000000000000`&&(W().clearGraph(e),Pe().clearGraph(e)),this.id=Ce,this.revision=0,this.state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0},this._version=-1,this._subgraphs.clear(),this._nodes)for(let e of this._nodes)e.onRemoved?.(),this.onNodeRemoved?.(e);this._nodes=[],this._nodes_by_id={},this._nodes_in_order=[],this._nodes_executable=null,this._links.clear(),this.reroutes.clear(),this.floatingLinksInternal.clear(),this._lastFloatingLinkId=0,this._groups=[],this.iteration=0,this.config={},this.vars={},this.extra={},this.globaltime=0,this.runningtime=0,this.fixedtime=0,this.fixedtime_lapse=.01,this.elapsed_time=.01,this.last_update_time=0,this.starttime=0,this.catch_errors=!0,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[],this.change(),this.canvasAction(e=>e.clear())}get subgraphs(){return this.rootGraph._subgraphs}get nodes(){return this._nodes}get groups(){return this._groups}attachCanvas(e){if(!(e instanceof Z))throw TypeError(`attachCanvas expects an LGraphCanvas instance`);this.primaryCanvas=e,this.list_of_graphcanvas??=[],this.list_of_graphcanvas.includes(e)||this.list_of_graphcanvas.push(e),e.graph!==this&&(e.graph?.detachCanvas(e),e.graph=this,e.subgraph=void 0)}detachCanvas(e){e.graph=null;let t=this.list_of_graphcanvas;if(t){let n=t.indexOf(e);n!==-1&&t.splice(n,1)}}start(e){if(this.status!=LGraph.STATUS_RUNNING)if(this.status=LGraph.STATUS_RUNNING,this.sendEventToAllNodes(`onStart`),this.starttime=Q.getTime(),this.last_update_time=this.starttime,e||=0,e==0&&typeof window<`u`&&window.requestAnimationFrame){let on_frame=()=>{this.execution_timer_id==-1&&(window.requestAnimationFrame(on_frame),this.runStep(1,!this.catch_errors))};this.execution_timer_id=-1,on_frame()}else this.execution_timer_id=setInterval(()=>{this.runStep(1,!this.catch_errors)},e)}stop(){this.status!=LGraph.STATUS_STOPPED&&(this.status=LGraph.STATUS_STOPPED,this.execution_timer_id!=null&&(this.execution_timer_id!=-1&&clearInterval(this.execution_timer_id),this.execution_timer_id=null),this.sendEventToAllNodes(`onStop`))}runStep(e,t,n){e||=1;let r=Q.getTime();this.globaltime=.001*(r-this.starttime);let i=this._nodes_executable||this._nodes;if(!i)return;if(n||=i.length,t)for(let t=0;t<e;t++){for(let e=0;e<n;++e){let t=i[e];t.mode==B.ALWAYS&&t.onExecute&&t.doExecute?.()}this.fixedtime+=this.fixedtime_lapse}else try{for(let t=0;t<e;t++){for(let e=0;e<n;++e){let t=i[e];t.mode==B.ALWAYS&&t.onExecute?.()}this.fixedtime+=this.fixedtime_lapse}this.errors_in_execution=!1}catch(e){if(this.errors_in_execution=!0,Q.throw_errors)throw e;Q.debug&&console.error(`Error during execution:`,e),this.stop()}let a=Q.getTime(),o=a-r;o==0&&(o=1),this.execution_time=.001*o,this.globaltime+=.001*o,this.iteration+=1,this.elapsed_time=(a-this.last_update_time)*.001,this.last_update_time=a,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[]}updateExecutionOrder(){this._nodes_in_order=this.computeExecutionOrder(!1),this._nodes_executable=[];for(let e of this._nodes_in_order)e.onExecute&&this._nodes_executable.push(e)}computeExecutionOrder(e,t){let n=[],r=[],i={},a={},o={};for(let n of this._nodes){if(e&&!n.onExecute)continue;i[n.id]=n;let a=0;if(n.inputs)for(let e of n.inputs)e?.link!=null&&(a+=1);a==0?(r.push(n),t&&(n._level=1)):(t&&(n._level=0),o[n.id]=a)}for(;;){let e=r.shift();if(e===void 0)break;if(n.push(e),delete i[e.id],e.outputs){for(let n of e.outputs)if(!(n?.links==null||n.links.length==0))for(let i of n.links){let n=this._links.get(i);if(!n||a[n.id])continue;let s=this.getNodeById(n.target_id);if(s==null){a[n.id]=!0;continue}t&&(e._level??=0,(!s._level||s._level<=e._level)&&(s._level=e._level+1)),a[n.id]=!0,--o[s.id],o[s.id]==0&&r.push(s)}}}for(let e in i)n.push(i[e]);n.length!=this._nodes.length&&Q.debug&&console.warn(`something went wrong, nodes missing`);function setOrder(e){let t=e.length;for(let n=0;n<t;++n)e[n].order=n}return setOrder(n),n.sort(function(e,t){let n=e.constructor.priority||e.priority||0,r=t.constructor.priority||t.priority||0;return n==r?e.order-t.order:n-r}),setOrder(n),n}arrange(e,t){e||=100;let n=this.computeExecutionOrder(!1,!0),r=[];for(let e of n){let t=e._level||1;r[t]||=[],r[t].push(e)}let i=e;for(let n of r){if(!n)continue;let r=100,a=e+Q.NODE_TITLE_HEIGHT;for(let o of n){o.setPos(t==Q.VERTICAL_LAYOUT?a:i,t==Q.VERTICAL_LAYOUT?i:a);let n=t==Q.VERTICAL_LAYOUT?1:0;o.size[n]>r&&(r=o.size[n]);let s=t==Q.VERTICAL_LAYOUT?0:1;a+=o.size[s]+e+Q.NODE_TITLE_HEIGHT}i+=r+e}this.setDirtyCanvas(!0,!0)}getTime(){return this.globaltime}getFixedTime(){return this.fixedtime}getElapsedTime(){return this.elapsed_time}incrementVersion(){this._version++}sendEventToAllNodes(e,t,n){n||=B.ALWAYS;let r=this._nodes_in_order||this._nodes;if(r)for(let i of r)!i[e]||i.mode!=n||(t===void 0?i[e]():t&&t.constructor===Array?i[e].apply(i,t):i[e](t))}canvasAction(e){let t=this.list_of_graphcanvas;if(t)for(let n of t)e(n)}sendActionToCanvas(e,t){let{list_of_graphcanvas:n}=this;if(n)for(let r of n){let n=r[e];if(typeof n==`function`){let e=t==null?[]:Array.isArray(t)?t:[t];n.apply(r,e)}}}add(e,t){if(!e)return;let n=typeof t==`object`?t:{skipComputeOrder:t??!1},r=n.skipComputeOrder??!1,{state:i}=this;
2if(Q.alwaysSnapToGrid){let t=this.getSnapToGridSize();t&&e.snapToGrid(t)}if(e instanceof X){(e.id==null||e.id===-1)&&(e.id=++i.lastGroupId),e.id>i.lastGroupId&&(i.lastGroupId=e.id),this._groups.push(e),this.setDirtyCanvas(!0),this.change(),e.graph=this,this.incrementVersion();return}if(e.id!=-1&&this._nodes_by_id[e.id]!=null&&(console.warn(`LiteGraph: there is already a node with this ID, changing it`),e.id=Q.use_uuids?Q.uuidv4():++i.lastNodeId),this._nodes.length>=Q.MAX_NUMBER_OF_NODES)throw`LiteGraph: max number of nodes in a graph reached`;if(Q.use_uuids?(e.id==null||e.id==-1)&&(e.id=Q.uuidv4()):e.id==null||e.id==-1?e.id=++i.lastNodeId:typeof e.id==`number`&&i.lastNodeId<e.id&&(i.lastNodeId=e.id),n.ghost&&(e.flags.ghost=!0),e.graph=this,this.incrementVersion(),e.widgets)for(let t of e.widgets)isNodeBindable(t)&&t.setNodeId(e.id);return this._nodes.push(e),this._nodes_by_id[e.id]=e,e.onAdded?.(this),this.config.align_to_grid&&e.alignToGrid(),r||this.updateExecutionOrder(),this.onNodeAdded?.(e),this.setDirtyCanvas(!0),this.change(),n.ghost&&this.canvasAction(t=>t.startGhostPlacement(e,n.dragEvent)),e.isSubgraphNode?.()&&forEachNode(e.subgraph,e=>{e.isSubgraphNode()&&this.subgraphs.set(e.subgraph.id,e.subgraph)}),e}remove(e){if(e instanceof X){this.canvasAction(t=>t.deselect(e));let t=this._groups.indexOf(e);t!=-1&&this._groups.splice(t,1),e.graph=void 0,this.incrementVersion(),this.setDirtyCanvas(!0,!0),this.change();return}if(this._nodes_by_id[e.id]==null){console.warn(`LiteGraph: node not found`,e);return}if(e.ignore_remove){console.warn(`LiteGraph: node cannot be removed`,e);return}this.beforeChange();let{inputs:t,outputs:n}=e;if(t)for(let[n,r]of t.entries())r.link!=null&&e.disconnectInput(n,!0);if(n)for(let[t,r]of n.entries())r.links?.length&&e.disconnectOutput(t);for(let t of this.floatingLinks.values())(t.origin_id===e.id||t.target_id===e.id)&&this.removeFloatingLink(t);e.isSubgraphNode()&&([this.rootGraph,...this.rootGraph.subgraphs.values()].some(t=>t.nodes.some(t=>t!==e&&t.isSubgraphNode()&&t.type===e.subgraph.id))||(forEachNode(e.subgraph,e=>{e.onRemoved?.(),e.graph?.onNodeRemoved?.(e)}),this.rootGraph.subgraphs.delete(e.subgraph.id))),e.onRemoved?.(),e.graph=null,this.incrementVersion();let{list_of_graphcanvas:r}=this;if(r)for(let t of r)t.selected_nodes[e.id]&&delete t.selected_nodes[e.id],t.deselect(e);let i=this._nodes.indexOf(e);i!=-1&&this._nodes.splice(i,1),delete this._nodes_by_id[e.id],this.onNodeRemoved?.(e),this.canvasAction(e=>e.checkPanels()),this.setDirtyCanvas(!0,!0),this.afterChange(),this.change(),this.updateExecutionOrder()}getNodeById(e){return e==null?null:this._nodes_by_id[e]}findNodesByClass(e,t){t||=[],t.length=0;let{_nodes:n}=this;for(let r of n)r.constructor===e&&t.push(r);return t}findNodesByType(e,t){let n=e.toLowerCase();t||=[],t.length=0;let{_nodes:r}=this;for(let e of r)e.type?.toLowerCase()==n&&t.push(e);return t}findNodeByTitle(e){let{_nodes:t}=this;for(let n of t)if(n.title==e)return n;return null}findNodesByTitle(e){let t=[],{_nodes:n}=this;for(let r of n)r.title==e&&t.push(r);return t}getNodeOnPos(e,t,n){let r=n||this._nodes,i=r.length;for(;--i>=0;){let n=r[i];if(n.isPointInside(e,t))return n}return null}getGroupOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){let r=this._groups[n];if(r.isPointInside(e,t))return r}}getGroupTitlebarOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){let r=this._groups[n];if(r.isPointInTitlebar(e,t))return r}}getRerouteOnPos(e,t,n){for(let r of n??this.reroutes.values())if(r.containsPoint([e,t]))return r}snapToGrid(e){let t=this.getSnapToGridSize();if(t)for(let n of getAllNestedItems(e))n.pinned||n.snapToGrid(t)}getSnapToGridSize(){return Q.alwaysSnapToGrid?Q.CANVAS_GRID_SIZE||1:Q.CANVAS_GRID_SIZE}checkNodeTypes(){let{_nodes:e}=this;for(let[t,n]of e.entries()){let r=Q.registered_node_types[n.type];if(n.constructor==r)continue;console.warn(`node being replaced by newer version:`,n.type);let i=Q.createNode(n.type);i&&(e[t]=i,i.configure(n.serialize()),i.graph=this,this._nodes_by_id[i.id]=i,n.inputs&&(i.inputs=[...n.inputs]),n.outputs&&(i.outputs=[...n.outputs]))}this.updateExecutionOrder()}trigger(e,t){new Set([`node:slot-links:changed`,`node:slot-errors:changed`,`node:property:changed`,`node:slot-label:changed`]).has(e)&&t&&typeof t==`object`&&this.onTrigger?.({type:e,...t})}triggerInput(e,t){let n=this.findNodesByTitle(e);for(let e of n)e.onTrigger(t)}setCallback(e,t){let n=this.findNodesByTitle(e);for(let e of n)e.setTrigger(t)}beforeChange(e){this.onBeforeChange?.(this,e),this.canvasAction(e=>e.onBeforeChange?.(this))}afterChange(e){this.onAfterChange?.(this,e),this.canvasAction(e=>e.onAfterChange?.(this))}clearTriggeredSlots(){for(let e of this._links.values())e&&(e._last_time&&=0)}change(){this.canvasAction(e=>e.setDirty(!0,!0)),this.on_change?.(this)}setDirtyCanvas(e,t){this.canvasAction(n=>n.setDirty(e,t))}addFloatingLink(e){e.id===-1&&(e.id=++this._lastFloatingLinkId),this.floatingLinksInternal.set(e.id,e);let t=e.target_id===-1?this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot]:this.getNodeById(e.target_id)?.input
2s?.[e.target_slot];t?(t._floatingLinks??=new Set,t._floatingLinks.add(e)):console.warn(`Adding invalid floating link: target/slot: [${e.target_id}/${e.target_slot}] origin/slot: [${e.origin_id}/${e.origin_slot}]`);let n=K.getReroutes(this,e);for(let t of n)t.floatingLinkIds.add(e.id);return e}removeFloatingLink(e){this.floatingLinksInternal.delete(e.id);let t=e.target_id===-1?this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot]:this.getNodeById(e.target_id)?.inputs?.[e.target_slot];t&&t._floatingLinks?.delete(e);let n=K.getReroutes(this,e);for(let t of n)t.floatingLinkIds.delete(e.id),t.floatingLinkIds.size===0&&delete t.floating,t.totalLinks===0&&this.removeReroute(t.id)}getLink(e){return e==null?void 0:this._links.get(e)}getReroute(e){return e==null?void 0:this.reroutes.get(e)}setReroute({id:e,parentId:t,pos:n,linkIds:r,floating:i}){e??=++this.state.lastRerouteId,e>this.state.lastRerouteId&&(this.state.lastRerouteId=e);let a=this.reroutes.get(e)??new q(e,this);return a.update(t,n,r,i),this.reroutes.set(e,a),a}createReroute(e,t){let n=useLayoutMutations(),r=++this.state.lastRerouteId,i=t instanceof q?t.linkIds:[t.id],a=t instanceof q?t.floatingLinkIds:[t.id],o=new q(r,this,e,t.parentId,i,a);this.reroutes.set(r,o),n.setSource(H.Canvas),n.createReroute(r,{x:e[0],y:e[1]},t.parentId,Array.from(i));for(let e of i){let n=this._links.get(e);if(!n)continue;n.parentId===t.parentId&&(n.parentId=r);let i=K.getReroutes(this,n);for(let e of i.filter(e=>e.parentId===t.parentId))e.parentId=r}for(let e of a){let n=this.floatingLinks.get(e);if(!n)continue;n.parentId===t.parentId&&(n.parentId=r);let i=K.getReroutes(this,n);for(let e of i.filter(e=>e.parentId===t.parentId))e.parentId=r}return o}removeReroute(e){let t=useLayoutMutations(),{reroutes:n}=this,r=n.get(e);if(!r)return;this.canvasAction(e=>e.deselect(r));let{parentId:i,linkIds:a,floatingLinkIds:o}=r;for(let t of n.values())t.parentId===e&&(t.parentId=i);for(let t of a){let n=this._links.get(t);n&&n.parentId===e&&(n.parentId=i)}for(let t of o){let n=this.floatingLinks.get(t);if(!n){console.warn(`Removed reroute had floating link ID that did not exist [${t}]`);continue}let a=K.getReroutes(this,n),o=a.at(-1),s=a.at(-2);r===o&&(s?.totalLinks===1?n.parentId===e&&(n.parentId=i,s.floating=r.floating):this.removeFloatingLink(n))}n.delete(e),t.setSource(H.Canvas),t.deleteReroute(e),this.setDirtyCanvas(!1,!0)}removeLink(e){let t=this._links.get(e);t&&(this.getNodeById(t.target_id)?.disconnectInput(t.target_slot,!1),t.disconnect(this))}_removeDuplicateLinks(){let e=groupLinksByTuple(this._links);for(let t of e.values()){if(t.length<=1)continue;let e=this._links.get(t[0]),n=this.getNodeById(e.target_id),r=selectSurvivorLink(t,n);purgeOrphanedLinks(t,r,this._links,e=>this.getNodeById(e)),repairInputLinks(t,r,n)}}createSubgraph(e){let{id:t}=e,n=new bt(this.rootGraph,e);return this.subgraphs.set(t,n),this.rootGraph.events.dispatch(`subgraph-created`,{subgraph:n,data:e}),n}convertToSubgraph(e){if(e.size===0)throw Error(`Cannot convert to subgraph: nothing to convert`);this.beforeChange(),this.canvasAction(e=>e.emitBeforeChange());try{function extractNodes(e){if(!(e instanceof Y)||!e.convertToNodes)return[e];let t=e.convertToNodes();for(let e of t)e.updateArea();return t}let t=new Set([...e].flatMap(extractNodes));return this._convertToSubgraphImpl(t)}finally{this.afterChange(),this.canvasAction(e=>e.emitAfterChange())}}_convertToSubgraphImpl(e){let{state:t,revision:n,config:r}=this,i=[...e][0];e.size===1&&i instanceof X&&(e=new Set([i]),i.recomputeInsideNodes(),i.children.forEach(t=>e.add(t)));let{boundaryLinks:a,boundaryFloatingLinks:o,internalLinks:s,boundaryInputLinks:c,boundaryOutputLinks:l}=getBoundaryLinks(this,e),{nodes:u,reroutes:d,groups:f}=splitPositionables(e),p=createBounds(e);if(!p)throw Error(`Failed to create bounding rect for subgraph`);let m=c.map(e=>e.resolve(this)),h=l.map(e=>e.resolve(this)),g=multiClone(u),_=s.map(e=>e.asSerialisable()),v=new Map([...d].map(e=>[e.id,e])),y=new Map([...this.reroutes].filter(([e])=>!v.has(e))),ee=mapSubgraphInputsAndLinks(m,_,v),te=mapSubgraphOutputsAndLinks(h,_,y),ne={id:createUuidv4(),name:`New Subgraph`,inputNode:{id:-10,bounding:[0,0,75,100]},outputNode:{id:-20,bounding:[0,0,75,100]},inputs:ee,outputs:te,widgets:[],version:LGraph.serialisedSchemaVersion,state:t,revision:n,config:r,links:_,nodes:g,reroutes:structuredClone([...d].map(e=>
2e.asSerialisable())),groups:structuredClone([...f].map(e=>e.serialize()))},b=this.createSubgraph(ne);b.configure(ne);for(let e of b.nodes)e.onGraphConfigured?.();for(let e of b.nodes)e.onAfterGraphConfigured?.();b.inputNode.arrange(),b.outputNode.arrange();let{boundingRect:re}=b.inputNode,{boundingRect:ie}=b.outputNode;alignOutsideContainer(re,V.MidLeft,p,[50,0]),alignOutsideContainer(ie,V.MidRight,p,[50,0]);for(let e of m)e.inputNode?.disconnectInput(e.inputNode.inputs.indexOf(e.input),!0);for(let e of h)e.outputNode?.disconnectOutput(e.outputNode.outputs.indexOf(e.output),e.inputNode);for(let e of u)this.remove(e);for(let e of d)this.removeReroute(e.id);for(let e of f)this.remove(e);this.rootGraph.events.dispatch(`convert-to-subgraph`,{subgraph:b,bounds:p,exportedSubgraph:ne,boundaryLinks:a,resolvedInputLinks:m,resolvedOutputLinks:h,boundaryFloatingLinks:o,internalLinks:s});let x=Q.createNode(b.id,b.name,{outputs:structuredClone(te)});if(!x)throw Error(`Failed to create subgraph node`);for(let e=0;e<ee.length;e++)Object.assign(x.inputs[e],ee[e]);x.setSize(x.computeSize()),alignToContainer(x._posSize,V.Centre|V.Middle,p),x.setPos(x.pos[0],x.pos[1]+Q.NODE_TITLE_HEIGHT/2),this.add(x);let S=groupResolvedByOutput(m),ae=0;for(let[,e]of S.entries()){let[t,...n]=e,{output:r,outputNode:i,link:a,subgraphInput:o}=t;
2if(ae++,a.origin_id===-10){if(a.target_id=x.id,a.target_slot=ae-1,o instanceof SubgraphInput)o.connect(x.findInputSlotByType(a.type,!0,!0),x,a.parentId);else throw TypeError(`Subgraph input node is not a SubgraphInput`);for(let e of n)e.link.disconnect(this);continue}if(!r||!i){console.warn(`Convert to Subgraph reconnect: Failed to resolve input link`,e[0]);continue}let s=x.inputs[ae-1];i.connectSlots(r,x,s,a.parentId)}let C=groupResolvedByOutput(h);ae=0;for(let[,e]of C.entries()){ae++;for(let t of e){let{input:e,inputNode:n,link:r,subgraphOutput:i}=t;if(r.target_id===-20){if(r.origin_id=x.id,r.origin_slot=ae-1,this.links.set(r.id,r),i instanceof SubgraphOutput)i.connect(x.findOutputSlotByType(r.type,!0,!0),x,r.parentId);else throw TypeError(`Subgraph input node is not a SubgraphInput`);continue}if(!e||!n){console.warn(`Convert to Subgraph reconnect: Failed to resolve output link`,t);continue}let a=x.outputs[ae-1];x.connectSlots(a,n,e,r.parentId)}}return x._setConcreteSlots(),x.arrange(),this.isRootGraph||this._repointAncestorPromotions(u,x),this.canvasAction(e=>e.canvas.dispatchEvent(new CustomEvent(`subgraph-converted`,{bubbles:!0,detail:{subgraphNode:x}}))),{subgraph:b,node:x}}_repointAncestorPromotions(e,t){let n=new Set([...e].map(e=>String(e.id))),r=W(),i=String(t.id),a=this.rootGraph.id,o=r.getPromotions(a,t.id),s=[...o],c=new Set(o.map(e=>makePromotionEntryKey(e))),l=[],u=[this.rootGraph,...this.rootGraph._subgraphs.values()];for(let e of u)for(let t of e._nodes){if(!t.isSubgraphNode()||t.type!==this.id)continue;let e=r.getPromotions(a,t.id),o=e.filter(e=>n.has(e.sourceNodeId));if(o.length===0)continue;for(let e of o){let t=makePromotionEntryKey(e);c.has(t)||(c.add(t),s.push(e))}let u=e.map(e=>n.has(e.sourceNodeId)?{sourceNodeId:i,sourceWidgetName:e.sourceWidgetName,disambiguatingSourceNodeId:e.disambiguatingSourceNodeId??e.sourceNodeId}:e);l.push({node:t,entries:u})}s.length!==o.length&&r.setPromotions(a,t.id,s);for(let{node:e,entries:t}of l)r.setPromotions(a,e.id,t),e.rebuildInputWidgetBindings()}unpackSubgraph(e,t){if(!(e instanceof SubgraphNode))throw Error(`Can only unpack Subgraph Nodes`);this.beforeChange();try{this._unpackSubgraphImpl(e,t)}finally{this.afterChange()}}_unpackSubgraphImpl(e,t){let n=t?.skipMissingNodes??!1,r=createBounds([...e.subgraph.nodes,...e.subgraph.reroutes.values(),...e.subgraph.groups].map(e=>({boundingRect:[e.pos[0],e.pos[1],e.size?.[0]??0,e.size?.[1]??0]})))??[0,0,0,0],i=[r[0]+r[2]/2,r[1]+r[3]/2],a=[],o=e.pos[0]-i[0]+e.size[0]/2,s=e.pos[1]-i[1]+e.size[1]/2,c=multiClone(e.subgraph.nodes),l=new Map;for(let e of c){let t=Q.createNode(String(e.type),e.title);if(!t)if(n)console.warn(`Cannot unpack node of type "${e.type}" - node type not found. Creating placeholder node.`),t=new Y(e.title||e.type||`Missing Node`),t.last_serialization=e,t.has_errors=!0,t.type=String(e.type);else throw Error(`Cannot unpack: node type "${e.type}" is not registered`);l.set(e.id,++this.last_node_id),t.id=this.last_node_id,e.id=this.last_node_id;for(let t of e.inputs??[])t.link=null;for(let t of e.outputs??[])t.links=[];this.add(t,!0),t.configure(e),t.setPos(t.pos[0]+o,t.pos[1]+s),a.push(t)}let u=structuredClone([...e.subgraph.groups].map(e=>e.serialize()));for(let e of u){let t=new X(e.title,e.id);this.add(t,!0),t.configure(e),t.pos[0]+=o,t.pos[1]+=s,a.push(t)}for(let t of e.inputs){if(!t.link)continue;let e=this.links.get(t.link);if(!e){console.warn(`Broken link`,t,t.link);continue}for(let t of K.getReroutes(this,e))t.linkIds.delete(e.id)}for(let t of e.outputs)for(let e of t.links??[]){let n=this.links.get(e);if(!n){console.warn(`Broken link`,t,e);continue}for(let e of K.getReroutes(this,n))e.linkIds.delete(n.id)}let d=[];for(let[,t]of e.subgraph._links){let n;if(t.origin_id===-10){let r=e.inputs[t.origin_slot].link;if(!r){console.error(`Missing Link ID when unpacking`);continue}let i=this.links[r];t.origin_id=i.origin_id,t.origin_slot=i.origin_slot,n=i.parentId}else{let e=l.get(t.origin_id);if(!e){console.error(`Missing Link ID when unpacking`);continue}t.origin_id=e}if(t.target_id===-20){for(let n of e.outputs[t.target_slot].links??[]){let e=this.links[n];d.push({oid:t.origin_id,oslot:t.origin_slot,tid:e.target_id,tslot:e.target_slot,i
2d:t.id,iparent:t.parentId,eparent:e.parentId,externalFirst:!0}),e.parentId=void 0}continue}else{let e=l.get(t.target_id);if(!e){console.error(`Missing Link ID when unpacking`);continue}t.target_id=e}d.push({oid:t.origin_id,oslot:t.origin_slot,tid:t.target_id,tslot:t.target_slot,id:t.id,iparent:t.parentId,eparent:n,externalFirst:!1})}this.remove(e);let f=new Set,p=d.filter(e=>{let t=`${e.oid}\0${e.oslot}\0${e.tid}\0${e.tslot}`;return f.has(t)?!1:(f.add(t),!0)}),m=new Map;for(let e of p){let t;if(e.oid==-10){if(!(this instanceof bt)){console.error(`Ignoring link to subgraph outside subgraph`);continue}let n=this._nodes_by_id[e.tid];t=this.inputNode.slots[e.oslot].connect(n.inputs[e.tslot],n)}else if(e.tid==-20){if(!(this instanceof bt)){console.error(`Ignoring link to subgraph outside subgraph`);continue}let n=this._nodes_by_id[e.oid];t=this.outputNode.slots[e.tslot].connect(n.outputs[e.oslot],n)}else t=this._nodes_by_id[e.oid].connect(e.oslot,this._nodes_by_id[e.tid],e.tslot);if(!t){console.error(`Failed to create link`);continue}let n=m.get(e.id)??[];
2n.push(t.id),m.has(e.id)||m.set(e.id,n),e.id=t.id}let h=new Map;for(let t of e.subgraph.reroutes.values()){t.parentId!==void 0&&h.get(t.parentId)===void 0&&console.error(`Missing Parent ID`);let e=new q(++this.state.lastRerouteId,this,[t.pos[0]+o,t.pos[1]+s]);h.set(t.id,e.id),this.reroutes.set(e.id,e),a.push(e)}for(let t of p){let n=this.links.get(t.id);if(!n)continue;let r=n,i;if(t.externalFirst)for(i=t.eparent;i;){if(r.parentId=i,r=this.reroutes.get(i),!r){console.error(`Broken Id link when unpacking`);break}if(r.linkIds.has(n.id))throw Error(`Infinite parentId loop`);r.linkIds.add(n.id),i=r.parentId}if(r){for(i=t.iparent;i;){let t=h.get(i);if(!t){console.error(`Broken Id link when unpacking`);break}if(r.parentId=t,r=this.reroutes.get(t),!r){console.error(`Broken Id link when unpacking`);break}if(r.linkIds.has(n.id))throw Error(`Infinite parentId loop`);r.linkIds.add(n.id);let a=e.subgraph.reroutes.get(i);if(!a){console.error(`Broken Id link when unpacking`);break}i=a.parentId}if(!r)break;if(!t.externalFirst)for(i=t.eparent;i;){if(r.parentId=i,r=this.reroutes.get(i),!r){console.error(`Broken Id link when unpacking`);break}if(r.linkIds.has(n.id))throw Error(`Infinite parentId loop`);r.linkIds.add(n.id),i=r.parentId}}}for(let e of l.values()){let t=this._nodes_by_id[e];t._setConcreteSlots(),t.arrange()}this.canvasAction(e=>e.selectItems(a))}resolveSubgraphIdPath(e){let t=[],n=this.rootGraph;for(let r of e){let i=n.getNodeById(r);if(!i)throw Error(`Node [${r}] not found.  ID Path: ${e.join(`:`)}`);if(!i.isSubgraphNode())throw Error(`Node [${r}] is not a SubgraphNode.  ID Path: ${e.join(`:`)}`);t.push(i),n=i.subgraph}return t}serialize(e){let{config:t,state:n,groups:r,nodes:i,reroutes:a,extra:o,floatingLinks:s,definitions:c}=this.asSerialisable(e),l=[...this._links.values()],u=l.map(e=>e.serialize());return a?.length&&(o.linkExtensions=l.filter(e=>e.parentId!==void 0).map(e=>({id:e.id,parentId:e.parentId}))),o.reroutes=a?.length?a:void 0,{id:this.id,revision:this.revision,last_node_id:n.lastNodeId,last_link_id:n.lastLinkId,nodes:i,links:u,floatingLinks:s,groups:r,definitions:c,config:t,extra:o,version:Q.VERSION}}toJSON(){return this.serialize()}_getDragAndScale(){let e=this.list_of_graphcanvas?.at(0)?.ds;if(e)return{scale:e.scale,offset:e.offset}}asSerialisable(e){let{id:t,revision:n,config:r,state:i}=this,a=(!Q.use_uuids&&e?.sortNodes?[...this._nodes].sort((e,t)=>e.id-t.id):this._nodes).map(e=>e.serialize()),o=this._groups.map(e=>e.serialize()),s=this._links.size?[...this._links.values()].map(e=>e.asSerialisable()):void 0,c=this.floatingLinks.size?[...this.floatingLinks.values()].map(e=>e.asSerialisable()):void 0,l=this.reroutes.size?[...this.reroutes.values()].map(e=>e.asSerialisable()):void 0,u={...this.extra};Q.saveViewportWithGraph&&(u.ds=this._getDragAndScale()),u.ds||delete u.ds;let d={id:t,revision:n,version:LGraph.serialisedSchemaVersion,config:r,state:i,groups:o,nodes:a,links:s,floatingLinks:c,reroutes:l,extra:u};if(this.isRootGraph&&this._subgraphs.size){let e=findUsedSubgraphIds(this,this._subgraphs),t=[...this._subgraphs.values()].filter(t=>e.has(t.id)).map(e=>e.asSerialisable());t.length>0&&(d.definitions={subgraphs:t})}return this.onSerialize?.(d),d}_configureBase(e){let{id:t,extra:n}=e;t&&!(this.isRootGraph&&t===`00000000-0000-0000-0000-000000000000`)?this.id=t:this.id===`00000000-0000-0000-0000-000000000000`&&(this.id=createUuidv4()),this.extra=n?structuredClone(n):{},delete this.extra.linkExtensions}configure(e,t){let n=useLayoutMutations(),r={data:e,clearGraph:!t};if(this.events.dispatch(`configuring`,r))try{if(!e)return;r.clearGraph&&this.clear(),this._configureBase(e);let t;if(e.version===.4){let{extra:n}=e;if(Array.isArray(e.links))for(let t of e.links){let e=K.createFromArray(t);this._links.set(e.id,e)}if(Array.isArray(n?.linkExtensions))for(let e of n.linkExtensions){let t=this._links.get(e.id);t&&(t.parentId=e.parentId)}t=n?.reroutes}else{if(e.state){let{lastGroupId:t,lastLinkId:n,lastNodeId:r,lastRerouteId:i}=e.state,{state:a}=this;t!=null&&(a.lastGroupId=Math.max(a.lastGroupId,t)),n!=null&&(a.lastLinkId=Math.max(a.lastLinkId,n)),r!=null&&(a.lastNodeId=Math.max(a.lastNodeId,r)),i!=null&&(a.lastRerouteId=Math.max(a.lastRerouteId,i))}if(Array.isArray(e.links))for(let t of e.links){let e=K.create(t);this._links.set(e.id,e)}t=e.reroutes}if(Array.isArray(t))for(let e of t)this.setReroute(e);let i=e.nodes;for(let t in e)LGraph.ConfigureProperties.has(t)||(this[t]=e[t]);let a=e.definitions?.subgraphs,o=i;if(a){let e=new Set;for(let t of this._nodes)typeof t.id==`number`&&e.add(t.id);for(let t of this.subgraphs.values())for(let n of t.nodes)typeof n.id==`number`&&e.add(n.id);for(let t of i??[])typeof t.id==`number`&&e.add(t.id);let t=this.isRootGraph?deduplicateSubgraphNodeIds(a,e,this.state,i):void 0,n=t?.subgraphs??a;o=t?.rootNodes??i;for(let e of n)this.createSubgraph(e);let r=topologicalSortSubgraphs(n);for(let e of r)this.subgraphs.get(e.id)?.configure(e)}let s=!1,c=new Map;if(this._nodes=[],o){for(let e of o){let t=Q.createNode(String(e.type),e.title);t||(Q.debug&&console.warn(`Node not found or has errors:`,e.type),t=new Y(``),t.last_serialization=e,t.has_errors=!0,s=!0),t.id=e.id,this.add(t,!0),c.set(t.id,e)}for(let[e,t]of c){let n=this.getNodeById(e);
2if(n?.configure(t),Q.alwaysSnapToGrid&&n){let e=this.getSnapToGridSize();n.snapToGrid(e)&&(n.pos=[n.pos[0],n.pos[1]]),snapPoint(n.size,e,`ceil`)}}}if(Array.isArray(e.floatingLinks))for(let t of e.floatingLinks){let e=K.create(t);this.addFloatingLink(e),e.id>this._lastFloatingLinkId&&(this._lastFloatingLinkId=e.id)}for(let e of this.reroutes.values())e.validateLinks(this._links,this.floatingLinks)||(this.reroutes.delete(e.id),n.setSource(H.Canvas),n.deleteReroute(e.id));this._removeDuplicateLinks(),this._groups.length=0;let l=e.groups;if(l)for(let e of l){let t=new Q.LGraphGroup;t.configure(e),this.add(t)}this.updateExecutionOrder(),this.onConfigure?.(e),this.incrementVersion();let{primaryCanvas:u}=this,d=u?.subgraph?.id;if(d){let e=this.subgraphs.get(d);e?u.setGraph(e):u.setGraph(this)}return this.setDirtyCanvas(!0,!0),s}finally{this.events.dispatch(`configured`)}}ensureGlobalIdUniqueness(e){let{state:t}=this,n=[this,...this._subgraphs.values()],r=new Set(e);for(let e of n){let n=new Map;for(let i of e._nodes)if(typeof i.id==`number`)if(r.has(i.id)){let a=i.id;for(;r.has(++t.lastNodeId););let o=t.lastNodeId;delete e._nodes_by_id[a],i.id=o,e._nodes_by_id[o]=i,r.add(o),n.set(a,o),console.warn(`LiteGraph: duplicate node ID ${a} reassigned to ${o} in graph ${e.id}`)}else r.add(i.id),i.id>t.lastNodeId&&(t.lastNodeId=i.id);n.size>0&&(patchLinkNodeIds(e._links,n),patchLinkNodeIds(e.floatingLinksInternal,n))}}_canvas;get primaryCanvas(){return this.rootGraph._canvas}set primaryCanvas(e){this.rootGraph._canvas=e}load(e,t){if(e instanceof Blob||e instanceof File){let n=new FileReader;n.addEventListener(`load`,e=>{let n=p(e.target?.result),r=JSON.parse(n);this.configure(r),t?.()}),n.readAsText(e);return}let n=new XMLHttpRequest;n.open(`GET`,e,!0),n.send(null),n.addEventListener(`load`,()=>{if(n.status!==200){console.error(`Error loading graph:`,n.status,n.response);return}let e=JSON.parse(n.response);this.configure(e),t?.()}),n.addEventListener(`error`,e=>{console.error(`Error loading graph:`,e)})}},bt=class Subgraph extends yt{events=new CustomEventTarget;static MAX_NESTED_SUBGRAPHS=1e3;name=`Unnamed Subgraph`;description;inputNode=new SubgraphInputNode(this);outputNode=new SubgraphOutputNode(this);inputs=[];outputs=[];widgets=[];_rootGraph;get rootGraph(){return this._rootGraph}get state(){return this._rootGraph.state}set state(e){}constructor(e,t){if(!e)throw Error(`Root graph is required`);super(),this._rootGraph=e;let n=structuredClone(t);this._configureBase(n),this._configureSubgraph(n)}getIoNodeOnPos(e,t){let{inputNode:n,outputNode:r}=this;if(n.containsPoint([e,t]))return n;if(r.containsPoint([e,t]))return r}_configureSubgraph(e){let{name:t,description:n,inputs:r,outputs:i,widgets:a}=e;if(this.name=t,this.description=n,r){this.inputs.length=0;for(let e of r){let t=new SubgraphInput(e,this.inputNode);this.inputs.push(t),this.events.dispatch(`input-added`,{input:t})}}if(i){this.outputs.length=0;for(let e of i)this.outputs.push(new SubgraphOutput(e,this.outputNode))}if(this._repairIOSlotLinkIds(),a){this.widgets.length=0;for(let e of a)this.widgets.push(e)}this.inputNode.configure(e.inputNode),this.outputNode.configure(e.outputNode);for(let e of this.nodes)e.updateComputedDisabled()}configure(e,t){let n=super.configure(e,t);return this._configureSubgraph(e),n}_repairIOSlotLinkIds(){for(let[e,t]of this.inputs.entries())this._repairSlotLinkIds(t.linkIds,-10,e);for(let[e,t]of this.outputs.entries())this._repairSlotLinkIds(t.linkIds,-20,e)}_repairSlotLinkIds(e,t,n){e.map(e=>this._links.has(e)?e:this._findLinkBySlot(t,n)?.id??e).forEach((t,n)=>{e[n]=t})}_findLinkBySlot(e,t){for(let n of this._links.values())if(n.origin_id===e&&n.origin_slot===t||n.target_id===e&&n.target_slot===t)return n}attachCanvas(e){super.attachCanvas(e),e.subgraph=this}addInput(e,t){if(e===null||t===null)throw Error(`Name and type are required for subgraph input`);this.events.dispatch(`adding-input`,{name:e,type:t});let n=new SubgraphInput({id:createUuidv4(),name:e,type:t},this.inputNode);return this.inputs.push(n),this.events.dispatch(`input-added`,{input:n}),n}addOutput(e,t){if(e===null||t===null)throw Error(`Name and type are required for subgraph output`);this.events.dispatch(`adding-output`,{name:e,type:t});let n=new SubgraphOutput({id:createUuidv4(),name:e,type:t},this.outputNode);
2return this.outputs.push(n),this.events.dispatch(`output-added`,{output:n}),n}renameInput(e,t){let n=this.inputs.indexOf(e);if(n===-1)throw Error(`Input not found`);let r=e.displayName;this.events.dispatch(`renaming-input`,{input:e,index:n,oldName:r,newName:t}),e.label=t}renameOutput(e,t){let n=this.outputs.indexOf(e);if(n===-1)throw Error(`Output not found`);let r=e.displayName;this.events.dispatch(`renaming-output`,{output:e,index:n,oldName:r,newName:t}),e.label=t}removeInput(e){let t=this.inputs.indexOf(e);if(t===-1)throw Error(`Input not found`);if(!this.events.dispatch(`removing-input`,{input:e,index:t}))return;e.disconnect(),this.inputs.splice(t,1);let{length:n}=this.inputs;for(let e=t;e<n;e++)this.inputs[e].decrementSlots(`inputs`)}removeOutput(e){let t=this.outputs.indexOf(e);if(t===-1)throw Error(`Output not found`);if(!this.events.dispatch(`removing-output`,{output:e,index:t}))return;e.disconnect(),this.outputs.splice(t,1);let{length:n}=this.outputs;for(let e=t;e<n;e++)this.outputs[e].decrementSlots(`outputs`)}draw(e,t,n,r){this.inputNode.draw(e,t,n,r),this.outputNode.draw(e,t,n,r)}clone(e=!1){let t=this.asSerialisable();e||(t.id=createUuidv4());let n=new Subgraph(this.rootGraph,t);return n.configure(t),n}asSerialisable(){return{id:this.id,version:yt.serialisedSchemaVersion,state:this.state,revision:this.revision,config:this.config,name:this.name,...this.description&&{description:this.description},inputNode:this.inputNode.asSerialisable(),outputNode:this.outputNode.asSerialisable(),inputs:this.inputs.map(e=>e.asSerialisable()),outputs:this.outputs.map(e=>e.asSerialisable()),widgets:[...this.widgets],nodes:this.nodes.map(e=>e.serialize()),groups:this.groups.map(e=>e.serialize()),links:[...this.links.values()].map(e=>e.asSerialisable()),reroutes:this.reroutes.size?[...this.reroutes.values()].map(e=>e.asSerialisable()):void 0,extra:this.extra}}};function patchLinkNodeIds(e,t){for(let n of e.values()){let e=t.get(n.origin_id);e!==void 0&&(n.origin_id=e);let r=t.get(n.target_id);r!==void 0&&(n.target_id=r)}}var InputIndicators=class{radius=8;startAngle=0;endAngle=Math.PI*2;inactiveColour=`#ffffff10`;colour1=`#ff5f00`;colour2=`#00ff7c`;colour3=`#dea7ff`;fontString=`bold 12px Inter, sans-serif`;enabled=!0;shiftDown=!1;undoDown=!1;redoDown=!1;ctrlDown=!1;altDown=!1;mouse0Down=!1;mouse1Down=!1;mouse2Down=!1;x=0;y=0;controller;constructor(e){this.canvas=e,this.controller=new AbortController;let{signal:t}=this.controller,n=e.canvas,r={capture:!0,signal:t};n.addEventListener(`pointerdown`,this._onPointerDownOrMove,r),n.addEventListener(`pointermove`,this._onPointerDownOrMove,r),n.addEventListener(`pointerup`,this._onPointerUp,r),n.addEventListener(`keydown`,this._onKeyDownOrUp,r),document.addEventListener(`keyup`,this._onKeyDownOrUp,r);let i=e.drawFrontCanvas.bind(e);t.addEventListener(`abort`,()=>{e.drawFrontCanvas=i}),e.drawFrontCanvas=()=>{i(),this.draw()}}_onPointerDownOrMove=this.onPointerDownOrMove.bind(this);onPointerDownOrMove(e){this.mouse0Down=(e.buttons&1)==1,this.mouse1Down=(e.buttons&4)==4,this.mouse2Down=(e.buttons&2)==2,this.x=e.clientX,this.y=e.clientY,this.canvas.setDirty(!0)}_onPointerUp=this.onPointerUp.bind(this);onPointerUp(){this.mouse0Down=!1,this.mouse1Down=!1,this.mouse2Down=!1}_onKeyDownOrUp=this.onKeyDownOrUp.bind(this);onKeyDownOrUp(e){this.ctrlDown=e.ctrlKey,this.altDown=e.altKey,this.shiftDown=e.shiftKey,this.undoDown=e.ctrlKey&&e.code===`KeyZ`&&e.type===`keydown`,this.redoDown=e.ctrlKey&&e.code===`KeyY`&&e.type===`keydown`}draw(){let{canvas:{ctx:e},radius:t,startAngle:n,endAngle:r,x:i,y:a,inactiveColour:o,colour1:s,colour2:c,colour3:l,fontString:u}=this,{fillStyle:d,font:f}=e,p=i,m=a-80,h=p,g=m-15;e.font=u,textMarker(h+0,g,`Shift`,this.shiftDown?s:o),textMarker(h+45,g+20,`Alt`,this.altDown?c:o),textMarker(h+30,g,`Control`,this.ctrlDown?l:o),textMarker(h-30,g,`↩️`,this.undoDown?`#000`:`transparent`),textMarker(h+45,g,`↪️`,this.redoDown?`#000`:`transparent`),e.beginPath(),drawDot(p,m),drawDot(p+15,m),drawDot(p+30,m),e.fillStyle=o,e.fill();let _=this.mouse0Down?s:o,v=this.mouse1Down?c:o,y=this.mouse2Down?l:o;this.mouse0Down&&mouseMarker(p,m,_),this.mouse1Down&&mouseMarker(p+15,m,v),this.mouse2Down&&mouseMarker(p+30,m,y),e.fillStyle=d,e.font=f;function textMarker(t,n,r,i){e.fillStyle=i,e.fillText(r,t,n)}function mouseMarker(t,n,r){e.beginPath(),e.fillStyle=r,drawDot(t,n),e.fill()}function drawDot(i,a){e.arc(i,a,t,n,r)}}dispose(){this.controller?.abort(),this.controller=void 0}[Symbol.dispose](){this.dispose()}}
2,LiteGraphGlobal=class{SlotShape=Ge;SlotDirection=Ke;SlotType=We;LabelPosition=qe;VERSION=.4;CANVAS_GRID_SIZE=10;NODE_TITLE_HEIGHT=30;NODE_TITLE_TEXT_Y=20;NODE_SLOT_HEIGHT=20;NODE_WIDGET_HEIGHT=20;NODE_WIDTH=140;NODE_MIN_WIDTH=50;NODE_COLLAPSED_RADIUS=10;NODE_COLLAPSED_WIDTH=80;NODE_TITLE_COLOR=`#999`;NODE_SELECTED_TITLE_COLOR=`#FFF`;NODE_TEXT_SIZE=14;NODE_TEXT_COLOR=`#AAA`;NODE_TEXT_HIGHLIGHT_COLOR=`#EEE`;NODE_SUBTEXT_SIZE=12;NODE_DEFAULT_COLOR=`#333`;NODE_DEFAULT_BGCOLOR=`#353535`;NODE_DEFAULT_BOXCOLOR=`#666`;NODE_DEFAULT_SHAPE=P.ROUND;NODE_BOX_OUTLINE_COLOR=`#FFF`;NODE_ERROR_COLOUR=`#E00`;NODE_FONT=`Inter`;NODE_DEFAULT_BYPASS_COLOR=`#FF00FF`;NODE_OPACITY=.9;DEFAULT_FONT=`Inter`;DEFAULT_SHADOW_COLOR=`rgba(0,0,0,0.5)`;GROUP_TEXT_SIZE=20;GROUP_FONT=`Inter`;WIDGET_BGCOLOR=`#222`;WIDGET_OUTLINE_COLOR=`#666`;WIDGET_PROMOTED_OUTLINE_COLOR=`#BF00FF`;WIDGET_ADVANCED_OUTLINE_COLOR=`rgba(56, 139, 253, 0.8)`;WIDGET_TEXT_COLOR=`#DDD`;WIDGET_SECONDARY_TEXT_COLOR=`#999`;WIDGET_DISABLED_TEXT_COLOR=`#666`;LINK_COLOR=`#9A9`;EVENT_LINK_COLOR=`#A86`;CONNECTING_LINK_COLOR=`#AFA`;MAX_NUMBER_OF_NODES=1e4;DEFAULT_POSITION=[100,100];VALID_SHAPES=[`default`,`box`,`round`,`card`];ROUND_RADIUS=8;BOX_SHAPE=P.BOX;ROUND_SHAPE=P.ROUND;CIRCLE_SHAPE=P.CIRCLE;CARD_SHAPE=P.CARD;ARROW_SHAPE=P.ARROW;GRID_SHAPE=P.GRID;INPUT=N.INPUT;OUTPUT=N.OUTPUT;EVENT=-1;ACTION=-1;NODE_MODES=[`Always`,`On Event`,`Never`,`On Trigger`];NODE_MODES_COLORS=[`#666`,`#422`,`#333`,`#224`,`#626`];ALWAYS=B.ALWAYS;ON_EVENT=B.ON_EVENT;NEVER=B.NEVER;ON_TRIGGER=B.ON_TRIGGER;UP=I.UP;DOWN=I.DOWN;LEFT=I.LEFT;RIGHT=I.RIGHT;CENTER=I.CENTER;LINK_RENDER_MODES=[`Straight`,`Linear`,`Spline`];HIDDEN_LINK=L.HIDDEN_LINK;STRAIGHT_LINK=L.STRAIGHT_LINK;LINEAR_LINK=L.LINEAR_LINK;SPLINE_LINK=L.SPLINE_LINK;NORMAL_TITLE=z.NORMAL_TITLE;NO_TITLE=z.NO_TITLE;TRANSPARENT_TITLE=z.TRANSPARENT_TITLE;AUTOHIDE_TITLE=z.AUTOHIDE_TITLE;VERTICAL_LAYOUT=`vertical`;proxy=null;node_images_path=``;debug=!1;catch_exceptions=!0;throw_errors=!0;allow_scripts=!1;registered_node_types={};node_types_by_file_extension={};Nodes={};Globals={};searchbox_extras={};node_box_coloured_when_on=!1;node_box_coloured_by_mode=!1;dialog_close_on_mouse_leave=!1;dialog_close_on_mouse_leave_delay=500;shift_click_do_break_link_from=!1;click_do_break_link_to=!1;ctrl_alt_click_do_break_link=!0;snaps_for_comfy=!0;snap_highlights_node=!0;alwaysSnapToGrid;snapToGrid;search_hide_on_mouse_leave=!0;search_filter_enabled=!1;search_show_all_on_open=!0;auto_load_slot_types=!1;registered_slot_in_types={};registered_slot_out_types={};slot_types_in=[];slot_types_out=[];slot_types_default_in={};slot_types_default_out={};alt_drag_do_clone_nodes=!1;do_add_triggers_slots=!1;allow_multi_output_for_events=!0;middle_click_slot_add_default_node=!1;release_link_on_empty_shows_menu=!1;pointerevents_method=`pointer`;ctrl_shift_v_paste_connect_unselected_outputs=!0;use_uuids=!1;highlight_selected_group=!0;context_menu_scaling=!1;alwaysRepeatWarnings=!1;onDeprecationWarning=[console.warn];macTrackpadGestures=!1;macGesturesRequireMac=!0;canvasNavigationMode=`legacy`;leftMouseClickBehavior=`panning`;mouseWheelScroll=`panning`;truncateWidgetTextEvenly=!1;truncateWidgetValuesFirst=!1;saveViewportWithGraph=!0;vueNodesMode=!1;nodeOpacity=1;nodeLightness=void 0;LGraph=yt;LLink=K;LGraphNode=Y;LGraphGroup=X;DragAndScale=DragAndScale;LGraphCanvas=Z;ContextMenu=xe;CurveEditor=CurveEditor;Reroute=q;constructor(){Object.defineProperty(this,`Classes`,{writable:!1})}Classes={get SubgraphSlot(){return Ze},get SubgraphIONodeBase(){return Qe},get Rectangle(){return G},get InputIndicators(){return InputIndicators}};registerNodeType(e,t){if(!t.prototype)throw`Cannot register a simple object, it must be a class with a prototype`;t.type=e;let n=t.name,r=e.lastIndexOf(`/`);t.category=e.substring(0,r),t.title||=n;for(let e in Y.prototype)t.prototype[e]||=Y.prototype[e];let i=this.registered_node_types[e];i&&this.debug&&console.warn(`replacing node type:`,e),this.registered_node_types[e]=t,t.constructor.name&&(this.Nodes[n]=t),this.onNodeTypeRegistered?.(e,t),i&&this.onNodeTypeReplaced?.(e,t,i),t.prototype.onPropertyChange&&console.warn(`LiteGraph node class ${e} has onPropertyChange method, it must be called onPropertyChanged with d at the end`),this.auto_load_slot_types&&new t(t.title||`tmpnode`)}unregisterNodeType(e){let t=typeof e==`string`?this.registered_node_types[e]:e;if(!t)throw`node type not found: ${String(e)}`;delete this.registered_node_types[String(t.type)];let n=t.constructor.name;n&&delete this.Nodes[n]}registerNodeAndSlotType(e,t,n){n||=!1;let r=(typeof e==`string`&&this.registered_node_types[e]!==`anonymous`?this.registered_node_types[e]:e).constructor.type,i=[];i=typeof t==`string`?t.split(`,`):t==this.EVENT||t==this.ACTION?[`_event_`]:[`*`];for(let e of i){e===``&&(e=`*`);let t=n?this.registered_slot_out_types:this.registered_slot_in_types;t[e]??={nodes:[]};let{nodes:i}=t[e];i.includes(r)||i.push(r);let a=n?this.slot_types_out:this.slot_types_in,o=e.toLowerCase();a.includes(o)||(a.push(o),a.sort())}}clearRegisteredTypes(){this.registered_node_types={},this.node_types_by_file_extension={},this.Nodes={},this.searchbox_extras={}}createNode(e,t,n){let r=this.registered_node_types[e];if(!r)return this.debug&&console.warn(`GraphNode type "${e}" not registered.`),null;t=t||r.title||e;let i=null;if(this.catch_exceptions)try{i=new r(t)}catch(e){return console.error(e),null}else i=new r(t);return i.type=e,!i.title&&t&&(i.title=t),i.properties||={},i.properties_info||=[],i.flags||={},i.size||=i.computeSize(),i.pos||=[this.DEFAULT_POSITION[0],this.DEFAULT_POSITION[1]],i.mode||=B.ALWAYS,n&&Object.assign(i,n),i.onNodeCreated?.(),i}getNodeType(e){return this.registered_node_types[e]}getNodeTypesInCategory(e,t){let n=[];for(let r in this.registered_node_types){let i=this.registered_node_types[r];i.filter==t&&(e==``?i.category??n.push(i):i.category==e&&n.push(i))}return n}getNodeTypesCategories(e){let t={"":1};for(let n in this.registered_node_types){let r=this.registered_node_types[n];if(r.category&&!r.skip_list){if(r.filter!=e)continue;t[r.category]=1}}let n=[];for(let e in t)n.push(e);return n}reloadNodes(e){let t=document.getElementsByTagName(`script`),n=[];for(let e of t)n.push(e);let r=document.getElementsByTagName(`head`)[0];e=document.location.href+e;for(let t of n){let n=t.src;if(!(!n||n.substr(0,e.length)!=e))try{let e=document.createElement(`script`);e.type=`text/javascript`,e.src=n,r.append(e),t.remove()}catch(e){if(this.throw_errors)throw e;this.debug&&console.error(`Error while reloading`,n)}}}cloneObject(e,t){if(e==null)return null;let n=JSON.parse(JSON.stringify(e));if(!t)return n;for(let e in n)t[e]=n[e];return t}uuidv4=createUuidv4;isValidConnection(e,t){if((e==``||e===`*`)&&(e=0),(t==``||t===`*`)&&(t=0),!e||!t||e==t||e==this.EVENT&&t==this.ACTION)return!0;
2if(e=String(e),t=String(t),e=e.toLowerCase(),t=t.toLowerCase(),!e.includes(`,`)&&!t.includes(`,`))return e==t;let n=e.split(`,`),r=t.split(`,`);for(let e of n)for(let t of r)if(this.isValidConnection(e,t))return!0;return!1}getParameterNames(e){return String(e).replaceAll(/\/\/.*$/gm,``).replaceAll(/\s+/g,``).replaceAll(/\/\*[^*/]*\*\//g,``).split(`){`,1)[0].replace(/^[^(]*\(/,``).replaceAll(/=[^,]+/g,``).split(`,`).filter(Boolean)}pointerListenerAdd(e,t,n,r=!1){if(!e||!e.addEventListener||!t||typeof n!=`function`)return;let i=this.pointerevents_method,a=t;if(i==`pointer`&&!window.PointerEvent)switch(console.warn(`sMethod=='pointer' && !window.PointerEvent`),console.warn(`Converting pointer[${a}] : down move up cancel enter TO touchstart touchmove touchend, etc ..`),a){case`down`:i=`touch`,a=`start`;break;case`move`:i=`touch`;break;case`up`:i=`touch`,a=`end`;break;case`cancel`:i=`touch`;break;case`enter`:break;default:console.warn(`PointerEvent not available in this browser ? The event ${a} would not be called`)}switch(a){case`down`:case`up`:case`move`:case`over`:case`out`:case`enter`:e.addEventListener(i+a,n,r);case`leave`:case`cancel`:case`gotpointercapture`:case`lostpointercapture`:if(i!=`mouse`)return e.addEventListener(i+a,n,r);default:return e.addEventListener(a,n,r)}}pointerListenerRemove(e,t,n,r=!1){if(!(!e||!e.removeEventListener||!t||typeof n!=`function`))switch(t){case`down`:case`up`:case`move`:case`over`:case`out`:case`enter`:(this.pointerevents_method==`pointer`||this.pointerevents_method==`mouse`)&&e.removeEventListener(this.pointerevents_method+t,n,r);case`leave`:case`cancel`:case`gotpointercapture`:case`lostpointercapture`:if(this.pointerevents_method==`pointer`)return e.removeEventListener(this.pointerevents_method+t,n,r);default:return e.removeEventListener(t,n,r)}}getTime(){return performance.now()}distance=distance;colorToString(e){return`rgba(${Math.round(e[0]*255).toFixed()},${Math.round(e[1]*255).toFixed()},${Math.round(e[2]*255).toFixed()},${e.length==4?e[3].toFixed(2):`1.0`})`}isInsideRectangle=isInsideRectangle;growBounding(e,t,n){t<e[0]?e[0]=t:t>e[2]&&(e[2]=t),n<e[1]?e[1]=n:n>e[3]&&(e[3]=n)}overlapBounding=overlapBounding;isInsideBounding(e,t){return!(e[0]<t[0][0]||e[1]<t[0][1]||e[0]>t[1][0]||e[1]>t[1][1])}hex2num(e){e.charAt(0)==`#`&&(e=e.slice(1)),e=e.toUpperCase();let t=`0123456789ABCDEF`,n=[,,,],r=0,i,a;for(let o=0;o<6;o+=2)i=t.indexOf(e.charAt(o)),a=t.indexOf(e.charAt(o+1)),n[r]=i*16+a,r++;return n}num2hex(e){let t=`0123456789ABCDEF`,n=`#`,r,i;for(let a=0;a<3;a++)r=e[a]/16,i=e[a]%16,n+=t.charAt(r)+t.charAt(i);return n}closeAllContextMenus(e=window){let t=[...e.document.querySelectorAll(`.litecontextmenu`)];if(t.length)for(let e of t)`close`in e&&typeof e.close==`function`?e.close():e.remove()}extendClass(e,t){for(let n in t)e.hasOwnProperty(n)||(e[n]=t[n]);if(t.prototype&&e.prototype){let n=t.prototype,r=e.prototype;for(let e in n){if(!n.hasOwnProperty(e)||r.hasOwnProperty(e))continue;let t=Object.getOwnPropertyDescriptor(n,e);t&&Object.defineProperty(r,e,t)}}}};Symbol.dispose??=Symbol(`Symbol.dispose`),Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);function loadPolyfills(){typeof window<`u`&&window.CanvasRenderingContext2D&&!window.CanvasRenderingContext2D.prototype.roundRect&&(window.CanvasRenderingContext2D.prototype.roundRect=function(e,t,n,r,i,a){let o=0,s=0,c=0,l=0;if(i===0){this.rect(e,t,n,r);return}if(a===void 0&&(a=i),Array.isArray(i))if(i.length==1)o=s=c=l=i[0];else if(i.length==2)o=l=i[0],s=c=i[1];else if(i.length==4)o=i[0],s=i[1],c=i[2],l=i[3];else return;else{o=i||0,s=i||0;let e=!Array.isArray(a)&&a?a:0;c=e,l=e}this.moveTo(e+o,t),this.lineTo(e+n-s,t),this.quadraticCurveTo(e+n,t,e+n,t+s),this.lineTo(e+n,t+r-l),this.quadraticCurveTo(e+n,t+r,e+n-l,t+r),this.lineTo(e+l,t+r),this.quadraticCurveTo(e,t+r,e,t+r-c),this.lineTo(e,t+c),this.quadraticCurveTo(e,t,e+o,t)}),typeof window<`u`&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){window.setTimeout(e,1e3/60)})}var Q=new LiteGraphGlobal;loadPolyfills();var xt=E([`LG`,`Vue`,`Vue-corrected`]),$=S([D().int(),w()]),St=w(),Ct=S([D().int(),w().transform(e=>parseInt(e)).refine(e=>!isNaN(e),{message:`Invalid number`})]),wt=S([w(),A(w()),D()]),Tt=S([C({0:D(),1:D()}).passthrough().transform(e=>[e[0],e[1]]),j([D(),D()])]),Et=C({name:w(),url:w().url(),hash:w().optional(),hash_type:w().optional(),directory:w()}),Dt=C({lastGroupId:D(),lastNodeId:D(),lastLinkId:D(),lastRerouteId:D()}).passthrough(),Ot=j([D(),$,Ct,$,Ct,wt]),kt=C({id:D(),parentId:D()}).passthrough(),At=C({id:D(),origin_id:$,origin_slot:Ct,target_id:$,target_slot:Ct,type:wt,parentId:D().optional()}).passthrough(),jt=C({id:D(),parentId:D().optional(),pos:Tt,linkIds:A(D()).nullish(),floating:C({slotType:E([`input`,`output`])}).optional()}).passthrough(),Mt=C({name:w(),type:wt,links:A(D()).nullable().optional(),slot_index:Ct.optional()}).passthrough(),Nt=C({name:St,type:wt,link:D().nullable().optional(),slot_index:Ct.optional()}).passthrough(),Pt=C({collapsed:T().optional(),pinned:T().optional(),allow_interaction:T().optional(),horizontal:T().optional(),skip_repeated_outputs:T().optional()}).passthrough(),Ft=/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/,It=/^(?!-)(?!.*--)[a-zA-Z0-9-]+(?<!-)$/,Lt=/^[0-9a-f]{4,40}$/i,Rt=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?(?:\+([\da-z-]+(?:\.[\da-z-]+)*))?$/,zt=w().min(1).max(100).regex(Ft,{message:`ID can only contain ASCII letters, digits, '_', '-', and '.'`}).refine(e=>!/^[_\-.]|[_\-.]$/.test(e),{message:`ID must not start or end with '_', '-', or '.'`}),Bt=zt,Vt=zt,Ht=w().min(1).max(39).regex(It,`Invalid GitHub username/org`),Ut=w().regex(/^[^/]+\/[^/]+$/,`Invalid format. Must be 'github-user/repo-name'`).transform(e=>e.split(`/`)).refine(([e,t])=>Ht.safeParse(e).success&&Vt.safeParse(t).success,`Invalid aux_id: Must be valid 'github-username/github-repo-name'`).transform(([e,t])=>`${e}/${t}`),Wt=w().superRefine((e,t)=>
2{Lt.test(e)||t.addIssue({code:ae.custom,message:`Node pack version has invalid Git commit hash: "${e}"`})}),Gt=w().superRefine((e,t)=>{Rt.test(e)||t.addIssue({code:ae.custom,message:`Node pack version has invalid semantic version: "${e}"`})}),Kt=S([w().transform(e=>e.replace(/^v/,``)).pipe(S([Gt,Wt])),k(`unknown`)]),qt=C({"Node name for S&R":w().optional(),cnr_id:Bt.optional(),aux_id:Ut.optional(),ver:Kt.optional(),models:A(Et).optional()}).passthrough(),Jt=S([A(O()),M(O())]),Yt=C({id:$,type:w(),pos:Tt,size:Tt,flags:Pt,order:D(),mode:D(),inputs:A(Nt).optional(),outputs:A(Mt).optional(),properties:qt,widgets_values:Jt.optional(),color:w().optional(),bgcolor:w().optional()}).passthrough(),Xt=Nt.extend({id:w().uuid(),type:w(),linkIds:A(D()).optional()}),Zt=C({id:$,type:w().uuid(),pos:Tt,size:Tt,flags:Pt,order:D(),mode:D(),inputs:A(Xt).optional(),outputs:A(Xt).optional(),widgets_values:Jt.optional(),color:w().optional(),bgcolor:w().optional()}).passthrough(),Qt=C({id:D().optional(),title:w(),bounding:j([D(),D(),D(),D()]),color:w().optional(),font_size:D().optional(),locked:T().optional()}).passthrough(),$t=C({scale:D(),offset:Tt}).passthrough(),en=C({links_ontop:T().optional(),align_to_grid:T().optional()}).passthrough(),tn=C({ds:$t.optional(),frontendVersion:w().optional(),linkExtensions:A(kt).optional(),reroutes:A(jt).optional(),workflowRendererVersion:xt.optional(),BlueprintDescription:w().optional(),BlueprintSearchAliases:A(w()).optional(),linearMode:T().optional(),linearData:C({inputs:A(S([j([$,w(),C({height:D().optional()}).passthrough()]),j([$,w()])])).optional(),outputs:A($).optional()}).optional()}).passthrough(),nn=C({subgraphs:oe(()=>A(ln))}),rn=C({id:w().uuid().optional(),revision:D().optional(),config:en.optional().nullable(),subgraphs:A(Zt).optional()}),an=rn.extend({id:w().uuid().optional(),revision:D().optional(),last_node_id:$,last_link_id:D(),nodes:A(Yt),links:A(Ot),floatingLinks:A(At).optional(),groups:A(Qt).optional(),config:en.optional().nullable(),extra:tn.optional().nullable(),version:D(),models:A(Et).optional(),definitions:nn.optional()}).passthrough(),on=rn.extend({id:w().uuid().optional(),revision:D().optional(),version:k(1),config:en.optional().nullable(),state:Dt,groups:A(Qt).optional(),nodes:A(Yt),links:A(At).optional(),floatingLinks:A(At).optional(),reroutes:A(jt).optional(),extra:tn.optional().nullable(),models:A(Et).optional(),definitions:C({subgraphs:oe(()=>A(ln))}).optional()}).passthrough(),sn=C({id:$,bounding:j([D(),D(),D(),D()]),pinned:T().optional()}),cn=C({id:w(),name:w()}),ln=on.extend({id:w().uuid(),revision:D(),name:w(),description:w().optional(),category:w().optional(),essentials_category:w().optional(),inputNode:sn,outputNode:sn,inputs:A(Xt).optional(),outputs:A(Xt).optional(),widgets:A(cn).optional(),definitions:C({subgraphs:oe(()=>ln.array())}).optional()}).passthrough(),un=C({version:D()});async function validateComfyWorkflow(e,t=console.warn){let n=un.safeParse(e),r;if(n.success)r=n.data.version===1?await on.safeParseAsync(e):await an.safeParseAsync(e);else return t(`Workflow does not contain a valid version.  Zod error:\n${ce(n.error)}`),null;return r.success?r.data:(t(`Invalid workflow against zod schema:\n${ce(r.error)}`),null)}M($,C({inputs:M(St,S([O(),j([$,Ct])])),class_type:w(),_meta:C({title:w()})}));var dn=C({CLIP:w(),CLIP_VISION:w(),CLIP_VISION_OUTPUT:w(),CONDITIONING:w(),CONTROL_NET:w(),IMAGE:w(),LATENT:w(),MASK:w(),MODEL:w(),STYLE_MODEL:w(),VAE:w(),NOISE:w(),GUIDER:w(),SAMPLER:w(),SIGMAS:w(),TAESD:w()}),fn=C({BACKGROUND_IMAGE:w(),CLEAR_BACKGROUND_COLOR:w(),NODE_TITLE_COLOR:w(),NODE_SELECTED_TITLE_COLOR:w(),NODE_TEXT_COLOR:w(),NODE_TEXT_HIGHLIGHT_COLOR:w(),NODE_DEFAULT_COLOR:w(),NODE_DEFAULT_BGCOLOR:w(),NODE_DEFAULT_BOXCOLOR:w(),NODE_DEFAULT_SHAPE:S([k(Q.BOX_SHAPE),k(Q.ROUND_SHAPE),k(Q.CARD_SHAPE),w()]),NODE_BOX_OUTLINE_COLOR:w(),NODE_BYPASS_BGCOLOR:w(),NODE_ERROR_COLOUR:w(),DEFAULT_SHADOW_COLOR:w(),WIDGET_BGCOLOR:w(),WIDGET_OUTLINE_COLOR:w(),WIDGET_TEXT_COLOR:w(),WIDGET_SECONDARY_TEXT_COLOR:w(),WIDGET_DISABLED_TEXT_COLOR:w(),LINK_COLOR:w(),EVENT_LINK_COLOR:w(),CONNECTING_LINK_COLOR:w(),BADGE_FG_COLOR:w(),BADGE_BG_COLOR:w()}),pn=C({"fg-color":w(),"bg-color":w(),"bg-img":w().optional(),"comfy-menu-bg":w(),"comfy-menu-secondary-bg":w(),"comfy-input-bg":w(),"input-text":w(),"descrip-text":w(),"drag-text":w(),"error-text":w(),"border-color":w(),"tr-even-bg-color":w(),"tr-odd-bg-color":w(),"content-bg":w(),"content-fg":w(),"content-hover-bg":w(),"content-hover-fg":w(),"bar-shadow":w(),"contrast-mix-color":w().optional(),"interface-stroke":w().optional(),"interface-panel-surface":w().optional(),"interface-panel-box-shadow":w().optional(),"interface-panel-drop-shadow":w().optional(),"interface-panel-hover-surface":w().optional(),"interface-panel-selected-surface":w().optional(),"interface-button-hover-surface":w().optional()}),mn=C({node_slot:dn,litegraph_base:fn,comfy_base:pn}),hn=C({node_slot:dn.partial(),litegraph_base:fn.partial(),comfy_base:pn.partial()}),gn=C({id:w(),name:w(),colors:hn,light_theme:T().optional()}).passthrough();C({id:w(),name:w(),colors:mn}).passthrough();var _n=M(gn),vn=C({key:w(),ctrl:T().optional(),alt:T().optional(),shift:T().optional(),meta:T().optional()}),yn=C({commandId:w(),combo:vn,targetElementId:w().optional()}),bn=C({name:w().trim().min(1,`Preset name cannot be empty`),newBindings:A(yn),unsetBindings:A(yn)}),xn=[`fixed`,`increment`,`decrement`,`randomize`],Sn=E([`input`,`output`,`temp`]),Cn=S([w(),D()]),wn=C({route:w().url().or(w().startsWith(`/`)),refresh:D().gte(128).safe().or(D().lte(0).safe()).optional(),response_key:w().optional(),query_params:M(w(),w()).optional(),refresh_button:T().optional(),control_after_refresh:E([`first`,`last`]).optional(),timeout:D().gte(0).optional(),max_retries:D().gte(0).optional()}),Tn=C({placeholder:w().optional(),chip:T().optional()}),En=C({default:O().optional(),defaultInput:T().optional(),display_name:w().optional(),forceInput:T().optional(),tooltip:w().optional(),socketless:T().optional(),hidden:T().optional(),advanced:T().optional(),widgetType:w().optional(),rawLink:T().optional(),lazy:T().optional()}).passthrough(),Dn=En.extend({min:D().optional(),max:D().optional(),step:D().optional(),default:S([D(),A(D())]).optional(),display:E([`slider`,`number`,`knob`,`gradientslider`]).optional()}),On=Dn.extend({control_after_generate:S([T(),E(xn)]).optional()}),kn=C({offset:D(),color:j([D(),D(),D()])}),An=Dn.extend({round:S([D(),k(!1)]).optional(),gradient_stops:A(kn).optional()}),jn=En.extend({label_on:w().optional(),label_off:w().optional(),default:T().optional()}),Mn=En.extend({default:w().optional(),multiline:T().optional(),dynamicPrompts:T().optional(),defaultVal:w().optional(),placeholder:w().optional()}),Nn=En.extend({control_after_generate:S([T(),E(xn)]).optional(),image_upload:T().optional(),image_folder:Sn.optional(),allow_batch:T().optional(),video_upload:T().optional(),audio_upload:T().optional(),mesh_upload:T().optional(),upload_subfolder:w().optional(),animated_
2image_upload:T().optional(),options:A(Cn).optional(),remote:wn.optional(),multi_select:Tn.optional()}),Pn=j([k(`INT`),On.optional()]),Fn=j([k(`FLOAT`),An.optional()]),In=j([k(`BOOLEAN`),jn.optional()]),Ln=j([k(`STRING`),Mn.optional()]),Rn=j([A(Cn),Nn.optional()]),zn=j([k(`COMBO`),Nn.optional()]);function isComboInputSpecV1(e){return Array.isArray(e[0])}function isIntInputSpec(e){return e[0]===`INT`}function isFloatInputSpec(e){return e[0]===`FLOAT`}function isComboInputSpecV2(e){return e[0]===`COMBO`}function isComboInputSpec(e){return isComboInputSpecV1(e)||isComboInputSpecV2(e)}function isMediaUploadComboInput(e){let[t,n]=e;return n?(n.image_upload===!0||n.video_upload===!0||n.animated_image_upload===!0)&&(isComboInputSpecV1(e)||t===`COMBO`):!1}function getInputSpecType(e){return isComboInputSpec(e)?`COMBO`:e[0]}function getComboSpecComboOptions(e){return(isComboInputSpecV2(e)?e[1]?.options:e[0])??[]}var Bn=new Set([`INT`,`FLOAT`,`BOOLEAN`,`STRING`,`COMBO`]),Vn=S([Pn,Fn,In,Ln,Rn,zn,j([w().refine(e=>!Bn.has(e)),En.optional()])]),Hn=C({required:M(Vn).optional(),optional:M(Vn).optional(),hidden:M(O()).optional()}),Un=A(S([w(),A(Cn)])),Wn=C({widgets:A(C({name:w(),type:w()})).optional().default([]),inputs:A(w()).optional().default([]),input_groups:A(w()).optional().default([])}),Gn=C({engine:k(`jsonata`).optional().default(`jsonata`),depends_on:Wn.optional().default({widgets:[],inputs:[],input_groups:[]}),expr:w()});C({input:Hn.optional(),output:Un.optional(),output_is_list:A(T()).optional(),output_name:A(w()).optional(),output_tooltips:A(w()).optional(),output_matchtypes:A(w().optional()).optional(),name:w(),display_name:w(),description:w(),help:w().optional(),category:w(),main_category:w().optional(),output_node:T(),python_module:w(),deprecated:T().optional(),experimental:T().optional(),dev_only:T().optional(),api_node:T().optional(),input_order:M(A(w())).optional(),search_aliases:A(w()).optional(),price_badge:Gn.optional(),essentials_category:w().optional(),isGlobal:T().optional()});var Kn=C({...En.shape,template:C({input:Hn,names:A(w()).optional(),max:D().optional(),min:D().optional(),prefix:w().optional()})}),qn=j([k(`COMFY_DYNAMICCOMBO_V3`),En.extend({options:A(C({inputs:Hn,key:w()}))})]),Jn=C({...En.shape,type:k(`COMFY_MATCHTYPE_V3`),template:C({allowed_types:w(),template_id:w()})}),Yn=`Subgraph Blueprints`,Xn=function(e){return e.Core=`core`,e.CustomNodes=`custom_nodes`,e.Blueprint=`blueprint`,e.Essentials=`essentials`,e.Unknown=`unknown`,e}({}),Zn=[`nodes`,`comfy_extras`,`comfy_api_nodes`],Qn={type:Xn.Unknown,className:`comfy-unknown`,displayText:`Unknown`,badgeText:`?`};function shortenNodeName(e){return e.replace(/^(ComfyUI-|ComfyUI_|Comfy-|Comfy_)/,``).replace(/(-ComfyUI|_ComfyUI|-Comfy|_Comfy)$/,``)}function getNodeSource(e,t){if(!e)return Qn;let n=e.split(`.`);if(t){let e=shortenNodeName((n[1]??n[0]??`essentials`).split(`@`)[0]);return{type:Xn.Essentials,className:`comfy-essentials`,displayText:e,badgeText:e}}else if(Zn.includes(n[0]))return{type:Xn.Core,className:`comfy-core`,displayText:`Comfy Core`,badgeText:`🦊`};else if(n[0]===`blueprint`)return{type:Xn.Blueprint,className:`blueprint`,displayText:`Blueprint`,badgeText:`bp`};else if(n[0]===`custom_nodes`){let e=n[1];if(!e)return Qn;let t=e.split(`@`)[0],r=shortenNodeName(t);return{type:Xn.CustomNodes,className:`comfy-custom-nodes`,displayText:r,badgeText:r}}else return Qn}function isEssentialNode(e){return e.nodeSource.type===Xn.Essentials}function isCustomNode(e){return e.nodeSource.type===Xn.CustomNodes}var $n=function(e){return e.None=`None`,e.ShowAll=`Show all`,e.HideBuiltIn=`Hide built-in`,e}({}),er=function(e){return e.CONTEXT_MENU=`context menu`,e.SEARCH_BOX=`search box`,e.NO_ACTION=`no action`,e}({}),tr=w(),nr=w(),rr=E([`input`,`output`,`temp`]);M(w(),x());var ir=C({filename:w().optional(),subfolder:w().optional(),type:rr.optional(),display_name:w().optional()}),ar=C({audio:A(ir).optional(),images:A(ir).optional(),video:A(ir).optional(),animated:A(T()).optional(),text:S([w(),A(w())]).optional()}).passthrough();C({status:C({exec_info:C({queue_remaining:D().int()})}).nullish(),sid:w().nullish()}),C({value:D().int(),max:D().int(),prompt_id:nr,node:$}),C({prompt_id:nr,nodes:M($,C({value:D(),max:D(),state:E([`pending`,`running`,`finished`,`error`]),node_id:$,prompt_id:nr,display_no
2de_id:$.optional(),parent_node_id:$.optional(),real_node_id:$.optional()}))}),C({node:$,display_node:$,prompt_id:nr}).extend({output:ar,merge:T().optional()});var or=C({prompt_id:nr,timestamp:D().int()});or.extend({nodes:A($)}),or.extend({node_id:$,node_type:tr,executed:A($)}),or.extend({node_id:$,node_type:tr,executed:A($),exception_message:w(),exception_type:w(),traceback:A(w()),current_inputs:O(),current_outputs:O()}),C({nodeId:$,text:w(),prompt_id:w().optional()}),C({value:w(),id:w().optional()});var sr=C({cols:D(),row:D()}),cr=C({t:w(),m:w()});C({size:sr.optional(),entries:A(cr)}),C({size:sr,entries:A(cr)}),M(w(),O()),C({task_id:w(),asset_name:w(),bytes_total:D(),bytes_downloaded:D(),progress:D(),status:E([`created`,`running`,`completed`,`failed`]),asset_id:w().optional(),error:w().optional()}),C({task_id:w(),export_name:w().optional(),assets_total:D(),assets_attempted:D(),assets_failed:D(),bytes_total:D(),bytes_processed:D(),progress:D(),status:E([`created`,`running`,`completed`,`failed`]),error:w().optional()});var lr=M($,ar);A(w()),A(w());var ur=C({type:w(),message:w(),details:w(),extra_info:C({input_name:w().optional()}).passthrough().optional()});C({node_errors:M($,C({errors:A(ur),class_type:w(),dependent_outputs:A(O())})).optional(),prompt_id:w().optional(),exec_info:C({queue_remaining:D().optional()}).optional(),error:S([w(),ur])}),C({type:w(),message:w(),details:w()});var dr=C({name:w(),type:w(),index:D(),vram_total:D(),vram_free:D(),torch_vram_total:D(),torch_vram_free:D()}),fr=C({name:w(),installed:w().nullable(),required:w().nullable()});C({system:C({os:w(),python_version:w(),embedded_python:T(),comfyui_version:w(),pytorch_version:w(),required_frontend_version:w().optional(),argv:A(w()),ram_total:D(),ram_free:D(),cloud_version:w().optional(),comfyui_frontend_version:w().optional(),workflow_templates_version:w().optional(),installed_templates_version:w().optional(),required_templates_version:w().optional(),comfy_package_versions:A(fr).optional()}),devices:A(dr)}),C({storage:E([`server`]),migrated:T().optional(),users:M(w(),w()).optional()}),A(A(w(),w())),C({path:w(),size:D(),modified:D()});var pr=C({icon:w().optional(),color:w().optional()}),mr=E(Object.values(er)),hr=E(Object.values($n)),gr=E([`default`,`none`,`auto`,`latent2rgb`,`taesd`]);C({"Comfy.ColorPalette":w(),"Comfy.CustomColorPalettes":_n,"Comfy.Canvas.BackgroundImage":w().optional(),"Comfy.ConfirmClear":T(),"Comfy.DevMode":T(),"Comfy.Appearance.DisableAnimations":T(),"Comfy.UI.TabBarLayout":E([`Default`,`Legacy`]),"Comfy.Workflow.ShowMissingModelsWarning":T(),"Comfy.Workflow.WarnBlueprintOverwrite":T(),"Comfy.Desktop.CloudNotificationShown":T(),"Comfy.DisableFloatRounding":T(),"Comfy.DisableSliders":T(),"Comfy.DOMClippingEnabled":T(),"Comfy.EditAttention.Delta":D(),"Comfy.EnableTooltips":T(),"Comfy.EnableWorkflowViewRestore":T(),"Comfy.FloatRoundingPrecision":D(),"Comfy.Graph.AutoPanSpeed":D(),"Comfy.Graph.CanvasInfo":T(),"Comfy.Graph.CanvasMenu":T(),"Comfy.Graph.CtrlShiftZoom":T(),"Comfy.Graph.DeduplicateSubgraphNodeIds":T(),"Comfy.Graph.LiveSelection":T(),"Comfy.Graph.LinkMarkers":se(R),"Comfy.Graph.ZoomSpeed":D(),"Comfy.Group.DoubleClickTitleToEdit":T(),"Comfy.GroupSelectedNodes.Padding":D(),"Comfy.Locale":w(),"Comfy.NodeLibrary.NewDesign":T(),"Comfy.NodeLibrary.Bookmarks":A(w()),"Comfy.NodeLibrary.Bookmarks.V2":A(w()),"Comfy.NodeLibrary.BookmarksCustomization":M(w(),pr),"Comfy.LinkRelease.Action":mr,"Comfy.LinkRelease.ActionShift":mr,"Comfy.ModelLibrary.AutoLoadAll":T(),"Comfy.ModelLibrary.NameFormat":E([`filename`,`title`]),"Comfy.NodeSearchBoxImpl.NodePreview":T(),"Comfy.NodeSearchBoxImpl.FollowCursor":T(),"Comfy.NodeSearchBoxImpl":E([`default`,`v1 (legacy)`,`litegraph (legacy)`]),"Comfy.NodeSearchBoxImpl.ShowCategory":T(),"Comfy.NodeSearchBoxImpl.ShowIdName":T(),"Comfy.NodeSearchBoxImpl.ShowNodeFrequency":T(),"Comfy.NodeSuggestions.number":D(),"Comfy.Node.BypassAllLinksOnDelete":T(),"Comfy.Node.Opacity":D(),"Comfy.Node.MiddleClickRerouteNode":T(),"Comfy.Node.ShowDeprecated":T(),"Comfy.Node.ShowExperimental":T(),"Comfy.NodeReplacement.Enabled":T(),"Comfy.Pointer.ClickBufferTime":D(),"Comfy.Pointer.ClickDrift":D(),"Comfy.Pointer.DoubleClickTime":D(),"Comfy.PreviewFormat":w(),"Comfy.PromptFilename":T(),"Comfy.Sidebar.
2Location":E([`left`,`right`]),"Comfy.Sidebar.Size":E([`small`,`normal`]),"Comfy.Sidebar.UnifiedWidth":T(),"Comfy.Sidebar.Style":E([`floating`,`connected`]),"Comfy.SnapToGrid.GridSize":D(),"Comfy.TextareaWidget.FontSize":D(),"Comfy.TextareaWidget.Spellcheck":T(),"Comfy.UseNewMenu":E([`Disabled`,`Top`]),"Comfy.TreeExplorer.ItemPadding":D(),"Comfy.Validation.Workflows":T(),"Comfy.Workflow.SortNodeIdOnSave":T(),"Comfy.Execution.PreviewMethod":gr,"Comfy.Workflow.WorkflowTabsPosition":E([`Sidebar`,`Topbar`]),"Comfy.Node.DoubleClickTitleToEdit":T(),"Comfy.WidgetControlMode":E([`before`,`after`]),"Comfy.Window.UnloadConfirmation":T(),"Comfy.NodeBadge.NodeSourceBadgeMode":hr,"Comfy.NodeBadge.NodeIdBadgeMode":hr,"Comfy.NodeBadge.NodeLifeCycleBadgeMode":hr,"Comfy.NodeBadge.ShowApiPricing":T(),"Comfy.Notification.ShowVersionUpdates":T(),"Comfy.QueueButton.BatchCountLimit":D(),"Comfy.Queue.MaxHistoryItems":D(),"Comfy.Queue.History.Expanded":T(),"Comfy.WorkflowActions.SeenItems":A(w()),"Comfy.Keybinding.UnsetBindings":A(yn),"Comfy.Keybinding.NewBindings":A(yn),"Comfy.Keybinding.CurrentPreset":w(),"Comfy.Extension.Disabled":A(w()),"Comfy.LinkRenderMode":D(),"Comfy.Node.AutoSnapLinkToSlot":T(),"Comfy.Node.SnapHighlightsNode":T(),"Comfy.Server.ServerConfigValues":M(w(),O()),"Comfy.Server.LaunchArgs":M(w(),w()),"LiteGraph.Canvas.MaximumFps":D(),"Comfy.Workflow.ConfirmDelete":T(),"Comfy.Workflow.AutoSaveDelay":D(),"Comfy.Workflow.AutoSave":E([`off`,`after delay`]),"Comfy.RerouteBeta":T(),"LiteGraph.Canvas.MinFontSizeForLOD":D(),"Comfy.Canvas.SelectionToolbox":T(),"LiteGraph.Node.TooltipDelay":D(),"LiteGraph.ContextMenu.Scaling":T(),"LiteGraph.Reroute.SplineOffset":D(),"LiteGraph.Canvas.LowQualityRenderingZoomThreshold":D(),"Comfy.Toast.DisableReconnectingToast":T(),"Comfy.Workflow.Persist":T(),"Comfy.TutorialCompleted":T(),"Comfy.InstalledVersion":w().nullable(),"Comfy.Node.AllowImageSizeDraw":T(),"Comfy.Minimap.Visible":T(),"Comfy.Minimap.NodeColors":T(),"Comfy.Minimap.ShowLinks":T(),"Comfy.Minimap.ShowGroups":T(),"Comfy.Minimap.RenderBypassState":T(),"Comfy.Minimap.RenderErrorState":T(),"Comfy.Canvas.NavigationMode":w(),"Comfy.Canvas.LeftMouseClickBehavior":w(),"Comfy.Canvas.MouseWheelScroll":w(),"Comfy.VueNodes.Enabled":T(),"Comfy.AppBuilder.VueNodeSwitchDismissed":T(),"Comfy.VueNodes.AutoScaleLayout":T(),"Comfy.Assets.UseAssetAPI":T(),"Comfy.Queue.QPOV2":T(),"Comfy.Queue.ShowRunProgressBar":T(),"Comfy-Desktop.AutoUpdate":T(),"Comfy-Desktop.SendStatistics":T(),"Comfy-Desktop.WindowStyle":w(),"Comfy-Desktop.UV.PythonInstallMirror":w(),"Comfy-Desktop.UV.PypiInstallMirror":w(),"Comfy-Desktop.UV.TorchInstallMirror":w(),"Comfy.MaskEditor.BrushAdjustmentSpeed":D(),"Comfy.MaskEditor.UseDominantAxis":T(),"Comfy.Load3D.ShowGrid":T(),"Comfy.Load3D.BackgroundColor":w(),"Comfy.Load3D.LightIntensity":D(),"Comfy.Load3D.LightIntensityMaximum":D(),"Comfy.Load3D.LightIntensityMinimum":D(),"Comfy.Load3D.LightAdjustmentIncrement":D(),"Comfy.Load3D.CameraType":E([`perspective`,`orthographic`]),"Comfy.Load3D.3DViewerEnable":T(),"Comfy.Load3D.PLYEngine":E([`threejs`,`fastply`,`sparkjs`]),"Comfy.Memory.AllowManualUnload":T(),"pysssss.SnapToGrid":T(),"VHS.AdvancedPreviews":w(),"Comfy.Release.Version":w(),"Comfy.Release.Status":E([`skipped`,`changelog seen`,`what's new seen`]),"Comfy.Release.Timestamp":D(),"Comfy.Templates.SelectedModels":A(w()),"Comfy.Templates.SelectedUseCases":A(w()),"Comfy.Templates.SelectedRunsOn":A(w()),"Comfy.Templates.SortBy":E([`default`,`recommended`,`popular`,`alphabetical`,`newest`,`vram-low-to-high`,`model-size-low-to-high`]),"test.setting":O(),"main.sub.setting.name":O(),"single.setting":O(),"LiteGraph.Node.DefaultPadding":T(),"LiteGraph.Pointer.TrackpadGestures":T(),"Comfy.VersionCompatibility.DisableWarnings":T(),"Comfy.RightSidePanel.IsOpen":T(),"Comfy.RightSidePanel.ShowErrorsTab":T(),"Comfy.Node.AlwaysShowAdvancedWidgets":T(),"LiteGraph.Group.SelectChildrenOnClick":T()});var _r=C({username:w(),name:w().optional(),description:w().optional(),coverImageUrl:w().nullish(),profilePictureUrl:w().nullish()}),vr=C({id:w(),name:w(),preview_url:w(),storage_url:w(),model:T(),public:T(),in_library:T()}),yr=C({assets:A(vr)}),br=E([`pending`,`in_progress`,`completed`,`failed`,`cancelled`]),xr=C({filename:w().optional(),subfolder:w().optional(),type:rr.optional(),nodeId:w(),mediaType:w(),display_name:w().optional()}).passthrough(),Sr=C({prompt_id:w().optional(),timestamp:D().optional(),node_id:w(),node_type:w(),executed:A(w()).optional(),exception_message:w(),exception_type:w(),traceback:A(w()),current_inputs:x(),current_outputs:x()}).passthrough(),Cr=C({id:w(),status:br,create_time:D(),execution_start_time:D().nullable().optional(),execution_end_time:D().nullable().optional(),preview_output:xr.nullable().optional(),outputs_count:D().nullable().optional(),execution_error:Sr.nullable().optional(),workflow_id:w().nullable().optional(),priority:D().optional()}).passthrough(),wr=Cr.extend({workflow:x().optional(),outputs:lr.optional(),update_time:D().optional(),execution_status:x().optional(),execution_meta:x().optional()}).passthrough(),Tr=C({offset:D(),limit:D(),total:D(),has_more:T()}),Er=C({jobs:A(Cr),pagination:Tr}),Dr=C({extra_data:C({extra_pnginfo:C({workflow:x()}).optional()}).optional()});async function fetchJobsRaw(e,t,n=200,r=0){let i=`/jobs?status=${t.join(`,`)}&limit=${n}&offset=${r}`;try{let t=await e(i);if(!t.ok)return console.error(`[Jobs API] Failed to fetch jobs: ${t.status}`),{jobs:[],total:0,offset:r,limit:n,hasMore:!1};let a=Er.parse(await t.json());return{jobs:a.jobs,total:a.pagination.total,offset:a.pagination.offset,limit:a.pagination.limit,hasMore:a.pagination.has_more}}catch(e){return console.error(`[Jobs API] Error fetching jobs:`,e),{jobs:[],total:0,offset:r,limit:n,hasMore:!1}}}var Or=1e6;function assignPriority(e,t){return e.map((e,n)=>({...e,priority:e.priority??t-n}))}async function fetchHistory(e,t=200,n=0){let{jobs:r}=await fetchHistoryPage(e,t,n);return r}async function fetchHistoryPage(e,t=200,n=0){let r=await fetchJobsRaw(e,[`completed`,`failed`,`cancelled`],t,n);return{jobs:assignPriority(r.jobs,r.total-r.offset),total:r.total,offset:r.offset,limit:r.limit,hasMore:r.hasMore}}async function fetchQueue(e){let{jobs:t}=await fetchJobsRaw(e,[`in_progress`,`pending`],200,0),n=t.filter(e=>e.status===`in_progress`),r=t.filter(e=>
2e.status===`pending`);return{Running:assignPriority(n,Or+n.length),Pending:assignPriority(r,Or+n.length+r.length)}}async function fetchJobDetail(e,t){try{let n=await e(`/jobs/${encodeURIComponent(t)}`);if(!n.ok){console.warn(`Job not found for job ${t}`);return}return wr.parse(await n.json())}catch(e){console.error(`Failed to fetch job detail for job ${t}:`,e);return}}async function extractWorkflow(e){let t=Dr.safeParse(e?.workflow);if(!t.success)return;let n=t.data.extra_data?.extra_pnginfo?.workflow;if(n)return await validateComfyWorkflow(n,e=>{console.warn(`[extractWorkflow] Workflow validation failed:`,e)})??void 0}var UnauthorizedError=class extends Error{};function addHeaderEntry(e,t,n){Array.isArray(e)?e.push([t,n]):e instanceof Headers?e.set(t,n):e[t]=n}var PromptExecutionError=class extends Error{response;status;constructor(e,t){super(`Prompt execution failed`),this.response=e,this.status=t}toString(){let e=``;typeof this.response.error==`string`?e+=this.response.error:this.response.error&&(e+=this.response.error.message+`: `+this.response.error.details);for(let[t,n]of Object.entries(this.response.node_errors??[])){e+=`
3`+n.class_type+`:`;for(let t of n.errors)e+=`
4    - `+t.message+`: `+t.details}return e}},ComfyApi=class extends EventTarget{_registered=new Set;api_host;api_base;initialClientId;clientId;user;socket=null;authStoreComposable;reportedUnknownMessageTypes=new Set;getClientFeatureFlags(){return{...ve}}serverFeatureFlags=r({});authToken;apiKey;constructor(){super(),this.user=``,this.api_host=location.host,this.api_base=y?``:location.pathname.split(`/`).slice(0,-1).join(`/`),this.initialClientId=sessionStorage.getItem(`clientId`)}internalURL(e){return this.api_base+`/internal`+e}apiURL(e){return e.startsWith(`/api`)?this.api_base+e:this.api_base+`/api`+e}fileURL(e){return this.api_base+e}async getAuthStore(){if(y)return this.authStoreComposable||=(await n(()=>import(`./authStore-DFx0_RKO.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54]),import.meta.url)).useAuthStore,this.authStoreComposable()}async waitForAuthInitialization(){if(y){let e=await this.getAuthStore();if(!e||e.isInitialized)return;let{isInitialized:t}=u(e);try{await Promise.race([te(t).toBe(!0),ne(1e4)])}catch{console.warn(`Firebase auth initialization timeout after 10 seconds`)}}}async fetchApi(e,t){let n=t?.headers??{};if(y){await this.waitForAuthInitialization();let getAuthHeaderIfAvailable=async()=>{try{let e=await this.getAuthStore();return e?await e.getAuthHeader():null}catch(e){return console.warn(`Failed to get auth header:`,e),null}},e=await getAuthHeaderIfAvailable();if(e)for(let[t,r]of Object.entries(e))addHeaderEntry(n,t,r)}return addHeaderEntry(n,`Comfy-User`,this.user),fetch(this.apiURL(e),{cache:`no-cache`,...t,headers:n})}addEventListener(e,t,n){super.addEventListener(e,t,n),this._registered.add(e)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}addCustomEventListener(e,t,n){super.addEventListener(e,t,n),this._registered.add(e)}removeCustomEventListener(e,t,n){super.removeEventListener(e,t,n)}dispatchCustomEvent(e,t){let n=t===void 0?new CustomEvent(e):new CustomEvent(e,{detail:t});return super.dispatchEvent(n)}dispatchEvent(e){return super.dispatchEvent(e)}_pollQueue(){setInterval(async()=>{try{let e=await(await this.fetchApi(`/prompt`)).json();this.dispatchCustomEvent(`status`,e)}catch{this.dispatchCustomEvent(`status`,null)}},1e3)}async createSocket(e){if(this.socket)return;let t=!1,n=window.name,r=new URLSearchParams;if(n&&r.set(`clientId`,n),y)try{let e=await(await this.getAuthStore())?.getAuthToken();e&&r.set(`token`,e)}catch(e){console.warn(`Could not get auth token for WebSocket connection:`,e)}let i=`${window.location.protocol===`https:`?`wss`:`ws`}://${this.api_host}${this.api_base}/ws`,a=r.toString(),o=a?`${i}?${a}`:i;this.socket=new WebSocket(o),this.socket.binaryType=`arraybuffer`,this.socket.addEventListener(`open`,()=>{t=!0,this.socket.send(JSON.stringify({type:`feature_flags`,data:this.getClientFeatureFlags()})),e&&this.dispatchCustomEvent(`reconnected`)}),this.socket.addEventListener(`error`,()=>{this.socket&&this.socket.close(),!e&&!t&&this._pollQueue()}),this.socket.addEventListener(`close`,()=>{setTimeout(async()=>{this.socket=null,await this.createSocket(!0)},300),t&&(this.dispatchCustomEvent(`status`,null),this.dispatchCustomEvent(`reconnecting`))}),this.socket.addEventListener(`message`,e=>{try{if(e.data instanceof ArrayBuffer){let t=new DataView(e.data),n=t.getUint32(0),r;switch(n){case 3:try{let t=new TextDecoder,n=e.data.slice(4),r=new DataView(n),i=0,a;if(this.serverSupportsFeature(`supports_progress_text_metadata`)){let e=r.getUint32(i);i+=4,a=t.decode(n.slice(i,i+e)),i+=e}let o=r.getUint32(i);i+=4;let s=t.decode(n.slice(i,i+o));i+=o;let c=t.decode(n.slice(i));this.dispatchCustomEvent(`progress_text`,{nodeId:s,text:c,...a!==void 0&&{prompt_id:a}})}catch(e){console.warn(`Failed to parse progress_text binary message`,e)}break;case 1:let i=t.getUint32(4),a=e.data.slice(8);switch(i){case 2:r=`image/png`;break;default:r=`image/jpeg`;break}let o=new Blob([a],{type:r});this.dispatchCustomEvent(`b_preview`,o);break;case 4:let s=new TextDecoder,c=t.getUint32(4),l=e.data.slice(8,8+c),u=JSON.parse(s.decode(l)),d=e.data.slice(8+c),f=u.image_type,p=new Blob([d],{type:f});this.dispatchCustomEvent(`b_preview_with_metadata`,{blob:p,nodeId:u.node_id,displayNodeId:u.display_no
4de_id,parentNodeId:u.parent_node_id,realNodeId:u.real_node_id,jobId:u.prompt_id}),this.dispatchCustomEvent(`b_preview`,p);break;default:throw Error(`Unknown binary websocket message of type ${n}`)}}else{let t=JSON.parse(e.data);switch(t.type){case`status`:if(t.data.sid){let e=t.data.sid;this.clientId=e,window.name=e,sessionStorage.setItem(`clientId`,e)}this.dispatchCustomEvent(`status`,t.data.status??null);break;case`executing`:this.dispatchCustomEvent(`executing`,t.data.display_node||t.data.node);break;case`execution_start`:case`execution_error`:case`execution_interrupted`:case`execution_cached`:case`execution_success`:case`progress`:case`progress_state`:case`executed`:case`graphChanged`:case`promptQueued`:case`logs`:case`b_preview`:case`notification`:this.dispatchCustomEvent(t.type,t.data);break;case`feature_flags`:this.serverFeatureFlags.value=t.data,this.serverFeatureFlags.value,this.dispatchCustomEvent(`feature_flags`,t.data);break;default:if(this._registered.has(t.type))super.dispatchEvent(new CustomEvent(t.type,{detail:t.data}));else if(!this.reportedUnknownMessageTypes.has(t.type))throw this.reportedUnknownMessageTypes.add(t.type),Error(`Unknown message type ${t.type}`)}}}catch(t){console.warn(`Unhandled message:`,e.data,t)}})}init(){this.createSocket()}async getExtensions(){return await(await this.fetchApi(`/extensions`,{cache:`no-store`})).json()}async getWorkflowTemplates(){return await(await this.fetchApi(`/workflow_templates`)).json()}async getCoreWorkflowTemplates(e){let t=e&&e!==`en`?`index.${e}.json`:`index.json`;try{let e=await b.get(this.fileURL(`/templates/${t}`));return e.headers[`content-type`]?.includes(`application/json`)?e.data:[]}catch(t){return e&&e!==`en`?(console.warn(`Localized templates for '${e}' not found, falling back to English`),this.getCoreWorkflowTemplates()):(console.error(`Error loading core workflow templates:`,t),[])}}async getEmbeddings(){return await(await this.fetchApi(`/embeddings`,{cache:`no-store`})).json()}async getNodeDefs(){return await(await this.fetchApi(`/object_info`,{cache:`no-store`})).json()}async queuePrompt(e,t,n){let{output:r,workflow:i}=t,a={client_id:this.clientId??``,prompt:r,...n?.partialExecutionTargets&&{partial_execution_targets:n.partialExecutionTargets},extra_data:{auth_token_comfy_org:this.authToken,api_key_comfy_org:this.apiKey,extra_pnginfo:{workflow:i},...n?.previewMethod&&n.previewMethod!==`default`&&{preview_method:n.previewMethod}}};e===-1?a.front=!0:e!=0&&(a.number=e);let o=await this.fetchApi(`/prompt`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(o.status!==200){let e=await o.text(),t;try{t=JSON.parse(e)}catch{t={error:{type:`server_error`,message:`${o.status} ${o.statusText}`,details:e}}}throw new PromptExecutionError(t,o.status)}return await o.json()}async getShareableAssets(e,t){let n={workflow_api_json:e};t?.owned!==void 0&&(n.owned=t.owned);let r=await this.fetchApi(`/assets/from-workflow`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(r.status!==200)throw Error(`Failed to fetch shareable assets: ${r.status}`);let i=await r.json();return yr.parse(i)}async getModelFolders(){let e=await this.fetchApi(`/experiment/models`);if(e.status===404)return[];let t=[`configs`,`custom_nodes`];return(await e.json()).filter(e=>!t.includes(e.name))}async getModels(e){let t=await this.fetchApi(`/experiment/models/${e}`);return t.status===404?[]:await t.json()}async viewMetadata(e,t){let n=await this.fetchApi(`/view_metadata/${e}?filename=${encodeURIComponent(t)}`),r=await n.text();if(!r)return null;try{return JSON.parse(r)}catch(e){return console.error(`Error viewing metadata`,n.status,n.statusText,r,e),null}}async getItems(e){return e===`queue`?this.getQueue():this.getHistory()}async getQueue(e){try{return await fetchQueue(this.fetchApi.bind(this))}catch(t){if(e?.throwOnError)throw t;return console.error(`Failed to fetch queue:`,t),{Running:[],Pending:[]}}}async getHistory(e=200,t){try{return await fetchHistory(this.fetchApi.bind(this),e,t?.offset)}catch(e){return console.error(e),[]}}async getJobDetail(e){return fetchJobDetail(this.fetchApi.bind(this),e)}async getSystemStats(){return await(await this.fetchApi(`/system_stats`)).json()}async _postItem(e,t){try{await this.fetchApi(`/`+e,{method:`POST`,headers:{"Content-Type":`application/json`},body:t?JSON.stringify(t):void 0})}catch(e){console.error(e)}}async deleteItem(e,t){await this._postItem(e,{delete:[t]})}async clearItems(e){await this._postItem(e,{clear:!0})}async interrupt(e){await this._postItem(`interrupt`,e?{prompt_id:e}:void 0)}async getUserConfig(){return(await this.fetchApi(`/users`)).json()}createUser(e){return this.fetchApi(`/users`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({username:e})})}async getSettings(){let e=await this.fetchApi(`/settings`);if(e.status==401)throw new UnauthorizedError(e.statusText);return await e.json()}async getSetting(e){return(await this.fetchApi(`/settings/${encodeURIComponent(e)}`)).json()}async storeSettings(e){return this.fetchApi(`/settings`,{method:`POST`,body:JSON.stringify(e)})}async storeSetting(e,t){return this.fetchApi(`/settings/${encodeURIComponent(e)}`,{method:`POST`,body:JSON.stringify(t)})}async getUserData(e,t){return this.fetchApi(`/userdata/${encodeURIComponent(e)}`,t)}async storeUserData(e,t,n={overwrite:!0,stringify:!0,throwOnError:!0,full_info:!1}){let r=await this.fetchApi(`/userdata/${encodeURIComponent(e)}
4?overwrite=${n.overwrite}&full_info=${n.full_info}`,{method:`POST`,body:n?.stringify?JSON.stringify(t):t,...n});if(r.status!==200&&n.throwOnError!==!1)throw Error(`Error storing user data file '${e}': ${r.status} ${(await r).statusText}`);return r}async deleteUserData(e){return await this.fetchApi(`/userdata/${encodeURIComponent(e)}`,{method:`DELETE`})}async moveUserData(e,t,n={overwrite:!1}){return await this.fetchApi(`/userdata/${encodeURIComponent(e)}/move/${encodeURIComponent(t)}?overwrite=${n?.overwrite}`,{method:`POST`})}async listUserDataFullInfo(e){let t=d(e,`/`),n=await this.fetchApi(`/userdata?dir=${encodeURIComponent(t)}&recurse=true&split=false&full_info=true`);if(n.status===404)return[];if(n.status!==200)throw Error(`Error getting user data list '${t}': ${n.status} ${n.statusText}`);return n.json()}async getGlobalSubgraphData(e){let t=await kr.fetchApi(`/global_subgraphs/`+e);if(t.status!==200)throw Error(`Failed to fetch global subgraph '${e}': ${t.status} ${t.statusText}`);let n=await t.json();if(!n?.data)throw Error(`Global subgraph '${e}' returned empty data`);return n.data}async getGlobalSubgraphs(){let e=await kr.fetchApi(`/global_subgraphs`);if(e.status!==200)return{};let t=await e.json();for(let[e,n]of Object.entries(t))n.data||=this.getGlobalSubgraphData(e);return t}async getLogs(){let e=y?this.apiURL(`/logs`):this.internalURL(`/logs`);return(await b.get(e)).data}async getRawLogs(){let e=y?this.apiURL(`/logs/raw`):this.internalURL(`/logs/raw`);return(await b.get(e)).data}async subscribeLogs(e){let t=y?this.apiURL(`/logs/subscribe`):this.internalURL(`/logs/subscribe`);return await b.patch(t,{enabled:e,clientId:this.clientId})}async getFolderPaths(){let e=await b.get(this.internalURL(`/folder_paths`)).catch(()=>null);return e?e.data:{}}async freeMemory(e){try{let t=``;t=e.freeExecutionCache?`{"unload_models": true, "free_memory": true}`:`{"unload_models": true}`,(await this.fetchApi(`/free`,{method:`POST`,headers:{"Content-Type":`application/json`},body:t})).status===200?e.freeExecutionCache?ie().add({severity:`success`,summary:`Models and Execution Cache have been cleared.`,life:3e3}):ie().add({severity:`success`,summary:`Models have been unloaded.`,life:3e3}):ie().add({severity:`error`,summary:`Unloading of models failed. Installed ComfyUI may be an outdated version.`})}catch{ie().add({severity:`error`,summary:`An error occurred while trying to unload models.`})}}async getCustomNodesI18n(){return(await b.get(this.apiURL(`/i18n`))).data}serverSupportsFeature(e){let t=re(e);return t===void 0?m(this.serverFeatureFlags.value,e)===!0:t}getServerFeature(e,t){let n=re(e);return n===void 0?m(this.serverFeatureFlags.value,e,t):n}getServerFeatures(){return{...this.serverFeatureFlags.value}}async getFuseOptions(){try{let e=await b.get(this.fileURL(`/templates/fuse_options.json`),{headers:{"Content-Type":`application/json`}});return e.headers[`content-type`]?.includes(`application/json`)?e.data:null}catch(e){return console.error(`Error loading fuse options:`,e),null}}},kr=new ComfyApi;window.comfyAPI=window.comfyAPI||{},window.comfyAPI.api=window.comfyAPI.api||{},window.comfyAPI.api.UnauthorizedError=UnauthorizedError,window.comfyAPI.api.PromptExecutionError=PromptExecutionError,window.comfyAPI.api.ComfyApi=ComfyApi,window.comfyAPI.api.api=kr;export{isPromotedWidgetView as $,Pe as $t,kn as A,getLocatorIdFromNodeData as At,validateComfyWorkflow as B,isNonNullish as Bt,isComboInputSpecV2 as C,xe as Cn,forEachSubgraphNode as Ct,Kn as D,getExecutionIdForNodeInGraph as Dt,isMediaUploadComboInput as E,getExecutionIdByNode as Et,Jn as F,isMissingCandidateActive as Ft,distributeNodes as G,createNodeExecutionId as Gt,yt as H,isSlotObject as Ht,Mn as I,mapAllNodes as It,ot as J,getParentExecutionIds as Jt,SubgraphNode as K,createNodeLocatorId as Kt,bn as L,reduceAllNodes as Lt,qn as M,getNodeByLocatorId as Mt,An as N,getRootParentNode as Nt,En as O,getExecutionIdFromNodeData as Ot,On as P,isAncestorPathActive as Pt,resolveConcretePromotedWidget as Q,stripGraphPrefix as Qt,pn as R,triggerCallbackOnAllNodes as Rt,isComboInputSpecV1 as S,z as Sn,forEachNode as St,isIntInputSpec as T,getAllNonIoNodesInSubgraph as Tt,Z as U,isSubgraph as Ut,Q as V,isResultItemType as Vt,alignNodes as W,compareExecutionId as Wt,resolveSubgraphInputTarget as X,parseNodeExecutionId as Xt,supportsVirtualCanvasImagePreview as Y,isNodeExecutionId as Yt,matchPromotedInput as Z,parseNodeLocatorId as Zt,isCustomNode as _,B as _n,AutoPanController as _t,extractWorkflow as a,isSizeEqual as an,J as at,getIn
4putSpecType as b,N as bn,executionIdToNodeLocatorId as bt,vr as c,removeNodeTitleHeight as cn,NodeSlot as ct,er as d,isNodeBindable as dn,isOverNodeOutput as dt,W as en,nt as et,Yn as f,DragAndScale as fn,K as ft,getNodeSource as g,snapPoint as gn,getSlotKey as gt,Xn as h,createBounds as hn,Ie as ht,kr as i,isPointEqual as in,LegacyWidget as it,Nn as j,getNodeByExecutionId as jt,jn as k,getExecutionIdsForSelectedNodes as kt,_r as l,commonType as ln,getSlotColor as lt,$n as m,containsRect as mn,LGraphBadge as mt,PromptExecutionError as n,U as nn,Y as nt,fetchHistoryPage as o,toPoint as on,defineDeprecatedProperty as ot,Zn as p,containsCentre as pn,ze as pt,lt as q,getAncestorExecutionIds as qt,UnauthorizedError as r,isBoundsEqual as rn,isComboWidget as rt,rr as s,H as sn,q as st,ComfyApi as t,useLayoutMutations as tn,X as tt,ir as u,isColorable as un,isOverNodeInput as ut,isEssentialNode as v,I as vn,collectAllNodes as vt,isFloatInputSpec as w,getActiveGraphNodeIds as wt,isComboInputSpec as x,P as xn,findSubgraphPathById as xt,getComboSpecComboOptions as y,R as yn,collectFromNodes as yt,gn as z,isAbortError as zt};
5//# sourceMappingURL=api-DzWNw5Ki.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.