@miadi/stateloom-web 0.1.9 → 0.2.1

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.
Files changed (70) hide show
  1. package/package.json +1 -1
  2. package/server/.next/BUILD_ID +1 -1
  3. package/server/.next/build-manifest.json +2 -2
  4. package/server/.next/server/app/_global-error.html +2 -2
  5. package/server/.next/server/app/_global-error.rsc +1 -1
  6. package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  7. package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  9. package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  10. package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  11. package/server/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  12. package/server/.next/server/app/_not-found.html +1 -1
  13. package/server/.next/server/app/_not-found.rsc +2 -2
  14. package/server/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  15. package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  16. package/server/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  17. package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  19. package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  20. package/server/.next/server/app/api/docs/route.js.nft.json +1 -1
  21. package/server/.next/server/app/api/file/route.js.nft.json +1 -1
  22. package/server/.next/server/app/api/rispec/route.js.nft.json +1 -1
  23. package/server/.next/server/app/api/watch/route.js.nft.json +1 -1
  24. package/server/.next/server/app/index.html +1 -1
  25. package/server/.next/server/app/index.rsc +3 -3
  26. package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  27. package/server/.next/server/app/index.segments/_full.segment.rsc +3 -3
  28. package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  29. package/server/.next/server/app/index.segments/_index.segment.rsc +2 -2
  30. package/server/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  31. package/server/.next/server/app/page.js.nft.json +1 -1
  32. package/server/.next/server/app/page_client-reference-manifest.js +1 -1
  33. package/server/.next/server/chunks/[root-of-the-server]__13c3d2a8._.js +1 -1
  34. package/server/.next/server/chunks/[root-of-the-server]__2046b812._.js +2 -2
  35. package/server/.next/server/chunks/[root-of-the-server]__87bf4b91._.js +1 -1
  36. package/server/.next/server/chunks/[root-of-the-server]__95b05635._.js +3 -3
  37. package/server/.next/server/chunks/ssr/{[root-of-the-server]__d5879c0c._.js → [root-of-the-server]__b1b2bf74._.js} +2 -2
  38. package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +4 -3
  39. package/server/.next/server/pages/404.html +1 -1
  40. package/server/.next/server/pages/500.html +2 -2
  41. package/server/.next/static/chunks/9390437c8b41a90e.js +11 -0
  42. package/server/.next/static/chunks/a8a37c487ef91a19.js +1 -0
  43. package/server/.next/static/chunks/c86e96e4d6eeb632.css +2 -0
  44. package/server/package-lock.json +2 -2
  45. package/server/package.json +1 -1
  46. package/server/src/app/api/file/route.ts +57 -12
  47. package/server/src/app/globals.css +15 -0
  48. package/server/src/app/page.tsx +52 -10
  49. package/server/src/components/BoardBoundary.tsx +46 -0
  50. package/server/src/components/PropertiesPanel.tsx +10 -0
  51. package/server/src/components/erd/ErdWorkspace.tsx +32 -3
  52. package/server/src/components/forms.tsx +129 -0
  53. package/server/src/components/sequence/SequenceWorkspace.tsx +1024 -0
  54. package/server/src/components/system/KindIcon.tsx +71 -0
  55. package/server/src/components/system/SystemStrip.tsx +285 -0
  56. package/server/src/components/system/SystemWorkspace.tsx +766 -0
  57. package/server/src/lib/docParam.ts +4 -1
  58. package/server/src/lib/machineFocus.ts +126 -0
  59. package/server/src/lib/projectFile.ts +180 -20
  60. package/server/src/lib/safely.ts +16 -0
  61. package/server/src/lib/systemLoad.ts +362 -0
  62. package/server/src/lib/systemParam.ts +110 -0
  63. package/server/src/types/definition.ts +2 -0
  64. package/server/stateloom-web.json +2 -2
  65. package/server/.next/static/chunks/636e7eb4aeda72e0.css +0 -2
  66. package/server/.next/static/chunks/92628504da59dcc8.js +0 -10
  67. package/server/.next/static/chunks/aea5b1716c68391c.js +0 -1
  68. /package/server/.next/static/{6dAVJYqnbe6oEAABQ1yMG → eIqAtQaBkU80e3XWuVwR8}/_buildManifest.js +0 -0
  69. /package/server/.next/static/{6dAVJYqnbe6oEAABQ1yMG → eIqAtQaBkU80e3XWuVwR8}/_clientMiddlewareManifest.json +0 -0
  70. /package/server/.next/static/{6dAVJYqnbe6oEAABQ1yMG → eIqAtQaBkU80e3XWuVwR8}/_ssgManifest.js +0 -0
