@miadi/stateloom-web 0.2.2 → 0.2.3
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.
- package/package.json +1 -1
- package/server/.next/BUILD_ID +1 -1
- package/server/.next/build-manifest.json +2 -2
- package/server/.next/server/app/_global-error.html +2 -2
- package/server/.next/server/app/_global-error.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.html +1 -1
- package/server/.next/server/app/_not-found.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/index.html +1 -1
- package/server/.next/server/app/index.rsc +2 -2
- package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/server/.next/server/app/index.segments/_full.segment.rsc +2 -2
- package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/server/.next/server/app/index.segments/_index.segment.rsc +1 -1
- package/server/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/server/.next/server/app/page_client-reference-manifest.js +1 -1
- package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +1 -1
- package/server/.next/server/pages/404.html +1 -1
- package/server/.next/server/pages/500.html +2 -2
- package/server/.next/static/chunks/{56e82acb03b39fde.js → 8fad55ffcb4402a1.js} +1 -1
- package/server/package-lock.json +2 -2
- package/server/package.json +1 -1
- package/server/stateloom-web.json +2 -2
- /package/server/.next/static/{1WAhhGZT7SAtxrGNolq7i → s006nwfeOEJ9fSHkFe8k7}/_buildManifest.js +0 -0
- /package/server/.next/static/{1WAhhGZT7SAtxrGNolq7i → s006nwfeOEJ9fSHkFe8k7}/_clientMiddlewareManifest.json +0 -0
- /package/server/.next/static/{1WAhhGZT7SAtxrGNolq7i → s006nwfeOEJ9fSHkFe8k7}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,63052,e=>{"use strict";let t,n,s,r;var a,i,o=e.i(14294),l=e.i(30878);function c(e){return JSON.parse(JSON.stringify(e))}function d(e,t){for(let n of e.states??[]){if(n.name===t)return e;let s=d(n,t);if(s)return s}return null}function h(e,t,n){let s=function e(t,n){if(t.name===n)return t;for(let s of t.states??[]){let t=e(s,n);if(t)return t}return null}(e,t);if(!s)throw Error(`applyPatchOps: ${n} references missing state "${t}"`);return s}function m(e,t,n){let s=function(e,t){for(let n of e.events){let e=n.events??[];for(let s=0;s<e.length;s++)if(e[s].id===t)return{source:n,event:e[s],index:s}}return null}(e,t);if(!s)throw Error(`applyPatchOps: ${n} references missing event "${t}"`);return s}function u(e,t){let n=c(e);for(let e of(Array.isArray(n.events)||(n.events=[]),t))switch(e.op){case"settings.update":n.settings={...n.settings,...e.patch},""===n.settings.notes&&delete n.settings.notes;break;case"state.add":{let t=null===e.parent?n.state:h(n.state,e.parent,"state.add");t.states||(t.states=[]);let s=e.index??t.states.length;t.states.splice(s,0,c(e.state));break}case"state.update":{let t=h(n.state,e.name,"state.update");Object.assign(t,e.patch),""===t.notes&&delete t.notes,""===t.prompt&&delete t.prompt;break}case"state.remove":{if(n.state.name===e.name)throw Error(`applyPatchOps: cannot remove root state "${e.name}"`);let t=d(n.state,e.name);if(!t||!t.states)throw Error(`applyPatchOps: state.remove references missing state "${e.name}"`);let s=t.states.findIndex(t=>t.name===e.name);if(s<0)throw Error(`applyPatchOps: state.remove references missing state "${e.name}"`);t.states.splice(s,1),0===t.states.length&&delete t.states;break}case"state.nest":{let t=h(n.state,e.child,"state.nest"),s=h(n.state,e.newParent,"state.nest"),r=d(n.state,e.child);if(!r||!r.states)throw Error(`applyPatchOps: state.nest cannot detach root or missing state "${e.child}"`);let a=r.states.findIndex(t=>t.name===e.child),[i]=r.states.splice(a,1);0===r.states.length&&delete r.states,s.states||(s.states=[]),s.states.push(i??c(t));break}case"eventSource.add":{let t=e.index??n.events.length;n.events.splice(t,0,c(e.source));break}case"eventSource.update":{let t=n.events[e.index];if(!t)throw Error(`applyPatchOps: eventSource.update index ${e.index} out of range`);n.events[e.index]={...t,...e.patch};break}case"eventSource.remove":if(!n.events[e.index])throw Error(`applyPatchOps: eventSource.remove index ${e.index} out of range`);n.events.splice(e.index,1);break;case"event.add":{let t=n.events[e.sourceIndex];if(!t)throw Error(`applyPatchOps: event.add sourceIndex ${e.sourceIndex} out of range`);t.events||(t.events=[]);let s=e.index??t.events.length;t.events.splice(s,0,c(e.event));break}case"event.update":Object.assign(m(n,e.id,"event.update").event,e.patch);break;case"event.remove":{let t=m(n,e.id,"event.remove");t.source.events.splice(t.index,1),0===t.source.events.length&&delete t.source.events;break}case"parameter.add":{let t=m(n,e.eventId,"parameter.add");t.event.parameters||(t.event.parameters=[]);let s=e.index??t.event.parameters.length;t.event.parameters.splice(s,0,c(e.parameter));break}case"parameter.update":{let t=m(n,e.eventId,"parameter.update").event.parameters??[];if(!t[e.index])throw Error(`applyPatchOps: parameter.update index ${e.index} out of range for event "${e.eventId}"`);t[e.index]={...t[e.index],...e.patch};break}case"parameter.remove":{let t=m(n,e.eventId,"parameter.remove"),s=t.event.parameters;if(!s||!s[e.index])throw Error(`applyPatchOps: parameter.remove index ${e.index} out of range for event "${e.eventId}"`);s.splice(e.index,1),0===s.length&&delete t.event.parameters;break}case"transition.add":{let t=h(n.state,e.state,"transition.add");t.transitions||(t.transitions=[]);let s=e.index??t.transitions.length;t.transitions.splice(s,0,c(e.transition));break}case"transition.update":{let t=h(n.state,e.state,"transition.update").transitions??[];if(!t[e.index])throw Error(`applyPatchOps: transition.update index ${e.index} out of range for state "${e.state}"`);t[e.index]={...t[e.index],...e.patch};break}case"transition.remove":{let t=h(n.state,e.state,"transition.remove"),s=t.transitions;if(!s||!s[e.index])throw Error(`applyPatchOps: transition.remove index ${e.index} out of range for state "${e.state}"`);s.splice(e.index,1),0===s.length&&delete t.transitions;break}case"action.add":{let t=h(n.state,e.state,"action.add"),s=t[e.hook]??(t[e.hook]={actions:[]}),r=e.index??s.actions.length;s.actions.splice(r,0,c(e.action));break}case"action.update":{let t=h(n.state,e.state,"action.update")[e.hook];if(!t||!t.actions[e.index])throw Error(`applyPatchOps: action.update index ${e.index} out of range for state "${e.state}" ${e.hook}`);t.actions[e.index]=c(e.action);break}case"action.remove":{let t=h(n.state,e.state,"action.remove"),s=t[e.hook];if(!s||!s.actions[e.index])throw Error(`applyPatchOps: action.remove index ${e.index} out of range for state "${e.state}" ${e.hook}`);s.actions.splice(e.index,1),0===s.actions.length&&delete t[e.hook];break}case"runtime.enter":case"runtime.exit":break;default:throw Error(`applyPatchOps: unknown op ${JSON.stringify(e)}`)}return n}function p(e){let t=[e];for(let n of e.states??[])t.push(...p(n));return t}function f(e){let t=new Map;t.set(e.name,null);let n=e=>{for(let s of e.states??[])t.set(s.name,e.name),n(s)};return n(e),t}function g(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x(e,t,n,s,r){let a=Math.min(n.length,s.length);for(let i=0;i<a;i++)g(n[i],s[i])||r.push({op:"action.update",state:e,hook:t,index:i,action:s[i]});for(let n=a;n<s.length;n++)r.push({op:"action.add",state:e,hook:t,action:s[n],index:n});for(let a=n.length-1;a>=s.length;a--)r.push({op:"action.remove",state:e,hook:t,index:a})}function y(e){let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;let n=(t%360+360)%360;return`hsl(${n}, 65%, 55%)`}var b=e.i(50382);let v={hSpacing:220,vSpacing:140,nodeWidth:160,nodeHeight:60,compositeWidth:300,compositeHeight:200,originX:100,originY:120,sweeps:2,includeRoot:!0},w=(e,t)=>`${e}\u0000${t}`;function j(e){let t=new Set,n=[];for(let s of e.states??[])t.has(s.name)||(t.add(s.name),n.push(s));return n}function k(e,t){let n=new Map(e.map(e=>[e,[]]));for(let e of t)n.get(e.from).push(e.to);return n}function $(e,t={}){let n={...v,...t},s="state"in e?e.state:e,r={};if(!s)return r;if(!function e(t,n,s,r,a){let i=j(t);if(0===i.length)return;let o=i.map(e=>e.name),l=new Map(i.map(e=>[e.name,e])),c=function(e){let t=new Set(e.map(e=>e.name)),n=new Set,s=[];for(let r of e)for(let e of r.transitions??[]){let a=e.nextState;if(!a||a===r.name||!t.has(a))continue;let i=w(r.name,a);n.has(i)||(n.add(i),s.push({from:r.name,to:a}))}return s}(i),d=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0])),r=new Set;for(let t of e){if(0!==s.get(t))continue;s.set(t,1);let e=[{node:t,i:0}];for(;e.length>0;){let t=e[e.length-1],a=n.get(t.node);if(t.i<a.length){let n=a[t.i++],i=s.get(n);1===i?r.add(w(t.node,n)):0===i&&(s.set(n,1),e.push({node:n,i:0}))}else s.set(t.node,2),e.pop()}}return r}(o,c),h=c.filter(e=>!d.has(w(e.from,e.to))),m=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0]));for(let e of t)s.set(e.to,(s.get(e.to)??0)+1);let r=new Map(e.map(e=>[e,0])),a=e.filter(e=>0===s.get(e));for(let e=0;e<a.length;e++){let t=a[e];for(let e of n.get(t)){r.set(e,Math.max(r.get(e),r.get(t)+1));let n=s.get(e)-1;s.set(e,n),0===n&&a.push(e)}}return r}(o,h),u=function(e,t,n){let s=new Map(e.map(e=>[e,[]]));for(let e of t)s.get(e.from).push(e.to),s.get(e.to).push(e.from);let r=new Set([n]),a=[n];for(;a.length>0;){let e=a.pop();for(let t of s.get(e)??[])r.has(t)||(r.add(t),a.push(t))}return r}(o,c,o[0]),p=0;for(let e of o)u.has(e)&&(p=Math.max(p,m.get(e)));for(let e of o)u.has(e)||m.set(e,m.get(e)+p+1);let f=Array.from({length:Math.max(...o.map(e=>m.get(e)))+1},()=>[]);for(let e of o)f[m.get(e)].push(e);!function(e,t,n){let s=new Map,r=new Map,a=(e,t,n)=>{let s=e.get(t);s?s.push(n):e.set(t,[n])};for(let e of t)a(s,e.to,e.from),a(r,e.from,e.to);let i=new Map,o=()=>{e.forEach(e=>e.forEach((e,t)=>i.set(e,t)))};o();let l=(e,t)=>{let n=e.map((e,n)=>{let s=(t.get(e)??[]).filter(e=>i.has(e));return{name:e,key:s.length?s.reduce((e,t)=>e+i.get(t),0)/s.length:n,i:n}});n.sort((e,t)=>e.key===t.key?e.i-t.i:e.key-t.key);for(let t=0;t<n.length;t++)e[t]=n[t].name};for(let t=0;t<n;t++){for(let t=1;t<e.length;t++)l(e[t],s),o();for(let t=e.length-2;t>=0;t--)l(e[t],r),o()}}(f,h,r.sweeps);let g=r.hSpacing-r.nodeWidth,x=r.vSpacing-r.nodeHeight,y=e=>Math.max(r.hSpacing,e+g),b=new Map(o.map(e=>{var t;return[e,(t=l.get(e),(t.states?.length??0)>0?{width:r.compositeWidth,height:r.compositeHeight}:{width:r.nodeWidth,height:r.nodeHeight})]})),v=f.map(e=>e.reduce((e,t)=>e+y(b.get(t).width),0)),$=n+Math.max(...v,0)/2,N=s;for(let t of(f.forEach((e,t)=>{let n=$-v[t]/2,s=r.nodeHeight;for(let t of e){let e=b.get(t),r=y(e.width);a[t]={x:Math.round(n+(r-e.width)/2),y:Math.round(N),width:e.width,height:e.height},n+=r,s=Math.max(s,e.height)}N+=s+x}),i)){if((t.states?.length??0)===0)continue;let n=a[t.name];e(t,n.x+20,n.y+40,r,a)}}(s,n.originX,n.originY,n,r),n.includeRoot){let e=j(s).map(e=>r[e.name]).filter(Boolean);if(0===e.length)r[s.name]={x:20,y:20,width:400,height:350};else{let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),a=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));r[s.name]={x:Math.round(t-40),y:Math.round(n-40),width:Math.round(a-t+80),height:Math.round(i-n+80)}}}return r}let N=(e,t)=>e.length*t*.55,S=e=>`[${e.length>32?`${e.slice(0,31).trimEnd()}…`:e}]`,E=e=>({width:Math.max(56,Math.max(N(e.event,11),e.condition?N(S(e.condition),9):0)+16)+16*!!e.glyph,height:e.condition?28:18}),C=e=>({x:e.x+5,y:e.cy-12-3}),M=(e,t)=>e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height,_={along:[.5,.36,.64,.24,.76,.14,.86],aside:[0,.6,-.6],across:[0,-1.3,1.3,-2.6,2.6]};function A(e,t,n={}){let{along:s,aside:r,across:a}={..._,...n},i=e.map((e,t)=>({label:e,i:t,width:E(e).width})).sort((e,t)=>e.width===t.width?e.i-t.i:t.width-e.width),o=[];for(let{label:e}of i){let{width:n,height:i}=E(e),l=8*!!e.glyph,c=null,d=1/0;e:for(let h of a)for(let a of r)for(let r of s){let s=e.at(r),m=s.x+a*n,u=s.y+h*i,p={x:m-n/2,y:u-18,width:n,height:i},f=[...o,...t].filter(e=>M(p,e)).length,g={...p,cx:m+l,cy:u,label:e};if(0===f){c=g;break e}f<d&&(d=f,c=g)}c&&o.push(c)}return o}let O=(e,t,n=2.2,s)=>({id:e,paths:t,strokeWidth:n,circles:s}),R=O("signal",["M3 12h10","m13 6 6 6-6 6Z"]),P=[{glyph:O("confirm",["m4 13 5.5 5.5L20 6"],2.4),words:["confirm","approve","accept","commit"]},{glyph:O("complete",["m8 12 3 3 5-6"],2.2,[{cx:12,cy:12,r:8.5}]),words:["complete","finish","done","close"]},{glyph:O("skip",["M4 17c0-6 4.5-9 9-9h6","m15 4 4.5 4-4.5 4"]),words:["skip","ignore","bypass"]},{glyph:O("flag",["M6 21V4","M6 4h12l-3 4.5 3 4.5H6Z"]),words:["flag","mark","revisit","review"]},{glyph:O("advance",["M4 6l8 6-8 6Z","M13 6l7 6-7 6Z"]),words:["advance","next","forward","step"]},{glyph:O("pause",["M9 5v14M15 5v14"],2.6),words:["pause","hold","suspend","stop"]},{glyph:O("play",["M7 4.5 19 12 7 19.5Z"]),words:["resume","start","begin","play","run"]},{glyph:O("clock",["M12 7.5V12l3.5 2.5"],2.2,[{cx:12,cy:12,r:8.5}]),words:["timeout","expire","tick","delay","after","elapse"]},{glyph:O("change",["M3 14c3-6 6-6 9 0s6 6 9 0"]),words:["change","update","edit","modify","set"]}];[...P.map(e=>e.glyph)];let T=e=>Math.round(100*e)/100;function I(e,t,n,s){return{p0:e,p1:t,p2:n,p3:s,path:`M ${T(e.x)} ${T(e.y)} C ${T(t.x)} ${T(t.y)}, ${T(n.x)} ${T(n.y)}, ${T(s.x)} ${T(s.y)}`,at:r=>{let a=1-r,i=a*a*a,o=3*a*a*r,l=3*a*r*r,c=r*r*r;return{x:i*e.x+o*t.x+l*n.x+c*s.x,y:i*e.y+o*t.y+l*n.y+c*s.y}}}}function L(e,t){let n=e.map(({from:e,to:n})=>{var s,r;return e===n?null:(s=t(e),(r=t(n)).y>=s.y+s.height?["bottom","top"]:r.y+r.height<=s.y?["top","bottom"]:r.x>=s.x+s.width?["right","left"]:r.x+r.width<=s.x?["left","right"]:["bottom","top"])}),s=new Map,r=(e,t,n)=>{let r=`${e}\0${t}`,a=s.get(r);a?a.push(n):s.set(r,[n])},a=(e,t)=>"top"===t||"bottom"===t?e.x+e.width/2:e.y+e.height/2;e.forEach((e,s)=>{let i=n[s];if(!i)return;let[o,l]=i;r(e.from,o,{edge:s,toward:a(t(e.to),o),role:"out"}),r(e.to,l,{edge:s,toward:a(t(e.from),l),role:"in"})});let i=new Map;for(let[e,n]of s){let[s,r]=e.split("\0"),a=t(s),o=[...n].sort((e,t)=>e.toward===t.toward?e.edge-t.edge:e.toward-t.toward);o.forEach((e,t)=>{i.set(`${e.edge}\0${e.role}`,function(e,t,n,s){let r="top"===t||"bottom"===t,a=r?e.width:e.height,i=r?e.x+e.width/2:e.y+e.height/2,o=s>1?Math.min(.72*a,40*(s-1)):0,l=s>1?i-o/2+o*n/(s-1):i;return"top"===t?{x:l,y:e.y}:"bottom"===t?{x:l,y:e.y+e.height}:"left"===t?{x:e.x,y:l}:{x:e.x+e.width,y:l}}(a,r,t,o.length))})}return e.map((e,s)=>{let r=n[s];if(!r){var a;let n,s,r;return n=(a=t(e.from)).x+a.width,s=a.y+.35*a.height,I({x:n,y:s},{x:n+44,y:s-12},{x:n+44,y:(r=a.y+.65*a.height)+12},{x:n,y:r})}let o=i.get(`${s}\0out`),l=i.get(`${s}\0in`);var c=r[0];if("top"===c||"bottom"===c){let e=(o.y+l.y)/2;return I(o,{x:o.x,y:e},{x:l.x,y:e},l)}let d=(o.x+l.x)/2;return I(o,{x:d,y:o.y},{x:d,y:l.y},l)})}let D={min:.2,max:2.5},q={x:0,y:0,scale:1};function B(e,t=D){return Number.isFinite(e)?Math.min(t.max,Math.max(t.min,e)):1}function F(e,t,n){return{x:e.x+t,y:e.y+n,scale:e.scale}}function Y(e,t,n,s=D){return z(e,e.scale*t,n,s)}function z(e,t,n,s=D){let r=B(t,s);if(r===e.scale)return e;let a={x:(n.x-e.x)/e.scale,y:(n.y-e.y)/e.scale};return{x:n.x-a.x*r,y:n.y-a.y*r,scale:r}}function U(e,t,n,s={}){let r=s.padding??48,a=s.maxScale??1,i=s.limits??D;if(0===e.length||t<=0||n<=0)return{...q};let o=1/0,l=1/0,c=-1/0,d=-1/0;for(let t of e)o=Math.min(o,t.x),l=Math.min(l,t.y),c=Math.max(c,t.x+t.width),d=Math.max(d,t.y+t.height);let h=Math.max(1,c-o),m=Math.max(1,d-l),u=B(Math.min(a,Math.min(Math.max(1,t-2*r)/h,Math.max(1,n-2*r)/m)),i);return{x:(t-h*u)/2-o*u,y:(n-m*u)/2-l*u,scale:u}}function X(e){return`translate(${e.x} ${e.y}) scale(${e.scale})`}function H(e){let t=new Set,n=[];for(let s of e.states??[])t.has(s.name)||(t.add(s.name),n.push(s));return n}function J(e){return e.stateOf?Array.isArray(e.stateOf)?e.stateOf:[e.stateOf]:[]}let V=["1:1","1:N","N:1","N:M"];function W(e){return!!e&&"object"==typeof e&&Array.isArray(e.entities)&&!("state"in e)}function K(e){let t=[],n=function(e){let t=new Map;for(let n of e.entities??[])n?.name&&!t.has(n.name)&&t.set(n.name,n);return t}(e),s=new Set;for(let[r,a]of(e.entities??[]).entries()){if(!a?.name){t.push({ruleId:"E001",message:`Entity at index ${r} has no name`,element:`entities[${r}]`});continue}s.has(a.name)&&t.push({ruleId:"E001",message:`Duplicate entity name "${a.name}"`,element:a.name}),s.add(a.name);let e=new Set;for(let[s,r]of(a.attributes??[]).entries()){if(!r?.name){t.push({ruleId:"E002",message:`Attribute at index ${s} of "${a.name}" has no name`,element:`${a.name}[${s}]`});continue}let i=`${a.name}.${r.name}`;if(e.has(r.name)&&t.push({ruleId:"E002",message:`Duplicate attribute "${i}"`,element:i}),e.add(r.name),r.references){let e=function(e){let t=e.indexOf(".");return t<0?{entity:e}:{entity:e.slice(0,t),attribute:e.slice(t+1)}}(r.references),s=n.get(e.entity);s?e.attribute&&!(s.attributes??[]).some(t=>t?.name===e.attribute)&&t.push({ruleId:"E005",message:`"${i}" references undefined attribute "${r.references}"`,element:i}):t.push({ruleId:"E005",message:`"${i}" references undefined entity "${e.entity}"`,element:i})}}}for(let[s,r]of(e.relationships??[]).entries()){let e=`relationships[${s}]`;for(let a of["from","to"]){let i=r?.[a];i&&n.has(i)||t.push({ruleId:"E003",message:`Relationship ${s} ${a} names undefined entity "${i??""}"`,element:e})}V.includes(r?.cardinality)||t.push({ruleId:"E004",message:`Relationship ${s} cardinality "${r?.cardinality??""}" is not one of ${V.join(", ")}`,element:e})}return t}function Z(e,t){let n=RegExp(`(?<![\\w.])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.([A-Za-z_]\\w*)\\b(?!\\s*\\()`,"g"),s=[];for(let t of e.matchAll(n))s.includes(t[1])||s.push(t[1]);return s}function G(e,t){let n=[],s=new Map;for(let e of t.entities??[])e?.name&&!s.has(e.name)&&s.set(e.name,e);let r=e.settings?.name??"",a=e.settings?.objects??[],i=e.state?function e(t){let n=[t];for(let s of t.states??[])n.push(...e(s));for(let s of t.parallel?.states??[])n.push(...e(s));return n}(e.state):[],o=i.flatMap(e=>(e.transitions??[]).map(e=>e.condition??"")),l=new Map;for(let e of a){let r=s.get(e.class);if(r){l.set(e.instance,r);continue}o.some(t=>Z(t,e.instance).length>0)&&n.push({ruleId:"L001",message:`Object "${e.instance}" has class "${e.class}", which is not an entity in "${t.settings?.name??""}", and a guard reads its fields`,element:e.instance})}for(let e of i)for(let t of e.transitions??[])if(t.condition)for(let[s,r]of l)for(let a of Z(t.condition,s))(r.attributes??[]).some(e=>e?.name===a)||n.push({ruleId:"L002",message:`Guard on ${e.name} [${t.event}] reads "${s}.${a}", which is not an attribute of "${r.name}"`,element:e.name});if(r){let e=new Set([...l.values()].map(e=>e.name));for(let s of t.entities??[])for(let t of s?.attributes??[])t&&J(t).includes(r)&&(e.has(s.name)||n.push({ruleId:"L003",message:`"${s.name}.${t.name}" stores the state of "${r}", but "${s.name}" is not the class of any of that machine's objects`,element:`${s.name}.${t.name}`}))}return n}function Q(e,t){let n=[];for(let s of e.entities??[])for(let e of s?.attributes??[])if(e)for(let r of J(e))t.includes(r)||n.push({ruleId:"L004",message:`"${s.name}.${e.name}" stores the state of "${r}", which is not among the machines checked (${t.join(", ")||"none"})`,element:`${s.name}.${e.name}`});return n}let ee=e=>({settings:{...e.settings},entities:(e.entities??[]).map(e=>({...e,attributes:(e.attributes??[]).map(e=>({...e}))})),relationships:(e.relationships??[]).map(e=>({...e}))});function et(e,t){let n=e.entities.find(e=>e.name===t);if(!n){let n=e.entities.map(e=>e.name).join(", ")||"none";throw Error(`Entity '${t}' not found. Entities: ${n}.`)}return n}function en(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function es(e,t){if(!t.name?.trim())throw Error("An entity needs a name.");let n=ee(e);if(n.entities.some(e=>e.name===t.name))throw Error(`Entity '${t.name}' already exists.`);return n.entities.push(en({...t,attributes:t.attributes??[]})),n}function er(e,t,n){let s=ee(e),r=et(s,t);return void 0!==n.notes&&(n.notes.trim()?r.notes=n.notes:delete r.notes),void 0!==n.description&&(n.description?r.description=n.description:delete r.description),void 0!==n.weak&&(n.weak?r.weak=!0:delete r.weak),s}let ea=e=>(e.attributes??[]).filter(e=>e?.name);function ei(e){return Math.max(110,Math.ceil(8.4*(e.name??"").length+36))}function eo(e){return Math.max(38,Math.ceil(3.5*Math.max(0,...e.map(e=>e.name.length))+14))}let el=e=>Math.ceil(e/2);function ec(e){let t=ea(e),n=ei(e);return 0===t.length?{width:n,height:40}:{width:n+2*(34+2*eo(t)),height:Math.max(40,32*el(t.length))}}let ed={"1:1":"||--||","1:N":"||--o{","N:1":"}o--||","N:M":"}o--o{"},eh=/^[A-Za-z_][A-Za-z0-9_-]*$/,em=e=>eh.test(e)?e:`"${e.replace(/"/g,"'")}"`,eu=(e,t)=>{let n=e.trim().replace(/[^A-Za-z0-9_()[\]-]+/g,"_").replace(/^_+|_+$/g,"");return/^[A-Za-z_]/.test(n)?n:n?`_${n}`:t},ep=e=>`"${e.replace(/"/g,"'")}"`,ef=["settings","states","parallel","entities","participants","messages","fragments","members","state"];function eg(e){let t=!1,n=e=>{if(Array.isArray(e)){let t=!1,s=e.map(e=>{let s=n(e);return s!==e&&(t=!0),s});return t?s:e}if(!e||"object"!=typeof e)return e;let s=null;if("notes"in e&&"string"!=typeof e.notes&&void 0!==e.notes){s={...e};let n=function(e){if(null!=e)return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"string"==typeof e?e:JSON.stringify(e)).join("\n\n"):JSON.stringify(e)}(e.notes);void 0!==n&&n.trim()?s.notes=n:delete s.notes,t=!0}for(let t of ef){if(!(t in e))continue;let r=(s??e)[t],a=n(r);a!==r&&((s??={...e})[t]=a)}return s??e},s=n(e);return t?s:e}function ex(e){return`${e.name} : ${e.type}`}function ey(e){let t=(e.attributes??[]).filter(e=>e?.name);return{width:Math.min(340,Math.max(170,Math.ceil(6.6*Math.max(1.15*(e.name??"").length,...t.map(e=>ex(e).length+6.96969696969697))+28))),height:30+20*Math.max(1,t.length)+8}}function eb(e){return e.trim().replace(/[\s_]+/g,"-").replace(/[^A-Za-z0-9.-]/g,"").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,60)}let ev=["alt","opt","loop"];function ew(e){return!!e&&"object"==typeof e&&Array.isArray(e.participants)&&Array.isArray(e.messages)&&!("state"in e)&&!("entities"in e)}function ej(e,t,n){return{settings:n?{namespace:e,name:t,description:n}:{namespace:e,name:t},participants:[],messages:[]}}function ek(e,t){return null===e?String(t+1):`f${e+1}.${t+1}`}function e$(e,t){if(/^\d+$/.exec(t)){let n=Number(t)-1,s=e.messages?.[n];return s?{fragment:null,index:n,message:s}:null}let n=/^f(\d+)\.(\d+)$/.exec(t);if(!n)return null;let s=Number(n[1])-1,r=Number(n[2])-1,a=e.fragments?.[s]?.messages?.[r];return a?{fragment:s,index:r,message:a}:null}function eN(e){let t=[];return(e.messages??[]).forEach((e,n)=>t.push({ref:ek(null,n),message:e,fragment:null})),(e.fragments??[]).forEach((e,n)=>(e?.messages??[]).forEach((e,s)=>t.push({ref:ek(n,s),message:e,fragment:n}))),t}function eS(e){let t=[];e?.settings?.name||t.push({ruleId:"S001",message:"The sequence has no settings.name",element:"settings"});let n=new Set;for(let[s,r]of(e.participants??[]).entries()){if(!r?.name){t.push({ruleId:"S002",message:`Participant at index ${s} has no name`,element:`participants[${s}]`});continue}n.has(r.name)&&t.push({ruleId:"S002",message:`Duplicate participant "${r.name}"`,element:r.name}),n.add(r.name)}let s=(e,s)=>{if(!e)return void t.push({ruleId:"S003",message:`Message ${s} is empty`,element:`message:${s}`});for(let r of["from","to"])e[r]&&n.has(e[r])||t.push({ruleId:"S003",message:`Message ${s} ${"from"===r?"comes from":"goes to"} "${e[r]??""}", which is not a participant`,element:`message:${s}`});e.label?.trim()||t.push({ruleId:"S004",message:`Message ${s} has no label`,element:`message:${s}`})};(e.messages??[]).forEach((e,t)=>s(e,ek(null,t)));let r=(e.messages??[]).length;for(let[n,a]of(e.fragments??[]).entries()){let e=`fragment:${n+1}`;if(!a||!ev.includes(a.kind)){t.push({ruleId:"S005",message:`Fragment ${n+1} has kind "${a?.kind??""}"; expected one of ${ev.join(", ")}`,element:e});continue}(!Number.isInteger(a.after)||a.after<0||a.after>r)&&t.push({ruleId:"S005",message:`Fragment ${n+1} branches after message ${a.after}, but the main sequence has messages 1 to ${r}`,element:e}),a.messages?.length||t.push({ruleId:"S006",message:`Fragment ${n+1} (${a.kind}) holds no message`,element:e}),(a.messages??[]).forEach((e,t)=>s(e,ek(n,t)))}return t}let eE=e=>{let t={settings:{...e.settings},participants:(e.participants??[]).map(e=>({...e,...e.holds?{holds:[...e.holds]}:{}})),messages:(e.messages??[]).map(e=>({...e}))};return e.fragments&&(t.fragments=e.fragments.map(e=>({...e,messages:(e.messages??[]).map(e=>({...e}))}))),t};function eC(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e&&!(Array.isArray(e)&&0===e.length)))}function eM(e,t){let n=e.participants.find(e=>e.name===t);if(!n){let n=e.participants.map(e=>e.name).join(", ")||"none";throw Error(`Participant '${t}' not found. Participants: ${n}.`)}return n}function e_(e,t){if(eM(e,t.from),eM(e,t.to),!t.label?.trim())throw Error("A message needs a label: what is said or done, in a few words.")}function eA(e,t){let n=e.fragments?.[t];if(n&&!Array.isArray(n.messages)&&(n.messages=[]),!n)throw Error(`Fragment ${t+1} not found. The sequence has ${e.fragments?.length??0} fragment(s).`);return n}function eO(e,t,n){let s=eE(e),r=eM(s,t),a=eC({...r,...n});return s.participants[s.participants.indexOf(r)]=a,s}function eR(e,t,n){let s=eE(e);e_(s,t);let r=void 0===n?s.messages.length:Math.max(0,Math.min(n,s.messages.length));if(s.messages.splice(r,0,eC({...t})),s.fragments)for(let e of s.fragments)e.after>r&&(e.after+=1);return s}function eP(e,t,n,s=null){let r=eE(e),a=null===s?r.messages:eA(r,s).messages,i=a[t];if(!i)throw Error(`Message ${t+1} not found${null===s?"":` in fragment ${s+1}`}.`);let o=eC({...i,...n});return e_(r,o),a[t]=o,r}function eT(e,t,n){let s=eE(e);if(!s.messages[t])throw Error(`Message ${t+1} not found.`);let r=Math.max(0,Math.min(n,s.messages.length-1)),a=(s.fragments??[]).map(e=>e.after>0?s.messages[e.after-1]:null),[i]=s.messages.splice(t,1);return s.messages.splice(r,0,i),(s.fragments??[]).forEach((e,t)=>{let n=a[t];n&&(e.after=s.messages.indexOf(n)+1)}),s}let eI={columnGap:150,rowHeight:34,headerHeight:34,topGap:30,fragmentPad:30,margin:24,fontSize:12};function eL(e,t={}){let n={...eI,...t},s=(Array.isArray(e.participants)?e.participants:[]).map(e=>({...e,name:"string"==typeof e?.name?e.name:""})),r=(Array.isArray(e.messages)?e.messages:[]).filter(e=>!!e&&"object"==typeof e),a=e=>Math.max(90,N(e,n.fontSize)+28),i=[],o=n.margin;s.forEach((t,l)=>{let c=a(t.name);if(0===l)i.push(o+c/2);else{let o=a(s[l-1].name),d=function(e,t,n,s,r){let a=0;for(let i of[...e,...(Array.isArray(t.fragments)?t.fragments:[]).flatMap(e=>(Array.isArray(e?.messages)?e.messages:[]).filter(e=>!!e&&"object"==typeof e))])(i.from===n&&i.to===s||i.from===s&&i.to===n)&&(a=Math.max(a,N("string"==typeof i.label?i.label:"",r)+30));return a}(r,e,s[l-1].name,t.name,n.fontSize),h=Math.max(n.columnGap,(o+c)/2+20,d+24);i.push(i[l-1]+h)}});let l=new Map(s.map((e,t)=>[e.name,i[t]])),c=s.map((e,t)=>{let s=a(e.name);return{name:e.name,x:i[t],left:i[t]-s/2,top:n.margin,width:s,height:n.headerHeight}}),d=[],h=n.margin+n.headerHeight+n.topGap,m=0,u=(e,t,s,r,a)=>{let i=l.get(s)??n.margin,o=l.get(r)??n.margin,c=s===r;c&&(m=Math.max(m,i+44+N("string"==typeof a?a:"",n.fontSize))),d.push({ref:ek(e,t),fragment:e,index:t,y:h,fromX:i,toX:o,self:c}),h+=n.rowHeight};(Array.isArray(e.messages)?e.messages:[]).forEach((e,t)=>{e&&"object"==typeof e&&u(null,t,e.from,e.to,e.label)});let p=n.margin/2,f=Math.max(i.length?i[i.length-1]+a(s[s.length-1].name)/2:n.margin,m)+n.margin/2,g=[];(Array.isArray(e.fragments)?e.fragments:[]).forEach((e,t)=>{if(!e||"object"!=typeof e)return;let s=(h+=n.rowHeight/2)-n.rowHeight/2;h+=n.fragmentPad-n.rowHeight/2+6,(Array.isArray(e.messages)?e.messages:[]).forEach((e,n)=>{e&&"object"==typeof e&&u(t,n,e.from,e.to,e.label)});let r=h-s+n.fragmentPad/2-n.rowHeight/2;g.push({index:t,left:p,top:s,width:f-p,height:r,headingY:s+16}),h=s+r+n.rowHeight/2});let x=n.margin+n.headerHeight,y=h;return{participants:c,rows:d,fragments:g,lifelineTop:x,lifelineBottom:y,width:Math.max(f+n.margin/2,2*n.margin+200),height:y+n.margin}}let eD=e=>e.replace(/[;#\n\r]+/g," ").replace(/\s+/g," ").trim(),eq=["propose","auto"];function eB(e,t){return"auto"===t||"propose"===t?t:e?.settings?.reconcile==="auto"?"auto":"propose"}let eF=["person","agent","service","external"];function eY(e){return e.toLowerCase().endsWith(".sysdf.json")}function ez(e){return!!e&&"object"==typeof e&&Array.isArray(e.members)&&!("state"in e)&&!("entities"in e)&&!("participants"in e)}function eU(e){return e.toLowerCase().endsWith(".erdf.json")?"erd":e.toLowerCase().endsWith(".sqdf.json")?"sequence":eY(e)?"system":"machine"}function eX(e){return e&&"object"==typeof e?W(e)?"erd":ew(e)?"sequence":ez(e)?"system":"state"in e?"machine":null:null}let eH=["erd","machine","sequence"];function eJ(e,t){return t.startsWith("/")?eV(t):eV((e.slice(0,e.lastIndexOf("/")+1)||"./")+t)}function eV(e){let t=e.startsWith("/"),n=[];for(let s of e.split("/"))if(s&&"."!==s){if(".."===s){n.length&&".."!==n[n.length-1]?n.pop():t||n.push("..");continue}n.push(s)}return(t?"/":"")+n.join("/")}let eW=e=>({settings:{...e.settings},members:(e.members??[]).map(e=>({...e})),actors:(e.actors??[]).map(e=>({...e}))});function eK(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e))}function eZ(e,t){let n=eW(e);return n.settings=eK({...n.settings,...t}),n}let eG=["refused","unknown-event","ended","state-mismatch"];function eQ(e,t=0){return e.settings?.name||e.state?.name||`machine ${t+1}`}function e0(e){let t=e.map((e,t)=>eQ(e,t));return t.map((e,n)=>t.indexOf(e)===n&&t.lastIndexOf(e)===n?e:`${e} #${n+1}`)}function e1(e,t){let n=e.states.get(t);for(;n&&n.states?.length;){let e=n.states.find(e=>"history"!==e.kind);if(!e)return null;n=e}return n?.name??null}function e2(e,t,n){let s=t;for(;s;){if(s===n)return!0;s=e.parent.get(s)}return!1}let e5=(e,t)=>e.states.get(t)?.kind==="final";function e4(e,t){let n,s,r=e0(t),a=t.map((e,t)=>(function(e,t,n){let s=new Map,r=new Map,a=(e,t)=>{if(e?.name){for(let n of(s.has(e.name)||(s.set(e.name,e),r.set(e.name,t)),e.states??[]))a(n,e.name);for(let t of e.parallel?.states??[])a(t,e.name)}};e.state&&a(e.state,null);let i=new Set;for(let t of e.events??[])for(let e of t?.events??[])e?.id&&i.add(e.id);for(let t of e.events??[])for(let e of t?.timers??[])e?.id&&i.add(e.id);let o={name:n,def:e,states:s,parent:r,events:i,initial:null};return o.initial=e.state?e1(o,e.state.name):null,o})(e,0,r[t])),i=(s=[{name:"main",kind:"main",items:n=(e.messages??[]).map((e,t)=>({ref:ek(null,t),message:e}))}],n.some(e=>e.message?.optional)&&s.push({name:"main without optional messages",kind:"without-optional",items:n.filter(e=>!e.message?.optional)}),(e.fragments??[]).forEach((e,t)=>{if(!e)return;let r=(e.messages??[]).map((e,n)=>({ref:ek(t,n),message:e})),a=Math.max(0,Math.min(e.after??0,n.length)),i=n.slice(0,a),o=n.slice(a),l=`${e.kind} ${t+1} \xb7 ${e.label??""}`.trim();"alt"===e.kind?s.push({name:l,kind:"alt",fragment:t,items:[...i,...r]}):"opt"===e.kind?s.push({name:l,kind:"opt",fragment:t,items:[...i,...r,...o]}):"loop"===e.kind&&s.push({name:l,kind:"loop",fragment:t,items:[...i,...r,...r,...o]})}),s).map(e=>(function(e,t){let n=new Map;for(let e of t){let t=e.initial&&e5(e,e.initial)?e.initial:null;n.set(e.name,{states:e.initial?[e.initial]:[],ended:t})}let s=[],r=new Map;for(let e of t){let t=eQ(e.def);r.set(t,r.has(t)?null:e),e.name!==t&&r.set(e.name,e)}for(let{ref:a,message:i}of e.items){if(!i)continue;let e=i.label??"";if(!i.event){let r={ref:a,label:e,from:[],to:[],result:"data"};i.state&&function(e,t,n,s){let r=n.filter(e=>t.machine?e.name===t.machine:e.states.has(t.state));if(!r.length){e.result="state-mismatch",e.note=t.machine?`no member machine is named "${t.machine}"`:`no member machine has a state "${t.state}"`;return}for(let n of r){let r=s.get(n.name),a=r.states.filter(e=>e2(n,e,t.state));if(a.length){r.states=a;continue}e.machine=n.name,e.from=e.to=[...r.states],e.result="state-mismatch",e.note=`the scenario says ${n.name} is in ${t.state}; the walk has it in ${r.states.join(" or ")||"no state"}`;return}}(r,i,t,n),s.push(r);continue}let o=i.event,l=t.filter(e=>e.events.has(o));if(i.machine){let t=r.get(i.machine);if(!t){let n=null===t?`two member machines are named "${i.machine}"`:`no member machine is named "${i.machine}"`;s.push({ref:a,label:e,event:o,from:[],to:[],result:"unknown-event",note:n});continue}if(!(l=l.filter(e=>e===t)).length){s.push({ref:a,label:e,event:o,machine:t.name,from:[],to:[],result:"unknown-event",note:`"${t.name}" does not define the event "${o}"`});continue}}if(!l.length){s.push({ref:a,label:e,event:o,from:[],to:[],result:"unknown-event",note:`no member machine defines the event "${o}"`});continue}for(let t of l){let r=n.get(t.name),l=[...r.states];if(r.ended){s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"ended",note:`${t.name} ended in ${r.ended} before this message`});continue}let c=l.filter(e=>!e5(t,e));if(!c.length){s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"ended",note:`${t.name} ended in ${l.join(" or ")} before this message`});continue}let d=new Set,h=new Map,m=new Set,u=[];for(let e of c)for(let n of function(e,t,n){let s=[],r=t;for(;r;){for(let t of e.states.get(r)?.transitions??[])if(t?.event===n&&(s.push(t),!t.condition))return s;r=e.parent.get(r)}return s}(t,e,o)){let s=n.nextState?e1(t,n.nextState):e;if(!s){u.push(n.nextState);continue}d.add(s),s!==e&&m.add(s),n.condition&&h.set(s,(h.get(s)??new Set).add(n.condition))}if(!d.size){let n=u.length?`${t.name}'s transition for "${o}" from ${c.join(" or ")} leads to ${[...new Set(u)].join(", ")}, which cannot be entered`:`${t.name} has no transition for "${o}" from ${c.join(" or ")}`;s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"refused",note:n});continue}let p=[...d],f={ref:a,label:e,event:o,machine:t.name,from:l,to:p,result:"moved"};if(i.state&&(!i.machine||i.machine===t.name)){let e=t.states.has(i.state);if(e||i.machine===t.name){let n=p.filter(e=>e2(t,e,i.state));n.length?p=n:(f.result="state-mismatch",f.note=e?`the scenario says ${t.name} is in ${i.state}; the walk has it in ${p.join(" or ")}`:`${t.name} has no state "${i.state}"`)}}f.to=p,"moved"!==f.result||p.some(e=>m.has(e))||(f.result="stayed");let g=new Set(p.flatMap(e=>[...h.get(e)??[]]));g.size&&(f.guards=[...g]),r.states=p;let x=p.filter(e=>e5(t,e));x.length&&x.length===p.length&&(r.ended=x[0]),s.push(f)}}let a={};for(let[e,t]of n)a[e]=t.states;return{name:e.name,kind:e.kind,...void 0===e.fragment?{}:{fragment:e.fragment},steps:s,accepted:!s.some(e=>eG.includes(e.result)),end:a}})(e,a));return{scenario:e.settings?.name??"",machines:a.map(e=>e.name),paths:i,accepted:i.every(e=>e.accepted)}}function e3(e){let t={machines:[],erds:[],sequences:[]};for(let n of e)n.def&&!n.error&&eX(n.def)===n.kind&&("machine"===n.kind&&t.machines.push({member:n.path,def:n.def}),"erd"===n.kind&&t.erds.push({member:n.path,def:n.def}),"sequence"===n.kind&&t.sequences.push({member:n.path,def:n.def}));return t}function e6(e,t){let n=[],s=(e,t,s,r)=>{n.push({ruleId:e,message:t,severity:"error",...s?{member:s}:{},...r?{element:r}:{}})},r=(e,t,s,r)=>{n.push({ruleId:e,message:t,severity:"warning",...s?{member:s}:{},...r?{element:r}:{}})};if(e){e.settings?.name||s("Y001","The system has no settings.name"),e.settings?.namespace||s("Y001","The system has no settings.namespace");let t=new Set;for(let[n,r]of(e.members??[]).entries()){if(!r?.path){s("Y002",`Member at index ${n} has no path`,void 0,`members[${n}]`);continue}t.has(r.path)&&s("Y002",`"${r.path}" is listed twice`,r.path),t.add(r.path),eH.includes(eU(r.path))&&r.path.endsWith(".json")||s("Y002",`"${r.path}" is not a document a system holds (.erdf.json, .smdf.json, .sqdf.json)`,r.path)}let n=new Set;for(let[t,r]of(e.actors??[]).entries()){if(!r?.name){s("Y004",`Actor at index ${t} has no name`,void 0,`actors[${t}]`);continue}n.has(r.name)&&s("Y004",`Duplicate actor "${r.name}"`,void 0,r.name),n.add(r.name),eF.includes(r.kind)||s("Y004",`Actor "${r.name}" has kind "${r.kind??""}"; expected one of ${eF.join(", ")}`,void 0,r.name)}}for(let e of t)e.error||!e.def?s("Y003",`"${e.path}" cannot be read: ${e.error??"no content"}`,e.path):eX(e.def)!==e.kind&&s("Y003",`"${e.path}" is named as a ${e.kind} but holds ${eX(e.def)??"something else"}`,e.path);let{machines:a,erds:i,sequences:o}=e3(t),l=new Map;for(let{member:e,def:t}of a){let n=eQ(t),r=l.get(n);r?s("Y005",`"${e}" and "${r}" are both machines named "${n}"; a message cannot say which`,e):l.set(n,e)}for(let{member:e,def:t}of i)for(let n of K(t))s(n.ruleId,n.message,e,n.element);for(let{member:e,def:t}of o)for(let n of eS(t))s(n.ruleId,n.message,e,n.element);let c=function(e){if(!e.length)return null;let t=new Set,n=e.flatMap(({def:e})=>e.entities??[]).filter(e=>e?.name&&!t.has(e.name)&&t.add(e.name));return{settings:{namespace:e[0].def.settings?.namespace??"",name:e.map(e=>e.def.settings?.name).join(" + ")},entities:n,relationships:e.flatMap(({def:e})=>e.relationships??[])}}(i);if(c){for(let{member:e,def:t}of a)for(let n of G(t,c))s(n.ruleId,n.message,e,n.element);let e=a.map(({def:e},t)=>eQ(e,t));for(let{member:t,def:n}of i)for(let r of Q(n,e))s(r.ruleId,r.message,t,r.element)}for(let{member:e,def:t}of a){let n=(s,a)=>{if(!s)return;let i=a||(s.transitions??[]).length>0,o=s.states??[];for(let a of(o.length||s.parallel||s===t.state||"final"===s.kind||"history"===s.kind||i||r("L009",`${eQ(t)}: ${s.name} has no way out and is not final; say how the machine leaves it, or mark it final`,e,`state:${s.name}`),o))n(a,i)};n(t.state,!1)}let d=a.map(e=>e.def),h=new Set(d.map((e,t)=>eQ(e,t))),m=new Map,u=new Set,p=new Set;d.forEach((e,t)=>{let n=new Set;for(let t of e.events??[]){for(let e of t?.events??[])e?.id&&n.add(e.id);for(let e of t?.timers??[])e?.id&&n.add(e.id)}m.set(eQ(e,t),n);let s=e=>{e&&(u.add(e.name),(e.states??[]).forEach(s),(e.parallel?.states??[]).forEach(s))};for(let t of(s(e.state),e.settings?.objects??[]))t?.instance&&p.add(t.instance)});let f=new Set((c?.entities??[]).map(e=>e.name)),g=new Set((e?.actors??[]).map(e=>e.name)),x=[];for(let{member:t,def:n}of o){let a=!1,i=e=>!!c||(a||r("L006",`${e} name entities, but the system has no ERD to hold them`,t),a=!0,!1);for(let r of n.participants??[]){if(!r?.name)continue;let n=`participant:${r.name}`;if(r.actor&&e&&!g.has(r.actor)&&s("L006",`Participant "${r.name}" is the actor "${r.actor}", which the system does not list`,t,n),r.object&&!p.has(r.object)&&s("L006",`Participant "${r.name}" is the object "${r.object}", which no member machine declares`,t,n),r.holds?.length&&i("Participants' holds"))for(let e of r.holds)f.has(e)||s("L006",`Participant "${r.name}" holds "${e}", which is not an entity`,t,n)}for(let{ref:e,message:a}of eN(n)){if(!a)continue;let n=`message:${e}`;a.machine&&!h.has(a.machine)?s("L005",`Message ${e} names the machine "${a.machine}", which is not a member`,t,n):a.event&&((a.machine?m.get(a.machine)?.has(a.event):[...m.values()].some(e=>e.has(a.event)))||s("L005",`Message ${e} fires "${a.event}", which ${a.machine?`"${a.machine}" does not define`:"no member machine defines"}`,t,n)),a.carries&&i("Messages' carries")&&!f.has(a.carries)&&s("L007",`Message ${e} carries "${a.carries}", which is not an entity`,t,n),a.state&&!u.has(a.state)&&r("L008",`Message ${e} says the machine is then in "${a.state}", which no member machine has`,t,n)}let o=e4(n,d);for(let e of(x.push({member:t,report:o}),o.paths)){let n=e.steps.filter(e=>"refused"===e.result||"ended"===e.result||"state-mismatch"===e.result);for(let s of[...new Set(n.map(e=>e.machine??""))]){let a=n.filter(e=>(e.machine??"")===s),i=a[0],o=a.length>1?` (${a.length-1} later message${a.length>2?"s stop":" stops"} too)`:"",l="without-optional"===e.kind?" — a message the rest depends on may not be optional":"";r("L008",`${e.name}, message ${i.ref}: ${i.note??i.result}${o}${l}`,t,`message:${i.ref}`)}}}return{issues:n,replays:x}}function e8(e){return`${e.kind}:${e.name}`}function e7(e){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);return["entity","attribute","machine","object","event","state","participant","message"].includes(n)?{kind:n,name:e.slice(t+1)}:null}function e9(e){let{machines:t,erds:n,sequences:s}=e3(e),r=[],a=new Map;for(let{member:e,def:t}of n)for(let n of t.entities??[])n?.name&&!a.has(n.name)&&a.set(n.name,e);let i=new Map;for(let{def:e}of n)for(let t of e.entities??[])i.set(t.name,new Set((t.attributes??[]).map(e=>e.name)));let o=new Map,l=new Map;t.forEach(({member:e,def:t},n)=>{let s=eQ(t,n);for(let n of t.events??[])for(let t of[...n?.events??[],...n?.timers??[]]){if(!t?.id)continue;let n=o.get(t.id)??[];n.push({member:e,machine:s}),o.set(t.id,n)}for(let n of t.settings?.objects??[]){if(!n?.instance)continue;l.has(n.instance)||l.set(n.instance,{member:e,className:n.class});let t=a.get(n.class);t&&r.push({from:{member:e,kind:"object",name:n.instance},to:{member:t,kind:"entity",name:n.class},rule:"L001",text:`is constructed as the entity ${n.class}`,back:`is the class of ${s}'s object ${n.instance}`})}let c=n=>{if(n){for(let s of n.transitions??[])if(s?.condition)for(let o of t.settings?.objects??[]){let t=a.get(o.class);if(t)for(let a of Z(s.condition,o.instance))i.get(o.class)?.has(a)&&r.push({from:{member:e,kind:"event",name:s.event},to:{member:t,kind:"attribute",name:`${o.class}.${a}`},rule:"L002",text:`its guard on ${n.name} reads ${o.class}.${a}`,back:`is read by the ${s.event} guard on ${n.name}`})}(n.states??[]).forEach(c)}};c(t.state)});let c=e0(t.map(e=>e.def)),d=new Map(t.map(({member:e},t)=>[c[t],e]));for(let{member:e,def:s}of n)for(let n of s.entities??[])for(let s of n.attributes??[])for(let a of J(s)){let i=d.get(a)??t.find(({def:e})=>eQ(e)===a)?.member;i&&r.push({from:{member:e,kind:"attribute",name:`${n.name}.${s.name}`},to:{member:i,kind:"machine",name:a},rule:"L003",text:`stores the state of ${a}`,back:`keeps its state in ${n.name}.${s.name}`})}for(let{member:e,def:n}of s){for(let t of n.participants??[]){if(!t?.name)continue;let n={member:e,kind:"participant",name:t.name},s=t.object?l.get(t.object):void 0;for(let e of(s&&r.push({from:n,to:{member:s.member,kind:"object",name:t.object},rule:"L006",text:`is the object ${t.object}`,back:`is the participant ${t.name}`}),t.holds??[])){let s=a.get(e);s&&r.push({from:n,to:{member:s,kind:"entity",name:e},rule:"L006",text:`holds ${e}`,back:`is held by ${t.name}`})}}for(let{ref:t,message:s}of eN(n)){if(!s)continue;let i={member:e,kind:"message",name:t};if(s.event)for(let e of o.get(s.event)??[])s.machine&&s.machine!==e.machine||r.push({from:i,to:{member:e.member,kind:"event",name:s.event},rule:"L005",text:`fires ${s.event}`,back:`is fired by message ${t} of ${n.settings?.name??"the scenario"}`});if(s.carries){let e=a.get(s.carries);e&&r.push({from:i,to:{member:e,kind:"entity",name:s.carries},rule:"L007",text:`carries ${s.carries}`,back:`is carried by message ${t}`})}}let s=e4(n,t.map(e=>e.def)).paths.find(e=>"main"===e.kind);for(let t of s?.steps??[]){if("moved"!==t.result||!t.machine)continue;let n=d.get(t.machine);if(n)for(let s of t.to)r.push({from:{member:e,kind:"message",name:t.ref},to:{member:n,kind:"state",name:s},rule:"L008",text:`moves ${t.machine} to ${s}`,back:`is entered on message ${t.ref}`})}}return r}let te=e=>{let t=e.replace(/[^A-Za-z0-9]+(.)?/g,(e,t)=>t?t.toUpperCase():"").replace(/^[^A-Za-z]+/,"");return t?t.charAt(0).toUpperCase()+t.slice(1):"Scenario"};function tt(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n)||(e.parallel?.states??[]).some(n));return n(e.state)}let tn=(e,t)=>t?"service":/\b(agent|bot|assistant)\b/i.test(e)?"agent":"person";function ts(e,t){let{machines:n,erds:s,sequences:r}=e3(t),a=[],i=e=>{a.includes(e)||a.push(e)},o=e,l=[];if(o)for(let{def:e}of r)for(let t of e.participants??[]){if(!t?.actor||(o.actors??[]).some(e=>e.name===t.actor))continue;let n=tn(t.actor,t.service);o=function(e,t){if(!t.name?.trim())throw Error("An actor needs a name.");if(!eF.includes(t.kind))throw Error(`An actor is one of ${eF.join(", ")}; got '${t.kind}'.`);let n=eW(e);if((n.actors??[]).some(e=>e.name===t.name))throw Error(`Actor '${t.name}' already exists.`);return(n.actors??=[]).push(eK({...t})),n}(o,{name:t.actor,kind:n}),l.push(`the system gains the ${n} "${t.actor}", who takes part in ${e.settings?.name??"a scenario"}`)}let c=s.map(e=>({member:e.member,def:e.def,reasons:[]})),d=new Set(c.flatMap(e=>(e.def.entities??[]).map(e=>e.name)));for(let{def:e}of r){let t=[];for(let n of e.participants??[])for(let s of n?.holds??[])s?.trim()&&t.push({name:s.trim(),why:`${n.name} holds it in ${e.settings?.name??"a scenario"}`});for(let{ref:n,message:s}of eN(e))s?.carries?.trim()&&t.push({name:s.carries,why:`message ${n} of ${e.settings?.name??"a scenario"} carries it`});for(let e of t){if(d.has(e.name))continue;if(!c.length){i(`"${e.name}" is named as data (${e.why}), but the system has no ERD to hold it; add a .erdf.json member`);continue}let t=c[0];t.def=es(t.def,{name:e.name,notes:`Added from the scenario: ${e.why}.`}),t.reasons.push(`${t.def.settings?.name??t.member} gains the entity ${e.name}, because ${e.why}`),d.add(e.name)}}let h=n.map(e=>e.def),m=e0(h),p=h.map(()=>[]),f=h.map(()=>[]),g=(e,t,n)=>{h=h.map((n,s)=>s===e?u(n,t):n),p[e].push(...t),f[e].push(n)};for(let{def:e}of r){for(let t of e.participants??[]){if(!t?.object||h.some(e=>(e.settings?.objects??[]).some(e=>e.instance===t.object)))continue;let e=(t.holds??[]).filter(e=>e?.trim()),n=1===e.length?e[0].trim():null;1===h.length&&n?g(0,[{op:"settings.update",patch:{objects:[...h[0].settings?.objects??[],{instance:t.object,class:n}]}}],`${m[0]} is constructed with the object ${t.object} : ${n}, because ${t.name} is it`):i(`${t.name} is the object "${t.object}", which no machine declares; ${1===h.length?"say which entity it is by holding exactly one":"declare it on the machine it belongs to"}`)}let t=function(e,t,n={}){let s=n.maxRounds??100,r=t.map(e=>e),a=e0(r),i=new Map,o=[],l=new Set,c=e4(e,r),d=new Set,h="",m=(e,t,n)=>{d.add(`${e}|${JSON.stringify(t)}`),r=r.map((n,s)=>s===e?u(n,t):n);let s=i.get(e)??{machine:a[e],index:e,ops:[],reasons:[]};s.ops.push(...t),s.reasons.push(n),i.set(e,s)},p=!0;for(let t=0;t<s;t++){let t=(function(e){let t=[];for(let n of e.paths)for(let e of n.steps)("refused"===e.result||"unknown-event"===e.result||"ended"===e.result||"state-mismatch"===e.result)&&t.push({path:n,step:e});return t})(e4(e,r)).find(({path:e,step:t})=>!l.has(`${t.ref}|${t.machine??""}|${t.result}|${e.name}`)&&!l.has(`${e.name}|${t.machine??""}`));if(!t){p=!1;break}let{path:n,step:s}=t,i=`${s.ref}|${s.machine??""}|${s.result}|${n.name}`,c=`${i}|${s.from.join("|")}`,u=c===h;h=c;let f=e$(e,s.ref)?.message,g=`message ${s.ref} (${n.name})`,x=(e,t)=>{l.add(i),l.add(`${n.name}|${s.machine??""}`),o.includes(t)||o.push(t)};if("without-optional"===n.kind){let t=(e.messages??[]).map((e,t)=>e?.optional?String(t+1):"").filter(Boolean);x(i,`${g}: without its optional message${t.length>1?"s":""} ${t.join(", ")} the scenario stops (${s.note??s.result}); if the rest depends on ${t.length>1?"them, they are":"it, it is"} not optional`);continue}if(!f){x(i,`${g}: cannot be read back from the sequence`);continue}if(u){x(i,`${g}: the change proposed for it did not let the walk through (${s.note??s.result}); a person has to look at ${s.machine??"the machine"}`);continue}let y=(e,t,n)=>{d.has(`${e}|${JSON.stringify(t)}`)?x(i,`${g}: the change it needs was already proposed and did not take effect (${s.note??s.result})`):m(e,t,n)};if("unknown-event"===s.result){let e=f.machine?r.map((e,t)=>a[t]===f.machine||(e.settings?.name??"")===f.machine?t:-1).filter(e=>e>=0):1===r.length?[0]:[];if(e.length>1){x(i,`${g}: ${e.length} member machines are named "${f.machine}"; rename one so the message can say which`);continue}let t=e.length?e[0]:-1;if(t<0){x(i,f.machine?`${g}: fires "${f.event}" for "${f.machine}", which is not a member machine`:`${g}: fires "${f.event}", which no machine defines; set the message's machine to say which one should`);continue}let n=r[t],s=`${te(f.from)}Events`,o=te(f.from),l=(n.events??[]).findIndex(e=>e?.name===s||e?.name===o||e?.name===f.from||e?.feeder===f.from),c=l>=0?n.events[l].name:s;y(t,l>=0?[{op:"event.add",sourceIndex:l,event:{id:f.event}}]:[{op:"eventSource.add",source:{name:s,events:[{id:f.event}]}}],`${a[t]} defines "${f.event}" in ${c}, because ${g} fires it`);continue}if("refused"===s.result){let e=a.indexOf(s.machine??"");if(!f.state){x(i,`${g}: ${s.machine} refuses "${f.event}" from ${s.from.join(" or ")}; give the message a state to say where it leads, and reconcile can add the transition`);continue}if(1!==s.from.length){x(i,`${g}: ${s.machine} could be in ${s.from.join(" or ")}; choose which state "${f.event}" leaves from`);continue}let t=r[e],n=s.from[0],o=tt(t,f.state);if(!o&&!f.machine){let t=a.filter((t,n)=>n!==e&&tt(r[n],f.state)),n=r.filter(e=>(function(e){let t=new Set;for(let n of e.events??[])for(let e of[...n?.events??[],...n?.timers??[]])e?.id&&t.add(e.id);return t})(e).has(f.event)).length;if(t.length||n>1){x(i,`${g}: "${f.state}" ${t.length?"is a state of another machine":"is claimed while several machines hear the event"}; set the message's machine to say which machine it is about`);continue}}if(!function(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n));return n(e.state)}(t,n)){x(i,`${g}: ${s.machine} is in ${n}, inside a parallel region, which reconcile does not edit`);continue}let l=[],c=[],d=n===t.state?.name&&!(t.state?.states??[]).length;if(o||(l.push({op:"state.add",parent:null,state:{name:f.state,transitions:[]}}),c.push(d?`gains its first state, ${f.state}`:`adds the state ${f.state}`)),d){y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says the machine is there`);continue}l.push(n===f.state?{op:"transition.add",state:n,transition:{event:f.event}}:{op:"transition.add",state:n,transition:{event:f.event,nextState:f.state}}),c.push(n===f.state?`handles "${f.event}" in ${n} without leaving it`:`goes from ${n} to ${f.state} on "${f.event}"`),y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says so`);continue}if("state-mismatch"===s.result){x(i,`${g}: ${s.note??"the scenario and the machine disagree"}; one of them has to change, and that is a person's call`);continue}x(i,`${g}: ${s.note??s.result}`)}return p&&o.push(`reconcile stopped after ${s} rounds; what it proposed so far is kept, and the rest needs a person`),{proposals:[...i.values()].sort((e,t)=>e.index-t.index),unresolved:o,before:c,after:e4(e,r),machines:r}}(e,h);for(let e of t.proposals)p[e.index].push(...e.ops),f[e.index].push(...e.reasons);for(let n of(h=t.machines,t.unresolved))i(`${e.settings?.name??"scenario"}: ${n}`)}let x=n.map((e,t)=>({member:e.member,index:t,machine:m[t],ops:p[t],reasons:f[t],def:h[t]})).filter(e=>e.ops.length),y=c.filter(e=>e.reasons.length);return{machines:x,erds:y,system:o&&l.length?{def:o,reasons:l}:null,unresolved:a,count:x.reduce((e,t)=>e+t.reasons.length,0)+y.reduce((e,t)=>e+t.reasons.length,0)+l.length}}function tr(e,t){if(!e.count&&!e.unresolved.length)return"auto"===t?"auto: the drawings already agree":"the drawings agree";let n=[...e.machines.map(e=>`${e.machine} +${e.reasons.length}`),...e.erds.map(e=>`${e.def.settings?.name??e.member} +${e.reasons.length}`),...e.system?[`system +${e.system.reasons.length}`]:[]],s=n.length?n.join(", "):"no change",r=e.unresolved.length?`; ${e.unresolved.length} left open`:"";return"auto"===t?`auto: ${s}${r}`:`${e.count} change${1===e.count?"":"s"} proposed (${s})${r}`}function ta(e){return e.parallel?e.parallel.states:e.states??[]}function ti(e,t){return ta(e).find(e=>e.name===t)??null}let to={surface:"--slc-surface",nodeFill:"--slc-node-fill",nodeStroke:"--slc-node-stroke",compositeFill:"--slc-composite-fill",finalFill:"--slc-final-fill",accent:"--slc-accent",accentFill:"--slc-accent-fill",accentInk:"--slc-accent-ink",danger:"--slc-danger",drawSource:"--slc-draw-source",edge:"--slc-edge",chipFill:"--slc-chip-fill",chipStroke:"--slc-chip-stroke",label:"--slc-label",muted:"--slc-muted",faint:"--slc-faint",entry:"--slc-entry",exit:"--slc-exit",composite:"--slc-composite",active:"--slc-active",panelBg:"--slc-panel-bg",panelBorder:"--slc-panel-border",panelHover:"--slc-panel-hover"};function tl(e){let t={};if(!e)return t;for(let[n,s]of Object.entries(e)){let e=to[n];e&&"string"==typeof s&&(t[e]=s)}return t}let tc={x:100,y:100,width:160,height:60};function td(e,t){return 1===t?16*e:2===t?400*e:e}function th(e){return!!e&&"string"==typeof e.tagName&&(!!e.isContentEditable||["INPUT","TEXTAREA","SELECT","BUTTON","OPTION"].includes(e.tagName))}function tm(e){return(e.states?.length??0)>0||(e.parallel?.states.length??0)>0}function tu({mark:e,x:t,y:n,selected:s}){return(0,o.jsxs)("g",{transform:`translate(${t} ${n}) scale(0.5)`,strokeWidth:e.strokeWidth,className:`slc-glyph${s?" slc-glyph--selected":""}`,children:[(e.circles??[]).map((e,t)=>(0,o.jsx)("circle",{cx:e.cx,cy:e.cy,r:e.r,className:e.filled?"slc-glyph-dot":void 0},`c${t}`)),e.paths.map((e,t)=>(0,o.jsx)("path",{d:e},`p${t}`))]})}let tp={kind:null,id:null},tf=(0,l.forwardRef)(function(e,t){let{definition:n,positions:s,path:r=[],rootLabel:a,viewport:i,onViewportChange:c,selection:d=tp,activeStates:h,errorElements:m,drawMode:u="select",drawSource:p=null,readOnly:f=!1,showBreadcrumb:g=!0,showHud:x=!0,fitKey:y,onSelect:b,onClearSelection:v,onStateMove:w,onNavigateInto:j,onNavigateTo:k,onContextMenu:$,onCreateTransition:N,onCancelDraw:E,onDeleteState:M,onUndo:_,onRedo:O,hudExtras:T,emptyHint:I,theme:B,className:H,style:J,svgId:V,pinchOwner:W="canvas"}=e,K=(0,l.useRef)(null),Z=(0,l.useId)().replace(/:/g,""),G=(0,l.useRef)(i);G.current=i;let[Q,ee]=(0,l.useState)(null),et=(0,l.useRef)(null),en=(0,l.useCallback)(e=>{et.current=e,ee(e)},[]),[es,er]=(0,l.useState)(null),ea=(0,l.useRef)(!1),[ei,eo]=(0,l.useState)(!1),el=(0,l.useRef)(null),[ec,ed]=(0,l.useState)(!1),eh=(0,l.useRef)(!1),em=(0,l.useRef)(new Map),eu=(0,l.useRef)(new Map),ep=(0,l.useRef)(null),[ef,eg]=(0,l.useState)(!1),ex=(0,l.useRef)(null),ey=(0,l.useRef)(!1),[eb,ev]=(0,l.useState)(!1),ew=n.state,ej=(0,l.useMemo)(()=>{let e=function(e,t){let n=[],s=e;for(let e of t){let t=ti(s,e);if(!t)break;n.push(e),s=t}return n}(ew,r);return[a??ew?.name??"Root",...e]},[ew,r,a]),ek=(0,l.useMemo)(()=>ew?ta(function(e,t){let n=e;for(let e of t){let t=ti(n,e);if(!t)break;n=t}return n}(ew,r)):[],[ew,r]),e$=ej[ej.length-1],eN=(0,l.useMemo)(()=>(function(e){let t=new Set,n=[];for(let s of e.events??[])for(let e of s.events??[])t.has(e.id)||(t.add(e.id),n.push(e.id));return n})(n),[n]),eS=(0,l.useMemo)(()=>new Set(h??[]),[h]),eE=(0,l.useMemo)(()=>new Set(m??[]),[m]),eC=(0,l.useCallback)((e,t)=>{let n=K.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]),eM=(0,l.useCallback)(e=>{let t=em.current.get(e);em.current.delete(e),t?.hasPointerCapture?.(e)&&t.releasePointerCapture?.(e)},[]),e_=(0,l.useCallback)(e=>{let t=ex.current;t&&(void 0===e||t.pointerId===e)&&(clearTimeout(t.timer),ex.current=null)},[]),eA=(0,l.useCallback)((e,t)=>{if("touch"!==e.pointerType||!$)return;e_();let{pointerId:n,clientX:s,clientY:r}=e,a=setTimeout(()=>{ex.current=null,en(null),el.current=null,ed(!1),ey.current=!0,navigator.vibrate?.(10),$(s,r,t)},500);ex.current={pointerId:n,x:s,y:r,target:t,timer:a}},[e_,$,en]);(0,l.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(pointer: coarse)"),t=()=>ev(e.matches);return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),(0,l.useEffect)(()=>{let e=e=>{eu.current.delete(e.pointerId)};return window.addEventListener("pointerup",e),window.addEventListener("pointercancel",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("pointercancel",e)}},[]),(0,l.useEffect)(()=>()=>e_(),[e_]);let eO=(0,l.useRef)(new Set),eR=(0,l.useRef)(new Map),eP=(0,l.useRef)(e$),eT=(0,l.useRef)(new Set),[eI,eL]=(0,l.useState)(new Set),[eD,eq]=(0,l.useState)(new Set),[eB,eF]=(0,l.useState)(new Map),eY=eb?10/i.scale:0,ez=eb?28/i.scale:0,eU=(0,l.useCallback)(e=>s[e]??tc,[s]);(0,l.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&"z"===e.key&&_&&(e.preventDefault(),_()),(e.ctrlKey||e.metaKey)&&("y"===e.key||e.shiftKey&&"z"===e.key)&&O&&(e.preventDefault(),O()),"Escape"===e.key&&(er(null),E?.()),"Delete"===e.key&&"state"===d.kind&&d.id&&M&&M(d.id)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[_,O,E,M,d]);let eX=(0,l.useCallback)(e=>{let t=G.current;el.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origX:t.x,origY:t.y},eh.current=!1,ed(!0);let n=K.current;n&&(em.current.set(e.pointerId,n),n.setPointerCapture(e.pointerId))},[]),eH=(0,l.useCallback)(()=>{let e=[...eu.current.entries()];if(e.length<2)return;let[[t,n],[s,r]]=e;e_(),en(null),el.current=null;let a=Math.max(1,Math.hypot(r.x-n.x,r.y-n.y)),i=eC((n.x+r.x)/2,(n.y+r.y)/2);ep.current={a:t,b:s,startDist:a,startMidX:i.x,startMidY:i.y,start:G.current},eh.current=!0,eg(!0);let o=K.current;if(o){for(let e of[t,s])if(!em.current.has(e))try{o.setPointerCapture(e),em.current.set(e,o)}catch{}}},[e_,eC,en]),eJ=(0,l.useCallback)(e=>{if(ey.current=!1,"touch"!==e.pointerType)return;ev(!0),eu.current.set(e.pointerId,{x:e.clientX,y:e.clientY});let t=eu.current.size;t<2||(e.stopPropagation(),2===t&&eH())},[eH]),eV=(0,l.useCallback)((e,t)=>{if(0!==e.button||ea.current)return;if(e.stopPropagation(),eA(e,{kind:"state",id:t}),!f&&"transition"===u)return void(p?p!==t&&er({stateName:p,targetName:t,x:e.clientX,y:e.clientY}):b?.("state",t));if(b?.("state",t),f||!w)return;let n=eU(t);en({name:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origX:n.x,origY:n.y});let s=e.currentTarget;em.current.set(e.pointerId,s),s.setPointerCapture?.(e.pointerId)},[b,eU,u,p,eA,en,f,w]),eW=(0,l.useCallback)(e=>{if("touch"===e.pointerType){eA(e,{kind:"canvas"}),eX(e);return}(1===e.button||0===e.button&&ea.current)&&(e.preventDefault(),eX(e))},[eA,eX]),eK=(0,l.useCallback)(e=>{eu.current.has(e.pointerId)&&eu.current.set(e.pointerId,{x:e.clientX,y:e.clientY});let t=ex.current;t&&t.pointerId===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>8&&e_(e.pointerId);let n=ep.current;if(n){if(e.pointerId!==n.a&&e.pointerId!==n.b)return;let t=eu.current.get(n.a),s=eu.current.get(n.b);if(!t||!s)return;let r=Math.hypot(s.x-t.x,s.y-t.y),a=eC((t.x+s.x)/2,(t.y+s.y)/2);c(F(z(n.start,n.start.scale*(r/n.startDist),{x:n.startMidX,y:n.startMidY}),a.x-n.startMidX,a.y-n.startMidY));return}let s=el.current;if(s){if(s.pointerId!==e.pointerId)return;let t=e.clientX-s.startX,n=e.clientY-s.startY,r=8*("touch"===e.pointerType);(Math.abs(t)>r||Math.abs(n)>r)&&(eh.current=!0),c({x:s.origX+t,y:s.origY+n,scale:G.current.scale});return}if(!Q||Q.pointerId!==e.pointerId||!w)return;let r=G.current.scale,a=(e.clientX-Q.startX)/r,i=(e.clientY-Q.startY)/r,o=eU(Q.name);w(Q.name,{...o,x:Math.max(0,Q.origX+a),y:Math.max(0,Q.origY+i)})},[Q,eU,w,c,e_,eC]),eZ=(0,l.useCallback)(e=>{eu.current.delete(e.pointerId),e_(e.pointerId),eM(e.pointerId);let t=ep.current;if(t&&(t.a===e.pointerId||t.b===e.pointerId)){ep.current=null,eg(!1);let n=t.a===e.pointerId?t.b:t.a,s=eu.current.get(n);if(s){let e=G.current;el.current={pointerId:n,startX:s.x,startY:s.y,origX:e.x,origY:e.y},eh.current=!0,ed(!0)}}el.current?.pointerId===e.pointerId&&(el.current=null),et.current?.pointerId===e.pointerId&&en(null),el.current||ed(!1),ep.current||eg(!1)},[e_,eM,en]);(0,l.useEffect)(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault();let t=G.current,n=td(e.deltaX,e.deltaMode),s=td(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey){let n=Y(t,Math.exp(-(.0025*s)),eC(e.clientX,e.clientY));n!==t&&c(n);return}let r=e.shiftKey?-(n||s):-n,a=e.shiftKey?0:-s;(0!==r||0!==a)&&c(F(t,r,a))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[c,eC]),(0,l.useEffect)(()=>{let e=e=>{"Space"!==e.code||e.repeat||th(e.target)||th(document.activeElement)||(e.preventDefault(),ea.current=!0,eo(!0))},t=e=>{"Space"===e.code&&(ea.current=!1,eo(!1))},n=()=>{ea.current=!1,eo(!1)};return window.addEventListener("keydown",e),window.addEventListener("keyup",t),window.addEventListener("blur",n),()=>{window.removeEventListener("keydown",e),window.removeEventListener("keyup",t),window.removeEventListener("blur",n)}},[]);let eG=(0,l.useCallback)(e=>{let t=K.current?.getBoundingClientRect(),n={x:(t?.width??0)/2,y:(t?.height??0)/2},s=G.current,r=Y(s,e,n);r!==s&&c(r)},[c]),eQ=(0,l.useCallback)(()=>{let e=K.current?.getBoundingClientRect(),t={x:(e?.width??0)/2,y:(e?.height??0)/2};c(z(G.current,1,t))},[c]),e0=(0,l.useCallback)(()=>{let e=K.current?.getBoundingClientRect();if(!e)return;let t=ek.map(e=>eU(e.name));c(t.length?U(t,e.width,e.height):{...q})},[ek,eU,c]);(0,l.useImperativeHandle)(t,()=>({fit:e0,zoomIn:()=>eG(1.25),zoomOut:()=>eG(.8),resetZoom:eQ,element:()=>K.current}),[e0,eG,eQ]);let e1=(0,l.useRef)(e0);e1.current=e0,(0,l.useEffect)(()=>{if(void 0===y)return;let e=requestAnimationFrame(()=>e1.current());return()=>cancelAnimationFrame(e)},[y]);let e2=(0,l.useCallback)((e,t)=>{$&&(e.preventDefault(),e.stopPropagation(),$(e.clientX,e.clientY,t?{kind:"state",id:t}:{kind:"canvas"}))},[$]),e5=(0,l.useMemo)(()=>{let e=new Set(ek.map(e=>e.name)),t=[];for(let n of ek)for(let[s,r]of(n.transitions??[]).entries())r.nextState&&e.has(r.nextState)&&t.push({from:n.name,to:r.nextState,event:r.event,stateName:n.name,index:s,condition:r.condition});return t},[ek]),e4=(0,l.useMemo)(()=>{let e=L(e5,eU),t=new Map(A(e5.map((t,n)=>{let s=eU(t.from);return{id:`${t.stateName}:${t.index}`,event:t.event,condition:t.condition,glyph:!0,at:t.from===t.to?()=>({x:s.x+s.width+44+30,y:s.y+s.height/2+4}):e[n].at}}),ek.map(e=>eU(e.name))).map(e=>[e.label.id,e]));return e5.flatMap((n,s)=>{let r=`${n.stateName}:${n.index}`,a=t.get(r);return a?[{arrow:n,id:r,curve:e[s],spot:a}]:[]})},[e5,ek,eU]);(0,l.useEffect)(()=>{let e=new Set(ek.map(e=>e.name)),t=new Set(e5.map(e=>`${e.stateName}:${e.index}`)),n=eP.current===e$,s=[...e].filter(e=>!eO.current.has(e));s.length&&eL(e=>{let t=new Set(e);return s.forEach(e=>t.add(e)),t});let r=[...t].filter(e=>!eT.current.has(e));r.length&&eq(e=>{let t=new Set(e);return r.forEach(e=>t.add(e)),t}),eL(t=>{let n=!1,s=new Set(t);return t.forEach(t=>{e.has(t)||(s.delete(t),n=!0)}),n?s:t}),eq(e=>{let n=!1,s=new Set(e);return e.forEach(e=>{t.has(e)||(s.delete(e),n=!0)}),n?s:e}),n?eF(t=>{let n=new Map(t),s=!1;return eR.current.forEach((t,r)=>{e.has(r)||n.has(r)||(n.set(r,t),s=!0)}),e.forEach(e=>{n.delete(e)&&(s=!0)}),s?n:t}):eF(e=>e.size?new Map:e),eO.current=e,eR.current=new Map(ek.map(e=>[e.name,{state:e,pos:eU(e.name)}])),eT.current=t,eP.current=e$},[ek,e$,e5,eU]);let e3={...tl(B),...J},e6=eb?" slc-hud--coarse":"";return(0,o.jsxs)("div",{className:`slc-pane${H?` ${H}`:""}`,style:e3,"data-pinch-owner":W,children:[g&&ej.length>1&&(0,o.jsx)("div",{className:"slc-crumbs",children:ej.map((e,t)=>(0,o.jsxs)("span",{className:"slc-crumb-item",children:[t>0&&(0,o.jsx)("span",{className:"slc-crumb-sep",children:"›"}),(0,o.jsx)("button",{type:"button",className:`slc-crumb${t===ej.length-1?" slc-crumb--current":""}`,onClick:()=>k?.(t),children:e})]},`${e}-${t}`))}),(0,o.jsxs)("svg",{ref:K,id:V,className:"slc-surface",style:{cursor:ec?"grabbing":ei?"grab":void 0,touchAction:"none",...eb?{WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"}:{}},onPointerDownCapture:eJ,onPointerDown:eW,onPointerMove:eK,onPointerUp:eZ,onPointerCancel:eZ,onAuxClick:e=>e.preventDefault(),onClick:e=>{if(ey.current){ey.current=!1,e.stopPropagation();return}if(eh.current){eh.current=!1;return}e.target?.tagName==="svg"&&(v?.(),er(null))},onContextMenu:e=>e2(e),children:[(0,o.jsxs)("defs",{children:[(0,o.jsx)("marker",{id:`slc-arrow-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,o.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead"})}),(0,o.jsx)("marker",{id:`slc-arrow-sel-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,o.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead slc-arrowhead--selected"})})]}),"transition"===u&&p&&(0,o.jsxs)("text",{x:"50%",y:"30",textAnchor:"middle",className:"slc-draw-hint",children:['Click target state to create transition from "',p,'"']}),(0,o.jsxs)("g",{transform:X(i),style:ec||ef?{pointerEvents:"none"}:void 0,children:[e4.map(({arrow:e,id:t,curve:n,spot:s})=>{let r="transition"===d.kind&&d.id===t,a=eD.has(t),i=n.at(.5),l=Math.hypot(i.x-s.cx,i.y-s.cy)>4;return(0,o.jsxs)("g",{children:[eb&&(0,o.jsx)("path",{d:n.path,fill:"none",stroke:"transparent",strokeWidth:ez,strokeLinecap:"round",pointerEvents:"stroke",onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,o.jsx)("path",{d:n.path,pathLength:1,markerEnd:`url(#slc-arrow${r?"-sel":""}-${Z})`,className:`slc-edge${r?" slc-edge--selected":""}${a?" slc-edge-enter":""}`,onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,o.jsxs)("g",{className:"slc-chip",onClick:e=>{e.stopPropagation(),b?.("transition",t)},children:[l&&(0,o.jsx)("line",{x1:i.x,y1:i.y,x2:s.cx,y2:s.cy-5,className:`slc-chip-leader${r?" slc-chip-leader--selected":""}`}),eb&&(0,o.jsx)("rect",{x:s.x-eY,y:s.y-eY,width:s.width+2*eY,height:s.height+2*eY,fill:"transparent",pointerEvents:"all"}),(0,o.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,rx:4,className:`slc-chip-plate${r?" slc-chip-plate--selected":""}`}),(0,o.jsx)(tu,{mark:function(e){let t=e.toLowerCase();for(let{glyph:e,words:n}of P)if(n.some(e=>t.includes(e)))return e;return R}(e.event),x:C(s).x,y:C(s).y,selected:r}),(0,o.jsx)("text",{x:s.cx,y:s.cy-5,textAnchor:"middle",className:`slc-chip-text${r?" slc-chip-text--selected":""}`,children:e.event}),e.condition&&(0,o.jsxs)("text",{x:s.cx,y:s.cy+7,textAnchor:"middle",className:"slc-chip-guard",children:[(0,o.jsx)("title",{children:e.condition}),S(e.condition)]})]})]},`arrow-${t}`)}),ek.map(e=>{let t=eU(e.name),n="state"===d.kind&&d.id===e.name,s="final"===e.kind,r="history"===e.kind,a=tm(e),i=p===e.name,l=eE.has(e.name),c=(e.onEntry?.actions?.length??0)>0,h=(e.onExit?.actions?.length??0)>0,m=eS.has(e.name),g=eI.has(e.name),x=ei?void 0:"transition"!==u||f?a?"slc-node--drillable":f||!w?"slc-node--static":"slc-node--draggable":"slc-node--drawing";return(0,o.jsxs)("g",{className:x,onPointerDown:t=>eV(t,e.name),onDoubleClick:t=>{t.stopPropagation(),a&&j?.(e.name)},onContextMenu:t=>e2(t,e.name),children:[eb&&(0,o.jsx)("rect",{x:t.x-eY,y:t.y-eY,width:t.width+2*eY,height:t.height+2*eY,rx:12,fill:"transparent",pointerEvents:"all"}),(0,o.jsxs)("g",{className:g?"slc-node-enter":void 0,children:[(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:r?30:s?4:8,strokeDasharray:s?"6 3":a?"4 2":void 0,className:["slc-node",s?"slc-node--final":a?"slc-node--composite":"",i?"slc-node--source":"",l?"slc-node--error":"",n?"slc-node--selected":"",m?"slc-node--active":""].filter(Boolean).join(" ")}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+(c||h?t.height/2:t.height/2+5),textAnchor:"middle",className:"slc-node-name",children:e.name}),e.kind&&"normal"!==e.kind&&(0,o.jsx)("text",{x:t.x+t.width-8,y:t.y+14,textAnchor:"end",className:"slc-node-kind",children:e.kind}),c&&(0,o.jsx)("text",{x:t.x+6,y:t.y+t.height-6,className:"slc-node-entry",children:"▸entry"}),h&&(0,o.jsx)("text",{x:t.x+t.width-6,y:t.y+t.height-6,textAnchor:"end",className:"slc-node-exit",children:"exit◂"}),l&&(0,o.jsx)("path",{d:`M ${t.x+6} ${t.y+15} l 5.5 -9.5 l 5.5 9.5 Z M ${t.x+11.5} ${t.y+9.5} v 2.6`,className:"slc-node-warn-mark"}),e.notes?.trim()&&(0,o.jsxs)("g",{children:[(0,o.jsx)("title",{children:`Notes: ${e.notes}`}),(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"})]}),a&&(0,o.jsxs)("text",{x:t.x+t.width/2,y:t.y+t.height-6,textAnchor:"middle",className:"slc-node-drill",children:["▼ ",(e.states?.length??0)+(e.parallel?.states.length??0)," children — ",eb?"double-tap":"double-click"," to enter"]})]})]},e.name)}),Array.from(eB.entries()).map(([e,{state:t,pos:n}])=>{let s="final"===t.kind,r=tm(t);return(0,o.jsxs)("g",{className:"slc-node-exit-group",onAnimationEnd:t=>{"slc-node-out"===t.animationName&&eF(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},children:[(0,o.jsx)("rect",{x:n.x,y:n.y,width:n.width,height:n.height,rx:"history"===t.kind?30:s?4:8,strokeDasharray:s?"6 3":r?"4 2":void 0,className:`slc-node${s?" slc-node--final":r?" slc-node--composite":""}`}),(0,o.jsx)("text",{x:n.x+n.width/2,y:n.y+n.height/2+5,textAnchor:"middle",className:"slc-node-name",children:e})]},`exit-${e}`)})]}),0===ek.length&&(0,o.jsx)("text",{x:"50%",y:"50%",textAnchor:"middle",className:"slc-empty",children:I??"This level has no states."})]}),x&&(0,o.jsxs)("div",{className:`slc-hud${e6}`,children:[(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Zoom out (Ctrl + wheel down, or pinch in)",disabled:i.scale<=D.min,onClick:()=>eG(.8),children:"−"}),(0,o.jsxs)("button",{type:"button",className:"slc-hud-btn slc-hud-btn--scale",title:"Reset zoom to 100%",onClick:eQ,children:[Math.round(100*i.scale),"%"]}),(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Zoom in (Ctrl + wheel up, or pinch out)",disabled:i.scale>=D.max,onClick:()=>eG(1.25),children:"+"}),(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Fit the whole machine in view",onClick:e0,children:"⤢ Fit"}),T&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),T]}),(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,o.jsx)("span",{className:"slc-hud-hint",title:eb?"Drag to pan · pinch with two fingers to zoom · press and hold for the menu · double-tap a composite to enter it":"Wheel scrolls · Shift+wheel scrolls sideways · Ctrl+wheel zooms at the cursor · middle-drag or Space+drag pans",children:ef?"pinching":ec?"panning":eb?"drag · pinch · hold":ei?"space to pan":"wheel · ⌃wheel · space"})]}),es&&(0,o.jsxs)("div",{className:"slc-picker",style:{left:es.x,top:es.y-80},onClick:e=>e.stopPropagation(),children:[(0,o.jsxs)("div",{className:"slc-picker-title",children:[es.stateName," → ",es.targetName]}),(0,o.jsx)("div",{className:"slc-picker-sub",children:"Select event:"}),0===eN.length?(0,o.jsx)("div",{className:"slc-picker-empty",children:"No events defined. Add events first."}):eN.map(e=>(0,o.jsx)("button",{type:"button",className:"slc-picker-item",onClick:()=>{es&&(N?.(es.stateName,es.targetName,e),er(null),E?.())},children:e},e)),(0,o.jsx)("button",{type:"button",className:"slc-picker-cancel",onClick:()=>{er(null),E?.()},children:"Cancel"})]})]})});function tg(e,t){return 1===t?16*e:2===t?400*e:e}let tx={"1:1":["one","one"],"1:N":["one","many"],"N:1":["many","one"],"N:M":["many","many"]};function ty(e,t,n){let s=t.x-e.x,r=t.y-e.y,a=Math.hypot(s,r)||1,i=s/a,o=r/a,l=-o,c=(t,n)=>`${(e.x+i*t+l*n).toFixed(1)} ${(e.y+o*t+i*n).toFixed(1)}`;return"one"===n?`M ${c(9,6)} L ${c(9,-6)}`:`M ${c(13,0)} L ${c(0,7)} M ${c(13,0)} L ${c(0,-7)} M ${c(13,0)} L ${c(0,0)}`}function tb(e){return[e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n\n")}function tv(e,t){if(!e)return"";let n=Math.min(e.x+e.width,Math.max(e.x,t.x)),s=Math.min(e.y+e.height,Math.max(e.y,t.y));return n===t.x&&s===t.y?"":`M ${t.x} ${t.y} L ${n} ${s}`}function tw({definition:e,notation:t="crowsfoot",positions:n,viewport:s,onViewportChange:r,selection:a=null,errorElements:i,readOnly:c=!1,fitKey:d,onSelect:h,onClearSelection:m,onEntityMove:u,onOpenMachine:p,onContextMenu:f,emptyHint:g,theme:x,className:y,style:b,svgId:v}){let w=(0,l.useRef)(null),j=(0,l.useRef)(s);j.current=s;let k=(0,l.useRef)(null),$=(0,l.useRef)(new Map),N=(0,l.useRef)(null),S=(0,l.useMemo)(()=>{let t=new Set;return(e.entities??[]).filter(e=>!(!e?.name||t.has(e.name))&&!!n[e.name]&&(t.add(e.name),!0))},[e.entities,n]),E="chen"===t,C=(0,l.useMemo)(()=>new Map(E?S.map(e=>{var t;let s,r,a,i,o,l,c;return[e.name,(t=n[e.name],s=ea(e),r=ei(e),a={x:t.x+(t.width-r)/2,y:t.y+(t.height-40)/2,width:r,height:40},i=eo(s),o=a.y+a.height/2,l=el(s.length),c=s.map((e,t)=>{let n=t<l,r=n?l:s.length-l,c=o+((n?t:t-l)-(r-1)/2)*32,d=n?a.x-34-i:a.x+a.width+34+i;return{attribute:e,cx:d,cy:c,rx:i,ry:13,from:{x:n?a.x:a.x+a.width,y:o},to:{x:n?d+i:d-i,y:c}}}),{rect:a,ovals:c,routingBox:{x:a.x,y:t.y,width:a.width,height:t.height}})]}):[]),[E,S,n]),M=(0,l.useMemo)(()=>{let t=new Map(S.map((e,t)=>[e.name,`e${t}`])),s=(e.relationships??[]).filter(e=>e&&t.has(e.from)&&t.has(e.to)),r=L(s.map(e=>({from:t.get(e.from),to:t.get(e.to)})),e=>{let t=S[Number(e.slice(1))].name;return C.get(t)?.routingBox??n[t]});return s.map((e,t)=>({rel:e,curve:r[t]}))},[e.relationships,S,n,C]),_=(0,l.useMemo)(()=>A(M.filter(({rel:e})=>E||e.label).map(({rel:e,curve:t})=>({event:e.label||" ",at:t.at,rel:e})),S.map(e=>n[e.name])),[E,M,S,n]),O=(0,l.useCallback)((e,t)=>{let n=w.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,l.useEffect)(()=>{if(void 0===d)return;let e=w.current?.getBoundingClientRect(),t=Object.values(n);e&&0!==t.length&&r(U(t,e.width,e.height))},[d]),(0,l.useEffect)(()=>{let e=w.current;if(!e)return;let t=e=>{e.preventDefault();let t=j.current,n=tg(e.deltaX,e.deltaMode),s=tg(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void r(Y(t,Math.exp(-(.0025*s)),O(e.clientX,e.clientY)));let a=e.shiftKey?-(n||s):-n,i=e.shiftKey?0:-s;(0!==a||0!==i)&&r(F(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[r,O]);let R=()=>{let e=[...$.current.values()];if(e.length<2)return null;let[t,n]=e;return{distance:Math.hypot(n.x-t.x,n.y-t.y)||1,mid:{x:(t.x+n.x)/2,y:(t.y+n.y)/2}}},P=(e,t)=>{if(0!==e.button&&"mouse"===e.pointerType)return;if(e.stopPropagation(),w.current?.setPointerCapture(e.pointerId),$.current.set(e.pointerId,O(e.clientX,e.clientY)),$.current.size>=2){k.current=null,N.current=R();return}let s=void 0!==t&&!c;k.current={kind:s?"move":"pan",pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,name:t,origin:s?n[t]:void 0,moved:!1}},T=e=>{if($.current.delete(e.pointerId),N.current){$.current.size<2&&(N.current=null);return}let t=k.current;!t||t.pointerId!==e.pointerId||(k.current=null,t.moved||(t.name?h?.(t.name):m?.()))},I=new Set(i??[]);return(0,o.jsxs)("div",{className:`slc-pane${y?` ${y}`:""}`,style:{...tl(x),...b},children:[(0,o.jsx)("svg",{ref:w,id:v,className:"slc-surface",onPointerDown:e=>P(e),onPointerMove:e=>{if($.current.has(e.pointerId)&&$.current.set(e.pointerId,O(e.clientX,e.clientY)),N.current){let e=R();if(!e)return;let t=N.current;r(Y(F(j.current,e.mid.x-t.mid.x,e.mid.y-t.mid.y),e.distance/t.distance,e.mid)),N.current=e;return}let t=k.current;if(t&&t.pointerId===e.pointerId&&!(!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY))){if(t.moved=!0,"pan"===t.kind)r(F(j.current,e.clientX-t.lastX,e.clientY-t.lastY));else if(t.name&&t.origin){var n,s,a;let r=(n=j.current,s=e.clientX-t.startX,a=e.clientY-t.startY,{x:s/n.scale,y:a/n.scale});u?.(t.name,{...t.origin,x:t.origin.x+r.x,y:t.origin.y+r.y})}t.lastX=e.clientX,t.lastY=e.clientY}},onPointerUp:T,onPointerCancel:T,onContextMenu:e=>{f&&(e.preventDefault(),f(e.clientX,e.clientY,{kind:"canvas"}))},children:(0,o.jsxs)("g",{transform:X(s),children:[M.map(({rel:e,curve:t},n)=>{if(E){let[s,r]=function(e){switch(e){case"1:1":return["1","1"];case"N:1":return["N","1"];case"N:M":return["M","N"];default:return["1","N"]}}(e.cardinality),a=t.at(.12),i=t.at(.88);return(0,o.jsxs)("g",{className:"slc-erd-rel",children:[(0,o.jsx)("path",{d:tv(C.get(e.from)?.rect,t.p0),className:"slc-erd-line"}),(0,o.jsx)("path",{d:tv(C.get(e.to)?.rect,t.p3),className:"slc-erd-line"}),(0,o.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,o.jsx)("text",{x:a.x+9,y:a.y+4,className:"slc-erd-card",children:s}),(0,o.jsx)("text",{x:i.x+9,y:i.y+4,className:"slc-erd-card",children:r})]},`r${n}`)}let[s,r]=tx[e.cardinality]??tx["1:N"];return(0,o.jsxs)("g",{className:"slc-erd-rel",children:[(0,o.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,o.jsx)("path",{d:ty(t.p0,t.p1,s),className:"slc-erd-mark"}),(0,o.jsx)("path",{d:ty(t.p3,t.p2,r),className:"slc-erd-mark"})]},`r${n}`)}),S.map(e=>{let t=n[e.name],s=(e.attributes??[]).filter(e=>e?.name),r=["slc-node",a===e.name?"slc-node--selected":"",I.has(e.name)?"slc-node--error":""].filter(Boolean).join(" "),i=C.get(e.name);if(i){let{rect:t,ovals:n}=i;return(0,o.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>P(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[n.map(e=>(0,o.jsx)("path",{d:`M ${e.from.x} ${e.from.y} L ${e.to.x} ${e.to.y}`,className:"slc-erd-attr-line"},`l-${e.attribute.name}`)),n.map(e=>{var t;let n,s=J(e.attribute),r=s.length>0&&!!p;return(0,o.jsxs)("g",{className:r?"slc-erd-state":void 0,onPointerDown:r?e=>e.stopPropagation():void 0,onClick:r?()=>p(s[0]):void 0,children:[(0,o.jsx)("title",{children:(n=J(t=e.attribute),[`${ex(t)}${t.nullable?" ?":""}`,"pk"===t.key?"primary key":"uk"===t.key?"unique":"",t.references?`references ${t.references}`:"",n.length?`stores the state of ${n.join(", ")}`:"",t.description??""].filter(Boolean).join(" — "))}),(0,o.jsx)("ellipse",{cx:e.cx,cy:e.cy,rx:e.rx,ry:e.ry,className:"slc-erd-oval"}),(0,o.jsxs)("text",{x:e.cx,y:e.cy+4,textAnchor:"middle",className:`slc-erd-oval-text${"pk"===e.attribute.key?" slc-erd-oval-text--pk":""}${s.length?" slc-erd-row--state":""}`,children:[s.length?"◉ ":"",e.attribute.name]})]},e.attribute.name)}),tb(e)&&(0,o.jsx)("title",{children:tb(e)}),(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:2,className:r}),e.notes?.trim()&&(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),e.weak&&(0,o.jsx)("rect",{x:t.x+4,y:t.y+4,width:t.width-8,height:t.height-8,rx:1,className:"slc-erd-weak"}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+t.height/2+5,textAnchor:"middle",className:"slc-node-name",children:e.name})]},e.name)}return(0,o.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>P(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[tb(e)&&(0,o.jsx)("title",{children:tb(e)}),(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:6,className:r}),e.notes?.trim()&&(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,o.jsx)("path",{d:`M ${t.x} ${t.y+30} h ${t.width}`,className:"slc-erd-rule"}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+15+5,textAnchor:"middle",className:"slc-node-name",children:e.name}),0===s.length&&(0,o.jsx)("text",{x:t.x+14,y:t.y+30+15,className:"slc-erd-row slc-erd-row--empty",children:"no attributes"}),s.map((e,n)=>{let s=t.y+30+20*n+15,r=J(e),a=["pk"===e.key?"PK":"uk"===e.key?"UK":"",e.references?"FK":""].filter(Boolean).join(" ");return(0,o.jsxs)("g",{className:r.length&&p?"slc-erd-state":void 0,onPointerDown:r.length&&p?e=>e.stopPropagation():void 0,onClick:r.length&&p?()=>p(r[0]):void 0,children:[(r.length>0||e.description)&&(0,o.jsx)("title",{children:[r.length?`stores the state of ${r.join(", ")}`:"",e.description??""].filter(Boolean).join(" — ")}),(0,o.jsxs)("text",{x:t.x+14,y:s,className:`slc-erd-row${r.length?" slc-erd-row--state":""}${"pk"===e.key?" slc-erd-row--pk":""}`,children:[r.length?"◉ ":"",ex(e),e.nullable?" ?":""]}),a&&(0,o.jsx)("text",{x:t.x+t.width-14,y:s,textAnchor:"end",className:"slc-erd-badge",children:a})]},e.name)})]},e.name)}),_.map((e,t)=>{if(!E)return null;let n=e.x+e.width/2,s=e.y+e.height/2,r=Math.max(34,Math.ceil(3.7*(e.label.rel.label??"").length+18));return(0,o.jsxs)("g",{pointerEvents:"none",children:[(0,o.jsx)("path",{d:`M ${n-r} ${s} L ${n} ${s-18} L ${n+r} ${s} L ${n} ${s+18} Z`,className:"slc-erd-diamond"}),(0,o.jsx)("text",{x:n,y:s+4,textAnchor:"middle",className:"slc-erd-rel-label",children:e.label.rel.label??""})]},`d${t}`)}),!E&&_.map((e,t)=>(0,o.jsxs)("g",{pointerEvents:"none",children:[(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:4,className:"slc-chip-plate"}),(0,o.jsx)("text",{x:e.cx,y:e.cy-5,textAnchor:"middle",className:"slc-erd-rel-label",children:e.label.event})]},`l${t}`))]})}),0===S.length&&g&&(0,o.jsx)("div",{className:"slc-erd-empty",children:g})]})}function tj(e,t){return 1===t?16*e:2===t?400*e:e}function tk(e,t,n,s){let r=e-9*n;return s?`M ${r} ${t-4.5} L ${e} ${t} L ${r} ${t+4.5}`:`M ${r} ${t-4.5} L ${e} ${t} L ${r} ${t+4.5} Z`}function t$(e){return[e.actor?`actor ${e.actor}`:e.object?`object ${e.object}`:e.service?`service ${e.service}`:"",e.holds?.length?`holds ${e.holds.join(", ")}`:"",e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n")}let tN=e=>"string"==typeof e?e:null==e?"":String(e);function tS(e){let t=e&&"object"==typeof e?e:{};return{from:tN(t.from),to:tN(t.to),label:tN(t.label),event:tN(t.event)||void 0,machine:tN(t.machine)||void 0,carries:tN(t.carries)||void 0,state:tN(t.state)||void 0,description:tN(t.description)||void 0,notes:tN(t.notes)||void 0,optional:!0===t.optional||void 0,reply:!0===t.reply||void 0}}function tE(e){let t=e&&"object"==typeof e?e:{},n=e=>Array.isArray(e)?e:[],s=t.settings&&"object"==typeof t.settings?t.settings:{};return{settings:{namespace:tN(s.namespace),name:tN(s.name),notes:tN(s.notes)||void 0},participants:n(t.participants).map(e=>{let t=e&&"object"==typeof e?e:{};return{name:tN(t.name),description:tN(t.description)||void 0,notes:tN(t.notes)||void 0,actor:tN(t.actor)||void 0,service:tN(t.service)||void 0,object:tN(t.object)||void 0,holds:Array.isArray(t.holds)?t.holds.map(tN):"string"==typeof t.holds?[t.holds]:void 0}}),messages:n(t.messages).map(tS),...Array.isArray(t.fragments)?{fragments:t.fragments.map(e=>{let t=e&&"object"==typeof e?e:{};return{kind:tN(t.kind),label:tN(t.label),after:"number"==typeof t.after&&Number.isFinite(t.after)?t.after:0,notes:tN(t.notes)||void 0,messages:n(t.messages).map(tS)}})}:{}}}function tC({definition:e,layout:t,viewport:n,onViewportChange:s,selection:r=null,errorElements:a,warningElements:i,fitKey:c,onSelect:d,onClearSelection:h,onContextMenu:m,emptyHint:u,theme:p,className:f,style:g,svgId:x}){let y=(0,l.useRef)(null),b=(0,l.useRef)(n);b.current=n;let v=(0,l.useRef)(null),w=(0,l.useRef)(new Map),j=(0,l.useRef)(null),k=(0,l.useMemo)(()=>tE(e),[e]),$=(0,l.useMemo)(()=>t??eL(k),[t,k]),S=(0,l.useRef)(new Map),[E,C]=(0,l.useState)({}),M=e=>t=>{t?S.current.set(e,t):S.current.delete(e)};(0,l.useLayoutEffect)(()=>{let e={},t=!1;for(let[n,s]of S.current){let r="function"==typeof s.getComputedTextLength?s.getComputedTextLength():0;r&&(e[n]=r,Math.abs((E[n]??-1)-r)>.5&&(t=!0))}t&&C(e)},[$,k]);let _=(0,l.useMemo)(()=>new Map(eN(k).map(e=>[e.ref,e.message])),[k]),A=(0,l.useMemo)(()=>new Map(k.participants.filter(e=>e.name).map(e=>[e.name,e])),[k.participants]),O=(0,l.useCallback)((e,t)=>{let n=y.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,l.useEffect)(()=>{if(void 0===c)return;let e=y.current?.getBoundingClientRect();e&&0!==$.participants.length&&s(U([{x:0,y:0,width:$.width,height:$.height}],e.width,e.height,{padding:16}))},[c]),(0,l.useEffect)(()=>{let e=y.current;if(!e)return;let t=e=>{e.preventDefault();let t=b.current,n=tj(e.deltaX,e.deltaMode),r=tj(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void s(Y(t,Math.exp(-(.0025*r)),O(e.clientX,e.clientY)));let a=e.shiftKey?-(n||r):-n,i=e.shiftKey?0:-r;(0!==a||0!==i)&&s(F(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[s,O]);let R=()=>{let e=[...w.current.values()];if(e.length<2)return null;let[t,n]=e;return{distance:Math.hypot(n.x-t.x,n.y-t.y)||1,mid:{x:(t.x+n.x)/2,y:(t.y+n.y)/2}}},P=(e,t)=>{if(0===e.button||"mouse"!==e.pointerType){if(e.stopPropagation(),y.current?.setPointerCapture(e.pointerId),w.current.set(e.pointerId,O(e.clientX,e.clientY)),w.current.size>=2){v.current=null,j.current=R();return}v.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,target:t,moved:!1}}},T=e=>{if(w.current.delete(e.pointerId),j.current){w.current.size<2&&(j.current=null);return}let t=v.current;!t||t.pointerId!==e.pointerId||(v.current=null,t.moved||(t.target?d?.(t.target.kind,t.target.id):h?.()))},I=e=>t=>{m&&(t.preventDefault(),t.stopPropagation(),m(t.clientX,t.clientY,e))},L=new Set(a??[]),D=new Set(i??[]),q=(e,t)=>r?.kind===e&&r.id===t,B=r?.kind==="message"?_.get(r.id):void 0;return(0,o.jsxs)("div",{className:`slc-pane${f?` ${f}`:""}`,style:{...tl(p),...g},children:[(0,o.jsx)("svg",{ref:y,id:x,className:"slc-surface",onPointerDown:e=>P(e),onPointerMove:e=>{if(w.current.has(e.pointerId)&&w.current.set(e.pointerId,O(e.clientX,e.clientY)),j.current){let e=R();if(!e)return;let t=j.current;s(Y(F(b.current,e.mid.x-t.mid.x,e.mid.y-t.mid.y),e.distance/t.distance,e.mid)),j.current=e;return}let t=v.current;!t||t.pointerId!==e.pointerId||!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY)||(t.moved=!0,s(F(b.current,e.clientX-t.lastX,e.clientY-t.lastY)),t.lastX=e.clientX,t.lastY=e.clientY)},onPointerUp:T,onPointerCancel:T,onContextMenu:I({kind:"canvas"}),children:(0,o.jsxs)("g",{transform:X(n),children:[$.fragments.map(e=>{let t=k.fragments?.[e.index];if(!t)return null;let n=N(`${t.kind} \xb7 after ${t.after} \xb7 ${t.label}`,11)+18,s=e.top;return(0,o.jsxs)("g",{className:"slc-sqd-fragment",children:[t.notes?.trim()&&(0,o.jsx)("title",{children:`Notes: ${t.notes}`}),(0,o.jsx)("rect",{x:e.left,y:s,width:e.width,height:e.height,rx:3,className:"slc-sqd-frame"}),(0,o.jsx)("path",{d:`M ${e.left} ${s+22} L ${e.left} ${s} L ${e.left+n} ${s} L ${e.left+n} ${s+15} L ${e.left+n-7} ${s+22} Z`,className:"slc-sqd-frame-tab"}),(0,o.jsxs)("text",{x:e.left+8,y:s+15,className:"slc-sqd-frame-heading",children:[(0,o.jsx)("tspan",{className:"slc-sqd-frame-kind",children:t.kind}),` \xb7 after ${t.after} \xb7 ${t.label}`]}),t.notes?.trim()&&(0,o.jsx)("rect",{x:e.left+n+6,y:s+7,width:13,height:5,rx:1.5,className:"slc-note-mark"})]},`f${e.index}`)}),$.participants.map(e=>{let t=q("participant",e.name);return(0,o.jsxs)("g",{onPointerDown:t=>P(t,{kind:"participant",id:e.name}),children:[(0,o.jsx)("path",{d:`M ${e.x} ${$.lifelineTop} V ${$.lifelineBottom}`,className:"slc-sqd-hit"}),(0,o.jsx)("path",{d:`M ${e.x} ${$.lifelineTop} V ${$.lifelineBottom}`,className:`slc-sqd-lifeline${t?" slc-sqd-lifeline--selected":""}`})]},`l-${e.name}`)}),$.fragments.map(e=>{let t=k.fragments?.[e.index],n=t&&t.after>0?$.rows.find(e=>null===e.fragment&&e.index===t.after-1):void 0;if(!n)return null;let s=e.left+4;return(0,o.jsx)("path",{d:`M ${Math.min(n.fromX,n.toX)-14} ${n.y} H ${s} V ${e.top}`,className:"slc-sqd-branch"},`fa${e.index}`)}),$.rows.map(e=>{var t;let n,s,r,a,i=_.get(e.ref);if(!i)return null;let l=`message:${e.ref}`,c=q("message",e.ref),d=L.has(l),h=!d&&D.has(l),m=["slc-sqd-line",i.reply?"slc-sqd-line--reply":"",i.optional?"slc-sqd-line--optional":"",d?"slc-sqd-line--error":h?"slc-sqd-line--warn":"",c?"slc-sqd-line--selected":""].filter(Boolean).join(" "),u=`slc-sqd-head${i.reply?" slc-sqd-head--open":""}${c?" slc-sqd-head--selected":d?" slc-sqd-head--error":""}`,p=e.ref,f=N(p,10)+8,g=E[`${e.ref}:label`]??N(i.label??"",11),x=i.optional?N("opt",10)+8:0,y=i.event?(E[`${e.ref}:event`]??6.1*i.event.length)+12:0,b=i.state?`→ ${i.state}`:"",v=i.state?E[`${e.ref}:state`]??N(b,11):0,w=f+5+g+(x?5+x:0)+(y?5+y:0)+(v?5+v:0);if(e.self){let t=e.fromX,l=e.y-7-2,c=l+14;r=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:`M ${t} ${l} H ${t+30} V ${c} H ${t+2}`,className:m}),(0,o.jsx)("path",{d:tk(t+1,c,-1,!!i.reply),className:u})]}),n=t+30+8,s=e.y+2,a={x:t-6,y:l-8,w:44+w,h:30}}else{let t=e.toX>=e.fromX?1:-1,l=e.toX-t;r=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:`M ${e.fromX} ${e.y} H ${l}`,className:m}),(0,o.jsx)("path",{d:tk(l,e.y,t,!!i.reply),className:u})]}),n=(e.fromX+e.toX)/2-w/2,s=e.y-6;let c=Math.min(e.fromX,e.toX,n),d=Math.max(e.fromX,e.toX,n+w);a={x:c-4,y:e.y-22,w:d-c+8,h:30}}let j=n,k=e=>{let t=j;return j+=e+5,t},$=k(f),S=k(g),C=x?k(x):0,A=y?k(y):0,O=v?k(v):0;return(0,o.jsxs)("g",{className:"slc-sqd-message",onPointerDown:t=>P(t,{kind:"message",id:e.ref}),onContextMenu:I({kind:"message",id:e.ref}),children:[(0,o.jsx)("title",{children:(t=e.ref,[`${t}. ${i.from} → ${i.to}: ${i.label}`,i.event?`fires ${i.event}${i.machine?` on ${i.machine}`:""}`:"",i.carries?`carries ${i.carries}`:"",i.state?`then ${i.state}`:"",i.optional?"optional":"",i.reply?"reply":"",i.description??"",i.notes?.trim()?`Notes: ${i.notes}`:""].filter(Boolean).join("\n"))}),(0,o.jsx)("rect",{x:a.x,y:a.y,width:a.w,height:a.h,className:"slc-sqd-hitbox"}),c&&(0,o.jsx)("rect",{x:a.x,y:a.y,width:a.w,height:a.h,rx:4,className:"slc-sqd-selected-plate"}),r,(0,o.jsx)("rect",{x:$,y:s-10,width:f-2,height:13,rx:6.5,className:`slc-sqd-ref-plate${c?" slc-sqd-ref-plate--selected":""}`}),(0,o.jsx)("text",{x:$+(f-2)/2,y:s,textAnchor:"middle",className:"slc-sqd-ref",children:p}),(0,o.jsx)("text",{ref:M(`${e.ref}:label`),x:S,y:s,className:`slc-sqd-label${c?" slc-sqd-label--selected":""}${d?" slc-sqd-label--error":""}`,children:i.label}),x>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:C,y:s-10,width:x,height:13,rx:3,className:"slc-sqd-opt"}),(0,o.jsx)("text",{x:C+x/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-opt-text",children:"opt"})]}),y>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:A,y:s-10.5,width:y,height:14,rx:7,className:"slc-sqd-event"}),(0,o.jsx)("text",{ref:M(`${e.ref}:event`),x:A+y/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-event-text",children:i.event})]}),v>0&&(0,o.jsx)("text",{ref:M(`${e.ref}:state`),x:O,y:s,className:"slc-sqd-state",children:b}),i.notes?.trim()&&(0,o.jsx)("rect",{x:j-5+3,y:s-9,width:5,height:11,rx:1.5,className:"slc-note-mark"})]},`m-${e.ref}`)}),$.participants.map(e=>{let t=A.get(e.name);if(!t)return null;let n=`participant:${e.name}`,s=q("participant",e.name)||!!B&&(B.from===e.name||B.to===e.name),r=["slc-node","slc-sqd-header",q("participant",e.name)?"slc-node--selected":s?"slc-sqd-header--involved":"",L.has(n)?"slc-node--error":""].filter(Boolean).join(" "),a=t.actor?"actor":t.object?"object":t.service?"service":"";return(0,o.jsxs)("g",{className:"slc-node--static slc-sqd-participant",onPointerDown:t=>P(t,{kind:"participant",id:e.name}),onContextMenu:I({kind:"participant",id:e.name}),children:[t$(t)&&(0,o.jsx)("title",{children:t$(t)}),(0,o.jsx)("rect",{x:e.left,y:e.top,width:e.width,height:e.height,rx:t.actor?e.height/2:4,className:r}),t.notes?.trim()&&(0,o.jsx)("rect",{x:e.left+e.width-24,y:e.top-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,o.jsx)("text",{x:e.x,y:e.top+e.height/2+(a?1:4),textAnchor:"middle",className:`slc-node-name slc-sqd-name${t.object?" slc-sqd-name--object":""}`,children:e.name}),a&&(0,o.jsxs)("text",{x:e.x,y:e.top+e.height-4,textAnchor:"middle",className:"slc-sqd-kind",children:["object"===a?`:${t.object}`:"service"===a?"service":"actor",t.holds?.length?` \xb7 holds ${t.holds.length}`:""]})]},`p-${e.name}`)})]})}),0===$.participants.length&&u&&(0,o.jsx)("div",{className:"slc-erd-empty",children:u})]})}let tM=e=>{let t,n=new Set,s=(e,s)=>{let r="function"==typeof e?e(t):e;if(!Object.is(r,t)){let e=t;t=(null!=s?s:"object"!=typeof r||null===r)?r:Object.assign({},t,r),n.forEach(n=>n(t,e))}},r=()=>t,a={setState:s,getState:r,getInitialState:()=>i,subscribe:e=>(n.add(e),()=>n.delete(e))},i=t=e(s,r,a);return a},t_=e=>{let t=e?tM(e):tM,n=e=>(function(e,t=e=>e){let n=l.default.useSyncExternalStore(e.subscribe,l.default.useCallback(()=>t(e.getState()),[e,t]),l.default.useCallback(()=>t(e.getInitialState()),[e,t]));return l.default.useDebugValue(n),n})(t,e);return Object.assign(n,t),n},tA=Object.create(null);tA.open="0",tA.close="1",tA.ping="2",tA.pong="3",tA.message="4",tA.upgrade="5",tA.noop="6";let tO=Object.create(null);Object.keys(tA).forEach(e=>{tO[tA[e]]=e});let tR={type:"error",data:"parser error"},tP="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tT="function"==typeof ArrayBuffer,tI=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,tL=({type:e,data:t},n,s)=>{if(tP&&t instanceof Blob)if(n)return s(t);else return tD(t,s);if(tT&&(t instanceof ArrayBuffer||tI(t)))if(n)return s(t);else return tD(new Blob([t]),s);return s(tA[e]+(t||""))},tD=(e,t)=>{let n=new FileReader;return n.onload=function(){t("b"+(n.result.split(",")[1]||""))},n.readAsDataURL(e)};function tq(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let tB="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tF="u"<typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<tB.length;e++)tF[tB.charCodeAt(e)]=e;let tY="function"==typeof ArrayBuffer,tz=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tX(e,t)};let n=e.charAt(0);return"b"===n?{type:"message",data:tU(e.substring(1),t)}:tO[n]?e.length>1?{type:tO[n],data:e.substring(1)}:{type:tO[n]}:tR},tU=(e,t)=>tY?tX((e=>{let t=.75*e.length,n=e.length,s,r=0,a,i,o,l;"="===e[e.length-1]&&(t--,"="===e[e.length-2]&&t--);let c=new ArrayBuffer(t),d=new Uint8Array(c);for(s=0;s<n;s+=4)a=tF[e.charCodeAt(s)],i=tF[e.charCodeAt(s+1)],o=tF[e.charCodeAt(s+2)],l=tF[e.charCodeAt(s+3)],d[r++]=a<<2|i>>4,d[r++]=(15&i)<<4|o>>2,d[r++]=(3&o)<<6|63&l;return c})(e),t):{base64:!0,data:e},tX=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer;function tH(e){return e.reduce((e,t)=>e+t.length,0)}function tJ(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),s=0;for(let r=0;r<t;r++)n[r]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function tV(e){if(e){var t=e;for(var n in tV.prototype)t[n]=tV.prototype[n];return t}}tV.prototype.on=tV.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},tV.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},tV.prototype.off=tV.prototype.removeListener=tV.prototype.removeAllListeners=tV.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+e];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<s.length;r++)if((n=s[r])===t||n.fn===t){s.splice(r,1);break}return 0===s.length&&delete this._callbacks["$"+e],this},tV.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,r=n.length;s<r;++s)n[s].apply(this,t)}return this},tV.prototype.emitReserved=tV.prototype.emit,tV.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},tV.prototype.hasListeners=function(e){return!!this.listeners(e).length};let tW="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),tK="u">typeof self?self:"u">typeof window?window:Function("return this")();function tZ(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}let tG=tK.setTimeout,tQ=tK.clearTimeout;function t0(e,t){t.useNativeTimers?(e.setTimeoutFn=tG.bind(tK),e.clearTimeoutFn=tQ.bind(tK)):(e.setTimeoutFn=tK.setTimeout.bind(tK),e.clearTimeoutFn=tK.clearTimeout.bind(tK))}function t1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class t2 extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class t5 extends tV{constructor(e){super(),this.writable=!1,t0(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new t2(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return("opening"===this.readyState||"open"===this.readyState)&&(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=tz(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return -1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){let t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class t4 extends t5{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)};((e,t)=>{let n=e.split("\x1e"),s=[];for(let e=0;e<n.length;e++){let r=tz(n[e],t);if(s.push(r),"error"===r.type)break}return s})(e,this.socket.binaryType).forEach(t),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){var t;let n,s,r;this.writable=!1,t=e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})},s=Array(n=e.length),r=0,e.forEach((e,a)=>{tL(e,!1,e=>{s[a]=e,++r===n&&t(s.join("\x1e"))})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=t1()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let t3=!1;try{t3="u">typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let t6=t3;function t8(){}class t7 extends t4{constructor(e){if(super(e),"u">typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="u">typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class t9 extends tV{constructor(e,t,n){super(),this.createRequest=e,t0(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;let t=tZ(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders)for(let e in n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0),this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null==(e=this._opts.cookieJar)||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null==(e=this._opts.cookieJar)||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}"u">typeof document&&(this._index=t9.requestsCount++,t9.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=t8,e)try{this._xhr.abort()}catch(e){}"u">typeof document&&delete t9.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function ne(){for(let e in t9.requests)t9.requests.hasOwnProperty(e)&&t9.requests[e].abort()}t9.requestsCount=0,t9.requests={},"u">typeof document&&("function"==typeof attachEvent?attachEvent("onunload",ne):"function"==typeof addEventListener&&addEventListener("onpagehide"in tK?"pagehide":"unload",ne,!1));let nt=(s=nn({xdomain:!1}))&&null!==s.responseType;function nn(e){let t=e.xdomain;try{if("u">typeof XMLHttpRequest&&(!t||t6))return new XMLHttpRequest}catch(e){}if(!t)try{return new tK[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let ns="u">typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class nr extends t5{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=ns?{}:tZ(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;tL(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&tW(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=t1()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let na=tK.WebSocket||tK.MozWebSocket,ni={websocket:class extends nr{createSocket(e,t,n){return ns?new na(e,t,n):t?new na(e,t):new na(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends t5{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{var s,r;let a,i,o,l,c=(s=Number.MAX_SAFE_INTEGER,r=this.socket.binaryType,n||(n=new TextDecoder),a=[],i=0,o=-1,l=!1,new TransformStream({transform(e,t){for(a.push(e);;){if(0===i){if(1>tH(a))break;let e=tJ(a,1);l=(128&e[0])==128,i=(o=127&e[0])<126?3:126===o?1:2}else if(1===i){if(2>tH(a))break;let e=tJ(a,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(8>tH(a))break;let e=tJ(a,8),n=new DataView(e.buffer,e.byteOffset,e.length),s=n.getUint32(0);if(s>2097151){t.enqueue(tR);break}o=0x100000000*s+n.getUint32(4),i=3}else{if(tH(a)<o)break;let e=tJ(a,o);t.enqueue(tz(l?e:n.decode(e),r)),i=0}if(0===o||o>s){t.enqueue(tR);break}}}})),d=e.readable.pipeThrough(c).getReader(),h=new TransformStream({transform(e,n){var s;s=t=>{let s,r=t.length;if(r<126)new DataView((s=new Uint8Array(1)).buffer).setUint8(0,r);else if(r<65536){let e=new DataView((s=new Uint8Array(3)).buffer);e.setUint8(0,126),e.setUint16(1,r)}else{let e=new DataView((s=new Uint8Array(9)).buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(s[0]|=128),n.enqueue(s),n.enqueue(t)},tP&&e.data instanceof Blob?e.data.arrayBuffer().then(tq).then(s):tT&&(e.data instanceof ArrayBuffer||tI(e.data))?s(tq(e.data)):tL(e,!1,e=>{t||(t=new TextEncoder),s(t.encode(e))})}});h.readable.pipeTo(e.writable),this._writer=h.writable.getWriter();let m=()=>{d.read().then(({done:e,value:t})=>{e||(this.onPacket(t),m())}).catch(e=>{})};m();let u={type:"open"};this.query.sid&&(u.data=`{"sid":"${this.query.sid}"}`),this._writer.write(u).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&tW(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}},polling:class extends t7{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=nt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new t9(nn,this.uri(),e)}}},no=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function nc(e){var t,n;let s,r;if(e.length>8e3)throw"URI too long";let a=e,i=e.indexOf("["),o=e.indexOf("]");-1!=i&&-1!=o&&(e=e.substring(0,i)+e.substring(i,o).replace(/:/g,";")+e.substring(o,e.length));let l=no.exec(e||""),c={},d=14;for(;d--;)c[nl[d]]=l[d]||"";return -1!=i&&-1!=o&&(c.source=a,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),s=(t=c.path).replace(/\/{2,9}/g,"/").split("/"),("/"==t.slice(0,1)||0===t.length)&&s.splice(0,1),"/"==t.slice(-1)&&s.splice(s.length-1,1),c.pathNames=s,n=c.query,r={},n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),c.queryKey=r,c}let nd="function"==typeof addEventListener&&"function"==typeof removeEventListener,nh=[];nd&&addEventListener("offline",()=>{nh.forEach(e=>e())},!1);class nm extends tV{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=nc(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=nc(t.host).host);t0(this,t),this.secure=null!=t.secure?t.secure:"u">typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("u">typeof location?location.hostname:"localhost"),this.port=t.port||("u">typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,s=n.length;e<s;e++){let s=n[e].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}(this.opts.query)),nd&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},nh.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);let e=this.opts.rememberUpgrade&&nm.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",nm.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+="string"==typeof n?function(e){let t=0,n=0;for(let s=0,r=e.length;s<r;s++)(t=e.charCodeAt(s))<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}(n):Math.ceil(1.33*(n.byteLength||n.size))),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,tW(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if("function"==typeof t&&(s=t,t=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;let r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return("opening"===this.readyState||"open"===this.readyState)&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(nm.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=nh.indexOf(this._offlineEventListener);-1!==e&&nh.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}nm.protocol=4;class nu extends nm{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;nm.priorWebsocketSuccess=!1;let s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;nm.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){n||(n=!0,c(),t.close(),t=null)}let a=e=>{let n=Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function i(){a("transport closed")}function o(){a("socket closed")}function l(e){t&&e.name!==t.name&&r()}let c=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",i),this.off("close",o),this.off("upgrading",l)};t.once("open",s),t.once("error",a),t.once("close",i),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}class np extends nu{constructor(e,t={}){const n="object"==typeof e,s=n?{...e}:{...t};(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>ni[e]).filter(e=>!!e)),super(n?s:e,s)}}np.protocol;let nf="function"==typeof ArrayBuffer,ng=Object.prototype.toString,nx="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===ng.call(Blob),ny="function"==typeof File||"u">typeof File&&"[object FileConstructor]"===ng.call(File);function nb(e){return nf&&(e instanceof ArrayBuffer||("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer))||nx&&e instanceof Blob||ny&&e instanceof File}let nv=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];(a=i||(i={}))[a.CONNECT=0]="CONNECT",a[a.DISCONNECT=1]="DISCONNECT",a[a.EVENT=2]="EVENT",a[a.ACK=3]="ACK",a[a.CONNECT_ERROR=4]="CONNECT_ERROR",a[a.BINARY_EVENT=5]="BINARY_EVENT",a[a.BINARY_ACK=6]="BINARY_ACK";class nw{constructor(e){this.replacer=e}encode(e){return(e.type===i.EVENT||e.type===i.ACK)&&function e(t,n){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let n=0,s=t.length;n<s;n++)if(e(t[n]))return!0;return!1}if(nb(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1==arguments.length)return e(t.toJSON(),!0);for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1}(e)?this.encodeAsBinary({type:e.type===i.EVENT?i.BINARY_EVENT:i.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===i.BINARY_EVENT||e.type===i.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t,n,s=(t=[],n=e.data,e.data=function e(t,n,s){if(!t)return t;if(nb(t)){let e={_placeholder:!0,num:n.length};return n.push(t),e}if(Array.isArray(t)){let s=Array(t.length);for(let r=0;r<t.length;r++)s[r]=e(t[r],n);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return e(t.toJSON(),n,!0);let r={};for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=e(t[s],n));return r}return t}(n,t),e.attachments=t.length,{packet:e,buffers:t}),r=this.encodeAsString(s.packet),a=s.buffers;return a.unshift(r),a}}class nj extends tV{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw Error("got plaintext data when reconstructing a packet");let n=(t=this.decodeString(e)).type===i.BINARY_EVENT;n||t.type===i.BINARY_ACK?(t.type=n?i.EVENT:i.ACK,this.reconstructor=new nk(t)):super.emitReserved("decoded",t)}else if(nb(e)||e.base64)if(this.reconstructor)(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw Error("got binary data when not reconstructing a packet");else throw Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(void 0===i[n.type])throw Error("unknown packet type "+n.type);if(n.type===i.BINARY_EVENT||n.type===i.BINARY_ACK){let s=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);let r=e.substring(s,t);if(r!=Number(r)||"-"!==e.charAt(t))throw Error("Illegal attachments");let a=Number(r);if(!n$(a)||a<1)throw Error("Illegal attachments");if(a>this.opts.maxAttachments)throw Error("too many attachments");n.attachments=a}if("/"===e.charAt(t+1)){let s=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(s,t)}else n.nsp="/";let s=e.charAt(t+1);if(""!==s&&Number(s)==s){let s=t+1;for(;++t;){let n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(nj.isPayloadValid(n.type,s))n.data=s;else throw Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case i.CONNECT:return nN(t);case i.DISCONNECT:return void 0===t;case i.CONNECT_ERROR:return"string"==typeof t||nN(t);case i.EVENT:case i.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===nv.indexOf(t[0]));case i.ACK:case i.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class nk{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t,n;let e=(t=this.reconPack,n=this.buffers,t.data=function e(t,n){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<n.length)return n[t.num];throw Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=e(t[s],n);else if("object"==typeof t)for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=e(t[s],n));return t}(t.data,n),delete t.attachments,t);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}let n$=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function nN(e){return"[object Object]"===Object.prototype.toString.call(e)}function nS(e){var t;return"string"==typeof e.nsp&&(void 0===(t=e.id)||n$(t))&&function(e,t){switch(e){case i.CONNECT:return void 0===t||nN(t);case i.DISCONNECT:return void 0===t;case i.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===nv.indexOf(t[0]));case i.ACK:return Array.isArray(t);case i.CONNECT_ERROR:return"string"==typeof t||nN(t);default:return!1}}(e.type,e.data)}function nE(e,t,n){return e.on(t,n),function(){e.off(t,n)}}e.s(["Decoder",()=>nj,"Encoder",()=>nw,"PacketType",()=>i,"isPacketValid",()=>nS,"protocol",0,5],11014);let nC=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class nM extends tV{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[nE(e,"open",this.onopen.bind(this)),nE(e,"packet",this.onpacket.bind(this)),nE(e,"error",this.onerror.bind(this)),nE(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,r;if(nC.hasOwnProperty(e))throw Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:i.EVENT,data:t};if(a.options={},a.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){let e=this.ids++,n=t.pop();this._registerAckCallback(e,n),a.id=e}let o=null==(s=null==(n=this.io.engine)?void 0:n.transport)?void 0:s.writable,l=this.connected&&!(null==(r=this.io.engine)?void 0:r._hasPingExpired());return this.flags.volatile&&!o||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var n;let s=null!=(n=this.flags.timeout)?n:this._opts.ackTimeout;if(void 0===s){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error("operation has timed out"))},s),a=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let r=(e,t)=>e?s(e):n(t);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...s)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:i.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case i.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case i.EVENT:case i.BINARY_EVENT:this.onevent(e);break;case i.ACK:case i.BINARY_ACK:this.onack(e);break;case i.DISCONNECT:this.ondisconnect();break;case i.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){let t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length)for(let t of this._anyListeners.slice())t.apply(this,e);super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,t.packet({type:i.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:i.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n]){t.splice(n,1);break}}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n]){t.splice(n,1);break}}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length)for(let t of this._anyOutgoingListeners.slice())t.apply(this,e.data)}}var n_=e.i(11014);function nA(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}nA.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(1&Math.floor(10*t))==0?e-n:e+n}return 0|Math.min(e,this.max)},nA.prototype.reset=function(){this.attempts=0},nA.prototype.setMin=function(e){this.ms=e},nA.prototype.setMax=function(e){this.max=e},nA.prototype.setJitter=function(e){this.jitter=e};class nO extends tV{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,t0(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!=(n=t.randomizationFactor)?n:.5),this.backoff=new nA({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||n_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null==(t=this.backoff)||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null==(t=this.backoff)||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null==(t=this.backoff)||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new np(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=nE(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},a=nE(t,"error",r);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{s(),r(Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(nE(e,"ping",this.onping.bind(this)),nE(e,"data",this.ondata.bind(this)),nE(e,"error",this.onerror.bind(this)),nE(e,"close",this.onclose.bind(this)),nE(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){tW(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new nM(this,e,t),this.nsps[e]=n),n}_destroy(e){for(let e of Object.keys(this.nsps))if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null==(n=this.engine)||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}let nR={};function nP(e,t){let n;"object"==typeof e&&(t=e,e=void 0);let s=function(e,t="",n){let s=e;n=n||"u">typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),s=nc(e)),!s.port&&(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";let r=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+t,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}(e,(t=t||{}).path||"/socket.io"),r=s.source,a=s.id,i=s.path,o=nR[a]&&i in nR[a].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?n=new nO(r,t):(nR[a]||(nR[a]=new nO(r,t)),n=nR[a]),s.query&&!t.query&&(t.query=s.queryKey),n.socket(s.path,t)}function nT(e){if(e&&"object"==typeof e&&"clientId"in e){let t=e.clientId;if("string"==typeof t)return t}}function nI(e){let{url:t,role:n,docId:s,name:r,token:a}=e,i=!1!==e.autoResync,o=nP(t,{auth:{token:a},autoConnect:!1}),l="disconnected",c=0,d="",h=[],m={patch:new Set,full:new Set,ack:new Set,presence:new Set,error:new Set,status:new Set,view:new Set};function u(e,t){for(let n of[...m[e]])n(t)}function p(e){l!==e&&(l=e,u("status",e))}function f(e){o.emit("def:request",{docId:s,sinceSeq:e})}function g(e){"number"==typeof e&&(i&&e>c+1&&f(c),c=Math.max(c,e))}function x(){u("presence",[...h])}function y(){return o.connected?Promise.resolve():new Promise((e,t)=>{p("connecting");let n=()=>{r(),e()},s=e=>{r(),t(e)},r=()=>{o.off("connect",n),o.off("connect_error",s)};o.once("connect",n),o.once("connect_error",s),o.connect()})}async function b(){return await y(),new Promise((e,t)=>{o.emit("bridge:join",{docId:s,role:n,name:r},n=>{if(!n||n.error){let e=n?.error??{code:"join_failed",message:"no join ack"};u("error",e),t(Error(`${e.code}: ${e.message}`));return}d=n.selfId,h=n.presence?[...n.presence]:[],c=n.snapshot?.seq??0,x(),e({selfId:d,snapshot:n.snapshot,presence:[...h]})})})}async function v(e){await y(),o.emit("view:show",{...e,docId:e.docId??s,origin:e.origin??(r||n)})}return o.on("connect",()=>p("connected")),o.on("disconnect",()=>p("disconnected")),o.on("connect_error",e=>{p("error"),u("error",{code:"connect_error",message:e?.message??String(e)})}),o.on("def:patch",e=>{g(e?.seq),e?.origin&&e.origin===d||u("patch",e)}),o.on("def:full",e=>{g(e?.seq),e?.origin&&e.origin===d||u("full",e)}),o.on("def:ack",e=>{u("ack",e)}),o.on("view:show",e=>{u("view",e)}),o.on("bridge:error",e=>{u("error",{code:e?.code??"error",message:e?.message??""})}),o.on("presence:list",e=>{h=Array.isArray(e)?[...e]:[],x()}),o.on("presence:join",e=>{let t=nT(e);t&&(h=[...h.filter(e=>e.clientId!==t),e],x())}),o.on("presence:leave",e=>{let t=nT(e);t&&(h=h.filter(e=>e.clientId!==t),x())}),o.on("presence:update",e=>{let t=nT(e);if(!t)return;let n=h.findIndex(e=>e.clientId===t);if(-1===n)h=[...h,e];else{let t={...h[n],...e};h=h.map((e,s)=>s===n?t:e)}x()}),{connect:y,join:b,emitPatch:function(e,t,n){o.emit("def:patch",{docId:s,ops:e,origin:d,baseSeq:n,mtime:t})},emitFull:function(e,t){o.emit("def:full",{docId:s,def:e,origin:d,mtime:t})},request:f,updatePresence:function(e){o.emit("presence:update",{docId:s,clientId:d,cursor:e.cursor,selection:e.selection})},emitView:v,on:function(e,t){let n=m[e];return n.add(t),()=>n.delete(t)},disconnect:function(){o.connected&&d&&o.emit("bridge:leave",{docId:s,clientId:d}),o.disconnect(),p("disconnected")},get status(){return l},get lastSeq(){return c},get presence(){return[...h]}}}function nL(e){return"runtime.enter"===e.op||"runtime.exit"===e.op}function nD(e){let{onFull:t,onPatch:n,onPresence:s,...r}=e,a=nI(r),i=null,o=0,l=[],c=[],d={status:a.status,def:null,seq:0,presence:[],activeStates:[]},h=new Set;function m(){for(let e of(d={status:a.status,def:i,seq:o,presence:l,activeStates:c},[...h]))e()}return a.on("status",()=>m()),a.on("full",e=>{i=e.def,"number"==typeof e.seq&&(o=e.seq),t?.(e),m()}),a.on("patch",e=>{"number"==typeof e.seq&&(o=e.seq);let t=e.ops??[],s=t.filter(nL),r=t.filter(e=>!nL(e));r.length>0&&i&&(i=u(i,r));for(let e of s)"runtime.enter"===e.op?c.includes(e.state)||(c=[...c,e.state]):"runtime.exit"===e.op&&c.includes(e.state)&&(c=c.filter(t=>t!==e.state));n?.(e),m()}),a.on("presence",e=>{l=e,s?.(e),m()}),{getSnapshot:function(){return d},subscribe:function(e){return h.add(e),()=>{h.delete(e)}},emitPatch:function(e){a.emitPatch(e)},emitFull:function(e){a.emitFull(e)},enter:function(e,t,n){let s={op:"runtime.enter",state:e,...void 0!==t?{from:t}:{},...void 0!==n?{eventId:n}:{}};a.emitPatch([s])},exit:function(e){a.emitPatch([{op:"runtime.exit",state:e}])},connect:function(){a.join().then(e=>{i=e.snapshot.def,o=e.snapshot.seq,l=e.presence,null!==i&&t?.({docId:e.snapshot.docId,def:i,seq:o,mtime:e.snapshot.mtime,origin:"join"}),m()}).catch(()=>{m()})},disconnect:function(){a.disconnect()}}}function nq(){return{settings:{namespace:"MyApp",name:"MyStateMachine",asynchronous:!1},events:[{name:"Internal",events:[]}],state:{name:"Root",states:[{name:"Idle",kind:"normal"},{name:"End",kind:"final"}]}}}function nB(){return{positions:{}}}function nF(e,t){if(e.name===t)return e;for(let n of e.states??[]){let e=nF(n,t);if(e)return e}return null}function nY(e,t,n){return e.name===t?n(e)??e:{...e,states:e.states?.map(e=>nY(e,t,n))}}function nz(e,t){return{...e,states:e.states?.filter(e=>e.name!==t).map(e=>nz(e,t))}}function nU(e){let t=[e.name];for(let n of e.states??[])t.push(...nU(n));return t}function nX(e){return e.events.flatMap(e=>(e.events??[]).map(e=>e.id))}function nH(e){let t=[],n=nU(e.state),s=nX(e);0===s.length&&t.push({ruleId:"V001",message:"No events defined"});let r=new Set;for(let e of n)r.has(e)&&t.push({ruleId:"V002",message:`Duplicate state name: ${e}`,element:e}),r.add(e);!function e(r){for(let e of r.transitions??[])s.includes(e.event)||t.push({ruleId:"V003",message:`Transition in '${r.name}' references unknown event '${e.event}'`,element:r.name}),e.nextState&&!n.includes(e.nextState)&&t.push({ruleId:"V004",message:`Transition in '${r.name}' targets unknown state '${e.nextState}'`,element:r.name});for(let n of("final"===r.kind&&(r.transitions?.length??0)>0&&t.push({ruleId:"V007",message:`Final state '${r.name}' must not have outgoing transitions`,element:r.name}),"final"===r.kind&&(r.states?.length??0)>0&&t.push({ruleId:"V008",message:`Final state '${r.name}' must not have child states`,element:r.name}),r.states??[]))e(n)}(e.state),e.state.states&&0!==e.state.states.length||t.push({ruleId:"V005",message:"Root state must have at least one child state",element:e.state.name});let a=new Set;for(let e of s)a.has(e)&&t.push({ruleId:"V003",message:`Duplicate event ID: ${e}`,element:e}),a.add(e);return t}function nJ(e,t){return{positions:{...$(e),...t.positions}}}Object.assign(nP,{Manager:nO,Socket:nM,io:nP,connect:nP});let nV=!1,nW=(r=(e,t)=>({definition:nq(),layout:nJ(nq(),nB()),viewport:{...q},fileName:null,docPath:null,dirty:!1,remoteMtime:null,remoteStatus:"idle",remoteMessage:null,activeStates:[],presence:[],_applyingRemote:!1,selection:{kind:null,id:null},drawMode:"select",drawSource:null,contextMenu:{visible:!1,x:0,y:0,target:null},undoStack:[],redoStack:[],activeTab:"properties",errors:[],showCodePreview:!1,generatedCode:null,navigationPath:["Root"],currentParent:"Root",_pushHistory:()=>{let{definition:n,layout:s,undoStack:r}=t(),a={definition:JSON.parse(JSON.stringify(n)),layout:JSON.parse(JSON.stringify(s))};e({undoStack:[...r.slice(-50),a],redoStack:[]})},setDefinition:n=>{t()._pushHistory();let s=nJ(n,t().layout);e({definition:n,layout:s,dirty:!0,errors:nH(n)})},updateSettings:n=>{t()._pushHistory(),e({definition:{...t().definition,settings:{...t().definition.settings,...n}},dirty:!0})},addState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=n??r.state.name;r.state=nY(r.state,a,e=>({...e,states:[...e.states??[],s]}));let i=nJ(r,t().layout);e({definition:r,layout:i,dirty:!0,errors:nH(r)})},updateState:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,...s})),e({definition:r,dirty:!0,errors:nH(r)})},removeState:n=>{t()._pushHistory();let s={...t().definition};s.state=nz(s.state,n);let r={positions:{...t().layout.positions}};delete r.positions[n],e({definition:s,layout:r,dirty:!0,errors:nH(s)})},nestState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=nF(r.state,n);if(!a||n===s)return;let i=JSON.parse(JSON.stringify(a));r.state=nz(r.state,n),r.state=nY(r.state,s,e=>({...e,states:[...e.states??[],i]})),e({definition:r,dirty:!0,errors:nH(r)})},addEventSource:n=>{t()._pushHistory(),e({definition:{...t().definition,events:[...t().definition.events,n]},dirty:!0})},updateEventSource:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map((e,t)=>t===n?{...e,...s}:e),e({definition:r,dirty:!0})},removeEventSource:n=>{t()._pushHistory();let s={...t().definition};s.events=s.events.filter((e,t)=>t!==n),e({definition:s,dirty:!0,errors:nH(s)})},addEvent:(n,s=0)=>{t()._pushHistory();let r={...t().definition},a=r.events[s]??{name:"Internal",events:[]};a.events=[...a.events??[],n],r.events=r.events.map((e,t)=>t===s?a:e),e({definition:r,dirty:!0,errors:nH(r)})},updateEvent:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,...s}:e)})),e({definition:r,dirty:!0})},removeEvent:n=>{t()._pushHistory();let s={...t().definition};s.events=s.events.map(e=>({...e,events:e.events?.filter(e=>e.id!==n)})),e({definition:s,dirty:!0,errors:nH(s)})},addParameter:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:[...e.parameters??[],s]}:e)})),e({definition:r,dirty:!0})},removeParameter:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:e.parameters?.filter((e,t)=>t!==s)}:e)})),e({definition:r,dirty:!0})},updateParameter:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.events=a.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:e.parameters?.map((e,t)=>t===s?{...e,...r}:e)}:e)})),e({definition:a,dirty:!0})},addAction:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>{let t=e[s]??{actions:[]};return{...e,[s]:{actions:[...t.actions,r]}}}),e({definition:a,dirty:!0})},removeAction:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.filter((e,t)=>t!==r)}}:e}),e({definition:a,dirty:!0})},updateAction:(n,s,r,a)=>{t()._pushHistory();let i={...t().definition};i.state=nY(i.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.map((e,t)=>t===r?a:e)}}:e}),e({definition:i,dirty:!0})},addTransition:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,transitions:[...e.transitions??[],s]})),e({definition:r,dirty:!0,errors:nH(r)})},updateTransition:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>({...e,transitions:e.transitions?.map((e,t)=>t===s?{...e,...r}:e)})),e({definition:a,dirty:!0})},removeTransition:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,transitions:e.transitions?.filter((e,t)=>t!==s)})),e({definition:r,dirty:!0,errors:nH(r)})},setStatePosition:(n,s)=>{e({layout:{positions:{...t().layout.positions,[n]:s}}})},arrangeLayout:()=>{t()._pushHistory(),e({layout:{positions:$(t().definition)}})},hydrateLayout:(n,s)=>{e({layout:{positions:{...t().layout.positions,...n}},...s?{viewport:s}:{}})},setViewport:t=>e({viewport:t}),select:(t,n)=>e({selection:{kind:t,id:n}}),clearSelection:()=>e({selection:{kind:null,id:null}}),setDrawMode:t=>e({drawMode:t,drawSource:null}),setDrawSource:t=>e({drawSource:t}),showContextMenu:(t,n,s)=>e({contextMenu:{visible:!0,x:t,y:n,target:s}}),hideContextMenu:()=>e({contextMenu:{visible:!1,x:0,y:0,target:null}}),undo:()=>{let{undoStack:n,definition:s,layout:r}=t();if(0===n.length)return;let a=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(r))};e({definition:a.definition,layout:a.layout,undoStack:n.slice(0,-1),redoStack:[...t().redoStack,i],dirty:!0,errors:nH(a.definition)})},redo:()=>{let{redoStack:n,definition:s,layout:r}=t();if(0===n.length)return;let a=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(r))};e({definition:a.definition,layout:a.layout,undoStack:[...t().undoStack,i],redoStack:n.slice(0,-1),dirty:!0,errors:nH(a.definition)})},canUndo:()=>t().undoStack.length>0,canRedo:()=>t().redoStack.length>0,setActiveTab:t=>e({activeTab:t}),loadFromJson:(t,n)=>{try{let s=JSON.parse(t),r=eg(s.stateMachine??s.StateMachine??s);nV=!!s&&"object"==typeof s&&"state"in s&&!("stateMachine"in s)&&!("StateMachine"in s);let a=nJ(r,nB()),i=r.state?.name??"Root";e({definition:r,layout:a,fileName:n??null,dirty:!1,errors:nH(r),selection:{kind:null,id:null},undoStack:[],redoStack:[],navigationPath:[i],currentParent:i})}catch(e){console.error("Failed to parse definition:",e)}},exportJson:()=>{let{definition:e}=t();return JSON.stringify(nV?e:{stateMachine:e},null,2)},applyRemote:(n,s,r)=>{try{let a=JSON.parse(n),i=eg(a.stateMachine??a.StateMachine??a);nV=!!a&&"object"==typeof a&&"state"in a&&!("stateMachine"in a)&&!("StateMachine"in a);let o=nJ(i,t().layout),l=i.state?.name??"Root",c=t(),d=new Set(nU(i.state)),h=c.navigationPath.filter(e=>d.has(e)),m=h.length?h:[l],u=m[m.length-1],p=c.selection,f=("state"===p.kind?!!p.id&&d.has(p.id):"transition"===p.kind?!!p.id&&d.has(p.id.split(":")[0]):"event"===p.kind&&!!p.id&&nX(i).includes(p.id))?p:{kind:null,id:null};e({definition:i,layout:o,fileName:r??t().fileName,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:nH(i),selection:f,navigationPath:m,currentParent:u})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}},setRemoteStatus:(t,n=null)=>e({remoteStatus:t,remoteMessage:n}),setRemoteMtime:t=>e({remoteMtime:t}),setDocPath:t=>e({docPath:t||null}),enterState:n=>{let s=t().activeStates;s.includes(n)||e({activeStates:[...s,n]})},exitState:n=>{let s=t().activeStates;s.includes(n)&&e({activeStates:s.filter(e=>e!==n)})},setPresence:t=>e({presence:t}),applyRemoteOps:(n,s,r)=>{e({_applyingRemote:!0});try{let r=t(),a=n.filter(e=>"runtime.enter"!==e.op&&"runtime.exit"!==e.op),i=a.length?u(r.definition,a):r.definition,o=r.activeStates;for(let e of n)"runtime.enter"===e.op?o.includes(e.state)||(o=[...o,e.state]):"runtime.exit"===e.op&&o.includes(e.state)&&(o=o.filter(t=>t!==e.state));let l=nJ(i,r.layout),c=i.state?.name??"Root",d=new Set(nU(i.state)),h=r.navigationPath.filter(e=>d.has(e)),m=h.length?h:[c],p=m[m.length-1],f=r.selection,g=("state"===f.kind?!!f.id&&d.has(f.id):"transition"===f.kind?!!f.id&&d.has(f.id.split(":")[0]):"event"===f.kind&&!!f.id&&nX(i).includes(f.id))?f:{kind:null,id:null};e({definition:i,layout:l,activeStates:o,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:nH(i),selection:g,navigationPath:m,currentParent:p})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}finally{e({_applyingRemote:!1})}},validate:()=>{let n=nH(t().definition);return e({errors:n}),n},setGeneratedCode:t=>e({generatedCode:t}),setShowCodePreview:t=>e({showCodePreview:t}),navigateInto:n=>{let{definition:s,navigationPath:r}=t(),a=nF(s.state,n);a&&(a.states?.length??0)>0&&e({navigationPath:[...r,n],currentParent:n,selection:{kind:null,id:null}})},navigateUp:n=>{let{navigationPath:s}=t();if(s.length<=1)return;let r=n??s.length-2,a=s.slice(0,r+1);e({navigationPath:a,currentParent:a[a.length-1],selection:{kind:null,id:null}})},getCurrentChildren:()=>{let{definition:e,currentParent:n}=t(),s=nF(e.state,n);return s?.states??[]}}))?t_(r):t_,nK="canvas",nZ=`[data-pinch-owner="${nK}"]`;function nG(e){return!!e&&"function"==typeof e.closest&&null!==e.closest(nZ)}let nQ="stateloom-canvas",n0="#030712",n1=["png","jpeg","svg","mermaid","markdown"],n2={png:"PNG",jpeg:"JPEG",svg:"SVG",mermaid:"Mermaid",markdown:"Markdown"},n5={png:"image/png",jpeg:"image/jpeg",svg:"image/svg+xml",mermaid:"text/vnd.mermaid",markdown:"text/markdown"},n4={png:"png",jpeg:"jpg",svg:"svg",mermaid:"mmd",markdown:"md"};async function n3(e,t,n={}){var s,r,a;let i;if("mermaid"===e||"markdown"===e){let n,a;i=new Blob([(s=t.definition,r="markdown"===e,n=["stateDiagram-v2"],s.state&&function e(t,n,s){let r=H(t);if(0===r.length)return;let a=" ".repeat(n+1),i=new Set;for(let e of r)for(let t of e.transitions??[]){if(!t.nextState)continue;let n=t.condition?`${t.event} [${t.condition}]`:t.event;s.push(`${a}${e.name} --> ${t.nextState} : ${n}`),i.add(e.name),i.add(t.nextState)}for(let e of r)i.has(e.name)||s.push(`${a}${e.name}`);for(let t of r)0!==H(t).length&&(s.push(`${a}state ${t.name} {`),e(t,n+1,s),s.push(`${a}}`))}(s.state,0,n),a=n.join("\n"),r?`\`\`\`mermaid
|
|
1
|
+
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,63052,e=>{"use strict";let t,n,s,r;var a,i,o=e.i(14294),l=e.i(30878);function c(e){return JSON.parse(JSON.stringify(e))}function d(e,t){for(let n of e.states??[]){if(n.name===t)return e;let s=d(n,t);if(s)return s}return null}function h(e,t,n){let s=function e(t,n){if(t.name===n)return t;for(let s of t.states??[]){let t=e(s,n);if(t)return t}return null}(e,t);if(!s)throw Error(`applyPatchOps: ${n} references missing state "${t}"`);return s}function m(e,t,n){let s=function(e,t){for(let n of e.events){let e=n.events??[];for(let s=0;s<e.length;s++)if(e[s].id===t)return{source:n,event:e[s],index:s}}return null}(e,t);if(!s)throw Error(`applyPatchOps: ${n} references missing event "${t}"`);return s}function u(e,t){let n=c(e);for(let e of(Array.isArray(n.events)||(n.events=[]),t))switch(e.op){case"settings.update":n.settings={...n.settings,...e.patch},""===n.settings.notes&&delete n.settings.notes;break;case"state.add":{let t=null===e.parent?n.state:h(n.state,e.parent,"state.add");t.states||(t.states=[]);let s=e.index??t.states.length;t.states.splice(s,0,c(e.state));break}case"state.update":{let t=h(n.state,e.name,"state.update");Object.assign(t,e.patch),""===t.notes&&delete t.notes,""===t.prompt&&delete t.prompt;break}case"state.remove":{if(n.state.name===e.name)throw Error(`applyPatchOps: cannot remove root state "${e.name}"`);let t=d(n.state,e.name);if(!t||!t.states)throw Error(`applyPatchOps: state.remove references missing state "${e.name}"`);let s=t.states.findIndex(t=>t.name===e.name);if(s<0)throw Error(`applyPatchOps: state.remove references missing state "${e.name}"`);t.states.splice(s,1),0===t.states.length&&delete t.states;break}case"state.nest":{let t=h(n.state,e.child,"state.nest"),s=h(n.state,e.newParent,"state.nest"),r=d(n.state,e.child);if(!r||!r.states)throw Error(`applyPatchOps: state.nest cannot detach root or missing state "${e.child}"`);let a=r.states.findIndex(t=>t.name===e.child),[i]=r.states.splice(a,1);0===r.states.length&&delete r.states,s.states||(s.states=[]),s.states.push(i??c(t));break}case"eventSource.add":{let t=e.index??n.events.length;n.events.splice(t,0,c(e.source));break}case"eventSource.update":{let t=n.events[e.index];if(!t)throw Error(`applyPatchOps: eventSource.update index ${e.index} out of range`);n.events[e.index]={...t,...e.patch};break}case"eventSource.remove":if(!n.events[e.index])throw Error(`applyPatchOps: eventSource.remove index ${e.index} out of range`);n.events.splice(e.index,1);break;case"event.add":{let t=n.events[e.sourceIndex];if(!t)throw Error(`applyPatchOps: event.add sourceIndex ${e.sourceIndex} out of range`);t.events||(t.events=[]);let s=e.index??t.events.length;t.events.splice(s,0,c(e.event));break}case"event.update":Object.assign(m(n,e.id,"event.update").event,e.patch);break;case"event.remove":{let t=m(n,e.id,"event.remove");t.source.events.splice(t.index,1),0===t.source.events.length&&delete t.source.events;break}case"parameter.add":{let t=m(n,e.eventId,"parameter.add");t.event.parameters||(t.event.parameters=[]);let s=e.index??t.event.parameters.length;t.event.parameters.splice(s,0,c(e.parameter));break}case"parameter.update":{let t=m(n,e.eventId,"parameter.update").event.parameters??[];if(!t[e.index])throw Error(`applyPatchOps: parameter.update index ${e.index} out of range for event "${e.eventId}"`);t[e.index]={...t[e.index],...e.patch};break}case"parameter.remove":{let t=m(n,e.eventId,"parameter.remove"),s=t.event.parameters;if(!s||!s[e.index])throw Error(`applyPatchOps: parameter.remove index ${e.index} out of range for event "${e.eventId}"`);s.splice(e.index,1),0===s.length&&delete t.event.parameters;break}case"transition.add":{let t=h(n.state,e.state,"transition.add");t.transitions||(t.transitions=[]);let s=e.index??t.transitions.length;t.transitions.splice(s,0,c(e.transition));break}case"transition.update":{let t=h(n.state,e.state,"transition.update").transitions??[];if(!t[e.index])throw Error(`applyPatchOps: transition.update index ${e.index} out of range for state "${e.state}"`);t[e.index]={...t[e.index],...e.patch};break}case"transition.remove":{let t=h(n.state,e.state,"transition.remove"),s=t.transitions;if(!s||!s[e.index])throw Error(`applyPatchOps: transition.remove index ${e.index} out of range for state "${e.state}"`);s.splice(e.index,1),0===s.length&&delete t.transitions;break}case"action.add":{let t=h(n.state,e.state,"action.add"),s=t[e.hook]??(t[e.hook]={actions:[]}),r=e.index??s.actions.length;s.actions.splice(r,0,c(e.action));break}case"action.update":{let t=h(n.state,e.state,"action.update")[e.hook];if(!t||!t.actions[e.index])throw Error(`applyPatchOps: action.update index ${e.index} out of range for state "${e.state}" ${e.hook}`);t.actions[e.index]=c(e.action);break}case"action.remove":{let t=h(n.state,e.state,"action.remove"),s=t[e.hook];if(!s||!s.actions[e.index])throw Error(`applyPatchOps: action.remove index ${e.index} out of range for state "${e.state}" ${e.hook}`);s.actions.splice(e.index,1),0===s.actions.length&&delete t[e.hook];break}case"runtime.enter":case"runtime.exit":break;default:throw Error(`applyPatchOps: unknown op ${JSON.stringify(e)}`)}return n}function p(e){let t=[e];for(let n of e.states??[])t.push(...p(n));return t}function f(e){let t=new Map;t.set(e.name,null);let n=e=>{for(let s of e.states??[])t.set(s.name,e.name),n(s)};return n(e),t}function g(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x(e,t,n,s,r){let a=Math.min(n.length,s.length);for(let i=0;i<a;i++)g(n[i],s[i])||r.push({op:"action.update",state:e,hook:t,index:i,action:s[i]});for(let n=a;n<s.length;n++)r.push({op:"action.add",state:e,hook:t,action:s[n],index:n});for(let a=n.length-1;a>=s.length;a--)r.push({op:"action.remove",state:e,hook:t,index:a})}function y(e){let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;let n=(t%360+360)%360;return`hsl(${n}, 65%, 55%)`}var b=e.i(50382);let v={hSpacing:220,vSpacing:140,nodeWidth:160,nodeHeight:60,compositeWidth:300,compositeHeight:200,originX:100,originY:120,sweeps:2,includeRoot:!0},w=(e,t)=>`${e}\u0000${t}`;function j(e){let t=new Set,n=[];for(let s of e.states??[])t.has(s.name)||(t.add(s.name),n.push(s));return n}function k(e,t){let n=new Map(e.map(e=>[e,[]]));for(let e of t)n.get(e.from).push(e.to);return n}function $(e,t={}){let n={...v,...t},s="state"in e?e.state:e,r={};if(!s)return r;if(!function e(t,n,s,r,a){let i=j(t);if(0===i.length)return;let o=i.map(e=>e.name),l=new Map(i.map(e=>[e.name,e])),c=function(e){let t=new Set,n=[];for(let s of e)for(let r of s.transitions??[]){let a=r.nextState?function(e,t){for(let n of e){if(n.name===t)return n.name;let e=[...n.states??[],...n.parallel?.states??[]];for(;e.length;){let s=e.pop();if(s.name===t)return n.name;e.push(...s.states??[],...s.parallel?.states??[])}}}(e,r.nextState):void 0;if(!a||a===s.name)continue;let i=w(s.name,a);t.has(i)||(t.add(i),n.push({from:s.name,to:a}))}return n}(i),d=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0])),r=new Set;for(let t of e){if(0!==s.get(t))continue;s.set(t,1);let e=[{node:t,i:0}];for(;e.length>0;){let t=e[e.length-1],a=n.get(t.node);if(t.i<a.length){let n=a[t.i++],i=s.get(n);1===i?r.add(w(t.node,n)):0===i&&(s.set(n,1),e.push({node:n,i:0}))}else s.set(t.node,2),e.pop()}}return r}(o,c),h=c.filter(e=>!d.has(w(e.from,e.to))),m=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0]));for(let e of t)s.set(e.to,(s.get(e.to)??0)+1);let r=new Map(e.map(e=>[e,0])),a=e.filter(e=>0===s.get(e));for(let e=0;e<a.length;e++){let t=a[e];for(let e of n.get(t)){r.set(e,Math.max(r.get(e),r.get(t)+1));let n=s.get(e)-1;s.set(e,n),0===n&&a.push(e)}}return r}(o,h),u=function(e,t,n){let s=new Map(e.map(e=>[e,[]]));for(let e of t)s.get(e.from).push(e.to),s.get(e.to).push(e.from);let r=new Set([n]),a=[n];for(;a.length>0;){let e=a.pop();for(let t of s.get(e)??[])r.has(t)||(r.add(t),a.push(t))}return r}(o,c,o[0]),p=0;for(let e of o)u.has(e)&&(p=Math.max(p,m.get(e)));for(let e of o)u.has(e)||m.set(e,m.get(e)+p+1);let f=Array.from({length:Math.max(...o.map(e=>m.get(e)))+1},()=>[]);for(let e of o)f[m.get(e)].push(e);!function(e,t,n){let s=new Map,r=new Map,a=(e,t,n)=>{let s=e.get(t);s?s.push(n):e.set(t,[n])};for(let e of t)a(s,e.to,e.from),a(r,e.from,e.to);let i=new Map,o=()=>{e.forEach(e=>e.forEach((e,t)=>i.set(e,t)))};o();let l=(e,t)=>{let n=e.map((e,n)=>{let s=(t.get(e)??[]).filter(e=>i.has(e));return{name:e,key:s.length?s.reduce((e,t)=>e+i.get(t),0)/s.length:n,i:n}});n.sort((e,t)=>e.key===t.key?e.i-t.i:e.key-t.key);for(let t=0;t<n.length;t++)e[t]=n[t].name};for(let t=0;t<n;t++){for(let t=1;t<e.length;t++)l(e[t],s),o();for(let t=e.length-2;t>=0;t--)l(e[t],r),o()}}(f,h,r.sweeps);let g=r.hSpacing-r.nodeWidth,x=r.vSpacing-r.nodeHeight,y=e=>Math.max(r.hSpacing,e+g),b=new Map(o.map(e=>{var t;return[e,(t=l.get(e),(t.states?.length??0)>0?{width:r.compositeWidth,height:r.compositeHeight}:{width:r.nodeWidth,height:r.nodeHeight})]})),v=f.map(e=>e.reduce((e,t)=>e+y(b.get(t).width),0)),$=n+Math.max(...v,0)/2,N=s;for(let t of(f.forEach((e,t)=>{let n=$-v[t]/2,s=r.nodeHeight;for(let t of e){let e=b.get(t),r=y(e.width);a[t]={x:Math.round(n+(r-e.width)/2),y:Math.round(N),width:e.width,height:e.height},n+=r,s=Math.max(s,e.height)}N+=s+x}),i)){if((t.states?.length??0)===0)continue;let n=a[t.name];e(t,n.x+20,n.y+40,r,a)}}(s,n.originX,n.originY,n,r),n.includeRoot){let e=j(s).map(e=>r[e.name]).filter(Boolean);if(0===e.length)r[s.name]={x:20,y:20,width:400,height:350};else{let t=Math.min(...e.map(e=>e.x)),n=Math.min(...e.map(e=>e.y)),a=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));r[s.name]={x:Math.round(t-40),y:Math.round(n-40),width:Math.round(a-t+80),height:Math.round(i-n+80)}}}return r}let N=(e,t)=>e.length*t*.55,S=e=>`[${e.length>32?`${e.slice(0,31).trimEnd()}…`:e}]`,E=e=>({width:Math.max(56,Math.max(N(e.event,11),e.condition?N(S(e.condition),9):0)+16)+16*!!e.glyph,height:e.condition?28:18}),C=e=>({x:e.x+5,y:e.cy-12-3}),M=(e,t)=>e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height,_={along:[.5,.36,.64,.24,.76,.14,.86],aside:[0,.6,-.6],across:[0,-1.3,1.3,-2.6,2.6]};function A(e,t,n={}){let{along:s,aside:r,across:a}={..._,...n},i=e.map((e,t)=>({label:e,i:t,width:E(e).width})).sort((e,t)=>e.width===t.width?e.i-t.i:t.width-e.width),o=[];for(let{label:e}of i){let{width:n,height:i}=E(e),l=8*!!e.glyph,c=null,d=1/0;e:for(let h of a)for(let a of r)for(let r of s){let s=e.at(r),m=s.x+a*n,u=s.y+h*i,p={x:m-n/2,y:u-18,width:n,height:i},f=[...o,...t].filter(e=>M(p,e)).length,g={...p,cx:m+l,cy:u,label:e};if(0===f){c=g;break e}f<d&&(d=f,c=g)}c&&o.push(c)}return o}let O=(e,t,n=2.2,s)=>({id:e,paths:t,strokeWidth:n,circles:s}),R=O("signal",["M3 12h10","m13 6 6 6-6 6Z"]),P=[{glyph:O("confirm",["m4 13 5.5 5.5L20 6"],2.4),words:["confirm","approve","accept","commit"]},{glyph:O("complete",["m8 12 3 3 5-6"],2.2,[{cx:12,cy:12,r:8.5}]),words:["complete","finish","done","close"]},{glyph:O("skip",["M4 17c0-6 4.5-9 9-9h6","m15 4 4.5 4-4.5 4"]),words:["skip","ignore","bypass"]},{glyph:O("flag",["M6 21V4","M6 4h12l-3 4.5 3 4.5H6Z"]),words:["flag","mark","revisit","review"]},{glyph:O("advance",["M4 6l8 6-8 6Z","M13 6l7 6-7 6Z"]),words:["advance","next","forward","step"]},{glyph:O("pause",["M9 5v14M15 5v14"],2.6),words:["pause","hold","suspend","stop"]},{glyph:O("play",["M7 4.5 19 12 7 19.5Z"]),words:["resume","start","begin","play","run"]},{glyph:O("clock",["M12 7.5V12l3.5 2.5"],2.2,[{cx:12,cy:12,r:8.5}]),words:["timeout","expire","tick","delay","after","elapse"]},{glyph:O("change",["M3 14c3-6 6-6 9 0s6 6 9 0"]),words:["change","update","edit","modify","set"]}];[...P.map(e=>e.glyph)];let T=e=>Math.round(100*e)/100;function I(e,t,n,s){return{p0:e,p1:t,p2:n,p3:s,path:`M ${T(e.x)} ${T(e.y)} C ${T(t.x)} ${T(t.y)}, ${T(n.x)} ${T(n.y)}, ${T(s.x)} ${T(s.y)}`,at:r=>{let a=1-r,i=a*a*a,o=3*a*a*r,l=3*a*r*r,c=r*r*r;return{x:i*e.x+o*t.x+l*n.x+c*s.x,y:i*e.y+o*t.y+l*n.y+c*s.y}}}}function L(e,t){let n=e.map(({from:e,to:n})=>{var s,r;return e===n?null:(s=t(e),(r=t(n)).y>=s.y+s.height?["bottom","top"]:r.y+r.height<=s.y?["top","bottom"]:r.x>=s.x+s.width?["right","left"]:r.x+r.width<=s.x?["left","right"]:["bottom","top"])}),s=new Map,r=(e,t,n)=>{let r=`${e}\0${t}`,a=s.get(r);a?a.push(n):s.set(r,[n])},a=(e,t)=>"top"===t||"bottom"===t?e.x+e.width/2:e.y+e.height/2;e.forEach((e,s)=>{let i=n[s];if(!i)return;let[o,l]=i;r(e.from,o,{edge:s,toward:a(t(e.to),o),role:"out"}),r(e.to,l,{edge:s,toward:a(t(e.from),l),role:"in"})});let i=new Map;for(let[e,n]of s){let[s,r]=e.split("\0"),a=t(s),o=[...n].sort((e,t)=>e.toward===t.toward?e.edge-t.edge:e.toward-t.toward);o.forEach((e,t)=>{i.set(`${e.edge}\0${e.role}`,function(e,t,n,s){let r="top"===t||"bottom"===t,a=r?e.width:e.height,i=r?e.x+e.width/2:e.y+e.height/2,o=s>1?Math.min(.72*a,40*(s-1)):0,l=s>1?i-o/2+o*n/(s-1):i;return"top"===t?{x:l,y:e.y}:"bottom"===t?{x:l,y:e.y+e.height}:"left"===t?{x:e.x,y:l}:{x:e.x+e.width,y:l}}(a,r,t,o.length))})}return e.map((e,s)=>{let r=n[s];if(!r){var a;let n,s,r;return n=(a=t(e.from)).x+a.width,s=a.y+.35*a.height,I({x:n,y:s},{x:n+44,y:s-12},{x:n+44,y:(r=a.y+.65*a.height)+12},{x:n,y:r})}let o=i.get(`${s}\0out`),l=i.get(`${s}\0in`);var c=r[0];if("top"===c||"bottom"===c){let e=(o.y+l.y)/2;return I(o,{x:o.x,y:e},{x:l.x,y:e},l)}let d=(o.x+l.x)/2;return I(o,{x:d,y:o.y},{x:d,y:l.y},l)})}let D={min:.2,max:2.5},q={x:0,y:0,scale:1};function B(e,t=D){return Number.isFinite(e)?Math.min(t.max,Math.max(t.min,e)):1}function F(e,t,n){return{x:e.x+t,y:e.y+n,scale:e.scale}}function Y(e,t,n,s=D){return z(e,e.scale*t,n,s)}function z(e,t,n,s=D){let r=B(t,s);if(r===e.scale)return e;let a={x:(n.x-e.x)/e.scale,y:(n.y-e.y)/e.scale};return{x:n.x-a.x*r,y:n.y-a.y*r,scale:r}}function U(e,t,n,s={}){let r=s.padding??48,a=s.maxScale??1,i=s.limits??D;if(0===e.length||t<=0||n<=0)return{...q};let o=1/0,l=1/0,c=-1/0,d=-1/0;for(let t of e)o=Math.min(o,t.x),l=Math.min(l,t.y),c=Math.max(c,t.x+t.width),d=Math.max(d,t.y+t.height);let h=Math.max(1,c-o),m=Math.max(1,d-l),u=B(Math.min(a,Math.min(Math.max(1,t-2*r)/h,Math.max(1,n-2*r)/m)),i);return{x:(t-h*u)/2-o*u,y:(n-m*u)/2-l*u,scale:u}}function X(e){return`translate(${e.x} ${e.y}) scale(${e.scale})`}function H(e){let t=new Set,n=[];for(let s of e.states??[])t.has(s.name)||(t.add(s.name),n.push(s));return n}function J(e){return e.stateOf?Array.isArray(e.stateOf)?e.stateOf:[e.stateOf]:[]}let V=["1:1","1:N","N:1","N:M"];function W(e){return!!e&&"object"==typeof e&&Array.isArray(e.entities)&&!("state"in e)}function K(e){let t=[],n=function(e){let t=new Map;for(let n of e.entities??[])n?.name&&!t.has(n.name)&&t.set(n.name,n);return t}(e),s=new Set;for(let[r,a]of(e.entities??[]).entries()){if(!a?.name){t.push({ruleId:"E001",message:`Entity at index ${r} has no name`,element:`entities[${r}]`});continue}s.has(a.name)&&t.push({ruleId:"E001",message:`Duplicate entity name "${a.name}"`,element:a.name}),s.add(a.name);let e=new Set;for(let[s,r]of(a.attributes??[]).entries()){if(!r?.name){t.push({ruleId:"E002",message:`Attribute at index ${s} of "${a.name}" has no name`,element:`${a.name}[${s}]`});continue}let i=`${a.name}.${r.name}`;if(e.has(r.name)&&t.push({ruleId:"E002",message:`Duplicate attribute "${i}"`,element:i}),e.add(r.name),r.references){let e=function(e){let t=e.indexOf(".");return t<0?{entity:e}:{entity:e.slice(0,t),attribute:e.slice(t+1)}}(r.references),s=n.get(e.entity);s?e.attribute&&!(s.attributes??[]).some(t=>t?.name===e.attribute)&&t.push({ruleId:"E005",message:`"${i}" references undefined attribute "${r.references}"`,element:i}):t.push({ruleId:"E005",message:`"${i}" references undefined entity "${e.entity}"`,element:i})}}}for(let[s,r]of(e.relationships??[]).entries()){let e=`relationships[${s}]`;for(let a of["from","to"]){let i=r?.[a];i&&n.has(i)||t.push({ruleId:"E003",message:`Relationship ${s} ${a} names undefined entity "${i??""}"`,element:e})}V.includes(r?.cardinality)||t.push({ruleId:"E004",message:`Relationship ${s} cardinality "${r?.cardinality??""}" is not one of ${V.join(", ")}`,element:e})}return t}function Z(e,t){let n=RegExp(`(?<![\\w.])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.([A-Za-z_]\\w*)\\b(?!\\s*\\()`,"g"),s=[];for(let t of e.matchAll(n))s.includes(t[1])||s.push(t[1]);return s}function G(e,t){let n=[],s=new Map;for(let e of t.entities??[])e?.name&&!s.has(e.name)&&s.set(e.name,e);let r=e.settings?.name??"",a=e.settings?.objects??[],i=e.state?function e(t){let n=[t];for(let s of t.states??[])n.push(...e(s));for(let s of t.parallel?.states??[])n.push(...e(s));return n}(e.state):[],o=i.flatMap(e=>(e.transitions??[]).map(e=>e.condition??"")),l=new Map;for(let e of a){let r=s.get(e.class);if(r){l.set(e.instance,r);continue}o.some(t=>Z(t,e.instance).length>0)&&n.push({ruleId:"L001",message:`Object "${e.instance}" has class "${e.class}", which is not an entity in "${t.settings?.name??""}", and a guard reads its fields`,element:e.instance})}for(let e of i)for(let t of e.transitions??[])if(t.condition)for(let[s,r]of l)for(let a of Z(t.condition,s))(r.attributes??[]).some(e=>e?.name===a)||n.push({ruleId:"L002",message:`Guard on ${e.name} [${t.event}] reads "${s}.${a}", which is not an attribute of "${r.name}"`,element:e.name});if(r){let e=new Set([...l.values()].map(e=>e.name));for(let s of t.entities??[])for(let t of s?.attributes??[])t&&J(t).includes(r)&&(e.has(s.name)||n.push({ruleId:"L003",message:`"${s.name}.${t.name}" stores the state of "${r}", but "${s.name}" is not the class of any of that machine's objects`,element:`${s.name}.${t.name}`}))}return n}function Q(e,t){let n=[];for(let s of e.entities??[])for(let e of s?.attributes??[])if(e)for(let r of J(e))t.includes(r)||n.push({ruleId:"L004",message:`"${s.name}.${e.name}" stores the state of "${r}", which is not among the machines checked (${t.join(", ")||"none"})`,element:`${s.name}.${e.name}`});return n}let ee=e=>({settings:{...e.settings},entities:(e.entities??[]).map(e=>({...e,attributes:(e.attributes??[]).map(e=>({...e}))})),relationships:(e.relationships??[]).map(e=>({...e}))});function et(e,t){let n=e.entities.find(e=>e.name===t);if(!n){let n=e.entities.map(e=>e.name).join(", ")||"none";throw Error(`Entity '${t}' not found. Entities: ${n}.`)}return n}function en(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function es(e,t){if(!t.name?.trim())throw Error("An entity needs a name.");let n=ee(e);if(n.entities.some(e=>e.name===t.name))throw Error(`Entity '${t.name}' already exists.`);return n.entities.push(en({...t,attributes:t.attributes??[]})),n}function er(e,t,n){let s=ee(e),r=et(s,t);return void 0!==n.notes&&(n.notes.trim()?r.notes=n.notes:delete r.notes),void 0!==n.description&&(n.description?r.description=n.description:delete r.description),void 0!==n.weak&&(n.weak?r.weak=!0:delete r.weak),s}let ea=e=>(e.attributes??[]).filter(e=>e?.name);function ei(e){return Math.max(110,Math.ceil(8.4*(e.name??"").length+36))}function eo(e){return Math.max(38,Math.ceil(3.5*Math.max(0,...e.map(e=>e.name.length))+14))}let el=e=>Math.ceil(e/2);function ec(e){let t=ea(e),n=ei(e);return 0===t.length?{width:n,height:40}:{width:n+2*(34+2*eo(t)),height:Math.max(40,32*el(t.length))}}let ed={"1:1":"||--||","1:N":"||--o{","N:1":"}o--||","N:M":"}o--o{"},eh=/^[A-Za-z_][A-Za-z0-9_-]*$/,em=e=>eh.test(e)?e:`"${e.replace(/"/g,"'")}"`,eu=(e,t)=>{let n=e.trim().replace(/[^A-Za-z0-9_()[\]-]+/g,"_").replace(/^_+|_+$/g,"");return/^[A-Za-z_]/.test(n)?n:n?`_${n}`:t},ep=e=>`"${e.replace(/"/g,"'")}"`,ef=["settings","states","parallel","entities","participants","messages","fragments","members","state"];function eg(e){let t=!1,n=e=>{if(Array.isArray(e)){let t=!1,s=e.map(e=>{let s=n(e);return s!==e&&(t=!0),s});return t?s:e}if(!e||"object"!=typeof e)return e;let s=null;if("notes"in e&&"string"!=typeof e.notes&&void 0!==e.notes){s={...e};let n=function(e){if(null!=e)return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"string"==typeof e?e:JSON.stringify(e)).join("\n\n"):JSON.stringify(e)}(e.notes);void 0!==n&&n.trim()?s.notes=n:delete s.notes,t=!0}for(let t of ef){if(!(t in e))continue;let r=(s??e)[t],a=n(r);a!==r&&((s??={...e})[t]=a)}return s??e},s=n(e);return t?s:e}function ex(e){return`${e.name} : ${e.type}`}function ey(e){let t=(e.attributes??[]).filter(e=>e?.name);return{width:Math.min(340,Math.max(170,Math.ceil(6.6*Math.max(1.15*(e.name??"").length,...t.map(e=>ex(e).length+6.96969696969697))+28))),height:30+20*Math.max(1,t.length)+8}}function eb(e){return e.trim().replace(/[\s_]+/g,"-").replace(/[^A-Za-z0-9.-]/g,"").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,60)}let ev=["alt","opt","loop"];function ew(e){return!!e&&"object"==typeof e&&Array.isArray(e.participants)&&Array.isArray(e.messages)&&!("state"in e)&&!("entities"in e)}function ej(e,t,n){return{settings:n?{namespace:e,name:t,description:n}:{namespace:e,name:t},participants:[],messages:[]}}function ek(e,t){return null===e?String(t+1):`f${e+1}.${t+1}`}function e$(e,t){if(/^\d+$/.exec(t)){let n=Number(t)-1,s=e.messages?.[n];return s?{fragment:null,index:n,message:s}:null}let n=/^f(\d+)\.(\d+)$/.exec(t);if(!n)return null;let s=Number(n[1])-1,r=Number(n[2])-1,a=e.fragments?.[s]?.messages?.[r];return a?{fragment:s,index:r,message:a}:null}function eN(e){let t=[];return(e.messages??[]).forEach((e,n)=>t.push({ref:ek(null,n),message:e,fragment:null})),(e.fragments??[]).forEach((e,n)=>(e?.messages??[]).forEach((e,s)=>t.push({ref:ek(n,s),message:e,fragment:n}))),t}function eS(e){let t=[];e?.settings?.name||t.push({ruleId:"S001",message:"The sequence has no settings.name",element:"settings"});let n=new Set;for(let[s,r]of(e.participants??[]).entries()){if(!r?.name){t.push({ruleId:"S002",message:`Participant at index ${s} has no name`,element:`participants[${s}]`});continue}n.has(r.name)&&t.push({ruleId:"S002",message:`Duplicate participant "${r.name}"`,element:r.name}),n.add(r.name)}let s=(e,s)=>{if(!e)return void t.push({ruleId:"S003",message:`Message ${s} is empty`,element:`message:${s}`});for(let r of["from","to"])e[r]&&n.has(e[r])||t.push({ruleId:"S003",message:`Message ${s} ${"from"===r?"comes from":"goes to"} "${e[r]??""}", which is not a participant`,element:`message:${s}`});e.label?.trim()||t.push({ruleId:"S004",message:`Message ${s} has no label`,element:`message:${s}`})};(e.messages??[]).forEach((e,t)=>s(e,ek(null,t)));let r=(e.messages??[]).length;for(let[n,a]of(e.fragments??[]).entries()){let e=`fragment:${n+1}`;if(!a||!ev.includes(a.kind)){t.push({ruleId:"S005",message:`Fragment ${n+1} has kind "${a?.kind??""}"; expected one of ${ev.join(", ")}`,element:e});continue}(!Number.isInteger(a.after)||a.after<0||a.after>r)&&t.push({ruleId:"S005",message:`Fragment ${n+1} branches after message ${a.after}, but the main sequence has messages 1 to ${r}`,element:e}),a.messages?.length||t.push({ruleId:"S006",message:`Fragment ${n+1} (${a.kind}) holds no message`,element:e}),(a.messages??[]).forEach((e,t)=>s(e,ek(n,t)))}return t}let eE=e=>{let t={settings:{...e.settings},participants:(e.participants??[]).map(e=>({...e,...e.holds?{holds:[...e.holds]}:{}})),messages:(e.messages??[]).map(e=>({...e}))};return e.fragments&&(t.fragments=e.fragments.map(e=>({...e,messages:(e.messages??[]).map(e=>({...e}))}))),t};function eC(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e&&!(Array.isArray(e)&&0===e.length)))}function eM(e,t){let n=e.participants.find(e=>e.name===t);if(!n){let n=e.participants.map(e=>e.name).join(", ")||"none";throw Error(`Participant '${t}' not found. Participants: ${n}.`)}return n}function e_(e,t){if(eM(e,t.from),eM(e,t.to),!t.label?.trim())throw Error("A message needs a label: what is said or done, in a few words.")}function eA(e,t){let n=e.fragments?.[t];if(n&&!Array.isArray(n.messages)&&(n.messages=[]),!n)throw Error(`Fragment ${t+1} not found. The sequence has ${e.fragments?.length??0} fragment(s).`);return n}function eO(e,t,n){let s=eE(e),r=eM(s,t),a=eC({...r,...n});return s.participants[s.participants.indexOf(r)]=a,s}function eR(e,t,n){let s=eE(e);e_(s,t);let r=void 0===n?s.messages.length:Math.max(0,Math.min(n,s.messages.length));if(s.messages.splice(r,0,eC({...t})),s.fragments)for(let e of s.fragments)e.after>r&&(e.after+=1);return s}function eP(e,t,n,s=null){let r=eE(e),a=null===s?r.messages:eA(r,s).messages,i=a[t];if(!i)throw Error(`Message ${t+1} not found${null===s?"":` in fragment ${s+1}`}.`);let o=eC({...i,...n});return e_(r,o),a[t]=o,r}function eT(e,t,n){let s=eE(e);if(!s.messages[t])throw Error(`Message ${t+1} not found.`);let r=Math.max(0,Math.min(n,s.messages.length-1)),a=(s.fragments??[]).map(e=>e.after>0?s.messages[e.after-1]:null),[i]=s.messages.splice(t,1);return s.messages.splice(r,0,i),(s.fragments??[]).forEach((e,t)=>{let n=a[t];n&&(e.after=s.messages.indexOf(n)+1)}),s}let eI={columnGap:150,rowHeight:34,headerHeight:34,topGap:30,fragmentPad:30,margin:24,fontSize:12};function eL(e,t={}){let n={...eI,...t},s=(Array.isArray(e.participants)?e.participants:[]).map(e=>({...e,name:"string"==typeof e?.name?e.name:""})),r=(Array.isArray(e.messages)?e.messages:[]).filter(e=>!!e&&"object"==typeof e),a=e=>Math.max(90,N(e,n.fontSize)+28),i=[],o=n.margin;s.forEach((t,l)=>{let c=a(t.name);if(0===l)i.push(o+c/2);else{let o=a(s[l-1].name),d=function(e,t,n,s,r){let a=0;for(let i of[...e,...(Array.isArray(t.fragments)?t.fragments:[]).flatMap(e=>(Array.isArray(e?.messages)?e.messages:[]).filter(e=>!!e&&"object"==typeof e))])(i.from===n&&i.to===s||i.from===s&&i.to===n)&&(a=Math.max(a,N("string"==typeof i.label?i.label:"",r)+30));return a}(r,e,s[l-1].name,t.name,n.fontSize),h=Math.max(n.columnGap,(o+c)/2+20,d+24);i.push(i[l-1]+h)}});let l=new Map(s.map((e,t)=>[e.name,i[t]])),c=s.map((e,t)=>{let s=a(e.name);return{name:e.name,x:i[t],left:i[t]-s/2,top:n.margin,width:s,height:n.headerHeight}}),d=[],h=n.margin+n.headerHeight+n.topGap,m=0,u=(e,t,s,r,a)=>{let i=l.get(s)??n.margin,o=l.get(r)??n.margin,c=s===r;c&&(m=Math.max(m,i+44+N("string"==typeof a?a:"",n.fontSize))),d.push({ref:ek(e,t),fragment:e,index:t,y:h,fromX:i,toX:o,self:c}),h+=n.rowHeight};(Array.isArray(e.messages)?e.messages:[]).forEach((e,t)=>{e&&"object"==typeof e&&u(null,t,e.from,e.to,e.label)});let p=n.margin/2,f=Math.max(i.length?i[i.length-1]+a(s[s.length-1].name)/2:n.margin,m)+n.margin/2,g=[];(Array.isArray(e.fragments)?e.fragments:[]).forEach((e,t)=>{if(!e||"object"!=typeof e)return;let s=(h+=n.rowHeight/2)-n.rowHeight/2;h+=n.fragmentPad-n.rowHeight/2+6,(Array.isArray(e.messages)?e.messages:[]).forEach((e,n)=>{e&&"object"==typeof e&&u(t,n,e.from,e.to,e.label)});let r=h-s+n.fragmentPad/2-n.rowHeight/2;g.push({index:t,left:p,top:s,width:f-p,height:r,headingY:s+16}),h=s+r+n.rowHeight/2});let x=n.margin+n.headerHeight,y=h;return{participants:c,rows:d,fragments:g,lifelineTop:x,lifelineBottom:y,width:Math.max(f+n.margin/2,2*n.margin+200),height:y+n.margin}}let eD=e=>e.replace(/[;#\n\r]+/g," ").replace(/\s+/g," ").trim(),eq=["propose","auto"];function eB(e,t){return"auto"===t||"propose"===t?t:e?.settings?.reconcile==="auto"?"auto":"propose"}let eF=["person","agent","service","external"];function eY(e){return e.toLowerCase().endsWith(".sysdf.json")}function ez(e){return!!e&&"object"==typeof e&&Array.isArray(e.members)&&!("state"in e)&&!("entities"in e)&&!("participants"in e)}function eU(e){return e.toLowerCase().endsWith(".erdf.json")?"erd":e.toLowerCase().endsWith(".sqdf.json")?"sequence":eY(e)?"system":"machine"}function eX(e){return e&&"object"==typeof e?W(e)?"erd":ew(e)?"sequence":ez(e)?"system":"state"in e?"machine":null:null}let eH=["erd","machine","sequence"];function eJ(e,t){return t.startsWith("/")?eV(t):eV((e.slice(0,e.lastIndexOf("/")+1)||"./")+t)}function eV(e){let t=e.startsWith("/"),n=[];for(let s of e.split("/"))if(s&&"."!==s){if(".."===s){n.length&&".."!==n[n.length-1]?n.pop():t||n.push("..");continue}n.push(s)}return(t?"/":"")+n.join("/")}let eW=e=>({settings:{...e.settings},members:(e.members??[]).map(e=>({...e})),actors:(e.actors??[]).map(e=>({...e}))});function eK(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e))}function eZ(e,t){let n=eW(e);return n.settings=eK({...n.settings,...t}),n}let eG=["refused","unknown-event","ended","state-mismatch"];function eQ(e,t=0){return e.settings?.name||e.state?.name||`machine ${t+1}`}function e0(e){let t=e.map((e,t)=>eQ(e,t));return t.map((e,n)=>t.indexOf(e)===n&&t.lastIndexOf(e)===n?e:`${e} #${n+1}`)}function e1(e,t){let n=e.states.get(t);for(;n&&n.states?.length;){let e=n.states.find(e=>"history"!==e.kind);if(!e)return null;n=e}return n?.name??null}function e2(e,t,n){let s=t;for(;s;){if(s===n)return!0;s=e.parent.get(s)}return!1}let e5=(e,t)=>e.states.get(t)?.kind==="final";function e4(e,t){let n,s,r=e0(t),a=t.map((e,t)=>(function(e,t,n){let s=new Map,r=new Map,a=(e,t)=>{if(e?.name){for(let n of(s.has(e.name)||(s.set(e.name,e),r.set(e.name,t)),e.states??[]))a(n,e.name);for(let t of e.parallel?.states??[])a(t,e.name)}};e.state&&a(e.state,null);let i=new Set;for(let t of e.events??[])for(let e of t?.events??[])e?.id&&i.add(e.id);for(let t of e.events??[])for(let e of t?.timers??[])e?.id&&i.add(e.id);let o={name:n,def:e,states:s,parent:r,events:i,initial:null};return o.initial=e.state?e1(o,e.state.name):null,o})(e,0,r[t])),i=(s=[{name:"main",kind:"main",items:n=(e.messages??[]).map((e,t)=>({ref:ek(null,t),message:e}))}],n.some(e=>e.message?.optional)&&s.push({name:"main without optional messages",kind:"without-optional",items:n.filter(e=>!e.message?.optional)}),(e.fragments??[]).forEach((e,t)=>{if(!e)return;let r=(e.messages??[]).map((e,n)=>({ref:ek(t,n),message:e})),a=Math.max(0,Math.min(e.after??0,n.length)),i=n.slice(0,a),o=n.slice(a),l=`${e.kind} ${t+1} \xb7 ${e.label??""}`.trim();"alt"===e.kind?s.push({name:l,kind:"alt",fragment:t,items:[...i,...r]}):"opt"===e.kind?s.push({name:l,kind:"opt",fragment:t,items:[...i,...r,...o]}):"loop"===e.kind&&s.push({name:l,kind:"loop",fragment:t,items:[...i,...r,...r,...o]})}),s).map(e=>(function(e,t){let n=new Map;for(let e of t){let t=e.initial&&e5(e,e.initial)?e.initial:null;n.set(e.name,{states:e.initial?[e.initial]:[],ended:t})}let s=[],r=new Map;for(let e of t){let t=eQ(e.def);r.set(t,r.has(t)?null:e),e.name!==t&&r.set(e.name,e)}for(let{ref:a,message:i}of e.items){if(!i)continue;let e=i.label??"";if(!i.event){let r={ref:a,label:e,from:[],to:[],result:"data"};i.state&&function(e,t,n,s){let r=n.filter(e=>t.machine?e.name===t.machine:e.states.has(t.state));if(!r.length){e.result="state-mismatch",e.note=t.machine?`no member machine is named "${t.machine}"`:`no member machine has a state "${t.state}"`;return}for(let n of r){let r=s.get(n.name),a=r.states.filter(e=>e2(n,e,t.state));if(a.length){r.states=a;continue}e.machine=n.name,e.from=e.to=[...r.states],e.result="state-mismatch",e.note=`the scenario says ${n.name} is in ${t.state}; the walk has it in ${r.states.join(" or ")||"no state"}`;return}}(r,i,t,n),s.push(r);continue}let o=i.event,l=t.filter(e=>e.events.has(o));if(i.machine){let t=r.get(i.machine);if(!t){let n=null===t?`two member machines are named "${i.machine}"`:`no member machine is named "${i.machine}"`;s.push({ref:a,label:e,event:o,from:[],to:[],result:"unknown-event",note:n});continue}if(!(l=l.filter(e=>e===t)).length){s.push({ref:a,label:e,event:o,machine:t.name,from:[],to:[],result:"unknown-event",note:`"${t.name}" does not define the event "${o}"`});continue}}if(!l.length){s.push({ref:a,label:e,event:o,from:[],to:[],result:"unknown-event",note:`no member machine defines the event "${o}"`});continue}for(let t of l){let r=n.get(t.name),l=[...r.states];if(r.ended){s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"ended",note:`${t.name} ended in ${r.ended} before this message`});continue}let c=l.filter(e=>!e5(t,e));if(!c.length){s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"ended",note:`${t.name} ended in ${l.join(" or ")} before this message`});continue}let d=new Set,h=new Map,m=new Set,u=[];for(let e of c)for(let n of function(e,t,n){let s=[],r=t;for(;r;){for(let t of e.states.get(r)?.transitions??[])if(t?.event===n&&(s.push(t),!t.condition))return s;r=e.parent.get(r)}return s}(t,e,o)){let s=n.nextState?e1(t,n.nextState):e;if(!s){u.push(n.nextState);continue}d.add(s),s!==e&&m.add(s),n.condition&&h.set(s,(h.get(s)??new Set).add(n.condition))}if(!d.size){let n=u.length?`${t.name}'s transition for "${o}" from ${c.join(" or ")} leads to ${[...new Set(u)].join(", ")}, which cannot be entered`:`${t.name} has no transition for "${o}" from ${c.join(" or ")}`;s.push({ref:a,label:e,event:o,machine:t.name,from:l,to:l,result:"refused",note:n});continue}let p=[...d],f={ref:a,label:e,event:o,machine:t.name,from:l,to:p,result:"moved"};if(i.state&&(!i.machine||i.machine===t.name)){let e=t.states.has(i.state);if(e||i.machine===t.name){let n=p.filter(e=>e2(t,e,i.state));n.length?p=n:(f.result="state-mismatch",f.note=e?`the scenario says ${t.name} is in ${i.state}; the walk has it in ${p.join(" or ")}`:`${t.name} has no state "${i.state}"`)}}f.to=p,"moved"!==f.result||p.some(e=>m.has(e))||(f.result="stayed");let g=new Set(p.flatMap(e=>[...h.get(e)??[]]));g.size&&(f.guards=[...g]),r.states=p;let x=p.filter(e=>e5(t,e));x.length&&x.length===p.length&&(r.ended=x[0]),s.push(f)}}let a={};for(let[e,t]of n)a[e]=t.states;return{name:e.name,kind:e.kind,...void 0===e.fragment?{}:{fragment:e.fragment},steps:s,accepted:!s.some(e=>eG.includes(e.result)),end:a}})(e,a));return{scenario:e.settings?.name??"",machines:a.map(e=>e.name),paths:i,accepted:i.every(e=>e.accepted)}}function e3(e){let t={machines:[],erds:[],sequences:[]};for(let n of e)n.def&&!n.error&&eX(n.def)===n.kind&&("machine"===n.kind&&t.machines.push({member:n.path,def:n.def}),"erd"===n.kind&&t.erds.push({member:n.path,def:n.def}),"sequence"===n.kind&&t.sequences.push({member:n.path,def:n.def}));return t}function e6(e,t){let n=[],s=(e,t,s,r)=>{n.push({ruleId:e,message:t,severity:"error",...s?{member:s}:{},...r?{element:r}:{}})},r=(e,t,s,r)=>{n.push({ruleId:e,message:t,severity:"warning",...s?{member:s}:{},...r?{element:r}:{}})};if(e){e.settings?.name||s("Y001","The system has no settings.name"),e.settings?.namespace||s("Y001","The system has no settings.namespace");let t=new Set;for(let[n,r]of(e.members??[]).entries()){if(!r?.path){s("Y002",`Member at index ${n} has no path`,void 0,`members[${n}]`);continue}t.has(r.path)&&s("Y002",`"${r.path}" is listed twice`,r.path),t.add(r.path),eH.includes(eU(r.path))&&r.path.endsWith(".json")||s("Y002",`"${r.path}" is not a document a system holds (.erdf.json, .smdf.json, .sqdf.json)`,r.path)}let n=new Set;for(let[t,r]of(e.actors??[]).entries()){if(!r?.name){s("Y004",`Actor at index ${t} has no name`,void 0,`actors[${t}]`);continue}n.has(r.name)&&s("Y004",`Duplicate actor "${r.name}"`,void 0,r.name),n.add(r.name),eF.includes(r.kind)||s("Y004",`Actor "${r.name}" has kind "${r.kind??""}"; expected one of ${eF.join(", ")}`,void 0,r.name)}}for(let e of t)e.error||!e.def?s("Y003",`"${e.path}" cannot be read: ${e.error??"no content"}`,e.path):eX(e.def)!==e.kind&&s("Y003",`"${e.path}" is named as a ${e.kind} but holds ${eX(e.def)??"something else"}`,e.path);let{machines:a,erds:i,sequences:o}=e3(t),l=new Map;for(let{member:e,def:t}of a){let n=eQ(t),r=l.get(n);r?s("Y005",`"${e}" and "${r}" are both machines named "${n}"; a message cannot say which`,e):l.set(n,e)}for(let{member:e,def:t}of i)for(let n of K(t))s(n.ruleId,n.message,e,n.element);for(let{member:e,def:t}of o)for(let n of eS(t))s(n.ruleId,n.message,e,n.element);let c=function(e){if(!e.length)return null;let t=new Set,n=e.flatMap(({def:e})=>e.entities??[]).filter(e=>e?.name&&!t.has(e.name)&&t.add(e.name));return{settings:{namespace:e[0].def.settings?.namespace??"",name:e.map(e=>e.def.settings?.name).join(" + ")},entities:n,relationships:e.flatMap(({def:e})=>e.relationships??[])}}(i);if(c){for(let{member:e,def:t}of a)for(let n of G(t,c))s(n.ruleId,n.message,e,n.element);let e=a.map(({def:e},t)=>eQ(e,t));for(let{member:t,def:n}of i)for(let r of Q(n,e))s(r.ruleId,r.message,t,r.element)}for(let{member:e,def:t}of a){let n=(s,a)=>{if(!s)return;let i=a||(s.transitions??[]).length>0,o=s.states??[];for(let a of(o.length||s.parallel||s===t.state||"final"===s.kind||"history"===s.kind||i||r("L009",`${eQ(t)}: ${s.name} has no way out and is not final; say how the machine leaves it, or mark it final`,e,`state:${s.name}`),o))n(a,i)};n(t.state,!1)}let d=a.map(e=>e.def),h=new Set(d.map((e,t)=>eQ(e,t))),m=new Map,u=new Set,p=new Set;d.forEach((e,t)=>{let n=new Set;for(let t of e.events??[]){for(let e of t?.events??[])e?.id&&n.add(e.id);for(let e of t?.timers??[])e?.id&&n.add(e.id)}m.set(eQ(e,t),n);let s=e=>{e&&(u.add(e.name),(e.states??[]).forEach(s),(e.parallel?.states??[]).forEach(s))};for(let t of(s(e.state),e.settings?.objects??[]))t?.instance&&p.add(t.instance)});let f=new Set((c?.entities??[]).map(e=>e.name)),g=new Set((e?.actors??[]).map(e=>e.name)),x=[];for(let{member:t,def:n}of o){let a=!1,i=e=>!!c||(a||r("L006",`${e} name entities, but the system has no ERD to hold them`,t),a=!0,!1);for(let r of n.participants??[]){if(!r?.name)continue;let n=`participant:${r.name}`;if(r.actor&&e&&!g.has(r.actor)&&s("L006",`Participant "${r.name}" is the actor "${r.actor}", which the system does not list`,t,n),r.object&&!p.has(r.object)&&s("L006",`Participant "${r.name}" is the object "${r.object}", which no member machine declares`,t,n),r.holds?.length&&i("Participants' holds"))for(let e of r.holds)f.has(e)||s("L006",`Participant "${r.name}" holds "${e}", which is not an entity`,t,n)}for(let{ref:e,message:a}of eN(n)){if(!a)continue;let n=`message:${e}`;a.machine&&!h.has(a.machine)?s("L005",`Message ${e} names the machine "${a.machine}", which is not a member`,t,n):a.event&&((a.machine?m.get(a.machine)?.has(a.event):[...m.values()].some(e=>e.has(a.event)))||s("L005",`Message ${e} fires "${a.event}", which ${a.machine?`"${a.machine}" does not define`:"no member machine defines"}`,t,n)),a.carries&&i("Messages' carries")&&!f.has(a.carries)&&s("L007",`Message ${e} carries "${a.carries}", which is not an entity`,t,n),a.state&&!u.has(a.state)&&r("L008",`Message ${e} says the machine is then in "${a.state}", which no member machine has`,t,n)}let o=e4(n,d);for(let e of(x.push({member:t,report:o}),o.paths)){let n=e.steps.filter(e=>"refused"===e.result||"ended"===e.result||"state-mismatch"===e.result);for(let s of[...new Set(n.map(e=>e.machine??""))]){let a=n.filter(e=>(e.machine??"")===s),i=a[0],o=a.length>1?` (${a.length-1} later message${a.length>2?"s stop":" stops"} too)`:"",l="without-optional"===e.kind?" — a message the rest depends on may not be optional":"";r("L008",`${e.name}, message ${i.ref}: ${i.note??i.result}${o}${l}`,t,`message:${i.ref}`)}}}return{issues:n,replays:x}}function e8(e){return`${e.kind}:${e.name}`}function e7(e){let t=e.indexOf(":");if(t<=0)return null;let n=e.slice(0,t);return["entity","attribute","machine","object","event","state","participant","message"].includes(n)?{kind:n,name:e.slice(t+1)}:null}function e9(e){let{machines:t,erds:n,sequences:s}=e3(e),r=[],a=new Map;for(let{member:e,def:t}of n)for(let n of t.entities??[])n?.name&&!a.has(n.name)&&a.set(n.name,e);let i=new Map;for(let{def:e}of n)for(let t of e.entities??[])i.set(t.name,new Set((t.attributes??[]).map(e=>e.name)));let o=new Map,l=new Map;t.forEach(({member:e,def:t},n)=>{let s=eQ(t,n);for(let n of t.events??[])for(let t of[...n?.events??[],...n?.timers??[]]){if(!t?.id)continue;let n=o.get(t.id)??[];n.push({member:e,machine:s}),o.set(t.id,n)}for(let n of t.settings?.objects??[]){if(!n?.instance)continue;l.has(n.instance)||l.set(n.instance,{member:e,className:n.class});let t=a.get(n.class);t&&r.push({from:{member:e,kind:"object",name:n.instance},to:{member:t,kind:"entity",name:n.class},rule:"L001",text:`is constructed as the entity ${n.class}`,back:`is the class of ${s}'s object ${n.instance}`})}let c=n=>{if(n){for(let s of n.transitions??[])if(s?.condition)for(let o of t.settings?.objects??[]){let t=a.get(o.class);if(t)for(let a of Z(s.condition,o.instance))i.get(o.class)?.has(a)&&r.push({from:{member:e,kind:"event",name:s.event},to:{member:t,kind:"attribute",name:`${o.class}.${a}`},rule:"L002",text:`its guard on ${n.name} reads ${o.class}.${a}`,back:`is read by the ${s.event} guard on ${n.name}`})}(n.states??[]).forEach(c)}};c(t.state)});let c=e0(t.map(e=>e.def)),d=new Map(t.map(({member:e},t)=>[c[t],e]));for(let{member:e,def:s}of n)for(let n of s.entities??[])for(let s of n.attributes??[])for(let a of J(s)){let i=d.get(a)??t.find(({def:e})=>eQ(e)===a)?.member;i&&r.push({from:{member:e,kind:"attribute",name:`${n.name}.${s.name}`},to:{member:i,kind:"machine",name:a},rule:"L003",text:`stores the state of ${a}`,back:`keeps its state in ${n.name}.${s.name}`})}for(let{member:e,def:n}of s){for(let t of n.participants??[]){if(!t?.name)continue;let n={member:e,kind:"participant",name:t.name},s=t.object?l.get(t.object):void 0;for(let e of(s&&r.push({from:n,to:{member:s.member,kind:"object",name:t.object},rule:"L006",text:`is the object ${t.object}`,back:`is the participant ${t.name}`}),t.holds??[])){let s=a.get(e);s&&r.push({from:n,to:{member:s,kind:"entity",name:e},rule:"L006",text:`holds ${e}`,back:`is held by ${t.name}`})}}for(let{ref:t,message:s}of eN(n)){if(!s)continue;let i={member:e,kind:"message",name:t};if(s.event)for(let e of o.get(s.event)??[])s.machine&&s.machine!==e.machine||r.push({from:i,to:{member:e.member,kind:"event",name:s.event},rule:"L005",text:`fires ${s.event}`,back:`is fired by message ${t} of ${n.settings?.name??"the scenario"}`});if(s.carries){let e=a.get(s.carries);e&&r.push({from:i,to:{member:e,kind:"entity",name:s.carries},rule:"L007",text:`carries ${s.carries}`,back:`is carried by message ${t}`})}}let s=e4(n,t.map(e=>e.def)).paths.find(e=>"main"===e.kind);for(let t of s?.steps??[]){if("moved"!==t.result||!t.machine)continue;let n=d.get(t.machine);if(n)for(let s of t.to)r.push({from:{member:e,kind:"message",name:t.ref},to:{member:n,kind:"state",name:s},rule:"L008",text:`moves ${t.machine} to ${s}`,back:`is entered on message ${t.ref}`})}}return r}let te=e=>{let t=e.replace(/[^A-Za-z0-9]+(.)?/g,(e,t)=>t?t.toUpperCase():"").replace(/^[^A-Za-z]+/,"");return t?t.charAt(0).toUpperCase()+t.slice(1):"Scenario"};function tt(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n)||(e.parallel?.states??[]).some(n));return n(e.state)}let tn=(e,t)=>t?"service":/\b(agent|bot|assistant)\b/i.test(e)?"agent":"person";function ts(e,t){let{machines:n,erds:s,sequences:r}=e3(t),a=[],i=e=>{a.includes(e)||a.push(e)},o=e,l=[];if(o)for(let{def:e}of r)for(let t of e.participants??[]){if(!t?.actor||(o.actors??[]).some(e=>e.name===t.actor))continue;let n=tn(t.actor,t.service);o=function(e,t){if(!t.name?.trim())throw Error("An actor needs a name.");if(!eF.includes(t.kind))throw Error(`An actor is one of ${eF.join(", ")}; got '${t.kind}'.`);let n=eW(e);if((n.actors??[]).some(e=>e.name===t.name))throw Error(`Actor '${t.name}' already exists.`);return(n.actors??=[]).push(eK({...t})),n}(o,{name:t.actor,kind:n}),l.push(`the system gains the ${n} "${t.actor}", who takes part in ${e.settings?.name??"a scenario"}`)}let c=s.map(e=>({member:e.member,def:e.def,reasons:[]})),d=new Set(c.flatMap(e=>(e.def.entities??[]).map(e=>e.name)));for(let{def:e}of r){let t=[];for(let n of e.participants??[])for(let s of n?.holds??[])s?.trim()&&t.push({name:s.trim(),why:`${n.name} holds it in ${e.settings?.name??"a scenario"}`});for(let{ref:n,message:s}of eN(e))s?.carries?.trim()&&t.push({name:s.carries,why:`message ${n} of ${e.settings?.name??"a scenario"} carries it`});for(let e of t){if(d.has(e.name))continue;if(!c.length){i(`"${e.name}" is named as data (${e.why}), but the system has no ERD to hold it; add a .erdf.json member`);continue}let t=c[0];t.def=es(t.def,{name:e.name,notes:`Added from the scenario: ${e.why}.`}),t.reasons.push(`${t.def.settings?.name??t.member} gains the entity ${e.name}, because ${e.why}`),d.add(e.name)}}let h=n.map(e=>e.def),m=e0(h),p=h.map(()=>[]),f=h.map(()=>[]),g=(e,t,n)=>{h=h.map((n,s)=>s===e?u(n,t):n),p[e].push(...t),f[e].push(n)};for(let{def:e}of r){for(let t of e.participants??[]){if(!t?.object||h.some(e=>(e.settings?.objects??[]).some(e=>e.instance===t.object)))continue;let e=(t.holds??[]).filter(e=>e?.trim()),n=1===e.length?e[0].trim():null;1===h.length&&n?g(0,[{op:"settings.update",patch:{objects:[...h[0].settings?.objects??[],{instance:t.object,class:n}]}}],`${m[0]} is constructed with the object ${t.object} : ${n}, because ${t.name} is it`):i(`${t.name} is the object "${t.object}", which no machine declares; ${1===h.length?"say which entity it is by holding exactly one":"declare it on the machine it belongs to"}`)}let t=function(e,t,n={}){let s=n.maxRounds??100,r=t.map(e=>e),a=e0(r),i=new Map,o=[],l=new Set,c=e4(e,r),d=new Set,h="",m=(e,t,n)=>{d.add(`${e}|${JSON.stringify(t)}`),r=r.map((n,s)=>s===e?u(n,t):n);let s=i.get(e)??{machine:a[e],index:e,ops:[],reasons:[]};s.ops.push(...t),s.reasons.push(n),i.set(e,s)},p=!0;for(let t=0;t<s;t++){let t=(function(e){let t=[];for(let n of e.paths)for(let e of n.steps)("refused"===e.result||"unknown-event"===e.result||"ended"===e.result||"state-mismatch"===e.result)&&t.push({path:n,step:e});return t})(e4(e,r)).find(({path:e,step:t})=>!l.has(`${t.ref}|${t.machine??""}|${t.result}|${e.name}`)&&!l.has(`${e.name}|${t.machine??""}`));if(!t){p=!1;break}let{path:n,step:s}=t,i=`${s.ref}|${s.machine??""}|${s.result}|${n.name}`,c=`${i}|${s.from.join("|")}`,u=c===h;h=c;let f=e$(e,s.ref)?.message,g=`message ${s.ref} (${n.name})`,x=(e,t)=>{l.add(i),l.add(`${n.name}|${s.machine??""}`),o.includes(t)||o.push(t)};if("without-optional"===n.kind){let t=(e.messages??[]).map((e,t)=>e?.optional?String(t+1):"").filter(Boolean);x(i,`${g}: without its optional message${t.length>1?"s":""} ${t.join(", ")} the scenario stops (${s.note??s.result}); if the rest depends on ${t.length>1?"them, they are":"it, it is"} not optional`);continue}if(!f){x(i,`${g}: cannot be read back from the sequence`);continue}if(u){x(i,`${g}: the change proposed for it did not let the walk through (${s.note??s.result}); a person has to look at ${s.machine??"the machine"}`);continue}let y=(e,t,n)=>{d.has(`${e}|${JSON.stringify(t)}`)?x(i,`${g}: the change it needs was already proposed and did not take effect (${s.note??s.result})`):m(e,t,n)};if("unknown-event"===s.result){let e=f.machine?r.map((e,t)=>a[t]===f.machine||(e.settings?.name??"")===f.machine?t:-1).filter(e=>e>=0):1===r.length?[0]:[];if(e.length>1){x(i,`${g}: ${e.length} member machines are named "${f.machine}"; rename one so the message can say which`);continue}let t=e.length?e[0]:-1;if(t<0){x(i,f.machine?`${g}: fires "${f.event}" for "${f.machine}", which is not a member machine`:`${g}: fires "${f.event}", which no machine defines; set the message's machine to say which one should`);continue}let n=r[t],s=`${te(f.from)}Events`,o=te(f.from),l=(n.events??[]).findIndex(e=>e?.name===s||e?.name===o||e?.name===f.from||e?.feeder===f.from),c=l>=0?n.events[l].name:s,d={id:f.event,...f.label?.trim()?{description:f.label.trim()}:{}};y(t,l>=0?[{op:"event.add",sourceIndex:l,event:d}]:[{op:"eventSource.add",source:{name:s,events:[d]}}],`${a[t]} defines "${f.event}" in ${c}, because ${g} fires it`);continue}if("refused"===s.result){let e=a.indexOf(s.machine??"");if(!f.state){x(i,`${g}: ${s.machine} refuses "${f.event}" from ${s.from.join(" or ")}; give the message a state to say where it leads, and reconcile can add the transition`);continue}if(1!==s.from.length){x(i,`${g}: ${s.machine} could be in ${s.from.join(" or ")}; choose which state "${f.event}" leaves from`);continue}let t=r[e],n=s.from[0],o=tt(t,f.state);if(!o&&!f.machine){let t=a.filter((t,n)=>n!==e&&tt(r[n],f.state)),n=r.filter(e=>(function(e){let t=new Set;for(let n of e.events??[])for(let e of[...n?.events??[],...n?.timers??[]])e?.id&&t.add(e.id);return t})(e).has(f.event)).length;if(t.length||n>1){x(i,`${g}: "${f.state}" ${t.length?"is a state of another machine":"is claimed while several machines hear the event"}; set the message's machine to say which machine it is about`);continue}}if(!function(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n));return n(e.state)}(t,n)){x(i,`${g}: ${s.machine} is in ${n}, inside a parallel region, which reconcile does not edit`);continue}let l=[],c=[],d=n===t.state?.name&&!(t.state?.states??[]).length;if(o||(l.push({op:"state.add",parent:null,state:{name:f.state,transitions:[]}}),c.push(d?`gains its first state, ${f.state}`:`adds the state ${f.state}`)),d){y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says the machine is there`);continue}let h=f.label?.trim()?{description:f.label.trim()}:{};l.push(n===f.state?{op:"transition.add",state:n,transition:{event:f.event,...h}}:{op:"transition.add",state:n,transition:{event:f.event,nextState:f.state,...h}}),c.push(n===f.state?`handles "${f.event}" in ${n} without leaving it`:`goes from ${n} to ${f.state} on "${f.event}"`),y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says so`);continue}if("state-mismatch"===s.result){x(i,`${g}: ${s.note??"the scenario and the machine disagree"}; one of them has to change, and that is a person's call`);continue}x(i,`${g}: ${s.note??s.result}`)}return p&&o.push(`reconcile stopped after ${s} rounds; what it proposed so far is kept, and the rest needs a person`),{proposals:[...i.values()].sort((e,t)=>e.index-t.index),unresolved:o,before:c,after:e4(e,r),machines:r}}(e,h);for(let e of t.proposals)p[e.index].push(...e.ops),f[e.index].push(...e.reasons);for(let n of(h=t.machines,t.unresolved))i(`${e.settings?.name??"scenario"}: ${n}`)}let x=n.map((e,t)=>({member:e.member,index:t,machine:m[t],ops:p[t],reasons:f[t],def:h[t]})).filter(e=>e.ops.length),y=c.filter(e=>e.reasons.length);return{machines:x,erds:y,system:o&&l.length?{def:o,reasons:l}:null,unresolved:a,count:x.reduce((e,t)=>e+t.reasons.length,0)+y.reduce((e,t)=>e+t.reasons.length,0)+l.length}}function tr(e,t){if(!e.count&&!e.unresolved.length)return"auto"===t?"auto: the drawings already agree":"the drawings agree";let n=[...e.machines.map(e=>`${e.machine} +${e.reasons.length}`),...e.erds.map(e=>`${e.def.settings?.name??e.member} +${e.reasons.length}`),...e.system?[`system +${e.system.reasons.length}`]:[]],s=n.length?n.join(", "):"no change",r=e.unresolved.length?`; ${e.unresolved.length} left open`:"";return"auto"===t?`auto: ${s}${r}`:`${e.count} change${1===e.count?"":"s"} proposed (${s})${r}`}function ta(e){return e.parallel?e.parallel.states:e.states??[]}function ti(e,t){return ta(e).find(e=>e.name===t)??null}let to={surface:"--slc-surface",nodeFill:"--slc-node-fill",nodeStroke:"--slc-node-stroke",compositeFill:"--slc-composite-fill",finalFill:"--slc-final-fill",accent:"--slc-accent",accentFill:"--slc-accent-fill",accentInk:"--slc-accent-ink",danger:"--slc-danger",drawSource:"--slc-draw-source",edge:"--slc-edge",chipFill:"--slc-chip-fill",chipStroke:"--slc-chip-stroke",label:"--slc-label",muted:"--slc-muted",faint:"--slc-faint",entry:"--slc-entry",exit:"--slc-exit",composite:"--slc-composite",active:"--slc-active",panelBg:"--slc-panel-bg",panelBorder:"--slc-panel-border",panelHover:"--slc-panel-hover"};function tl(e){let t={};if(!e)return t;for(let[n,s]of Object.entries(e)){let e=to[n];e&&"string"==typeof s&&(t[e]=s)}return t}let tc={x:100,y:100,width:160,height:60};function td(e,t){return 1===t?16*e:2===t?400*e:e}function th(e){return!!e&&"string"==typeof e.tagName&&(!!e.isContentEditable||["INPUT","TEXTAREA","SELECT","BUTTON","OPTION"].includes(e.tagName))}function tm(e){return(e.states?.length??0)>0||(e.parallel?.states.length??0)>0}function tu({mark:e,x:t,y:n,selected:s}){return(0,o.jsxs)("g",{transform:`translate(${t} ${n}) scale(0.5)`,strokeWidth:e.strokeWidth,className:`slc-glyph${s?" slc-glyph--selected":""}`,children:[(e.circles??[]).map((e,t)=>(0,o.jsx)("circle",{cx:e.cx,cy:e.cy,r:e.r,className:e.filled?"slc-glyph-dot":void 0},`c${t}`)),e.paths.map((e,t)=>(0,o.jsx)("path",{d:e},`p${t}`))]})}let tp={kind:null,id:null},tf=(0,l.forwardRef)(function(e,t){let{definition:n,positions:s,path:r=[],rootLabel:a,viewport:i,onViewportChange:c,selection:d=tp,activeStates:h,errorElements:m,drawMode:u="select",drawSource:p=null,readOnly:f=!1,showBreadcrumb:g=!0,showHud:x=!0,fitKey:y,onSelect:b,onClearSelection:v,onStateMove:w,onNavigateInto:j,onNavigateTo:k,onContextMenu:$,onCreateTransition:N,onCancelDraw:E,onDeleteState:M,onUndo:_,onRedo:O,hudExtras:T,emptyHint:I,theme:B,className:H,style:J,svgId:V,pinchOwner:W="canvas"}=e,K=(0,l.useRef)(null),Z=(0,l.useId)().replace(/:/g,""),G=(0,l.useRef)(i);G.current=i;let[Q,ee]=(0,l.useState)(null),et=(0,l.useRef)(null),en=(0,l.useCallback)(e=>{et.current=e,ee(e)},[]),[es,er]=(0,l.useState)(null),ea=(0,l.useRef)(!1),[ei,eo]=(0,l.useState)(!1),el=(0,l.useRef)(null),[ec,ed]=(0,l.useState)(!1),eh=(0,l.useRef)(!1),em=(0,l.useRef)(new Map),eu=(0,l.useRef)(new Map),ep=(0,l.useRef)(null),[ef,eg]=(0,l.useState)(!1),ex=(0,l.useRef)(null),ey=(0,l.useRef)(!1),[eb,ev]=(0,l.useState)(!1),ew=n.state,ej=(0,l.useMemo)(()=>{let e=function(e,t){let n=[],s=e;for(let e of t){let t=ti(s,e);if(!t)break;n.push(e),s=t}return n}(ew,r);return[a??ew?.name??"Root",...e]},[ew,r,a]),ek=(0,l.useMemo)(()=>ew?ta(function(e,t){let n=e;for(let e of t){let t=ti(n,e);if(!t)break;n=t}return n}(ew,r)):[],[ew,r]),e$=ej[ej.length-1],eN=(0,l.useMemo)(()=>(function(e){let t=new Set,n=[];for(let s of e.events??[])for(let e of s.events??[])t.has(e.id)||(t.add(e.id),n.push(e.id));return n})(n),[n]),eS=(0,l.useMemo)(()=>new Set(h??[]),[h]),eE=(0,l.useMemo)(()=>new Set(m??[]),[m]),eC=(0,l.useCallback)((e,t)=>{let n=K.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]),eM=(0,l.useCallback)(e=>{let t=em.current.get(e);em.current.delete(e),t?.hasPointerCapture?.(e)&&t.releasePointerCapture?.(e)},[]),e_=(0,l.useCallback)(e=>{let t=ex.current;t&&(void 0===e||t.pointerId===e)&&(clearTimeout(t.timer),ex.current=null)},[]),eA=(0,l.useCallback)((e,t)=>{if("touch"!==e.pointerType||!$)return;e_();let{pointerId:n,clientX:s,clientY:r}=e,a=setTimeout(()=>{ex.current=null,en(null),el.current=null,ed(!1),ey.current=!0,navigator.vibrate?.(10),$(s,r,t)},500);ex.current={pointerId:n,x:s,y:r,target:t,timer:a}},[e_,$,en]);(0,l.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(pointer: coarse)"),t=()=>ev(e.matches);return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),(0,l.useEffect)(()=>{let e=e=>{eu.current.delete(e.pointerId)};return window.addEventListener("pointerup",e),window.addEventListener("pointercancel",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("pointercancel",e)}},[]),(0,l.useEffect)(()=>()=>e_(),[e_]);let eO=(0,l.useRef)(new Set),eR=(0,l.useRef)(new Map),eP=(0,l.useRef)(e$),eT=(0,l.useRef)(new Set),[eI,eL]=(0,l.useState)(new Set),[eD,eq]=(0,l.useState)(new Set),[eB,eF]=(0,l.useState)(new Map),eY=eb?10/i.scale:0,ez=eb?28/i.scale:0,eU=(0,l.useCallback)(e=>s[e]??tc,[s]);(0,l.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&"z"===e.key&&_&&(e.preventDefault(),_()),(e.ctrlKey||e.metaKey)&&("y"===e.key||e.shiftKey&&"z"===e.key)&&O&&(e.preventDefault(),O()),"Escape"===e.key&&(er(null),E?.()),"Delete"===e.key&&"state"===d.kind&&d.id&&M&&M(d.id)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[_,O,E,M,d]);let eX=(0,l.useCallback)(e=>{let t=G.current;el.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origX:t.x,origY:t.y},eh.current=!1,ed(!0);let n=K.current;n&&(em.current.set(e.pointerId,n),n.setPointerCapture(e.pointerId))},[]),eH=(0,l.useCallback)(()=>{let e=[...eu.current.entries()];if(e.length<2)return;let[[t,n],[s,r]]=e;e_(),en(null),el.current=null;let a=Math.max(1,Math.hypot(r.x-n.x,r.y-n.y)),i=eC((n.x+r.x)/2,(n.y+r.y)/2);ep.current={a:t,b:s,startDist:a,startMidX:i.x,startMidY:i.y,start:G.current},eh.current=!0,eg(!0);let o=K.current;if(o){for(let e of[t,s])if(!em.current.has(e))try{o.setPointerCapture(e),em.current.set(e,o)}catch{}}},[e_,eC,en]),eJ=(0,l.useCallback)(e=>{if(ey.current=!1,"touch"!==e.pointerType)return;ev(!0),eu.current.set(e.pointerId,{x:e.clientX,y:e.clientY});let t=eu.current.size;t<2||(e.stopPropagation(),2===t&&eH())},[eH]),eV=(0,l.useCallback)((e,t)=>{if(0!==e.button||ea.current)return;if(e.stopPropagation(),eA(e,{kind:"state",id:t}),!f&&"transition"===u)return void(p?p!==t&&er({stateName:p,targetName:t,x:e.clientX,y:e.clientY}):b?.("state",t));if(b?.("state",t),f||!w)return;let n=eU(t);en({name:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origX:n.x,origY:n.y});let s=e.currentTarget;em.current.set(e.pointerId,s),s.setPointerCapture?.(e.pointerId)},[b,eU,u,p,eA,en,f,w]),eW=(0,l.useCallback)(e=>{if("touch"===e.pointerType){eA(e,{kind:"canvas"}),eX(e);return}(1===e.button||0===e.button&&ea.current)&&(e.preventDefault(),eX(e))},[eA,eX]),eK=(0,l.useCallback)(e=>{eu.current.has(e.pointerId)&&eu.current.set(e.pointerId,{x:e.clientX,y:e.clientY});let t=ex.current;t&&t.pointerId===e.pointerId&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>8&&e_(e.pointerId);let n=ep.current;if(n){if(e.pointerId!==n.a&&e.pointerId!==n.b)return;let t=eu.current.get(n.a),s=eu.current.get(n.b);if(!t||!s)return;let r=Math.hypot(s.x-t.x,s.y-t.y),a=eC((t.x+s.x)/2,(t.y+s.y)/2);c(F(z(n.start,n.start.scale*(r/n.startDist),{x:n.startMidX,y:n.startMidY}),a.x-n.startMidX,a.y-n.startMidY));return}let s=el.current;if(s){if(s.pointerId!==e.pointerId)return;let t=e.clientX-s.startX,n=e.clientY-s.startY,r=8*("touch"===e.pointerType);(Math.abs(t)>r||Math.abs(n)>r)&&(eh.current=!0),c({x:s.origX+t,y:s.origY+n,scale:G.current.scale});return}if(!Q||Q.pointerId!==e.pointerId||!w)return;let r=G.current.scale,a=(e.clientX-Q.startX)/r,i=(e.clientY-Q.startY)/r,o=eU(Q.name);w(Q.name,{...o,x:Math.max(0,Q.origX+a),y:Math.max(0,Q.origY+i)})},[Q,eU,w,c,e_,eC]),eZ=(0,l.useCallback)(e=>{eu.current.delete(e.pointerId),e_(e.pointerId),eM(e.pointerId);let t=ep.current;if(t&&(t.a===e.pointerId||t.b===e.pointerId)){ep.current=null,eg(!1);let n=t.a===e.pointerId?t.b:t.a,s=eu.current.get(n);if(s){let e=G.current;el.current={pointerId:n,startX:s.x,startY:s.y,origX:e.x,origY:e.y},eh.current=!0,ed(!0)}}el.current?.pointerId===e.pointerId&&(el.current=null),et.current?.pointerId===e.pointerId&&en(null),el.current||ed(!1),ep.current||eg(!1)},[e_,eM,en]);(0,l.useEffect)(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault();let t=G.current,n=td(e.deltaX,e.deltaMode),s=td(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey){let n=Y(t,Math.exp(-(.0025*s)),eC(e.clientX,e.clientY));n!==t&&c(n);return}let r=e.shiftKey?-(n||s):-n,a=e.shiftKey?0:-s;(0!==r||0!==a)&&c(F(t,r,a))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[c,eC]),(0,l.useEffect)(()=>{let e=e=>{"Space"!==e.code||e.repeat||th(e.target)||th(document.activeElement)||(e.preventDefault(),ea.current=!0,eo(!0))},t=e=>{"Space"===e.code&&(ea.current=!1,eo(!1))},n=()=>{ea.current=!1,eo(!1)};return window.addEventListener("keydown",e),window.addEventListener("keyup",t),window.addEventListener("blur",n),()=>{window.removeEventListener("keydown",e),window.removeEventListener("keyup",t),window.removeEventListener("blur",n)}},[]);let eG=(0,l.useCallback)(e=>{let t=K.current?.getBoundingClientRect(),n={x:(t?.width??0)/2,y:(t?.height??0)/2},s=G.current,r=Y(s,e,n);r!==s&&c(r)},[c]),eQ=(0,l.useCallback)(()=>{let e=K.current?.getBoundingClientRect(),t={x:(e?.width??0)/2,y:(e?.height??0)/2};c(z(G.current,1,t))},[c]),e0=(0,l.useCallback)(()=>{let e=K.current?.getBoundingClientRect();if(!e)return;let t=ek.map(e=>eU(e.name));c(t.length?U(t,e.width,e.height):{...q})},[ek,eU,c]);(0,l.useImperativeHandle)(t,()=>({fit:e0,zoomIn:()=>eG(1.25),zoomOut:()=>eG(.8),resetZoom:eQ,element:()=>K.current}),[e0,eG,eQ]);let e1=(0,l.useRef)(e0);e1.current=e0,(0,l.useEffect)(()=>{if(void 0===y)return;let e=requestAnimationFrame(()=>e1.current());return()=>cancelAnimationFrame(e)},[y]);let e2=(0,l.useCallback)((e,t)=>{$&&(e.preventDefault(),e.stopPropagation(),$(e.clientX,e.clientY,t?{kind:"state",id:t}:{kind:"canvas"}))},[$]),e5=(0,l.useMemo)(()=>{let e=new Set(ek.map(e=>e.name)),t=[];for(let n of ek)for(let[s,r]of(n.transitions??[]).entries())r.nextState&&e.has(r.nextState)&&t.push({from:n.name,to:r.nextState,event:r.event,stateName:n.name,index:s,condition:r.condition});return t},[ek]),e4=(0,l.useMemo)(()=>{let e=L(e5,eU),t=new Map(A(e5.map((t,n)=>{let s=eU(t.from);return{id:`${t.stateName}:${t.index}`,event:t.event,condition:t.condition,glyph:!0,at:t.from===t.to?()=>({x:s.x+s.width+44+30,y:s.y+s.height/2+4}):e[n].at}}),ek.map(e=>eU(e.name))).map(e=>[e.label.id,e]));return e5.flatMap((n,s)=>{let r=`${n.stateName}:${n.index}`,a=t.get(r);return a?[{arrow:n,id:r,curve:e[s],spot:a}]:[]})},[e5,ek,eU]);(0,l.useEffect)(()=>{let e=new Set(ek.map(e=>e.name)),t=new Set(e5.map(e=>`${e.stateName}:${e.index}`)),n=eP.current===e$,s=[...e].filter(e=>!eO.current.has(e));s.length&&eL(e=>{let t=new Set(e);return s.forEach(e=>t.add(e)),t});let r=[...t].filter(e=>!eT.current.has(e));r.length&&eq(e=>{let t=new Set(e);return r.forEach(e=>t.add(e)),t}),eL(t=>{let n=!1,s=new Set(t);return t.forEach(t=>{e.has(t)||(s.delete(t),n=!0)}),n?s:t}),eq(e=>{let n=!1,s=new Set(e);return e.forEach(e=>{t.has(e)||(s.delete(e),n=!0)}),n?s:e}),n?eF(t=>{let n=new Map(t),s=!1;return eR.current.forEach((t,r)=>{e.has(r)||n.has(r)||(n.set(r,t),s=!0)}),e.forEach(e=>{n.delete(e)&&(s=!0)}),s?n:t}):eF(e=>e.size?new Map:e),eO.current=e,eR.current=new Map(ek.map(e=>[e.name,{state:e,pos:eU(e.name)}])),eT.current=t,eP.current=e$},[ek,e$,e5,eU]);let e3={...tl(B),...J},e6=eb?" slc-hud--coarse":"";return(0,o.jsxs)("div",{className:`slc-pane${H?` ${H}`:""}`,style:e3,"data-pinch-owner":W,children:[g&&ej.length>1&&(0,o.jsx)("div",{className:"slc-crumbs",children:ej.map((e,t)=>(0,o.jsxs)("span",{className:"slc-crumb-item",children:[t>0&&(0,o.jsx)("span",{className:"slc-crumb-sep",children:"›"}),(0,o.jsx)("button",{type:"button",className:`slc-crumb${t===ej.length-1?" slc-crumb--current":""}`,onClick:()=>k?.(t),children:e})]},`${e}-${t}`))}),(0,o.jsxs)("svg",{ref:K,id:V,className:"slc-surface",style:{cursor:ec?"grabbing":ei?"grab":void 0,touchAction:"none",...eb?{WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"}:{}},onPointerDownCapture:eJ,onPointerDown:eW,onPointerMove:eK,onPointerUp:eZ,onPointerCancel:eZ,onAuxClick:e=>e.preventDefault(),onClick:e=>{if(ey.current){ey.current=!1,e.stopPropagation();return}if(eh.current){eh.current=!1;return}e.target?.tagName==="svg"&&(v?.(),er(null))},onContextMenu:e=>e2(e),children:[(0,o.jsxs)("defs",{children:[(0,o.jsx)("marker",{id:`slc-arrow-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,o.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead"})}),(0,o.jsx)("marker",{id:`slc-arrow-sel-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,o.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead slc-arrowhead--selected"})})]}),"transition"===u&&p&&(0,o.jsxs)("text",{x:"50%",y:"30",textAnchor:"middle",className:"slc-draw-hint",children:['Click target state to create transition from "',p,'"']}),(0,o.jsxs)("g",{transform:X(i),style:ec||ef?{pointerEvents:"none"}:void 0,children:[e4.map(({arrow:e,id:t,curve:n,spot:s})=>{let r="transition"===d.kind&&d.id===t,a=eD.has(t),i=n.at(.5),l=Math.hypot(i.x-s.cx,i.y-s.cy)>4;return(0,o.jsxs)("g",{children:[eb&&(0,o.jsx)("path",{d:n.path,fill:"none",stroke:"transparent",strokeWidth:ez,strokeLinecap:"round",pointerEvents:"stroke",onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,o.jsx)("path",{d:n.path,pathLength:1,markerEnd:`url(#slc-arrow${r?"-sel":""}-${Z})`,className:`slc-edge${r?" slc-edge--selected":""}${a?" slc-edge-enter":""}`,onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,o.jsxs)("g",{className:"slc-chip",onClick:e=>{e.stopPropagation(),b?.("transition",t)},children:[l&&(0,o.jsx)("line",{x1:i.x,y1:i.y,x2:s.cx,y2:s.cy-5,className:`slc-chip-leader${r?" slc-chip-leader--selected":""}`}),eb&&(0,o.jsx)("rect",{x:s.x-eY,y:s.y-eY,width:s.width+2*eY,height:s.height+2*eY,fill:"transparent",pointerEvents:"all"}),(0,o.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,rx:4,className:`slc-chip-plate${r?" slc-chip-plate--selected":""}`}),(0,o.jsx)(tu,{mark:function(e){let t=e.toLowerCase();for(let{glyph:e,words:n}of P)if(n.some(e=>t.includes(e)))return e;return R}(e.event),x:C(s).x,y:C(s).y,selected:r}),(0,o.jsx)("text",{x:s.cx,y:s.cy-5,textAnchor:"middle",className:`slc-chip-text${r?" slc-chip-text--selected":""}`,children:e.event}),e.condition&&(0,o.jsxs)("text",{x:s.cx,y:s.cy+7,textAnchor:"middle",className:"slc-chip-guard",children:[(0,o.jsx)("title",{children:e.condition}),S(e.condition)]})]})]},`arrow-${t}`)}),ek.map(e=>{let t=eU(e.name),n="state"===d.kind&&d.id===e.name,s="final"===e.kind,r="history"===e.kind,a=tm(e),i=p===e.name,l=eE.has(e.name),c=(e.onEntry?.actions?.length??0)>0,h=(e.onExit?.actions?.length??0)>0,m=eS.has(e.name),g=eI.has(e.name),x=ei?void 0:"transition"!==u||f?a?"slc-node--drillable":f||!w?"slc-node--static":"slc-node--draggable":"slc-node--drawing";return(0,o.jsxs)("g",{className:x,onPointerDown:t=>eV(t,e.name),onDoubleClick:t=>{t.stopPropagation(),a&&j?.(e.name)},onContextMenu:t=>e2(t,e.name),children:[eb&&(0,o.jsx)("rect",{x:t.x-eY,y:t.y-eY,width:t.width+2*eY,height:t.height+2*eY,rx:12,fill:"transparent",pointerEvents:"all"}),(0,o.jsxs)("g",{className:g?"slc-node-enter":void 0,children:[(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:r?30:s?4:8,strokeDasharray:s?"6 3":a?"4 2":void 0,className:["slc-node",s?"slc-node--final":a?"slc-node--composite":"",i?"slc-node--source":"",l?"slc-node--error":"",n?"slc-node--selected":"",m?"slc-node--active":""].filter(Boolean).join(" ")}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+(c||h?t.height/2:t.height/2+5),textAnchor:"middle",className:"slc-node-name",children:e.name}),e.kind&&"normal"!==e.kind&&(0,o.jsx)("text",{x:t.x+t.width-8,y:t.y+14,textAnchor:"end",className:"slc-node-kind",children:e.kind}),c&&(0,o.jsx)("text",{x:t.x+6,y:t.y+t.height-6,className:"slc-node-entry",children:"▸entry"}),h&&(0,o.jsx)("text",{x:t.x+t.width-6,y:t.y+t.height-6,textAnchor:"end",className:"slc-node-exit",children:"exit◂"}),l&&(0,o.jsx)("path",{d:`M ${t.x+6} ${t.y+15} l 5.5 -9.5 l 5.5 9.5 Z M ${t.x+11.5} ${t.y+9.5} v 2.6`,className:"slc-node-warn-mark"}),e.notes?.trim()&&(0,o.jsxs)("g",{children:[(0,o.jsx)("title",{children:`Notes: ${e.notes}`}),(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"})]}),a&&(0,o.jsxs)("text",{x:t.x+t.width/2,y:t.y+t.height-6,textAnchor:"middle",className:"slc-node-drill",children:["▼ ",(e.states?.length??0)+(e.parallel?.states.length??0)," children — ",eb?"double-tap":"double-click"," to enter"]})]})]},e.name)}),Array.from(eB.entries()).map(([e,{state:t,pos:n}])=>{let s="final"===t.kind,r=tm(t);return(0,o.jsxs)("g",{className:"slc-node-exit-group",onAnimationEnd:t=>{"slc-node-out"===t.animationName&&eF(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},children:[(0,o.jsx)("rect",{x:n.x,y:n.y,width:n.width,height:n.height,rx:"history"===t.kind?30:s?4:8,strokeDasharray:s?"6 3":r?"4 2":void 0,className:`slc-node${s?" slc-node--final":r?" slc-node--composite":""}`}),(0,o.jsx)("text",{x:n.x+n.width/2,y:n.y+n.height/2+5,textAnchor:"middle",className:"slc-node-name",children:e})]},`exit-${e}`)})]}),0===ek.length&&(0,o.jsx)("text",{x:"50%",y:"50%",textAnchor:"middle",className:"slc-empty",children:I??"This level has no states."})]}),x&&(0,o.jsxs)("div",{className:`slc-hud${e6}`,children:[(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Zoom out (Ctrl + wheel down, or pinch in)",disabled:i.scale<=D.min,onClick:()=>eG(.8),children:"−"}),(0,o.jsxs)("button",{type:"button",className:"slc-hud-btn slc-hud-btn--scale",title:"Reset zoom to 100%",onClick:eQ,children:[Math.round(100*i.scale),"%"]}),(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Zoom in (Ctrl + wheel up, or pinch out)",disabled:i.scale>=D.max,onClick:()=>eG(1.25),children:"+"}),(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,o.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Fit the whole machine in view",onClick:e0,children:"⤢ Fit"}),T&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),T]}),(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,o.jsx)("span",{className:"slc-hud-hint",title:eb?"Drag to pan · pinch with two fingers to zoom · press and hold for the menu · double-tap a composite to enter it":"Wheel scrolls · Shift+wheel scrolls sideways · Ctrl+wheel zooms at the cursor · middle-drag or Space+drag pans",children:ef?"pinching":ec?"panning":eb?"drag · pinch · hold":ei?"space to pan":"wheel · ⌃wheel · space"})]}),es&&(0,o.jsxs)("div",{className:"slc-picker",style:{left:es.x,top:es.y-80},onClick:e=>e.stopPropagation(),children:[(0,o.jsxs)("div",{className:"slc-picker-title",children:[es.stateName," → ",es.targetName]}),(0,o.jsx)("div",{className:"slc-picker-sub",children:"Select event:"}),0===eN.length?(0,o.jsx)("div",{className:"slc-picker-empty",children:"No events defined. Add events first."}):eN.map(e=>(0,o.jsx)("button",{type:"button",className:"slc-picker-item",onClick:()=>{es&&(N?.(es.stateName,es.targetName,e),er(null),E?.())},children:e},e)),(0,o.jsx)("button",{type:"button",className:"slc-picker-cancel",onClick:()=>{er(null),E?.()},children:"Cancel"})]})]})});function tg(e,t){return 1===t?16*e:2===t?400*e:e}let tx={"1:1":["one","one"],"1:N":["one","many"],"N:1":["many","one"],"N:M":["many","many"]};function ty(e,t,n){let s=t.x-e.x,r=t.y-e.y,a=Math.hypot(s,r)||1,i=s/a,o=r/a,l=-o,c=(t,n)=>`${(e.x+i*t+l*n).toFixed(1)} ${(e.y+o*t+i*n).toFixed(1)}`;return"one"===n?`M ${c(9,6)} L ${c(9,-6)}`:`M ${c(13,0)} L ${c(0,7)} M ${c(13,0)} L ${c(0,-7)} M ${c(13,0)} L ${c(0,0)}`}function tb(e){return[e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n\n")}function tv(e,t){if(!e)return"";let n=Math.min(e.x+e.width,Math.max(e.x,t.x)),s=Math.min(e.y+e.height,Math.max(e.y,t.y));return n===t.x&&s===t.y?"":`M ${t.x} ${t.y} L ${n} ${s}`}function tw({definition:e,notation:t="crowsfoot",positions:n,viewport:s,onViewportChange:r,selection:a=null,errorElements:i,readOnly:c=!1,fitKey:d,onSelect:h,onClearSelection:m,onEntityMove:u,onOpenMachine:p,onContextMenu:f,emptyHint:g,theme:x,className:y,style:b,svgId:v}){let w=(0,l.useRef)(null),j=(0,l.useRef)(s);j.current=s;let k=(0,l.useRef)(null),$=(0,l.useRef)(new Map),N=(0,l.useRef)(null),S=(0,l.useMemo)(()=>{let t=new Set;return(e.entities??[]).filter(e=>!(!e?.name||t.has(e.name))&&!!n[e.name]&&(t.add(e.name),!0))},[e.entities,n]),E="chen"===t,C=(0,l.useMemo)(()=>new Map(E?S.map(e=>{var t;let s,r,a,i,o,l,c;return[e.name,(t=n[e.name],s=ea(e),r=ei(e),a={x:t.x+(t.width-r)/2,y:t.y+(t.height-40)/2,width:r,height:40},i=eo(s),o=a.y+a.height/2,l=el(s.length),c=s.map((e,t)=>{let n=t<l,r=n?l:s.length-l,c=o+((n?t:t-l)-(r-1)/2)*32,d=n?a.x-34-i:a.x+a.width+34+i;return{attribute:e,cx:d,cy:c,rx:i,ry:13,from:{x:n?a.x:a.x+a.width,y:o},to:{x:n?d+i:d-i,y:c}}}),{rect:a,ovals:c,routingBox:{x:a.x,y:t.y,width:a.width,height:t.height}})]}):[]),[E,S,n]),M=(0,l.useMemo)(()=>{let t=new Map(S.map((e,t)=>[e.name,`e${t}`])),s=(e.relationships??[]).filter(e=>e&&t.has(e.from)&&t.has(e.to)),r=L(s.map(e=>({from:t.get(e.from),to:t.get(e.to)})),e=>{let t=S[Number(e.slice(1))].name;return C.get(t)?.routingBox??n[t]});return s.map((e,t)=>({rel:e,curve:r[t]}))},[e.relationships,S,n,C]),_=(0,l.useMemo)(()=>A(M.filter(({rel:e})=>E||e.label).map(({rel:e,curve:t})=>({event:e.label||" ",at:t.at,rel:e})),S.map(e=>n[e.name])),[E,M,S,n]),O=(0,l.useCallback)((e,t)=>{let n=w.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,l.useEffect)(()=>{if(void 0===d)return;let e=w.current?.getBoundingClientRect(),t=Object.values(n);e&&0!==t.length&&r(U(t,e.width,e.height))},[d]),(0,l.useEffect)(()=>{let e=w.current;if(!e)return;let t=e=>{e.preventDefault();let t=j.current,n=tg(e.deltaX,e.deltaMode),s=tg(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void r(Y(t,Math.exp(-(.0025*s)),O(e.clientX,e.clientY)));let a=e.shiftKey?-(n||s):-n,i=e.shiftKey?0:-s;(0!==a||0!==i)&&r(F(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[r,O]);let R=()=>{let e=[...$.current.values()];if(e.length<2)return null;let[t,n]=e;return{distance:Math.hypot(n.x-t.x,n.y-t.y)||1,mid:{x:(t.x+n.x)/2,y:(t.y+n.y)/2}}},P=(e,t)=>{if(0!==e.button&&"mouse"===e.pointerType)return;if(e.stopPropagation(),w.current?.setPointerCapture(e.pointerId),$.current.set(e.pointerId,O(e.clientX,e.clientY)),$.current.size>=2){k.current=null,N.current=R();return}let s=void 0!==t&&!c;k.current={kind:s?"move":"pan",pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,name:t,origin:s?n[t]:void 0,moved:!1}},T=e=>{if($.current.delete(e.pointerId),N.current){$.current.size<2&&(N.current=null);return}let t=k.current;!t||t.pointerId!==e.pointerId||(k.current=null,t.moved||(t.name?h?.(t.name):m?.()))},I=new Set(i??[]);return(0,o.jsxs)("div",{className:`slc-pane${y?` ${y}`:""}`,style:{...tl(x),...b},children:[(0,o.jsx)("svg",{ref:w,id:v,className:"slc-surface",onPointerDown:e=>P(e),onPointerMove:e=>{if($.current.has(e.pointerId)&&$.current.set(e.pointerId,O(e.clientX,e.clientY)),N.current){let e=R();if(!e)return;let t=N.current;r(Y(F(j.current,e.mid.x-t.mid.x,e.mid.y-t.mid.y),e.distance/t.distance,e.mid)),N.current=e;return}let t=k.current;if(t&&t.pointerId===e.pointerId&&!(!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY))){if(t.moved=!0,"pan"===t.kind)r(F(j.current,e.clientX-t.lastX,e.clientY-t.lastY));else if(t.name&&t.origin){var n,s,a;let r=(n=j.current,s=e.clientX-t.startX,a=e.clientY-t.startY,{x:s/n.scale,y:a/n.scale});u?.(t.name,{...t.origin,x:t.origin.x+r.x,y:t.origin.y+r.y})}t.lastX=e.clientX,t.lastY=e.clientY}},onPointerUp:T,onPointerCancel:T,onContextMenu:e=>{f&&(e.preventDefault(),f(e.clientX,e.clientY,{kind:"canvas"}))},children:(0,o.jsxs)("g",{transform:X(s),children:[M.map(({rel:e,curve:t},n)=>{if(E){let[s,r]=function(e){switch(e){case"1:1":return["1","1"];case"N:1":return["N","1"];case"N:M":return["M","N"];default:return["1","N"]}}(e.cardinality),a=t.at(.12),i=t.at(.88);return(0,o.jsxs)("g",{className:"slc-erd-rel",children:[(0,o.jsx)("path",{d:tv(C.get(e.from)?.rect,t.p0),className:"slc-erd-line"}),(0,o.jsx)("path",{d:tv(C.get(e.to)?.rect,t.p3),className:"slc-erd-line"}),(0,o.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,o.jsx)("text",{x:a.x+9,y:a.y+4,className:"slc-erd-card",children:s}),(0,o.jsx)("text",{x:i.x+9,y:i.y+4,className:"slc-erd-card",children:r})]},`r${n}`)}let[s,r]=tx[e.cardinality]??tx["1:N"];return(0,o.jsxs)("g",{className:"slc-erd-rel",children:[(0,o.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,o.jsx)("path",{d:ty(t.p0,t.p1,s),className:"slc-erd-mark"}),(0,o.jsx)("path",{d:ty(t.p3,t.p2,r),className:"slc-erd-mark"})]},`r${n}`)}),S.map(e=>{let t=n[e.name],s=(e.attributes??[]).filter(e=>e?.name),r=["slc-node",a===e.name?"slc-node--selected":"",I.has(e.name)?"slc-node--error":""].filter(Boolean).join(" "),i=C.get(e.name);if(i){let{rect:t,ovals:n}=i;return(0,o.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>P(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[n.map(e=>(0,o.jsx)("path",{d:`M ${e.from.x} ${e.from.y} L ${e.to.x} ${e.to.y}`,className:"slc-erd-attr-line"},`l-${e.attribute.name}`)),n.map(e=>{var t;let n,s=J(e.attribute),r=s.length>0&&!!p;return(0,o.jsxs)("g",{className:r?"slc-erd-state":void 0,onPointerDown:r?e=>e.stopPropagation():void 0,onClick:r?()=>p(s[0]):void 0,children:[(0,o.jsx)("title",{children:(n=J(t=e.attribute),[`${ex(t)}${t.nullable?" ?":""}`,"pk"===t.key?"primary key":"uk"===t.key?"unique":"",t.references?`references ${t.references}`:"",n.length?`stores the state of ${n.join(", ")}`:"",t.description??""].filter(Boolean).join(" — "))}),(0,o.jsx)("ellipse",{cx:e.cx,cy:e.cy,rx:e.rx,ry:e.ry,className:"slc-erd-oval"}),(0,o.jsxs)("text",{x:e.cx,y:e.cy+4,textAnchor:"middle",className:`slc-erd-oval-text${"pk"===e.attribute.key?" slc-erd-oval-text--pk":""}${s.length?" slc-erd-row--state":""}`,children:[s.length?"◉ ":"",e.attribute.name]})]},e.attribute.name)}),tb(e)&&(0,o.jsx)("title",{children:tb(e)}),(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:2,className:r}),e.notes?.trim()&&(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),e.weak&&(0,o.jsx)("rect",{x:t.x+4,y:t.y+4,width:t.width-8,height:t.height-8,rx:1,className:"slc-erd-weak"}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+t.height/2+5,textAnchor:"middle",className:"slc-node-name",children:e.name})]},e.name)}return(0,o.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>P(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[tb(e)&&(0,o.jsx)("title",{children:tb(e)}),(0,o.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:6,className:r}),e.notes?.trim()&&(0,o.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,o.jsx)("path",{d:`M ${t.x} ${t.y+30} h ${t.width}`,className:"slc-erd-rule"}),(0,o.jsx)("text",{x:t.x+t.width/2,y:t.y+15+5,textAnchor:"middle",className:"slc-node-name",children:e.name}),0===s.length&&(0,o.jsx)("text",{x:t.x+14,y:t.y+30+15,className:"slc-erd-row slc-erd-row--empty",children:"no attributes"}),s.map((e,n)=>{let s=t.y+30+20*n+15,r=J(e),a=["pk"===e.key?"PK":"uk"===e.key?"UK":"",e.references?"FK":""].filter(Boolean).join(" ");return(0,o.jsxs)("g",{className:r.length&&p?"slc-erd-state":void 0,onPointerDown:r.length&&p?e=>e.stopPropagation():void 0,onClick:r.length&&p?()=>p(r[0]):void 0,children:[(r.length>0||e.description)&&(0,o.jsx)("title",{children:[r.length?`stores the state of ${r.join(", ")}`:"",e.description??""].filter(Boolean).join(" — ")}),(0,o.jsxs)("text",{x:t.x+14,y:s,className:`slc-erd-row${r.length?" slc-erd-row--state":""}${"pk"===e.key?" slc-erd-row--pk":""}`,children:[r.length?"◉ ":"",ex(e),e.nullable?" ?":""]}),a&&(0,o.jsx)("text",{x:t.x+t.width-14,y:s,textAnchor:"end",className:"slc-erd-badge",children:a})]},e.name)})]},e.name)}),_.map((e,t)=>{if(!E)return null;let n=e.x+e.width/2,s=e.y+e.height/2,r=Math.max(34,Math.ceil(3.7*(e.label.rel.label??"").length+18));return(0,o.jsxs)("g",{pointerEvents:"none",children:[(0,o.jsx)("path",{d:`M ${n-r} ${s} L ${n} ${s-18} L ${n+r} ${s} L ${n} ${s+18} Z`,className:"slc-erd-diamond"}),(0,o.jsx)("text",{x:n,y:s+4,textAnchor:"middle",className:"slc-erd-rel-label",children:e.label.rel.label??""})]},`d${t}`)}),!E&&_.map((e,t)=>(0,o.jsxs)("g",{pointerEvents:"none",children:[(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:4,className:"slc-chip-plate"}),(0,o.jsx)("text",{x:e.cx,y:e.cy-5,textAnchor:"middle",className:"slc-erd-rel-label",children:e.label.event})]},`l${t}`))]})}),0===S.length&&g&&(0,o.jsx)("div",{className:"slc-erd-empty",children:g})]})}function tj(e,t){return 1===t?16*e:2===t?400*e:e}function tk(e,t,n,s){let r=e-9*n;return s?`M ${r} ${t-4.5} L ${e} ${t} L ${r} ${t+4.5}`:`M ${r} ${t-4.5} L ${e} ${t} L ${r} ${t+4.5} Z`}function t$(e){return[e.actor?`actor ${e.actor}`:e.object?`object ${e.object}`:e.service?`service ${e.service}`:"",e.holds?.length?`holds ${e.holds.join(", ")}`:"",e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n")}let tN=e=>"string"==typeof e?e:null==e?"":String(e);function tS(e){let t=e&&"object"==typeof e?e:{};return{from:tN(t.from),to:tN(t.to),label:tN(t.label),event:tN(t.event)||void 0,machine:tN(t.machine)||void 0,carries:tN(t.carries)||void 0,state:tN(t.state)||void 0,description:tN(t.description)||void 0,notes:tN(t.notes)||void 0,optional:!0===t.optional||void 0,reply:!0===t.reply||void 0}}function tE(e){let t=e&&"object"==typeof e?e:{},n=e=>Array.isArray(e)?e:[],s=t.settings&&"object"==typeof t.settings?t.settings:{};return{settings:{namespace:tN(s.namespace),name:tN(s.name),notes:tN(s.notes)||void 0},participants:n(t.participants).map(e=>{let t=e&&"object"==typeof e?e:{};return{name:tN(t.name),description:tN(t.description)||void 0,notes:tN(t.notes)||void 0,actor:tN(t.actor)||void 0,service:tN(t.service)||void 0,object:tN(t.object)||void 0,holds:Array.isArray(t.holds)?t.holds.map(tN):"string"==typeof t.holds?[t.holds]:void 0}}),messages:n(t.messages).map(tS),...Array.isArray(t.fragments)?{fragments:t.fragments.map(e=>{let t=e&&"object"==typeof e?e:{};return{kind:tN(t.kind),label:tN(t.label),after:"number"==typeof t.after&&Number.isFinite(t.after)?t.after:0,notes:tN(t.notes)||void 0,messages:n(t.messages).map(tS)}})}:{}}}function tC({definition:e,layout:t,viewport:n,onViewportChange:s,selection:r=null,errorElements:a,warningElements:i,fitKey:c,onSelect:d,onClearSelection:h,onContextMenu:m,emptyHint:u,theme:p,className:f,style:g,svgId:x}){let y=(0,l.useRef)(null),b=(0,l.useRef)(n);b.current=n;let v=(0,l.useRef)(null),w=(0,l.useRef)(new Map),j=(0,l.useRef)(null),k=(0,l.useMemo)(()=>tE(e),[e]),$=(0,l.useMemo)(()=>t??eL(k),[t,k]),S=(0,l.useRef)(new Map),[E,C]=(0,l.useState)({}),M=e=>t=>{t?S.current.set(e,t):S.current.delete(e)};(0,l.useLayoutEffect)(()=>{let e={},t=!1;for(let[n,s]of S.current){let r="function"==typeof s.getComputedTextLength?s.getComputedTextLength():0;r&&(e[n]=r,Math.abs((E[n]??-1)-r)>.5&&(t=!0))}t&&C(e)},[$,k]);let _=(0,l.useMemo)(()=>new Map(eN(k).map(e=>[e.ref,e.message])),[k]),A=(0,l.useMemo)(()=>new Map(k.participants.filter(e=>e.name).map(e=>[e.name,e])),[k.participants]),O=(0,l.useCallback)((e,t)=>{let n=y.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,l.useEffect)(()=>{if(void 0===c)return;let e=y.current?.getBoundingClientRect();e&&0!==$.participants.length&&s(U([{x:0,y:0,width:$.width,height:$.height}],e.width,e.height,{padding:16}))},[c]),(0,l.useEffect)(()=>{let e=y.current;if(!e)return;let t=e=>{e.preventDefault();let t=b.current,n=tj(e.deltaX,e.deltaMode),r=tj(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void s(Y(t,Math.exp(-(.0025*r)),O(e.clientX,e.clientY)));let a=e.shiftKey?-(n||r):-n,i=e.shiftKey?0:-r;(0!==a||0!==i)&&s(F(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[s,O]);let R=()=>{let e=[...w.current.values()];if(e.length<2)return null;let[t,n]=e;return{distance:Math.hypot(n.x-t.x,n.y-t.y)||1,mid:{x:(t.x+n.x)/2,y:(t.y+n.y)/2}}},P=(e,t)=>{if(0===e.button||"mouse"!==e.pointerType){if(e.stopPropagation(),y.current?.setPointerCapture(e.pointerId),w.current.set(e.pointerId,O(e.clientX,e.clientY)),w.current.size>=2){v.current=null,j.current=R();return}v.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,target:t,moved:!1}}},T=e=>{if(w.current.delete(e.pointerId),j.current){w.current.size<2&&(j.current=null);return}let t=v.current;!t||t.pointerId!==e.pointerId||(v.current=null,t.moved||(t.target?d?.(t.target.kind,t.target.id):h?.()))},I=e=>t=>{m&&(t.preventDefault(),t.stopPropagation(),m(t.clientX,t.clientY,e))},L=new Set(a??[]),D=new Set(i??[]),q=(e,t)=>r?.kind===e&&r.id===t,B=r?.kind==="message"?_.get(r.id):void 0;return(0,o.jsxs)("div",{className:`slc-pane${f?` ${f}`:""}`,style:{...tl(p),...g},children:[(0,o.jsx)("svg",{ref:y,id:x,className:"slc-surface",onPointerDown:e=>P(e),onPointerMove:e=>{if(w.current.has(e.pointerId)&&w.current.set(e.pointerId,O(e.clientX,e.clientY)),j.current){let e=R();if(!e)return;let t=j.current;s(Y(F(b.current,e.mid.x-t.mid.x,e.mid.y-t.mid.y),e.distance/t.distance,e.mid)),j.current=e;return}let t=v.current;!t||t.pointerId!==e.pointerId||!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY)||(t.moved=!0,s(F(b.current,e.clientX-t.lastX,e.clientY-t.lastY)),t.lastX=e.clientX,t.lastY=e.clientY)},onPointerUp:T,onPointerCancel:T,onContextMenu:I({kind:"canvas"}),children:(0,o.jsxs)("g",{transform:X(n),children:[$.fragments.map(e=>{let t=k.fragments?.[e.index];if(!t)return null;let n=N(`${t.kind} \xb7 after ${t.after} \xb7 ${t.label}`,11)+18,s=e.top;return(0,o.jsxs)("g",{className:"slc-sqd-fragment",children:[t.notes?.trim()&&(0,o.jsx)("title",{children:`Notes: ${t.notes}`}),(0,o.jsx)("rect",{x:e.left,y:s,width:e.width,height:e.height,rx:3,className:"slc-sqd-frame"}),(0,o.jsx)("path",{d:`M ${e.left} ${s+22} L ${e.left} ${s} L ${e.left+n} ${s} L ${e.left+n} ${s+15} L ${e.left+n-7} ${s+22} Z`,className:"slc-sqd-frame-tab"}),(0,o.jsxs)("text",{x:e.left+8,y:s+15,className:"slc-sqd-frame-heading",children:[(0,o.jsx)("tspan",{className:"slc-sqd-frame-kind",children:t.kind}),` \xb7 after ${t.after} \xb7 ${t.label}`]}),t.notes?.trim()&&(0,o.jsx)("rect",{x:e.left+n+6,y:s+7,width:13,height:5,rx:1.5,className:"slc-note-mark"})]},`f${e.index}`)}),$.participants.map(e=>{let t=q("participant",e.name);return(0,o.jsxs)("g",{onPointerDown:t=>P(t,{kind:"participant",id:e.name}),children:[(0,o.jsx)("path",{d:`M ${e.x} ${$.lifelineTop} V ${$.lifelineBottom}`,className:"slc-sqd-hit"}),(0,o.jsx)("path",{d:`M ${e.x} ${$.lifelineTop} V ${$.lifelineBottom}`,className:`slc-sqd-lifeline${t?" slc-sqd-lifeline--selected":""}`})]},`l-${e.name}`)}),$.fragments.map(e=>{let t=k.fragments?.[e.index],n=t&&t.after>0?$.rows.find(e=>null===e.fragment&&e.index===t.after-1):void 0;if(!n)return null;let s=e.left+4;return(0,o.jsx)("path",{d:`M ${Math.min(n.fromX,n.toX)-14} ${n.y} H ${s} V ${e.top}`,className:"slc-sqd-branch"},`fa${e.index}`)}),$.rows.map(e=>{var t;let n,s,r,a,i=_.get(e.ref);if(!i)return null;let l=`message:${e.ref}`,c=q("message",e.ref),d=L.has(l),h=!d&&D.has(l),m=["slc-sqd-line",i.reply?"slc-sqd-line--reply":"",i.optional?"slc-sqd-line--optional":"",d?"slc-sqd-line--error":h?"slc-sqd-line--warn":"",c?"slc-sqd-line--selected":""].filter(Boolean).join(" "),u=`slc-sqd-head${i.reply?" slc-sqd-head--open":""}${c?" slc-sqd-head--selected":d?" slc-sqd-head--error":""}`,p=e.ref,f=N(p,10)+8,g=E[`${e.ref}:label`]??N(i.label??"",11),x=i.optional?N("opt",10)+8:0,y=i.event?(E[`${e.ref}:event`]??6.1*i.event.length)+12:0,b=i.state?`→ ${i.state}`:"",v=i.state?E[`${e.ref}:state`]??N(b,11):0,w=f+5+g+(x?5+x:0)+(y?5+y:0)+(v?5+v:0);if(e.self){let t=e.fromX,l=e.y-7-2,c=l+14;r=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:`M ${t} ${l} H ${t+30} V ${c} H ${t+2}`,className:m}),(0,o.jsx)("path",{d:tk(t+1,c,-1,!!i.reply),className:u})]}),n=t+30+8,s=e.y+2,a={x:t-6,y:l-8,w:44+w,h:30}}else{let t=e.toX>=e.fromX?1:-1,l=e.toX-t;r=(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:`M ${e.fromX} ${e.y} H ${l}`,className:m}),(0,o.jsx)("path",{d:tk(l,e.y,t,!!i.reply),className:u})]}),n=(e.fromX+e.toX)/2-w/2,s=e.y-6;let c=Math.min(e.fromX,e.toX,n),d=Math.max(e.fromX,e.toX,n+w);a={x:c-4,y:e.y-22,w:d-c+8,h:30}}let j=n,k=e=>{let t=j;return j+=e+5,t},$=k(f),S=k(g),C=x?k(x):0,A=y?k(y):0,O=v?k(v):0;return(0,o.jsxs)("g",{className:"slc-sqd-message",onPointerDown:t=>P(t,{kind:"message",id:e.ref}),onContextMenu:I({kind:"message",id:e.ref}),children:[(0,o.jsx)("title",{children:(t=e.ref,[`${t}. ${i.from} → ${i.to}: ${i.label}`,i.event?`fires ${i.event}${i.machine?` on ${i.machine}`:""}`:"",i.carries?`carries ${i.carries}`:"",i.state?`then ${i.state}`:"",i.optional?"optional":"",i.reply?"reply":"",i.description??"",i.notes?.trim()?`Notes: ${i.notes}`:""].filter(Boolean).join("\n"))}),(0,o.jsx)("rect",{x:a.x,y:a.y,width:a.w,height:a.h,className:"slc-sqd-hitbox"}),c&&(0,o.jsx)("rect",{x:a.x,y:a.y,width:a.w,height:a.h,rx:4,className:"slc-sqd-selected-plate"}),r,(0,o.jsx)("rect",{x:$,y:s-10,width:f-2,height:13,rx:6.5,className:`slc-sqd-ref-plate${c?" slc-sqd-ref-plate--selected":""}`}),(0,o.jsx)("text",{x:$+(f-2)/2,y:s,textAnchor:"middle",className:"slc-sqd-ref",children:p}),(0,o.jsx)("text",{ref:M(`${e.ref}:label`),x:S,y:s,className:`slc-sqd-label${c?" slc-sqd-label--selected":""}${d?" slc-sqd-label--error":""}`,children:i.label}),x>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:C,y:s-10,width:x,height:13,rx:3,className:"slc-sqd-opt"}),(0,o.jsx)("text",{x:C+x/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-opt-text",children:"opt"})]}),y>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:A,y:s-10.5,width:y,height:14,rx:7,className:"slc-sqd-event"}),(0,o.jsx)("text",{ref:M(`${e.ref}:event`),x:A+y/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-event-text",children:i.event})]}),v>0&&(0,o.jsx)("text",{ref:M(`${e.ref}:state`),x:O,y:s,className:"slc-sqd-state",children:b}),i.notes?.trim()&&(0,o.jsx)("rect",{x:j-5+3,y:s-9,width:5,height:11,rx:1.5,className:"slc-note-mark"})]},`m-${e.ref}`)}),$.participants.map(e=>{let t=A.get(e.name);if(!t)return null;let n=`participant:${e.name}`,s=q("participant",e.name)||!!B&&(B.from===e.name||B.to===e.name),r=["slc-node","slc-sqd-header",q("participant",e.name)?"slc-node--selected":s?"slc-sqd-header--involved":"",L.has(n)?"slc-node--error":""].filter(Boolean).join(" "),a=t.actor?"actor":t.object?"object":t.service?"service":"";return(0,o.jsxs)("g",{className:"slc-node--static slc-sqd-participant",onPointerDown:t=>P(t,{kind:"participant",id:e.name}),onContextMenu:I({kind:"participant",id:e.name}),children:[t$(t)&&(0,o.jsx)("title",{children:t$(t)}),(0,o.jsx)("rect",{x:e.left,y:e.top,width:e.width,height:e.height,rx:t.actor?e.height/2:4,className:r}),t.notes?.trim()&&(0,o.jsx)("rect",{x:e.left+e.width-24,y:e.top-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,o.jsx)("text",{x:e.x,y:e.top+e.height/2+(a?1:4),textAnchor:"middle",className:`slc-node-name slc-sqd-name${t.object?" slc-sqd-name--object":""}`,children:e.name}),a&&(0,o.jsxs)("text",{x:e.x,y:e.top+e.height-4,textAnchor:"middle",className:"slc-sqd-kind",children:["object"===a?`:${t.object}`:"service"===a?"service":"actor",t.holds?.length?` \xb7 holds ${t.holds.length}`:""]})]},`p-${e.name}`)})]})}),0===$.participants.length&&u&&(0,o.jsx)("div",{className:"slc-erd-empty",children:u})]})}let tM=e=>{let t,n=new Set,s=(e,s)=>{let r="function"==typeof e?e(t):e;if(!Object.is(r,t)){let e=t;t=(null!=s?s:"object"!=typeof r||null===r)?r:Object.assign({},t,r),n.forEach(n=>n(t,e))}},r=()=>t,a={setState:s,getState:r,getInitialState:()=>i,subscribe:e=>(n.add(e),()=>n.delete(e))},i=t=e(s,r,a);return a},t_=e=>{let t=e?tM(e):tM,n=e=>(function(e,t=e=>e){let n=l.default.useSyncExternalStore(e.subscribe,l.default.useCallback(()=>t(e.getState()),[e,t]),l.default.useCallback(()=>t(e.getInitialState()),[e,t]));return l.default.useDebugValue(n),n})(t,e);return Object.assign(n,t),n},tA=Object.create(null);tA.open="0",tA.close="1",tA.ping="2",tA.pong="3",tA.message="4",tA.upgrade="5",tA.noop="6";let tO=Object.create(null);Object.keys(tA).forEach(e=>{tO[tA[e]]=e});let tR={type:"error",data:"parser error"},tP="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tT="function"==typeof ArrayBuffer,tI=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,tL=({type:e,data:t},n,s)=>{if(tP&&t instanceof Blob)if(n)return s(t);else return tD(t,s);if(tT&&(t instanceof ArrayBuffer||tI(t)))if(n)return s(t);else return tD(new Blob([t]),s);return s(tA[e]+(t||""))},tD=(e,t)=>{let n=new FileReader;return n.onload=function(){t("b"+(n.result.split(",")[1]||""))},n.readAsDataURL(e)};function tq(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let tB="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tF="u"<typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<tB.length;e++)tF[tB.charCodeAt(e)]=e;let tY="function"==typeof ArrayBuffer,tz=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tX(e,t)};let n=e.charAt(0);return"b"===n?{type:"message",data:tU(e.substring(1),t)}:tO[n]?e.length>1?{type:tO[n],data:e.substring(1)}:{type:tO[n]}:tR},tU=(e,t)=>tY?tX((e=>{let t=.75*e.length,n=e.length,s,r=0,a,i,o,l;"="===e[e.length-1]&&(t--,"="===e[e.length-2]&&t--);let c=new ArrayBuffer(t),d=new Uint8Array(c);for(s=0;s<n;s+=4)a=tF[e.charCodeAt(s)],i=tF[e.charCodeAt(s+1)],o=tF[e.charCodeAt(s+2)],l=tF[e.charCodeAt(s+3)],d[r++]=a<<2|i>>4,d[r++]=(15&i)<<4|o>>2,d[r++]=(3&o)<<6|63&l;return c})(e),t):{base64:!0,data:e},tX=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer;function tH(e){return e.reduce((e,t)=>e+t.length,0)}function tJ(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),s=0;for(let r=0;r<t;r++)n[r]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function tV(e){if(e){var t=e;for(var n in tV.prototype)t[n]=tV.prototype[n];return t}}tV.prototype.on=tV.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},tV.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},tV.prototype.off=tV.prototype.removeListener=tV.prototype.removeAllListeners=tV.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,s=this._callbacks["$"+e];if(!s)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<s.length;r++)if((n=s[r])===t||n.fn===t){s.splice(r,1);break}return 0===s.length&&delete this._callbacks["$"+e],this},tV.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,r=n.length;s<r;++s)n[s].apply(this,t)}return this},tV.prototype.emitReserved=tV.prototype.emit,tV.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},tV.prototype.hasListeners=function(e){return!!this.listeners(e).length};let tW="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),tK="u">typeof self?self:"u">typeof window?window:Function("return this")();function tZ(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}let tG=tK.setTimeout,tQ=tK.clearTimeout;function t0(e,t){t.useNativeTimers?(e.setTimeoutFn=tG.bind(tK),e.clearTimeoutFn=tQ.bind(tK)):(e.setTimeoutFn=tK.setTimeout.bind(tK),e.clearTimeoutFn=tK.clearTimeout.bind(tK))}function t1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class t2 extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class t5 extends tV{constructor(e){super(),this.writable=!1,t0(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new t2(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return("opening"===this.readyState||"open"===this.readyState)&&(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=tz(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return -1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){let t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class t4 extends t5{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)};((e,t)=>{let n=e.split("\x1e"),s=[];for(let e=0;e<n.length;e++){let r=tz(n[e],t);if(s.push(r),"error"===r.type)break}return s})(e,this.socket.binaryType).forEach(t),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){let e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){var t;let n,s,r;this.writable=!1,t=e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})},s=Array(n=e.length),r=0,e.forEach((e,a)=>{tL(e,!1,e=>{s[a]=e,++r===n&&t(s.join("\x1e"))})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=t1()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let t3=!1;try{t3="u">typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let t6=t3;function t8(){}class t7 extends t4{constructor(e){if(super(e),"u">typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="u">typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){let n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class t9 extends tV{constructor(e,t,n){super(),this.createRequest=e,t0(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;let t=tZ(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders)for(let e in n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0),this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null==(e=this._opts.cookieJar)||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null==(e=this._opts.cookieJar)||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){this.setTimeoutFn(()=>{this._onError(e)},0);return}"u">typeof document&&(this._index=t9.requestsCount++,t9.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=t8,e)try{this._xhr.abort()}catch(e){}"u">typeof document&&delete t9.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function ne(){for(let e in t9.requests)t9.requests.hasOwnProperty(e)&&t9.requests[e].abort()}t9.requestsCount=0,t9.requests={},"u">typeof document&&("function"==typeof attachEvent?attachEvent("onunload",ne):"function"==typeof addEventListener&&addEventListener("onpagehide"in tK?"pagehide":"unload",ne,!1));let nt=(s=nn({xdomain:!1}))&&null!==s.responseType;function nn(e){let t=e.xdomain;try{if("u">typeof XMLHttpRequest&&(!t||t6))return new XMLHttpRequest}catch(e){}if(!t)try{return new tK[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let ns="u">typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class nr extends t5{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=ns?{}:tZ(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;tL(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&tW(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=t1()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let na=tK.WebSocket||tK.MozWebSocket,ni={websocket:class extends nr{createSocket(e,t,n){return ns?new na(e,t,n):t?new na(e,t):new na(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends t5{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{var s,r;let a,i,o,l,c=(s=Number.MAX_SAFE_INTEGER,r=this.socket.binaryType,n||(n=new TextDecoder),a=[],i=0,o=-1,l=!1,new TransformStream({transform(e,t){for(a.push(e);;){if(0===i){if(1>tH(a))break;let e=tJ(a,1);l=(128&e[0])==128,i=(o=127&e[0])<126?3:126===o?1:2}else if(1===i){if(2>tH(a))break;let e=tJ(a,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(8>tH(a))break;let e=tJ(a,8),n=new DataView(e.buffer,e.byteOffset,e.length),s=n.getUint32(0);if(s>2097151){t.enqueue(tR);break}o=0x100000000*s+n.getUint32(4),i=3}else{if(tH(a)<o)break;let e=tJ(a,o);t.enqueue(tz(l?e:n.decode(e),r)),i=0}if(0===o||o>s){t.enqueue(tR);break}}}})),d=e.readable.pipeThrough(c).getReader(),h=new TransformStream({transform(e,n){var s;s=t=>{let s,r=t.length;if(r<126)new DataView((s=new Uint8Array(1)).buffer).setUint8(0,r);else if(r<65536){let e=new DataView((s=new Uint8Array(3)).buffer);e.setUint8(0,126),e.setUint16(1,r)}else{let e=new DataView((s=new Uint8Array(9)).buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(s[0]|=128),n.enqueue(s),n.enqueue(t)},tP&&e.data instanceof Blob?e.data.arrayBuffer().then(tq).then(s):tT&&(e.data instanceof ArrayBuffer||tI(e.data))?s(tq(e.data)):tL(e,!1,e=>{t||(t=new TextEncoder),s(t.encode(e))})}});h.readable.pipeTo(e.writable),this._writer=h.writable.getWriter();let m=()=>{d.read().then(({done:e,value:t})=>{e||(this.onPacket(t),m())}).catch(e=>{})};m();let u={type:"open"};this.query.sid&&(u.data=`{"sid":"${this.query.sid}"}`),this._writer.write(u).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&tW(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}},polling:class extends t7{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=nt&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new t9(nn,this.uri(),e)}}},no=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function nc(e){var t,n;let s,r;if(e.length>8e3)throw"URI too long";let a=e,i=e.indexOf("["),o=e.indexOf("]");-1!=i&&-1!=o&&(e=e.substring(0,i)+e.substring(i,o).replace(/:/g,";")+e.substring(o,e.length));let l=no.exec(e||""),c={},d=14;for(;d--;)c[nl[d]]=l[d]||"";return -1!=i&&-1!=o&&(c.source=a,c.host=c.host.substring(1,c.host.length-1).replace(/;/g,":"),c.authority=c.authority.replace("[","").replace("]","").replace(/;/g,":"),c.ipv6uri=!0),s=(t=c.path).replace(/\/{2,9}/g,"/").split("/"),("/"==t.slice(0,1)||0===t.length)&&s.splice(0,1),"/"==t.slice(-1)&&s.splice(s.length-1,1),c.pathNames=s,n=c.query,r={},n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(r[t]=n)}),c.queryKey=r,c}let nd="function"==typeof addEventListener&&"function"==typeof removeEventListener,nh=[];nd&&addEventListener("offline",()=>{nh.forEach(e=>e())},!1);class nm extends tV{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=nc(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=nc(t.host).host);t0(this,t),this.secure=null!=t.secure?t.secure:"u">typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("u">typeof location?location.hostname:"localhost"),this.port=t.port||("u">typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{let t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,s=n.length;e<s;e++){let s=n[e].split("=");t[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return t}(this.opts.query)),nd&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},nh.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){let t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);let n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);let e=this.opts.rememberUpgrade&&nm.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",nm.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){let n=this.writeBuffer[t].data;if(n&&(e+="string"==typeof n?function(e){let t=0,n=0;for(let s=0,r=e.length;s<r;s++)(t=e.charCodeAt(s))<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}(n):Math.ceil(1.33*(n.byteLength||n.size))),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,tW(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if("function"==typeof t&&(s=t,t=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;let r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return("opening"===this.readyState||"open"===this.readyState)&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(nm.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),nd&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=nh.indexOf(this._offlineEventListener);-1!==e&&nh.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}nm.protocol=4;class nu extends nm{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;nm.priorWebsocketSuccess=!1;let s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;nm.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let e=Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){n||(n=!0,c(),t.close(),t=null)}let a=e=>{let n=Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function i(){a("transport closed")}function o(){a("socket closed")}function l(e){t&&e.name!==t.name&&r()}let c=()=>{t.removeListener("open",s),t.removeListener("error",a),t.removeListener("close",i),this.off("close",o),this.off("upgrading",l)};t.once("open",s),t.once("error",a),t.once("close",i),this.once("close",o),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}class np extends nu{constructor(e,t={}){const n="object"==typeof e,s=n?{...e}:{...t};(!s.transports||s.transports&&"string"==typeof s.transports[0])&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(e=>ni[e]).filter(e=>!!e)),super(n?s:e,s)}}np.protocol;let nf="function"==typeof ArrayBuffer,ng=Object.prototype.toString,nx="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===ng.call(Blob),ny="function"==typeof File||"u">typeof File&&"[object FileConstructor]"===ng.call(File);function nb(e){return nf&&(e instanceof ArrayBuffer||("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer))||nx&&e instanceof Blob||ny&&e instanceof File}let nv=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];(a=i||(i={}))[a.CONNECT=0]="CONNECT",a[a.DISCONNECT=1]="DISCONNECT",a[a.EVENT=2]="EVENT",a[a.ACK=3]="ACK",a[a.CONNECT_ERROR=4]="CONNECT_ERROR",a[a.BINARY_EVENT=5]="BINARY_EVENT",a[a.BINARY_ACK=6]="BINARY_ACK";class nw{constructor(e){this.replacer=e}encode(e){return(e.type===i.EVENT||e.type===i.ACK)&&function e(t,n){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let n=0,s=t.length;n<s;n++)if(e(t[n]))return!0;return!1}if(nb(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1==arguments.length)return e(t.toJSON(),!0);for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return!0;return!1}(e)?this.encodeAsBinary({type:e.type===i.EVENT?i.BINARY_EVENT:i.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===i.BINARY_EVENT||e.type===i.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t,n,s=(t=[],n=e.data,e.data=function e(t,n,s){if(!t)return t;if(nb(t)){let e={_placeholder:!0,num:n.length};return n.push(t),e}if(Array.isArray(t)){let s=Array(t.length);for(let r=0;r<t.length;r++)s[r]=e(t[r],n);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return e(t.toJSON(),n,!0);let r={};for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=e(t[s],n));return r}return t}(n,t),e.attachments=t.length,{packet:e,buffers:t}),r=this.encodeAsString(s.packet),a=s.buffers;return a.unshift(r),a}}class nj extends tV{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw Error("got plaintext data when reconstructing a packet");let n=(t=this.decodeString(e)).type===i.BINARY_EVENT;n||t.type===i.BINARY_ACK?(t.type=n?i.EVENT:i.ACK,this.reconstructor=new nk(t)):super.emitReserved("decoded",t)}else if(nb(e)||e.base64)if(this.reconstructor)(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw Error("got binary data when not reconstructing a packet");else throw Error("Unknown type: "+e)}decodeString(e){let t=0,n={type:Number(e.charAt(0))};if(void 0===i[n.type])throw Error("unknown packet type "+n.type);if(n.type===i.BINARY_EVENT||n.type===i.BINARY_ACK){let s=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);let r=e.substring(s,t);if(r!=Number(r)||"-"!==e.charAt(t))throw Error("Illegal attachments");let a=Number(r);if(!n$(a)||a<1)throw Error("Illegal attachments");if(a>this.opts.maxAttachments)throw Error("too many attachments");n.attachments=a}if("/"===e.charAt(t+1)){let s=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(s,t)}else n.nsp="/";let s=e.charAt(t+1);if(""!==s&&Number(s)==s){let s=t+1;for(;++t;){let n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(s,t+1))}if(e.charAt(++t)){let s=this.tryParse(e.substr(t));if(nj.isPayloadValid(n.type,s))n.data=s;else throw Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case i.CONNECT:return nN(t);case i.DISCONNECT:return void 0===t;case i.CONNECT_ERROR:return"string"==typeof t||nN(t);case i.EVENT:case i.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===nv.indexOf(t[0]));case i.ACK:case i.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class nk{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t,n;let e=(t=this.reconPack,n=this.buffers,t.data=function e(t,n){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<n.length)return n[t.num];throw Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=e(t[s],n);else if("object"==typeof t)for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=e(t[s],n));return t}(t.data,n),delete t.attachments,t);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}let n$=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function nN(e){return"[object Object]"===Object.prototype.toString.call(e)}function nS(e){var t;return"string"==typeof e.nsp&&(void 0===(t=e.id)||n$(t))&&function(e,t){switch(e){case i.CONNECT:return void 0===t||nN(t);case i.DISCONNECT:return void 0===t;case i.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===nv.indexOf(t[0]));case i.ACK:return Array.isArray(t);case i.CONNECT_ERROR:return"string"==typeof t||nN(t);default:return!1}}(e.type,e.data)}function nE(e,t,n){return e.on(t,n),function(){e.off(t,n)}}e.s(["Decoder",()=>nj,"Encoder",()=>nw,"PacketType",()=>i,"isPacketValid",()=>nS,"protocol",0,5],11014);let nC=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class nM extends tV{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[nE(e,"open",this.onopen.bind(this)),nE(e,"packet",this.onpacket.bind(this)),nE(e,"error",this.onerror.bind(this)),nE(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,r;if(nC.hasOwnProperty(e))throw Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let a={type:i.EVENT,data:t};if(a.options={},a.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){let e=this.ids++,n=t.pop();this._registerAckCallback(e,n),a.id=e}let o=null==(s=null==(n=this.io.engine)?void 0:n.transport)?void 0:s.writable,l=this.connected&&!(null==(r=this.io.engine)?void 0:r._hasPingExpired());return this.flags.volatile&&!o||(l?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),this.flags={},this}_registerAckCallback(e,t){var n;let s=null!=(n=this.flags.timeout)?n:this._opts.ackTimeout;if(void 0===s){this.acks[e]=t;return}let r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,Error("operation has timed out"))},s),a=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};a.withError=!0,this.acks[e]=a}emitWithAck(e,...t){return new Promise((n,s)=>{let r=(e,t)=>e?s(e):n(t);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());let n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...s)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;let t=this._queue[0];(!t.pending||e)&&(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:i.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case i.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case i.EVENT:case i.BINARY_EVENT:this.onevent(e);break;case i.ACK:case i.BINARY_ACK:this.onack(e);break;case i.DISCONNECT:this.ondisconnect();break;case i.CONNECT_ERROR:this.destroy();let t=Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){let t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length)for(let t of this._anyListeners.slice())t.apply(this,e);super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,n=!1;return function(...s){n||(n=!0,t.packet({type:i.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:i.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n]){t.splice(n,1);break}}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n]){t.splice(n,1);break}}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length)for(let t of this._anyOutgoingListeners.slice())t.apply(this,e.data)}}var n_=e.i(11014);function nA(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}nA.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(1&Math.floor(10*t))==0?e-n:e+n}return 0|Math.min(e,this.max)},nA.prototype.reset=function(){this.attempts=0},nA.prototype.setMin=function(e){this.ms=e},nA.prototype.setMax=function(e){this.max=e},nA.prototype.setJitter=function(e){this.jitter=e};class nO extends tV{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,t0(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!=(n=t.randomizationFactor)?n:.5),this.backoff=new nA({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||n_;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null==(t=this.backoff)||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null==(t=this.backoff)||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null==(t=this.backoff)||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new np(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=nE(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},a=nE(t,"error",r);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{s(),r(Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(a),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(nE(e,"ping",this.onping.bind(this)),nE(e,"data",this.ondata.bind(this)),nE(e,"error",this.onerror.bind(this)),nE(e,"close",this.onclose.bind(this)),nE(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){tW(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new nM(this,e,t),this.nsps[e]=n),n}_destroy(e){for(let e of Object.keys(this.nsps))if(this.nsps[e].active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null==(n=this.engine)||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}let nR={};function nP(e,t){let n;"object"==typeof e&&(t=e,e=void 0);let s=function(e,t="",n){let s=e;n=n||"u">typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),s=nc(e)),!s.port&&(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";let r=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+r+":"+s.port+t,s.href=s.protocol+"://"+r+(n&&n.port===s.port?"":":"+s.port),s}(e,(t=t||{}).path||"/socket.io"),r=s.source,a=s.id,i=s.path,o=nR[a]&&i in nR[a].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?n=new nO(r,t):(nR[a]||(nR[a]=new nO(r,t)),n=nR[a]),s.query&&!t.query&&(t.query=s.queryKey),n.socket(s.path,t)}function nT(e){if(e&&"object"==typeof e&&"clientId"in e){let t=e.clientId;if("string"==typeof t)return t}}function nI(e){let{url:t,role:n,docId:s,name:r,token:a}=e,i=!1!==e.autoResync,o=nP(t,{auth:{token:a},autoConnect:!1}),l="disconnected",c=0,d="",h=[],m={patch:new Set,full:new Set,ack:new Set,presence:new Set,error:new Set,status:new Set,view:new Set};function u(e,t){for(let n of[...m[e]])n(t)}function p(e){l!==e&&(l=e,u("status",e))}function f(e){o.emit("def:request",{docId:s,sinceSeq:e})}function g(e){"number"==typeof e&&(i&&e>c+1&&f(c),c=Math.max(c,e))}function x(){u("presence",[...h])}function y(){return o.connected?Promise.resolve():new Promise((e,t)=>{p("connecting");let n=()=>{r(),e()},s=e=>{r(),t(e)},r=()=>{o.off("connect",n),o.off("connect_error",s)};o.once("connect",n),o.once("connect_error",s),o.connect()})}async function b(){return await y(),new Promise((e,t)=>{o.emit("bridge:join",{docId:s,role:n,name:r},n=>{if(!n||n.error){let e=n?.error??{code:"join_failed",message:"no join ack"};u("error",e),t(Error(`${e.code}: ${e.message}`));return}d=n.selfId,h=n.presence?[...n.presence]:[],c=n.snapshot?.seq??0,x(),e({selfId:d,snapshot:n.snapshot,presence:[...h]})})})}async function v(e){await y(),o.emit("view:show",{...e,docId:e.docId??s,origin:e.origin??(r||n)})}return o.on("connect",()=>p("connected")),o.on("disconnect",()=>p("disconnected")),o.on("connect_error",e=>{p("error"),u("error",{code:"connect_error",message:e?.message??String(e)})}),o.on("def:patch",e=>{g(e?.seq),e?.origin&&e.origin===d||u("patch",e)}),o.on("def:full",e=>{g(e?.seq),e?.origin&&e.origin===d||u("full",e)}),o.on("def:ack",e=>{u("ack",e)}),o.on("view:show",e=>{u("view",e)}),o.on("bridge:error",e=>{u("error",{code:e?.code??"error",message:e?.message??""})}),o.on("presence:list",e=>{h=Array.isArray(e)?[...e]:[],x()}),o.on("presence:join",e=>{let t=nT(e);t&&(h=[...h.filter(e=>e.clientId!==t),e],x())}),o.on("presence:leave",e=>{let t=nT(e);t&&(h=h.filter(e=>e.clientId!==t),x())}),o.on("presence:update",e=>{let t=nT(e);if(!t)return;let n=h.findIndex(e=>e.clientId===t);if(-1===n)h=[...h,e];else{let t={...h[n],...e};h=h.map((e,s)=>s===n?t:e)}x()}),{connect:y,join:b,emitPatch:function(e,t,n){o.emit("def:patch",{docId:s,ops:e,origin:d,baseSeq:n,mtime:t})},emitFull:function(e,t){o.emit("def:full",{docId:s,def:e,origin:d,mtime:t})},request:f,updatePresence:function(e){o.emit("presence:update",{docId:s,clientId:d,cursor:e.cursor,selection:e.selection})},emitView:v,on:function(e,t){let n=m[e];return n.add(t),()=>n.delete(t)},disconnect:function(){o.connected&&d&&o.emit("bridge:leave",{docId:s,clientId:d}),o.disconnect(),p("disconnected")},get status(){return l},get lastSeq(){return c},get presence(){return[...h]}}}function nL(e){return"runtime.enter"===e.op||"runtime.exit"===e.op}function nD(e){let{onFull:t,onPatch:n,onPresence:s,...r}=e,a=nI(r),i=null,o=0,l=[],c=[],d={status:a.status,def:null,seq:0,presence:[],activeStates:[]},h=new Set;function m(){for(let e of(d={status:a.status,def:i,seq:o,presence:l,activeStates:c},[...h]))e()}return a.on("status",()=>m()),a.on("full",e=>{i=e.def,"number"==typeof e.seq&&(o=e.seq),t?.(e),m()}),a.on("patch",e=>{"number"==typeof e.seq&&(o=e.seq);let t=e.ops??[],s=t.filter(nL),r=t.filter(e=>!nL(e));r.length>0&&i&&(i=u(i,r));for(let e of s)"runtime.enter"===e.op?c.includes(e.state)||(c=[...c,e.state]):"runtime.exit"===e.op&&c.includes(e.state)&&(c=c.filter(t=>t!==e.state));n?.(e),m()}),a.on("presence",e=>{l=e,s?.(e),m()}),{getSnapshot:function(){return d},subscribe:function(e){return h.add(e),()=>{h.delete(e)}},emitPatch:function(e){a.emitPatch(e)},emitFull:function(e){a.emitFull(e)},enter:function(e,t,n){let s={op:"runtime.enter",state:e,...void 0!==t?{from:t}:{},...void 0!==n?{eventId:n}:{}};a.emitPatch([s])},exit:function(e){a.emitPatch([{op:"runtime.exit",state:e}])},connect:function(){a.join().then(e=>{i=e.snapshot.def,o=e.snapshot.seq,l=e.presence,null!==i&&t?.({docId:e.snapshot.docId,def:i,seq:o,mtime:e.snapshot.mtime,origin:"join"}),m()}).catch(()=>{m()})},disconnect:function(){a.disconnect()}}}function nq(){return{settings:{namespace:"MyApp",name:"MyStateMachine",asynchronous:!1},events:[{name:"Internal",events:[]}],state:{name:"Root",states:[{name:"Idle",kind:"normal"},{name:"End",kind:"final"}]}}}function nB(){return{positions:{}}}function nF(e,t){if(e.name===t)return e;for(let n of e.states??[]){let e=nF(n,t);if(e)return e}return null}function nY(e,t,n){return e.name===t?n(e)??e:{...e,states:e.states?.map(e=>nY(e,t,n))}}function nz(e,t){return{...e,states:e.states?.filter(e=>e.name!==t).map(e=>nz(e,t))}}function nU(e){let t=[e.name];for(let n of e.states??[])t.push(...nU(n));return t}function nX(e){return e.events.flatMap(e=>(e.events??[]).map(e=>e.id))}function nH(e){let t=[],n=nU(e.state),s=nX(e);0===s.length&&t.push({ruleId:"V001",message:"No events defined"});let r=new Set;for(let e of n)r.has(e)&&t.push({ruleId:"V002",message:`Duplicate state name: ${e}`,element:e}),r.add(e);!function e(r){for(let e of r.transitions??[])s.includes(e.event)||t.push({ruleId:"V003",message:`Transition in '${r.name}' references unknown event '${e.event}'`,element:r.name}),e.nextState&&!n.includes(e.nextState)&&t.push({ruleId:"V004",message:`Transition in '${r.name}' targets unknown state '${e.nextState}'`,element:r.name});for(let n of("final"===r.kind&&(r.transitions?.length??0)>0&&t.push({ruleId:"V007",message:`Final state '${r.name}' must not have outgoing transitions`,element:r.name}),"final"===r.kind&&(r.states?.length??0)>0&&t.push({ruleId:"V008",message:`Final state '${r.name}' must not have child states`,element:r.name}),r.states??[]))e(n)}(e.state),e.state.states&&0!==e.state.states.length||t.push({ruleId:"V005",message:"Root state must have at least one child state",element:e.state.name});let a=new Set;for(let e of s)a.has(e)&&t.push({ruleId:"V003",message:`Duplicate event ID: ${e}`,element:e}),a.add(e);return t}function nJ(e,t){return{positions:{...$(e),...t.positions}}}Object.assign(nP,{Manager:nO,Socket:nM,io:nP,connect:nP});let nV=!1,nW=(r=(e,t)=>({definition:nq(),layout:nJ(nq(),nB()),viewport:{...q},fileName:null,docPath:null,dirty:!1,remoteMtime:null,remoteStatus:"idle",remoteMessage:null,activeStates:[],presence:[],_applyingRemote:!1,selection:{kind:null,id:null},drawMode:"select",drawSource:null,contextMenu:{visible:!1,x:0,y:0,target:null},undoStack:[],redoStack:[],activeTab:"properties",errors:[],showCodePreview:!1,generatedCode:null,navigationPath:["Root"],currentParent:"Root",_pushHistory:()=>{let{definition:n,layout:s,undoStack:r}=t(),a={definition:JSON.parse(JSON.stringify(n)),layout:JSON.parse(JSON.stringify(s))};e({undoStack:[...r.slice(-50),a],redoStack:[]})},setDefinition:n=>{t()._pushHistory();let s=nJ(n,t().layout);e({definition:n,layout:s,dirty:!0,errors:nH(n)})},updateSettings:n=>{t()._pushHistory(),e({definition:{...t().definition,settings:{...t().definition.settings,...n}},dirty:!0})},addState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=n??r.state.name;r.state=nY(r.state,a,e=>({...e,states:[...e.states??[],s]}));let i=nJ(r,t().layout);e({definition:r,layout:i,dirty:!0,errors:nH(r)})},updateState:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,...s})),e({definition:r,dirty:!0,errors:nH(r)})},removeState:n=>{t()._pushHistory();let s={...t().definition};s.state=nz(s.state,n);let r={positions:{...t().layout.positions}};delete r.positions[n],e({definition:s,layout:r,dirty:!0,errors:nH(s)})},nestState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=nF(r.state,n);if(!a||n===s)return;let i=JSON.parse(JSON.stringify(a));r.state=nz(r.state,n),r.state=nY(r.state,s,e=>({...e,states:[...e.states??[],i]})),e({definition:r,dirty:!0,errors:nH(r)})},addEventSource:n=>{t()._pushHistory(),e({definition:{...t().definition,events:[...t().definition.events,n]},dirty:!0})},updateEventSource:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map((e,t)=>t===n?{...e,...s}:e),e({definition:r,dirty:!0})},removeEventSource:n=>{t()._pushHistory();let s={...t().definition};s.events=s.events.filter((e,t)=>t!==n),e({definition:s,dirty:!0,errors:nH(s)})},addEvent:(n,s=0)=>{t()._pushHistory();let r={...t().definition},a=r.events[s]??{name:"Internal",events:[]};a.events=[...a.events??[],n],r.events=r.events.map((e,t)=>t===s?a:e),e({definition:r,dirty:!0,errors:nH(r)})},updateEvent:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,...s}:e)})),e({definition:r,dirty:!0})},removeEvent:n=>{t()._pushHistory();let s={...t().definition};s.events=s.events.map(e=>({...e,events:e.events?.filter(e=>e.id!==n)})),e({definition:s,dirty:!0,errors:nH(s)})},addParameter:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:[...e.parameters??[],s]}:e)})),e({definition:r,dirty:!0})},removeParameter:(n,s)=>{t()._pushHistory();let r={...t().definition};r.events=r.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:e.parameters?.filter((e,t)=>t!==s)}:e)})),e({definition:r,dirty:!0})},updateParameter:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.events=a.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,parameters:e.parameters?.map((e,t)=>t===s?{...e,...r}:e)}:e)})),e({definition:a,dirty:!0})},addAction:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>{let t=e[s]??{actions:[]};return{...e,[s]:{actions:[...t.actions,r]}}}),e({definition:a,dirty:!0})},removeAction:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.filter((e,t)=>t!==r)}}:e}),e({definition:a,dirty:!0})},updateAction:(n,s,r,a)=>{t()._pushHistory();let i={...t().definition};i.state=nY(i.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.map((e,t)=>t===r?a:e)}}:e}),e({definition:i,dirty:!0})},addTransition:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,transitions:[...e.transitions??[],s]})),e({definition:r,dirty:!0,errors:nH(r)})},updateTransition:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nY(a.state,n,e=>({...e,transitions:e.transitions?.map((e,t)=>t===s?{...e,...r}:e)})),e({definition:a,dirty:!0})},removeTransition:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nY(r.state,n,e=>({...e,transitions:e.transitions?.filter((e,t)=>t!==s)})),e({definition:r,dirty:!0,errors:nH(r)})},setStatePosition:(n,s)=>{e({layout:{positions:{...t().layout.positions,[n]:s}}})},arrangeLayout:()=>{t()._pushHistory(),e({layout:{positions:$(t().definition)}})},hydrateLayout:(n,s)=>{e({layout:{positions:{...t().layout.positions,...n}},...s?{viewport:s}:{}})},setViewport:t=>e({viewport:t}),select:(t,n)=>e({selection:{kind:t,id:n}}),clearSelection:()=>e({selection:{kind:null,id:null}}),setDrawMode:t=>e({drawMode:t,drawSource:null}),setDrawSource:t=>e({drawSource:t}),showContextMenu:(t,n,s)=>e({contextMenu:{visible:!0,x:t,y:n,target:s}}),hideContextMenu:()=>e({contextMenu:{visible:!1,x:0,y:0,target:null}}),undo:()=>{let{undoStack:n,definition:s,layout:r}=t();if(0===n.length)return;let a=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(r))};e({definition:a.definition,layout:a.layout,undoStack:n.slice(0,-1),redoStack:[...t().redoStack,i],dirty:!0,errors:nH(a.definition)})},redo:()=>{let{redoStack:n,definition:s,layout:r}=t();if(0===n.length)return;let a=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(r))};e({definition:a.definition,layout:a.layout,undoStack:[...t().undoStack,i],redoStack:n.slice(0,-1),dirty:!0,errors:nH(a.definition)})},canUndo:()=>t().undoStack.length>0,canRedo:()=>t().redoStack.length>0,setActiveTab:t=>e({activeTab:t}),loadFromJson:(t,n)=>{try{let s=JSON.parse(t),r=eg(s.stateMachine??s.StateMachine??s);nV=!!s&&"object"==typeof s&&"state"in s&&!("stateMachine"in s)&&!("StateMachine"in s);let a=nJ(r,nB()),i=r.state?.name??"Root";e({definition:r,layout:a,fileName:n??null,dirty:!1,errors:nH(r),selection:{kind:null,id:null},undoStack:[],redoStack:[],navigationPath:[i],currentParent:i})}catch(e){console.error("Failed to parse definition:",e)}},exportJson:()=>{let{definition:e}=t();return JSON.stringify(nV?e:{stateMachine:e},null,2)},applyRemote:(n,s,r)=>{try{let a=JSON.parse(n),i=eg(a.stateMachine??a.StateMachine??a);nV=!!a&&"object"==typeof a&&"state"in a&&!("stateMachine"in a)&&!("StateMachine"in a);let o=nJ(i,t().layout),l=i.state?.name??"Root",c=t(),d=new Set(nU(i.state)),h=c.navigationPath.filter(e=>d.has(e)),m=h.length?h:[l],u=m[m.length-1],p=c.selection,f=("state"===p.kind?!!p.id&&d.has(p.id):"transition"===p.kind?!!p.id&&d.has(p.id.split(":")[0]):"event"===p.kind&&!!p.id&&nX(i).includes(p.id))?p:{kind:null,id:null};e({definition:i,layout:o,fileName:r??t().fileName,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:nH(i),selection:f,navigationPath:m,currentParent:u})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}},setRemoteStatus:(t,n=null)=>e({remoteStatus:t,remoteMessage:n}),setRemoteMtime:t=>e({remoteMtime:t}),setDocPath:t=>e({docPath:t||null}),enterState:n=>{let s=t().activeStates;s.includes(n)||e({activeStates:[...s,n]})},exitState:n=>{let s=t().activeStates;s.includes(n)&&e({activeStates:s.filter(e=>e!==n)})},setPresence:t=>e({presence:t}),applyRemoteOps:(n,s,r)=>{e({_applyingRemote:!0});try{let r=t(),a=n.filter(e=>"runtime.enter"!==e.op&&"runtime.exit"!==e.op),i=a.length?u(r.definition,a):r.definition,o=r.activeStates;for(let e of n)"runtime.enter"===e.op?o.includes(e.state)||(o=[...o,e.state]):"runtime.exit"===e.op&&o.includes(e.state)&&(o=o.filter(t=>t!==e.state));let l=nJ(i,r.layout),c=i.state?.name??"Root",d=new Set(nU(i.state)),h=r.navigationPath.filter(e=>d.has(e)),m=h.length?h:[c],p=m[m.length-1],f=r.selection,g=("state"===f.kind?!!f.id&&d.has(f.id):"transition"===f.kind?!!f.id&&d.has(f.id.split(":")[0]):"event"===f.kind&&!!f.id&&nX(i).includes(f.id))?f:{kind:null,id:null};e({definition:i,layout:l,activeStates:o,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:nH(i),selection:g,navigationPath:m,currentParent:p})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}finally{e({_applyingRemote:!1})}},validate:()=>{let n=nH(t().definition);return e({errors:n}),n},setGeneratedCode:t=>e({generatedCode:t}),setShowCodePreview:t=>e({showCodePreview:t}),navigateInto:n=>{let{definition:s,navigationPath:r}=t(),a=nF(s.state,n);a&&(a.states?.length??0)>0&&e({navigationPath:[...r,n],currentParent:n,selection:{kind:null,id:null}})},navigateUp:n=>{let{navigationPath:s}=t();if(s.length<=1)return;let r=n??s.length-2,a=s.slice(0,r+1);e({navigationPath:a,currentParent:a[a.length-1],selection:{kind:null,id:null}})},getCurrentChildren:()=>{let{definition:e,currentParent:n}=t(),s=nF(e.state,n);return s?.states??[]}}))?t_(r):t_,nK="canvas",nZ=`[data-pinch-owner="${nK}"]`;function nG(e){return!!e&&"function"==typeof e.closest&&null!==e.closest(nZ)}let nQ="stateloom-canvas",n0="#030712",n1=["png","jpeg","svg","mermaid","markdown"],n2={png:"PNG",jpeg:"JPEG",svg:"SVG",mermaid:"Mermaid",markdown:"Markdown"},n5={png:"image/png",jpeg:"image/jpeg",svg:"image/svg+xml",mermaid:"text/vnd.mermaid",markdown:"text/markdown"},n4={png:"png",jpeg:"jpg",svg:"svg",mermaid:"mmd",markdown:"md"};async function n3(e,t,n={}){var s,r,a;let i;if("mermaid"===e||"markdown"===e){let n,a;i=new Blob([(s=t.definition,r="markdown"===e,n=["stateDiagram-v2"],s.state&&function e(t,n,s){let r=H(t);if(0===r.length)return;let a=" ".repeat(n+1),i=new Set;for(let e of r)for(let t of e.transitions??[]){if(!t.nextState)continue;let n=t.condition?`${t.event} [${t.condition}]`:t.event;s.push(`${a}${e.name} --> ${t.nextState} : ${n}`),i.add(e.name),i.add(t.nextState)}for(let e of r)i.has(e.name)||s.push(`${a}${e.name}`);for(let t of r)0!==H(t).length&&(s.push(`${a}state ${t.name} {`),e(t,n+1,s),s.push(`${a}}`))}(s.state,0,n),a=n.join("\n"),r?`\`\`\`mermaid
|
|
2
2
|
${a}
|
|
3
3
|
\`\`\`
|
|
4
4
|
`:`${a}
|