@miadi/stateloom-web 0.3.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) 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/marks/route.js.nft.json +1 -1
  23. package/server/.next/server/app/api/rispec/route.js.nft.json +1 -1
  24. package/server/.next/server/app/api/watch/route.js.nft.json +1 -1
  25. package/server/.next/server/app/index.html +1 -1
  26. package/server/.next/server/app/index.rsc +3 -3
  27. package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  28. package/server/.next/server/app/index.segments/_full.segment.rsc +3 -3
  29. package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  30. package/server/.next/server/app/index.segments/_index.segment.rsc +2 -2
  31. package/server/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  32. package/server/.next/server/app/page.js.nft.json +1 -1
  33. package/server/.next/server/app/page_client-reference-manifest.js +1 -1
  34. package/server/.next/server/chunks/ssr/{[root-of-the-server]__9e661f75._.js → [root-of-the-server]__a593e8b6._.js} +1 -1
  35. package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +6 -6
  36. package/server/.next/server/pages/404.html +1 -1
  37. package/server/.next/server/pages/500.html +2 -2
  38. package/server/.next/static/chunks/59a1ec89a1dc7e34.js +14 -0
  39. package/server/.next/static/chunks/{0d24f3e3dbdef25e.css → 8f45e56f40c207bf.css} +2 -2
  40. package/server/package-lock.json +2 -2
  41. package/server/package.json +1 -1
  42. package/server/src/app/globals.css +20 -0
  43. package/server/src/components/stage/CompanionLayer.tsx +10 -1
  44. package/server/src/components/stage/StageLayer.tsx +84 -8
  45. package/server/src/components/stage/StageProvider.tsx +4 -1
  46. package/server/src/components/stage/useEpisodePresence.ts +71 -0
  47. package/server/stateloom-web.json +2 -2
  48. package/server/tsconfig.tsbuildinfo +1 -1
  49. package/server/.next/static/chunks/f03f883bab5194ab.js +0 -14
  50. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → CZ4wRF1efsHnxjkcKHITP}/_buildManifest.js +0 -0
  51. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → CZ4wRF1efsHnxjkcKHITP}/_clientMiddlewareManifest.json +0 -0
  52. /package/server/.next/static/{HNER2j3kS6-hB98CL_HRG → CZ4wRF1efsHnxjkcKHITP}/_ssgManifest.js +0 -0