@@ -0,0 +1,11 @@
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,"'")}"`;function ef(e){return`${e.name} : ${e.type}`}function eg(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=>ef(e).length+6.96969696969697))+28))),height:30+20*Math.max(1,t.length)+8}}function ex(e){return e.trim().replace(/[\s_]+/g,"-").replace(/[^A-Za-z0-9.-]/g,"").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,60)}let ey=["alt","opt","loop"];function eb(e){return!!e&&"object"==typeof e&&Array.isArray(e.participants)&&Array.isArray(e.messages)&&!("state"in e)&&!("entities"in e)}function ev(e,t,n){return{settings:n?{namespace:e,name:t,description:n}:{namespace:e,name:t},participants:[],messages:[]}}function ew(e,t){return null===e?String(t+1):`f${e+1}.${t+1}`}function ej(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 ek(e){let t=[];return(e.messages??[]).forEach((e,n)=>t.push({ref:ew(null,n),message:e,fragment:null})),(e.fragments??[]).forEach((e,n)=>(e?.messages??[]).forEach((e,s)=>t.push({ref:ew(n,s),message:e,fragment:n}))),t}function e$(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,ew(null,t)));let r=(e.messages??[]).length;for(let[n,a]of(e.fragments??[]).entries()){let e=`fragment:${n+1}`;if(!a||!ey.includes(a.kind)){t.push({ruleId:"S005",message:`Fragment ${n+1} has kind "${a?.kind??""}"; expected one of ${ey.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,ew(n,t)))}return t}let eN=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 eS(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e&&!(Array.isArray(e)&&0===e.length)))}function eE(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 eC(e,t){if(eE(e,t.from),eE(e,t.to),!t.label?.trim())throw Error("A message needs a label: what is said or done, in a few words.")}function eM(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 e_(e,t,n){let s=eN(e),r=eE(s,t),a=eS({...r,...n});return s.participants[s.participants.indexOf(r)]=a,s}function eA(e,t,n){let s=eN(e);eC(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,eS({...t})),s.fragments)for(let e of s.fragments)e.after>r&&(e.after+=1);return s}function eO(e,t,n,s=null){let r=eN(e),a=null===s?r.messages:eM(r,s).messages,i=a[t];if(!i)throw Error(`Message ${t+1} not found${null===s?"":` in fragment ${s+1}`}.`);let o=eS({...i,...n});return eC(r,o),a[t]=o,r}function eR(e,t,n){let s=eN(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 eP={columnGap:150,rowHeight:34,headerHeight:34,topGap:30,fragmentPad:30,margin:24,fontSize:12};function eT(e,t={}){let n={...eP,...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:ew(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 eI=e=>e.replace(/[;#\n\r]+/g," ").replace(/\s+/g," ").trim(),eL=["propose","auto"];function eD(e,t){return"auto"===t||"propose"===t?t:e?.settings?.reconcile==="auto"?"auto":"propose"}let eq=["person","agent","service","external"];function eB(e){return e.toLowerCase().endsWith(".sysdf.json")}function eF(e){return!!e&&"object"==typeof e&&Array.isArray(e.members)&&!("state"in e)&&!("entities"in e)&&!("participants"in e)}function eY(e){return e.toLowerCase().endsWith(".erdf.json")?"erd":e.toLowerCase().endsWith(".sqdf.json")?"sequence":eB(e)?"system":"machine"}function ez(e){return e&&"object"==typeof e?W(e)?"erd":eb(e)?"sequence":eF(e)?"system":"state"in e?"machine":null:null}let eU=["erd","machine","sequence"];function eX(e,t){return t.startsWith("/")?eH(t):eH((e.slice(0,e.lastIndexOf("/")+1)||"./")+t)}function eH(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 eJ=e=>({settings:{...e.settings},members:(e.members??[]).map(e=>({...e})),actors:(e.actors??[]).map(e=>({...e}))});function eV(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e))}function eW(e,t){let n=eJ(e);return n.settings=eV({...n.settings,...t}),n}let eK=["refused","unknown-event","ended","state-mismatch"];function eZ(e,t=0){return e.settings?.name||e.state?.name||`machine ${t+1}`}function eG(e){let t=e.map((e,t)=>eZ(e,t));return t.map((e,n)=>t.indexOf(e)===n&&t.lastIndexOf(e)===n?e:`${e} #${n+1}`)}function eQ(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 e0(e,t,n){let s=t;for(;s;){if(s===n)return!0;s=e.parent.get(s)}return!1}let e1=(e,t)=>e.states.get(t)?.kind==="final";function e2(e,t){let n,s,r=eG(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?eQ(o,e.state.name):null,o})(e,0,r[t])),i=(s=[{name:"main",kind:"main",items:n=(e.messages??[]).map((e,t)=>({ref:ew(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:ew(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&&e1(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=eZ(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=>e0(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=>!e1(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?eQ(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=>e0(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=>e1(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=>eK.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 e5(e){let t={machines:[],erds:[],sequences:[]};for(let n of e)n.def&&!n.error&&ez(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 e4(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),eU.includes(eY(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),eq.includes(r.kind)||s("Y004",`Actor "${r.name}" has kind "${r.kind??""}"; expected one of ${eq.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):ez(e.def)!==e.kind&&s("Y003",`"${e.path}" is named as a ${e.kind} but holds ${ez(e.def)??"something else"}`,e.path);let{machines:a,erds:i,sequences:o}=e5(t),l=new Map;for(let{member:e,def:t}of a){let n=eZ(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 e$(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)=>eZ(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",`${eZ(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)=>eZ(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(eZ(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 ek(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=e2(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 e3(e){return`${e.kind}:${e.name}`}function e6(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 e8(e){let{machines:t,erds:n,sequences:s}=e5(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=eZ(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=eG(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})=>eZ(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 ek(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=e2(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 e7=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 e9(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n)||(e.parallel?.states??[]).some(n));return n(e.state)}let te=(e,t)=>t?"service":/\b(agent|bot|assistant)\b/i.test(e)?"agent":"person";function tt(e,t){let{machines:n,erds:s,sequences:r}=e5(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=te(t.actor,t.service);o=function(e,t){if(!t.name?.trim())throw Error("An actor needs a name.");if(!eq.includes(t.kind))throw Error(`An actor is one of ${eq.join(", ")}; got '${t.kind}'.`);let n=eJ(e);if((n.actors??[]).some(e=>e.name===t.name))throw Error(`Actor '${t.name}' already exists.`);return(n.actors??=[]).push(eV({...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 ek(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=eG(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=eG(r),i=new Map,o=[],l=new Set,c=e2(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})(e2(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=ej(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=`${e7(f.from)}Events`,o=e7(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=e9(t,f.state);if(!o&&!f.machine){let t=a.filter((t,n)=>n!==e&&e9(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:e2(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 tn(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 ts(e){return e.parallel?e.parallel.states:e.states??[]}function tr(e,t){return ts(e).find(e=>e.name===t)??null}let ta={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 ti(e){let t={};if(!e)return t;for(let[n,s]of Object.entries(e)){let e=ta[n];e&&"string"==typeof s&&(t[e]=s)}return t}let to={x:100,y:100,width:160,height:60};function tl(e,t){return 1===t?16*e:2===t?400*e:e}function tc(e){return!!e&&"string"==typeof e.tagName&&(!!e.isContentEditable||["INPUT","TEXTAREA","SELECT","BUTTON","OPTION"].includes(e.tagName))}function td(e){return(e.states?.length??0)>0||(e.parallel?.states.length??0)>0}function th({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 tm={kind:null,id:null},tu=(0,l.forwardRef)(function(e,t){let{definition:n,positions:s,path:r=[],rootLabel:a,viewport:i,onViewportChange:c,selection:d=tm,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=tr(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?ts(function(e,t){let n=e;for(let e of t){let t=tr(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]??to,[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=tl(e.deltaX,e.deltaMode),s=tl(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||tc(e.target)||tc(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={...ti(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)(th,{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=td(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=td(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 tp(e,t){return 1===t?16*e:2===t?400*e:e}let tf={"1:1":["one","one"],"1:N":["one","many"],"N:1":["many","one"],"N:M":["many","many"]};function tg(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 tx(e){return[e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n\n")}function ty(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 tb({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=tp(e.deltaX,e.deltaMode),s=tp(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:{...ti(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:ty(C.get(e.from)?.rect,t.p0),className:"slc-erd-line"}),(0,o.jsx)("path",{d:ty(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]=tf[e.cardinality]??tf["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:tg(t.p0,t.p1,s),className:"slc-erd-mark"}),(0,o.jsx)("path",{d:tg(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),[`${ef(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)}),tx(e)&&(0,o.jsx)("title",{children:tx(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:[tx(e)&&(0,o.jsx)("title",{children:tx(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?"◉ ":"",ef(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 tv(e,t){return 1===t?16*e:2===t?400*e:e}function tw(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 tj(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 tk=e=>"string"==typeof e?e:null==e?"":String(e);function t$(e){let t=e&&"object"==typeof e?e:{};return{from:tk(t.from),to:tk(t.to),label:tk(t.label),event:tk(t.event)||void 0,machine:tk(t.machine)||void 0,carries:tk(t.carries)||void 0,state:tk(t.state)||void 0,description:tk(t.description)||void 0,notes:tk(t.notes)||void 0,optional:!0===t.optional||void 0,reply:!0===t.reply||void 0}}function tN(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:tk(s.namespace),name:tk(s.name),notes:tk(s.notes)||void 0},participants:n(t.participants).map(e=>{let t=e&&"object"==typeof e?e:{};return{name:tk(t.name),description:tk(t.description)||void 0,notes:tk(t.notes)||void 0,actor:tk(t.actor)||void 0,service:tk(t.service)||void 0,object:tk(t.object)||void 0,holds:Array.isArray(t.holds)?t.holds.map(tk):"string"==typeof t.holds?[t.holds]:void 0}}),messages:n(t.messages).map(t$),...Array.isArray(t.fragments)?{fragments:t.fragments.map(e=>{let t=e&&"object"==typeof e?e:{};return{kind:tk(t.kind),label:tk(t.label),after:"number"==typeof t.after&&Number.isFinite(t.after)?t.after:0,notes:tk(t.notes)||void 0,messages:n(t.messages).map(t$)}})}:{}}}function tS({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)(()=>tN(e),[e]),$=(0,l.useMemo)(()=>t??eT(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(ek(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=tv(e.deltaX,e.deltaMode),r=tv(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:{...ti(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:tw(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:tw(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:[tj(t)&&(0,o.jsx)("title",{children:tj(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 tE=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},tC=e=>{let t=e?tE(e):tE,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},tM=Object.create(null);tM.open="0",tM.close="1",tM.ping="2",tM.pong="3",tM.message="4",tM.upgrade="5",tM.noop="6";let t_=Object.create(null);Object.keys(tM).forEach(e=>{t_[tM[e]]=e});let tA={type:"error",data:"parser error"},tO="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),tR="function"==typeof ArrayBuffer,tP=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,tT=({type:e,data:t},n,s)=>{if(tO&&t instanceof Blob)if(n)return s(t);else return tI(t,s);if(tR&&(t instanceof ArrayBuffer||tP(t)))if(n)return s(t);else return tI(new Blob([t]),s);return s(tM[e]+(t||""))},tI=(e,t)=>{let n=new FileReader;return n.onload=function(){t("b"+(n.result.split(",")[1]||""))},n.readAsDataURL(e)};function tL(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let tD="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tq="u"<typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<tD.length;e++)tq[tD.charCodeAt(e)]=e;let tB="function"==typeof ArrayBuffer,tF=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tz(e,t)};let n=e.charAt(0);return"b"===n?{type:"message",data:tY(e.substring(1),t)}:t_[n]?e.length>1?{type:t_[n],data:e.substring(1)}:{type:t_[n]}:tA},tY=(e,t)=>tB?tz((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=tq[e.charCodeAt(s)],i=tq[e.charCodeAt(s+1)],o=tq[e.charCodeAt(s+2)],l=tq[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},tz=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer;function tU(e){return e.reduce((e,t)=>e+t.length,0)}function tX(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 tH(e){if(e){var t=e;for(var n in tH.prototype)t[n]=tH.prototype[n];return t}}tH.prototype.on=tH.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},tH.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},tH.prototype.off=tH.prototype.removeListener=tH.prototype.removeAllListeners=tH.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},tH.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},tH.prototype.emitReserved=tH.prototype.emit,tH.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},tH.prototype.hasListeners=function(e){return!!this.listeners(e).length};let tJ="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),tV="u">typeof self?self:"u">typeof window?window:Function("return this")();function tW(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}let tK=tV.setTimeout,tZ=tV.clearTimeout;function tG(e,t){t.useNativeTimers?(e.setTimeoutFn=tK.bind(tV),e.clearTimeoutFn=tZ.bind(tV)):(e.setTimeoutFn=tV.setTimeout.bind(tV),e.clearTimeoutFn=tV.clearTimeout.bind(tV))}function tQ(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class t0 extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class t1 extends tH{constructor(e){super(),this.writable=!1,tG(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 t0(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=tF(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 t2 extends t1{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=tF(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)=>{tT(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]=tQ()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let t5=!1;try{t5="u">typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let t4=t5;function t3(){}class t6 extends t2{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 t8 extends tH{constructor(e,t,n){super(),this.createRequest=e,tG(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=tW(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=t8.requestsCount++,t8.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=t3,e)try{this._xhr.abort()}catch(e){}"u">typeof document&&delete t8.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 t7(){for(let e in t8.requests)t8.requests.hasOwnProperty(e)&&t8.requests[e].abort()}t8.requestsCount=0,t8.requests={},"u">typeof document&&("function"==typeof attachEvent?attachEvent("onunload",t7):"function"==typeof addEventListener&&addEventListener("onpagehide"in tV?"pagehide":"unload",t7,!1));let t9=(s=ne({xdomain:!1}))&&null!==s.responseType;function ne(e){let t=e.xdomain;try{if("u">typeof XMLHttpRequest&&(!t||t4))return new XMLHttpRequest}catch(e){}if(!t)try{return new tV[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let nt="u">typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class nn extends t1{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=nt?{}:tW(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;tT(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&tJ(()=>{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]=tQ()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let ns=tV.WebSocket||tV.MozWebSocket,nr={websocket:class extends nn{createSocket(e,t,n){return nt?new ns(e,t,n):t?new ns(e,t):new ns(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends t1{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>tU(a))break;let e=tX(a,1);l=(128&e[0])==128,i=(o=127&e[0])<126?3:126===o?1:2}else if(1===i){if(2>tU(a))break;let e=tX(a,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(8>tU(a))break;let e=tX(a,8),n=new DataView(e.buffer,e.byteOffset,e.length),s=n.getUint32(0);if(s>2097151){t.enqueue(tA);break}o=0x100000000*s+n.getUint32(4),i=3}else{if(tU(a)<o)break;let e=tX(a,o);t.enqueue(tF(l?e:n.decode(e),r)),i=0}if(0===o||o>s){t.enqueue(tA);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)},tO&&e.data instanceof Blob?e.data.arrayBuffer().then(tL).then(s):tR&&(e.data instanceof ArrayBuffer||tP(e.data))?s(tL(e.data)):tT(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&&tJ(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}},polling:class extends t6{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=t9&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new t8(ne,this.uri(),e)}}},na=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ni=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function no(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=na.exec(e||""),c={},d=14;for(;d--;)c[ni[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 nl="function"==typeof addEventListener&&"function"==typeof removeEventListener,nc=[];nl&&addEventListener("offline",()=>{nc.forEach(e=>e())},!1);class nd extends tH{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=no(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=no(t.host).host);tG(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)),nl&&(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"})},nc.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&&nd.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",nd.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,tJ(()=>{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(nd.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(),nl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=nc.indexOf(this._offlineEventListener);-1!==e&&nc.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}nd.protocol=4;class nh extends nd{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;nd.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;nd.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 nm extends nh{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=>nr[e]).filter(e=>!!e)),super(n?s:e,s)}}nm.protocol;let nu="function"==typeof ArrayBuffer,np=Object.prototype.toString,nf="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===np.call(Blob),ng="function"==typeof File||"u">typeof File&&"[object FileConstructor]"===np.call(File);function nx(e){return nu&&(e instanceof ArrayBuffer||("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer))||nf&&e instanceof Blob||ng&&e instanceof File}let ny=["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 nb{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(nx(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(nx(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 nv extends tH{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 nw(t)):super.emitReserved("decoded",t)}else if(nx(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(!nj(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(nv.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 nk(t);case i.DISCONNECT:return void 0===t;case i.CONNECT_ERROR:return"string"==typeof t||nk(t);case i.EVENT:case i.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ny.indexOf(t[0]));case i.ACK:case i.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class nw{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 nj=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function nk(e){return"[object Object]"===Object.prototype.toString.call(e)}function n$(e){var t;return"string"==typeof e.nsp&&(void 0===(t=e.id)||nj(t))&&function(e,t){switch(e){case i.CONNECT:return void 0===t||nk(t);case i.DISCONNECT:return void 0===t;case i.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===ny.indexOf(t[0]));case i.ACK:return Array.isArray(t);case i.CONNECT_ERROR:return"string"==typeof t||nk(t);default:return!1}}(e.type,e.data)}function nN(e,t,n){return e.on(t,n),function(){e.off(t,n)}}e.s(["Decoder",()=>nv,"Encoder",()=>nb,"PacketType",()=>i,"isPacketValid",()=>n$,"protocol",0,5],11014);let nS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class nE extends tH{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=[nN(e,"open",this.onopen.bind(this)),nN(e,"packet",this.onpacket.bind(this)),nN(e,"error",this.onerror.bind(this)),nN(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(nS.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 nC=e.i(11014);function nM(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}nM.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)},nM.prototype.reset=function(){this.attempts=0},nM.prototype.setMin=function(e){this.ms=e},nM.prototype.setMax=function(e){this.max=e},nM.prototype.setJitter=function(e){this.jitter=e};class n_ extends tH{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,tG(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 nM({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||nC;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 nm(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=nN(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},a=nN(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(nN(e,"ping",this.onping.bind(this)),nN(e,"data",this.ondata.bind(this)),nN(e,"error",this.onerror.bind(this)),nN(e,"close",this.onclose.bind(this)),nN(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){tJ(()=>{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 nE(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 nA={};function nO(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=no(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=nA[a]&&i in nA[a].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?n=new n_(r,t):(nA[a]||(nA[a]=new n_(r,t)),n=nA[a]),s.query&&!t.query&&(t.query=s.queryKey),n.socket(s.path,t)}function nR(e){if(e&&"object"==typeof e&&"clientId"in e){let t=e.clientId;if("string"==typeof t)return t}}function nP(e){let{url:t,role:n,docId:s,name:r,token:a}=e,i=!1!==e.autoResync,o=nO(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=nR(e);t&&(h=[...h.filter(e=>e.clientId!==t),e],x())}),o.on("presence:leave",e=>{let t=nR(e);t&&(h=h.filter(e=>e.clientId!==t),x())}),o.on("presence:update",e=>{let t=nR(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 nT(e){return"runtime.enter"===e.op||"runtime.exit"===e.op}function nI(e){let{onFull:t,onPatch:n,onPresence:s,...r}=e,a=nP(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(nT),r=t.filter(e=>!nT(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 nL(){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 nD(){return{positions:{}}}function nq(e,t){if(e.name===t)return e;for(let n of e.states??[]){let e=nq(n,t);if(e)return e}return null}function nB(e,t,n){return e.name===t?n(e)??e:{...e,states:e.states?.map(e=>nB(e,t,n))}}function nF(e,t){return{...e,states:e.states?.filter(e=>e.name!==t).map(e=>nF(e,t))}}function nY(e){let t=[e.name];for(let n of e.states??[])t.push(...nY(n));return t}function nz(e){return e.events.flatMap(e=>(e.events??[]).map(e=>e.id))}function nU(e){let t=[],n=nY(e.state),s=nz(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 nX(e,t){return{positions:{...$(e),...t.positions}}}Object.assign(nO,{Manager:n_,Socket:nE,io:nO,connect:nO});let nH=(r=(e,t)=>({definition:nL(),layout:nX(nL(),nD()),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=nX(n,t().layout);e({definition:n,layout:s,dirty:!0,errors:nU(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=nB(r.state,a,e=>({...e,states:[...e.states??[],s]}));let i=nX(r,t().layout);e({definition:r,layout:i,dirty:!0,errors:nU(r)})},updateState:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=nB(r.state,n,e=>({...e,...s})),e({definition:r,dirty:!0,errors:nU(r)})},removeState:n=>{t()._pushHistory();let s={...t().definition};s.state=nF(s.state,n);let r={positions:{...t().layout.positions}};delete r.positions[n],e({definition:s,layout:r,dirty:!0,errors:nU(s)})},nestState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=nq(r.state,n);if(!a||n===s)return;let i=JSON.parse(JSON.stringify(a));r.state=nF(r.state,n),r.state=nB(r.state,s,e=>({...e,states:[...e.states??[],i]})),e({definition:r,dirty:!0,errors:nU(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:nU(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:nU(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:nU(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=nB(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=nB(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=nB(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=nB(r.state,n,e=>({...e,transitions:[...e.transitions??[],s]})),e({definition:r,dirty:!0,errors:nU(r)})},updateTransition:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=nB(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=nB(r.state,n,e=>({...e,transitions:e.transitions?.filter((e,t)=>t!==s)})),e({definition:r,dirty:!0,errors:nU(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:nU(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:nU(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=s.stateMachine??s.StateMachine??s,a=nX(r,nD()),i=r.state?.name??"Root";e({definition:r,layout:a,fileName:n??null,dirty:!1,errors:nU(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({stateMachine:e},null,2)},applyRemote:(n,s,r)=>{try{let a=JSON.parse(n),i=a.stateMachine??a.StateMachine??a,o=nX(i,t().layout),l=i.state?.name??"Root",c=t(),d=new Set(nY(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&&nz(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:nU(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=nX(i,r.layout),c=i.state?.name??"Root",d=new Set(nY(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&&nz(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:nU(i),selection:g,navigationPath:m,currentParent:p})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}finally{e({_applyingRemote:!1})}},validate:()=>{let n=nU(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=nq(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=nq(e.state,n);return s?.states??[]}}))?tC(r):tC,nJ="canvas",nV=`[data-pinch-owner="${nJ}"]`;function nW(e){return!!e&&"function"==typeof e.closest&&null!==e.closest(nV)}let nK="stateloom-canvas",nZ="#030712",nG=["png","jpeg","svg","mermaid","markdown"],nQ={png:"PNG",jpeg:"JPEG",svg:"SVG",mermaid:"Mermaid",markdown:"Markdown"},n0={png:"image/png",jpeg:"image/jpeg",svg:"image/svg+xml",mermaid:"text/vnd.mermaid",markdown:"text/markdown"},n1={png:"png",jpeg:"jpg",svg:"svg",mermaid:"mmd",markdown:"md"};async function n2(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
+ ${a}
3
+ \`\`\`
4
+ `:`${a}
5
+ `)],{type:`${n0[e]};charset=utf-8`})}else{let t=function(e={}){let t="u"<typeof document?null:document.getElementById(nK);if(!t)return null;let n=function(e){let t=e.querySelector(":scope > g");if(!t)return null;try{let e=t.getBBox();return e.width>0&&e.height>0?e:null}catch{return null}}(t);if(!n)return null;let s=e.padding??48,r=e.background??nZ,a=Math.round(n.x-s),i=Math.round(n.y-s),o=Math.round(n.width+2*s),l=Math.round(n.height+2*s),c=t.cloneNode(!0);c.removeAttribute("id"),c.removeAttribute("class"),c.removeAttribute("style"),c.setAttribute("xmlns","http://www.w3.org/2000/svg"),c.setAttribute("width",String(o)),c.setAttribute("height",String(l)),c.setAttribute("viewBox",`${a} ${i} ${o} ${l}`),c.setAttribute("font-family","ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"),function e(t){for(let n of Array.from(t.children)){if("transparent"===n.getAttribute("fill")||"transparent"===n.getAttribute("stroke")){n.remove();continue}n.removeAttribute("class"),n.removeAttribute("style"),e(n)}}(c);let d=c.querySelector(":scope > g");d?.removeAttribute("transform");let h=document.createElementNS("http://www.w3.org/2000/svg","rect");return h.setAttribute("x",String(a)),h.setAttribute("y",String(i)),h.setAttribute("width",String(o)),h.setAttribute("height",String(l)),h.setAttribute("fill",r),c.insertBefore(h,c.firstChild),new XMLSerializer().serializeToString(c)}(n);if(!t)throw Error("nothing on the board to export yet");i="svg"===e?new Blob([t],{type:`${n0.svg};charset=utf-8`}):await (a=n.scale??2,new Promise((n,s)=>{let r=t.match(/width="(\d+)"\s+height="(\d+)"/),i=r?Number(r[1]):1200,o=r?Number(r[2]):800,l=URL.createObjectURL(new Blob([t],{type:"image/svg+xml;charset=utf-8"})),c=new Image;c.onload=()=>{URL.revokeObjectURL(l);let t=document.createElement("canvas");t.width=Math.max(1,Math.round(i*a)),t.height=Math.max(1,Math.round(o*a));let r=t.getContext("2d");r?(r.fillStyle=nZ,r.fillRect(0,0,t.width,t.height),r.drawImage(c,0,0,t.width,t.height),t.toBlob(e=>e?n(e):s(Error("the canvas produced no image")),n0[e],"jpeg"===e?.92:void 0)):s(Error("this browser gave no 2d context to draw into"))},c.onerror=()=>{URL.revokeObjectURL(l),s(Error("the browser could not read the serialized board"))},c.src=l}))}let o=function({doc:e,machine:t,format:n,at:s}){let r,a,i=ex(t??"")||ex(e?(e.split(/[/\\]/).pop()??e).replace(/\.smdf\.json$/i,"").replace(/\.json$/i,""):"")||"statemachine",o=e&&(r=e.match(/(?:^|[/\\-])ep(?:isode)?-?(\d{2,4})(?:[/\\-]|$)/i))?`ep${r[1]}`:null,l=o?`${o}--`:"";return`${l}${i}--${(a=e=>String(e).padStart(2,"0"))(s.getFullYear()%100)+a(s.getMonth()+1)+a(s.getDate())+a(s.getHours())+a(s.getMinutes())+a(s.getSeconds())}.${n}`}({doc:t.docPath??t.fileName??null,machine:t.definition?.settings?.name??null,format:n1[e]??String(e),at:(void 0)??new Date}),l=URL.createObjectURL(i),c=document.createElement("a");return c.href=l,c.download=o,c.click(),URL.revokeObjectURL(l),o}let n5="stateloom.layout.v1:";async function n4(){try{let{requestedDoc:t,docQuery:n}=await e.A(32058),s=await fetch(`/api/file${n(t())}`,{cache:"no-store"});if(s.ok){let e=(await s.json())?.path;if("string"==typeof e&&e.length>0)return e}}catch{}return nH.getState().fileName??"untitled"}function n3(){let e,t,n=nH(e=>e.definition),s=nH(e=>e.layout),r=nH(e=>e.selection),a=nH(e=>e.select),i=nH(e=>e.clearSelection),c=nH(e=>e.setStatePosition),d=nH(e=>e.drawMode),h=nH(e=>e.drawSource),m=nH(e=>e.setDrawSource),u=nH(e=>e.setDrawMode),p=nH(e=>e.addTransition),f=nH(e=>e.showContextMenu),g=nH(e=>e.removeState),x=nH(e=>e.undo),y=nH(e=>e.redo),b=nH(e=>e.errors),v=nH(e=>e.navigationPath),w=nH(e=>e.navigateInto),j=nH(e=>e.navigateUp),k=nH(e=>e.activeStates),N=nH(e=>e.viewport),S=nH(e=>e.setViewport);e=(0,l.useRef)(!1),t=(0,l.useRef)(null),(0,l.useEffect)(()=>{let n=!1,s=null;(async()=>{let s=await n4();if(n)return;t.current=s;let r=function(e){try{let t=window.localStorage.getItem(`${n5}${e}`);if(!t)return null;let n=JSON.parse(t),s={};for(let[e,t]of Object.entries(n?.positions??{}))t&&"object"==typeof t&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)&&(s[e]=t);return{positions:s,viewport:function(e,t=D){return e?{x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,scale:B(e.scale??1,t)}:{...q}}(n?.viewport)}}catch{return null}}(s);r&&nH.getState().hydrateLayout(r.positions,r.viewport),e.current=!0})();let r=nH.subscribe((n,r)=>{e.current&&t.current&&(n.layout!==r.layout||n.viewport!==r.viewport)&&(s&&clearTimeout(s),s=setTimeout(()=>{let e=nH.getState();!function(e,t,n){try{window.localStorage.setItem(`${n5}${e}`,JSON.stringify({positions:t,viewport:n,savedAt:Date.now()}))}catch{}}(t.current,function(e,t){let n={};for(let[s,r]of Object.entries(e)){let e=t[s];e&&(r.x!==e.x||r.y!==e.y||r.width!==e.width||r.height!==e.height)&&(n[s]=r)}return n}(e.layout.positions,$(e.definition)),e.viewport)},300))});return()=>{n=!0,s&&clearTimeout(s),r()}},[]);let E=v.slice(1);return(0,o.jsx)(tu,{definition:n,positions:s.positions,path:E,rootLabel:v[0],viewport:N,onViewportChange:S,selection:{kind:"state"===r.kind||"transition"===r.kind?r.kind:null,id:r.id},activeStates:k,errorElements:b.flatMap(e=>e.element?[e.element]:[]),drawMode:"transition"===d?"transition":"select",drawSource:h,svgId:nK,pinchOwner:nJ,emptyHint:window.matchMedia?.("(pointer: coarse)").matches?"Press and hold to add a state, or load a .smdf.json file":"Right-click to add a state, or load a .smdf.json file",onSelect:(e,t)=>{"state"!==e||"transition"!==d||h?a(e,t):m(t)},onClearSelection:i,onStateMove:c,onNavigateInto:w,onNavigateTo:e=>j(e),onContextMenu:(e,t,n)=>f(e,t,"state"===n.kind?{kind:"state",id:n.id}:{kind:"canvas"}),onCreateTransition:(e,t,n)=>{p(e,{event:n,nextState:t}),m(null),u("select")},onCancelDraw:()=>{u("select"),m(null)},onDeleteState:e=>{g(e),i()},onUndo:x,onRedo:y})}function n6({label:e,actions:t,onChange:n}){let s=(e,s)=>n(t.map((t,n)=>n===e?{...t,...s}:t));return(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:"flex items-center justify-between",children:[(0,o.jsx)("span",{className:"text-xs font-medium text-gray-500",children:e}),(0,o.jsx)("button",{onClick:()=>n([...t,{action:"code",code:""}]),className:"text-xs text-blue-500 hover:text-blue-400",children:"+ action"})]}),t.map((e,r)=>(0,o.jsxs)("div",{className:"flex items-start gap-1 mt-1",children:[(0,o.jsxs)("select",{className:"bg-gray-800 border border-gray-700 rounded px-1 py-0.5 text-xs text-gray-200",value:e.action,onChange:e=>s(r,{action:e.target.value}),children:[(0,o.jsx)("option",{value:"code",children:"Code"}),(0,o.jsx)("option",{value:"timerStart",children:"Timer Start"}),(0,o.jsx)("option",{value:"timerStop",children:"Timer Stop"})]}),"code"===e.action?(0,o.jsx)("textarea",{className:"flex-1 bg-gray-800 border border-gray-700 rounded px-1 py-0.5 text-xs text-gray-200 h-10 font-mono",value:e.code??"",placeholder:"// action code...",onChange:e=>s(r,{code:e.target.value})}):(0,o.jsx)("input",{className:"flex-1 bg-gray-800 border border-gray-700 rounded px-1 py-0.5 text-xs text-gray-200",value:e.name??"",placeholder:"Timer name",onChange:e=>s(r,{name:e.target.value})}),(0,o.jsx)("button",{onClick:()=>n(t.filter((e,t)=>t!==r)),className:"text-red-600 hover:text-red-400 text-xs mt-0.5",children:"✕"})]},r)),0===t.length&&(0,o.jsx)("span",{className:"text-xs text-gray-700 italic",children:"none"})]})}function n8(){let e=nH(e=>e.definition),t=nH(e=>e.selection),n=nH(e=>e.updateState),s=nH(e=>e.removeState);nH(e=>e.addAction),nH(e=>e.removeAction);let r=nH(e=>e.updateTransition),a=nH(e=>e.removeTransition);if(!t.kind||!t.id)return(0,o.jsx)("div",{className:"p-3 text-xs text-gray-500",children:"Select a state or transition to edit its properties."});let i=(e,t)=>{if(e.name===t)return e;for(let n of e.states??[]){let e=i(n,t);if(e)return e}return null};if("state"===t.kind){let r=i(e.state,t.id);if(!r)return(0,o.jsx)("div",{className:"p-3 text-gray-500 text-xs",children:"State not found"});let l=r.onEntry?.actions??[],c=r.onExit?.actions??[];return(0,o.jsxs)("div",{className:"p-3 space-y-3 text-sm md:overflow-y-auto md:max-h-[calc(100vh-160px)]",children:[(0,o.jsxs)("h3",{className:"text-xs font-semibold text-gray-400",children:["State: ",r.name]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Name"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:r.name,onChange:e=>n(t.id,{name:e.target.value})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Kind"}),(0,o.jsxs)("select",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:r.kind??"normal",onChange:e=>n(t.id,{kind:e.target.value}),children:[(0,o.jsx)("option",{value:"normal",children:"Normal"}),(0,o.jsx)("option",{value:"final",children:"Final"}),(0,o.jsx)("option",{value:"history",children:"History"})]})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Description"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-12",value:r.description??"",onChange:e=>n(t.id,{description:e.target.value||void 0})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Prompt for the agent in this state"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-20",placeholder:"What the agent resolves here, and how it opens…",value:r.prompt??"",onChange:e=>n(t.id,{prompt:e.target.value||void 0})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Notes"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-20",placeholder:"An open question, a decision, something to tell the agent…",value:r.notes??"",onChange:e=>n(t.id,{notes:e.target.value||void 0})})]}),(0,o.jsx)(n6,{label:"▸ onEntry Actions",actions:l,onChange:e=>n(t.id,{onEntry:{actions:e}})}),(0,o.jsx)(n6,{label:"◂ onExit Actions",actions:c,onChange:e=>n(t.id,{onExit:{actions:e}})}),(0,o.jsxs)("div",{children:[(0,o.jsx)("span",{className:"text-xs font-medium text-gray-500",children:"Transitions"}),(r.transitions??[]).map((e,n)=>(0,o.jsxs)("div",{className:"flex items-center gap-1 text-xs text-gray-400 py-1 border-b border-gray-800/50",children:[(0,o.jsxs)("span",{className:"flex-1",children:[e.event," → ",e.nextState??"(internal)"]}),e.condition&&(0,o.jsxs)("span",{className:"text-gray-600",children:["[",e.condition,"]"]}),(0,o.jsx)("button",{onClick:()=>a(t.id,n),className:"text-red-600 hover:text-red-400",children:"✕"})]},n)),(r.transitions?.length??0)===0&&(0,o.jsx)("span",{className:"text-xs text-gray-700 italic",children:"none"})]}),(0,o.jsx)("button",{onClick:()=>s(t.id),className:"text-red-500 hover:text-red-400 text-xs mt-2",children:"🗑 Delete State"})]})}if("transition"===t.kind){let[n,s]=t.id.split(":"),l=parseInt(s,10),c=i(e.state,n),d=c?.transitions?.[l];if(!d)return(0,o.jsx)("div",{className:"p-3 text-gray-500 text-xs",children:"Transition not found"});let h=nz(e),m=(function e(t){let n=[t];for(let s of t.states??[])n.push(...e(s));return n})(e.state).map(e=>e.name).filter(e=>"Root"!==e);return(0,o.jsxs)("div",{className:"p-3 space-y-3 text-sm",children:[(0,o.jsx)("h3",{className:"text-xs font-semibold text-gray-400",children:"Transition"}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Event"}),(0,o.jsx)("select",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:d.event,onChange:e=>r(n,l,{event:e.target.value}),children:h.map(e=>(0,o.jsx)("option",{value:e,children:e},e))})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Target State"}),(0,o.jsxs)("select",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:d.nextState??"",onChange:e=>r(n,l,{nextState:e.target.value||void 0}),children:[(0,o.jsx)("option",{value:"",children:"(internal transition)"}),m.map(e=>(0,o.jsx)("option",{value:e,children:e},e))]})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Condition (guard)"}),(0,o.jsx)("textarea",{rows:3,className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200 resize-y leading-snug",value:d.condition??"",onChange:e=>r(n,l,{condition:e.target.value||void 0})})]}),(0,o.jsx)("button",{onClick:()=>a(n,l),className:"text-red-500 hover:text-red-400 text-xs",children:"🗑 Delete Transition"})]})}return null}let n7=["string","int","float","bool","object"];function n9(){let e=nH(e=>e.definition),t=nH(e=>e.addEvent),n=nH(e=>e.updateEvent),s=nH(e=>e.removeEvent),r=nH(e=>e.addParameter),a=nH(e=>e.removeParameter),i=nH(e=>e.updateParameter),c=nH(e=>e.updateEventSource),d=nH(e=>e.select),h=nH(e=>e.selection),[m,u]=(0,l.useState)(""),[p,f]=(0,l.useState)(null),[g,x]=(0,l.useState)(null);return(0,o.jsxs)("div",{className:"p-3 text-sm",children:[e.events.map((e,t)=>(0,o.jsxs)("div",{className:"mb-3",children:[(0,o.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,o.jsx)("span",{className:"text-xs font-semibold text-gray-500",children:"Source:"}),(0,o.jsx)("input",{className:"flex-1 bg-transparent border-b border-gray-700 text-xs text-gray-300 px-1 py-0.5 focus:border-blue-500 outline-none",value:e.name,onChange:e=>c(t,{name:e.target.value})}),void 0!==e.feeder&&(0,o.jsx)("input",{className:"w-24 bg-transparent border-b border-gray-700 text-xs text-gray-400 px-1 py-0.5 focus:border-blue-500 outline-none",value:e.feeder??"",placeholder:"Feeder...",onChange:e=>c(t,{feeder:e.target.value||void 0})}),void 0===e.feeder&&(0,o.jsx)("button",{className:"text-xs text-gray-600 hover:text-gray-400",title:"Add feeder class",onClick:()=>c(t,{feeder:`${e.name}Feeder`}),children:"+feeder"})]}),(0,o.jsx)("div",{className:"-mx-1 overflow-x-auto px-1",children:(0,o.jsxs)("table",{className:"w-full text-xs",children:[(0,o.jsx)("thead",{children:(0,o.jsxs)("tr",{className:"text-gray-600 border-b border-gray-800",children:[(0,o.jsx)("th",{className:"text-left py-1 font-medium",children:"ID"}),(0,o.jsx)("th",{className:"text-left py-1 font-medium",children:"Description"}),(0,o.jsx)("th",{className:"text-left py-1 font-medium",children:"Params"}),(0,o.jsx)("th",{className:"w-6"})]})}),(0,o.jsx)("tbody",{children:(e.events??[]).map(e=>(0,o.jsxs)(l.Fragment,{children:[(0,o.jsxs)("tr",{className:`border-b border-gray-800/50 hover:bg-gray-800/30 cursor-pointer ${"event"===h.kind&&h.id===e.id?"bg-blue-900/30":""}`,onClick:()=>{d("event",e.id),f(p===e.id?null:e.id)},children:[(0,o.jsx)("td",{className:"py-1 pr-1",children:g===e.id?(0,o.jsx)("input",{autoFocus:!0,className:"w-full bg-gray-800 border border-gray-700 rounded px-1 text-gray-200",value:e.id,onChange:t=>n(e.id,{id:t.target.value}),onBlur:()=>x(null),onKeyDown:e=>"Enter"===e.key&&x(null),onClick:e=>e.stopPropagation()}):(0,o.jsx)("span",{className:"text-gray-300",onDoubleClick:t=>{t.stopPropagation(),x(e.id)},children:e.id})}),(0,o.jsx)("td",{className:"py-1 pr-1 text-gray-500 truncate max-w-[80px]",children:e.description??"—"}),(0,o.jsx)("td",{className:"py-1 text-gray-500",children:(e.parameters?.length??0)>0?e.parameters.map(e=>`${e.name}:${e.type}`).join(", "):"—"}),(0,o.jsx)("td",{className:"py-1",children:(0,o.jsx)("button",{onClick:t=>{t.stopPropagation(),s(e.id)},className:"text-red-600 hover:text-red-400",children:"✕"})})]}),p===e.id&&(0,o.jsx)("tr",{children:(0,o.jsx)("td",{colSpan:4,className:"py-2 px-1 bg-gray-900/50",children:(0,o.jsxs)("div",{className:"space-y-2",children:[(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-gray-600",children:"Description"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-gray-200 mt-0.5",value:e.description??"",onChange:t=>n(e.id,{description:t.target.value||void 0})})]}),(0,o.jsxs)("div",{children:[(0,o.jsx)("span",{className:"text-gray-600",children:"Parameters"}),(e.parameters??[]).map((t,n)=>(0,o.jsxs)("div",{className:"flex items-center gap-1 mt-1",children:[(0,o.jsx)("input",{className:"flex-1 bg-gray-800 border border-gray-700 rounded px-1 py-0.5 text-gray-200",value:t.name,placeholder:"name",onChange:t=>i(e.id,n,{name:t.target.value})}),(0,o.jsx)("select",{className:"bg-gray-800 border border-gray-700 rounded px-1 py-0.5 text-gray-200",value:t.type,onChange:t=>i(e.id,n,{type:t.target.value}),children:n7.map(e=>(0,o.jsx)("option",{value:e,children:e},e))}),(0,o.jsx)("button",{onClick:()=>a(e.id,n),className:"text-red-600 hover:text-red-400",children:"✕"})]},n)),(0,o.jsx)("button",{className:"text-blue-500 hover:text-blue-400 mt-1",onClick:()=>r(e.id,{name:"param",type:"string"}),children:"+ parameter"})]}),(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsx)("span",{className:"text-gray-600",children:"Generated method:"}),(0,o.jsxs)("code",{className:"block bg-gray-800 rounded px-2 py-1 text-green-400 mt-0.5 font-mono",children:["on_",e.id.toLowerCase(),"(context",(e.parameters??[]).map(e=>`, ${e.name}: ${e.type}`).join(""),")"]})]})]})})})]},e.id))})]})})]},t)),(0,o.jsxs)("div",{className:"flex gap-1 mt-2",children:[(0,o.jsx)("input",{className:"flex-1 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-gray-200",placeholder:"New event ID...",value:m,onChange:e=>u(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m.trim()&&(t({id:m.trim()}),u(""))}}),(0,o.jsx)("button",{onClick:()=>{m.trim()&&(t({id:m.trim()}),u(""))},className:"bg-blue-600 hover:bg-blue-500 text-white px-2 py-1 rounded",children:"+"})]})]})}function se(){let e=nH(e=>e.definition.settings),t=nH(e=>e.definition.settings.context),n=nH(e=>e.updateSettings);return(0,o.jsxs)("div",{className:"p-3 space-y-3 text-sm",children:[(0,o.jsx)("h3",{className:"text-xs font-semibold text-gray-400",children:"Machine Settings"}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Namespace"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:e.namespace,onChange:e=>n({namespace:e.target.value})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Name"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:e.name??"",onChange:e=>n({name:e.target.value||void 0})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Description"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-12",value:e.description??"",onChange:e=>n({description:e.target.value||void 0})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Notes on this diagram"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-24",placeholder:"What was discussed, what is still open, what to tell the agent…",value:e.notes??"",onChange:e=>n({notes:e.target.value||void 0})})]}),(0,o.jsxs)("label",{className:"flex items-center gap-2 text-sm text-gray-300",children:[(0,o.jsx)("input",{type:"checkbox",checked:e.asynchronous,onChange:e=>n({asynchronous:e.target.checked}),className:"rounded bg-gray-800 border-gray-600"}),"Asynchronous"]}),(0,o.jsx)("hr",{className:"border-gray-800"}),(0,o.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Context"}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Context Class"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200",value:t?.class??"",placeholder:"e.g. MyStateMachineContext",onChange:e=>n({context:{...t,class:e.target.value||void 0}})})]}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Base Class"}),(0,o.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200",value:t?.baseClass??"",placeholder:"e.g. Context",onChange:e=>n({context:{...t,baseClass:e.target.value||void 0}})})]}),(0,o.jsx)("hr",{className:"border-gray-800"}),(0,o.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Imports"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-16 font-mono",value:(e.imports??[]).join("\n"),placeholder:"One import per line",onChange:e=>n({imports:e.target.value?e.target.value.split("\n"):[]})}),(0,o.jsx)("hr",{className:"border-gray-800"}),(0,o.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Object References"}),(0,o.jsx)("textarea",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200 h-12 font-mono",value:(e.objects??[]).map(e=>`${e.instance}: ${e.class}`).join("\n"),placeholder:"instance: Class (one per line)",onChange:e=>{n({objects:e.target.value.split("\n").filter(e=>e.includes(":")).map(e=>{let[t,n]=e.split(":").map(e=>e.trim());return{instance:t,class:n}})})}}),(0,o.jsx)("hr",{className:"border-gray-800"}),(0,o.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Code Generation"}),(0,o.jsxs)("label",{className:"block",children:[(0,o.jsx)("span",{className:"text-xs text-gray-500",children:"Target Language"}),(0,o.jsxs)("select",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-xs text-gray-200",value:e.targetLanguage??"python",onChange:e=>n({targetLanguage:e.target.value}),children:[(0,o.jsx)("option",{value:"python",children:"Python"}),(0,o.jsx)("option",{value:"typescript",children:"TypeScript"}),(0,o.jsx)("option",{value:"csharp",children:"C#"})]})]})]})}function st(){let e=nH(e=>e.errors),t=nH(e=>e.validate),n=nH(e=>e.select);return(0,o.jsxs)("div",{className:"p-3",children:[(0,o.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,o.jsxs)("h3",{className:"text-xs font-semibold text-gray-400",children:["Validation ",e.length>0&&(0,o.jsxs)("span",{className:"text-red-500",children:["(",e.length,")"]})]}),(0,o.jsx)("button",{onClick:()=>t(),className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-2 py-0.5 rounded",children:"Re-check"})]}),0===e.length?(0,o.jsxs)("div",{className:"flex items-center gap-2 text-green-500 text-xs",children:[(0,o.jsx)("span",{children:"✓"}),(0,o.jsx)("span",{children:"Definition is valid"})]}):(0,o.jsx)("div",{className:"space-y-0.5",children:e.map((e,t)=>(0,o.jsxs)("div",{className:`flex items-start gap-1.5 text-[13px] py-2.5 border-b border-gray-800/50 md:text-xs md:py-1 ${e.element?"cursor-pointer hover:bg-gray-800/30":""}`,onClick:()=>{e.element&&n("state",e.element)},title:e.element?`Click to select "${e.element}"`:void 0,children:[(0,o.jsx)("span",{className:`font-mono text-[10px] mt-0.5 ${"error"===e.severity?"text-red-600":"text-yellow-600"}`,children:e.ruleId}),(0,o.jsx)("span",{className:`flex-1 ${"error"===e.severity?"text-red-400":"text-yellow-400"}`,children:e.message}),e.element&&(0,o.jsxs)("span",{className:"text-gray-600 text-[10px]",children:["→ ",e.element]})]},t))})]})}var sn=e.i(76800);function ss(){let e=(0,sn.useRequestedDoc)(),[t,n]=(0,l.useState)(!1),[s,r]=(0,l.useState)(""),[a,i]=(0,l.useState)(null),[c,d]=(0,l.useState)([]),[h,m]=(0,l.useState)(null),[u,p]=(0,l.useState)(null);(0,l.useEffect)(()=>{if(!t)return;let e=!0;return p(null),fetch("/api/docs",{cache:"no-store"}).then(e=>e.ok?e.json():Promise.reject(Error(`HTTP ${e.status}`))).then(t=>{e&&(i(t.docs??[]),d(t.roots??[]),m(t.current??null))}).catch(t=>{e&&(i([]),p(t.message))}),()=>{e=!1}},[t]);let f=e=>{n(!1),r(""),(0,sn.navigateToDoc)(e)},g=new Set((a??[]).map(e=>e.path)),x=t?(function(){try{let e=[];for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(n5)&&e.push(n.slice(n5.length))}return e.sort()}catch{return[]}})().filter(t=>t.startsWith("/")&&t!==e&&!g.has(t)):[],y=e??h,b=(a??[]).filter(e=>e.path!==y),v=s.trim().toLowerCase(),w=v?b.filter(e=>e.path.toLowerCase().includes(v)):b,j="block w-full truncate rounded px-1.5 py-1 text-left text-xs text-gray-300 hover:bg-gray-800";return(0,o.jsxs)("span",{className:"relative inline-flex",children:[(0,o.jsx)("button",{onClick:()=>n(e=>!e),className:"toolbar-btn",title:e?`Document: ${e}`:"Switch document",children:"⇄"}),t&&(0,o.jsxs)("div",{className:"absolute left-0 top-full z-50 mt-1 w-80 rounded border border-gray-700 bg-gray-900 p-2 shadow-lg",children:[(0,o.jsx)("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-gray-500",children:"switch document"}),(0,o.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=s.trim();if(t){if(1===w.length)return f(w[0].path);if(t.startsWith("/"))return f(t)}},className:"mb-1 flex gap-1",children:[(0,o.jsx)("input",{value:s,onChange:e=>r(e.target.value),placeholder:null===a?"loading…":"filter, or /absolute/path.json",className:"min-w-0 flex-1 rounded border border-gray-700 bg-gray-950 px-1.5 py-1 text-xs text-gray-200 placeholder:text-gray-600"}),(0,o.jsx)("button",{type:"submit",className:"toolbar-btn",title:"Open",children:"→"})]}),(0,o.jsxs)("div",{className:"max-h-64 overflow-y-auto",children:[e&&(0,o.jsx)("button",{onClick:()=>f(null),className:j,title:"Return to the default project file",children:"⌂ default document"}),w.map(e=>(0,o.jsxs)("button",{onClick:()=>f(e.path),className:j,title:e.path,children:[e.name,(0,o.jsx)("span",{className:"ml-1 text-[10px] text-gray-600",children:e.dir})]},e.path)),x.length>0&&(0,o.jsxs)("div",{className:"mt-1 border-t border-gray-800 pt-1",children:[(0,o.jsx)("div",{className:"px-1.5 pb-0.5 text-[10px] uppercase tracking-wide text-gray-600",children:"recent"}),x.map(e=>(0,o.jsxs)("button",{onClick:()=>f(e),className:j,title:e,children:[e.split("/").pop(),(0,o.jsx)("span",{className:"ml-1 text-[10px] text-gray-600",children:e})]},e))]}),null!==a&&0===w.length&&0===x.length&&(0,o.jsx)("div",{className:"px-1.5 py-1 text-[11px] text-gray-500",children:v?"nothing matches":"no other documents here"})]}),c.length>0&&(0,o.jsxs)("div",{className:"mt-1 truncate border-t border-gray-800 pt-1 text-[10px] text-gray-600",children:["paths are as the server sees them: ",c.join(", ")]}),u&&(0,o.jsxs)("div",{className:"mt-1 text-[10px] text-gray-600",children:["this server does not list documents (",u,") — type a path"]})]})]})}function sr(){let e=nH(e=>e.presence),[t,n]=(0,l.useState)(!1);if(0===e.length)return null;let s=new Map;for(let t of e)s.set(t.role,(s.get(t.role)??0)+1);let r=[...s].map(([e,t])=>t>1?`${e} \xd7${t}`:e).join(" · ");return(0,o.jsxs)("span",{className:"relative inline-flex",children:[(0,o.jsxs)("button",{onClick:()=>n(e=>!e),className:"toolbar-btn inline-flex items-center gap-1.5",title:`Connected: ${r}`,"aria-expanded":t,"aria-label":`${e.length} connected: ${r}`,children:[(0,o.jsx)("span",{className:"flex -space-x-1",children:e.slice(0,4).map(e=>(0,o.jsx)("span",{className:"inline-block h-2 w-2 rounded-full ring-1 ring-gray-900",style:{backgroundColor:e.color??y(e.clientId)}},e.clientId))}),(0,o.jsx)("span",{className:"tabular-nums",children:e.length})]}),t&&(0,o.jsxs)("div",{className:"absolute left-0 top-full z-50 mt-1 max-h-64 w-56 overflow-y-auto rounded border border-gray-700 bg-gray-900 p-2 shadow-lg",children:[(0,o.jsxs)("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-gray-500",children:["connected · ",r]}),e.map(e=>(0,o.jsxs)("div",{className:"flex items-center gap-1.5 rounded px-1 py-1 text-xs text-gray-300",title:e.clientId,children:[(0,o.jsx)("span",{className:"inline-block h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:e.color??y(e.clientId)}}),(0,o.jsx)("span",{className:"shrink-0",children:e.role}),e.name&&(0,o.jsx)("span",{className:"truncate text-gray-500",children:e.name})]},e.clientId))]})]})}function sa(){let e=nH(e=>e.definition),t=nH(e=>e.fileName),n=nH(e=>e.docPath),s=nH(e=>e.dirty),r=nH(e=>e.loadFromJson),a=nH(e=>e.exportJson),i=nH(e=>e.addState),c=nH(e=>e.validate),d=nH(e=>e.showCodePreview),h=nH(e=>e.setShowCodePreview),m=nH(e=>e.setGeneratedCode),u=nH(e=>e.drawMode),p=nH(e=>e.setDrawMode),f=nH(e=>e.arrangeLayout),g=nH(e=>e.undo),x=nH(e=>e.redo),y=nH(e=>e.undoStack),b=nH(e=>e.redoStack),v=nH(e=>e.remoteStatus),w=nH(e=>e.remoteMessage),j=nH(e=>e.setRemoteStatus),k=nH(e=>e.setRemoteMtime),$=nH(e=>e.applyRemote),N=(0,sn.useRequestedDoc)(),S=(0,l.useRef)(null),[E,C]=(0,l.useState)(!1),[M,_]=(0,l.useState)(""),[A,O]=(0,l.useState)(!1),[R,P]=(0,l.useState)("png"),[T,I]=(0,l.useState)(!1),[L,D]=(0,l.useState)(null),[q,B]=(0,l.useState)(null),F=async()=>{let e=a();O(!0);try{let t=await fetch(`/api/file${(0,sn.docQuery)(N)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:e})});if(t.ok){let e=await t.json();k(e.mtime),nH.setState({dirty:!1}),j("synced",null)}else{let e=await t.json().catch(()=>({error:"unknown"}));j("error",`Save failed: ${e.error??t.statusText}`)}}catch(e){j("error",`Save failed: ${e}`)}finally{O(!1)}},Y=async()=>{I(!0),D(null);try{let s=await n2(R,{definition:e,docPath:n,fileName:t});B(s)}catch(e){D(e instanceof Error?e.message:String(e))}finally{I(!1)}},z=async()=>{try{let e=await fetch(`/api/file${(0,sn.docQuery)(N)}`,{cache:"no-store"});if(!e.ok)return void j("error","Reload failed");let t=await e.json();t.exists&&t.content?$(t.content,t.mtime,t.path.split("/").pop()):j("idle",`No file at ${t.path}`)}catch(e){j("error",`Reload failed: ${e}`)}},U=()=>{M.trim()&&(i(null,{name:M.trim(),kind:"normal"}),_(""),C(!1))},[X,H]=(0,l.useState)("python"),J=async()=>{try{let e=await fetch("/api/rispec",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(e.ok){let t=await e.json();m(t.rispec)}else{let t=await e.json().catch(()=>({error:"Unknown"}));m(`# RISE rispec generation failed
6
+ ${t.error}`)}}catch(e){m(`# RISE rispec generation failed
7
+ ${e}`)}h(!0)},V=async()=>{let e=a();try{let t=await fetch("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({definition:e,language:X})});if(t.ok){let e=await t.json();m(e.code)}else{let n=await t.json().catch(()=>({error:"Unknown error"}));m(`// Code generation failed: ${n.error}
8
+ // Showing definition JSON as fallback:
9
+ ${e}`)}}catch{m(`// Backend unavailable — showing definition JSON
10
+ ${e}`)}h(!0)};return(0,o.jsxs)("div",{className:"flex flex-col gap-1.5 px-2 py-1.5 bg-gray-900 border-b border-gray-800 md:flex-row md:flex-wrap md:items-center md:px-3",children:[(0,o.jsxs)("div",{className:"toolbar-ident",children:[(0,o.jsx)("input",{ref:S,type:"file",accept:".json,.smdf.json",onChange:e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=e=>{r(e.target?.result,t.name)},n.readAsText(t),e.target.value=""},className:"hidden"}),(0,o.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[t??"untitled.smdf.json",s&&(0,o.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,o.jsx)(ss,{}),"synced"===v&&(0,o.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===v&&(0,o.jsx)("span",{className:"text-[10px] text-amber-400",title:w??"",children:"↻ remote changed"}),"error"===v&&(0,o.jsx)("span",{className:"text-[10px] text-red-400",title:w??"",children:"⚠ disk error"}),"idle"===v&&(0,o.jsx)("span",{className:"text-[10px] text-gray-600",title:w??"No file bound",children:"○ no disk"}),(0,o.jsx)(sr,{}),(0,o.jsx)("div",{className:"flex-1"})]}),(0,o.jsxs)("div",{className:"toolbar-strip",children:[(0,o.jsx)("button",{onClick:g,disabled:0===y.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,o.jsx)("button",{onClick:x,disabled:0===b.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:f,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>p("select"===u?"transition":"select"),className:`toolbar-btn ${"transition"===u?"!bg-amber-700 !text-white":""}`,title:"transition"===u?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===u?"✏️ Drawing":"↗ Draw"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>S.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,o.jsx)("button",{onClick:F,disabled:A,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,o.jsx)("button",{onClick:z,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,o.jsx)("button",{onClick:()=>{let e=new Blob([a()],{type:"application/json"}),n=URL.createObjectURL(e),s=document.createElement("a");s.href=n,s.download=t??"statemachine.smdf.json",s.click(),URL.revokeObjectURL(n)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,o.jsx)("select",{value:R,onChange:e=>{P(e.target.value),B(null),D(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:nG.map(e=>(0,o.jsx)("option",{value:e,children:nQ[e]},e))}),(0,o.jsx)("button",{onClick:Y,disabled:T,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${nQ[R]}`,children:T?"…":"🖼 Export"}),q&&!L&&(0,o.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:q,children:["⤓ ",q]}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),E?(0,o.jsxs)("div",{className:"flex items-center gap-1",children:[(0,o.jsx)("input",{autoFocus:!0,className:"bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-xs text-gray-200 w-32 md:w-24",placeholder:"State name...",value:M,onChange:e=>_(e.target.value),onKeyDown:e=>{"Enter"===e.key&&U(),"Escape"===e.key&&C(!1)}}),(0,o.jsx)("button",{onClick:U,className:"toolbar-btn-sm",children:"✓"}),(0,o.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,o.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,o.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,o.jsx)("button",{onClick:()=>c(),className:"toolbar-btn",children:"✓ Validate"}),(0,o.jsxs)("select",{value:X,onChange:e=>H(e.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,o.jsx)("option",{value:"python",children:"Python"}),(0,o.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,o.jsx)("button",{onClick:V,className:"toolbar-btn",children:"⚡ Generate"}),(0,o.jsx)("button",{onClick:J,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,o.jsxs)("button",{onClick:()=>h(!d),className:`toolbar-btn ${d?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function si(){let e=nH(e=>e.generatedCode),t=nH(e=>e.showCodePreview),n=nH(e=>e.setShowCodePreview);return t?(0,o.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,o.jsxs)("div",{className:"bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-h-[85dvh] md:w-[80%] md:max-w-3xl md:max-h-[80dvh] flex flex-col",children:[(0,o.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,o.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,o.jsx)("button",{onClick:()=>n(!1),className:"text-gray-500 hover:text-gray-300 text-lg min-h-11 min-w-11 md:min-h-0 md:min-w-0","aria-label":"Close preview",children:"✕"})]}),(0,o.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:e??"No code generated yet"}),(0,o.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,o.jsx)("button",{onClick:()=>{e&&navigator.clipboard.writeText(e)},className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-4 py-3 rounded md:px-3 md:py-1",children:"Copy to Clipboard"})})]})}):null}function so(){let e=nH(e=>e.applyRemote),t=nH(e=>e.setRemoteStatus),n=nH(e=>e.setRemoteMtime),s=(0,sn.useRequestedDoc)();return(0,l.useEffect)(()=>{let r=!1,a=(0,sn.docQuery)(s);async function i(){try{let e=await fetch(`/api/file${a}`,{cache:"no-store"});if(!e.ok)return null;return await e.json()}catch{return null}}(async()=>{let n=await i();r||(n?.path&&nH.getState().setDocPath(n.path),n?.exists&&n.content?e(n.content,n.mtime,n.path.split("/").pop()):t("idle",n?`No file at ${n.path}`:null))})();let o=new EventSource(`/api/watch${a}`);return o.addEventListener("hello",e=>{try{let t=JSON.parse(e.data);"number"==typeof t?.mtime&&n(t.mtime)}catch{}}),o.addEventListener("change",async s=>{let r=0;try{r=JSON.parse(s.data)?.mtime??0}catch{}if(r<=(nH.getState().remoteMtime??0))return;let a=await i();a?.exists&&a.content&&(nH.getState().dirty?(t("remote-changed",`Disk changed at ${new Date(a.mtime).toLocaleTimeString()} — local has unsaved edits`),n(a.mtime)):e(a.content,a.mtime,a.path.split("/").pop()))}),o.addEventListener("error",()=>{t("error","Watch stream disconnected")}),()=>{r=!0,o.close()}},[e,t,n,s]),null}function sl({url:e}){let t=(0,sn.useRequestedDoc)();return(0,l.useEffect)(()=>{if(!e)return;let n=!1,s=null,r=null,a=null,i=null;return(async()=>{let o="";try{let e=await fetch(`/api/file${(0,sn.docQuery)(t)}`,{cache:"no-store"});e.ok&&(o=(await e.json())?.path??"")}catch{}n||(o&&nH.getState().setDocPath(o),(s=nI({url:e,role:"web",docId:o,name:"web-designer",onFull:e=>{nH.getState().applyRemote(JSON.stringify({stateMachine:e.def}),e.mtime??Date.now(),o&&o.split("/").pop()||void 0),i=e.def},onPatch:e=>{nH.getState().applyRemoteOps(e.ops,e.mtime??Date.now(),e.seq),i=nH.getState().definition},onPresence:e=>{nH.getState().setPresence(e)}})).connect(),r=nH.subscribe((e,t)=>{e.definition===t.definition||e._applyingRemote||(a&&clearTimeout(a),a=setTimeout(()=>{var e,t;let n,r;if(!s||"connected"!==s.getSnapshot().status)return;let a=nH.getState().definition;if(null===i){s.emitFull(a),i=a;return}let o=(e=i,t=a,n=e??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:t.state.name,states:[]}},function(e,t,n){let s={},r=!1,a=new Set([...Object.keys(e.settings),...Object.keys(t.settings)]),i=e.settings,o=t.settings;for(let e of a)g(i[e],o[e])||void 0===o[e]||(s[e]=o[e],r=!0);void 0!==e.settings.notes&&void 0===t.settings.notes&&(s.notes="",r=!0),r&&n.push({op:"settings.update",patch:s})}(n,t,r=[]),function(e,t,n){let s=e.events,r=t.events,a=Math.min(s.length,r.length);for(let e=0;e<a;e++)!function(e,t,n,s){let r={},a=!1;for(let e of["name","file","feeder","description","timers"])g(t[e],n[e])||void 0===n[e]||(r[e]=n[e],a=!0);a&&s.push({op:"eventSource.update",index:e,patch:r});let i=t.events??[],o=n.events??[],l=new Set(o.map(e=>e.id));for(let e of i)l.has(e.id)||s.push({op:"event.remove",id:e.id});let c=i.filter(e=>l.has(e.id)),d=0;for(;d<o.length;){let t=o[d];d<c.length&&c[d].id===t.id?(function(e,t,n){let s={},r=!1;for(let n of["name","description","preAction","postAction"])g(e[n],t[n])||void 0===t[n]||(s[n]=t[n],r=!0);r&&n.push({op:"event.update",id:t.id,patch:s})}(c[d],t,s),function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++)if(!g(t[a],n[a])){let r={};t[a].name!==n[a].name&&(r.name=n[a].name),t[a].type!==n[a].type&&(r.type=n[a].type),s.push({op:"parameter.update",eventId:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"parameter.add",eventId:e,parameter:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"parameter.remove",eventId:e,index:r})}(t.id,c[d].parameters??[],t.parameters??[],s)):(s.push({op:"event.add",sourceIndex:e,event:t,index:d}),c.splice(d,0,t)),d++}}(e,s[e],r[e],n);for(let e=s.length;e<r.length;e++)n.push({op:"eventSource.add",source:r[e]});for(let e=s.length-1;e>=r.length;e--)n.push({op:"eventSource.remove",index:e})}(n,t,r),function(e,t,n){let s=p(e.state),r=p(t.state),a=new Map(s.map(e=>[e.name,e])),i=new Map(r.map(e=>[e.name,e])),o=f(e.state),l=f(t.state),c=[];for(let e of r){if(a.has(e.name))continue;let t=l.get(e.name)??null,{states:s,transitions:r,...i}=e;n.push({op:"state.add",parent:t,state:{...i}}),r&&r.length>0&&c.push({state:e.name,transitions:r})}for(let e of r){if(!a.has(e.name))continue;let t=o.get(e.name)??null,s=l.get(e.name)??null;t!==s&&null!==s&&n.push({op:"state.nest",child:e.name,newParent:s})}for(let e of r){let t=a.get(e.name);if(!t)continue;let s={},r=!1;g(t.kind,e.kind)||void 0===e.kind||(s.kind=e.kind,r=!0),g(t.description,e.description)||void 0===e.description||(s.description=e.description,r=!0),g(t.notes,e.notes)||(s.notes=e.notes??"",r=!0),g(t.prompt,e.prompt)||(s.prompt=e.prompt??"",r=!0),r&&n.push({op:"state.update",name:e.name,patch:s}),x(e.name,"onEntry",t.onEntry?.actions??[],e.onEntry?.actions??[],n),x(e.name,"onExit",t.onExit?.actions??[],e.onExit?.actions??[],n)}for(let e of c)e.transitions.forEach((t,s)=>{n.push({op:"transition.add",state:e.state,transition:t,index:s})});for(let e of r){let t=a.get(e.name);t&&function(e,t,n,s){let r=Math.min(t.length,n.length);for(let a=0;a<r;a++){if(g(t[a],n[a]))continue;let r={};for(let e of["event","nextState","condition","description","actions"])g(t[a][e],n[a][e])||void 0===n[a][e]||(r[e]=n[a][e]);Object.keys(r).length>0&&s.push({op:"transition.update",state:e,index:a,patch:r})}for(let t=r;t<n.length;t++)s.push({op:"transition.add",state:e,transition:n[t],index:t});for(let r=t.length-1;r>=n.length;r--)s.push({op:"transition.remove",state:e,index:r})}(e.name,t.transitions??[],e.transitions??[],n)}for(let e=s.length-1;e>=0;e--){let t=s[e];if(i.has(t.name))continue;let r=t.transitions??[];for(let e=r.length-1;e>=0;e--)n.push({op:"transition.remove",state:t.name,index:e});n.push({op:"state.remove",name:t.name})}}(n,t,r),r);0!==o.length&&(s.emitPatch(o),i=a)},60))}))})(),()=>{n=!0,a&&clearTimeout(a),r&&r(),s&&s.disconnect()}},[e,t]),null}function sc(){let e=b.default.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??b.default.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof e&&e.length>0?e:void 0}let sd=null;function sh(){return sd||(sd=(async()=>{let e=sc()??null;try{let t=await fetch("/api/config",{cache:"no-store"});if(t.ok){let n=await t.json();return{bridgeUrl:n.bridgeUrl||e,projectFile:n.projectFile??null}}}catch{}return{bridgeUrl:e,projectFile:null}})())}function sm(){let e=sc(),[t,n]=(0,l.useState)(e);return((0,l.useEffect)(()=>{let e=!0;return sh().then(t=>{e&&t.bridgeUrl&&n(t.bridgeUrl)}),()=>{e=!1}},[]),"string"==typeof t&&t.length>0)?(0,o.jsx)(sl,{url:t}):(0,o.jsx)(so,{})}let su="stateloom.uiScale.v1";function sp(e){return Number.isFinite(e)?Math.min(1.75,Math.max(.75,e)):1}function sf(e){"u">typeof document&&(document.documentElement.style.fontSize=`${16*sp(e)}px`)}let sg=1,sx=!1,sy=new Set;function sb(){return sx||(sx=!0,sg=function(){try{let e=window.localStorage.getItem(su);if(null===e)return 1;return sp(Number.parseFloat(e))}catch{return 1}}()),sg}function sv(){return 1}function sw(e){return sy.add(e),()=>{sy.delete(e)}}function sj(e,t){let n=sp(e);if(sf(n),t&&function(e){try{window.localStorage.setItem(su,String(sp(e)))}catch{}}(n),sx=!0,n!==sg)for(let e of(sg=n,sy))e()}function sk(e,t){return Math.max(1,Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY))}function s$(e,t){for(let n=0;n<e.length;n++)if(e[n].identifier===t)return e[n];return null}function sN(){let e=(0,l.useSyncExternalStore)(sw,sb,sv),t=(0,l.useRef)(null),n=(0,l.useRef)(null),s=(0,l.useRef)(null);(0,l.useEffect)(()=>{sf(e)},[e]);let r=(0,l.useCallback)(e=>{n.current=e,null===s.current&&(s.current=requestAnimationFrame(()=>{s.current=null,null!==n.current&&sj(n.current,!1)}))},[]),a=(0,l.useCallback)(()=>{n.current=null,sj(1,!0)},[]);return((0,l.useEffect)(()=>{let e=()=>{let e=t.current;if(t.current=null,!e?.engaged)return;null!==s.current&&(cancelAnimationFrame(s.current),s.current=null);let r=n.current??sb();n.current=null,sj(sp(r),!0)},a=n=>{if(2!==n.touches.length){t.current&&e();return}let[s,r]=[n.touches[0],n.touches[1]];nW(s.target)||nW(r.target)||(t.current={a:s.identifier,b:r.identifier,startScale:sb(),startDist:sk(s,r),engaged:!1})},i=e=>{let n=t.current;if(!n)return;let s=s$(e.touches,n.a),a=s$(e.touches,n.b);if(!s||!a)return;e.preventDefault();let i=sk(s,a);if(!n.engaged){if(12>Math.abs(i-n.startDist))return;n.engaged=!0,n.startDist=i;return}r(sp(n.startScale*(i/n.startDist)))},o=n=>{let s=t.current;s&&(s$(n.touches,s.a)&&s$(n.touches,s.b)||e())};return document.addEventListener("touchstart",a,{passive:!0,capture:!0}),document.addEventListener("touchmove",i,{passive:!1,capture:!0}),document.addEventListener("touchend",o,{passive:!0,capture:!0}),document.addEventListener("touchcancel",o,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",a,{capture:!0}),document.removeEventListener("touchmove",i,{capture:!0}),document.removeEventListener("touchend",o,{capture:!0}),document.removeEventListener("touchcancel",o,{capture:!0}),null!==s.current&&cancelAnimationFrame(s.current)}},[r]),1===e)?null:(0,o.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,o.jsxs)("span",{children:["UI ",Math.round(100*e),"%"]}),(0,o.jsx)("button",{type:"button",onClick:a,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var sS=l;class sE extends sS.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,e,t.componentStack)}componentDidUpdate(e){this.state.error&&e.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:e}=this.state;return e?(0,o.jsx)("div",{role:"alert",className:"flex h-full w-full items-center justify-center p-6 text-center text-sm text-amber-300",children:(0,o.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",e.message,". The file on disk is unchanged — correct it in the panel, in the file, or with the agent that wrote it."]})}):this.props.children}}function sC({size:e=16}){return(0,o.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,o.jsx)("path",{d:"M12 10v4.5"}),(0,o.jsx)("path",{d:"M12 17.3v.01"})]})}function sM({locked:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,o.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,o.jsx)("path",{d:e?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function s_(e){let{onClose:t,restVh:n,tallVh:s}=e,[r,a]=(0,l.useState)(!1),[i,o]=(0,l.useState)(null),c=(0,l.useRef)(null),d=()=>{a(!1),t()},h=e=>{let t=c.current;if(!t||t.id!==e.pointerId)return;c.current=null;let n=e.clientY-t.y;if(o(null),6>Math.abs(n))return a(e=>!e);if(n<=-50)return a(!0);if(n>=80){if(r&&n<260)return a(!1);d()}},m=r?s:n,u=null!==i;return{zoneProps:{onPointerDown:e=>{e.target.closest("button")||(c.current={y:e.clientY,id:e.pointerId},e.currentTarget.setPointerCapture(e.pointerId),o(0))},onPointerMove:e=>{let t=c.current;t&&t.id===e.pointerId&&o(e.clientY-t.y)},onPointerUp:h,onPointerCancel:h,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":u&&i<0?`min(calc(${m}dvh + ${-i}px), ${s}dvh)`:`${m}dvh`,...u?{transition:"none"}:{},...u&&i>0?{transform:`translateY(${i}px)`}:{}},close:d}}let sA="stateloom:focus",sO="stateloom:focus-request",sR="stateloom:system-changed",sP="stateloom:strip-note";function sT(e){return new URLSearchParams(window.location.search).get(e)}function sI(e){let[t,n]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let t=()=>n(sT(e));t();let s=["popstate",sn.DOC_CHANGE_EVENT,sA,sO];for(let e of s)window.addEventListener(e,t);return()=>{for(let e of s)window.removeEventListener(e,t)}},[e]),t}function sL(e){let t=new URL(window.location.href),n=t.searchParams.get("doc")!==e.doc;t.searchParams.set("doc",e.doc);let s=void 0===e.system?t.searchParams.get("system"):e.system;s?t.searchParams.set("system",s):t.searchParams.delete("system"),e.focus?t.searchParams.set("focus",e.focus):t.searchParams.delete("focus"),n?window.history.pushState({},"",t):window.history.replaceState(window.history.state,"",t),n&&window.dispatchEvent(new Event(sn.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(sO))}function sD(e){let t=new URL(window.location.href);(t.searchParams.get("focus")??null)!==e&&(e?t.searchParams.set("focus",e):t.searchParams.delete("focus"),window.history.replaceState(window.history.state,"",t),window.dispatchEvent(new CustomEvent(sA)))}function sq(){let[e,t]=(0,l.useState)({focus:null,nonce:0});return(0,l.useEffect)(()=>{let e=()=>t(e=>({focus:sT("focus"),nonce:e.nonce+1}));e();let n=["popstate",sn.DOC_CHANGE_EVENT,sO];for(let t of n)window.addEventListener(t,e);return()=>{for(let t of n)window.removeEventListener(t,e)}},[]),e}function sB(e,t,n){try{return e()}catch(s){let e=s instanceof Error?s.message:String(s);return console.warn("[stateloom] skipped on a malformed document:",e),n?.(e),t}}let sF=(e,t)=>"chen"===t?`stateloom:erd-layout:chen:${e}`:`stateloom:erd-layout:${e}`,sY="stateloom:erd-notation",sz="stateloom:erd-lock";function sU(e,t){try{return JSON.parse(localStorage.getItem(sF(e,t))??"{}")}catch{return{}}}async function sX(e){let t=e.slice(0,e.lastIndexOf("/")),n=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(e=>e.path).filter(e=>e.endsWith(".smdf.json")&&e.slice(0,e.lastIndexOf("/"))===t),s=[];for(let e of n)try{let t=await (await fetch(`/api/file${(0,sn.docQuery)(e)}`,{cache:"no-store"})).json(),n=JSON.parse(t.content??"null"),r=n?.stateMachine??n?.StateMachine??n;r?.state&&s.push({path:e,def:r})}catch{}return s}let sH="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",sJ="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",sV="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function sW(){let e=(0,sn.useRequestedDoc)(),[t,n]=(0,l.useState)(""),[s,r]=(0,l.useState)(null),[a,i]=(0,l.useState)({}),[c,d]=(0,l.useState)("crowsfoot"),[h,m]=(0,l.useState)(!1),[u,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("entities"),[S,E]=(0,l.useState)(!1),[C,M]=(0,l.useState)(!1),[_,A]=(0,l.useState)(!1),O=(0,l.useRef)(null),R=s_({onClose:()=>E(!1),restVh:62,tallVh:92}),[P,T]=(0,l.useState)(0),[I,L]=(0,l.useState)(null),D=(0,l.useRef)(null);(0,l.useEffect)(()=>{let t=!1,s=null;return(async()=>{let a=await (await fetch(`/api/file${(0,sn.docQuery)(e)}`,{cache:"no-store"})).json();if(t)return;if(a.error)return w(a.error,"warn");let o=a.path??"",l=null;try{let e=a.content?JSON.parse(a.content):null;W(e)&&(l={...e,relationships:e.relationships??[]})}catch{}if(a.exists&&!l)return w(`${o} is not a readable ERD definition`,"warn");let c=(o.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),h=function(){try{return"chen"===localStorage.getItem(sY)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();n(o),r(l??{settings:{namespace:"Default",name:c},entities:[],relationships:[]}),d(h),m(function(){try{let e=localStorage.getItem(sz);if(null!==e)return"1"===e;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),i(sU(o,h)),y(null),L(null),g(e=>e+1),w(a.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:u}=await sh();!t&&u&&(D.current=s=nI({url:u,role:"web",docId:o,name:"web-designer",onFull:e=>{let t=e.def;W(t)&&(r({...t,relationships:t.relationships??[]}),w("updated live"))},onPatch:()=>{},onPresence:e=>T(e.length)}),s.connect())})().catch(e=>!t&&w(String(e),"warn")),()=>{t=!0,D.current=null,s?.disconnect()}},[e,w]);let B=(0,l.useMemo)(()=>{if(!s)return{};let e=sB(()=>(function(e,t={}){let n=t.notation??"crowsfoot",s=t.hSpacing??70,r=t.vSpacing??("chen"===n?130:90),a="chen"===n?ec:eg,i=[],o=new Set;for(let t of e.entities??[])!t?.name||o.has(t.name)||(o.add(t.name),i.push(t));let l=new Map,c=(e,t,n=new Set)=>e===t||!n.has(e)&&(n.add(e),(l.get(e)??[]).some(e=>c(e,t,n)));for(let t of e.relationships??[]){if(!t||!o.has(t.from)||!o.has(t.to)||t.from===t.to)continue;let[e,n]="N:1"===t.cardinality?[t.to,t.from]:[t.from,t.to];if((l.get(e)??[]).includes(n)||c(n,e))continue;let s=l.get(e);s?s.push(n):l.set(e,[n])}let d=new Map,h=(e,t)=>{if(!((d.get(e)??-1)>=t))for(let n of(d.set(e,t),l.get(e)??[]))h(n,t+1)},m=new Set([...l.values()].flat());for(let e of i)m.has(e.name)||h(e.name,0);for(let e of i)d.has(e.name)||h(e.name,0);for(let e of[...i].sort((e,t)=>d.get(t.name)-d.get(e.name))){let t=l.get(e.name)??[];t.length&&d.set(e.name,Math.min(...t.map(e=>d.get(e)))-1)}let u=[],p=new Map,f=(e,t)=>((u[t]??=[]).push(e),p.set(e.id,e),e);for(let e of i)f({id:e.name,entity:e.name,...a(e),upper:[],lower:[],x:0},d.get(e.name)??0);let g=0;for(let[e,t]of l)for(let n of t){let t=e;for(let s=d.get(e)+1;s<d.get(n);s++){let e=f({id:`\u0000lane${g++}`,width:28,height:0,upper:[],lower:[],x:0},s);p.get(t).lower.push(e.id),e.upper.push(t),t=e.id}p.get(t).lower.push(n),p.get(n).upper.push(t)}for(let e=u.length-1;e>=0;e--)u[e]?.length||u.splice(e,1);let x=(e,t)=>e.length?e.reduce((e,n)=>e+t(p.get(n)),0)/e.length:null,y=(e,t)=>{let n=new Map;for(let e of u)e.forEach((e,t)=>n.set(e.id,t));let s=new Map(e.map((e,s)=>[e.id,x(e[t],e=>n.get(e.id))??s]));e.sort((e,t)=>s.get(e.id)-s.get(t.id))};for(let e=0;e<2;e++){for(let e=1;e<u.length;e++)y(u[e],"upper");for(let e=u.length-2;e>=0;e--)y(u[e],"lower")}let b=e=>e.x+e.width/2,v=(e,t)=>{let n=0;for(let r of e){let e=x(r[t],b);r.x=Math.max(n,null===e?n:e-r.width/2),n=r.x+r.width+s}};for(let e of u)v(e,"upper");for(let e=u.length-2;e>=0;e--)v(u[e],"lower");let w=Math.min(0,...[...p.values()].map(e=>e.x)),j={},k=40;for(let e of u){for(let t of e)t.entity&&(j[t.entity]={x:Math.round(t.x-w)+40,y:k,width:t.width,height:t.height});k+=Math.max(0,...e.map(e=>e.height))+r}return j})(s,{notation:c}),{});for(let[t,n]of Object.entries(a))e[t]&&(e[t]={...e[t],...n});return e},[s,a,c]),F=(0,l.useMemo)(()=>{if(!s)return[];let e="";return sB(()=>K(s),null,t=>e=t)??[{ruleId:"E000",message:`The document could not be checked (${e}): a field is not the shape Spec 80 gives it`}]},[s]),z=(0,l.useMemo)(()=>F.map(e=>(e.element??"").split(/[.[]/)[0]).filter(Boolean),[F]),X=(0,l.useCallback)(async e=>{let n;if(s&&t){try{n=e(s)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}r(n),L(null);try{let e=await fetch(`/api/file${(0,sn.docQuery)(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(n,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);D.current?.emitFull(n),w("saved")}catch(e){w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}}},[s,t,w]),H=(0,l.useCallback)((e,n)=>{i(s=>{let r={...s,[e]:{x:Math.round(n.x),y:Math.round(n.y)}};try{localStorage.setItem(sF(t,c),JSON.stringify(r))}catch{}return r})},[t,c]),Z=()=>{i({});try{localStorage.removeItem(sF(t,c))}catch{}g(e=>e+1)},ea=async()=>{if(!s)return;w("checking links…");let e=await sX(t);if(0===e.length)return L("none"),N("issues"),E(!0),w("no .smdf.json beside this document to check against","warn");let n=e.flatMap(e=>G(e.def,s).map(t=>({...t,message:`${e.def.settings?.name??e.path}: ${t.message}`})));n.push(...Q(s,e.map(e=>e.def.settings?.name??""))),L(n),N("issues"),E(!0),A(!1),w(`checked ${e.length} machine(s): ${n.length} problem(s)`,n.length?"warn":"ok")},ei=async e=>{let n=(await sX(t)).find(t=>t.def.settings?.name===e);n?(0,sn.navigateToDoc)(n.path):w(`no .smdf.json beside this document defines '${e}'`,"warn")},eo=()=>{let e=O.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},el=e=>{let{width:t,height:n}=eo();p(s=>Y(s,e,{x:t/2,y:n/2}))},eh=e=>{let t=B[e],{width:n,height:s}=eo();t&&n&&(p(U([t],n,s,{padding:28,maxScale:1.25})),y(e),R.close())},ef=sq(),ex=(0,l.useRef)(-1);(0,l.useEffect)(()=>{if(!s||ex.current===ef.nonce)return;ex.current=ef.nonce;let e=ef.focus?e6(ef.focus):null,t=e?.kind==="entity"?e.name:e?.kind==="attribute"?e.name.split(".")[0]:null;t&&B[t]&&eh(t)},[s,ef,B]),(0,l.useEffect)(()=>{x&&!sT("focus")?.startsWith(`attribute:${x}.`)&&sD(`entity:${x}`)},[x]);let ey=s?.entities.find(e=>e.name===x)??null,eb=t.split("/").pop()||"…",ev=Array.isArray(I)?I:[],ew=F.length+ev.length,ej=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,o.jsx)(sC,{}),badge:ew||void 0}],ek=e=>$===e?"":"hidden md:block",e$=()=>{s&&navigator.clipboard?.writeText(function(e){let t=["erDiagram"],n=" ",s=new Set;for(let r of e.relationships??[]){if(!r?.from||!r?.to)continue;let e=ed[r.cardinality]??ed["1:N"];t.push(`${n}${em(r.from)} ${e} ${em(r.to)} : ${ep(r.label??"")}`),s.add(r.from),s.add(r.to)}let r=new Set;for(let a of e.entities??[]){if(!a?.name||r.has(a.name))continue;r.add(a.name);let e=(a.attributes??[]).filter(e=>e?.name);if(0===e.length){s.has(a.name)||t.push(`${n}${em(a.name)}`);continue}for(let s of(t.push(`${n}${em(a.name)} {`),e))t.push(`${n}${n}${function(e){let t=[];"pk"===e.key&&t.push("PK"),"uk"===e.key&&t.push("UK"),e.references&&t.push("FK");let n=[],s=J(e);s.length&&n.push(`stateOf ${s.join(", ")}`),e.description&&n.push(e.description);let r=[eu(e.type??"","unknown"),eu(e.name,"unnamed")];return t.length&&r.push(t.join(", ")),n.length&&r.push(ep(n.join(" — "))),r.join(" ")}(s)}`);t.push(`${n}}`)}return t.join("\n")}(s)).then(()=>w("mermaid copied"))};return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&M(!1),children:[(0,o.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,o.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,o.jsx)(ss,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:t,children:[s?.settings.name??eb,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",eb]})]}),(0,o.jsx)("span",{className:"inline-flex shrink-0 overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Notation",children:[["crowsfoot","▤","Crow's foot — attributes listed inside the entity box"],["chen","◇","Chen — attributes as ovals, relationships as diamonds"]].map(([e,n,s])=>(0,o.jsx)("button",{title:s,"aria-label":s,"aria-pressed":c===e,onClick:()=>(e=>{if(e!==c){try{localStorage.setItem(sY,e)}catch{}d(e),i(sU(t,e)),g(e=>e+1)}})(e),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${c===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:n},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:sJ,onClick:Z,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,o.jsx)("button",{className:sJ,onClick:ea,title:"Check the state machines beside this document against it",children:"Check links"}),(0,o.jsx)("button",{className:sJ,onClick:e$,children:"Copy mermaid"}),(0,o.jsx)("button",{className:sJ,onClick:()=>A(e=>!e),"aria-pressed":!_,title:_?"Show the panel":"Hide the panel — the board takes the full width",children:_?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:e=>{e.stopPropagation(),M(e=>!e)},children:"⋯"}),C&&(0,o.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:[["⤢ Arrange the board",Z],["Check links to the machines",ea],["Copy as mermaid",e$]].map(([e,t])=>(0,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{M(!1),t()},children:e},e))})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:O,className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&(0,o.jsx)(sE,{what:"diagram",resetKey:s,children:(0,o.jsx)(tb,{definition:s,notation:c,positions:B,viewport:u,onViewportChange:p,selection:x,readOnly:h,errorElements:z,fitKey:f,onSelect:y,onClearSelection:()=>y(null),onEntityMove:H,onOpenMachine:ei,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),(0,o.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===b.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,P>1?` \xb7 ${P} in the room`:""]})]}),(0,o.jsxs)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[(0,o.jsx)("button",{title:h?"Shapes are locked: dragging moves the view. Tap to unlock.":"Lock the shapes in place, so dragging only moves the view","aria-label":"Lock shapes in place","aria-pressed":h,onClick:()=>{let e=!h;m(e);try{localStorage.setItem(sz,e?"1":"0")}catch{}w(e?"shapes locked — a drag anywhere moves the view":"shapes unlocked — drag one to move it")},className:`flex h-10 w-10 items-center justify-center border-b border-gray-800 hover:bg-gray-800 md:h-8 md:w-8 ${h?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,o.jsx)(sM,{locked:h})}),[["+","Zoom in",()=>el(1.25)],["−","Zoom out",()=>el(.8)],["⛶","Fit the whole diagram",()=>g(e=>e+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:e},t))]}),ey&&!S&&(0,o.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{N("entities"),E(!0)},children:["✎ ",ey.name]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:R.close,"aria-hidden":"true"}),s&&(0,o.jsxs)("aside",{style:R.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${S?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${_?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...R.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:ej.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:R.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:ek("entities"),children:[(0,o.jsx)("div",{className:sV,style:{marginTop:0},children:"Entities"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.map(e=>(0,o.jsx)("button",{className:`${sJ} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))}),(0,o.jsx)(sZ,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:e=>{X(t=>es(t,{name:e.name.trim()})),y(e.name.trim())}}),ey&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${sV} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ey.name}),(0,o.jsx)("button",{className:`${sJ} normal-case tracking-normal`,onClick:()=>eh(ey.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,o.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] text-gray-400",title:"Exists only through another entity (an order line, without its order). Chen draws it as a double rectangle.",children:[(0,o.jsx)("input",{type:"checkbox",checked:!!ey.weak,onChange:e=>X(t=>er(t,ey.name,{weak:e.target.checked}))}),"weak entity"]}),(ey.attributes??[]).map(e=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,o.jsxs)("span",{className:e.stateOf?"text-blue-300":"text-gray-300",children:[e.name," : ",e.type,(0,o.jsxs)("span",{className:"text-gray-500",children:[e.key?` ${e.key.toUpperCase()}`:"",e.references?` → ${e.references}`:"",e.stateOf?` ◉ ${[e.stateOf].flat().join(", ")}`:""]})]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${e.name}`,onClick:()=>X(t=>(function(e,t,n){let s=ee(e),r=et(s,t),a=r.attributes?.length??0;if(r.attributes=(r.attributes??[]).filter(e=>e.name!==n),r.attributes.length===a)throw Error(`Attribute '${t}.${n}' not found.`);return s})(t,ey.name,e.name)),children:"✕"})]},e.name)),(0,o.jsx)(sZ,{fields:[{name:"name",placeholder:"attribute"},{name:"type",placeholder:"type",initial:"string"},{name:"key",options:["","pk","uk"]},{name:"references",placeholder:"references Entity.attr"},{name:"stateOf",placeholder:"stateOf Machine"}],submit:"+ Attribute",onSubmit:e=>X(t=>(function(e,t,n){if(!n.name?.trim())throw Error("An attribute needs a name.");let s=ee(e),r=et(s,t);if(r.attributes??=[],r.attributes.some(e=>e.name===n.name))throw Error(`Attribute '${t}.${n.name}' already exists.`);return r.attributes.push(en({...n})),s})(t,ey.name,{name:e.name.trim(),type:e.type.trim()||"string",key:"pk"===e.key||"uk"===e.key?e.key:void 0,references:e.references.trim()||void 0,stateOf:e.stateOf.trim()||void 0}))}),(0,o.jsxs)("button",{className:`${sJ} mt-2 text-red-300`,onClick:()=>{X(e=>{var t;let n;return t=ey.name,et(n=ee(e),t),n.entities=n.entities.filter(e=>e.name!==t),n.relationships=n.relationships.filter(e=>e.from!==t&&e.to!==t),n}),y(null)},children:["🗑 Delete ",ey.name]})]})]}),(0,o.jsxs)("section",{className:ek("relations"),children:[(0,o.jsx)("div",{className:`${sV} max-md:mt-0`,children:"Relationships"}),0===s.relationships.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),s.relationships.map((e,t)=>(0,o.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,o.jsxs)("span",{children:[e.from," ",(0,o.jsx)("span",{className:"text-gray-500",children:e.cardinality})," ",e.to,e.label?(0,o.jsxs)("span",{className:"text-gray-500",children:[" : ",e.label]}):null]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>X(t=>(function(e,t,n,s){let r=ee(e),a=r.relationships.length;if(r.relationships=r.relationships.filter(e=>e.from!==t||e.to!==n||void 0!==s&&e.label!==s),r.relationships.length===a)throw Error(`No relationship from '${t}' to '${n}'${void 0===s?"":` labelled '${s}'`}.`);return r})(t,e.from,e.to,e.label)),children:"✕"})]},t)),s.entities.length>0&&(0,o.jsx)(sZ,{fields:[{name:"from",options:s.entities.map(e=>e.name)},{name:"cardinality",options:[...V],initial:"1:N"},{name:"to",options:s.entities.map(e=>e.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:e=>X(t=>(function(e,t){let n=ee(e);if(et(n,t.from),et(n,t.to),!V.includes(t.cardinality))throw Error(`Cardinality '${t.cardinality}' is not one of ${V.join(", ")}.`);return n.relationships.push(en({...t})),n})(t,{from:e.from,to:e.to,cardinality:e.cardinality,label:e.label.trim()||void 0}))})]}),(0,o.jsxs)("section",{className:ek("notes"),children:[(0,o.jsx)("div",{className:`${sV} max-md:mt-0`,children:"Notes"}),(0,o.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent (it reads them with get_notes)."}),(0,o.jsx)(sK,{label:"On this diagram",value:s.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>X(t=>(function(e,t){let n=ee(e);for(let e of["description","notes"]){let s=t[e];void 0!==s&&(s.trim()?n.settings[e]=s:delete n.settings[e])}return n})(t,{notes:e}))},"diagram"),ey?(0,o.jsx)(sK,{label:`On ${ey.name}`,value:ey.notes??"",placeholder:`A question or a decision about ${ey.name}…`,onSave:e=>X(t=>er(t,ey.name,{notes:e}))},`entity:${ey.name}`):(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),s.entities.some(e=>e.notes?.trim())&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:sV,children:"Entities with notes"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:`${sJ} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))})]})]}),(0,o.jsxs)("section",{className:ek("issues"),children:[(0,o.jsx)("div",{className:`${sV} max-md:mt-0 ${0===ew&&!I?"md:hidden":""}`,children:"Issues"}),F.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ev.map((e,t)=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",e.ruleId,"] ",e.message]},`l${t}`)),"none"===I&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-amber-300",children:"No state machine (.smdf.json) sits beside this document, so there was nothing to check it against."}),0===ew&&"none"!==I&&(0,o.jsx)("div",{className:`py-0.5 text-[11px] ${I?"text-green-400":"text-gray-600 md:hidden"}`,children:I?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,o.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:ej.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?R.close():E(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function sK({label:e,value:t,placeholder:n,onSave:s}){let[r,a]=(0,l.useState)(t),[i,c]=(0,l.useState)(t),[d,h]=(0,l.useState)(!1);t!==i&&(c(t),d||a(t));let m=(0,l.useRef)(null),u=e=>{m.current&&clearTimeout(m.current),m.current=null,e!==t&&s(e)};return(0,o.jsxs)("label",{className:"mt-2 block",children:[(0,o.jsx)("span",{className:"text-[11px] text-gray-500",children:e}),(0,o.jsx)("textarea",{className:`${sH} h-24 resize-y leading-snug`,placeholder:n,value:r,onChange:e=>{let t=e.target.value;a(t),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>u(t),900)},onFocus:()=>h(!0),onBlur:()=>{h(!1),u(r)}})]})}function sZ({fields:e,submit:t,onSubmit:n}){let s=()=>Object.fromEntries(e.map(e=>[e.name,e.initial??e.options?.[0]??""])),[r,a]=(0,l.useState)(s),i=e[0];return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:t=>{t.preventDefault();let o={...s(),...r};o[i.name]?.trim()&&(n(o),a(t=>Object.fromEntries(e.map(e=>[e.name,e.options?t[e.name]??"":e.initial??""]))))},children:[e.map(e=>e.options?(0,o.jsx)("select",{className:sH,"aria-label":e.name,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value})),children:e.options.map(t=>(0,o.jsx)("option",{value:t,children:t||`(${e.name})`},t))},e.name):(0,o.jsx)("input",{className:sH,"aria-label":e.name,placeholder:e.placeholder,value:r[e.name]??"",onChange:t=>a(n=>({...n,[e.name]:t.target.value}))},e.name)),(0,o.jsx)("button",{type:"submit",className:`${sJ} ${1===e.length?"":"col-span-2"}`,children:t})]})}let sG="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",sQ="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",s0="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function s1({id:e,fields:t,submit:n,onSubmit:s,reset:r=!1,required:a}){let i=()=>Object.fromEntries(t.map(e=>[e.name,e.initial??(!e.checkbox&&(e.options?e.options[0]??"":""))])),[c,d]=(0,l.useState)(i),h=(e,t)=>d(n=>({...n,[e]:t}));return(0,o.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:e=>{e.preventDefault();let n={...i(),...c};!(a??[]).some(e=>!String(n[e]??"").trim())&&(s(n),r&&d(e=>Object.fromEntries(t.map(t=>[t.name,t.options||t.checkbox?e[t.name]??"":t.initial??""]))))},children:[t.map(t=>{let n=t.label??t.name;if(t.checkbox)return(0,o.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,o.jsx)("input",{type:"checkbox",checked:!!c[t.name],onChange:e=>h(t.name,e.target.checked)}),n]},t.name);if(t.options)return(0,o.jsx)("select",{className:`${sG} ${t.wide?"col-span-2":""}`,"aria-label":n,title:n,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value),children:t.options.map(e=>(0,o.jsx)("option",{value:e,children:e||`(${n})`},e))},t.name);let s=t.suggest?.length?`${e}-${t.name}`:void 0;return(0,o.jsxs)("span",{className:t.wide?"col-span-2":"",children:[(0,o.jsx)("input",{className:sG,"aria-label":n,title:n,placeholder:t.placeholder??n,list:s,value:String(c[t.name]??""),onChange:e=>h(t.name,e.target.value)}),s&&(0,o.jsx)("datalist",{id:s,children:t.suggest.map(e=>(0,o.jsx)("option",{value:e},e))})]},t.name)}),(0,o.jsx)("button",{type:"submit",className:`${sQ} col-span-2`,children:n})]})}function s2({kind:e,size:t=16}){return(0,o.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,o.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,o.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,o.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,o.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,o.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,o.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1.2 1.2"}),(0,o.jsx)("path",{d:"M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.2-1.2"})]}),"actor"===e&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,o.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}async function s5(e){try{let t=await fetch(`/api/file${(0,sn.docQuery)(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||n.error)return{path:e??"",content:null,exists:!1,error:n.error??`HTTP ${t.status}`};return{path:n.path??e??"",content:n.content??null,exists:!!n.exists,mtime:n.mtime}}catch(t){return{path:e??"",content:null,exists:!1,error:t instanceof Error?t.message:String(t)}}}class s4 extends Error{constructor(e){super(`${e.split("/").pop()} changed on disk since it was read`)}}async function s3(e,t,n){let s=await fetch(`/api/file${(0,sn.docQuery)(e)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n",...void 0!==n?{mtime:n}:{}})}),r=await s.json().catch(()=>({}));if(409===s.status)throw new s4(e);if(!s.ok)throw Error(r?.error??`HTTP ${s.status}`);return r?.mtime}async function s6(e){let t=await s5(e),n={path:t.path||e,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(t.error)return{...n,error:t.error};if(!t.exists||!t.content)return{...n,error:`${e} does not exist`};let s=null;try{let e=JSON.parse(t.content);eF(e)&&(s=e)}catch{}if(!s)return{...n,error:`${t.path} is not a readable system definition`};let r={},a={},i={[t.path]:t.mtime??0},o=await Promise.all((s.members??[]).filter(e=>e?.path).map(async e=>{let n=eX(t.path,e.path);r[e.path]=n;let s=eY(e.path),o=await s5(n);if(o.error)return{path:e.path,kind:s,def:null,error:o.error};if(!o.exists||!o.content)return{path:e.path,kind:s,def:null,error:"the file does not exist"};i[e.path]=o.mtime??0;try{let t=JSON.parse(o.content);if("machine"===s&&t&&(t.stateMachine||t.StateMachine))return a[e.path]=!0,{path:e.path,kind:s,def:t.stateMachine??t.StateMachine};return{path:e.path,kind:s,def:t}}catch(t){return{path:e.path,kind:s,def:null,error:`not JSON: ${t instanceof Error?t.message:String(t)}`}}}));return{path:t.path,def:s,members:o,absOf:r,wrapped:a,mtimes:i}}function s8(){window.dispatchEvent(new Event(sR))}function s7(e){let[t,n]=(0,l.useState)(null),[s,r]=(0,l.useState)(0),a=(0,l.useCallback)(()=>r(e=>e+1),[]);return(0,l.useEffect)(()=>(window.addEventListener(sR,a),()=>window.removeEventListener(sR,a)),[a]),(0,l.useEffect)(()=>{if(!e)return;let t=!0;return s6(e).then(s=>t&&n({for:e,system:s})),()=>{t=!1}},[e,s]),{system:e&&t?.for===e?t.system:null,reload:a}}function s9(e,t){if(!e||!t)return null;for(let[n,s]of Object.entries(e.absOf))if(s===t)return n;return null}async function re(e,t,n,s){let{bridgeUrl:r}=await sh();if(!r)return;let a=nP({url:r,role:"web",docId:e,name:"web-reconcile",autoResync:!1});try{let e=await Promise.race([a.join(),new Promise((e,t)=>setTimeout(()=>t(Error("join timeout")),3e3))]),r=e.snapshot?.def,i=e=>(function(e){let t=JSON.stringify(e),n=0x811c9dc5;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,0x1000193);return(n>>>0).toString(16).padStart(8,"0")})(e);if(r&&i(r)===i(t))return;await new Promise(e=>{let o=a.on("ack",()=>{o(),e()});s&&r&&i(r)===i(s.from)?a.emitPatch(s.ops,n):a.emitFull(t,n),setTimeout(e,800)})}catch{}finally{a.disconnect()}}async function rt(e,t){let n=[],s=[],r=[],a=async(e,t)=>{try{await t(),n.push(e)}catch(t){t instanceof s4?r.push(e):s.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}};for(let n of t.machines){let t=e.absOf[n.member];t&&n.ops.length&&await a(n.member,async()=>{let s=e.wrapped[n.member]?{stateMachine:n.def}:n.def,r=await s3(t,s,e.mtimes[n.member]),a=e.members.find(e=>e.path===n.member)?.def;await re(t,n.def,r,{from:a,ops:n.ops})})}for(let n of t.erds){let t=e.absOf[n.member];t&&await a(n.member,async()=>{let s=await s3(t,n.def,e.mtimes[n.member]);await re(t,n.def,s)})}return t.system&&await a(e.path.split("/").pop()??e.path,async()=>{let n=await s3(e.path,t.system.def,e.mtimes[e.path]);await re(e.path,t.system.def,n)}),s8(),{written:n,failed:s,conflicts:r}}async function rn(e){let t={result:null,written:[],failed:[],conflicts:[]};for(let n=0;n<2;n+=1){let s=await s6(e);if(!s.def)return{...t,failed:[s.error??"the system could not be read"],retried:n>0};let r=tt(s.def,s.members);if(!r.count)return{...t,result:r,conflicts:n?t.conflicts:[],retried:n>0};let a=await rt(s,r);if(t={result:r,written:[...t.written,...a.written],failed:a.failed,conflicts:a.conflicts},!a.conflicts.length)return{...t,retried:n>0}}return{...t,retried:!0}}let rs=["","actor","service","object"],rr=e=>"string"==typeof e?e.trim():"",ra=e=>rr(e).split(",").map(e=>e.trim()).filter(Boolean);function ri(e){return{from:rr(e.from),to:rr(e.to),label:rr(e.label),event:rr(e.event),machine:rr(e.machine),carries:rr(e.carries),state:rr(e.state),description:rr(e.description),optional:!!e.optional||void 0,reply:!!e.reply||void 0}}function ro(){let e,t,n,s=(0,sn.useRequestedDoc)(),r=sI("system"),{system:a}=s7(r),i=sq(),[c,d]=(0,l.useState)(""),[h,m]=(0,l.useState)(null),[u,p]=(0,l.useState)({...q}),[f,g]=(0,l.useState)(void 0),[x,y]=(0,l.useState)(null),[b,v]=(0,l.useState)({text:"loading…",tone:"ok"}),w=(0,l.useCallback)((e,t="ok")=>v({text:e,tone:t}),[]),[j,k]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,l.useState)("messages"),[S,E]=(0,l.useState)(!1),[C,M]=(0,l.useState)(!1),[_,A]=(0,l.useState)(!1),O=(0,l.useRef)(null),R=s_({onClose:()=>E(!1),restVh:62,tallVh:92}),[P,T]=(0,l.useState)(0),I=(0,l.useRef)(null),L=(0,l.useRef)(!0),D=(0,l.useRef)(-1);(0,l.useEffect)(()=>{let e=!1,t=null;return(async()=>{let n=await (await fetch(`/api/file${(0,sn.docQuery)(s)}`,{cache:"no-store"})).json();if(e)return;if(n.error)return w(n.error,"warn");let r=n.path??"",a=null;try{let e=n.content?JSON.parse(n.content):null;eb(e)&&(a=e)}catch{}if(n.exists&&!a)return w(`${r} is not a readable sequence definition`,"warn");let i=(r.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");d(r),m(a??ev("Default",i)),w(n.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:o}=await sh();!e&&o&&(I.current=t=nI({url:o,role:"web",docId:r,name:"web-designer",onFull:e=>{let t=e.def;eb(t)&&(m(t),w("updated live"))},onPatch:()=>{},onPresence:e=>T(e.length)}),t.connect())})().catch(t=>!e&&w(String(t),"warn")),()=>{e=!0,I.current=null,t?.disconnect()}},[s,w]);let F=(0,l.useMemo)(()=>h?tN(h):null,[h]),z=(0,l.useMemo)(()=>F?eT(F):null,[F]),X=(0,l.useMemo)(()=>{if(!h)return[];let e="";return sB(()=>e$(h),null,t=>e=t)??[{ruleId:"S000",message:`The document could not be checked (${e}): a field is not the shape Spec 81 gives it`}]},[h]),H=s9(a,c),J=(0,l.useMemo)(()=>a?.def&&H&&h?sB(()=>e4(a.def,a.members.map(e=>e.path===H?{...e,def:h,error:void 0}:e)),null):null,[a,H,h]),V=(0,l.useMemo)(()=>(J?.issues??[]).filter(e=>e.member===H&&!/^S0/.test(e.ruleId)),[J,H]),W=J?.replays.find(e=>e.member===H)?.report??null,K=(0,l.useMemo)(()=>(function(e){let t={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!e)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:n,erds:s}=e5(e.members);for(let{def:e}of(n.forEach(({def:e},n)=>{for(let s of(t.machines.add(eZ(e,n)),e.events??[]))for(let e of[...s?.events??[],...s?.timers??[]])e?.id&&t.events.add(e.id);for(let n of e.settings?.objects??[])n?.instance&&t.objects.add(n.instance);let s=e=>{e&&(t.states.add(e.name),(e.states??[]).forEach(s),(e.parallel?.states??[]).forEach(s))};s(e.state)}),s))for(let n of e.entities??[])n?.name&&t.entities.add(n.name);for(let n of e.def?.actors??[])n?.name&&t.actors.add(n.name);let r=e=>[...e].sort((e,t)=>e.localeCompare(t));return{events:r(t.events),states:r(t.states),machines:r(t.machines),objects:r(t.objects),entities:r(t.entities),actors:r(t.actors)}})(a),[a]),Z=(0,l.useMemo)(()=>{let e=e=>e?/^(message|participant):/.test(e)?e:F?.participants.some(t=>t.name===e)?`participant:${e}`:"":"";return[...X.map(t=>e(t.element)),...V.filter(e=>"error"===e.severity).map(t=>e(t.element))].filter(Boolean)},[X,V,F]),G=(0,l.useMemo)(()=>V.filter(e=>"warning"===e.severity).map(e=>e.element??""),[V]),Q=()=>{let e=O.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},ee=(0,l.useCallback)(e=>{let t=O.current?.getBoundingClientRect();if(!t?.width)return;let n=B(Math.max(U([e],t.width,t.height,{padding:24,maxScale:1.1}).scale,.7));p({scale:n,x:t.width/2-(e.x+e.width/2)*n,y:t.height/2-(e.y+e.height/2)*n})},[]),et=(0,l.useCallback)(e=>{if(z)if("message"===e.kind){let t=z.rows.find(t=>t.ref===e.id);if(!t)return;let n=t.self?t.fromX:Math.min(t.fromX,t.toX),s=t.self?220:Math.abs(t.toX-t.fromX);ee({x:n-10,y:t.y-24,width:s+20,height:40})}else{let t=z.participants.find(t=>t.name===e.id);t&&ee({x:t.left-20,y:t.top,width:t.width+40,height:Math.min(260,z.height-t.top)})}},[z,ee]),en=(0,l.useCallback)(e=>{y(e),e&&sD(`${e.kind}:${e.id}`)},[]);(0,l.useEffect)(()=>{if(!h||!z||D.current===i.nonce)return;D.current=i.nonce;let e=i.focus?e6(i.focus):null;if(!e)return;let t=null;if("message"===e.kind&&ej(F??h,e.name)&&(t={kind:"message",id:e.name}),"participant"===e.kind&&(F??h).participants.some(t=>t.name===e.name)&&(t={kind:"participant",id:e.name}),!t)return w(`${i.focus} is not in this sequence`,"warn");L.current=!1,y(t),et(t)},[h,F,z,i,et,w]),(0,l.useEffect)(()=>{if(!z||!L.current)return;let{width:e,height:t}=Q();e&&(L.current=!1,Math.min((e-32)/z.width,(t-32)/z.height)>=.5||0===z.participants.length?g(e=>(e??0)+1):p({x:8,y:8,scale:.6}))},[z]);let es=(0,l.useCallback)(async e=>{let t;if(h&&c){try{t=e(h)}catch(e){return w(e instanceof Error?e.message:String(e),"warn")}m(t);try{let e=await fetch(`/api/file${(0,sn.docQuery)(c)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n"})});if(!e.ok)throw Error((await e.json())?.error??`HTTP ${e.status}`);I.current?.emitFull(t),w("saved")}catch(e){return w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}if(a?.def&&H){if("auto"===eD(a.def)){let{result:e,failed:t,conflicts:s}=await rn(a.path);if(e&&e.count>0){var n;return void(n=t.length?`auto: not written — ${t[0]}`:s.length?`auto: ${s.join(", ")} kept changing on disk; not written — save again`:tn(e,"auto"),window.dispatchEvent(new CustomEvent(sP,{detail:{text:n,origin:void 0}})))}}s8()}}},[h,c,w,a,H]),er=e=>{let{width:t,height:n}=Q();p(s=>Y(s,e,{x:t/2,y:n/2}))},ea=()=>{let e,t,n,s,r,a,i,o,l;h&&navigator.clipboard?.writeText((e=["sequenceDiagram"],t=new Map,(h.participants??[]).forEach((n,s)=>{let r=`p${s+1}`;t.set(n.name,r),e.push(` ${n.actor?"actor":"participant"} ${r} as ${eI(n.name)}`)}),n=e=>t.get(e)??eI(e).replace(/\W+/g,"_"),s=(e,t,s)=>{let r=e.reply?"-->>":"->>",a=[`${t} ${eI(e.label??"")}`,e.event?eI(e.event):""].filter(Boolean).join(" · "),i=`${s}${n(e.from)}${r}${n(e.to)}: ${a}`;return e.optional?[`${s}opt optional`,` ${i}`,`${s}end`]:[i]},r=h.messages??[],a=h.fragments??[],i=e=>a.filter(t=>t?.after===e),o=(t,n)=>(t.messages??[]).forEach((r,i)=>e.push(...s(r,`f${a.indexOf(t)+1}.${i+1}`,n+" "))),(l=(t,n,a)=>{for(let c=t;c<=r.length;c++){let t=c===a?[]:i(c);for(let s of t.filter(e=>"alt"!==e.kind))e.push(`${n}${s.kind} ${eI(s.label??"")}`),o(s,n),e.push(`${n}end`);let d=t.filter(e=>"alt"===e.kind);if(d.length){d.forEach((t,s)=>{e.push(`${n}${0===s?"alt":"else"} ${eI(t.label??"")}`),o(t,n)}),c<r.length&&(e.push(`${n}else as written`),l(c,n+" ",c)),e.push(`${n}end`);return}c<r.length&&e.push(...s(r[c],String(c+1),n))}})(0," ",null),e.join("\n")+"\n")).then(()=>w("mermaid copied"))},ei=e=>{let t=e?e6(e):null;if(!t||"message"!==t.kind&&"participant"!==t.kind)return;let n={kind:t.kind,id:t.name};en(n),et(n),R.close()},eo=F??ev("",""),el=ek(eo),ec=h&&x?.kind==="message"?ej(eo,x.id):null,ed=h&&x?.kind==="participant"?eo.participants.find(e=>e.name===x.id)??null:null,eh=eo.participants.map(e=>e.name),em=c.split("/").pop()||"…",eu=X.length+V.filter(e=>"error"===e.severity).length,ep=V.filter(e=>"warning"===e.severity).length,ef=[{id:"participants",label:"Participants",icon:(0,o.jsx)(s2,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,o.jsx)(s2,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,o.jsx)(sC,{}),badge:eu+ep||void 0}],eg=e=>[{name:"from",label:"from",options:eh,initial:e?.from??eh[0]??""},{name:"to",label:"to",options:eh,initial:e?.to??eh[1]??eh[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:e?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:K.events,initial:e?.event??""},{name:"state",label:"state after",suggest:K.states,initial:e?.state??""},{name:"carries",label:"entity it carries",suggest:K.entities,initial:e?.carries??""},{name:"machine",label:"machine",suggest:K.machines,initial:e?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!e?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!e?.reply}],ex=e=>e.actor?"actor":e.object?"object":e.service?"service":"",ew=["main: at the end",...ec&&null===ec.fragment?[`main: after ${ec.index+1}`]:[],...(h?.fragments??[]).map((e,t)=>`fragment ${t+1}: ${e.kind} \xb7 ${e.label}`)];return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&M(!1),children:[(0,o.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(s2,{kind:"sequence",size:14}),"SEQ"]}),(0,o.jsx)(ss,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:c,children:[h?.settings.name??em,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",em]})]}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:sQ,onClick:ea,children:"Copy mermaid"}),(0,o.jsx)("button",{className:sQ,onClick:()=>A(e=>!e),"aria-pressed":!_,title:_?"Show the panel":"Hide the panel — the board takes the full width",children:_?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:e=>{e.stopPropagation(),M(e=>!e)},children:"⋯"}),C&&(0,o.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{M(!1),ea()},children:"Copy as mermaid"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:O,className:"relative min-w-0 flex-1 overflow-hidden",children:[h&&z&&(0,o.jsx)(sE,{what:"sequence",resetKey:h,children:(0,o.jsx)(tS,{definition:F,layout:z,viewport:u,onViewportChange:p,selection:x,errorElements:Z,warningElements:G,fitKey:f,onSelect:(e,t)=>en({kind:e,id:t}),onClearSelection:()=>y(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),(0,o.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===b.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,P>1?` \xb7 ${P} in the room`:""]})]}),(0,o.jsx)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[["+","Zoom in",()=>er(1.25)],["−","Zoom out",()=>er(.8)],["⛶","Fit the whole diagram",()=>g(e=>(e??0)+1)]].map(([e,t,n])=>(0,o.jsx)("button",{title:t,"aria-label":t,onClick:n,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:e},t))}),x&&!S&&(0,o.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{N("message"===x.kind?"messages":"participants"),E(!0)},children:["Edit ","message"===x.kind?`${x.id}. ${ec?.message.label??""}`:x.id]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:R.close,"aria-hidden":"true"}),h&&(0,o.jsxs)("aside",{style:R.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${S?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${_?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...R.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:ef.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:R.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:ef.map(e=>(0,o.jsxs)("button",{onClick:()=>N(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${$===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,o.jsxs)(sE,{what:"panel",resetKey:h,children:[(0,o.jsxs)("section",{className:"participants"===$?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Participants"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:eo.participants.map(e=>(0,o.jsxs)("button",{className:`${sQ} ${x?.kind==="participant"&&x.id===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{en({kind:"participant",id:e.name}),et({kind:"participant",id:e.name})},title:ex(e)||"participant",children:[e.name,ex(e)&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" · ",ex(e)]})]},e.name))}),(0,o.jsx)(s1,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:rs,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...K.actors,...K.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:K.entities}],submit:"+ Participant",onSubmit:e=>{let t=rr(e.name),n=rr(e.kind);es(s=>(function(e,t,n){if(!t.name?.trim())throw Error("A participant needs a name.");let s=eN(e);if(s.participants.some(e=>e.name===t.name))throw Error(`Participant '${t.name}' already exists.`);let r=s.participants.length;return s.participants.splice(r,0,eS({...t})),s})(s,{name:t,...n?{[n]:rr(e.value)||t}:{},holds:ra(e.holds)})),en({kind:"participant",id:t})}}),ed&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${s0} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ed.name}),(0,o.jsx)("button",{className:`${sQ} normal-case tracking-normal`,onClick:()=>et({kind:"participant",id:ed.name}),children:"◎ Show on board"})]}),(e=eo.participants.findIndex(e=>e.name===ed.name),t=eo.participants.length-1,n=e=>es(t=>{var n;let s,r;return n=ed.name,r=eE(s=eN(t),n),s.participants.splice(s.participants.indexOf(r),1),s.participants.splice(Math.max(0,Math.min(e,s.participants.length)),0,r),s}),(0,o.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,o.jsx)("button",{className:`${sQ} disabled:opacity-40`,disabled:e<=0,onClick:()=>n(e-1),"aria-label":"Move one column left",children:"← Left"}),(0,o.jsxs)("span",{className:"flex-1 text-center",children:["column ",e+1," of ",t+1]}),(0,o.jsx)("button",{className:`${sQ} disabled:opacity-40`,disabled:e>=t,onClick:()=>n(e+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,o.jsx)(s1,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:ed.name}],submit:"Rename (every message follows)",onSubmit:e=>{let t=rr(e.to);t!==ed.name&&(es(e=>(function(e,t,n){if(!n?.trim())throw Error("A participant needs a name.");let s=eN(e),r=eE(s,t);if(n===t)return s;if(s.participants.some(e=>e.name===n))throw Error(`Participant '${n}' already exists.`);r.name=n;let a=e=>{e.from===t&&(e.from=n),e.to===t&&(e.to=n)};for(let e of(s.messages.forEach(a),s.fragments??[]))e.messages.forEach(a);return s})(e,ed.name,t)),en({kind:"participant",id:t}))}},`rename:${ed.name}`),(0,o.jsx)(s1,{id:"edit-participant",fields:[{name:"kind",options:rs,label:"kind",initial:ex(ed)},{name:"value",placeholder:"actor / service / object",suggest:[...K.actors,...K.objects],initial:ed.actor??ed.object??ed.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:K.entities,initial:(ed.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:ed.description??"",wide:!0}],submit:"Save participant",onSubmit:e=>es(t=>{let n,s;return e_(t,ed.name,{...(n=rr(e.kind),s=rr(e.value)||ed.name,{actor:"actor"===n?s:"",service:"service"===n?s:"",object:"object"===n?s:""}),holds:ra(e.holds),description:rr(e.description)})})},`p:${JSON.stringify(ed)}`),(0,o.jsxs)("button",{className:`${sQ} mt-2 text-red-300`,onClick:()=>{es(e=>{var t;let n,s;return t=ed.name,eE(n=eN(e),t),n.participants=n.participants.filter(e=>e.name!==t),s=e=>e.from!==t&&e.to!==t,n.messages=n.messages.filter(s),n.fragments&&(n.fragments=n.fragments.map(t=>{let n;return{...t,after:Math.max(0,t.after-(n=t.after,e.messages.slice(0,n).filter(e=>!s(e)).length)),messages:t.messages.filter(s)}}).filter(e=>e.messages.length>0),n.fragments.length||delete n.fragments),n}),y(null),sD(null)},title:"Also removes every message it sends or receives",children:["Delete ",ed.name," and its messages"]})]})]}),(0,o.jsxs)("section",{className:"messages"===$?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Messages"}),0===el.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,o.jsx)("div",{className:"flex flex-col",children:el.map(({ref:e,message:t,fragment:n},s)=>{let r=null!==n&&(0===s||el[s-1].fragment!==n),a=null!==n?eo.fragments?.[n]:void 0,i=x?.kind==="message"&&x.id===e;return(0,o.jsxs)("div",{children:[r&&a&&(0,o.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,o.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.label]}),(0,o.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${i?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{en({kind:"message",id:e}),et({kind:"message",id:e})},title:`${t.from} → ${t.to}: ${t.label}`,children:[(0,o.jsxs)("span",{className:"text-gray-500",children:[e,"."]})," ",t.from," → ",t.to,": ",t.label,t.event?(0,o.jsxs)("span",{className:"text-blue-300",children:[" [",t.event,"]"]}):null,t.state?(0,o.jsxs)("span",{className:"text-emerald-400",children:[" → ",t.state]}):null,t.optional?(0,o.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},e)})}),ec&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${s0} flex items-center justify-between gap-2`,children:[(0,o.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",x.id]}),(0,o.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===ec.fragment&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{className:sQ,"aria-label":"Move up",title:"Move up",disabled:0===ec.index,onClick:()=>{es(e=>eR(e,ec.index,ec.index-1)),en({kind:"message",id:String(ec.index)})},children:"↑"}),(0,o.jsx)("button",{className:sQ,"aria-label":"Move down",title:"Move down",disabled:ec.index>=eo.messages.length-1,onClick:()=>{es(e=>eR(e,ec.index,ec.index+1)),en({kind:"message",id:String(ec.index+2)})},children:"↓"})]}),(0,o.jsx)("button",{className:sQ,onClick:()=>et(x),children:"◎ Show"})]})]}),(0,o.jsx)(s1,{id:"edit-message",required:["label"],fields:[...eg(ec.message),{name:"description",placeholder:"description",initial:ec.message.description??"",wide:!0}],submit:"Save message",onSubmit:e=>es(t=>eO(t,ec.index,ri(e),ec.fragment))},`m:${x.id}:${JSON.stringify(ec.message)}`),(0,o.jsxs)("button",{className:`${sQ} mt-2 text-red-300`,onClick:()=>{es(e=>(function(e,t,n=null){let s=eN(e);if(null!==n){let e=eM(s,n);if(!e.messages[t])throw Error(`Message ${t+1} not found in fragment ${n+1}.`);return e.messages.splice(t,1),s}if(!s.messages[t])throw Error(`Message ${t+1} not found. The sequence has ${s.messages.length}.`);if(s.messages.splice(t,1),s.fragments)for(let e of s.fragments)e.after>t&&(e.after-=1);return s})(e,ec.index,ec.fragment)),y(null),sD(null)},children:["Delete message ",x.id]})]}),(0,o.jsx)("div",{className:s0,children:"Add a message"}),(0,o.jsx)(s1,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:ew,label:"where",wide:!0},...eg()],submit:"+ Message",onSubmit:e=>{let t=rr(e.where),n=ri(e),s=/^fragment (\d+):/.exec(t),r=/^main: after (\d+)$/.exec(t);s?es(e=>{var t;let r,a,i;return t=Number(s[1])-1,a=eM(r=eN(e),t),eC(r,n),i=a.messages.length,a.messages.splice(i,0,eS({...n})),r}):r?es(e=>eA(e,n,Number(r[1]))):es(e=>eA(e,n))}},`add:${ew.join("|")}:${eh.join("|")}`),(0,o.jsx)("div",{className:s0,children:"Fragments"}),0===(eo.fragments??[]).length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(eo.fragments??[]).map((e,t)=>(0,o.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,o.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,o.jsxs)("span",{children:[t+1,". ",(0,o.jsx)("span",{className:"font-semibold",children:e.kind})," · after ",e.after," · ",e.messages.length," message(s)"]}),(0,o.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${t+1}`,onClick:()=>es(e=>{let n;return eM(n=eN(e),t),n.fragments.splice(t,1),n.fragments.length||delete n.fragments,n}),children:"✕"})]}),(0,o.jsx)(s1,{id:`edit-fragment-${t}`,fields:[{name:"kind",options:ey,initial:e.kind},{name:"after",placeholder:"after message",initial:String(e.after)},{name:"label",placeholder:"the condition, in words",initial:e.label,wide:!0}],submit:"Save fragment",onSubmit:e=>es(n=>(function(e,t,n){let s=eN(e),r=eM(s,t);if(void 0!==n.kind&&!ey.includes(n.kind))throw Error(`A fragment is one of ${ey.join(", ")}; got '${n.kind}'.`);if(void 0!==n.after&&(!Number.isInteger(n.after)||n.after<0||n.after>s.messages.length))throw Error(`A fragment branches after a main message, 0 to ${s.messages.length}; got ${n.after}.`);return s.fragments[t]={...eS({...r,...n,messages:void 0}),messages:r.messages??[]},s})(n,t,{kind:rr(e.kind),after:Number(rr(e.after)),label:rr(e.label)}))})]},`${t}:${JSON.stringify({...e,messages:void 0})}`)),(0,o.jsx)(s1,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:ey},{name:"after",placeholder:"after message",initial:String(ec&&null===ec.fragment?ec.index+1:eo.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:eh,label:"first message from"},{name:"to",options:eh,label:"to",initial:eh[1]??eh[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:e=>es(t=>(function(e,t){if(!ey.includes(t.kind))throw Error(`A fragment is one of ${ey.join(", ")}; got '${t.kind}'.`);if(!t.label?.trim())throw Error("A fragment needs a label: the condition in words.");let n=eN(e);if(!Number.isInteger(t.after)||t.after<0||t.after>n.messages.length)throw Error(`A fragment branches after a main message, 0 to ${n.messages.length}; got ${t.after}.`);for(let e of t.messages??[])eC(n,e);return(n.fragments??=[]).push({...eS({...t,messages:void 0}),messages:(t.messages??[]).map(e=>eS({...e}))}),n})(t,{kind:rr(e.kind),after:Number(rr(e.after)),label:rr(e.label),messages:rr(e.first)?[{from:rr(e.from),to:rr(e.to),label:rr(e.first)}]:[]}))},`add-fragment:${eo.messages.length}:${ec?.index??""}`)]}),(0,o.jsxs)("section",{className:"notes"===$?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Notes"}),(0,o.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent."}),(0,o.jsx)(sK,{label:"On this sequence",value:h.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>es(t=>{var n;let s;return n={notes:e},(s=eN(t)).settings=eS({...s.settings,...n}),s})},"sequence"),ed&&(0,o.jsx)(sK,{label:`On ${ed.name}`,value:ed.notes??"",placeholder:`A question or a decision about ${ed.name}…`,onSave:e=>es(t=>e_(t,ed.name,{notes:e}))},`participant:${ed.name}`),ec&&(0,o.jsx)(sK,{label:`On message ${x.id}`,value:ec.message.notes??"",placeholder:"A question or a decision about this message…",onSave:e=>es(t=>eO(t,ec.index,{notes:e},ec.fragment))},`message:${x.id}`),!x&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...eo.participants.filter(e=>e.notes?.trim()),...el.filter(e=>e.message.notes?.trim())].length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:s0,children:"With notes"}),(0,o.jsxs)("div",{className:"flex flex-wrap gap-1",children:[eo.participants.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:sQ,onClick:()=>ei(`participant:${e.name}`),children:e.name},`p${e.name}`)),el.filter(e=>e.message.notes?.trim()).map(e=>(0,o.jsxs)("button",{className:sQ,onClick:()=>ei(`message:${e.ref}`),children:["message ",e.ref]},`m${e.ref}`))]})]})]}),(0,o.jsxs)("section",{className:"issues"===$?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Issues"}),X.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ei(e.element),children:["[",e.ruleId,"] ",e.message]},`p${t}`)),V.map((e,t)=>(0,o.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===e.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ei(e.element),children:["[",e.ruleId,"] ",e.message]},`s${t}`)),0===X.length&&0===V.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:J?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!r&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Open this sequence from its system to check it against the machines and the data."}),r&&!H&&a&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),W&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:s0,children:["Replay against ",W.machines.join(", ")||"no machine"]}),W.paths.map(e=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${e.accepted?"text-green-400":"text-amber-300"}`,children:[e.name," — ",e.accepted?"accepted":"stops"]}),e.steps.filter(e=>"data"!==e.result).map(t=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===t.result||"stayed"===t.result?"text-gray-400":"text-amber-300"}`,title:t.note??t.result,onClick:()=>ei(`message:${t.ref}`),children:[t.ref,". ",t.event??""," ",t.from.join("|")||"·"," → ",t.to.join("|")||"·"," ",t.result]},`${e.name}:${t.ref}`))]},e.name))]})]})]})})]})]}),(0,o.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:ef.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?R.close():E(!0),N(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function rl(e,t){let n=e?.members.find(e=>e.path===t)?.def;return n?.settings?.name||(t.split("/").pop()??t).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let rc=(e,t)=>e?.members.find(e=>e.path===t)?.kind??"machine";function rd(e){return"message"===e.kind?`message ${e.name}`:`${e.kind} ${e.name}`}function rh({systemPath:e}){let t=sI("doc"),n=sI("focus"),{system:s}=s7(e),[r,a]=(0,l.useState)(!1),[i,c]=(0,l.useState)(null),d=(0,l.useRef)(s);(0,l.useEffect)(()=>{d.current=s},[s]);let h=(0,l.useMemo)(()=>s?sB(()=>e8(s.members),[]):[],[s]),m=s9(s,t),u=!!s&&(t===s.path||t===e),p=m&&n?function(e,t,n){let s=e6(n);if(!s)return[];let r=e=>e.member===t&&e.kind===s.kind&&e.name===s.name,a=[];for(let t of e)r(t.from)?a.push({other:t.to,text:t.text,rule:t.rule}):r(t.to)&&a.push({other:t.from,text:t.back,rule:t.rule});return a}(h,m,n):[],f=function(e,t){if(!t)return[];let n=new Map;for(let s of e)for(let e of[s.from,s.to]){if(e.member!==t)continue;let s=e3(e);n.set(s,(n.get(s)??0)+1)}return[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0]))}(h,m);(0,l.useEffect)(()=>{let e=e=>{let t=e.detail;t?.text&&c({...t,at:Date.now()})};return window.addEventListener(sP,e),()=>window.removeEventListener(sP,e)},[]),(0,l.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>c(null),9e3);return()=>clearTimeout(e)},[i]);let g=s?.path;(0,l.useEffect)(()=>{if(!g)return;let t=!0,n=null,s=null;return(async()=>{let{bridgeUrl:r}=await sh();if(t&&r){var i;let t,o,l,h;(n=nP({url:r,role:"web",docId:g,name:"web-system-strip"})).on("view",t=>{let n=d.current;if(!n)return;let s=t.member?void 0!==n.absOf[t.member]?t.member:Object.keys(n.absOf).find(e=>n.absOf[e]===t.member):void 0;if(t.member&&!s)return void c({text:`ignored a view of ${t.member.split("/").pop()}: it is not a member of this system`,origin:t.origin,at:Date.now()});sL({doc:s?n.absOf[s]:g,system:e,focus:t.focus??null}),a(!1);let r=[s?rl(n,s):"the system map",t.focus].filter(Boolean).join(" · ");c({text:t.note?t.note:`showing ${r}`,origin:t.origin,at:Date.now()})}),n.on("full",()=>s8()),i=n,t=!1,o=!1,l=()=>{i.join().then(()=>{t=!0}).catch(()=>{})},h=i.on("status",e=>{"connected"!==e?o=t:o&&(o=!1,l())}),l(),s=()=>{h()}}})(),()=>{t=!1,s?.(),n?.disconnect()}},[g,e]);let x=t=>{a(!1),s&&sL({doc:t.member?s.absOf[t.member]??eX(s.path,t.member):s.path,system:e,focus:t.focus??null})},y=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],b=s?.def?.settings?.name??(e.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),v=p.length;return(0,o.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,o.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,o.jsxs)("button",{onClick:()=>x({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${u?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${e} — the system map`,children:[(0,o.jsx)(s2,{kind:"system",size:15}),(0,o.jsx)("span",{className:"truncate font-semibold",children:b})]}),(0,o.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,o.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[y.map(e=>{let t=e===m,n=s?.members.find(t=>t.path===e)?.error;return(0,o.jsxs)("button",{onClick:()=>x({member:e}),"aria-current":t?"page":void 0,title:`${rl(s,e)} — ${e}${n?` (cannot be read: ${n})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${t?"bg-blue-950/60 text-blue-200":n?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,o.jsx)(s2,{kind:rc(s,e),size:15}),(0,o.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${t?"":"hidden md:inline"}`,children:rl(s,e)})]},e)}),!s&&(0,o.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),s?.error&&(0,o.jsx)("span",{className:"truncate px-1 text-amber-300",children:s.error})]}),(0,o.jsxs)("button",{onClick:()=>a(e=>!e),disabled:!m,"aria-expanded":r,title:m?n?`What ${n} links to in the other drawings`:"Elements of this drawing that link to the others":"Open a member to follow its links",className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 disabled:opacity-40 ${r?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,o.jsx)(s2,{kind:"link",size:15}),(0,o.jsx)("span",{className:"hidden sm:inline",children:"Links"}),v>0&&(0,o.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:v})]})]}),i&&!r&&(0,o.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,o.jsxs)("span",{className:"max-w-full truncate rounded border border-gray-700 bg-gray-900/95 px-2 py-0.5 text-[11px] text-gray-300 shadow",children:[i.origin?(0,o.jsxs)("span",{className:"text-blue-300",children:[i.origin,": "]}):null,i.text]})}),r&&m&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>a(!1),"aria-hidden":"true"}),(0,o.jsxs)("div",{className:"absolute right-1 top-full z-50 mt-1 max-h-[60vh] w-[min(24rem,calc(100vw-0.5rem))] overflow-y-auto rounded-lg border border-gray-700 bg-gray-900 p-2 shadow-xl",children:[n&&e6(n)?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,o.jsxs)("span",{className:"truncate",children:[(0,o.jsx)("span",{className:"text-gray-200",children:rd(e6(n))})," in ",rl(s,m)]}),(0,o.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>sL({doc:t,focus:null}),children:"clear"})]}),0===p.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),p.map((e,t)=>(0,o.jsxs)("button",{onClick:()=>x({member:e.other.member,focus:e3(e.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,o.jsx)(s2,{kind:rc(s,e.other.member),size:14})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block text-[12px] text-gray-200",children:e.text}),(0,o.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[rd(e.other)," · ",rl(s,e.other.member)," · ",e.rule]})]})]},t))]}):null,(!n||!e6(n))&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",rl(s,m)," that the other drawings name — pick one to follow it."]}),0===f.length&&(0,o.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:f.map(([e,n])=>(0,o.jsxs)("button",{onClick:()=>{a(!0),sL({doc:t,focus:e})},className:"rounded border border-gray-700 bg-gray-800 px-1.5 py-0.5 text-[11px] text-gray-200 hover:bg-gray-700",children:[e," ",(0,o.jsx)("span",{className:"text-gray-500",children:n})]},e))})]})]})]})]})}let rm={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function ru(e,t,n=!1){if(!t)return"";if("erd"===e)return`${t.entities?.length??0} entities \xb7 ${t.relationships?.length??0} relationships`;if("sequence"===e){let e=t.fragments?.length??0;return`${t.participants?.length??0} participants \xb7 ${t.messages?.length??0} messages${e&&!n?` \xb7 ${e} fragment${e>1?"s":""}`:""}`}let s=0,r=e=>{e&&(s+=1,(e.states??[]).forEach(r),(e.parallel?.states??[]).forEach(r))};(t.state?.states??[]).forEach(r),(t.state?.parallel?.states??[]).forEach(r);let a=(t.events??[]).reduce((e,t)=>e+(t?.events?.length??0)+(t?.timers?.length??0),0);return`${s} states \xb7 ${a} events`}let rp=(e,t)=>e<t?`${e}\u0000${t}`:`${t}\u0000${e}`;function rf(e){let t="message"===e.from.kind?`message ${e.from.name}`:`${e.from.kind} ${e.from.name}`;return`${t} ${e.text}`}function rg(){let e=(0,sn.useRequestedDoc)(),[t,n]=(0,l.useState)(e);(0,l.useEffect)(()=>{let t=!0;return e?n(e):sT("doc")||s5(null).then(e=>t&&n(e.path||null)),()=>{t=!1}},[e]);let{system:s,reload:r}=s7(t),[a,i]=(0,l.useState)("members"),[c,d]=(0,l.useState)(!1),[h,m]=(0,l.useState)(!1),[u,p]=(0,l.useState)(!1),[f,g]=(0,l.useState)(null),[x,y]=(0,l.useState)({text:"loading…",tone:"ok"}),b=(0,l.useCallback)((e,t="ok")=>y({text:e,tone:t}),[]),[v,w]=(0,l.useState)(!1),j=s_({onClose:()=>d(!1),restVh:62,tallVh:92}),k=(0,l.useRef)(null),[$,N]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();t.width&&N(t.height>1.1*t.width)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let S=(0,l.useRef)(!1);(0,l.useEffect)(()=>{s&&(s.error?b(s.error,"warn"):S.current||b(`${s.members.length} member${1===s.members.length?"":"s"} loaded`),S.current=!0)},[s,b]);let[E,C]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(e),C(!1)}},[x]);let M=(0,l.useMemo)(()=>s?.def?sB(()=>e4(s.def,s.members),null):null,[s]),_=(0,l.useMemo)(()=>s?sB(()=>e8(s.members),[]):[],[s]),A=(0,l.useMemo)(()=>s?.def?sB(()=>tt(s.def,s.members),null):null,[s]),O=eD(s?.def),R=(0,l.useMemo)(()=>{let e=new Map;for(let t of _){if(t.from.member===t.to.member)continue;let n=rp(t.from.member,t.to.member),s=e.get(n)??{a:n.split("\0")[0],b:n.split("\0")[1],links:[]};s.links.push(t),e.set(n,s)}return e},[_]),P=(M?.issues??[]).filter(e=>"error"===e.severity),T=(M?.issues??[]).filter(e=>"warning"===e.severity),I=(t,n)=>{s&&sL({doc:s.absOf[t]??t,system:e??s.path,focus:n??null})},L=async(e,t)=>{if(s)try{await s3(s.path,e,s.mtimes[s.path]),b(t),s8()}catch(e){e instanceof s4?(b("the system changed on disk — reloaded; make the change again","warn"),s8()):b(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}},D=async()=>{if(!s||!A||!A.count)return;w(!0);let{result:e,written:t,failed:n,conflicts:r}=await rn(s.path);w(!1),n.length?b(`not all written: ${n.join("; ")}`,"warn"):r.length?b(`${r.join(", ")} kept changing on disk — not written; apply again`,"warn"):e?.count?b(`${tn(e,"propose").replace(/ proposed/," applied")} — ${t.length} file(s) written`):b("nothing to apply: the drawings on disk already agree")},q=$?420:760,B=$?640:520,F=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],Y=s?.def?.actors??[],z=64*!!Y.length,U=(0,l.useMemo)(()=>{let e=F.length,t=q/2,n=(B-z)/2+6,s=Math.max(0,q/2-98-16),r=Math.max(0,(B-z)/2-46-18),a=new Map;return F.forEach((i,o)=>{if(1===e)return a.set(i,{x:t,y:n});if($){let t=B-z-46-16;return a.set(i,{x:o%2?.67*q:.33*q,y:62+(t-62)*o/(e-1)})}if(2===e)return a.set(i,$?{x:t,y:o?n+r:n-r}:{x:o?t+s:t-s,y:n});let l=-Math.PI/2+2*o*Math.PI/e;a.set(i,{x:t+s*Math.cos(l),y:n+r*Math.sin(l)})}),a},[F.join("|"),q,B,196,z,$]),X=(0,l.useMemo)(()=>{let e=new Map;for(let{member:t,def:n}of e5(s?.members??[]).sequences)for(let s of n.participants??[]){if(!s?.actor)continue;let n=e.get(s.actor)??[];n.includes(t)||n.push(t),e.set(s.actor,n)}return e},[s]),H=s?.def,J=(s?.path??t??"").split("/").pop()||"…",V=[{id:"members",label:"Members",icon:(0,o.jsx)(s2,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,o.jsx)(sC,{}),badge:P.length+T.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],W=f?R.get(f):void 0,K=(0,l.useMemo)(()=>{let e=[];for(let t of["error","warning"]){let n=new Map;for(let e of M?.issues??[])e.severity===t&&n.set(e.ruleId,[...n.get(e.ruleId)??[],e]);for(let[s,r]of[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0])))e.push({key:`${t}:${s}`,ruleId:s,severity:t,issues:r})}return e},[M]);return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>h&&m(!1),children:[(0,o.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,o.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,o.jsx)(s2,{kind:"system",size:14}),"SYS"]}),(0,o.jsx)(ss,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:s?.path,children:[H?.settings?.name??J,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",J]})]}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:sQ,onClick:r,title:"Read the system and every member again",children:"Re-check"}),(0,o.jsx)("button",{className:sQ,onClick:()=>p(e=>!e),"aria-pressed":!u,children:u?"⟨ Panel":"Panel ⟩"})]}),(0,o.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,o.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":h,onClick:e=>{e.stopPropagation(),m(e=>!e)},children:"⋯"}),h&&(0,o.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,o.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{m(!1),r()},children:"Re-check the system"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:k,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[s&&H&&(0,o.jsx)(sE,{what:"system map",resetKey:s,children:(0,o.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${q} ${B}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${H.settings?.name}`,children:[[...R.entries()].map(([e,t])=>{let n=U.get(t.a),s=U.get(t.b);if(!n||!s)return null;let r=(n.x+s.x)/2,a=(n.y+s.y)/2,l=`${t.links.length} link${1===t.links.length?"":"s"}`,c=6.4*l.length+16,h=f===e;return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>{g(h?null:e),i("members"),d(!0)},children:[(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:"transparent",strokeWidth:18}),(0,o.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:h?"#3b82f6":"#475569",strokeWidth:h?2.5:1.6}),(0,o.jsx)("rect",{x:r-c/2,y:a-11,width:c,height:22,rx:11,fill:"#0f172a",stroke:h?"#3b82f6":"#334155"}),(0,o.jsx)("text",{x:r,y:a+4,textAnchor:"middle",fontSize:11.5,fill:h?"#93c5fd":"#cbd5e1",children:l})]},e)}),Y.map((e,t)=>{let n=(t+1)*q/(Y.length+1),s=B-30;return(0,o.jsxs)("g",{children:[(X.get(e.name)??[]).map(e=>{let t=U.get(e);return t?(0,o.jsx)("line",{x1:n,y1:s-14,x2:t.x,y2:t.y+46,stroke:"#334155",strokeDasharray:"3 4"},e):null}),(0,o.jsx)("title",{children:[`${e.kind}`,e.description??"",e.wheelNode??""].filter(Boolean).join(" — ")}),(0,o.jsx)("rect",{x:n-62,y:s-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,o.jsx)("g",{transform:`translate(${n-54} ${s-8})`,color:"#a5b4fc",children:(0,o.jsx)(s2,{kind:"actor",size:16})}),(0,o.jsx)("text",{x:n-34,y:s-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:e.name.length>12?`${e.name.slice(0,11)}…`:e.name}),(0,o.jsx)("text",{x:n-34,y:s+9,fontSize:8.5,fill:"#94a3b8",children:e.kind})]},e.name)}),F.map(e=>{let t=U.get(e),n=s.members.find(t=>t.path===e);if(!t||!n)return null;let r=n.kind,a=(M?.issues??[]).filter(t=>t.member===e),i=a.filter(e=>"error"===e.severity).length,l=a.filter(e=>"warning"===e.severity).length,c=t.x-98,d=t.y-46,h=rl(s,e),m=W&&(W.a===e||W.b===e);return(0,o.jsxs)("g",{className:"cursor-pointer",onClick:()=>I(e),children:[(0,o.jsx)("title",{children:`${e}${n.error?` — cannot be read: ${n.error}`:""}
11
+ Tap to open it inside the system.`}),(0,o.jsx)("rect",{x:c,y:d,width:196,height:92,rx:10,fill:"#0f172a",stroke:n.error?"#ef4444":m?"#3b82f6":i?"#b91c1c":"#475569",strokeWidth:m?2.2:1.5,strokeDasharray:n.error?"5 4":void 0}),(0,o.jsx)("g",{transform:`translate(${c+10} ${d+9})`,color:"#93c5fd",children:(0,o.jsx)(s2,{kind:r,size:16})}),(0,o.jsx)("text",{x:c+32,y:d+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:rm[r]}),(0,o.jsx)("text",{x:c+10,y:d+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:h.length>22?`${h.slice(0,21)}…`:h}),(0,o.jsx)("text",{x:c+10,y:d+60,fontSize:10.5,fill:"#94a3b8",children:n.error?"cannot be read":ru(r,n.def,!0)}),(0,o.jsx)("text",{x:c+10,y:d+79,fontSize:10.5,fill:i?"#fca5a5":l?"#fcd34d":"#4ade80",children:n.error?n.error.length>30?`${n.error.slice(0,29)}…`:n.error:i||l?[i?`${i} error${i>1?"s":""}`:"",l?`${l} warning${l>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,o.jsx)("text",{x:c+196-10,y:d+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},e)})]})}),s&&!H&&(0,o.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:s.error}),(0,o.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===x.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,o.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===x.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,o.jsx)("span",{className:`truncate transition-opacity duration-500 ${E&&"ok"===x.tone?"opacity-0":"opacity-100"}`,children:x.text})]})]}),c&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:j.close,"aria-hidden":"true"}),s&&H&&(0,o.jsxs)("aside",{style:j.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${c?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-96 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${u?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...j.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:V.find(e=>e.id===a)?.label}),(0,o.jsx)("button",{onClick:j.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:V.map(e=>(0,o.jsxs)("button",{onClick:()=>i(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${a===e.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,o.jsxs)("section",{className:"members"===a?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Members"}),F.map(e=>{let t=s.members.find(t=>t.path===e),n=H.members.find(t=>t.path===e)?.notes;return(0,o.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,o.jsxs)("button",{onClick:()=>I(e),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,o.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,o.jsx)(s2,{kind:t?.kind??"machine"})}),(0,o.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,o.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:rl(s,e)}),(0,o.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:e}),(0,o.jsx)("span",{className:`block text-[11px] ${t?.error?"text-red-300":"text-gray-400"}`,children:t?.error?`cannot be read: ${t.error}`:ru(t?.kind??"machine",t?.def)})]}),(0,o.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,o.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,o.jsx)(sK,{label:"Note on this member, in the system",value:n??"",placeholder:`Why ${rl(s,e)} is part of this system, what is open…`,onSave:t=>void L(function(e,t,n){let s=eJ(e),r=s.members.findIndex(e=>e.path===t);if(r<0)throw Error(`'${t}' is not a member. Members: ${e.members.map(e=>e.path).join(", ")||"none"}.`);return s.members[r]=eV({...s.members[r],...n}),s}(H,e,{notes:t}),"saved")},`member:${e}`)})]},e)}),(0,o.jsx)("div",{className:s0,children:"Links between members"}),0===R.size&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...R.entries()].map(([e,t])=>(0,o.jsxs)("div",{className:"mb-1",children:[(0,o.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${f===e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>g(f===e?null:e),children:[(0,o.jsxs)("span",{className:"truncate",children:[rl(s,t.a)," ↔ ",rl(s,t.b)]}),(0,o.jsx)("span",{className:"shrink-0 text-gray-500",children:t.links.length})]}),f===e&&(0,o.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:t.links.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${rf(e)} — ${e.rule}`,onClick:()=>{let t;return I((t=e.from).member,e3(t))},children:[(0,o.jsx)("span",{className:"text-gray-600",children:e.rule})," ",rf(e)]},t))})]},e)),Y.length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:s0,children:"Actors"}),Y.map(e=>(0,o.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[e.name," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.kind]}),e.description?(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",e.description]}):null]},e.name))]})]}),(0,o.jsxs)("section",{className:"checks"===a?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Checks"}),(0,o.jsxs)("div",{className:`text-[11px] ${P.length?"text-red-300":T.length?"text-amber-300":"text-green-400"}`,children:[P.length," error",1===P.length?"":"s"," · ",T.length," warning",1===T.length?"":"s"]}),K.map(e=>(0,o.jsxs)("div",{className:"mt-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:[e.ruleId," · ",e.issues.length," ",e.severity,1===e.issues.length?"":"s"]}),e.issues.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{e.member&&I(e.member,e.element&&/^[a-z]+:/.test(e.element)?e.element:null)},title:e.member?`Open ${e.member}${e.element?` at ${e.element}`:""}`:void 0,children:[e.message,e.member&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" — ",rl(s,e.member)]})]},t))]},e.key)),(0,o.jsx)("div",{className:s0,children:"Reconcile"}),(0,o.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,o.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,o.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,o.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:eL.map(e=>(0,o.jsx)("button",{"aria-pressed":O===e,onClick:()=>{s?.def&&e!==O&&L(function(e,t){if(!eL.includes(t))throw Error(`The reconcile mode is ${eL.join(" or ")}; got '${t}'.`);return eW(e,{reconcile:t})}(s.def,e),`reconcile mode: ${e}`)},className:`px-3 py-1 text-xs ${O===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:e},e))}),(0,o.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),A&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-500",children:tn(A,"propose")}),A.machines.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.machine," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),A.erds.map(e=>(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.def.settings?.name??e.member," ",(0,o.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),A.system&&(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),A.system.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]}),A.unresolved.map((e,t)=>(0,o.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",e]},t)),(0,o.jsx)("button",{className:`${sQ} mt-2 disabled:opacity-40`,disabled:!A.count||v,onClick:D,children:v?"Applying…":`Apply${A.count?` ${A.count} change${1===A.count?"":"s"}`:""}`})]}),(M?.replays??[]).map(({member:e,report:t})=>(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:s0,children:["Replay · ",rl(s,e)]}),(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",t.machines.join(", ")||"no machine"]}),t.paths.map(t=>(0,o.jsxs)("div",{className:"mb-2",children:[(0,o.jsxs)("div",{className:`text-[11px] font-semibold ${t.accepted?"text-green-400":"text-amber-300"}`,children:[t.name," — ",t.accepted?"accepted":"stops"]}),t.steps.filter(e=>"data"!==e.result).map(n=>(0,o.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===n.result||"stayed"===n.result?"text-gray-400":"text-amber-300"}`,title:n.note??n.result,onClick:()=>I(e,`message:${n.ref}`),children:[n.ref,". ",n.event??""," ",n.from.join("|")||"·"," → ",n.to.join("|")||"·"," ",n.result]},`${t.name}:${n.ref}`))]},t.name))]},e))]}),(0,o.jsxs)("section",{className:"notes"===a?"":"hidden",children:[(0,o.jsx)("div",{className:s0,style:{marginTop:0},children:"Notes"}),(0,o.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,o.jsx)(sK,{label:"On this system",value:H.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:e=>void L(eW(H,{notes:e}),"saved")},"system"),H.settings?.description&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:s0,children:"Description"}),(0,o.jsx)("p",{className:"text-[11px] text-gray-400",children:H.settings.description})]})]})]})]})]}),(0,o.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:V.map(e=>{let t=c&&a===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(c&&a===t?j.close():d(!0),i(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,o.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}let rx=e=>e.parallel?e.parallel.states:e.states??[];function ry(e,t){if(!e)return null;if(e.name===t)return[e.name];for(let n of rx(e)){let s=ry(n,t);if(s)return[e.name,...s]}return null}function rb(){let e=(0,sn.useRequestedDoc)(),t=sI("system"),[n,s]=(0,l.useState)(null);(0,l.useEffect)(()=>{let e=!0;return sh().then(t=>{e&&s(t.projectFile?eY(t.projectFile):"machine")}),()=>{e=!1}},[]);let r=e?eY(e):n;if(null===r)return(0,o.jsx)("div",{className:"app-shell bg-gray-950"});let a=e??"default",i="erd"===r?(0,o.jsx)(sW,{},a):"sequence"===r?(0,o.jsx)(ro,{},a):"system"===r?(0,o.jsx)(rg,{},a):(0,o.jsx)(rv,{}),c=(0,o.jsx)(sE,{what:"document",resetKey:e,children:i});return t&&eB(t)?(0,o.jsxs)("div",{className:"system-frame",children:[(0,o.jsx)(rh,{systemPath:t}),c]}):c}function rv(){var e,t;let n,s,r,a;n=sq(),s=(0,l.useRef)(null),(0,l.useEffect)(()=>{let e=()=>{let e=s.current;if(!e)return;let t=nH.getState(),n=sT("doc");if(n&&t.docPath!==n||e.docAt!==t.docPath&&t.definition===e.defAt)return;s.current=null;let r=e6(e.focus);if(!r)return;let a=null,i=null;if("state"===r.kind)(a=ry(t.definition.state,r.name))&&(i={kind:"state",id:r.name});else if("event"===r.kind){let e=function e(t,n){if(!t)return null;let s=(t.transitions??[]).findIndex(e=>e?.event===n);if(s>=0)return{state:t.name,index:s};for(let s of rx(t)){let t=e(s,n);if(t)return t}return null}(t.definition.state,r.name);e&&(a=ry(t.definition.state,e.state),i={kind:"transition",id:`${e.state}:${e.index}`})}if(!a||!i)return;let o=a.length>1?a.slice(0,-1):a;nH.setState({navigationPath:o,currentParent:o[o.length-1]}),t.select(i.kind,i.id);let l=()=>{let e=nH.getState().layout.positions[a[a.length-1]],t=document.getElementById(nK)?.getBoundingClientRect();if(!e||!t?.width)return;let n=U([e],t.width,t.height,{padding:60,maxScale:1});nH.getState().setViewport(n)};requestAnimationFrame(l),setTimeout(l,450)};if(n.nonce>0){let t=nH.getState();s.current=n.focus?{focus:n.focus,docAt:t.docPath,defAt:t.definition}:null,e()}return nH.subscribe(e)},[n]),(0,l.useEffect)(()=>nH.subscribe((e,t)=>{if(e.selection===t.selection||!e.selection.id)return;let{kind:n,id:s}=e.selection;if("state"===n)sD(`state:${s}`);else if("event"===n)sD(`event:${s}`);else if("transition"===n){let t=function(e,t){let n=t.lastIndexOf(":"),s=ry(e.state,t.slice(0,n));if(!s)return null;let r=e.state;for(let e of s.slice(1))r=rx(r).find(t=>t.name===e);return r?.transitions?.[Number(t.slice(n+1))]?.event??null}(e.definition,s);t&&sD(`event:${t}`)}}),[]);let[i,c]=(0,l.useState)("properties"),[d,h]=(0,l.useState)(!1),m=s_({onClose:()=>h(!1),restVh:70,tallVh:92}),u=nH(e=>e.errors),p=nH(e=>e.contextMenu),f=nH(e=>e.hideContextMenu),g=nH(e=>e.addState),x=nH(e=>e.removeState),y=nH(e=>e.setDrawMode),b=nH(e=>e.setDrawSource),v=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,o.jsx)(sC,{}),badge:u.length||void 0}],w=v.find(e=>e.id===i)?.label??"";return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>p.visible&&f(),children:[(0,o.jsx)(sm,{}),(0,o.jsx)(sN,{}),(0,o.jsx)(sa,{}),(0,o.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,o.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,o.jsx)(sE,{what:"state machine",children:(0,o.jsx)(n3,{})})}),d&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:m.close,"aria-hidden":"true"}),(0,o.jsxs)("aside",{style:m.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 h-[var(--sheet-h)] flex flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${d?"translate-y-0":"translate-y-full pointer-events-none"} md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:pointer-events-auto md:rounded-none md:border-t-0 md:border-l md:shadow-none md:transition-none`,children:[(0,o.jsxs)("div",{className:"md:hidden",...m.zoneProps,children:[(0,o.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,o.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,o.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,o.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:w}),(0,o.jsx)("button",{onClick:m.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,o.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:v.map(e=>(0,o.jsxs)("button",{onClick:()=>c(e.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${i===e.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[e.label,void 0!==e.badge&&e.badge>0&&(0,o.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:e.badge})]},e.id))}),(0,o.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===i&&(0,o.jsx)(n8,{}),"events"===i&&(0,o.jsx)(n9,{}),"settings"===i&&(0,o.jsx)(se,{}),"validation"===i&&(0,o.jsx)(st,{})]})]}),(0,o.jsx)(si,{})]}),(0,o.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:v.map(e=>{let t=d&&i===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(d&&i===t?m.close():h(!0),c(t))},"aria-pressed":t,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${t?"text-blue-400":"text-gray-500"}`,children:[(0,o.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,o.jsx)("span",{children:e.label}),void 0!==e.badge&&e.badge>0&&(0,o.jsx)("span",{className:"absolute top-1 right-1/2 translate-x-4 rounded-full bg-red-600 px-1 text-[10px] leading-4 text-white min-w-[16px]",children:e.badge}),t&&(0,o.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})}),p.visible&&(0,o.jsx)("div",{className:"fixed z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-1 min-w-[180px] md:min-w-[140px]",style:(e=p.x,t=p.y,r=window.innerWidth,a=window.innerHeight,{left:e,top:t,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:`translate(${r>0&&e>r/2?"-100%":"0"}, ${a>0&&t>a/2?"-100%":"0"})`}),onClick:e=>e.stopPropagation(),children:p.target?.kind==="state"?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{y("transition"),b(p.target.id),f()},children:"↗ Draw transition from here"}),(0,o.jsx)("button",{className:"block w-full text-left text-sm text-red-400 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{p.target?.id&&x(p.target.id),f()},children:"🗑 Delete state"})]}):(0,o.jsx)(o.Fragment,{children:(0,o.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{let e=prompt("State name:");e&&g(null,{name:e,kind:"normal"}),f()},children:"+ Add state here"})})})]})}e.s(["default",()=>rb],63052)}]);