spytial-core 1.9.11 → 1.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -848,7 +848,7 @@ Expecting `+M1.join(", ")+", got '"+(this.terminals_[to]||to)+"'":g1="Parse erro
848
848
  </svg>
849
849
  </div>
850
850
  <div id="error" style="display: none; color: red;"></div>
851
- `;}initializeD3(){Co||(Co=window.d3),this.svg=Co.select(this.shadowRoot.querySelector("#svg")),this.container=this.svg.select(".zoomable"),Co.zoom?(this.zoomBehavior=Co.zoom().scaleExtent([.01,20]).on("start",()=>{Co.event.sourceEvent&&(this.userHasManuallyZoomed=true);}).on("zoom",()=>{this.container.attr("transform",Co.event.transform),this.updateZoomControlStates(),this.updateSmallNodeClasses();}),this.svg.call(this.zoomBehavior),this.initializeZoomControls()):console.warn("D3 zoom behavior not available. Ensure D3 v4+ is loaded.");}initializeZoomControls(){let n=this.shadowRoot.querySelector("#zoom-in"),c=this.shadowRoot.querySelector("#zoom-out"),s=this.shadowRoot.querySelector("#zoom-fit");n&&n.addEventListener("click",()=>{this.userHasManuallyZoomed=true,this.zoomIn();}),c&&c.addEventListener("click",()=>{this.userHasManuallyZoomed=true,this.zoomOut();}),s&&s.addEventListener("click",()=>{this.resetViewToFitContent();});let e=this.shadowRoot.querySelector("#routing-mode");if(e){let o=this.layoutFormat||"default";e.value=o,e.addEventListener("change",()=>{this.handleRoutingModeChange(e.value);});}let i=this.shadowRoot.querySelector("#screenshot-btn");i&&i.addEventListener("click",()=>{this.takeScreenshot();}),this.updateZoomControlStates();}handleRoutingModeChange(n){this.setAttribute("layoutFormat",n),this.currentLayout&&this.colaLayout&&(n==="grid"?this.gridify(10,25,10):this.routeEdges(),this.dispatchEvent(new CustomEvent("routing-mode-changed",{detail:{mode:n}})));}updateRoutingModeDropdown(){let n=this.shadowRoot?.querySelector("#routing-mode");if(n){let c=this.layoutFormat||"default";n.value=c;}}initializeInputModeHandlers(){this.inputModeEnabled&&this.attachInputModeListeners();}attachInputModeListeners(){this.inputModeListenersAttached||(document.addEventListener("keydown",this.handleInputModeKeydown),document.addEventListener("keyup",this.handleInputModeKeyup),window.addEventListener("blur",this.handleInputModeBlur),this.inputModeListenersAttached=true);}detachInputModeListeners(){this.inputModeListenersAttached&&(document.removeEventListener("keydown",this.handleInputModeKeydown),document.removeEventListener("keyup",this.handleInputModeKeyup),window.removeEventListener("blur",this.handleInputModeBlur),this.inputModeListenersAttached=false);}activateInputMode(){this.isInputModeActive=true,this.svg&&this.svg.classed("input-mode",true),this.disableNodeDragging(),this.disableZoom(),this.updateEdgeEndpointMarkers(),this.dispatchEvent(new CustomEvent("input-mode-activated",{detail:{active:true}}));}deactivateInputMode(){this.isInputModeActive=false,this.svg&&this.svg.classed("input-mode",false),this.cleanupEdgeCreation(),this.enableNodeDragging(),this.enableZoom(),this.updateEdgeEndpointMarkers(),this.dispatchEvent(new CustomEvent("input-mode-deactivated",{detail:{active:false}}));}disableNodeDragging(){this.svgNodes&&this.colaLayout&&this.svgNodes.on(".drag",null);}enableNodeDragging(){if(this.svgNodes&&this.colaLayout&&this.colaLayout.drag){let n=this.colaLayout.drag();this.setupNodeDragHandlers(n),this.svgNodes.call(n);}}disableZoom(){this.svg&&this.zoomBehavior&&(this.storedTransform=Co.zoomTransform(this.svg.node()),this.svg.on(".zoom",null));}enableZoom(){this.svg&&this.zoomBehavior&&(this.svg.call(this.zoomBehavior),this.storedTransform&&this.svg.call(this.zoomBehavior.transform,this.storedTransform));}zoomIn(){this.svg&&this.zoomBehavior&&this.svg.transition().duration(200).call(this.zoomBehavior.scaleBy,1.5);}zoomOut(){this.svg&&this.zoomBehavior&&this.svg.transition().duration(200).call(this.zoomBehavior.scaleBy,1/1.5);}updateZoomControlStates(){if(!this.svg||!this.zoomBehavior)return;let c=Co.zoomTransform(this.svg.node()).k,[s,e]=this.zoomBehavior.scaleExtent(),i=this.shadowRoot.querySelector("#zoom-in"),o=this.shadowRoot.querySelector("#zoom-out");i&&(i.disabled=c>=e),o&&(o.disabled=c<=s);}cleanupEdgeCreation(){this.edgeCreationState.temporaryEdge&&this.edgeCreationState.temporaryEdge.remove(),this.edgeCreationState={isCreating:false,sourceNode:null,temporaryEdge:null};}setupNodeDragHandlers(n){n.on("start.cnd",c=>{this.userHasManuallyZoomed=true;let s={x:c.x,y:c.y};this.dragStartPositions.set(c.id,s),this.dispatchEvent(new CustomEvent("node-drag-start",{detail:{id:c.id,position:s}}));}).on("end.cnd",c=>{let s=this.dragStartPositions.get(c.id);this.dragStartPositions.delete(c.id);let e={id:c.id,previous:s,current:{x:c.x,y:c.y}};this.dispatchEvent(new CustomEvent("node-drag-end",{detail:e}));});}startEdgeCreation(n){this.isInputModeActive&&(this.cleanupEdgeCreation(),this.edgeCreationState.isCreating=true,this.edgeCreationState.sourceNode=n,this.edgeCreationState.temporaryEdge=this.container.append("line").attr("class","temporary-edge").attr("x1",n.x).attr("y1",n.y).attr("x2",n.x).attr("y2",n.y).attr("stroke","#007bff").attr("stroke-width",2).attr("stroke-dasharray","5,5").attr("opacity",.7),this.svg.on("mousemove.edgecreation",()=>{if(this.edgeCreationState.isCreating&&this.edgeCreationState.temporaryEdge){let[c,s]=Co.mouse(this.container.node());this.edgeCreationState.temporaryEdge.attr("x2",c).attr("y2",s);}}));}async finishEdgeCreation(n){if(!this.isInputModeActive||!this.edgeCreationState.isCreating||!this.edgeCreationState.sourceNode)return;let c=this.edgeCreationState.sourceNode;if(c.id===n.id&&!await this.showConfirmDialog(`Are you sure you want to create a self-loop edge on "${c.label||c.id}"?`)){this.cleanupEdgeCreation();return}this.svg.on("mousemove.edgecreation",null),await this.showEdgeLabelInput(c,n);}async showEdgeLabelInput(n,c){let s=await this.showPromptDialog(`Enter label for edge from "${n.label||n.id}" to "${c.label||c.id}":`,"");s!==null&&await this.createNewEdge(n,c,s||""),this.cleanupEdgeCreation();}async createNewEdge(n,c,s){if(!this.currentLayout)return;let e=this.currentLayout.nodes.findIndex(E=>E.id===n.id),i=this.currentLayout.nodes.findIndex(E=>E.id===c.id);if(e===-1||i===-1){console.error("Could not find node indices for edge creation");return}let p={id:`edge_${n.id}_${c.id}_${Date.now()}`,source:e,target:i,label:s,relName:s,color:"#333",isUserCreated:true};this.currentLayout.links.push(p),await this.updateExternalStateForNewEdge(n,c,s),this.dispatchEvent(new CustomEvent("edge-created",{detail:{edge:p,sourceNode:n,targetNode:c}})),this.rerenderGraph();}async updateExternalStateForNewEdge(n,c,s){if(s.trim())try{let e={atoms:[n.id,c.id],types:[n.type||"untyped",c.type||"untyped"]};console.log(`Dispatching edge creation request: ${s}(${n.id}, ${c.id})`);let i=new CustomEvent("edge-creation-requested",{detail:{relationId:s,sourceNodeId:n.id,targetNodeId:c.id,tuple:e},bubbles:!0});this.dispatchEvent(i);}catch(e){console.error("Failed to update external state for new edge:",e);}}rerenderGraph(){!this.currentLayout||!this.colaLayout||(this.colaLayout.links(this.currentLayout.links),this.container.selectAll(".link-group").remove(),this.renderLinks(this.currentLayout.links,this.colaLayout),this.colaLayout.start());}async editEdgeLabel(n){if(!this.isInputModeActive)return;let c=n.label||n.relName||"",s=await this.showEdgeEditDialog("Edit edge label:",c);if(s==="DELETE"){await this.deleteEdge(n);return}if(s!==null&&s!==c){let e=s,i=this.getNodeFromEdge(n,"source"),o=this.getNodeFromEdge(n,"target");await this.updateExternalStateForEdgeModification(i,o,c,e),n.label=e,n.relName=e,this.dispatchEvent(new CustomEvent("edge-modified",{detail:{edge:n,oldLabel:c,newLabel:e}})),this.rerenderGraph();}}getNodeFromEdge(n,c){if(!this.currentLayout)return null;let s=typeof n[c]=="number"?n[c]:n[c].index;return this.currentLayout.nodes[s]||null}async updateExternalStateForEdgeModification(n,c,s,e){if(!(!n||!c))try{let i={atoms:[n.id,c.id],types:[n.type||"untyped",c.type||"untyped"]};console.log(`Dispatching edge modification request: ${s} -> ${e}`);let o=new CustomEvent("edge-modification-requested",{detail:{oldRelationId:s,newRelationId:e,sourceNodeId:n.id,targetNodeId:c.id,tuple:i},bubbles:!0});this.dispatchEvent(o);}catch(i){console.error("Failed to update external state for edge modification:",i);}}async renderLayout(n,c){if(!NT(n))throw new Error("Invalid instance layout provided. Expected an InstanceLayout instance.");let s,e=false;if(c?.policy&&c.prevInstance&&c.currInstance){let E=this.buildPolicyRawState(c),b=this.getViewportBoundsInLayoutSpace(E.transform),y=c.policy.apply({priorState:E,prevInstance:c.prevInstance,currInstance:c.currInstance,spec:{constraints:{orientation:{relative:[],cyclic:[]},alignment:[],grouping:{groups:[],subgroups:[]}},directives:{sizes:[],hiddenAtoms:[],icons:[],projections:[],edgeStyles:[]}},viewportBounds:b});s=y.effectivePriorState,e=y.useReducedIterations;}else c?.priorPositions&&(s=c.priorPositions);let i=!!(s&&s.positions.length>0),o=this.hasValidTransform(s?.transform),p=i?{priorPositions:s}:void 0;if(this.applyViewportRenderPolicy(i,o),this.svg&&this.zoomBehavior&&Co)try{if(o){let E=s.transform,b=Co.zoomIdentity.translate(E.x,E.y).scale(E.k);this.svg.call(this.zoomBehavior.transform,b);}else if(!i){let E=Co.zoomIdentity;this.svg.call(this.zoomBehavior.transform,E);}}catch(E){console.warn("Failed to set zoom transform:",E);}try{if(!Co)throw new Error("D3 library not available. Please ensure D3 v4 is loaded from CDN.");if(!Md){if(!window.cola)throw new Error("WebCola library not available. Please ensure vendor/cola.js is loaded.");Md=window.cola;}if((!this.container||!this.svg)&&this.initializeD3(),!this.container)throw new Error("Failed to initialize D3 container. SVG elements may not be available.");this.showLoading(),this.updateLoadingProgress("Translating layout...");let b=this.shadowRoot.querySelector("#svg-container").getBoundingClientRect(),y=b.width||800,m=b.height||600,l=await new exports.WebColaTranslator().translate(n,y,m,p);this.updateLoadingProgress(`Computing layout for ${l.nodes.length} nodes...`);let a=l.nodes.length,h=Pi.INITIAL_UNCONSTRAINED_ITERATIONS,d=Pi.INITIAL_USER_CONSTRAINT_ITERATIONS,g=Pi.INITIAL_ALL_CONSTRAINTS_ITERATIONS;i&&e&&(h=0,d=Math.min(10,d),g=Math.min(20,g)),a>100?(h=Math.max(i?0:5,Math.floor(h*.5)),d=Math.max(25,Math.floor(d*.5)),g=Math.max(100,Math.floor(g*.5))):a>50&&(h=Math.max(i?0:8,Math.floor(h*.8)),d=Math.max(40,Math.floor(d*.8)),g=Math.max(150,Math.floor(g*.75)));let{scaledConstraints:_,linkLength:S,groupCompactness:v}=this.getScaledDetails(l.constraints,zF,l.nodes,l.groups,l.links);this.updateLoadingProgress("Applying constraints and initializing...");let T=i?.1:.001,G=Md.d3adaptor(Co).linkDistance(S).convergenceThreshold(T).avoidOverlaps(!0).handleDisconnected(!0).nodes(l.nodes).links(l.links).constraints(_).groups(l.groups).groupCompactness(v).size([l.FIG_WIDTH,l.FIG_HEIGHT]);this.currentLayout=l,this.colaLayout=G,this.container.selectAll("*").remove(),this.renderGroups(l.groups,G),this.renderLinks(l.links,G),this.renderNodes(l.nodes,G);let q=0,j=h+d+g;G.on("tick",()=>{if(q++,q%20===0){let B=Math.min(95,Math.round(q/j*100));this.updateLoadingProgress(`Computing layout... ${B}%`);}this.layoutFormat==="default"||!this.layoutFormat||this.layoutFormat===null?this.updatePositions():this.layoutFormat==="grid"?this.gridUpdatePositions():console.warn(`Unknown layout format: ${this.layoutFormat}. Skipping position updates.`);}).on("end",()=>{this.updateLoadingProgress("Finalizing..."),this.layoutFormat==="default"||!this.layoutFormat?this.routeEdges():this.layoutFormat==="grid"?this.gridify(10,25,10):console.warn(`Unknown layout format: ${this.layoutFormat}. Skipping edge routing.`),this.isUnsatCore&&this.showErrorIcon(),this.dispatchRelationsAvailableEvent(),this.dispatchEvent(new CustomEvent("layout-complete",{detail:{nodePositions:this.getNodePositions()}})),this.updateRoutingModeDropdown(),this.hideLoading();});try{G.start(h,d,g,Pi.GRID_SNAP_ITERATIONS);}catch(B){console.warn("WebCola layout start encountered an error, trying alternative approach:",B);try{G.start();}catch(J){throw console.error("Both WebCola start methods failed:",J),new Error(`WebCola layout failed to start: ${J.message}`)}}}catch(E){console.error("Error rendering layout:",E),this.showError(`Layout rendering failed: ${E.message}`);}}clear(){if(this.colaLayout)try{this.colaLayout.stop?.();}catch{}this.container&&this.container.selectAll("*").remove(),this.currentLayout=null,this.colaLayout=null,this.svgNodes=null,this.svgLinks=null,this.svgGroups=null,this.edgeRoutingCache.edgesBetweenNodes.clear(),this.edgeRoutingCache.alignmentEdges.clear(),this.dragStartPositions.clear(),this.hideLoading();}getNodePositions(){return this.currentLayout?.nodes?this.currentLayout.nodes.map(n=>({id:n.id,x:n.x,y:n.y})):[]}getCurrentTransform(){if(this.svg&&this.svg.node())try{let n=Co.zoomTransform(this.svg.node());return {k:n.k,x:n.x,y:n.y}}catch{return {k:1,x:0,y:0}}return {k:1,x:0,y:0}}getLayoutState(){return {positions:this.getNodePositions(),transform:this.getCurrentTransform()}}addToolbarControl(n){let c=this.shadowRoot?.querySelector("#graph-toolbar");c&&c.appendChild(n);}getToolbar(){return this.shadowRoot?.querySelector("#graph-toolbar")||null}renderGroups(n,c){if(!this.currentLayout.nodes||this.currentLayout.nodes.length===0){console.warn("Cannot render groups: nodes not available");return}this.svgGroups=this.setupGroups(n,this.currentLayout.nodes,c);}setupLinks(n,c){let s=this.container.selectAll(".link-group").data(n).enter().append("g").attr("class","link-group");return this.setupLinkPaths(s),this.setupLinkLabels(s),this.setupEdgeEndpointMarkers(s),s}setupLinkPaths(n){n.append("path").attr("class",c=>this.isAlignmentEdge(c)?"alignmentLink":this.isInferredEdge(c)?"inferredLink":"link").attr("data-link-id",c=>c.id||"").attr("stroke",c=>this.isAlignmentEdge(c)?"none":c.color).attr("fill","none").attr("opacity",c=>this.isAlignmentEdge(c)?0:null).style("stroke-width",c=>this.isAlignmentEdge(c)?"0":c.weight!=null?`${c.weight}px`:null).attr("stroke-dasharray",c=>this.isAlignmentEdge(c)?null:this.getEdgeDasharray(c.style)).attr("marker-end",c=>this.isAlignmentEdge(c)?"none":"url(#end-arrow)").attr("marker-start",c=>this.isAlignmentEdge(c)||!c.bidirectional?"none":"url(#start-arrow)").on("click.inputmode",c=>{this.isInputModeActive&&!this.isAlignmentEdge(c)&&(Co.event.stopPropagation(),this.editEdgeLabel(c).catch(s=>{console.error("Error editing edge label:",s);}));}).style("cursor",()=>this.isInputModeActive?"pointer":"default");}getEdgeDasharray(n){if(!n)return null;switch(n.toLowerCase()){case "dotted":return "1,4";case "dashed":return "6,4";case "solid":return null;default:return null}}setupLinkLabels(n){n.filter(c=>!this.isAlignmentEdge(c)&&(this.isInferredEdge(c)||c.showLabel!==false)).append("text").attr("class","linklabel").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("font-family","system-ui").attr("pointer-events","none").text(c=>c.label||c.relName||"");}setupEdgeEndpointMarkers(n){n.filter(c=>!this.isAlignmentEdge(c)).append("circle").attr("class","edge-endpoint-marker target-marker").attr("r",8).attr("fill","#007bff").attr("stroke","white").attr("stroke-width",2).attr("opacity",0).attr("cursor","move").style("pointer-events","none").call(Co.drag().on("start",c=>this.startEdgeEndpointDrag(c,"target")).on("drag",c=>this.dragEdgeEndpoint(c,"target")).on("end",c=>this.endEdgeEndpointDrag(c,"target"))),n.filter(c=>!this.isAlignmentEdge(c)).append("circle").attr("class","edge-endpoint-marker source-marker").attr("r",8).attr("fill","#28a745").attr("stroke","white").attr("stroke-width",2).attr("opacity",0).attr("cursor","move").style("pointer-events","none").call(Co.drag().on("start",c=>this.startEdgeEndpointDrag(c,"source")).on("drag",c=>this.dragEdgeEndpoint(c,"source")).on("end",c=>this.endEdgeEndpointDrag(c,"source")));}startEdgeEndpointDrag(n,c){Co.event.sourceEvent.stopPropagation(),this.edgeDragState.isDragging=true,this.edgeDragState.edge=n,this.edgeDragState.endpoint=c,console.log(`\u{1F535} Started dragging ${c} endpoint of edge:`,n.id);}dragEdgeEndpoint(n,c){if(!this.edgeDragState.isDragging)return;let[s,e]=Co.mouse(this.container.node()),i=c==="target"?".target-marker":".source-marker";this.container.selectAll(".link-group").filter(o=>o.id===n.id).select(i).attr("cx",s).attr("cy",e);}async endEdgeEndpointDrag(n,c){if(!this.edgeDragState.isDragging)return;let[s,e]=Co.mouse(this.container.node()),i=this.findNodeAtPosition(s,e);i?(console.log(`\u{1F517} Reconnecting ${c} to node:`,i.id),await this.reconnectEdge(n,c,i)):(console.log("\u{1F5D1}\uFE0F No node found - deleting edge:",n.id),await this.deleteEdge(n)),this.edgeDragState={isDragging:false,edge:null,endpoint:null,dragMarker:null},this.rerenderGraph();}findNodeAtPosition(n,c){if(!this.currentLayout?.nodes)return null;for(let s of this.currentLayout.nodes){let e=(s.visualWidth??s.width??0)/2,i=(s.visualHeight??s.height??0)/2;if(n>=s.x-e&&n<=s.x+e&&c>=s.y-i&&c<=s.y+i)return s}return null}async reconnectEdge(n,c,s){let e=this.getNodeFromEdge(n,"source"),i=this.getNodeFromEdge(n,"target");if(!e||!i){console.error("Could not find source or target node");return}let o,p;if(c==="source"?(o=s,p=i):(o=e,p=s),o.id===e.id&&p.id===i.id){console.log("\u23ED\uFE0F Edge already connected to this node, no change needed");return}let E=n.label||n.relName||"";if(!E.trim()){console.warn("Edge has no relation name, cannot reconnect");return}let b={atoms:[e.id,i.id],types:[e.type||"untyped",i.type||"untyped"]},y={atoms:[o.id,p.id],types:[o.type||"untyped",p.type||"untyped"]};console.log(`\u{1F504} Reconnecting edge from ${e.id}->${i.id} to ${o.id}->${p.id}`);let m=new CustomEvent("edge-reconnection-requested",{detail:{relationId:E,oldTuple:b,newTuple:y,oldSourceNodeId:e.id,oldTargetNodeId:i.id,newSourceNodeId:o.id,newTargetNodeId:p.id},bubbles:true});this.dispatchEvent(m);let u=this.currentLayout.nodes.findIndex(a=>a.id===o.id),l=this.currentLayout.nodes.findIndex(a=>a.id===p.id);u!==-1&&l!==-1&&(n.source=u,n.target=l);}async deleteEdge(n){let c=this.getNodeFromEdge(n,"source"),s=this.getNodeFromEdge(n,"target");if(!c||!s){console.error("Could not find source or target node for edge deletion");return}let e=n.label||n.relName||"";if(!e.trim()){console.warn("Edge has no relation name, cannot delete from data instance"),this.removeEdgeFromLayout(n);return}let i={atoms:[c.id,s.id],types:[c.type||"untyped",s.type||"untyped"]};console.log(`\u{1F5D1}\uFE0F Deleting edge: ${e}(${c.id}, ${s.id})`);let o=new CustomEvent("edge-modification-requested",{detail:{oldRelationId:e,newRelationId:"",sourceNodeId:c.id,targetNodeId:s.id,tuple:i},bubbles:true});this.dispatchEvent(o),this.removeEdgeFromLayout(n);}removeEdgeFromLayout(n){if(!this.currentLayout?.links)return;let c=this.currentLayout.links.findIndex(s=>s.id===n.id);c!==-1&&(this.currentLayout.links.splice(c,1),console.log(`\u2705 Edge removed from layout: ${n.id}`));}setupGroups(n,c,s){let e=this.setupGroupRectangles(n,c,s);return this.svgGroupLabels=this.setupGroupLabels(n,s),e}setupGroupRectangles(n,c,s){return this.container.selectAll(".group").data(n).enter().append("rect").attr("class",i=>this.isDisconnectedGroup(i)?"disconnectedNode":this.isErrorGroup(i)?"error-group":"group").attr("rx",Pi.GROUP_BORDER_RADIUS).attr("ry",Pi.GROUP_BORDER_RADIUS).style("fill",i=>this.isDisconnectedGroup(i)?"transparent":c[i.keyNode]?.color||"#cccccc").attr("fill-opacity",Pi.GROUP_FILL_OPACITY).attr("stroke",i=>this.isDisconnectedGroup(i)?"none":c[i.keyNode]?.color||"#999999").attr("stroke-width",1).call(s.drag)}resolveGroupLeafToNodeIndex(n){if(typeof n=="number"&&Number.isInteger(n)&&n>=0)return n;if(n&&typeof n=="object"){let c=n;if(typeof c.index=="number"&&Number.isInteger(c.index)&&c.index>=0)return c.index;if(typeof c.id=="string"&&this.currentLayout?.nodes){let s=this.currentLayout.nodes.findIndex(e=>e.id===c.id);return s>=0?s:null}}return null}collectGroupNodeIndices(n,c){let s=new Set,e=new Set,i=(p,E)=>{if(p){if(typeof E=="number"){if(e.has(E))return;e.add(E);}Array.isArray(p.leaves)&&p.leaves.forEach(b=>{let y=this.resolveGroupLeafToNodeIndex(b);y!==null&&s.add(y);}),Array.isArray(p.groups)&&p.groups.forEach(b=>{typeof b=="number"&&Number.isInteger(b)&&b>=0&&b<c.length&&i(c[b],b);});}},o=c.indexOf(n);return i(n,o>=0?o:void 0),Array.from(s)}getNodeMainLabelFontSize(n){let c=n?._mainLabelFontSize;if(typeof c=="number"&&Number.isFinite(c))return c;let s=n?.visualWidth??n?.width??100,e=n?.visualHeight??n?.height??60,i=Math.max(1,s-Pi.TEXT_PADDING*2),o=Math.max(1,e-Pi.TEXT_PADDING*2),p=n?.label||n?.name||n?.id||"Node",E=Object.keys(n?.labels||{}).length>0,b=Object.keys(n?.attributes||{}).length>0,m=E||b?o*.5:o;return this.calculateOptimalFontSize(p,i,Math.max(1,m),"system-ui")}calculateGroupLabelFontSize(n,c){if(!this.currentLayout?.nodes?.length)return Pi.DEFAULT_FONT_SIZE;let s=this.collectGroupNodeIndices(n,c);if(s.length===0)return Pi.DEFAULT_FONT_SIZE;let e=s.map(p=>this.currentLayout.nodes[p]).filter(p=>!!p).map(p=>this.getNodeMainLabelFontSize(p));if(e.length===0)return Pi.DEFAULT_FONT_SIZE;let i=e.reduce((p,E)=>p+E,0)/e.length,o=Math.max(Pi.MIN_FONT_SIZE,Math.min(i,Pi.MAX_FONT_SIZE));return Math.round(o*10)/10}setupGroupLabels(n,c){return this.container.selectAll(".groupLabel").data(n).enter().append("text").attr("class","groupLabel").attr("text-anchor","middle").attr("dominant-baseline","hanging").attr("font-family","system-ui").attr("font-size",s=>{let e=this.calculateGroupLabelFontSize(s,n);return s._groupLabelFontSize=e,`${e}px`}).attr("font-weight","bold").attr("fill","#333").attr("pointer-events","none").text(s=>s.showLabel||false?(s.padding&&(s.padding=Math.max(s.padding,Pi.GROUP_LABEL_PADDING)),s.name||""):"").call(c.drag)}renderLinks(n,c){this.edgeRoutingCache.alignmentEdges.clear(),this.svgLinkGroups=this.setupLinks(n,c);}setupNodes(n,c){let s=c.drag();this.setupNodeDragHandlers(s);let e=this.container.selectAll(".node").data(n).enter().append("g").attr("class",i=>{let o=this.isErrorNode(i)?"error-node":"node";return this.isErrorNode(i)&&this.isSmallNode(i)?o+" small-error-node":o}).call(s).on("mousedown.inputmode",i=>{this.isInputModeActive&&(Co.event.stopPropagation(),this.startEdgeCreation(i));}).on("mouseup.inputmode",i=>{this.isInputModeActive&&this.edgeCreationState.isCreating&&(Co.event.stopPropagation(),this.finishEdgeCreation(i).catch(o=>{console.error("Error finishing edge creation:",o);}));}).on("mouseover",function(i){Co.select(this).append("title").attr("class","node-tooltip").text(`ID: ${i.id}`);}).on("mouseout",function(){Co.select(this).select("title.node-tooltip").remove();});return this.setupNodeRectangles(e),this.setupNodeIcons(e),this.setupMostSpecificTypeLabels(e),this.setupNodeLabels(e),e}setupNodeRectangles(n){n.append("rect").attr("width",c=>c.visualWidth??c.width).attr("height",c=>c.visualHeight??c.height).attr("x",c=>-(c.visualWidth??c.width)/2).attr("y",c=>-(c.visualHeight??c.height)/2).attr("stroke",c=>c.color||"black").attr("rx",Pi.NODE_BORDER_RADIUS).attr("ry",Pi.NODE_BORDER_RADIUS).attr("stroke-width",Pi.NODE_STROKE_WIDTH).attr("fill",c=>{let s=this.isHiddenNode(c),e=!!c.icon,i=c.showLabels;return s||e&&!i?"transparent":"white"});}setupNodeIcons(n){n.filter(c=>c.icon).append("image").attr("xlink:href",c=>c.icon).attr("width",c=>{let s=c.visualWidth??c.width;return c.showLabels?s*Pi.SMALL_IMG_SCALE_FACTOR:s}).attr("height",c=>{let s=c.visualHeight??c.height;return c.showLabels?s*Pi.SMALL_IMG_SCALE_FACTOR:s}).attr("x",c=>{let s=c.visualWidth??c.width;return c.showLabels?c.x+s-s*Pi.SMALL_IMG_SCALE_FACTOR:c.x-s/2}).attr("y",c=>{let s=c.visualHeight??c.height;return c.y-s/2}).append("title").text(c=>c.label||c.name||c.id||"Node").on("error",function(c,s){Co.select(this).attr("xlink:href","img/default.png"),console.error(`Failed to load icon for node ${s.id}: ${s.icon}`);});}setupMostSpecificTypeLabels(n){n.append("text").attr("class","mostSpecificTypeLabel").style("fill",c=>c.color||"black").text(c=>c.mostSpecificType||"");}getTextMeasurementContext(){return this.textMeasurementCanvas||(this.textMeasurementCanvas=document.createElement("canvas")),this.textMeasurementCanvas.getContext("2d")}measureTextWidth(n,c,s="system-ui"){let e=this.getTextMeasurementContext();return e.font=`${c}px ${s}`,e.measureText(n).width}calculateOptimalFontSize(n,c,s,e="system-ui"){let i=Pi.DEFAULT_FONT_SIZE;for(;i>Pi.MIN_FONT_SIZE;){let o=this.measureTextWidth(n,i,e),p=i*Pi.LINE_HEIGHT_RATIO;if(o<=c&&p<=s)break;i-=.5;}for(;i<Pi.MAX_FONT_SIZE;){let o=i+.5,p=this.measureTextWidth(n,o,e),E=o*Pi.LINE_HEIGHT_RATIO;if(p>c||E>s)break;i=o;}return Math.max(Pi.MIN_FONT_SIZE,Math.min(i,Pi.MAX_FONT_SIZE))}wrapText(n,c,s,e="system-ui"){let i=n.split(/\s+/),o=[],p="";for(let E of i){let b=p?`${p} ${E}`:E;this.measureTextWidth(b,s,e)<=c?p=b:p?(o.push(p),p=E):o.push(E);}return p&&o.push(p),o}setupNodeLabelsWithDynamicSizing(n){n.append("text").attr("class","label").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("font-family","system-ui").attr("fill","black").each((c,s,e)=>{if(this.isHiddenNode(c)||!c.showLabels)return;let o=Co.select(e[s]),p=c.width||100,E=c.height||60,b=p-Pi.TEXT_PADDING*2,y=E-Pi.TEXT_PADDING*2,m=c.label||c.name||c.id||"Node",u=c.attributes||{},l=Object.entries(u).sort(([z],[tt])=>z.localeCompare(tt)),a=c.labels||{},h=Object.entries(a),d=h.length>0,g=l.length>0,_=d||g,S=_?y*.5:y,v=this.calculateOptimalFontSize(m,b,S,"system-ui");c._mainLabelFontSize=v,o.attr("font-size",`${v}px`);let T=v*Pi.LINE_HEIGHT_RATIO,G=h.length+l.length,q=_?-G*T*.5:0;c._labelVerticalOffset=q,c._labelLineHeight=T,o.append("tspan").attr("x",0).attr("dy",`${q}px`).attr("class","main-label-tspan").style("font-weight","bold").style("font-size",`${v}px`).text(m);let j="";for(let[z,tt]of h){let pt=Array.isArray(tt)?tt.join(", "):String(tt);pt.length>j.length&&(j=pt);}for(let[z,tt]of l){let pt=`${z}: ${tt}`;pt.length>j.length&&(j=pt);}let B=v*.65,J=y-T,w=G>0?this.calculateOptimalFontSize(j||"SampleText",b,J/G,"system-ui"):v*.8,$=Math.max(w,B);if(d){let z="black";for(let[tt,pt]of h){let Z=Array.isArray(pt)?pt.join(", "):String(pt);o.append("tspan").attr("x",0).attr("dy",`${$*Pi.LINE_HEIGHT_RATIO}px`).style("font-size",`${$}px`).style("fill",z).style("font-style","italic").text(Z);}}if(g)for(let z=0;z<l.length;z++){let[tt,pt]=l[z],Z=`${tt}: ${pt}`;o.append("tspan").attr("x",0).attr("dy",`${$*Pi.LINE_HEIGHT_RATIO}px`).style("font-size",`${$}px`).text(Z);}});}setupNodeLabels(n){this.setupNodeLabelsWithDynamicSizing(n);}renderNodes(n,c){this.svgNodes=this.setupNodes(n,c);}resolveGroupEdgeEndpoints(n){if(!n.groupId)return {source:n.source,target:n.target};let c=this.currentLayout?.groups||[],s=c.find(p=>p.id===n.groupId);if(this._groupEdgeDebugLogged||(this._groupEdgeDebugLogged=new Set),this._groupEdgeDebugLogged.has(n.id)||(this._groupEdgeDebugLogged.add(n.id),console.log("[groupEdge DEBUG]",{edgeId:n.id,groupId:n.groupId,keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id,sourceIsInt:typeof n.source=="number",targetIsInt:typeof n.target=="number",groupFound:!!s,groupId_on_group:s?.id,availableGroupIds:c.map(p=>p.id)})),!s)return {source:n.source,target:n.target};let e=n.source,i=n.target;n.source?.id===n.keyNodeId?i=s:n.target?.id===n.keyNodeId?e=s:console.warn("[groupEdge] keyNodeId matched neither side",{keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id});let o=e===s?n.source:i===s?n.target:null;if(o&&!s.bounds&&o.x!=null&&Md?.Rectangle){let p=(o.visualWidth??o.width??50)/2,E=(o.visualHeight??o.height??30)/2;s.bounds=new Md.Rectangle(o.x-p,o.x+p,o.y-E,o.y+E);}return {source:e,target:i}}updatePositions(){this.svgGroups.attr("x",n=>n.bounds.x).attr("y",n=>n.bounds.y).attr("width",n=>n.bounds.width()).attr("height",n=>n.bounds.height()).lower(),this.svgNodes.select("rect").each(n=>{n.bounds&&(n.innerBounds=n.bounds.inflate(-1));}).attr("x",n=>n.x-(n.visualWidth??n.width)/2).attr("y",n=>n.y-(n.visualHeight??n.height)/2).attr("width",n=>n.visualWidth??n.width).attr("height",n=>n.visualHeight??n.height),this.svgNodes.select("image").attr("x",n=>{let c=n.visualWidth??n.width;return n.showLabels?n.x+c/2-c*Pi.SMALL_IMG_SCALE_FACTOR:n.x-c/2}).attr("y",n=>{let c=n.visualHeight??n.height;return n.showLabels,n.y-c/2}),this.svgNodes.select(".mostSpecificTypeLabel").attr("x",n=>n.x-(n.visualWidth??n.width??0)/2+5).attr("y",n=>n.y-(n.visualHeight??n.height??0)/2+10).raise(),this.svgNodes.select(".label").attr("x",n=>n.x).attr("y",n=>n.y).each((n,c,s)=>{let e=n._labelVerticalOffset||0,i=n._labelLineHeight||12;Co.select(s[c]).selectAll("tspan").attr("x",n.x).attr("dy",(o,p)=>p===0?`${e}px`:`${i}px`);}).raise(),this.svgLinkGroups.select("path").attr("d",n=>{let{source:c,target:s}=this.resolveGroupEdgeEndpoints(n),e=this.getStableEdgePath(c,s);return this.lineFunction(e)}).attr("marker-end",n=>this.isAlignmentEdge(n)?"none":"url(#end-arrow)").attr("marker-start",n=>this.isAlignmentEdge(n)||!n.bidirectional?"none":"url(#start-arrow)").raise(),this.svgLinkGroups.select(".linklabel").attr("x",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?this.calculateNewPosition(c,"x"):(n.source.x+n.target.x)/2}).attr("y",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?this.calculateNewPosition(c,"y"):(n.source.y+n.target.y)/2}).style("font-size",()=>{let n=this.getCurrentZoomScale(),c=12,s=n<1?c/Math.sqrt(n):c;return `${Math.min(s,16)}px`}).raise(),this.updateEdgeEndpointMarkers(),this.svgGroupLabels.attr("x",n=>n.bounds?n.bounds.x+n.bounds.width()/2:0).attr("y",n=>{if(!n.bounds)return 0;let c=n._groupLabelFontSize||Pi.DEFAULT_FONT_SIZE;return n.bounds.y+Math.max(4,c*.35)}).attr("text-anchor","middle").lower(),this.svgLinkGroups.selectAll("marker").raise(),this.svgLinkGroups.selectAll(".linklabel").raise(),this.svgGroups.selectAll(".error-group").raise(),this.svgNodes.selectAll(".error-node").raise();}updateEdgeEndpointMarkers(){this.svgLinkGroups&&(this.svgLinkGroups.select(".target-marker").attr("cx",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(c){let s=c.getTotalLength();return c.getPointAtLength(s).x}return n.target.x||0}).attr("cy",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(c){let s=c.getTotalLength();return c.getPointAtLength(s).y}return n.target.y||0}).attr("opacity",this.isInputModeActive?.8:0).style("pointer-events",this.isInputModeActive?"all":"none").raise(),this.svgLinkGroups.select(".source-marker").attr("cx",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?c.getPointAtLength(0).x:n.source.x||0}).attr("cy",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?c.getPointAtLength(0).y:n.source.y||0}).attr("opacity",this.isInputModeActive?.8:0).style("pointer-events",this.isInputModeActive?"all":"none").raise());}gridUpdatePositions(){this.ensureNodeBounds(true);let n=this.container.selectAll(".node"),c=this.container.selectAll(".mostSpecificTypeLabel"),s=this.container.selectAll(".label"),e=this.container.selectAll(".group"),i=this.container.selectAll(".groupLabel");n.select("rect").each(function(p){p.innerBounds=p.bounds.inflate(-1);}).attr("x",function(p){return p.bounds.x}).attr("y",function(p){return p.bounds.y}).attr("width",function(p){return p.bounds.width()}).attr("height",function(p){return p.bounds.height()}),n.select("image").attr("x",function(p){let E=p.visualWidth??p.width;return p.showLabels?p.x+E/2-E*Pi.SMALL_IMG_SCALE_FACTOR:p.bounds.x}).attr("y",function(p){let E=p.visualHeight??p.height;return p.showLabels?p.y-E/2:p.bounds.y}),c.attr("x",function(p){return p.bounds.x+5}).attr("y",function(p){return p.bounds.y+10}).raise(),s.attr("x",p=>p.x).attr("y",p=>p.y).each(function(p){var E=0;Co.select(this).selectAll("tspan").attr("x",p.x).attr("dy",function(){return E+=1,E===1?"0em":"1em"});}).raise(),e.attr("x",function(p){return p.bounds.x}).attr("y",function(p){return p.bounds.y}).attr("width",function(p){return p.bounds.width()}).attr("height",function(p){return p.bounds.height()}).lower(),i.attr("x",function(p){return p.bounds.x+p.bounds.width()/2}).attr("y",function(p){let E=p._groupLabelFontSize||Pi.DEFAULT_FONT_SIZE;return p.bounds.y+Math.max(4,E*.35)}).attr("text-anchor","middle").raise();let o=this.container.selectAll(".link-group");o.select("path").attr("d",p=>{if(p.source?.id===p.target?.id){let h=this.createSelfLoopRoute(p);return this.lineFunction(h)}let{source:E,target:b}=this.resolveGroupEdgeEndpoints(p),y=h=>h.bounds?typeof h.bounds.cx=="function"?{x:h.bounds.cx(),y:h.bounds.cy()}:{x:(h.bounds.x+h.bounds.X)/2,y:(h.bounds.y+h.bounds.Y)/2}:{x:h.x??0,y:h.y??0},m=y(E),u=y(b),l=u.x-m.x,a=u.y-m.y;if(Math.abs(l)>Math.abs(a)){let h=m.x+l/2;return this.gridLineFunction([{x:m.x,y:m.y},{x:h,y:m.y},{x:h,y:u.y},{x:u.x,y:u.y}])}else {let h=m.y+a/2;return this.gridLineFunction([{x:m.x,y:m.y},{x:m.x,y:h},{x:u.x,y:h},{x:u.x,y:u.y}])}}),o.select("text.linklabel").attr("x",p=>{let E=this.shadowRoot?.querySelector(`path[data-link-id="${p.id}"]`);if(E){let m=E.getTotalLength();return E.getPointAtLength(m/2).x}let b=p.source?.x??p.source?.bounds?.cx()??0,y=p.target?.x??p.target?.bounds?.cx()??0;return (b+y)/2}).attr("y",p=>{let E=this.shadowRoot?.querySelector(`path[data-link-id="${p.id}"]`);if(E){let m=E.getTotalLength();return E.getPointAtLength(m/2).y}let b=p.source?.y??p.source?.bounds?.cy()??0,y=p.target?.y??p.target?.bounds?.cy()??0;return (b+y)/2}).raise();}routeEdges(){try{this.ensureNodeBounds(!0),typeof this.colaLayout?.prepareEdgeRouting=="function"&&this.colaLayout.prepareEdgeRouting(Pi.VIEWBOX_PADDING/Pi.EDGE_ROUTE_MARGIN_DIVISOR),this.buildEdgeRoutingCaches(),this.routeLinkPaths(),this.updateLinkLabelsAfterRouting(),this.fitViewportToContent();}catch(n){console.error("Error in edge routing:",n),this.showError(`Edge routing failed: ${n.message}`);}}ensureNodeBounds(n=false){if(!(!this.currentLayout?.nodes||!Md?.Rectangle))for(let c of this.currentLayout.nodes){if(!n&&c.bounds&&typeof c.bounds.rayIntersection=="function"){let b=c.bounds.cx(),y=c.bounds.cy(),m=1;if(Math.abs(b-(c.x||0))<m&&Math.abs(y-(c.y||0))<m)continue}let s=(c.visualWidth??c.width??50)/2,e=(c.visualHeight??c.height??30)/2,i=(c.x||0)-s,o=(c.x||0)+s,p=(c.y||0)-e,E=(c.y||0)+e;c.bounds=new Md.Rectangle(i,o,p,E),c.innerBounds=c.bounds.inflate(-1);}}buildEdgeRoutingCaches(){this.edgeRoutingCache.edgesBetweenNodes.clear(),this.edgeRoutingCache.alignmentEdges.clear(),this.currentLayout?.links&&(this.currentLayout.links.forEach(n=>{n.id?.startsWith("_alignment_")&&this.edgeRoutingCache.alignmentEdges.add(n.id);}),this.currentLayout.links.forEach(n=>{if(this.isAlignmentEdge(n))return;let c=n.source.id,s=n.target.id,e=this.getNodePairKey(c,s);this.edgeRoutingCache.edgesBetweenNodes.has(e)||this.edgeRoutingCache.edgesBetweenNodes.set(e,[]),this.edgeRoutingCache.edgesBetweenNodes.get(e).push(n);}));}getNodePairKey(n,c){return n<c?`${n}:${c}`:`${c}:${n}`}route(n=[],c=[],s,e){n.forEach(o=>{let p=o.bounds||o.innerBounds||this.createFallbackBounds(o);o.routerNode={name:o.name,bounds:p};}),c.forEach(o=>{o.bounds||console.warn("Grid routing group missing bounds; routing may be degraded.",o),o.routerNode={bounds:o.bounds?.inflate(-e)??o.bounds,children:(typeof o.groups<"u"?o.groups.map(p=>n.length+p.id):[]).concat(typeof o.leaves<"u"?o.leaves.map(p=>p.index):[])};});let i=n.concat(c).map((o,p)=>o.routerNode?(o.routerNode.id=p,o.routerNode):null).filter(Boolean);return new Md.GridRouter(i,{getChildren:o=>o.children,getBounds:o=>o.bounds},s-e)}gridify(n,c,s){if(this.isGridifyingInProgress){console.warn("[gridify] Already in progress, skipping re-entrant call");return}this.isGridifyingInProgress=true;try{this.gridifyInternal(n,c,s);}catch(e){console.log("Error routing edges in GridRouter"),console.error(e);try{this.fallbackGridRouting(this.currentLayout?.links??[]);}catch(o){console.error("Fallback grid routing also failed:",o);}let i=document.getElementById("runtime_messages");if(i){let o=document.createElement("div");o.className="alert alert-danger alert-dismissible fade show",o.setAttribute("role","alert"),o.innerHTML="Runtime (WebCola) error when gridifying edges. You may have to click and drag these nodes slightly to un-stick layout.",i.querySelectorAll(".alert").forEach(E=>{E.innerHTML===o.innerHTML&&E.remove();}),i.appendChild(o);}}finally{this.isGridifyingInProgress=false;}}gridifyInternal(n,c,s){let e=this.currentLayout?.nodes??[],i=this.currentLayout?.groups??[],o=this.currentLayout?.links??[];if(e.length===0){console.warn("No nodes available for GridRouter; skipping gridify.");return}if(o.length===0){console.warn("No edges to route in GridRouter");return}console.log("[gridify] Node positions BEFORE ensureNodeBounds:"),e.slice(0,3).forEach(a=>{console.log(` ${a.id}: x=${a.x?.toFixed(2)}, y=${a.y?.toFixed(2)}, bounds.cx=${a.bounds?.cx?.()?.toFixed(2)}, bounds.x=${a.bounds?.x?.toFixed(2)}`);}),this.ensureNodeBounds(true);let p=e.filter(a=>!Number.isFinite(a.x)||!Number.isFinite(a.y));if(p.length>0){console.warn("[gridify] Found nodes with invalid positions, falling back to default routing:",p.map(a=>({id:a.id,x:a.x,y:a.y}))),this.fallbackGridRouting(o);return}console.log("[gridify] Node positions AFTER ensureNodeBounds:"),e.slice(0,3).forEach(a=>{console.log(` ${a.id}: x=${a.x?.toFixed(2)}, y=${a.y?.toFixed(2)}, bounds.cx=${a.bounds?.cx?.()?.toFixed(2)}, bounds.x=${a.bounds?.x?.toFixed(2)}`);});let E=this.route(e,i,c,s),b=[],y=o.filter(a=>{let h=a?.source?.routerNode&&a?.target?.routerNode,d=a?.source?.id===a?.target?.id;return h&&!d}),m=o.filter(a=>a?.source?.id===a?.target?.id);console.log("[gridify] Total edges:",o.length,"Routable:",y.length,"Self-loops:",m.length),y.length+m.length!==o.length&&o.filter(h=>(!h?.source?.routerNode||!h?.target?.routerNode)&&h?.source?.id!==h?.target?.id).forEach(h=>{console.warn("[gridify] Unroutable edge:",h.id,"source routerNode:",!!h?.source?.routerNode,"target routerNode:",!!h?.target?.routerNode,"source:",h?.source?.id,"x:",h?.source?.x,"y:",h?.source?.y,"target:",h?.target?.id,"x:",h?.target?.x,"y:",h?.target?.y);}),b=E.routeEdges(y,n,function(a){return a.source.routerNode.id},function(a){return a.target.routerNode.id});let u=new Map;y.forEach((a,h)=>{let d=b[h];a?.id&&d&&u.set(a.id,this.adjustGridRouteForEdge(a,d));}),console.log("[gridify] Routes generated:",u.size,"out of",y.length),this.container.selectAll(".link-group").data(o,a=>a.id??a).select("path").attr("d",a=>{if(a.source?.id===a.target?.id){let T=this.createSelfLoopRoute(a);return this.lineFunction(T)}let h=u.get(a.id);if(!h){let T=a.source?.x??a.source?.bounds?.cx()??0,G=a.source?.y??a.source?.bounds?.cy()??0,q=a.target?.x??a.target?.bounds?.cx()??0,j=a.target?.y??a.target?.bounds?.cy()??0;console.log("[gridify] Fallback path for edge:",a.id,"from",a.source?.id,"(",T,",",G,")","to",a.target?.id,"(",q,",",j,")");let B=q-T,J=j-G;if(Math.abs(B)>Math.abs(J)){let w=T+B/2;return this.gridLineFunction([{x:T,y:G},{x:w,y:G},{x:w,y:j},{x:q,y:j}])}else {let w=G+J/2;return this.gridLineFunction([{x:T,y:G},{x:T,y:w},{x:q,y:w},{x:q,y:j}])}}let S=Md.GridRouter.getRoutePath(h,5,3,7);return this.adjustGridRouteForArrowPositioning(a,S.routepath,h)||S.routepath}),this.gridUpdateLinkLabels(o,u),this.fitViewportToContent(),this.dispatchEvent(new Event("relationsAvailable"));}fallbackGridRouting(n){this.container.selectAll(".link-group").data(n,s=>s.id??s).select("path").attr("d",s=>{if(s.source?.id===s.target?.id){let y=this.createSelfLoopRoute(s);return this.lineFunction(y)}let e=s.source?.x??s.source?.bounds?.cx()??0,i=s.source?.y??s.source?.bounds?.cy()??0,o=s.target?.x??s.target?.bounds?.cx()??0,p=s.target?.y??s.target?.bounds?.cy()??0,E=o-e,b=p-i;if(Math.abs(E)>Math.abs(b)){let y=e+E/2;return this.gridLineFunction([{x:e,y:i},{x:y,y:i},{x:y,y:p},{x:o,y:p}])}else {let y=i+b/2;return this.gridLineFunction([{x:e,y:i},{x:e,y},{x:o,y},{x:o,y:p}])}}),this.fitViewportToContent();}gridUpdateLinkLabels(n,c){this.container.selectAll(".link-group").filter(e=>!this.isAlignmentEdge(e)).select("text.linklabel").attr("x",e=>{let i=this.shadowRoot?.querySelector(`path[data-link-id="${e.id}"]`);if(i)try{let p=i.getTotalLength();return i.getPointAtLength(p/2).x}catch{}return this.getGridRouteMidpoint(e,c)?.x??e.source?.x??e.source?.bounds?.cx()??0}).attr("y",e=>{let i=this.shadowRoot?.querySelector(`path[data-link-id="${e.id}"]`);if(i)try{let p=i.getTotalLength();return i.getPointAtLength(p/2).y}catch{}return this.getGridRouteMidpoint(e,c)?.y??e.source?.y??e.source?.bounds?.cy()??0}).attr("text-anchor","middle").attr("dominant-baseline","middle");}getGridRouteMidpoint(n,c){let s=c.get(n.id);if(!s){let y=n.source?.x??n.source?.bounds?.cx()??0,m=n.source?.y??n.source?.bounds?.cy()??0,u=n.target?.x??n.target?.bounds?.cx()??0,l=n.target?.y??n.target?.bounds?.cy()??0;return {x:(y+u)/2,y:(m+l)/2}}let e=[];if(s.forEach(y=>{e.length===0&&y.length>0&&e.push(y[0]),y.length>1&&e.push(y[1]);}),e.length<2)return null;let i=0,o=[];for(let y=0;y<e.length-1;y++){let m=e[y+1].x-e[y].x,u=e[y+1].y-e[y].y,l=Math.sqrt(m*m+u*u);o.push(l),i+=l;}let p=i/2,E=0;for(let y=0;y<o.length;y++){let m=o[y];if(E+m>=p){let u=p-E,l=m>0?u/m:0;return {x:e[y].x+l*(e[y+1].x-e[y].x),y:e[y].y+l*(e[y+1].y-e[y].y)}}E+=m;}let b=Math.floor(e.length/2);return e[b]}adjustGridRouteForEdge(n,c){if(!n?.id?.startsWith("_g_"))return c;let s=this.gridRouteToPoints(c);if(s.length<2)return c;let e=this.routeGroupEdge(n,s);return this.pointsToGridRoute(e)}adjustGridRouteForArrowPositioning(n,c,s){if(!c||!n.source||!n.target)return null;try{let e=this.gridRouteToPoints(s);if(e.length<2)return null;let i=n.source,o=n.target,p=i.bounds||{x:i.x-(i.width||0)/2,y:i.y-(i.height||0)/2,width:()=>i.width||0,height:()=>i.height||0},E=o.bounds||{x:o.x-(o.width||0)/2,y:o.y-(o.height||0)/2,width:()=>o.width||0,height:()=>o.height||0},y=this.getTouchDirection(p,E,5);if(y!=="none"){let{sourcePoint:h,targetPoint:d,middlePoints:g}=this.computePerpendicularRoute(p,E,y),_=[h,...g,d];return this.gridLineFunction(_)}let m=e.length>1?e[1]:e[0],u=this.getRectangleIntersection(p.x+p.width()/2,p.y+p.height()/2,m.x,m.y,p);u&&(e[0]=u);let l=e.length>1?e[e.length-2]:e[e.length-1],a=this.getRectangleIntersection(E.x+E.width()/2,E.y+E.height()/2,l.x,l.y,E);return a&&(e[e.length-1]=a),this.gridLineFunction(e)}catch(e){return console.warn("Error adjusting grid route for arrow positioning:",e),null}}getTouchDirection(n,c,s){let e=n.x,i=n.x+n.width(),o=n.y,p=n.y+n.height(),E=c.x,b=c.x+c.width(),y=c.y,m=c.y+c.height(),u=Math.max(0,Math.max(E-i,e-b)),l=Math.max(0,Math.max(y-p,o-m)),a=!(p<y||m<o),h=!(i<E||b<e);return u<=s&&a?"horizontal":l<=s&&h?"vertical":"none"}computePerpendicularRoute(n,c,s){let e=n.width(),i=n.height(),o=c.width(),p=c.height(),E=n.x+e/2,b=n.y+i/2,y=c.x+o/2,m=c.y+p/2,u=15;if(s==="horizontal")if(b<=m){let a=Math.min(n.y,c.y)-u;return {sourcePoint:{x:E,y:n.y},targetPoint:{x:y,y:c.y},middlePoints:[{x:E,y:a},{x:y,y:a}]}}else {let a=Math.max(n.y+i,c.y+p)+u;return {sourcePoint:{x:E,y:n.y+i},targetPoint:{x:y,y:c.y+p},middlePoints:[{x:E,y:a},{x:y,y:a}]}}else if(E<=y){let a=Math.min(n.x,c.x)-u;return {sourcePoint:{x:n.x,y:b},targetPoint:{x:c.x,y:m},middlePoints:[{x:a,y:b},{x:a,y:m}]}}else {let a=Math.max(n.x+e,c.x+o)+u;return {sourcePoint:{x:n.x+e,y:b},targetPoint:{x:c.x+o,y:m},middlePoints:[{x:a,y:b},{x:a,y:m}]}}}areBoundsNear(n,c,s){let e=n.x,i=n.x+n.width(),o=n.y,p=n.y+n.height(),E=c.x,b=c.x+c.width(),y=c.y,m=c.y+c.height(),u=Math.max(0,Math.max(E-i,e-b)),l=Math.max(0,Math.max(y-p,o-m));return Math.sqrt(u*u+l*l)<=s}chooseBoundaryPoint(n,c,s,e){let i=Math.max(1,s.width()),o=Math.max(1,s.height()),p=[{x:s.x,y:s.y+o/2},{x:s.x+i,y:s.y+o/2},{x:s.x+i/2,y:s.y},{x:s.x+i/2,y:s.y+o}],E=p[0],b=-1/0;for(let y of p){let m=y.x-e.x,u=y.y-e.y,l=Math.sqrt(m*m+u*u);l>b&&(b=l,E=y);}return E}normalizeNodeBounds(n){let c=n.visualWidth??n.width??50,s=n.visualHeight??n.height??30,e=n.bounds||{x:n.x-c/2,y:n.y-s/2,width:()=>c,height:()=>s};return {x:typeof e.x=="number"||e.X!==void 0?e.x:n.x-c/2,y:typeof e.y=="number"?e.y:n.y-s/2,width:()=>typeof e.width=="function"?e.width():e.X!==void 0?e.X-e.x:c,height:()=>typeof e.height=="function"?e.height():e.Y!==void 0?e.Y-e.y:s}}lineIntersectsRect(n,c,s){let e=s.x,i=s.x+s.width(),o=s.y,p=s.y+s.height(),E=Math.min(n.x,c.x),b=Math.max(n.x,c.x),y=Math.min(n.y,c.y),m=Math.max(n.y,c.y);if(b<e||E>i||m<o||y>p)return false;let u=n.x>=e&&n.x<=i&&n.y>=o&&n.y<=p,l=c.x>=e&&c.x<=i&&c.y>=o&&c.y<=p;if(u||l)return true;let a=c.x-n.x,h=c.y-n.y,d=(_,S,v)=>{if(h===0)return false;let T=(_-n.y)/h;if(T<0||T>1)return false;let G=n.x+T*a;return G>=S&&G<=v},g=(_,S,v)=>{if(a===0)return false;let T=(_-n.x)/a;if(T<0||T>1)return false;let G=n.y+T*h;return G>=S&&G<=v};return d(o,e,i)||d(p,e,i)||g(e,o,p)||g(i,o,p)}findBlockingNodes(n,c,s,e){if(!this.currentLayout?.nodes)return [];let i=this.normalizeNodeBounds(n),o=this.normalizeNodeBounds(c),p={x:i.x+i.width()/2,y:i.y+i.height()/2},E={x:o.x+o.width()/2,y:o.y+o.height()/2},b=[];for(let y of this.currentLayout.nodes){if(y.id===s||y.id===e)continue;let m=this.normalizeNodeBounds(y);if(this.lineIntersectsRect(p,E,m)){let u={x:m.x+m.width()/2,y:m.y+m.height()/2},l=Math.sqrt(Math.pow(u.x-p.x,2)+Math.pow(u.y-p.y,2));b.push({node:y,bounds:m,distance:l});}}return b.sort((y,m)=>y.distance-m.distance),b.map(y=>({node:y.node,bounds:y.bounds}))}computeRouteAroundBlockingNodes(n,c,s){let i=Math.min(n.x,c.x),o=Math.max(n.x+n.width(),c.x+c.width()),p=Math.min(n.y,c.y),E=Math.max(n.y+n.height(),c.y+c.height());for(let{bounds:h}of s)i=Math.min(i,h.x),o=Math.max(o,h.x+h.width()),p=Math.min(p,h.y),E=Math.max(E,h.y+h.height());let b=n.x+n.width()/2,y=n.y+n.height()/2,m=c.x+c.width()/2,u=c.y+c.height()/2,l=Math.abs(m-b);if(Math.abs(u-y)>l)if(b<=m){let d=i-15;return {sourcePoint:{x:n.x,y},targetPoint:{x:c.x,y:u},middlePoints:[{x:d,y},{x:d,y:u}]}}else {let d=o+15;return {sourcePoint:{x:n.x+n.width(),y},targetPoint:{x:c.x+c.width(),y:u},middlePoints:[{x:d,y},{x:d,y:u}]}}else if(y<=u){let d=p-15;return {sourcePoint:{x:b,y:n.y},targetPoint:{x:m,y:c.y},middlePoints:[{x:b,y:d},{x:m,y:d}]}}else {let d=E+15;return {sourcePoint:{x:b,y:n.y+n.height()},targetPoint:{x:m,y:c.y+c.height()},middlePoints:[{x:b,y:d},{x:m,y:d}]}}}getNearTouchPerpendicularRoute(n){if(!n.source||!n.target||n.source.id===n.target.id)return null;let c=n.source,s=n.target,e=this.normalizeNodeBounds(c),i=this.normalizeNodeBounds(s),p=this.getTouchDirection(e,i,5);if(p!=="none"){let{sourcePoint:b,targetPoint:y,middlePoints:m}=this.computePerpendicularRoute(e,i,p);return [b,...m,y]}let E=this.findBlockingNodes(c,s,c.id,s.id);if(E.length>0){let{sourcePoint:b,targetPoint:y,middlePoints:m}=this.computeRouteAroundBlockingNodes(e,i,E);return [b,...m,y]}return null}gridRouteToPoints(n){let c=[];return n.forEach((s,e)=>{e===0&&c.push({x:s[0].x,y:s[0].y}),c.push({x:s[1].x,y:s[1].y});}),c}pointsToGridRoute(n){let c=[];for(let s=0;s<n.length-1;s+=1)c.push([n[s],n[s+1]]);return c}createFallbackBounds(n){if(!Md?.Rectangle)return null;let c=((n.visualWidth??n.width)||50)/2,s=((n.visualHeight??n.height)||30)/2,e=(n.x||0)-c,i=(n.x||0)+c,o=(n.y||0)-s,p=(n.y||0)+s;return new Md.Rectangle(e,i,o,p)}getRectangleIntersection(n,c,s,e,i){let o=i.x,p=i.x+i.width(),E=i.y,b=i.y+i.height(),y=s-n,m=e-c;if(y===0&&m===0)return {x:n,y:c};let u=0,l=1;if(y!==0){let h=(o-n)/y,d=(p-n)/y;u=Math.max(u,Math.min(h,d)),l=Math.min(l,Math.max(h,d));}if(m!==0){let h=(E-c)/m,d=(b-c)/m;u=Math.max(u,Math.min(h,d)),l=Math.min(l,Math.max(h,d));}if(u>l)return null;let a=u>0?u:l;return {x:n+a*y,y:c+a*m}}routeLinkPaths(){this.container.selectAll(".link-group path").attr("d",n=>{try{return this.routeSingleEdge(n)}catch(c){return console.error(`Error routing edge ${n.id} from ${n.source.id} to ${n.target.id}:`,c),this.showRuntimeAlert(n.source.id,n.target.id),this.lineFunction([{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}])}});}routeSingleEdge(n){if(this.isAlignmentEdge(n))return this.lineFunction([{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}]);let c=[{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}],s;if(typeof this.colaLayout?.routeEdge=="function")try{if(s=this.colaLayout.routeEdge(n),!s||!Array.isArray(s)||s.length<2||!s[0]||!s[1]||s[0].x===void 0||s[0].y===void 0)throw new Error(`WebCola failed to route edge ${n.id} from ${n.source.id} to ${n.target.id}`)}catch(i){return console.log("Error routing edge",n.id,`from ${n.source.id} to ${n.target.id}`),console.error(i),this.lineFunction(c)}else s=c;if(n.source.id===n.target.id)s=this.createSelfLoopRoute(n);else {if(n.id?.startsWith("_g_"))return s=this.routeGroupEdge(n,s),this.lineFunction(s);s=this.handleMultipleEdgeRouting(n,s);}let e=this.getNearTouchPerpendicularRoute(n);return e?this.lineFunction(e):this.lineFunction(s)}createSelfLoopRoute(n){let c=n.source,s=c.bounds;if(!s)return [{x:c.x,y:c.y},{x:c.x+20,y:c.y-20},{x:c.x,y:c.y}];let e=s.X-s.x,i=s.Y-s.y,o={x:s.x+e/2,y:s.y},p={x:s.X,y:s.y+i/2},b=1+(n.selfLoopIndex||0)*Pi.SELF_LOOP_CURVATURE_SCALE,y={x:s.X+e/2*b,y:s.y-i/2*b};return [o,y,p]}routeGroupEdge(n,c){let s=n.groupId?(this.currentLayout?.groups||[]).find(e=>e.id===n.groupId):null;if(!s)console.warn("[routeGroupEdge] Group not found for edge:",n.id,"\u2014 groupId:",n.groupId);else {if(!s.bounds&&Md?.Rectangle){let e=n.source?.id===n.keyNodeId?c[c.length-1]:c[0];e&&(s.bounds=new Md.Rectangle(e.x-50,e.x+50,e.y-30,e.y+30));}if(s.bounds)if(n.source?.id===n.keyNodeId)c[c.length-1]=this.closestPointOnRect(s.bounds,c[0]);else if(n.target?.id===n.keyNodeId){let e=s.bounds.inflate?.(-1)??s.bounds;c[0]=this.closestPointOnRect(e,c[c.length-1]);}else console.warn("[routeGroupEdge] keyNodeId matched neither side",{keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id});}return c.length>2&&c.splice(1,c.length-2),c}handleMultipleEdgeRouting(n,c){let s=this.getAllEdgesBetweenNodes(n.source.id,n.target.id);if(s.length<=1)return c;if(c.length===2){let b={x:(c[0].x+c[1].x)/2,y:(c[0].y+c[1].y)/2};c.splice(1,0,b);}let e=c[1].x-c[0].x,i=c[1].y-c[0].y,o=Math.atan2(i,e),p=this.getRouteLength(c),E=s.findIndex(b=>b.id===n.id);if(E!==-1){c=this.applyEdgeOffsetWithIndex(n,c,s,o,E,p);let b=this.calculateCurvatureWithIndex(s,n.id,E),y=this.clampCurvature(b);c=this.applyCurvatureToRoute(c,y,o,p);}return c}getAllEdgesBetweenNodes(n,c){if(!this.currentLayout?.links)return [];let s=this.getNodePairKey(n,c);return this.edgeRoutingCache.edgesBetweenNodes.has(s)?this.edgeRoutingCache.edgesBetweenNodes.get(s):this.currentLayout.links.filter(e=>!this.isAlignmentEdge(e)&&(e.source.id===n&&e.target.id===c||e.source.id===c&&e.target.id===n))}calculateCurvature(n,c,s,e){if(e.startsWith("_alignment_"))return 0;let i=n.length,o=n.findIndex(p=>p.id===e);return i<=1?0:(o%2===0?1:-1)*(Math.floor(o/2)+1)*Pi.CURVATURE_BASE_MULTIPLIER*i}calculateCurvatureWithIndex(n,c,s){let e=n.length;return e<=1?0:(s%2===0?1:-1)*(Math.floor(s/2)+1)*Pi.CURVATURE_BASE_MULTIPLIER*e}applyEdgeOffset(n,c,s,e){let i=s.findIndex(p=>p.id===n.id),o=this.getRouteLength(c);return this.applyEdgeOffsetWithIndex(n,c,s,e,i,o)}applyEdgeOffsetWithIndex(n,c,s,e,i,o){let p=(i%2===0?1:-1)*(Math.floor(i/2)+1)*Pi.MIN_EDGE_DISTANCE,E=this.clampOffset(p,o),b=this.getDominantDirection(e);return b==="right"||b==="left"?(c[0].y+=E,c[c.length-1].y+=E):(b==="up"||b==="down")&&(c[0].x+=E,c[c.length-1].x+=E),n.source.innerBounds&&(c[0]=this.adjustPointToRectanglePerimeter(c[0],n.source.innerBounds)),n.target.innerBounds&&(c[c.length-1]=this.adjustPointToRectanglePerimeter(c[c.length-1],n.target.innerBounds)),c}clampOffset(n,c){let s=Math.max(Pi.MIN_EDGE_DISTANCE,c*Pi.MAX_EDGE_OFFSET_RATIO);return Math.max(-s,Math.min(s,n))}getRouteLength(n){return n.length<2?0:n.slice(1).reduce((c,s,e)=>{let i=n[e],o=s.x-i.x,p=s.y-i.y;return c+Math.sqrt(o*o+p*p)},0)}clampCurvature(n){return Math.max(-Pi.MAX_EDGE_CURVATURE_RATIO,Math.min(Pi.MAX_EDGE_CURVATURE_RATIO,n))}applyCurvatureToRoute(n,c,s,e){return c===0||n.forEach((i,o)=>{if(o>0&&o<n.length-1){let p=c*Math.abs(Math.sin(s))*e,E=c*Math.abs(Math.cos(s))*e;i.x+=p,i.y+=E;}}),n}getDominantDirection(n){return n=(n+Math.PI)%(2*Math.PI)-Math.PI,n>=-Math.PI/4&&n<=Math.PI/4?"right":n>Math.PI/4&&n<3*Math.PI/4?"up":n>=3*Math.PI/4||n<=-3*Math.PI/4?"left":n>-3*Math.PI/4&&n<-Math.PI/4?"down":null}closestPointOnRect(n,c){if(!n)return c;let{x:s,y:e,X:i,Y:o}=n,p=Math.max(s,Math.min(c.x,i)),E=Math.max(e,Math.min(c.y,o));return {x:p,y:E}}getStableEdgeAnchor(n,c){if(!n)return c;let s,e,i,o;if(typeof n.cx=="function")s=n.cx(),e=n.cy(),i=n.width()/2,o=n.height()/2;else if(n.x!==void 0&&n.X!==void 0)s=(n.x+n.X)/2,e=(n.y+n.Y)/2,i=(n.X-n.x)/2,o=(n.Y-n.y)/2;else return c;let p=c.x-s,E=c.y-e,b=Math.abs(p)/i,y=Math.abs(E)/o;return b>y?p>0?{x:s+i,y:e}:{x:s-i,y:e}:E>0?{x:s,y:e+o}:{x:s,y:e-o}}getStableEdgePath(n,c){let s={x:n.x||0,y:n.y||0},e={x:c.x||0,y:c.y||0},i=y=>{let m=((y.visualWidth??y.width)||0)/2,u=((y.visualHeight??y.height)||0)/2;if(m===0&&u===0)return null;let l=y.x||0,a=y.y||0;return {cx:()=>l,cy:()=>a,width:()=>m*2,height:()=>u*2,x:l-m,X:l+m,y:a-u,Y:a+u}},o=i(n)??n.bounds??n.innerBounds,p=i(c)??c.bounds??c.innerBounds,E=o?this.getStableEdgeAnchor(o,e):s,b=p?this.getStableEdgeAnchor(p,s):e;return [E,b]}adjustPointToRectanglePerimeter(n,c){return c?this.closestPointOnRect(c,n):n}updateLinkLabelsAfterRouting(){this.container.selectAll(".link-group .linklabel").attr("x",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(!c)return 0;let s=c.getTotalLength();return c.getPointAtLength(s/2).x}).attr("y",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(!c)return 0;let s=c.getTotalLength();return c.getPointAtLength(s/2).y}).attr("text-anchor","middle").each((n,c,s)=>{this.handleLabelOverlap(s[c]);}).raise();}handleLabelOverlap(n){let c=[];this.container.selectAll(".linklabel").each(function(){this!==n&&_ft(this,n)&&c.push(this);}),c.length>0&&this.minimizeOverlap(n,c);}minimizeOverlap(n,c){}fitViewportToContent(n=false){let c=this.svg?.node();if(!c||!this.zoomBehavior||this.userHasManuallyZoomed&&!this.isInitialRender&&!n)return;let s=this.calculateContentBounds();if(!s)return;let e=c.clientWidth||c.parentElement?.clientWidth||800,i=c.clientHeight||c.parentElement?.clientHeight||600,o=Pi.VIEWBOX_PADDING*4,p=(e-o*2)/s.width,E=(i-o*2)/s.height,b=Math.min(p,E,1),[y,m]=this.zoomBehavior.scaleExtent(),u=Math.max(y,Math.min(m,b)),l=s.x+s.width/2,a=s.y+s.height/2,h=e/2-l*u,d=i/2-a*u,g=Co.zoomIdentity.translate(h,d).scale(u);this.isInitialRender?(this.svg.call(this.zoomBehavior.transform,g),this.isInitialRender=false):this.svg.transition().duration(300).ease(Co.easeCubicOut).call(this.zoomBehavior.transform,g),this.updateZoomControlStates();}resetViewToFitContent(){this.userHasManuallyZoomed=false,this.fitViewportToContent(true);}calculateContentBounds(){try{if(!this.currentLayout||!this.container)return null;let n=1/0,c=1/0,s=-1/0,e=-1/0,i=(l,a,h,d)=>{[l,a,h,d].every(Number.isFinite)&&(n=Math.min(n,l),s=Math.max(s,a),c=Math.min(c,h),e=Math.max(e,d));},o=this.currentLayout.nodes;o&&o.length>0&&o.forEach(l=>{if(this.isHiddenNode(l)||typeof l.x!="number"||typeof l.y!="number")return;let a=l.visualWidth??l.width??0,h=l.visualHeight??l.height??0,d=a/2,g=h/2;i(l.x-d,l.x+d,l.y-g,l.y+g);});let p=this,E=this.container.selectAll(".link-group path");E.empty()||E.each(function(l){if(!(l?.id&&p.isAlignmentEdge(l)))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x,a.x+a.width,a.y,a.y+a.height);}catch{}});let b=this.container.selectAll(".node, .error-node");b.empty()||b.each(function(l){if(!p.isHiddenNode(l))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x,a.x+a.width,a.y,a.y+a.height);}catch{}});let y=this.container.selectAll("text");y.empty()||y.each(function(l){if(!(l&&(typeof l.name=="string"||typeof l.id=="string")&&p.isHiddenNode(l)))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x-5,a.x+a.width+5,a.y-5,a.y+a.height+5);}catch{}});let m=this.container.selectAll(".group");return m.empty()||m.each(function(){try{let l=this.getBBox();(l.width>0||l.height>0)&&i(l.x,l.x+l.width,l.y,l.y+l.height);}catch{}}),n===1/0||c===1/0||s===-1/0||e===-1/0?(console.warn("Could not calculate content bounds - no valid elements found"),null):{x:n,y:c,width:s-n,height:e-c}}catch(n){return console.error("Error calculating content bounds:",n),null}}dispatchRelationsAvailableEvent(){let n=this.getAllRelations(),c=new CustomEvent("relations-available",{detail:{relations:n,count:n.length,timestamp:Date.now(),graphId:this.id||"unknown"},bubbles:true,cancelable:true});this.dispatchEvent(c);}getAllRelations(){if(!this.currentLayout?.links)return [];let n=new Set(this.currentLayout.links.filter(c=>!this.isAlignmentEdge(c)).map(c=>c.relName).filter(Boolean));return Array.from(n)}highlightRelation(n){return this.currentLayout?.links?(this.svgLinkGroups.filter(c=>c.relName===n&&!this.isAlignmentEdge(c)).selectAll("path").classed("highlighted",true),true):false}clearHighlightRelation(n){return this.currentLayout?.links?(this.svgLinkGroups.filter(c=>c.relName===n&&!this.isAlignmentEdge(c)).selectAll("path").classed("highlighted",false),true):false}highlightNodes(n){if(!this.currentLayout?.nodes||!this.svgNodes||!n||n.length===0)return false;let c=new Set(n),s=false;return this.svgNodes.each((e,i,o)=>{c.has(e.id)&&(Co.select(o[i]).classed("highlighted",true),s=true);}),s}highlightNodePairs(n,c={}){if(!this.currentLayout?.nodes||!this.svgNodes||!n||n.length===0)return false;let{showBadges:s=false}=c,e=new Set,i=new Set;n.forEach((p,E)=>{if(!Array.isArray(p)){console.warn(`highlightNodePairs: Pair at index ${E} is not an array, skipping`);return}if(p.length!==2){console.warn(`highlightNodePairs: Pair at index ${E} has ${p.length} elements (expected 2), skipping`);return}let[b,y]=p;b&&e.add(b),y&&i.add(y);});let o=false;return this.svgNodes.each((p,E,b)=>{let y=Co.select(b[E]);e.has(p.id)&&(y.classed("highlighted-first",true),o=true,s&&this.addHighlightBadge(y,p,"1","#007aff")),i.has(p.id)&&(y.classed("highlighted-second",true),o=true,s&&(e.has(p.id)?this.addHighlightBadge(y,p,"1,2","#9B59B6"):this.addHighlightBadge(y,p,"2","#ff3b30")));}),o}clearNodeHighlights(){return this.svgNodes?(this.svgNodes.classed("highlighted",false).classed("highlighted-first",false).classed("highlighted-second",false).selectAll(".highlight-badge, .highlight-badge-bg").remove(),true):false}addHighlightBadge(n,c,s,e){n.selectAll(".highlight-badge, .highlight-badge-bg").remove();let i=16,o=4,p=(c.width||0)/2-i/2-o,E=-(c.height||0)/2+i/2+o;n.append("circle").attr("class","highlight-badge-bg").attr("cx",p).attr("cy",E).attr("r",i/2).attr("fill",e),n.append("text").attr("class","highlight-badge").attr("x",p).attr("y",E).attr("dy","0.35em").text(s);}showRuntimeAlert(n,c){console.warn(`Runtime (WebCola) error when laying out an edge from ${n} to ${c}. You may have to click and drag these nodes slightly to un-stick layout.`);}getCSS(){return `
851
+ `;}initializeD3(){Co||(Co=window.d3),this.svg=Co.select(this.shadowRoot.querySelector("#svg")),this.container=this.svg.select(".zoomable"),Co.zoom?(this.zoomBehavior=Co.zoom().scaleExtent([.01,20]).on("start",()=>{Co.event.sourceEvent&&(this.userHasManuallyZoomed=true);}).on("zoom",()=>{this.container.attr("transform",Co.event.transform),this.updateZoomControlStates(),this.updateSmallNodeClasses();}),this.svg.call(this.zoomBehavior),this.initializeZoomControls()):console.warn("D3 zoom behavior not available. Ensure D3 v4+ is loaded.");}initializeZoomControls(){let n=this.shadowRoot.querySelector("#zoom-in"),c=this.shadowRoot.querySelector("#zoom-out"),s=this.shadowRoot.querySelector("#zoom-fit");n&&n.addEventListener("click",()=>{this.userHasManuallyZoomed=true,this.zoomIn();}),c&&c.addEventListener("click",()=>{this.userHasManuallyZoomed=true,this.zoomOut();}),s&&s.addEventListener("click",()=>{this.resetViewToFitContent();});let e=this.shadowRoot.querySelector("#routing-mode");if(e){let o=this.layoutFormat||"default";e.value=o,e.addEventListener("change",()=>{this.handleRoutingModeChange(e.value);});}let i=this.shadowRoot.querySelector("#screenshot-btn");i&&i.addEventListener("click",()=>{this.takeScreenshot();}),this.updateZoomControlStates();}handleRoutingModeChange(n){this.setAttribute("layoutFormat",n),this.currentLayout&&this.colaLayout&&(n==="grid"?this.gridify(10,25,10):this.routeEdges(),this.dispatchEvent(new CustomEvent("routing-mode-changed",{detail:{mode:n}})));}updateRoutingModeDropdown(){let n=this.shadowRoot?.querySelector("#routing-mode");if(n){let c=this.layoutFormat||"default";n.value=c;}}initializeInputModeHandlers(){this.inputModeEnabled&&this.attachInputModeListeners();}attachInputModeListeners(){this.inputModeListenersAttached||(document.addEventListener("keydown",this.handleInputModeKeydown),document.addEventListener("keyup",this.handleInputModeKeyup),window.addEventListener("blur",this.handleInputModeBlur),this.inputModeListenersAttached=true);}detachInputModeListeners(){this.inputModeListenersAttached&&(document.removeEventListener("keydown",this.handleInputModeKeydown),document.removeEventListener("keyup",this.handleInputModeKeyup),window.removeEventListener("blur",this.handleInputModeBlur),this.inputModeListenersAttached=false);}activateInputMode(){this.isInputModeActive=true,this.svg&&this.svg.classed("input-mode",true),this.disableNodeDragging(),this.disableZoom(),this.updateEdgeEndpointMarkers(),this.dispatchEvent(new CustomEvent("input-mode-activated",{detail:{active:true}}));}deactivateInputMode(){this.isInputModeActive=false,this.svg&&this.svg.classed("input-mode",false),this.cleanupEdgeCreation(),this.enableNodeDragging(),this.enableZoom(),this.updateEdgeEndpointMarkers(),this.dispatchEvent(new CustomEvent("input-mode-deactivated",{detail:{active:false}}));}disableNodeDragging(){this.svgNodes&&this.colaLayout&&this.svgNodes.on(".drag",null);}enableNodeDragging(){if(this.svgNodes&&this.colaLayout&&this.colaLayout.drag){let n=this.colaLayout.drag();this.setupNodeDragHandlers(n),this.svgNodes.call(n);}}disableZoom(){this.svg&&this.zoomBehavior&&(this.storedTransform=Co.zoomTransform(this.svg.node()),this.svg.on(".zoom",null));}enableZoom(){this.svg&&this.zoomBehavior&&(this.svg.call(this.zoomBehavior),this.storedTransform&&this.svg.call(this.zoomBehavior.transform,this.storedTransform));}zoomIn(){this.svg&&this.zoomBehavior&&this.svg.transition().duration(200).call(this.zoomBehavior.scaleBy,1.5);}zoomOut(){this.svg&&this.zoomBehavior&&this.svg.transition().duration(200).call(this.zoomBehavior.scaleBy,1/1.5);}updateZoomControlStates(){if(!this.svg||!this.zoomBehavior)return;let c=Co.zoomTransform(this.svg.node()).k,[s,e]=this.zoomBehavior.scaleExtent(),i=this.shadowRoot.querySelector("#zoom-in"),o=this.shadowRoot.querySelector("#zoom-out");i&&(i.disabled=c>=e),o&&(o.disabled=c<=s);}cleanupEdgeCreation(){this.edgeCreationState.temporaryEdge&&this.edgeCreationState.temporaryEdge.remove(),this.edgeCreationState={isCreating:false,sourceNode:null,temporaryEdge:null};}setupNodeDragHandlers(n){n.on("start.cnd",c=>{this.userHasManuallyZoomed=true;let s={x:c.x,y:c.y};this.dragStartPositions.set(c.id,s),this.dispatchEvent(new CustomEvent("node-drag-start",{detail:{id:c.id,position:s}}));}).on("end.cnd",c=>{let s=this.dragStartPositions.get(c.id);this.dragStartPositions.delete(c.id);let e={id:c.id,previous:s,current:{x:c.x,y:c.y}};this.dispatchEvent(new CustomEvent("node-drag-end",{detail:e}));});}startEdgeCreation(n){this.isInputModeActive&&(this.cleanupEdgeCreation(),this.edgeCreationState.isCreating=true,this.edgeCreationState.sourceNode=n,this.edgeCreationState.temporaryEdge=this.container.append("line").attr("class","temporary-edge").attr("x1",n.x).attr("y1",n.y).attr("x2",n.x).attr("y2",n.y).attr("stroke","#007bff").attr("stroke-width",2).attr("stroke-dasharray","5,5").attr("opacity",.7),this.svg.on("mousemove.edgecreation",()=>{if(this.edgeCreationState.isCreating&&this.edgeCreationState.temporaryEdge){let[c,s]=Co.mouse(this.container.node());this.edgeCreationState.temporaryEdge.attr("x2",c).attr("y2",s);}}));}async finishEdgeCreation(n){if(!this.isInputModeActive||!this.edgeCreationState.isCreating||!this.edgeCreationState.sourceNode)return;let c=this.edgeCreationState.sourceNode;if(c.id===n.id&&!await this.showConfirmDialog(`Are you sure you want to create a self-loop edge on "${c.label||c.id}"?`)){this.cleanupEdgeCreation();return}this.svg.on("mousemove.edgecreation",null),await this.showEdgeLabelInput(c,n);}async showEdgeLabelInput(n,c){let s=await this.showPromptDialog(`Enter label for edge from "${n.label||n.id}" to "${c.label||c.id}":`,"");s!==null&&await this.createNewEdge(n,c,s||""),this.cleanupEdgeCreation();}async createNewEdge(n,c,s){if(!this.currentLayout)return;let e=this.currentLayout.nodes.findIndex(E=>E.id===n.id),i=this.currentLayout.nodes.findIndex(E=>E.id===c.id);if(e===-1||i===-1){console.error("Could not find node indices for edge creation");return}let p={id:`edge_${n.id}_${c.id}_${Date.now()}`,source:e,target:i,label:s,relName:s,color:"#333",isUserCreated:true};this.currentLayout.links.push(p),await this.updateExternalStateForNewEdge(n,c,s),this.dispatchEvent(new CustomEvent("edge-created",{detail:{edge:p,sourceNode:n,targetNode:c}})),this.rerenderGraph();}async updateExternalStateForNewEdge(n,c,s){if(s.trim())try{let e={atoms:[n.id,c.id],types:[n.type||"untyped",c.type||"untyped"]};console.log(`Dispatching edge creation request: ${s}(${n.id}, ${c.id})`);let i=new CustomEvent("edge-creation-requested",{detail:{relationId:s,sourceNodeId:n.id,targetNodeId:c.id,tuple:e},bubbles:!0});this.dispatchEvent(i);}catch(e){console.error("Failed to update external state for new edge:",e);}}rerenderGraph(){!this.currentLayout||!this.colaLayout||(this.colaLayout.links(this.currentLayout.links),this.container.selectAll(".link-group").remove(),this.renderLinks(this.currentLayout.links,this.colaLayout),this.colaLayout.start());}async editEdgeLabel(n){if(!this.isInputModeActive)return;let c=n.label||n.relName||"",s=await this.showEdgeEditDialog("Edit edge label:",c);if(s==="DELETE"){await this.deleteEdge(n);return}if(s!==null&&s!==c){let e=s,i=this.getNodeFromEdge(n,"source"),o=this.getNodeFromEdge(n,"target");await this.updateExternalStateForEdgeModification(i,o,c,e),n.label=e,n.relName=e,this.dispatchEvent(new CustomEvent("edge-modified",{detail:{edge:n,oldLabel:c,newLabel:e}})),this.rerenderGraph();}}getNodeFromEdge(n,c){if(!this.currentLayout)return null;let s=typeof n[c]=="number"?n[c]:n[c].index;return this.currentLayout.nodes[s]||null}async updateExternalStateForEdgeModification(n,c,s,e){if(!(!n||!c))try{let i={atoms:[n.id,c.id],types:[n.type||"untyped",c.type||"untyped"]};console.log(`Dispatching edge modification request: ${s} -> ${e}`);let o=new CustomEvent("edge-modification-requested",{detail:{oldRelationId:s,newRelationId:e,sourceNodeId:n.id,targetNodeId:c.id,tuple:i},bubbles:!0});this.dispatchEvent(o);}catch(i){console.error("Failed to update external state for edge modification:",i);}}async renderLayout(n,c){if(!NT(n))throw new Error("Invalid instance layout provided. Expected an InstanceLayout instance.");let s,e=false;if(c?.policy&&c.prevInstance&&c.currInstance){let E=this.buildPolicyRawState(c),b=this.getViewportBoundsInLayoutSpace(E.transform),y=c.policy.apply({priorState:E,prevInstance:c.prevInstance,currInstance:c.currInstance,spec:{constraints:{orientation:{relative:[],cyclic:[]},alignment:[],grouping:{groups:[],subgroups:[]}},directives:{sizes:[],hiddenAtoms:[],icons:[],projections:[],edgeStyles:[]}},viewportBounds:b});s=y.effectivePriorState,e=y.useReducedIterations;}else c?.priorPositions&&(s=c.priorPositions,e=true);let i=!!(s&&s.positions.length>0),o=this.hasValidTransform(s?.transform),p=i?{priorPositions:s}:void 0;if(this.applyViewportRenderPolicy(i,o),this.svg&&this.zoomBehavior&&Co)try{if(o){let E=s.transform,b=Co.zoomIdentity.translate(E.x,E.y).scale(E.k);this.svg.call(this.zoomBehavior.transform,b);}else if(!i){let E=Co.zoomIdentity;this.svg.call(this.zoomBehavior.transform,E);}}catch(E){console.warn("Failed to set zoom transform:",E);}try{if(!Co)throw new Error("D3 library not available. Please ensure D3 v4 is loaded from CDN.");if(!Md){if(!window.cola)throw new Error("WebCola library not available. Please ensure vendor/cola.js is loaded.");Md=window.cola;}if((!this.container||!this.svg)&&this.initializeD3(),!this.container)throw new Error("Failed to initialize D3 container. SVG elements may not be available.");this.showLoading(),this.updateLoadingProgress("Translating layout...");let b=this.shadowRoot.querySelector("#svg-container").getBoundingClientRect(),y=b.width||800,m=b.height||600,l=await new exports.WebColaTranslator().translate(n,y,m,p);this.updateLoadingProgress(`Computing layout for ${l.nodes.length} nodes...`);let a=l.nodes.length,h=Pi.INITIAL_UNCONSTRAINED_ITERATIONS,d=Pi.INITIAL_USER_CONSTRAINT_ITERATIONS,g=Pi.INITIAL_ALL_CONSTRAINTS_ITERATIONS;i&&e&&(h=0,d=Math.min(10,d),g=Math.min(20,g)),a>100?(h=Math.max(i?0:5,Math.floor(h*.5)),d=Math.max(25,Math.floor(d*.5)),g=Math.max(100,Math.floor(g*.5))):a>50&&(h=Math.max(i?0:8,Math.floor(h*.8)),d=Math.max(40,Math.floor(d*.8)),g=Math.max(150,Math.floor(g*.75)));let{scaledConstraints:_,linkLength:S,groupCompactness:v}=this.getScaledDetails(l.constraints,zF,l.nodes,l.groups,l.links);this.updateLoadingProgress("Applying constraints and initializing...");let T=i?.1:.001,G=Md.d3adaptor(Co).linkDistance(S).convergenceThreshold(T).avoidOverlaps(!0).handleDisconnected(!0).nodes(l.nodes).links(l.links).constraints(_).groups(l.groups).groupCompactness(v).size([l.FIG_WIDTH,l.FIG_HEIGHT]);this.currentLayout=l,this.colaLayout=G,this.container.selectAll("*").remove(),this.renderGroups(l.groups,G),this.renderLinks(l.links,G),this.renderNodes(l.nodes,G);let q=0,j=h+d+g;G.on("tick",()=>{if(q++,q%20===0){let B=Math.min(95,Math.round(q/j*100));this.updateLoadingProgress(`Computing layout... ${B}%`);}this.layoutFormat==="default"||!this.layoutFormat||this.layoutFormat===null?this.updatePositions():this.layoutFormat==="grid"?this.gridUpdatePositions():console.warn(`Unknown layout format: ${this.layoutFormat}. Skipping position updates.`);}).on("end",()=>{this.updateLoadingProgress("Finalizing..."),this.layoutFormat==="default"||!this.layoutFormat?this.routeEdges():this.layoutFormat==="grid"?this.gridify(10,25,10):console.warn(`Unknown layout format: ${this.layoutFormat}. Skipping edge routing.`),this.isUnsatCore&&this.showErrorIcon(),this.dispatchRelationsAvailableEvent(),this.dispatchEvent(new CustomEvent("layout-complete",{detail:{nodePositions:this.getNodePositions()}})),this.updateRoutingModeDropdown(),this.hideLoading();});try{G.start(h,d,g,Pi.GRID_SNAP_ITERATIONS);}catch(B){console.warn("WebCola layout start encountered an error, trying alternative approach:",B);try{G.start();}catch(J){throw console.error("Both WebCola start methods failed:",J),new Error(`WebCola layout failed to start: ${J.message}`)}}}catch(E){console.error("Error rendering layout:",E),this.showError(`Layout rendering failed: ${E.message}`);}}clear(){if(this.colaLayout)try{this.colaLayout.stop?.();}catch{}this.container&&this.container.selectAll("*").remove(),this.currentLayout=null,this.colaLayout=null,this.svgNodes=null,this.svgLinks=null,this.svgGroups=null,this.edgeRoutingCache.edgesBetweenNodes.clear(),this.edgeRoutingCache.alignmentEdges.clear(),this.dragStartPositions.clear(),this.hideLoading();}getNodePositions(){return this.currentLayout?.nodes?this.currentLayout.nodes.map(n=>({id:n.id,x:n.x,y:n.y})):[]}getCurrentTransform(){if(this.svg&&this.svg.node())try{let n=Co.zoomTransform(this.svg.node());return {k:n.k,x:n.x,y:n.y}}catch{return {k:1,x:0,y:0}}return {k:1,x:0,y:0}}getLayoutState(){return {positions:this.getNodePositions(),transform:this.getCurrentTransform()}}addToolbarControl(n){let c=this.shadowRoot?.querySelector("#graph-toolbar");c&&c.appendChild(n);}getToolbar(){return this.shadowRoot?.querySelector("#graph-toolbar")||null}renderGroups(n,c){if(!this.currentLayout.nodes||this.currentLayout.nodes.length===0){console.warn("Cannot render groups: nodes not available");return}this.svgGroups=this.setupGroups(n,this.currentLayout.nodes,c);}setupLinks(n,c){let s=this.container.selectAll(".link-group").data(n).enter().append("g").attr("class","link-group");return this.setupLinkPaths(s),this.setupLinkLabels(s),this.setupEdgeEndpointMarkers(s),s}setupLinkPaths(n){n.append("path").attr("class",c=>this.isAlignmentEdge(c)?"alignmentLink":this.isInferredEdge(c)?"inferredLink":"link").attr("data-link-id",c=>c.id||"").attr("stroke",c=>this.isAlignmentEdge(c)?"none":c.color).attr("fill","none").attr("opacity",c=>this.isAlignmentEdge(c)?0:null).style("stroke-width",c=>this.isAlignmentEdge(c)?"0":c.weight!=null?`${c.weight}px`:null).attr("stroke-dasharray",c=>this.isAlignmentEdge(c)?null:this.getEdgeDasharray(c.style)).attr("marker-end",c=>this.isAlignmentEdge(c)?"none":"url(#end-arrow)").attr("marker-start",c=>this.isAlignmentEdge(c)||!c.bidirectional?"none":"url(#start-arrow)").on("click.inputmode",c=>{this.isInputModeActive&&!this.isAlignmentEdge(c)&&(Co.event.stopPropagation(),this.editEdgeLabel(c).catch(s=>{console.error("Error editing edge label:",s);}));}).style("cursor",()=>this.isInputModeActive?"pointer":"default");}getEdgeDasharray(n){if(!n)return null;switch(n.toLowerCase()){case "dotted":return "1,4";case "dashed":return "6,4";case "solid":return null;default:return null}}setupLinkLabels(n){n.filter(c=>!this.isAlignmentEdge(c)&&(this.isInferredEdge(c)||c.showLabel!==false)).append("text").attr("class","linklabel").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("font-family","system-ui").attr("pointer-events","none").text(c=>c.label||c.relName||"");}setupEdgeEndpointMarkers(n){n.filter(c=>!this.isAlignmentEdge(c)).append("circle").attr("class","edge-endpoint-marker target-marker").attr("r",8).attr("fill","#007bff").attr("stroke","white").attr("stroke-width",2).attr("opacity",0).attr("cursor","move").style("pointer-events","none").call(Co.drag().on("start",c=>this.startEdgeEndpointDrag(c,"target")).on("drag",c=>this.dragEdgeEndpoint(c,"target")).on("end",c=>this.endEdgeEndpointDrag(c,"target"))),n.filter(c=>!this.isAlignmentEdge(c)).append("circle").attr("class","edge-endpoint-marker source-marker").attr("r",8).attr("fill","#28a745").attr("stroke","white").attr("stroke-width",2).attr("opacity",0).attr("cursor","move").style("pointer-events","none").call(Co.drag().on("start",c=>this.startEdgeEndpointDrag(c,"source")).on("drag",c=>this.dragEdgeEndpoint(c,"source")).on("end",c=>this.endEdgeEndpointDrag(c,"source")));}startEdgeEndpointDrag(n,c){Co.event.sourceEvent.stopPropagation(),this.edgeDragState.isDragging=true,this.edgeDragState.edge=n,this.edgeDragState.endpoint=c,console.log(`\u{1F535} Started dragging ${c} endpoint of edge:`,n.id);}dragEdgeEndpoint(n,c){if(!this.edgeDragState.isDragging)return;let[s,e]=Co.mouse(this.container.node()),i=c==="target"?".target-marker":".source-marker";this.container.selectAll(".link-group").filter(o=>o.id===n.id).select(i).attr("cx",s).attr("cy",e);}async endEdgeEndpointDrag(n,c){if(!this.edgeDragState.isDragging)return;let[s,e]=Co.mouse(this.container.node()),i=this.findNodeAtPosition(s,e);i?(console.log(`\u{1F517} Reconnecting ${c} to node:`,i.id),await this.reconnectEdge(n,c,i)):(console.log("\u{1F5D1}\uFE0F No node found - deleting edge:",n.id),await this.deleteEdge(n)),this.edgeDragState={isDragging:false,edge:null,endpoint:null,dragMarker:null},this.rerenderGraph();}findNodeAtPosition(n,c){if(!this.currentLayout?.nodes)return null;for(let s of this.currentLayout.nodes){let e=(s.visualWidth??s.width??0)/2,i=(s.visualHeight??s.height??0)/2;if(n>=s.x-e&&n<=s.x+e&&c>=s.y-i&&c<=s.y+i)return s}return null}async reconnectEdge(n,c,s){let e=this.getNodeFromEdge(n,"source"),i=this.getNodeFromEdge(n,"target");if(!e||!i){console.error("Could not find source or target node");return}let o,p;if(c==="source"?(o=s,p=i):(o=e,p=s),o.id===e.id&&p.id===i.id){console.log("\u23ED\uFE0F Edge already connected to this node, no change needed");return}let E=n.label||n.relName||"";if(!E.trim()){console.warn("Edge has no relation name, cannot reconnect");return}let b={atoms:[e.id,i.id],types:[e.type||"untyped",i.type||"untyped"]},y={atoms:[o.id,p.id],types:[o.type||"untyped",p.type||"untyped"]};console.log(`\u{1F504} Reconnecting edge from ${e.id}->${i.id} to ${o.id}->${p.id}`);let m=new CustomEvent("edge-reconnection-requested",{detail:{relationId:E,oldTuple:b,newTuple:y,oldSourceNodeId:e.id,oldTargetNodeId:i.id,newSourceNodeId:o.id,newTargetNodeId:p.id},bubbles:true});this.dispatchEvent(m);let u=this.currentLayout.nodes.findIndex(a=>a.id===o.id),l=this.currentLayout.nodes.findIndex(a=>a.id===p.id);u!==-1&&l!==-1&&(n.source=u,n.target=l);}async deleteEdge(n){let c=this.getNodeFromEdge(n,"source"),s=this.getNodeFromEdge(n,"target");if(!c||!s){console.error("Could not find source or target node for edge deletion");return}let e=n.label||n.relName||"";if(!e.trim()){console.warn("Edge has no relation name, cannot delete from data instance"),this.removeEdgeFromLayout(n);return}let i={atoms:[c.id,s.id],types:[c.type||"untyped",s.type||"untyped"]};console.log(`\u{1F5D1}\uFE0F Deleting edge: ${e}(${c.id}, ${s.id})`);let o=new CustomEvent("edge-modification-requested",{detail:{oldRelationId:e,newRelationId:"",sourceNodeId:c.id,targetNodeId:s.id,tuple:i},bubbles:true});this.dispatchEvent(o),this.removeEdgeFromLayout(n);}removeEdgeFromLayout(n){if(!this.currentLayout?.links)return;let c=this.currentLayout.links.findIndex(s=>s.id===n.id);c!==-1&&(this.currentLayout.links.splice(c,1),console.log(`\u2705 Edge removed from layout: ${n.id}`));}setupGroups(n,c,s){let e=this.setupGroupRectangles(n,c,s);return this.svgGroupLabels=this.setupGroupLabels(n,s),e}setupGroupRectangles(n,c,s){return this.container.selectAll(".group").data(n).enter().append("rect").attr("class",i=>this.isDisconnectedGroup(i)?"disconnectedNode":this.isErrorGroup(i)?"error-group":"group").attr("rx",Pi.GROUP_BORDER_RADIUS).attr("ry",Pi.GROUP_BORDER_RADIUS).style("fill",i=>this.isDisconnectedGroup(i)?"transparent":c[i.keyNode]?.color||"#cccccc").attr("fill-opacity",Pi.GROUP_FILL_OPACITY).attr("stroke",i=>this.isDisconnectedGroup(i)?"none":c[i.keyNode]?.color||"#999999").attr("stroke-width",1).call(s.drag)}resolveGroupLeafToNodeIndex(n){if(typeof n=="number"&&Number.isInteger(n)&&n>=0)return n;if(n&&typeof n=="object"){let c=n;if(typeof c.index=="number"&&Number.isInteger(c.index)&&c.index>=0)return c.index;if(typeof c.id=="string"&&this.currentLayout?.nodes){let s=this.currentLayout.nodes.findIndex(e=>e.id===c.id);return s>=0?s:null}}return null}collectGroupNodeIndices(n,c){let s=new Set,e=new Set,i=(p,E)=>{if(p){if(typeof E=="number"){if(e.has(E))return;e.add(E);}Array.isArray(p.leaves)&&p.leaves.forEach(b=>{let y=this.resolveGroupLeafToNodeIndex(b);y!==null&&s.add(y);}),Array.isArray(p.groups)&&p.groups.forEach(b=>{typeof b=="number"&&Number.isInteger(b)&&b>=0&&b<c.length&&i(c[b],b);});}},o=c.indexOf(n);return i(n,o>=0?o:void 0),Array.from(s)}getNodeMainLabelFontSize(n){let c=n?._mainLabelFontSize;if(typeof c=="number"&&Number.isFinite(c))return c;let s=n?.visualWidth??n?.width??100,e=n?.visualHeight??n?.height??60,i=Math.max(1,s-Pi.TEXT_PADDING*2),o=Math.max(1,e-Pi.TEXT_PADDING*2),p=n?.label||n?.name||n?.id||"Node",E=Object.keys(n?.labels||{}).length>0,b=Object.keys(n?.attributes||{}).length>0,m=E||b?o*.5:o;return this.calculateOptimalFontSize(p,i,Math.max(1,m),"system-ui")}calculateGroupLabelFontSize(n,c){if(!this.currentLayout?.nodes?.length)return Pi.DEFAULT_FONT_SIZE;let s=this.collectGroupNodeIndices(n,c);if(s.length===0)return Pi.DEFAULT_FONT_SIZE;let e=s.map(p=>this.currentLayout.nodes[p]).filter(p=>!!p).map(p=>this.getNodeMainLabelFontSize(p));if(e.length===0)return Pi.DEFAULT_FONT_SIZE;let i=e.reduce((p,E)=>p+E,0)/e.length,o=Math.max(Pi.MIN_FONT_SIZE,Math.min(i,Pi.MAX_FONT_SIZE));return Math.round(o*10)/10}setupGroupLabels(n,c){return this.container.selectAll(".groupLabel").data(n).enter().append("text").attr("class","groupLabel").attr("text-anchor","middle").attr("dominant-baseline","hanging").attr("font-family","system-ui").attr("font-size",s=>{let e=this.calculateGroupLabelFontSize(s,n);return s._groupLabelFontSize=e,`${e}px`}).attr("font-weight","bold").attr("fill","#333").attr("pointer-events","none").text(s=>s.showLabel||false?(s.padding&&(s.padding=Math.max(s.padding,Pi.GROUP_LABEL_PADDING)),s.name||""):"").call(c.drag)}renderLinks(n,c){this.edgeRoutingCache.alignmentEdges.clear(),this.svgLinkGroups=this.setupLinks(n,c);}setupNodes(n,c){let s=c.drag();this.setupNodeDragHandlers(s);let e=this.container.selectAll(".node").data(n).enter().append("g").attr("class",i=>{let o=this.isErrorNode(i)?"error-node":"node";return this.isErrorNode(i)&&this.isSmallNode(i)?o+" small-error-node":o}).call(s).on("mousedown.inputmode",i=>{this.isInputModeActive&&(Co.event.stopPropagation(),this.startEdgeCreation(i));}).on("mouseup.inputmode",i=>{this.isInputModeActive&&this.edgeCreationState.isCreating&&(Co.event.stopPropagation(),this.finishEdgeCreation(i).catch(o=>{console.error("Error finishing edge creation:",o);}));}).on("mouseover",function(i){Co.select(this).append("title").attr("class","node-tooltip").text(`ID: ${i.id}`);}).on("mouseout",function(){Co.select(this).select("title.node-tooltip").remove();});return this.setupNodeRectangles(e),this.setupNodeIcons(e),this.setupMostSpecificTypeLabels(e),this.setupNodeLabels(e),e}setupNodeRectangles(n){n.append("rect").attr("width",c=>c.visualWidth??c.width).attr("height",c=>c.visualHeight??c.height).attr("x",c=>-(c.visualWidth??c.width)/2).attr("y",c=>-(c.visualHeight??c.height)/2).attr("stroke",c=>c.color||"black").attr("rx",Pi.NODE_BORDER_RADIUS).attr("ry",Pi.NODE_BORDER_RADIUS).attr("stroke-width",Pi.NODE_STROKE_WIDTH).attr("fill",c=>{let s=this.isHiddenNode(c),e=!!c.icon,i=c.showLabels;return s||e&&!i?"transparent":"white"});}setupNodeIcons(n){n.filter(c=>c.icon).append("image").attr("xlink:href",c=>c.icon).attr("width",c=>{let s=c.visualWidth??c.width;return c.showLabels?s*Pi.SMALL_IMG_SCALE_FACTOR:s}).attr("height",c=>{let s=c.visualHeight??c.height;return c.showLabels?s*Pi.SMALL_IMG_SCALE_FACTOR:s}).attr("x",c=>{let s=c.visualWidth??c.width;return c.showLabels?c.x+s-s*Pi.SMALL_IMG_SCALE_FACTOR:c.x-s/2}).attr("y",c=>{let s=c.visualHeight??c.height;return c.y-s/2}).append("title").text(c=>c.label||c.name||c.id||"Node").on("error",function(c,s){Co.select(this).attr("xlink:href","img/default.png"),console.error(`Failed to load icon for node ${s.id}: ${s.icon}`);});}setupMostSpecificTypeLabels(n){n.append("text").attr("class","mostSpecificTypeLabel").style("fill",c=>c.color||"black").text(c=>c.mostSpecificType||"");}getTextMeasurementContext(){return this.textMeasurementCanvas||(this.textMeasurementCanvas=document.createElement("canvas")),this.textMeasurementCanvas.getContext("2d")}measureTextWidth(n,c,s="system-ui"){let e=this.getTextMeasurementContext();return e.font=`${c}px ${s}`,e.measureText(n).width}calculateOptimalFontSize(n,c,s,e="system-ui"){let i=Pi.DEFAULT_FONT_SIZE;for(;i>Pi.MIN_FONT_SIZE;){let o=this.measureTextWidth(n,i,e),p=i*Pi.LINE_HEIGHT_RATIO;if(o<=c&&p<=s)break;i-=.5;}for(;i<Pi.MAX_FONT_SIZE;){let o=i+.5,p=this.measureTextWidth(n,o,e),E=o*Pi.LINE_HEIGHT_RATIO;if(p>c||E>s)break;i=o;}return Math.max(Pi.MIN_FONT_SIZE,Math.min(i,Pi.MAX_FONT_SIZE))}wrapText(n,c,s,e="system-ui"){let i=n.split(/\s+/),o=[],p="";for(let E of i){let b=p?`${p} ${E}`:E;this.measureTextWidth(b,s,e)<=c?p=b:p?(o.push(p),p=E):o.push(E);}return p&&o.push(p),o}setupNodeLabelsWithDynamicSizing(n){n.append("text").attr("class","label").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("font-family","system-ui").attr("fill","black").each((c,s,e)=>{if(this.isHiddenNode(c)||!c.showLabels)return;let o=Co.select(e[s]),p=c.width||100,E=c.height||60,b=p-Pi.TEXT_PADDING*2,y=E-Pi.TEXT_PADDING*2,m=c.label||c.name||c.id||"Node",u=c.attributes||{},l=Object.entries(u).sort(([z],[tt])=>z.localeCompare(tt)),a=c.labels||{},h=Object.entries(a),d=h.length>0,g=l.length>0,_=d||g,S=_?y*.5:y,v=this.calculateOptimalFontSize(m,b,S,"system-ui");c._mainLabelFontSize=v,o.attr("font-size",`${v}px`);let T=v*Pi.LINE_HEIGHT_RATIO,G=h.length+l.length,q=_?-G*T*.5:0;c._labelVerticalOffset=q,c._labelLineHeight=T,o.append("tspan").attr("x",0).attr("dy",`${q}px`).attr("class","main-label-tspan").style("font-weight","bold").style("font-size",`${v}px`).text(m);let j="";for(let[z,tt]of h){let pt=Array.isArray(tt)?tt.join(", "):String(tt);pt.length>j.length&&(j=pt);}for(let[z,tt]of l){let pt=`${z}: ${tt}`;pt.length>j.length&&(j=pt);}let B=v*.65,J=y-T,w=G>0?this.calculateOptimalFontSize(j||"SampleText",b,J/G,"system-ui"):v*.8,$=Math.max(w,B);if(d){let z="black";for(let[tt,pt]of h){let Z=Array.isArray(pt)?pt.join(", "):String(pt);o.append("tspan").attr("x",0).attr("dy",`${$*Pi.LINE_HEIGHT_RATIO}px`).style("font-size",`${$}px`).style("fill",z).style("font-style","italic").text(Z);}}if(g)for(let z=0;z<l.length;z++){let[tt,pt]=l[z],Z=`${tt}: ${pt}`;o.append("tspan").attr("x",0).attr("dy",`${$*Pi.LINE_HEIGHT_RATIO}px`).style("font-size",`${$}px`).text(Z);}});}setupNodeLabels(n){this.setupNodeLabelsWithDynamicSizing(n);}renderNodes(n,c){this.svgNodes=this.setupNodes(n,c);}resolveGroupEdgeEndpoints(n){if(!n.groupId)return {source:n.source,target:n.target};let c=this.currentLayout?.groups||[],s=c.find(p=>p.id===n.groupId);if(this._groupEdgeDebugLogged||(this._groupEdgeDebugLogged=new Set),this._groupEdgeDebugLogged.has(n.id)||(this._groupEdgeDebugLogged.add(n.id),console.log("[groupEdge DEBUG]",{edgeId:n.id,groupId:n.groupId,keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id,sourceIsInt:typeof n.source=="number",targetIsInt:typeof n.target=="number",groupFound:!!s,groupId_on_group:s?.id,availableGroupIds:c.map(p=>p.id)})),!s)return {source:n.source,target:n.target};let e=n.source,i=n.target;n.source?.id===n.keyNodeId?i=s:n.target?.id===n.keyNodeId?e=s:console.warn("[groupEdge] keyNodeId matched neither side",{keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id});let o=e===s?n.source:i===s?n.target:null;if(o&&!s.bounds&&o.x!=null&&Md?.Rectangle){let p=(o.visualWidth??o.width??50)/2,E=(o.visualHeight??o.height??30)/2;s.bounds=new Md.Rectangle(o.x-p,o.x+p,o.y-E,o.y+E);}return {source:e,target:i}}updatePositions(){this.svgGroups.attr("x",n=>n.bounds.x).attr("y",n=>n.bounds.y).attr("width",n=>n.bounds.width()).attr("height",n=>n.bounds.height()).lower(),this.svgNodes.select("rect").each(n=>{n.bounds&&(n.innerBounds=n.bounds.inflate(-1));}).attr("x",n=>n.x-(n.visualWidth??n.width)/2).attr("y",n=>n.y-(n.visualHeight??n.height)/2).attr("width",n=>n.visualWidth??n.width).attr("height",n=>n.visualHeight??n.height),this.svgNodes.select("image").attr("x",n=>{let c=n.visualWidth??n.width;return n.showLabels?n.x+c/2-c*Pi.SMALL_IMG_SCALE_FACTOR:n.x-c/2}).attr("y",n=>{let c=n.visualHeight??n.height;return n.showLabels,n.y-c/2}),this.svgNodes.select(".mostSpecificTypeLabel").attr("x",n=>n.x-(n.visualWidth??n.width??0)/2+5).attr("y",n=>n.y-(n.visualHeight??n.height??0)/2+10).raise(),this.svgNodes.select(".label").attr("x",n=>n.x).attr("y",n=>n.y).each((n,c,s)=>{let e=n._labelVerticalOffset||0,i=n._labelLineHeight||12;Co.select(s[c]).selectAll("tspan").attr("x",n.x).attr("dy",(o,p)=>p===0?`${e}px`:`${i}px`);}).raise(),this.svgLinkGroups.select("path").attr("d",n=>{let{source:c,target:s}=this.resolveGroupEdgeEndpoints(n),e=this.getStableEdgePath(c,s);return this.lineFunction(e)}).attr("marker-end",n=>this.isAlignmentEdge(n)?"none":"url(#end-arrow)").attr("marker-start",n=>this.isAlignmentEdge(n)||!n.bidirectional?"none":"url(#start-arrow)").raise(),this.svgLinkGroups.select(".linklabel").attr("x",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?this.calculateNewPosition(c,"x"):(n.source.x+n.target.x)/2}).attr("y",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?this.calculateNewPosition(c,"y"):(n.source.y+n.target.y)/2}).style("font-size",()=>{let n=this.getCurrentZoomScale(),c=12,s=n<1?c/Math.sqrt(n):c;return `${Math.min(s,16)}px`}).raise(),this.updateEdgeEndpointMarkers(),this.svgGroupLabels.attr("x",n=>n.bounds?n.bounds.x+n.bounds.width()/2:0).attr("y",n=>{if(!n.bounds)return 0;let c=n._groupLabelFontSize||Pi.DEFAULT_FONT_SIZE;return n.bounds.y+Math.max(4,c*.35)}).attr("text-anchor","middle").lower(),this.svgLinkGroups.selectAll("marker").raise(),this.svgLinkGroups.selectAll(".linklabel").raise(),this.svgGroups.selectAll(".error-group").raise(),this.svgNodes.selectAll(".error-node").raise();}updateEdgeEndpointMarkers(){this.svgLinkGroups&&(this.svgLinkGroups.select(".target-marker").attr("cx",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(c){let s=c.getTotalLength();return c.getPointAtLength(s).x}return n.target.x||0}).attr("cy",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(c){let s=c.getTotalLength();return c.getPointAtLength(s).y}return n.target.y||0}).attr("opacity",this.isInputModeActive?.8:0).style("pointer-events",this.isInputModeActive?"all":"none").raise(),this.svgLinkGroups.select(".source-marker").attr("cx",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?c.getPointAtLength(0).x:n.source.x||0}).attr("cy",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);return c?c.getPointAtLength(0).y:n.source.y||0}).attr("opacity",this.isInputModeActive?.8:0).style("pointer-events",this.isInputModeActive?"all":"none").raise());}gridUpdatePositions(){this.ensureNodeBounds(true);let n=this.container.selectAll(".node"),c=this.container.selectAll(".mostSpecificTypeLabel"),s=this.container.selectAll(".label"),e=this.container.selectAll(".group"),i=this.container.selectAll(".groupLabel");n.select("rect").each(function(p){p.innerBounds=p.bounds.inflate(-1);}).attr("x",function(p){return p.bounds.x}).attr("y",function(p){return p.bounds.y}).attr("width",function(p){return p.bounds.width()}).attr("height",function(p){return p.bounds.height()}),n.select("image").attr("x",function(p){let E=p.visualWidth??p.width;return p.showLabels?p.x+E/2-E*Pi.SMALL_IMG_SCALE_FACTOR:p.bounds.x}).attr("y",function(p){let E=p.visualHeight??p.height;return p.showLabels?p.y-E/2:p.bounds.y}),c.attr("x",function(p){return p.bounds.x+5}).attr("y",function(p){return p.bounds.y+10}).raise(),s.attr("x",p=>p.x).attr("y",p=>p.y).each(function(p){var E=0;Co.select(this).selectAll("tspan").attr("x",p.x).attr("dy",function(){return E+=1,E===1?"0em":"1em"});}).raise(),e.attr("x",function(p){return p.bounds.x}).attr("y",function(p){return p.bounds.y}).attr("width",function(p){return p.bounds.width()}).attr("height",function(p){return p.bounds.height()}).lower(),i.attr("x",function(p){return p.bounds.x+p.bounds.width()/2}).attr("y",function(p){let E=p._groupLabelFontSize||Pi.DEFAULT_FONT_SIZE;return p.bounds.y+Math.max(4,E*.35)}).attr("text-anchor","middle").raise();let o=this.container.selectAll(".link-group");o.select("path").attr("d",p=>{if(p.source?.id===p.target?.id){let h=this.createSelfLoopRoute(p);return this.lineFunction(h)}let{source:E,target:b}=this.resolveGroupEdgeEndpoints(p),y=h=>h.bounds?typeof h.bounds.cx=="function"?{x:h.bounds.cx(),y:h.bounds.cy()}:{x:(h.bounds.x+h.bounds.X)/2,y:(h.bounds.y+h.bounds.Y)/2}:{x:h.x??0,y:h.y??0},m=y(E),u=y(b),l=u.x-m.x,a=u.y-m.y;if(Math.abs(l)>Math.abs(a)){let h=m.x+l/2;return this.gridLineFunction([{x:m.x,y:m.y},{x:h,y:m.y},{x:h,y:u.y},{x:u.x,y:u.y}])}else {let h=m.y+a/2;return this.gridLineFunction([{x:m.x,y:m.y},{x:m.x,y:h},{x:u.x,y:h},{x:u.x,y:u.y}])}}),o.select("text.linklabel").attr("x",p=>{let E=this.shadowRoot?.querySelector(`path[data-link-id="${p.id}"]`);if(E){let m=E.getTotalLength();return E.getPointAtLength(m/2).x}let b=p.source?.x??p.source?.bounds?.cx()??0,y=p.target?.x??p.target?.bounds?.cx()??0;return (b+y)/2}).attr("y",p=>{let E=this.shadowRoot?.querySelector(`path[data-link-id="${p.id}"]`);if(E){let m=E.getTotalLength();return E.getPointAtLength(m/2).y}let b=p.source?.y??p.source?.bounds?.cy()??0,y=p.target?.y??p.target?.bounds?.cy()??0;return (b+y)/2}).raise();}routeEdges(){try{this.ensureNodeBounds(!0),typeof this.colaLayout?.prepareEdgeRouting=="function"&&this.colaLayout.prepareEdgeRouting(Pi.VIEWBOX_PADDING/Pi.EDGE_ROUTE_MARGIN_DIVISOR),this.buildEdgeRoutingCaches(),this.routeLinkPaths(),this.updateLinkLabelsAfterRouting(),this.fitViewportToContent();}catch(n){console.error("Error in edge routing:",n),this.showError(`Edge routing failed: ${n.message}`);}}ensureNodeBounds(n=false){if(!(!this.currentLayout?.nodes||!Md?.Rectangle))for(let c of this.currentLayout.nodes){if(!n&&c.bounds&&typeof c.bounds.rayIntersection=="function"){let b=c.bounds.cx(),y=c.bounds.cy(),m=1;if(Math.abs(b-(c.x||0))<m&&Math.abs(y-(c.y||0))<m)continue}let s=(c.visualWidth??c.width??50)/2,e=(c.visualHeight??c.height??30)/2,i=(c.x||0)-s,o=(c.x||0)+s,p=(c.y||0)-e,E=(c.y||0)+e;c.bounds=new Md.Rectangle(i,o,p,E),c.innerBounds=c.bounds.inflate(-1);}}buildEdgeRoutingCaches(){this.edgeRoutingCache.edgesBetweenNodes.clear(),this.edgeRoutingCache.alignmentEdges.clear(),this.currentLayout?.links&&(this.currentLayout.links.forEach(n=>{n.id?.startsWith("_alignment_")&&this.edgeRoutingCache.alignmentEdges.add(n.id);}),this.currentLayout.links.forEach(n=>{if(this.isAlignmentEdge(n))return;let c=n.source.id,s=n.target.id,e=this.getNodePairKey(c,s);this.edgeRoutingCache.edgesBetweenNodes.has(e)||this.edgeRoutingCache.edgesBetweenNodes.set(e,[]),this.edgeRoutingCache.edgesBetweenNodes.get(e).push(n);}));}getNodePairKey(n,c){return n<c?`${n}:${c}`:`${c}:${n}`}route(n=[],c=[],s,e){n.forEach(o=>{let p=o.bounds||o.innerBounds||this.createFallbackBounds(o);o.routerNode={name:o.name,bounds:p};}),c.forEach(o=>{o.bounds||console.warn("Grid routing group missing bounds; routing may be degraded.",o),o.routerNode={bounds:o.bounds?.inflate(-e)??o.bounds,children:(typeof o.groups<"u"?o.groups.map(p=>n.length+p.id):[]).concat(typeof o.leaves<"u"?o.leaves.map(p=>p.index):[])};});let i=n.concat(c).map((o,p)=>o.routerNode?(o.routerNode.id=p,o.routerNode):null).filter(Boolean);return new Md.GridRouter(i,{getChildren:o=>o.children,getBounds:o=>o.bounds},s-e)}gridify(n,c,s){if(this.isGridifyingInProgress){console.warn("[gridify] Already in progress, skipping re-entrant call");return}this.isGridifyingInProgress=true;try{this.gridifyInternal(n,c,s);}catch(e){console.log("Error routing edges in GridRouter"),console.error(e);try{this.fallbackGridRouting(this.currentLayout?.links??[]);}catch(o){console.error("Fallback grid routing also failed:",o);}let i=document.getElementById("runtime_messages");if(i){let o=document.createElement("div");o.className="alert alert-danger alert-dismissible fade show",o.setAttribute("role","alert"),o.innerHTML="Runtime (WebCola) error when gridifying edges. You may have to click and drag these nodes slightly to un-stick layout.",i.querySelectorAll(".alert").forEach(E=>{E.innerHTML===o.innerHTML&&E.remove();}),i.appendChild(o);}}finally{this.isGridifyingInProgress=false;}}gridifyInternal(n,c,s){let e=this.currentLayout?.nodes??[],i=this.currentLayout?.groups??[],o=this.currentLayout?.links??[];if(e.length===0){console.warn("No nodes available for GridRouter; skipping gridify.");return}if(o.length===0){console.warn("No edges to route in GridRouter");return}console.log("[gridify] Node positions BEFORE ensureNodeBounds:"),e.slice(0,3).forEach(a=>{console.log(` ${a.id}: x=${a.x?.toFixed(2)}, y=${a.y?.toFixed(2)}, bounds.cx=${a.bounds?.cx?.()?.toFixed(2)}, bounds.x=${a.bounds?.x?.toFixed(2)}`);}),this.ensureNodeBounds(true);let p=e.filter(a=>!Number.isFinite(a.x)||!Number.isFinite(a.y));if(p.length>0){console.warn("[gridify] Found nodes with invalid positions, falling back to default routing:",p.map(a=>({id:a.id,x:a.x,y:a.y}))),this.fallbackGridRouting(o);return}console.log("[gridify] Node positions AFTER ensureNodeBounds:"),e.slice(0,3).forEach(a=>{console.log(` ${a.id}: x=${a.x?.toFixed(2)}, y=${a.y?.toFixed(2)}, bounds.cx=${a.bounds?.cx?.()?.toFixed(2)}, bounds.x=${a.bounds?.x?.toFixed(2)}`);});let E=this.route(e,i,c,s),b=[],y=o.filter(a=>{let h=a?.source?.routerNode&&a?.target?.routerNode,d=a?.source?.id===a?.target?.id;return h&&!d}),m=o.filter(a=>a?.source?.id===a?.target?.id);console.log("[gridify] Total edges:",o.length,"Routable:",y.length,"Self-loops:",m.length),y.length+m.length!==o.length&&o.filter(h=>(!h?.source?.routerNode||!h?.target?.routerNode)&&h?.source?.id!==h?.target?.id).forEach(h=>{console.warn("[gridify] Unroutable edge:",h.id,"source routerNode:",!!h?.source?.routerNode,"target routerNode:",!!h?.target?.routerNode,"source:",h?.source?.id,"x:",h?.source?.x,"y:",h?.source?.y,"target:",h?.target?.id,"x:",h?.target?.x,"y:",h?.target?.y);}),b=E.routeEdges(y,n,function(a){return a.source.routerNode.id},function(a){return a.target.routerNode.id});let u=new Map;y.forEach((a,h)=>{let d=b[h];a?.id&&d&&u.set(a.id,this.adjustGridRouteForEdge(a,d));}),console.log("[gridify] Routes generated:",u.size,"out of",y.length),this.container.selectAll(".link-group").data(o,a=>a.id??a).select("path").attr("d",a=>{if(a.source?.id===a.target?.id){let T=this.createSelfLoopRoute(a);return this.lineFunction(T)}let h=u.get(a.id);if(!h){let T=a.source?.x??a.source?.bounds?.cx()??0,G=a.source?.y??a.source?.bounds?.cy()??0,q=a.target?.x??a.target?.bounds?.cx()??0,j=a.target?.y??a.target?.bounds?.cy()??0;console.log("[gridify] Fallback path for edge:",a.id,"from",a.source?.id,"(",T,",",G,")","to",a.target?.id,"(",q,",",j,")");let B=q-T,J=j-G;if(Math.abs(B)>Math.abs(J)){let w=T+B/2;return this.gridLineFunction([{x:T,y:G},{x:w,y:G},{x:w,y:j},{x:q,y:j}])}else {let w=G+J/2;return this.gridLineFunction([{x:T,y:G},{x:T,y:w},{x:q,y:w},{x:q,y:j}])}}let S=Md.GridRouter.getRoutePath(h,5,3,7);return this.adjustGridRouteForArrowPositioning(a,S.routepath,h)||S.routepath}),this.gridUpdateLinkLabels(o,u),this.fitViewportToContent(),this.dispatchEvent(new Event("relationsAvailable"));}fallbackGridRouting(n){this.container.selectAll(".link-group").data(n,s=>s.id??s).select("path").attr("d",s=>{if(s.source?.id===s.target?.id){let y=this.createSelfLoopRoute(s);return this.lineFunction(y)}let e=s.source?.x??s.source?.bounds?.cx()??0,i=s.source?.y??s.source?.bounds?.cy()??0,o=s.target?.x??s.target?.bounds?.cx()??0,p=s.target?.y??s.target?.bounds?.cy()??0,E=o-e,b=p-i;if(Math.abs(E)>Math.abs(b)){let y=e+E/2;return this.gridLineFunction([{x:e,y:i},{x:y,y:i},{x:y,y:p},{x:o,y:p}])}else {let y=i+b/2;return this.gridLineFunction([{x:e,y:i},{x:e,y},{x:o,y},{x:o,y:p}])}}),this.fitViewportToContent();}gridUpdateLinkLabels(n,c){this.container.selectAll(".link-group").filter(e=>!this.isAlignmentEdge(e)).select("text.linklabel").attr("x",e=>{let i=this.shadowRoot?.querySelector(`path[data-link-id="${e.id}"]`);if(i)try{let p=i.getTotalLength();return i.getPointAtLength(p/2).x}catch{}return this.getGridRouteMidpoint(e,c)?.x??e.source?.x??e.source?.bounds?.cx()??0}).attr("y",e=>{let i=this.shadowRoot?.querySelector(`path[data-link-id="${e.id}"]`);if(i)try{let p=i.getTotalLength();return i.getPointAtLength(p/2).y}catch{}return this.getGridRouteMidpoint(e,c)?.y??e.source?.y??e.source?.bounds?.cy()??0}).attr("text-anchor","middle").attr("dominant-baseline","middle");}getGridRouteMidpoint(n,c){let s=c.get(n.id);if(!s){let y=n.source?.x??n.source?.bounds?.cx()??0,m=n.source?.y??n.source?.bounds?.cy()??0,u=n.target?.x??n.target?.bounds?.cx()??0,l=n.target?.y??n.target?.bounds?.cy()??0;return {x:(y+u)/2,y:(m+l)/2}}let e=[];if(s.forEach(y=>{e.length===0&&y.length>0&&e.push(y[0]),y.length>1&&e.push(y[1]);}),e.length<2)return null;let i=0,o=[];for(let y=0;y<e.length-1;y++){let m=e[y+1].x-e[y].x,u=e[y+1].y-e[y].y,l=Math.sqrt(m*m+u*u);o.push(l),i+=l;}let p=i/2,E=0;for(let y=0;y<o.length;y++){let m=o[y];if(E+m>=p){let u=p-E,l=m>0?u/m:0;return {x:e[y].x+l*(e[y+1].x-e[y].x),y:e[y].y+l*(e[y+1].y-e[y].y)}}E+=m;}let b=Math.floor(e.length/2);return e[b]}adjustGridRouteForEdge(n,c){if(!n?.id?.startsWith("_g_"))return c;let s=this.gridRouteToPoints(c);if(s.length<2)return c;let e=this.routeGroupEdge(n,s);return this.pointsToGridRoute(e)}adjustGridRouteForArrowPositioning(n,c,s){if(!c||!n.source||!n.target)return null;try{let e=this.gridRouteToPoints(s);if(e.length<2)return null;let i=n.source,o=n.target,p=i.bounds||{x:i.x-(i.width||0)/2,y:i.y-(i.height||0)/2,width:()=>i.width||0,height:()=>i.height||0},E=o.bounds||{x:o.x-(o.width||0)/2,y:o.y-(o.height||0)/2,width:()=>o.width||0,height:()=>o.height||0},y=this.getTouchDirection(p,E,5);if(y!=="none"){let{sourcePoint:h,targetPoint:d,middlePoints:g}=this.computePerpendicularRoute(p,E,y),_=[h,...g,d];return this.gridLineFunction(_)}let m=e.length>1?e[1]:e[0],u=this.getRectangleIntersection(p.x+p.width()/2,p.y+p.height()/2,m.x,m.y,p);u&&(e[0]=u);let l=e.length>1?e[e.length-2]:e[e.length-1],a=this.getRectangleIntersection(E.x+E.width()/2,E.y+E.height()/2,l.x,l.y,E);return a&&(e[e.length-1]=a),this.gridLineFunction(e)}catch(e){return console.warn("Error adjusting grid route for arrow positioning:",e),null}}getTouchDirection(n,c,s){let e=n.x,i=n.x+n.width(),o=n.y,p=n.y+n.height(),E=c.x,b=c.x+c.width(),y=c.y,m=c.y+c.height(),u=Math.max(0,Math.max(E-i,e-b)),l=Math.max(0,Math.max(y-p,o-m)),a=!(p<y||m<o),h=!(i<E||b<e);return u<=s&&a?"horizontal":l<=s&&h?"vertical":"none"}computePerpendicularRoute(n,c,s){let e=n.width(),i=n.height(),o=c.width(),p=c.height(),E=n.x+e/2,b=n.y+i/2,y=c.x+o/2,m=c.y+p/2,u=15;if(s==="horizontal")if(b<=m){let a=Math.min(n.y,c.y)-u;return {sourcePoint:{x:E,y:n.y},targetPoint:{x:y,y:c.y},middlePoints:[{x:E,y:a},{x:y,y:a}]}}else {let a=Math.max(n.y+i,c.y+p)+u;return {sourcePoint:{x:E,y:n.y+i},targetPoint:{x:y,y:c.y+p},middlePoints:[{x:E,y:a},{x:y,y:a}]}}else if(E<=y){let a=Math.min(n.x,c.x)-u;return {sourcePoint:{x:n.x,y:b},targetPoint:{x:c.x,y:m},middlePoints:[{x:a,y:b},{x:a,y:m}]}}else {let a=Math.max(n.x+e,c.x+o)+u;return {sourcePoint:{x:n.x+e,y:b},targetPoint:{x:c.x+o,y:m},middlePoints:[{x:a,y:b},{x:a,y:m}]}}}areBoundsNear(n,c,s){let e=n.x,i=n.x+n.width(),o=n.y,p=n.y+n.height(),E=c.x,b=c.x+c.width(),y=c.y,m=c.y+c.height(),u=Math.max(0,Math.max(E-i,e-b)),l=Math.max(0,Math.max(y-p,o-m));return Math.sqrt(u*u+l*l)<=s}chooseBoundaryPoint(n,c,s,e){let i=Math.max(1,s.width()),o=Math.max(1,s.height()),p=[{x:s.x,y:s.y+o/2},{x:s.x+i,y:s.y+o/2},{x:s.x+i/2,y:s.y},{x:s.x+i/2,y:s.y+o}],E=p[0],b=-1/0;for(let y of p){let m=y.x-e.x,u=y.y-e.y,l=Math.sqrt(m*m+u*u);l>b&&(b=l,E=y);}return E}normalizeNodeBounds(n){let c=n.visualWidth??n.width??50,s=n.visualHeight??n.height??30,e=n.bounds||{x:n.x-c/2,y:n.y-s/2,width:()=>c,height:()=>s};return {x:typeof e.x=="number"||e.X!==void 0?e.x:n.x-c/2,y:typeof e.y=="number"?e.y:n.y-s/2,width:()=>typeof e.width=="function"?e.width():e.X!==void 0?e.X-e.x:c,height:()=>typeof e.height=="function"?e.height():e.Y!==void 0?e.Y-e.y:s}}lineIntersectsRect(n,c,s){let e=s.x,i=s.x+s.width(),o=s.y,p=s.y+s.height(),E=Math.min(n.x,c.x),b=Math.max(n.x,c.x),y=Math.min(n.y,c.y),m=Math.max(n.y,c.y);if(b<e||E>i||m<o||y>p)return false;let u=n.x>=e&&n.x<=i&&n.y>=o&&n.y<=p,l=c.x>=e&&c.x<=i&&c.y>=o&&c.y<=p;if(u||l)return true;let a=c.x-n.x,h=c.y-n.y,d=(_,S,v)=>{if(h===0)return false;let T=(_-n.y)/h;if(T<0||T>1)return false;let G=n.x+T*a;return G>=S&&G<=v},g=(_,S,v)=>{if(a===0)return false;let T=(_-n.x)/a;if(T<0||T>1)return false;let G=n.y+T*h;return G>=S&&G<=v};return d(o,e,i)||d(p,e,i)||g(e,o,p)||g(i,o,p)}findBlockingNodes(n,c,s,e){if(!this.currentLayout?.nodes)return [];let i=this.normalizeNodeBounds(n),o=this.normalizeNodeBounds(c),p={x:i.x+i.width()/2,y:i.y+i.height()/2},E={x:o.x+o.width()/2,y:o.y+o.height()/2},b=[];for(let y of this.currentLayout.nodes){if(y.id===s||y.id===e)continue;let m=this.normalizeNodeBounds(y);if(this.lineIntersectsRect(p,E,m)){let u={x:m.x+m.width()/2,y:m.y+m.height()/2},l=Math.sqrt(Math.pow(u.x-p.x,2)+Math.pow(u.y-p.y,2));b.push({node:y,bounds:m,distance:l});}}return b.sort((y,m)=>y.distance-m.distance),b.map(y=>({node:y.node,bounds:y.bounds}))}computeRouteAroundBlockingNodes(n,c,s){let i=Math.min(n.x,c.x),o=Math.max(n.x+n.width(),c.x+c.width()),p=Math.min(n.y,c.y),E=Math.max(n.y+n.height(),c.y+c.height());for(let{bounds:h}of s)i=Math.min(i,h.x),o=Math.max(o,h.x+h.width()),p=Math.min(p,h.y),E=Math.max(E,h.y+h.height());let b=n.x+n.width()/2,y=n.y+n.height()/2,m=c.x+c.width()/2,u=c.y+c.height()/2,l=Math.abs(m-b);if(Math.abs(u-y)>l)if(b<=m){let d=i-15;return {sourcePoint:{x:n.x,y},targetPoint:{x:c.x,y:u},middlePoints:[{x:d,y},{x:d,y:u}]}}else {let d=o+15;return {sourcePoint:{x:n.x+n.width(),y},targetPoint:{x:c.x+c.width(),y:u},middlePoints:[{x:d,y},{x:d,y:u}]}}else if(y<=u){let d=p-15;return {sourcePoint:{x:b,y:n.y},targetPoint:{x:m,y:c.y},middlePoints:[{x:b,y:d},{x:m,y:d}]}}else {let d=E+15;return {sourcePoint:{x:b,y:n.y+n.height()},targetPoint:{x:m,y:c.y+c.height()},middlePoints:[{x:b,y:d},{x:m,y:d}]}}}getNearTouchPerpendicularRoute(n){if(!n.source||!n.target||n.source.id===n.target.id)return null;let c=n.source,s=n.target,e=this.normalizeNodeBounds(c),i=this.normalizeNodeBounds(s),p=this.getTouchDirection(e,i,5);if(p!=="none"){let{sourcePoint:b,targetPoint:y,middlePoints:m}=this.computePerpendicularRoute(e,i,p);return [b,...m,y]}let E=this.findBlockingNodes(c,s,c.id,s.id);if(E.length>0){let{sourcePoint:b,targetPoint:y,middlePoints:m}=this.computeRouteAroundBlockingNodes(e,i,E);return [b,...m,y]}return null}gridRouteToPoints(n){let c=[];return n.forEach((s,e)=>{e===0&&c.push({x:s[0].x,y:s[0].y}),c.push({x:s[1].x,y:s[1].y});}),c}pointsToGridRoute(n){let c=[];for(let s=0;s<n.length-1;s+=1)c.push([n[s],n[s+1]]);return c}createFallbackBounds(n){if(!Md?.Rectangle)return null;let c=((n.visualWidth??n.width)||50)/2,s=((n.visualHeight??n.height)||30)/2,e=(n.x||0)-c,i=(n.x||0)+c,o=(n.y||0)-s,p=(n.y||0)+s;return new Md.Rectangle(e,i,o,p)}getRectangleIntersection(n,c,s,e,i){let o=i.x,p=i.x+i.width(),E=i.y,b=i.y+i.height(),y=s-n,m=e-c;if(y===0&&m===0)return {x:n,y:c};let u=0,l=1;if(y!==0){let h=(o-n)/y,d=(p-n)/y;u=Math.max(u,Math.min(h,d)),l=Math.min(l,Math.max(h,d));}if(m!==0){let h=(E-c)/m,d=(b-c)/m;u=Math.max(u,Math.min(h,d)),l=Math.min(l,Math.max(h,d));}if(u>l)return null;let a=u>0?u:l;return {x:n+a*y,y:c+a*m}}routeLinkPaths(){this.container.selectAll(".link-group path").attr("d",n=>{try{return this.routeSingleEdge(n)}catch(c){return console.error(`Error routing edge ${n.id} from ${n.source.id} to ${n.target.id}:`,c),this.showRuntimeAlert(n.source.id,n.target.id),this.lineFunction([{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}])}});}routeSingleEdge(n){if(this.isAlignmentEdge(n))return this.lineFunction([{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}]);let c=[{x:n.source.x||0,y:n.source.y||0},{x:n.target.x||0,y:n.target.y||0}],s;if(typeof this.colaLayout?.routeEdge=="function")try{if(s=this.colaLayout.routeEdge(n),!s||!Array.isArray(s)||s.length<2||!s[0]||!s[1]||s[0].x===void 0||s[0].y===void 0)throw new Error(`WebCola failed to route edge ${n.id} from ${n.source.id} to ${n.target.id}`)}catch(i){return console.log("Error routing edge",n.id,`from ${n.source.id} to ${n.target.id}`),console.error(i),this.lineFunction(c)}else s=c;if(n.source.id===n.target.id)s=this.createSelfLoopRoute(n);else {if(n.id?.startsWith("_g_"))return s=this.routeGroupEdge(n,s),this.lineFunction(s);s=this.handleMultipleEdgeRouting(n,s);}let e=this.getNearTouchPerpendicularRoute(n);return e?this.lineFunction(e):this.lineFunction(s)}createSelfLoopRoute(n){let c=n.source,s=c.bounds;if(!s)return [{x:c.x,y:c.y},{x:c.x+20,y:c.y-20},{x:c.x,y:c.y}];let e=s.X-s.x,i=s.Y-s.y,o={x:s.x+e/2,y:s.y},p={x:s.X,y:s.y+i/2},b=1+(n.selfLoopIndex||0)*Pi.SELF_LOOP_CURVATURE_SCALE,y={x:s.X+e/2*b,y:s.y-i/2*b};return [o,y,p]}routeGroupEdge(n,c){let s=n.groupId?(this.currentLayout?.groups||[]).find(e=>e.id===n.groupId):null;if(!s)console.warn("[routeGroupEdge] Group not found for edge:",n.id,"\u2014 groupId:",n.groupId);else {if(!s.bounds&&Md?.Rectangle){let e=n.source?.id===n.keyNodeId?c[c.length-1]:c[0];e&&(s.bounds=new Md.Rectangle(e.x-50,e.x+50,e.y-30,e.y+30));}if(s.bounds)if(n.source?.id===n.keyNodeId)c[c.length-1]=this.closestPointOnRect(s.bounds,c[0]);else if(n.target?.id===n.keyNodeId){let e=s.bounds.inflate?.(-1)??s.bounds;c[0]=this.closestPointOnRect(e,c[c.length-1]);}else console.warn("[routeGroupEdge] keyNodeId matched neither side",{keyNodeId:n.keyNodeId,sourceId:n.source?.id,targetId:n.target?.id});}return c.length>2&&c.splice(1,c.length-2),c}handleMultipleEdgeRouting(n,c){let s=this.getAllEdgesBetweenNodes(n.source.id,n.target.id);if(s.length<=1)return c;if(c.length===2){let b={x:(c[0].x+c[1].x)/2,y:(c[0].y+c[1].y)/2};c.splice(1,0,b);}let e=c[1].x-c[0].x,i=c[1].y-c[0].y,o=Math.atan2(i,e),p=this.getRouteLength(c),E=s.findIndex(b=>b.id===n.id);if(E!==-1){c=this.applyEdgeOffsetWithIndex(n,c,s,o,E,p);let b=this.calculateCurvatureWithIndex(s,n.id,E),y=this.clampCurvature(b);c=this.applyCurvatureToRoute(c,y,o,p);}return c}getAllEdgesBetweenNodes(n,c){if(!this.currentLayout?.links)return [];let s=this.getNodePairKey(n,c);return this.edgeRoutingCache.edgesBetweenNodes.has(s)?this.edgeRoutingCache.edgesBetweenNodes.get(s):this.currentLayout.links.filter(e=>!this.isAlignmentEdge(e)&&(e.source.id===n&&e.target.id===c||e.source.id===c&&e.target.id===n))}calculateCurvature(n,c,s,e){if(e.startsWith("_alignment_"))return 0;let i=n.length,o=n.findIndex(p=>p.id===e);return i<=1?0:(o%2===0?1:-1)*(Math.floor(o/2)+1)*Pi.CURVATURE_BASE_MULTIPLIER*i}calculateCurvatureWithIndex(n,c,s){let e=n.length;return e<=1?0:(s%2===0?1:-1)*(Math.floor(s/2)+1)*Pi.CURVATURE_BASE_MULTIPLIER*e}applyEdgeOffset(n,c,s,e){let i=s.findIndex(p=>p.id===n.id),o=this.getRouteLength(c);return this.applyEdgeOffsetWithIndex(n,c,s,e,i,o)}applyEdgeOffsetWithIndex(n,c,s,e,i,o){let p=(i%2===0?1:-1)*(Math.floor(i/2)+1)*Pi.MIN_EDGE_DISTANCE,E=this.clampOffset(p,o),b=this.getDominantDirection(e);return b==="right"||b==="left"?(c[0].y+=E,c[c.length-1].y+=E):(b==="up"||b==="down")&&(c[0].x+=E,c[c.length-1].x+=E),n.source.innerBounds&&(c[0]=this.adjustPointToRectanglePerimeter(c[0],n.source.innerBounds)),n.target.innerBounds&&(c[c.length-1]=this.adjustPointToRectanglePerimeter(c[c.length-1],n.target.innerBounds)),c}clampOffset(n,c){let s=Math.max(Pi.MIN_EDGE_DISTANCE,c*Pi.MAX_EDGE_OFFSET_RATIO);return Math.max(-s,Math.min(s,n))}getRouteLength(n){return n.length<2?0:n.slice(1).reduce((c,s,e)=>{let i=n[e],o=s.x-i.x,p=s.y-i.y;return c+Math.sqrt(o*o+p*p)},0)}clampCurvature(n){return Math.max(-Pi.MAX_EDGE_CURVATURE_RATIO,Math.min(Pi.MAX_EDGE_CURVATURE_RATIO,n))}applyCurvatureToRoute(n,c,s,e){return c===0||n.forEach((i,o)=>{if(o>0&&o<n.length-1){let p=c*Math.abs(Math.sin(s))*e,E=c*Math.abs(Math.cos(s))*e;i.x+=p,i.y+=E;}}),n}getDominantDirection(n){return n=(n+Math.PI)%(2*Math.PI)-Math.PI,n>=-Math.PI/4&&n<=Math.PI/4?"right":n>Math.PI/4&&n<3*Math.PI/4?"up":n>=3*Math.PI/4||n<=-3*Math.PI/4?"left":n>-3*Math.PI/4&&n<-Math.PI/4?"down":null}closestPointOnRect(n,c){if(!n)return c;let{x:s,y:e,X:i,Y:o}=n,p=Math.max(s,Math.min(c.x,i)),E=Math.max(e,Math.min(c.y,o));return {x:p,y:E}}getStableEdgeAnchor(n,c){if(!n)return c;let s,e,i,o;if(typeof n.cx=="function")s=n.cx(),e=n.cy(),i=n.width()/2,o=n.height()/2;else if(n.x!==void 0&&n.X!==void 0)s=(n.x+n.X)/2,e=(n.y+n.Y)/2,i=(n.X-n.x)/2,o=(n.Y-n.y)/2;else return c;let p=c.x-s,E=c.y-e,b=Math.abs(p)/i,y=Math.abs(E)/o;return b>y?p>0?{x:s+i,y:e}:{x:s-i,y:e}:E>0?{x:s,y:e+o}:{x:s,y:e-o}}getStableEdgePath(n,c){let s={x:n.x||0,y:n.y||0},e={x:c.x||0,y:c.y||0},i=y=>{let m=((y.visualWidth??y.width)||0)/2,u=((y.visualHeight??y.height)||0)/2;if(m===0&&u===0)return null;let l=y.x||0,a=y.y||0;return {cx:()=>l,cy:()=>a,width:()=>m*2,height:()=>u*2,x:l-m,X:l+m,y:a-u,Y:a+u}},o=i(n)??n.bounds??n.innerBounds,p=i(c)??c.bounds??c.innerBounds,E=o?this.getStableEdgeAnchor(o,e):s,b=p?this.getStableEdgeAnchor(p,s):e;return [E,b]}adjustPointToRectanglePerimeter(n,c){return c?this.closestPointOnRect(c,n):n}updateLinkLabelsAfterRouting(){this.container.selectAll(".link-group .linklabel").attr("x",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(!c)return 0;let s=c.getTotalLength();return c.getPointAtLength(s/2).x}).attr("y",n=>{let c=this.shadowRoot?.querySelector(`path[data-link-id="${n.id}"]`);if(!c)return 0;let s=c.getTotalLength();return c.getPointAtLength(s/2).y}).attr("text-anchor","middle").each((n,c,s)=>{this.handleLabelOverlap(s[c]);}).raise();}handleLabelOverlap(n){let c=[];this.container.selectAll(".linklabel").each(function(){this!==n&&_ft(this,n)&&c.push(this);}),c.length>0&&this.minimizeOverlap(n,c);}minimizeOverlap(n,c){}fitViewportToContent(n=false){let c=this.svg?.node();if(!c||!this.zoomBehavior||this.userHasManuallyZoomed&&!this.isInitialRender&&!n)return;let s=this.calculateContentBounds();if(!s)return;let e=c.clientWidth||c.parentElement?.clientWidth||800,i=c.clientHeight||c.parentElement?.clientHeight||600,o=Pi.VIEWBOX_PADDING*4,p=(e-o*2)/s.width,E=(i-o*2)/s.height,b=Math.min(p,E,1),[y,m]=this.zoomBehavior.scaleExtent(),u=Math.max(y,Math.min(m,b)),l=s.x+s.width/2,a=s.y+s.height/2,h=e/2-l*u,d=i/2-a*u,g=Co.zoomIdentity.translate(h,d).scale(u);this.isInitialRender?(this.svg.call(this.zoomBehavior.transform,g),this.isInitialRender=false):this.svg.transition().duration(300).ease(Co.easeCubicOut).call(this.zoomBehavior.transform,g),this.updateZoomControlStates();}resetViewToFitContent(){this.userHasManuallyZoomed=false,this.fitViewportToContent(true);}calculateContentBounds(){try{if(!this.currentLayout||!this.container)return null;let n=1/0,c=1/0,s=-1/0,e=-1/0,i=(l,a,h,d)=>{[l,a,h,d].every(Number.isFinite)&&(n=Math.min(n,l),s=Math.max(s,a),c=Math.min(c,h),e=Math.max(e,d));},o=this.currentLayout.nodes;o&&o.length>0&&o.forEach(l=>{if(this.isHiddenNode(l)||typeof l.x!="number"||typeof l.y!="number")return;let a=l.visualWidth??l.width??0,h=l.visualHeight??l.height??0,d=a/2,g=h/2;i(l.x-d,l.x+d,l.y-g,l.y+g);});let p=this,E=this.container.selectAll(".link-group path");E.empty()||E.each(function(l){if(!(l?.id&&p.isAlignmentEdge(l)))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x,a.x+a.width,a.y,a.y+a.height);}catch{}});let b=this.container.selectAll(".node, .error-node");b.empty()||b.each(function(l){if(!p.isHiddenNode(l))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x,a.x+a.width,a.y,a.y+a.height);}catch{}});let y=this.container.selectAll("text");y.empty()||y.each(function(l){if(!(l&&(typeof l.name=="string"||typeof l.id=="string")&&p.isHiddenNode(l)))try{let a=this.getBBox();(a.width>0||a.height>0)&&i(a.x-5,a.x+a.width+5,a.y-5,a.y+a.height+5);}catch{}});let m=this.container.selectAll(".group");return m.empty()||m.each(function(){try{let l=this.getBBox();(l.width>0||l.height>0)&&i(l.x,l.x+l.width,l.y,l.y+l.height);}catch{}}),n===1/0||c===1/0||s===-1/0||e===-1/0?(console.warn("Could not calculate content bounds - no valid elements found"),null):{x:n,y:c,width:s-n,height:e-c}}catch(n){return console.error("Error calculating content bounds:",n),null}}dispatchRelationsAvailableEvent(){let n=this.getAllRelations(),c=new CustomEvent("relations-available",{detail:{relations:n,count:n.length,timestamp:Date.now(),graphId:this.id||"unknown"},bubbles:true,cancelable:true});this.dispatchEvent(c);}getAllRelations(){if(!this.currentLayout?.links)return [];let n=new Set(this.currentLayout.links.filter(c=>!this.isAlignmentEdge(c)).map(c=>c.relName).filter(Boolean));return Array.from(n)}highlightRelation(n){return this.currentLayout?.links?(this.svgLinkGroups.filter(c=>c.relName===n&&!this.isAlignmentEdge(c)).selectAll("path").classed("highlighted",true),true):false}clearHighlightRelation(n){return this.currentLayout?.links?(this.svgLinkGroups.filter(c=>c.relName===n&&!this.isAlignmentEdge(c)).selectAll("path").classed("highlighted",false),true):false}highlightNodes(n){if(!this.currentLayout?.nodes||!this.svgNodes||!n||n.length===0)return false;let c=new Set(n),s=false;return this.svgNodes.each((e,i,o)=>{c.has(e.id)&&(Co.select(o[i]).classed("highlighted",true),s=true);}),s}highlightNodePairs(n,c={}){if(!this.currentLayout?.nodes||!this.svgNodes||!n||n.length===0)return false;let{showBadges:s=false}=c,e=new Set,i=new Set;n.forEach((p,E)=>{if(!Array.isArray(p)){console.warn(`highlightNodePairs: Pair at index ${E} is not an array, skipping`);return}if(p.length!==2){console.warn(`highlightNodePairs: Pair at index ${E} has ${p.length} elements (expected 2), skipping`);return}let[b,y]=p;b&&e.add(b),y&&i.add(y);});let o=false;return this.svgNodes.each((p,E,b)=>{let y=Co.select(b[E]);e.has(p.id)&&(y.classed("highlighted-first",true),o=true,s&&this.addHighlightBadge(y,p,"1","#007aff")),i.has(p.id)&&(y.classed("highlighted-second",true),o=true,s&&(e.has(p.id)?this.addHighlightBadge(y,p,"1,2","#9B59B6"):this.addHighlightBadge(y,p,"2","#ff3b30")));}),o}clearNodeHighlights(){return this.svgNodes?(this.svgNodes.classed("highlighted",false).classed("highlighted-first",false).classed("highlighted-second",false).selectAll(".highlight-badge, .highlight-badge-bg").remove(),true):false}addHighlightBadge(n,c,s,e){n.selectAll(".highlight-badge, .highlight-badge-bg").remove();let i=16,o=4,p=(c.width||0)/2-i/2-o,E=-(c.height||0)/2+i/2+o;n.append("circle").attr("class","highlight-badge-bg").attr("cx",p).attr("cy",E).attr("r",i/2).attr("fill",e),n.append("text").attr("class","highlight-badge").attr("x",p).attr("y",E).attr("dy","0.35em").text(s);}showRuntimeAlert(n,c){console.warn(`Runtime (WebCola) error when laying out an edge from ${n} to ${c}. You may have to click and drag these nodes slightly to un-stick layout.`);}getCSS(){return `
852
852
  :host {
853
853
  display: block;
854
854
  width: 100%;
@@ -1408,7 +1408,7 @@ Expecting `+M1.join(", ")+", got '"+(this.terminals_[to]||to)+"'":g1="Parse erro
1408
1408
  <button class="modal-button primary" data-action="ok">OK</button>
1409
1409
  </div>
1410
1410
  </div>
1411
- `;let i=e.querySelector(".modal-input");e.addEventListener("click",p=>{let E=p.target;if(E.classList.contains("modal-overlay"))this.shadowRoot.removeChild(e),s(null);else if(E.dataset.action==="cancel")this.shadowRoot.removeChild(e),s(null);else if(E.dataset.action==="delete")this.shadowRoot.removeChild(e),s("DELETE");else if(E.dataset.action==="ok"){let b=i.value;this.shadowRoot.removeChild(e),s(b);}});let o=p=>{if(p.key==="Enter"){let E=i.value;this.shadowRoot.removeChild(e),document.removeEventListener("keydown",o),s(E);}else p.key==="Escape"&&(this.shadowRoot.removeChild(e),document.removeEventListener("keydown",o),s(null));};document.addEventListener("keydown",o),this.shadowRoot.appendChild(e),i.focus(),i.select();})}async takeScreenshot(){let n=this.shadowRoot?.querySelector("#svg");if(!n){console.warn("No SVG element found for screenshot.");return}try{let c=n.cloneNode(!0),s=n.getAttribute("viewBox"),e=n.clientWidth||800,i=n.clientHeight||600;if(s){let a=s.split(/[\s,]+/).map(Number);a.length===4&&(e=a[2],i=a[3]),c.setAttribute("viewBox",s);}c.setAttribute("width",String(e)),c.setAttribute("height",String(i)),c.removeAttribute("preserveAspectRatio"),this.inlineComputedStyles(n,c),await this.convertImagesToBase64(c);let o=document.createElementNS("http://www.w3.org/2000/svg","rect");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.setAttribute("fill","white"),c.insertBefore(o,c.firstChild);let E=new XMLSerializer().serializeToString(c),b=Pi.SCREENSHOT_SCALE,y=await this.svgStringToPngBlob(E,e,i,b);if(!y){console.error("Failed to generate PNG blob from SVG.");return}let m=URL.createObjectURL(y),u=document.createElement("a");u.href=m;let l=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);u.download=`graph-screenshot-${l}.png`,document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(m);}catch(c){console.error("Screenshot failed:",c);}}inlineComputedStyles(n,c){let s=["font-family","font-size","font-weight","font-style","fill","stroke","stroke-width","stroke-dasharray","stroke-linejoin","opacity","text-anchor","dominant-baseline","paint-order","visibility","display"],e=n.children,i=c.children;if(n instanceof HTMLElement||n instanceof SVGElement){let p=getComputedStyle(n),E=c;for(let b of s){let y=p.getPropertyValue(b);y&&E.style.setProperty(b,y);}}let o=Math.min(e.length,i.length);for(let p=0;p<o;p++)this.inlineComputedStyles(e[p],i[p]);}async convertImagesToBase64(n){let c=n.querySelectorAll("image"),s=[];c.forEach(e=>{let i=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!i||i.startsWith("data:"))return;let o=this.fetchImageAsBase64(i).then(p=>{e.setAttribute("href",p),e.removeAttributeNS("http://www.w3.org/1999/xlink","href");}).catch(()=>{e.remove();});s.push(o);}),await Promise.all(s);}fetchImageAsBase64(n){return new Promise((c,s)=>{let e=new Image;e.crossOrigin="anonymous",e.onload=()=>{let i=document.createElement("canvas");i.width=e.naturalWidth,i.height=e.naturalHeight;let o=i.getContext("2d");if(!o){s(new Error("No canvas context"));return}o.drawImage(e,0,0),c(i.toDataURL("image/png"));},e.onerror=()=>s(new Error(`Failed to load: ${n}`)),e.src=n;})}svgStringToPngBlob(n,c,s,e){return new Promise(i=>{let o=new Blob([n],{type:"image/svg+xml;charset=utf-8"}),p=URL.createObjectURL(o),E=new Image;E.onload=()=>{let b=document.createElement("canvas");b.width=c*e,b.height=s*e;let y=b.getContext("2d");if(!y){URL.revokeObjectURL(p),i(null);return}y.scale(e,e),y.fillStyle="white",y.fillRect(0,0,c,s),y.drawImage(E,0,0,c,s),b.toBlob(m=>{URL.revokeObjectURL(p),i(m);},"image/png");},E.onerror=()=>{URL.revokeObjectURL(p),i(null);},E.src=p;})}disconnectedCallback(){this.dispose();}dispose(){this.detachInputModeListeners(),this.deactivateInputMode(),this.svg&&(this.svg.on(".zoom",null),this.svg.selectAll("*").remove()),this.container&&this.container.selectAll("*").remove(),this.svgNodes&&(this.svgNodes.on(".drag",null),this.svgNodes.on(".cnd",null)),this.colaLayout&&(typeof this.colaLayout.stop=="function"&&this.colaLayout.stop(),this.colaLayout.on("tick",null),this.colaLayout.on("end",null)),this.currentLayout=null,this.colaLayout=null,this.svgNodes=null,this.svgLinkGroups=null,this.svgGroups=null,this.svgGroupLabels=null,this.zoomBehavior=null,this.storedTransform=null,this.dragStartPositions.clear(),this.cleanupEdgeCreation(),this.textMeasurementCanvas&&(this.textMeasurementCanvas=null);}getMemoryStats(){return {nodeCount:this.currentLayout?.nodes?.length||0,edgeCount:this.currentLayout?.links?.length||0,groupCount:this.currentLayout?.groups?.length||0,constraintCount:this.currentLayout?.constraints?.length||0,hasActiveLayout:!!this.colaLayout}}};Pi.DEFAULT_SVG_WIDTH=800,Pi.DEFAULT_SVG_HEIGHT=600,Pi.SMALL_IMG_SCALE_FACTOR=.3,Pi.NODE_BORDER_RADIUS=3,Pi.NODE_STROKE_WIDTH=1.5,Pi.DEFAULT_FONT_SIZE=10,Pi.MIN_FONT_SIZE=6,Pi.MAX_FONT_SIZE=16,Pi.TEXT_PADDING=8,Pi.LINE_HEIGHT_RATIO=1.2,Pi.SCREENSHOT_SCALE=3,Pi.DISCONNECTED_NODE_PREFIX="_d_",Pi.GROUP_BORDER_RADIUS=8,Pi.GROUP_FILL_OPACITY=.25,Pi.GROUP_LABEL_PADDING=20,Pi.DEFAULT_GROUP_COMPACTNESS=1e-5,Pi.EDGE_ROUTE_MARGIN_DIVISOR=3,Pi.CURVATURE_BASE_MULTIPLIER=.15,Pi.MIN_EDGE_DISTANCE=10,Pi.MAX_EDGE_OFFSET_RATIO=.35,Pi.MAX_EDGE_CURVATURE_RATIO=.6,Pi.SELF_LOOP_CURVATURE_SCALE=.2,Pi.VIEWBOX_PADDING=10,Pi.INITIAL_UNCONSTRAINED_ITERATIONS=10,Pi.INITIAL_USER_CONSTRAINT_ITERATIONS=50,Pi.INITIAL_ALL_CONSTRAINTS_ITERATIONS=200,Pi.GRID_SNAP_ITERATIONS=1,Pi.LOADING_INDICATOR_DELAY_MS=180;fx=Pi;typeof customElements<"u"&&typeof HTMLElement<"u"&&customElements.define("webcola-cnd-graph",fx);});var YF;exports.JSONDataInstance=void 0;exports.DataInstanceNormalizer=void 0;var o6=Cn(()=>{YF=Di(Up()),exports.JSONDataInstance=class t{constructor(r,n={}){this.atoms=[];this.relations=[];this.types=[];this.errors=[];this.eventListeners=new Map;try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object")throw new Error("Invalid data: expected object with atoms and relations");if(!Array.isArray(c.atoms))throw new Error("Invalid data: atoms must be an array");if(!Array.isArray(c.relations))throw new Error("Invalid data: relations must be an array");let s=exports.DataInstanceNormalizer.normalize(c,n);this.atoms=s.atoms,this.relations=s.relations,this.types=s.types,this.errors=s.errors;}catch(c){throw new Error(`Failed to create JSONDataInstance: ${c instanceof Error?c.message:String(c)}`)}}addEventListener(r,n){this.eventListeners.has(r)||this.eventListeners.set(r,new Set),this.eventListeners.get(r).add(n);}removeEventListener(r,n){let c=this.eventListeners.get(r);c&&c.delete(n);}emitEvent(r){let n=this.eventListeners.get(r.type);n&&n.forEach(c=>{try{c(r);}catch(s){console.error("Error in data instance event listener:",s);}});}isAtomBuiltin(r){return false}getAtomType(r){let n=this.atoms.find(s=>s.id===r);if(!n)throw new Error(`Atom with ID '${r}' not found`);let c=this.types.find(s=>s.id===n.type);if(!c)throw new Error(`Type '${n.type}' not found for atom '${r}'`);return c}getTypes(){return this.types}getAtoms(){return this.atoms}getRelations(){return this.relations}getTopLevelTypeId(r){let n=this.types.find(c=>c.id===r);return n&&n.types.length>0?n.types[n.types.length-1]:r}typeIsOfType(r,n){let c=this.types.find(s=>s.id===r);return c?c.types.includes(n):r===n}applyProjections(r){if(r.length===0)return this.clone();let n={};for(let E of r){let b=this.atoms.find(m=>m.id===E);if(!b)throw new Error(`Cannot project over atom '${E}': atom not found`);let y=this.getTopLevelTypeId(b.type);if(n[y])throw new Error(`Cannot project over '${E}' and '${n[y]}'. Both are of type '${y}'`);n[y]=E;}let c=Object.keys(n),s=Object.values(n),e=new Set(s),i=this.types.map(E=>{let b=c.some(y=>this.typeIsOfType(E.id,y));return {...E,atoms:b?[]:E.atoms.filter(y=>!e.has(y.id))}}),o=this.relations.map(E=>{if(!E.types.some(l=>c.some(a=>this.typeIsOfType(l,a))))return E;let y=[];E.types.forEach((l,a)=>{c.some(h=>this.typeIsOfType(l,h))&&y.push(a);});let m=E.tuples.filter(l=>y.every(a=>{let h=l.atoms[a],d=E.types[a],g=c.find(S=>this.typeIsOfType(d,S));if(!g)return true;let _=n[g];return h===_})).map(l=>({atoms:l.atoms.filter((a,h)=>!y.includes(h)),types:l.types.filter((a,h)=>!y.includes(h))})).filter(l=>l.atoms.length>0),u=E.types.filter((l,a)=>!y.includes(a));return {...E,types:u,tuples:m}}).filter(E=>E.tuples.length>0||E.types.length>0),p=this.atoms.filter(E=>{let b=this.getTopLevelTypeId(E.type);return !c.includes(b)});return new t({atoms:p,relations:o,types:i})}generateGraph(r=false,n=false){let c=new YF.Graph({directed:true,multigraph:true});if(this.atoms.forEach(s=>{c.setNode(s.id,{id:s.id,label:s.label,type:s.type,isBuiltin:this.isAtomBuiltin(s)});}),this.relations.forEach(s=>{s.tuples.forEach((e,i)=>{if(e.atoms.length>=2){let o=e.atoms[0],p=e.atoms[e.atoms.length-1],E=e.atoms.slice(1,-1),b=s.name;if(E.length>0){let m=E.map(u=>{let l=this.atoms.find(a=>a.id===u);return l?l.label:u});b=`${s.name}[${m.join(", ")}]`;}let y=`${s.id}_${i}`;c.setEdge(o,p,b,y);}else if(e.atoms.length===1){let o=e.atoms[0],p=`${s.id}_${i}`;c.setEdge(o,o,s.name,p);}});}),r||n){let s=[];c.nodes().forEach(e=>{let i=c.inEdges(e)||[],o=c.outEdges(e)||[];if(i.length===0&&o.length===0){let b=c.node(e)?.isBuiltin||false;(r||b&&n)&&s.push(e);}}),s.forEach(e=>{c.removeNode(e);});}return c}addAtom(r){if(this.atoms.some(c=>c.id===r.id))throw new Error(`Atom with ID '${r.id}' already exists`);this.atoms.push(r);let n=this.types.find(c=>c.id===r.type);n||(n={id:r.type,types:[r.type],atoms:[],isBuiltin:false},this.types.push(n)),n.atoms.push(r),this.emitEvent({type:"atomAdded",data:{atom:r}});}addRelationTuple(r,n){for(let s of n.atoms)if(!this.atoms.some(e=>e.id===s))throw new Error(`Cannot add tuple: referenced atom '${s}' does not exist`);let c=this.relations.find(s=>s.id===r||s.name===r);if(!c)c={id:r,name:r,types:[...n.types],tuples:[]},this.relations.push(c);else {let s=new Set(c.types);for(let e of n.types)s.has(e)||c.types.push(e);}c.tuples.push(n),this.emitEvent({type:"relationTupleAdded",data:{relationId:r,tuple:n}});}removeAtom(r){let n=this.atoms.findIndex(e=>e.id===r);if(n===-1)throw new Error(`Cannot remove atom: atom with ID '${r}' not found`);let c=this.atoms[n];this.atoms.splice(n,1);let s=this.types.find(e=>e.id===c.type);s&&(s.atoms=s.atoms.filter(e=>e.id!==r));for(let e of this.relations)e.tuples=e.tuples.filter(i=>!i.atoms.includes(r));this.emitEvent({type:"atomRemoved",data:{atomId:r}});}removeRelationTuple(r,n){let c=this.relations.find(i=>i.id===r||i.name===r);if(!c)throw new Error(`Cannot remove tuple: relation '${r}' not found`);let s=(i,o)=>i.atoms.length!==o.atoms.length?false:i.atoms.every((p,E)=>p===o.atoms[E]),e=c.tuples.length;if(c.tuples=c.tuples.filter(i=>!s(i,n)),c.tuples.length===e)throw new Error(`Tuple not found in relation '${r}'`);this.emitEvent({type:"relationTupleRemoved",data:{relationId:r,tuple:n}});}reify(){return {atoms:[...this.atoms],relations:this.relations.map(r=>({...r,tuples:[...r.tuples]})),types:this.types.map(r=>({...r,atoms:[...r.atoms]}))}}addFromDataInstance(r,n){if(!r)return false;let c=new Map;return r.getAtoms().forEach(s=>{let e=this.isAtomBuiltin(s);if(n&&e){let p=this.atoms.find(E=>E.type===s.type&&E.label===s.label);if(p){c.set(s.id,p.id);return}}let i=`atom_${this.atoms.length+1}`;c.set(s.id,i);let o={...s,id:i};this.addAtom(o);}),r.getRelations().forEach(s=>{let e=s.tuples.map(o=>({atoms:o.atoms.map(p=>c.get(p)||p),types:o.types})),i=this.relations.find(o=>o.id===s.id||o.name===s.name);if(i){let o=new Set(i.tuples.map(p=>JSON.stringify(p)));e.forEach(p=>{let E=JSON.stringify(p);o.has(E)||(i.tuples.push(p),o.add(E));});}else this.relations.push({...s,tuples:e});}),r.getTypes().forEach(s=>{let e=this.types.find(i=>i.id===s.id);if(!e)this.types.push({...s,atoms:s.atoms.map(i=>({...i,id:c.get(i.id)||i.id}))});else {let i=new Set(e.atoms.map(o=>o.id));s.atoms.forEach(o=>{let p=c.get(o.id)||o.id;i.has(p)||(e.atoms.push({...o,id:p}),i.add(p));});}}),true}getErrors(){return [...this.errors]}isValid(){return this.errors.length===0}getStatistics(){return {atomCount:this.atoms.length,relationCount:this.relations.length,typeCount:this.types.length,tupleCount:this.relations.reduce((r,n)=>r+n.tuples.length,0),errorCount:this.errors.length,hasBuiltinTypes:this.types.some(r=>r.isBuiltin)}}clone(){return new t(this.reify())}},exports.DataInstanceNormalizer=class t{static mergeRelations(r){let n=new Map;for(let c of r){let s=n.get(c.name);if(s){let e=new Set(s.tuples.map(o=>JSON.stringify(o)));for(let o of c.tuples){let p=JSON.stringify(o);e.has(p)||(s.tuples.push(o),e.add(p));}let i=new Set(s.types);for(let o of c.types)i.has(o)||(s.types.push(o),i.add(o));}else n.set(c.name,{id:c.id||c.name,name:c.name,types:[...c.types],tuples:[...c.tuples]});}return Array.from(n.values())}static inferTypes(r){let n=new Map;for(let c of r)n.has(c.type)||n.set(c.type,{id:c.type,types:[c.type],atoms:[],isBuiltin:t.isBuiltinType(c.type)}),n.get(c.type).atoms.push(c);return Array.from(n.values())}static isBuiltinType(r){return new Set(["String","Int","Bool","seq/Int","univ","none","Entity","Object","Node","Edge","Atom"]).has(r)}static deduplicateAtoms(r){let n=new Map,c=new Set;for(let s of r)n.has(s.id)?c.add(s.id):n.set(s.id,s);return c.size>0&&console.warn(`Found duplicate atoms with IDs: ${Array.from(c).join(", ")}`),Array.from(n.values())}static validateReferences(r,n){let c=new Set(r.map(e=>e.id)),s=[];for(let e of n)for(let i=0;i<e.tuples.length;i++){let o=e.tuples[i];for(let p=0;p<o.atoms.length;p++){let E=o.atoms[p];c.has(E)||s.push(`Relation "${e.name}" tuple ${i} position ${p}: references unknown atom "${E}"`);}}return {isValid:s.length===0,errors:s}}static normalize(r,n={}){let c={mergeRelations:true,inferTypes:true,validateReferences:true,deduplicateAtoms:true,...n},s=r.atoms||[],e=r.relations||[],i=r.types||[],o=[];if(c.deduplicateAtoms&&s.length>0){let p=s.length;s=this.deduplicateAtoms(s),s.length<p&&o.push(`Removed ${p-s.length} duplicate atoms`);}if(c.mergeRelations&&e.length>0){let p=e.length;e=this.mergeRelations(e),e.length<p&&o.push(`Merged ${p-e.length} duplicate relations`);}if(c.inferTypes&&i.length===0&&s.length>0&&(i=this.inferTypes(s),o.push(`Inferred ${i.length} types from atoms`)),c.validateReferences){let p=this.validateReferences(s,e);o.push(...p.errors);}return {atoms:s,relations:e,types:i,errors:o}}};});var WF={};Qx(WF,{StructuredInputGraph:()=>exports.StructuredInputGraph});exports.StructuredInputGraph=void 0;var a6=Cn(()=>{K4();o6();sv();Ov();O3();exports.StructuredInputGraph=class extends fx{constructor(n){super(true);this.evaluator=null;this.layoutInstance=null;this.cndSpecString="";this.controlsContainer=null;this.customTypes=new Set;this.relationAtomPositions=["",""];this.currentConstraintError=null;this.dataInstanceEventHandlers={atomAdded:null,atomRemoved:null,relationTupleAdded:null,relationTupleRemoved:null};let c=n||new exports.JSONDataInstance({atoms:[],relations:[]});console.log("StructuredInputGraph initialized with data instance:",c),this.setDataInstance(c),this.initializeStructuredInput(),this.addEventListener("edge-creation-requested",this.handleEdgeCreationRequest.bind(this)),this.addEventListener("edge-modification-requested",this.handleEdgeModificationRequest.bind(this)),this.addEventListener("edge-reconnection-requested",this.handleEdgeReconnectionRequest.bind(this));}static get observedAttributes(){return ["cnd-spec","data-instance","show-export"]}attributeChangedCallback(n,c,s){if(c!==s)switch(n){case "cnd-spec":this.parseCnDSpec(s);break;case "data-instance":this.updateDataInstance(s);break;case "show-export":this.updateExportVisibility(s==="true");break}}initializeStructuredInput(){requestAnimationFrame(()=>{this.createControlsInterface();});}createControlsInterface(){if(!this.shadowRoot)return;this.controlsContainer=document.createElement("div"),this.controlsContainer.className="structured-input-controls",this.controlsContainer.innerHTML=this.getControlsHTML();let n=document.createElement("style");n.textContent=this.getControlsCSS(),this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(this.controlsContainer),this.bindControlEvents();}getControlsHTML(){return `
1411
+ `;let i=e.querySelector(".modal-input");e.addEventListener("click",p=>{let E=p.target;if(E.classList.contains("modal-overlay"))this.shadowRoot.removeChild(e),s(null);else if(E.dataset.action==="cancel")this.shadowRoot.removeChild(e),s(null);else if(E.dataset.action==="delete")this.shadowRoot.removeChild(e),s("DELETE");else if(E.dataset.action==="ok"){let b=i.value;this.shadowRoot.removeChild(e),s(b);}});let o=p=>{if(p.key==="Enter"){let E=i.value;this.shadowRoot.removeChild(e),document.removeEventListener("keydown",o),s(E);}else p.key==="Escape"&&(this.shadowRoot.removeChild(e),document.removeEventListener("keydown",o),s(null));};document.addEventListener("keydown",o),this.shadowRoot.appendChild(e),i.focus(),i.select();})}async takeScreenshot(){let n=this.shadowRoot?.querySelector("#svg");if(!n){console.warn("No SVG element found for screenshot.");return}try{let c=n.cloneNode(!0),s=n.getAttribute("viewBox"),e=n.clientWidth||800,i=n.clientHeight||600;if(s){let a=s.split(/[\s,]+/).map(Number);a.length===4&&(e=a[2],i=a[3]),c.setAttribute("viewBox",s);}c.setAttribute("width",String(e)),c.setAttribute("height",String(i)),c.removeAttribute("preserveAspectRatio"),this.inlineComputedStyles(n,c),await this.convertImagesToBase64(c);let o=document.createElementNS("http://www.w3.org/2000/svg","rect");o.setAttribute("width","100%"),o.setAttribute("height","100%"),o.setAttribute("fill","white"),c.insertBefore(o,c.firstChild);let E=new XMLSerializer().serializeToString(c),b=Pi.SCREENSHOT_SCALE,y=await this.svgStringToPngBlob(E,e,i,b);if(!y){console.error("Failed to generate PNG blob from SVG.");return}let m=URL.createObjectURL(y),u=document.createElement("a");u.href=m;let l=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19);u.download=`graph-screenshot-${l}.png`,document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(m);}catch(c){console.error("Screenshot failed:",c);}}inlineComputedStyles(n,c){let s=["font-family","font-size","font-weight","font-style","fill","stroke","stroke-width","stroke-dasharray","stroke-linejoin","opacity","text-anchor","dominant-baseline","paint-order","visibility","display"],e=n.children,i=c.children;if(n instanceof HTMLElement||n instanceof SVGElement){let p=getComputedStyle(n),E=c;for(let b of s){let y=p.getPropertyValue(b);y&&E.style.setProperty(b,y);}}let o=Math.min(e.length,i.length);for(let p=0;p<o;p++)this.inlineComputedStyles(e[p],i[p]);}async convertImagesToBase64(n){let c=n.querySelectorAll("image"),s=[];c.forEach(e=>{let i=e.getAttribute("href")||e.getAttributeNS("http://www.w3.org/1999/xlink","href");if(!i||i.startsWith("data:"))return;let o=this.fetchImageAsBase64(i).then(p=>{e.setAttribute("href",p),e.removeAttributeNS("http://www.w3.org/1999/xlink","href");}).catch(()=>{e.remove();});s.push(o);}),await Promise.all(s);}fetchImageAsBase64(n){return new Promise((c,s)=>{let e=new Image;e.crossOrigin="anonymous",e.onload=()=>{let i=document.createElement("canvas");i.width=e.naturalWidth,i.height=e.naturalHeight;let o=i.getContext("2d");if(!o){s(new Error("No canvas context"));return}o.drawImage(e,0,0),c(i.toDataURL("image/png"));},e.onerror=()=>s(new Error(`Failed to load: ${n}`)),e.src=n;})}svgStringToPngBlob(n,c,s,e){return new Promise(i=>{let o=new Blob([n],{type:"image/svg+xml;charset=utf-8"}),p=URL.createObjectURL(o),E=new Image;E.onload=()=>{let b=document.createElement("canvas");b.width=c*e,b.height=s*e;let y=b.getContext("2d");if(!y){URL.revokeObjectURL(p),i(null);return}y.scale(e,e),y.fillStyle="white",y.fillRect(0,0,c,s),y.drawImage(E,0,0,c,s),b.toBlob(m=>{URL.revokeObjectURL(p),i(m);},"image/png");},E.onerror=()=>{URL.revokeObjectURL(p),i(null);},E.src=p;})}disconnectedCallback(){this.dispose();}dispose(){this.detachInputModeListeners(),this.deactivateInputMode(),this.svg&&(this.svg.on(".zoom",null),this.svg.selectAll("*").remove()),this.container&&this.container.selectAll("*").remove(),this.svgNodes&&(this.svgNodes.on(".drag",null),this.svgNodes.on(".cnd",null)),this.colaLayout&&(typeof this.colaLayout.stop=="function"&&this.colaLayout.stop(),this.colaLayout.on("tick",null),this.colaLayout.on("end",null)),this.currentLayout=null,this.colaLayout=null,this.svgNodes=null,this.svgLinkGroups=null,this.svgGroups=null,this.svgGroupLabels=null,this.zoomBehavior=null,this.storedTransform=null,this.dragStartPositions.clear(),this.cleanupEdgeCreation(),this.textMeasurementCanvas&&(this.textMeasurementCanvas=null);}getMemoryStats(){return {nodeCount:this.currentLayout?.nodes?.length||0,edgeCount:this.currentLayout?.links?.length||0,groupCount:this.currentLayout?.groups?.length||0,constraintCount:this.currentLayout?.constraints?.length||0,hasActiveLayout:!!this.colaLayout}}};Pi.DEFAULT_SVG_WIDTH=800,Pi.DEFAULT_SVG_HEIGHT=600,Pi.SMALL_IMG_SCALE_FACTOR=.3,Pi.NODE_BORDER_RADIUS=3,Pi.NODE_STROKE_WIDTH=1.5,Pi.DEFAULT_FONT_SIZE=10,Pi.MIN_FONT_SIZE=6,Pi.MAX_FONT_SIZE=16,Pi.TEXT_PADDING=8,Pi.LINE_HEIGHT_RATIO=1.2,Pi.SCREENSHOT_SCALE=3,Pi.DISCONNECTED_NODE_PREFIX="_d_",Pi.GROUP_BORDER_RADIUS=8,Pi.GROUP_FILL_OPACITY=.25,Pi.GROUP_LABEL_PADDING=20,Pi.DEFAULT_GROUP_COMPACTNESS=1e-5,Pi.EDGE_ROUTE_MARGIN_DIVISOR=3,Pi.CURVATURE_BASE_MULTIPLIER=.15,Pi.MIN_EDGE_DISTANCE=10,Pi.MAX_EDGE_OFFSET_RATIO=.35,Pi.MAX_EDGE_CURVATURE_RATIO=.6,Pi.SELF_LOOP_CURVATURE_SCALE=.2,Pi.VIEWBOX_PADDING=10,Pi.INITIAL_UNCONSTRAINED_ITERATIONS=10,Pi.INITIAL_USER_CONSTRAINT_ITERATIONS=50,Pi.INITIAL_ALL_CONSTRAINTS_ITERATIONS=200,Pi.GRID_SNAP_ITERATIONS=1,Pi.LOADING_INDICATOR_DELAY_MS=180;fx=Pi;typeof customElements<"u"&&typeof HTMLElement<"u"&&customElements.define("webcola-cnd-graph",fx);});var YF;exports.JSONDataInstance=void 0;exports.DataInstanceNormalizer=void 0;var o6=Cn(()=>{YF=Di(Up()),exports.JSONDataInstance=class t{constructor(r,n={}){this.atoms=[];this.relations=[];this.types=[];this.errors=[];this.eventListeners=new Map;try{let c=typeof r=="string"?JSON.parse(r):r;if(!c||typeof c!="object")throw new Error("Invalid data: expected object with atoms and relations");if(!Array.isArray(c.atoms))throw new Error("Invalid data: atoms must be an array");if(!Array.isArray(c.relations))throw new Error("Invalid data: relations must be an array");let s=exports.DataInstanceNormalizer.normalize(c,n);this.atoms=s.atoms,this.relations=s.relations,this.types=s.types,this.errors=s.errors;}catch(c){throw new Error(`Failed to create JSONDataInstance: ${c instanceof Error?c.message:String(c)}`)}}addEventListener(r,n){this.eventListeners.has(r)||this.eventListeners.set(r,new Set),this.eventListeners.get(r).add(n);}removeEventListener(r,n){let c=this.eventListeners.get(r);c&&c.delete(n);}emitEvent(r){let n=this.eventListeners.get(r.type);n&&n.forEach(c=>{try{c(r);}catch(s){console.error("Error in data instance event listener:",s);}});}isAtomBuiltin(r){return false}getAtomType(r){let n=this.atoms.find(s=>s.id===r);if(!n)throw new Error(`Atom with ID '${r}' not found`);let c=this.types.find(s=>s.id===n.type);if(!c)throw new Error(`Type '${n.type}' not found for atom '${r}'`);return c}getTypes(){return this.types}getAtoms(){return this.atoms}getRelations(){return this.relations}getTopLevelTypeId(r){let n=this.types.find(c=>c.id===r);return n&&n.types.length>0?n.types[n.types.length-1]:r}typeIsOfType(r,n){let c=this.types.find(s=>s.id===r);return c?c.types.includes(n):r===n}applyProjections(r){if(r.length===0)return this.clone();let n={};for(let E of r){let b=this.atoms.find(m=>m.id===E);if(!b)throw new Error(`Cannot project over atom '${E}': atom not found`);let y=this.getTopLevelTypeId(b.type);if(n[y])throw new Error(`Cannot project over '${E}' and '${n[y]}'. Both are of type '${y}'`);n[y]=E;}let c=Object.keys(n),s=Object.values(n),e=new Set(s),i=this.types.map(E=>{let b=c.some(y=>this.typeIsOfType(E.id,y));return {...E,atoms:b?[]:E.atoms.filter(y=>!e.has(y.id))}}),o=this.relations.map(E=>{if(!E.types.some(l=>c.some(a=>this.typeIsOfType(l,a))))return E;let y=[];E.types.forEach((l,a)=>{c.some(h=>this.typeIsOfType(l,h))&&y.push(a);});let m=E.tuples.filter(l=>y.every(a=>{let h=l.atoms[a],d=E.types[a],g=c.find(S=>this.typeIsOfType(d,S));if(!g)return true;let _=n[g];return h===_})).map(l=>({atoms:l.atoms.filter((a,h)=>!y.includes(h)),types:l.types.filter((a,h)=>!y.includes(h))})).filter(l=>l.atoms.length>0),u=E.types.filter((l,a)=>!y.includes(a));return {...E,types:u,tuples:m}}).filter(E=>E.tuples.length>0||E.types.length>0),p=this.atoms.filter(E=>{let b=this.getTopLevelTypeId(E.type);return !c.includes(b)});return new t({atoms:p,relations:o,types:i})}generateGraph(r=false,n=false){let c=new YF.Graph({directed:true,multigraph:true});if(this.atoms.forEach(s=>{c.setNode(s.id,{id:s.id,label:s.label,type:s.type,isBuiltin:this.isAtomBuiltin(s)});}),this.relations.forEach(s=>{s.tuples.forEach((e,i)=>{if(e.atoms.length>=2){let o=e.atoms[0],p=e.atoms[e.atoms.length-1],E=e.atoms.slice(1,-1),b=s.name;if(E.length>0){let m=E.map(u=>{let l=this.atoms.find(a=>a.id===u);return l?l.label:u});b=`${s.name}[${m.join(", ")}]`;}let y=`${s.id}_${i}`;c.setEdge(o,p,b,y);}else if(e.atoms.length===1){let o=e.atoms[0],p=`${s.id}_${i}`;c.setEdge(o,o,s.name,p);}});}),r||n){let s=[];c.nodes().forEach(e=>{let i=c.inEdges(e)||[],o=c.outEdges(e)||[];if(i.length===0&&o.length===0){let b=c.node(e)?.isBuiltin||false;(r||b&&n)&&s.push(e);}}),s.forEach(e=>{c.removeNode(e);});}return c}addAtom(r){if(this.atoms.some(c=>c.id===r.id))throw new Error(`Atom with ID '${r.id}' already exists`);this.atoms.push(r);let n=this.types.find(c=>c.id===r.type);n||(n={id:r.type,types:[r.type],atoms:[],isBuiltin:false},this.types.push(n)),n.atoms.push(r),this.emitEvent({type:"atomAdded",data:{atom:r}});}addRelationTuple(r,n){for(let s of n.atoms)if(!this.atoms.some(e=>e.id===s))throw new Error(`Cannot add tuple: referenced atom '${s}' does not exist`);let c=this.relations.find(s=>s.id===r||s.name===r);if(!c)c={id:r,name:r,types:[...n.types],tuples:[]},this.relations.push(c);else {let s=new Set(c.types);for(let e of n.types)s.has(e)||c.types.push(e);}c.tuples.push(n),this.emitEvent({type:"relationTupleAdded",data:{relationId:r,tuple:n}});}removeAtom(r){let n=this.atoms.findIndex(e=>e.id===r);if(n===-1)throw new Error(`Cannot remove atom: atom with ID '${r}' not found`);let c=this.atoms[n];this.atoms.splice(n,1);let s=this.types.find(e=>e.id===c.type);s&&(s.atoms=s.atoms.filter(e=>e.id!==r));for(let e of this.relations)e.tuples=e.tuples.filter(i=>!i.atoms.includes(r));this.emitEvent({type:"atomRemoved",data:{atomId:r}});}removeRelationTuple(r,n){let c=this.relations.find(i=>i.id===r||i.name===r);if(!c)throw new Error(`Cannot remove tuple: relation '${r}' not found`);let s=(i,o)=>i.atoms.length!==o.atoms.length?false:i.atoms.every((p,E)=>p===o.atoms[E]),e=c.tuples.length;if(c.tuples=c.tuples.filter(i=>!s(i,n)),c.tuples.length===e)throw new Error(`Tuple not found in relation '${r}'`);this.emitEvent({type:"relationTupleRemoved",data:{relationId:r,tuple:n}});}reify(){return {atoms:[...this.atoms],relations:this.relations.map(r=>({...r,tuples:[...r.tuples]})),types:this.types.map(r=>({...r,atoms:[...r.atoms]}))}}addFromDataInstance(r,n){if(!r)return false;let c=new Map;return r.getAtoms().forEach(s=>{let e=this.isAtomBuiltin(s);if(n&&e){let p=this.atoms.find(E=>E.type===s.type&&E.label===s.label);if(p){c.set(s.id,p.id);return}}let i=`atom_${this.atoms.length+1}`;c.set(s.id,i);let o={...s,id:i};this.addAtom(o);}),r.getRelations().forEach(s=>{let e=s.tuples.map(o=>({atoms:o.atoms.map(p=>c.get(p)||p),types:o.types})),i=this.relations.find(o=>o.id===s.id||o.name===s.name);if(i){let o=new Set(i.tuples.map(p=>JSON.stringify(p)));e.forEach(p=>{let E=JSON.stringify(p);o.has(E)||(i.tuples.push(p),o.add(E));});}else this.relations.push({...s,tuples:e});}),r.getTypes().forEach(s=>{let e=this.types.find(i=>i.id===s.id);if(!e)this.types.push({...s,atoms:s.atoms.map(i=>({...i,id:c.get(i.id)||i.id}))});else {let i=new Set(e.atoms.map(o=>o.id));s.atoms.forEach(o=>{let p=c.get(o.id)||o.id;i.has(p)||(e.atoms.push({...o,id:p}),i.add(p));});}}),true}getErrors(){return [...this.errors]}isValid(){return this.errors.length===0}getStatistics(){return {atomCount:this.atoms.length,relationCount:this.relations.length,typeCount:this.types.length,tupleCount:this.relations.reduce((r,n)=>r+n.tuples.length,0),errorCount:this.errors.length,hasBuiltinTypes:this.types.some(r=>r.isBuiltin)}}clone(){return new t(this.reify())}},exports.DataInstanceNormalizer=class t{static mergeRelations(r){let n=new Map;for(let c of r){let s=n.get(c.name);if(s){let e=new Set(s.tuples.map(o=>JSON.stringify(o)));for(let o of c.tuples){let p=JSON.stringify(o);e.has(p)||(s.tuples.push(o),e.add(p));}let i=new Set(s.types);for(let o of c.types)i.has(o)||(s.types.push(o),i.add(o));}else n.set(c.name,{id:c.id||c.name,name:c.name,types:[...c.types],tuples:[...c.tuples]});}return Array.from(n.values())}static inferTypes(r){let n=new Map;for(let c of r)n.has(c.type)||n.set(c.type,{id:c.type,types:[c.type],atoms:[],isBuiltin:t.isBuiltinType(c.type)}),n.get(c.type).atoms.push(c);return Array.from(n.values())}static isBuiltinType(r){return new Set(["String","Int","Bool","seq/Int","univ","none","Entity","Object","Node","Edge","Atom"]).has(r)}static deduplicateAtoms(r){let n=new Map,c=new Set;for(let s of r)n.has(s.id)?c.add(s.id):n.set(s.id,s);return c.size>0&&console.warn(`Found duplicate atoms with IDs: ${Array.from(c).join(", ")}`),Array.from(n.values())}static validateReferences(r,n){let c=new Set(r.map(e=>e.id)),s=[];for(let e of n)for(let i=0;i<e.tuples.length;i++){let o=e.tuples[i];for(let p=0;p<o.atoms.length;p++){let E=o.atoms[p];c.has(E)||s.push(`Relation "${e.name}" tuple ${i} position ${p}: references unknown atom "${E}"`);}}return {isValid:s.length===0,errors:s}}static normalize(r,n={}){let c={mergeRelations:true,inferTypes:true,validateReferences:true,deduplicateAtoms:true,...n},s=r.atoms||[],e=r.relations||[],i=r.types||[],o=[];if(c.deduplicateAtoms&&s.length>0){let p=s.length;s=this.deduplicateAtoms(s),s.length<p&&o.push(`Removed ${p-s.length} duplicate atoms`);}if(c.mergeRelations&&e.length>0){let p=e.length;e=this.mergeRelations(e),e.length<p&&o.push(`Merged ${p-e.length} duplicate relations`);}if(c.inferTypes&&i.length===0&&s.length>0&&(i=this.inferTypes(s),o.push(`Inferred ${i.length} types from atoms`)),c.validateReferences){let p=this.validateReferences(s,e);o.push(...p.errors);}return {atoms:s,relations:e,types:i,errors:o}}};});var WF={};Qx(WF,{StructuredInputGraph:()=>exports.StructuredInputGraph});exports.StructuredInputGraph=void 0;var a6=Cn(()=>{K4();o6();sv();Ov();O3();exports.StructuredInputGraph=class extends fx{constructor(n){super(true);this.evaluator=null;this.layoutInstance=null;this.cndSpecString="";this.controlsContainer=null;this.customTypes=new Set;this.relationAtomPositions=["",""];this.currentConstraintError=null;this._suppressDataChangeRerender=false;this.dataInstanceEventHandlers={atomAdded:null,atomRemoved:null,relationTupleAdded:null,relationTupleRemoved:null};let c=n||new exports.JSONDataInstance({atoms:[],relations:[]});console.log("StructuredInputGraph initialized with data instance:",c),this.setDataInstance(c),this.initializeStructuredInput(),this.addEventListener("edge-creation-requested",this.handleEdgeCreationRequest.bind(this)),this.addEventListener("edge-modification-requested",this.handleEdgeModificationRequest.bind(this)),this.addEventListener("edge-reconnection-requested",this.handleEdgeReconnectionRequest.bind(this));}static get observedAttributes(){return ["cnd-spec","data-instance","show-export"]}attributeChangedCallback(n,c,s){if(c!==s)switch(n){case "cnd-spec":this.parseCnDSpec(s);break;case "data-instance":this.updateDataInstance(s);break;case "show-export":this.updateExportVisibility(s==="true");break}}initializeStructuredInput(){requestAnimationFrame(()=>{this.createControlsInterface();});}createControlsInterface(){if(!this.shadowRoot)return;this.controlsContainer=document.createElement("div"),this.controlsContainer.className="structured-input-controls",this.controlsContainer.innerHTML=this.getControlsHTML();let n=document.createElement("style");n.textContent=this.getControlsCSS(),this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(this.controlsContainer),this.bindControlEvents();}getControlsHTML(){return `
1412
1412
  <div class="structured-input-panel">
1413
1413
  <div class="panel-header">
1414
1414
  <h3>Data Editor</h3>
@@ -1914,7 +1914,7 @@ Expecting `+M1.join(", ")+", got '"+(this.terminals_[to]||to)+"'":g1="Parse erro
1914
1914
  font-weight: 500;
1915
1915
  border: 1px solid #b6d7f0;
1916
1916
  }
1917
- `}bindControlEvents(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".toggle-panel"),c=this.controlsContainer.querySelector(".panel-content");n?.addEventListener("click",()=>{let T=c.classList.contains("collapsed");c.classList.toggle("collapsed"),n.textContent=T?"\u25B2":"\u25BC";}),this.controlsContainer.querySelectorAll(".section-header").forEach(T=>{let G=T.querySelector(".section-toggle"),j=T.closest(".section-card")?.querySelector(".section-content");G&&j&&(T.addEventListener("click",B=>{if(B.target===G)return;let J=j.classList.contains("collapsed");j.classList.toggle("collapsed"),G.textContent=J?"\u25B2":"\u25BC";}),G.addEventListener("click",B=>{B.stopPropagation();let J=j.classList.contains("collapsed");j.classList.toggle("collapsed"),G.textContent=J?"\u25B2":"\u25BC";}));});let e=this.controlsContainer.querySelector(".atom-type-select"),i=this.controlsContainer.querySelector(".custom-type-input"),o=this.controlsContainer.querySelector(".atom-label-input"),p=this.controlsContainer.querySelector(".add-atom-btn"),E=()=>{let T=e.value,q=i.value.trim()||T;p.disabled=!q||!o.value.trim();};e?.addEventListener("change",()=>{e.value&&e.value!=="Other..."&&(i.value=""),E();}),i?.addEventListener("input",()=>{i.value.trim()&&(e.value=""),E();}),o?.addEventListener("input",E),p?.addEventListener("click",async()=>{let T=i.value.trim(),G=T||e.value;if(T){this.customTypes.add(T);let q=Array.from(e.options).find(B=>B.value==="Other...");if(q&&e.removeChild(q),!Array.from(e.options).find(B=>B.value===T)){let B=document.createElement("option");B.value=T,B.textContent=T,e.appendChild(B);}q&&e.appendChild(q),e.value="",i.value="";}else if(!G)return;await this.addAtomFromForm(G,o.value.trim()),o.value="",E(),this.updateDeletionSelects(),this.updateAtomPositions();});let b=this.controlsContainer.querySelector(".relation-type-input"),y=this.controlsContainer.querySelector(".add-relation-btn"),m=this.controlsContainer.querySelector(".add-position-btn"),u=this.controlsContainer.querySelector(".remove-position-btn"),l=()=>{let G=this.relationAtomPositions.filter(j=>j.trim()!=="").length>=2,q=b.value.trim();y.disabled=!G||!q;};b?.addEventListener("input",l),this.updateAtomPositions(),m?.addEventListener("click",()=>{this.relationAtomPositions.push(""),this.updateAtomPositions(),l();}),u?.addEventListener("click",()=>{this.relationAtomPositions.length>2&&(this.relationAtomPositions.pop(),this.updateAtomPositions(),l());}),y?.addEventListener("click",async()=>{await this.addRelationFromForm(),b.value="",this.relationAtomPositions=["",""],this.updateAtomPositions(),l(),this.updateDeletionSelects();});let a=this.controlsContainer.querySelector(".atom-delete-select"),h=this.controlsContainer.querySelector(".relation-delete-select"),d=this.controlsContainer.querySelector(".delete-atom-btn"),g=this.controlsContainer.querySelector(".delete-relation-btn"),_=this.controlsContainer.querySelector(".clear-all-btn"),S=()=>{d.disabled=!a.value,g.disabled=!h.value;};a?.addEventListener("change",S),h?.addEventListener("change",S),d?.addEventListener("click",async()=>{await this.deleteAtom(a.value),this.updateDeletionSelects(),this.updateAtomPositions(),S();}),g?.addEventListener("click",async()=>{await this.deleteRelation(h.value),this.updateDeletionSelects(),S();}),_?.addEventListener("click",async()=>{await this.clearAllItems(),this.updateDeletionSelects(),this.updateAtomPositions(),S();}),this.controlsContainer.querySelector(".export-json-btn")?.addEventListener("click",()=>{this.exportDataAsJSON();}),this.updateDeletionSelects();}async handleEdgeCreationRequest(n){console.log("\u{1F517} Handling edge creation request:",n.detail);let{relationId:c,sourceNodeId:s,targetNodeId:e,tuple:i}=n.detail;try{this.dataInstance.addRelationTuple(c,i),console.log(`\u2705 Added relation to data instance: ${c}(${s}, ${e})`),await this.enforceConstraintsAndRegenerate();}catch(o){console.error("\u274C Failed to handle edge creation request:",o);}}async handleEdgeModificationRequest(n){console.log("\u{1F517} Handling edge modification request:",n.detail);let{oldRelationId:c,newRelationId:s,sourceNodeId:e,targetNodeId:i,tuple:o}=n.detail;try{if(!s||s.trim()==="")console.log("\u{1F5D1}\uFE0F Deleting edge (empty new relation name)"),c&&c.trim()&&(this.dataInstance.removeRelationTuple(c,o),console.log(`\u2705 Removed relation tuple from ${c}`));else if(c.trim()===s.trim()){console.log("\u23ED\uFE0F Same relation name, no data changes needed");return}else {if(c&&c.trim())try{this.dataInstance.removeRelationTuple(c,o),console.log(`\u{1F5D1}\uFE0F Removed from ${c}`);}catch(p){let E=p instanceof Error?p.message:String(p);console.log(`\u26A0\uFE0F Could not remove from ${c}: ${E}`);}this.dataInstance.addRelationTuple(s,o),console.log(`\u2795 Added to ${s}`);}await this.enforceConstraintsAndRegenerate();}catch(p){console.error("\u274C Failed to handle edge modification request:",p);}}async handleEdgeReconnectionRequest(n){console.log("\u{1F504} Handling edge reconnection request:",n.detail);let{relationId:c,oldTuple:s,newTuple:e,oldSourceNodeId:i,oldTargetNodeId:o,newSourceNodeId:p,newTargetNodeId:E}=n.detail;try{if(c&&c.trim())try{this.dataInstance.removeRelationTuple(c,s),console.log(`\u{1F5D1}\uFE0F Removed old tuple from ${c}: ${i} -> ${o}`);}catch(b){let y=b instanceof Error?b.message:String(b);console.log(`\u26A0\uFE0F Could not remove old tuple from ${c}: ${y}`);}this.dataInstance.addRelationTuple(c,e),console.log(`\u2795 Added new tuple to ${c}: ${p} -> ${E}`),await this.enforceConstraintsAndRegenerate();}catch(b){console.error("\u274C Failed to handle edge reconnection request:",b);}}async parseCnDSpec(n){try{console.log("\u{1F504} Parsing CnD spec and initializing pipeline..."),this.cndSpecString=n,await this.initializeCnDPipeline(n),this.updateTypeSelector(),this.updateSpecInfo(),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("spec-loaded",{detail:{spec:this.cndSpecString}})),console.log("\u2705 CnD spec parsed and pipeline initialized");}catch(c){console.error("\u274C Failed to parse CnD spec:",c),this.updateSpecInfo("error",c instanceof Error?c.message:"Parse error");}}async initializeCnDPipeline(n){if(!n.trim()){console.log("\u{1F4DD} Empty spec - clearing pipeline"),this.evaluator=null,this.layoutInstance=null;return}try{console.log("\u{1F527} Initializing CnD pipeline with spec...");let c=J2(n);console.log("\u{1F4CB} Layout spec parsed successfully"),this.evaluator=new exports.SGraphQueryEvaluator,this.evaluator.initialize({sourceData:this.dataInstance}),console.log("\u{1F50D} SGraphQueryEvaluator initialized with data instance"),this.layoutInstance=new exports.LayoutInstance(c,this.evaluator,0,!0),console.log("\u{1F4D0} LayoutInstance created"),console.log("\u2705 CnD pipeline initialized successfully (evaluator + layout instance)");}catch(c){throw console.error("\u274C Failed to initialize CnD pipeline:",c),this.evaluator=null,this.layoutInstance=null,c}}async enforceConstraintsAndRegenerate(){console.log("\u{1F504} enforceConstraintsAndRegenerate() called");try{if(!this.layoutInstance){console.log("\u26A0\uFE0F Cannot enforce constraints - no layout instance available");return}console.log("\u{1F4CA} Current data instance state:",{atoms:this.dataInstance.getAtoms().length,relations:this.dataInstance.getRelations().length}),this.evaluator&&(console.log("\u{1F504} Re-initializing evaluator with updated data instance..."),this.evaluator.initialize({sourceData:this.dataInstance}),console.log("\u2705 Evaluator re-initialized")),console.log("\u{1F527} Generating layout with constraint enforcement...");let n=this.layoutInstance.generateLayout(this.dataInstance);n.error?(console.warn("\u26A0\uFE0F Constraint validation error detected:",n.error),this.currentConstraintError=n.error,this.dispatchEvent(new CustomEvent("constraint-error",{detail:{error:n.error,layout:n.layout},bubbles:!0})),console.log("\u{1F4E4} Dispatched constraint-error event with UNSAT core information")):(console.log("\u2705 Layout generated successfully - all constraints satisfied"),this.currentConstraintError!==null&&(console.log("\u{1F9F9} Clearing previous constraint error - constraints now satisfied"),this.currentConstraintError=null,this.dispatchEvent(new CustomEvent("constraints-satisfied",{detail:{layout:n.layout},bubbles:!0})),console.log("\u{1F4E4} Dispatched constraints-satisfied event"))),console.log("\u{1F3A8} Rendering layout...");let c=this.getLayoutState(),s=c.positions.length>0;await this.renderLayout(n.layout,s?{priorPositions:c}:void 0),console.log("\u2705 Constraints enforced and layout regenerated successfully");}catch(n){console.error("\u274C Failed to enforce constraints and regenerate layout:",n),this.dispatchEvent(new CustomEvent("layout-generation-error",{detail:{error:n},bubbles:true}));}}refreshTypesFromDataInstance(){this.updateTypeSelector();}getAvailableAtomTypes(){let n=new Set;return this.dataInstance&&this.dataInstance.getAtoms().forEach(s=>{s.type&&n.add(s.type);}),n.size===0&&(n.add("Entity"),n.add("Person"),n.add("Object")),Array.from(n)}updateDataInstance(n){try{console.log("Data instance updated:",n);}catch(c){console.error("Failed to update data instance:",c);}}updateExportVisibility(n){let c=this.controlsContainer?.querySelector(".export-section");c&&(c.style.display=n?"block":"none");}updateTypeSelector(){let n=this.controlsContainer?.querySelector(".atom-type-select");if(!n)return;for(;n.children.length>1;)n.removeChild(n.lastChild);this.getAvailableAtomTypes().forEach(e=>{let i=document.createElement("option");i.value=e,i.textContent=e,n.appendChild(i);}),this.customTypes.forEach(e=>{if(!Array.from(n.options).find(o=>o.value===e)){let o=document.createElement("option");o.value=e,o.textContent=e,n.appendChild(o);}});let s=document.createElement("option");s.value="Other...",s.textContent="Other...",n.appendChild(s);}updateSpecInfo(n="loaded",c){let s=this.controlsContainer?.querySelector(".spec-status"),e=this.controlsContainer?.querySelector(".type-list");if(!s||!e)return;if(s.className=`spec-status ${n}`,n==="error"){s.textContent=c||"Error loading spec",e.innerHTML="";return}let i=this.getAvailableAtomTypes();s.textContent=`Loaded: ${i.length} atom types available`,e.innerHTML=i.map(o=>`<span class="type-item">${o}</span>`).join("");}generateAtomId(n){if(!this.dataInstance)return `${n}-1`;let c=this.dataInstance.getAtoms(),s=new Set(c.map(o=>o.id)),e=1,i=`${n}-${e}`;for(;s.has(i);)e++,i=`${n}-${e}`;return i}async addAtomFromForm(n,c){if(!(!n||!c))try{console.log(`\u{1F535} Adding atom: ${c} (${n})`);let e={id:this.generateAtomId(n),type:n,label:c};this.dataInstance.addAtom(e),console.log(`\u2705 Atom added to data instance: ${e.label} (${e.id}:${e.type})`),this.refreshTypesFromDataInstance(),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("atom-added",{detail:{atom:e}})),console.log(`\u{1F389} Atom addition completed: ${e.label} (${e.id}:${e.type})`);}catch(s){console.error("\u274C Failed to add atom:",s);}}updateAtomPositions(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".atom-positions"),c=this.controlsContainer.querySelector(".arity-display"),s=this.controlsContainer.querySelector(".remove-position-btn");if(!n)return;c&&(c.textContent=this.relationAtomPositions.length.toString()),s&&(s.disabled=this.relationAtomPositions.length<=2),n.innerHTML="";let e=this.dataInstance.getAtoms();if(e.length===0){n.innerHTML='<div style="color: #666; font-size: 11px;">No atoms available</div>';return}this.relationAtomPositions.forEach((i,o)=>{let p=document.createElement("div");p.className="atom-position";let E=document.createElement("label");E.textContent=`Position ${o+1}:`;let b=document.createElement("select");b.dataset.position=o.toString();let y=document.createElement("option");y.value="",y.textContent="Select Atom",b.appendChild(y),e.forEach(m=>{let u=document.createElement("option");u.value=m.id,u.textContent=`${m.label} (${m.type})`,m.id===i&&(u.selected=true),b.appendChild(u);}),b.addEventListener("change",()=>{this.relationAtomPositions[o]=b.value,this.updateRelationButtonState();}),p.appendChild(E),p.appendChild(b),n.appendChild(p);});}updateRelationButtonState(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".relation-type-input"),c=this.controlsContainer.querySelector(".add-relation-btn"),e=this.relationAtomPositions.filter(o=>o.trim()!=="").length>=2,i=n?.value.trim();c&&(c.disabled=!e||!i);}async addRelationFromForm(){if(this.controlsContainer)try{let c=this.controlsContainer.querySelector(".relation-type-input").value.trim();if(!c)return;let s=this.relationAtomPositions.filter(p=>p.trim()!=="");if(s.length<2){console.warn("Need at least 2 atoms for a relation");return}console.log(`\u{1F517} Adding relation: ${c}(${s.join(", ")})`);let e=this.dataInstance.getAtoms(),i=s.map(p=>e.find(b=>b.id===p)?.type||"untyped"),o={atoms:s,types:i};this.dataInstance.addRelationTuple(c,o),console.log(`\u2705 Relation added to data instance: ${c}(${s.join(", ")})`),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("relation-added",{detail:{relationType:c,tuple:o}})),console.log(`\u{1F389} Relation addition completed: ${c}(${s.join(", ")})`);}catch(n){console.error("\u274C Failed to add relation:",n);}}exportDataAsJSON(){try{console.log("\u{1F4E4} Exporting data instance using reify()...");let n=this.dataInstance.reify(),c=typeof n=="string"?n:JSON.stringify(n,null,2),s=this.controlsContainer?.querySelector(".export-output");s&&(s.value=c),this.dispatchEvent(new CustomEvent("data-exported",{detail:{data:c,format:typeof n=="string"?"text":"json",reified:n}})),console.log("\u2705 Data exported using reify()");}catch(n){console.error("\u274C Failed to export data:",n);}}handleDataChangeUIUpdate(n=false){this.refreshTypesFromDataInstance(),this.updateDeletionSelects(),n&&this.updateAtomPositions();}async handleDataDeletionWithValidation(n=false){this.handleDataChangeUIUpdate(n),await this.enforceConstraintsAndRegenerate();}setDataInstance(n){console.log("\u{1F504} Setting new data instance"),this.dataInstance&&(this.dataInstanceEventHandlers.atomAdded&&this.dataInstance.removeEventListener("atomAdded",this.dataInstanceEventHandlers.atomAdded),this.dataInstanceEventHandlers.atomRemoved&&this.dataInstance.removeEventListener("atomRemoved",this.dataInstanceEventHandlers.atomRemoved),this.dataInstanceEventHandlers.relationTupleAdded&&this.dataInstance.removeEventListener("relationTupleAdded",this.dataInstanceEventHandlers.relationTupleAdded),this.dataInstanceEventHandlers.relationTupleRemoved&&this.dataInstance.removeEventListener("relationTupleRemoved",this.dataInstanceEventHandlers.relationTupleRemoved)),this.dataInstance=n,this.refreshTypesFromDataInstance(),this.dataInstanceEventHandlers.atomAdded=async()=>{console.log("\u{1F4CD} Atom added to instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(true),await this.enforceConstraintsAndRegenerate();},this.dataInstanceEventHandlers.relationTupleAdded=async()=>{console.log("\u{1F517} Relation added to instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(false),await this.enforceConstraintsAndRegenerate();},this.dataInstanceEventHandlers.atomRemoved=async()=>{console.log("\u{1F5D1}\uFE0F Atom removed from instance - updating UI and re-validating constraints"),await this.handleDataDeletionWithValidation(true);},this.dataInstanceEventHandlers.relationTupleRemoved=async()=>{console.log("\u{1F5D1}\uFE0F Relation tuple removed from instance - updating UI and re-validating constraints"),await this.handleDataDeletionWithValidation(false);},n.addEventListener("atomAdded",this.dataInstanceEventHandlers.atomAdded),n.addEventListener("relationTupleAdded",this.dataInstanceEventHandlers.relationTupleAdded),n.addEventListener("atomRemoved",this.dataInstanceEventHandlers.atomRemoved),n.addEventListener("relationTupleRemoved",this.dataInstanceEventHandlers.relationTupleRemoved),this.updateDeletionSelects(),this.updateAtomPositions(),console.log("\u2705 Data instance set successfully");}updateDeletionSelects(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".atom-delete-select"),c=this.controlsContainer.querySelector(".relation-delete-select");if(n){for(;n.children.length>1;)n.removeChild(n.lastChild);this.dataInstance.getAtoms().forEach(e=>{let i=document.createElement("option");i.value=e.id,i.textContent=`${e.label} (${e.type})`,n.appendChild(i);});}if(c){for(;c.children.length>1;)c.removeChild(c.lastChild);let s=this.dataInstance.getRelations(),e=0;s.forEach(i=>{i.tuples.forEach(o=>{let p=document.createElement("option");p.value=e.toString();let E=o.atoms.map(y=>{let m=this.dataInstance.getAtoms().find(u=>u.id===y);return m?m.label:y}),b=i.id||i.name||"relation";p.textContent=`${b}: ${E.join(" \u2192 ")}`,c.appendChild(p),e++;});});}}async deleteAtom(n){if(n)try{console.log(`\u{1F5D1}\uFE0F Deleting atom: ${n}`);let s=this.dataInstance.getAtoms().find(e=>e.id===n);if(!s){console.warn(`\u26A0\uFE0F Atom ${n} not found`);return}this.dataInstance.removeAtom(n),console.log(`\u2705 Atom removed from data instance: ${s.label} (${s.id})`),console.log(`\u{1F389} Atom deletion completed: ${s.label} (${s.id})`),this.dispatchEvent(new CustomEvent("atom-deleted",{detail:{atom:s}}));}catch(c){console.error("\u274C Failed to delete atom:",c);}}async deleteRelation(n){if(n)try{let c=parseInt(n,10);console.log(`\u{1F5D1}\uFE0F Deleting relation tuple at index: ${c}`);let s=this.dataInstance.getRelations(),e=0,i=null,o=null;for(let E of s){for(let b of E.tuples){if(e===c){i=E,o=b;break}e++;}if(i)break}if(!i||!o){console.warn(`\u26A0\uFE0F Relation tuple at index ${c} not found`);return}let p=i.id||i.name;console.log(`\u{1F5D1}\uFE0F Found tuple in relation "${p}": ${o.atoms.join(" \u2192 ")}`),this.dataInstance.removeRelationTuple(p,o),console.log(`\u2705 Relation tuple removed from data instance: ${p}: ${o.atoms.join(" \u2192 ")}`),console.log(`\u{1F389} Relation tuple deletion completed: ${p}: ${o.atoms.join(" \u2192 ")}`),this.dispatchEvent(new CustomEvent("relation-tuple-deleted",{detail:{relationId:p,tuple:o}}));}catch(c){console.error("\u274C Failed to delete relation tuple:",c);}}async clearAllItems(){try{console.log("\u{1F9F9} Clearing all atoms and relations...");let n=new exports.JSONDataInstance({atoms:[],relations:[],types:[]});this.setDataInstance(n),console.log("\u2705 All items cleared from data instance"),await this.enforceConstraintsAndRegenerate(),console.log("\u{1F389} Clear all completed"),this.dispatchEvent(new CustomEvent("all-items-cleared",{detail:{}}));}catch(n){console.error("\u274C Failed to clear all items:",n);}}getDataInstance(){return this.dataInstance}getCurrentConstraintError(){return this.currentConstraintError}hasConstraintErrors(){return this.currentConstraintError!==null}async setCnDSpec(n){this.setAttribute("cnd-spec",n),await this.parseCnDSpec(n);}getAvailableTypes(){return this.getAvailableAtomTypes()}};});var rB=Te((xg,Lv)=>{(function(){var t,r="4.17.23",n=200,c="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",e="Invalid `variable` option passed into `_.template`",i="__lodash_hash_undefined__",o=500,p="__lodash_placeholder__",E=1,b=2,y=4,m=1,u=2,l=1,a=2,h=4,d=8,g=16,_=32,S=64,v=128,T=256,G=512,q=30,j="...",B=800,J=16,w=1,$=2,z=3,tt=1/0,pt=9007199254740991,Z=17976931348623157e292,dt=NaN,gt=4294967295,bt=gt-1,mt=gt>>>1,St=[["ary",v],["bind",l],["bindKey",a],["curry",d],["curryRight",g],["flip",G],["partial",_],["partialRight",S],["rearg",T]],Zt="[object Arguments]",oe="[object Array]",te="[object AsyncFunction]",Se="[object Boolean]",ee="[object Date]",Jt="[object DOMException]",Et="[object Error]",ht="[object Function]",xt="[object GeneratorFunction]",Tt="[object Map]",Lt="[object Number]",Pt="[object Null]",Bt="[object Object]",re="[object Promise]",ce="[object Proxy]",Ht="[object RegExp]",Ae="[object Set]",kt="[object String]",jt="[object Symbol]",Kt="[object Undefined]",$t="[object WeakMap]",yt="[object WeakSet]",zt="[object ArrayBuffer]",Le="[object DataView]",ie="[object Float32Array]",gr="[object Float64Array]",wn="[object Int8Array]",ri="[object Int16Array]",Fn="[object Int32Array]",He="[object Uint8Array]",Ge="[object Uint8ClampedArray]",Xr="[object Uint16Array]",Gn="[object Uint32Array]",ti=/\b__p \+= '';/g,oi=/\b(__p \+=) '' \+/g,fi=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Mi=/&(?:amp|lt|gt|quot|#39);/g,Fi=/[&<>"']/g,ve=RegExp(Mi.source),Kr=RegExp(Fi.source),gn=/<%-([\s\S]+?)%>/g,Un=/<%([\s\S]+?)%>/g,Yn=/<%=([\s\S]+?)%>/g,$i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ri=/^\w*$/,ps=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,eo=/[\\^$.*+?()[\]{}|]/g,Wi=RegExp(eo.source),ki=/^\s+/,ks=/\s/,_a=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Mo=/\{\n\/\* \[wrapped with (.+)\] \*/,gu=/,? & /,Ml=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ou=/[()=,{}\[\]\/\s]/,Ta=/\\(\\)?/g,ko=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ju=/\w*$/,yu=/^[-+]0x[0-9a-f]+$/i,vl=/^0b[01]+$/i,Va=/^\[object .+?Constructor\]$/,Ro=/^0o[0-7]+$/i,wo=/^(?:0|[1-9]\d*)$/,au=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Pu=/($^)/,Zu=/['\n\r\u2028\u2029\\]/g,oo="\\ud800-\\udfff",uu="\\u0300-\\u036f",pn="\\ufe20-\\ufe2f",L="\\u20d0-\\u20ff",O=uu+pn+L,it="\\u2700-\\u27bf",Gt="a-z\\xdf-\\xf6\\xf8-\\xff",Jr="\\xac\\xb1\\xd7\\xf7",Wn="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",f="\\u2000-\\u206f",H=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",k="A-Z\\xc0-\\xd6\\xd8-\\xde",F="\\ufe0e\\ufe0f",W=Jr+Wn+f+H,P="['\u2019]",X="["+oo+"]",Q="["+W+"]",lt="["+O+"]",pe="\\d+",fe="["+it+"]",Mt="["+Gt+"]",Rt="[^"+oo+W+pe+it+Gt+k+"]",qt="\\ud83c[\\udffb-\\udfff]",we="(?:"+lt+"|"+qt+")",Ee="[^"+oo+"]",Pe="(?:\\ud83c[\\udde6-\\uddff]){2}",ge="[\\ud800-\\udbff][\\udc00-\\udfff]",se="["+k+"]",Br="\\u200d",Be="(?:"+Mt+"|"+Rt+")",en="(?:"+se+"|"+Rt+")",br="(?:"+P+"(?:d|ll|m|re|s|t|ve))?",sr="(?:"+P+"(?:D|LL|M|RE|S|T|VE))?",Ar=we+"?",nn="["+F+"]?",Tn="(?:"+Br+"(?:"+[Ee,Pe,ge].join("|")+")"+nn+Ar+")*",ei="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Ve="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",yn=nn+Ar+Tn,mn="(?:"+[fe,Pe,ge].join("|")+")"+yn,cn="(?:"+[Ee+lt+"?",lt,Pe,ge,X].join("|")+")",Ei=RegExp(P,"g"),_s=RegExp(lt,"g"),Qs=RegExp(qt+"(?="+qt+")|"+cn+yn,"g"),Ko=RegExp([se+"?"+Mt+"+"+br+"(?="+[Q,se,"$"].join("|")+")",en+"+"+sr+"(?="+[Q,se+Be,"$"].join("|")+")",se+"?"+Be+"+"+br,se+"+"+sr,Ve,ei,pe,mn].join("|"),"g"),Cs=RegExp("["+Br+oo+O+F+"]"),Gi=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,xs=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Ya=-1,ts={};ts[ie]=ts[gr]=ts[wn]=ts[ri]=ts[Fn]=ts[He]=ts[Ge]=ts[Xr]=ts[Gn]=true,ts[Zt]=ts[oe]=ts[zt]=ts[Se]=ts[Le]=ts[ee]=ts[Et]=ts[ht]=ts[Tt]=ts[Lt]=ts[Bt]=ts[Ht]=ts[Ae]=ts[kt]=ts[$t]=false;var Jn={};Jn[Zt]=Jn[oe]=Jn[zt]=Jn[Le]=Jn[Se]=Jn[ee]=Jn[ie]=Jn[gr]=Jn[wn]=Jn[ri]=Jn[Fn]=Jn[Tt]=Jn[Lt]=Jn[Bt]=Jn[Ht]=Jn[Ae]=Jn[kt]=Jn[jt]=Jn[He]=Jn[Ge]=Jn[Xr]=Jn[Gn]=true,Jn[Et]=Jn[ht]=Jn[$t]=false;var us={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},Xo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},La={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},tl={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},kl=parseFloat,ma=parseInt,Us=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,gs=typeof self=="object"&&self&&self.Object===Object&&self,$n=Us||gs||Function("return this")(),A0=typeof xg=="object"&&xg&&!xg.nodeType&&xg,Qc=A0&&typeof Lv=="object"&&Lv&&!Lv.nodeType&&Lv,Wt=Qc&&Qc.exports===A0,Yt=Wt&&Us.process,ue=(function(){try{var or=Qc&&Qc.require&&Qc.require("util").types;return or||Yt&&Yt.binding&&Yt.binding("util")}catch{}})(),Ce=ue&&ue.isArrayBuffer,me=ue&&ue.isDate,ae=ue&&ue.isMap,ke=ue&&ue.isRegExp,Ke=ue&&ue.isSet,Xe=ue&&ue.isTypedArray;function qi(or,rr,Rr){switch(Rr.length){case 0:return or.call(rr);case 1:return or.call(rr,Rr[0]);case 2:return or.call(rr,Rr[0],Rr[1]);case 3:return or.call(rr,Rr[0],Rr[1],Rr[2])}return or.apply(rr,Rr)}function ca(or,rr,Rr,wi){for(var os=-1,Vs=or==null?0:or.length;++os<Vs;){var vu=or[os];rr(wi,vu,Rr(vu),or);}return wi}function ha(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi&&rr(or[Rr],Rr,or)!==false;);return or}function Fo(or,rr){for(var Rr=or==null?0:or.length;Rr--&&rr(or[Rr],Rr,or)!==false;);return or}function be(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi;)if(!rr(or[Rr],Rr,or))return false;return true}function Ne(or,rr){for(var Rr=-1,wi=or==null?0:or.length,os=0,Vs=[];++Rr<wi;){var vu=or[Rr];rr(vu,Rr,or)&&(Vs[os++]=vu);}return Vs}function Oe(or,rr){var Rr=or==null?0:or.length;return !!Rr&&yr(or,rr,0)>-1}function $e(or,rr,Rr){for(var wi=-1,os=or==null?0:or.length;++wi<os;)if(Rr(rr,or[wi]))return true;return false}function De(or,rr){for(var Rr=-1,wi=or==null?0:or.length,os=Array(wi);++Rr<wi;)os[Rr]=rr(or[Rr],Rr,or);return os}function tr(or,rr){for(var Rr=-1,wi=rr.length,os=or.length;++Rr<wi;)or[os+Rr]=rr[Rr];return or}function dr(or,rr,Rr,wi){var os=-1,Vs=or==null?0:or.length;for(wi&&Vs&&(Rr=or[++os]);++os<Vs;)Rr=rr(Rr,or[os],os,or);return Rr}function er(or,rr,Rr,wi){var os=or==null?0:or.length;for(wi&&os&&(Rr=or[--os]);os--;)Rr=rr(Rr,or[os],os,or);return Rr}function _r(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi;)if(rr(or[Rr],Rr,or))return true;return false}var jr=Vr("length");function Qr(or){return or.split("")}function Je(or){return or.match(Ml)||[]}function Tr(or,rr,Rr){var wi;return Rr(or,function(os,Vs,vu){if(rr(os,Vs,vu))return wi=Vs,false}),wi}function Or(or,rr,Rr,wi){for(var os=or.length,Vs=Rr+(wi?1:-1);wi?Vs--:++Vs<os;)if(rr(or[Vs],Vs,or))return Vs;return -1}function yr(or,rr,Rr){return rr===rr?Dc(or,rr,Rr):Or(or,Gr,Rr)}function $r(or,rr,Rr,wi){for(var os=Rr-1,Vs=or.length;++os<Vs;)if(wi(or[os],rr))return os;return -1}function Gr(or){return or!==or}function pr(or,rr){var Rr=or==null?0:or.length;return Rr?Cr(or,rr)/Rr:dt}function Vr(or){return function(rr){return rr==null?t:rr[or]}}function Yr(or){return function(rr){return or==null?t:or[rr]}}function qr(or,rr,Rr,wi,os){return os(or,function(Vs,vu,Ys){Rr=wi?(wi=false,Vs):rr(Rr,Vs,vu,Ys);}),Rr}function Wr(or,rr){var Rr=or.length;for(or.sort(rr);Rr--;)or[Rr]=or[Rr].value;return or}function Cr(or,rr){for(var Rr,wi=-1,os=or.length;++wi<os;){var Vs=rr(or[wi]);Vs!==t&&(Rr=Rr===t?Vs:Rr+Vs);}return Rr}function Pr(or,rr){for(var Rr=-1,wi=Array(or);++Rr<or;)wi[Rr]=rr(Rr);return wi}function Ir(or,rr){return De(rr,function(Rr){return [Rr,or[Rr]]})}function mr(or){return or&&or.slice(0,O0(or)+1).replace(ki,"")}function fr(or){return function(rr){return or(rr)}}function wr(or,rr){return De(rr,function(Rr){return or[Rr]})}function Sr(or,rr){return or.has(rr)}function vr(or,rr){for(var Rr=-1,wi=or.length;++Rr<wi&&yr(rr,or[Rr],0)>-1;);return Rr}function Mr(or,rr){for(var Rr=or.length;Rr--&&yr(rr,or[Rr],0)>-1;);return Rr}function lr(or,rr){for(var Rr=or.length,wi=0;Rr--;)or[Rr]===rr&&++wi;return wi}var Er=Yr(us),kr=Yr(Xo);function Dr(or){return "\\"+tl[or]}function Fr(or,rr){return or==null?t:or[rr]}function ir(or){return Cs.test(or)}function Zr(or){return Gi.test(or)}function tn(or){for(var rr,Rr=[];!(rr=or.next()).done;)Rr.push(rr.value);return Rr}function zr(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi,os){Rr[++rr]=[os,wi];}),Rr}function Ze(or,rr){return function(Rr){return or(rr(Rr))}}function We(or,rr){for(var Rr=-1,wi=or.length,os=0,Vs=[];++Rr<wi;){var vu=or[Rr];(vu===rr||vu===p)&&(or[Rr]=p,Vs[os++]=Rr);}return Vs}function Ic(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi){Rr[++rr]=wi;}),Rr}function Jc(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi){Rr[++rr]=[wi,wi];}),Rr}function Dc(or,rr,Rr){for(var wi=Rr-1,os=or.length;++wi<os;)if(or[wi]===rr)return wi;return -1}function tf(or,rr,Rr){for(var wi=Rr+1;wi--;)if(or[wi]===rr)return wi;return wi}function yo(or){return ir(or)?Lc(or):jr(or)}function ro(or){return ir(or)?Fd(or):Qr(or)}function O0(or){for(var rr=or.length;rr--&&ks.test(or.charAt(rr)););return rr}var vh=Yr(La);function Lc(or){for(var rr=Qs.lastIndex=0;Qs.test(or);)++rr;return rr}function Fd(or){return or.match(Qs)||[]}function sd(or){return or.match(Ko)||[]}var ef=(function or(rr){rr=rr==null?$n:Qo.defaults($n.Object(),rr,Qo.pick($n,xs));var Rr=rr.Array,wi=rr.Date,os=rr.Error,Vs=rr.Function,vu=rr.Math,Ys=rr.Object,ar=rr.RegExp,fn=rr.String,Ur=rr.TypeError,Ci=Rr.prototype,ls=Vs.prototype,At=Ys.prototype,$o=rr["__core-js_shared__"],Ks=ls.toString,Ns=At.hasOwnProperty,Ws=0,Jo=(function(){var R=/[^.]+$/.exec($o&&$o.keys&&$o.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""})(),Mu=At.toString,ic=Ks.call(Ys),ku=$n._,Ga=ar("^"+Ks.call(Ns).replace(eo,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Eu=Wt?rr.Buffer:t,$s=rr.Symbol,el=rr.Uint8Array,rf=Eu?Eu.allocUnsafe:t,sc=Ze(Ys.getPrototypeOf,Ys),Eh=Ys.create,Oi=At.propertyIsEnumerable,si=Ci.splice,hn=$s?$s.isConcatSpreadable:t,sn=$s?$s.iterator:t,An=$s?$s.toStringTag:t,Pc=(function(){try{var R=Ia(Ys,"defineProperty");return R({},"",{}),R}catch{}})(),On=rr.clearTimeout!==$n.clearTimeout&&rr.clearTimeout,kn=wi&&wi.now!==$n.Date.now&&wi.now,Bn=rr.setTimeout!==$n.setTimeout&&rr.setTimeout,ui=vu.ceil,ci=vu.floor,Hn=Ys.getOwnPropertySymbols,qn=Eu?Eu.isBuffer:t,_i=rr.isFinite,Bi=Ci.join,hi=Ze(Ys.keys,Ys),_n=vu.max,vn=vu.min,Kn=wi.now,Mn=rr.parseInt,ni=vu.random,Zn=Ci.reverse,Pn=Ia(rr,"DataView"),En=Ia(rr,"Map"),bn=Ia(rr,"Promise"),Nn=Ia(rr,"Set"),Ti=Ia(rr,"WeakMap"),pi=Ia(Ys,"create"),di=Ti&&new Ti,gi={},yi=sh(Pn),xi=sh(En),bi=sh(bn),Ni=sh(Nn),Si=sh(Ti),Xn=$s?$s.prototype:t,Ai=Xn?Xn.valueOf:t,oc=Xn?Xn.toString:t;function he(R){if(ul(R)&&!qs(R)&&!(R instanceof Gs)){if(R instanceof El)return R;if(Ns.call(R,"__wrapped__"))return qu(R)}return new El(R)}var Yl=(function(){function R(){}return function(U){if(!Wu(U))return {};if(Eh)return Eh(U);R.prototype=U;var at=new R;return R.prototype=t,at}})();function _h(){}function El(R,U){this.__wrapped__=R,this.__actions__=[],this.__chain__=!!U,this.__index__=0,this.__values__=t;}he.templateSettings={escape:gn,evaluate:Un,interpolate:Yn,variable:"",imports:{_:he}},he.prototype=_h.prototype,he.prototype.constructor=he,El.prototype=Yl(_h.prototype),El.prototype.constructor=El;function Gs(R){this.__wrapped__=R,this.__actions__=[],this.__dir__=1,this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=gt,this.__views__=[];}function Gh(){var R=new Gs(this.__wrapped__);return R.__actions__=jl(this.__actions__),R.__dir__=this.__dir__,R.__filtered__=this.__filtered__,R.__iteratees__=jl(this.__iteratees__),R.__takeCount__=this.__takeCount__,R.__views__=jl(this.__views__),R}function Pa(){if(this.__filtered__){var R=new Gs(this);R.__dir__=-1,R.__filtered__=true;}else R=this.clone(),R.__dir__*=-1;return R}function ac(){var R=this.__wrapped__.value(),U=this.__dir__,at=qs(R),Nt=U<0,Qt=at?R.length:0,ye=Qn(0,Qt,this.__views__),Ue=ye.start,Qe=ye.end,C=Qe-Ue,M=Nt?Qe:Ue-1,nt=this.__iteratees__,vt=nt.length,Ft=0,ne=vn(C,this.__takeCount__);if(!at||!Nt&&Qt==C&&ne==C)return fd(R,this.__actions__);var Re=[];t:for(;C--&&Ft<ne;){M+=U;for(var je=-1,Ye=R[M];++je<vt;){var on=nt[je],an=on.iteratee,Dn=on.type,li=an(Ye);if(Dn==$)Ye=li;else if(!li){if(Dn==w)continue t;break t}}Re[Ft++]=Ye;}return Re}Gs.prototype=Yl(_h.prototype),Gs.prototype.constructor=Gs;function le(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function ys(){this.__data__=pi?pi(null):{},this.size=0;}function S0(R){var U=this.has(R)&&delete this.__data__[R];return this.size-=U?1:0,U}function sa(R){var U=this.__data__;if(pi){var at=U[R];return at===i?t:at}return Ns.call(U,R)?U[R]:t}function Rs(R){var U=this.__data__;return pi?U[R]!==t:Ns.call(U,R)}function ba(R,U){var at=this.__data__;return this.size+=this.has(R)?0:1,at[R]=pi&&U===t?i:U,this}le.prototype.clear=ys,le.prototype.delete=S0,le.prototype.get=sa,le.prototype.has=Rs,le.prototype.set=ba;function ho(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function qh(){this.__data__=[],this.size=0;}function _u(R){var U=this.__data__,at=bu(U,R);if(at<0)return false;var Nt=U.length-1;return at==Nt?U.pop():si.call(U,at,1),--this.size,true}function od(R){var U=this.__data__,at=bu(U,R);return at<0?t:U[at][1]}function C0(R){return bu(this.__data__,R)>-1}function ws(R,U){var at=this.__data__,Nt=bu(at,R);return Nt<0?(++this.size,at.push([R,U])):at[Nt][1]=U,this}ho.prototype.clear=qh,ho.prototype.delete=_u,ho.prototype.get=od,ho.prototype.has=C0,ho.prototype.set=ws;function Wa(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function ad(){this.size=0,this.__data__={hash:new le,map:new(En||ho),string:new le};}function Aa(R){var U=$c(this,R).delete(R);return this.size-=U?1:0,U}function _l(R){return $c(this,R).get(R)}function nf(R){return $c(this,R).has(R)}function wf(R,U){var at=$c(this,R),Nt=at.size;return at.set(R,U),this.size+=at.size==Nt?0:1,this}Wa.prototype.clear=ad,Wa.prototype.delete=Aa,Wa.prototype.get=_l,Wa.prototype.has=nf,Wa.prototype.set=wf;function uc(R){var U=-1,at=R==null?0:R.length;for(this.__data__=new Wa;++U<at;)this.add(R[U]);}function Bd(R){return this.__data__.set(R,i),this}function Mc(R){return this.__data__.has(R)}uc.prototype.add=uc.prototype.push=Bd,uc.prototype.has=Mc;function lc(R){var U=this.__data__=new ho(R);this.size=U.size;}function Th(){this.__data__=new ho,this.size=0;}function Fu(R){var U=this.__data__,at=U.delete(R);return this.size=U.size,at}function Xa(R){return this.__data__.get(R)}function Fl(R){return this.__data__.has(R)}function Zo(R,U){var at=this.__data__;if(at instanceof ho){var Nt=at.__data__;if(!En||Nt.length<n-1)return Nt.push([R,U]),this.size=++at.size,this;at=this.__data__=new Wa(Nt);}return at.set(R,U),this.size=at.size,this}lc.prototype.clear=Th,lc.prototype.delete=Fu,lc.prototype.get=Xa,lc.prototype.has=Fl,lc.prototype.set=Zo;function Qa(R,U){var at=qs(R),Nt=!at&&b1(R),Qt=!at&&!Nt&&qf(R),ye=!at&&!Nt&&!Qt&&zd(R),Ue=at||Nt||Qt||ye,Qe=Ue?Pr(R.length,fn):[],C=Qe.length;for(var M in R)(U||Ns.call(R,M))&&!(Ue&&(M=="length"||Qt&&(M=="offset"||M=="parent")||ye&&(M=="buffer"||M=="byteLength"||M=="byteOffset")||rh(M,C)))&&Qe.push(M);return Qe}function rl(R){var U=R.length;return U?R[sf(0,U-1)]:t}function Ho(R,U){return F0(jl(R),da(U,0,R.length))}function cl(R){return F0(jl(R))}function Tu(R,U,at){(at!==t&&!uh(R[U],at)||at===t&&!(U in R))&&Bo(R,U,at);}function Ma(R,U,at){var Nt=R[U];(!(Ns.call(R,U)&&uh(Nt,at))||at===t&&!(U in R))&&Bo(R,U,at);}function bu(R,U){for(var at=R.length;at--;)if(uh(R[at][0],U))return at;return -1}function ta(R,U,at,Nt){return vo(R,function(Qt,ye,Ue){U(Nt,Qt,at(Qt),Ue);}),Nt}function fa(R,U){return R&&Zc(U,Hl(U),R)}function Au(R,U){return R&&Zc(U,Fh(U),R)}function Bo(R,U,at){U=="__proto__"&&Pc?Pc(R,U,{configurable:true,enumerable:true,value:at,writable:true}):R[U]=at;}function Bu(R,U){for(var at=-1,Nt=U.length,Qt=Rr(Nt),ye=R==null;++at<Nt;)Qt[at]=ye?t:Y1(R,U[at]);return Qt}function da(R,U,at){return R===R&&(at!==t&&(R=R<=at?R:at),U!==t&&(R=R>=U?R:U)),R}function no(R,U,at,Nt,Qt,ye){var Ue,Qe=U&E,C=U&b,M=U&y;if(at&&(Ue=Qt?at(R,Nt,Qt,ye):at(R)),Ue!==t)return Ue;if(!Wu(R))return R;var nt=qs(R);if(nt){if(Ue=t0(R),!Qe)return jl(R,Ue)}else {var vt=Eo(R),Ft=vt==ht||vt==xt;if(qf(R))return hl(R,Qe);if(vt==Bt||vt==Zt||Ft&&!Qt){if(Ue=C||Ft?{}:Oo(R),!Qe)return C?pc(R,Au(Ue,R)):kf(R,fa(Ue,R))}else {if(!Jn[vt])return Qt?R:{};Ue=Bf(R,vt,Qe);}}ye||(ye=new lc);var ne=ye.get(R);if(ne)return ne;ye.set(R,Ue),J3(R)?R.forEach(function(Ye){Ue.add(no(Ye,U,at,Ye,R,ye));}):X3(R)&&R.forEach(function(Ye,on){Ue.set(on,no(Ye,U,at,on,R,ye));});var Re=M?C?Fs:Ls:C?Fh:Hl,je=nt?t:Re(R);return ha(je||R,function(Ye,on){je&&(on=Ye,Ye=R[on]),Ma(Ue,on,no(Ye,U,at,on,R,ye));}),Ue}function oa(R){var U=Hl(R);return function(at){return Ou(at,R,U)}}function Ou(R,U,at){var Nt=at.length;if(R==null)return !Nt;for(R=Ys(R);Nt--;){var Qt=at[Nt],ye=U[Qt],Ue=R[Qt];if(Ue===t&&!(Qt in R)||!ye(Ue))return false}return true}function ju(R,U,at){if(typeof R!="function")throw new Ur(s);return Ih(function(){R.apply(t,at);},U)}function Ja(R,U,at,Nt){var Qt=-1,ye=Oe,Ue=true,Qe=R.length,C=[],M=U.length;if(!Qe)return C;at&&(U=De(U,fr(at))),Nt?(ye=$e,Ue=false):U.length>=n&&(ye=Sr,Ue=false,U=new uc(U));t:for(;++Qt<Qe;){var nt=R[Qt],vt=at==null?nt:at(nt);if(nt=Nt||nt!==0?nt:0,Ue&&vt===vt){for(var Ft=M;Ft--;)if(U[Ft]===vt)continue t;C.push(nt);}else ye(U,vt,Nt)||C.push(nt);}return C}var vo=Rh(Sa),Su=Rh(lu,true);function aa(R,U){var at=true;return vo(R,function(Nt,Qt,ye){return at=!!U(Nt,Qt,ye),at}),at}function jo(R,U,at){for(var Nt=-1,Qt=R.length;++Nt<Qt;){var ye=R[Nt],Ue=U(ye);if(Ue!=null&&(Qe===t?Ue===Ue&&!o0(Ue):at(Ue,Qe)))var Qe=Ue,C=ye;}return C}function nl(R,U,at,Nt){var Qt=R.length;for(at=js(at),at<0&&(at=-at>Qt?0:Qt+at),Nt=Nt===t||Nt>Qt?Qt:js(Nt),Nt<0&&(Nt+=Qt),Nt=at>Nt?0:zf(Nt);at<Nt;)R[at++]=U;return R}function il(R,U){var at=[];return vo(R,function(Nt,Qt,ye){U(Nt,Qt,ye)&&at.push(Nt);}),at}function io(R,U,at,Nt,Qt){var ye=-1,Ue=R.length;for(at||(at=tu),Qt||(Qt=[]);++ye<Ue;){var Qe=R[ye];U>0&&at(Qe)?U>1?io(Qe,U-1,at,Nt,Qt):tr(Qt,Qe):Nt||(Qt[Qt.length]=Qe);}return Qt}var ka=D0(),Oa=D0(true);function Sa(R,U){return R&&ka(R,U,Hl)}function lu(R,U){return R&&Oa(R,U,Hl)}function Io(R,U){return Ne(U,function(at){return bc(R[at])})}function qa(R,U){U=Bl(U,R);for(var at=0,Nt=U.length;R!=null&&at<Nt;)R=R[Ql(U[at++])];return at&&at==Nt?R:t}function sl(R,U,at){var Nt=U(R);return qs(R)?Nt:tr(Nt,at(R))}function Is(R){return R==null?R===t?Kt:Pt:An&&An in Ys(R)?Gu(R):Kf(R)}function cu(R,U){return R>U}function ga(R,U){return R!=null&&Ns.call(R,U)}function pa(R,U){return R!=null&&U in Ys(R)}function hu(R,U,at){return R>=vn(U,at)&&R<_n(U,at)}function Ca(R,U,at){for(var Nt=at?$e:Oe,Qt=R[0].length,ye=R.length,Ue=ye,Qe=Rr(ye),C=1/0,M=[];Ue--;){var nt=R[Ue];Ue&&U&&(nt=De(nt,fr(U))),C=vn(nt.length,C),Qe[Ue]=!at&&(U||Qt>=120&&nt.length>=120)?new uc(Ue&&nt):t;}nt=R[0];var vt=-1,Ft=Qe[0];t:for(;++vt<Qt&&M.length<C;){var ne=nt[vt],Re=U?U(ne):ne;if(ne=at||ne!==0?ne:0,!(Ft?Sr(Ft,Re):Nt(M,Re,at))){for(Ue=ye;--Ue;){var je=Qe[Ue];if(!(je?Sr(je,Re):Nt(R[Ue],Re,at)))continue t}Ft&&Ft.push(Re),M.push(ne);}}return M}function Na(R,U,at,Nt){return Sa(R,function(Qt,ye,Ue){U(Nt,at(Qt),ye,Ue);}),Nt}function Go(R,U,at){U=Bl(U,R),R=vc(R,U);var Nt=R==null?R:R[Ql(Nl(U))];return Nt==null?t:qi(Nt,R,at)}function vi(R){return ul(R)&&Is(R)==Zt}function Wl(R){return ul(R)&&Is(R)==zt}function ud(R){return ul(R)&&Is(R)==ee}function cs(R,U,at,Nt,Qt){return R===U?true:R==null||U==null||!ul(R)&&!ul(U)?R!==R&&U!==U:Uu(R,U,at,Nt,cs,Qt)}function Uu(R,U,at,Nt,Qt,ye){var Ue=qs(R),Qe=qs(U),C=Ue?oe:Eo(R),M=Qe?oe:Eo(U);C=C==Zt?Bt:C,M=M==Zt?Bt:M;var nt=C==Bt,vt=M==Bt,Ft=C==M;if(Ft&&qf(R)){if(!qf(U))return false;Ue=true,nt=false;}if(Ft&&!nt)return ye||(ye=new lc),Ue||zd(R)?Ol(R,U,at,Nt,Qt,ye):cf(R,U,C,at,Nt,Qt,ye);if(!(at&m)){var ne=nt&&Ns.call(R,"__wrapped__"),Re=vt&&Ns.call(U,"__wrapped__");if(ne||Re){var je=ne?R.value():R,Ye=Re?U.value():U;return ye||(ye=new lc),Qt(je,Ye,at,Nt,ye)}}return Ft?(ye||(ye=new lc),Kc(R,U,at,Nt,Qt,ye)):false}function If(R){return ul(R)&&Eo(R)==Tt}function ii(R,U,at,Nt){var Qt=at.length,ye=Qt,Ue=!Nt;if(R==null)return !ye;for(R=Ys(R);Qt--;){var Qe=at[Qt];if(Ue&&Qe[2]?Qe[1]!==R[Qe[0]]:!(Qe[0]in R))return false}for(;++Qt<ye;){Qe=at[Qt];var C=Qe[0],M=R[C],nt=Qe[1];if(Ue&&Qe[2]){if(M===t&&!(C in R))return false}else {var vt=new lc;if(Nt)var Ft=Nt(M,nt,C,R,U,vt);if(!(Ft===t?cs(nt,M,m|u,Nt,vt):Ft))return false}}return true}function zh(R){if(!Wu(R)||Nu(R))return false;var U=bc(R)?Ga:Va;return U.test(sh(R))}function Df(R){return ul(R)&&Is(R)==Ht}function l1(R){return ul(R)&&Eo(R)==Ae}function fo(R){return ul(R)&&H1(R.length)&&!!ts[Is(R)]}function ea(R){return typeof R=="function"?R:R==null?na:typeof R=="object"?qs(R)?cd(R[0],R[1]):ld(R):$x(R)}function cc(R){if(!Uf(R))return hi(R);var U=[];for(var at in Ys(R))Ns.call(R,at)&&at!="constructor"&&U.push(at);return U}function hc(R){if(!Wu(R))return k0(R);var U=Uf(R),at=[];for(var Nt in R)Nt=="constructor"&&(U||!Ns.call(R,Nt))||at.push(Nt);return at}function Vh(R,U){return R<U}function Yh(R,U){var at=-1,Nt=Tc(R)?Rr(R.length):[];return vo(R,function(Qt,ye,Ue){Nt[++at]=U(Qt,ye,Ue);}),Nt}function ld(R){var U=Ka(R);return U.length==1&&U[0][2]?Zs(U[0][0],U[0][1]):function(at){return at===R||ii(at,R,U)}}function cd(R,U){return jf(R)&&al(U)?Zs(Ql(R),U):function(at){var Nt=Y1(at,R);return Nt===t&&Nt===U?Ix(at,R):cs(U,Nt,m|u)}}function N0(R,U,at,Nt,Qt){R!==U&&ka(U,function(ye,Ue){if(Qt||(Qt=new lc),Wu(ye))jd(R,U,Ue,at,N0,Nt,Qt);else {var Qe=Nt?Nt(nh(R,Ue),ye,Ue+"",R,U,Qt):t;Qe===t&&(Qe=ye),Tu(R,Ue,Qe);}},Fh);}function jd(R,U,at,Nt,Qt,ye,Ue){var Qe=nh(R,at),C=nh(U,at),M=Ue.get(C);if(M){Tu(R,at,M);return}var nt=ye?ye(Qe,C,at+"",R,U,Ue):t,vt=nt===t;if(vt){var Ft=qs(C),ne=!Ft&&qf(C),Re=!Ft&&!ne&&zd(C);nt=C,Ft||ne||Re?qs(Qe)?nt=Qe:Vu(Qe)?nt=jl(Qe):ne?(vt=false,nt=hl(C,true)):Re?(vt=false,nt=Al(C,true)):nt=[]:G1(C)||b1(C)?(nt=Qe,b1(Qe)?nt=Ax(Qe):(!Wu(Qe)||bc(Qe))&&(nt=Oo(C))):vt=false;}vt&&(Ue.set(C,nt),Qt(nt,C,Nt,ye,Ue),Ue.delete(C)),Tu(R,at,nt);}function bh(R,U){var at=R.length;if(at)return U+=U<0?at:0,rh(U,at)?R[U]:t}function Xl(R,U,at){U.length?U=De(U,function(ye){return qs(ye)?function(Ue){return qa(Ue,ye.length===1?ye[0]:ye)}:ye}):U=[na];var Nt=-1;U=De(U,fr(zi()));var Qt=Yh(R,function(ye,Ue,Qe){var C=De(U,function(M){return M(ye)});return {criteria:C,index:++Nt,value:ye}});return Wr(Qt,function(ye,Ue){return ns(ye,Ue,at)})}function Wh(R,U){return R0(R,U,function(at,Nt){return Ix(R,Nt)})}function R0(R,U,at){for(var Nt=-1,Qt=U.length,ye={};++Nt<Qt;){var Ue=U[Nt],Qe=qa(R,Ue);at(Qe,Ue)&&Ao(ye,Bl(Ue,R),Qe);}return ye}function fc(R){return function(U){return qa(U,R)}}function w0(R,U,at,Nt){var Qt=Nt?$r:yr,ye=-1,Ue=U.length,Qe=R;for(R===U&&(U=jl(U)),at&&(Qe=De(R,fr(at)));++ye<Ue;)for(var C=0,M=U[ye],nt=at?at(M):M;(C=Qt(Qe,nt,C,Nt))>-1;)Qe!==R&&si.call(Qe,C,1),si.call(R,C,1);return R}function Ah(R,U){for(var at=R?U.length:0,Nt=at-1;at--;){var Qt=U[at];if(at==Nt||Qt!==ye){var ye=Qt;rh(Qt)?si.call(R,Qt,1):bl(R,Qt);}}return R}function sf(R,U){return R+ci(ni()*(U-R+1))}function Lf(R,U,at,Nt){for(var Qt=-1,ye=_n(ui((U-R)/(at||1)),0),Ue=Rr(ye);ye--;)Ue[Nt?ye:++Qt]=R,R+=at;return Ue}function Fa(R,U){var at="";if(!R||U<1||U>pt)return at;do U%2&&(at+=R),U=ci(U/2),U&&(R+=R);while(U);return at}function Yi(R,U){return ih(e0(R,U,na),R+"")}function Ku(R){return rl(nu(R))}function Ra(R,U){var at=nu(R);return F0(at,da(U,0,at.length))}function Ao(R,U,at,Nt){if(!Wu(R))return R;U=Bl(U,R);for(var Qt=-1,ye=U.length,Ue=ye-1,Qe=R;Qe!=null&&++Qt<ye;){var C=Ql(U[Qt]),M=at;if(C==="__proto__"||C==="constructor"||C==="prototype")return R;if(Qt!=Ue){var nt=Qe[C];M=Nt?Nt(nt,C,Qe):t,M===t&&(M=Wu(nt)?nt:rh(U[Qt+1])?[]:{});}Ma(Qe,C,M),Qe=Qe[C];}return R}var dc=di?function(R,U){return di.set(R,U),R}:na,hd=Pc?function(R,U){return Pc(R,"toString",{configurable:true,enumerable:false,value:X1(U),writable:true})}:na;function qo(R){return F0(nu(R))}function Tl(R,U,at){var Nt=-1,Qt=R.length;U<0&&(U=-U>Qt?0:Qt+U),at=at>Qt?Qt:at,at<0&&(at+=Qt),Qt=U>at?0:at-U>>>0,U>>>=0;for(var ye=Rr(Qt);++Nt<Qt;)ye[Nt]=R[Nt+U];return ye}function Ds(R,U){var at;return vo(R,function(Nt,Qt,ye){return at=U(Nt,Qt,ye),!at}),!!at}function Oh(R,U,at){var Nt=0,Qt=R==null?Nt:R.length;if(typeof U=="number"&&U===U&&Qt<=mt){for(;Nt<Qt;){var ye=Nt+Qt>>>1,Ue=R[ye];Ue!==null&&!o0(Ue)&&(at?Ue<=U:Ue<U)?Nt=ye+1:Qt=ye;}return Qt}return Pf(R,U,na,at)}function Pf(R,U,at,Nt){var Qt=0,ye=R==null?0:R.length;if(ye===0)return 0;U=at(U);for(var Ue=U!==U,Qe=U===null,C=o0(U),M=U===t;Qt<ye;){var nt=ci((Qt+ye)/2),vt=at(R[nt]),Ft=vt!==t,ne=vt===null,Re=vt===vt,je=o0(vt);if(Ue)var Ye=Nt||Re;else M?Ye=Re&&(Nt||Ft):Qe?Ye=Re&&Ft&&(Nt||!ne):C?Ye=Re&&Ft&&!ne&&(Nt||!je):ne||je?Ye=false:Ye=Nt?vt<=U:vt<U;Ye?Qt=nt+1:ye=nt;}return vn(ye,bt)}function I0(R,U){for(var at=-1,Nt=R.length,Qt=0,ye=[];++at<Nt;){var Ue=R[at],Qe=U?U(Ue):Ue;if(!at||!uh(Qe,C)){var C=Qe;ye[Qt++]=Ue===0?0:Ue;}}return ye}function Ud(R){return typeof R=="number"?R:o0(R)?dt:+R}function wa(R){if(typeof R=="string")return R;if(qs(R))return De(R,wa)+"";if(o0(R))return oc?oc.call(R):"";var U=R+"";return U=="0"&&1/R==-tt?"-0":U}function Sh(R,U,at){var Nt=-1,Qt=Oe,ye=R.length,Ue=true,Qe=[],C=Qe;if(at)Ue=false,Qt=$e;else if(ye>=n){var M=U?null:md(R);if(M)return Ic(M);Ue=false,Qt=Sr,C=new uc;}else C=U?[]:Qe;t:for(;++Nt<ye;){var nt=R[Nt],vt=U?U(nt):nt;if(nt=at||nt!==0?nt:0,Ue&&vt===vt){for(var Ft=C.length;Ft--;)if(C[Ft]===vt)continue t;U&&C.push(vt),Qe.push(nt);}else Qt(C,vt,at)||(C!==Qe&&C.push(vt),Qe.push(nt));}return Qe}function bl(R,U){U=Bl(U,R);var at=-1,Nt=U.length;if(!Nt)return true;for(var Qt=R==null||typeof R!="object"&&typeof R!="function";++at<Nt;){var ye=U[at];if(typeof ye=="string"){if(ye==="__proto__"&&!Ns.call(R,"__proto__"))return false;if(ye==="constructor"&&at+1<Nt&&typeof U[at+1]=="string"&&U[at+1]==="prototype"){if(Qt&&at===0)continue;return false}}}var Ue=vc(R,U);return Ue==null||delete Ue[Ql(Nl(U))]}function kc(R,U,at,Nt){return Ao(R,U,at(qa(R,U)),Nt)}function Ch(R,U,at,Nt){for(var Qt=R.length,ye=Nt?Qt:-1;(Nt?ye--:++ye<Qt)&&U(R[ye],ye,R););return at?Tl(R,Nt?0:ye,Nt?ye+1:Qt):Tl(R,Nt?ye+1:0,Nt?Qt:ye)}function fd(R,U){var at=R;return at instanceof Gs&&(at=at.value()),dr(U,function(Nt,Qt){return Qt.func.apply(Qt.thisArg,tr([Nt],Qt.args))},at)}function Fc(R,U,at){var Nt=R.length;if(Nt<2)return Nt?Sh(R[0]):[];for(var Qt=-1,ye=Rr(Nt);++Qt<Nt;)for(var Ue=R[Qt],Qe=-1;++Qe<Nt;)Qe!=Qt&&(ye[Qt]=Ja(ye[Qt]||Ue,R[Qe],U,at));return Sh(io(ye,1),U,at)}function Xh(R,U,at){for(var Nt=-1,Qt=R.length,ye=U.length,Ue={};++Nt<Qt;){var Qe=Nt<ye?U[Nt]:t;at(Ue,R[Nt],Qe);}return Ue}function Ba(R){return Vu(R)?R:[]}function $u(R){return typeof R=="function"?R:na}function Bl(R,U){return qs(R)?R:jf(R,U)?[R]:$d(ya(R))}var c1=Yi;function Bc(R,U,at){var Nt=R.length;return at=at===t?Nt:at,!U&&at>=Nt?R:Tl(R,U,at)}var Kd=On||function(R){return $n.clearTimeout(R)};function hl(R,U){if(U)return R.slice();var at=R.length,Nt=rf?rf(at):new R.constructor(at);return R.copy(Nt),Nt}function dd(R){var U=new R.constructor(R.byteLength);return new el(U).set(new el(R)),U}function Mf(R,U){var at=U?dd(R.buffer):R.buffer;return new R.constructor(at,R.byteOffset,R.byteLength)}function of(R){var U=new R.constructor(R.source,Ju.exec(R));return U.lastIndex=R.lastIndex,U}function Za(R){return Ai?Ys(Ai.call(R)):{}}function Al(R,U){var at=U?dd(R.buffer):R.buffer;return new R.constructor(at,R.byteOffset,R.length)}function ja(R,U){if(R!==U){var at=R!==t,Nt=R===null,Qt=R===R,ye=o0(R),Ue=U!==t,Qe=U===null,C=U===U,M=o0(U);if(!Qe&&!M&&!ye&&R>U||ye&&Ue&&C&&!Qe&&!M||Nt&&Ue&&C||!at&&C||!Qt)return 1;if(!Nt&&!ye&&!M&&R<U||M&&at&&Qt&&!Nt&&!ye||Qe&&at&&Qt||!Ue&&Qt||!C)return -1}return 0}function ns(R,U,at){for(var Nt=-1,Qt=R.criteria,ye=U.criteria,Ue=Qt.length,Qe=at.length;++Nt<Ue;){var C=ja(Qt[Nt],ye[Nt]);if(C){if(Nt>=Qe)return C;var M=at[Nt];return C*(M=="desc"?-1:1)}}return R.index-U.index}function Qh(R,U,at,Nt){for(var Qt=-1,ye=R.length,Ue=at.length,Qe=-1,C=U.length,M=_n(ye-Ue,0),nt=Rr(C+M),vt=!Nt;++Qe<C;)nt[Qe]=U[Qe];for(;++Qt<Ue;)(vt||Qt<ye)&&(nt[at[Qt]]=R[Qt]);for(;M--;)nt[Qe++]=R[Qt++];return nt}function Nh(R,U,at,Nt){for(var Qt=-1,ye=R.length,Ue=-1,Qe=at.length,C=-1,M=U.length,nt=_n(ye-Qe,0),vt=Rr(nt+M),Ft=!Nt;++Qt<nt;)vt[Qt]=R[Qt];for(var ne=Qt;++C<M;)vt[ne+C]=U[C];for(;++Ue<Qe;)(Ft||Qt<ye)&&(vt[ne+at[Ue]]=R[Qt++]);return vt}function jl(R,U){var at=-1,Nt=R.length;for(U||(U=Rr(Nt));++at<Nt;)U[at]=R[at];return U}function Zc(R,U,at,Nt){var Qt=!at;at||(at={});for(var ye=-1,Ue=U.length;++ye<Ue;){var Qe=U[ye],C=Nt?Nt(at[Qe],R[Qe],Qe,at,R):t;C===t&&(C=R[Qe]),Qt?Bo(at,Qe,C):Ma(at,Qe,C);}return at}function kf(R,U){return Zc(R,Zh(R),U)}function pc(R,U){return Zc(R,Hc(R),U)}function xc(R,U){return function(at,Nt){var Qt=qs(at)?ca:ta,ye=U?U():{};return Qt(at,R,zi(Nt,2),ye)}}function mc(R){return Yi(function(U,at){var Nt=-1,Qt=at.length,ye=Qt>1?at[Qt-1]:t,Ue=Qt>2?at[2]:t;for(ye=R.length>3&&typeof ye=="function"?(Qt--,ye):t,Ue&&Cu(at[0],at[1],Ue)&&(ye=Qt<3?t:ye,Qt=1),U=Ys(U);++Nt<Qt;){var Qe=at[Nt];Qe&&R(U,Qe,Nt,ye);}return U})}function Rh(R,U){return function(at,Nt){if(at==null)return at;if(!Tc(at))return R(at,Nt);for(var Qt=at.length,ye=U?Qt:-1,Ue=Ys(at);(U?ye--:++ye<Qt)&&Nt(Ue[ye],ye,Ue)!==false;);return at}}function D0(R){return function(U,at,Nt){for(var Qt=-1,ye=Ys(U),Ue=Nt(U),Qe=Ue.length;Qe--;){var C=Ue[R?Qe:++Qt];if(at(ye[C],C,ye)===false)break}return U}}function fl(R,U,at){var Nt=U&l,Qt=af(R);function ye(){var Ue=this&&this!==$n&&this instanceof ye?Qt:R;return Ue.apply(Nt?at:this,arguments)}return ye}function Ul(R){return function(U){U=ya(U);var at=ir(U)?ro(U):t,Nt=at?at[0]:U.charAt(0),Qt=at?Bc(at,1).join(""):U.slice(1);return Nt[R]()+Qt}}function L0(R){return function(U){return dr(S1(Yf(U).replace(Ei,"")),R,"")}}function af(R){return function(){var U=arguments;switch(U.length){case 0:return new R;case 1:return new R(U[0]);case 2:return new R(U[0],U[1]);case 3:return new R(U[0],U[1],U[2]);case 4:return new R(U[0],U[1],U[2],U[3]);case 5:return new R(U[0],U[1],U[2],U[3],U[4]);case 6:return new R(U[0],U[1],U[2],U[3],U[4],U[5]);case 7:return new R(U[0],U[1],U[2],U[3],U[4],U[5],U[6])}var at=Yl(R.prototype),Nt=R.apply(at,U);return Wu(Nt)?Nt:at}}function pd(R,U,at){var Nt=af(R);function Qt(){for(var ye=arguments.length,Ue=Rr(ye),Qe=ye,C=Ua(Qt);Qe--;)Ue[Qe]=arguments[Qe];var M=ye<3&&Ue[0]!==C&&Ue[ye-1]!==C?[]:We(Ue,C);if(ye-=M.length,ye<at)return yc(R,U,th,Qt.placeholder,t,Ue,M,t,t,at-ye);var nt=this&&this!==$n&&this instanceof Qt?Nt:R;return qi(nt,this,Ue)}return Qt}function gc(R){return function(U,at,Nt){var Qt=Ys(U);if(!Tc(U)){var ye=zi(at,3);U=Hl(U),at=function(Qe){return ye(Qt[Qe],Qe,Qt)};}var Ue=R(U,at,Nt);return Ue>-1?Qt[ye?U[Ue]:Ue]:t}}function uf(R){return ao(function(U){var at=U.length,Nt=at,Qt=El.prototype.thru;for(R&&U.reverse();Nt--;){var ye=U[Nt];if(typeof ye!="function")throw new Ur(s);if(Qt&&!Ue&&eh(ye)=="wrapper")var Ue=new El([],true);}for(Nt=Ue?Nt:at;++Nt<at;){ye=U[Nt];var Qe=eh(ye),C=Qe=="wrapper"?hf(ye):t;C&&wh(C[0])&&C[1]==(v|d|_|T)&&!C[4].length&&C[9]==1?Ue=Ue[eh(C[0])].apply(Ue,C[3]):Ue=ye.length==1&&wh(ye)?Ue[Qe]():Ue.thru(ye);}return function(){var M=arguments,nt=M[0];if(Ue&&M.length==1&&qs(nt))return Ue.plant(nt).value();for(var vt=0,Ft=at?U[vt].apply(this,M):nt;++vt<at;)Ft=U[vt].call(this,Ft);return Ft}})}function th(R,U,at,Nt,Qt,ye,Ue,Qe,C,M){var nt=U&v,vt=U&l,Ft=U&a,ne=U&(d|g),Re=U&G,je=Ft?t:af(R);function Ye(){for(var on=arguments.length,an=Rr(on),Dn=on;Dn--;)an[Dn]=arguments[Dn];if(ne)var li=Ua(Ye),Ui=lr(an,li);if(Nt&&(an=Qh(an,Nt,Qt,ne)),ye&&(an=Nh(an,ye,Ue,ne)),on-=Ui,ne&&on<M){var Ki=We(an,li);return yc(R,U,th,Ye.placeholder,at,an,Ki,Qe,C,M-on)}var Ss=vt?at:this,es=Ft?Ss[R]:R;return on=an.length,Qe?an=r0(an,Qe):Re&&on>1&&an.reverse(),nt&&C<on&&(an.length=C),this&&this!==$n&&this instanceof Ye&&(es=je||af(es)),es.apply(Ss,an)}return Ye}function h1(R,U){return function(at,Nt){return Na(at,R,U(Nt),{})}}function Jh(R,U){return function(at,Nt){var Qt;if(at===t&&Nt===t)return U;if(at!==t&&(Qt=at),Nt!==t){if(Qt===t)return Nt;typeof at=="string"||typeof Nt=="string"?(at=wa(at),Nt=wa(Nt)):(at=Ud(at),Nt=Ud(Nt)),Qt=R(at,Nt);}return Qt}}function jc(R){return ao(function(U){return U=De(U,fr(zi())),Yi(function(at){var Nt=this;return R(U,function(Qt){return qi(Qt,Nt,at)})})})}function dl(R,U){U=U===t?" ":wa(U);var at=U.length;if(at<2)return at?Fa(U,R):U;var Nt=Fa(U,ui(R/yo(U)));return ir(U)?Bc(ro(Nt),0,R).join(""):Nt.slice(0,R)}function Uc(R,U,at,Nt){var Qt=U&l,ye=af(R);function Ue(){for(var Qe=-1,C=arguments.length,M=-1,nt=Nt.length,vt=Rr(nt+C),Ft=this&&this!==$n&&this instanceof Ue?ye:R;++M<nt;)vt[M]=Nt[M];for(;C--;)vt[M++]=arguments[++Qe];return qi(Ft,Qt?at:this,vt)}return Ue}function xd(R){return function(U,at,Nt){return Nt&&typeof Nt!="number"&&Cu(U,at,Nt)&&(at=Nt=t),U=Ru(U),at===t?(at=U,U=0):at=Ru(at),Nt=Nt===t?U<at?1:-1:Ru(Nt),Lf(U,at,Nt,R)}}function Ff(R){return function(U,at){return typeof U=="string"&&typeof at=="string"||(U=a0(U),at=a0(at)),R(U,at)}}function yc(R,U,at,Nt,Qt,ye,Ue,Qe,C,M){var nt=U&d,vt=nt?Ue:t,Ft=nt?t:Ue,ne=nt?ye:t,Re=nt?t:ye;U|=nt?_:S,U&=~(nt?S:_),U&h||(U&=-4);var je=[R,U,Qt,ne,vt,Re,Ft,Qe,C,M],Ye=at.apply(t,je);return wh(R)&&Ec(Ye,je),Ye.placeholder=Nt,Gc(Ye,R,U)}function Ts(R){var U=vu[R];return function(at,Nt){if(at=a0(at),Nt=Nt==null?0:vn(js(Nt),292),Nt&&_i(at)){var Qt=(ya(at)+"e").split("e"),ye=U(Qt[0]+"e"+(+Qt[1]+Nt));return Qt=(ya(ye)+"e").split("e"),+(Qt[0]+"e"+(+Qt[1]-Nt))}return U(at)}}var md=Nn&&1/Ic(new Nn([,-0]))[1]==tt?function(R){return new Nn(R)}:wu;function Hu(R){return function(U){var at=Eo(U);return at==Tt?zr(U):at==Ae?Jc(U):Ir(U,R(U))}}function Js(R,U,at,Nt,Qt,ye,Ue,Qe){var C=U&a;if(!C&&typeof R!="function")throw new Ur(s);var M=Nt?Nt.length:0;if(M||(U&=-97,Nt=Qt=t),Ue=Ue===t?Ue:_n(js(Ue),0),Qe=Qe===t?Qe:js(Qe),M-=Qt?Qt.length:0,U&S){var nt=Nt,vt=Qt;Nt=Qt=t;}var Ft=C?t:hf(R),ne=[R,U,at,Nt,Qt,nt,vt,ye,Ue,Qe];if(Ft&&gd(ne,Ft),R=ne[0],U=ne[1],at=ne[2],Nt=ne[3],Qt=ne[4],Qe=ne[9]=ne[9]===t?C?0:R.length:_n(ne[9]-M,0),!Qe&&U&(d|g)&&(U&=-25),!U||U==l)var Re=fl(R,U,at);else U==d||U==g?Re=pd(R,U,Qe):(U==_||U==(l|_))&&!Qt.length?Re=Uc(R,U,at,Nt):Re=th.apply(t,ne);var je=Ft?dc:Ec;return Gc(je(Re,ne),R,U)}function Xi(R,U,at,Nt){return R===t||uh(R,At[at])&&!Ns.call(Nt,at)?U:R}function pl(R,U,at,Nt,Qt,ye){return Wu(R)&&Wu(U)&&(ye.set(U,R),N0(R,U,t,pl,ye),ye.delete(U)),R}function lf(R){return G1(R)?t:R}function Ol(R,U,at,Nt,Qt,ye){var Ue=at&m,Qe=R.length,C=U.length;if(Qe!=C&&!(Ue&&C>Qe))return false;var M=ye.get(R),nt=ye.get(U);if(M&&nt)return M==U&&nt==R;var vt=-1,Ft=true,ne=at&u?new uc:t;for(ye.set(R,U),ye.set(U,R);++vt<Qe;){var Re=R[vt],je=U[vt];if(Nt)var Ye=Ue?Nt(je,Re,vt,U,R,ye):Nt(Re,je,vt,R,U,ye);if(Ye!==t){if(Ye)continue;Ft=false;break}if(ne){if(!_r(U,function(on,an){if(!Sr(ne,an)&&(Re===on||Qt(Re,on,at,Nt,ye)))return ne.push(an)})){Ft=false;break}}else if(!(Re===je||Qt(Re,je,at,Nt,ye))){Ft=false;break}}return ye.delete(R),ye.delete(U),Ft}function cf(R,U,at,Nt,Qt,ye,Ue){switch(at){case Le:if(R.byteLength!=U.byteLength||R.byteOffset!=U.byteOffset)return false;R=R.buffer,U=U.buffer;case zt:return !(R.byteLength!=U.byteLength||!ye(new el(R),new el(U)));case Se:case ee:case Lt:return uh(+R,+U);case Et:return R.name==U.name&&R.message==U.message;case Ht:case kt:return R==U+"";case Tt:var Qe=zr;case Ae:var C=Nt&m;if(Qe||(Qe=Ic),R.size!=U.size&&!C)return false;var M=Ue.get(R);if(M)return M==U;Nt|=u,Ue.set(R,U);var nt=Ol(Qe(R),Qe(U),Nt,Qt,ye,Ue);return Ue.delete(R),nt;case jt:if(Ai)return Ai.call(R)==Ai.call(U)}return false}function Kc(R,U,at,Nt,Qt,ye){var Ue=at&m,Qe=Ls(R),C=Qe.length,M=Ls(U),nt=M.length;if(C!=nt&&!Ue)return false;for(var vt=C;vt--;){var Ft=Qe[vt];if(!(Ue?Ft in U:Ns.call(U,Ft)))return false}var ne=ye.get(R),Re=ye.get(U);if(ne&&Re)return ne==U&&Re==R;var je=true;ye.set(R,U),ye.set(U,R);for(var Ye=Ue;++vt<C;){Ft=Qe[vt];var on=R[Ft],an=U[Ft];if(Nt)var Dn=Ue?Nt(an,on,Ft,U,R,ye):Nt(on,an,Ft,R,U,ye);if(!(Dn===t?on===an||Qt(on,an,at,Nt,ye):Dn)){je=false;break}Ye||(Ye=Ft=="constructor");}if(je&&!Ye){var li=R.constructor,Ui=U.constructor;li!=Ui&&"constructor"in R&&"constructor"in U&&!(typeof li=="function"&&li instanceof li&&typeof Ui=="function"&&Ui instanceof Ui)&&(je=false);}return ye.delete(R),ye.delete(U),je}function ao(R){return ih(e0(R,t,df),R+"")}function Ls(R){return sl(R,Hl,Zh)}function Fs(R){return sl(R,Fh,Hc)}var hf=di?function(R){return di.get(R)}:wu;function eh(R){for(var U=R.name+"",at=gi[U],Nt=Ns.call(gi,U)?at.length:0;Nt--;){var Qt=at[Nt],ye=Qt.func;if(ye==null||ye==R)return Qt.name}return U}function Ua(R){var U=Ns.call(he,"placeholder")?he:R;return U.placeholder}function zi(){var R=he.iteratee||Np;return R=R===Np?ea:R,arguments.length?R(arguments[0],arguments[1]):R}function $c(R,U){var at=R.__data__;return ol(U)?at[typeof U=="string"?"string":"hash"]:at.map}function Ka(R){for(var U=Hl(R),at=U.length;at--;){var Nt=U[at],Qt=R[Nt];U[at]=[Nt,Qt,al(Qt)];}return U}function Ia(R,U){var at=Fr(R,U);return zh(at)?at:t}function Gu(R){var U=Ns.call(R,An),at=R[An];try{R[An]=t;var Nt=!0;}catch{}var Qt=Mu.call(R);return Nt&&(U?R[An]=at:delete R[An]),Qt}var Zh=Hn?function(R){return R==null?[]:(R=Ys(R),Ne(Hn(R),function(U){return Oi.call(R,U)}))}:C2,Hc=Hn?function(R){for(var U=[];R;)tr(U,Zh(R)),R=sc(R);return U}:C2,Eo=Is;(Pn&&Eo(new Pn(new ArrayBuffer(1)))!=Le||En&&Eo(new En)!=Tt||bn&&Eo(bn.resolve())!=re||Nn&&Eo(new Nn)!=Ae||Ti&&Eo(new Ti)!=$t)&&(Eo=function(R){var U=Is(R),at=U==Bt?R.constructor:t,Nt=at?sh(at):"";if(Nt)switch(Nt){case yi:return Le;case xi:return Tt;case bi:return re;case Ni:return Ae;case Si:return $t}return U});function Qn(R,U,at){for(var Nt=-1,Qt=at.length;++Nt<Qt;){var ye=at[Nt],Ue=ye.size;switch(ye.type){case "drop":R+=Ue;break;case "dropRight":U-=Ue;break;case "take":U=vn(U,R+Ue);break;case "takeRight":R=_n(R,U-Ue);break}}return {start:R,end:U}}function P0(R){var U=R.match(Mo);return U?U[1].split(gu):[]}function xl(R,U,at){U=Bl(U,R);for(var Nt=-1,Qt=U.length,ye=false;++Nt<Qt;){var Ue=Ql(U[Nt]);if(!(ye=R!=null&&at(R,Ue)))break;R=R[Ue];}return ye||++Nt!=Qt?ye:(Qt=R==null?0:R.length,!!Qt&&H1(Qt)&&rh(Ue,Qt)&&(qs(R)||b1(R)))}function t0(R){var U=R.length,at=new R.constructor(U);return U&&typeof R[0]=="string"&&Ns.call(R,"index")&&(at.index=R.index,at.input=R.input),at}function Oo(R){return typeof R.constructor=="function"&&!Uf(R)?Yl(sc(R)):{}}function Bf(R,U,at){var Nt=R.constructor;switch(U){case zt:return dd(R);case Se:case ee:return new Nt(+R);case Le:return Mf(R,at);case ie:case gr:case wn:case ri:case Fn:case He:case Ge:case Xr:case Gn:return Al(R,at);case Tt:return new Nt;case Lt:case kt:return new Nt(R);case Ht:return of(R);case Ae:return new Nt;case jt:return Za(R)}}function M0(R,U){var at=U.length;if(!at)return R;var Nt=at-1;return U[Nt]=(at>1?"& ":"")+U[Nt],U=U.join(at>2?", ":" "),R.replace(_a,`{
1917
+ `}bindControlEvents(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".toggle-panel"),c=this.controlsContainer.querySelector(".panel-content");n?.addEventListener("click",()=>{let T=c.classList.contains("collapsed");c.classList.toggle("collapsed"),n.textContent=T?"\u25B2":"\u25BC";}),this.controlsContainer.querySelectorAll(".section-header").forEach(T=>{let G=T.querySelector(".section-toggle"),j=T.closest(".section-card")?.querySelector(".section-content");G&&j&&(T.addEventListener("click",B=>{if(B.target===G)return;let J=j.classList.contains("collapsed");j.classList.toggle("collapsed"),G.textContent=J?"\u25B2":"\u25BC";}),G.addEventListener("click",B=>{B.stopPropagation();let J=j.classList.contains("collapsed");j.classList.toggle("collapsed"),G.textContent=J?"\u25B2":"\u25BC";}));});let e=this.controlsContainer.querySelector(".atom-type-select"),i=this.controlsContainer.querySelector(".custom-type-input"),o=this.controlsContainer.querySelector(".atom-label-input"),p=this.controlsContainer.querySelector(".add-atom-btn"),E=()=>{let T=e.value,q=i.value.trim()||T;p.disabled=!q||!o.value.trim();};e?.addEventListener("change",()=>{e.value&&e.value!=="Other..."&&(i.value=""),E();}),i?.addEventListener("input",()=>{i.value.trim()&&(e.value=""),E();}),o?.addEventListener("input",E),p?.addEventListener("click",async()=>{let T=i.value.trim(),G=T||e.value;if(T){this.customTypes.add(T);let q=Array.from(e.options).find(B=>B.value==="Other...");if(q&&e.removeChild(q),!Array.from(e.options).find(B=>B.value===T)){let B=document.createElement("option");B.value=T,B.textContent=T,e.appendChild(B);}q&&e.appendChild(q),e.value="",i.value="";}else if(!G)return;await this.addAtomFromForm(G,o.value.trim()),o.value="",E(),this.updateDeletionSelects(),this.updateAtomPositions();});let b=this.controlsContainer.querySelector(".relation-type-input"),y=this.controlsContainer.querySelector(".add-relation-btn"),m=this.controlsContainer.querySelector(".add-position-btn"),u=this.controlsContainer.querySelector(".remove-position-btn"),l=()=>{let G=this.relationAtomPositions.filter(j=>j.trim()!=="").length>=2,q=b.value.trim();y.disabled=!G||!q;};b?.addEventListener("input",l),this.updateAtomPositions(),m?.addEventListener("click",()=>{this.relationAtomPositions.push(""),this.updateAtomPositions(),l();}),u?.addEventListener("click",()=>{this.relationAtomPositions.length>2&&(this.relationAtomPositions.pop(),this.updateAtomPositions(),l());}),y?.addEventListener("click",async()=>{await this.addRelationFromForm(),b.value="",this.relationAtomPositions=["",""],this.updateAtomPositions(),l(),this.updateDeletionSelects();});let a=this.controlsContainer.querySelector(".atom-delete-select"),h=this.controlsContainer.querySelector(".relation-delete-select"),d=this.controlsContainer.querySelector(".delete-atom-btn"),g=this.controlsContainer.querySelector(".delete-relation-btn"),_=this.controlsContainer.querySelector(".clear-all-btn"),S=()=>{d.disabled=!a.value,g.disabled=!h.value;};a?.addEventListener("change",S),h?.addEventListener("change",S),d?.addEventListener("click",async()=>{await this.deleteAtom(a.value),this.updateDeletionSelects(),this.updateAtomPositions(),S();}),g?.addEventListener("click",async()=>{await this.deleteRelation(h.value),this.updateDeletionSelects(),S();}),_?.addEventListener("click",async()=>{await this.clearAllItems(),this.updateDeletionSelects(),this.updateAtomPositions(),S();}),this.controlsContainer.querySelector(".export-json-btn")?.addEventListener("click",()=>{this.exportDataAsJSON();}),this.updateDeletionSelects();}async handleEdgeCreationRequest(n){console.log("\u{1F517} Handling edge creation request:",n.detail);let{relationId:c,sourceNodeId:s,targetNodeId:e,tuple:i}=n.detail;try{this._suppressDataChangeRerender=!0;try{this.dataInstance.addRelationTuple(c,i),console.log(`\u2705 Added relation to data instance: ${c}(${s}, ${e})`);}finally{this._suppressDataChangeRerender=!1;}await this.enforceConstraintsAndRegenerate();}catch(o){console.error("\u274C Failed to handle edge creation request:",o);}}async handleEdgeModificationRequest(n){console.log("\u{1F517} Handling edge modification request:",n.detail);let{oldRelationId:c,newRelationId:s,sourceNodeId:e,targetNodeId:i,tuple:o}=n.detail;try{this._suppressDataChangeRerender=!0;try{if(!s||s.trim()==="")console.log("\u{1F5D1}\uFE0F Deleting edge (empty new relation name)"),c&&c.trim()&&(this.dataInstance.removeRelationTuple(c,o),console.log(`\u2705 Removed relation tuple from ${c}`));else if(c.trim()===s.trim()){console.log("\u23ED\uFE0F Same relation name, no data changes needed");return}else {if(c&&c.trim())try{this.dataInstance.removeRelationTuple(c,o),console.log(`\u{1F5D1}\uFE0F Removed from ${c}`);}catch(p){let E=p instanceof Error?p.message:String(p);console.log(`\u26A0\uFE0F Could not remove from ${c}: ${E}`);}this.dataInstance.addRelationTuple(s,o),console.log(`\u2795 Added to ${s}`);}}finally{this._suppressDataChangeRerender=!1;}await this.enforceConstraintsAndRegenerate();}catch(p){console.error("\u274C Failed to handle edge modification request:",p);}}async handleEdgeReconnectionRequest(n){console.log("\u{1F504} Handling edge reconnection request:",n.detail);let{relationId:c,oldTuple:s,newTuple:e,oldSourceNodeId:i,oldTargetNodeId:o,newSourceNodeId:p,newTargetNodeId:E}=n.detail;try{this._suppressDataChangeRerender=!0;try{if(c&&c.trim())try{this.dataInstance.removeRelationTuple(c,s),console.log(`\u{1F5D1}\uFE0F Removed old tuple from ${c}: ${i} -> ${o}`);}catch(b){let y=b instanceof Error?b.message:String(b);console.log(`\u26A0\uFE0F Could not remove old tuple from ${c}: ${y}`);}this.dataInstance.addRelationTuple(c,e),console.log(`\u2795 Added new tuple to ${c}: ${p} -> ${E}`);}finally{this._suppressDataChangeRerender=!1;}await this.enforceConstraintsAndRegenerate();}catch(b){console.error("\u274C Failed to handle edge reconnection request:",b);}}async parseCnDSpec(n){try{console.log("\u{1F504} Parsing CnD spec and initializing pipeline..."),this.cndSpecString=n,await this.initializeCnDPipeline(n),this.updateTypeSelector(),this.updateSpecInfo(),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("spec-loaded",{detail:{spec:this.cndSpecString}})),console.log("\u2705 CnD spec parsed and pipeline initialized");}catch(c){console.error("\u274C Failed to parse CnD spec:",c),this.updateSpecInfo("error",c instanceof Error?c.message:"Parse error");}}async initializeCnDPipeline(n){if(!n.trim()){console.log("\u{1F4DD} Empty spec - clearing pipeline"),this.evaluator=null,this.layoutInstance=null;return}try{console.log("\u{1F527} Initializing CnD pipeline with spec...");let c=J2(n);console.log("\u{1F4CB} Layout spec parsed successfully"),this.evaluator=new exports.SGraphQueryEvaluator,this.evaluator.initialize({sourceData:this.dataInstance}),console.log("\u{1F50D} SGraphQueryEvaluator initialized with data instance"),this.layoutInstance=new exports.LayoutInstance(c,this.evaluator,0,!0),console.log("\u{1F4D0} LayoutInstance created"),console.log("\u2705 CnD pipeline initialized successfully (evaluator + layout instance)");}catch(c){throw console.error("\u274C Failed to initialize CnD pipeline:",c),this.evaluator=null,this.layoutInstance=null,c}}async enforceConstraintsAndRegenerate(){console.log("\u{1F504} enforceConstraintsAndRegenerate() called");try{if(!this.layoutInstance){console.log("\u26A0\uFE0F Cannot enforce constraints - no layout instance available");return}console.log("\u{1F4CA} Current data instance state:",{atoms:this.dataInstance.getAtoms().length,relations:this.dataInstance.getRelations().length}),this.evaluator&&(console.log("\u{1F504} Re-initializing evaluator with updated data instance..."),this.evaluator.initialize({sourceData:this.dataInstance}),console.log("\u2705 Evaluator re-initialized")),console.log("\u{1F527} Generating layout with constraint enforcement...");let n=this.layoutInstance.generateLayout(this.dataInstance);n.error?(console.warn("\u26A0\uFE0F Constraint validation error detected:",n.error),this.currentConstraintError=n.error,this.dispatchEvent(new CustomEvent("constraint-error",{detail:{error:n.error,layout:n.layout},bubbles:!0})),console.log("\u{1F4E4} Dispatched constraint-error event with UNSAT core information")):(console.log("\u2705 Layout generated successfully - all constraints satisfied"),this.currentConstraintError!==null&&(console.log("\u{1F9F9} Clearing previous constraint error - constraints now satisfied"),this.currentConstraintError=null,this.dispatchEvent(new CustomEvent("constraints-satisfied",{detail:{layout:n.layout},bubbles:!0})),console.log("\u{1F4E4} Dispatched constraints-satisfied event"))),console.log("\u{1F3A8} Rendering layout...");let c=this.getLayoutState(),s=c.positions.length>0;await this.renderLayout(n.layout,s?{priorPositions:c}:void 0),console.log("\u2705 Constraints enforced and layout regenerated successfully");}catch(n){console.error("\u274C Failed to enforce constraints and regenerate layout:",n),this.dispatchEvent(new CustomEvent("layout-generation-error",{detail:{error:n},bubbles:true}));}}refreshTypesFromDataInstance(){this.updateTypeSelector();}getAvailableAtomTypes(){let n=new Set;return this.dataInstance&&this.dataInstance.getAtoms().forEach(s=>{s.type&&n.add(s.type);}),n.size===0&&(n.add("Entity"),n.add("Person"),n.add("Object")),Array.from(n)}updateDataInstance(n){try{console.log("Data instance updated:",n);}catch(c){console.error("Failed to update data instance:",c);}}updateExportVisibility(n){let c=this.controlsContainer?.querySelector(".export-section");c&&(c.style.display=n?"block":"none");}updateTypeSelector(){let n=this.controlsContainer?.querySelector(".atom-type-select");if(!n)return;for(;n.children.length>1;)n.removeChild(n.lastChild);this.getAvailableAtomTypes().forEach(e=>{let i=document.createElement("option");i.value=e,i.textContent=e,n.appendChild(i);}),this.customTypes.forEach(e=>{if(!Array.from(n.options).find(o=>o.value===e)){let o=document.createElement("option");o.value=e,o.textContent=e,n.appendChild(o);}});let s=document.createElement("option");s.value="Other...",s.textContent="Other...",n.appendChild(s);}updateSpecInfo(n="loaded",c){let s=this.controlsContainer?.querySelector(".spec-status"),e=this.controlsContainer?.querySelector(".type-list");if(!s||!e)return;if(s.className=`spec-status ${n}`,n==="error"){s.textContent=c||"Error loading spec",e.innerHTML="";return}let i=this.getAvailableAtomTypes();s.textContent=`Loaded: ${i.length} atom types available`,e.innerHTML=i.map(o=>`<span class="type-item">${o}</span>`).join("");}generateAtomId(n){if(!this.dataInstance)return `${n}-1`;let c=this.dataInstance.getAtoms(),s=new Set(c.map(o=>o.id)),e=1,i=`${n}-${e}`;for(;s.has(i);)e++,i=`${n}-${e}`;return i}async addAtomFromForm(n,c){if(!(!n||!c))try{console.log(`\u{1F535} Adding atom: ${c} (${n})`);let e={id:this.generateAtomId(n),type:n,label:c};this.dataInstance.addAtom(e),console.log(`\u2705 Atom added to data instance: ${e.label} (${e.id}:${e.type})`),this.refreshTypesFromDataInstance(),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("atom-added",{detail:{atom:e}})),console.log(`\u{1F389} Atom addition completed: ${e.label} (${e.id}:${e.type})`);}catch(s){console.error("\u274C Failed to add atom:",s);}}updateAtomPositions(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".atom-positions"),c=this.controlsContainer.querySelector(".arity-display"),s=this.controlsContainer.querySelector(".remove-position-btn");if(!n)return;c&&(c.textContent=this.relationAtomPositions.length.toString()),s&&(s.disabled=this.relationAtomPositions.length<=2),n.innerHTML="";let e=this.dataInstance.getAtoms();if(e.length===0){n.innerHTML='<div style="color: #666; font-size: 11px;">No atoms available</div>';return}this.relationAtomPositions.forEach((i,o)=>{let p=document.createElement("div");p.className="atom-position";let E=document.createElement("label");E.textContent=`Position ${o+1}:`;let b=document.createElement("select");b.dataset.position=o.toString();let y=document.createElement("option");y.value="",y.textContent="Select Atom",b.appendChild(y),e.forEach(m=>{let u=document.createElement("option");u.value=m.id,u.textContent=`${m.label} (${m.type})`,m.id===i&&(u.selected=true),b.appendChild(u);}),b.addEventListener("change",()=>{this.relationAtomPositions[o]=b.value,this.updateRelationButtonState();}),p.appendChild(E),p.appendChild(b),n.appendChild(p);});}updateRelationButtonState(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".relation-type-input"),c=this.controlsContainer.querySelector(".add-relation-btn"),e=this.relationAtomPositions.filter(o=>o.trim()!=="").length>=2,i=n?.value.trim();c&&(c.disabled=!e||!i);}async addRelationFromForm(){if(this.controlsContainer)try{let c=this.controlsContainer.querySelector(".relation-type-input").value.trim();if(!c)return;let s=this.relationAtomPositions.filter(p=>p.trim()!=="");if(s.length<2){console.warn("Need at least 2 atoms for a relation");return}console.log(`\u{1F517} Adding relation: ${c}(${s.join(", ")})`);let e=this.dataInstance.getAtoms(),i=s.map(p=>e.find(b=>b.id===p)?.type||"untyped"),o={atoms:s,types:i};this.dataInstance.addRelationTuple(c,o),console.log(`\u2705 Relation added to data instance: ${c}(${s.join(", ")})`),await this.enforceConstraintsAndRegenerate(),this.dispatchEvent(new CustomEvent("relation-added",{detail:{relationType:c,tuple:o}})),console.log(`\u{1F389} Relation addition completed: ${c}(${s.join(", ")})`);}catch(n){console.error("\u274C Failed to add relation:",n);}}exportDataAsJSON(){try{console.log("\u{1F4E4} Exporting data instance using reify()...");let n=this.dataInstance.reify(),c=typeof n=="string"?n:JSON.stringify(n,null,2),s=this.controlsContainer?.querySelector(".export-output");s&&(s.value=c),this.dispatchEvent(new CustomEvent("data-exported",{detail:{data:c,format:typeof n=="string"?"text":"json",reified:n}})),console.log("\u2705 Data exported using reify()");}catch(n){console.error("\u274C Failed to export data:",n);}}handleDataChangeUIUpdate(n=false){this.refreshTypesFromDataInstance(),this.updateDeletionSelects(),n&&this.updateAtomPositions();}async handleDataDeletionWithValidation(n=false){this.handleDataChangeUIUpdate(n),await this.enforceConstraintsAndRegenerate();}setDataInstance(n){console.log("\u{1F504} Setting new data instance"),this.dataInstance&&(this.dataInstanceEventHandlers.atomAdded&&this.dataInstance.removeEventListener("atomAdded",this.dataInstanceEventHandlers.atomAdded),this.dataInstanceEventHandlers.atomRemoved&&this.dataInstance.removeEventListener("atomRemoved",this.dataInstanceEventHandlers.atomRemoved),this.dataInstanceEventHandlers.relationTupleAdded&&this.dataInstance.removeEventListener("relationTupleAdded",this.dataInstanceEventHandlers.relationTupleAdded),this.dataInstanceEventHandlers.relationTupleRemoved&&this.dataInstance.removeEventListener("relationTupleRemoved",this.dataInstanceEventHandlers.relationTupleRemoved)),this.dataInstance=n,this.refreshTypesFromDataInstance(),this.dataInstanceEventHandlers.atomAdded=async()=>{console.log("\u{1F4CD} Atom added to instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(true),this._suppressDataChangeRerender||await this.enforceConstraintsAndRegenerate();},this.dataInstanceEventHandlers.relationTupleAdded=async()=>{console.log("\u{1F517} Relation added to instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(false),this._suppressDataChangeRerender||await this.enforceConstraintsAndRegenerate();},this.dataInstanceEventHandlers.atomRemoved=async()=>{console.log("\u{1F5D1}\uFE0F Atom removed from instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(true),this._suppressDataChangeRerender||await this.handleDataDeletionWithValidation(true);},this.dataInstanceEventHandlers.relationTupleRemoved=async()=>{console.log("\u{1F5D1}\uFE0F Relation tuple removed from instance - updating UI and re-validating constraints"),this.handleDataChangeUIUpdate(false),this._suppressDataChangeRerender||await this.handleDataDeletionWithValidation(false);},n.addEventListener("atomAdded",this.dataInstanceEventHandlers.atomAdded),n.addEventListener("relationTupleAdded",this.dataInstanceEventHandlers.relationTupleAdded),n.addEventListener("atomRemoved",this.dataInstanceEventHandlers.atomRemoved),n.addEventListener("relationTupleRemoved",this.dataInstanceEventHandlers.relationTupleRemoved),this.updateDeletionSelects(),this.updateAtomPositions(),console.log("\u2705 Data instance set successfully");}updateDeletionSelects(){if(!this.controlsContainer)return;let n=this.controlsContainer.querySelector(".atom-delete-select"),c=this.controlsContainer.querySelector(".relation-delete-select");if(n){for(;n.children.length>1;)n.removeChild(n.lastChild);this.dataInstance.getAtoms().forEach(e=>{let i=document.createElement("option");i.value=e.id,i.textContent=`${e.label} (${e.type})`,n.appendChild(i);});}if(c){for(;c.children.length>1;)c.removeChild(c.lastChild);let s=this.dataInstance.getRelations(),e=0;s.forEach(i=>{i.tuples.forEach(o=>{let p=document.createElement("option");p.value=e.toString();let E=o.atoms.map(y=>{let m=this.dataInstance.getAtoms().find(u=>u.id===y);return m?m.label:y}),b=i.id||i.name||"relation";p.textContent=`${b}: ${E.join(" \u2192 ")}`,c.appendChild(p),e++;});});}}async deleteAtom(n){if(n)try{console.log(`\u{1F5D1}\uFE0F Deleting atom: ${n}`);let s=this.dataInstance.getAtoms().find(e=>e.id===n);if(!s){console.warn(`\u26A0\uFE0F Atom ${n} not found`);return}this.dataInstance.removeAtom(n),console.log(`\u2705 Atom removed from data instance: ${s.label} (${s.id})`),console.log(`\u{1F389} Atom deletion completed: ${s.label} (${s.id})`),this.dispatchEvent(new CustomEvent("atom-deleted",{detail:{atom:s}}));}catch(c){console.error("\u274C Failed to delete atom:",c);}}async deleteRelation(n){if(n)try{let c=parseInt(n,10);console.log(`\u{1F5D1}\uFE0F Deleting relation tuple at index: ${c}`);let s=this.dataInstance.getRelations(),e=0,i=null,o=null;for(let E of s){for(let b of E.tuples){if(e===c){i=E,o=b;break}e++;}if(i)break}if(!i||!o){console.warn(`\u26A0\uFE0F Relation tuple at index ${c} not found`);return}let p=i.id||i.name;console.log(`\u{1F5D1}\uFE0F Found tuple in relation "${p}": ${o.atoms.join(" \u2192 ")}`),this.dataInstance.removeRelationTuple(p,o),console.log(`\u2705 Relation tuple removed from data instance: ${p}: ${o.atoms.join(" \u2192 ")}`),console.log(`\u{1F389} Relation tuple deletion completed: ${p}: ${o.atoms.join(" \u2192 ")}`),this.dispatchEvent(new CustomEvent("relation-tuple-deleted",{detail:{relationId:p,tuple:o}}));}catch(c){console.error("\u274C Failed to delete relation tuple:",c);}}async clearAllItems(){try{console.log("\u{1F9F9} Clearing all atoms and relations...");let n=new exports.JSONDataInstance({atoms:[],relations:[],types:[]});this.setDataInstance(n),console.log("\u2705 All items cleared from data instance"),await this.enforceConstraintsAndRegenerate(),console.log("\u{1F389} Clear all completed"),this.dispatchEvent(new CustomEvent("all-items-cleared",{detail:{}}));}catch(n){console.error("\u274C Failed to clear all items:",n);}}getDataInstance(){return this.dataInstance}getCurrentConstraintError(){return this.currentConstraintError}hasConstraintErrors(){return this.currentConstraintError!==null}async setCnDSpec(n){this.setAttribute("cnd-spec",n),await this.parseCnDSpec(n);}getAvailableTypes(){return this.getAvailableAtomTypes()}};});var rB=Te((xg,Lv)=>{(function(){var t,r="4.17.23",n=200,c="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",e="Invalid `variable` option passed into `_.template`",i="__lodash_hash_undefined__",o=500,p="__lodash_placeholder__",E=1,b=2,y=4,m=1,u=2,l=1,a=2,h=4,d=8,g=16,_=32,S=64,v=128,T=256,G=512,q=30,j="...",B=800,J=16,w=1,$=2,z=3,tt=1/0,pt=9007199254740991,Z=17976931348623157e292,dt=NaN,gt=4294967295,bt=gt-1,mt=gt>>>1,St=[["ary",v],["bind",l],["bindKey",a],["curry",d],["curryRight",g],["flip",G],["partial",_],["partialRight",S],["rearg",T]],Zt="[object Arguments]",oe="[object Array]",te="[object AsyncFunction]",Se="[object Boolean]",ee="[object Date]",Jt="[object DOMException]",Et="[object Error]",ht="[object Function]",xt="[object GeneratorFunction]",Tt="[object Map]",Lt="[object Number]",Pt="[object Null]",Bt="[object Object]",re="[object Promise]",ce="[object Proxy]",Ht="[object RegExp]",Ae="[object Set]",kt="[object String]",jt="[object Symbol]",Kt="[object Undefined]",$t="[object WeakMap]",yt="[object WeakSet]",zt="[object ArrayBuffer]",Le="[object DataView]",ie="[object Float32Array]",gr="[object Float64Array]",wn="[object Int8Array]",ri="[object Int16Array]",Fn="[object Int32Array]",He="[object Uint8Array]",Ge="[object Uint8ClampedArray]",Xr="[object Uint16Array]",Gn="[object Uint32Array]",ti=/\b__p \+= '';/g,oi=/\b(__p \+=) '' \+/g,fi=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Mi=/&(?:amp|lt|gt|quot|#39);/g,Fi=/[&<>"']/g,ve=RegExp(Mi.source),Kr=RegExp(Fi.source),gn=/<%-([\s\S]+?)%>/g,Un=/<%([\s\S]+?)%>/g,Yn=/<%=([\s\S]+?)%>/g,$i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ri=/^\w*$/,ps=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,eo=/[\\^$.*+?()[\]{}|]/g,Wi=RegExp(eo.source),ki=/^\s+/,ks=/\s/,_a=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Mo=/\{\n\/\* \[wrapped with (.+)\] \*/,gu=/,? & /,Ml=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ou=/[()=,{}\[\]\/\s]/,Ta=/\\(\\)?/g,ko=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ju=/\w*$/,yu=/^[-+]0x[0-9a-f]+$/i,vl=/^0b[01]+$/i,Va=/^\[object .+?Constructor\]$/,Ro=/^0o[0-7]+$/i,wo=/^(?:0|[1-9]\d*)$/,au=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Pu=/($^)/,Zu=/['\n\r\u2028\u2029\\]/g,oo="\\ud800-\\udfff",uu="\\u0300-\\u036f",pn="\\ufe20-\\ufe2f",L="\\u20d0-\\u20ff",O=uu+pn+L,it="\\u2700-\\u27bf",Gt="a-z\\xdf-\\xf6\\xf8-\\xff",Jr="\\xac\\xb1\\xd7\\xf7",Wn="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",f="\\u2000-\\u206f",H=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",k="A-Z\\xc0-\\xd6\\xd8-\\xde",F="\\ufe0e\\ufe0f",W=Jr+Wn+f+H,P="['\u2019]",X="["+oo+"]",Q="["+W+"]",lt="["+O+"]",pe="\\d+",fe="["+it+"]",Mt="["+Gt+"]",Rt="[^"+oo+W+pe+it+Gt+k+"]",qt="\\ud83c[\\udffb-\\udfff]",we="(?:"+lt+"|"+qt+")",Ee="[^"+oo+"]",Pe="(?:\\ud83c[\\udde6-\\uddff]){2}",ge="[\\ud800-\\udbff][\\udc00-\\udfff]",se="["+k+"]",Br="\\u200d",Be="(?:"+Mt+"|"+Rt+")",en="(?:"+se+"|"+Rt+")",br="(?:"+P+"(?:d|ll|m|re|s|t|ve))?",sr="(?:"+P+"(?:D|LL|M|RE|S|T|VE))?",Ar=we+"?",nn="["+F+"]?",Tn="(?:"+Br+"(?:"+[Ee,Pe,ge].join("|")+")"+nn+Ar+")*",ei="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Ve="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",yn=nn+Ar+Tn,mn="(?:"+[fe,Pe,ge].join("|")+")"+yn,cn="(?:"+[Ee+lt+"?",lt,Pe,ge,X].join("|")+")",Ei=RegExp(P,"g"),_s=RegExp(lt,"g"),Qs=RegExp(qt+"(?="+qt+")|"+cn+yn,"g"),Ko=RegExp([se+"?"+Mt+"+"+br+"(?="+[Q,se,"$"].join("|")+")",en+"+"+sr+"(?="+[Q,se+Be,"$"].join("|")+")",se+"?"+Be+"+"+br,se+"+"+sr,Ve,ei,pe,mn].join("|"),"g"),Cs=RegExp("["+Br+oo+O+F+"]"),Gi=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,xs=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Ya=-1,ts={};ts[ie]=ts[gr]=ts[wn]=ts[ri]=ts[Fn]=ts[He]=ts[Ge]=ts[Xr]=ts[Gn]=true,ts[Zt]=ts[oe]=ts[zt]=ts[Se]=ts[Le]=ts[ee]=ts[Et]=ts[ht]=ts[Tt]=ts[Lt]=ts[Bt]=ts[Ht]=ts[Ae]=ts[kt]=ts[$t]=false;var Jn={};Jn[Zt]=Jn[oe]=Jn[zt]=Jn[Le]=Jn[Se]=Jn[ee]=Jn[ie]=Jn[gr]=Jn[wn]=Jn[ri]=Jn[Fn]=Jn[Tt]=Jn[Lt]=Jn[Bt]=Jn[Ht]=Jn[Ae]=Jn[kt]=Jn[jt]=Jn[He]=Jn[Ge]=Jn[Xr]=Jn[Gn]=true,Jn[Et]=Jn[ht]=Jn[$t]=false;var us={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"Ae",\u00E6:"ae",\u00DE:"Th",\u00FE:"th",\u00DF:"ss",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"IJ",\u0133:"ij",\u0152:"Oe",\u0153:"oe",\u0149:"'n",\u017F:"s"},Xo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},La={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},tl={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},kl=parseFloat,ma=parseInt,Us=typeof globalThis=="object"&&globalThis&&globalThis.Object===Object&&globalThis,gs=typeof self=="object"&&self&&self.Object===Object&&self,$n=Us||gs||Function("return this")(),A0=typeof xg=="object"&&xg&&!xg.nodeType&&xg,Qc=A0&&typeof Lv=="object"&&Lv&&!Lv.nodeType&&Lv,Wt=Qc&&Qc.exports===A0,Yt=Wt&&Us.process,ue=(function(){try{var or=Qc&&Qc.require&&Qc.require("util").types;return or||Yt&&Yt.binding&&Yt.binding("util")}catch{}})(),Ce=ue&&ue.isArrayBuffer,me=ue&&ue.isDate,ae=ue&&ue.isMap,ke=ue&&ue.isRegExp,Ke=ue&&ue.isSet,Xe=ue&&ue.isTypedArray;function qi(or,rr,Rr){switch(Rr.length){case 0:return or.call(rr);case 1:return or.call(rr,Rr[0]);case 2:return or.call(rr,Rr[0],Rr[1]);case 3:return or.call(rr,Rr[0],Rr[1],Rr[2])}return or.apply(rr,Rr)}function ca(or,rr,Rr,wi){for(var os=-1,Vs=or==null?0:or.length;++os<Vs;){var vu=or[os];rr(wi,vu,Rr(vu),or);}return wi}function ha(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi&&rr(or[Rr],Rr,or)!==false;);return or}function Fo(or,rr){for(var Rr=or==null?0:or.length;Rr--&&rr(or[Rr],Rr,or)!==false;);return or}function be(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi;)if(!rr(or[Rr],Rr,or))return false;return true}function Ne(or,rr){for(var Rr=-1,wi=or==null?0:or.length,os=0,Vs=[];++Rr<wi;){var vu=or[Rr];rr(vu,Rr,or)&&(Vs[os++]=vu);}return Vs}function Oe(or,rr){var Rr=or==null?0:or.length;return !!Rr&&yr(or,rr,0)>-1}function $e(or,rr,Rr){for(var wi=-1,os=or==null?0:or.length;++wi<os;)if(Rr(rr,or[wi]))return true;return false}function De(or,rr){for(var Rr=-1,wi=or==null?0:or.length,os=Array(wi);++Rr<wi;)os[Rr]=rr(or[Rr],Rr,or);return os}function tr(or,rr){for(var Rr=-1,wi=rr.length,os=or.length;++Rr<wi;)or[os+Rr]=rr[Rr];return or}function dr(or,rr,Rr,wi){var os=-1,Vs=or==null?0:or.length;for(wi&&Vs&&(Rr=or[++os]);++os<Vs;)Rr=rr(Rr,or[os],os,or);return Rr}function er(or,rr,Rr,wi){var os=or==null?0:or.length;for(wi&&os&&(Rr=or[--os]);os--;)Rr=rr(Rr,or[os],os,or);return Rr}function _r(or,rr){for(var Rr=-1,wi=or==null?0:or.length;++Rr<wi;)if(rr(or[Rr],Rr,or))return true;return false}var jr=Vr("length");function Qr(or){return or.split("")}function Je(or){return or.match(Ml)||[]}function Tr(or,rr,Rr){var wi;return Rr(or,function(os,Vs,vu){if(rr(os,Vs,vu))return wi=Vs,false}),wi}function Or(or,rr,Rr,wi){for(var os=or.length,Vs=Rr+(wi?1:-1);wi?Vs--:++Vs<os;)if(rr(or[Vs],Vs,or))return Vs;return -1}function yr(or,rr,Rr){return rr===rr?Dc(or,rr,Rr):Or(or,Gr,Rr)}function $r(or,rr,Rr,wi){for(var os=Rr-1,Vs=or.length;++os<Vs;)if(wi(or[os],rr))return os;return -1}function Gr(or){return or!==or}function pr(or,rr){var Rr=or==null?0:or.length;return Rr?Cr(or,rr)/Rr:dt}function Vr(or){return function(rr){return rr==null?t:rr[or]}}function Yr(or){return function(rr){return or==null?t:or[rr]}}function qr(or,rr,Rr,wi,os){return os(or,function(Vs,vu,Ys){Rr=wi?(wi=false,Vs):rr(Rr,Vs,vu,Ys);}),Rr}function Wr(or,rr){var Rr=or.length;for(or.sort(rr);Rr--;)or[Rr]=or[Rr].value;return or}function Cr(or,rr){for(var Rr,wi=-1,os=or.length;++wi<os;){var Vs=rr(or[wi]);Vs!==t&&(Rr=Rr===t?Vs:Rr+Vs);}return Rr}function Pr(or,rr){for(var Rr=-1,wi=Array(or);++Rr<or;)wi[Rr]=rr(Rr);return wi}function Ir(or,rr){return De(rr,function(Rr){return [Rr,or[Rr]]})}function mr(or){return or&&or.slice(0,O0(or)+1).replace(ki,"")}function fr(or){return function(rr){return or(rr)}}function wr(or,rr){return De(rr,function(Rr){return or[Rr]})}function Sr(or,rr){return or.has(rr)}function vr(or,rr){for(var Rr=-1,wi=or.length;++Rr<wi&&yr(rr,or[Rr],0)>-1;);return Rr}function Mr(or,rr){for(var Rr=or.length;Rr--&&yr(rr,or[Rr],0)>-1;);return Rr}function lr(or,rr){for(var Rr=or.length,wi=0;Rr--;)or[Rr]===rr&&++wi;return wi}var Er=Yr(us),kr=Yr(Xo);function Dr(or){return "\\"+tl[or]}function Fr(or,rr){return or==null?t:or[rr]}function ir(or){return Cs.test(or)}function Zr(or){return Gi.test(or)}function tn(or){for(var rr,Rr=[];!(rr=or.next()).done;)Rr.push(rr.value);return Rr}function zr(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi,os){Rr[++rr]=[os,wi];}),Rr}function Ze(or,rr){return function(Rr){return or(rr(Rr))}}function We(or,rr){for(var Rr=-1,wi=or.length,os=0,Vs=[];++Rr<wi;){var vu=or[Rr];(vu===rr||vu===p)&&(or[Rr]=p,Vs[os++]=Rr);}return Vs}function Ic(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi){Rr[++rr]=wi;}),Rr}function Jc(or){var rr=-1,Rr=Array(or.size);return or.forEach(function(wi){Rr[++rr]=[wi,wi];}),Rr}function Dc(or,rr,Rr){for(var wi=Rr-1,os=or.length;++wi<os;)if(or[wi]===rr)return wi;return -1}function tf(or,rr,Rr){for(var wi=Rr+1;wi--;)if(or[wi]===rr)return wi;return wi}function yo(or){return ir(or)?Lc(or):jr(or)}function ro(or){return ir(or)?Fd(or):Qr(or)}function O0(or){for(var rr=or.length;rr--&&ks.test(or.charAt(rr)););return rr}var vh=Yr(La);function Lc(or){for(var rr=Qs.lastIndex=0;Qs.test(or);)++rr;return rr}function Fd(or){return or.match(Qs)||[]}function sd(or){return or.match(Ko)||[]}var ef=(function or(rr){rr=rr==null?$n:Qo.defaults($n.Object(),rr,Qo.pick($n,xs));var Rr=rr.Array,wi=rr.Date,os=rr.Error,Vs=rr.Function,vu=rr.Math,Ys=rr.Object,ar=rr.RegExp,fn=rr.String,Ur=rr.TypeError,Ci=Rr.prototype,ls=Vs.prototype,At=Ys.prototype,$o=rr["__core-js_shared__"],Ks=ls.toString,Ns=At.hasOwnProperty,Ws=0,Jo=(function(){var R=/[^.]+$/.exec($o&&$o.keys&&$o.keys.IE_PROTO||"");return R?"Symbol(src)_1."+R:""})(),Mu=At.toString,ic=Ks.call(Ys),ku=$n._,Ga=ar("^"+Ks.call(Ns).replace(eo,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Eu=Wt?rr.Buffer:t,$s=rr.Symbol,el=rr.Uint8Array,rf=Eu?Eu.allocUnsafe:t,sc=Ze(Ys.getPrototypeOf,Ys),Eh=Ys.create,Oi=At.propertyIsEnumerable,si=Ci.splice,hn=$s?$s.isConcatSpreadable:t,sn=$s?$s.iterator:t,An=$s?$s.toStringTag:t,Pc=(function(){try{var R=Ia(Ys,"defineProperty");return R({},"",{}),R}catch{}})(),On=rr.clearTimeout!==$n.clearTimeout&&rr.clearTimeout,kn=wi&&wi.now!==$n.Date.now&&wi.now,Bn=rr.setTimeout!==$n.setTimeout&&rr.setTimeout,ui=vu.ceil,ci=vu.floor,Hn=Ys.getOwnPropertySymbols,qn=Eu?Eu.isBuffer:t,_i=rr.isFinite,Bi=Ci.join,hi=Ze(Ys.keys,Ys),_n=vu.max,vn=vu.min,Kn=wi.now,Mn=rr.parseInt,ni=vu.random,Zn=Ci.reverse,Pn=Ia(rr,"DataView"),En=Ia(rr,"Map"),bn=Ia(rr,"Promise"),Nn=Ia(rr,"Set"),Ti=Ia(rr,"WeakMap"),pi=Ia(Ys,"create"),di=Ti&&new Ti,gi={},yi=sh(Pn),xi=sh(En),bi=sh(bn),Ni=sh(Nn),Si=sh(Ti),Xn=$s?$s.prototype:t,Ai=Xn?Xn.valueOf:t,oc=Xn?Xn.toString:t;function he(R){if(ul(R)&&!qs(R)&&!(R instanceof Gs)){if(R instanceof El)return R;if(Ns.call(R,"__wrapped__"))return qu(R)}return new El(R)}var Yl=(function(){function R(){}return function(U){if(!Wu(U))return {};if(Eh)return Eh(U);R.prototype=U;var at=new R;return R.prototype=t,at}})();function _h(){}function El(R,U){this.__wrapped__=R,this.__actions__=[],this.__chain__=!!U,this.__index__=0,this.__values__=t;}he.templateSettings={escape:gn,evaluate:Un,interpolate:Yn,variable:"",imports:{_:he}},he.prototype=_h.prototype,he.prototype.constructor=he,El.prototype=Yl(_h.prototype),El.prototype.constructor=El;function Gs(R){this.__wrapped__=R,this.__actions__=[],this.__dir__=1,this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=gt,this.__views__=[];}function Gh(){var R=new Gs(this.__wrapped__);return R.__actions__=jl(this.__actions__),R.__dir__=this.__dir__,R.__filtered__=this.__filtered__,R.__iteratees__=jl(this.__iteratees__),R.__takeCount__=this.__takeCount__,R.__views__=jl(this.__views__),R}function Pa(){if(this.__filtered__){var R=new Gs(this);R.__dir__=-1,R.__filtered__=true;}else R=this.clone(),R.__dir__*=-1;return R}function ac(){var R=this.__wrapped__.value(),U=this.__dir__,at=qs(R),Nt=U<0,Qt=at?R.length:0,ye=Qn(0,Qt,this.__views__),Ue=ye.start,Qe=ye.end,C=Qe-Ue,M=Nt?Qe:Ue-1,nt=this.__iteratees__,vt=nt.length,Ft=0,ne=vn(C,this.__takeCount__);if(!at||!Nt&&Qt==C&&ne==C)return fd(R,this.__actions__);var Re=[];t:for(;C--&&Ft<ne;){M+=U;for(var je=-1,Ye=R[M];++je<vt;){var on=nt[je],an=on.iteratee,Dn=on.type,li=an(Ye);if(Dn==$)Ye=li;else if(!li){if(Dn==w)continue t;break t}}Re[Ft++]=Ye;}return Re}Gs.prototype=Yl(_h.prototype),Gs.prototype.constructor=Gs;function le(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function ys(){this.__data__=pi?pi(null):{},this.size=0;}function S0(R){var U=this.has(R)&&delete this.__data__[R];return this.size-=U?1:0,U}function sa(R){var U=this.__data__;if(pi){var at=U[R];return at===i?t:at}return Ns.call(U,R)?U[R]:t}function Rs(R){var U=this.__data__;return pi?U[R]!==t:Ns.call(U,R)}function ba(R,U){var at=this.__data__;return this.size+=this.has(R)?0:1,at[R]=pi&&U===t?i:U,this}le.prototype.clear=ys,le.prototype.delete=S0,le.prototype.get=sa,le.prototype.has=Rs,le.prototype.set=ba;function ho(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function qh(){this.__data__=[],this.size=0;}function _u(R){var U=this.__data__,at=bu(U,R);if(at<0)return false;var Nt=U.length-1;return at==Nt?U.pop():si.call(U,at,1),--this.size,true}function od(R){var U=this.__data__,at=bu(U,R);return at<0?t:U[at][1]}function C0(R){return bu(this.__data__,R)>-1}function ws(R,U){var at=this.__data__,Nt=bu(at,R);return Nt<0?(++this.size,at.push([R,U])):at[Nt][1]=U,this}ho.prototype.clear=qh,ho.prototype.delete=_u,ho.prototype.get=od,ho.prototype.has=C0,ho.prototype.set=ws;function Wa(R){var U=-1,at=R==null?0:R.length;for(this.clear();++U<at;){var Nt=R[U];this.set(Nt[0],Nt[1]);}}function ad(){this.size=0,this.__data__={hash:new le,map:new(En||ho),string:new le};}function Aa(R){var U=$c(this,R).delete(R);return this.size-=U?1:0,U}function _l(R){return $c(this,R).get(R)}function nf(R){return $c(this,R).has(R)}function wf(R,U){var at=$c(this,R),Nt=at.size;return at.set(R,U),this.size+=at.size==Nt?0:1,this}Wa.prototype.clear=ad,Wa.prototype.delete=Aa,Wa.prototype.get=_l,Wa.prototype.has=nf,Wa.prototype.set=wf;function uc(R){var U=-1,at=R==null?0:R.length;for(this.__data__=new Wa;++U<at;)this.add(R[U]);}function Bd(R){return this.__data__.set(R,i),this}function Mc(R){return this.__data__.has(R)}uc.prototype.add=uc.prototype.push=Bd,uc.prototype.has=Mc;function lc(R){var U=this.__data__=new ho(R);this.size=U.size;}function Th(){this.__data__=new ho,this.size=0;}function Fu(R){var U=this.__data__,at=U.delete(R);return this.size=U.size,at}function Xa(R){return this.__data__.get(R)}function Fl(R){return this.__data__.has(R)}function Zo(R,U){var at=this.__data__;if(at instanceof ho){var Nt=at.__data__;if(!En||Nt.length<n-1)return Nt.push([R,U]),this.size=++at.size,this;at=this.__data__=new Wa(Nt);}return at.set(R,U),this.size=at.size,this}lc.prototype.clear=Th,lc.prototype.delete=Fu,lc.prototype.get=Xa,lc.prototype.has=Fl,lc.prototype.set=Zo;function Qa(R,U){var at=qs(R),Nt=!at&&b1(R),Qt=!at&&!Nt&&qf(R),ye=!at&&!Nt&&!Qt&&zd(R),Ue=at||Nt||Qt||ye,Qe=Ue?Pr(R.length,fn):[],C=Qe.length;for(var M in R)(U||Ns.call(R,M))&&!(Ue&&(M=="length"||Qt&&(M=="offset"||M=="parent")||ye&&(M=="buffer"||M=="byteLength"||M=="byteOffset")||rh(M,C)))&&Qe.push(M);return Qe}function rl(R){var U=R.length;return U?R[sf(0,U-1)]:t}function Ho(R,U){return F0(jl(R),da(U,0,R.length))}function cl(R){return F0(jl(R))}function Tu(R,U,at){(at!==t&&!uh(R[U],at)||at===t&&!(U in R))&&Bo(R,U,at);}function Ma(R,U,at){var Nt=R[U];(!(Ns.call(R,U)&&uh(Nt,at))||at===t&&!(U in R))&&Bo(R,U,at);}function bu(R,U){for(var at=R.length;at--;)if(uh(R[at][0],U))return at;return -1}function ta(R,U,at,Nt){return vo(R,function(Qt,ye,Ue){U(Nt,Qt,at(Qt),Ue);}),Nt}function fa(R,U){return R&&Zc(U,Hl(U),R)}function Au(R,U){return R&&Zc(U,Fh(U),R)}function Bo(R,U,at){U=="__proto__"&&Pc?Pc(R,U,{configurable:true,enumerable:true,value:at,writable:true}):R[U]=at;}function Bu(R,U){for(var at=-1,Nt=U.length,Qt=Rr(Nt),ye=R==null;++at<Nt;)Qt[at]=ye?t:Y1(R,U[at]);return Qt}function da(R,U,at){return R===R&&(at!==t&&(R=R<=at?R:at),U!==t&&(R=R>=U?R:U)),R}function no(R,U,at,Nt,Qt,ye){var Ue,Qe=U&E,C=U&b,M=U&y;if(at&&(Ue=Qt?at(R,Nt,Qt,ye):at(R)),Ue!==t)return Ue;if(!Wu(R))return R;var nt=qs(R);if(nt){if(Ue=t0(R),!Qe)return jl(R,Ue)}else {var vt=Eo(R),Ft=vt==ht||vt==xt;if(qf(R))return hl(R,Qe);if(vt==Bt||vt==Zt||Ft&&!Qt){if(Ue=C||Ft?{}:Oo(R),!Qe)return C?pc(R,Au(Ue,R)):kf(R,fa(Ue,R))}else {if(!Jn[vt])return Qt?R:{};Ue=Bf(R,vt,Qe);}}ye||(ye=new lc);var ne=ye.get(R);if(ne)return ne;ye.set(R,Ue),J3(R)?R.forEach(function(Ye){Ue.add(no(Ye,U,at,Ye,R,ye));}):X3(R)&&R.forEach(function(Ye,on){Ue.set(on,no(Ye,U,at,on,R,ye));});var Re=M?C?Fs:Ls:C?Fh:Hl,je=nt?t:Re(R);return ha(je||R,function(Ye,on){je&&(on=Ye,Ye=R[on]),Ma(Ue,on,no(Ye,U,at,on,R,ye));}),Ue}function oa(R){var U=Hl(R);return function(at){return Ou(at,R,U)}}function Ou(R,U,at){var Nt=at.length;if(R==null)return !Nt;for(R=Ys(R);Nt--;){var Qt=at[Nt],ye=U[Qt],Ue=R[Qt];if(Ue===t&&!(Qt in R)||!ye(Ue))return false}return true}function ju(R,U,at){if(typeof R!="function")throw new Ur(s);return Ih(function(){R.apply(t,at);},U)}function Ja(R,U,at,Nt){var Qt=-1,ye=Oe,Ue=true,Qe=R.length,C=[],M=U.length;if(!Qe)return C;at&&(U=De(U,fr(at))),Nt?(ye=$e,Ue=false):U.length>=n&&(ye=Sr,Ue=false,U=new uc(U));t:for(;++Qt<Qe;){var nt=R[Qt],vt=at==null?nt:at(nt);if(nt=Nt||nt!==0?nt:0,Ue&&vt===vt){for(var Ft=M;Ft--;)if(U[Ft]===vt)continue t;C.push(nt);}else ye(U,vt,Nt)||C.push(nt);}return C}var vo=Rh(Sa),Su=Rh(lu,true);function aa(R,U){var at=true;return vo(R,function(Nt,Qt,ye){return at=!!U(Nt,Qt,ye),at}),at}function jo(R,U,at){for(var Nt=-1,Qt=R.length;++Nt<Qt;){var ye=R[Nt],Ue=U(ye);if(Ue!=null&&(Qe===t?Ue===Ue&&!o0(Ue):at(Ue,Qe)))var Qe=Ue,C=ye;}return C}function nl(R,U,at,Nt){var Qt=R.length;for(at=js(at),at<0&&(at=-at>Qt?0:Qt+at),Nt=Nt===t||Nt>Qt?Qt:js(Nt),Nt<0&&(Nt+=Qt),Nt=at>Nt?0:zf(Nt);at<Nt;)R[at++]=U;return R}function il(R,U){var at=[];return vo(R,function(Nt,Qt,ye){U(Nt,Qt,ye)&&at.push(Nt);}),at}function io(R,U,at,Nt,Qt){var ye=-1,Ue=R.length;for(at||(at=tu),Qt||(Qt=[]);++ye<Ue;){var Qe=R[ye];U>0&&at(Qe)?U>1?io(Qe,U-1,at,Nt,Qt):tr(Qt,Qe):Nt||(Qt[Qt.length]=Qe);}return Qt}var ka=D0(),Oa=D0(true);function Sa(R,U){return R&&ka(R,U,Hl)}function lu(R,U){return R&&Oa(R,U,Hl)}function Io(R,U){return Ne(U,function(at){return bc(R[at])})}function qa(R,U){U=Bl(U,R);for(var at=0,Nt=U.length;R!=null&&at<Nt;)R=R[Ql(U[at++])];return at&&at==Nt?R:t}function sl(R,U,at){var Nt=U(R);return qs(R)?Nt:tr(Nt,at(R))}function Is(R){return R==null?R===t?Kt:Pt:An&&An in Ys(R)?Gu(R):Kf(R)}function cu(R,U){return R>U}function ga(R,U){return R!=null&&Ns.call(R,U)}function pa(R,U){return R!=null&&U in Ys(R)}function hu(R,U,at){return R>=vn(U,at)&&R<_n(U,at)}function Ca(R,U,at){for(var Nt=at?$e:Oe,Qt=R[0].length,ye=R.length,Ue=ye,Qe=Rr(ye),C=1/0,M=[];Ue--;){var nt=R[Ue];Ue&&U&&(nt=De(nt,fr(U))),C=vn(nt.length,C),Qe[Ue]=!at&&(U||Qt>=120&&nt.length>=120)?new uc(Ue&&nt):t;}nt=R[0];var vt=-1,Ft=Qe[0];t:for(;++vt<Qt&&M.length<C;){var ne=nt[vt],Re=U?U(ne):ne;if(ne=at||ne!==0?ne:0,!(Ft?Sr(Ft,Re):Nt(M,Re,at))){for(Ue=ye;--Ue;){var je=Qe[Ue];if(!(je?Sr(je,Re):Nt(R[Ue],Re,at)))continue t}Ft&&Ft.push(Re),M.push(ne);}}return M}function Na(R,U,at,Nt){return Sa(R,function(Qt,ye,Ue){U(Nt,at(Qt),ye,Ue);}),Nt}function Go(R,U,at){U=Bl(U,R),R=vc(R,U);var Nt=R==null?R:R[Ql(Nl(U))];return Nt==null?t:qi(Nt,R,at)}function vi(R){return ul(R)&&Is(R)==Zt}function Wl(R){return ul(R)&&Is(R)==zt}function ud(R){return ul(R)&&Is(R)==ee}function cs(R,U,at,Nt,Qt){return R===U?true:R==null||U==null||!ul(R)&&!ul(U)?R!==R&&U!==U:Uu(R,U,at,Nt,cs,Qt)}function Uu(R,U,at,Nt,Qt,ye){var Ue=qs(R),Qe=qs(U),C=Ue?oe:Eo(R),M=Qe?oe:Eo(U);C=C==Zt?Bt:C,M=M==Zt?Bt:M;var nt=C==Bt,vt=M==Bt,Ft=C==M;if(Ft&&qf(R)){if(!qf(U))return false;Ue=true,nt=false;}if(Ft&&!nt)return ye||(ye=new lc),Ue||zd(R)?Ol(R,U,at,Nt,Qt,ye):cf(R,U,C,at,Nt,Qt,ye);if(!(at&m)){var ne=nt&&Ns.call(R,"__wrapped__"),Re=vt&&Ns.call(U,"__wrapped__");if(ne||Re){var je=ne?R.value():R,Ye=Re?U.value():U;return ye||(ye=new lc),Qt(je,Ye,at,Nt,ye)}}return Ft?(ye||(ye=new lc),Kc(R,U,at,Nt,Qt,ye)):false}function If(R){return ul(R)&&Eo(R)==Tt}function ii(R,U,at,Nt){var Qt=at.length,ye=Qt,Ue=!Nt;if(R==null)return !ye;for(R=Ys(R);Qt--;){var Qe=at[Qt];if(Ue&&Qe[2]?Qe[1]!==R[Qe[0]]:!(Qe[0]in R))return false}for(;++Qt<ye;){Qe=at[Qt];var C=Qe[0],M=R[C],nt=Qe[1];if(Ue&&Qe[2]){if(M===t&&!(C in R))return false}else {var vt=new lc;if(Nt)var Ft=Nt(M,nt,C,R,U,vt);if(!(Ft===t?cs(nt,M,m|u,Nt,vt):Ft))return false}}return true}function zh(R){if(!Wu(R)||Nu(R))return false;var U=bc(R)?Ga:Va;return U.test(sh(R))}function Df(R){return ul(R)&&Is(R)==Ht}function l1(R){return ul(R)&&Eo(R)==Ae}function fo(R){return ul(R)&&H1(R.length)&&!!ts[Is(R)]}function ea(R){return typeof R=="function"?R:R==null?na:typeof R=="object"?qs(R)?cd(R[0],R[1]):ld(R):$x(R)}function cc(R){if(!Uf(R))return hi(R);var U=[];for(var at in Ys(R))Ns.call(R,at)&&at!="constructor"&&U.push(at);return U}function hc(R){if(!Wu(R))return k0(R);var U=Uf(R),at=[];for(var Nt in R)Nt=="constructor"&&(U||!Ns.call(R,Nt))||at.push(Nt);return at}function Vh(R,U){return R<U}function Yh(R,U){var at=-1,Nt=Tc(R)?Rr(R.length):[];return vo(R,function(Qt,ye,Ue){Nt[++at]=U(Qt,ye,Ue);}),Nt}function ld(R){var U=Ka(R);return U.length==1&&U[0][2]?Zs(U[0][0],U[0][1]):function(at){return at===R||ii(at,R,U)}}function cd(R,U){return jf(R)&&al(U)?Zs(Ql(R),U):function(at){var Nt=Y1(at,R);return Nt===t&&Nt===U?Ix(at,R):cs(U,Nt,m|u)}}function N0(R,U,at,Nt,Qt){R!==U&&ka(U,function(ye,Ue){if(Qt||(Qt=new lc),Wu(ye))jd(R,U,Ue,at,N0,Nt,Qt);else {var Qe=Nt?Nt(nh(R,Ue),ye,Ue+"",R,U,Qt):t;Qe===t&&(Qe=ye),Tu(R,Ue,Qe);}},Fh);}function jd(R,U,at,Nt,Qt,ye,Ue){var Qe=nh(R,at),C=nh(U,at),M=Ue.get(C);if(M){Tu(R,at,M);return}var nt=ye?ye(Qe,C,at+"",R,U,Ue):t,vt=nt===t;if(vt){var Ft=qs(C),ne=!Ft&&qf(C),Re=!Ft&&!ne&&zd(C);nt=C,Ft||ne||Re?qs(Qe)?nt=Qe:Vu(Qe)?nt=jl(Qe):ne?(vt=false,nt=hl(C,true)):Re?(vt=false,nt=Al(C,true)):nt=[]:G1(C)||b1(C)?(nt=Qe,b1(Qe)?nt=Ax(Qe):(!Wu(Qe)||bc(Qe))&&(nt=Oo(C))):vt=false;}vt&&(Ue.set(C,nt),Qt(nt,C,Nt,ye,Ue),Ue.delete(C)),Tu(R,at,nt);}function bh(R,U){var at=R.length;if(at)return U+=U<0?at:0,rh(U,at)?R[U]:t}function Xl(R,U,at){U.length?U=De(U,function(ye){return qs(ye)?function(Ue){return qa(Ue,ye.length===1?ye[0]:ye)}:ye}):U=[na];var Nt=-1;U=De(U,fr(zi()));var Qt=Yh(R,function(ye,Ue,Qe){var C=De(U,function(M){return M(ye)});return {criteria:C,index:++Nt,value:ye}});return Wr(Qt,function(ye,Ue){return ns(ye,Ue,at)})}function Wh(R,U){return R0(R,U,function(at,Nt){return Ix(R,Nt)})}function R0(R,U,at){for(var Nt=-1,Qt=U.length,ye={};++Nt<Qt;){var Ue=U[Nt],Qe=qa(R,Ue);at(Qe,Ue)&&Ao(ye,Bl(Ue,R),Qe);}return ye}function fc(R){return function(U){return qa(U,R)}}function w0(R,U,at,Nt){var Qt=Nt?$r:yr,ye=-1,Ue=U.length,Qe=R;for(R===U&&(U=jl(U)),at&&(Qe=De(R,fr(at)));++ye<Ue;)for(var C=0,M=U[ye],nt=at?at(M):M;(C=Qt(Qe,nt,C,Nt))>-1;)Qe!==R&&si.call(Qe,C,1),si.call(R,C,1);return R}function Ah(R,U){for(var at=R?U.length:0,Nt=at-1;at--;){var Qt=U[at];if(at==Nt||Qt!==ye){var ye=Qt;rh(Qt)?si.call(R,Qt,1):bl(R,Qt);}}return R}function sf(R,U){return R+ci(ni()*(U-R+1))}function Lf(R,U,at,Nt){for(var Qt=-1,ye=_n(ui((U-R)/(at||1)),0),Ue=Rr(ye);ye--;)Ue[Nt?ye:++Qt]=R,R+=at;return Ue}function Fa(R,U){var at="";if(!R||U<1||U>pt)return at;do U%2&&(at+=R),U=ci(U/2),U&&(R+=R);while(U);return at}function Yi(R,U){return ih(e0(R,U,na),R+"")}function Ku(R){return rl(nu(R))}function Ra(R,U){var at=nu(R);return F0(at,da(U,0,at.length))}function Ao(R,U,at,Nt){if(!Wu(R))return R;U=Bl(U,R);for(var Qt=-1,ye=U.length,Ue=ye-1,Qe=R;Qe!=null&&++Qt<ye;){var C=Ql(U[Qt]),M=at;if(C==="__proto__"||C==="constructor"||C==="prototype")return R;if(Qt!=Ue){var nt=Qe[C];M=Nt?Nt(nt,C,Qe):t,M===t&&(M=Wu(nt)?nt:rh(U[Qt+1])?[]:{});}Ma(Qe,C,M),Qe=Qe[C];}return R}var dc=di?function(R,U){return di.set(R,U),R}:na,hd=Pc?function(R,U){return Pc(R,"toString",{configurable:true,enumerable:false,value:X1(U),writable:true})}:na;function qo(R){return F0(nu(R))}function Tl(R,U,at){var Nt=-1,Qt=R.length;U<0&&(U=-U>Qt?0:Qt+U),at=at>Qt?Qt:at,at<0&&(at+=Qt),Qt=U>at?0:at-U>>>0,U>>>=0;for(var ye=Rr(Qt);++Nt<Qt;)ye[Nt]=R[Nt+U];return ye}function Ds(R,U){var at;return vo(R,function(Nt,Qt,ye){return at=U(Nt,Qt,ye),!at}),!!at}function Oh(R,U,at){var Nt=0,Qt=R==null?Nt:R.length;if(typeof U=="number"&&U===U&&Qt<=mt){for(;Nt<Qt;){var ye=Nt+Qt>>>1,Ue=R[ye];Ue!==null&&!o0(Ue)&&(at?Ue<=U:Ue<U)?Nt=ye+1:Qt=ye;}return Qt}return Pf(R,U,na,at)}function Pf(R,U,at,Nt){var Qt=0,ye=R==null?0:R.length;if(ye===0)return 0;U=at(U);for(var Ue=U!==U,Qe=U===null,C=o0(U),M=U===t;Qt<ye;){var nt=ci((Qt+ye)/2),vt=at(R[nt]),Ft=vt!==t,ne=vt===null,Re=vt===vt,je=o0(vt);if(Ue)var Ye=Nt||Re;else M?Ye=Re&&(Nt||Ft):Qe?Ye=Re&&Ft&&(Nt||!ne):C?Ye=Re&&Ft&&!ne&&(Nt||!je):ne||je?Ye=false:Ye=Nt?vt<=U:vt<U;Ye?Qt=nt+1:ye=nt;}return vn(ye,bt)}function I0(R,U){for(var at=-1,Nt=R.length,Qt=0,ye=[];++at<Nt;){var Ue=R[at],Qe=U?U(Ue):Ue;if(!at||!uh(Qe,C)){var C=Qe;ye[Qt++]=Ue===0?0:Ue;}}return ye}function Ud(R){return typeof R=="number"?R:o0(R)?dt:+R}function wa(R){if(typeof R=="string")return R;if(qs(R))return De(R,wa)+"";if(o0(R))return oc?oc.call(R):"";var U=R+"";return U=="0"&&1/R==-tt?"-0":U}function Sh(R,U,at){var Nt=-1,Qt=Oe,ye=R.length,Ue=true,Qe=[],C=Qe;if(at)Ue=false,Qt=$e;else if(ye>=n){var M=U?null:md(R);if(M)return Ic(M);Ue=false,Qt=Sr,C=new uc;}else C=U?[]:Qe;t:for(;++Nt<ye;){var nt=R[Nt],vt=U?U(nt):nt;if(nt=at||nt!==0?nt:0,Ue&&vt===vt){for(var Ft=C.length;Ft--;)if(C[Ft]===vt)continue t;U&&C.push(vt),Qe.push(nt);}else Qt(C,vt,at)||(C!==Qe&&C.push(vt),Qe.push(nt));}return Qe}function bl(R,U){U=Bl(U,R);var at=-1,Nt=U.length;if(!Nt)return true;for(var Qt=R==null||typeof R!="object"&&typeof R!="function";++at<Nt;){var ye=U[at];if(typeof ye=="string"){if(ye==="__proto__"&&!Ns.call(R,"__proto__"))return false;if(ye==="constructor"&&at+1<Nt&&typeof U[at+1]=="string"&&U[at+1]==="prototype"){if(Qt&&at===0)continue;return false}}}var Ue=vc(R,U);return Ue==null||delete Ue[Ql(Nl(U))]}function kc(R,U,at,Nt){return Ao(R,U,at(qa(R,U)),Nt)}function Ch(R,U,at,Nt){for(var Qt=R.length,ye=Nt?Qt:-1;(Nt?ye--:++ye<Qt)&&U(R[ye],ye,R););return at?Tl(R,Nt?0:ye,Nt?ye+1:Qt):Tl(R,Nt?ye+1:0,Nt?Qt:ye)}function fd(R,U){var at=R;return at instanceof Gs&&(at=at.value()),dr(U,function(Nt,Qt){return Qt.func.apply(Qt.thisArg,tr([Nt],Qt.args))},at)}function Fc(R,U,at){var Nt=R.length;if(Nt<2)return Nt?Sh(R[0]):[];for(var Qt=-1,ye=Rr(Nt);++Qt<Nt;)for(var Ue=R[Qt],Qe=-1;++Qe<Nt;)Qe!=Qt&&(ye[Qt]=Ja(ye[Qt]||Ue,R[Qe],U,at));return Sh(io(ye,1),U,at)}function Xh(R,U,at){for(var Nt=-1,Qt=R.length,ye=U.length,Ue={};++Nt<Qt;){var Qe=Nt<ye?U[Nt]:t;at(Ue,R[Nt],Qe);}return Ue}function Ba(R){return Vu(R)?R:[]}function $u(R){return typeof R=="function"?R:na}function Bl(R,U){return qs(R)?R:jf(R,U)?[R]:$d(ya(R))}var c1=Yi;function Bc(R,U,at){var Nt=R.length;return at=at===t?Nt:at,!U&&at>=Nt?R:Tl(R,U,at)}var Kd=On||function(R){return $n.clearTimeout(R)};function hl(R,U){if(U)return R.slice();var at=R.length,Nt=rf?rf(at):new R.constructor(at);return R.copy(Nt),Nt}function dd(R){var U=new R.constructor(R.byteLength);return new el(U).set(new el(R)),U}function Mf(R,U){var at=U?dd(R.buffer):R.buffer;return new R.constructor(at,R.byteOffset,R.byteLength)}function of(R){var U=new R.constructor(R.source,Ju.exec(R));return U.lastIndex=R.lastIndex,U}function Za(R){return Ai?Ys(Ai.call(R)):{}}function Al(R,U){var at=U?dd(R.buffer):R.buffer;return new R.constructor(at,R.byteOffset,R.length)}function ja(R,U){if(R!==U){var at=R!==t,Nt=R===null,Qt=R===R,ye=o0(R),Ue=U!==t,Qe=U===null,C=U===U,M=o0(U);if(!Qe&&!M&&!ye&&R>U||ye&&Ue&&C&&!Qe&&!M||Nt&&Ue&&C||!at&&C||!Qt)return 1;if(!Nt&&!ye&&!M&&R<U||M&&at&&Qt&&!Nt&&!ye||Qe&&at&&Qt||!Ue&&Qt||!C)return -1}return 0}function ns(R,U,at){for(var Nt=-1,Qt=R.criteria,ye=U.criteria,Ue=Qt.length,Qe=at.length;++Nt<Ue;){var C=ja(Qt[Nt],ye[Nt]);if(C){if(Nt>=Qe)return C;var M=at[Nt];return C*(M=="desc"?-1:1)}}return R.index-U.index}function Qh(R,U,at,Nt){for(var Qt=-1,ye=R.length,Ue=at.length,Qe=-1,C=U.length,M=_n(ye-Ue,0),nt=Rr(C+M),vt=!Nt;++Qe<C;)nt[Qe]=U[Qe];for(;++Qt<Ue;)(vt||Qt<ye)&&(nt[at[Qt]]=R[Qt]);for(;M--;)nt[Qe++]=R[Qt++];return nt}function Nh(R,U,at,Nt){for(var Qt=-1,ye=R.length,Ue=-1,Qe=at.length,C=-1,M=U.length,nt=_n(ye-Qe,0),vt=Rr(nt+M),Ft=!Nt;++Qt<nt;)vt[Qt]=R[Qt];for(var ne=Qt;++C<M;)vt[ne+C]=U[C];for(;++Ue<Qe;)(Ft||Qt<ye)&&(vt[ne+at[Ue]]=R[Qt++]);return vt}function jl(R,U){var at=-1,Nt=R.length;for(U||(U=Rr(Nt));++at<Nt;)U[at]=R[at];return U}function Zc(R,U,at,Nt){var Qt=!at;at||(at={});for(var ye=-1,Ue=U.length;++ye<Ue;){var Qe=U[ye],C=Nt?Nt(at[Qe],R[Qe],Qe,at,R):t;C===t&&(C=R[Qe]),Qt?Bo(at,Qe,C):Ma(at,Qe,C);}return at}function kf(R,U){return Zc(R,Zh(R),U)}function pc(R,U){return Zc(R,Hc(R),U)}function xc(R,U){return function(at,Nt){var Qt=qs(at)?ca:ta,ye=U?U():{};return Qt(at,R,zi(Nt,2),ye)}}function mc(R){return Yi(function(U,at){var Nt=-1,Qt=at.length,ye=Qt>1?at[Qt-1]:t,Ue=Qt>2?at[2]:t;for(ye=R.length>3&&typeof ye=="function"?(Qt--,ye):t,Ue&&Cu(at[0],at[1],Ue)&&(ye=Qt<3?t:ye,Qt=1),U=Ys(U);++Nt<Qt;){var Qe=at[Nt];Qe&&R(U,Qe,Nt,ye);}return U})}function Rh(R,U){return function(at,Nt){if(at==null)return at;if(!Tc(at))return R(at,Nt);for(var Qt=at.length,ye=U?Qt:-1,Ue=Ys(at);(U?ye--:++ye<Qt)&&Nt(Ue[ye],ye,Ue)!==false;);return at}}function D0(R){return function(U,at,Nt){for(var Qt=-1,ye=Ys(U),Ue=Nt(U),Qe=Ue.length;Qe--;){var C=Ue[R?Qe:++Qt];if(at(ye[C],C,ye)===false)break}return U}}function fl(R,U,at){var Nt=U&l,Qt=af(R);function ye(){var Ue=this&&this!==$n&&this instanceof ye?Qt:R;return Ue.apply(Nt?at:this,arguments)}return ye}function Ul(R){return function(U){U=ya(U);var at=ir(U)?ro(U):t,Nt=at?at[0]:U.charAt(0),Qt=at?Bc(at,1).join(""):U.slice(1);return Nt[R]()+Qt}}function L0(R){return function(U){return dr(S1(Yf(U).replace(Ei,"")),R,"")}}function af(R){return function(){var U=arguments;switch(U.length){case 0:return new R;case 1:return new R(U[0]);case 2:return new R(U[0],U[1]);case 3:return new R(U[0],U[1],U[2]);case 4:return new R(U[0],U[1],U[2],U[3]);case 5:return new R(U[0],U[1],U[2],U[3],U[4]);case 6:return new R(U[0],U[1],U[2],U[3],U[4],U[5]);case 7:return new R(U[0],U[1],U[2],U[3],U[4],U[5],U[6])}var at=Yl(R.prototype),Nt=R.apply(at,U);return Wu(Nt)?Nt:at}}function pd(R,U,at){var Nt=af(R);function Qt(){for(var ye=arguments.length,Ue=Rr(ye),Qe=ye,C=Ua(Qt);Qe--;)Ue[Qe]=arguments[Qe];var M=ye<3&&Ue[0]!==C&&Ue[ye-1]!==C?[]:We(Ue,C);if(ye-=M.length,ye<at)return yc(R,U,th,Qt.placeholder,t,Ue,M,t,t,at-ye);var nt=this&&this!==$n&&this instanceof Qt?Nt:R;return qi(nt,this,Ue)}return Qt}function gc(R){return function(U,at,Nt){var Qt=Ys(U);if(!Tc(U)){var ye=zi(at,3);U=Hl(U),at=function(Qe){return ye(Qt[Qe],Qe,Qt)};}var Ue=R(U,at,Nt);return Ue>-1?Qt[ye?U[Ue]:Ue]:t}}function uf(R){return ao(function(U){var at=U.length,Nt=at,Qt=El.prototype.thru;for(R&&U.reverse();Nt--;){var ye=U[Nt];if(typeof ye!="function")throw new Ur(s);if(Qt&&!Ue&&eh(ye)=="wrapper")var Ue=new El([],true);}for(Nt=Ue?Nt:at;++Nt<at;){ye=U[Nt];var Qe=eh(ye),C=Qe=="wrapper"?hf(ye):t;C&&wh(C[0])&&C[1]==(v|d|_|T)&&!C[4].length&&C[9]==1?Ue=Ue[eh(C[0])].apply(Ue,C[3]):Ue=ye.length==1&&wh(ye)?Ue[Qe]():Ue.thru(ye);}return function(){var M=arguments,nt=M[0];if(Ue&&M.length==1&&qs(nt))return Ue.plant(nt).value();for(var vt=0,Ft=at?U[vt].apply(this,M):nt;++vt<at;)Ft=U[vt].call(this,Ft);return Ft}})}function th(R,U,at,Nt,Qt,ye,Ue,Qe,C,M){var nt=U&v,vt=U&l,Ft=U&a,ne=U&(d|g),Re=U&G,je=Ft?t:af(R);function Ye(){for(var on=arguments.length,an=Rr(on),Dn=on;Dn--;)an[Dn]=arguments[Dn];if(ne)var li=Ua(Ye),Ui=lr(an,li);if(Nt&&(an=Qh(an,Nt,Qt,ne)),ye&&(an=Nh(an,ye,Ue,ne)),on-=Ui,ne&&on<M){var Ki=We(an,li);return yc(R,U,th,Ye.placeholder,at,an,Ki,Qe,C,M-on)}var Ss=vt?at:this,es=Ft?Ss[R]:R;return on=an.length,Qe?an=r0(an,Qe):Re&&on>1&&an.reverse(),nt&&C<on&&(an.length=C),this&&this!==$n&&this instanceof Ye&&(es=je||af(es)),es.apply(Ss,an)}return Ye}function h1(R,U){return function(at,Nt){return Na(at,R,U(Nt),{})}}function Jh(R,U){return function(at,Nt){var Qt;if(at===t&&Nt===t)return U;if(at!==t&&(Qt=at),Nt!==t){if(Qt===t)return Nt;typeof at=="string"||typeof Nt=="string"?(at=wa(at),Nt=wa(Nt)):(at=Ud(at),Nt=Ud(Nt)),Qt=R(at,Nt);}return Qt}}function jc(R){return ao(function(U){return U=De(U,fr(zi())),Yi(function(at){var Nt=this;return R(U,function(Qt){return qi(Qt,Nt,at)})})})}function dl(R,U){U=U===t?" ":wa(U);var at=U.length;if(at<2)return at?Fa(U,R):U;var Nt=Fa(U,ui(R/yo(U)));return ir(U)?Bc(ro(Nt),0,R).join(""):Nt.slice(0,R)}function Uc(R,U,at,Nt){var Qt=U&l,ye=af(R);function Ue(){for(var Qe=-1,C=arguments.length,M=-1,nt=Nt.length,vt=Rr(nt+C),Ft=this&&this!==$n&&this instanceof Ue?ye:R;++M<nt;)vt[M]=Nt[M];for(;C--;)vt[M++]=arguments[++Qe];return qi(Ft,Qt?at:this,vt)}return Ue}function xd(R){return function(U,at,Nt){return Nt&&typeof Nt!="number"&&Cu(U,at,Nt)&&(at=Nt=t),U=Ru(U),at===t?(at=U,U=0):at=Ru(at),Nt=Nt===t?U<at?1:-1:Ru(Nt),Lf(U,at,Nt,R)}}function Ff(R){return function(U,at){return typeof U=="string"&&typeof at=="string"||(U=a0(U),at=a0(at)),R(U,at)}}function yc(R,U,at,Nt,Qt,ye,Ue,Qe,C,M){var nt=U&d,vt=nt?Ue:t,Ft=nt?t:Ue,ne=nt?ye:t,Re=nt?t:ye;U|=nt?_:S,U&=~(nt?S:_),U&h||(U&=-4);var je=[R,U,Qt,ne,vt,Re,Ft,Qe,C,M],Ye=at.apply(t,je);return wh(R)&&Ec(Ye,je),Ye.placeholder=Nt,Gc(Ye,R,U)}function Ts(R){var U=vu[R];return function(at,Nt){if(at=a0(at),Nt=Nt==null?0:vn(js(Nt),292),Nt&&_i(at)){var Qt=(ya(at)+"e").split("e"),ye=U(Qt[0]+"e"+(+Qt[1]+Nt));return Qt=(ya(ye)+"e").split("e"),+(Qt[0]+"e"+(+Qt[1]-Nt))}return U(at)}}var md=Nn&&1/Ic(new Nn([,-0]))[1]==tt?function(R){return new Nn(R)}:wu;function Hu(R){return function(U){var at=Eo(U);return at==Tt?zr(U):at==Ae?Jc(U):Ir(U,R(U))}}function Js(R,U,at,Nt,Qt,ye,Ue,Qe){var C=U&a;if(!C&&typeof R!="function")throw new Ur(s);var M=Nt?Nt.length:0;if(M||(U&=-97,Nt=Qt=t),Ue=Ue===t?Ue:_n(js(Ue),0),Qe=Qe===t?Qe:js(Qe),M-=Qt?Qt.length:0,U&S){var nt=Nt,vt=Qt;Nt=Qt=t;}var Ft=C?t:hf(R),ne=[R,U,at,Nt,Qt,nt,vt,ye,Ue,Qe];if(Ft&&gd(ne,Ft),R=ne[0],U=ne[1],at=ne[2],Nt=ne[3],Qt=ne[4],Qe=ne[9]=ne[9]===t?C?0:R.length:_n(ne[9]-M,0),!Qe&&U&(d|g)&&(U&=-25),!U||U==l)var Re=fl(R,U,at);else U==d||U==g?Re=pd(R,U,Qe):(U==_||U==(l|_))&&!Qt.length?Re=Uc(R,U,at,Nt):Re=th.apply(t,ne);var je=Ft?dc:Ec;return Gc(je(Re,ne),R,U)}function Xi(R,U,at,Nt){return R===t||uh(R,At[at])&&!Ns.call(Nt,at)?U:R}function pl(R,U,at,Nt,Qt,ye){return Wu(R)&&Wu(U)&&(ye.set(U,R),N0(R,U,t,pl,ye),ye.delete(U)),R}function lf(R){return G1(R)?t:R}function Ol(R,U,at,Nt,Qt,ye){var Ue=at&m,Qe=R.length,C=U.length;if(Qe!=C&&!(Ue&&C>Qe))return false;var M=ye.get(R),nt=ye.get(U);if(M&&nt)return M==U&&nt==R;var vt=-1,Ft=true,ne=at&u?new uc:t;for(ye.set(R,U),ye.set(U,R);++vt<Qe;){var Re=R[vt],je=U[vt];if(Nt)var Ye=Ue?Nt(je,Re,vt,U,R,ye):Nt(Re,je,vt,R,U,ye);if(Ye!==t){if(Ye)continue;Ft=false;break}if(ne){if(!_r(U,function(on,an){if(!Sr(ne,an)&&(Re===on||Qt(Re,on,at,Nt,ye)))return ne.push(an)})){Ft=false;break}}else if(!(Re===je||Qt(Re,je,at,Nt,ye))){Ft=false;break}}return ye.delete(R),ye.delete(U),Ft}function cf(R,U,at,Nt,Qt,ye,Ue){switch(at){case Le:if(R.byteLength!=U.byteLength||R.byteOffset!=U.byteOffset)return false;R=R.buffer,U=U.buffer;case zt:return !(R.byteLength!=U.byteLength||!ye(new el(R),new el(U)));case Se:case ee:case Lt:return uh(+R,+U);case Et:return R.name==U.name&&R.message==U.message;case Ht:case kt:return R==U+"";case Tt:var Qe=zr;case Ae:var C=Nt&m;if(Qe||(Qe=Ic),R.size!=U.size&&!C)return false;var M=Ue.get(R);if(M)return M==U;Nt|=u,Ue.set(R,U);var nt=Ol(Qe(R),Qe(U),Nt,Qt,ye,Ue);return Ue.delete(R),nt;case jt:if(Ai)return Ai.call(R)==Ai.call(U)}return false}function Kc(R,U,at,Nt,Qt,ye){var Ue=at&m,Qe=Ls(R),C=Qe.length,M=Ls(U),nt=M.length;if(C!=nt&&!Ue)return false;for(var vt=C;vt--;){var Ft=Qe[vt];if(!(Ue?Ft in U:Ns.call(U,Ft)))return false}var ne=ye.get(R),Re=ye.get(U);if(ne&&Re)return ne==U&&Re==R;var je=true;ye.set(R,U),ye.set(U,R);for(var Ye=Ue;++vt<C;){Ft=Qe[vt];var on=R[Ft],an=U[Ft];if(Nt)var Dn=Ue?Nt(an,on,Ft,U,R,ye):Nt(on,an,Ft,R,U,ye);if(!(Dn===t?on===an||Qt(on,an,at,Nt,ye):Dn)){je=false;break}Ye||(Ye=Ft=="constructor");}if(je&&!Ye){var li=R.constructor,Ui=U.constructor;li!=Ui&&"constructor"in R&&"constructor"in U&&!(typeof li=="function"&&li instanceof li&&typeof Ui=="function"&&Ui instanceof Ui)&&(je=false);}return ye.delete(R),ye.delete(U),je}function ao(R){return ih(e0(R,t,df),R+"")}function Ls(R){return sl(R,Hl,Zh)}function Fs(R){return sl(R,Fh,Hc)}var hf=di?function(R){return di.get(R)}:wu;function eh(R){for(var U=R.name+"",at=gi[U],Nt=Ns.call(gi,U)?at.length:0;Nt--;){var Qt=at[Nt],ye=Qt.func;if(ye==null||ye==R)return Qt.name}return U}function Ua(R){var U=Ns.call(he,"placeholder")?he:R;return U.placeholder}function zi(){var R=he.iteratee||Np;return R=R===Np?ea:R,arguments.length?R(arguments[0],arguments[1]):R}function $c(R,U){var at=R.__data__;return ol(U)?at[typeof U=="string"?"string":"hash"]:at.map}function Ka(R){for(var U=Hl(R),at=U.length;at--;){var Nt=U[at],Qt=R[Nt];U[at]=[Nt,Qt,al(Qt)];}return U}function Ia(R,U){var at=Fr(R,U);return zh(at)?at:t}function Gu(R){var U=Ns.call(R,An),at=R[An];try{R[An]=t;var Nt=!0;}catch{}var Qt=Mu.call(R);return Nt&&(U?R[An]=at:delete R[An]),Qt}var Zh=Hn?function(R){return R==null?[]:(R=Ys(R),Ne(Hn(R),function(U){return Oi.call(R,U)}))}:C2,Hc=Hn?function(R){for(var U=[];R;)tr(U,Zh(R)),R=sc(R);return U}:C2,Eo=Is;(Pn&&Eo(new Pn(new ArrayBuffer(1)))!=Le||En&&Eo(new En)!=Tt||bn&&Eo(bn.resolve())!=re||Nn&&Eo(new Nn)!=Ae||Ti&&Eo(new Ti)!=$t)&&(Eo=function(R){var U=Is(R),at=U==Bt?R.constructor:t,Nt=at?sh(at):"";if(Nt)switch(Nt){case yi:return Le;case xi:return Tt;case bi:return re;case Ni:return Ae;case Si:return $t}return U});function Qn(R,U,at){for(var Nt=-1,Qt=at.length;++Nt<Qt;){var ye=at[Nt],Ue=ye.size;switch(ye.type){case "drop":R+=Ue;break;case "dropRight":U-=Ue;break;case "take":U=vn(U,R+Ue);break;case "takeRight":R=_n(R,U-Ue);break}}return {start:R,end:U}}function P0(R){var U=R.match(Mo);return U?U[1].split(gu):[]}function xl(R,U,at){U=Bl(U,R);for(var Nt=-1,Qt=U.length,ye=false;++Nt<Qt;){var Ue=Ql(U[Nt]);if(!(ye=R!=null&&at(R,Ue)))break;R=R[Ue];}return ye||++Nt!=Qt?ye:(Qt=R==null?0:R.length,!!Qt&&H1(Qt)&&rh(Ue,Qt)&&(qs(R)||b1(R)))}function t0(R){var U=R.length,at=new R.constructor(U);return U&&typeof R[0]=="string"&&Ns.call(R,"index")&&(at.index=R.index,at.input=R.input),at}function Oo(R){return typeof R.constructor=="function"&&!Uf(R)?Yl(sc(R)):{}}function Bf(R,U,at){var Nt=R.constructor;switch(U){case zt:return dd(R);case Se:case ee:return new Nt(+R);case Le:return Mf(R,at);case ie:case gr:case wn:case ri:case Fn:case He:case Ge:case Xr:case Gn:return Al(R,at);case Tt:return new Nt;case Lt:case kt:return new Nt(R);case Ht:return of(R);case Ae:return new Nt;case jt:return Za(R)}}function M0(R,U){var at=U.length;if(!at)return R;var Nt=at-1;return U[Nt]=(at>1?"& ":"")+U[Nt],U=U.join(at>2?", ":" "),R.replace(_a,`{
1918
1918
  /* [wrapped with `+U+`] */
1919
1919
  `)}function tu(R){return qs(R)||b1(R)||!!(hn&&R&&R[hn])}function rh(R,U){var at=typeof R;return U=U??pt,!!U&&(at=="number"||at!="symbol"&&wo.test(R))&&R>-1&&R%1==0&&R<U}function Cu(R,U,at){if(!Wu(at))return false;var Nt=typeof U;return (Nt=="number"?Tc(at)&&rh(U,at.length):Nt=="string"&&U in at)?uh(at[U],R):false}function jf(R,U){if(qs(R))return false;var at=typeof R;return at=="number"||at=="symbol"||at=="boolean"||R==null||o0(R)?true:Ri.test(R)||!$i.test(R)||U!=null&&R in Ys(U)}function ol(R){var U=typeof R;return U=="string"||U=="number"||U=="symbol"||U=="boolean"?R!=="__proto__":R===null}function wh(R){var U=eh(R),at=he[U];if(typeof at!="function"||!(U in Gs.prototype))return false;if(R===at)return true;var Nt=hf(at);return !!Nt&&R===Nt[0]}function Nu(R){return !!Jo&&Jo in R}var f1=$o?bc:N2;function Uf(R){var U=R&&R.constructor,at=typeof U=="function"&&U.prototype||At;return R===at}function al(R){return R===R&&!Wu(R)}function Zs(R,U){return function(at){return at==null?false:at[R]===U&&(U!==t||R in Ys(at))}}function eu(R){var U=E1(R,function(Nt){return at.size===o&&at.clear(),Nt}),at=U.cache;return U}function gd(R,U){var at=R[1],Nt=U[1],Qt=at|Nt,ye=Qt<(l|a|v),Ue=Nt==v&&at==d||Nt==v&&at==T&&R[7].length<=U[8]||Nt==(v|T)&&U[7].length<=U[8]&&at==d;if(!(ye||Ue))return R;Nt&l&&(R[2]=U[2],Qt|=at&l?0:h);var Qe=U[3];if(Qe){var C=R[3];R[3]=C?Qh(C,Qe,U[4]):Qe,R[4]=C?We(R[3],p):U[4];}return Qe=U[5],Qe&&(C=R[5],R[5]=C?Nh(C,Qe,U[6]):Qe,R[6]=C?We(R[5],p):U[6]),Qe=U[7],Qe&&(R[7]=Qe),Nt&v&&(R[8]=R[8]==null?U[8]:vn(R[8],U[8])),R[9]==null&&(R[9]=U[9]),R[0]=U[0],R[1]=Qt,R}function k0(R){var U=[];if(R!=null)for(var at in Ys(R))U.push(at);return U}function Kf(R){return Mu.call(R)}function e0(R,U,at){return U=_n(U===t?R.length-1:U,0),function(){for(var Nt=arguments,Qt=-1,ye=_n(Nt.length-U,0),Ue=Rr(ye);++Qt<ye;)Ue[Qt]=Nt[U+Qt];Qt=-1;for(var Qe=Rr(U+1);++Qt<U;)Qe[Qt]=Nt[Qt];return Qe[U]=at(Ue),qi(R,this,Qe)}}function vc(R,U){return U.length<2?R:qa(R,Tl(U,0,-1))}function r0(R,U){for(var at=R.length,Nt=vn(U.length,at),Qt=jl(R);Nt--;){var ye=U[Nt];R[Nt]=rh(ye,at)?Qt[ye]:t;}return R}function nh(R,U){if(!(U==="constructor"&&typeof R[U]=="function")&&U!="__proto__")return R[U]}var Ec=n0(dc),Ih=Bn||function(R,U){return $n.setTimeout(R,U)},ih=n0(hd);function Gc(R,U,at){var Nt=U+"";return ih(R,M0(Nt,i0(P0(Nt),at)))}function n0(R){var U=0,at=0;return function(){var Nt=Kn(),Qt=J-(Nt-at);if(at=Nt,Qt>0){if(++U>=B)return arguments[0]}else U=0;return R.apply(t,arguments)}}function F0(R,U){var at=-1,Nt=R.length,Qt=Nt-1;for(U=U===t?Nt:U;++at<U;){var ye=sf(at,Qt),Ue=R[ye];R[ye]=R[at],R[at]=Ue;}return R.length=U,R}var $d=eu(function(R){var U=[];return R.charCodeAt(0)===46&&U.push(""),R.replace(ps,function(at,Nt,Qt,ye){U.push(Qt?ye.replace(Ta,"$1"):Nt||at);}),U});function Ql(R){if(typeof R=="string"||o0(R))return R;var U=R+"";return U=="0"&&1/R==-tt?"-0":U}function sh(R){if(R!=null){try{return Ks.call(R)}catch{}try{return R+""}catch{}}return ""}function i0(R,U){return ha(St,function(at){var Nt="_."+at[0];U&at[1]&&!Oe(R,Nt)&&R.push(Nt);}),R.sort()}function qu(R){if(R instanceof Gs)return R.clone();var U=new El(R.__wrapped__,R.__chain__);return U.__actions__=jl(R.__actions__),U.__index__=R.__index__,U.__values__=R.__values__,U}function yd(R,U,at){(at?Cu(R,U,at):U===t)?U=1:U=_n(js(U),0);var Nt=R==null?0:R.length;if(!Nt||U<1)return [];for(var Qt=0,ye=0,Ue=Rr(ui(Nt/U));Qt<Nt;)Ue[ye++]=Tl(R,Qt,Qt+=U);return Ue}function vd(R){for(var U=-1,at=R==null?0:R.length,Nt=0,Qt=[];++U<at;){var ye=R[U];ye&&(Qt[Nt++]=ye);}return Qt}function $f(){var R=arguments.length;if(!R)return [];for(var U=Rr(R-1),at=arguments[0],Nt=R;Nt--;)U[Nt-1]=arguments[Nt];return tr(qs(at)?jl(at):[at],io(U,1))}var B0=Yi(function(R,U){return Vu(R)?Ja(R,io(U,1,Vu,true)):[]}),Sl=Yi(function(R,U){var at=Nl(U);return Vu(at)&&(at=t),Vu(R)?Ja(R,io(U,1,Vu,true),zi(at,2)):[]}),_c=Yi(function(R,U){var at=Nl(U);return Vu(at)&&(at=t),Vu(R)?Ja(R,io(U,1,Vu,true),t,at):[]});function Cl(R,U,at){var Nt=R==null?0:R.length;return Nt?(U=at||U===t?1:js(U),Tl(R,U<0?0:U,Nt)):[]}function Hf(R,U,at){var Nt=R==null?0:R.length;return Nt?(U=at||U===t?1:js(U),U=Nt-U,Tl(R,0,U<0?0:U)):[]}function d1(R,U){return R&&R.length?Ch(R,zi(U,3),true,true):[]}function p1(R,U){return R&&R.length?Ch(R,zi(U,3),true):[]}function Hd(R,U,at,Nt){var Qt=R==null?0:R.length;return Qt?(at&&typeof at!="number"&&Cu(R,U,at)&&(at=0,Nt=Qt),nl(R,U,at,Nt)):[]}function Gf(R,U,at){var Nt=R==null?0:R.length;if(!Nt)return -1;var Qt=at==null?0:js(at);return Qt<0&&(Qt=_n(Nt+Qt,0)),Or(R,zi(U,3),Qt)}function ff(R,U,at){var Nt=R==null?0:R.length;if(!Nt)return -1;var Qt=Nt-1;return at!==t&&(Qt=js(at),Qt=at<0?_n(Nt+Qt,0):vn(Qt,Nt-1)),Or(R,zi(U,3),Qt,true)}function df(R){var U=R==null?0:R.length;return U?io(R,1):[]}function Dh(R){var U=R==null?0:R.length;return U?io(R,tt):[]}function oh(R,U){var at=R==null?0:R.length;return at?(U=U===t?1:js(U),io(R,U)):[]}function pf(R){for(var U=-1,at=R==null?0:R.length,Nt={};++U<at;){var Qt=R[U];Nt[Qt[0]]=Qt[1];}return Nt}function xf(R){return R&&R.length?R[0]:t}function j0(R,U,at){var Nt=R==null?0:R.length;if(!Nt)return -1;var Qt=at==null?0:js(at);return Qt<0&&(Qt=_n(Nt+Qt,0)),yr(R,U,Qt)}function U0(R){var U=R==null?0:R.length;return U?Tl(R,0,-1):[]}var Ed=Yi(function(R){var U=De(R,Ba);return U.length&&U[0]===R[0]?Ca(U):[]}),_d=Yi(function(R){var U=Nl(R),at=De(R,Ba);return U===Nl(at)?U=t:at.pop(),at.length&&at[0]===R[0]?Ca(at,zi(U,2)):[]}),x1=Yi(function(R){var U=Nl(R),at=De(R,Ba);return U=typeof U=="function"?U:t,U&&at.pop(),at.length&&at[0]===R[0]?Ca(at,t,U):[]});function Gd(R,U){return R==null?"":Bi.call(R,U)}function Nl(R){var U=R==null?0:R.length;return U?R[U-1]:t}function K0(R,U,at){var Nt=R==null?0:R.length;if(!Nt)return -1;var Qt=Nt;return at!==t&&(Qt=js(at),Qt=Qt<0?_n(Nt+Qt,0):vn(Qt,Nt-1)),U===U?tf(R,U,Qt):Or(R,Gr,Qt,true)}function Lh(R,U){return R&&R.length?bh(R,js(U)):t}var mf=Yi(I);function I(R,U){return R&&R.length&&U&&U.length?w0(R,U):R}function Y(R,U,at){return R&&R.length&&U&&U.length?w0(R,U,zi(at,2)):R}function ft(R,U,at){return R&&R.length&&U&&U.length?w0(R,U,t,at):R}var wt=ao(function(R,U){var at=R==null?0:R.length,Nt=Bu(R,U);return Ah(R,De(U,function(Qt){return rh(Qt,at)?+Qt:Qt}).sort(ja)),Nt});function Xt(R,U){var at=[];if(!(R&&R.length))return at;var Nt=-1,Qt=[],ye=R.length;for(U=zi(U,3);++Nt<ye;){var Ue=R[Nt];U(Ue,Nt,R)&&(at.push(Ue),Qt.push(Nt));}return Ah(R,Qt),at}function _e(R){return R==null?R:Zn.call(R)}function qe(R,U,at){var Nt=R==null?0:R.length;return Nt?(at&&typeof at!="number"&&Cu(R,U,at)?(U=0,at=Nt):(U=U==null?0:js(U),at=at===t?Nt:js(at)),Tl(R,U,at)):[]}function nr(R,U){return Oh(R,U)}function Lr(R,U,at){return Pf(R,U,zi(at,2))}function Rn(R,U){var at=R==null?0:R.length;if(at){var Nt=Oh(R,U);if(Nt<at&&uh(R[Nt],U))return Nt}return -1}function Sn(R,U){return Oh(R,U,true)}function Vn(R,U,at){return Pf(R,U,zi(at,2),true)}function ji(R,U){var at=R==null?0:R.length;if(at){var Nt=Oh(R,U,true)-1;if(uh(R[Nt],U))return Nt}return -1}function Hi(R){return R&&R.length?I0(R):[]}function Ji(R,U){return R&&R.length?I0(R,zi(U,2)):[]}function In(R){var U=R==null?0:R.length;return U?Tl(R,1,U):[]}function ai(R,U,at){return R&&R.length?(U=at||U===t?1:js(U),Tl(R,0,U<0?0:U)):[]}function Qi(R,U,at){var Nt=R==null?0:R.length;return Nt?(U=at||U===t?1:js(U),U=Nt-U,Tl(R,U<0?0:U,Nt)):[]}function Ii(R,U){return R&&R.length?Ch(R,zi(U,3),false,true):[]}function ds(R,U){return R&&R.length?Ch(R,zi(U,3)):[]}var vs=Yi(function(R){return Sh(io(R,1,Vu,true))}),Ps=Yi(function(R){var U=Nl(R);return Vu(U)&&(U=t),Sh(io(R,1,Vu,true),zi(U,2))}),xn=Yi(function(R){var U=Nl(R);return U=typeof U=="function"?U:t,Sh(io(R,1,Vu,true),t,U)});function jn(R){return R&&R.length?Sh(R):[]}function It(R,U){return R&&R.length?Sh(R,zi(U,2)):[]}function hs(R,U){return U=typeof U=="function"?U:t,R&&R.length?Sh(R,t,U):[]}function st(R){if(!(R&&R.length))return [];var U=0;return R=Ne(R,function(at){if(Vu(at))return U=_n(at.length,U),true}),Pr(U,function(at){return De(R,Vr(at))})}function Ms(R,U){if(!(R&&R.length))return [];var at=st(R);return U==null?at:De(at,function(Nt){return qi(U,t,Nt)})}var ot=Yi(function(R,U){return Vu(R)?Ja(R,U):[]}),fu=Yi(function(R){return Fc(Ne(R,Vu))}),Kl=Yi(function(R){var U=Nl(R);return Vu(U)&&(U=t),Fc(Ne(R,Vu),zi(U,2))}),po=Yi(function(R){var U=Nl(R);return U=typeof U=="function"?U:t,Fc(Ne(R,Vu),t,U)}),$a=Yi(st);function Jl(R,U){return Xh(R||[],U||[],Ma)}function ah(R,U){return Xh(R||[],U||[],Ao)}var Do=Yi(function(R){var U=R.length,at=U>1?R[U-1]:t;return at=typeof at=="function"?(R.pop(),at):t,Ms(R,at)});function ml(R){var U=he(R);return U.__chain__=true,U}function Rl(R,U){return U(R),R}function zu(R,U){return U(R)}var $0=ao(function(R){var U=R.length,at=U?R[0]:0,Nt=this.__wrapped__,Qt=function(ye){return Bu(ye,R)};return U>1||this.__actions__.length||!(Nt instanceof Gs)||!rh(at)?this.thru(Qt):(Nt=Nt.slice(at,+at+(U?1:0)),Nt.__actions__.push({func:zu,args:[Qt],thisArg:t}),new El(Nt,this.__chain__).thru(function(ye){return U&&!ye.length&&ye.push(t),ye}))});function s0(){return ml(this)}function Ph(){return new El(this.value(),this.__chain__)}function to(){this.__values__===t&&(this.__values__=Vd(this.value()));var R=this.__index__>=this.__values__.length,U=R?t:this.__values__[this.__index__++];return {done:R,value:U}}function Zl(){return this}function wl(R){for(var U,at=this;at instanceof _h;){var Nt=qu(at);Nt.__index__=0,Nt.__values__=t,U?Qt.__wrapped__=Nt:U=Nt;var Qt=Nt;at=at.__wrapped__;}return Qt.__wrapped__=R,U}function $l(){var R=this.__wrapped__;if(R instanceof Gs){var U=R;return this.__actions__.length&&(U=new Gs(this)),U=U.reverse(),U.__actions__.push({func:zu,args:[_e],thisArg:t}),new El(U,this.__chain__)}return this.thru(_e)}function Mh(){return fd(this.__wrapped__,this.__actions__)}var pp=xc(function(R,U,at){Ns.call(R,at)?++R[at]:Bo(R,at,1);});function qd(R,U,at){var Nt=qs(R)?be:aa;return at&&Cu(R,U,at)&&(U=t),Nt(R,zi(U,3))}function P1(R,U){var at=qs(R)?Ne:il;return at(R,zi(U,3))}var gf=gc(Gf),Xp=gc(ff);function M1(R,U){return io(mp(R,U),1)}function m1(R,U){return io(mp(R,U),tt)}function g1(R,U,at){return at=at===t?1:js(at),io(mp(R,U),at)}function k1(R,U){var at=qs(R)?ha:vo;return at(R,zi(U,3))}function tc(R,U){var at=qs(R)?Fo:Su;return at(R,zi(U,3))}var F1=xc(function(R,U,at){Ns.call(R,at)?R[at].push(U):Bo(R,at,[U]);});function xp(R,U,at,Nt){R=Tc(R)?R:nu(R),at=at&&!Nt?js(at):0;var Qt=R.length;return at<0&&(at=_n(Qt+at,0)),Tp(R)?at<=Qt&&R.indexOf(U,at)>-1:!!Qt&&yr(R,U,at)>-1}var B3=Yi(function(R,U,at){var Nt=-1,Qt=typeof U=="function",ye=Tc(R)?Rr(R.length):[];return vo(R,function(Ue){ye[++Nt]=Qt?qi(U,Ue,at):Go(Ue,U,at);}),ye}),j3=xc(function(R,U,at){Bo(R,at,U);});function mp(R,U){var at=qs(R)?De:Yh;return at(R,zi(U,3))}function B1(R,U,at,Nt){return R==null?[]:(qs(U)||(U=U==null?[]:[U]),at=Nt?t:at,qs(at)||(at=at==null?[]:[at]),Xl(R,U,at))}var mx=xc(function(R,U,at){R[at?0:1].push(U);},function(){return [[],[]]});function U3(R,U,at){var Nt=qs(R)?dr:qr,Qt=arguments.length<3;return Nt(R,zi(U,4),at,Qt,vo)}function gx(R,U,at){var Nt=qs(R)?er:qr,Qt=arguments.length<3;return Nt(R,zi(U,4),at,Qt,Su)}function Qp(R,U){var at=qs(R)?Ne:il;return at(R,Td(zi(U,3)))}function gp(R){var U=qs(R)?rl:Ku;return U(R)}function K3(R,U,at){(at?Cu(R,U,at):U===t)?U=1:U=js(U);var Nt=qs(R)?Ho:Ra;return Nt(R,U)}function yp(R){var U=qs(R)?cl:qo;return U(R)}function $3(R){if(R==null)return 0;if(Tc(R))return Tp(R)?yo(R):R.length;var U=Eo(R);return U==Tt||U==Ae?R.size:cc(R).length}function vp(R,U,at){var Nt=qs(R)?_r:Ds;return at&&Cu(R,U,at)&&(U=t),Nt(R,zi(U,3))}var yx=Yi(function(R,U){if(R==null)return [];var at=U.length;return at>1&&Cu(R,U[0],U[1])?U=[]:at>2&&Cu(U[0],U[1],U[2])&&(U=[U[0]]),Xl(R,io(U,1),[])}),Ep=kn||function(){return $n.Date.now()};function Jp(R,U){if(typeof U!="function")throw new Ur(s);return R=js(R),function(){if(--R<1)return U.apply(this,arguments)}}function _p(R,U,at){return U=at?t:U,U=R&&U==null?R.length:U,Js(R,v,t,t,t,t,U)}function j1(R,U){var at;if(typeof U!="function")throw new Ur(s);return R=js(R),function(){return --R>0&&(at=U.apply(this,arguments)),R<=1&&(U=t),at}}var y1=Yi(function(R,U,at){var Nt=l;if(at.length){var Qt=We(at,Ua(y1));Nt|=_;}return Js(R,Nt,U,at,Qt)}),H3=Yi(function(R,U,at){var Nt=l|a;if(at.length){var Qt=We(at,Ua(H3));Nt|=_;}return Js(U,Nt,R,at,Qt)});function G3(R,U,at){U=at?t:U;var Nt=Js(R,d,t,t,t,t,t,U);return Nt.placeholder=G3.placeholder,Nt}function Zp(R,U,at){U=at?t:U;var Nt=Js(R,g,t,t,t,t,t,U);return Nt.placeholder=Zp.placeholder,Nt}function v1(R,U,at){var Nt,Qt,ye,Ue,Qe,C,M=0,nt=false,vt=false,Ft=true;if(typeof R!="function")throw new Ur(s);U=a0(U)||0,Wu(at)&&(nt=!!at.leading,vt="maxWait"in at,ye=vt?_n(a0(at.maxWait)||0,U):ye,Ft="trailing"in at?!!at.trailing:Ft);function ne(Ki){var Ss=Nt,es=Qt;return Nt=Qt=t,M=Ki,Ue=R.apply(es,Ss),Ue}function Re(Ki){return M=Ki,Qe=Ih(on,U),nt?ne(Ki):Ue}function je(Ki){var Ss=Ki-C,es=Ki-M,xo=U-Ss;return vt?vn(xo,ye-es):xo}function Ye(Ki){var Ss=Ki-C,es=Ki-M;return C===t||Ss>=U||Ss<0||vt&&es>=ye}function on(){var Ki=Ep();if(Ye(Ki))return an(Ki);Qe=Ih(on,je(Ki));}function an(Ki){return Qe=t,Ft&&Nt?ne(Ki):(Nt=Qt=t,Ue)}function Dn(){Qe!==t&&Kd(Qe),M=0,Nt=C=Qt=Qe=t;}function li(){return Qe===t?Ue:an(Ep())}function Ui(){var Ki=Ep(),Ss=Ye(Ki);if(Nt=arguments,Qt=this,C=Ki,Ss){if(Qe===t)return Re(C);if(vt)return Kd(Qe),Qe=Ih(on,U),ne(C)}return Qe===t&&(Qe=Ih(on,U)),Ue}return Ui.cancel=Dn,Ui.flush=li,Ui}var q3=Yi(function(R,U){return ju(R,1,U)}),t2=Yi(function(R,U,at){return ju(R,a0(U)||0,at)});function vx(R){return Js(R,G)}function E1(R,U){if(typeof R!="function"||U!=null&&typeof U!="function")throw new Ur(s);var at=function(){var Nt=arguments,Qt=U?U.apply(this,Nt):Nt[0],ye=at.cache;if(ye.has(Qt))return ye.get(Qt);var Ue=R.apply(this,Nt);return at.cache=ye.set(Qt,Ue)||ye,Ue};return at.cache=new(E1.Cache||Wa),at}E1.Cache=Wa;function Td(R){if(typeof R!="function")throw new Ur(s);return function(){var U=arguments;switch(U.length){case 0:return !R.call(this);case 1:return !R.call(this,U[0]);case 2:return !R.call(this,U[0],U[1]);case 3:return !R.call(this,U[0],U[1],U[2])}return !R.apply(this,U)}}function e2(R){return j1(2,R)}var Ex=c1(function(R,U){U=U.length==1&&qs(U[0])?De(U[0],fr(zi())):De(io(U,1),fr(zi()));var at=U.length;return Yi(function(Nt){for(var Qt=-1,ye=vn(Nt.length,at);++Qt<ye;)Nt[Qt]=U[Qt].call(this,Nt[Qt]);return qi(R,this,Nt)})}),r2=Yi(function(R,U){var at=We(U,Ua(r2));return Js(R,_,t,U,at)}),z3=Yi(function(R,U){var at=We(U,Ua(z3));return Js(R,S,t,U,at)}),Sg=ao(function(R,U){return Js(R,T,t,t,t,U)});function Cg(R,U){if(typeof R!="function")throw new Ur(s);return U=U===t?U:js(U),Yi(R,U)}function n2(R,U){if(typeof R!="function")throw new Ur(s);return U=U==null?0:_n(js(U),0),Yi(function(at){var Nt=at[U],Qt=Bc(at,0,U);return Nt&&tr(Qt,Nt),qi(R,this,Qt)})}function i2(R,U,at){var Nt=true,Qt=true;if(typeof R!="function")throw new Ur(s);return Wu(at)&&(Nt="leading"in at?!!at.leading:Nt,Qt="trailing"in at?!!at.trailing:Qt),v1(R,U,{leading:Nt,maxWait:U,trailing:Qt})}function s2(R){return _p(R,1)}function U1(R,U){return r2($u(U),R)}function _1(){if(!arguments.length)return [];var R=arguments[0];return qs(R)?R:[R]}function K1(R){return no(R,y)}function V3(R,U){return U=typeof U=="function"?U:t,no(R,y,U)}function o2(R){return no(R,E|y)}function T1(R,U){return U=typeof U=="function"?U:t,no(R,E|y,U)}function a2(R,U){return U==null||Ou(R,U,Hl(U))}function uh(R,U){return R===U||R!==R&&U!==U}var Y3=Ff(cu),Ng=Ff(function(R,U){return R>=U}),b1=vi((function(){return arguments})())?vi:function(R){return ul(R)&&Ns.call(R,"callee")&&!Oi.call(R,"callee")},qs=Rr.isArray,_x=Ce?fr(Ce):Wl;function Tc(R){return R!=null&&H1(R.length)&&!bc(R)}function Vu(R){return ul(R)&&Tc(R)}function H0(R){return R===true||R===false||ul(R)&&Is(R)==Se}var qf=qn||N2,u2=me?fr(me):ud;function A1(R){return ul(R)&&R.nodeType===1&&!G1(R)}function Xs(R){if(R==null)return true;if(Tc(R)&&(qs(R)||typeof R=="string"||typeof R.splice=="function"||qf(R)||zd(R)||b1(R)))return !R.length;var U=Eo(R);if(U==Tt||U==Ae)return !R.size;if(Uf(R))return !cc(R).length;for(var at in R)if(Ns.call(R,at))return false;return true}function $1(R,U){return cs(R,U)}function kh(R,U,at){at=typeof at=="function"?at:t;var Nt=at?at(R,U):t;return Nt===t?cs(R,U,t,at):!!Nt}function Yu(R){if(!ul(R))return false;var U=Is(R);return U==Et||U==Jt||typeof R.message=="string"&&typeof R.name=="string"&&!G1(R)}function W3(R){return typeof R=="number"&&_i(R)}function bc(R){if(!Wu(R))return false;var U=Is(R);return U==ht||U==xt||U==te||U==ce}function Tx(R){return typeof R=="number"&&R==js(R)}function H1(R){return typeof R=="number"&&R>-1&&R%1==0&&R<=pt}function Wu(R){var U=typeof R;return R!=null&&(U=="object"||U=="function")}function ul(R){return R!=null&&typeof R=="object"}var X3=ae?fr(ae):If;function bx(R,U){return R===U||ii(R,U,Ka(U))}function Rg(R,U,at){return at=typeof at=="function"?at:t,ii(R,U,Ka(U),at)}function bd(R){return Xu(R)&&R!=+R}function Q3(R){if(f1(R))throw new os(c);return zh(R)}function l2(R){return R===null}function ru(R){return R==null}function Xu(R){return typeof R=="number"||ul(R)&&Is(R)==Lt}function G1(R){if(!ul(R)||Is(R)!=Bt)return false;var U=sc(R);if(U===null)return true;var at=Ns.call(U,"constructor")&&U.constructor;return typeof at=="function"&&at instanceof at&&Ks.call(at)==ic}var c2=ke?fr(ke):Df;function q1(R){return Tx(R)&&R>=-pt&&R<=pt}var J3=Ke?fr(Ke):l1;function Tp(R){return typeof R=="string"||!qs(R)&&ul(R)&&Is(R)==kt}function o0(R){return typeof R=="symbol"||ul(R)&&Is(R)==jt}var zd=Xe?fr(Xe):fo;function Z3(R){return R===t}function z1(R){return ul(R)&&Eo(R)==$t}function bp(R){return ul(R)&&Is(R)==yt}var V1=Ff(Vh),O1=Ff(function(R,U){return R<=U});function Vd(R){if(!R)return [];if(Tc(R))return Tp(R)?ro(R):jl(R);if(sn&&R[sn])return tn(R[sn]());var U=Eo(R),at=U==Tt?zr:U==Ae?Ic:nu;return at(R)}function Ru(R){if(!R)return R===0?R:0;if(R=a0(R),R===tt||R===-tt){var U=R<0?-1:1;return U*Z}return R===R?R:0}function js(R){var U=Ru(R),at=U%1;return U===U?at?U-at:U:0}function zf(R){return R?da(js(R),0,gt):0}function a0(R){if(typeof R=="number")return R;if(o0(R))return dt;if(Wu(R)){var U=typeof R.valueOf=="function"?R.valueOf():R;R=Wu(U)?U+"":U;}if(typeof R!="string")return R===0?R:+R;R=mr(R);var at=vl.test(R);return at||Ro.test(R)?ma(R.slice(2),at?2:8):yu.test(R)?dt:+R}function Ax(R){return Zc(R,Fh(R))}function wg(R){return R?da(js(R),-pt,pt):R===0?R:0}function ya(R){return R==null?"":wa(R)}var Ox=mc(function(R,U){if(Uf(U)||Tc(U)){Zc(U,Hl(U),R);return}for(var at in U)Ns.call(U,at)&&Ma(R,at,U[at]);}),yf=mc(function(R,U){Zc(U,Fh(U),R);}),Hs=mc(function(R,U,at,Nt){Zc(U,Fh(U),R,Nt);}),Ap=mc(function(R,U,at,Nt){Zc(U,Hl(U),R,Nt);}),u0=ao(Bu);function Sx(R,U){var at=Yl(R);return U==null?at:fa(at,U)}var Ig=Yi(function(R,U){R=Ys(R);var at=-1,Nt=U.length,Qt=Nt>2?U[2]:t;for(Qt&&Cu(U[0],U[1],Qt)&&(Nt=1);++at<Nt;)for(var ye=U[at],Ue=Fh(ye),Qe=-1,C=Ue.length;++Qe<C;){var M=Ue[Qe],nt=R[M];(nt===t||uh(nt,At[M])&&!Ns.call(R,M))&&(R[M]=ye[M]);}return R}),ua=Yi(function(R){return R.push(t,pl),qi(Lx,t,R)});function Cx(R,U){return Tr(R,zi(U,3),Sa)}function tm(R,U){return Tr(R,zi(U,3),lu)}function Vf(R,U){return R==null?R:ka(R,zi(U,3),Fh)}function em(R,U){return R==null?R:Oa(R,zi(U,3),Fh)}function Nx(R,U){return R&&Sa(R,zi(U,3))}function Rx(R,U){return R&&lu(R,zi(U,3))}function Op(R){return R==null?[]:Io(R,Hl(R))}function wx(R){return R==null?[]:Io(R,Fh(R))}function Y1(R,U,at){var Nt=R==null?t:qa(R,U);return Nt===t?at:Nt}function rm(R,U){return R!=null&&xl(R,U,ga)}function Ix(R,U){return R!=null&&xl(R,U,pa)}var Dg=h1(function(R,U,at){U!=null&&typeof U.toString!="function"&&(U=Mu.call(U)),R[U]=at;},X1(na)),Lg=h1(function(R,U,at){U!=null&&typeof U.toString!="function"&&(U=Mu.call(U)),Ns.call(R,U)?R[U].push(at):R[U]=[at];},zi),h2=Yi(Go);function Hl(R){return Tc(R)?Qa(R):cc(R)}function Fh(R){return Tc(R)?Qa(R,true):hc(R)}function Dx(R,U){var at={};return U=zi(U,3),Sa(R,function(Nt,Qt,ye){Bo(at,U(Nt,Qt,ye),Nt);}),at}function Pg(R,U){var at={};return U=zi(U,3),Sa(R,function(Nt,Qt,ye){Bo(at,Qt,U(Nt,Qt,ye));}),at}var Ac=mc(function(R,U,at){N0(R,U,at);}),Lx=mc(function(R,U,at,Nt){N0(R,U,at,Nt);}),Mg=ao(function(R,U){var at={};if(R==null)return at;var Nt=false;U=De(U,function(ye){return ye=Bl(ye,R),Nt||(Nt=ye.length>1),ye}),Zc(R,Fs(R),at),Nt&&(at=no(at,E|b|y,lf));for(var Qt=U.length;Qt--;)bl(at,U[Qt]);return at});function kg(R,U){return lh(R,Td(zi(U)))}var Gl=ao(function(R,U){return R==null?{}:Wh(R,U)});function lh(R,U){if(R==null)return {};var at=De(Fs(R),function(Nt){return [Nt]});return U=zi(U),R0(R,at,function(Nt,Qt){return U(Nt,Qt[0])})}function f2(R,U,at){U=Bl(U,R);var Nt=-1,Qt=U.length;for(Qt||(Qt=1,R=t);++Nt<Qt;){var ye=R==null?t:R[Ql(U[Nt])];ye===t&&(Nt=Qt,ye=at),R=bc(ye)?ye.call(R):ye;}return R}function nm(R,U,at){return R==null?R:Ao(R,U,at)}function im(R,U,at,Nt){return Nt=typeof Nt=="function"?Nt:t,R==null?R:Ao(R,U,at,Nt)}var d2=Hu(Hl),p2=Hu(Fh);function Px(R,U,at){var Nt=qs(R),Qt=Nt||qf(R)||zd(R);if(U=zi(U,4),at==null){var ye=R&&R.constructor;Qt?at=Nt?new ye:[]:Wu(R)?at=bc(ye)?Yl(sc(R)):{}:at={};}return (Qt?ha:Sa)(R,function(Ue,Qe,C){return U(at,Ue,Qe,C)}),at}function Mx(R,U){return R==null?true:bl(R,U)}function Qu(R,U,at){return R==null?R:kc(R,U,$u(at))}function l0(R,U,at,Nt){return Nt=typeof Nt=="function"?Nt:t,R==null?R:kc(R,U,$u(at),Nt)}function nu(R){return R==null?[]:wr(R,Hl(R))}function G0(R){return R==null?[]:wr(R,Fh(R))}function Yd(R,U,at){return at===t&&(at=U,U=t),at!==t&&(at=a0(at),at=at===at?at:0),U!==t&&(U=a0(U),U=U===U?U:0),da(a0(R),U,at)}function kx(R,U,at){return U=Ru(U),at===t?(at=U,U=0):at=Ru(at),R=a0(R),hu(R,U,at)}function sm(R,U,at){if(at&&typeof at!="boolean"&&Cu(R,U,at)&&(U=at=t),at===t&&(typeof U=="boolean"?(at=U,U=t):typeof R=="boolean"&&(at=R,R=t)),R===t&&U===t?(R=0,U=1):(R=Ru(R),U===t?(U=R,R=0):U=Ru(U)),R>U){var Nt=R;R=U,U=Nt;}if(at||R%1||U%1){var Qt=ni();return vn(R+Qt*(U-R+kl("1e-"+((Qt+"").length-1))),U)}return sf(R,U)}var W1=L0(function(R,U,at){return U=U.toLowerCase(),R+(at?Ad(U):U)});function Ad(R){return ra(ya(R).toLowerCase())}function Yf(R){return R=ya(R),R&&R.replace(au,Er).replace(_s,"")}function Od(R,U,at){R=ya(R),U=wa(U);var Nt=R.length;at=at===t?Nt:da(js(at),0,Nt);var Qt=at;return at-=U.length,at>=0&&R.slice(at,Qt)==U}function x2(R){return R=ya(R),R&&Kr.test(R)?R.replace(Fi,kr):R}function m2(R){return R=ya(R),R&&Wi.test(R)?R.replace(eo,"\\$&"):R}var g2=L0(function(R,U,at){return R+(at?"-":"")+U.toLowerCase()}),y2=L0(function(R,U,at){return R+(at?" ":"")+U.toLowerCase()}),v2=Ul("toLowerCase");function Sp(R,U,at){R=ya(R),U=js(U);var Nt=U?yo(R):0;if(!U||Nt>=U)return R;var Qt=(U-Nt)/2;return dl(ci(Qt),at)+R+dl(ui(Qt),at)}function Cp(R,U,at){R=ya(R),U=js(U);var Nt=U?yo(R):0;return U&&Nt<U?R+dl(U-Nt,at):R}function Fx(R,U,at){R=ya(R),U=js(U);var Nt=U?yo(R):0;return U&&Nt<U?dl(U-Nt,at)+R:R}function Bx(R,U,at){return at||U==null?U=0:U&&(U=+U),Mn(ya(R).replace(ki,""),U||0)}function jx(R,U,at){return (at?Cu(R,U,at):U===t)?U=1:U=js(U),Fa(ya(R),U)}function om(){var R=arguments,U=ya(R[0]);return R.length<3?U:U.replace(R[1],R[2])}var am=L0(function(R,U,at){return R+(at?"_":"")+U.toLowerCase()});function ch(R,U,at){return at&&typeof at!="number"&&Cu(R,U,at)&&(U=at=t),at=at===t?gt:at>>>0,at?(R=ya(R),R&&(typeof U=="string"||U!=null&&!c2(U))&&(U=wa(U),!U&&ir(R))?Bc(ro(R),0,at):R.split(U,at)):[]}var hh=L0(function(R,U,at){return R+(at?" ":"")+ra(U)});function fh(R,U,at){return R=ya(R),at=at==null?0:da(js(at),0,R.length),U=wa(U),R.slice(at,at+U.length)==U}function E2(R,U,at){var Nt=he.templateSettings;at&&Cu(R,U,at)&&(U=t),R=ya(R),U=Hs({},U,Nt,Xi);var Qt=Hs({},U.imports,Nt.imports,Xi),ye=Hl(Qt),Ue=wr(Qt,ye),Qe,C,M=0,nt=U.interpolate||Pu,vt="__p += '",Ft=ar((U.escape||Pu).source+"|"+nt.source+"|"+(nt===Yn?ko:Pu).source+"|"+(U.evaluate||Pu).source+"|$","g"),ne="//# sourceURL="+(Ns.call(U,"sourceURL")?(U.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Ya+"]")+`
1920
1920
  `;R.replace(Ft,function(Ye,on,an,Dn,li,Ui){return an||(an=Dn),vt+=R.slice(M,Ui).replace(Zu,Dr),on&&(Qe=true,vt+=`' +