@@ -1,14 +0,0 @@
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 u(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 m(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(u(n,e.id,"event.update").event,e.patch);break;case"event.remove":{let t=u(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=u(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=u(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=u(n,e.eventId,"parameter.remove"),s=t.event.parameters;if(!s||!s[e.index])throw Error(`applyPatchOps: parameter.remove index ${e.index} out of range for event "${e.eventId}"`);s.splice(e.index,1),0===s.length&&delete t.event.parameters;break}case"transition.add":{let t=h(n.state,e.state,"transition.add");t.transitions||(t.transitions=[]);let s=e.index??t.transitions.length;t.transitions.splice(s,0,c(e.transition));break}case"transition.update":{let t=h(n.state,e.state,"transition.update").transitions??[];if(!t[e.index])throw Error(`applyPatchOps: transition.update index ${e.index} out of range for state "${e.state}"`);t[e.index]={...t[e.index],...e.patch};break}case"transition.remove":{let t=h(n.state,e.state,"transition.remove"),s=t.transitions;if(!s||!s[e.index])throw Error(`applyPatchOps: transition.remove index ${e.index} out of range for state "${e.state}"`);s.splice(e.index,1),0===s.length&&delete t.transitions;break}case"action.add":{let t=h(n.state,e.state,"action.add"),s=t[e.hook]??(t[e.hook]={actions:[]}),r=e.index??s.actions.length;s.actions.splice(r,0,c(e.action));break}case"action.update":{let t=h(n.state,e.state,"action.update")[e.hook];if(!t||!t.actions[e.index])throw Error(`applyPatchOps: action.update index ${e.index} out of range for state "${e.state}" ${e.hook}`);t.actions[e.index]=c(e.action);break}case"action.remove":{let t=h(n.state,e.state,"action.remove"),s=t[e.hook];if(!s||!s.actions[e.index])throw Error(`applyPatchOps: action.remove index ${e.index} out of range for state "${e.state}" ${e.hook}`);s.actions.splice(e.index,1),0===s.actions.length&&delete t[e.hook];break}case"runtime.enter":case"runtime.exit":break;default:throw Error(`applyPatchOps: unknown op ${JSON.stringify(e)}`)}return n}function p(e){let t=[e];for(let n of e.states??[])t.push(...p(n));return t}function f(e){let t=new Map;t.set(e.name,null);let n=e=>{for(let s of e.states??[])t.set(s.name,e.name),n(s)};return n(e),t}function g(e,t){return JSON.stringify(e)===JSON.stringify(t)}function x(e,t,n,s,r){let a=Math.min(n.length,s.length);for(let i=0;i<a;i++)g(n[i],s[i])||r.push({op:"action.update",state:e,hook:t,index:i,action:s[i]});for(let n=a;n<s.length;n++)r.push({op:"action.add",state:e,hook:t,action:s[n],index:n});for(let a=n.length-1;a>=s.length;a--)r.push({op:"action.remove",state:e,hook:t,index:a})}function y(e){let t=0;for(let n=0;n<e.length;n++)t=Math.imul(t,31)+e.charCodeAt(n)|0;let n=(t%360+360)%360;return`hsl(${n}, 65%, 55%)`}var b=e.i(50382);let v={hSpacing:220,vSpacing:140,nodeWidth:160,nodeHeight:60,compositeWidth:300,compositeHeight:200,originX:100,originY:120,sweeps:2,includeRoot:!0},w=(e,t)=>`${e}\u0000${t}`;function j(e){let t=new Set,n=[];for(let s of e.states??[])t.has(s.name)||(t.add(s.name),n.push(s));return n}function k(e,t){let n=new Map(e.map(e=>[e,[]]));for(let e of t)n.get(e.from).push(e.to);return n}function $(e,t={}){let n={...v,...t},s="state"in e?e.state:e,r={};if(!s)return r;if(!function e(t,n,s,r,a){let i=j(t);if(0===i.length)return;let o=i.map(e=>e.name),l=new Map(i.map(e=>[e.name,e])),c=function(e){let t=new Set,n=[];for(let s of e)for(let r of s.transitions??[]){let a=r.nextState?function(e,t){for(let n of e){if(n.name===t)return n.name;let e=[...n.states??[],...n.parallel?.states??[]];for(;e.length;){let s=e.pop();if(s.name===t)return n.name;e.push(...s.states??[],...s.parallel?.states??[])}}}(e,r.nextState):void 0;if(!a||a===s.name)continue;let i=w(s.name,a);t.has(i)||(t.add(i),n.push({from:s.name,to:a}))}return n}(i),d=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0])),r=new Set;for(let t of e){if(0!==s.get(t))continue;s.set(t,1);let e=[{node:t,i:0}];for(;e.length>0;){let t=e[e.length-1],a=n.get(t.node);if(t.i<a.length){let n=a[t.i++],i=s.get(n);1===i?r.add(w(t.node,n)):0===i&&(s.set(n,1),e.push({node:n,i:0}))}else s.set(t.node,2),e.pop()}}return r}(o,c),h=c.filter(e=>!d.has(w(e.from,e.to))),u=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),m=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)m.has(e)&&(p=Math.max(p,u.get(e)));for(let e of o)m.has(e)||u.set(e,u.get(e)+p+1);let f=Array.from({length:Math.max(...o.map(e=>u.get(e)))+1},()=>[]);for(let e of o)f[u.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}]`,M=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}),E=(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,R={along:[.5,.36,.64,.24,.76,.14,.86],aside:[0,.6,-.6],across:[0,-1.3,1.3,-2.6,2.6]};function _(e,t,n={}){let{along:s,aside:r,across:a}={...R,...n},i=e.map((e,t)=>({label:e,i:t,width:M(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}=M(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),u=s.x+a*n,m=s.y+h*i,p={x:u-n/2,y:m-18,width:n,height:i},f=[...o,...t].filter(e=>E(p,e)).length,g={...p,cx:u+l,cy:m,label:e};if(0===f){c=g;break e}f<d&&(d=f,c=g)}c&&o.push(c)}return o}let A=(e,t,n=2.2,s)=>({id:e,paths:t,strokeWidth:n,circles:s}),T=A("signal",["M3 12h10","m13 6 6 6-6 6Z"]),O=[{glyph:A("confirm",["m4 13 5.5 5.5L20 6"],2.4),words:["confirm","approve","accept","commit"]},{glyph:A("complete",["m8 12 3 3 5-6"],2.2,[{cx:12,cy:12,r:8.5}]),words:["complete","finish","done","close"]},{glyph:A("skip",["M4 17c0-6 4.5-9 9-9h6","m15 4 4.5 4-4.5 4"]),words:["skip","ignore","bypass"]},{glyph:A("flag",["M6 21V4","M6 4h12l-3 4.5 3 4.5H6Z"]),words:["flag","mark","revisit","review"]},{glyph:A("advance",["M4 6l8 6-8 6Z","M13 6l7 6-7 6Z"]),words:["advance","next","forward","step"]},{glyph:A("pause",["M9 5v14M15 5v14"],2.6),words:["pause","hold","suspend","stop"]},{glyph:A("play",["M7 4.5 19 12 7 19.5Z"]),words:["resume","start","begin","play","run"]},{glyph:A("clock",["M12 7.5V12l3.5 2.5"],2.2,[{cx:12,cy:12,r:8.5}]),words:["timeout","expire","tick","delay","after","elapse"]},{glyph:A("change",["M3 14c3-6 6-6 9 0s6 6 9 0"]),words:["change","update","edit","modify","set"]}];[...O.map(e=>e.glyph)];let P=e=>Math.round(100*e)/100;function I(e,t,n,s){return{p0:e,p1:t,p2:n,p3:s,path:`M ${P(e.x)} ${P(e.y)} C ${P(t.x)} ${P(t.y)}, ${P(n.x)} ${P(n.y)}, ${P(s.x)} ${P(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){return{x:(t.x-e.x)/e.scale,y:(t.y-e.y)/e.scale}}function U(e,t,n){return{x:e.x+t,y:e.y+n,scale:e.scale}}function z(e,t,n,s=D){return Y(e,e.scale*t,n,s)}function Y(e,t,n,s=D){let r=B(t,s);if(r===e.scale)return e;let a=F(e,n);return{x:n.x-a.x*r,y:n.y-a.y*r,scale:r}}function H(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),u=Math.max(1,d-l),m=B(Math.min(a,Math.min(Math.max(1,t-2*r)/h,Math.max(1,n-2*r)/u)),i);return{x:(t-h*m)/2-o*m,y:(n-u*m)/2-l*m,scale:m}}function X(e){return`translate(${e.x} ${e.y}) scale(${e.scale})`}function V(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 W=["1:1","1:N","N:1","N:M"];function K(e){return!!e&&"object"==typeof e&&Array.isArray(e.entities)&&!("state"in e)}function Z(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})}W.includes(r?.cardinality)||t.push({ruleId:"E004",message:`Relationship ${s} cardinality "${r?.cardinality??""}" is not one of ${W.join(", ")}`,element:e})}return t}function G(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 Q(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=>G(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 G(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 ee(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 et=e=>({settings:{...e.settings},entities:(e.entities??[]).map(e=>({...e,attributes:(e.attributes??[]).map(e=>({...e}))})),relationships:(e.relationships??[]).map(e=>({...e}))});function en(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 es(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function er(e,t){if(!t.name?.trim())throw Error("An entity needs a name.");let n=et(e);if(n.entities.some(e=>e.name===t.name))throw Error(`Entity '${t.name}' already exists.`);return n.entities.push(es({...t,attributes:t.attributes??[]})),n}function ea(e,t,n){let s=et(e),r=en(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 ei=e=>(e.attributes??[]).filter(e=>e?.name);function eo(e){return Math.max(110,Math.ceil(8.4*(e.name??"").length+36))}function el(e){return Math.max(38,Math.ceil(3.5*Math.max(0,...e.map(e=>e.name.length))+14))}let ec=e=>Math.ceil(e/2);function ed(e){let t=ei(e),n=eo(e);return 0===t.length?{width:n,height:40}:{width:n+2*(34+2*el(t)),height:Math.max(40,32*ec(t.length))}}let eh={"1:1":"||--||","1:N":"||--o{","N:1":"}o--||","N:M":"}o--o{"},eu=/^[A-Za-z_][A-Za-z0-9_-]*$/,em=e=>eu.test(e)?e:`"${e.replace(/"/g,"'")}"`,ep=(e,t)=>{let n=e.trim().replace(/[^A-Za-z0-9_()[\]-]+/g,"_").replace(/^_+|_+$/g,"");return/^[A-Za-z_]/.test(n)?n:n?`_${n}`:t},ef=e=>`"${e.replace(/"/g,"'")}"`,eg=["settings","states","parallel","entities","participants","messages","fragments","members","state"];function ex(e){let t=!1,n=e=>{if(Array.isArray(e)){let t=!1,s=e.map(e=>{let s=n(e);return s!==e&&(t=!0),s});return t?s:e}if(!e||"object"!=typeof e)return e;let s=null;if("notes"in e&&"string"!=typeof e.notes&&void 0!==e.notes){s={...e};let n=function(e){if(null!=e)return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"string"==typeof e?e:JSON.stringify(e)).join("\n\n"):JSON.stringify(e)}(e.notes);void 0!==n&&n.trim()?s.notes=n:delete s.notes,t=!0}for(let t of eg){if(!(t in e))continue;let r=(s??e)[t],a=n(r);a!==r&&((s??={...e})[t]=a)}return s??e},s=n(e);return t?s:e}function ey(e){return`${e.name} : ${e.type}`}function eb(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=>ey(e).length+6.96969696969697))+28))),height:30+20*Math.max(1,t.length)+8}}function ev(e){return e.trim().replace(/[\s_]+/g,"-").replace(/[^A-Za-z0-9.-]/g,"").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,60)}let ew=["alt","opt","loop"];function ej(e){return!!e&&"object"==typeof e&&Array.isArray(e.participants)&&Array.isArray(e.messages)&&!("state"in e)&&!("entities"in e)}function ek(e,t,n){return{settings:n?{namespace:e,name:t,description:n}:{namespace:e,name:t},participants:[],messages:[]}}function e$(e,t){return null===e?String(t+1):`f${e+1}.${t+1}`}function eN(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 eS(e){let t=[];return(e.messages??[]).forEach((e,n)=>t.push({ref:e$(null,n),message:e,fragment:null})),(e.fragments??[]).forEach((e,n)=>(e?.messages??[]).forEach((e,s)=>t.push({ref:e$(n,s),message:e,fragment:n}))),t}function eM(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,e$(null,t)));let r=(e.messages??[]).length;for(let[n,a]of(e.fragments??[]).entries()){let e=`fragment:${n+1}`;if(!a||!ew.includes(a.kind)){t.push({ruleId:"S005",message:`Fragment ${n+1} has kind "${a?.kind??""}"; expected one of ${ew.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,e$(n,t)))}return t}let eC=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 eE(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e&&!(Array.isArray(e)&&0===e.length)))}function eR(e,t){let n=e.participants.find(e=>e.name===t);if(!n){let n=e.participants.map(e=>e.name).join(", ")||"none";throw Error(`Participant '${t}' not found. Participants: ${n}.`)}return n}function e_(e,t){if(eR(e,t.from),eR(e,t.to),!t.label?.trim())throw Error("A message needs a label: what is said or done, in a few words.")}function eA(e,t){let n=e.fragments?.[t];if(n&&!Array.isArray(n.messages)&&(n.messages=[]),!n)throw Error(`Fragment ${t+1} not found. The sequence has ${e.fragments?.length??0} fragment(s).`);return n}function eT(e,t,n){let s=eC(e),r=eR(s,t),a=eE({...r,...n});return s.participants[s.participants.indexOf(r)]=a,s}function eO(e,t,n){let s=eC(e);e_(s,t);let r=void 0===n?s.messages.length:Math.max(0,Math.min(n,s.messages.length));if(s.messages.splice(r,0,eE({...t})),s.fragments)for(let e of s.fragments)e.after>r&&(e.after+=1);return s}function eP(e,t,n,s=null){let r=eC(e),a=null===s?r.messages:eA(r,s).messages,i=a[t];if(!i)throw Error(`Message ${t+1} not found${null===s?"":` in fragment ${s+1}`}.`);let o=eE({...i,...n});return e_(r,o),a[t]=o,r}function eI(e,t,n){let s=eC(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 eL={columnGap:150,rowHeight:34,headerHeight:34,topGap:30,fragmentPad:30,margin:24,fontSize:12};function eD(e,t={}){let n={...eL,...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,u=0,m=(e,t,s,r,a)=>{let i=l.get(s)??n.margin,o=l.get(r)??n.margin,c=s===r;c&&(u=Math.max(u,i+44+N("string"==typeof a?a:"",n.fontSize))),d.push({ref:e$(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&&m(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,u)+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&&m(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 eq=e=>e.replace(/[;#\n\r]+/g," ").replace(/\s+/g," ").trim(),eB=["propose","auto"];function eF(e,t){return"auto"===t||"propose"===t?t:e?.settings?.reconcile==="auto"?"auto":"propose"}let eU=["person","agent","service","external"];function ez(e){return e.toLowerCase().endsWith(".sysdf.json")}function eY(e){return!!e&&"object"==typeof e&&Array.isArray(e.members)&&!("state"in e)&&!("entities"in e)&&!("participants"in e)}function eH(e){return e.toLowerCase().endsWith(".erdf.json")?"erd":e.toLowerCase().endsWith(".sqdf.json")?"sequence":ez(e)?"system":"machine"}function eX(e){return e&&"object"==typeof e?K(e)?"erd":ej(e)?"sequence":eY(e)?"system":"state"in e?"machine":null:null}let eV=["erd","machine","sequence"];function eJ(e,t){return t.startsWith("/")?eW(t):eW((e.slice(0,e.lastIndexOf("/")+1)||"./")+t)}function eW(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 eK=e=>({settings:{...e.settings},members:(e.members??[]).map(e=>({...e})),actors:(e.actors??[]).map(e=>({...e}))});function eZ(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&""!==e))}function eG(e,t){let n=eK(e);return n.settings=eZ({...n.settings,...t}),n}let eQ=["refused","unknown-event","ended","state-mismatch"];function e0(e,t=0){return e.settings?.name||e.state?.name||`machine ${t+1}`}function e1(e){let t=e.map((e,t)=>e0(e,t));return t.map((e,n)=>t.indexOf(e)===n&&t.lastIndexOf(e)===n?e:`${e} #${n+1}`)}function e2(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 e5(e,t,n){let s=t;for(;s;){if(s===n)return!0;s=e.parent.get(s)}return!1}let e4=(e,t)=>e.states.get(t)?.kind==="final";function e3(e,t){let n,s,r=e1(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?e2(o,e.state.name):null,o})(e,0,r[t])),i=(s=[{name:"main",kind:"main",items:n=(e.messages??[]).map((e,t)=>({ref:e$(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:e$(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&&e4(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=e0(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=>e5(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=>!e4(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,u=new Set,m=[];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?e2(t,n.nextState):e;if(!s){m.push(n.nextState);continue}d.add(s),s!==e&&u.add(s),n.condition&&h.set(s,(h.get(s)??new Set).add(n.condition))}if(!d.size){let n=m.length?`${t.name}'s transition for "${o}" from ${c.join(" or ")} leads to ${[...new Set(m)].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=>e5(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=>u.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=>e4(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=>eQ.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 e6(e){let t={machines:[],erds:[],sequences:[]};for(let n of e)n.def&&!n.error&&eX(n.def)===n.kind&&("machine"===n.kind&&t.machines.push({member:n.path,def:n.def}),"erd"===n.kind&&t.erds.push({member:n.path,def:n.def}),"sequence"===n.kind&&t.sequences.push({member:n.path,def:n.def}));return t}function e8(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),eV.includes(eH(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),eU.includes(r.kind)||s("Y004",`Actor "${r.name}" has kind "${r.kind??""}"; expected one of ${eU.join(", ")}`,void 0,r.name)}}for(let e of t)e.error||!e.def?s("Y003",`"${e.path}" cannot be read: ${e.error??"no content"}`,e.path):eX(e.def)!==e.kind&&s("Y003",`"${e.path}" is named as a ${e.kind} but holds ${eX(e.def)??"something else"}`,e.path);let{machines:a,erds:i,sequences:o}=e6(t),l=new Map;for(let{member:e,def:t}of a){let n=e0(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 Z(t))s(n.ruleId,n.message,e,n.element);for(let{member:e,def:t}of o)for(let n of eM(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 Q(t,c))s(n.ruleId,n.message,e,n.element);let e=a.map(({def:e},t)=>e0(e,t));for(let{member:t,def:n}of i)for(let r of ee(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",`${e0(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)=>e0(e,t))),u=new Map,m=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)}u.set(e0(e,t),n);let s=e=>{e&&(m.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 eS(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?u.get(a.machine)?.has(a.event):[...u.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&&!m.has(a.state)&&r("L008",`Message ${e} says the machine is then in "${a.state}", which no member machine has`,t,n)}let o=e3(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 e7(e){return`${e.kind}:${e.name}`}function e9(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 te(e){let{machines:t,erds:n,sequences:s}=e6(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=e0(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 G(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=e1(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})=>e0(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 eS(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=e3(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 tt=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 tn(e,t){let n=e=>!!e&&(e.name===t||(e.states??[]).some(n)||(e.parallel?.states??[]).some(n));return n(e.state)}let ts=(e,t)=>t?"service":/\b(agent|bot|assistant)\b/i.test(e)?"agent":"person";function tr(e,t){let{machines:n,erds:s,sequences:r}=e6(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=ts(t.actor,t.service);o=function(e,t){if(!t.name?.trim())throw Error("An actor needs a name.");if(!eU.includes(t.kind))throw Error(`An actor is one of ${eU.join(", ")}; got '${t.kind}'.`);let n=eK(e);if((n.actors??[]).some(e=>e.name===t.name))throw Error(`Actor '${t.name}' already exists.`);return(n.actors??=[]).push(eZ({...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 eS(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=er(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),u=e1(h),p=h.map(()=>[]),f=h.map(()=>[]),g=(e,t,n)=>{h=h.map((n,s)=>s===e?m(n,t):n),p[e].push(...t),f[e].push(n)},x=e=>e.charAt(0).toLowerCase()+e.slice(1);for(let{def:e}of c)for(let t of e.entities??[])for(let e of t.attributes??[])for(let n of e?.stateOf===void 0?[]:Array.isArray(e.stateOf)?e.stateOf:[e.stateOf]){let s=u.findIndex((e,t)=>e===n||e0(h[t])===n);if(s<0)continue;let r=h[s].settings?.objects??[];if(r.some(e=>e.class===t.name))continue;let a=x(t.name);for(;r.some(e=>e.instance===a);)a+="_";g(s,[{op:"settings.update",patch:{objects:[...r,{instance:a,class:t.name}]}}],`${u[s]} is constructed with the object ${a} : ${t.name}, because ${t.name}.${e.name} stores its state`)}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}]}}],`${u[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=e1(r),i=new Map,o=[],l=new Set,c=e3(e,r),d=new Set,h="",u=(e,t,n)=>{d.add(`${e}|${JSON.stringify(t)}`),r=r.map((n,s)=>s===e?m(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})(e3(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("|")}`,m=c===h;h=c;let f=eN(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(m){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})`):u(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=`${tt(f.from)}Events`,o=tt(f.from),l=(n.events??[]).findIndex(e=>e?.name===s||e?.name===o||e?.name===f.from||e?.feeder===f.from),c=l>=0?n.events[l].name:s,d={id:f.event,...f.label?.trim()?{description:f.label.trim()}:{}};y(t,l>=0?[{op:"event.add",sourceIndex:l,event:d}]:[{op:"eventSource.add",source:{name:s,events:[d]}}],`${a[t]} defines "${f.event}" in ${c}, because ${g} fires it`);continue}if("refused"===s.result){let e=a.indexOf(s.machine??"");if(!f.state){x(i,`${g}: ${s.machine} refuses "${f.event}" from ${s.from.join(" or ")}; give the message a state to say where it leads, and reconcile can add the transition`);continue}if(1!==s.from.length){x(i,`${g}: ${s.machine} could be in ${s.from.join(" or ")}; choose which state "${f.event}" leaves from`);continue}let t=r[e],n=s.from[0],o=tn(t,f.state);if(!o&&!f.machine){let t=a.filter((t,n)=>n!==e&&tn(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,...f.label?.trim()?{description:`Reached when: ${f.label.trim()}`}:{},transitions:[]}}),c.push(d?`gains its first state, ${f.state}`:`adds the state ${f.state}`)),d){y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says the machine is there`);continue}let h=f.label?.trim()?{description:f.label.trim()}:{};l.push(n===f.state?{op:"transition.add",state:n,transition:{event:f.event,...h}}:{op:"transition.add",state:n,transition:{event:f.event,nextState:f.state,...h}}),c.push(n===f.state?`handles "${f.event}" in ${n} without leaving it`:`goes from ${n} to ${f.state} on "${f.event}"`),y(e,l,`${a[e]} ${c.join(" and ")}, because ${g} says so`);continue}if("state-mismatch"===s.result){x(i,`${g}: ${s.note??"the scenario and the machine disagree"}; one of them has to change, and that is a person's call`);continue}x(i,`${g}: ${s.note??s.result}`)}return p&&o.push(`reconcile stopped after ${s} rounds; what it proposed so far is kept, and the rest needs a person`),{proposals:[...i.values()].sort((e,t)=>e.index-t.index),unresolved:o,before:c,after:e3(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 y=n.map((e,t)=>({member:e.member,index:t,machine:u[t],ops:p[t],reasons:f[t],def:h[t]})).filter(e=>e.ops.length),b=c.filter(e=>e.reasons.length);return{machines:y,erds:b,system:o&&l.length?{def:o,reasons:l}:null,unresolved:a,count:y.reduce((e,t)=>e+t.reasons.length,0)+b.reduce((e,t)=>e+t.reasons.length,0)+l.length}}function ta(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}`}let ti="default",to=/^[A-Za-z0-9._-]{1,64}$/;function tl(e){return"string"==typeof e&&to.test(e)}let tc=["comment","question","looks_good","delete"],td=["open","answered","resolved"],th=e=>"string"==typeof e?e:"";function tu(e){let t=e&&"object"==typeof e?e:{},n="agent"===t.role?"agent":"person",s=th(t.name)||th(t.id)||("agent"===n?"agent":"someone");return{id:th(t.id)||s,name:s,role:n}}function tm(e){let t=e&&"object"==typeof e?e:{},n=th(t.text).trim();return n?{author:tu(t.author),text:n,at:th(t.at)}:null}function tp(e){if(!e||"object"!=typeof e)return null;let t=th(e.id),n=th(e.text).trim();if(!t||!n)return null;let s=Array.isArray(e.elements)?e.elements.filter(e=>"string"==typeof e&&e.length>0):[],r=function(e){if(!e||"object"!=typeof e)return;let t=t=>"number"==typeof e[t]&&Number.isFinite(e[t])?e[t]:NaN,n={x:t("x"),y:t("y"),width:t("width"),height:t("height")};if(!Object.values(n).some(Number.isNaN)&&!(n.width<=0)&&!(n.height<=0))return n}(e.region),a=Array.isArray(e.replies)?e.replies.map(tm).filter(e=>null!==e):[];return{id:t,kind:tc.includes(e.kind)?e.kind:"comment",...s.length?{elements:s}:{},...r?{region:r}:{},...th(e.level)?{level:th(e.level)}:{},text:n,author:tu(e.author),at:th(e.at),status:td.includes(e.status)?e.status:"open",...a.length?{replies:a}:{}}}function tf(e){let t=[];if(e.elements?.length&&t.push(e.elements.join(", ")),e.region){let n=e.region;t.push(`the area ${Math.round(n.x)},${Math.round(n.y)} ${Math.round(n.width)}\xd7${Math.round(n.height)}${e.level?` inside ${e.level}`:""}`)}return t.length?t.join(" in "):"the drawing"}function tg(e){let t;return"number"==typeof(t=e.holdMs)&&Number.isFinite(t)&&e.holdMs>=0?e.holdMs:Math.min(2e4,Math.max(2500,1200+400*`${e.title??""} ${e.say??""}`.trim().split(/\s+/).filter(Boolean).length))}function tx(e){if(!e.length)return null;let t=1/0,n=1/0,s=-1/0,r=-1/0;for(let a of e)t=Math.min(t,a.x),n=Math.min(n,a.y),s=Math.max(s,a.x+a.width),r=Math.max(r,a.y+a.height);return{x:t,y:n,width:s-t,height:r-n}}function ty(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function tb(e,t){let n=new Set(t);return e.filter(e=>n.has(e.focus)).map(e=>e.box)}let tv=e=>e.split("/").pop()||e;function tw(e){return e.replace(/\s+/g," ").trim()}function tj(e){return e.parallel?e.parallel.states:e.states??[]}function tk(e,t){return tj(e).find(e=>e.name===t)??null}function t$(e,t){return tj(function(e,t){let n=e;for(let e of t){let t=tk(n,e);if(!t)break;n=t}return n}(e,t))}let tN={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 tS(e){let t={};if(!e)return t;for(let[n,s]of Object.entries(e)){let e=tN[n];e&&"string"==typeof s&&(t[e]=s)}return t}let tM={x:100,y:100,width:160,height:60};function tC(e,t){return 1===t?16*e:2===t?400*e:e}function tE(e){return!!e&&"string"==typeof e.tagName&&(!!e.isContentEditable||["INPUT","TEXTAREA","SELECT","BUTTON","OPTION"].includes(e.tagName))}function tR(e){return(e.states?.length??0)>0||(e.parallel?.states.length??0)>0}function t_({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 tA={kind:null,id:null},tT=(0,l.forwardRef)(function(e,t){let{definition:n,positions:s,path:r=[],rootLabel:a,viewport:i,onViewportChange:c,selection:d=tA,activeStates:h,errorElements:u,drawMode:m="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:M,onDeleteState:E,onUndo:R,onRedo:A,hudExtras:P,emptyHint:I,theme:B,className:F,style:V,svgId:J,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),eu=(0,l.useRef)(new Map),em=(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=tk(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?t$(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]),eM=(0,l.useMemo)(()=>new Set(u??[]),[u]),eC=(0,l.useCallback)((e,t)=>{let n=K.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]),eE=(0,l.useCallback)(e=>{let t=eu.current.get(e);eu.current.delete(e),t?.hasPointerCapture?.(e)&&t.releasePointerCapture?.(e)},[]),eR=(0,l.useCallback)(e=>{let t=ex.current;t&&(void 0===e||t.pointerId===e)&&(clearTimeout(t.timer),ex.current=null)},[]),e_=(0,l.useCallback)((e,t)=>{if("touch"!==e.pointerType||!$)return;eR();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}},[eR,$,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=>{em.current.delete(e.pointerId)};return window.addEventListener("pointerup",e),window.addEventListener("pointercancel",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("pointercancel",e)}},[]),(0,l.useEffect)(()=>()=>eR(),[eR]);let eA=(0,l.useRef)(new Set),eT=(0,l.useRef)(new Map),eO=(0,l.useRef)(e$),eP=(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),eU=eb?10/i.scale:0,ez=eb?28/i.scale:0,eY=(0,l.useCallback)(e=>s[e]??tM,[s]);(0,l.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&"z"===e.key&&R&&(e.preventDefault(),R()),(e.ctrlKey||e.metaKey)&&("y"===e.key||e.shiftKey&&"z"===e.key)&&A&&(e.preventDefault(),A()),"Escape"===e.key&&(er(null),M?.()),"Delete"===e.key&&"state"===d.kind&&d.id&&E&&E(d.id)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[R,A,M,E,d]);let eH=(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&&(eu.current.set(e.pointerId,n),n.setPointerCapture(e.pointerId))},[]),eX=(0,l.useCallback)(()=>{let e=[...em.current.entries()];if(e.length<2)return;let[[t,n],[s,r]]=e;eR(),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(!eu.current.has(e))try{o.setPointerCapture(e),eu.current.set(e,o)}catch{}}},[eR,eC,en]),eV=(0,l.useCallback)(e=>{if(ey.current=!1,"touch"!==e.pointerType)return;ev(!0),em.current.set(e.pointerId,{x:e.clientX,y:e.clientY});let t=em.current.size;t<2||(e.stopPropagation(),2===t&&eX())},[eX]),eJ=(0,l.useCallback)((e,t)=>{if(0!==e.button||ea.current)return;if(e.stopPropagation(),e_(e,{kind:"state",id:t}),!f&&"transition"===m)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=eY(t);en({name:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,origX:n.x,origY:n.y});let s=e.currentTarget;eu.current.set(e.pointerId,s),s.setPointerCapture?.(e.pointerId)},[b,eY,m,p,e_,en,f,w]),eW=(0,l.useCallback)(e=>{if("touch"===e.pointerType){e_(e,{kind:"canvas"}),eH(e);return}(1===e.button||0===e.button&&ea.current)&&(e.preventDefault(),eH(e))},[e_,eH]),eK=(0,l.useCallback)(e=>{em.current.has(e.pointerId)&&em.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&&eR(e.pointerId);let n=ep.current;if(n){if(e.pointerId!==n.a&&e.pointerId!==n.b)return;let t=em.current.get(n.a),s=em.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(U(Y(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=eY(Q.name);w(Q.name,{...o,x:Math.max(0,Q.origX+a),y:Math.max(0,Q.origY+i)})},[Q,eY,w,c,eR,eC]),eZ=(0,l.useCallback)(e=>{em.current.delete(e.pointerId),eR(e.pointerId),eE(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=em.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)},[eR,eE,en]);(0,l.useEffect)(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault();let t=G.current,n=tC(e.deltaX,e.deltaMode),s=tC(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey){let n=z(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(U(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||tE(e.target)||tE(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=z(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(Y(G.current,1,t))},[c]),e0=(0,l.useCallback)(()=>{let e=K.current?.getBoundingClientRect();if(!e)return;let t=ek.map(e=>eY(e.name));c(t.length?H(t,e.width,e.height):{...q})},[ek,eY,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,eY),t=new Map(_(e5.map((t,n)=>{let s=eY(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=>eY(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,eY]);(0,l.useEffect)(()=>{let e=new Set(ek.map(e=>e.name)),t=new Set(e5.map(e=>`${e.stateName}:${e.index}`)),n=eO.current===e$,s=[...e].filter(e=>!eA.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=>!eP.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 eT.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),eA.current=e,eT.current=new Map(ek.map(e=>[e.name,{state:e,pos:eY(e.name)}])),eP.current=t,eO.current=e$},[ek,e$,e5,eY]);let e3={...tS(B),...V},e6=eb?" slc-hud--coarse":"";return(0,o.jsxs)("div",{className:`slc-pane${F?` ${F}`:""}`,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:J,className:"slc-surface",style:{cursor:ec?"grabbing":ei?"grab":void 0,touchAction:"none",...eb?{WebkitUserSelect:"none",userSelect:"none",WebkitTouchCallout:"none"}:{}},onPointerDownCapture:eV,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"===m&&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-eU,y:s.y-eU,width:s.width+2*eU,height:s.height+2*eU,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)(t_,{mark:function(e){let t=e.toLowerCase();for(let{glyph:e,words:n}of O)if(n.some(e=>t.includes(e)))return e;return T}(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=eY(e.name),n="state"===d.kind&&d.id===e.name,s="final"===e.kind,r="history"===e.kind,a=tR(e),i=p===e.name,l=eM.has(e.name),c=(e.onEntry?.actions?.length??0)>0,h=(e.onExit?.actions?.length??0)>0,u=eS.has(e.name),g=eI.has(e.name),x=ei?void 0:"transition"!==m||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=>eJ(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-eU,y:t.y-eU,width:t.width+2*eU,height:t.height+2*eU,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":"",u?"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=tR(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"}),P&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"slc-hud-sep",children:"|"}),P]}),(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),M?.())},children:e},e)),(0,o.jsx)("button",{type:"button",className:"slc-picker-cancel",onClick:()=>{er(null),M?.()},children:"Cancel"})]})]})});function tO(e,t){return 1===t?16*e:2===t?400*e:e}let tP={"1:1":["one","one"],"1:N":["one","many"],"N:1":["many","one"],"N:M":["many","many"]};function tI(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 tL(e){return[e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n\n")}function tD(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 tq({definition:e,notation:t="crowsfoot",positions:n,viewport:s,onViewportChange:r,selection:a=null,errorElements:i,readOnly:c=!1,fitKey:d,onSelect:h,onClearSelection:u,onEntityMove:m,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]),M="chen"===t,C=(0,l.useMemo)(()=>new Map(M?S.map(e=>{var t;let s,r,a,i,o,l,c;return[e.name,(t=n[e.name],s=ei(e),r=eo(e),a={x:t.x+(t.width-r)/2,y:t.y+(t.height-40)/2,width:r,height:40},i=el(s),o=a.y+a.height/2,l=ec(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}})]}):[]),[M,S,n]),E=(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]),R=(0,l.useMemo)(()=>_(E.filter(({rel:e})=>M||e.label).map(({rel:e,curve:t})=>({event:e.label||" ",at:t.at,rel:e})),S.map(e=>n[e.name])),[M,E,S,n]),A=(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(H(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=tO(e.deltaX,e.deltaMode),s=tO(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void r(z(t,Math.exp(-(.0025*s)),A(e.clientX,e.clientY)));let a=e.shiftKey?-(n||s):-n,i=e.shiftKey?0:-s;(0!==a||0!==i)&&r(U(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[r,A]);let T=()=>{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}}},O=(e,t)=>{if(0!==e.button&&"mouse"===e.pointerType)return;if(e.stopPropagation(),w.current?.setPointerCapture(e.pointerId),$.current.set(e.pointerId,A(e.clientX,e.clientY)),$.current.size>=2){k.current=null,N.current=T();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}},P=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):u?.()))},I=new Set(i??[]);return(0,o.jsxs)("div",{className:`slc-pane${y?` ${y}`:""}`,style:{...tS(x),...b},children:[(0,o.jsx)("svg",{ref:w,id:v,className:"slc-surface",onPointerDown:e=>O(e),onPointerMove:e=>{if($.current.has(e.pointerId)&&$.current.set(e.pointerId,A(e.clientX,e.clientY)),N.current){let e=T();if(!e)return;let t=N.current;r(z(U(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(U(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});m?.(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:P,onPointerCancel:P,onContextMenu:e=>{f&&(e.preventDefault(),f(e.clientX,e.clientY,{kind:"canvas"}))},children:(0,o.jsxs)("g",{transform:X(s),children:[E.map(({rel:e,curve:t},n)=>{if(M){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:tD(C.get(e.from)?.rect,t.p0),className:"slc-erd-line"}),(0,o.jsx)("path",{d:tD(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]=tP[e.cardinality]??tP["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:tI(t.p0,t.p1,s),className:"slc-erd-mark"}),(0,o.jsx)("path",{d:tI(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=>O(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),[`${ey(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)}),tL(e)&&(0,o.jsx)("title",{children:tL(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=>O(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[tL(e)&&(0,o.jsx)("title",{children:tL(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?"◉ ":"",ey(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)}),R.map((e,t)=>{if(!M)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}`)}),!M&&R.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 tB(e,t){return 1===t?16*e:2===t?400*e:e}function tF(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 tU(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 tz=e=>"string"==typeof e?e:null==e?"":String(e);function tY(e){let t=e&&"object"==typeof e?e:{};return{from:tz(t.from),to:tz(t.to),label:tz(t.label),event:tz(t.event)||void 0,machine:tz(t.machine)||void 0,carries:tz(t.carries)||void 0,state:tz(t.state)||void 0,description:tz(t.description)||void 0,notes:tz(t.notes)||void 0,optional:!0===t.optional||void 0,reply:!0===t.reply||void 0}}function tH(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:tz(s.namespace),name:tz(s.name),notes:tz(s.notes)||void 0},participants:n(t.participants).map(e=>{let t=e&&"object"==typeof e?e:{};return{name:tz(t.name),description:tz(t.description)||void 0,notes:tz(t.notes)||void 0,actor:tz(t.actor)||void 0,service:tz(t.service)||void 0,object:tz(t.object)||void 0,holds:Array.isArray(t.holds)?t.holds.map(tz):"string"==typeof t.holds?[t.holds]:void 0}}),messages:n(t.messages).map(tY),...Array.isArray(t.fragments)?{fragments:t.fragments.map(e=>{let t=e&&"object"==typeof e?e:{};return{kind:tz(t.kind),label:tz(t.label),after:"number"==typeof t.after&&Number.isFinite(t.after)?t.after:0,notes:tz(t.notes)||void 0,messages:n(t.messages).map(tY)}})}:{}}}function tX({definition:e,layout:t,viewport:n,onViewportChange:s,selection:r=null,errorElements:a,warningElements:i,fitKey:c,onSelect:d,onClearSelection:h,onContextMenu:u,emptyHint:m,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)(()=>tH(e),[e]),$=(0,l.useMemo)(()=>t??eD(k),[t,k]),S=(0,l.useRef)(new Map),[M,C]=(0,l.useState)({}),E=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((M[n]??-1)-r)>.5&&(t=!0))}t&&C(e)},[$,k]);let R=(0,l.useMemo)(()=>new Map(eS(k).map(e=>[e.ref,e.message])),[k]),_=(0,l.useMemo)(()=>new Map(k.participants.filter(e=>e.name).map(e=>[e.name,e])),[k.participants]),A=(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(H([{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=tB(e.deltaX,e.deltaMode),r=tB(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void s(z(t,Math.exp(-(.0025*r)),A(e.clientX,e.clientY)));let a=e.shiftKey?-(n||r):-n,i=e.shiftKey?0:-r;(0!==a||0!==i)&&s(U(t,a,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[s,A]);let T=()=>{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}}},O=(e,t)=>{if(0===e.button||"mouse"!==e.pointerType){if(e.stopPropagation(),y.current?.setPointerCapture(e.pointerId),w.current.set(e.pointerId,A(e.clientX,e.clientY)),w.current.size>=2){v.current=null,j.current=T();return}v.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,target:t,moved:!1}}},P=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=>{u&&(t.preventDefault(),t.stopPropagation(),u(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"?R.get(r.id):void 0;return(0,o.jsxs)("div",{className:`slc-pane${f?` ${f}`:""}`,style:{...tS(p),...g},children:[(0,o.jsx)("svg",{ref:y,id:x,className:"slc-surface",onPointerDown:e=>O(e),onPointerMove:e=>{if(w.current.has(e.pointerId)&&w.current.set(e.pointerId,A(e.clientX,e.clientY)),j.current){let e=T();if(!e)return;let t=j.current;s(z(U(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(U(b.current,e.clientX-t.lastX,e.clientY-t.lastY)),t.lastX=e.clientX,t.lastY=e.clientY)},onPointerUp:P,onPointerCancel:P,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=>O(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=R.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),u=["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(" "),m=`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=M[`${e.ref}:label`]??N(i.label??"",11),x=i.optional?N("opt",10)+8:0,y=i.event?(M[`${e.ref}:event`]??6.1*i.event.length)+12:0,b=i.state?`→ ${i.state}`:"",v=i.state?M[`${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:u}),(0,o.jsx)("path",{d:tF(t+1,c,-1,!!i.reply),className:m})]}),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:u}),(0,o.jsx)("path",{d:tF(l,e.y,t,!!i.reply),className:m})]}),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,_=y?k(y):0,A=v?k(v):0;return(0,o.jsxs)("g",{className:"slc-sqd-message",onPointerDown:t=>O(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:E(`${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:_,y:s-10.5,width:y,height:14,rx:7,className:"slc-sqd-event"}),(0,o.jsx)("text",{ref:E(`${e.ref}:event`),x:_+y/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-event-text",children:i.event})]}),v>0&&(0,o.jsx)("text",{ref:E(`${e.ref}:state`),x:A,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=_.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=>O(t,{kind:"participant",id:e.name}),onContextMenu:I({kind:"participant",id:e.name}),children:[tU(t)&&(0,o.jsx)("title",{children:tU(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&&m&&(0,o.jsx)("div",{className:"slc-erd-empty",children:m})]})}function tV({viewport:e,boxes:t,spotlight:n,region:s,marks:r,selectedMark:a=null,onSelectMark:i,hideResolved:c=!0,marking:d=!1,onDraft:h,draft:u=null,theme:m,className:p,style:f}){let g=`slc-stage-mask-${(0,l.useId)().replace(/[^a-zA-Z0-9_-]/g,"")}`,x=(0,l.useRef)(null),y=(0,l.useRef)(null),[b,v]=(0,l.useState)(null),w=(0,l.useMemo)(()=>n?.length?tb(t,n).map(e=>ty(e,8)):[],[t,n]),j=X(e),k=r?.find(e=>e.id===a)??null,$=(0,l.useMemo)(()=>{let e=[];return k?.elements?.length&&e.push(...tb(t,k.elements)),u?.elements.length&&e.push(...tb(t,u.elements)),e.map(e=>ty(e,4))},[t,k,u]),N=[k?.region,u?.region].filter(e=>!!e),S=(r??[]).map((e,t)=>({mark:e,n:t+1})).filter(({mark:e})=>!(c&&"resolved"===e.status&&e.id!==a)).map(({mark:n,n:s})=>{var r;let a=tx(n.elements?.length?tb(t,n.elements):[])??n.region??null;if(!a)return null;let i={x:(r={x:a.x+a.width,y:a.y}).x*e.scale+e.x,y:r.y*e.scale+e.y};return{mark:n,n:s,x:i.x,y:i.y}}).filter(e=>null!==e),M=e=>{let t=x.current?.getBoundingClientRect();return{x:e.clientX-(t?.left??0),y:e.clientY-(t?.top??0)}};return(0,o.jsxs)("div",{ref:x,className:`slc-stage${d?" slc-stage--marking":""}${p?` ${p}`:""}`,style:{...tS(m),...f},children:[(0,o.jsxs)("svg",{className:"slc-stage-svg","aria-hidden":"true",children:[w.length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("defs",{children:(0,o.jsxs)("mask",{id:g,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"100%",height:"100%",children:[(0,o.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:"white"}),(0,o.jsx)("g",{transform:j,children:w.map((e,t)=>(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:10,fill:"black"},t))})]})}),(0,o.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",className:"slc-stage-scrim",mask:`url(#${g})`}),(0,o.jsx)("g",{transform:j,children:w.map((e,t)=>(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:10,className:"slc-stage-ring",vectorEffect:"non-scaling-stroke"},t))})]}),(0,o.jsxs)("g",{transform:j,children:[s&&(0,o.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,rx:6,className:"slc-stage-region",vectorEffect:"non-scaling-stroke"}),$.map((e,t)=>(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:8,className:"slc-stage-mark-ring",vectorEffect:"non-scaling-stroke"},`r${t}`)),N.map((e,t)=>(0,o.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:4,className:"slc-stage-mark-area",vectorEffect:"non-scaling-stroke"},`f${t}`))]}),b&&(0,o.jsx)("rect",{x:b.x,y:b.y,width:b.w,height:b.h,rx:4,className:"slc-stage-drag"})]}),S.map(({mark:e,n:t,x:n,y:s})=>(0,o.jsxs)("button",{type:"button",className:`slc-stage-pin slc-stage-pin--${"resolved"===e.status?"resolved":"agent"===e.author.role?"answered"===e.status?"answered":"question":"answered"===e.status?"answered":"open"}${e.id===a?" slc-stage-pin--selected":""}`,style:{left:n,top:s},title:`${e.author.name}: ${e.text}${e.replies?.length?` (${e.replies.length} repl${1===e.replies.length?"y":"ies"})`:""}`,"aria-label":`Mark ${t}, ${e.status}: ${e.text}`,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),i?.(e.id)},children:[t,(e.replies?.length??0)>0&&(0,o.jsx)("span",{className:"slc-stage-pin-count",children:e.replies.length})]},e.id)),d&&(0,o.jsx)("div",{className:"slc-stage-catch",onPointerDown:e=>{if(0!==e.button&&"mouse"===e.pointerType)return;e.currentTarget.setPointerCapture(e.pointerId);let t=M(e);y.current={id:e.pointerId,x:t.x,y:t.y,moved:!1}},onPointerMove:e=>{let t=y.current;if(!t||t.id!==e.pointerId)return;let n=M(e);!t.moved&&6>Math.hypot(n.x-t.x,n.y-t.y)||(t.moved=!0,v({x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),w:Math.abs(n.x-t.x),h:Math.abs(n.y-t.y)}))},onPointerUp:n=>{let s=y.current;if(!s||s.id!==n.pointerId)return;y.current=null,v(null);let r=M(n);if(s.moved){let n=F(e,{x:Math.min(s.x,r.x),y:Math.min(s.y,r.y)}),a=F(e,{x:Math.max(s.x,r.x),y:Math.max(s.y,r.y)}),i={x:n.x,y:n.y,width:Math.max(1,a.x-n.x),height:Math.max(1,a.y-n.y)};h?.({elements:function(e,t,n=1/3){let s=[];for(let{focus:r,box:a}of e){let e=a.width*a.height;!(e<=0||s.includes(r))&&function(e,t){let n=Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x),s=Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y);return n>0&&s>0?n*s:0}(a,t)/e>=n&&s.push(r)}return s}(t,i),region:i});return}let a=F(e,r),i=function(e,t,n){let s=null;for(let r of e){let{box:e}=r;t<e.x||n<e.y||t>e.x+e.width||n>e.y+e.height||(!s||e.width*e.height<s.box.width*s.box.height)&&(s=r)}return s?.focus??null}(t,a.x,a.y);if(i)return h?.({elements:[i]});let o=28/(e.scale||1);h?.({elements:[],region:{x:a.x-o,y:a.y-o,width:2*o,height:2*o}})},onPointerCancel:()=>{y.current=null,v(null)}})]})}function tJ({size:e=16,children:t,...n}){return(0,o.jsx)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",className:"slc-icon",...n,children:t})}function tW(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),(0,o.jsx)("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21M8.5 21h7"})]})}function tK(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("path",{d:"M4 9.5h3.5L12 5.5v13l-4.5-4H4z"}),(0,o.jsx)("path",{d:"M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11"})]})}function tZ(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("path",{d:"M4 9.5h3.5L12 5.5v13l-4.5-4H4z"}),(0,o.jsx)("path",{d:"M16 10l4 4M20 10l-4 4"})]})}function tG(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("path",{d:"M5 5h14a1.5 1.5 0 0 1 1.5 1.5v8A1.5 1.5 0 0 1 19 16h-7l-4.5 3.5V16H5a1.5 1.5 0 0 1-1.5-1.5v-8A1.5 1.5 0 0 1 5 5z"})})}function tQ(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("path",{d:"M8 5.5v13l10-6.5z",fill:"currentColor"})})}function t0(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("path",{d:"M8.5 5.5v13M15.5 5.5v13",strokeWidth:2.6})})}function t1(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("rect",{x:"7",y:"7",width:"10",height:"10",rx:"1.5",fill:"currentColor"})})}function t2(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("path",{d:"M17 5.5v13L8 12z"}),(0,o.jsx)("path",{d:"M6.5 5.5v13"})]})}function t5(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("path",{d:"M7 5.5v13l9-6.5z"}),(0,o.jsx)("path",{d:"M17.5 5.5v13"})]})}function t4(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("path",{d:"M7.5 10.5v9H4.5v-9zM7.5 10.5l3.5-6.5a2 2 0 0 1 2.5 2.2l-.6 3.3h5.4a2 2 0 0 1 2 2.4l-1.3 6.2a2 2 0 0 1-2 1.4H7.5"})})}function t3(e){return(0,o.jsx)(tJ,{...e,style:{transform:"scaleY(-1)",...e.style},children:(0,o.jsx)("path",{d:"M7.5 10.5v9H4.5v-9zM7.5 10.5l3.5-6.5a2 2 0 0 1 2.5 2.2l-.6 3.3h5.4a2 2 0 0 1 2 2.4l-1.3 6.2a2 2 0 0 1-2 1.4H7.5"})})}function t6(e){return(0,o.jsx)(tJ,{...e,children:(0,o.jsx)("path",{d:"M6.5 6.5l11 11M17.5 6.5l-11 11"})})}function t8(e){return(0,o.jsxs)(tJ,{...e,children:[(0,o.jsx)("path",{d:"M4.5 19.5l1-4.2L15.8 5a1.8 1.8 0 0 1 2.5 0l.7.7a1.8 1.8 0 0 1 0 2.5L8.7 18.5z"}),(0,o.jsx)("path",{d:"M13.8 7l3.2 3.2"})]})}function t7({shown:e,playing:t=!1,speaking:n=!1,voice:s,onToggleVoice:r,onPlay:a,onPause:i,onNext:l,onPrev:c,onGoto:d,onClose:h,onAnswer:u,theme:m,className:p,style:f}){if(!e)return null;let{step:g,index:x,count:y,title:b,origin:v}=e,w=null!==x&&null!==y,j=[b,g.title].filter(Boolean).join(" · ");return(0,o.jsxs)("section",{className:`slc-stage-caption${p?` ${p}`:""}`,style:{...tS(m),...f},role:"region","aria-label":"What the agent is showing","aria-live":"polite",children:[(0,o.jsxs)("header",{className:"slc-stage-caption-head",children:[v&&(0,o.jsx)("span",{className:"slc-stage-caption-origin",children:v}),j&&(0,o.jsx)("span",{className:"slc-stage-caption-title",children:j}),w&&(0,o.jsxs)("span",{className:"slc-stage-caption-count",children:[x+1," / ",y]}),n&&(0,o.jsx)("span",{className:"slc-stage-caption-speaking","aria-label":"speaking"}),h&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:h,"aria-label":"Close",title:"Close",children:(0,o.jsx)(t6,{})})]}),(0,o.jsx)("p",{className:"slc-stage-caption-say",children:g.say}),w&&y<=24&&y>1&&(0,o.jsx)("nav",{className:"slc-stage-dots","aria-label":"Steps",children:Array.from({length:y},(e,t)=>(0,o.jsx)("button",{type:"button",className:`slc-stage-dot${t===x?" slc-stage-dot--current":t<x?" slc-stage-dot--seen":""}`,onClick:()=>d?.(t),"aria-label":`Step ${t+1}`,"aria-current":t===x?"step":void 0},t))}),(0,o.jsxs)("footer",{className:"slc-stage-caption-controls",children:[w&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:c,disabled:0===x,"aria-label":"Previous step",title:"Previous step",children:(0,o.jsx)(t2,{})}),t?(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:i,"aria-label":"Pause",title:"Pause",children:(0,o.jsx)(t0,{})}):(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:a,"aria-label":"Play",title:"Play",children:(0,o.jsx)(tQ,{})}),(0,o.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:l,disabled:x===y-1,"aria-label":"Next step",title:"Next step",children:(0,o.jsx)(t5,{})})]}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),void 0!==s&&(0,o.jsx)("button",{type:"button",className:`slc-stage-btn${s?" slc-stage-btn--on":""}`,onClick:r,"aria-pressed":s,title:s?"Voice on — the steps are read aloud":"Voice off — the steps are read on screen",children:s?(0,o.jsx)(tK,{}):(0,o.jsx)(tZ,{})}),u&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--answer",onClick:u,title:"Answer — mark what is lit and say something about it",children:"Answer"})]})]})}let t9={comment:"Comment",question:"Question",looks_good:"Looks good",delete:"Should go"};function ne(e,t){let[n,s]=(0,l.useState)(!1),r=(0,l.useRef)("");return(0,l.useEffect)(()=>()=>e?.stop(),[e]),{listening:n,toggle:a=>{if(e){if(n){e.stop(),s(!1);return}r.current=a?`${a.trimEnd()} `:"",s(!0),e.start(e=>t(r.current+e),()=>s(!1))}}}}function nt({elements:e,region:t}){return e?.length||t?(0,o.jsxs)(o.Fragment,{children:[e?.map(e=>(0,o.jsx)("span",{className:"slc-stage-chip",children:e},e)),t&&!e?.length&&(0,o.jsx)("span",{className:"slc-stage-chip slc-stage-chip--quiet",children:"an area"})]}):(0,o.jsx)("span",{className:"slc-stage-chip slc-stage-chip--quiet",children:"the drawing"})}function nn({elements:e,region:t,author:n,onAuthorChange:s,onSubmit:r,onCancel:a,listener:i,listenAtOnce:c=!1,busy:d=!1,error:h,placeholder:u="What should the agent know about this?",theme:m,className:p,style:f}){let[g,x]=(0,l.useState)(""),[y,b]=(0,l.useState)("comment"),[v,w]=(0,l.useState)(n),{listening:j,toggle:k}=ne(i,x),$=(0,l.useRef)(null);(0,l.useEffect)(()=>{c&&i?k(""):$.current?.focus()},[]);let N=e=>{if(e?.preventDefault(),!g.trim()||d)return;j&&i?.stop();let t=n||v.trim();!n&&t&&s?.(t),r({text:g.trim(),kind:y,author:t})};return(0,o.jsxs)("form",{className:`slc-stage-card slc-stage-composer${p?` ${p}`:""}`,style:{...tS(m),...f},onSubmit:N,onPointerDown:e=>e.stopPropagation(),children:[(0,o.jsxs)("div",{className:"slc-stage-card-anchor",children:[(0,o.jsx)("span",{className:"slc-stage-card-label",children:"On"}),(0,o.jsx)(nt,{elements:e,region:t})]}),(0,o.jsx)("textarea",{ref:$,className:"slc-stage-input slc-stage-textarea",value:g,placeholder:j?"Listening…":u,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&N(),"Escape"===e.key&&a()},rows:3}),!n&&(0,o.jsx)("input",{className:"slc-stage-input",value:v,placeholder:"Your name (signs your marks)",onChange:e=>w(e.target.value)}),(0,o.jsxs)("div",{className:"slc-stage-card-row",children:[(0,o.jsx)("select",{className:"slc-stage-input slc-stage-select",value:y,onChange:e=>b(e.target.value),"aria-label":"Kind of mark",children:tc.map(e=>(0,o.jsx)("option",{value:e,children:t9[e]},e))}),i&&(0,o.jsx)("button",{type:"button",className:`slc-stage-btn${j?" slc-stage-btn--live":""}`,onClick:()=>k(g),"aria-pressed":j,title:j?"Stop listening":"Speak instead of typing",children:(0,o.jsx)(tW,{})}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:a,children:"Cancel"}),(0,o.jsx)("button",{type:"submit",className:"slc-stage-btn slc-stage-btn--main",disabled:!g.trim()||d||!n&&!v.trim(),children:d?"Saving…":"Mark"})]}),h&&(0,o.jsx)("div",{className:"slc-stage-card-error",children:h})]})}function ns({mark:e,number:t,onReply:n,onResolve:s,onReopen:r,onRemove:a,onClose:i,listener:c,busy:d=!1,error:h,theme:u,className:m,style:p}){let[f,g]=(0,l.useState)(""),{listening:x,toggle:y}=ne(c,g);return(0,o.jsxs)("div",{className:`slc-stage-card slc-stage-thread${m?` ${m}`:""}`,style:{...tS(u),...p},onPointerDown:e=>e.stopPropagation(),children:[(0,o.jsxs)("div",{className:"slc-stage-card-row",children:[void 0!==t&&(0,o.jsx)("span",{className:`slc-stage-pin slc-stage-pin--inline slc-stage-pin--${"resolved"===e.status?"resolved":e.status}`,children:t}),(0,o.jsxs)("span",{className:"slc-stage-card-label",children:[t9[e.kind]," · ",e.status]}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:i,"aria-label":"Close",children:(0,o.jsx)(t6,{})})]}),(0,o.jsx)("div",{className:"slc-stage-card-anchor",children:(0,o.jsx)(nt,{elements:e.elements,region:e.region})}),(0,o.jsxs)("ol",{className:"slc-stage-thread-list",children:[(0,o.jsxs)("li",{className:`slc-stage-said slc-stage-said--${e.author.role}`,children:[(0,o.jsx)("span",{className:"slc-stage-said-who",children:e.author.name}),(0,o.jsx)("span",{className:"slc-stage-said-text",children:e.text})]}),(e.replies??[]).map((e,t)=>(0,o.jsxs)("li",{className:`slc-stage-said slc-stage-said--${e.author.role}`,children:[(0,o.jsx)("span",{className:"slc-stage-said-who",children:e.author.name}),(0,o.jsx)("span",{className:"slc-stage-said-text",children:e.text})]},t))]}),n&&(0,o.jsxs)("form",{className:"slc-stage-card-row",onSubmit:e=>{e?.preventDefault(),f.trim()&&!d&&(x&&c?.stop(),n?.(f.trim()),g(""))},children:[(0,o.jsx)("input",{className:"slc-stage-input slc-stage-grow",value:f,placeholder:x?"Listening…":"Reply…",onChange:e=>g(e.target.value)}),c&&(0,o.jsx)("button",{type:"button",className:`slc-stage-btn${x?" slc-stage-btn--live":""}`,onClick:()=>y(f),"aria-pressed":x,title:"Speak the reply",children:(0,o.jsx)(tW,{})}),(0,o.jsx)("button",{type:"submit",className:"slc-stage-btn slc-stage-btn--main",disabled:!f.trim()||d,children:"Reply"})]}),(0,o.jsxs)("div",{className:"slc-stage-card-row",children:["resolved"===e.status?r&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:r,children:"Reopen"}):s&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:s,children:"Resolve"}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),a&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--danger",onClick:a,children:"Remove"})]}),h&&(0,o.jsx)("div",{className:"slc-stage-card-error",children:h})]})}function nr({marks:e,selected:t,onSelect:n,onCopy:s,copied:r,onClose:a,theme:i,className:c,style:d}){let[h,u]=(0,l.useState)(!1),m=e.map((e,t)=>({m:e,n:t+1})),p=h?m:m.filter(({m:e})=>"resolved"!==e.status),f=e.filter(e=>"resolved"!==e.status).length;return(0,o.jsxs)("div",{className:`slc-stage-card slc-stage-panel${c?` ${c}`:""}`,style:{...tS(i),...d},onPointerDown:e=>e.stopPropagation(),children:[(0,o.jsxs)("div",{className:"slc-stage-card-row",children:[(0,o.jsx)("span",{className:"slc-stage-card-label",children:"Marks on this drawing"}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),(0,o.jsxs)("span",{className:"slc-stage-segment",role:"group","aria-label":"Which marks to list",children:[(0,o.jsxs)("button",{type:"button",className:`slc-stage-segment-btn${h?"":" slc-stage-segment-btn--on"}`,"aria-pressed":!h,onClick:()=>u(!1),children:["Open ",f]}),(0,o.jsxs)("button",{type:"button",className:`slc-stage-segment-btn${h?" slc-stage-segment-btn--on":""}`,"aria-pressed":h,onClick:()=>u(!0),children:["All ",e.length]})]}),a&&(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:a,"aria-label":"Close",children:(0,o.jsx)(t6,{})})]}),0===p.length&&(0,o.jsx)("div",{className:"slc-stage-empty",children:e.length?"Every mark is resolved.":"No marks yet. Turn on marking (✎) and tap or draw around what you mean."}),(0,o.jsx)("ul",{className:"slc-stage-panel-list",children:p.map(({m:e,n:s})=>(0,o.jsx)("li",{children:(0,o.jsxs)("button",{type:"button",className:`slc-stage-panel-item${e.id===t?" slc-stage-panel-item--selected":""}`,onClick:()=>n(e.id),children:[(0,o.jsx)("span",{className:`slc-stage-pin slc-stage-pin--inline slc-stage-pin--${"resolved"===e.status?"resolved":"agent"===e.author.role&&"open"===e.status?"question":e.status}`,children:s}),(0,o.jsxs)("span",{className:"slc-stage-panel-text",children:[(0,o.jsx)("span",{className:"slc-stage-panel-said",children:e.text}),(0,o.jsxs)("span",{className:"slc-stage-panel-meta",children:[e.author.name," · ",tf(e),e.replies?.length?` \xb7 ${e.replies.length} repl${1===e.replies.length?"y":"ies"}`:""]})]})]})},e.id))}),s&&(0,o.jsxs)("div",{className:"slc-stage-card-row",children:[(0,o.jsx)("span",{className:"slc-stage-spacer"}),(0,o.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:s,title:"Copy what is on screen and the waiting marks, to paste into any agent",children:r?"Copied":"Copy for the agent"})]})]})}let na=e=>`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`,ni=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},no=e=>(e?e.split("/").pop()??e:"").replace(/\.(smdf|erdf|sqdf|sysdf)\.json$/i,"").replace(/\.json$/i,"");function nl(e){let t=(e.spotlight?.length?e.spotlight:e.focus?[e.focus]:[]).map(e=>e.startsWith("message:")?`#${e.slice(8)}`:e.slice(e.indexOf(":")+1));return t.length?t.length<=2?t.join(", "):`${t.slice(0,2).join(", ")} +${t.length-2}`:""}let nc={idle:"● Record",starting:"Opening the mic…",recording:"■ Stop & send",sending:"Sending…",retry:"Send again"};function nd({open:e,onOpenChange:t,who:n="Mia",episode:s,episodes:r,onEpisode:a,presence:i,recorder:l,onRecord:c,items:d,unheard:h=[],playing:u=null,playingStep:m=null,onPlay:p,onStop:f,onFeedback:g,autoplay:x,onAutoplay:y,waiting:b,notice:v,error:w,theme:j,className:k,style:$}){let N="recording"===l.state,S="starting"===l.state||"sending"===l.state,M=h.length;if(!e)return(0,o.jsx)("div",{className:`slc-talk${k?` ${k}`:""}`,style:{...tS(j),...$},children:(0,o.jsxs)("button",{type:"button",className:`slc-talk-fab${N?" slc-talk-fab--live":""}${!N&&u?" slc-talk-fab--speaking":""}`,onClick:()=>N?c():t(!0),"aria-label":N?`Stop and send (${na(l.seconds)})`:u?`${n} is speaking. Open the conversation`:`Talk with ${n}${M?`, ${M} new`:""}`,title:N?"Stop and send your take":u?`${n} is walking the diagram`:`Talk with ${n} about what is on the canvas`,children:[N?(0,o.jsx)("span",{className:"slc-talk-fab-clock",children:na(l.seconds)}):u?(0,o.jsx)(tK,{size:24}):(0,o.jsx)(tW,{size:24}),!N&&M>0&&(0,o.jsx)("span",{className:"slc-talk-fab-badge",children:M})]})});let C=function(e,t,n){if(!n)return{text:"Choose the episode you are speaking in.",away:!0};switch(t?.state){case"listening":return{text:`${e} is listening.`,away:!1};case"answering":return{text:`${e} is answering${t.takes?.length?` take ${t.takes.join(", ")}`:""}.`,away:!1};case"answered":return{text:`${e} has answered and is getting ready to listen again.`,away:!1};default:return{text:`Nobody is listening yet. A take waits in the episode until ${e} does.`,away:!0}}}(n,i,s),E=[...d].reverse();return(0,o.jsx)("div",{className:`slc-talk slc-talk--open${k?` ${k}`:""}`,style:{...tS(j),...$},children:(0,o.jsxs)("section",{className:"slc-talk-panel","aria-label":`Conversation with ${n}`,onPointerDown:e=>e.stopPropagation(),children:[(0,o.jsxs)("header",{className:"slc-talk-head",children:[(0,o.jsxs)("span",{className:"slc-talk-title",children:[(0,o.jsx)(tW,{})," Talk with ",n]}),(0,o.jsx)("span",{className:`slc-talk-presence${C.away?" slc-talk-presence--away":""}`,title:C.text}),(0,o.jsx)("span",{className:"slc-stage-spacer"}),(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:()=>t(!1),"aria-label":"Close the conversation",children:(0,o.jsx)(t6,{})})]}),r?.length&&a?(0,o.jsxs)("select",{className:"slc-stage-input slc-talk-episode",value:s??"",onChange:e=>a(e.target.value),disabled:N||S,"aria-label":"The episode this conversation belongs to",children:[!s&&(0,o.jsx)("option",{value:"",children:"Choose the episode…"}),r.map(e=>(0,o.jsxs)("option",{value:e.path,children:[e.number?`${String(e.number).padStart(3,"0")} \xb7 `:"",e.path.replace(/^\d{4}-\d{2}-\d{2}-episode-\d+-/,"")]},e.path))]}):(0,o.jsx)("div",{className:"slc-talk-meta",children:s??"No episode chosen."}),(0,o.jsx)("div",{className:`slc-talk-meta${C.away?" slc-talk-meta--away":""}`,children:C.text}),(0,o.jsxs)("button",{type:"button",className:`slc-talk-record${N?" slc-talk-record--live":""}${"retry"===l.state?" slc-talk-record--retry":""}`,onClick:c,disabled:S||!!l.unavailable||!s,title:l.unavailable?`Cannot record: ${l.unavailable}`:N?"Stop and send your take":"Speak to the episode, about what is on the canvas",children:[nc[l.state],N&&(0,o.jsx)("span",{className:"slc-talk-clock",children:na(l.seconds)})]}),l.unavailable&&(0,o.jsxs)("div",{className:"slc-talk-meta slc-talk-meta--error",children:["Cannot record here: ",l.unavailable,"."]}),l.message&&(0,o.jsx)("div",{className:`slc-talk-meta${l.error?" slc-talk-meta--error":""}`,children:l.message}),b&&(0,o.jsxs)("div",{className:"slc-talk-meta",children:["Waiting for ",n,"… ",na(b.seconds)]}),v&&(0,o.jsx)("div",{className:"slc-talk-notice",children:v}),w&&(0,o.jsx)("div",{className:"slc-talk-meta slc-talk-meta--error",children:w}),(0,o.jsxs)("label",{className:"slc-talk-toggle",children:[(0,o.jsx)("input",{type:"checkbox",checked:x,onChange:e=>y(e.target.checked)}),"Play ",n,"'s replies on the diagram as they arrive"]}),(0,o.jsxs)("ol",{className:"slc-talk-thread",children:[0===E.length&&(0,o.jsx)("li",{className:"slc-stage-empty",children:"Nothing said in this episode yet. Look at a drawing, press Record, and speak."}),E.map(e=>"take"===e.kind?(0,o.jsxs)("li",{className:"slc-talk-entry slc-talk-entry--take",children:[(0,o.jsxs)("div",{className:"slc-talk-who",children:[(0,o.jsx)("strong",{children:"You"}),(0,o.jsxs)("span",{children:["take ",e.take," · ",ni(e.at)]})]}),e.canvas?.doc&&(0,o.jsxs)("div",{className:"slc-talk-canvas",children:["on ",no(e.canvas.doc),e.canvas.focus?` \xb7 ${e.canvas.focus.slice(e.canvas.focus.indexOf(":")+1)}`:"",e.canvas.step?.title?` \xb7 during “${e.canvas.step.title}”`:""]}),(0,o.jsx)("div",{className:"slc-talk-text",children:e.text||"(no transcript yet)"})]},`t${e.take}`):(0,o.jsxs)("li",{className:`slc-talk-entry slc-talk-entry--reply${h.includes(e.id)?" slc-talk-entry--new":""}`,children:[(0,o.jsxs)("div",{className:"slc-talk-who",children:[(0,o.jsx)("strong",{children:n}),(0,o.jsx)("span",{children:ni(e.at)}),(!e.unvoiced||(e.steps?.length??0)>0)&&(u===e.id?(0,o.jsx)("button",{type:"button",className:"slc-stage-btn slc-talk-play slc-talk-play--on",onClick:f,"aria-label":"Stop",title:"Stop",children:(0,o.jsx)(t1,{})}):(0,o.jsxs)("button",{type:"button",className:"slc-stage-btn slc-talk-play",onClick:()=>p(e.id),disabled:N,title:e.unvoiced?`Walk the diagram with ${n}'s words (no voice)`:e.steps?.length?`Hear ${n} walk the diagram (${e.steps.length} steps)`:`Hear ${n}`,children:[(0,o.jsx)(tQ,{}),(e.steps?.length??0)>0?(0,o.jsxs)("span",{children:["Walk ",e.steps.length," steps"]}):null,h.includes(e.id)?(0,o.jsx)("span",{className:"slc-talk-new",children:"New"}):null]})),g&&(0,o.jsx)("span",{className:"slc-talk-thumbs",children:["up","down"].map(t=>(0,o.jsx)("button",{type:"button",className:`slc-talk-thumb${e.feedback===t?" slc-talk-thumb--on":""}`,onClick:()=>g(e.id,e.feedback===t?"":t),"aria-label":"up"===t?"This reply worked":"This reply missed",children:"up"===t?(0,o.jsx)(t4,{size:15}):(0,o.jsx)(t3,{size:15})},t))})]}),(e.steps?.length??0)>0?(0,o.jsx)("ol",{className:"slc-talk-steps","aria-label":`${n}'s walk through the diagram`,children:e.steps.map((t,n)=>{let s=u===e.id&&m===n;return(0,o.jsx)("li",{children:(0,o.jsxs)("button",{type:"button",className:`slc-talk-step${s?" slc-talk-step--here":""}`,onClick:()=>p(e.id,n),disabled:N,"aria-current":s?"step":void 0,title:`Walk from step ${n+1}`,children:[(0,o.jsx)("span",{className:"slc-talk-step-n",children:n+1}),(0,o.jsxs)("span",{className:"slc-talk-step-body",children:[(t.title||t.doc)&&(0,o.jsxs)("span",{className:"slc-talk-step-head",children:[t.title&&(0,o.jsx)("strong",{children:t.title}),(t.doc||nl(t))&&(0,o.jsx)("span",{className:"slc-talk-step-where",children:[no(t.doc),nl(t)].filter(Boolean).join(" · ")})]}),(0,o.jsx)("span",{className:"slc-talk-step-say",children:t.say})]})]})},n)})}):(0,o.jsx)("div",{className:"slc-talk-text",children:e.text}),e.unvoiced&&(0,o.jsx)("div",{className:"slc-talk-meta",children:e.unvoiced})]},`r${e.id}`))]})]})})}let nh=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},nu=e=>{let t=e?nh(e):nh,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},nm=Object.create(null);nm.open="0",nm.close="1",nm.ping="2",nm.pong="3",nm.message="4",nm.upgrade="5",nm.noop="6";let np=Object.create(null);Object.keys(nm).forEach(e=>{np[nm[e]]=e});let nf={type:"error",data:"parser error"},ng="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),nx="function"==typeof ArrayBuffer,ny=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nb=({type:e,data:t},n,s)=>{if(ng&&t instanceof Blob)if(n)return s(t);else return nv(t,s);if(nx&&(t instanceof ArrayBuffer||ny(t)))if(n)return s(t);else return nv(new Blob([t]),s);return s(nm[e]+(t||""))},nv=(e,t)=>{let n=new FileReader;return n.onload=function(){t("b"+(n.result.split(",")[1]||""))},n.readAsDataURL(e)};function nw(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let nj="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",nk="u"<typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<nj.length;e++)nk[nj.charCodeAt(e)]=e;let n$="function"==typeof ArrayBuffer,nN=(e,t)=>{if("string"!=typeof e)return{type:"message",data:nM(e,t)};let n=e.charAt(0);return"b"===n?{type:"message",data:nS(e.substring(1),t)}:np[n]?e.length>1?{type:np[n],data:e.substring(1)}:{type:np[n]}:nf},nS=(e,t)=>n$?nM((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=nk[e.charCodeAt(s)],i=nk[e.charCodeAt(s+1)],o=nk[e.charCodeAt(s+2)],l=nk[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},nM=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer;function nC(e){return e.reduce((e,t)=>e+t.length,0)}function nE(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 nR(e){if(e){var t=e;for(var n in nR.prototype)t[n]=nR.prototype[n];return t}}nR.prototype.on=nR.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},nR.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},nR.prototype.off=nR.prototype.removeListener=nR.prototype.removeAllListeners=nR.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},nR.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},nR.prototype.emitReserved=nR.prototype.emit,nR.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},nR.prototype.hasListeners=function(e){return!!this.listeners(e).length};let n_="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),nA="u">typeof self?self:"u">typeof window?window:Function("return this")();function nT(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}let nO=nA.setTimeout,nP=nA.clearTimeout;function nI(e,t){t.useNativeTimers?(e.setTimeoutFn=nO.bind(nA),e.clearTimeoutFn=nP.bind(nA)):(e.setTimeoutFn=nA.setTimeout.bind(nA),e.clearTimeoutFn=nA.clearTimeout.bind(nA))}function nL(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class nD extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class nq extends nR{constructor(e){super(),this.writable=!1,nI(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 nD(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=nN(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 nB extends nq{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=nN(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)=>{nb(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]=nL()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let nF=!1;try{nF="u">typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let nU=nF;function nz(){}class nY extends nB{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 nH extends nR{constructor(e,t,n){super(),this.createRequest=e,nI(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=nT(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=nH.requestsCount++,nH.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=nz,e)try{this._xhr.abort()}catch(e){}"u">typeof document&&delete nH.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 nX(){for(let e in nH.requests)nH.requests.hasOwnProperty(e)&&nH.requests[e].abort()}nH.requestsCount=0,nH.requests={},"u">typeof document&&("function"==typeof attachEvent?attachEvent("onunload",nX):"function"==typeof addEventListener&&addEventListener("onpagehide"in nA?"pagehide":"unload",nX,!1));let nV=(s=nJ({xdomain:!1}))&&null!==s.responseType;function nJ(e){let t=e.xdomain;try{if("u">typeof XMLHttpRequest&&(!t||nU))return new XMLHttpRequest}catch(e){}if(!t)try{return new nA[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let nW="u">typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class nK extends nq{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=nW?{}:nT(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;nb(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&n_(()=>{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]=nL()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let nZ=nA.WebSocket||nA.MozWebSocket,nG={websocket:class extends nK{createSocket(e,t,n){return nW?new nZ(e,t,n):t?new nZ(e,t):new nZ(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends nq{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>nC(a))break;let e=nE(a,1);l=(128&e[0])==128,i=(o=127&e[0])<126?3:126===o?1:2}else if(1===i){if(2>nC(a))break;let e=nE(a,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(8>nC(a))break;let e=nE(a,8),n=new DataView(e.buffer,e.byteOffset,e.length),s=n.getUint32(0);if(s>2097151){t.enqueue(nf);break}o=0x100000000*s+n.getUint32(4),i=3}else{if(nC(a)<o)break;let e=nE(a,o);t.enqueue(nN(l?e:n.decode(e),r)),i=0}if(0===o||o>s){t.enqueue(nf);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)},ng&&e.data instanceof Blob?e.data.arrayBuffer().then(nw).then(s):nx&&(e.data instanceof ArrayBuffer||ny(e.data))?s(nw(e.data)):nb(e,!1,e=>{t||(t=new TextEncoder),s(t.encode(e))})}});h.readable.pipeTo(e.writable),this._writer=h.writable.getWriter();let u=()=>{d.read().then(({done:e,value:t})=>{e||(this.onPacket(t),u())}).catch(e=>{})};u();let m={type:"open"};this.query.sid&&(m.data=`{"sid":"${this.query.sid}"}`),this._writer.write(m).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&&n_(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}},polling:class extends nY{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=nV&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new nH(nJ,this.uri(),e)}}},nQ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n0=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function n1(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=nQ.exec(e||""),c={},d=14;for(;d--;)c[n0[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 n2="function"==typeof addEventListener&&"function"==typeof removeEventListener,n5=[];n2&&addEventListener("offline",()=>{n5.forEach(e=>e())},!1);class n4 extends nR{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=n1(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=n1(t.host).host);nI(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)),n2&&(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"})},n5.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&&n4.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",n4.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,n_(()=>{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(n4.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(),n2&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=n5.indexOf(this._offlineEventListener);-1!==e&&n5.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}n4.protocol=4;class n3 extends n4{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;n4.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;n4.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 n6 extends n3{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=>nG[e]).filter(e=>!!e)),super(n?s:e,s)}}n6.protocol;let n8="function"==typeof ArrayBuffer,n7=Object.prototype.toString,n9="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===n7.call(Blob),se="function"==typeof File||"u">typeof File&&"[object FileConstructor]"===n7.call(File);function st(e){return n8&&(e instanceof ArrayBuffer||("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer))||n9&&e instanceof Blob||se&&e instanceof File}let sn=["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 ss{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(st(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(st(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 sr extends nR{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 sa(t)):super.emitReserved("decoded",t)}else if(st(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(!si(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(sr.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 so(t);case i.DISCONNECT:return void 0===t;case i.CONNECT_ERROR:return"string"==typeof t||so(t);case i.EVENT:case i.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sn.indexOf(t[0]));case i.ACK:case i.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sa{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 si=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function so(e){return"[object Object]"===Object.prototype.toString.call(e)}function sl(e){var t;return"string"==typeof e.nsp&&(void 0===(t=e.id)||si(t))&&function(e,t){switch(e){case i.CONNECT:return void 0===t||so(t);case i.DISCONNECT:return void 0===t;case i.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sn.indexOf(t[0]));case i.ACK:return Array.isArray(t);case i.CONNECT_ERROR:return"string"==typeof t||so(t);default:return!1}}(e.type,e.data)}function sc(e,t,n){return e.on(t,n),function(){e.off(t,n)}}e.s(["Decoder",()=>sr,"Encoder",()=>ss,"PacketType",()=>i,"isPacketValid",()=>sl,"protocol",0,5],11014);let sd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class sh extends nR{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=[sc(e,"open",this.onopen.bind(this)),sc(e,"packet",this.onpacket.bind(this)),sc(e,"error",this.onerror.bind(this)),sc(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(sd.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 su=e.i(11014);function sm(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}sm.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)},sm.prototype.reset=function(){this.attempts=0},sm.prototype.setMin=function(e){this.ms=e},sm.prototype.setMax=function(e){this.max=e},sm.prototype.setJitter=function(e){this.jitter=e};class sp extends nR{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,nI(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 sm({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||su;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 n6(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=sc(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},a=sc(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(sc(e,"ping",this.onping.bind(this)),sc(e,"data",this.ondata.bind(this)),sc(e,"error",this.onerror.bind(this)),sc(e,"close",this.onclose.bind(this)),sc(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){n_(()=>{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 sh(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 sf={};function sg(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=n1(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=sf[a]&&i in sf[a].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?n=new sp(r,t):(sf[a]||(sf[a]=new sp(r,t)),n=sf[a]),s.query&&!t.query&&(t.query=s.queryKey),n.socket(s.path,t)}function sx(e){if(e&&"object"==typeof e&&"clientId"in e){let t=e.clientId;if("string"==typeof t)return t}}function sy(e){let{url:t,role:n,docId:s,name:r,token:a}=e,i=!1!==e.autoResync,o=sg(t,{auth:{token:a},autoConnect:!1}),l="disconnected",c=0,d="",h=[],u={patch:new Set,full:new Set,ack:new Set,presence:new Set,error:new Set,status:new Set,view:new Set,"stage-step":new Set,"stage-load":new Set,"stage-control":new Set,"stage-context":new Set,marks:new Set};function m(e,t){for(let n of[...u[e]])n(t)}function p(e){l!==e&&(l=e,m("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(){m("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"};m("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)})}async function w(e){return await y(),new Promise((t,n)=>{o.emit("stage:join",{stage:e},e=>{if(!e||e.error||!e.state){let t=e?.error??{code:"stage_join_failed",message:"no stage join ack"};m("error",t),n(Error(`${t.code}: ${t.message}`));return}e.selfId&&(d=e.selfId),t({selfId:e.selfId??d,state:e.state})})})}async function j(e){await y(),o.emit("stage:step",{...e,origin:e.origin??(r||n)})}async function k(e){await y(),o.emit("stage:load",{...e,origin:e.origin??(r||n)})}async function $(e){await y(),o.emit("stage:control",{...e,origin:e.origin??(r||n)})}async function N(e){await y(),o.emit("marks:changed",{...e,origin:e.origin??(r||n)})}return o.on("connect",()=>p("connected")),o.on("disconnect",()=>p("disconnected")),o.on("connect_error",e=>{p("error"),m("error",{code:"connect_error",message:e?.message??String(e)})}),o.on("def:patch",e=>{g(e?.seq),e?.origin&&e.origin===d||m("patch",e)}),o.on("def:full",e=>{g(e?.seq),e?.origin&&e.origin===d||m("full",e)}),o.on("def:ack",e=>{m("ack",e)}),o.on("view:show",e=>{m("view",e)}),o.on("stage:step",e=>m("stage-step",e)),o.on("stage:load",e=>m("stage-load",e)),o.on("stage:control",e=>m("stage-control",e)),o.on("stage:context",e=>m("stage-context",e)),o.on("marks:changed",e=>m("marks",e)),o.on("bridge:error",e=>{m("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=sx(e);t&&(h=[...h.filter(e=>e.clientId!==t),e],x())}),o.on("presence:leave",e=>{let t=sx(e);t&&(h=h.filter(e=>e.clientId!==t),x())}),o.on("presence:update",e=>{let t=sx(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,joinStage:w,leaveStage:function(e){o.connected&&o.emit("stage:leave",{stage:e})},emitStep:j,emitLoad:k,emitControl:$,emitContext:function(e){o.connected&&o.emit("stage:context",{...e,at:e.at??new Date().toISOString()})},emitMarks:N,on:function(e,t){let n=u[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 sb(e){return"runtime.enter"===e.op||"runtime.exit"===e.op}function sv(e){let{onFull:t,onPatch:n,onPresence:s,...r}=e,a=sy(r),i=null,o=0,l=[],c=[],d={status:a.status,def:null,seq:0,presence:[],activeStates:[]},h=new Set;function u(){for(let e of(d={status:a.status,def:i,seq:o,presence:l,activeStates:c},[...h]))e()}return a.on("status",()=>u()),a.on("full",e=>{i=e.def,"number"==typeof e.seq&&(o=e.seq),t?.(e),u()}),a.on("patch",e=>{"number"==typeof e.seq&&(o=e.seq);let t=e.ops??[],s=t.filter(sb),r=t.filter(e=>!sb(e));r.length>0&&i&&(i=m(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),u()}),a.on("presence",e=>{l=e,s?.(e),u()}),{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"}),u()}).catch(()=>{u()})},disconnect:function(){a.disconnect()}}}function sw(e={}){let t=window.speechSynthesis,n="u">typeof Audio;if(!t&&!n)return null;let s=null,r=null,a=()=>{let e=r;r=null,e?.()},i=()=>{s&&(s.onended=null,s.onerror=null,s.onplaying=null,s.pause(),s=null),(t?.speaking||t?.pending)&&t.cancel(),a()};return{speak:o=>(i(),new Promise(i=>{let l=setTimeout(a,2*tg({...o,holdMs:void 0})+4e3);if(r=()=>{clearTimeout(l),i()},o.audio&&n&&!1!==e.recordings){let e=new Audio(o.audio);s=e,e.onended=a,e.onerror=a,e.onplaying=()=>{s===e&&Number.isFinite(e.duration)&&(clearTimeout(l),l=setTimeout(a,(e.duration-e.currentTime)*1e3+4e3))},e.play().catch(a);return}if(!1===e.speech){let e=setTimeout(a,tg(o)),t=r;r=()=>{clearTimeout(e),t?.()};return}if(!t||!o.say?.trim())return a();let c=new SpeechSynthesisUtterance([o.title,o.say].filter(Boolean).join(". "));if(e.lang&&(c.lang=e.lang),e.rate&&(c.rate=e.rate),e.voiceName){let n=t.getVoices().find(t=>t.name===e.voiceName);n&&(c.voice=n)}c.onend=a,c.onerror=a,t.speak(c)})),cancel:i}}Object.assign(sg,{Manager:sp,Socket:sh,io:sg,connect:sg});let sj=["audio/mp4;codecs=mp4a.40.2","audio/mp4"];function sk(e,t){let n=new DataView(new ArrayBuffer(44)),s=(e,t)=>[...t].forEach((t,s)=>n.setUint8(e+s,t.charCodeAt(0)));return s(0,"RIFF"),n.setUint32(4,36+e,!0),s(8,"WAVE"),s(12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,1,!0),n.setUint16(22,1,!0),n.setUint32(24,t,!0),n.setUint32(28,2*t,!0),n.setUint16(32,2,!0),n.setUint16(34,16,!0),s(36,"data"),n.setUint32(40,e,!0),n.buffer}let s$=e=>e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`;function sN(){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 sS(){return{positions:{}}}function sM(e,t){if(e.name===t)return e;for(let n of e.states??[]){let e=sM(n,t);if(e)return e}return null}function sC(e,t,n){return e.name===t?n(e)??e:{...e,states:e.states?.map(e=>sC(e,t,n))}}function sE(e,t){return{...e,states:e.states?.filter(e=>e.name!==t).map(e=>sE(e,t))}}function sR(e){let t=[e.name];for(let n of e.states??[])t.push(...sR(n));return t}function s_(e){return e.events.flatMap(e=>(e.events??[]).map(e=>e.id))}function sA(e){let t=[],n=sR(e.state),s=s_(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 sT(e,t){return{positions:{...$(e),...t.positions}}}let sO=!1,sP=(r=(e,t)=>({definition:sN(),layout:sT(sN(),sS()),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=sT(n,t().layout);e({definition:n,layout:s,dirty:!0,errors:sA(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=sC(r.state,a,e=>({...e,states:[...e.states??[],s]}));let i=sT(r,t().layout);e({definition:r,layout:i,dirty:!0,errors:sA(r)})},updateState:(n,s)=>{t()._pushHistory();let r={...t().definition};r.state=sC(r.state,n,e=>({...e,...s})),e({definition:r,dirty:!0,errors:sA(r)})},removeState:n=>{t()._pushHistory();let s={...t().definition};s.state=sE(s.state,n);let r={positions:{...t().layout.positions}};delete r.positions[n],e({definition:s,layout:r,dirty:!0,errors:sA(s)})},nestState:(n,s)=>{t()._pushHistory();let r={...t().definition},a=sM(r.state,n);if(!a||n===s)return;let i=JSON.parse(JSON.stringify(a));r.state=sE(r.state,n),r.state=sC(r.state,s,e=>({...e,states:[...e.states??[],i]})),e({definition:r,dirty:!0,errors:sA(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:sA(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:sA(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:sA(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=sC(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=sC(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=sC(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=sC(r.state,n,e=>({...e,transitions:[...e.transitions??[],s]})),e({definition:r,dirty:!0,errors:sA(r)})},updateTransition:(n,s,r)=>{t()._pushHistory();let a={...t().definition};a.state=sC(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=sC(r.state,n,e=>({...e,transitions:e.transitions?.filter((e,t)=>t!==s)})),e({definition:r,dirty:!0,errors:sA(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:sA(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:sA(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=ex(s.stateMachine??s.StateMachine??s);sO=!!s&&"object"==typeof s&&"state"in s&&!("stateMachine"in s)&&!("StateMachine"in s);let a=sT(r,sS()),i=r.state?.name??"Root";e({definition:r,layout:a,fileName:n??null,dirty:!1,errors:sA(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(sO?e:{stateMachine:e},null,2)},applyRemote:(n,s,r)=>{try{let a=JSON.parse(n),i=ex(a.stateMachine??a.StateMachine??a);sO=!!a&&"object"==typeof a&&"state"in a&&!("stateMachine"in a)&&!("StateMachine"in a);let o=sT(i,t().layout),l=i.state?.name??"Root",c=t(),d=new Set(sR(i.state)),h=c.navigationPath.filter(e=>d.has(e)),u=h.length?h:[l],m=u[u.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&&s_(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:sA(i),selection:f,navigationPath:u,currentParent:m})}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?m(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=sT(i,r.layout),c=i.state?.name??"Root",d=new Set(sR(i.state)),h=r.navigationPath.filter(e=>d.has(e)),u=h.length?h:[c],p=u[u.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&&s_(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:sA(i),selection:g,navigationPath:u,currentParent:p})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}finally{e({_applyingRemote:!1})}},validate:()=>{let n=sA(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=sM(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=sM(e.state,n);return s?.states??[]}}))?nu(r):nu,sI="canvas",sL=`[data-pinch-owner="${sI}"]`;function sD(e){return!!e&&"function"==typeof e.closest&&null!==e.closest(sL)}let sq="stateloom-canvas",sB="#030712",sF=["png","jpeg","svg","mermaid","markdown"],sU={png:"PNG",jpeg:"JPEG",svg:"SVG",mermaid:"Mermaid",markdown:"Markdown"},sz={png:"image/png",jpeg:"image/jpeg",svg:"image/svg+xml",mermaid:"text/vnd.mermaid",markdown:"text/markdown"},sY={png:"png",jpeg:"jpg",svg:"svg",mermaid:"mmd",markdown:"md"};async function sH(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=V(t);if(0===r.length)return;let a=" ".repeat(n+1),i=new Set,o=r.find(e=>"history"!==e.kind);for(let e of(o&&(s.push(`${a}[*] --> ${o.name}`),i.add(o.name)),r))for(let t of e.transitions??[]){let n=t.condition?`${t.event} [${t.condition}]`:t.event;if(!t.nextState){s.push(`${a}${e.name} --> ${e.name} : ${n} (stays)`),i.add(e.name);continue}s.push(`${a}${e.name} --> ${t.nextState} : ${n}`),i.add(e.name),i.add(t.nextState)}for(let e of r)"final"===e.kind&&(s.push(`${a}${e.name} --> [*]`),i.add(e.name));for(let e of r)i.has(e.name)||s.push(`${a}${e.name}`);for(let t of r)0!==V(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:`${sz[e]};charset=utf-8`})}else{let t=function(e={}){let t="u"<typeof document?null:document.getElementById(sq);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??sB,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:`${sz.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=sB,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")),sz[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=ev(t??"")||ev(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:sY[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 sX="stateloom.layout.v1:";async function sV(){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 sP.getState().fileName??"untitled"}function sJ(){let e,t,n=sP(e=>e.definition),s=sP(e=>e.layout),r=sP(e=>e.selection),a=sP(e=>e.select),i=sP(e=>e.clearSelection),c=sP(e=>e.setStatePosition),d=sP(e=>e.drawMode),h=sP(e=>e.drawSource),u=sP(e=>e.setDrawSource),m=sP(e=>e.setDrawMode),p=sP(e=>e.addTransition),f=sP(e=>e.showContextMenu),g=sP(e=>e.removeState),x=sP(e=>e.undo),y=sP(e=>e.redo),b=sP(e=>e.errors),v=sP(e=>e.navigationPath),w=sP(e=>e.navigateInto),j=sP(e=>e.navigateUp),k=sP(e=>e.activeStates),N=sP(e=>e.viewport),S=sP(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 sV();if(n)return;t.current=s;let r=function(e){try{let t=window.localStorage.getItem(`${sX}${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&&sP.getState().hydrateLayout(r.positions,r.viewport),e.current=!0})();let r=sP.subscribe((n,r)=>{e.current&&t.current&&(n.layout!==r.layout||n.viewport!==r.viewport)&&(s&&clearTimeout(s),s=setTimeout(()=>{let e=sP.getState();!function(e,t,n){try{window.localStorage.setItem(`${sX}${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 M=v.slice(1);return(0,o.jsx)(tT,{definition:n,positions:s.positions,path:M,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:sq,pinchOwner:sI,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):u(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}),u(null),m("select")},onCancelDraw:()=>{m("select"),u(null)},onDeleteState:e=>{g(e),i()},onUndo:x,onRedo:y})}function sW({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 sK(){let e=sP(e=>e.definition),t=sP(e=>e.selection),n=sP(e=>e.updateState),s=sP(e=>e.removeState);sP(e=>e.addAction),sP(e=>e.removeAction);let r=sP(e=>e.updateTransition),a=sP(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)(sW,{label:"▸ onEntry Actions",actions:l,onChange:e=>n(t.id,{onEntry:{actions:e}})}),(0,o.jsx)(sW,{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=s_(e),u=(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)"}),u.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 sZ=["string","int","float","bool","object"];function sG(){let e=sP(e=>e.definition),t=sP(e=>e.addEvent),n=sP(e=>e.updateEvent),s=sP(e=>e.removeEvent),r=sP(e=>e.addParameter),a=sP(e=>e.removeParameter),i=sP(e=>e.updateParameter),c=sP(e=>e.updateEventSource),d=sP(e=>e.select),h=sP(e=>e.selection),[u,m]=(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:sZ.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:u,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"===e.key&&u.trim()&&(t({id:u.trim()}),m(""))}}),(0,o.jsx)("button",{onClick:()=>{u.trim()&&(t({id:u.trim()}),m(""))},className:"bg-blue-600 hover:bg-blue-500 text-white px-2 py-1 rounded",children:"+"})]})]})}function sQ(){let e=sP(e=>e.definition.settings),t=sP(e=>e.definition.settings.context),n=sP(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 s0(){let e=sP(e=>e.errors),t=sP(e=>e.validate),n=sP(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 s1=e.i(76800);function s2(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(!1),[s,r]=(0,l.useState)(""),[a,i]=(0,l.useState)(null),[c,d]=(0,l.useState)([]),[h,u]=(0,l.useState)(null),[m,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??[]),u(t.current??null))}).catch(t=>{e&&(i([]),p(t.message))}),()=>{e=!1}},[t]);let f=e=>{n(!1),r(""),(0,s1.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(sX)&&e.push(n.slice(sX.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(", ")]}),m&&(0,o.jsxs)("div",{className:"mt-1 text-[10px] text-gray-600",children:["this server does not list documents (",m,") — type a path"]})]})]})}function s5(){let e=sP(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 s4(){let e=sP(e=>e.definition),t=sP(e=>e.fileName),n=sP(e=>e.docPath),s=sP(e=>e.dirty),r=sP(e=>e.loadFromJson),a=sP(e=>e.exportJson),i=sP(e=>e.addState),c=sP(e=>e.validate),d=sP(e=>e.showCodePreview),h=sP(e=>e.setShowCodePreview),u=sP(e=>e.setGeneratedCode),m=sP(e=>e.drawMode),p=sP(e=>e.setDrawMode),f=sP(e=>e.arrangeLayout),g=sP(e=>e.undo),x=sP(e=>e.redo),y=sP(e=>e.undoStack),b=sP(e=>e.redoStack),v=sP(e=>e.remoteStatus),w=sP(e=>e.remoteMessage),j=sP(e=>e.setRemoteStatus),k=sP(e=>e.setRemoteMtime),$=sP(e=>e.applyRemote),N=(0,s1.useRequestedDoc)(),S=(0,l.useRef)(null),[M,C]=(0,l.useState)(!1),[E,R]=(0,l.useState)(""),[_,A]=(0,l.useState)(!1),[T,O]=(0,l.useState)("png"),[P,I]=(0,l.useState)(!1),[L,D]=(0,l.useState)(null),[q,B]=(0,l.useState)(null),F=async()=>{let e=a();A(!0);try{let t=await fetch(`/api/file${(0,s1.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),sP.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{A(!1)}},U=async()=>{I(!0),D(null);try{let s=await sH(T,{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,s1.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}`)}},Y=()=>{E.trim()&&(i(null,{name:E.trim(),kind:"normal"}),R(""),C(!1))},[H,X]=(0,l.useState)("python"),V=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();u(t.rispec)}else{let t=await e.json().catch(()=>({error:"Unknown"}));u(`# RISE rispec generation failed
6
- ${t.error}`)}}catch(e){u(`# RISE rispec generation failed
7
- ${e}`)}h(!0)},J=async()=>{let e=a();try{let t=await fetch("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({definition:e,language:H})});if(t.ok){let e=await t.json();u(e.code)}else{let n=await t.json().catch(()=>({error:"Unknown error"}));u(`// Code generation failed: ${n.error}
8
- // Showing definition JSON as fallback:
9
- ${e}`)}}catch{u(`// 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)(s2,{}),"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)(s5,{}),(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"===m?"transition":"select"),className:`toolbar-btn ${"transition"===m?"!bg-amber-700 !text-white":""}`,title:"transition"===m?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===m?"✏️ 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:_,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:T,onChange:e=>{O(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:sF.map(e=>(0,o.jsx)("option",{value:e,children:sU[e]},e))}),(0,o.jsx)("button",{onClick:U,disabled:P,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${sU[T]}`,children:P?"…":"🖼 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"}),M?(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:E,onChange:e=>R(e.target.value),onKeyDown:e=>{"Enter"===e.key&&Y(),"Escape"===e.key&&C(!1)}}),(0,o.jsx)("button",{onClick:Y,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:H,onChange:e=>X(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:J,className:"toolbar-btn",children:"⚡ Generate"}),(0,o.jsx)("button",{onClick:V,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 s3(){let e=sP(e=>e.generatedCode),t=sP(e=>e.showCodePreview),n=sP(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 s6(){let e=sP(e=>e.applyRemote),t=sP(e=>e.setRemoteStatus),n=sP(e=>e.setRemoteMtime),s=(0,s1.useRequestedDoc)();return(0,l.useEffect)(()=>{let r=!1,a=(0,s1.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&&sP.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<=(sP.getState().remoteMtime??0))return;let a=await i();a?.exists&&a.content&&(sP.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 s8({url:e}){let t=(0,s1.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,s1.docQuery)(t)}`,{cache:"no-store"});e.ok&&(o=(await e.json())?.path??"")}catch{}n||(o&&sP.getState().setDocPath(o),(s=sv({url:e,role:"web",docId:o,name:"web-designer",onFull:e=>{sP.getState().applyRemote(JSON.stringify({stateMachine:e.def}),e.mtime??Date.now(),o&&o.split("/").pop()||void 0),i=e.def},onPatch:e=>{sP.getState().applyRemoteOps(e.ops,e.mtime??Date.now(),e.seq),i=sP.getState().definition},onPresence:e=>{sP.getState().setPresence(e)}})).connect(),r=sP.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=sP.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 s7(){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 s9=null;function re(){return s9||(s9=(async()=>{let e=s7()??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,stage:n.stage??null,companion:!0===n.companion,companionEpisode:n.companionEpisode??null}}}catch{}return{bridgeUrl:e,projectFile:null,stage:null,companion:!1,companionEpisode:null}})())}function rt(){let e=s7(),[t,n]=(0,l.useState)(e);return((0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&t.bridgeUrl&&n(t.bridgeUrl)}),()=>{e=!1}},[]),"string"==typeof t&&t.length>0)?(0,o.jsx)(s8,{url:t}):(0,o.jsx)(s6,{})}let rn="stateloom.uiScale.v1";function rs(e){return Number.isFinite(e)?Math.min(1.75,Math.max(.75,e)):1}function rr(e){"u">typeof document&&(document.documentElement.style.fontSize=`${16*rs(e)}px`)}let ra=1,ri=!1,ro=new Set;function rl(){return ri||(ri=!0,ra=function(){try{let e=window.localStorage.getItem(rn);if(null===e)return 1;return rs(Number.parseFloat(e))}catch{return 1}}()),ra}function rc(){return 1}function rd(e){return ro.add(e),()=>{ro.delete(e)}}function rh(e,t){let n=rs(e);if(rr(n),t&&function(e){try{window.localStorage.setItem(rn,String(rs(e)))}catch{}}(n),ri=!0,n!==ra)for(let e of(ra=n,ro))e()}function ru(e,t){return Math.max(1,Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY))}function rm(e,t){for(let n=0;n<e.length;n++)if(e[n].identifier===t)return e[n];return null}function rp(){let e=(0,l.useSyncExternalStore)(rd,rl,rc),t=(0,l.useRef)(null),n=(0,l.useRef)(null),s=(0,l.useRef)(null);(0,l.useEffect)(()=>{rr(e)},[e]);let r=(0,l.useCallback)(e=>{n.current=e,null===s.current&&(s.current=requestAnimationFrame(()=>{s.current=null,null!==n.current&&rh(n.current,!1)}))},[]),a=(0,l.useCallback)(()=>{n.current=null,rh(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??rl();n.current=null,rh(rs(r),!0)},a=n=>{if(2!==n.touches.length){t.current&&e();return}let[s,r]=[n.touches[0],n.touches[1]];sD(s.target)||sD(r.target)||(t.current={a:s.identifier,b:r.identifier,startScale:rl(),startDist:ru(s,r),engaged:!1})},i=e=>{let n=t.current;if(!n)return;let s=rm(e.touches,n.a),a=rm(e.touches,n.b);if(!s||!a)return;e.preventDefault();let i=ru(s,a);if(!n.engaged){if(12>Math.abs(i-n.startDist))return;n.engaged=!0,n.startDist=i;return}r(rs(n.startScale*(i/n.startDist)))},o=n=>{let s=t.current;s&&(rm(n.touches,s.a)&&rm(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 rf=l;class rg extends rf.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 rx({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 ry({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 rb(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()}},u=r?s:n,m=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":m&&i<0?`min(calc(${u}dvh + ${-i}px), ${s}dvh)`:`${u}dvh`,...m?{transition:"none"}:{},...m&&i>0?{transform:`translateY(${i}px)`}:{}},close:d}}let rv="stateloom:focus",rw="stateloom:focus-request",rj="stateloom:system-changed",rk="stateloom:strip-note";function r$(e){return new URLSearchParams(window.location.search).get(e)}function rN(e){let[t,n]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let t=()=>n(r$(e));t();let s=["popstate",s1.DOC_CHANGE_EVENT,rv,rw];for(let e of s)window.addEventListener(e,t);return()=>{for(let e of s)window.removeEventListener(e,t)}},[e]),t}function rS(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(s1.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(rw))}function rM(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(rv)))}function rC(){let[e,t]=(0,l.useState)({focus:null,nonce:0});return(0,l.useEffect)(()=>{let e=()=>t(e=>({focus:r$("focus"),nonce:e.nonce+1}));e();let n=["popstate",s1.DOC_CHANGE_EVENT,rw];for(let t of n)window.addEventListener(t,e);return()=>{for(let t of n)window.removeEventListener(t,e)}},[]),e}let rE="/api/companion/",rR="stateloom.companion.autoplay",r_=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/,rA=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},rT=e=>"starting"===e||"recording"===e||"sending"===e,rO={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},rP={episode:null,items:[],presence:null,waiting:null,error:null};function rI({stage:e,defaultEpisode:t}){let[n,s]=(0,l.useState)(!1),[r,a]=(0,l.useState)(()=>"0"!==function(e){try{return window.localStorage.getItem(e)}catch{return null}}(rR)),[i,c]=(0,l.useState)(()=>{var e;let n,s=r$("episode");return(s&&r_.test(s)?s:null)??(e=(0,s1.requestedDoc)(),(n=e?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/))?n[1]:null)??t}),[d,h]=(0,l.useState)([]),[u,m]=(0,l.useState)(rO),[p,f]=(0,l.useState)(rP),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)([]),[v,w]=(0,l.useState)(null),[j,k]=(0,l.useState)(null),[$,N]=(0,l.useState)(()=>Date.now()),S=(0,l.useRef)(e),M=(0,l.useRef)(i),C=(0,l.useRef)(r);(0,l.useEffect)(()=>{S.current=e,M.current=i,C.current=r});let E=(0,l.useRef)(rO),R=(0,l.useRef)(null),_=(0,l.useRef)([]),A=(0,l.useRef)(!1),T=(0,l.useRef)([]),O=(0,l.useRef)(null),P=(0,l.useRef)(null),I=(0,l.useMemo)(()=>sw({recordings:!0,speech:!1}),[]),L=e=>{R.current=e,x(e)},D=(0,l.useRef)(async()=>{}),q=(0,l.useCallback)(async(e,t=0)=>{L(e.id),b(t=>t.filter(t=>t!==e.id)),e.steps?.length&&window.matchMedia("(max-width: 767px)").matches&&s(!1);let n=_.current.length;w(n?`${n} more of Mia's replies wait after this one.`:null);let r=await S.current.present(function(e,t,n="Mia"){let s=new Date(e.at),r=Number.isNaN(s.getTime())?`${n}'s reply`:`Reply at ${s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,a=!e.unvoiced,i=(e,n)=>(function(e,t){if(!t)return;if(/^https?:\/\//.test(t))return t;let n=t.replace(/^\/?api\//,"");return`${e.endsWith("/")?e:`${e}/`}${n}`})(t,e||(a?n:null));return{settings:{namespace:"companion",name:r,author:n},steps:e.steps?.length?e.steps.map(({audio:t,...n},s)=>{let r=i(t,`api/replies/${e.id}/steps/${s}/audio`);return{...n,...r?{audio:r}:{}}}):[{say:e.text,...i(e.audio,`api/replies/${e.id}/audio`)?{audio:i(e.audio,`api/replies/${e.id}/audio`)}:{}}]}}(e,rE,"Mia"),{voice:I,origin:"Mia",from:t});if(R.current!==e.id||(L(null),A.current))return;if(!r){_.current=[];return}let a=_.current.shift();a&&!rT(E.current.state)?D.current(a):a&&_.current.unshift(a)},[I]);(0,l.useEffect)(()=>{D.current=q},[q]);let B=(0,l.useCallback)(e=>{let t=e.id;if(!C.current)return void b(e=>e.includes(t)?e:[...e,t]);if(rT(E.current.state)||R.current){b(e=>e.includes(t)?e:[...e,t]),_.current.some(e=>e.id===t)||_.current.push(e),w(rT(E.current.state)?`Mia replied at ${rA(e.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${rA(e.at)}. It plays when this one ends.`);return}D.current(e)},[]);(0,l.useEffect)(()=>{let e=function(e){let t=e.base.endsWith("/")?e.base:`${e.base}/`,n=e.fetch??((...e)=>fetch(...e)),s=e.everyMs??1e4,r=e.waitEveryMs??4e3,a=e.waitForMs??9e5,i={episode:null,items:[],presence:null,waiting:null,error:null},o=new Set,l=!1,c=null,d=null,h="",u=0,m=t=>{i={...i,...t},e.onChange?.(i)};async function p(){let s=i.episode;if(!s)return;let r=u;try{let c=await n(`${t}thread?episode=${encodeURIComponent(s)}`,{cache:"no-store"}),p=await c.json();if(r!==u)return;if(!p.success)return m({error:p.error??`HTTP ${c.status}`});let f=p.items??[],g=f.map(e=>"reply"===e.kind?`${e.id}:${+!!e.audio}:${e.feedback??""}`:`${e.take}:${e.text.length}`).join(",")+`|${p.presence?.state}`,x=f.filter(e=>"reply"===e.kind&&!o.has(e.id));for(let e of x)o.add(e.id);if((g!==h||i.error)&&(h=g,m({items:f,presence:p.presence??null,error:null})),l)for(let t of x)e.onReply?.(t);l=!0;let y=i.waiting;y&&(f.some(e=>"reply"===e.kind&&e.take===y.take)||Date.now()-y.since>a)&&(d&&clearInterval(d),d=null,m({waiting:null}))}catch(e){r===u&&m({error:e instanceof Error?e.message:String(e)})}}let f=()=>{"visible"===document.visibilityState&&p()};return"u">typeof document&&document.addEventListener("visibilitychange",f),{getSnapshot:()=>i,setEpisode(e){e!==i.episode&&(u+=1,o.clear(),l=!1,h="",d&&clearInterval(d),d=null,m({episode:e,items:[],presence:null,waiting:null,error:null}),e?(c&&clearInterval(c),c=setInterval(()=>{("u"<typeof document||"visible"===document.visibilityState)&&p()},s),p()):c&&(clearInterval(c),c=null))},refresh:p,waitFor(e){m({waiting:{take:e,since:Date.now()}}),d&&clearInterval(d),d=setInterval(()=>void p(),r),p()},async feedback(e,s){await n(`${t}replies/${e}/feedback`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({value:s})}),h="",await p()},destroy(){for(let e of(u+=1,[c,d]))e&&clearInterval(e);c=d=null,"u">typeof document&&document.removeEventListener("visibilitychange",f)}}}({base:rE,onChange:f,onReply:B}),t=function(e){let t,n=e.base.endsWith("/")?e.base:`${e.base}/`,s=e.fetch??((...e)=>fetch(...e)),r=e.partEveryMs??1e4,a=e.beatEveryMs??15e3,i=(t=window.MediaRecorder)&&sj.some(e=>!t.isTypeSupported||t.isTypeSupported(e))?"mp4":window.AudioContext??window.webkitAudioContext?"wav":null,o=!1!==window.isSecureContext,l=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),c=e.createRecorder??(e=>{let t,n,s,r,a,o,l,c;return"mp4"===i?new window.MediaRecorder(e,{mimeType:sj.find(e=>window.MediaRecorder.isTypeSupported?.(e)??!0)}):(n=(t=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(e),s=t.createScriptProcessor(4096,1,1),r=[],a=[],o=!1,l=null,c={mimeType:"audio/wav",ondataavailable:null,onstop:null,onerror:null,start(e=1e3){s.onaudioprocess=e=>{let t=e.inputBuffer.getChannelData(0),n=new Int16Array(t.length);for(let e=0;e<t.length;e++)n[e]=Math.max(-32768,Math.min(32767,Math.round(32767*t[e])));r.push(n),a.push(n)},n.connect(s),s.connect(t.destination),l=setInterval(()=>{if(!a.length)return;let e=o?[]:[sk(0x7fffffff,t.sampleRate)];o=!0,e.push(...a.map(e=>e.buffer)),a=[],c.ondataavailable?.({data:new Blob(e,{type:"audio/wav"})})},e)},stop(){l&&clearInterval(l),l=null;try{n.disconnect(),s.disconnect()}catch{}t.close().catch(()=>{}),c.whole=new Blob([sk(r.reduce((e,t)=>e+t.byteLength,0),t.sampleRate),...r.map(e=>e.buffer)],{type:"audio/wav"}),c.onstop?.()}})}),d={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!e.createRecorder&&(!i||!o)?{unavailable:o?"this browser cannot record audio":"the microphone needs a secure page (https, or this machine's own address)"}:{}},h=t=>{d={...d,...t},e.onChange?.(d)},u=null,m=null,p=[],f="",g="",x=null,y=0,b=null,v=null,w=null,j=null,k=!1,$=()=>y?Math.floor((Date.now()-y)/1e3):0,N=()=>(m?.mimeType||"audio/mp4").split(";")[0]||"audio/mp4",S=(e="")=>`episode=${encodeURIComponent(g)}${f?`&rec=${f}`:""}${x?`&context=${encodeURIComponent(x)}`:""}${e}`;function M(e){g&&s(`${n}recorder`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({episode:g,recording:e})}).catch(()=>{})}function C(e,t={}){f&&s(`${n}takes/diagnostic`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rec:f,episode:g,kind:e,at:new Date().toISOString(),mime:m?.mimeType??i,visibility:"u">typeof document?document.visibilityState:"",agent:"u">typeof navigator?navigator.userAgent:"",source:"stateloom-canvas",...t}),keepalive:!0}).catch(()=>{})}function E(){for(let e of[v,w,j])e&&clearInterval(e);v=w=j=null}function R(){try{u?.getTracks().forEach(e=>e.stop())}catch{}u=null}async function _(){if(!f||k||!p.length)return;let e=new Blob(p,{type:N()});if(e.size<=d.held)return;k=!0;let t=f;try{let r=await s(`${n}takes/part?${S(`&offset=${d.held}`)}`,{method:"POST",headers:{"content-type":N()},body:e.slice(d.held)}),a=await r.json();t===f&&"number"==typeof a.bytes&&h({held:a.bytes})}catch{}finally{k=!1}}async function A(){let t;if("idle"!==d.state&&"retry"!==d.state)return;if(d.unavailable)return h({message:`Cannot record: ${d.unavailable}.`,error:!0});if(!(g=e.episode()??""))return h({message:"Choose the episode this take belongs to.",error:!0});let n=e.context?.()??null;x=n?JSON.stringify(n).slice(0,4e3):null,b=null,h({state:"starting",message:"",error:!1,held:0,seconds:0}),M(!0);try{t=await l({audio:!0})}catch(e){return M(!1),h({state:"idle",message:`Microphone refused: ${e instanceof Error?e.message:String(e)}`,error:!0})}if("starting"!==d.state)return void t.getTracks().forEach(e=>e.stop());u=t,p=[],f=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;try{m=c(t)}catch(e){return R(),M(!1),h({state:"idle",message:`This browser refused to record: ${e instanceof Error?e.message:String(e)}`,error:!0})}m.ondataavailable=e=>{e.data&&e.data.size&&p.push(e.data)},m.onerror=e=>{let t=$(),n=new Blob(p,{type:N()});if(C("recorder-error",{name:e?.error?.name??"",message:e?.error?.message??"",seconds:t,bytes:n.size,held:d.held}),E(),R(),M(!1),n.size)b=n,h({state:"retry",message:`The recorder stopped with an error after ${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}. What it captured is kept: Send again.${d.held?` ${s$(d.held)} of it is already stored.`:""}`,error:!0});else h({state:"idle",message:"The recorder stopped before it captured anything. Nothing was sent.",error:!0})},m.start(1e3),y=Date.now(),v=setInterval(()=>void _(),r),w=setInterval(()=>M(!0),a),j=setInterval(()=>h({seconds:$()}),500),h({state:"recording",seconds:0,message:""})}async function T(t){h({state:"sending",message:`Sending ${s$(t.size)}, then transcribing and storing…`,error:!1});try{let r=await s(`${n}takes?${S()}`,{method:"POST",headers:{"content-type":(t.type||"audio/mp4").split(";")[0]},body:t}),a=await r.json();if(!a.success||!a.take)throw Error(a.error||`HTTP ${r.status}`);b=null,f="";let i=a.presence??{state:a.listening?"listening":"away"},o=a.transcriptError?` Transcription failed, so no session wakes yet: ${a.transcriptError}`:({listening:" The session listening there will hear it.",answering:" Mia is answering an earlier take; she hears this one next.",answered:" The session hears it as soon as it listens again."})[i.state]??" No session is listening yet; the take waits, and her reply comes here when one answers.";h({state:"idle",seconds:0,held:0,message:`Take ${a.take} is in the episode.${o}`,error:!!a.transcriptError,stored:{take:a.take,english:a.english??"",transcriptError:a.transcriptError,presence:i}}),a.transcriptError||e.onStored?.(a.take)}catch(e){b=t,C("send-failed",{message:e instanceof Error?e.message:String(e),bytes:t.size,held:d.held}),h({state:"retry",message:`Not stored: ${e instanceof Error?e.message:String(e)}. Your recording is kept — Send again.${d.held?` ${s$(d.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function O(){if("recording"!==d.state)return;let e=$();E(),M(!1),h({state:"sending",seconds:e});let t=await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e(m?.whole??new Blob(p,{type:N()})))},s=setTimeout(n,3e3);if(!m)return n();m.onstop=()=>{clearTimeout(s),n()};try{m.stop()}catch{clearTimeout(s),n()}});if(R(),!t.size)return C("empty-at-stop",{seconds:e,held:d.held}),h({state:"idle",message:d.held?`The recorder handed back nothing at Stop, but ${s$(d.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await T(t)}async function P(){"retry"===d.state&&b&&await T(b)}return{getSnapshot:()=>d,press:async()=>"recording"===d.state?O():"retry"===d.state&&b?P():A(),start:A,stop:O,resend:P,destroy(){E(),("recording"===d.state||"starting"===d.state)&&M(!1);try{m?.stop()}catch{}R()}}}({base:rE,episode:()=>M.current,context:()=>{let e=S.current.shown,t=e?{...e.title||e.step.title?{title:[e.title,e.step.title].filter(Boolean).join(" · ")}:{},say:e.step.say.slice(0,400),...null!==e.index&&null!==e.count?{index:e.index,count:e.count}:{},...e.origin?{by:e.origin}:{}}:null;return function(e,t={}){if(!e?.doc)return null;let n={stage:e.stage,doc:e.doc,kind:e.kind,system:e.system,focus:e.focus??void 0,visible:e.visible,tour:e.tour,who:e.who,at:new Date().toISOString(),...t};for(let e of Object.keys(n))(void 0===n[e]||null===n[e])&&delete n[e];return n}(S.current.lastReport(),{...T.current.length?{marks:T.current}:{},...e?.step.spotlight?.length?{spotlight:e.step.spotlight}:{},...t?{step:t}:{}})},onChange:e=>{let t=E.current.state;if(E.current=e,m(e),!rT(t)||rT(e.state)||(A.current=!1,!C.current||R.current))return;let n=_.current.shift();n?D.current(n):w(null)},onStored:t=>e.waitFor(t)});return P.current=e,O.current=t,E.current=t.getSnapshot(),m(t.getSnapshot()),()=>{t.destroy(),e.destroy(),P.current=null,O.current=null}},[B]),(0,l.useEffect)(()=>{P.current?.setEpisode(i)},[i]),(0,l.useEffect)(()=>{let e=!0;return fetch(`${rE}health`,{cache:"no-store"}).then(e=>e.json()).then(t=>{if(e){if(!t.success)return k(`The companion does not answer: ${t.error??"no reason given"}.`);k(null),t.defaultEpisode&&c(e=>e??t.defaultEpisode??null)}}).catch(t=>e&&k(`The companion does not answer: ${t instanceof Error?t.message:String(t)}.`)),()=>{e=!1}},[]),(0,l.useEffect)(()=>{if(!n||d.length)return;let e=!0;return fetch(`${rE}episodes`,{cache:"no-store"}).then(e=>e.json()).then(t=>{e&&t.success&&t.episodes&&h(t.episodes)}).catch(()=>{}),()=>{e=!1}},[n,d.length]);let F=(0,l.useRef)(null),U=(0,l.useCallback)(async(e=!1)=>{let t=S.current.lastReport()?.doc??null;if(e||t!==F.current){if(F.current=t,!t){T.current=[];return}try{var n,s;let e=await fetch(`/api/marks?doc=${encodeURIComponent(t)}`,{cache:"no-store"}),r=await e.json();T.current=(n=function(e,t=""){let n=e&&"object"==typeof e?e:{},s=Array.isArray(n.marks)?n.marks.map(tp).filter(e=>null!==e):[];return{doc:th(n.doc)||t,marks:s}}(r,t).marks,s="agent",n.filter(e=>"open"===e.status&&e.author.role!==s||"answered"===e.status&&e.author.role===s)).map(e=>e.id)}catch{T.current=[]}}},[]);(0,l.useEffect)(()=>{U(!0);let e=S.current.onMarks(()=>void U(!0)),t=setInterval(()=>void U(),3e3);return()=>{e(),clearInterval(t)}},[U]),(0,l.useEffect)(()=>{if(!p.waiting)return;let e=setInterval(()=>N(Date.now()),1e3);return()=>clearInterval(e)},[p.waiting]);let z=(0,l.useCallback)(()=>{let e=O.current;e&&(!rT(E.current.state)&&"retry"!==E.current.state&&R.current&&(A.current=!0,S.current.stop()),e.press())},[]),Y=(0,l.useCallback)((e,t)=>{let n=P.current?.getSnapshot().items.find(t=>"reply"===t.kind&&t.id===e);if(n){if(rT(E.current.state))return void w(`Send your take first. Then press ▶ to hear Mia.`);_.current=[],A.current=!1,D.current(n,t)}},[]),H=(0,l.useCallback)(()=>{_.current=[],A.current=!1,S.current.stop()},[]),X=p.waiting?{take:p.waiting.take,seconds:Math.max(0,Math.floor(($-p.waiting.since)/1e3))}:null;return(0,o.jsx)("div",{className:"stage-talk-host",children:(0,o.jsx)(nd,{open:n,onOpenChange:e=>{s(e),e&&U(!0)},who:"Mia",episode:i,episodes:d,onEpisode:e=>{r_.test(e)&&e!==i&&(_.current=[],b([]),w(null),c(e))},presence:p.presence,recorder:u,onRecord:z,items:p.items,unheard:y,playing:g,playingStep:g&&e.shown?.origin==="Mia"?e.shown.index:null,onPlay:Y,onStop:H,onFeedback:(e,t)=>{P.current?.feedback(e,t).catch(e=>k(`Your thumb was not kept: ${e instanceof Error?e.message:String(e)}.`))},autoplay:r,onAutoplay:e=>{a(e);try{window.localStorage.setItem(rR,e?"1":"0")}catch{}e||(_.current=[])},waiting:X,notice:v,error:j??p.error})})}let rL=(0,l.createContext)(null);function rD(){return(0,l.useContext)(rL)}let rq="stateloom.stage.voice",rB="stateloom.author";function rF(e){try{return window.localStorage.getItem(e)??""}catch{return""}}function rU(e,t){try{window.localStorage.setItem(e,t)}catch{}}function rz({children:e}){var t;let n,s,r,a,i,c,d,h,[u,m]=(0,l.useState)({bridgeUrl:null,stage:ti,companion:!1,companionEpisode:null});(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{if(!e)return;let n=r$("stage"),s=tl(n)?n:tl(t.stage)?t.stage:ti;m({bridgeUrl:t.bridgeUrl,stage:s,companion:t.companion,companionEpisode:t.companionEpisode})}),()=>{e=!1}},[]);let[p,f]=(0,l.useState)(()=>"1"===rF(rq)),[g,x]=(0,l.useState)(()=>rF(rB)),y=(0,l.useMemo)(()=>p?sw():null,[p]),b=(0,l.useMemo)(()=>(function(e={}){let t=window,n=t.SpeechRecognition??t.webkitSpeechRecognition;if(!n)return null;let s=null;return{start(t,r){s?.stop();let a=new n;s=a,a.lang=e.lang??("u">typeof navigator?navigator.language:"en-US"),a.continuous=!0,a.interimResults=!0;let i="";a.onresult=e=>{let n="";for(let t=e.resultIndex;t<e.results.length;t++){let s=e.results[t],r=s[0]?.transcript??"";s.isFinal?i+=r:n+=r}t((i+n).trim(),""===n)},a.onerror=e=>r?.(e.error??"error"),a.onend=()=>{s===a&&(s=null),r?.()},a.start()},stop(){s?.stop(),s=null}}})(),[]),[v,w]=(0,l.useState)(null),j=(0,l.useRef)(new Set),k=(0,l.useCallback)(e=>{if(!e)return void w(null);let{step:t}=e,n=(0,s1.requestedDoc)();if(e.caught&&r$("doc"))return void w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce});if(t.doc&&t.doc!==n)rS({doc:t.doc,system:t.system??void 0,focus:t.focus??null});else if(t.focus)if(t.system&&r$("system")!==t.system&&n)rS({doc:n,system:t.system,focus:t.focus});else{var s;let e;s=t.focus,(e=new URL(window.location.href)).searchParams.set("focus",s),window.history.replaceState(window.history.state,"",e),window.dispatchEvent(new Event(rw))}w({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce})},[]),$=(t={url:u.bridgeUrl??"",stage:u.stage,name:"web-stage",voice:y,enabled:!!u.bridgeUrl,onShow:k,onMarks:e=>{for(let t of[...j.current])t(e)}},(n=(0,l.useRef)({onShow:t.onShow,onMarks:t.onMarks})).current={onShow:t.onShow,onMarks:t.onMarks},s=(0,l.useRef)(null),r=`${t.url}\u0000${t.stage??""}\u0000${t.token??""}`,a=(0,l.useRef)(r),(null===s.current||a.current!==r)&&(a.current=r,s.current=function(e){let t,n=tl(e.stage)?e.stage:ti,s=e.setTimer??((e,t)=>setTimeout(e,t)),r=e.clearTimer??(e=>clearTimeout(e)),a=e.gapMs??900,i=e.client??sy({url:e.url,role:e.role??"web",docId:`stage:${n}`,name:e.name??"web-stage",token:e.token,autoResync:!1}),o=e.voice??null,l=e=>e&&void 0!==t?t:o,c=null,d=null,h=e=>{let t=d;d=null,t?.(e)},u=null,m=null,p=[],f=[],g=0,x=!1,y=!1,b=0,v=null,w=0,j=!1,k=!1,$=!1,N=!1,S=!1,M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!1},C=new Set;function E(){for(let e of(M={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!!m&&void 0!==t},[...C]))e()}function R(){w+=1,v&&r(v),v=null,y&&c?.cancel(),y=!1,c=null}function _(e,t,n=t){R();let r=++w,i=()=>{r!==w||(y&&(y=!1,E()),t&&x&&(v=s(()=>{v=null,r===w&&x&&L()},o?a:0)))},o=l(n);o?(y=!0,c=o,E(),o.speak(e).then(i,i)):t&&(v=s(()=>{v=null,i()},tg(e)))}function A(t,n){b+=1,R(),u=t?{...t,nonce:b,...S?{caught:!0}:{}}:null,E(),e.onShow?.(u);let s=!!u&&null!==u.index;u&&(l(s)||n)&&_(u.step,n,s)}function T(e){if(!m)return null;let t=m.def.steps[e];if(!t)return null;let n=t.doc??p[e],s=t.system??f[e];return{step:{...t,...n?{doc:n}:{},...s?{system:s}:{}},index:e,count:m.def.steps.length,title:m.def.settings?.name,origin:m.origin,tourPath:m.path}}function O(e,n,s){var r;let a,i;h(!1),t=s;let o=Array.isArray(e.tour?.steps)?e.tour.steps:[];r=(m={def:{...e.tour,steps:o},path:e.path,origin:e.origin}).def,i=void 0,p=r.steps.map(e=>i=e.doc??i),f=o.map(e=>a=e.system??a),g=Math.min(Math.max(0,e.from??0),Math.max(0,o.length-1)),j=!1,x=n&&o.length>0,A(T(g),x)}function P(e){x=!1,A({step:e.step,index:null,count:null,title:e.title,origin:e.origin,tourPath:e.tour},!1)}function I(e){if(!m)return;let t=m.def.steps.length-1;t<0||(j=!1,A(T(g=Math.min(Math.max(0,Math.floor(e)),t)),x))}function L(){if(m){if(g>=m.def.steps.length-1){let e=x;j=x||j,x=!1,R(),E(),e&&h(!0);return}I(g+1)}}function D(){m&&g>0&&I(g-1)}function q(){m&&m.def.steps.length&&(x=!0,j&&(j=!1,g=0),u?.index!==g||u.caught?A(T(g),!0):(E(),_(u.step,!0)))}function B(){x=!1,R(),E()}function F(){h(!1),t=void 0,j=!1,m=null,p=[],f=[],g=0,x=!1,A(null,!1)}function U(){N||(N=!0,i.joinStage(n).then(({state:e})=>{N=!1,$=!0,u||m||function(e){S=!0;try{e.tour&&O(e.tour,!1),e.step&&P(e.step)}finally{S=!1}}(e),E()}).catch(()=>{N=!1,E()}))}return i.on("stage-step",e=>{e?.stage===n&&e.step&&P(e)}),i.on("stage-load",e=>{e?.stage===n&&e.tour&&O(e,!1!==e.autoplay)}),i.on("stage-control",e=>{e?.stage===n&&function(e){switch(e.action){case"play":return q();case"pause":return B();case"next":return L();case"prev":return D();case"goto":return I(e.index??0);case"stop":return F()}}(e)}),i.on("marks",t=>e.onMarks?.(t)),i.on("status",e=>{"disconnected"===e||"error"===e?$=!1:"connected"===e&&k&&!$&&U(),E()}),{getSnapshot:()=>M,subscribe:e=>(C.add(e),()=>{C.delete(e)}),connect(){k=!0,U()},disconnect(){k=!1,R(),i.leaveStage(n),i.disconnect()},play:q,pause:B,next:L,prev:D,goto:I,stop:F,dismiss:function(){if(u){if(null===u.index&&m)return void A(T(g),!1);null===u.index?A(null,!1):F()}},setVoice(e){void 0===t&&R(),o=e,E()},present:(e,t={})=>Array.isArray(e?.steps)&&e.steps.length?new Promise(s=>{O({stage:n,tour:e,from:t.from??0,autoplay:!1!==t.autoplay,origin:t.origin??"page"},!1!==t.autoplay,t.voice),d=s}):Promise.resolve(!1),sendContext(e){i.emitContext({...e,stage:n,...m?{tour:{path:m.path,title:m.def.settings?.name,index:g,count:m.def.steps.length,playing:x}}:{}})},sendMarks(e){i.emitMarks({...e,stage:n}).catch(()=>{})}}}({...t,voice:t.voice??null,onShow:e=>n.current.onShow?.(e),onMarks:e=>n.current.onMarks?.(e)})),i=s.current,c=(0,l.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),d=!1!==t.enabled&&!!t.url,(0,l.useEffect)(()=>{if(d)return i.connect(),()=>i.disconnect()},[i,d]),h=t.voice??null,(0,l.useEffect)(()=>{i.setVoice(h)},[i,h]),{...c,play:i.play,pause:i.pause,next:i.next,prev:i.prev,goto:i.goto,stop:i.stop,dismiss:i.dismiss,sendContext:i.sendContext,sendMarks:i.sendMarks,present:i.present}),N=(0,l.useRef)(null),S=(0,l.useRef)(null),M=$.sendContext,C=(0,l.useCallback)(e=>{N.current={...e,stage:u.stage,who:g||void 0,at:new Date().toISOString()},S.current&&clearTimeout(S.current),S.current=setTimeout(()=>M({...e,who:g||void 0}),400)},[u.stage,g,M]);(0,l.useEffect)(()=>()=>{S.current&&clearTimeout(S.current)},[]),(0,l.useEffect)(()=>{N.current&&M({...N.current,who:g||void 0})},[$.index,$.playing,$.tour,M,g]);let[E,R]=(0,l.useState)(0),_=!!$.shown;(0,l.useEffect)(()=>{let e=document.documentElement,t=_?document.querySelector(".stage-caption-host .slc-stage-caption"):null;if(!t||"u"<typeof ResizeObserver)return void e.style.removeProperty("--stage-caption-h");let n=()=>e.style.setProperty("--stage-caption-h",`${Math.ceil(t.getBoundingClientRect().height)+12}px`),s=new ResizeObserver(n);return s.observe(t),n(),()=>{s.disconnect(),e.style.removeProperty("--stage-caption-h")}},[_]);let A=(0,l.useMemo)(()=>({stage:u.stage,connected:"connected"===$.status,lit:v,author:g,setAuthor:e=>{x(e),rU(rB,e)},listener:b,answerNonce:E,report:C,lastReport:()=>N.current,sendMarks:$.sendMarks,onMarks:e=>(j.current.add(e),()=>{j.current.delete(e)}),shown:$.shown,present:$.present,pause:$.pause,stop:$.stop}),[u.stage,$.status,$.shown,$.sendMarks,$.present,$.pause,$.stop,v,g,b,E,C]);return(0,o.jsxs)(rL.Provider,{value:A,children:[e,$.shown&&(0,o.jsx)("div",{className:"stage-caption-host",children:(0,o.jsx)(t7,{shown:$.shown,playing:$.playing,speaking:$.speaking,voice:$.ownVoice?void 0:p,onToggleVoice:()=>{let e=!p;f(e),rU(rq,e?"1":"0")},onPlay:$.play,onPause:$.pause,onNext:$.next,onPrev:$.prev,onGoto:$.goto,onClose:$.dismiss,onAnswer:()=>R(e=>e+1)})}),u.companion&&(0,o.jsx)(rI,{stage:A,defaultEpisode:u.companionEpisode})]})}let rY="flex h-9 min-w-9 items-center justify-center gap-1 rounded-lg border border-gray-700 bg-gray-900/90 px-2 text-sm text-gray-200 shadow-lg backdrop-blur hover:bg-gray-800";async function rH(e,t){let n=await fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),s=await n.json().catch(()=>({}));if(!n.ok)throw Error(s?.error??`the marks could not be written (${n.status})`);return s}function rX({docPath:e,kind:t,viewport:n,setViewport:s,boxes:r,boardRef:a,focus:i=null,level:c,onReveal:d}){let h=rD(),[u,m]=(0,l.useState)([]),[p,f]=(0,l.useState)(!1),[g,x]=(0,l.useState)(null),[y,b]=(0,l.useState)(null),[v,w]=(0,l.useState)(!1),[j,k]=(0,l.useState)(!1),[$,N]=(0,l.useState)(null),[S,M]=(0,l.useState)(!1),C=(0,l.useCallback)(()=>{e&&fetch(`/api/marks?doc=${encodeURIComponent(e)}`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>e&&Array.isArray(e.marks)&&m(e.marks)).catch(()=>{})},[e]);(0,l.useEffect)(()=>(m([]),b(null),x(null),C(),window.addEventListener("focus",C),()=>window.removeEventListener("focus",C)),[C]),(0,l.useEffect)(()=>h?.onMarks(t=>{e&&t.docId===e&&Array.isArray(t.marks)&&m(t.marks)}),[h,e]);let E=async t=>{if(!e)return!1;k(!0),N(null);try{let n=await rH(e,t);return m(n.marks),h?.sendMarks({docId:e,marks:n.marks,change:n.change}),!0}catch(e){return N(e instanceof Error?e.message:String(e)),!1}finally{k(!1)}},R=h?.lit??null,_=R&&(!R.doc||R.doc===e)?R:null,A=_?.spotlight,T=_?.region??null,O=(0,l.useRef)(-1),P=(0,l.useRef)(-1),I=(0,l.useRef)(null),L=(0,l.useMemo)(()=>A?.length?tb(r,A):[],[r,A]);(0,l.useEffect)(()=>{if(!_||O.current===_.nonce)return;let e=[...L,...T?[T]:[]];if(!e.length){A?.length&&P.current!==_.nonce&&(P.current=_.nonce,d?.(A));return}O.current=_.nonce;let t=()=>{let t=a.current?.getBoundingClientRect();if(!t?.width)return;let n=document.querySelector(".stage-caption-host .slc-stage-caption")?.getBoundingClientRect(),r=n&&n.top<t.bottom?Math.max(0,t.bottom-n.top+8):0,i=Math.max(.4*t.height,t.height-r);s(H(e,t.width,i,{padding:48,maxScale:1}))};t(),I.current&&clearTimeout(I.current),I.current=setTimeout(t,520)},[_,L,T,A,a,s,d]),(0,l.useEffect)(()=>()=>{I.current&&clearTimeout(I.current)},[]);let D=(0,l.useRef)(h?.answerNonce??0);(0,l.useEffect)(()=>{if(!h||h.answerNonce===D.current)return;D.current=h.answerNonce;let e=A?.length?[...A]:_?.focus?[_.focus]:i?[i]:[];w(!1),b(null),x({elements:e,region:T??void 0,listen:!!h.listener})},[h,A,_,i,T]);let q=h?.report;if((0,l.useEffect)(()=>{if(!q||!e)return;let s=a.current?.getBoundingClientRect(),r=F(n,{x:0,y:0}),o=s?F(n,{x:s.width,y:s.height}):r;q({doc:e,kind:t,system:r$("system")??void 0,focus:i,...s?.width?{visible:{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(o.x-r.x),height:Math.round(o.y-r.y)}}:{}})},[q,e,t,i,n,a]),!e)return null;let B=u.filter(e=>"open"===e.status&&"person"===e.author.role).length,U=u.filter(e=>"open"===e.status&&"agent"===e.author.role).length,z=u.find(e=>e.id===y)??null;return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(tV,{viewport:n,boxes:r,spotlight:A,region:T,marks:u,selectedMark:y,onSelectMark:e=>{x(null),w(!1),b(t=>t===e?null:e)},marking:p,onDraft:e=>{f(!1),b(null),w(!1),x(e)},draft:g}),(0,o.jsxs)("div",{className:"stage-board-controls",children:[(0,o.jsxs)("button",{type:"button",className:`${rY} ${p?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":p,onClick:()=>{x(null),f(e=>!e)},title:p?"Marking: tap an element, or drag around several. Tap ✎ again to stop.":"Mark something for the agent — tap an element or drag around several",children:[(0,o.jsx)(t8,{}),p&&(0,o.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,o.jsxs)("button",{type:"button",className:rY,"aria-expanded":v,onClick:()=>{x(null),b(null),w(e=>!e)},title:"Marks on this drawing",children:[(0,o.jsx)(tG,{}),B+U>0&&(0,o.jsx)("span",{className:"text-xs text-amber-300",children:B+U})]})]}),p&&!g&&(0,o.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),(g||z||v)&&(0,o.jsx)("div",{className:"stage-board-card",children:g?(0,o.jsx)(nn,{elements:g.elements,region:g.region,author:h?.author??"",onAuthorChange:h?.setAuthor,listener:h?.listener,listenAtOnce:!!g.listen,busy:j,error:$,onCancel:()=>{x(null),N(null)},onSubmit:async({text:e,kind:t,author:n})=>{await E({action:"add",mark:{text:e,kind:t,elements:g.elements,region:g.region,level:c,author:{name:n||"someone"}}})&&x(null)}},`${g.elements.join(",")}|${g.region?JSON.stringify(g.region):""}`):z?(0,o.jsx)(ns,{mark:z,number:u.indexOf(z)+1,listener:h?.listener,busy:j,error:$,onClose:()=>b(null),onReply:e=>void E({action:"reply",id:z.id,text:e,author:{name:h?.author||"someone"}}),onResolve:()=>void E({action:"resolve",id:z.id}),onReopen:()=>void E({action:"reopen",id:z.id}),onRemove:async()=>{await E({action:"remove",id:z.id})&&b(null)}}):(0,o.jsx)(nr,{marks:u,selected:y,onSelect:e=>{w(!1),b(e)},onCopy:()=>{var t,n;let s,r;if(!e)return;let a=(t=h?.lastReport()??null,s=(n=[{doc:e,marks:u.filter(e=>"resolved"!==e.status)}]).reduce((e,t)=>e+t.marks.length,0),r=function(e){if(!e||!e.doc)return"No canvas has said what it is showing.";let t=[`${e.who?`${e.who} is`:"The canvas is"} on ${tv(e.doc)}${e.kind?` (${e.kind})`:""}`];e.system&&t.push(`as a member of ${tv(e.system)}`),e.focus&&t.push(`with ${e.focus} in hand`);let n=t.join(", ")+".";return e.tour&&(n+=` Tour ${e.tour.title?`'${e.tour.title}' `:""}at step ${e.tour.index+1} of ${e.tour.count}, ${e.tour.playing?"playing":"paused"}.`),e.at&&(n+=` (reported ${e.at})`),n}(t),s?`${r}
11
- ${s} mark(s):
12
- ${function(e,t={}){let n=[],s=t.start??1;for(let{doc:t,marks:r}of e)for(let e of r){for(let r of(n.push(`${s}. [${e.status} \xb7 ${e.kind}] ${e.author.name}${"agent"===e.author.role?" (agent)":""} on ${tf(e)} (${tv(t)}) — ${e.id}`),n.push(` "${tw(e.text)}"`),e.replies??[]))n.push(` ↳ ${r.author.name}${"agent"===r.author.role?" (agent)":""}: "${tw(r.text)}"`);s++}return n.join("\n")}(n)}`:`${r}
13
- No marks.`);navigator.clipboard?.writeText(a).then(()=>{M(!0),setTimeout(()=>M(!1),2e3)})},copied:S,onClose:()=>w(!1)})})]})}function rV({docPath:e,onReveal:t}){let n=rD(),s=n?.lit??null,r=(0,l.useRef)(-1);return(0,l.useEffect)(()=>{!s||r.current===s.nonce||s.doc&&s.doc!==e||(s.spotlight?.length||s.region)&&(r.current=s.nonce,t())},[s,e,t]),null}function rJ(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 rW=(e,t)=>"chen"===t?`stateloom:erd-layout:chen:${e}`:`stateloom:erd-layout:${e}`,rK="stateloom:erd-notation",rZ="stateloom:erd-lock";function rG(e,t){try{return JSON.parse(localStorage.getItem(rW(e,t))??"{}")}catch{return{}}}async function rQ(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,s1.docQuery)(e)}`,{cache:"no-store"})).json(),n=JSON.parse(t.content??"null"),r=ex(n?.stateMachine??n?.StateMachine??n);r?.state&&s.push({path:e,def:r})}catch{}return s}let r0="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",r1="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r2="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function r5(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(""),[s,r]=(0,l.useState)(null),[a,i]=(0,l.useState)({}),[c,d]=(0,l.useState)("crowsfoot"),[h,u]=(0,l.useState)(!1),[m,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,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),A=(0,l.useRef)(null),T=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[O,P]=(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,s1.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?ex(JSON.parse(a.content)):null;K(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(rK)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();n(o),r(l??{settings:{namespace:"Default",name:c},entities:[],relationships:[]}),d(h),u(function(){try{let e=localStorage.getItem(rZ);if(null!==e)return"1"===e;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),i(rG(o,h)),y(null),L(null),g(e=>e+1),w(a.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:m}=await re();!t&&m&&(D.current=s=sv({url:m,role:"web",docId:o,name:"web-designer",onFull:e=>{let t=e.def;K(t)&&(r({...t,relationships:t.relationships??[]}),w("updated live"))},onPatch:()=>{},onPresence:e=>P(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=rJ(()=>(function(e,t={}){let n=t.notation??"crowsfoot",s=t.hSpacing??70,r=t.vSpacing??("chen"===n?130:90),a="chen"===n?ed:eb,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)},u=new Set([...l.values()].flat());for(let e of i)u.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 m=[],p=new Map,f=(e,t)=>((m[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=m.length-1;e>=0;e--)m[e]?.length||m.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 m)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<m.length;e++)y(m[e],"upper");for(let e=m.length-2;e>=0;e--)y(m[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 m)v(e,"upper");for(let e=m.length-2;e>=0;e--)v(m[e],"lower");let w=Math.min(0,...[...p.values()].map(e=>e.x)),j={},k=40;for(let e of m){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 rJ(()=>Z(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]),U=(0,l.useMemo)(()=>F.map(e=>(e.element??"").split(/[.[]/)[0]).filter(Boolean),[F]),Y=(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,s1.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]),X=(0,l.useCallback)((e,n)=>{i(s=>{let r={...s,[e]:{x:Math.round(n.x),y:Math.round(n.y)}};try{localStorage.setItem(rW(t,c),JSON.stringify(r))}catch{}return r})},[t,c]),V=()=>{i({});try{localStorage.removeItem(rW(t,c))}catch{}g(e=>e+1)},G=async()=>{if(!s)return;w("checking links…");let e=await rQ(t);if(0===e.length)return L("none"),N("issues"),M(!0),w("no .smdf.json beside this document to check against","warn");let n=e.flatMap(e=>Q(e.def,s).map(t=>({...t,message:`${e.def.settings?.name??e.path}: ${t.message}`})));n.push(...ee(s,e.map(e=>e.def.settings?.name??""))),L(n),N("issues"),M(!0),_(!1),w(`checked ${e.length} machine(s): ${n.length} problem(s)`,n.length?"warn":"ok")},ei=async e=>{let n=(await rQ(t)).find(t=>t.def.settings?.name===e);n?(0,s1.navigateToDoc)(n.path):w(`no .smdf.json beside this document defines '${e}'`,"warn")},eo=()=>{let e=A.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},el=e=>{let{width:t,height:n}=eo();p(s=>z(s,e,{x:t/2,y:n/2}))},ec=e=>{let t=B[e],{width:n,height:s}=eo();t&&n&&(p(H([t],n,s,{padding:28,maxScale:1.25})),y(e),T.close())},eu=rC(),eg=rN("focus"),ey=(0,l.useMemo)(()=>s?rJ(()=>(function(e,t,n={}){let s=!1!==n.rows,r=[];for(let n of e?.entities??[]){let e=n?.name?t[n.name]:void 0;e&&(r.push({focus:`entity:${n.name}`,box:e}),(n.attributes??[]).filter(e=>e?.name).forEach((t,a)=>{r.push({focus:`attribute:${n.name}.${t.name}`,box:s?{x:e.x,y:e.y+30+20*a,width:e.width,height:20}:e})}))}return r})(s,B,{rows:"chen"!==c}),[]):[],[s,B,c]),ev=(0,l.useRef)(-1);(0,l.useEffect)(()=>{if(!s||ev.current===eu.nonce)return;ev.current=eu.nonce;let e=eu.focus?e9(eu.focus):null,t=e?.kind==="entity"?e.name:e?.kind==="attribute"?e.name.split(".")[0]:null;t&&B[t]&&ec(t)},[s,eu,B]),(0,l.useEffect)(()=>{x&&!r$("focus")?.startsWith(`attribute:${x}.`)&&rM(`entity:${x}`)},[x]);let ew=s?.entities.find(e=>e.name===x)??null,ej=t.split("/").pop()||"…",ek=Array.isArray(I)?I:[],e$=F.length+ek.length,eN=[{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)(rx,{}),badge:e$||void 0}],eS=e=>$===e?"":"hidden md:block",eM=()=>{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=eh[r.cardinality]??eh["1:N"];t.push(`${n}${em(r.from)} ${e} ${em(r.to)} : ${ef(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=[ep(e.type??"","unknown"),ep(e.name,"unnamed")];return t.length&&r.push(t.join(", ")),n.length&&r.push(ef(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&&E(!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)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:t,children:[s?.settings.name??ej,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",ej]})]}),(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(rK,e)}catch{}d(e),i(rG(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:r1,onClick:V,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,o.jsx)("button",{className:r1,onClick:G,title:"Check the state machines beside this document against it",children:"Check links"}),(0,o.jsx)("button",{className:r1,onClick:eM,children:"Copy mermaid"}),(0,o.jsx)("button",{className:r1,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ 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(),E(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",V],["Check links to the machines",G],["Copy as mermaid",eM]].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:()=>{E(!1),t()},children:e},e))})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:A,className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&(0,o.jsx)(rg,{what:"diagram",resetKey:s,children:(0,o.jsx)(tq,{definition:s,notation:c,positions:B,viewport:m,onViewportChange:p,selection:x,readOnly:h,errorElements:U,fitKey:f,onSelect:y,onClearSelection:()=>y(null),onEntityMove:X,onOpenMachine:ei,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),s&&(0,o.jsx)(rX,{docPath:t||null,kind:"erd",viewport:m,setViewport:p,boxes:ey,boardRef:A,focus:eg}),(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,O>1?` \xb7 ${O} 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;u(e);try{localStorage.setItem(rZ,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)(ry,{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))]}),ew&&!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"),M(!0)},children:["✎ ",ew.name]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:T.close,"aria-hidden":"true"}),s&&(0,o.jsxs)("aside",{style:T.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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...T.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:eN.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:T.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:eS("entities"),children:[(0,o.jsx)("div",{className:r2,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:`${r1} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))}),(0,o.jsx)(r3,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:e=>{Y(t=>er(t,{name:e.name.trim()})),y(e.name.trim())}}),ew&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r2} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ew.name}),(0,o.jsx)("button",{className:`${r1} normal-case tracking-normal`,onClick:()=>ec(ew.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:!!ew.weak,onChange:e=>Y(t=>ea(t,ew.name,{weak:e.target.checked}))}),"weak entity"]}),(ew.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:()=>Y(t=>(function(e,t,n){let s=et(e),r=en(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,ew.name,e.name)),children:"✕"})]},e.name)),(0,o.jsx)(r3,{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=>Y(t=>(function(e,t,n){if(!n.name?.trim())throw Error("An attribute needs a name.");let s=et(e),r=en(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(es({...n})),s})(t,ew.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:`${r1} mt-2 text-red-300`,onClick:()=>{Y(e=>{var t;let n;return t=ew.name,en(n=et(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 ",ew.name]})]})]}),(0,o.jsxs)("section",{className:eS("relations"),children:[(0,o.jsx)("div",{className:`${r2} 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:()=>Y(t=>(function(e,t,n,s){let r=et(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)(r3,{fields:[{name:"from",options:s.entities.map(e=>e.name)},{name:"cardinality",options:[...W],initial:"1:N"},{name:"to",options:s.entities.map(e=>e.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:e=>Y(t=>(function(e,t){let n=et(e);if(en(n,t.from),en(n,t.to),!W.includes(t.cardinality))throw Error(`Cardinality '${t.cardinality}' is not one of ${W.join(", ")}.`);return n.relationships.push(es({...t})),n})(t,{from:e.from,to:e.to,cardinality:e.cardinality,label:e.label.trim()||void 0}))})]}),(0,o.jsxs)("section",{className:eS("notes"),children:[(0,o.jsx)("div",{className:`${r2} 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)(r4,{label:"On this diagram",value:s.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>Y(t=>(function(e,t){let n=et(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"),ew?(0,o.jsx)(r4,{label:`On ${ew.name}`,value:ew.notes??"",placeholder:`A question or a decision about ${ew.name}…`,onSave:e=>Y(t=>ea(t,ew.name,{notes:e}))},`entity:${ew.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:r2,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:`${r1} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))})]})]}),(0,o.jsxs)("section",{className:eS("issues"),children:[(0,o.jsx)("div",{className:`${r2} max-md:mt-0 ${0===e$&&!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}`)),ek.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===e$&&"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:eN.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?T.close():M(!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 r4({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 u=(0,l.useRef)(null),m=e=>{u.current&&clearTimeout(u.current),u.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:`${r0} h-24 resize-y leading-snug`,placeholder:n,value:r,onChange:e=>{let t=e.target.value;a(t),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>m(t),900)},onFocus:()=>h(!0),onBlur:()=>{h(!1),m(r)}})]})}function r3({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:r0,"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:r0,"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:`${r1} ${1===e.length?"":"col-span-2"}`,children:t})]})}let r6="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",r8="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r7="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function r9({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:`${r6} ${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:r6,"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:`${r8} col-span-2`,children:n})]})}function ae({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"})]})]})}let at=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],an=e=>`seq-read-${e.kind}-${e.id}`;function as({definition:e,selection:t,issues:n,onSelect:s,onShowInDiagram:r}){let a=new Map(e.participants.map((e,t)=>[e.name,at[t%at.length]])),i=eS(e),l=i.filter(e=>null===e.fragment),c=(e.fragments??[]).map((e,t)=>({f:e,fi:t,rows:i.filter(e=>e.fragment===t)})),d=(e,n)=>t?.kind===e&&t.id===n,h=e=>(0,o.jsx)("span",{className:`font-semibold ${a.get(e)??"text-gray-300"}`,children:e||"?"}),u=(e,t)=>{let a={kind:"message",id:e},i=n.get(`message:${e}`)??[],l=i.some(e=>"error"===e.severity)?"error":i.length?"warning":null,c=d("message",e);return(0,o.jsx)("li",{id:an(a),className:"scroll-mt-16 scroll-mb-24",children:(0,o.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":c,onClick:()=>s(a),onKeyDown:e=>("Enter"===e.key||" "===e.key)&&(e.preventDefault(),s(a)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${c?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===l?"border-red-500":"warning"===l?"border-amber-400":"border-transparent"}`,children:[(0,o.jsx)("span",{className:"mt-0.5 flex h-6 min-w-6 shrink-0 items-center justify-center rounded-full border border-gray-700 bg-gray-900 px-1 font-mono text-[11px] text-gray-300",children:e}),(0,o.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,o.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[h(t.from),t.from===t.to?(0,o.jsx)("span",{children:" to itself"}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{className:"px-1.5 text-gray-500",children:t.reply?"⇠":"→"}),h(t.to)]}),t.reply&&(0,o.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),t.optional&&(0,o.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,o.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${t.reply?"text-gray-300":"text-gray-100"}`,children:t.label||(0,o.jsx)("span",{className:"text-gray-500",children:"no label"})}),(t.event||t.state||t.carries)&&(0,o.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[t.event&&(0,o.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:t.event}),t.event&&t.machine&&(0,o.jsxs)("span",{className:"text-gray-400",children:["on ",t.machine]}),t.state&&(0,o.jsxs)("span",{className:"text-emerald-300",children:["→ ",t.state]}),t.carries&&(0,o.jsxs)("span",{className:"text-gray-400",children:["carries ",t.carries]})]}),i.map((e,t)=>(0,o.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===e.severity?"text-red-300":"text-amber-300"}`,children:e.text},t)),c&&(0,o.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:e=>{e.stopPropagation(),r(a)},children:"Show in the diagram"})]})]})},e)};return(0,o.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,o.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[e.participants.length>0&&(0,o.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:e.participants.map(e=>{let t={kind:"participant",id:e.name},r=e.actor?"actor":e.object?"object":e.service?"service":"",a=n.get(`participant:${e.name}`)??[];return(0,o.jsx)("li",{id:an(t),children:(0,o.jsxs)("button",{onClick:()=>s(t),"aria-pressed":d("participant",e.name),title:a.map(e=>e.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${d("participant",e.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${a.length?"ring-1 ring-amber-400/70":""}`,children:[h(e.name),r&&(0,o.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:r})]})},e.name)})}),0===i.length&&(0,o.jsx)("p",{className:"text-sm text-gray-400",children:"No messages yet — add them in the panel, or let an agent write the scenario."}),(0,o.jsx)("ol",{className:"flex flex-col gap-1",children:l.map(({ref:e,message:t})=>u(e,t))}),c.map(({f:e,fi:t,rows:n})=>(0,o.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,o.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,o.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,o.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:e.kind}),(0,o.jsxs)("span",{className:"text-indigo-300",children:[" · after ",e.after]})]}),(0,o.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:e.label})]}),0===n.length?(0,o.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,o.jsx)("ol",{className:"flex flex-col gap-1",children:n.map(({ref:e,message:t})=>u(e,t))})]},t))]})})}async function ar(e){try{let t=await fetch(`/api/file${(0,s1.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 aa extends Error{constructor(e){super(`${e.split("/").pop()} changed on disk since it was read`)}}async function ai(e,t,n){let s=await fetch(`/api/file${(0,s1.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 aa(e);if(!s.ok)throw Error(r?.error??`HTTP ${s.status}`);return r?.mtime}async function ao(e){let t=await ar(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=ex(JSON.parse(t.content));eY(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=eJ(t.path,e.path);r[e.path]=n;let s=eH(e.path),o=await ar(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:ex(t.stateMachine??t.StateMachine)};return{path:e.path,kind:s,def:ex(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 al(){window.dispatchEvent(new Event(rj))}function ac(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(rj,a),()=>window.removeEventListener(rj,a)),[a]),(0,l.useEffect)(()=>{if(!e)return;let t=!0;return ao(e).then(s=>t&&n({for:e,system:s})),()=>{t=!1}},[e,s]),{system:e&&t?.for===e?t.system:null,reload:a}}function ad(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 ah(e,t,n,s){let{bridgeUrl:r}=await re();if(!r)return;let a=sy({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 au(e,t){let n=[],s=[],r=[],a=async(e,t)=>{try{await t(),n.push(e)}catch(t){t instanceof aa?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 ai(t,s,e.mtimes[n.member]),a=e.members.find(e=>e.path===n.member)?.def;await ah(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 ai(t,n.def,e.mtimes[n.member]);await ah(t,n.def,s)})}return t.system&&await a(e.path.split("/").pop()??e.path,async()=>{let n=await ai(e.path,t.system.def,e.mtimes[e.path]);await ah(e.path,t.system.def,n)}),al(),{written:n,failed:s,conflicts:r}}async function am(e){let t={result:null,written:[],failed:[],conflicts:[]};for(let n=0;n<2;n+=1){let s=await ao(e);if(!s.def)return{...t,failed:[s.error??"the system could not be read"],retried:n>0};let r=tr(s.def,s.members);if(!r.count)return{...t,result:r,conflicts:n?t.conflicts:[],retried:n>0};let a=await au(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 ap="stateloom.sequence.view",af=["","actor","service","object"],ag=e=>"string"==typeof e?e.trim():"",ax=e=>ag(e).split(",").map(e=>e.trim()).filter(Boolean);function ay(e){return{from:ag(e.from),to:ag(e.to),label:ag(e.label),event:ag(e.event),machine:ag(e.machine),carries:ag(e.carries),state:ag(e.state),description:ag(e.description),optional:!!e.optional||void 0,reply:!!e.reply||void 0}}function ab(){let e,t,n,s=(0,s1.useRequestedDoc)(),r=rN("system"),{system:a}=ac(r),i=rC(),[c,d]=(0,l.useState)(""),[h,u]=(0,l.useState)(null),[m,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,M]=(0,l.useState)(!1),[C,E]=(0,l.useState)(!1),[R,_]=(0,l.useState)(!1),[A,T]=(0,l.useState)("diagram"),O=(0,l.useRef)("diagram");(0,l.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ap)}catch{}let t="list"===e||"diagram"===e?e:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";O.current=t,T(t)},[]);let P=(0,l.useCallback)(e=>{O.current=e,T(e);try{window.localStorage.setItem(ap,e)}catch{}},[]),I=(0,l.useRef)(null),L=rb({onClose:()=>M(!1),restVh:62,tallVh:92}),[D,F]=(0,l.useState)(0),U=(0,l.useRef)(null),Y=(0,l.useRef)(!0),X=(0,l.useRef)(-1);(0,l.useEffect)(()=>{let e=!1,t=null;return(async()=>{let n=await (await fetch(`/api/file${(0,s1.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?ex(JSON.parse(n.content)):null;ej(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),u(a??ek("Default",i)),w(n.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:o}=await re();!e&&o&&(U.current=t=sv({url:o,role:"web",docId:r,name:"web-designer",onFull:e=>{let t=e.def;ej(t)&&(u(t),w("updated live"))},onPatch:()=>{},onPresence:e=>F(e.length)}),t.connect())})().catch(t=>!e&&w(String(t),"warn")),()=>{e=!0,U.current=null,t?.disconnect()}},[s,w]);let V=(0,l.useMemo)(()=>h?tH(h):null,[h]),J=(0,l.useMemo)(()=>V?eD(V):null,[V]),W=(0,l.useMemo)(()=>V&&J?rJ(()=>(function(e,t){let n=[];for(let e of t.participants)n.push({focus:`participant:${e.name}`,box:{x:e.left,y:e.top,width:e.width,height:Math.max(e.height,t.lifelineBottom-e.top)}});let s=new Map(eS(e).map(e=>[e.ref,e.message]));for(let e of t.rows){let t=e.self?e.fromX:Math.min(e.fromX,e.toX),r=e.self?220:Math.max(40,Math.abs(e.toX-e.fromX)),a={x:t-10,y:e.y-24,width:r+20,height:40};n.push({focus:`message:${e.ref}`,box:a});let i=s.get(e.ref)?.event;i&&n.push({focus:`event:${i}`,box:a})}return n})(V,J),[]):[],[V,J]),K=rN("focus"),Z=(0,l.useMemo)(()=>{if(!h)return[];let e="";return rJ(()=>eM(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]),G=ad(a,c),Q=(0,l.useMemo)(()=>a?.def&&G&&h?rJ(()=>e8(a.def,a.members.map(e=>e.path===G?{...e,def:h,error:void 0}:e)),null):null,[a,G,h]),ee=(0,l.useMemo)(()=>(Q?.issues??[]).filter(e=>e.member===G&&!/^S0/.test(e.ruleId)),[Q,G]),et=Q?.replays.find(e=>e.member===G)?.report??null,en=(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}=e6(e.members);for(let{def:e}of(n.forEach(({def:e},n)=>{for(let s of(t.machines.add(e0(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]),es=(0,l.useMemo)(()=>{let e=e=>e?/^(message|participant):/.test(e)?e:V?.participants.some(t=>t.name===e)?`participant:${e}`:"":"";return[...Z.map(t=>e(t.element)),...ee.filter(e=>"error"===e.severity).map(t=>e(t.element))].filter(Boolean)},[Z,ee,V]),er=(0,l.useMemo)(()=>ee.filter(e=>"warning"===e.severity).map(e=>e.element??""),[ee]),ea=(0,l.useMemo)(()=>{let e=new Map,t=(t,n)=>{let s=t?/^(message|participant):/.test(t)?t:V?.participants.some(e=>e.name===t)?`participant:${t}`:"":"";s&&e.set(s,[...e.get(s)??[],n])};return Z.forEach(e=>t(e.element,{severity:"error",text:e.message})),ee.forEach(e=>t(e.element,{severity:"error"===e.severity?"error":"warning",text:e.message})),e},[Z,ee,V]),ei=()=>{let e=I.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},eo=(0,l.useCallback)(e=>{let t=I.current?.getBoundingClientRect();if(!t?.width)return;let n=B(Math.max(H([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})},[]),el=(0,l.useCallback)(e=>{if(J)if("message"===e.kind){let t=J.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);eo({x:n-10,y:t.y-24,width:s+20,height:40})}else{let t=J.participants.find(t=>t.name===e.id);t&&eo({x:t.left-20,y:t.top,width:t.width+40,height:Math.min(260,J.height-t.top)})}},[J,eo]),ec=(0,l.useCallback)(e=>{if("diagram"===O.current)return el(e);requestAnimationFrame(()=>document.getElementById(an(e))?.scrollIntoView({block:"center",behavior:"smooth"}))},[el]),ed=(0,l.useCallback)(e=>{y(e),e&&rM(`${e.kind}:${e.id}`)},[]);(0,l.useEffect)(()=>{if(!h||!J||X.current===i.nonce)return;X.current=i.nonce;let e=i.focus?e9(i.focus):null;if(!e)return;let t=null;if("message"===e.kind&&eN(V??h,e.name)&&(t={kind:"message",id:e.name}),"participant"===e.kind&&(V??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");Y.current=!1,y(t),ec(t)},[h,V,J,i,ec,w]),(0,l.useEffect)(()=>{if(!J||!Y.current||"diagram"!==A)return;let{width:e,height:t}=ei();e&&(Y.current=!1,Math.min((e-32)/J.width,(t-32)/J.height)>=.5||0===J.participants.length?g(e=>(e??0)+1):p({x:8,y:8,scale:.6}))},[J,A]);let eh=(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")}u(t);try{let e=await fetch(`/api/file${(0,s1.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}`);U.current?.emitFull(t),w("saved")}catch(e){return w(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}if(a?.def&&G){if("auto"===eF(a.def)){let{result:e,failed:t,conflicts:s}=await am(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`:ta(e,"auto"),window.dispatchEvent(new CustomEvent(rk,{detail:{text:n,origin:void 0}})))}}al()}}},[h,c,w,a,G]),eu=e=>{let{width:t,height:n}=ei();p(s=>z(s,e,{x:t/2,y:n/2}))},em=()=>{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 ${eq(n.name)}`)}),n=e=>t.get(e)??eq(e).replace(/\W+/g,"_"),s=(e,t,s)=>{let r=e.reply?"-->>":"->>",a=[`${t} ${eq(e.label??"")}`,e.event?eq(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} ${eq(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"} ${eq(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"))},ep=e=>{let t=e?e9(e):null;if(!t||"message"!==t.kind&&"participant"!==t.kind)return;let n={kind:t.kind,id:t.name};ed(n),ec(n),L.close()},ef=V??ek("",""),eg=eS(ef),ey=h&&x?.kind==="message"?eN(ef,x.id):null,eb=h&&x?.kind==="participant"?ef.participants.find(e=>e.name===x.id)??null:null,ev=ef.participants.map(e=>e.name),e$=c.split("/").pop()||"…",eL=Z.length+ee.filter(e=>"error"===e.severity).length,eB=ee.filter(e=>"warning"===e.severity).length,eU=[{id:"participants",label:"Participants",icon:(0,o.jsx)(ae,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,o.jsx)(ae,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,o.jsx)(rx,{}),badge:eL+eB||void 0}],ez=e=>[{name:"from",label:"from",options:ev,initial:e?.from??ev[0]??""},{name:"to",label:"to",options:ev,initial:e?.to??ev[1]??ev[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:e?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:en.events,initial:e?.event??""},{name:"state",label:"state after",suggest:en.states,initial:e?.state??""},{name:"carries",label:"entity it carries",suggest:en.entities,initial:e?.carries??""},{name:"machine",label:"machine",suggest:en.machines,initial:e?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!e?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!e?.reply}],eY=e=>e.actor?"actor":e.object?"object":e.service?"service":"",eH=["main: at the end",...ey&&null===ey.fragment?[`main: after ${ey.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&&E(!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)(ae,{kind:"sequence",size:14}),"SEQ"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:c,children:[h?.settings.name??e$,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",e$]})]}),(0,o.jsx)("div",{className:"flex shrink-0 overflow-hidden rounded border border-gray-700 text-[12px] leading-none",role:"group","aria-label":"View",children:[["list","List","Read the messages in order, one under the other"],["diagram","Diagram","The lifelines and arrows"]].map(([e,t,n])=>(0,o.jsx)("button",{title:n,"aria-pressed":A===e,onClick:()=>{A!==e&&(x&&(Y.current=!1),P(e),x&&requestAnimationFrame(()=>ec(x)))},className:`px-2.5 py-1.5 ${A===e?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:t},e))}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r8,onClick:em,children:"Copy mermaid"}),(0,o.jsx)("button",{className:r8,onClick:()=>_(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ 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(),E(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:()=>{E(!1),em()},children:"Copy as mermaid"})})]})]}),(0,o.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,o.jsxs)("div",{ref:I,className:"relative min-w-0 flex-1 overflow-hidden",children:[h&&J&&"list"===A&&V&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(as,{definition:V,selection:x,issues:ea,onSelect:e=>ed(e),onShowInDiagram:e=>{Y.current=!1,P("diagram"),requestAnimationFrame(()=>el(e))}})}),h&&J&&"diagram"===A&&(0,o.jsx)(rg,{what:"sequence",resetKey:h,children:(0,o.jsx)(tX,{definition:V,layout:J,viewport:m,onViewportChange:p,selection:x,errorElements:es,warningElements:er,fitKey:f,onSelect:(e,t)=>ed({kind:e,id:t}),onClearSelection:()=>y(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),h&&J&&"diagram"===A&&(0,o.jsx)(rX,{docPath:c||null,kind:"sequence",viewport:m,setViewport:p,boxes:W,boardRef:I,focus:K}),h&&J&&"list"===A&&(0,o.jsx)(rV,{docPath:c,onReveal:()=>P("diagram")}),(0,o.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 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"} ${"list"===A&&j&&"ok"===b.tone?"hidden":"flex"}`,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,D>1?` \xb7 ${D} in the room`:""]})]}),(0,o.jsx)("div",{className:`absolute bottom-3 right-3 flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur ${"diagram"===A?"flex":"hidden"}`,children:[["+","Zoom in",()=>eu(1.25)],["−","Zoom out",()=>eu(.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"),M(!0)},children:["Edit ","message"===x.kind?`${x.id}. ${ey?.message.label??""}`:x.id]})]}),S&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),h&&(0,o.jsxs)("aside",{style:L.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 ${R?"md:hidden":""}`,children:[(0,o.jsxs)("div",{className:"md:hidden",...L.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:eU.find(e=>e.id===$)?.label}),(0,o.jsx)("button",{onClick:L.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:eU.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)(rg,{what:"panel",resetKey:h,children:[(0,o.jsxs)("section",{className:"participants"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Participants"}),(0,o.jsx)("div",{className:"flex flex-wrap gap-1",children:ef.participants.map(e=>(0,o.jsxs)("button",{className:`${r8} ${x?.kind==="participant"&&x.id===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ed({kind:"participant",id:e.name}),ec({kind:"participant",id:e.name})},title:eY(e)||"participant",children:[e.name,eY(e)&&(0,o.jsxs)("span",{className:"text-gray-500",children:[" · ",eY(e)]})]},e.name))}),(0,o.jsx)(r9,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:af,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities}],submit:"+ Participant",onSubmit:e=>{let t=ag(e.name),n=ag(e.kind);eh(s=>(function(e,t,n){if(!t.name?.trim())throw Error("A participant needs a name.");let s=eC(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,eE({...t})),s})(s,{name:t,...n?{[n]:ag(e.value)||t}:{},holds:ax(e.holds)})),ed({kind:"participant",id:t})}}),eb&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r7} flex items-center justify-between gap-2`,children:[(0,o.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:eb.name}),(0,o.jsx)("button",{className:`${r8} normal-case tracking-normal`,onClick:()=>ec({kind:"participant",id:eb.name}),children:"◎ Show on board"})]}),(e=ef.participants.findIndex(e=>e.name===eb.name),t=ef.participants.length-1,n=e=>eh(t=>{var n;let s,r;return n=eb.name,r=eR(s=eC(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:`${r8} 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:`${r8} disabled:opacity-40`,disabled:e>=t,onClick:()=>n(e+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,o.jsx)(r9,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:eb.name}],submit:"Rename (every message follows)",onSubmit:e=>{let t=ag(e.to);t!==eb.name&&(eh(e=>(function(e,t,n){if(!n?.trim())throw Error("A participant needs a name.");let s=eC(e),r=eR(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,eb.name,t)),ed({kind:"participant",id:t}))}},`rename:${eb.name}`),(0,o.jsx)(r9,{id:"edit-participant",fields:[{name:"kind",options:af,label:"kind",initial:eY(eb)},{name:"value",placeholder:"actor / service / object",suggest:[...en.actors,...en.objects],initial:eb.actor??eb.object??eb.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:en.entities,initial:(eb.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:eb.description??"",wide:!0}],submit:"Save participant",onSubmit:e=>eh(t=>{let n,s;return eT(t,eb.name,{...(n=ag(e.kind),s=ag(e.value)||eb.name,{actor:"actor"===n?s:"",service:"service"===n?s:"",object:"object"===n?s:""}),holds:ax(e.holds),description:ag(e.description)})})},`p:${JSON.stringify(eb)}`),(0,o.jsxs)("button",{className:`${r8} mt-2 text-red-300`,onClick:()=>{eh(e=>{var t;let n,s;return t=eb.name,eR(n=eC(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),rM(null)},title:"Also removes every message it sends or receives",children:["Delete ",eb.name," and its messages"]})]})]}),(0,o.jsxs)("section",{className:"messages"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Messages"}),0===eg.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:eg.map(({ref:e,message:t,fragment:n},s)=>{let r=null!==n&&(0===s||eg[s-1].fragment!==n),a=null!==n?ef.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:()=>{ed({kind:"message",id:e}),ec({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)})}),ey&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:`${r7} 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===ey.fragment&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("button",{className:r8,"aria-label":"Move up",title:"Move up",disabled:0===ey.index,onClick:()=>{eh(e=>eI(e,ey.index,ey.index-1)),ed({kind:"message",id:String(ey.index)})},children:"↑"}),(0,o.jsx)("button",{className:r8,"aria-label":"Move down",title:"Move down",disabled:ey.index>=ef.messages.length-1,onClick:()=>{eh(e=>eI(e,ey.index,ey.index+1)),ed({kind:"message",id:String(ey.index+2)})},children:"↓"})]}),(0,o.jsx)("button",{className:r8,onClick:()=>ec(x),children:"◎ Show"})]})]}),(0,o.jsx)(r9,{id:"edit-message",required:["label"],fields:[...ez(ey.message),{name:"description",placeholder:"description",initial:ey.message.description??"",wide:!0}],submit:"Save message",onSubmit:e=>eh(t=>eP(t,ey.index,ay(e),ey.fragment))},`m:${x.id}:${JSON.stringify(ey.message)}`),(0,o.jsxs)("button",{className:`${r8} mt-2 text-red-300`,onClick:()=>{eh(e=>(function(e,t,n=null){let s=eC(e);if(null!==n){let e=eA(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,ey.index,ey.fragment)),y(null),rM(null)},children:["Delete message ",x.id]})]}),(0,o.jsx)("div",{className:r7,children:"Add a message"}),(0,o.jsx)(r9,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:eH,label:"where",wide:!0},...ez()],submit:"+ Message",onSubmit:e=>{let t=ag(e.where),n=ay(e),s=/^fragment (\d+):/.exec(t),r=/^main: after (\d+)$/.exec(t);s?eh(e=>{var t;let r,a,i;return t=Number(s[1])-1,a=eA(r=eC(e),t),e_(r,n),i=a.messages.length,a.messages.splice(i,0,eE({...n})),r}):r?eh(e=>eO(e,n,Number(r[1]))):eh(e=>eO(e,n))}},`add:${eH.join("|")}:${ev.join("|")}`),(0,o.jsx)("div",{className:r7,children:"Fragments"}),0===(ef.fragments??[]).length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ef.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:()=>eh(e=>{let n;return eA(n=eC(e),t),n.fragments.splice(t,1),n.fragments.length||delete n.fragments,n}),children:"✕"})]}),(0,o.jsx)(r9,{id:`edit-fragment-${t}`,fields:[{name:"kind",options:ew,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=>eh(n=>(function(e,t,n){let s=eC(e),r=eA(s,t);if(void 0!==n.kind&&!ew.includes(n.kind))throw Error(`A fragment is one of ${ew.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]={...eE({...r,...n,messages:void 0}),messages:r.messages??[]},s})(n,t,{kind:ag(e.kind),after:Number(ag(e.after)),label:ag(e.label)}))})]},`${t}:${JSON.stringify({...e,messages:void 0})}`)),(0,o.jsx)(r9,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:ew},{name:"after",placeholder:"after message",initial:String(ey&&null===ey.fragment?ey.index+1:ef.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:ev,label:"first message from"},{name:"to",options:ev,label:"to",initial:ev[1]??ev[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:e=>eh(t=>(function(e,t){if(!ew.includes(t.kind))throw Error(`A fragment is one of ${ew.join(", ")}; got '${t.kind}'.`);if(!t.label?.trim())throw Error("A fragment needs a label: the condition in words.");let n=eC(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??[])e_(n,e);return(n.fragments??=[]).push({...eE({...t,messages:void 0}),messages:(t.messages??[]).map(e=>eE({...e}))}),n})(t,{kind:ag(e.kind),after:Number(ag(e.after)),label:ag(e.label),messages:ag(e.first)?[{from:ag(e.from),to:ag(e.to),label:ag(e.first)}]:[]}))},`add-fragment:${ef.messages.length}:${ey?.index??""}`)]}),(0,o.jsxs)("section",{className:"notes"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,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)(r4,{label:"On this sequence",value:h.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>eh(t=>{var n;let s;return n={notes:e},(s=eC(t)).settings=eE({...s.settings,...n}),s})},"sequence"),eb&&(0,o.jsx)(r4,{label:`On ${eb.name}`,value:eb.notes??"",placeholder:`A question or a decision about ${eb.name}…`,onSave:e=>eh(t=>eT(t,eb.name,{notes:e}))},`participant:${eb.name}`),ey&&(0,o.jsx)(r4,{label:`On message ${x.id}`,value:ey.message.notes??"",placeholder:"A question or a decision about this message…",onSave:e=>eh(t=>eP(t,ey.index,{notes:e},ey.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."}),[...ef.participants.filter(e=>e.notes?.trim()),...eg.filter(e=>e.message.notes?.trim())].length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"With notes"}),(0,o.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ef.participants.filter(e=>e.notes?.trim()).map(e=>(0,o.jsx)("button",{className:r8,onClick:()=>ep(`participant:${e.name}`),children:e.name},`p${e.name}`)),eg.filter(e=>e.message.notes?.trim()).map(e=>(0,o.jsxs)("button",{className:r8,onClick:()=>ep(`message:${e.ref}`),children:["message ",e.ref]},`m${e.ref}`))]})]})]}),(0,o.jsxs)("section",{className:"issues"===$?"":"hidden",children:[(0,o.jsx)("div",{className:r7,style:{marginTop:0},children:"Issues"}),Z.map((e,t)=>(0,o.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ee.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:()=>ep(e.element),children:["[",e.ruleId,"] ",e.message]},`s${t}`)),0===Z.length&&0===ee.length&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:Q?"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&&!G&&a&&(0,o.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),et&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:r7,children:["Replay against ",et.machines.join(", ")||"no machine"]}),et.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:()=>ep(`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:eU.map(e=>{let t=S&&$===e.id;return(0,o.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===t?L.close():M(!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 av(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 aw=(e,t)=>e?.members.find(e=>e.path===t)?.kind??"machine";function aj(e){return"message"===e.kind?`message ${e.name}`:`${e.kind} ${e.name}`}function ak({systemPath:e}){let t=rN("doc"),n=rN("focus"),{system:s}=ac(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?rJ(()=>te(s.members),[]):[],[s]),u=ad(s,t),m=!!s&&(t===s.path||t===e),p=u&&n?function(e,t,n){let s=e9(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,u,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=e7(e);n.set(s,(n.get(s)??0)+1)}return[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0]))}(h,u);(0,l.useEffect)(()=>{let e=e=>{let t=e.detail;t?.text&&c({...t,at:Date.now()})};return window.addEventListener(rk,e),()=>window.removeEventListener(rk,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 re();if(t&&r){var i;let t,o,l,h;(n=sy({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()});rS({doc:s?n.absOf[s]:g,system:e,focus:t.focus??null}),a(!1);let r=[s?av(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",()=>al()),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&&rS({doc:t.member?s.absOf[t.member]??eJ(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] ${m?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${e} — the system map`,children:[(0,o.jsx)(ae,{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===u,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:`${av(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)(ae,{kind:aw(s,e),size:15}),(0,o.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${t?"":"hidden md:inline"}`,children:av(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:!u,"aria-expanded":r,title:u?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)(ae,{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&&u&&(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&&e9(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:aj(e9(n))})," in ",av(s,u)]}),(0,o.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>rS({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:e7(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)(ae,{kind:aw(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:[aj(e.other)," · ",av(s,e.other.member)," · ",e.rule]})]})]},t))]}):null,(!n||!e9(n))&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",av(s,u)," 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),rS({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 a$={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function aN(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 aS=(e,t)=>e<t?`${e}\u0000${t}`:`${t}\u0000${e}`;function aM(e){let t="message"===e.from.kind?`message ${e.from.name}`:`${e.from.kind} ${e.from.name}`;return`${t} ${e.text}`}function aC(){let e=(0,s1.useRequestedDoc)(),[t,n]=(0,l.useState)(e);(0,l.useEffect)(()=>{let t=!0;return e?n(e):r$("doc")||ar(null).then(e=>t&&n(e.path||null)),()=>{t=!1}},[e]);let{system:s,reload:r}=ac(t),[a,i]=(0,l.useState)("members"),[c,d]=(0,l.useState)(!1),[h,u]=(0,l.useState)(!1),[m,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=rb({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[M,C]=(0,l.useState)(!1);(0,l.useEffect)(()=>{let e=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(e),C(!1)}},[x]);let E=(0,l.useMemo)(()=>s?.def?rJ(()=>e8(s.def,s.members),null):null,[s]),R=(0,l.useMemo)(()=>s?rJ(()=>te(s.members),[]):[],[s]),_=(0,l.useMemo)(()=>s?.def?rJ(()=>tr(s.def,s.members),null):null,[s]),A=eF(s?.def),T=(0,l.useMemo)(()=>{let e=new Map;for(let t of R){if(t.from.member===t.to.member)continue;let n=aS(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},[R]),O=(E?.issues??[]).filter(e=>"error"===e.severity),P=(E?.issues??[]).filter(e=>"warning"===e.severity),I=(t,n)=>{s&&rS({doc:s.absOf[t]??t,system:e??s.path,focus:n??null})},L=async(e,t)=>{if(s)try{await ai(s.path,e,s.mtimes[s.path]),b(t),al()}catch(e){e instanceof aa?(b("the system changed on disk — reloaded; make the change again","warn"),al()):b(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}},D=async()=>{if(!s||!_||!_.count)return;w(!0);let{result:e,written:t,failed:n,conflicts:r}=await am(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(`${ta(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)??[],U=s?.def?.actors??[],z=64*!!U.length,Y=(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,$]),H=(0,l.useMemo)(()=>{let e=new Map;for(let{member:t,def:n}of e6(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]),X=s?.def,V=(s?.path??t??"").split("/").pop()||"…",J=[{id:"members",label:"Members",icon:(0,o.jsx)(ae,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,o.jsx)(rx,{}),badge:O.length+P.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],W=f?T.get(f):void 0,K=(0,l.useMemo)(()=>{let e=[];for(let t of["error","warning"]){let n=new Map;for(let e of E?.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},[E]);return(0,o.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>h&&u(!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)(ae,{kind:"system",size:14}),"SYS"]}),(0,o.jsx)(s2,{}),(0,o.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:s?.path,children:[X?.settings?.name??V,(0,o.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,o.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,o.jsx)("button",{className:r8,onClick:r,title:"Read the system and every member again",children:"Re-check"}),(0,o.jsx)("button",{className:r8,onClick:()=>p(e=>!e),"aria-pressed":!m,children:m?"⟨ 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(),u(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:()=>{u(!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&&X&&(0,o.jsx)(rg,{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 ${X.settings?.name}`,children:[[...T.entries()].map(([e,t])=>{let n=Y.get(t.a),s=Y.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)}),U.map((e,t)=>{let n=(t+1)*q/(U.length+1),s=B-30;return(0,o.jsxs)("g",{children:[(H.get(e.name)??[]).map(e=>{let t=Y.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)(ae,{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=Y.get(e),n=s.members.find(t=>t.path===e);if(!t||!n)return null;let r=n.kind,a=(E?.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=av(s,e),u=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}`:""}
14
- 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":u?"#3b82f6":i?"#b91c1c":"#475569",strokeWidth:u?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)(ae,{kind:r,size:16})}),(0,o.jsx)("text",{x:c+32,y:d+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:a$[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":aN(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&&!X&&(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 ${M&&"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&&X&&(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 ${m?"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:J.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:J.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:r7,style:{marginTop:0},children:"Members"}),F.map(e=>{let t=s.members.find(t=>t.path===e),n=X.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)(ae,{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:av(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}`:aN(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)(r4,{label:"Note on this member, in the system",value:n??"",placeholder:`Why ${av(s,e)} is part of this system, what is open…`,onSave:t=>void L(function(e,t,n){let s=eK(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]=eZ({...s.members[r],...n}),s}(X,e,{notes:t}),"saved")},`member:${e}`)})]},e)}),(0,o.jsx)("div",{className:r7,children:"Links between members"}),0===T.size&&(0,o.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...T.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:[av(s,t.a)," ↔ ",av(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:`${aM(e)} — ${e.rule}`,onClick:()=>{let t;return I((t=e.from).member,e7(t))},children:[(0,o.jsx)("span",{className:"text-gray-600",children:e.rule})," ",aM(e)]},t))})]},e)),U.length>0&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"Actors"}),U.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:r7,style:{marginTop:0},children:"Checks"}),(0,o.jsxs)("div",{className:`text-[11px] ${O.length?"text-red-300":P.length?"text-amber-300":"text-green-400"}`,children:[O.length," error",1===O.length?"":"s"," · ",P.length," warning",1===P.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:[" — ",av(s,e.member)]})]},t))]},e.key)),(0,o.jsx)("div",{className:r7,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:eB.map(e=>(0,o.jsx)("button",{"aria-pressed":A===e,onClick:()=>{s?.def&&e!==A&&L(function(e,t){if(!eB.includes(t))throw Error(`The reconcile mode is ${eB.join(" or ")}; got '${t}'.`);return eG(e,{reconcile:t})}(s.def,e),`reconcile mode: ${e}`)},className:`px-3 py-1 text-xs ${A===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"}),_&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-500",children:ta(_,"propose")}),_.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)),_.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)),_.system&&(0,o.jsxs)("div",{className:"mt-1",children:[(0,o.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),_.system.reasons.map((e,t)=>(0,o.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]}),_.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:`${r8} mt-2 disabled:opacity-40`,disabled:!_.count||v,onClick:D,children:v?"Applying…":`Apply${_.count?` ${_.count} change${1===_.count?"":"s"}`:""}`})]}),(E?.replays??[]).map(({member:e,report:t})=>(0,o.jsxs)("div",{children:[(0,o.jsxs)("div",{className:r7,children:["Replay · ",av(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:r7,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)(r4,{label:"On this system",value:X.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:e=>void L(eG(X,{notes:e}),"saved")},"system"),X.settings?.description&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:r7,children:"Description"}),(0,o.jsx)("p",{className:"text-[11px] text-gray-400",children:X.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:J.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)})})]})}function aE(){let e=sP(e=>e.definition),t=sP(e=>e.layout.positions),n=sP(e=>e.navigationPath),s=sP(e=>e.viewport),r=sP(e=>e.setViewport),a=sP(e=>e.docPath),i=rN("focus"),c=(0,l.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),d=n.slice(1),h=(0,l.useMemo)(()=>e?.state?function(e,t){let n=[];for(let s of e){let e=s?.name?t[s.name]:void 0;e&&n.push({focus:`state:${s.name}`,box:e})}for(let s of e){let r=s?.name?t[s.name]:void 0;if(r)for(let a of s.transitions??[]){if(!a?.event)continue;let s=a.nextState?t[a.nextState]:void 0;n.push({focus:`event:${a.event}`,box:s&&e.some(e=>e.name===a.nextState)?tx([r,s]):r})}}return n}(t$(e.state,d),t):[],[e,t,n]);return(0,o.jsx)(rX,{docPath:a,kind:"machine",viewport:s,setViewport:r,boxes:h,boardRef:c,focus:i,level:n[n.length-1],onReveal:e=>{let t=e.map(e9).find(e=>e?.kind==="state");if(!t)return;let n=new URL(window.location.href);n.searchParams.set("focus",`state:${t.name}`),window.history.replaceState(window.history.state,"",n),window.dispatchEvent(new Event(rw))}})}let aR=e=>e.parallel?e.parallel.states:e.states??[];function a_(e,t){if(!e)return null;if(e.name===t)return[e.name];for(let n of aR(e)){let s=a_(n,t);if(s)return[e.name,...s]}return null}function aA(){let e=(0,s1.useRequestedDoc)(),t=rN("system"),[n,s]=(0,l.useState)(null);(0,l.useEffect)(()=>{let e=!0;return re().then(t=>{e&&s(t.projectFile?eH(t.projectFile):"machine")}),()=>{e=!1}},[]);let r=e?eH(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)(r5,{},a):"sequence"===r?(0,o.jsx)(ab,{},a):"system"===r?(0,o.jsx)(aC,{},a):(0,o.jsx)(aT,{}),c=(0,o.jsx)(rg,{what:"document",resetKey:e,children:i});return t&&ez(t)?(0,o.jsx)(rz,{children:(0,o.jsxs)("div",{className:"system-frame",children:[(0,o.jsx)(ak,{systemPath:t}),c]})}):(0,o.jsx)(rz,{children:c})}function aT(){var e,t;let n,s,r,a;n=rC(),s=(0,l.useRef)(null),(0,l.useEffect)(()=>{let e=()=>{let e=s.current;if(!e)return;let t=sP.getState(),n=r$("doc");if(n&&t.docPath!==n||e.docAt!==t.docPath&&t.definition===e.defAt)return;s.current=null;let r=e9(e.focus);if(!r)return;let a=null,i=null;if("state"===r.kind)(a=a_(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 aR(t)){let t=e(s,n);if(t)return t}return null}(t.definition.state,r.name);e&&(a=a_(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;sP.setState({navigationPath:o,currentParent:o[o.length-1]}),t.select(i.kind,i.id);let l=()=>{let e=sP.getState().layout.positions[a[a.length-1]],t=document.getElementById(sq)?.getBoundingClientRect();if(!e||!t?.width)return;let n=H([e],t.width,t.height,{padding:60,maxScale:1});sP.getState().setViewport(n)};requestAnimationFrame(l),setTimeout(l,450)};if(n.nonce>0){let t=sP.getState();s.current=n.focus?{focus:n.focus,docAt:t.docPath,defAt:t.definition}:null,e()}return sP.subscribe(e)},[n]),(0,l.useEffect)(()=>sP.subscribe((e,t)=>{if(e.selection===t.selection||!e.selection.id)return;let{kind:n,id:s}=e.selection;if("state"===n)rM(`state:${s}`);else if("event"===n)rM(`event:${s}`);else if("transition"===n){let t=function(e,t){let n=t.lastIndexOf(":"),s=a_(e.state,t.slice(0,n));if(!s)return null;let r=e.state;for(let e of s.slice(1))r=aR(r).find(t=>t.name===e);return r?.transitions?.[Number(t.slice(n+1))]?.event??null}(e.definition,s);t&&rM(`event:${t}`)}}),[]);let[i,c]=(0,l.useState)("properties"),[d,h]=(0,l.useState)(!1),u=rb({onClose:()=>h(!1),restVh:70,tallVh:92}),m=sP(e=>e.errors),p=sP(e=>e.contextMenu),f=sP(e=>e.hideContextMenu),g=sP(e=>e.addState),x=sP(e=>e.removeState),y=sP(e=>e.setDrawMode),b=sP(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)(rx,{}),badge:m.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)(rt,{}),(0,o.jsx)(rp,{}),(0,o.jsx)(s4,{}),(0,o.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,o.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,o.jsx)(rg,{what:"state machine",children:(0,o.jsx)(sJ,{})}),(0,o.jsx)(aE,{})]}),d&&(0,o.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:u.close,"aria-hidden":"true"}),(0,o.jsxs)("aside",{style:u.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",...u.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:u.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)(sK,{}),"events"===i&&(0,o.jsx)(sG,{}),"settings"===i&&(0,o.jsx)(sQ,{}),"validation"===i&&(0,o.jsx)(s0,{})]})]}),(0,o.jsx)(s3,{})]}),(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?u.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",()=>aA],63052)}]);