@miadi/stateloom-web 0.3.3 → 0.3.4

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 (78) hide show
  1. package/package.json +1 -1
  2. package/server/.next/BUILD_ID +1 -1
  3. package/server/.next/build-manifest.json +5 -5
  4. package/server/.next/server/app/_global-error/page/build-manifest.json +3 -3
  5. package/server/.next/server/app/_global-error/page.js.nft.json +1 -1
  6. package/server/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/server/.next/server/app/_global-error.html +2 -2
  8. package/server/.next/server/app/_global-error.rsc +1 -1
  9. package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  10. package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  12. package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  13. package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/server/.next/server/app/_not-found/page/build-manifest.json +3 -3
  15. package/server/.next/server/app/_not-found/page.js.nft.json +1 -1
  16. package/server/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/server/.next/server/app/_not-found.html +1 -1
  18. package/server/.next/server/app/_not-found.rsc +2 -2
  19. package/server/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  20. package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/server/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  22. package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  23. package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  24. package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  25. package/server/.next/server/app/api/docs/route.js.nft.json +1 -1
  26. package/server/.next/server/app/api/file/route.js.nft.json +1 -1
  27. package/server/.next/server/app/api/marks/route.js.nft.json +1 -1
  28. package/server/.next/server/app/api/rispec/route.js.nft.json +1 -1
  29. package/server/.next/server/app/api/watch/route.js.nft.json +1 -1
  30. package/server/.next/server/app/index.html +1 -1
  31. package/server/.next/server/app/index.rsc +3 -3
  32. package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  33. package/server/.next/server/app/index.segments/_full.segment.rsc +3 -3
  34. package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  35. package/server/.next/server/app/index.segments/_index.segment.rsc +2 -2
  36. package/server/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  37. package/server/.next/server/app/page/build-manifest.json +3 -3
  38. package/server/.next/server/app/page.js.nft.json +1 -1
  39. package/server/.next/server/app/page_client-reference-manifest.js +1 -1
  40. package/server/.next/server/chunks/ssr/{2374f_next_dist_0c464f98._.js → 2374f_next_dist_491bc9ca._.js} +2 -2
  41. package/server/.next/server/chunks/ssr/{[root-of-the-server]__385c85a7._.js → [root-of-the-server]__0d719a8a._.js} +2 -2
  42. package/server/.next/server/chunks/ssr/[root-of-the-server]__199d50b6._.js +3 -0
  43. package/server/.next/server/chunks/ssr/[root-of-the-server]__5c28bab6._.js +3 -0
  44. package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +6 -6
  45. package/server/.next/server/middleware-build-manifest.js +3 -3
  46. package/server/.next/server/pages/404.html +1 -1
  47. package/server/.next/server/pages/500.html +2 -2
  48. package/server/.next/static/chunks/33df24ad2d3a04e7.js +1 -0
  49. package/server/.next/static/chunks/6052c4bfdd66ef5c.css +2 -0
  50. package/server/.next/static/chunks/b0af2862e9bb3e18.js +14 -0
  51. package/server/.next/static/chunks/b71bf89a3bbb72e1.js +5 -0
  52. package/server/.next/static/chunks/{turbopack-b3cae9131ae5086f.js → turbopack-3a774f5a5a8a9023.js} +1 -1
  53. package/server/package-lock.json +2 -2
  54. package/server/package.json +1 -1
  55. package/server/src/app/globals.css +40 -2
  56. package/server/src/app/page.tsx +8 -6
  57. package/server/src/components/ChromeIcon.tsx +106 -0
  58. package/server/src/components/PropertiesPanel.tsx +3 -2
  59. package/server/src/components/Toolbar.tsx +37 -20
  60. package/server/src/components/erd/ErdWorkspace.tsx +2 -1
  61. package/server/src/components/sequence/SequenceWorkspace.tsx +10 -1
  62. package/server/src/components/stage/CompanionLayer.tsx +41 -6
  63. package/server/src/components/stage/StageLayer.tsx +206 -23
  64. package/server/src/components/stage/StageProvider.tsx +146 -25
  65. package/server/src/components/system/SystemWorkspace.tsx +26 -12
  66. package/server/src/lib/markRequest.ts +24 -0
  67. package/server/src/lib/useNarrow.ts +30 -0
  68. package/server/stateloom-web.json +2 -2
  69. package/server/tsconfig.tsbuildinfo +1 -1
  70. package/server/.next/server/chunks/ssr/[root-of-the-server]__a593e8b6._.js +0 -3
  71. package/server/.next/server/chunks/ssr/[root-of-the-server]__f25b51be._.js +0 -3
  72. package/server/.next/static/chunks/59a1ec89a1dc7e34.js +0 -14
  73. package/server/.next/static/chunks/662d1b0ce457c16b.js +0 -1
  74. package/server/.next/static/chunks/8f45e56f40c207bf.css +0 -2
  75. package/server/.next/static/chunks/96818f5620f039a1.js +0 -5
  76. /package/server/.next/static/{CZ4wRF1efsHnxjkcKHITP → ZoijkpoWD861NG-cIGJrO}/_buildManifest.js +0 -0
  77. /package/server/.next/static/{CZ4wRF1efsHnxjkcKHITP → ZoijkpoWD861NG-cIGJrO}/_clientMiddlewareManifest.json +0 -0
  78. /package/server/.next/static/{CZ4wRF1efsHnxjkcKHITP → ZoijkpoWD861NG-cIGJrO}/_ssgManifest.js +0 -0
@@ -0,0 +1,14 @@
1
+ (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,63052,e=>{"use strict";let t,n,s,a;var r,i,l=e.i(14294),o=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"),a=d(n.state,e.child);if(!a||!a.states)throw Error(`applyPatchOps: state.nest cannot detach root or missing state "${e.child}"`);let r=a.states.findIndex(t=>t.name===e.child),[i]=a.states.splice(r,1);0===a.states.length&&delete a.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:[]}),a=e.index??s.actions.length;s.actions.splice(a,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,a){let r=Math.min(n.length,s.length);for(let i=0;i<r;i++)g(n[i],s[i])||a.push({op:"action.update",state:e,hook:t,index:i,action:s[i]});for(let n=r;n<s.length;n++)a.push({op:"action.add",state:e,hook:t,action:s[n],index:n});for(let r=n.length-1;r>=s.length;r--)a.push({op:"action.remove",state:e,hook:t,index:r})}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 w={hSpacing:220,vSpacing:140,nodeWidth:160,nodeHeight:60,compositeWidth:300,compositeHeight:200,originX:100,originY:120,sweeps:2,includeRoot:!0},v=(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={...w,...t},s="state"in e?e.state:e,a={};if(!s)return a;if(!function e(t,n,s,a,r){let i=j(t);if(0===i.length)return;let l=i.map(e=>e.name),o=new Map(i.map(e=>[e.name,e])),c=function(e){let t=new Set,n=[];for(let s of e)for(let a of s.transitions??[]){let r=a.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,a.nextState):void 0;if(!r||r===s.name)continue;let i=v(s.name,r);t.has(i)||(t.add(i),n.push({from:s.name,to:r}))}return n}(i),d=function(e,t){let n=k(e,t),s=new Map(e.map(e=>[e,0])),a=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],r=n.get(t.node);if(t.i<r.length){let n=r[t.i++],i=s.get(n);1===i?a.add(v(t.node,n)):0===i&&(s.set(n,1),e.push({node:n,i:0}))}else s.set(t.node,2),e.pop()}}return a}(l,c),h=c.filter(e=>!d.has(v(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 a=new Map(e.map(e=>[e,0])),r=e.filter(e=>0===s.get(e));for(let e=0;e<r.length;e++){let t=r[e];for(let e of n.get(t)){a.set(e,Math.max(a.get(e),a.get(t)+1));let n=s.get(e)-1;s.set(e,n),0===n&&r.push(e)}}return a}(l,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 a=new Set([n]),r=[n];for(;r.length>0;){let e=r.pop();for(let t of s.get(e)??[])a.has(t)||(a.add(t),r.push(t))}return a}(l,c,l[0]),p=0;for(let e of l)m.has(e)&&(p=Math.max(p,u.get(e)));for(let e of l)m.has(e)||u.set(e,u.get(e)+p+1);let f=Array.from({length:Math.max(...l.map(e=>u.get(e)))+1},()=>[]);for(let e of l)f[u.get(e)].push(e);!function(e,t,n){let s=new Map,a=new Map,r=(e,t,n)=>{let s=e.get(t);s?s.push(n):e.set(t,[n])};for(let e of t)r(s,e.to,e.from),r(a,e.from,e.to);let i=new Map,l=()=>{e.forEach(e=>e.forEach((e,t)=>i.set(e,t)))};l();let o=(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++)o(e[t],s),l();for(let t=e.length-2;t>=0;t--)o(e[t],a),l()}}(f,h,a.sweeps);let g=a.hSpacing-a.nodeWidth,x=a.vSpacing-a.nodeHeight,y=e=>Math.max(a.hSpacing,e+g),b=new Map(l.map(e=>{var t;return[e,(t=o.get(e),(t.states?.length??0)>0?{width:a.compositeWidth,height:a.compositeHeight}:{width:a.nodeWidth,height:a.nodeHeight})]})),w=f.map(e=>e.reduce((e,t)=>e+y(b.get(t).width),0)),$=n+Math.max(...w,0)/2,N=s;for(let t of(f.forEach((e,t)=>{let n=$-w[t]/2,s=a.nodeHeight;for(let t of e){let e=b.get(t),a=y(e.width);r[t]={x:Math.round(n+(a-e.width)/2),y:Math.round(N),width:e.width,height:e.height},n+=a,s=Math.max(s,e.height)}N+=s+x}),i)){if((t.states?.length??0)===0)continue;let n=r[t.name];e(t,n.x+20,n.y+40,a,r)}}(s,n.originX,n.originY,n,a),n.includeRoot){let e=j(s).map(e=>a[e.name]).filter(Boolean);if(0===e.length)a[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)),r=Math.max(...e.map(e=>e.x+e.width)),i=Math.max(...e.map(e=>e.y+e.height));a[s.name]={x:Math.round(t-40),y:Math.round(n-40),width:Math.round(r-t+80),height:Math.round(i-n+80)}}}return a}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 A(e,t,n={}){let{along:s,aside:a,across:r}={...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),l=[];for(let{label:e}of i){let{width:n,height:i}=M(e),o=8*!!e.glyph,c=null,d=1/0;e:for(let h of r)for(let r of a)for(let a of s){let s=e.at(a),u=s.x+r*n,m=s.y+h*i,p={x:u-n/2,y:m-18,width:n,height:i},f=[...l,...t].filter(e=>E(p,e)).length,g={...p,cx:u+o,cy:m,label:e};if(0===f){c=g;break e}f<d&&(d=f,c=g)}c&&l.push(c)}return l}let O=(e,t,n=2.2,s)=>({id:e,paths:t,strokeWidth:n,circles:s}),_=O("signal",["M3 12h10","m13 6 6 6-6 6Z"]),T=[{glyph:O("confirm",["m4 13 5.5 5.5L20 6"],2.4),words:["confirm","approve","accept","commit"]},{glyph:O("complete",["m8 12 3 3 5-6"],2.2,[{cx:12,cy:12,r:8.5}]),words:["complete","finish","done","close"]},{glyph:O("skip",["M4 17c0-6 4.5-9 9-9h6","m15 4 4.5 4-4.5 4"]),words:["skip","ignore","bypass"]},{glyph:O("flag",["M6 21V4","M6 4h12l-3 4.5 3 4.5H6Z"]),words:["flag","mark","revisit","review"]},{glyph:O("advance",["M4 6l8 6-8 6Z","M13 6l7 6-7 6Z"]),words:["advance","next","forward","step"]},{glyph:O("pause",["M9 5v14M15 5v14"],2.6),words:["pause","hold","suspend","stop"]},{glyph:O("play",["M7 4.5 19 12 7 19.5Z"]),words:["resume","start","begin","play","run"]},{glyph:O("clock",["M12 7.5V12l3.5 2.5"],2.2,[{cx:12,cy:12,r:8.5}]),words:["timeout","expire","tick","delay","after","elapse"]},{glyph:O("change",["M3 14c3-6 6-6 9 0s6 6 9 0"]),words:["change","update","edit","modify","set"]}];[...T.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:a=>{let r=1-a,i=r*r*r,l=3*r*r*a,o=3*r*a*a,c=a*a*a;return{x:i*e.x+l*t.x+o*n.x+c*s.x,y:i*e.y+l*t.y+o*n.y+c*s.y}}}}function L(e,t){let n=e.map(({from:e,to:n})=>{var s,a;return e===n?null:(s=t(e),(a=t(n)).y>=s.y+s.height?["bottom","top"]:a.y+a.height<=s.y?["top","bottom"]:a.x>=s.x+s.width?["right","left"]:a.x+a.width<=s.x?["left","right"]:["bottom","top"])}),s=new Map,a=(e,t,n)=>{let a=`${e}\0${t}`,r=s.get(a);r?r.push(n):s.set(a,[n])},r=(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[l,o]=i;a(e.from,l,{edge:s,toward:r(t(e.to),l),role:"out"}),a(e.to,o,{edge:s,toward:r(t(e.from),o),role:"in"})});let i=new Map;for(let[e,n]of s){let[s,a]=e.split("\0"),r=t(s),l=[...n].sort((e,t)=>e.toward===t.toward?e.edge-t.edge:e.toward-t.toward);l.forEach((e,t)=>{i.set(`${e.edge}\0${e.role}`,function(e,t,n,s){let a="top"===t||"bottom"===t,r=a?e.width:e.height,i=a?e.x+e.width/2:e.y+e.height/2,l=s>1?Math.min(.72*r,40*(s-1)):0,o=s>1?i-l/2+l*n/(s-1):i;return"top"===t?{x:o,y:e.y}:"bottom"===t?{x:o,y:e.y+e.height}:"left"===t?{x:e.x,y:o}:{x:e.x+e.width,y:o}}(r,a,t,l.length))})}return e.map((e,s)=>{let a=n[s];if(!a){var r;let n,s,a;return n=(r=t(e.from)).x+r.width,s=r.y+.35*r.height,I({x:n,y:s},{x:n+44,y:s-12},{x:n+44,y:(a=r.y+.65*r.height)+12},{x:n,y:a})}let l=i.get(`${s}\0out`),o=i.get(`${s}\0in`);var c=a[0];if("top"===c||"bottom"===c){let e=(l.y+o.y)/2;return I(l,{x:l.x,y:e},{x:o.x,y:e},o)}let d=(l.x+o.x)/2;return I(l,{x:d,y:l.y},{x:d,y:o.y},o)})}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 z(e,t,n){return{x:e.x+t,y:e.y+n,scale:e.scale}}function U(e,t,n,s=D){return Y(e,e.scale*t,n,s)}function Y(e,t,n,s=D){let a=B(t,s);if(a===e.scale)return e;let r=F(e,n);return{x:n.x-r.x*a,y:n.y-r.y*a,scale:a}}function H(e,t,n,s={}){let a=s.padding??48,r=s.maxScale??1,i=s.limits??D;if(0===e.length||t<=0||n<=0)return{...q};let l=1/0,o=1/0,c=-1/0,d=-1/0;for(let t of e)l=Math.min(l,t.x),o=Math.min(o,t.y),c=Math.max(c,t.x+t.width),d=Math.max(d,t.y+t.height);let h=Math.max(1,c-l),u=Math.max(1,d-o),m=B(Math.min(r,Math.min(Math.max(1,t-2*a)/h,Math.max(1,n-2*a)/u)),i);return{x:(t-h*m)/2-l*m,y:(n-u*m)/2-o*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[a,r]of(e.entities??[]).entries()){if(!r?.name){t.push({ruleId:"E001",message:`Entity at index ${a} has no name`,element:`entities[${a}]`});continue}s.has(r.name)&&t.push({ruleId:"E001",message:`Duplicate entity name "${r.name}"`,element:r.name}),s.add(r.name);let e=new Set;for(let[s,a]of(r.attributes??[]).entries()){if(!a?.name){t.push({ruleId:"E002",message:`Attribute at index ${s} of "${r.name}" has no name`,element:`${r.name}[${s}]`});continue}let i=`${r.name}.${a.name}`;if(e.has(a.name)&&t.push({ruleId:"E002",message:`Duplicate attribute "${i}"`,element:i}),e.add(a.name),a.references){let e=function(e){let t=e.indexOf(".");return t<0?{entity:e}:{entity:e.slice(0,t),attribute:e.slice(t+1)}}(a.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 "${a.references}"`,element:i}):t.push({ruleId:"E005",message:`"${i}" references undefined entity "${e.entity}"`,element:i})}}}for(let[s,a]of(e.relationships??[]).entries()){let e=`relationships[${s}]`;for(let r of["from","to"]){let i=a?.[r];i&&n.has(i)||t.push({ruleId:"E003",message:`Relationship ${s} ${r} names undefined entity "${i??""}"`,element:e})}W.includes(a?.cardinality)||t.push({ruleId:"E004",message:`Relationship ${s} cardinality "${a?.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 a=e.settings?.name??"",r=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):[],l=i.flatMap(e=>(e.transitions??[]).map(e=>e.condition??"")),o=new Map;for(let e of r){let a=s.get(e.class);if(a){o.set(e.instance,a);continue}l.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,a]of o)for(let r of G(t.condition,s))(a.attributes??[]).some(e=>e?.name===r)||n.push({ruleId:"L002",message:`Guard on ${e.name} [${t.event}] reads "${s}.${r}", which is not an attribute of "${a.name}"`,element:e.name});if(a){let e=new Set([...o.values()].map(e=>e.name));for(let s of t.entities??[])for(let t of s?.attributes??[])t&&J(t).includes(a)&&(e.has(s.name)||n.push({ruleId:"L003",message:`"${s.name}.${t.name}" stores the state of "${a}", 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 a of J(e))t.includes(a)||n.push({ruleId:"L004",message:`"${s.name}.${e.name}" stores the state of "${a}", 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 ea(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 er(e,t,n){let s=et(e),a=en(s,t);return void 0!==n.notes&&(n.notes.trim()?a.notes=n.notes:delete a.notes),void 0!==n.description&&(n.description?a.description=n.description:delete a.description),void 0!==n.weak&&(n.weak?a.weak=!0:delete a.weak),s}let ei=e=>(e.attributes??[]).filter(e=>e?.name);function el(e){return Math.max(110,Math.ceil(8.4*(e.name??"").length+36))}function eo(e){return Math.max(38,Math.ceil(3.5*Math.max(0,...e.map(e=>e.name.length))+14))}let ec=e=>Math.ceil(e/2);function ed(e){let t=ei(e),n=el(e);return 0===t.length?{width:n,height:40}:{width:n+2*(34+2*eo(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 a=(s??e)[t],r=n(a);r!==a&&((s??={...e})[t]=r)}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 ew(e){return e.trim().replace(/[\s_]+/g,"-").replace(/[^A-Za-z0-9.-]/g,"").replace(/-{2,}/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,60)}let ev=["alt","opt","loop"];function 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,a=Number(n[2])-1,r=e.fragments?.[s]?.messages?.[a];return r?{fragment:s,index:a,message:r}: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,a]of(e.participants??[]).entries()){if(!a?.name){t.push({ruleId:"S002",message:`Participant at index ${s} has no name`,element:`participants[${s}]`});continue}n.has(a.name)&&t.push({ruleId:"S002",message:`Duplicate participant "${a.name}"`,element:a.name}),n.add(a.name)}let s=(e,s)=>{if(!e)return void t.push({ruleId:"S003",message:`Message ${s} is empty`,element:`message:${s}`});for(let a of["from","to"])e[a]&&n.has(e[a])||t.push({ruleId:"S003",message:`Message ${s} ${"from"===a?"comes from":"goes to"} "${e[a]??""}", 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 a=(e.messages??[]).length;for(let[n,r]of(e.fragments??[]).entries()){let e=`fragment:${n+1}`;if(!r||!ev.includes(r.kind)){t.push({ruleId:"S005",message:`Fragment ${n+1} has kind "${r?.kind??""}"; expected one of ${ev.join(", ")}`,element:e});continue}(!Number.isInteger(r.after)||r.after<0||r.after>a)&&t.push({ruleId:"S005",message:`Fragment ${n+1} branches after message ${r.after}, but the main sequence has messages 1 to ${a}`,element:e}),r.messages?.length||t.push({ruleId:"S006",message:`Fragment ${n+1} (${r.kind}) holds no message`,element:e}),(r.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 eA(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 eO(e,t){let n=e.fragments?.[t];if(n&&!Array.isArray(n.messages)&&(n.messages=[]),!n)throw Error(`Fragment ${t+1} not found. The sequence has ${e.fragments?.length??0} fragment(s).`);return n}function e_(e,t,n){let s=eC(e),a=eR(s,t),r=eE({...a,...n});return s.participants[s.participants.indexOf(a)]=r,s}function eT(e,t,n){let s=eC(e);eA(s,t);let a=void 0===n?s.messages.length:Math.max(0,Math.min(n,s.messages.length));if(s.messages.splice(a,0,eE({...t})),s.fragments)for(let e of s.fragments)e.after>a&&(e.after+=1);return s}function eP(e,t,n,s=null){let a=eC(e),r=null===s?a.messages:eO(a,s).messages,i=r[t];if(!i)throw Error(`Message ${t+1} not found${null===s?"":` in fragment ${s+1}`}.`);let l=eE({...i,...n});return eA(a,l),r[t]=l,a}function eI(e,t,n){let s=eC(e);if(!s.messages[t])throw Error(`Message ${t+1} not found.`);let a=Math.max(0,Math.min(n,s.messages.length-1)),r=(s.fragments??[]).map(e=>e.after>0?s.messages[e.after-1]:null),[i]=s.messages.splice(t,1);return s.messages.splice(a,0,i),(s.fragments??[]).forEach((e,t)=>{let n=r[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:""})),a=(Array.isArray(e.messages)?e.messages:[]).filter(e=>!!e&&"object"==typeof e),r=e=>Math.max(90,N(e,n.fontSize)+28),i=[],l=n.margin;s.forEach((t,o)=>{let c=r(t.name);if(0===o)i.push(l+c/2);else{let l=r(s[o-1].name),d=function(e,t,n,s,a){let r=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)&&(r=Math.max(r,N("string"==typeof i.label?i.label:"",a)+30));return r}(a,e,s[o-1].name,t.name,n.fontSize),h=Math.max(n.columnGap,(l+c)/2+20,d+24);i.push(i[o-1]+h)}});let o=new Map(s.map((e,t)=>[e.name,i[t]])),c=s.map((e,t)=>{let s=r(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,a,r)=>{let i=o.get(s)??n.margin,l=o.get(a)??n.margin,c=s===a;c&&(u=Math.max(u,i+44+N("string"==typeof r?r:"",n.fontSize))),d.push({ref:e$(e,t),fragment:e,index:t,y:h,fromX:i,toX:l,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]+r(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 a=h-s+n.fragmentPad/2-n.rowHeight/2;g.push({index:t,left:p,top:s,width:f-p,height:a,headingY:s+16}),h=s+a+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 ez=["person","agent","service","external"];function eU(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":eU(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,a=e1(t),r=t.map((e,t)=>(function(e,t,n){let s=new Map,a=new Map,r=(e,t)=>{if(e?.name){for(let n of(s.has(e.name)||(s.set(e.name,e),a.set(e.name,t)),e.states??[]))r(n,e.name);for(let t of e.parallel?.states??[])r(t,e.name)}};e.state&&r(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 l={name:n,def:e,states:s,parent:a,events:i,initial:null};return l.initial=e.state?e2(l,e.state.name):null,l})(e,0,a[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 a=(e.messages??[]).map((e,n)=>({ref:e$(t,n),message:e})),r=Math.max(0,Math.min(e.after??0,n.length)),i=n.slice(0,r),l=n.slice(r),o=`${e.kind} ${t+1} \xb7 ${e.label??""}`.trim();"alt"===e.kind?s.push({name:o,kind:"alt",fragment:t,items:[...i,...a]}):"opt"===e.kind?s.push({name:o,kind:"opt",fragment:t,items:[...i,...a,...l]}):"loop"===e.kind&&s.push({name:o,kind:"loop",fragment:t,items:[...i,...a,...a,...l]})}),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=[],a=new Map;for(let e of t){let t=e0(e.def);a.set(t,a.has(t)?null:e),e.name!==t&&a.set(e.name,e)}for(let{ref:r,message:i}of e.items){if(!i)continue;let e=i.label??"";if(!i.event){let a={ref:r,label:e,from:[],to:[],result:"data"};i.state&&function(e,t,n,s){let a=n.filter(e=>t.machine?e.name===t.machine:e.states.has(t.state));if(!a.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 a){let a=s.get(n.name),r=a.states.filter(e=>e5(n,e,t.state));if(r.length){a.states=r;continue}e.machine=n.name,e.from=e.to=[...a.states],e.result="state-mismatch",e.note=`the scenario says ${n.name} is in ${t.state}; the walk has it in ${a.states.join(" or ")||"no state"}`;return}}(a,i,t,n),s.push(a);continue}let l=i.event,o=t.filter(e=>e.events.has(l));if(i.machine){let t=a.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:r,label:e,event:l,from:[],to:[],result:"unknown-event",note:n});continue}if(!(o=o.filter(e=>e===t)).length){s.push({ref:r,label:e,event:l,machine:t.name,from:[],to:[],result:"unknown-event",note:`"${t.name}" does not define the event "${l}"`});continue}}if(!o.length){s.push({ref:r,label:e,event:l,from:[],to:[],result:"unknown-event",note:`no member machine defines the event "${l}"`});continue}for(let t of o){let a=n.get(t.name),o=[...a.states];if(a.ended){s.push({ref:r,label:e,event:l,machine:t.name,from:o,to:o,result:"ended",note:`${t.name} ended in ${a.ended} before this message`});continue}let c=o.filter(e=>!e4(t,e));if(!c.length){s.push({ref:r,label:e,event:l,machine:t.name,from:o,to:o,result:"ended",note:`${t.name} ended in ${o.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=[],a=t;for(;a;){for(let t of e.states.get(a)?.transitions??[])if(t?.event===n&&(s.push(t),!t.condition))return s;a=e.parent.get(a)}return s}(t,e,l)){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 "${l}" from ${c.join(" or ")} leads to ${[...new Set(m)].join(", ")}, which cannot be entered`:`${t.name} has no transition for "${l}" from ${c.join(" or ")}`;s.push({ref:r,label:e,event:l,machine:t.name,from:o,to:o,result:"refused",note:n});continue}let p=[...d],f={ref:r,label:e,event:l,machine:t.name,from:o,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]),a.states=p;let x=p.filter(e=>e4(t,e));x.length&&x.length===p.length&&(a.ended=x[0]),s.push(f)}}let r={};for(let[e,t]of n)r[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:r}})(e,r));return{scenario:e.settings?.name??"",machines:r.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,a)=>{n.push({ruleId:e,message:t,severity:"error",...s?{member:s}:{},...a?{element:a}:{}})},a=(e,t,s,a)=>{n.push({ruleId:e,message:t,severity:"warning",...s?{member:s}:{},...a?{element:a}:{}})};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,a]of(e.members??[]).entries()){if(!a?.path){s("Y002",`Member at index ${n} has no path`,void 0,`members[${n}]`);continue}t.has(a.path)&&s("Y002",`"${a.path}" is listed twice`,a.path),t.add(a.path),eV.includes(eH(a.path))&&a.path.endsWith(".json")||s("Y002",`"${a.path}" is not a document a system holds (.erdf.json, .smdf.json, .sqdf.json)`,a.path)}let n=new Set;for(let[t,a]of(e.actors??[]).entries()){if(!a?.name){s("Y004",`Actor at index ${t} has no name`,void 0,`actors[${t}]`);continue}n.has(a.name)&&s("Y004",`Duplicate actor "${a.name}"`,void 0,a.name),n.add(a.name),ez.includes(a.kind)||s("Y004",`Actor "${a.name}" has kind "${a.kind??""}"; expected one of ${ez.join(", ")}`,void 0,a.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:r,erds:i,sequences:l}=e6(t),o=new Map;for(let{member:e,def:t}of r){let n=e0(t),a=o.get(n);a?s("Y005",`"${e}" and "${a}" are both machines named "${n}"; a message cannot say which`,e):o.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 l)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 r)for(let n of Q(t,c))s(n.ruleId,n.message,e,n.element);let e=r.map(({def:e},t)=>e0(e,t));for(let{member:t,def:n}of i)for(let a of ee(n,e))s(a.ruleId,a.message,t,a.element)}for(let{member:e,def:t}of r){let n=(s,r)=>{if(!s)return;let i=r||(s.transitions??[]).length>0,l=s.states??[];for(let r of(l.length||s.parallel||s===t.state||"final"===s.kind||"history"===s.kind||i||a("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}`),l))n(r,i)};n(t.state,!1)}let d=r.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 l){let r=!1,i=e=>!!c||(r||a("L006",`${e} name entities, but the system has no ERD to hold them`,t),r=!0,!1);for(let a of n.participants??[]){if(!a?.name)continue;let n=`participant:${a.name}`;if(a.actor&&e&&!g.has(a.actor)&&s("L006",`Participant "${a.name}" is the actor "${a.actor}", which the system does not list`,t,n),a.object&&!p.has(a.object)&&s("L006",`Participant "${a.name}" is the object "${a.object}", which no member machine declares`,t,n),a.holds?.length&&i("Participants' holds"))for(let e of a.holds)f.has(e)||s("L006",`Participant "${a.name}" holds "${e}", which is not an entity`,t,n)}for(let{ref:e,message:r}of eS(n)){if(!r)continue;let n=`message:${e}`;r.machine&&!h.has(r.machine)?s("L005",`Message ${e} names the machine "${r.machine}", which is not a member`,t,n):r.event&&((r.machine?u.get(r.machine)?.has(r.event):[...u.values()].some(e=>e.has(r.event)))||s("L005",`Message ${e} fires "${r.event}", which ${r.machine?`"${r.machine}" does not define`:"no member machine defines"}`,t,n)),r.carries&&i("Messages' carries")&&!f.has(r.carries)&&s("L007",`Message ${e} carries "${r.carries}", which is not an entity`,t,n),r.state&&!m.has(r.state)&&a("L008",`Message ${e} says the machine is then in "${r.state}", which no member machine has`,t,n)}let l=e3(n,d);for(let e of(x.push({member:t,report:l}),l.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 r=n.filter(e=>(e.machine??"")===s),i=r[0],l=r.length>1?` (${r.length-1} later message${r.length>2?"s stop":" stops"} too)`:"",o="without-optional"===e.kind?" — a message the rest depends on may not be optional":"";a("L008",`${e.name}, message ${i.ref}: ${i.note??i.result}${l}${o}`,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),a=[],r=new Map;for(let{member:e,def:t}of n)for(let n of t.entities??[])n?.name&&!r.has(n.name)&&r.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 l=new Map,o=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=l.get(t.id)??[];n.push({member:e,machine:s}),l.set(t.id,n)}for(let n of t.settings?.objects??[]){if(!n?.instance)continue;o.has(n.instance)||o.set(n.instance,{member:e,className:n.class});let t=r.get(n.class);t&&a.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 l of t.settings?.objects??[]){let t=r.get(l.class);if(t)for(let r of G(s.condition,l.instance))i.get(l.class)?.has(r)&&a.push({from:{member:e,kind:"event",name:s.event},to:{member:t,kind:"attribute",name:`${l.class}.${r}`},rule:"L002",text:`its guard on ${n.name} reads ${l.class}.${r}`,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 r of J(s)){let i=d.get(r)??t.find(({def:e})=>e0(e)===r)?.member;i&&a.push({from:{member:e,kind:"attribute",name:`${n.name}.${s.name}`},to:{member:i,kind:"machine",name:r},rule:"L003",text:`stores the state of ${r}`,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?o.get(t.object):void 0;for(let e of(s&&a.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=r.get(e);s&&a.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 l.get(s.event)??[])s.machine&&s.machine!==e.machine||a.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=r.get(s.carries);e&&a.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)a.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 a}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 ta(e,t){let{machines:n,erds:s,sequences:a}=e6(t),r=[],i=e=>{r.includes(e)||r.push(e)},l=e,o=[];if(l)for(let{def:e}of a)for(let t of e.participants??[]){if(!t?.actor||(l.actors??[]).some(e=>e.name===t.actor))continue;let n=ts(t.actor,t.service);l=function(e,t){if(!t.name?.trim())throw Error("An actor needs a name.");if(!ez.includes(t.kind))throw Error(`An actor is one of ${ez.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}(l,{name:t.actor,kind:n}),o.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 a){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=ea(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 a=h[s].settings?.objects??[];if(a.some(e=>e.class===t.name))continue;let r=x(t.name);for(;a.some(e=>e.instance===r);)r+="_";g(s,[{op:"settings.update",patch:{objects:[...a,{instance:r,class:t.name}]}}],`${u[s]} is constructed with the object ${r} : ${t.name}, because ${t.name}.${e.name} stores its state`)}for(let{def:e}of a){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,a=t.map(e=>e),r=e1(a),i=new Map,l=[],o=new Set,c=e3(e,a),d=new Set,h="",u=(e,t,n)=>{d.add(`${e}|${JSON.stringify(t)}`),a=a.map((n,s)=>s===e?m(n,t):n);let s=i.get(e)??{machine:r[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,a)).find(({path:e,step:t})=>!o.has(`${t.ref}|${t.machine??""}|${t.result}|${e.name}`)&&!o.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)=>{o.add(i),o.add(`${n.name}|${s.machine??""}`),l.includes(t)||l.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?a.map((e,t)=>r[t]===f.machine||(e.settings?.name??"")===f.machine?t:-1).filter(e=>e>=0):1===a.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=a[t],s=`${tt(f.from)}Events`,l=tt(f.from),o=(n.events??[]).findIndex(e=>e?.name===s||e?.name===l||e?.name===f.from||e?.feeder===f.from),c=o>=0?n.events[o].name:s,d={id:f.event,...f.label?.trim()?{description:f.label.trim()}:{}};y(t,o>=0?[{op:"event.add",sourceIndex:o,event:d}]:[{op:"eventSource.add",source:{name:s,events:[d]}}],`${r[t]} defines "${f.event}" in ${c}, because ${g} fires it`);continue}if("refused"===s.result){let e=r.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=a[e],n=s.from[0],l=tn(t,f.state);if(!l&&!f.machine){let t=r.filter((t,n)=>n!==e&&tn(a[n],f.state)),n=a.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 o=[],c=[],d=n===t.state?.name&&!(t.state?.states??[]).length;if(l||(o.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,o,`${r[e]} ${c.join(" and ")}, because ${g} says the machine is there`);continue}let h=f.label?.trim()?{description:f.label.trim()}:{};o.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,o,`${r[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&&l.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:l,before:c,after:e3(e,a),machines:a}}(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:l&&o.length?{def:l,reasons:o}:null,unresolved:r,count:y.reduce((e,t)=>e+t.reasons.length,0)+b.reduce((e,t)=>e+t.reasons.length,0)+o.length}}function tr(e,t){if(!e.count&&!e.unresolved.length)return"auto"===t?"auto: the drawings already agree":"the drawings agree";let n=[...e.machines.map(e=>`${e.machine} +${e.reasons.length}`),...e.erds.map(e=>`${e.def.settings?.name??e.member} +${e.reasons.length}`),...e.system?[`system +${e.system.reasons.length}`]:[]],s=n.length?n.join(", "):"no change",a=e.unresolved.length?`; ${e.unresolved.length} left open`:"";return"auto"===t?`auto: ${s}${a}`:`${e.count} change${1===e.count?"":"s"} proposed (${s})${a}`}let ti="default",tl=/^[A-Za-z0-9._-]{1,64}$/;function to(e){return"string"==typeof e&&tl.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):[],a=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),r=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}:{},...a?{region:a}:{},...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",...r.length?{replies:r}:{}}}function tf(e,t){return e.filter(e=>"open"===e.status&&e.author.role!==t||"answered"===e.status&&e.author.role===t)}function tg(e){return e.replies?.length?e.replies[e.replies.length-1].author.role:e.author.role}function tx(e,t={}){return e.filter(e=>(function(e,t={}){if("resolved"===e.status||"agent"!==tg(e))return!1;let n=t[e.id];return"number"!=typeof n||n<(e.replies?.length??0)})(e,t))}function ty(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 tb(e){if(!e.length)return null;let t=1/0,n=1/0,s=-1/0,a=-1/0;for(let r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x+r.width),a=Math.max(a,r.y+r.height);return{x:t,y:n,width:s-t,height:a-n}}function tw(e,t){return{x:e.x-t,y:e.y-t,width:e.width+2*t,height:e.height+2*t}}function tv(e,t){let n=new Set(t);return e.filter(e=>n.has(e.focus)).map(e=>e.box)}let tj=e=>e.split("/").pop()||e;function tk(e){return e.replace(/\s+/g," ").trim()}function t$(e){return e.parallel?e.parallel.states:e.states??[]}function tN(e,t){return t$(e).find(e=>e.name===t)??null}function tS(e,t){return t$(function(e,t){let n=e;for(let e of t){let t=tN(n,e);if(!t)break;n=t}return n}(e,t))}let tM={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 tC(e){let t={};if(!e)return t;for(let[n,s]of Object.entries(e)){let e=tM[n];e&&"string"==typeof s&&(t[e]=s)}return t}let tE={x:100,y:100,width:160,height:60};function tR(e,t){return 1===t?16*e:2===t?400*e:e}function tA(e){return!!e&&"string"==typeof e.tagName&&(!!e.isContentEditable||["INPUT","TEXTAREA","SELECT","BUTTON","OPTION"].includes(e.tagName))}function tO(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,l.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,l.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,l.jsx)("path",{d:e},`p${t}`))]})}let tT={kind:null,id:null},tP=(0,o.forwardRef)(function(e,t){let{definition:n,positions:s,path:a=[],rootLabel:r,viewport:i,onViewportChange:c,selection:d=tT,activeStates:h,errorElements:u,drawMode:m="select",drawSource:p=null,readOnly:f=!1,showBreadcrumb:g=!0,showHud:x=!0,fitKey:y,onSelect:b,onClearSelection:w,onStateMove:v,onNavigateInto:j,onNavigateTo:k,onContextMenu:$,onCreateTransition:N,onCancelDraw:M,onDeleteState:E,onUndo:R,onRedo:O,hudExtras:P,emptyHint:I,theme:B,className:F,style:V,svgId:J,pinchOwner:W="canvas"}=e,K=(0,o.useRef)(null),Z=(0,o.useId)().replace(/:/g,""),G=(0,o.useRef)(i);G.current=i;let[Q,ee]=(0,o.useState)(null),et=(0,o.useRef)(null),en=(0,o.useCallback)(e=>{et.current=e,ee(e)},[]),[es,ea]=(0,o.useState)(null),er=(0,o.useRef)(!1),[ei,el]=(0,o.useState)(!1),eo=(0,o.useRef)(null),[ec,ed]=(0,o.useState)(!1),eh=(0,o.useRef)(!1),eu=(0,o.useRef)(new Map),em=(0,o.useRef)(new Map),ep=(0,o.useRef)(null),[ef,eg]=(0,o.useState)(!1),ex=(0,o.useRef)(null),ey=(0,o.useRef)(!1),[eb,ew]=(0,o.useState)(!1),ev=n.state,ej=(0,o.useMemo)(()=>{let e=function(e,t){let n=[],s=e;for(let e of t){let t=tN(s,e);if(!t)break;n.push(e),s=t}return n}(ev,a);return[r??ev?.name??"Root",...e]},[ev,a,r]),ek=(0,o.useMemo)(()=>ev?tS(ev,a):[],[ev,a]),e$=ej[ej.length-1],eN=(0,o.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,o.useMemo)(()=>new Set(h??[]),[h]),eM=(0,o.useMemo)(()=>new Set(u??[]),[u]),eC=(0,o.useCallback)((e,t)=>{let n=K.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]),eE=(0,o.useCallback)(e=>{let t=eu.current.get(e);eu.current.delete(e),t?.hasPointerCapture?.(e)&&t.releasePointerCapture?.(e)},[]),eR=(0,o.useCallback)(e=>{let t=ex.current;t&&(void 0===e||t.pointerId===e)&&(clearTimeout(t.timer),ex.current=null)},[]),eA=(0,o.useCallback)((e,t)=>{if("touch"!==e.pointerType||!$)return;eR();let{pointerId:n,clientX:s,clientY:a}=e,r=setTimeout(()=>{ex.current=null,en(null),eo.current=null,ed(!1),ey.current=!0,navigator.vibrate?.(10),$(s,a,t)},500);ex.current={pointerId:n,x:s,y:a,target:t,timer:r}},[eR,$,en]);(0,o.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(pointer: coarse)"),t=()=>ew(e.matches);return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),(0,o.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,o.useEffect)(()=>()=>eR(),[eR]);let eO=(0,o.useRef)(new Set),e_=(0,o.useRef)(new Map),eT=(0,o.useRef)(e$),eP=(0,o.useRef)(new Set),[eI,eL]=(0,o.useState)(new Set),[eD,eq]=(0,o.useState)(new Set),[eB,eF]=(0,o.useState)(new Map),ez=eb?10/i.scale:0,eU=eb?28/i.scale:0,eY=(0,o.useCallback)(e=>s[e]??tE,[s]);(0,o.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)&&O&&(e.preventDefault(),O()),"Escape"===e.key&&(ea(null),M?.()),"Delete"===e.key&&"state"===d.kind&&d.id&&E&&E(d.id)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[R,O,M,E,d]);let eH=(0,o.useCallback)(e=>{let t=G.current;eo.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,o.useCallback)(()=>{let e=[...em.current.entries()];if(e.length<2)return;let[[t,n],[s,a]]=e;eR(),en(null),eo.current=null;let r=Math.max(1,Math.hypot(a.x-n.x,a.y-n.y)),i=eC((n.x+a.x)/2,(n.y+a.y)/2);ep.current={a:t,b:s,startDist:r,startMidX:i.x,startMidY:i.y,start:G.current},eh.current=!0,eg(!0);let l=K.current;if(l){for(let e of[t,s])if(!eu.current.has(e))try{l.setPointerCapture(e),eu.current.set(e,l)}catch{}}},[eR,eC,en]),eV=(0,o.useCallback)(e=>{if(ey.current=!1,"touch"!==e.pointerType)return;ew(!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,o.useCallback)((e,t)=>{if(0!==e.button||er.current)return;if(e.stopPropagation(),eA(e,{kind:"state",id:t}),!f&&"transition"===m)return void(p?p!==t&&ea({stateName:p,targetName:t,x:e.clientX,y:e.clientY}):b?.("state",t));if(b?.("state",t),f||!v)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,eA,en,f,v]),eW=(0,o.useCallback)(e=>{if("touch"===e.pointerType){eA(e,{kind:"canvas"}),eH(e);return}(1===e.button||0===e.button&&er.current)&&(e.preventDefault(),eH(e))},[eA,eH]),eK=(0,o.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 a=Math.hypot(s.x-t.x,s.y-t.y),r=eC((t.x+s.x)/2,(t.y+s.y)/2);c(z(Y(n.start,n.start.scale*(a/n.startDist),{x:n.startMidX,y:n.startMidY}),r.x-n.startMidX,r.y-n.startMidY));return}let s=eo.current;if(s){if(s.pointerId!==e.pointerId)return;let t=e.clientX-s.startX,n=e.clientY-s.startY,a=8*("touch"===e.pointerType);(Math.abs(t)>a||Math.abs(n)>a)&&(eh.current=!0),c({x:s.origX+t,y:s.origY+n,scale:G.current.scale});return}if(!Q||Q.pointerId!==e.pointerId||!v)return;let a=G.current.scale,r=(e.clientX-Q.startX)/a,i=(e.clientY-Q.startY)/a,l=eY(Q.name);v(Q.name,{...l,x:Math.max(0,Q.origX+r),y:Math.max(0,Q.origY+i)})},[Q,eY,v,c,eR,eC]),eZ=(0,o.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;eo.current={pointerId:n,startX:s.x,startY:s.y,origX:e.x,origY:e.y},eh.current=!0,ed(!0)}}eo.current?.pointerId===e.pointerId&&(eo.current=null),et.current?.pointerId===e.pointerId&&en(null),eo.current||ed(!1),ep.current||eg(!1)},[eR,eE,en]);(0,o.useEffect)(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault();let t=G.current,n=tR(e.deltaX,e.deltaMode),s=tR(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey){let n=U(t,Math.exp(-(.0025*s)),eC(e.clientX,e.clientY));n!==t&&c(n);return}let a=e.shiftKey?-(n||s):-n,r=e.shiftKey?0:-s;(0!==a||0!==r)&&c(z(t,a,r))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[c,eC]),(0,o.useEffect)(()=>{let e=e=>{"Space"!==e.code||e.repeat||tA(e.target)||tA(document.activeElement)||(e.preventDefault(),er.current=!0,el(!0))},t=e=>{"Space"===e.code&&(er.current=!1,el(!1))},n=()=>{er.current=!1,el(!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,o.useCallback)(e=>{let t=K.current?.getBoundingClientRect(),n={x:(t?.width??0)/2,y:(t?.height??0)/2},s=G.current,a=U(s,e,n);a!==s&&c(a)},[c]),eQ=(0,o.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,o.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,o.useImperativeHandle)(t,()=>({fit:e0,zoomIn:()=>eG(1.25),zoomOut:()=>eG(.8),resetZoom:eQ,element:()=>K.current}),[e0,eG,eQ]);let e1=(0,o.useRef)(e0);e1.current=e0,(0,o.useEffect)(()=>{if(void 0===y)return;let e=requestAnimationFrame(()=>e1.current());return()=>cancelAnimationFrame(e)},[y]);let e2=(0,o.useCallback)((e,t)=>{$&&(e.preventDefault(),e.stopPropagation(),$(e.clientX,e.clientY,t?{kind:"state",id:t}:{kind:"canvas"}))},[$]),e5=(0,o.useMemo)(()=>{let e=new Set(ek.map(e=>e.name)),t=[];for(let n of ek)for(let[s,a]of(n.transitions??[]).entries())a.nextState&&e.has(a.nextState)&&t.push({from:n.name,to:a.nextState,event:a.event,stateName:n.name,index:s,condition:a.condition});return t},[ek]),e4=(0,o.useMemo)(()=>{let e=L(e5,eY),t=new Map(A(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 a=`${n.stateName}:${n.index}`,r=t.get(a);return r?[{arrow:n,id:a,curve:e[s],spot:r}]:[]})},[e5,ek,eY]);(0,o.useEffect)(()=>{let e=new Set(ek.map(e=>e.name)),t=new Set(e5.map(e=>`${e.stateName}:${e.index}`)),n=eT.current===e$,s=[...e].filter(e=>!eO.current.has(e));s.length&&eL(e=>{let t=new Set(e);return s.forEach(e=>t.add(e)),t});let a=[...t].filter(e=>!eP.current.has(e));a.length&&eq(e=>{let t=new Set(e);return a.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 e_.current.forEach((t,a)=>{e.has(a)||n.has(a)||(n.set(a,t),s=!0)}),e.forEach(e=>{n.delete(e)&&(s=!0)}),s?n:t}):eF(e=>e.size?new Map:e),eO.current=e,e_.current=new Map(ek.map(e=>[e.name,{state:e,pos:eY(e.name)}])),eP.current=t,eT.current=e$},[ek,e$,e5,eY]);let e3={...tC(B),...V},e6=eb?" slc-hud--coarse":"";return(0,l.jsxs)("div",{className:`slc-pane${F?` ${F}`:""}`,style:e3,"data-pinch-owner":W,children:[g&&ej.length>1&&(0,l.jsx)("div",{className:"slc-crumbs",children:ej.map((e,t)=>(0,l.jsxs)("span",{className:"slc-crumb-item",children:[t>0&&(0,l.jsx)("span",{className:"slc-crumb-sep",children:"›"}),(0,l.jsx)("button",{type:"button",className:`slc-crumb${t===ej.length-1?" slc-crumb--current":""}`,onClick:()=>k?.(t),children:e})]},`${e}-${t}`))}),(0,l.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"&&(w?.(),ea(null))},onContextMenu:e=>e2(e),children:[(0,l.jsxs)("defs",{children:[(0,l.jsx)("marker",{id:`slc-arrow-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,l.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead"})}),(0,l.jsx)("marker",{id:`slc-arrow-sel-${Z}`,markerWidth:"10",markerHeight:"7",refX:"10",refY:"3.5",orient:"auto",children:(0,l.jsx)("polygon",{points:"0 0, 10 3.5, 0 7",className:"slc-arrowhead slc-arrowhead--selected"})})]}),"transition"===m&&p&&(0,l.jsxs)("text",{x:"50%",y:"30",textAnchor:"middle",className:"slc-draw-hint",children:['Click target state to create transition from "',p,'"']}),(0,l.jsxs)("g",{transform:X(i),style:ec||ef?{pointerEvents:"none"}:void 0,children:[e4.map(({arrow:e,id:t,curve:n,spot:s})=>{let a="transition"===d.kind&&d.id===t,r=eD.has(t),i=n.at(.5),o=Math.hypot(i.x-s.cx,i.y-s.cy)>4;return(0,l.jsxs)("g",{children:[eb&&(0,l.jsx)("path",{d:n.path,fill:"none",stroke:"transparent",strokeWidth:eU,strokeLinecap:"round",pointerEvents:"stroke",onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,l.jsx)("path",{d:n.path,pathLength:1,markerEnd:`url(#slc-arrow${a?"-sel":""}-${Z})`,className:`slc-edge${a?" slc-edge--selected":""}${r?" slc-edge-enter":""}`,onClick:e=>{e.stopPropagation(),b?.("transition",t)}}),(0,l.jsxs)("g",{className:"slc-chip",onClick:e=>{e.stopPropagation(),b?.("transition",t)},children:[o&&(0,l.jsx)("line",{x1:i.x,y1:i.y,x2:s.cx,y2:s.cy-5,className:`slc-chip-leader${a?" slc-chip-leader--selected":""}`}),eb&&(0,l.jsx)("rect",{x:s.x-ez,y:s.y-ez,width:s.width+2*ez,height:s.height+2*ez,fill:"transparent",pointerEvents:"all"}),(0,l.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,rx:4,className:`slc-chip-plate${a?" slc-chip-plate--selected":""}`}),(0,l.jsx)(t_,{mark:function(e){let t=e.toLowerCase();for(let{glyph:e,words:n}of T)if(n.some(e=>t.includes(e)))return e;return _}(e.event),x:C(s).x,y:C(s).y,selected:a}),(0,l.jsx)("text",{x:s.cx,y:s.cy-5,textAnchor:"middle",className:`slc-chip-text${a?" slc-chip-text--selected":""}`,children:e.event}),e.condition&&(0,l.jsxs)("text",{x:s.cx,y:s.cy+7,textAnchor:"middle",className:"slc-chip-guard",children:[(0,l.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,a="history"===e.kind,r=tO(e),i=p===e.name,o=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?r?"slc-node--drillable":f||!v?"slc-node--static":"slc-node--draggable":"slc-node--drawing";return(0,l.jsxs)("g",{className:x,onPointerDown:t=>eJ(t,e.name),onDoubleClick:t=>{t.stopPropagation(),r&&j?.(e.name)},onContextMenu:t=>e2(t,e.name),children:[eb&&(0,l.jsx)("rect",{x:t.x-ez,y:t.y-ez,width:t.width+2*ez,height:t.height+2*ez,rx:12,fill:"transparent",pointerEvents:"all"}),(0,l.jsxs)("g",{className:g?"slc-node-enter":void 0,children:[(0,l.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:a?30:s?4:8,strokeDasharray:s?"6 3":r?"4 2":void 0,className:["slc-node",s?"slc-node--final":r?"slc-node--composite":"",i?"slc-node--source":"",o?"slc-node--error":"",n?"slc-node--selected":"",u?"slc-node--active":""].filter(Boolean).join(" ")}),(0,l.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,l.jsx)("text",{x:t.x+t.width-8,y:t.y+14,textAnchor:"end",className:"slc-node-kind",children:e.kind}),c&&(0,l.jsx)("text",{x:t.x+6,y:t.y+t.height-6,className:"slc-node-entry",children:"▸entry"}),h&&(0,l.jsx)("text",{x:t.x+t.width-6,y:t.y+t.height-6,textAnchor:"end",className:"slc-node-exit",children:"exit◂"}),o&&(0,l.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,l.jsxs)("g",{children:[(0,l.jsx)("title",{children:`Notes: ${e.notes}`}),(0,l.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"})]}),r&&(0,l.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,a=tO(t);return(0,l.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,l.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":a?"4 2":void 0,className:`slc-node${s?" slc-node--final":a?" slc-node--composite":""}`}),(0,l.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,l.jsx)("text",{x:"50%",y:"50%",textAnchor:"middle",className:"slc-empty",children:I??"This level has no states."})]}),x&&(0,l.jsxs)("div",{className:`slc-hud${e6}`,children:[(0,l.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,l.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,l.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,l.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,l.jsx)("button",{type:"button",className:"slc-hud-btn",title:"Fit the whole machine in view",onClick:e0,children:"⤢ Fit"}),P&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{className:"slc-hud-sep",children:"|"}),P]}),(0,l.jsx)("span",{className:"slc-hud-sep",children:"|"}),(0,l.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,l.jsxs)("div",{className:"slc-picker",style:{left:es.x,top:es.y-80},onClick:e=>e.stopPropagation(),children:[(0,l.jsxs)("div",{className:"slc-picker-title",children:[es.stateName," → ",es.targetName]}),(0,l.jsx)("div",{className:"slc-picker-sub",children:"Select event:"}),0===eN.length?(0,l.jsx)("div",{className:"slc-picker-empty",children:"No events defined. Add events first."}):eN.map(e=>(0,l.jsx)("button",{type:"button",className:"slc-picker-item",onClick:()=>{es&&(N?.(es.stateName,es.targetName,e),ea(null),M?.())},children:e},e)),(0,l.jsx)("button",{type:"button",className:"slc-picker-cancel",onClick:()=>{ea(null),M?.()},children:"Cancel"})]})]})});function tI(e,t){return 1===t?16*e:2===t?400*e:e}let tL={"1:1":["one","one"],"1:N":["one","many"],"N:1":["many","one"],"N:M":["many","many"]};function tD(e,t,n){let s=t.x-e.x,a=t.y-e.y,r=Math.hypot(s,a)||1,i=s/r,l=a/r,o=-l,c=(t,n)=>`${(e.x+i*t+o*n).toFixed(1)} ${(e.y+l*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 tq(e){return[e.description??"",e.notes?.trim()?`Notes: ${e.notes}`:""].filter(Boolean).join("\n\n")}function tB(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 tF({definition:e,notation:t="crowsfoot",positions:n,viewport:s,onViewportChange:a,selection:r=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:w}){let v=(0,o.useRef)(null),j=(0,o.useRef)(s);j.current=s;let k=(0,o.useRef)(null),$=(0,o.useRef)(new Map),N=(0,o.useRef)(null),S=(0,o.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,o.useMemo)(()=>new Map(M?S.map(e=>{var t;let s,a,r,i,l,o,c;return[e.name,(t=n[e.name],s=ei(e),a=el(e),r={x:t.x+(t.width-a)/2,y:t.y+(t.height-40)/2,width:a,height:40},i=eo(s),l=r.y+r.height/2,o=ec(s.length),c=s.map((e,t)=>{let n=t<o,a=n?o:s.length-o,c=l+((n?t:t-o)-(a-1)/2)*32,d=n?r.x-34-i:r.x+r.width+34+i;return{attribute:e,cx:d,cy:c,rx:i,ry:13,from:{x:n?r.x:r.x+r.width,y:l},to:{x:n?d+i:d-i,y:c}}}),{rect:r,ovals:c,routingBox:{x:r.x,y:t.y,width:r.width,height:t.height}})]}):[]),[M,S,n]),E=(0,o.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)),a=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:a[t]}))},[e.relationships,S,n,C]),R=(0,o.useMemo)(()=>A(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]),O=(0,o.useCallback)((e,t)=>{let n=v.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,o.useEffect)(()=>{if(void 0===d)return;let e=v.current?.getBoundingClientRect(),t=Object.values(n);e&&0!==t.length&&a(H(t,e.width,e.height))},[d]),(0,o.useEffect)(()=>{let e=v.current;if(!e)return;let t=e=>{e.preventDefault();let t=j.current,n=tI(e.deltaX,e.deltaMode),s=tI(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void a(U(t,Math.exp(-(.0025*s)),O(e.clientX,e.clientY)));let r=e.shiftKey?-(n||s):-n,i=e.shiftKey?0:-s;(0!==r||0!==i)&&a(z(t,r,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[a,O]);let _=()=>{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}}},T=(e,t)=>{if(0!==e.button&&"mouse"===e.pointerType)return;if(e.stopPropagation(),v.current?.setPointerCapture(e.pointerId),$.current.set(e.pointerId,O(e.clientX,e.clientY)),$.current.size>=2){k.current=null,N.current=_();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,l.jsxs)("div",{className:`slc-pane${y?` ${y}`:""}`,style:{...tC(x),...b},children:[(0,l.jsx)("svg",{ref:v,id:w,className:"slc-surface",onPointerDown:e=>T(e),onPointerMove:e=>{if($.current.has(e.pointerId)&&$.current.set(e.pointerId,O(e.clientX,e.clientY)),N.current){let e=_();if(!e)return;let t=N.current;a(U(z(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)a(z(j.current,e.clientX-t.lastX,e.clientY-t.lastY));else if(t.name&&t.origin){var n,s,r;let a=(n=j.current,s=e.clientX-t.startX,r=e.clientY-t.startY,{x:s/n.scale,y:r/n.scale});m?.(t.name,{...t.origin,x:t.origin.x+a.x,y:t.origin.y+a.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,l.jsxs)("g",{transform:X(s),children:[E.map(({rel:e,curve:t},n)=>{if(M){let[s,a]=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),r=t.at(.12),i=t.at(.88);return(0,l.jsxs)("g",{className:"slc-erd-rel",children:[(0,l.jsx)("path",{d:tB(C.get(e.from)?.rect,t.p0),className:"slc-erd-line"}),(0,l.jsx)("path",{d:tB(C.get(e.to)?.rect,t.p3),className:"slc-erd-line"}),(0,l.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,l.jsx)("text",{x:r.x+9,y:r.y+4,className:"slc-erd-card",children:s}),(0,l.jsx)("text",{x:i.x+9,y:i.y+4,className:"slc-erd-card",children:a})]},`r${n}`)}let[s,a]=tL[e.cardinality]??tL["1:N"];return(0,l.jsxs)("g",{className:"slc-erd-rel",children:[(0,l.jsx)("path",{d:t.path,className:"slc-erd-line"}),(0,l.jsx)("path",{d:tD(t.p0,t.p1,s),className:"slc-erd-mark"}),(0,l.jsx)("path",{d:tD(t.p3,t.p2,a),className:"slc-erd-mark"})]},`r${n}`)}),S.map(e=>{let t=n[e.name],s=(e.attributes??[]).filter(e=>e?.name),a=["slc-node",r===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,l.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>T(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,l.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),a=s.length>0&&!!p;return(0,l.jsxs)("g",{className:a?"slc-erd-state":void 0,onPointerDown:a?e=>e.stopPropagation():void 0,onClick:a?()=>p(s[0]):void 0,children:[(0,l.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,l.jsx)("ellipse",{cx:e.cx,cy:e.cy,rx:e.rx,ry:e.ry,className:"slc-erd-oval"}),(0,l.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)}),tq(e)&&(0,l.jsx)("title",{children:tq(e)}),(0,l.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:2,className:a}),e.notes?.trim()&&(0,l.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,l.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,l.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,l.jsxs)("g",{className:c?"slc-node--static":"slc-node--draggable",onPointerDown:t=>T(t,e.name),onContextMenu:t=>{f&&(t.preventDefault(),t.stopPropagation(),f(t.clientX,t.clientY,{kind:"entity",id:e.name}))},children:[tq(e)&&(0,l.jsx)("title",{children:tq(e)}),(0,l.jsx)("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:6,className:a}),e.notes?.trim()&&(0,l.jsx)("rect",{x:t.x+t.width-24,y:t.y-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,l.jsx)("path",{d:`M ${t.x} ${t.y+30} h ${t.width}`,className:"slc-erd-rule"}),(0,l.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,l.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,a=J(e),r=["pk"===e.key?"PK":"uk"===e.key?"UK":"",e.references?"FK":""].filter(Boolean).join(" ");return(0,l.jsxs)("g",{className:a.length&&p?"slc-erd-state":void 0,onPointerDown:a.length&&p?e=>e.stopPropagation():void 0,onClick:a.length&&p?()=>p(a[0]):void 0,children:[(a.length>0||e.description)&&(0,l.jsx)("title",{children:[a.length?`stores the state of ${a.join(", ")}`:"",e.description??""].filter(Boolean).join(" — ")}),(0,l.jsxs)("text",{x:t.x+14,y:s,className:`slc-erd-row${a.length?" slc-erd-row--state":""}${"pk"===e.key?" slc-erd-row--pk":""}`,children:[a.length?"◉ ":"",ey(e),e.nullable?" ?":""]}),r&&(0,l.jsx)("text",{x:t.x+t.width-14,y:s,textAnchor:"end",className:"slc-erd-badge",children:r})]},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,a=Math.max(34,Math.ceil(3.7*(e.label.rel.label??"").length+18));return(0,l.jsxs)("g",{pointerEvents:"none",children:[(0,l.jsx)("path",{d:`M ${n-a} ${s} L ${n} ${s-18} L ${n+a} ${s} L ${n} ${s+18} Z`,className:"slc-erd-diamond"}),(0,l.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,l.jsxs)("g",{pointerEvents:"none",children:[(0,l.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:4,className:"slc-chip-plate"}),(0,l.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,l.jsx)("div",{className:"slc-erd-empty",children:g})]})}function tz(e,t){return 1===t?16*e:2===t?400*e:e}function tU(e,t,n,s){let a=e-9*n;return s?`M ${a} ${t-4.5} L ${e} ${t} L ${a} ${t+4.5}`:`M ${a} ${t-4.5} L ${e} ${t} L ${a} ${t+4.5} Z`}function tY(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 tH=e=>"string"==typeof e?e:null==e?"":String(e);function tX(e){let t=e&&"object"==typeof e?e:{};return{from:tH(t.from),to:tH(t.to),label:tH(t.label),event:tH(t.event)||void 0,machine:tH(t.machine)||void 0,carries:tH(t.carries)||void 0,state:tH(t.state)||void 0,description:tH(t.description)||void 0,notes:tH(t.notes)||void 0,optional:!0===t.optional||void 0,reply:!0===t.reply||void 0}}function tV(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:tH(s.namespace),name:tH(s.name),notes:tH(s.notes)||void 0},participants:n(t.participants).map(e=>{let t=e&&"object"==typeof e?e:{};return{name:tH(t.name),description:tH(t.description)||void 0,notes:tH(t.notes)||void 0,actor:tH(t.actor)||void 0,service:tH(t.service)||void 0,object:tH(t.object)||void 0,holds:Array.isArray(t.holds)?t.holds.map(tH):"string"==typeof t.holds?[t.holds]:void 0}}),messages:n(t.messages).map(tX),...Array.isArray(t.fragments)?{fragments:t.fragments.map(e=>{let t=e&&"object"==typeof e?e:{};return{kind:tH(t.kind),label:tH(t.label),after:"number"==typeof t.after&&Number.isFinite(t.after)?t.after:0,notes:tH(t.notes)||void 0,messages:n(t.messages).map(tX)}})}:{}}}function tJ({definition:e,layout:t,viewport:n,onViewportChange:s,selection:a=null,errorElements:r,warningElements:i,fitKey:c,onSelect:d,onClearSelection:h,onContextMenu:u,emptyHint:m,theme:p,className:f,style:g,svgId:x}){let y=(0,o.useRef)(null),b=(0,o.useRef)(n);b.current=n;let w=(0,o.useRef)(null),v=(0,o.useRef)(new Map),j=(0,o.useRef)(null),k=(0,o.useMemo)(()=>tV(e),[e]),$=(0,o.useMemo)(()=>t??eD(k),[t,k]),S=(0,o.useRef)(new Map),[M,C]=(0,o.useState)({}),E=e=>t=>{t?S.current.set(e,t):S.current.delete(e)};(0,o.useLayoutEffect)(()=>{let e={},t=!1;for(let[n,s]of S.current){let a="function"==typeof s.getComputedTextLength?s.getComputedTextLength():0;a&&(e[n]=a,Math.abs((M[n]??-1)-a)>.5&&(t=!0))}t&&C(e)},[$,k]);let R=(0,o.useMemo)(()=>new Map(eS(k).map(e=>[e.ref,e.message])),[k]),A=(0,o.useMemo)(()=>new Map(k.participants.filter(e=>e.name).map(e=>[e.name,e])),[k.participants]),O=(0,o.useCallback)((e,t)=>{let n=y.current?.getBoundingClientRect();return{x:e-(n?.left??0),y:t-(n?.top??0)}},[]);(0,o.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,o.useEffect)(()=>{let e=y.current;if(!e)return;let t=e=>{e.preventDefault();let t=b.current,n=tz(e.deltaX,e.deltaMode),a=tz(e.deltaY,e.deltaMode);if(e.ctrlKey||e.metaKey)return void s(U(t,Math.exp(-(.0025*a)),O(e.clientX,e.clientY)));let r=e.shiftKey?-(n||a):-n,i=e.shiftKey?0:-a;(0!==r||0!==i)&&s(z(t,r,i))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[s,O]);let _=()=>{let e=[...v.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}}},T=(e,t)=>{if(0===e.button||"mouse"!==e.pointerType){if(e.stopPropagation(),y.current?.setPointerCapture(e.pointerId),v.current.set(e.pointerId,O(e.clientX,e.clientY)),v.current.size>=2){w.current=null,j.current=_();return}w.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,target:t,moved:!1}}},P=e=>{if(v.current.delete(e.pointerId),j.current){v.current.size<2&&(j.current=null);return}let t=w.current;!t||t.pointerId!==e.pointerId||(w.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(r??[]),D=new Set(i??[]),q=(e,t)=>a?.kind===e&&a.id===t,B=a?.kind==="message"?R.get(a.id):void 0;return(0,l.jsxs)("div",{className:`slc-pane${f?` ${f}`:""}`,style:{...tC(p),...g},children:[(0,l.jsx)("svg",{ref:y,id:x,className:"slc-surface",onPointerDown:e=>T(e),onPointerMove:e=>{if(v.current.has(e.pointerId)&&v.current.set(e.pointerId,O(e.clientX,e.clientY)),j.current){let e=_();if(!e)return;let t=j.current;s(U(z(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=w.current;!t||t.pointerId!==e.pointerId||!t.moved&&4>Math.hypot(e.clientX-t.startX,e.clientY-t.startY)||(t.moved=!0,s(z(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,l.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,l.jsxs)("g",{className:"slc-sqd-fragment",children:[t.notes?.trim()&&(0,l.jsx)("title",{children:`Notes: ${t.notes}`}),(0,l.jsx)("rect",{x:e.left,y:s,width:e.width,height:e.height,rx:3,className:"slc-sqd-frame"}),(0,l.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,l.jsxs)("text",{x:e.left+8,y:s+15,className:"slc-sqd-frame-heading",children:[(0,l.jsx)("tspan",{className:"slc-sqd-frame-kind",children:t.kind}),` \xb7 after ${t.after} \xb7 ${t.label}`]}),t.notes?.trim()&&(0,l.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,l.jsxs)("g",{onPointerDown:t=>T(t,{kind:"participant",id:e.name}),children:[(0,l.jsx)("path",{d:`M ${e.x} ${$.lifelineTop} V ${$.lifelineBottom}`,className:"slc-sqd-hit"}),(0,l.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,l.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,a,r,i=R.get(e.ref);if(!i)return null;let o=`message:${e.ref}`,c=q("message",e.ref),d=L.has(o),h=!d&&D.has(o),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}`:"",w=i.state?M[`${e.ref}:state`]??N(b,11):0,v=f+5+g+(x?5+x:0)+(y?5+y:0)+(w?5+w:0);if(e.self){let t=e.fromX,o=e.y-7-2,c=o+14;a=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:`M ${t} ${o} H ${t+30} V ${c} H ${t+2}`,className:u}),(0,l.jsx)("path",{d:tU(t+1,c,-1,!!i.reply),className:m})]}),n=t+30+8,s=e.y+2,r={x:t-6,y:o-8,w:44+v,h:30}}else{let t=e.toX>=e.fromX?1:-1,o=e.toX-t;a=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:`M ${e.fromX} ${e.y} H ${o}`,className:u}),(0,l.jsx)("path",{d:tU(o,e.y,t,!!i.reply),className:m})]}),n=(e.fromX+e.toX)/2-v/2,s=e.y-6;let c=Math.min(e.fromX,e.toX,n),d=Math.max(e.fromX,e.toX,n+v);r={x:c-4,y:e.y-22,w:d-c+8,h:30}}let j=n,k=e=>{let t=j;return j+=e+5,t},$=k(f),S=k(g),C=x?k(x):0,A=y?k(y):0,O=w?k(w):0;return(0,l.jsxs)("g",{className:"slc-sqd-message",onPointerDown:t=>T(t,{kind:"message",id:e.ref}),onContextMenu:I({kind:"message",id:e.ref}),children:[(0,l.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,l.jsx)("rect",{x:r.x,y:r.y,width:r.w,height:r.h,className:"slc-sqd-hitbox"}),c&&(0,l.jsx)("rect",{x:r.x,y:r.y,width:r.w,height:r.h,rx:4,className:"slc-sqd-selected-plate"}),a,(0,l.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,l.jsx)("text",{x:$+(f-2)/2,y:s,textAnchor:"middle",className:"slc-sqd-ref",children:p}),(0,l.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,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:C,y:s-10,width:x,height:13,rx:3,className:"slc-sqd-opt"}),(0,l.jsx)("text",{x:C+x/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-opt-text",children:"opt"})]}),y>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:A,y:s-10.5,width:y,height:14,rx:7,className:"slc-sqd-event"}),(0,l.jsx)("text",{ref:E(`${e.ref}:event`),x:A+y/2,y:s-.5,textAnchor:"middle",className:"slc-sqd-event-text",children:i.event})]}),w>0&&(0,l.jsx)("text",{ref:E(`${e.ref}:state`),x:O,y:s,className:"slc-sqd-state",children:b}),i.notes?.trim()&&(0,l.jsx)("rect",{x:j-5+3,y:s-9,width:5,height:11,rx:1.5,className:"slc-note-mark"})]},`m-${e.ref}`)}),$.participants.map(e=>{let t=A.get(e.name);if(!t)return null;let n=`participant:${e.name}`,s=q("participant",e.name)||!!B&&(B.from===e.name||B.to===e.name),a=["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(" "),r=t.actor?"actor":t.object?"object":t.service?"service":"";return(0,l.jsxs)("g",{className:"slc-node--static slc-sqd-participant",onPointerDown:t=>T(t,{kind:"participant",id:e.name}),onContextMenu:I({kind:"participant",id:e.name}),children:[tY(t)&&(0,l.jsx)("title",{children:tY(t)}),(0,l.jsx)("rect",{x:e.left,y:e.top,width:e.width,height:e.height,rx:t.actor?e.height/2:4,className:a}),t.notes?.trim()&&(0,l.jsx)("rect",{x:e.left+e.width-24,y:e.top-5,width:13,height:5,rx:1.5,className:"slc-note-mark"}),(0,l.jsx)("text",{x:e.x,y:e.top+e.height/2+(r?1:4),textAnchor:"middle",className:`slc-node-name slc-sqd-name${t.object?" slc-sqd-name--object":""}`,children:e.name}),r&&(0,l.jsxs)("text",{x:e.x,y:e.top+e.height-4,textAnchor:"middle",className:"slc-sqd-kind",children:["object"===r?`:${t.object}`:"service"===r?"service":"actor",t.holds?.length?` \xb7 holds ${t.holds.length}`:""]})]},`p-${e.name}`)})]})}),0===$.participants.length&&m&&(0,l.jsx)("div",{className:"slc-erd-empty",children:m})]})}function tW(e,t){return tb(e.elements?.length?tv(t,e.elements):[])??e.region??null}function tK({viewport:e,boxes:t,spotlight:n,region:s,marks:a,selectedMark:r=null,onSelectMark:i,unread:c,hideResolved:d=!0,marking:h=!1,onDraft:u,draft:m=null,avoid:p,theme:f,className:g,style:x}){let y=`slc-stage-mask-${(0,o.useId)().replace(/[^a-zA-Z0-9_-]/g,"")}`,b=(0,o.useRef)(null),w=(0,o.useRef)(null),[v,j]=(0,o.useState)(null),[k,$]=(0,o.useState)(null),[N,S]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=b.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();$(e=>e&&e.w===t.width&&e.h===t.height?e:{w:t.width,h:t.height})};t();try{S(window.matchMedia("(pointer: coarse)").matches)}catch{}if("u"<typeof ResizeObserver)return;let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let M=(0,o.useMemo)(()=>n?.length?tv(t,n).map(e=>tw(e,8)):[],[t,n]),C=X(e),E=a?.find(e=>e.id===r)??null,R=(0,o.useMemo)(()=>new Set(c??[]),[c]),A=(0,o.useMemo)(()=>{let e=[];return E?.elements?.length&&e.push(...tv(t,E.elements)),m?.elements.length&&e.push(...tv(t,m.elements)),e.map(e=>tw(e,4))},[t,E,m]),O=[E?.region,m?.region].filter(e=>!!e),_=(a??[]).map((e,t)=>({mark:e,n:t+1})).filter(({mark:e})=>!(d&&"resolved"===e.status&&e.id!==r)).map(({mark:n,n:s})=>{var a;let r=tW(n,t);if(!r)return null;let i={x:(a={x:r.x+r.width,y:r.y}).x*e.scale+e.x,y:a.y*e.scale+e.y};return{mark:n,n:s,x:i.x,y:i.y}}).filter(e=>null!==e),T=k?.w?function(e,t){let n=t.size??22,s=t.spacing??n+4,a=t.inset??8,r=t.avoid??[],i=a+.4*n,l=t.width-a-.6*n,o=a+.6*n,c=t.height-a-.4*n,d=(e,t,n)=>n<t?(t+n)/2:Math.min(n,Math.max(t,e)),h=(e,t)=>r.find(s=>(function(e,t,n=0){return e.x<t.x+t.width+n&&t.x<e.x+e.width+n&&e.y<t.y+t.height+n&&t.y<e.y+e.height+n})({x:e-.4*n,y:t-.6*n,width:n,height:n},s,4)),u=[],m=(e,t)=>u.some(s=>Math.abs(s.x-e)<n&&Math.abs(s.y-t)<n),p=e.length+r.length+2,f=(e,t)=>{for(let a=0;a<p;a++){let a=h(e,t);if(a)t=a.y+a.height+4+.6*n;else if(m(e,t))t+=s;else break}return t},g=(e,t)=>{for(let a=0;a<p;a++){let a=h(e,t);if(a)t=a.y-4-.4*n;else if(m(e,t))t-=s;else break}return t};for(let t of e){let e=d(t.x,i,l),n=d(t.y,o,c),s=f(e,n);s>c&&(s=Math.max(o,g(e,n))),u.push({x:e,y:s})}return u}(_,{width:k.w,height:k.h,size:N?30:22,avoid:p}):_,P=_.map((e,t)=>({...e,x:T[t].x,y:T[t].y})),I=e=>{let t=b.current?.getBoundingClientRect();return{x:e.clientX-(t?.left??0),y:e.clientY-(t?.top??0)}};return(0,l.jsxs)("div",{ref:b,className:`slc-stage${h?" slc-stage--marking":""}${g?` ${g}`:""}`,style:{...tC(f),...x},children:[(0,l.jsxs)("svg",{className:"slc-stage-svg","aria-hidden":"true",children:[M.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("defs",{children:(0,l.jsxs)("mask",{id:y,maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"100%",height:"100%",children:[(0,l.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:"white"}),(0,l.jsx)("g",{transform:C,children:M.map((e,t)=>(0,l.jsx)("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:10,fill:"black"},t))})]})}),(0,l.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",className:"slc-stage-scrim",mask:`url(#${y})`}),(0,l.jsx)("g",{transform:C,children:M.map((e,t)=>(0,l.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,l.jsxs)("g",{transform:C,children:[s&&(0,l.jsx)("rect",{x:s.x,y:s.y,width:s.width,height:s.height,rx:6,className:"slc-stage-region",vectorEffect:"non-scaling-stroke"}),A.map((e,t)=>(0,l.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}`)),O.map((e,t)=>(0,l.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}`))]}),v&&(0,l.jsx)("rect",{x:v.x,y:v.y,width:v.w,height:v.h,rx:4,className:"slc-stage-drag"})]}),P.map(({mark:e,n:t,x:n,y:s})=>(0,l.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"}${R.has(e.id)?" slc-stage-pin--new":""}${e.id===r?" 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"})`:""}${R.has(e.id)?" · new":""}`,"aria-label":`Mark ${t}, ${e.status}${R.has(e.id)?", new":""}: ${e.text}`,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),i?.(e.id)},children:[t,(e.replies?.length??0)>0&&(0,l.jsx)("span",{className:"slc-stage-pin-count",children:e.replies.length})]},e.id)),h&&(0,l.jsx)("div",{className:"slc-stage-catch",onPointerDown:e=>{if(0!==e.button&&"mouse"===e.pointerType)return;e.currentTarget.setPointerCapture(e.pointerId);let t=I(e);w.current={id:e.pointerId,x:t.x,y:t.y,moved:!1}},onPointerMove:e=>{let t=w.current;if(!t||t.id!==e.pointerId)return;let n=I(e);!t.moved&&6>Math.hypot(n.x-t.x,n.y-t.y)||(t.moved=!0,j({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=w.current;if(!s||s.id!==n.pointerId)return;w.current=null,j(null);let a=I(n);if(s.moved){let n=F(e,{x:Math.min(s.x,a.x),y:Math.min(s.y,a.y)}),r=F(e,{x:Math.max(s.x,a.x),y:Math.max(s.y,a.y)}),i={x:n.x,y:n.y,width:Math.max(1,r.x-n.x),height:Math.max(1,r.y-n.y)};u?.({elements:function(e,t,n=1/3){let s=[];for(let{focus:a,box:r}of e){let e=r.width*r.height;!(e<=0||s.includes(a))&&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}(r,t)/e>=n&&s.push(a)}return s}(t,i),region:i});return}let r=F(e,a),i=function(e,t,n){let s=null;for(let a of e){let{box:e}=a;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=a)}return s?.focus??null}(t,r.x,r.y);if(i)return u?.({elements:[i]});if("touch"===n.pointerType)return;let l=28/(e.scale||1);u?.({elements:[],region:{x:r.x-l,y:r.y-l,width:2*l,height:2*l}})},onPointerCancel:()=>{w.current=null,j(null)}})]})}function tZ(e,t){let n=t?.[e];if(n)return n;let s=e.indexOf(":");if(s<=0)return e;let a=e.slice(0,s),r=e.slice(s+1);if("message"===a)return`message ${r}`;if("attribute"===a){let e=r.indexOf(".");return e>0?`${r.slice(e+1)} in ${r.slice(0,e)}`:r}return r}function tG(e,t){var n;let s,a,r=(n=e.elements,a=new Set(s=n??[]),s.filter(e=>{let t=/^attribute:([^.]+)\./.exec(e);return!t||!a.has(`entity:${t[1]}`)}).map(e=>tZ(e,t)));return r.length?r.length<=1?r[0]??"":r.length<=3?`${r.slice(0,-1).join(", ")} and ${r[r.length-1]}`:`${r.slice(0,2).join(", ")} and ${r.length-2} more`:e.region?e.level&&"Root"!==e.level?`an area inside ${e.level}`:"an area":"the drawing"}function tQ(e,t){return t||(e?e.split("/").pop()??e:"").replace(/\.(smdf|erdf|sqdf|sysdf)\.json$/i,"").replace(/\.json$/i,"")||"the drawing"}function t0(e){if("resolved"===e.status)return"resolved";let t=e.author?.role==="agent";return"answered"===e.status?t?"waits for agent":"answered":t?"waits for you":"waits for agent"}function t1({size:e=16,children:t,...n}){return(0,l.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 t2(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),(0,l.jsx)("path",{d:"M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21M8.5 21h7"})]})}function t5(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("path",{d:"M4 9.5h3.5L12 5.5v13l-4.5-4H4z"}),(0,l.jsx)("path",{d:"M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11"})]})}function t4(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("path",{d:"M4 9.5h3.5L12 5.5v13l-4.5-4H4z"}),(0,l.jsx)("path",{d:"M16 10l4 4M20 10l-4 4"})]})}function t3(e){return(0,l.jsx)(t1,{...e,children:(0,l.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 t6(e){return(0,l.jsx)(t1,{...e,children:(0,l.jsx)("path",{d:"M8 5.5v13l10-6.5z",fill:"currentColor"})})}function t8(e){return(0,l.jsx)(t1,{...e,children:(0,l.jsx)("path",{d:"M8.5 5.5v13M15.5 5.5v13",strokeWidth:2.6})})}function t7(e){return(0,l.jsx)(t1,{...e,children:(0,l.jsx)("rect",{x:"7",y:"7",width:"10",height:"10",rx:"1.5",fill:"currentColor"})})}function t9(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("path",{d:"M17 5.5v13L8 12z"}),(0,l.jsx)("path",{d:"M6.5 5.5v13"})]})}function ne(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("path",{d:"M7 5.5v13l9-6.5z"}),(0,l.jsx)("path",{d:"M17.5 5.5v13"})]})}function nt(e){return(0,l.jsx)(t1,{...e,children:(0,l.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 nn(e){return(0,l.jsx)(t1,{...e,style:{transform:"scaleY(-1)",...e.style},children:(0,l.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 ns(e){return(0,l.jsx)(t1,{...e,children:(0,l.jsx)("path",{d:"M6.5 6.5l11 11M17.5 6.5l-11 11"})})}function na(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.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,l.jsx)("path",{d:"M13.8 7l3.2 3.2"})]})}function nr(e){return(0,l.jsxs)(t1,{...e,children:[(0,l.jsx)("path",{d:"M12 21s-6.5-6.2-6.5-11.2a6.5 6.5 0 0 1 13 0C18.5 14.8 12 21 12 21z"}),(0,l.jsx)("circle",{cx:"12",cy:"9.8",r:"2.3"})]})}function ni({shown:e,playing:t=!1,speaking:n=!1,voice:s,onToggleVoice:a,onPlay:r,onPause:i,onNext:o,onPrev:c,onGoto:d,onClose:h,onAnswer:u,held:m=null,theme:p,className:f,style:g}){if(!e)return null;let{step:x,index:y,count:b,title:w,origin:v}=e,j=null!==y&&null!==b,k=x.title||w||"",$=[j?`${y+1} / ${b}`:"",x.title?w:""].filter(Boolean).join(" · "),N=j&&b>7;return(0,l.jsxs)("section",{className:`slc-stage-caption${f?` ${f}`:""}`,style:{...tC(p),...g},role:"region","aria-label":"What the agent is showing","aria-live":"polite",children:[(0,l.jsxs)("header",{className:"slc-stage-caption-head",children:[v&&(0,l.jsx)("span",{className:"slc-stage-caption-origin",children:v}),(0,l.jsxs)("span",{className:"slc-stage-caption-heading",children:[k&&(0,l.jsx)("span",{className:"slc-stage-caption-title",children:k}),$&&(0,l.jsx)("span",{className:"slc-stage-caption-count",children:$})]}),n&&(0,l.jsx)("span",{className:"slc-stage-caption-speaking","aria-label":"speaking"}),h&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:h,"aria-label":"Close",title:"Close",children:(0,l.jsx)(ns,{})})]}),m&&(0,l.jsxs)("p",{className:"slc-stage-caption-held",children:["About ",(0,l.jsx)("strong",{children:m.drawing}),", not the drawing open here."]}),(0,l.jsx)("p",{className:"slc-stage-caption-say",children:x.say}),j&&b<=24&&b>1&&(0,l.jsx)("nav",{className:`slc-stage-dots${N?" slc-stage-dots--many":""}`,"aria-label":"Steps",children:Array.from({length:b},(e,t)=>(0,l.jsx)("button",{type:"button",className:`slc-stage-dot${t===y?" slc-stage-dot--current":t<y?" slc-stage-dot--seen":""}`,onClick:()=>d?.(t),"aria-label":`Step ${t+1}`,"aria-current":t===y?"step":void 0},t))}),(0,l.jsxs)("footer",{className:"slc-stage-caption-controls",children:[j&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:c,disabled:0===y,"aria-label":"Previous step",title:"Previous step",children:(0,l.jsx)(t9,{})}),m?(0,l.jsxs)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:m.onOpen,title:`Open ${m.drawing} and play from this step`,children:[(0,l.jsx)(t6,{}),m.label??"Open and play"]}):t?(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:i,"aria-label":"Pause",title:"Pause",children:(0,l.jsx)(t8,{})}):(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:r,"aria-label":"Play",title:"Play",children:(0,l.jsx)(t6,{})}),(0,l.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:o,disabled:y===b-1,"aria-label":"Next step",title:"Next step",children:(0,l.jsx)(ne,{})})]}),!j&&m&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--main",onClick:m.onOpen,title:`Open ${m.drawing}`,children:m.label??"Open the drawing"}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),void 0!==s&&(0,l.jsx)("button",{type:"button",className:`slc-stage-btn${s?" slc-stage-btn--on":""}`,onClick:a,"aria-pressed":s,title:s?"Voice on — the steps are read aloud":"Voice off — the steps are read on screen",children:s?(0,l.jsx)(t5,{}):(0,l.jsx)(t4,{})}),u&&!m&&(0,l.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 nl={comment:"Comment",question:"Question",looks_good:"Looks good",delete:"Should go"};function no(e,t){let[n,s]=(0,o.useState)(!1),a=(0,o.useRef)("");return(0,o.useEffect)(()=>()=>e?.stop(),[e]),{listening:n,toggle:r=>{if(e){if(n){e.stop(),s(!1);return}a.current=r?`${r.trimEnd()} `:"",s(!0),e.start(e=>t(a.current+e),()=>s(!1))}}}}function nc({elements:e,region:t,labels:n}){if(!e?.length&&!t)return(0,l.jsx)("span",{className:"slc-stage-chip slc-stage-chip--quiet",children:"the drawing"});let s=new Set(e??[]),a=(e??[]).filter(e=>{let t=/^attribute:([^.]+)\./.exec(e);return!t||!s.has(`entity:${t[1]}`)});return(0,l.jsxs)(l.Fragment,{children:[a.map(e=>(0,l.jsx)("span",{className:"slc-stage-chip",title:e,children:tZ(e,n)},e)),t&&!e?.length&&(0,l.jsx)("span",{className:"slc-stage-chip slc-stage-chip--quiet",children:"an area"})]})}function nd({children:e}){return null==e||!1===e||""===e?null:(0,l.jsx)("div",{className:"slc-stage-card-note",role:"status",children:e})}function nh({elements:e,region:t,author:n,onAuthorChange:s,onSubmit:a,onCancel:r,listener:i,listenAtOnce:c=!1,busy:d=!1,error:h,placeholder:u="What should the agent know about this?",note:m,labels:p,theme:f,className:g,style:x}){let[y,b]=(0,o.useState)(""),[w,v]=(0,o.useState)("comment"),[j,k]=(0,o.useState)(n),{listening:$,toggle:N}=no(i,b),S=(0,o.useRef)(null);(0,o.useEffect)(()=>{c&&i?N(""):(c||function(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(pointer: fine)").matches}catch{return!1}}())&&S.current?.focus()},[]);let M=e=>{if(e?.preventDefault(),!y.trim()||d)return;$&&i?.stop();let t=n||j.trim();!n&&t&&s?.(t),a({text:y.trim(),kind:w,author:t})};return(0,l.jsxs)("form",{className:`slc-stage-card slc-stage-composer${g?` ${g}`:""}`,style:{...tC(f),...x},onSubmit:M,onPointerDown:e=>e.stopPropagation(),children:[(0,l.jsxs)("div",{className:"slc-stage-card-anchor",children:[(0,l.jsx)("span",{className:"slc-stage-card-label",children:"On"}),(0,l.jsx)(nc,{elements:e,region:t,labels:p})]}),(0,l.jsx)("textarea",{ref:S,className:"slc-stage-input slc-stage-textarea",value:y,placeholder:$?"Listening…":u,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&M(),"Escape"===e.key&&r()},rows:3}),!n&&(0,l.jsx)("input",{className:"slc-stage-input",value:j,placeholder:"Your name (signs your marks)",onChange:e=>k(e.target.value)}),(0,l.jsxs)("div",{className:"slc-stage-card-row",children:[(0,l.jsx)("select",{className:"slc-stage-input slc-stage-select",value:w,onChange:e=>v(e.target.value),"aria-label":"Kind of mark",children:tc.map(e=>(0,l.jsx)("option",{value:e,children:nl[e]},e))}),i&&(0,l.jsx)("button",{type:"button",className:`slc-stage-btn${$?" slc-stage-btn--live":""}`,onClick:()=>N(y),"aria-pressed":$,title:$?"Stop listening":"Speak instead of typing",children:(0,l.jsx)(t2,{})}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:r,children:"Cancel"}),(0,l.jsx)("button",{type:"submit",className:"slc-stage-btn slc-stage-btn--main",disabled:!y.trim()||d||!n&&!j.trim(),children:d?"Saving…":"Mark"})]}),(0,l.jsx)(nd,{children:m}),h&&(0,l.jsx)("div",{className:"slc-stage-card-error",children:h})]})}function nu({mark:e,number:t,onReply:n,onResolve:s,onReopen:a,onRemove:r,onClose:i,listener:c,busy:d=!1,error:h,note:u,labels:m,theme:p,className:f,style:g}){let[x,y]=(0,o.useState)(""),{listening:b,toggle:w}=no(c,y);return(0,l.jsxs)("div",{className:`slc-stage-card slc-stage-thread${f?` ${f}`:""}`,style:{...tC(p),...g},onPointerDown:e=>e.stopPropagation(),children:[(0,l.jsxs)("div",{className:"slc-stage-card-row",children:[void 0!==t&&(0,l.jsx)("span",{className:`slc-stage-pin slc-stage-pin--inline slc-stage-pin--${"resolved"===e.status?"resolved":e.status}`,children:t}),(0,l.jsxs)("span",{className:"slc-stage-card-label",children:[nl[e.kind]," · ",e.status]}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:i,"aria-label":"Close",children:(0,l.jsx)(ns,{})})]}),(0,l.jsx)("div",{className:"slc-stage-card-anchor",children:(0,l.jsx)(nc,{elements:e.elements,region:e.region,labels:m})}),(0,l.jsxs)("ol",{className:"slc-stage-thread-list",children:[(0,l.jsxs)("li",{className:`slc-stage-said slc-stage-said--${e.author.role}`,children:[(0,l.jsx)("span",{className:"slc-stage-said-who",children:e.author.name}),(0,l.jsx)("span",{className:"slc-stage-said-text",children:e.text})]}),(e.replies??[]).map((e,t)=>(0,l.jsxs)("li",{className:`slc-stage-said slc-stage-said--${e.author.role}`,children:[(0,l.jsx)("span",{className:"slc-stage-said-who",children:e.author.name}),(0,l.jsx)("span",{className:"slc-stage-said-text",children:e.text})]},t))]}),"resolved"!==e.status&&"person"===tg(e)&&(0,l.jsx)(nd,{children:u}),n&&(0,l.jsxs)("form",{className:"slc-stage-card-row",onSubmit:e=>{e?.preventDefault(),x.trim()&&!d&&(b&&c?.stop(),n?.(x.trim()),y(""))},children:[(0,l.jsx)("input",{className:"slc-stage-input slc-stage-grow",value:x,placeholder:b?"Listening…":"Reply…",onChange:e=>y(e.target.value)}),c&&(0,l.jsx)("button",{type:"button",className:`slc-stage-btn${b?" slc-stage-btn--live":""}`,onClick:()=>w(x),"aria-pressed":b,title:"Speak the reply",children:(0,l.jsx)(t2,{})}),(0,l.jsx)("button",{type:"submit",className:"slc-stage-btn slc-stage-btn--main",disabled:!x.trim()||d,children:"Reply"})]}),(0,l.jsxs)("div",{className:"slc-stage-card-row",children:["resolved"===e.status?a&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:a,children:"Reopen"}):s&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn",onClick:s,children:"Resolve"}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),r&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--danger",onClick:r,children:"Remove"})]}),h&&(0,l.jsx)("div",{className:"slc-stage-card-error",children:h})]})}function nm({marks:e,selected:t,onSelect:n,onCopy:s,copied:a,onClose:r,note:i,unread:c,labels:d,theme:h,className:u,style:m}){let[p,f]=(0,o.useState)(!1),g=new Set(c??[]),x=e.map((e,t)=>({m:e,n:t+1})),y=[...x.filter(({m:e})=>g.has(e.id)),...x.filter(({m:e})=>!g.has(e.id))],b=p?y:y.filter(({m:e})=>"resolved"!==e.status),w=e.filter(e=>"resolved"!==e.status).length;return(0,l.jsxs)("div",{className:`slc-stage-card slc-stage-panel${u?` ${u}`:""}`,style:{...tC(h),...m},onPointerDown:e=>e.stopPropagation(),children:[(0,l.jsxs)("div",{className:"slc-stage-card-row",children:[(0,l.jsx)("span",{className:"slc-stage-card-label",children:"Marks on this drawing"}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),(0,l.jsxs)("span",{className:"slc-stage-segment",role:"group","aria-label":"Which marks to list",children:[(0,l.jsxs)("button",{type:"button",className:`slc-stage-segment-btn${p?"":" slc-stage-segment-btn--on"}`,"aria-pressed":!p,onClick:()=>f(!1),children:["Open ",w]}),(0,l.jsxs)("button",{type:"button",className:`slc-stage-segment-btn${p?" slc-stage-segment-btn--on":""}`,"aria-pressed":p,onClick:()=>f(!0),children:["All ",e.length]})]}),r&&(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:r,"aria-label":"Close",children:(0,l.jsx)(ns,{})})]}),0===b.length&&(0,l.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,l.jsx)("ul",{className:"slc-stage-panel-list",children:b.map(({m:e,n:s})=>(0,l.jsx)("li",{children:(0,l.jsxs)("button",{type:"button",className:`slc-stage-panel-item${e.id===t?" slc-stage-panel-item--selected":""}`,onClick:()=>n(e.id),children:[(0,l.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}${g.has(e.id)?" slc-stage-pin--new":""}`,children:s}),(0,l.jsxs)("span",{className:"slc-stage-panel-text",children:[(0,l.jsx)("span",{className:"slc-stage-panel-said",children:e.text}),(0,l.jsxs)("span",{className:"slc-stage-panel-meta",children:[g.has(e.id)&&(0,l.jsx)("span",{className:"slc-stage-new",children:"new"}),e.author.name," · ",tG(e,d),e.replies?.length?` \xb7 ${e.replies.length} repl${1===e.replies.length?"y":"ies"}`:""]})]})]})},e.id))}),(0,l.jsx)(nd,{children:i}),s&&(0,l.jsxs)("div",{className:"slc-stage-card-row",children:[(0,l.jsx)("span",{className:"slc-stage-spacer"}),(0,l.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:a?"Copied":"Copy for the agent"})]})]})}function np({children:e,onOpen:t,onDismiss:n,theme:s,className:a,style:r}){return(0,l.jsxs)("div",{className:`slc-stage-notice${a?` ${a}`:""}`,style:{...tC(s),...r},role:"status","aria-live":"polite",onPointerDown:e=>e.stopPropagation(),children:[(0,l.jsxs)("button",{type:"button",className:"slc-stage-notice-open",onClick:t,title:"Open the thread",children:[(0,l.jsx)("span",{className:"slc-stage-notice-dot","aria-hidden":"true"}),(0,l.jsx)("span",{className:"slc-stage-notice-text",children:e})]}),n&&(0,l.jsx)("button",{type:"button",className:"slc-stage-notice-close",onClick:n,"aria-label":"Dismiss",children:(0,l.jsx)(ns,{})})]})}function nf(e){return`stateloom.marks.read.v1:${e}`}function ng(e){try{let t=window.localStorage.getItem(nf(e)),n=t?JSON.parse(t):null;if(!n||"object"!=typeof n||Array.isArray(n))return{};let s={};for(let[e,t]of Object.entries(n))"number"==typeof t&&Number.isFinite(t)&&t>=0&&(s[e]=t);return s}catch{return{}}}let nx=e=>`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`,ny=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},nb=e=>(e?e.split("/").pop()??e:"").replace(/\.(smdf|erdf|sqdf|sysdf)\.json$/i,"").replace(/\.json$/i,"");function nw(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 nv=(e,t)=>"agent"===e.role?e.name||t:"You",nj={idle:"● Record",starting:"Opening the mic…",recording:"■ Stop & send",sending:"Sending…",retry:"Send again"};function nk({open:e,onOpenChange:t,variant:n="fab",onOpenMark:s,who:a="Mia",episode:r,episodes:i,onEpisode:o,presence:c,recorder:d,onRecord:h,items:u,unheard:m=[],playing:p=null,playingStep:f=null,onPlay:g,onStop:x,onFeedback:y,autoplay:b,onAutoplay:w,waiting:v,notice:j,error:k,theme:$,className:N,style:S}){let M="recording"===d.state,C="starting"===d.state||"sending"===d.state,E=m.length,R=function(e,t,n){if(!n)return{text:"Choose the episode you are speaking in.",word:"no episode",away:!0};switch(t?.state){case"listening":return{text:`${e} is listening.`,word:"listening",away:!1};case"answering":{let n=t.takes?.length?` take ${t.takes.join(", ")}`:"";return{text:`${e} is answering${n}.`,word:`answering${n}`,away:!1}}case"answered":return{text:`${e} has answered and is getting ready to listen again.`,word:"answered",away:!1};default:return{text:`Nobody is listening yet. A take waits in the episode until ${e} does.`,word:"away",away:!0}}}(a,c,r);if(!e&&"bar"===n)return(0,l.jsx)("div",{className:`slc-talk slc-talk--bar${N?` ${N}`:""}`,style:{...tC($),...S},children:(0,l.jsxs)("button",{type:"button",className:`slc-talk-bar${M?" slc-talk-bar--live":""}${!M&&p?" slc-talk-bar--speaking":""}`,onClick:()=>M?h():t(!0),"aria-label":M?`Stop and send (${nx(d.seconds)})`:`Talk with ${a}: ${R.word}${E?`, ${E} new`:""}. Open the conversation`,title:M?"Stop and send your take":`Talk with ${a} about what is on the canvas`,children:[M?(0,l.jsx)(t7,{}):p?(0,l.jsx)(t5,{}):(0,l.jsx)(t2,{}),(0,l.jsx)("span",{className:"slc-talk-bar-title",children:M?"Stop and send":p?`${a} is speaking`:`Talk with ${a}`}),M?(0,l.jsx)("span",{className:"slc-talk-clock",children:nx(d.seconds)}):!p&&(0,l.jsx)("span",{className:`slc-talk-state${R.away?" slc-talk-state--away":""}`,children:R.word}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),!M&&E>0&&(0,l.jsxs)("span",{className:"slc-talk-new",children:[E," new"]})]})});if(!e)return(0,l.jsx)("div",{className:`slc-talk${N?` ${N}`:""}`,style:{...tC($),...S},children:(0,l.jsxs)("button",{type:"button",className:`slc-talk-fab${M?" slc-talk-fab--live":""}${!M&&p?" slc-talk-fab--speaking":""}`,onClick:()=>M?h():t(!0),"aria-label":M?`Stop and send (${nx(d.seconds)})`:p?`${a} is speaking. Open the conversation`:`Talk with ${a}${E?`, ${E} new`:""}`,title:M?"Stop and send your take":p?`${a} is walking the diagram`:`Talk with ${a} about what is on the canvas`,children:[M?(0,l.jsx)("span",{className:"slc-talk-fab-clock",children:nx(d.seconds)}):p?(0,l.jsx)(t5,{size:24}):(0,l.jsx)(t2,{size:24}),!M&&E>0&&(0,l.jsx)("span",{className:"slc-talk-fab-badge",children:E})]})});let A=[...u].reverse(),O=u.filter(e=>"mark"===e.kind),_=new Map(O.map(e=>[e.id,e])),T=u.some(e=>"take"===e.kind||"reply"===e.kind),P={"waits for agent":`waits for ${a}`,"waits for you":"waits for you",answered:"answered",resolved:"resolved"},I=e=>`${tG(e)} on ${tQ(e.doc??e.drawing,e.title)}`;return(0,l.jsx)("div",{className:`slc-talk slc-talk--open${N?` ${N}`:""}`,style:{...tC($),...S},children:(0,l.jsxs)("section",{className:"slc-talk-panel","aria-label":`Conversation with ${a}`,onPointerDown:e=>e.stopPropagation(),children:[(0,l.jsxs)("header",{className:"slc-talk-head",children:[(0,l.jsxs)("span",{className:"slc-talk-title",children:[(0,l.jsx)(t2,{})," Talk with ",a]}),(0,l.jsx)("span",{className:`slc-talk-state${R.away?" slc-talk-state--away":""}`,title:R.text,children:R.word}),(0,l.jsx)("span",{className:"slc-stage-spacer"}),(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-stage-btn--quiet",onClick:()=>t(!1),"aria-label":"Close the conversation",children:(0,l.jsx)(ns,{})})]}),i?.length&&o?(0,l.jsxs)("select",{className:"slc-stage-input slc-talk-episode",value:r??"",onChange:e=>o(e.target.value),disabled:M||C,"aria-label":"The episode this conversation belongs to",children:[!r&&(0,l.jsx)("option",{value:"",children:"Choose the episode…"}),i.map(e=>(0,l.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,l.jsx)("div",{className:"slc-talk-meta",children:r??"No episode chosen."}),(0,l.jsx)("div",{className:`slc-talk-meta${R.away?" slc-talk-meta--away":""}`,children:R.text}),(0,l.jsxs)("button",{type:"button",className:`slc-talk-record${M?" slc-talk-record--live":""}${"retry"===d.state?" slc-talk-record--retry":""}`,onClick:h,disabled:C||!!d.unavailable||!r,title:d.unavailable?`Cannot record: ${d.unavailable}`:M?"Stop and send your take":"Speak to the episode, about what is on the canvas",children:[nj[d.state],M&&(0,l.jsx)("span",{className:"slc-talk-clock",children:nx(d.seconds)})]}),d.unavailable&&(0,l.jsxs)("div",{className:"slc-talk-meta slc-talk-meta--error",children:["Cannot record here: ",d.unavailable,"."]}),d.message&&(0,l.jsx)("div",{className:`slc-talk-meta${d.error?" slc-talk-meta--error":""}`,children:d.message}),v&&(0,l.jsxs)("div",{className:"slc-talk-meta",children:["Waiting for ",a,"… ",nx(v.seconds)]}),j&&(0,l.jsx)("div",{className:"slc-talk-notice",children:j}),k&&(0,l.jsx)("div",{className:"slc-talk-meta slc-talk-meta--error",children:k}),(0,l.jsxs)("label",{className:"slc-talk-toggle",children:[(0,l.jsx)("input",{type:"checkbox",checked:b,onChange:e=>w(e.target.checked)}),"Play ",a,"'s replies on the diagram as they arrive"]}),(0,l.jsxs)("ol",{className:"slc-talk-thread",children:[0===A.length&&(0,l.jsx)("li",{className:"slc-stage-empty",children:"Nothing said or marked in this episode yet. Look at a drawing, press Record, and speak, or mark it."}),!T&&O.length>0&&(0,l.jsxs)("li",{className:"slc-stage-empty",children:[function(e,t="the agent"){let n=new Map;for(let t of e){let e=tQ(t.doc??t.drawing,t.title);n.set(e,[...n.get(e)??[],t])}return[...n.entries()].sort((e,t)=>t[1].length-e[1].length).map(([e,n])=>{let s=e=>n.filter(t=>t0(t)===e).length,a=[`${n.length} mark${1===n.length?"":"s"} on ${e}`];return s("answered")&&a.push(`${s("answered")} answered`),s("waits for agent")&&a.push(`${s("waits for agent")} waiting on ${t}`),s("waits for you")&&a.push(`${s("waits for you")} waiting on you`),s("resolved")&&a.push(`${s("resolved")} resolved`),a.join(", ")}).join("; ")}(O,a),". Nothing said by voice yet."]}),A.map(e=>"mark"===e.kind?(0,l.jsx)("li",{className:`slc-talk-entry slc-talk-entry--mark${"waits for agent"===t0(e)?" slc-talk-entry--waits":""}`,children:(0,l.jsxs)("button",{type:"button",className:"slc-talk-mark",onClick:()=>s?.(e),disabled:!s,title:`Open ${tQ(e.doc??e.drawing,e.title)} at this mark`,children:[(0,l.jsxs)("span",{className:"slc-talk-who",children:[(0,l.jsx)(nr,{size:14}),(0,l.jsxs)("span",{className:"slc-talk-mark-head",children:[(0,l.jsx)("strong",{children:nv(e.author,a)})," marked ",I(e)]}),(0,l.jsx)("span",{children:ny(e.at)})]}),(0,l.jsx)("span",{className:"slc-talk-text",children:e.text}),e.replies.length>0&&(0,l.jsx)("span",{className:"slc-talk-mark-replies",children:e.replies.map((e,t)=>(0,l.jsxs)("span",{className:`slc-talk-mark-reply slc-talk-mark-reply--${e.author.role}`,children:[(0,l.jsxs)("span",{className:"slc-talk-mark-by",children:[nv(e.author,a),e.at?` \xb7 ${ny(e.at)}`:""]}),(0,l.jsx)("span",{className:"slc-talk-text",children:e.text})]},t))}),(0,l.jsx)("span",{className:`slc-talk-mark-state${"waits for agent"===t0(e)?" slc-talk-mark-state--waits":""}`,children:P[t0(e)]})]})},`m${e.id}`):"take"===e.kind?(0,l.jsxs)("li",{className:"slc-talk-entry slc-talk-entry--take",children:[(0,l.jsxs)("div",{className:"slc-talk-who",children:[(0,l.jsx)("strong",{children:"You"}),(0,l.jsxs)("span",{children:["take ",e.take," · ",ny(e.at)]})]}),e.canvas?.doc&&(0,l.jsxs)("div",{className:"slc-talk-canvas",children:["on ",nb(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,l.jsx)("div",{className:"slc-talk-text",children:e.text||"(no transcript yet)"})]},`t${e.take}`):(0,l.jsxs)("li",{className:`slc-talk-entry slc-talk-entry--reply${m.includes(e.id)?" slc-talk-entry--new":""}`,children:[(0,l.jsxs)("div",{className:"slc-talk-who",children:[(0,l.jsx)("strong",{children:a}),(0,l.jsx)("span",{children:ny(e.at)}),(!e.unvoiced||(e.steps?.length??0)>0)&&(p===e.id?(0,l.jsx)("button",{type:"button",className:"slc-stage-btn slc-talk-play slc-talk-play--on",onClick:x,"aria-label":"Stop",title:"Stop",children:(0,l.jsx)(t7,{})}):(0,l.jsxs)("button",{type:"button",className:"slc-stage-btn slc-talk-play",onClick:()=>g(e.id),disabled:M,title:e.unvoiced?`Walk the diagram with ${a}'s words (no voice)`:e.steps?.length?`Hear ${a} walk the diagram (${e.steps.length} steps)`:`Hear ${a}`,children:[(0,l.jsx)(t6,{}),(e.steps?.length??0)>0?(0,l.jsxs)("span",{children:["Walk ",e.steps.length," steps"]}):null,m.includes(e.id)?(0,l.jsx)("span",{className:"slc-talk-new",children:"New"}):null]})),y&&(0,l.jsx)("span",{className:"slc-talk-thumbs",children:["up","down"].map(t=>(0,l.jsx)("button",{type:"button",className:`slc-talk-thumb${e.feedback===t?" slc-talk-thumb--on":""}`,onClick:()=>y(e.id,e.feedback===t?"":t),"aria-label":"up"===t?"This reply worked":"This reply missed",children:"up"===t?(0,l.jsx)(nt,{size:15}):(0,l.jsx)(nn,{size:15})},t))})]}),e.mark&&(0,l.jsxs)("button",{type:"button",className:"slc-talk-answers",onClick:()=>{let t=_.get(e.mark.id);t&&s?.(t)},disabled:!s||!_.has(e.mark.id),children:[(0,l.jsx)(nr,{size:13}),"answers your mark on ",_.has(e.mark.id)?I(_.get(e.mark.id)):tQ(e.mark.doc)]}),(e.steps?.length??0)>0?(0,l.jsx)("ol",{className:"slc-talk-steps","aria-label":`${a}'s walk through the diagram`,children:e.steps.map((t,n)=>{let s=p===e.id&&f===n;return(0,l.jsx)("li",{children:(0,l.jsxs)("button",{type:"button",className:`slc-talk-step${s?" slc-talk-step--here":""}`,onClick:()=>g(e.id,n),disabled:M,"aria-current":s?"step":void 0,title:`Walk from step ${n+1}`,children:[(0,l.jsx)("span",{className:"slc-talk-step-n",children:n+1}),(0,l.jsxs)("span",{className:"slc-talk-step-body",children:[(t.title||t.doc)&&(0,l.jsxs)("span",{className:"slc-talk-step-head",children:[t.title&&(0,l.jsx)("strong",{children:t.title}),(t.doc||nw(t))&&(0,l.jsx)("span",{className:"slc-talk-step-where",children:[nb(t.doc),nw(t)].filter(Boolean).join(" · ")})]}),(0,l.jsx)("span",{className:"slc-talk-step-say",children:t.say})]})]})},n)})}):(0,l.jsx)("div",{className:"slc-talk-text",children:e.text}),e.unvoiced&&(0,l.jsx)("div",{className:"slc-talk-meta",children:e.unvoiced})]},`r${e.id}`))]})]})})}let n$=e=>{let t,n=new Set,s=(e,s)=>{let a="function"==typeof e?e(t):e;if(!Object.is(a,t)){let e=t;t=(null!=s?s:"object"!=typeof a||null===a)?a:Object.assign({},t,a),n.forEach(n=>n(t,e))}},a=()=>t,r={setState:s,getState:a,getInitialState:()=>i,subscribe:e=>(n.add(e),()=>n.delete(e))},i=t=e(s,a,r);return r},nN=e=>{let t=e?n$(e):n$,n=e=>(function(e,t=e=>e){let n=o.default.useSyncExternalStore(e.subscribe,o.default.useCallback(()=>t(e.getState()),[e,t]),o.default.useCallback(()=>t(e.getInitialState()),[e,t]));return o.default.useDebugValue(n),n})(t,e);return Object.assign(n,t),n},nS=Object.create(null);nS.open="0",nS.close="1",nS.ping="2",nS.pong="3",nS.message="4",nS.upgrade="5",nS.noop="6";let nM=Object.create(null);Object.keys(nS).forEach(e=>{nM[nS[e]]=e});let nC={type:"error",data:"parser error"},nE="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),nR="function"==typeof ArrayBuffer,nA=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,nO=({type:e,data:t},n,s)=>{if(nE&&t instanceof Blob)if(n)return s(t);else return n_(t,s);if(nR&&(t instanceof ArrayBuffer||nA(t)))if(n)return s(t);else return n_(new Blob([t]),s);return s(nS[e]+(t||""))},n_=(e,t)=>{let n=new FileReader;return n.onload=function(){t("b"+(n.result.split(",")[1]||""))},n.readAsDataURL(e)};function nT(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let nP="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",nI="u"<typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<nP.length;e++)nI[nP.charCodeAt(e)]=e;let nL="function"==typeof ArrayBuffer,nD=(e,t)=>{if("string"!=typeof e)return{type:"message",data:nB(e,t)};let n=e.charAt(0);return"b"===n?{type:"message",data:nq(e.substring(1),t)}:nM[n]?e.length>1?{type:nM[n],data:e.substring(1)}:{type:nM[n]}:nC},nq=(e,t)=>nL?nB((e=>{let t=.75*e.length,n=e.length,s,a=0,r,i,l,o;"="===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)r=nI[e.charCodeAt(s)],i=nI[e.charCodeAt(s+1)],l=nI[e.charCodeAt(s+2)],o=nI[e.charCodeAt(s+3)],d[a++]=r<<2|i>>4,d[a++]=(15&i)<<4|l>>2,d[a++]=(3&l)<<6|63&o;return c})(e),t):{base64:!0,data:e},nB=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer;function nF(e){return e.reduce((e,t)=>e+t.length,0)}function nz(e,t){if(e[0].length===t)return e.shift();let n=new Uint8Array(t),s=0;for(let a=0;a<t;a++)n[a]=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 nU(e){if(e){var t=e;for(var n in nU.prototype)t[n]=nU.prototype[n];return t}}nU.prototype.on=nU.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},nU.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},nU.prototype.off=nU.prototype.removeListener=nU.prototype.removeAllListeners=nU.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 a=0;a<s.length;a++)if((n=s[a])===t||n.fn===t){s.splice(a,1);break}return 0===s.length&&delete this._callbacks["$"+e],this},nU.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,a=n.length;s<a;++s)n[s].apply(this,t)}return this},nU.prototype.emitReserved=nU.prototype.emit,nU.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},nU.prototype.hasListeners=function(e){return!!this.listeners(e).length};let nY="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),nH="u">typeof self?self:"u">typeof window?window:Function("return this")();function nX(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}let nV=nH.setTimeout,nJ=nH.clearTimeout;function nW(e,t){t.useNativeTimers?(e.setTimeoutFn=nV.bind(nH),e.clearTimeoutFn=nJ.bind(nH)):(e.setTimeoutFn=nH.setTimeout.bind(nH),e.clearTimeoutFn=nH.clearTimeout.bind(nH))}function nK(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class nZ extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class nG extends nU{constructor(e){super(),this.writable=!1,nW(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 nZ(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=nD(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 nQ extends nG{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 a=nD(n[e],t);if(s.push(a),"error"===a.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,a;this.writable=!1,t=e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})},s=Array(n=e.length),a=0,e.forEach((e,r)=>{nO(e,!1,e=>{s[r]=e,++a===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]=nK()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let n0=!1;try{n0="u">typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}let n1=n0;function n2(){}class n5 extends nQ{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 n4 extends nU{constructor(e,t,n){super(),this.createRequest=e,nW(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=nX(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=n4.requestsCount++,n4.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=n2,e)try{this._xhr.abort()}catch(e){}"u">typeof document&&delete n4.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 n3(){for(let e in n4.requests)n4.requests.hasOwnProperty(e)&&n4.requests[e].abort()}n4.requestsCount=0,n4.requests={},"u">typeof document&&("function"==typeof attachEvent?attachEvent("onunload",n3):"function"==typeof addEventListener&&addEventListener("onpagehide"in nH?"pagehide":"unload",n3,!1));let n6=(s=n8({xdomain:!1}))&&null!==s.responseType;function n8(e){let t=e.xdomain;try{if("u">typeof XMLHttpRequest&&(!t||n1))return new XMLHttpRequest}catch(e){}if(!t)try{return new nH[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch(e){}}let n7="u">typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class n9 extends nG{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,n=n7?{}:nX(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;nO(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}s&&nY(()=>{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]=nK()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}let se=nH.WebSocket||nH.MozWebSocket,st={websocket:class extends n9{createSocket(e,t,n){return n7?new se(e,t,n):t?new se(e,t):new se(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends nG{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,a;let r,i,l,o,c=(s=Number.MAX_SAFE_INTEGER,a=this.socket.binaryType,n||(n=new TextDecoder),r=[],i=0,l=-1,o=!1,new TransformStream({transform(e,t){for(r.push(e);;){if(0===i){if(1>nF(r))break;let e=nz(r,1);o=(128&e[0])==128,i=(l=127&e[0])<126?3:126===l?1:2}else if(1===i){if(2>nF(r))break;let e=nz(r,2);l=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(8>nF(r))break;let e=nz(r,8),n=new DataView(e.buffer,e.byteOffset,e.length),s=n.getUint32(0);if(s>2097151){t.enqueue(nC);break}l=0x100000000*s+n.getUint32(4),i=3}else{if(nF(r)<l)break;let e=nz(r,l);t.enqueue(nD(o?e:n.decode(e),a)),i=0}if(0===l||l>s){t.enqueue(nC);break}}}})),d=e.readable.pipeThrough(c).getReader(),h=new TransformStream({transform(e,n){var s;s=t=>{let s,a=t.length;if(a<126)new DataView((s=new Uint8Array(1)).buffer).setUint8(0,a);else if(a<65536){let e=new DataView((s=new Uint8Array(3)).buffer);e.setUint8(0,126),e.setUint16(1,a)}else{let e=new DataView((s=new Uint8Array(9)).buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(a))}e.data&&"string"!=typeof e.data&&(s[0]|=128),n.enqueue(s),n.enqueue(t)},nE&&e.data instanceof Blob?e.data.arrayBuffer().then(nT).then(s):nR&&(e.data instanceof ArrayBuffer||nA(e.data))?s(nT(e.data)):nO(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&&nY(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null==(e=this._transport)||e.close()}},polling:class extends n5{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=n6&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new n4(n8,this.uri(),e)}}},sn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ss=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function sa(e){var t,n;let s,a;if(e.length>8e3)throw"URI too long";let r=e,i=e.indexOf("["),l=e.indexOf("]");-1!=i&&-1!=l&&(e=e.substring(0,i)+e.substring(i,l).replace(/:/g,";")+e.substring(l,e.length));let o=sn.exec(e||""),c={},d=14;for(;d--;)c[ss[d]]=o[d]||"";return -1!=i&&-1!=l&&(c.source=r,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,a={},n.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(a[t]=n)}),c.queryKey=a,c}let sr="function"==typeof addEventListener&&"function"==typeof removeEventListener,si=[];sr&&addEventListener("offline",()=>{si.forEach(e=>e())},!1);class sl extends nU{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=sa(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=sa(t.host).host);nW(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)),sr&&(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"})},si.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&&sl.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",sl.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,a=e.length;s<a;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,nY(()=>{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 a={type:e,data:t,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),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(sl.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(),sr&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let e=si.indexOf(this._offlineEventListener);-1!==e&&si.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}sl.protocol=4;class so extends sl{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;sl.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;sl.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 a(){n||(n=!0,c(),t.close(),t=null)}let r=e=>{let n=Error("probe error: "+e);n.transport=t.name,a(),this.emitReserved("upgradeError",n)};function i(){r("transport closed")}function l(){r("socket closed")}function o(e){t&&e.name!==t.name&&a()}let c=()=>{t.removeListener("open",s),t.removeListener("error",r),t.removeListener("close",i),this.off("close",l),this.off("upgrading",o)};t.once("open",s),t.once("error",r),t.once("close",i),this.once("close",l),this.once("upgrading",o),-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 sc extends so{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=>st[e]).filter(e=>!!e)),super(n?s:e,s)}}sc.protocol;let sd="function"==typeof ArrayBuffer,sh=Object.prototype.toString,su="function"==typeof Blob||"u">typeof Blob&&"[object BlobConstructor]"===sh.call(Blob),sm="function"==typeof File||"u">typeof File&&"[object FileConstructor]"===sh.call(File);function sp(e){return sd&&(e instanceof ArrayBuffer||("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer))||su&&e instanceof Blob||sm&&e instanceof File}let sf=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];(r=i||(i={}))[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK";class sg{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(sp(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(sp(t)){let e={_placeholder:!0,num:n.length};return n.push(t),e}if(Array.isArray(t)){let s=Array(t.length);for(let a=0;a<t.length;a++)s[a]=e(t[a],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 a={};for(let s in t)Object.prototype.hasOwnProperty.call(t,s)&&(a[s]=e(t[s],n));return a}return t}(n,t),e.attachments=t.length,{packet:e,buffers:t}),a=this.encodeAsString(s.packet),r=s.buffers;return r.unshift(a),r}}class sx extends nU{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 sy(t)):super.emitReserved("decoded",t)}else if(sp(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 a=e.substring(s,t);if(a!=Number(a)||"-"!==e.charAt(t))throw Error("Illegal attachments");let r=Number(a);if(!sb(r)||r<1)throw Error("Illegal attachments");if(r>this.opts.maxAttachments)throw Error("too many attachments");n.attachments=r}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(sx.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 sw(t);case i.DISCONNECT:return void 0===t;case i.CONNECT_ERROR:return"string"==typeof t||sw(t);case i.EVENT:case i.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sf.indexOf(t[0]));case i.ACK:case i.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class sy{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 sb=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function sw(e){return"[object Object]"===Object.prototype.toString.call(e)}function sv(e){var t;return"string"==typeof e.nsp&&(void 0===(t=e.id)||sb(t))&&function(e,t){switch(e){case i.CONNECT:return void 0===t||sw(t);case i.DISCONNECT:return void 0===t;case i.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===sf.indexOf(t[0]));case i.ACK:return Array.isArray(t);case i.CONNECT_ERROR:return"string"==typeof t||sw(t);default:return!1}}(e.type,e.data)}function sj(e,t,n){return e.on(t,n),function(){e.off(t,n)}}e.s(["Decoder",()=>sx,"Encoder",()=>sg,"PacketType",()=>i,"isPacketValid",()=>sv,"protocol",0,5],11014);let sk=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class s$ extends nU{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=[sj(e,"open",this.onopen.bind(this)),sj(e,"packet",this.onpacket.bind(this)),sj(e,"error",this.onerror.bind(this)),sj(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,a;if(sk.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 r={type:i.EVENT,data:t};if(r.options={},r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){let e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}let l=null==(s=null==(n=this.io.engine)?void 0:n.transport)?void 0:s.writable,o=this.connected&&!(null==(a=this.io.engine)?void 0:a._hasPingExpired());return this.flags.volatile&&!l||(o?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),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 a=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),r=(...e)=>{this.io.clearTimeoutFn(a),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((n,s)=>{let a=(e,t)=>e?s(e):n(t);a.withError=!0,t.push(a),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 sN=e.i(11014);function sS(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}sS.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)},sS.prototype.reset=function(){this.attempts=0},sS.prototype.setMin=function(e){this.ms=e},sS.prototype.setMax=function(e){this.max=e},sS.prototype.setJitter=function(e){this.jitter=e};class sM extends nU{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,nW(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 sS({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||sN;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 sc(this.uri,this.opts);let t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;let s=sj(t,"open",function(){n.onopen(),e&&e()}),a=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=sj(t,"error",a);if(!1!==this._timeout){let e=this._timeout,n=this.setTimeoutFn(()=>{s(),a(Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(sj(e,"ping",this.onping.bind(this)),sj(e,"data",this.ondata.bind(this)),sj(e,"error",this.onerror.bind(this)),sj(e,"close",this.onclose.bind(this)),sj(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){nY(()=>{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 s$(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 sC={};function sE(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=sa(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 a=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+a+":"+s.port+t,s.href=s.protocol+"://"+a+(n&&n.port===s.port?"":":"+s.port),s}(e,(t=t||{}).path||"/socket.io"),a=s.source,r=s.id,i=s.path,l=sC[r]&&i in sC[r].nsps;return t.forceNew||t["force new connection"]||!1===t.multiplex||l?n=new sM(a,t):(sC[r]||(sC[r]=new sM(a,t)),n=sC[r]),s.query&&!t.query&&(t.query=s.queryKey),n.socket(s.path,t)}function sR(e){if(e&&"object"==typeof e&&"clientId"in e){let t=e.clientId;if("string"==typeof t)return t}}function sA(e){let{url:t,role:n,docId:s,name:a,token:r}=e,i=!1!==e.autoResync,l=sE(t,{auth:{token:r},autoConnect:!1}),o="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){o!==e&&(o=e,m("status",e))}function f(e){l.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 l.connected?Promise.resolve():new Promise((e,t)=>{p("connecting");let n=()=>{a(),e()},s=e=>{a(),t(e)},a=()=>{l.off("connect",n),l.off("connect_error",s)};l.once("connect",n),l.once("connect_error",s),l.connect()})}async function b(){return await y(),new Promise((e,t)=>{l.emit("bridge:join",{docId:s,role:n,name:a},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 w(e){await y(),l.emit("view:show",{...e,docId:e.docId??s,origin:e.origin??(a||n)})}async function v(e){return await y(),new Promise((t,n)=>{l.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(),l.emit("stage:step",{...e,origin:e.origin??(a||n)})}async function k(e){await y(),l.emit("stage:load",{...e,origin:e.origin??(a||n)})}async function $(e){await y(),l.emit("stage:control",{...e,origin:e.origin??(a||n)})}async function N(e){await y(),l.emit("marks:changed",{...e,origin:e.origin??(a||n)})}return l.on("connect",()=>p("connected")),l.on("disconnect",()=>p("disconnected")),l.on("connect_error",e=>{p("error"),m("error",{code:"connect_error",message:e?.message??String(e)})}),l.on("def:patch",e=>{g(e?.seq),e?.origin&&e.origin===d||m("patch",e)}),l.on("def:full",e=>{g(e?.seq),e?.origin&&e.origin===d||m("full",e)}),l.on("def:ack",e=>{m("ack",e)}),l.on("view:show",e=>{m("view",e)}),l.on("stage:step",e=>m("stage-step",e)),l.on("stage:load",e=>m("stage-load",e)),l.on("stage:control",e=>m("stage-control",e)),l.on("stage:context",e=>m("stage-context",e)),l.on("marks:changed",e=>m("marks",e)),l.on("bridge:error",e=>{m("error",{code:e?.code??"error",message:e?.message??""})}),l.on("presence:list",e=>{h=Array.isArray(e)?[...e]:[],x()}),l.on("presence:join",e=>{let t=sR(e);t&&(h=[...h.filter(e=>e.clientId!==t),e],x())}),l.on("presence:leave",e=>{let t=sR(e);t&&(h=h.filter(e=>e.clientId!==t),x())}),l.on("presence:update",e=>{let t=sR(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){l.emit("def:patch",{docId:s,ops:e,origin:d,baseSeq:n,mtime:t})},emitFull:function(e,t){l.emit("def:full",{docId:s,def:e,origin:d,mtime:t})},request:f,updatePresence:function(e){l.emit("presence:update",{docId:s,clientId:d,cursor:e.cursor,selection:e.selection})},emitView:w,joinStage:v,leaveStage:function(e){l.connected&&l.emit("stage:leave",{stage:e})},emitStep:j,emitLoad:k,emitControl:$,emitContext:function(e){l.connected&&l.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(){l.connected&&d&&l.emit("bridge:leave",{docId:s,clientId:d}),l.disconnect(),p("disconnected")},get status(){return o},get lastSeq(){return c},get presence(){return[...h]}}}function sO(e){return"runtime.enter"===e.op||"runtime.exit"===e.op}function s_(e){let{onFull:t,onPatch:n,onPresence:s,...a}=e,r=sA(a),i=null,l=0,o=[],c=[],d={status:r.status,def:null,seq:0,presence:[],activeStates:[]},h=new Set;function u(){for(let e of(d={status:r.status,def:i,seq:l,presence:o,activeStates:c},[...h]))e()}return r.on("status",()=>u()),r.on("full",e=>{i=e.def,"number"==typeof e.seq&&(l=e.seq),t?.(e),u()}),r.on("patch",e=>{"number"==typeof e.seq&&(l=e.seq);let t=e.ops??[],s=t.filter(sO),a=t.filter(e=>!sO(e));a.length>0&&i&&(i=m(i,a));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()}),r.on("presence",e=>{o=e,s?.(e),u()}),{getSnapshot:function(){return d},subscribe:function(e){return h.add(e),()=>{h.delete(e)}},emitPatch:function(e){r.emitPatch(e)},emitFull:function(e){r.emitFull(e)},enter:function(e,t,n){let s={op:"runtime.enter",state:e,...void 0!==t?{from:t}:{},...void 0!==n?{eventId:n}:{}};r.emitPatch([s])},exit:function(e){r.emitPatch([{op:"runtime.exit",state:e}])},connect:function(){r.join().then(e=>{i=e.snapshot.def,l=e.snapshot.seq,o=e.presence,null!==i&&t?.({docId:e.snapshot.docId,def:i,seq:l,mtime:e.snapshot.mtime,origin:"join"}),u()}).catch(()=>{u()})},disconnect:function(){r.disconnect()}}}function sT(e={}){let t=window.speechSynthesis,n="u">typeof Audio;if(!t&&!n)return null;let s=null,a=null,r=()=>{let e=a;a=null,e?.()},i=()=>{s&&(s.onended=null,s.onerror=null,s.onplaying=null,s.pause(),s=null),(t?.speaking||t?.pending)&&t.cancel(),r()};return{speak:l=>(i(),new Promise(i=>{let o=setTimeout(r,2*ty({...l,holdMs:void 0})+4e3);if(a=()=>{clearTimeout(o),i()},l.audio&&n&&!1!==e.recordings){let e=new Audio(l.audio);s=e,e.onended=r,e.onerror=r,e.onplaying=()=>{s===e&&Number.isFinite(e.duration)&&(clearTimeout(o),o=setTimeout(r,(e.duration-e.currentTime)*1e3+4e3))},e.play().catch(r);return}if(!1===e.speech){let e=setTimeout(r,ty(l)),t=a;a=()=>{clearTimeout(e),t?.()};return}if(!t||!l.say?.trim())return r();let c=new SpeechSynthesisUtterance([l.title,l.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=r,c.onerror=r,t.speak(c)})),cancel:i}}function sP(e,t){return t?e?`${e.trimEnd()} ${t.trimStart()}`:t:e}Object.assign(sE,{Manager:sM,Socket:s$,io:sE,connect:sE});let sI=e=>"string"==typeof e?e:"",sL=e=>{let t=e&&"object"==typeof e?e:{},n="agent"===t.role?"agent":"person";return{name:sI(t.name)||("agent"===n?"agent":"someone"),role:n}},sD=["audio/mp4;codecs=mp4a.40.2","audio/mp4"];function sq(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 sB=e=>e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`;function sF(){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 sz(){return{positions:{}}}function sU(e,t){if(e.name===t)return e;for(let n of e.states??[]){let e=sU(n,t);if(e)return e}return null}function sY(e,t,n){return e.name===t?n(e)??e:{...e,states:e.states?.map(e=>sY(e,t,n))}}function sH(e,t){return{...e,states:e.states?.filter(e=>e.name!==t).map(e=>sH(e,t))}}function sX(e){let t=[e.name];for(let n of e.states??[])t.push(...sX(n));return t}function sV(e){return e.events.flatMap(e=>(e.events??[]).map(e=>e.id))}function sJ(e){let t=[],n=sX(e.state),s=sV(e);0===s.length&&t.push({ruleId:"V001",message:"No events defined"});let a=new Set;for(let e of n)a.has(e)&&t.push({ruleId:"V002",message:`Duplicate state name: ${e}`,element:e}),a.add(e);!function e(a){for(let e of a.transitions??[])s.includes(e.event)||t.push({ruleId:"V003",message:`Transition in '${a.name}' references unknown event '${e.event}'`,element:a.name}),e.nextState&&!n.includes(e.nextState)&&t.push({ruleId:"V004",message:`Transition in '${a.name}' targets unknown state '${e.nextState}'`,element:a.name});for(let n of("final"===a.kind&&(a.transitions?.length??0)>0&&t.push({ruleId:"V007",message:`Final state '${a.name}' must not have outgoing transitions`,element:a.name}),"final"===a.kind&&(a.states?.length??0)>0&&t.push({ruleId:"V008",message:`Final state '${a.name}' must not have child states`,element:a.name}),a.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 r=new Set;for(let e of s)r.has(e)&&t.push({ruleId:"V003",message:`Duplicate event ID: ${e}`,element:e}),r.add(e);return t}function sW(e,t){return{positions:{...$(e),...t.positions}}}let sK=!1,sZ=(a=(e,t)=>({definition:sF(),layout:sW(sF(),sz()),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:a}=t(),r={definition:JSON.parse(JSON.stringify(n)),layout:JSON.parse(JSON.stringify(s))};e({undoStack:[...a.slice(-50),r],redoStack:[]})},setDefinition:n=>{t()._pushHistory();let s=sW(n,t().layout);e({definition:n,layout:s,dirty:!0,errors:sJ(n)})},updateSettings:n=>{t()._pushHistory(),e({definition:{...t().definition,settings:{...t().definition.settings,...n}},dirty:!0})},addState:(n,s)=>{t()._pushHistory();let a={...t().definition},r=n??a.state.name;a.state=sY(a.state,r,e=>({...e,states:[...e.states??[],s]}));let i=sW(a,t().layout);e({definition:a,layout:i,dirty:!0,errors:sJ(a)})},updateState:(n,s)=>{t()._pushHistory();let a={...t().definition};a.state=sY(a.state,n,e=>({...e,...s})),e({definition:a,dirty:!0,errors:sJ(a)})},removeState:n=>{t()._pushHistory();let s={...t().definition};s.state=sH(s.state,n);let a={positions:{...t().layout.positions}};delete a.positions[n],e({definition:s,layout:a,dirty:!0,errors:sJ(s)})},nestState:(n,s)=>{t()._pushHistory();let a={...t().definition},r=sU(a.state,n);if(!r||n===s)return;let i=JSON.parse(JSON.stringify(r));a.state=sH(a.state,n),a.state=sY(a.state,s,e=>({...e,states:[...e.states??[],i]})),e({definition:a,dirty:!0,errors:sJ(a)})},addEventSource:n=>{t()._pushHistory(),e({definition:{...t().definition,events:[...t().definition.events,n]},dirty:!0})},updateEventSource:(n,s)=>{t()._pushHistory();let a={...t().definition};a.events=a.events.map((e,t)=>t===n?{...e,...s}:e),e({definition:a,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:sJ(s)})},addEvent:(n,s=0)=>{t()._pushHistory();let a={...t().definition},r=a.events[s]??{name:"Internal",events:[]};r.events=[...r.events??[],n],a.events=a.events.map((e,t)=>t===s?r:e),e({definition:a,dirty:!0,errors:sJ(a)})},updateEvent:(n,s)=>{t()._pushHistory();let a={...t().definition};a.events=a.events.map(e=>({...e,events:e.events?.map(e=>e.id===n?{...e,...s}:e)})),e({definition:a,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:sJ(s)})},addParameter:(n,s)=>{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??[],s]}:e)})),e({definition:a,dirty:!0})},removeParameter:(n,s)=>{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?.filter((e,t)=>t!==s)}:e)})),e({definition:a,dirty:!0})},updateParameter:(n,s,a)=>{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?.map((e,t)=>t===s?{...e,...a}:e)}:e)})),e({definition:r,dirty:!0})},addAction:(n,s,a)=>{t()._pushHistory();let r={...t().definition};r.state=sY(r.state,n,e=>{let t=e[s]??{actions:[]};return{...e,[s]:{actions:[...t.actions,a]}}}),e({definition:r,dirty:!0})},removeAction:(n,s,a)=>{t()._pushHistory();let r={...t().definition};r.state=sY(r.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.filter((e,t)=>t!==a)}}:e}),e({definition:r,dirty:!0})},updateAction:(n,s,a,r)=>{t()._pushHistory();let i={...t().definition};i.state=sY(i.state,n,e=>{let t=e[s];return t?{...e,[s]:{actions:t.actions.map((e,t)=>t===a?r:e)}}:e}),e({definition:i,dirty:!0})},addTransition:(n,s)=>{t()._pushHistory();let a={...t().definition};a.state=sY(a.state,n,e=>({...e,transitions:[...e.transitions??[],s]})),e({definition:a,dirty:!0,errors:sJ(a)})},updateTransition:(n,s,a)=>{t()._pushHistory();let r={...t().definition};r.state=sY(r.state,n,e=>({...e,transitions:e.transitions?.map((e,t)=>t===s?{...e,...a}:e)})),e({definition:r,dirty:!0})},removeTransition:(n,s)=>{t()._pushHistory();let a={...t().definition};a.state=sY(a.state,n,e=>({...e,transitions:e.transitions?.filter((e,t)=>t!==s)})),e({definition:a,dirty:!0,errors:sJ(a)})},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:a}=t();if(0===n.length)return;let r=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(a))};e({definition:r.definition,layout:r.layout,undoStack:n.slice(0,-1),redoStack:[...t().redoStack,i],dirty:!0,errors:sJ(r.definition)})},redo:()=>{let{redoStack:n,definition:s,layout:a}=t();if(0===n.length)return;let r=n[n.length-1],i={definition:JSON.parse(JSON.stringify(s)),layout:JSON.parse(JSON.stringify(a))};e({definition:r.definition,layout:r.layout,undoStack:[...t().undoStack,i],redoStack:n.slice(0,-1),dirty:!0,errors:sJ(r.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),a=ex(s.stateMachine??s.StateMachine??s);sK=!!s&&"object"==typeof s&&"state"in s&&!("stateMachine"in s)&&!("StateMachine"in s);let r=sW(a,sz()),i=a.state?.name??"Root";e({definition:a,layout:r,fileName:n??null,dirty:!1,errors:sJ(a),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(sK?e:{stateMachine:e},null,2)},applyRemote:(n,s,a)=>{try{let r=JSON.parse(n),i=ex(r.stateMachine??r.StateMachine??r);sK=!!r&&"object"==typeof r&&"state"in r&&!("stateMachine"in r)&&!("StateMachine"in r);let l=sW(i,t().layout),o=i.state?.name??"Root",c=t(),d=new Set(sX(i.state)),h=c.navigationPath.filter(e=>d.has(e)),u=h.length?h:[o],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&&sV(i).includes(p.id))?p:{kind:null,id:null};e({definition:i,layout:l,fileName:a??t().fileName,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:sJ(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,a)=>{e({_applyingRemote:!0});try{let a=t(),r=n.filter(e=>"runtime.enter"!==e.op&&"runtime.exit"!==e.op),i=r.length?m(a.definition,r):a.definition,l=a.activeStates;for(let e of n)"runtime.enter"===e.op?l.includes(e.state)||(l=[...l,e.state]):"runtime.exit"===e.op&&l.includes(e.state)&&(l=l.filter(t=>t!==e.state));let o=sW(i,a.layout),c=i.state?.name??"Root",d=new Set(sX(i.state)),h=a.navigationPath.filter(e=>d.has(e)),u=h.length?h:[c],p=u[u.length-1],f=a.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&&sV(i).includes(f.id))?f:{kind:null,id:null};e({definition:i,layout:o,activeStates:l,dirty:!1,remoteMtime:s,remoteStatus:"synced",remoteMessage:null,errors:sJ(i),selection:g,navigationPath:u,currentParent:p})}catch(t){e({remoteStatus:"error",remoteMessage:String(t)})}finally{e({_applyingRemote:!1})}},validate:()=>{let n=sJ(t().definition);return e({errors:n}),n},setGeneratedCode:t=>e({generatedCode:t}),setShowCodePreview:t=>e({showCodePreview:t}),navigateInto:n=>{let{definition:s,navigationPath:a}=t(),r=sU(s.state,n);r&&(r.states?.length??0)>0&&e({navigationPath:[...a,n],currentParent:n,selection:{kind:null,id:null}})},navigateUp:n=>{let{navigationPath:s}=t();if(s.length<=1)return;let a=n??s.length-2,r=s.slice(0,a+1);e({navigationPath:r,currentParent:r[r.length-1],selection:{kind:null,id:null}})},getCurrentChildren:()=>{let{definition:e,currentParent:n}=t(),s=sU(e.state,n);return s?.states??[]}}))?nN(a):nN,sG="canvas",sQ=`[data-pinch-owner="${sG}"]`;function s0(e){return!!e&&"function"==typeof e.closest&&null!==e.closest(sQ)}let s1="stateloom-canvas",s2="#030712",s5=["png","jpeg","svg","mermaid","markdown"],s4={png:"PNG",jpeg:"JPEG",svg:"SVG",mermaid:"Mermaid",markdown:"Markdown"},s3={png:"image/png",jpeg:"image/jpeg",svg:"image/svg+xml",mermaid:"text/vnd.mermaid",markdown:"text/markdown"},s6={png:"png",jpeg:"jpg",svg:"svg",mermaid:"mmd",markdown:"md"};async function s8(e,t,n={}){var s,a,r;let i;if("mermaid"===e||"markdown"===e){let n,r;i=new Blob([(s=t.definition,a="markdown"===e,n=["stateDiagram-v2"],s.state&&function e(t,n,s){let a=V(t);if(0===a.length)return;let r=" ".repeat(n+1),i=new Set,l=a.find(e=>"history"!==e.kind);for(let e of(l&&(s.push(`${r}[*] --> ${l.name}`),i.add(l.name)),a))for(let t of e.transitions??[]){let n=t.condition?`${t.event} [${t.condition}]`:t.event;if(!t.nextState){s.push(`${r}${e.name} --> ${e.name} : ${n} (stays)`),i.add(e.name);continue}s.push(`${r}${e.name} --> ${t.nextState} : ${n}`),i.add(e.name),i.add(t.nextState)}for(let e of a)"final"===e.kind&&(s.push(`${r}${e.name} --> [*]`),i.add(e.name));for(let e of a)i.has(e.name)||s.push(`${r}${e.name}`);for(let t of a)0!==V(t).length&&(s.push(`${r}state ${t.name} {`),e(t,n+1,s),s.push(`${r}}`))}(s.state,0,n),r=n.join("\n"),a?`\`\`\`mermaid
2
+ ${r}
3
+ \`\`\`
4
+ `:`${r}
5
+ `)],{type:`${s3[e]};charset=utf-8`})}else{let t=function(e={}){let t="u"<typeof document?null:document.getElementById(s1);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,a=e.background??s2,r=Math.round(n.x-s),i=Math.round(n.y-s),l=Math.round(n.width+2*s),o=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(l)),c.setAttribute("height",String(o)),c.setAttribute("viewBox",`${r} ${i} ${l} ${o}`),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(r)),h.setAttribute("y",String(i)),h.setAttribute("width",String(l)),h.setAttribute("height",String(o)),h.setAttribute("fill",a),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:`${s3.svg};charset=utf-8`}):await (r=n.scale??2,new Promise((n,s)=>{let a=t.match(/width="(\d+)"\s+height="(\d+)"/),i=a?Number(a[1]):1200,l=a?Number(a[2]):800,o=URL.createObjectURL(new Blob([t],{type:"image/svg+xml;charset=utf-8"})),c=new Image;c.onload=()=>{URL.revokeObjectURL(o);let t=document.createElement("canvas");t.width=Math.max(1,Math.round(i*r)),t.height=Math.max(1,Math.round(l*r));let a=t.getContext("2d");a?(a.fillStyle=s2,a.fillRect(0,0,t.width,t.height),a.drawImage(c,0,0,t.width,t.height),t.toBlob(e=>e?n(e):s(Error("the canvas produced no image")),s3[e],"jpeg"===e?.92:void 0)):s(Error("this browser gave no 2d context to draw into"))},c.onerror=()=>{URL.revokeObjectURL(o),s(Error("the browser could not read the serialized board"))},c.src=o}))}let l=function({doc:e,machine:t,format:n,at:s}){let a,r,i=ew(t??"")||ew(e?(e.split(/[/\\]/).pop()??e).replace(/\.smdf\.json$/i,"").replace(/\.json$/i,""):"")||"statemachine",l=e&&(a=e.match(/(?:^|[/\\-])ep(?:isode)?-?(\d{2,4})(?:[/\\-]|$)/i))?`ep${a[1]}`:null,o=l?`${l}--`:"";return`${o}${i}--${(r=e=>String(e).padStart(2,"0"))(s.getFullYear()%100)+r(s.getMonth()+1)+r(s.getDate())+r(s.getHours())+r(s.getMinutes())+r(s.getSeconds())}.${n}`}({doc:t.docPath??t.fileName??null,machine:t.definition?.settings?.name??null,format:s6[e]??String(e),at:(void 0)??new Date}),o=URL.createObjectURL(i),c=document.createElement("a");return c.href=o,c.download=l,c.click(),URL.revokeObjectURL(o),l}let s7="stateloom.layout.v1:";async function s9(){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 sZ.getState().fileName??"untitled"}function ae(){let e,t,n=sZ(e=>e.definition),s=sZ(e=>e.layout),a=sZ(e=>e.selection),r=sZ(e=>e.select),i=sZ(e=>e.clearSelection),c=sZ(e=>e.setStatePosition),d=sZ(e=>e.drawMode),h=sZ(e=>e.drawSource),u=sZ(e=>e.setDrawSource),m=sZ(e=>e.setDrawMode),p=sZ(e=>e.addTransition),f=sZ(e=>e.showContextMenu),g=sZ(e=>e.removeState),x=sZ(e=>e.undo),y=sZ(e=>e.redo),b=sZ(e=>e.errors),w=sZ(e=>e.navigationPath),v=sZ(e=>e.navigateInto),j=sZ(e=>e.navigateUp),k=sZ(e=>e.activeStates),N=sZ(e=>e.viewport),S=sZ(e=>e.setViewport);e=(0,o.useRef)(!1),t=(0,o.useRef)(null),(0,o.useEffect)(()=>{let n=!1,s=null;(async()=>{let s=await s9();if(n)return;t.current=s;let a=function(e){try{let t=window.localStorage.getItem(`${s7}${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);a&&sZ.getState().hydrateLayout(a.positions,a.viewport),e.current=!0})();let a=sZ.subscribe((n,a)=>{e.current&&t.current&&(n.layout!==a.layout||n.viewport!==a.viewport)&&(s&&clearTimeout(s),s=setTimeout(()=>{let e=sZ.getState();!function(e,t,n){try{window.localStorage.setItem(`${s7}${e}`,JSON.stringify({positions:t,viewport:n,savedAt:Date.now()}))}catch{}}(t.current,function(e,t){let n={};for(let[s,a]of Object.entries(e)){let e=t[s];e&&(a.x!==e.x||a.y!==e.y||a.width!==e.width||a.height!==e.height)&&(n[s]=a)}return n}(e.layout.positions,$(e.definition)),e.viewport)},300))});return()=>{n=!0,s&&clearTimeout(s),a()}},[]);let M=w.slice(1);return(0,l.jsx)(tP,{definition:n,positions:s.positions,path:M,rootLabel:w[0],viewport:N,onViewportChange:S,selection:{kind:"state"===a.kind||"transition"===a.kind?a.kind:null,id:a.id},activeStates:k,errorElements:b.flatMap(e=>e.element?[e.element]:[]),drawMode:"transition"===d?"transition":"select",drawSource:h,svgId:s1,pinchOwner:sG,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?r(e,t):u(t)},onClearSelection:i,onStateMove:c,onNavigateInto:v,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 at({name:e,size:t=14}){return(0,l.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",focusable:"false",className:"inline-block shrink-0 align-[-2px]",children:["undo"===e&&(0,l.jsx)("path",{d:"M9 7 4.5 11.5 9 16M5 11.5h9.5a5 5 0 0 1 0 10H12"}),"redo"===e&&(0,l.jsx)("path",{d:"M15 7l4.5 4.5L15 16M19 11.5H9.5a5 5 0 0 0 0 10H12"}),"arrange"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:"8.5",y:"3",width:"7",height:"5",rx:"1.5"}),(0,l.jsx)("rect",{x:"3",y:"16",width:"7",height:"5",rx:"1.5"}),(0,l.jsx)("rect",{x:"14",y:"16",width:"7",height:"5",rx:"1.5"}),(0,l.jsx)("path",{d:"M12 8v4M6.5 16v-2a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v2"})]}),"draw"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("circle",{cx:"5.5",cy:"18.5",r:"2"}),(0,l.jsx)("path",{d:"M7 17 18.5 5.5M11.5 5.5h7v7"})]}),"open"===e&&(0,l.jsx)("path",{d:"M3.5 7.5V18a1.5 1.5 0 0 0 1.5 1.5h14a1.5 1.5 0 0 0 1.5-1.5V9.5A1.5 1.5 0 0 0 19 8h-7l-2-2.5H5A1.5 1.5 0 0 0 3.5 7z"}),"save"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:"M5 4h11l3.5 3.5V19a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"}),(0,l.jsx)("path",{d:"M8 4v5h7V4M8 20v-6h8v6"})]}),"reload"===e&&(0,l.jsx)("path",{d:"M19.5 12a7.5 7.5 0 1 1-2.2-5.3M19.5 4v4.5H15"}),"download"===e&&(0,l.jsx)("path",{d:"M12 4v11M7.5 10.5 12 15l4.5-4.5M4.5 19.5h15"}),"image"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:"3.5",y:"5",width:"17",height:"14",rx:"1.5"}),(0,l.jsx)("circle",{cx:"9",cy:"10",r:"1.6"}),(0,l.jsx)("path",{d:"m4 17.5 5-5 4 4 2.5-2.5 4.5 4.5"})]}),"plus"===e&&(0,l.jsx)("path",{d:"M12 5v14M5 12h14"}),"check"===e&&(0,l.jsx)("path",{d:"m5 12.5 4.5 4.5L19 7.5"}),"bolt"===e&&(0,l.jsx)("path",{d:"M13 3 5.5 13.5h5.5L10 21l8-11h-5.5z"}),"scroll"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:"M6.5 3.5h8l4 4v12a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1v-15a1 1 0 0 1 1-1z"}),(0,l.jsx)("path",{d:"M14.5 3.5v4h4M8.5 12h7M8.5 15.5h7M8.5 9h3"})]}),"code"===e&&(0,l.jsx)("path",{d:"m8.5 7.5-5 4.5 5 4.5M15.5 7.5l5 4.5-5 4.5M13.5 5l-3 14"}),"trash"===e&&(0,l.jsx)("path",{d:"M4.5 6.5h15M9.5 6.5V4.5h5v2M6.5 6.5l.9 12.6a1.5 1.5 0 0 0 1.5 1.4h6.2a1.5 1.5 0 0 0 1.5-1.4l.9-12.6M10 10.5v6M14 10.5v6"}),"sliders"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:"M5 4v16M12 4v16M19 4v16"}),(0,l.jsx)("circle",{cx:"5",cy:"9",r:"2",fill:"currentColor",stroke:"none"}),(0,l.jsx)("circle",{cx:"12",cy:"15",r:"2",fill:"currentColor",stroke:"none"}),(0,l.jsx)("circle",{cx:"19",cy:"7.5",r:"2",fill:"currentColor",stroke:"none"})]}),"gear"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,l.jsx)("path",{d:"M12 3.5v2.2M12 18.3v2.2M3.5 12h2.2M18.3 12h2.2M6 6l1.6 1.6M16.4 16.4 18 18M6 18l1.6-1.6M16.4 7.6 18 6"})]})]})}function an({label:e,actions:t,onChange:n}){let s=(e,s)=>n(t.map((t,n)=>n===e?{...t,...s}:t));return(0,l.jsxs)("div",{children:[(0,l.jsxs)("div",{className:"flex items-center justify-between",children:[(0,l.jsx)("span",{className:"text-xs font-medium text-gray-500",children:e}),(0,l.jsx)("button",{onClick:()=>n([...t,{action:"code",code:""}]),className:"text-xs text-blue-500 hover:text-blue-400",children:"+ action"})]}),t.map((e,a)=>(0,l.jsxs)("div",{className:"flex items-start gap-1 mt-1",children:[(0,l.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(a,{action:e.target.value}),children:[(0,l.jsx)("option",{value:"code",children:"Code"}),(0,l.jsx)("option",{value:"timerStart",children:"Timer Start"}),(0,l.jsx)("option",{value:"timerStop",children:"Timer Stop"})]}),"code"===e.action?(0,l.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(a,{code:e.target.value})}):(0,l.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(a,{name:e.target.value})}),(0,l.jsx)("button",{onClick:()=>n(t.filter((e,t)=>t!==a)),className:"text-red-600 hover:text-red-400 text-xs mt-0.5",children:"✕"})]},a)),0===t.length&&(0,l.jsx)("span",{className:"text-xs text-gray-700 italic",children:"none"})]})}function as(){let e=sZ(e=>e.definition),t=sZ(e=>e.selection),n=sZ(e=>e.updateState),s=sZ(e=>e.removeState);sZ(e=>e.addAction),sZ(e=>e.removeAction);let a=sZ(e=>e.updateTransition),r=sZ(e=>e.removeTransition);if(!t.kind||!t.id)return(0,l.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 a=i(e.state,t.id);if(!a)return(0,l.jsx)("div",{className:"p-3 text-gray-500 text-xs",children:"State not found"});let o=a.onEntry?.actions??[],c=a.onExit?.actions??[];return(0,l.jsxs)("div",{className:"p-3 space-y-3 text-sm md:overflow-y-auto md:max-h-[calc(100vh-160px)]",children:[(0,l.jsxs)("h3",{className:"text-xs font-semibold text-gray-400",children:["State: ",a.name]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Name"}),(0,l.jsx)("input",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:a.name,onChange:e=>n(t.id,{name:e.target.value})})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Kind"}),(0,l.jsxs)("select",{className:"w-full bg-gray-800 border border-gray-700 rounded px-2 py-1 text-sm text-gray-200",value:a.kind??"normal",onChange:e=>n(t.id,{kind:e.target.value}),children:[(0,l.jsx)("option",{value:"normal",children:"Normal"}),(0,l.jsx)("option",{value:"final",children:"Final"}),(0,l.jsx)("option",{value:"history",children:"History"})]})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Description"}),(0,l.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:a.description??"",onChange:e=>n(t.id,{description:e.target.value||void 0})})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Prompt for the agent in this state"}),(0,l.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:a.prompt??"",onChange:e=>n(t.id,{prompt:e.target.value||void 0})})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Notes"}),(0,l.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:a.notes??"",onChange:e=>n(t.id,{notes:e.target.value||void 0})})]}),(0,l.jsx)(an,{label:"▸ onEntry Actions",actions:o,onChange:e=>n(t.id,{onEntry:{actions:e}})}),(0,l.jsx)(an,{label:"◂ onExit Actions",actions:c,onChange:e=>n(t.id,{onExit:{actions:e}})}),(0,l.jsxs)("div",{children:[(0,l.jsx)("span",{className:"text-xs font-medium text-gray-500",children:"Transitions"}),(a.transitions??[]).map((e,n)=>(0,l.jsxs)("div",{className:"flex items-center gap-1 text-xs text-gray-400 py-1 border-b border-gray-800/50",children:[(0,l.jsxs)("span",{className:"flex-1",children:[e.event," → ",e.nextState??"(internal)"]}),e.condition&&(0,l.jsxs)("span",{className:"text-gray-600",children:["[",e.condition,"]"]}),(0,l.jsx)("button",{onClick:()=>r(t.id,n),className:"text-red-600 hover:text-red-400",children:"✕"})]},n)),(a.transitions?.length??0)===0&&(0,l.jsx)("span",{className:"text-xs text-gray-700 italic",children:"none"})]}),(0,l.jsxs)("button",{onClick:()=>s(t.id),className:"text-red-500 hover:text-red-400 text-xs mt-2",children:[(0,l.jsx)(at,{name:"trash"})," Delete State"]})]})}if("transition"===t.kind){let[n,s]=t.id.split(":"),o=parseInt(s,10),c=i(e.state,n),d=c?.transitions?.[o];if(!d)return(0,l.jsx)("div",{className:"p-3 text-gray-500 text-xs",children:"Transition not found"});let h=sV(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,l.jsxs)("div",{className:"p-3 space-y-3 text-sm",children:[(0,l.jsx)("h3",{className:"text-xs font-semibold text-gray-400",children:"Transition"}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Event"}),(0,l.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=>a(n,o,{event:e.target.value}),children:h.map(e=>(0,l.jsx)("option",{value:e,children:e},e))})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Target State"}),(0,l.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=>a(n,o,{nextState:e.target.value||void 0}),children:[(0,l.jsx)("option",{value:"",children:"(internal transition)"}),u.map(e=>(0,l.jsx)("option",{value:e,children:e},e))]})]}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Condition (guard)"}),(0,l.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=>a(n,o,{condition:e.target.value||void 0})})]}),(0,l.jsxs)("button",{onClick:()=>r(n,o),className:"text-red-500 hover:text-red-400 text-xs",children:[(0,l.jsx)(at,{name:"trash"})," Delete Transition"]})]})}return null}let aa=["string","int","float","bool","object"];function ar(){let e=sZ(e=>e.definition),t=sZ(e=>e.addEvent),n=sZ(e=>e.updateEvent),s=sZ(e=>e.removeEvent),a=sZ(e=>e.addParameter),r=sZ(e=>e.removeParameter),i=sZ(e=>e.updateParameter),c=sZ(e=>e.updateEventSource),d=sZ(e=>e.select),h=sZ(e=>e.selection),[u,m]=(0,o.useState)(""),[p,f]=(0,o.useState)(null),[g,x]=(0,o.useState)(null);return(0,l.jsxs)("div",{className:"p-3 text-sm",children:[e.events.map((e,t)=>(0,l.jsxs)("div",{className:"mb-3",children:[(0,l.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,l.jsx)("span",{className:"text-xs font-semibold text-gray-500",children:"Source:"}),(0,l.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,l.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,l.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,l.jsx)("div",{className:"-mx-1 overflow-x-auto px-1",children:(0,l.jsxs)("table",{className:"w-full text-xs",children:[(0,l.jsx)("thead",{children:(0,l.jsxs)("tr",{className:"text-gray-600 border-b border-gray-800",children:[(0,l.jsx)("th",{className:"text-left py-1 font-medium",children:"ID"}),(0,l.jsx)("th",{className:"text-left py-1 font-medium",children:"Description"}),(0,l.jsx)("th",{className:"text-left py-1 font-medium",children:"Params"}),(0,l.jsx)("th",{className:"w-6"})]})}),(0,l.jsx)("tbody",{children:(e.events??[]).map(e=>(0,l.jsxs)(o.Fragment,{children:[(0,l.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,l.jsx)("td",{className:"py-1 pr-1",children:g===e.id?(0,l.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,l.jsx)("span",{className:"text-gray-300",onDoubleClick:t=>{t.stopPropagation(),x(e.id)},children:e.id})}),(0,l.jsx)("td",{className:"py-1 pr-1 text-gray-500 truncate max-w-[80px]",children:e.description??"—"}),(0,l.jsx)("td",{className:"py-1 text-gray-500",children:(e.parameters?.length??0)>0?e.parameters.map(e=>`${e.name}:${e.type}`).join(", "):"—"}),(0,l.jsx)("td",{className:"py-1",children:(0,l.jsx)("button",{onClick:t=>{t.stopPropagation(),s(e.id)},className:"text-red-600 hover:text-red-400",children:"✕"})})]}),p===e.id&&(0,l.jsx)("tr",{children:(0,l.jsx)("td",{colSpan:4,className:"py-2 px-1 bg-gray-900/50",children:(0,l.jsxs)("div",{className:"space-y-2",children:[(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-gray-600",children:"Description"}),(0,l.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,l.jsxs)("div",{children:[(0,l.jsx)("span",{className:"text-gray-600",children:"Parameters"}),(e.parameters??[]).map((t,n)=>(0,l.jsxs)("div",{className:"flex items-center gap-1 mt-1",children:[(0,l.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,l.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:aa.map(e=>(0,l.jsx)("option",{value:e,children:e},e))}),(0,l.jsx)("button",{onClick:()=>r(e.id,n),className:"text-red-600 hover:text-red-400",children:"✕"})]},n)),(0,l.jsx)("button",{className:"text-blue-500 hover:text-blue-400 mt-1",onClick:()=>a(e.id,{name:"param",type:"string"}),children:"+ parameter"})]}),(0,l.jsxs)("div",{className:"mt-1",children:[(0,l.jsx)("span",{className:"text-gray-600",children:"Generated method:"}),(0,l.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,l.jsxs)("div",{className:"flex gap-1 mt-2",children:[(0,l.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,l.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 ai(){let e=sZ(e=>e.definition.settings),t=sZ(e=>e.definition.settings.context),n=sZ(e=>e.updateSettings);return(0,l.jsxs)("div",{className:"p-3 space-y-3 text-sm",children:[(0,l.jsx)("h3",{className:"text-xs font-semibold text-gray-400",children:"Machine Settings"}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Namespace"}),(0,l.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,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Name"}),(0,l.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,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Description"}),(0,l.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,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Notes on this diagram"}),(0,l.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,l.jsxs)("label",{className:"flex items-center gap-2 text-sm text-gray-300",children:[(0,l.jsx)("input",{type:"checkbox",checked:e.asynchronous,onChange:e=>n({asynchronous:e.target.checked}),className:"rounded bg-gray-800 border-gray-600"}),"Asynchronous"]}),(0,l.jsx)("hr",{className:"border-gray-800"}),(0,l.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Context"}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Context Class"}),(0,l.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,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Base Class"}),(0,l.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,l.jsx)("hr",{className:"border-gray-800"}),(0,l.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Imports"}),(0,l.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,l.jsx)("hr",{className:"border-gray-800"}),(0,l.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Object References"}),(0,l.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,l.jsx)("hr",{className:"border-gray-800"}),(0,l.jsx)("h4",{className:"text-xs font-semibold text-gray-500",children:"Code Generation"}),(0,l.jsxs)("label",{className:"block",children:[(0,l.jsx)("span",{className:"text-xs text-gray-500",children:"Target Language"}),(0,l.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,l.jsx)("option",{value:"python",children:"Python"}),(0,l.jsx)("option",{value:"typescript",children:"TypeScript"}),(0,l.jsx)("option",{value:"csharp",children:"C#"})]})]})]})}function al(){let e=sZ(e=>e.errors),t=sZ(e=>e.validate),n=sZ(e=>e.select);return(0,l.jsxs)("div",{className:"p-3",children:[(0,l.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,l.jsxs)("h3",{className:"text-xs font-semibold text-gray-400",children:["Validation ",e.length>0&&(0,l.jsxs)("span",{className:"text-red-500",children:["(",e.length,")"]})]}),(0,l.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,l.jsxs)("div",{className:"flex items-center gap-2 text-green-500 text-xs",children:[(0,l.jsx)("span",{children:"✓"}),(0,l.jsx)("span",{children:"Definition is valid"})]}):(0,l.jsx)("div",{className:"space-y-0.5",children:e.map((e,t)=>(0,l.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,l.jsx)("span",{className:`font-mono text-[10px] mt-0.5 ${"error"===e.severity?"text-red-600":"text-yellow-600"}`,children:e.ruleId}),(0,l.jsx)("span",{className:`flex-1 ${"error"===e.severity?"text-red-400":"text-yellow-400"}`,children:e.message}),e.element&&(0,l.jsxs)("span",{className:"text-gray-600 text-[10px]",children:["→ ",e.element]})]},t))})]})}var ao=e.i(76800);function ac(){let e=(0,ao.useRequestedDoc)(),[t,n]=(0,o.useState)(!1),[s,a]=(0,o.useState)(""),[r,i]=(0,o.useState)(null),[c,d]=(0,o.useState)([]),[h,u]=(0,o.useState)(null),[m,p]=(0,o.useState)(null);(0,o.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),a(""),(0,ao.navigateToDoc)(e)},g=new Set((r??[]).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(s7)&&e.push(n.slice(s7.length))}return e.sort()}catch{return[]}})().filter(t=>t.startsWith("/")&&t!==e&&!g.has(t)):[],y=e??h,b=(r??[]).filter(e=>e.path!==y),w=s.trim().toLowerCase(),v=w?b.filter(e=>e.path.toLowerCase().includes(w)):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,l.jsxs)("span",{className:"relative inline-flex",children:[(0,l.jsx)("button",{onClick:()=>n(e=>!e),className:"toolbar-btn",title:e?`Document: ${e}`:"Switch document",children:"⇄"}),t&&(0,l.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,l.jsx)("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-gray-500",children:"switch document"}),(0,l.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=s.trim();if(t){if(1===v.length)return f(v[0].path);if(t.startsWith("/"))return f(t)}},className:"mb-1 flex gap-1",children:[(0,l.jsx)("input",{value:s,onChange:e=>a(e.target.value),placeholder:null===r?"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,l.jsx)("button",{type:"submit",className:"toolbar-btn",title:"Open",children:"→"})]}),(0,l.jsxs)("div",{className:"max-h-64 overflow-y-auto",children:[e&&(0,l.jsx)("button",{onClick:()=>f(null),className:j,title:"Return to the default project file",children:"⌂ default document"}),v.map(e=>(0,l.jsxs)("button",{onClick:()=>f(e.path),className:j,title:e.path,children:[e.name,(0,l.jsx)("span",{className:"ml-1 text-[10px] text-gray-600",children:e.dir})]},e.path)),x.length>0&&(0,l.jsxs)("div",{className:"mt-1 border-t border-gray-800 pt-1",children:[(0,l.jsx)("div",{className:"px-1.5 pb-0.5 text-[10px] uppercase tracking-wide text-gray-600",children:"recent"}),x.map(e=>(0,l.jsxs)("button",{onClick:()=>f(e),className:j,title:e,children:[e.split("/").pop(),(0,l.jsx)("span",{className:"ml-1 text-[10px] text-gray-600",children:e})]},e))]}),null!==r&&0===v.length&&0===x.length&&(0,l.jsx)("div",{className:"px-1.5 py-1 text-[11px] text-gray-500",children:w?"nothing matches":"no other documents here"})]}),c.length>0&&(0,l.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,l.jsxs)("div",{className:"mt-1 text-[10px] text-gray-600",children:["this server does not list documents (",m,") — type a path"]})]})]})}function ad({size:e=16}){return(0,l.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,l.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,l.jsx)("path",{d:"M12 10v4.5"}),(0,l.jsx)("path",{d:"M12 17.3v.01"})]})}function ah(){let e=sZ(e=>e.presence),[t,n]=(0,o.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 a=[...s].map(([e,t])=>t>1?`${e} \xd7${t}`:e).join(" · ");return(0,l.jsxs)("span",{className:"relative inline-flex",children:[(0,l.jsxs)("button",{onClick:()=>n(e=>!e),className:"toolbar-btn inline-flex items-center gap-1.5",title:`Connected: ${a}`,"aria-expanded":t,"aria-label":`${e.length} connected: ${a}`,children:[(0,l.jsx)("span",{className:"flex -space-x-1",children:e.slice(0,4).map(e=>(0,l.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,l.jsx)("span",{className:"tabular-nums",children:e.length})]}),t&&(0,l.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,l.jsxs)("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-gray-500",children:["connected · ",a]}),e.map(e=>(0,l.jsxs)("div",{className:"flex items-center gap-1.5 rounded px-1 py-1 text-xs text-gray-300",title:e.clientId,children:[(0,l.jsx)("span",{className:"inline-block h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:e.color??y(e.clientId)}}),(0,l.jsx)("span",{className:"shrink-0",children:e.role}),e.name&&(0,l.jsx)("span",{className:"truncate text-gray-500",children:e.name})]},e.clientId))]})]})}function au(){let e=sZ(e=>e.definition),t=sZ(e=>e.fileName),n=sZ(e=>e.docPath),s=sZ(e=>e.dirty),a=sZ(e=>e.loadFromJson),r=sZ(e=>e.exportJson),i=sZ(e=>e.addState),c=sZ(e=>e.validate),d=sZ(e=>e.showCodePreview),h=sZ(e=>e.setShowCodePreview),u=sZ(e=>e.setGeneratedCode),m=sZ(e=>e.drawMode),p=sZ(e=>e.setDrawMode),f=sZ(e=>e.arrangeLayout),g=sZ(e=>e.undo),x=sZ(e=>e.redo),y=sZ(e=>e.undoStack),b=sZ(e=>e.redoStack),w=sZ(e=>e.remoteStatus),v=sZ(e=>e.remoteMessage),j=sZ(e=>e.setRemoteStatus),k=sZ(e=>e.setRemoteMtime),$=sZ(e=>e.applyRemote),N=(0,ao.useRequestedDoc)(),S=(0,o.useRef)(null),[M,C]=(0,o.useState)(!1),[E,R]=(0,o.useState)(""),[A,O]=(0,o.useState)(!1),[_,T]=(0,o.useState)("png"),[P,I]=(0,o.useState)(!1),[L,D]=(0,o.useState)(null),[q,B]=(0,o.useState)(null),F=async()=>{let e=r();O(!0);try{let t=await fetch(`/api/file${(0,ao.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),sZ.setState({dirty:!1}),j("synced",null)}else{let e=await t.json().catch(()=>({error:"unknown"}));j("error",`Save failed: ${e.error??t.statusText}`)}}catch(e){j("error",`Save failed: ${e}`)}finally{O(!1)}},z=async()=>{I(!0),D(null);try{let s=await s8(_,{definition:e,docPath:n,fileName:t});B(s)}catch(e){D(e instanceof Error?e.message:String(e))}finally{I(!1)}},U=async()=>{try{let e=await fetch(`/api/file${(0,ao.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,o.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=r();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,l.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,l.jsxs)("div",{className:"toolbar-ident",children:[(0,l.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=>{a(e.target?.result,t.name)},n.readAsText(t),e.target.value=""},className:"hidden"}),(0,l.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,l.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,l.jsx)(ac,{}),"synced"===w&&(0,l.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===w&&(0,l.jsx)("span",{className:"text-[10px] text-amber-400",title:v??"",children:"↻ remote changed"}),"error"===w&&(0,l.jsxs)("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-red-400",title:v??"",children:[(0,l.jsx)(ad,{size:11})," disk error"]}),"idle"===w&&(0,l.jsx)("span",{className:"text-[10px] text-gray-600",title:v??"No file bound",children:"○ no disk"}),(0,l.jsx)(ah,{}),(0,l.jsx)("div",{className:"flex-1"})]}),(0,l.jsxs)("div",{className:"toolbar-strip",children:[(0,l.jsx)("button",{onClick:g,disabled:0===y.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)","aria-label":"Undo",children:(0,l.jsx)(at,{name:"undo"})}),(0,l.jsx)("button",{onClick:x,disabled:0===b.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)","aria-label":"Redo",children:(0,l.jsx)(at,{name:"redo"})}),(0,l.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,l.jsxs)("button",{onClick:f,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:[(0,l.jsx)(at,{name:"arrange"})," Arrange"]}),(0,l.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,l.jsxs)("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:[(0,l.jsx)(at,{name:"draw"})," ","transition"===m?"Drawing":"Draw"]}),(0,l.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,l.jsx)("button",{onClick:()=>S.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)","aria-label":"Open a local file",children:(0,l.jsx)(at,{name:"open"})}),(0,l.jsxs)("button",{onClick:F,disabled:A,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:[(0,l.jsx)(at,{name:"save"})," Disk"]}),(0,l.jsx)("button",{onClick:U,className:"toolbar-btn",title:"Reload from disk","aria-label":"Reload from disk",children:(0,l.jsx)(at,{name:"reload"})}),(0,l.jsx)("button",{onClick:()=>{let e=new Blob([r()],{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","aria-label":"Download as file",children:(0,l.jsx)(at,{name:"download"})}),(0,l.jsx)("select",{value:_,onChange:e=>{T(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:s5.map(e=>(0,l.jsx)("option",{value:e,children:s4[e]},e))}),(0,l.jsx)("button",{onClick:z,disabled:P,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${s4[_]}`,children:P?"…":(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(at,{name:"image"})," Export"]})}),q&&!L&&(0,l.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:q,children:["⤓ ",q]}),(0,l.jsx)("div",{className:"w-px h-4 bg-gray-700"}),M?(0,l.jsxs)("div",{className:"flex items-center gap-1",children:[(0,l.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,l.jsx)("button",{onClick:Y,className:"toolbar-btn-sm","aria-label":"Add the state",children:(0,l.jsx)(at,{name:"check"})}),(0,l.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm","aria-label":"Cancel",children:"✕"})]}):(0,l.jsxs)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:[(0,l.jsx)(at,{name:"plus"})," State"]}),(0,l.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,l.jsxs)("button",{onClick:()=>c(),className:"toolbar-btn",children:[(0,l.jsx)(at,{name:"check"})," Validate"]}),(0,l.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,l.jsx)("option",{value:"python",children:"Python"}),(0,l.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,l.jsxs)("button",{onClick:J,className:"toolbar-btn",children:[(0,l.jsx)(at,{name:"bolt"})," Generate"]}),(0,l.jsxs)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:[(0,l.jsx)(at,{name:"scroll"})," RISE"]}),(0,l.jsxs)("button",{onClick:()=>h(!d),className:`toolbar-btn ${d?"text-blue-400":""}`,children:[(0,l.jsx)(at,{name:"code"})," Code"]})]})]})}function am(){let e=sZ(e=>e.generatedCode),t=sZ(e=>e.showCodePreview),n=sZ(e=>e.setShowCodePreview);return t?(0,l.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,l.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,l.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,l.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,l.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,l.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,l.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,l.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 ap(){let e=sZ(e=>e.applyRemote),t=sZ(e=>e.setRemoteStatus),n=sZ(e=>e.setRemoteMtime),s=(0,ao.useRequestedDoc)();return(0,o.useEffect)(()=>{let a=!1,r=(0,ao.docQuery)(s);async function i(){try{let e=await fetch(`/api/file${r}`,{cache:"no-store"});if(!e.ok)return null;return await e.json()}catch{return null}}(async()=>{let n=await i();a||(n?.path&&sZ.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 l=new EventSource(`/api/watch${r}`);return l.addEventListener("hello",e=>{try{let t=JSON.parse(e.data);"number"==typeof t?.mtime&&n(t.mtime)}catch{}}),l.addEventListener("change",async s=>{let a=0;try{a=JSON.parse(s.data)?.mtime??0}catch{}if(a<=(sZ.getState().remoteMtime??0))return;let r=await i();r?.exists&&r.content&&(sZ.getState().dirty?(t("remote-changed",`Disk changed at ${new Date(r.mtime).toLocaleTimeString()} — local has unsaved edits`),n(r.mtime)):e(r.content,r.mtime,r.path.split("/").pop()))}),l.addEventListener("error",()=>{t("error","Watch stream disconnected")}),()=>{a=!0,l.close()}},[e,t,n,s]),null}function af({url:e}){let t=(0,ao.useRequestedDoc)();return(0,o.useEffect)(()=>{if(!e)return;let n=!1,s=null,a=null,r=null,i=null;return(async()=>{let l="";try{let e=await fetch(`/api/file${(0,ao.docQuery)(t)}`,{cache:"no-store"});e.ok&&(l=(await e.json())?.path??"")}catch{}n||(l&&sZ.getState().setDocPath(l),(s=s_({url:e,role:"web",docId:l,name:"web-designer",onFull:e=>{sZ.getState().applyRemote(JSON.stringify({stateMachine:e.def}),e.mtime??Date.now(),l&&l.split("/").pop()||void 0),i=e.def},onPatch:e=>{sZ.getState().applyRemoteOps(e.ops,e.mtime??Date.now(),e.seq),i=sZ.getState().definition},onPresence:e=>{sZ.getState().setPresence(e)}})).connect(),a=sZ.subscribe((e,t)=>{e.definition===t.definition||e._applyingRemote||(r&&clearTimeout(r),r=setTimeout(()=>{var e,t;let n,a;if(!s||"connected"!==s.getSnapshot().status)return;let r=sZ.getState().definition;if(null===i){s.emitFull(r),i=r;return}let l=(e=i,t=r,n=e??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:t.state.name,states:[]}},function(e,t,n){let s={},a=!1,r=new Set([...Object.keys(e.settings),...Object.keys(t.settings)]),i=e.settings,l=t.settings;for(let e of r)g(i[e],l[e])||void 0===l[e]||(s[e]=l[e],a=!0);void 0!==e.settings.notes&&void 0===t.settings.notes&&(s.notes="",a=!0),a&&n.push({op:"settings.update",patch:s})}(n,t,a=[]),function(e,t,n){let s=e.events,a=t.events,r=Math.min(s.length,a.length);for(let e=0;e<r;e++)!function(e,t,n,s){let a={},r=!1;for(let e of["name","file","feeder","description","timers"])g(t[e],n[e])||void 0===n[e]||(a[e]=n[e],r=!0);r&&s.push({op:"eventSource.update",index:e,patch:a});let i=t.events??[],l=n.events??[],o=new Set(l.map(e=>e.id));for(let e of i)o.has(e.id)||s.push({op:"event.remove",id:e.id});let c=i.filter(e=>o.has(e.id)),d=0;for(;d<l.length;){let t=l[d];d<c.length&&c[d].id===t.id?(function(e,t,n){let s={},a=!1;for(let n of["name","description","preAction","postAction"])g(e[n],t[n])||void 0===t[n]||(s[n]=t[n],a=!0);a&&n.push({op:"event.update",id:t.id,patch:s})}(c[d],t,s),function(e,t,n,s){let a=Math.min(t.length,n.length);for(let r=0;r<a;r++)if(!g(t[r],n[r])){let a={};t[r].name!==n[r].name&&(a.name=n[r].name),t[r].type!==n[r].type&&(a.type=n[r].type),s.push({op:"parameter.update",eventId:e,index:r,patch:a})}for(let t=a;t<n.length;t++)s.push({op:"parameter.add",eventId:e,parameter:n[t],index:t});for(let a=t.length-1;a>=n.length;a--)s.push({op:"parameter.remove",eventId:e,index:a})}(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],a[e],n);for(let e=s.length;e<a.length;e++)n.push({op:"eventSource.add",source:a[e]});for(let e=s.length-1;e>=a.length;e--)n.push({op:"eventSource.remove",index:e})}(n,t,a),function(e,t,n){let s=p(e.state),a=p(t.state),r=new Map(s.map(e=>[e.name,e])),i=new Map(a.map(e=>[e.name,e])),l=f(e.state),o=f(t.state),c=[];for(let e of a){if(r.has(e.name))continue;let t=o.get(e.name)??null,{states:s,transitions:a,...i}=e;n.push({op:"state.add",parent:t,state:{...i}}),a&&a.length>0&&c.push({state:e.name,transitions:a})}for(let e of a){if(!r.has(e.name))continue;let t=l.get(e.name)??null,s=o.get(e.name)??null;t!==s&&null!==s&&n.push({op:"state.nest",child:e.name,newParent:s})}for(let e of a){let t=r.get(e.name);if(!t)continue;let s={},a=!1;g(t.kind,e.kind)||void 0===e.kind||(s.kind=e.kind,a=!0),g(t.description,e.description)||void 0===e.description||(s.description=e.description,a=!0),g(t.notes,e.notes)||(s.notes=e.notes??"",a=!0),g(t.prompt,e.prompt)||(s.prompt=e.prompt??"",a=!0),a&&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 a){let t=r.get(e.name);t&&function(e,t,n,s){let a=Math.min(t.length,n.length);for(let r=0;r<a;r++){if(g(t[r],n[r]))continue;let a={};for(let e of["event","nextState","condition","description","actions"])g(t[r][e],n[r][e])||void 0===n[r][e]||(a[e]=n[r][e]);Object.keys(a).length>0&&s.push({op:"transition.update",state:e,index:r,patch:a})}for(let t=a;t<n.length;t++)s.push({op:"transition.add",state:e,transition:n[t],index:t});for(let a=t.length-1;a>=n.length;a--)s.push({op:"transition.remove",state:e,index:a})}(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 a=t.transitions??[];for(let e=a.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,a),a);0!==l.length&&(s.emitPatch(l),i=r)},60))}))})(),()=>{n=!0,r&&clearTimeout(r),a&&a(),s&&s.disconnect()}},[e,t]),null}function ag(){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 ax=null;function ay(){return ax||(ax=(async()=>{let e=ag()??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 ab(){let e=ag(),[t,n]=(0,o.useState)(e);return((0,o.useEffect)(()=>{let e=!0;return ay().then(t=>{e&&t.bridgeUrl&&n(t.bridgeUrl)}),()=>{e=!1}},[]),"string"==typeof t&&t.length>0)?(0,l.jsx)(af,{url:t}):(0,l.jsx)(ap,{})}let aw="stateloom.uiScale.v1";function av(e){return Number.isFinite(e)?Math.min(1.75,Math.max(.75,e)):1}function aj(e){"u">typeof document&&(document.documentElement.style.fontSize=`${16*av(e)}px`)}let ak=1,a$=!1,aN=new Set;function aS(){return a$||(a$=!0,ak=function(){try{let e=window.localStorage.getItem(aw);if(null===e)return 1;return av(Number.parseFloat(e))}catch{return 1}}()),ak}function aM(){return 1}function aC(e){return aN.add(e),()=>{aN.delete(e)}}function aE(e,t){let n=av(e);if(aj(n),t&&function(e){try{window.localStorage.setItem(aw,String(av(e)))}catch{}}(n),a$=!0,n!==ak)for(let e of(ak=n,aN))e()}function aR(e,t){return Math.max(1,Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY))}function aA(e,t){for(let n=0;n<e.length;n++)if(e[n].identifier===t)return e[n];return null}function aO(){let e=(0,o.useSyncExternalStore)(aC,aS,aM),t=(0,o.useRef)(null),n=(0,o.useRef)(null),s=(0,o.useRef)(null);(0,o.useEffect)(()=>{aj(e)},[e]);let a=(0,o.useCallback)(e=>{n.current=e,null===s.current&&(s.current=requestAnimationFrame(()=>{s.current=null,null!==n.current&&aE(n.current,!1)}))},[]),r=(0,o.useCallback)(()=>{n.current=null,aE(1,!0)},[]);return((0,o.useEffect)(()=>{let e=()=>{let e=t.current;if(t.current=null,!e?.engaged)return;null!==s.current&&(cancelAnimationFrame(s.current),s.current=null);let a=n.current??aS();n.current=null,aE(av(a),!0)},r=n=>{if(2!==n.touches.length){t.current&&e();return}let[s,a]=[n.touches[0],n.touches[1]];s0(s.target)||s0(a.target)||(t.current={a:s.identifier,b:a.identifier,startScale:aS(),startDist:aR(s,a),engaged:!1})},i=e=>{let n=t.current;if(!n)return;let s=aA(e.touches,n.a),r=aA(e.touches,n.b);if(!s||!r)return;e.preventDefault();let i=aR(s,r);if(!n.engaged){if(12>Math.abs(i-n.startDist))return;n.engaged=!0,n.startDist=i;return}a(av(n.startScale*(i/n.startDist)))},l=n=>{let s=t.current;s&&(aA(n.touches,s.a)&&aA(n.touches,s.b)||e())};return document.addEventListener("touchstart",r,{passive:!0,capture:!0}),document.addEventListener("touchmove",i,{passive:!1,capture:!0}),document.addEventListener("touchend",l,{passive:!0,capture:!0}),document.addEventListener("touchcancel",l,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",r,{capture:!0}),document.removeEventListener("touchmove",i,{capture:!0}),document.removeEventListener("touchend",l,{capture:!0}),document.removeEventListener("touchcancel",l,{capture:!0}),null!==s.current&&cancelAnimationFrame(s.current)}},[a]),1===e)?null:(0,l.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,l.jsxs)("span",{children:["UI ",Math.round(100*e),"%"]}),(0,l.jsx)("button",{type:"button",onClick:r,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var a_=o;class aT extends a_.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,l.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,l.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 aP({locked:e,size:t=16}){return(0,l.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,l.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,l.jsx)("path",{d:e?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function aI(e){let{onClose:t,restVh:n,tallVh:s}=e,[a,r]=(0,o.useState)(!1),[i,l]=(0,o.useState)(null),c=(0,o.useRef)(null),d=()=>{r(!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(l(null),6>Math.abs(n))return r(e=>!e);if(n<=-50)return r(!0);if(n>=80){if(a&&n<260)return r(!1);d()}},u=a?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),l(0))},onPointerMove:e=>{let t=c.current;t&&t.id===e.pointerId&&l(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 aL="stateloom:focus",aD="stateloom:focus-request",aq="stateloom:system-changed",aB="stateloom:strip-note";function aF(e){return new URLSearchParams(window.location.search).get(e)}function az(e){let[t,n]=(0,o.useState)(null);return(0,o.useEffect)(()=>{let t=()=>n(aF(e));t();let s=["popstate",ao.DOC_CHANGE_EVENT,aL,aD];for(let e of s)window.addEventListener(e,t);return()=>{for(let e of s)window.removeEventListener(e,t)}},[e]),t}function aU(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(ao.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(aD))}function aY(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(aL)))}function aH(){let[e,t]=(0,o.useState)({focus:null,nonce:0});return(0,o.useEffect)(()=>{let e=()=>t(e=>({focus:aF("focus"),nonce:e.nonce+1}));e();let n=["popstate",ao.DOC_CHANGE_EVENT,aD];for(let t of n)window.addEventListener(t,e);return()=>{for(let t of n)window.removeEventListener(t,e)}},[]),e}var aX=e.i(73340);let aV="stateloom:mark-request",aJ=null,aW="/api/companion/",aK="stateloom.companion.autoplay",aZ="stateloom.companion.episode",aG=/^\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+$/;function aQ(e){let t=e?.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}-episode-\d+-[a-z0-9-]+)\/diagrams\/[^/]+$/);return t?t[1]:null}function a0(e){try{return window.localStorage.getItem(e)}catch{return null}}function a1(e,t){try{window.localStorage.setItem(e,t)}catch{}}let a2=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})},a5=e=>"starting"===e||"recording"===e||"sending"===e,a4={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null},a3={episode:null,items:[],presence:null,waiting:null,error:null};function a6({stage:e,defaultEpisode:t}){let[n,s]=(0,o.useState)(!1),[a,r]=(0,o.useState)(()=>"0"!==a0(aK)),[i,c]=(0,o.useState)(()=>{let e=aF("episode"),n=a0(aZ);return(e&&aG.test(e)?e:null)??aQ((0,ao.requestedDoc)())??(n&&aG.test(n)?n:null)??t}),[d,h]=(0,o.useState)([]),[u,m]=(0,o.useState)(a4),[p,f]=(0,o.useState)(a3),[g,x]=(0,o.useState)(null),[y,b]=(0,o.useState)([]),[w,v]=(0,o.useState)(null),[j,k]=(0,o.useState)(null),[$,N]=(0,o.useState)(()=>Date.now()),S=(0,o.useRef)(e),M=(0,o.useRef)(i),C=(0,o.useRef)(a);(0,o.useEffect)(()=>{S.current=e,M.current=i,C.current=a});let E=(0,o.useRef)(a4),R=(0,o.useRef)(null),A=(0,o.useRef)([]),O=(0,o.useRef)(!1),_=(0,o.useRef)([]),T=(0,o.useRef)(null),P=(0,o.useRef)(null),I=(0,o.useMemo)(()=>sT({recordings:!0,speech:!1}),[]),L=e=>{R.current=e,x(e)},D=(0,o.useRef)(async()=>{}),q=(0,o.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=A.current.length;v(n?`${n} more of Mia's replies wait after this one.`:null);let a=await S.current.present(function(e,t,n="Mia"){let s=new Date(e.at),a=Number.isNaN(s.getTime())?`${n}'s reply`:`Reply at ${s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,r=!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||(r?n:null));return{settings:{namespace:"companion",name:a,author:n},steps:e.steps?.length?e.steps.map(({audio:t,...n},s)=>{let a=i(t,`api/replies/${e.id}/steps/${s}/audio`);return{...n,...a?{audio:a}:{}}}):[{say:e.text,...i(e.audio,`api/replies/${e.id}/audio`)?{audio:i(e.audio,`api/replies/${e.id}/audio`)}:{}}]}}(e,aW,"Mia"),{voice:I,origin:"Mia",from:t});if(R.current!==e.id||(L(null),O.current))return;if(!a){A.current=[];return}let r=A.current.shift();r&&!a5(E.current.state)?D.current(r):r&&A.current.unshift(r)},[I]);(0,o.useEffect)(()=>{D.current=q},[q]);let B=(0,o.useCallback)(e=>{let t=e.id;if(!C.current)return void b(e=>e.includes(t)?e:[...e,t]);if(a5(E.current.state)||R.current){b(e=>e.includes(t)?e:[...e,t]),A.current.some(e=>e.id===t)||A.current.push(e),v(a5(E.current.state)?`Mia replied at ${a2(e.at)}. Her voice waits until you have sent your take.`:`Mia replied again at ${a2(e.at)}. It plays when this one ends.`);return}D.current(e)},[]);(0,o.useEffect)(()=>{let e=function(e){let t=e.base.endsWith("/")?e.base:`${e.base}/`,n=e.fetch??((...e)=>fetch(...e)),s=e.everyMs??1e4,a=e.waitEveryMs??4e3,r=e.waitForMs??9e5,i={episode:null,items:[],presence:null,waiting:null,error:null},l=new Set,o=!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 a=u;try{var c;let p=await n(`${t}thread?episode=${encodeURIComponent(s)}&include=marks`,{cache:"no-store"}),f=await p.json();if(a!==u)return;if(!f.success)return m({error:f.error??`HTTP ${p.status}`});let g=function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)if(n&&"object"==typeof n){if("take"===n.kind&&sI(n.take))t.push({...n,text:sI(n.text),at:sI(n.at)});else if("reply"===n.kind&&sI(n.id))t.push({...n,text:sI(n.text),at:sI(n.at)});else if("mark"===n.kind&&sI(n.id)&&sI(n.doc)){let e=n.region;t.push({kind:"mark",id:sI(n.id),doc:sI(n.doc),...sI(n.drawing)?{drawing:sI(n.drawing)}:{},...sI(n.title)?{title:sI(n.title)}:{},elements:Array.isArray(n.elements)?n.elements.filter(e=>"string"==typeof e&&!!e):[],...e&&"object"==typeof e&&"number"==typeof e.x?{region:e}:{},text:sI(n.text),author:sL(n.author),at:sI(n.at),...sI(n.lastAt)?{lastAt:sI(n.lastAt)}:{},status:"answered"===n.status||"resolved"===n.status?n.status:"open",replies:(Array.isArray(n.replies)?n.replies:[]).flatMap(e=>{let t=e&&"object"==typeof e?e:{};return sI(t.text)?[{author:sL(t.author),text:sI(t.text),at:sI(t.at)}]:[]})})}}return t}(f.items),x=(c=f.presence,g.map(e=>"reply"===e.kind?`${e.id}:${+!!e.audio}:${e.feedback??""}`:"mark"===e.kind?`m${e.id}:${e.status}:${e.replies.length}`:`${e.take}:${e.text.length}`).join(",")+`|${c?.state??""}`),y=g.filter(e=>"reply"===e.kind&&!l.has(e.id));for(let e of y)l.add(e.id);if((x!==h||i.error)&&(h=x,m({items:g,presence:f.presence??null,error:null})),o)for(let t of y)e.onReply?.(t);o=!0;let b=i.waiting;b&&(g.some(e=>"reply"===e.kind&&e.take===b.take)||Date.now()-b.since>r)&&(d&&clearInterval(d),d=null,m({waiting:null}))}catch(e){a===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,l.clear(),o=!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(),a),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:aW,onChange:f,onReply:B}),t=function(e){let t,n=e.base.endsWith("/")?e.base:`${e.base}/`,s=e.fetch??((...e)=>fetch(...e)),a=e.partEveryMs??1e4,r=e.beatEveryMs??15e3,i=(t=window.MediaRecorder)&&sD.some(e=>!t.isTypeSupported||t.isTypeSupported(e))?"mp4":window.AudioContext??window.webkitAudioContext?"wav":null,l=!1!==window.isSecureContext,o=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),c=e.createRecorder??(e=>{let t,n,s,a,r,l,o,c;return"mp4"===i?new window.MediaRecorder(e,{mimeType:sD.find(e=>window.MediaRecorder.isTypeSupported?.(e)??!0)}):(n=(t=new(window.AudioContext??window.webkitAudioContext)).createMediaStreamSource(e),s=t.createScriptProcessor(4096,1,1),a=[],r=[],l=!1,o=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])));a.push(n),r.push(n)},n.connect(s),s.connect(t.destination),o=setInterval(()=>{if(!r.length)return;let e=l?[]:[sq(0x7fffffff,t.sampleRate)];l=!0,e.push(...r.map(e=>e.buffer)),r=[],c.ondataavailable?.({data:new Blob(e,{type:"audio/wav"})})},e)},stop(){o&&clearInterval(o),o=null;try{n.disconnect(),s.disconnect()}catch{}t.close().catch(()=>{}),c.whole=new Blob([sq(a.reduce((e,t)=>e+t.byteLength,0),t.sampleRate),...a.map(e=>e.buffer)],{type:"audio/wav"}),c.onstop?.()}})}),d={state:"idle",seconds:0,held:0,message:"",error:!1,stored:null,...!e.createRecorder&&(!i||!l)?{unavailable:l?"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,w=null,v=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[w,v,j])e&&clearInterval(e);w=v=j=null}function R(){try{u?.getTracks().forEach(e=>e.stop())}catch{}u=null}async function A(){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 a=await s(`${n}takes/part?${S(`&offset=${d.held}`)}`,{method:"POST",headers:{"content-type":N()},body:e.slice(d.held)}),r=await a.json();t===f&&"number"==typeof r.bytes&&h({held:r.bytes})}catch{}finally{k=!1}}async function O(){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 o({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?` ${sB(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(),w=setInterval(()=>void A(),a),v=setInterval(()=>M(!0),r),j=setInterval(()=>h({seconds:$()}),500),h({state:"recording",seconds:0,message:""})}async function _(t){h({state:"sending",message:`Sending ${sB(t.size)}, then transcribing and storing…`,error:!1});try{let a=await s(`${n}takes?${S()}`,{method:"POST",headers:{"content-type":(t.type||"audio/mp4").split(";")[0]},body:t}),r=await a.json();if(!r.success||!r.take)throw Error(r.error||`HTTP ${a.status}`);b=null,f="";let i=r.presence??{state:r.listening?"listening":"away"},l=r.transcriptError?` Transcription failed, so no session wakes yet: ${r.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 ${r.take} is in the episode.${l}`,error:!!r.transcriptError,stored:{take:r.take,english:r.english??"",transcriptError:r.transcriptError,presence:i}}),r.transcriptError||e.onStored?.(r.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?` ${sB(d.held)} of it is already stored, and becomes a take by itself if you leave.`:""}`,error:!0})}}async function T(){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 ${sB(d.held)} is stored; it becomes a take within a few minutes.`:"Nothing was recorded. Try again.",error:!0});await _(t)}async function P(){"retry"===d.state&&b&&await _(b)}return{getSnapshot:()=>d,press:async()=>"recording"===d.state?T():"retry"===d.state&&b?P():O(),start:O,stop:T,resend:P,destroy(){E(),("recording"===d.state||"starting"===d.state)&&M(!1);try{m?.stop()}catch{}R()}}}({base:aW,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(),{..._.current.length?{marks:_.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),!a5(t)||a5(e.state)||(O.current=!1,!C.current||R.current))return;let n=A.current.shift();n?D.current(n):v(null)},onStored:t=>e.waitFor(t)});return P.current=e,T.current=t,E.current=t.getSnapshot(),m(t.getSnapshot()),()=>{t.destroy(),e.destroy(),P.current=null,T.current=null}},[B]),(0,o.useEffect)(()=>{P.current?.setEpisode(i)},[i]),(0,o.useEffect)(()=>{let e=!0;return fetch(`${aW}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,o.useEffect)(()=>{if(!n||d.length)return;let e=!0;return fetch(`${aW}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,o.useRef)(null),z=(0,o.useCallback)(async(e=!1)=>{let t=S.current.lastReport()?.doc??null;if(e||t!==F.current){if(F.current=t,!t){_.current=[];return}try{let e=await fetch(`/api/marks?doc=${encodeURIComponent(t)}`,{cache:"no-store"}),n=await e.json();_.current=tf(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}}(n,t).marks,"agent").map(e=>e.id)}catch{_.current=[]}}},[]);(0,o.useEffect)(()=>{z(!0);let e=S.current.onMarks(()=>void z(!0)),t=setInterval(()=>void z(),3e3);return()=>{e(),clearInterval(t)}},[z]),(0,o.useEffect)(()=>{if(!p.waiting)return;let e=setInterval(()=>N(Date.now()),1e3);return()=>clearInterval(e)},[p.waiting]);let U=(0,o.useCallback)(()=>{let e=T.current;e&&(!a5(E.current.state)&&"retry"!==E.current.state&&R.current&&(O.current=!0,S.current.stop()),e.press())},[]),Y=(0,o.useCallback)((e,t)=>{let n=P.current?.getSnapshot().items.find(t=>"reply"===t.kind&&t.id===e);if(n){if(a5(E.current.state))return void v("Send your take first. Then press play to hear Mia.");A.current=[],O.current=!1,D.current(n,t)}},[]),H=(0,o.useCallback)(()=>{A.current=[],O.current=!1,S.current.stop()},[]),X=p.waiting?{take:p.waiting.take,seconds:Math.max(0,Math.floor(($-p.waiting.since)/1e3))}:null,{narrow:V,sheet:J,claimSheet:W,releaseSheet:K}=e;(0,o.useEffect)(()=>{n?W("talk"):K("talk")},[n,W,K]),(0,o.useEffect)(()=>()=>K("talk"),[K]);let[Z,G]=(0,o.useState)(J);Z!==J&&(G(J),V&&"card"===J&&s(!1));let Q=(0,o.useCallback)(e=>{window.matchMedia("(max-width: 767px)").matches&&s(!1),aJ={doc:e.doc,id:e.id},window.dispatchEvent(new Event(aV)),S.current.board!==e.doc&&aU({doc:e.doc,focus:null})},[]),ee=(0,l.jsx)(nk,{open:n,onOpenChange:e=>{s(e),e&&z(!0)},variant:V?"bar":"fab",onOpenMark:Q,who:"Mia",episode:i,episodes:d,onEpisode:e=>{aG.test(e)&&e!==i&&(A.current=[],b([]),v(null),c(e),a1(aZ,e))},presence:p.presence,recorder:u,onRecord:U,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:a,onAutoplay:e=>{r(e),a1(aK,e?"1":"0"),e||(A.current=[])},waiting:X,notice:w,error:j??p.error});if(V){let t=n?e.sheetBody:e.sheetHandle;return t?(0,aX.createPortal)(ee,t):null}return(0,l.jsx)("div",{className:"stage-talk-host",children:ee})}let a8=(0,o.createContext)(null);function a7(){return(0,o.useContext)(a8)}let a9="stateloom.stage.voice",re="stateloom.author";function rt(e){try{return window.localStorage.getItem(e)??""}catch{return""}}function rn(e,t){try{window.localStorage.setItem(e,t)}catch{}}let rs=new Map;function ra({children:e}){var t;let n,s,a,r,i,c,d,h,[u,m]=(0,o.useState)({bridgeUrl:null,stage:ti,companion:!1,companionEpisode:null});(0,o.useEffect)(()=>{let e=!0;return ay().then(t=>{if(!e)return;let n=aF("stage"),s=to(n)?n:to(t.stage)?t.stage:ti;m({bridgeUrl:t.bridgeUrl,stage:s,companion:t.companion,companionEpisode:t.companionEpisode})}),()=>{e=!1}},[]);let[p,f]=(0,o.useState)(()=>"1"===rt(a9)),[g,x]=(0,o.useState)(()=>rt(re)),y=(0,o.useMemo)(()=>p?sT():null,[p]),b=(0,o.useMemo)(()=>(function(e={}){let t=window,n=t.SpeechRecognition??t.webkitSpeechRecognition;if(!n)return null;let s=null;return{start(t,a){s?.stop();let r=new n;s=r,r.lang=e.lang??("u">typeof navigator?navigator.language:"en-US"),r.continuous=!0,r.interimResults=!0;let i="";r.onresult=e=>{let n="";for(let t=e.resultIndex;t<e.results.length;t++){let s=e.results[t],a=s[0]?.transcript??"";s.isFinal?i=sP(i,a):n=sP(n,a)}t(sP(i,n).trim(),""===n)},r.onerror=e=>a?.(e.error??"error"),r.onend=()=>{s===r&&(s=null),a?.()},r.start()},stop(){s?.stop(),s=null}}})(),[]),[w,v]=(0,o.useState)(null),j=(0,o.useRef)(new Set),[k,$]=(0,o.useState)(null),[N,S]=(0,o.useState)(null),M=(0,o.useRef)(null),C=(0,o.useCallback)(e=>S({doc:e,from:M.current}),[]),E=(0,o.useCallback)(e=>{M.current=e,$(e)},[]),R=(0,o.useCallback)(e=>{if(!e)return void v(null);let{step:t}=e,n=(0,ao.requestedDoc)();if(e.caught&&aF("doc"))return void v({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce});if(t.doc&&t.doc!==n)C(t.doc),aU({doc:t.doc,system:t.system??void 0,focus:t.focus??null});else if(t.focus)if(t.system&&aF("system")!==t.system&&n)aU({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(aD))}v({doc:t.doc,focus:t.focus,spotlight:t.spotlight,region:t.region,nonce:e.nonce})},[C]),A=(t={url:u.bridgeUrl??"",stage:u.stage,name:"web-stage",voice:y,enabled:!!u.bridgeUrl,onShow:R,onMarks:e=>{for(let t of[...j.current])t(e)}},(n=(0,o.useRef)({onShow:t.onShow,onMarks:t.onMarks})).current={onShow:t.onShow,onMarks:t.onMarks},s=(0,o.useRef)(null),a=`${t.url}\u0000${t.stage??""}\u0000${t.token??""}`,r=(0,o.useRef)(a),(null===s.current||r.current!==a)&&(r.current=a,s.current=function(e){let t,n=to(e.stage)?e.stage:ti,s=e.setTimer??((e,t)=>setTimeout(e,t)),a=e.clearTimer??(e=>clearTimeout(e)),r=e.gapMs??900,i=e.client??sA({url:e.url,role:e.role??"web",docId:`stage:${n}`,name:e.name??"web-stage",token:e.token,autoResync:!1}),l=e.voice??null,o=e=>e&&void 0!==t?t:l,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,w=null,v=0,j=!1,k=!1,$=!1,N=!1,S=0,M=!1,C={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!1},E=new Set;function R(){for(let e of(C={status:i.status,stage:n,shown:u,tour:m,index:g,playing:x,speaking:y,ownVoice:!!m&&void 0!==t},[...E]))e()}function A(){v+=1,w&&a(w),w=null,y&&c?.cancel(),y=!1,c=null}function O(e,t,n=t){A();let a=++v,i=()=>{a!==v||(y&&(y=!1,R()),t&&x&&(w=s(()=>{w=null,a===v&&x&&D()},l?r:0)))},l=o(n);l?(y=!0,c=l,R(),l.speak(e).then(i,i)):t&&(w=s(()=>{w=null,i()},ty(e)))}function _(t,n){b+=1,A(),u=t?{...t,nonce:b,...M?{caught:!0}:{}}:null,R(),e.onShow?.(u);let s=!!u&&null!==u.index;u&&(o(s)||n)&&O(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 P(e,n,s){var a;let r,i;h(!1),t=s;let l=Array.isArray(e.tour?.steps)?e.tour.steps:[];a=(m={def:{...e.tour,steps:l},path:e.path,origin:e.origin}).def,i=void 0,p=a.steps.map(e=>i=e.doc??i),f=l.map(e=>r=e.system??r),g=Math.min(Math.max(0,e.from??0),Math.max(0,l.length-1)),j=!1,x=n&&l.length>0,_(T(g),x)}function I(e){x=!1,_({step:e.step,index:null,count:null,title:e.title,origin:e.origin,tourPath:e.tour},!1)}function L(e){if(!m)return;let t=m.def.steps.length-1;t<0||(j=!1,_(T(g=Math.min(Math.max(0,Math.floor(e)),t)),x))}function D(){if(m){if(g>=m.def.steps.length-1){let e=x;j=x||j,x=!1,A(),R(),e&&h(!0);return}L(g+1)}}function q(){m&&g>0&&L(g-1)}function B(){m&&m.def.steps.length&&(x=!0,j&&(j=!1,g=0),u?.index!==g||u.caught?_(T(g),!0):(R(),O(u.step,!0)))}function F(){x=!1,A(),R()}function z(){h(!1),t=void 0,j=!1,m=null,p=[],f=[],g=0,x=!1,_(null,!1)}function U(){if(N)return;N=!0;let e=++S;i.joinStage(n).then(({state:t})=>{e===S&&(N=!1,$=!0,u||m||function(e){M=!0;try{e.tour&&P(e.tour,!1),e.step&&I(e.step)}finally{M=!1}}(t),R())}).catch(()=>{e===S&&(N=!1,R())})}return i.on("stage-step",e=>{e?.stage===n&&e.step&&I(e)}),i.on("stage-load",e=>{e?.stage===n&&e.tour&&P(e,!1!==e.autoplay)}),i.on("stage-control",e=>{e?.stage===n&&function(e){switch(e.action){case"play":return B();case"pause":return F();case"next":return D();case"prev":return q();case"goto":return L(e.index??0);case"stop":return z()}}(e)}),i.on("marks",t=>e.onMarks?.(t)),i.on("status",e=>{"disconnected"===e||"error"===e?$=!1:"connected"===e&&k&&!$&&U(),R()}),{getSnapshot:()=>C,subscribe:e=>(E.add(e),()=>{E.delete(e)}),connect(){k=!0,U()},disconnect(){k=!1,S+=1,N=!1,$=!1,A(),i.leaveStage(n),i.disconnect()},play:B,pause:F,next:D,prev:q,goto:L,stop:z,dismiss:function(){if(u){if(null===u.index&&m)return void _(T(g),!1);null===u.index?_(null,!1):z()}},setVoice(e){void 0===t&&A(),l=e,R()},present:(e,t={})=>Array.isArray(e?.steps)&&e.steps.length?new Promise(s=>{P({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,o.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),d=!1!==t.enabled&&!!t.url,(0,o.useEffect)(()=>{if(d)return i.connect(),()=>i.disconnect()},[i,d]),h=t.voice??null,(0,o.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}),O=(0,o.useRef)(null),_=(0,o.useRef)(null),T=A.sendContext,P=(0,o.useCallback)(e=>{O.current={...e,stage:u.stage,who:g||void 0,at:new Date().toISOString()},_.current&&clearTimeout(_.current),_.current=setTimeout(()=>T({...e,who:g||void 0}),400)},[u.stage,g,T]);(0,o.useEffect)(()=>()=>{_.current&&clearTimeout(_.current)},[]),(0,o.useEffect)(()=>{O.current&&T({...O.current,who:g||void 0})},[A.index,A.playing,A.tour,T,g]);let[I,L]=(0,o.useState)(0),D=function(e="(max-width: 599px)"){let[t,n]=(0,o.useState)(()=>(function(e){try{return"function"==typeof window.matchMedia&&window.matchMedia(e).matches}catch{return!1}})(e));return(0,o.useEffect)(()=>{if("function"!=typeof window.matchMedia)return;let t=window.matchMedia(e),s=()=>n(t.matches);return s(),t.addEventListener("change",s),()=>t.removeEventListener("change",s)},[e]),t}(),[q,B]=(0,o.useState)(null),F=(0,o.useCallback)(e=>B(e),[]),z=(0,o.useCallback)(e=>B(t=>t===e?null:t),[]),[U,Y]=(0,o.useState)(null),[H,X]=(0,o.useState)(null),V=A.shown?.step??null,J=aF("doc"),W=k??(J&&!eU(J)?J:null),K=N&&N.from===k?N.doc:null,Z=V?.doc&&V.doc!==W&&V.doc!==K?V.doc:null,[G,Q]=(0,o.useState)(null);(0,o.useEffect)(()=>{let e;if(!Z)return;let t=!0;return(!(e=rs.get(Z))&&(e=fetch(`/api/file?doc=${encodeURIComponent(Z)}`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{let t=e?.content?JSON.parse(e.content):null,n=(t?.settings??t?.stateMachine?.settings)?.name;return"string"==typeof n&&n?n:null}).catch(()=>null),rs.set(Z,e)),e).then(e=>t&&Q({doc:Z,title:e})),()=>{t=!1}},[Z]);let ee=A.play,et=(0,o.useMemo)(()=>{if(!Z||!V)return null;let e=(G?.doc===Z?G.title:null)??(Z.split("/").pop()??Z).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$/i,"").replace(/\.json$/i,""),t=A.shown?.index!==null&&A.shown?.index!==void 0;return{drawing:e,label:t?"Open and play":"Open the drawing",onOpen:()=>{C(Z),aU({doc:Z,system:V.system??void 0,focus:V.focus??null}),t&&ee()}}},[Z,G,V,A.shown?.index,ee,C]),en=!!A.shown&&!D;(0,o.useEffect)(()=>{let e=document.documentElement,t=en?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")}},[en]);let es=(0,o.useMemo)(()=>({stage:u.stage,connected:"connected"===A.status,lit:w,author:g,setAuthor:e=>{x(e),rn(re,e)},listener:b,answerNonce:I,report:P,lastReport:()=>O.current,sendMarks:A.sendMarks,onMarks:e=>(j.current.add(e),()=>{j.current.delete(e)}),shown:A.shown,present:A.present,companion:u.companion,pause:A.pause,stop:A.stop,board:k,setBoard:E,narrow:D,sheet:q,claimSheet:F,releaseSheet:z,sheetHandle:U,sheetBody:H}),[u.stage,u.companion,A.status,A.shown,A.sendMarks,A.present,A.pause,A.stop,w,g,b,I,P,k,E,D,q,F,z,U,H]),ea=A.shown?(0,l.jsx)(ni,{shown:A.shown,playing:A.playing,speaking:A.speaking,voice:A.ownVoice?void 0:p,onToggleVoice:()=>{let e=!p;f(e),rn(a9,e?"1":"0")},onPlay:A.play,onPause:A.pause,onNext:A.next,onPrev:A.prev,onGoto:A.goto,onClose:A.dismiss,onAnswer:()=>L(e=>e+1),held:et}):null;return(0,l.jsxs)(a8.Provider,{value:es,children:[e,D?(0,l.jsxs)("div",{className:"stage-sheet",children:[(0,l.jsx)("div",{className:"stage-sheet-handle",ref:Y}),(0,l.jsx)("div",{className:"stage-sheet-body",ref:X}),!q&&ea&&(0,l.jsx)("div",{className:"stage-sheet-caption",children:ea})]}):ea&&(0,l.jsx)("div",{className:"stage-caption-host",children:ea}),u.companion&&(0,l.jsx)(a6,{stage:es,defaultEpisode:u.companionEpisode})]})}let rr="stage-quiet-btn 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";function ri(e){let t=1/0;for(let n of[".stage-sheet",".stage-caption-host .slc-stage-caption"]){let s=document.querySelector(n)?.getBoundingClientRect();s&&s.height>0&&s.top<e.bottom&&(t=Math.min(t,s.top))}return t===1/0?0:Math.max(0,e.bottom-t+8)}async function rl(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 ro({docPath:e,kind:t,viewport:n,setViewport:s,boxes:a,boardRef:r,focus:i=null,level:c,onReveal:d,labels:h}){let u,m=a7(),[p,f]=(0,o.useState)([]),[g,x]=(0,o.useState)(!1),[y,b]=(0,o.useState)(null),[w,v]=(0,o.useState)(null),[j,k]=(0,o.useState)(!1),[$,N]=(0,o.useState)(!1),[S,M]=(0,o.useState)(null),[C,E]=(0,o.useState)(!1),[R,A]=(0,o.useState)(null),O=(0,o.useRef)(null),_=(0,o.useRef)(null);_.current=w;let{read:T,markRead:P}=function(e){let[t,n]=(0,o.useState)(()=>({doc:e,read:e?ng(e):{}}));(0,o.useEffect)(()=>{n(t=>t.doc===e?t:{doc:e,read:e?ng(e):{}})},[e]);let s=(0,o.useCallback)(t=>{e&&n(n=>{let s=n.doc===e?n.read:ng(e);if(s[t.id]===(t.replies?.length??0)&&n.doc===e)return n;let a={...s,[t.id]:t.replies?.length??0};try{window.localStorage.setItem(nf(e),JSON.stringify(a))}catch{}return{doc:e,read:a}})},[e]);return{read:t.doc===e?t.read:{},markRead:s}}(e),I=m?.setBoard;(0,o.useEffect)(()=>{if(I&&e)return I(e),()=>I(null)},[I,e]);let L=(0,o.useCallback)((e,t={})=>{let n=r.current?.getBoundingClientRect();if(!n?.width||!e.length)return;let a=ri(n),i=Math.max(.4*n.height,n.height-a);s(function(e,t,n,s={}){let a=s.padding??48,r=s.floor??.55,i=H(e,t,n,{padding:a,maxScale:s.maxScale??1});if(!e.length||i.scale>=r)return i;let l=1/0,o=1/0,c=-1/0,d=-1/0;for(let t of e)l=Math.min(l,t.x),o=Math.min(o,t.y),c=Math.max(c,t.x+t.width),d=Math.max(d,t.y+t.height);let h=(c-l)*r,u=(d-o)*r;return{x:h<=t-2*a?(t-h)/2-l*r:a-l*r,y:u<=n-2*a?(n-u)/2-o*r:a-o*r,scale:r}}(e,n.width,i,{padding:48,maxScale:1,floor:t.floor??.2}))},[r,s]),D=(0,o.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)&&f(e.marks)).catch(()=>{})},[e]);(0,o.useEffect)(()=>(f([]),v(null),b(null),D(),window.addEventListener("focus",D),()=>window.removeEventListener("focus",D)),[D]),(0,o.useEffect)(()=>m?.onMarks(t=>{if(!e||t.docId!==e||!Array.isArray(t.marks))return;f(t.marks);let n=function(e){let t=e.change;if(!t||"reply"!==t.action&&"add"!==t.action||!Array.isArray(e.marks))return null;let n=e.marks.findIndex(e=>e&&e.id===t.id);if(n<0)return null;let s=e.marks[n];if("add"===t.action)return s.author?.role==="agent"?{action:"add",mark:s,number:n+1,name:s.author.name||"the agent"}:null;let a=s.replies?.[s.replies.length-1];return a&&a.author?.role==="agent"?{action:"reply",mark:s,number:n+1,name:a.author.name||"the agent"}:null}(t);n&&n.mark.id!==_.current&&(A({id:n.mark.id,text:"reply"===n.action?`${n.name} answered mark ${n.number}`:`${n.name} asked about mark ${n.number}`}),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>A(null),7e3))}),[m,e]),(0,o.useEffect)(()=>(A(null),()=>{O.current&&clearTimeout(O.current)}),[e]);let q=async t=>{if(!e)return!1;N(!0),M(null);try{let n=await rl(e,t);return f(n.marks),m?.sendMarks({docId:e,marks:n.marks,change:n.change}),!0}catch(e){return M(e instanceof Error?e.message:String(e)),!1}finally{N(!1)}},B=m?.lit??null,z=B&&(!B.doc||B.doc===e)?B:null,U=z?.spotlight,Y=z?.region??null,X=(0,o.useRef)(-1),V=(0,o.useRef)(-1),J=(0,o.useRef)(null),W=(0,o.useMemo)(()=>U?.length?tv(a,U):[],[a,U]);(0,o.useEffect)(()=>{if(!z||X.current===z.nonce)return;let e=[...W,...Y?[Y]:[]];if(!e.length){U?.length&&V.current!==z.nonce&&(V.current=z.nonce,d?.(U));return}X.current=z.nonce;let t=()=>L(e);t(),J.current&&clearTimeout(J.current),J.current=setTimeout(t,520)},[z,W,Y,U,L,d]),(0,o.useEffect)(()=>()=>{J.current&&clearTimeout(J.current)},[]);let K=(0,o.useRef)(null),Z=(0,o.useRef)([]),G=(0,o.useRef)(n);G.current=n,(0,o.useEffect)(()=>{if(!e||K.current===e)return;if(z){K.current=e;return}let t=p.filter(e=>"resolved"!==e.status&&(!e.level||!c||e.level===c));if(!t.length||!a.length)return;let n=t.filter(e=>e.elements?.length),s=n.filter(e=>tv(a,e.elements).length>0);if(n.length&&!s.length)return;let l=[...s,...t.filter(e=>!e.elements?.length)].map(e=>tW(e,a)).filter(e=>!!e);if(K.current=e,!l.length)return;let o=[...l,...i?tv(a,[i]):[]],d=()=>{let e=r.current?.getBoundingClientRect();if(!e?.width)return;let t=G.current,n=F(t,{x:0,y:0}),s=F(t,{x:e.width,y:e.height-ri(e)});o.every(e=>e.x>=n.x&&e.y>=n.y&&e.x+e.width<=s.x&&e.y+e.height<=s.y)||L(o,{floor:.55})};for(let e of(d(),Z.current))clearTimeout(e);Z.current=[setTimeout(d,520),setTimeout(d,1400)]},[e,p,a,z,c,i,L,r]),(0,o.useEffect)(()=>()=>{for(let e of Z.current)clearTimeout(e)},[]);let Q=(0,o.useRef)(m?.answerNonce??0);(0,o.useEffect)(()=>{if(!m||m.answerNonce===Q.current)return;Q.current=m.answerNonce;let e=U?.length?[...U]:z?.focus?[z.focus]:i?[i]:[];k(!1),v(null),b({elements:e,region:Y??void 0,listen:!!m.listener})},[m,U,z,i,Y]);let ee=m?.report;(0,o.useEffect)(()=>{if(!ee||!e)return;let s=r.current?.getBoundingClientRect(),a=F(n,{x:0,y:0}),l=s?F(n,{x:s.width,y:s.height}):a;ee({doc:e,kind:t,system:aF("system")??void 0,focus:i,...s?.width?{visible:{x:Math.round(a.x),y:Math.round(a.y),width:Math.round(l.x-a.x),height:Math.round(l.y-a.y)}}:{}})},[ee,e,t,i,n,r]);let et=m?.companion?aQ(e):null,en=function(e,t){let n;if(!e||!t)return null;let s=(n=t.match(/-episode-(\d+)-/))?Number(n[1]):null,a=null===s?"this episode":`episode ${s}`;switch(e){case"listening":return`Mia is listening in ${a}: she answers here`;case"answering":return"Mia is answering";case"answered":return`Mia has answered in ${a}: your mark waits until she listens again`;case"away":return`No seat is listening in ${a}: your mark waits until one does`;default:return null}}(function(e,t){let[n,s]=(0,o.useState)(null);return(0,o.useEffect)(()=>{if(!e||!t)return;let n=!0,a=async()=>{if("u"<typeof document||"visible"===document.visibilityState)try{let t=await fetch(`/api/companion/thread?episode=${encodeURIComponent(e)}`,{cache:"no-store"}),a=await t.json();n&&s({episode:e,state:a.success?a.presence?.state??null:null})}catch{n&&s({episode:e,state:null})}};a();let r=setInterval(()=>void a(),1e4);return()=>{n=!1,clearInterval(r)}},[e,t]),n&&n.episode===e?n.state:null}(et,!!(y||w||j)),et),es=(0,o.useMemo)(()=>tx(p,T).map(e=>e.id),[p,T]),ea=function(e,t={}){return{forYou:tf(e,"person").length,forAgent:tf(e,"agent").length,unread:tx(e,t).length}}(p,T),er=p.find(e=>e.id===w)??null,ei=er?.replies?.length??0;(0,o.useEffect)(()=>{er&&P(er)},[er?.id,ei,P]);let el=(0,o.useCallback)(e=>{b(null),k(!1),x(!1),v(e),A(null)},[]);(0,o.useEffect)(()=>{let t=()=>{let t=e&&aJ?.doc===e?aJ.id:null,n=t?p.find(e=>e.id===t):null;if(!n)return;aJ=null,el(n.id);let s=tW(n,a);s&&setTimeout(()=>L([s],{floor:.55}),60)};return t(),window.addEventListener(aV,t),()=>window.removeEventListener(aV,t)},[e,p,a,el,L]);let eo=!!(y||er||j),ec=m?.claimSheet,ed=m?.releaseSheet;(0,o.useEffect)(()=>{eo?ec?.("card"):ed?.("card")},[eo,ec,ed]),(0,o.useEffect)(()=>()=>ed?.("card"),[ed]);let eh=!!m?.narrow,eu=m?.sheet??null,[em,ep]=(0,o.useState)(eu);em!==eu&&(ep(eu),eh&&"talk"===eu&&(b(null),v(null),k(!1)));let ef=(0,o.useRef)(null),[eg,ex]=(0,o.useState)(null);(0,o.useEffect)(()=>{let e=ef.current;if(!e)return;let t=()=>{let t={x:e.offsetLeft,y:e.offsetTop,width:e.offsetWidth,height:e.offsetHeight};ex(e=>e&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height?e:t)};if(t(),window.addEventListener("resize",t),"u"<typeof ResizeObserver)return()=>window.removeEventListener("resize",t);let n=new ResizeObserver(t);return n.observe(e),()=>{n.disconnect(),window.removeEventListener("resize",t)}},[e]);let[ey,eb]=(0,o.useState)(null),ew=m?.shown??null;(0,o.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>document.querySelector(".stage-sheet")??document.querySelector(".stage-caption-host .slc-stage-caption"),n=0,s=()=>{cancelAnimationFrame(n),n=requestAnimationFrame(()=>{let n=e.getBoundingClientRect(),s=t()?.getBoundingClientRect(),a=s&&s.height>0&&s.top<n.bottom?{x:s.left-n.left,y:s.top-n.top,width:s.width,height:Math.min(s.bottom,n.bottom)-s.top}:null;eb(e=>e&&a&&e.x===a.x&&e.y===a.y&&e.width===a.width&&e.height===a.height?e:a)})};s();let a=t(),i=a&&"u">typeof ResizeObserver?new ResizeObserver(s):null;return a&&i?.observe(a),window.addEventListener("resize",s),()=>{cancelAnimationFrame(n),i?.disconnect(),window.removeEventListener("resize",s)}},[r,ew,eo,eu,eh,e]);let ev=(0,o.useMemo)(()=>[eg,ey].filter(e=>!!e),[eg,ey]);return e?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)(tK,{viewport:n,boxes:a,spotlight:U,region:Y,marks:p,unread:es,selectedMark:w,onSelectMark:e=>{b(null),k(!1),v(t=>t===e?null:e)},marking:g,onDraft:e=>{x(!1),v(null),k(!1),A(null),b(e)},draft:y,avoid:ev}),(0,l.jsxs)("div",{className:"stage-board-controls",ref:ef,children:[R&&(0,l.jsx)(np,{className:"stage-board-notice",onOpen:()=>el(R.id),onDismiss:()=>A(null),children:R.text}),(0,l.jsxs)("button",{type:"button",className:`${rr} ${g?"!border-amber-400 !text-amber-300":""}`,"aria-pressed":g,onClick:()=>{b(null),x(e=>!e)},title:g?"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,l.jsx)(na,{}),g&&(0,l.jsx)("span",{className:"text-xs",children:"marking"})]}),(0,l.jsxs)("button",{type:"button",className:rr,"aria-expanded":j,onClick:()=>{b(null),v(null),A(null),k(e=>!e)},title:`Marks on this drawing${ea.forYou?` \xb7 ${ea.forYou} for you`:""}${ea.forAgent?` \xb7 ${ea.forAgent} waiting on the agent`:""}`,"aria-label":`Marks on this drawing: ${ea.forYou} for you${ea.unread?` (${ea.unread} new)`:""}, ${ea.forAgent} waiting on the agent`,children:[(0,l.jsx)(t3,{}),ea.forYou>0&&(0,l.jsxs)("span",{className:`stage-for-you${ea.unread?" stage-for-you--new":""}`,children:[ea.forYou," for you"]}),ea.forAgent>0&&(0,l.jsx)("span",{className:"text-xs text-gray-400",children:ea.forAgent})]})]}),g&&!y&&!R&&(0,l.jsx)("div",{className:"stage-board-hint",role:"status",children:"Tap an element, or drag around several, to say something about it."}),eo&&(u=y?(0,l.jsx)(nh,{elements:y.elements,region:y.region,author:m?.author??"",onAuthorChange:m?.setAuthor,listener:m?.listener,listenAtOnce:!!y.listen,busy:$,error:S,note:en,labels:h,onCancel:()=>{b(null),M(null)},onSubmit:async({text:e,kind:t,author:n})=>{await q({action:"add",mark:{text:e,kind:t,elements:y.elements,region:y.region,level:c,author:{name:n||"someone"}}})&&b(null)}},`${y.elements.join(",")}|${y.region?JSON.stringify(y.region):""}`):er?(0,l.jsx)(nu,{mark:er,number:p.indexOf(er)+1,listener:m?.listener,busy:$,error:S,note:en,labels:h,onClose:()=>v(null),onReply:e=>void q({action:"reply",id:er.id,text:e,author:{name:m?.author||"someone"}}),onResolve:()=>void q({action:"resolve",id:er.id}),onReopen:()=>void q({action:"reopen",id:er.id}),onRemove:async()=>{await q({action:"remove",id:er.id})&&v(null)}}):(0,l.jsx)(nm,{marks:p,unread:es,selected:w,onSelect:e=>{k(!1),v(e)},onCopy:()=>{var t,n;let s,a;if(!e)return;let r=(t=m?.lastReport()??null,s=(n=[{doc:e,marks:p.filter(e=>"resolved"!==e.status)}]).reduce((e,t)=>e+t.marks.length,0),a=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 ${tj(e.doc)}${e.kind?` (${e.kind})`:""}`];e.system&&t.push(`as a member of ${tj(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?`${a}
11
+ ${s} mark(s):
12
+ ${function(e,t={}){let n=[],s=t.start??1;for(let{doc:t,marks:a}of e)for(let e of a){for(let a of(n.push(`${s}. [${e.status} \xb7 ${e.kind}] ${e.author.name}${"agent"===e.author.role?" (agent)":""} on ${function(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"}(e)} (${tj(t)}) — ${e.id}`),n.push(` "${tk(e.text)}"`),e.replies??[]))n.push(` ↳ ${a.author.name}${"agent"===a.author.role?" (agent)":""}: "${tk(a.text)}"`);s++}return n.join("\n")}(n)}`:`${a}
13
+ No marks.`);navigator.clipboard?.writeText(r).then(()=>{E(!0),setTimeout(()=>E(!1),2e3)})},copied:C,note:en,labels:h,onClose:()=>k(!1)}),eh&&m?.sheetBody?(0,aX.createPortal)(u,m.sheetBody):(0,l.jsx)("div",{className:"stage-board-card",children:u}))]}):null}function rc({docPath:e,onReveal:t}){let n=a7(),s=n?.lit??null,a=(0,o.useRef)(-1);return(0,o.useEffect)(()=>{!s||a.current===s.nonce||s.doc&&s.doc!==e||(s.spotlight?.length||s.region)&&(a.current=s.nonce,t())},[s,e,t]),null}function rd(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 rh=(e,t)=>"chen"===t?`stateloom:erd-layout:chen:${e}`:`stateloom:erd-layout:${e}`,ru="stateloom:erd-notation",rm="stateloom:erd-lock";function rp(e,t){try{return JSON.parse(localStorage.getItem(rh(e,t))??"{}")}catch{return{}}}async function rf(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,ao.docQuery)(e)}`,{cache:"no-store"})).json(),n=JSON.parse(t.content??"null"),a=ex(n?.stateMachine??n?.StateMachine??n);a?.state&&s.push({path:e,def:a})}catch{}return s}let rg="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",rx="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",ry="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function rb(){let e=(0,ao.useRequestedDoc)(),[t,n]=(0,o.useState)(""),[s,a]=(0,o.useState)(null),[r,i]=(0,o.useState)({}),[c,d]=(0,o.useState)("crowsfoot"),[h,u]=(0,o.useState)(!1),[m,p]=(0,o.useState)({...q}),[f,g]=(0,o.useState)(0),[x,y]=(0,o.useState)(null),[b,w]=(0,o.useState)({text:"loading…",tone:"ok"}),v=(0,o.useCallback)((e,t="ok")=>w({text:e,tone:t}),[]),[j,k]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,o.useState)("entities"),[S,M]=(0,o.useState)(!1),[C,E]=(0,o.useState)(!1),[R,A]=(0,o.useState)(!1),O=(0,o.useRef)(null),_=aI({onClose:()=>M(!1),restVh:62,tallVh:92}),[T,P]=(0,o.useState)(0),[I,L]=(0,o.useState)(null),D=(0,o.useRef)(null);(0,o.useEffect)(()=>{let t=!1,s=null;return(async()=>{let r=await (await fetch(`/api/file${(0,ao.docQuery)(e)}`,{cache:"no-store"})).json();if(t)return;if(r.error)return v(r.error,"warn");let l=r.path??"",o=null;try{let e=r.content?ex(JSON.parse(r.content)):null;K(e)&&(o={...e,relationships:e.relationships??[]})}catch{}if(r.exists&&!o)return v(`${l} is not a readable ERD definition`,"warn");let c=(l.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),h=function(){try{return"chen"===localStorage.getItem(ru)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();n(l),a(o??{settings:{namespace:"Default",name:c},entities:[],relationships:[]}),d(h),u(function(){try{let e=localStorage.getItem(rm);if(null!==e)return"1"===e;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),i(rp(l,h)),y(null),L(null),g(e=>e+1),v(r.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:m}=await ay();!t&&m&&(D.current=s=s_({url:m,role:"web",docId:l,name:"web-designer",onFull:e=>{let t=e.def;K(t)&&(a({...t,relationships:t.relationships??[]}),v("updated live"))},onPatch:()=>{},onPresence:e=>P(e.length)}),s.connect())})().catch(e=>!t&&v(String(e),"warn")),()=>{t=!0,D.current=null,s?.disconnect()}},[e,v]);let B=(0,o.useMemo)(()=>{if(!s)return{};let e=rd(()=>(function(e,t={}){let n=t.notation??"crowsfoot",s=t.hSpacing??70,a=t.vSpacing??("chen"===n?130:90),r="chen"===n?ed:eb,i=[],l=new Set;for(let t of e.entities??[])!t?.name||l.has(t.name)||(l.add(t.name),i.push(t));let o=new Map,c=(e,t,n=new Set)=>e===t||!n.has(e)&&(n.add(e),(o.get(e)??[]).some(e=>c(e,t,n)));for(let t of e.relationships??[]){if(!t||!l.has(t.from)||!l.has(t.to)||t.from===t.to)continue;let[e,n]="N:1"===t.cardinality?[t.to,t.from]:[t.from,t.to];if((o.get(e)??[]).includes(n)||c(n,e))continue;let s=o.get(e);s?s.push(n):o.set(e,[n])}let d=new Map,h=(e,t)=>{if(!((d.get(e)??-1)>=t))for(let n of(d.set(e,t),o.get(e)??[]))h(n,t+1)},u=new Set([...o.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=o.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,...r(e),upper:[],lower:[],x:0},d.get(e.name)??0);let g=0;for(let[e,t]of o)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,w=(e,t)=>{let n=0;for(let a of e){let e=x(a[t],b);a.x=Math.max(n,null===e?n:e-a.width/2),n=a.x+a.width+s}};for(let e of m)w(e,"upper");for(let e=m.length-2;e>=0;e--)w(m[e],"lower");let v=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-v)+40,y:k,width:t.width,height:t.height});k+=Math.max(0,...e.map(e=>e.height))+a}return j})(s,{notation:c}),{});for(let[t,n]of Object.entries(r))e[t]&&(e[t]={...e[t],...n});return e},[s,r,c]),F=(0,o.useMemo)(()=>{if(!s)return[];let e="";return rd(()=>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]),z=(0,o.useMemo)(()=>F.map(e=>(e.element??"").split(/[.[]/)[0]).filter(Boolean),[F]),Y=(0,o.useCallback)(async e=>{let n;if(s&&t){try{n=e(s)}catch(e){return v(e instanceof Error?e.message:String(e),"warn")}a(n),L(null);try{let e=await fetch(`/api/file${(0,ao.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),v("saved")}catch(e){v(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}}},[s,t,v]),X=(0,o.useCallback)((e,n)=>{i(s=>{let a={...s,[e]:{x:Math.round(n.x),y:Math.round(n.y)}};try{localStorage.setItem(rh(t,c),JSON.stringify(a))}catch{}return a})},[t,c]),V=()=>{i({});try{localStorage.removeItem(rh(t,c))}catch{}g(e=>e+1)},G=async()=>{if(!s)return;v("checking links…");let e=await rf(t);if(0===e.length)return L("none"),N("issues"),M(!0),v("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),A(!1),v(`checked ${e.length} machine(s): ${n.length} problem(s)`,n.length?"warn":"ok")},ei=async e=>{let n=(await rf(t)).find(t=>t.def.settings?.name===e);n?(0,ao.navigateToDoc)(n.path):v(`no .smdf.json beside this document defines '${e}'`,"warn")},el=()=>{let e=O.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},eo=e=>{let{width:t,height:n}=el();p(s=>U(s,e,{x:t/2,y:n/2}))},ec=e=>{let t=B[e],{width:n,height:s}=el();t&&n&&(p(H([t],n,s,{padding:28,maxScale:1.25})),y(e),_.close())},eu=aH(),eg=az("focus"),ey=(0,o.useMemo)(()=>s?rd(()=>(function(e,t,n={}){let s=!1!==n.rows,a=[];for(let n of e?.entities??[]){let e=n?.name?t[n.name]:void 0;e&&(a.push({focus:`entity:${n.name}`,box:e}),(n.attributes??[]).filter(e=>e?.name).forEach((t,r)=>{a.push({focus:`attribute:${n.name}.${t.name}`,box:s?{x:e.x,y:e.y+30+20*r,width:e.width,height:20}:e})}))}return a})(s,B,{rows:"chen"!==c}),[]):[],[s,B,c]),ew=(0,o.useRef)(-1);(0,o.useEffect)(()=>{if(!s||ew.current===eu.nonce)return;ew.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,o.useEffect)(()=>{x&&!aF("focus")?.startsWith(`attribute:${x}.`)&&aY(`entity:${x}`)},[x]);let ev=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,l.jsx)(ad,{}),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 a of e.relationships??[]){if(!a?.from||!a?.to)continue;let e=eh[a.cardinality]??eh["1:N"];t.push(`${n}${em(a.from)} ${e} ${em(a.to)} : ${ef(a.label??"")}`),s.add(a.from),s.add(a.to)}let a=new Set;for(let r of e.entities??[]){if(!r?.name||a.has(r.name))continue;a.add(r.name);let e=(r.attributes??[]).filter(e=>e?.name);if(0===e.length){s.has(r.name)||t.push(`${n}${em(r.name)}`);continue}for(let s of(t.push(`${n}${em(r.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 a=[ep(e.type??"","unknown"),ep(e.name,"unnamed")];return t.length&&a.push(t.join(", ")),n.length&&a.push(ef(n.join(" — "))),a.join(" ")}(s)}`);t.push(`${n}}`)}return t.join("\n")}(s)).then(()=>v("mermaid copied"))};return(0,l.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,l.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,l.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,l.jsx)(ac,{}),(0,l.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:t,children:[s?.settings.name??ej,(0,l.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",ej]})]}),(0,l.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,l.jsx)("button",{title:s,"aria-label":s,"aria-pressed":c===e,onClick:()=>(e=>{if(e!==c){try{localStorage.setItem(ru,e)}catch{}d(e),i(rp(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,l.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,l.jsx)("button",{className:rx,onClick:V,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,l.jsx)("button",{className:rx,onClick:G,title:"Check the state machines beside this document against it",children:"Check links"}),(0,l.jsx)("button",{className:rx,onClick:eM,children:"Copy mermaid"}),(0,l.jsx)("button",{className:rx,onClick:()=>A(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,l.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,l.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,l.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,l.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,l.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,l.jsxs)("div",{ref:O,className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&(0,l.jsx)(aT,{what:"diagram",resetKey:s,children:(0,l.jsx)(tF,{definition:s,notation:c,positions:B,viewport:m,onViewportChange:p,selection:x,readOnly:h,errorElements:z,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,l.jsx)(ro,{docPath:t||null,kind:"erd",viewport:m,setViewport:p,boxes:ey,boardRef:O,focus:eg}),(0,l.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,l.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,l.jsxs)("span",{className:`truncate transition-opacity duration-500 ${j&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:[b.text,T>1?` \xb7 ${T} in the room`:""]})]}),(0,l.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,l.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(rm,e?"1":"0")}catch{}v(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,l.jsx)(aP,{locked:h})}),[["+","Zoom in",()=>eo(1.25)],["−","Zoom out",()=>eo(.8)],["⛶","Fit the whole diagram",()=>g(e=>e+1)]].map(([e,t,n])=>(0,l.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))]}),ev&&!S&&(0,l.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:["✎ ",ev.name]})]}),S&&(0,l.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:_.close,"aria-hidden":"true"}),s&&(0,l.jsxs)("aside",{style:_.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,l.jsxs)("div",{className:"md:hidden",..._.zoneProps,children:[(0,l.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,l.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,l.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eN.find(e=>e.id===$)?.label}),(0,l.jsx)("button",{onClick:_.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,l.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,l.jsxs)("section",{className:eS("entities"),children:[(0,l.jsx)("div",{className:ry,style:{marginTop:0},children:"Entities"}),(0,l.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.map(e=>(0,l.jsx)("button",{className:`${rx} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))}),(0,l.jsx)(rv,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:e=>{Y(t=>ea(t,{name:e.name.trim()})),y(e.name.trim())}}),ev&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:`${ry} flex items-center justify-between gap-2`,children:[(0,l.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ev.name}),(0,l.jsx)("button",{className:`${rx} normal-case tracking-normal`,onClick:()=>ec(ev.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,l.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,l.jsx)("input",{type:"checkbox",checked:!!ev.weak,onChange:e=>Y(t=>er(t,ev.name,{weak:e.target.checked}))}),"weak entity"]}),(ev.attributes??[]).map(e=>(0,l.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,l.jsxs)("span",{className:e.stateOf?"text-blue-300":"text-gray-300",children:[e.name," : ",e.type,(0,l.jsxs)("span",{className:"text-gray-500",children:[e.key?` ${e.key.toUpperCase()}`:"",e.references?` → ${e.references}`:"",e.stateOf?` ◉ ${[e.stateOf].flat().join(", ")}`:""]})]}),(0,l.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),a=en(s,t),r=a.attributes?.length??0;if(a.attributes=(a.attributes??[]).filter(e=>e.name!==n),a.attributes.length===r)throw Error(`Attribute '${t}.${n}' not found.`);return s})(t,ev.name,e.name)),children:"✕"})]},e.name)),(0,l.jsx)(rv,{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),a=en(s,t);if(a.attributes??=[],a.attributes.some(e=>e.name===n.name))throw Error(`Attribute '${t}.${n.name}' already exists.`);return a.attributes.push(es({...n})),s})(t,ev.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,l.jsxs)("button",{className:`${rx} mt-2 text-red-300`,onClick:()=>{Y(e=>{var t;let n;return t=ev.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:[(0,l.jsx)(at,{name:"trash"})," Delete ",ev.name]})]})]}),(0,l.jsxs)("section",{className:eS("relations"),children:[(0,l.jsx)("div",{className:`${ry} max-md:mt-0`,children:"Relationships"}),0===s.relationships.length&&(0,l.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),s.relationships.map((e,t)=>(0,l.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,l.jsxs)("span",{children:[e.from," ",(0,l.jsx)("span",{className:"text-gray-500",children:e.cardinality})," ",e.to,e.label?(0,l.jsxs)("span",{className:"text-gray-500",children:[" : ",e.label]}):null]}),(0,l.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>Y(t=>(function(e,t,n,s){let a=et(e),r=a.relationships.length;if(a.relationships=a.relationships.filter(e=>e.from!==t||e.to!==n||void 0!==s&&e.label!==s),a.relationships.length===r)throw Error(`No relationship from '${t}' to '${n}'${void 0===s?"":` labelled '${s}'`}.`);return a})(t,e.from,e.to,e.label)),children:"✕"})]},t)),s.entities.length>0&&(0,l.jsx)(rv,{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,l.jsxs)("section",{className:eS("notes"),children:[(0,l.jsx)("div",{className:`${ry} max-md:mt-0`,children:"Notes"}),(0,l.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,l.jsx)(rw,{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"),ev?(0,l.jsx)(rw,{label:`On ${ev.name}`,value:ev.notes??"",placeholder:`A question or a decision about ${ev.name}…`,onSave:e=>Y(t=>er(t,ev.name,{notes:e}))},`entity:${ev.name}`):(0,l.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,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:ry,children:"Entities with notes"}),(0,l.jsx)("div",{className:"flex flex-wrap gap-1",children:s.entities.filter(e=>e.notes?.trim()).map(e=>(0,l.jsx)("button",{className:`${rx} ${x===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>y(e.name),children:e.name},e.name))})]})]}),(0,l.jsxs)("section",{className:eS("issues"),children:[(0,l.jsx)("div",{className:`${ry} max-md:mt-0 ${0===e$&&!I?"md:hidden":""}`,children:"Issues"}),F.map((e,t)=>(0,l.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",e.ruleId,"] ",e.message]},`p${t}`)),ek.map((e,t)=>(0,l.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",e.ruleId,"] ",e.message]},`l${t}`)),"none"===I&&(0,l.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,l.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,l.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,l.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(S&&$===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,l.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,l.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,l.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,l.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function rw({label:e,value:t,placeholder:n,onSave:s}){let[a,r]=(0,o.useState)(t),[i,c]=(0,o.useState)(t),[d,h]=(0,o.useState)(!1);t!==i&&(c(t),d||r(t));let u=(0,o.useRef)(null),m=e=>{u.current&&clearTimeout(u.current),u.current=null,e!==t&&s(e)};return(0,l.jsxs)("label",{className:"mt-2 block",children:[(0,l.jsx)("span",{className:"text-[11px] text-gray-500",children:e}),(0,l.jsx)("textarea",{className:`${rg} h-24 resize-y leading-snug`,placeholder:n,value:a,onChange:e=>{let t=e.target.value;r(t),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>m(t),900)},onFocus:()=>h(!0),onBlur:()=>{h(!1),m(a)}})]})}function rv({fields:e,submit:t,onSubmit:n}){let s=()=>Object.fromEntries(e.map(e=>[e.name,e.initial??e.options?.[0]??""])),[a,r]=(0,o.useState)(s),i=e[0];return(0,l.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:t=>{t.preventDefault();let l={...s(),...a};l[i.name]?.trim()&&(n(l),r(t=>Object.fromEntries(e.map(e=>[e.name,e.options?t[e.name]??"":e.initial??""]))))},children:[e.map(e=>e.options?(0,l.jsx)("select",{className:rg,"aria-label":e.name,value:a[e.name]??"",onChange:t=>r(n=>({...n,[e.name]:t.target.value})),children:e.options.map(t=>(0,l.jsx)("option",{value:t,children:t||`(${e.name})`},t))},e.name):(0,l.jsx)("input",{className:rg,"aria-label":e.name,placeholder:e.placeholder,value:a[e.name]??"",onChange:t=>r(n=>({...n,[e.name]:t.target.value}))},e.name)),(0,l.jsx)("button",{type:"submit",className:`${rx} ${1===e.length?"":"col-span-2"}`,children:t})]})}let rj="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",rk="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",r$="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function rN({id:e,fields:t,submit:n,onSubmit:s,reset:a=!1,required:r}){let i=()=>Object.fromEntries(t.map(e=>[e.name,e.initial??(!e.checkbox&&(e.options?e.options[0]??"":""))])),[c,d]=(0,o.useState)(i),h=(e,t)=>d(n=>({...n,[e]:t}));return(0,l.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:e=>{e.preventDefault();let n={...i(),...c};!(r??[]).some(e=>!String(n[e]??"").trim())&&(s(n),a&&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,l.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,l.jsx)("input",{type:"checkbox",checked:!!c[t.name],onChange:e=>h(t.name,e.target.checked)}),n]},t.name);if(t.options)return(0,l.jsx)("select",{className:`${rj} ${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,l.jsx)("option",{value:e,children:e||`(${n})`},e))},t.name);let s=t.suggest?.length?`${e}-${t.name}`:void 0;return(0,l.jsxs)("span",{className:t.wide?"col-span-2":"",children:[(0,l.jsx)("input",{className:rj,"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,l.jsx)("datalist",{id:s,children:t.suggest.map(e=>(0,l.jsx)("option",{value:e},e))})]},t.name)}),(0,l.jsx)("button",{type:"submit",className:`${rk} col-span-2`,children:n})]})}function rS({kind:e,size:t=16}){return(0,l.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,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,l.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,l.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,l.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,l.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,l.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,l.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,l.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,l.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,l.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===e&&(0,l.jsxs)(l.Fragment,{children:[(0,l.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,l.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,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,l.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let rM=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],rC=e=>`seq-read-${e.kind}-${e.id}`;function rE({definition:e,selection:t,issues:n,onSelect:s,onShowInDiagram:a}){let r=new Map(e.participants.map((e,t)=>[e.name,rM[t%rM.length]])),i=eS(e),o=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,l.jsx)("span",{className:`font-semibold ${r.get(e)??"text-gray-300"}`,children:e||"?"}),u=(e,t)=>{let r={kind:"message",id:e},i=n.get(`message:${e}`)??[],o=i.some(e=>"error"===e.severity)?"error":i.length?"warning":null,c=d("message",e);return(0,l.jsx)("li",{id:rC(r),className:"scroll-mt-16 scroll-mb-24",children:(0,l.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":c,onClick:()=>s(r),onKeyDown:e=>("Enter"===e.key||" "===e.key)&&(e.preventDefault(),s(r)),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"===o?"border-red-500":"warning"===o?"border-amber-400":"border-transparent"}`,children:[(0,l.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,l.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,l.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[h(t.from),t.from===t.to?(0,l.jsx)("span",{children:" to itself"}):(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{className:"px-1.5 text-gray-500",children:t.reply?"⇠":"→"}),h(t.to)]}),t.reply&&(0,l.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),t.optional&&(0,l.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,l.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${t.reply?"text-gray-300":"text-gray-100"}`,children:t.label||(0,l.jsx)("span",{className:"text-gray-500",children:"no label"})}),(t.event||t.state||t.carries)&&(0,l.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,l.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,l.jsxs)("span",{className:"text-gray-400",children:["on ",t.machine]}),t.state&&(0,l.jsxs)("span",{className:"text-emerald-300",children:["→ ",t.state]}),t.carries&&(0,l.jsxs)("span",{className:"text-gray-400",children:["carries ",t.carries]})]}),i.map((e,t)=>(0,l.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,l.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(),a(r)},children:"Show in the diagram"})]})]})},e)};return(0,l.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,l.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[e.participants.length>0&&(0,l.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},a=e.actor?"actor":e.object?"object":e.service?"service":"",r=n.get(`participant:${e.name}`)??[];return(0,l.jsx)("li",{id:rC(t),children:(0,l.jsxs)("button",{onClick:()=>s(t),"aria-pressed":d("participant",e.name),title:r.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"} ${r.length?"ring-1 ring-amber-400/70":""}`,children:[h(e.name),a&&(0,l.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:a})]})},e.name)})}),0===i.length&&(0,l.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,l.jsx)("ol",{className:"flex flex-col gap-1",children:o.map(({ref:e,message:t})=>u(e,t))}),c.map(({f:e,fi:t,rows:n})=>(0,l.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,l.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,l.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,l.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:e.kind}),(0,l.jsxs)("span",{className:"text-indigo-300",children:[" · after ",e.after]})]}),(0,l.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:e.label})]}),0===n.length?(0,l.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,l.jsx)("ol",{className:"flex flex-col gap-1",children:n.map(({ref:e,message:t})=>u(e,t))})]},t))]})})}async function rR(e){try{let t=await fetch(`/api/file${(0,ao.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 rA extends Error{constructor(e){super(`${e.split("/").pop()} changed on disk since it was read`)}}async function rO(e,t,n){let s=await fetch(`/api/file${(0,ao.docQuery)(e)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(t,null,2)+"\n",...void 0!==n?{mtime:n}:{}})}),a=await s.json().catch(()=>({}));if(409===s.status)throw new rA(e);if(!s.ok)throw Error(a?.error??`HTTP ${s.status}`);return a?.mtime}async function r_(e){let t=await rR(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 a={},r={},i={[t.path]:t.mtime??0},l=await Promise.all((s.members??[]).filter(e=>e?.path).map(async e=>{let n=eJ(t.path,e.path);a[e.path]=n;let s=eH(e.path),l=await rR(n);if(l.error)return{path:e.path,kind:s,def:null,error:l.error};if(!l.exists||!l.content)return{path:e.path,kind:s,def:null,error:"the file does not exist"};i[e.path]=l.mtime??0;try{let t=JSON.parse(l.content);if("machine"===s&&t&&(t.stateMachine||t.StateMachine))return r[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:l,absOf:a,wrapped:r,mtimes:i}}function rT(){window.dispatchEvent(new Event(aq))}function rP(e){let[t,n]=(0,o.useState)(null),[s,a]=(0,o.useState)(0),r=(0,o.useCallback)(()=>a(e=>e+1),[]);return(0,o.useEffect)(()=>(window.addEventListener(aq,r),()=>window.removeEventListener(aq,r)),[r]),(0,o.useEffect)(()=>{if(!e)return;let t=!0;return r_(e).then(s=>t&&n({for:e,system:s})),()=>{t=!1}},[e,s]),{system:e&&t?.for===e?t.system:null,reload:r}}function rI(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 rL(e,t,n,s){let{bridgeUrl:a}=await ay();if(!a)return;let r=sA({url:a,role:"web",docId:e,name:"web-reconcile",autoResync:!1});try{let e=await Promise.race([r.join(),new Promise((e,t)=>setTimeout(()=>t(Error("join timeout")),3e3))]),a=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(a&&i(a)===i(t))return;await new Promise(e=>{let l=r.on("ack",()=>{l(),e()});s&&a&&i(a)===i(s.from)?r.emitPatch(s.ops,n):r.emitFull(t,n),setTimeout(e,800)})}catch{}finally{r.disconnect()}}async function rD(e,t){let n=[],s=[],a=[],r=async(e,t)=>{try{await t(),n.push(e)}catch(t){t instanceof rA?a.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 r(n.member,async()=>{let s=e.wrapped[n.member]?{stateMachine:n.def}:n.def,a=await rO(t,s,e.mtimes[n.member]),r=e.members.find(e=>e.path===n.member)?.def;await rL(t,n.def,a,{from:r,ops:n.ops})})}for(let n of t.erds){let t=e.absOf[n.member];t&&await r(n.member,async()=>{let s=await rO(t,n.def,e.mtimes[n.member]);await rL(t,n.def,s)})}return t.system&&await r(e.path.split("/").pop()??e.path,async()=>{let n=await rO(e.path,t.system.def,e.mtimes[e.path]);await rL(e.path,t.system.def,n)}),rT(),{written:n,failed:s,conflicts:a}}async function rq(e){let t={result:null,written:[],failed:[],conflicts:[]};for(let n=0;n<2;n+=1){let s=await r_(e);if(!s.def)return{...t,failed:[s.error??"the system could not be read"],retried:n>0};let a=ta(s.def,s.members);if(!a.count)return{...t,result:a,conflicts:n?t.conflicts:[],retried:n>0};let r=await rD(s,a);if(t={result:a,written:[...t.written,...r.written],failed:r.failed,conflicts:r.conflicts},!r.conflicts.length)return{...t,retried:n>0}}return{...t,retried:!0}}let rB="stateloom.sequence.view",rF=["","actor","service","object"],rz=e=>"string"==typeof e?e.trim():"",rU=e=>rz(e).split(",").map(e=>e.trim()).filter(Boolean);function rY(e){return{from:rz(e.from),to:rz(e.to),label:rz(e.label),event:rz(e.event),machine:rz(e.machine),carries:rz(e.carries),state:rz(e.state),description:rz(e.description),optional:!!e.optional||void 0,reply:!!e.reply||void 0}}function rH(){let e,t,n,s=(0,ao.useRequestedDoc)(),a=az("system"),{system:r}=rP(a),i=aH(),[c,d]=(0,o.useState)(""),[h,u]=(0,o.useState)(null),[m,p]=(0,o.useState)({...q}),[f,g]=(0,o.useState)(void 0),[x,y]=(0,o.useState)(null),[b,w]=(0,o.useState)({text:"loading…",tone:"ok"}),v=(0,o.useCallback)((e,t="ok")=>w({text:e,tone:t}),[]),[j,k]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=setTimeout(()=>k(!0),4e3);return()=>{clearTimeout(e),k(!1)}},[b]);let[$,N]=(0,o.useState)("messages"),[S,M]=(0,o.useState)(!1),[C,E]=(0,o.useState)(!1),[R,A]=(0,o.useState)(!1),[O,_]=(0,o.useState)("diagram"),T=(0,o.useRef)("diagram");(0,o.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(rB)}catch{}let t="list"===e||"diagram"===e?e:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";T.current=t,_(t)},[]);let P=(0,o.useCallback)(e=>{T.current=e,_(e);try{window.localStorage.setItem(rB,e)}catch{}},[]),I=(0,o.useRef)(null),L=aI({onClose:()=>M(!1),restVh:62,tallVh:92}),[D,F]=(0,o.useState)(0),z=(0,o.useRef)(null),Y=(0,o.useRef)(!0),X=(0,o.useRef)(-1);(0,o.useEffect)(()=>{let e=!1,t=null;return(async()=>{let n=await (await fetch(`/api/file${(0,ao.docQuery)(s)}`,{cache:"no-store"})).json();if(e)return;if(n.error)return v(n.error,"warn");let a=n.path??"",r=null;try{let e=n.content?ex(JSON.parse(n.content)):null;ej(e)&&(r=e)}catch{}if(n.exists&&!r)return v(`${a} is not a readable sequence definition`,"warn");let i=(a.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");d(a),u(r??ek("Default",i)),v(n.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:l}=await ay();!e&&l&&(z.current=t=s_({url:l,role:"web",docId:a,name:"web-designer",onFull:e=>{let t=e.def;ej(t)&&(u(t),v("updated live"))},onPatch:()=>{},onPresence:e=>F(e.length)}),t.connect())})().catch(t=>!e&&v(String(t),"warn")),()=>{e=!0,z.current=null,t?.disconnect()}},[s,v]);let V=(0,o.useMemo)(()=>h?tV(h):null,[h]),J=(0,o.useMemo)(()=>V?eD(V):null,[V]),W=(0,o.useMemo)(()=>V&&J?rd(()=>(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),a=e.self?220:Math.max(40,Math.abs(e.toX-e.fromX)),r={x:t-10,y:e.y-24,width:a+20,height:40};n.push({focus:`message:${e.ref}`,box:r});let i=s.get(e.ref)?.event;i&&n.push({focus:`event:${i}`,box:r})}return n})(V,J),[]):[],[V,J]),K=(0,o.useMemo)(()=>{let e={};for(let{ref:t,message:n}of V?rd(()=>eS(V),[]):[]){let s=n?.label?`${t}. ${n.label}`:`message ${t}`;e[`message:${t}`]=s.length>48?`${s.slice(0,47)}…`:s}return e},[V]),Z=az("focus"),G=(0,o.useMemo)(()=>{if(!h)return[];let e="";return rd(()=>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]),Q=rI(r,c),ee=(0,o.useMemo)(()=>r?.def&&Q&&h?rd(()=>e8(r.def,r.members.map(e=>e.path===Q?{...e,def:h,error:void 0}:e)),null):null,[r,Q,h]),et=(0,o.useMemo)(()=>(ee?.issues??[]).filter(e=>e.member===Q&&!/^S0/.test(e.ruleId)),[ee,Q]),en=ee?.replays.find(e=>e.member===Q)?.report??null,es=(0,o.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 a=e=>[...e].sort((e,t)=>e.localeCompare(t));return{events:a(t.events),states:a(t.states),machines:a(t.machines),objects:a(t.objects),entities:a(t.entities),actors:a(t.actors)}})(r),[r]),ea=(0,o.useMemo)(()=>{let e=e=>e?/^(message|participant):/.test(e)?e:V?.participants.some(t=>t.name===e)?`participant:${e}`:"":"";return[...G.map(t=>e(t.element)),...et.filter(e=>"error"===e.severity).map(t=>e(t.element))].filter(Boolean)},[G,et,V]),er=(0,o.useMemo)(()=>et.filter(e=>"warning"===e.severity).map(e=>e.element??""),[et]),ei=(0,o.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 G.forEach(e=>t(e.element,{severity:"error",text:e.message})),et.forEach(e=>t(e.element,{severity:"error"===e.severity?"error":"warning",text:e.message})),e},[G,et,V]),el=()=>{let e=I.current?.getBoundingClientRect();return{width:e?.width??0,height:e?.height??0}},eo=(0,o.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})},[]),ec=(0,o.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]),ed=(0,o.useCallback)(e=>{if("diagram"===T.current)return ec(e);requestAnimationFrame(()=>document.getElementById(rC(e))?.scrollIntoView({block:"center",behavior:"smooth"}))},[ec]),eh=(0,o.useCallback)(e=>{y(e),e&&aY(`${e.kind}:${e.id}`)},[]);(0,o.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 v(`${i.focus} is not in this sequence`,"warn");Y.current=!1,y(t),ed(t)},[h,V,J,i,ed,v]),(0,o.useEffect)(()=>{if(!J||!Y.current||"diagram"!==O)return;let{width:e,height:t}=el();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,O]);let eu=(0,o.useCallback)(async e=>{let t;if(h&&c){try{t=e(h)}catch(e){return v(e instanceof Error?e.message:String(e),"warn")}u(t);try{let e=await fetch(`/api/file${(0,ao.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}`);z.current?.emitFull(t),v("saved")}catch(e){return v(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}if(r?.def&&Q){if("auto"===eF(r.def)){let{result:e,failed:t,conflicts:s}=await rq(r.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`:tr(e,"auto"),window.dispatchEvent(new CustomEvent(aB,{detail:{text:n,origin:void 0}})))}}rT()}}},[h,c,v,r,Q]),em=e=>{let{width:t,height:n}=el();p(s=>U(s,e,{x:t/2,y:n/2}))},ep=()=>{let e,t,n,s,a,r,i,l,o;h&&navigator.clipboard?.writeText((e=["sequenceDiagram"],t=new Map,(h.participants??[]).forEach((n,s)=>{let a=`p${s+1}`;t.set(n.name,a),e.push(` ${n.actor?"actor":"participant"} ${a} as ${eq(n.name)}`)}),n=e=>t.get(e)??eq(e).replace(/\W+/g,"_"),s=(e,t,s)=>{let a=e.reply?"-->>":"->>",r=[`${t} ${eq(e.label??"")}`,e.event?eq(e.event):""].filter(Boolean).join(" · "),i=`${s}${n(e.from)}${a}${n(e.to)}: ${r}`;return e.optional?[`${s}opt optional`,` ${i}`,`${s}end`]:[i]},a=h.messages??[],r=h.fragments??[],i=e=>r.filter(t=>t?.after===e),l=(t,n)=>(t.messages??[]).forEach((a,i)=>e.push(...s(a,`f${r.indexOf(t)+1}.${i+1}`,n+" "))),(o=(t,n,r)=>{for(let c=t;c<=a.length;c++){let t=c===r?[]:i(c);for(let s of t.filter(e=>"alt"!==e.kind))e.push(`${n}${s.kind} ${eq(s.label??"")}`),l(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??"")}`),l(t,n)}),c<a.length&&(e.push(`${n}else as written`),o(c,n+" ",c)),e.push(`${n}end`);return}c<a.length&&e.push(...s(a[c],String(c+1),n))}})(0," ",null),e.join("\n")+"\n")).then(()=>v("mermaid copied"))},ef=e=>{let t=e?e9(e):null;if(!t||"message"!==t.kind&&"participant"!==t.kind)return;let n={kind:t.kind,id:t.name};eh(n),ed(n),L.close()},eg=V??ek("",""),ey=eS(eg),eb=h&&x?.kind==="message"?eN(eg,x.id):null,ew=h&&x?.kind==="participant"?eg.participants.find(e=>e.name===x.id)??null:null,e$=eg.participants.map(e=>e.name),eL=c.split("/").pop()||"…",eB=G.length+et.filter(e=>"error"===e.severity).length,ez=et.filter(e=>"warning"===e.severity).length,eU=[{id:"participants",label:"Participants",icon:(0,l.jsx)(rS,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,l.jsx)(rS,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,l.jsx)(ad,{}),badge:eB+ez||void 0}],eY=e=>[{name:"from",label:"from",options:e$,initial:e?.from??e$[0]??""},{name:"to",label:"to",options:e$,initial:e?.to??e$[1]??e$[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:e?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:es.events,initial:e?.event??""},{name:"state",label:"state after",suggest:es.states,initial:e?.state??""},{name:"carries",label:"entity it carries",suggest:es.entities,initial:e?.carries??""},{name:"machine",label:"machine",suggest:es.machines,initial:e?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!e?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!e?.reply}],eH=e=>e.actor?"actor":e.object?"object":e.service?"service":"",eX=["main: at the end",...eb&&null===eb.fragment?[`main: after ${eb.index+1}`]:[],...(h?.fragments??[]).map((e,t)=>`fragment ${t+1}: ${e.kind} \xb7 ${e.label}`)];return(0,l.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&E(!1),children:[(0,l.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,l.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,l.jsx)(rS,{kind:"sequence",size:14}),"SEQ"]}),(0,l.jsx)(ac,{}),(0,l.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:c,children:[h?.settings.name??eL,(0,l.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",eL]})]}),(0,l.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,l.jsx)("button",{title:n,"aria-pressed":O===e,onClick:()=>{O!==e&&(x&&(Y.current=!1),P(e),x&&requestAnimationFrame(()=>ed(x)))},className:`px-2.5 py-1.5 ${O===e?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:t},e))}),(0,l.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,l.jsx)("button",{className:rk,onClick:ep,children:"Copy mermaid"}),(0,l.jsx)("button",{className:rk,onClick:()=>A(e=>!e),"aria-pressed":!R,title:R?"Show the panel":"Hide the panel — the board takes the full width",children:R?"⟨ Panel":"Panel ⟩"})]}),(0,l.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,l.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,l.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,l.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{E(!1),ep()},children:"Copy as mermaid"})})]})]}),(0,l.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,l.jsxs)("div",{ref:I,className:"relative min-w-0 flex-1 overflow-hidden",children:[h&&J&&"list"===O&&V&&(0,l.jsx)(aT,{what:"sequence",resetKey:h,children:(0,l.jsx)(rE,{definition:V,selection:x,issues:ei,onSelect:e=>eh(e),onShowInDiagram:e=>{Y.current=!1,P("diagram"),requestAnimationFrame(()=>ec(e))}})}),h&&J&&"diagram"===O&&(0,l.jsx)(aT,{what:"sequence",resetKey:h,children:(0,l.jsx)(tJ,{definition:V,layout:J,viewport:m,onViewportChange:p,selection:x,errorElements:ea,warningElements:er,fitKey:f,onSelect:(e,t)=>eh({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"===O&&(0,l.jsx)(ro,{docPath:c||null,kind:"sequence",viewport:m,setViewport:p,boxes:W,boardRef:I,focus:Z,labels:K}),h&&J&&"list"===O&&(0,l.jsx)(rc,{docPath:c,onReveal:()=>P("diagram")}),(0,l.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"===O&&j&&"ok"===b.tone?"hidden":"flex"}`,role:"status",children:[(0,l.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,l.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,l.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"===O?"flex":"hidden"}`,children:[["+","Zoom in",()=>em(1.25)],["−","Zoom out",()=>em(.8)],["⛶","Fit the whole diagram",()=>g(e=>(e??0)+1)]].map(([e,t,n])=>(0,l.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,l.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}. ${eb?.message.label??""}`:x.id]})]}),S&&(0,l.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),h&&(0,l.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,l.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,l.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,l.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,l.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:eU.find(e=>e.id===$)?.label}),(0,l.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,l.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:eU.map(e=>(0,l.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,l.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,l.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,l.jsxs)(aT,{what:"panel",resetKey:h,children:[(0,l.jsxs)("section",{className:"participants"===$?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Participants"}),(0,l.jsx)("div",{className:"flex flex-wrap gap-1",children:eg.participants.map(e=>(0,l.jsxs)("button",{className:`${rk} ${x?.kind==="participant"&&x.id===e.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{eh({kind:"participant",id:e.name}),ed({kind:"participant",id:e.name})},title:eH(e)||"participant",children:[e.name,eH(e)&&(0,l.jsxs)("span",{className:"text-gray-500",children:[" · ",eH(e)]})]},e.name))}),(0,l.jsx)(rN,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:rF,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...es.actors,...es.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:es.entities}],submit:"+ Participant",onSubmit:e=>{let t=rz(e.name),n=rz(e.kind);eu(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 a=s.participants.length;return s.participants.splice(a,0,eE({...t})),s})(s,{name:t,...n?{[n]:rz(e.value)||t}:{},holds:rU(e.holds)})),eh({kind:"participant",id:t})}}),ew&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:`${r$} flex items-center justify-between gap-2`,children:[(0,l.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ew.name}),(0,l.jsx)("button",{className:`${rk} normal-case tracking-normal`,onClick:()=>ed({kind:"participant",id:ew.name}),children:"◎ Show on board"})]}),(e=eg.participants.findIndex(e=>e.name===ew.name),t=eg.participants.length-1,n=e=>eu(t=>{var n;let s,a;return n=ew.name,a=eR(s=eC(t),n),s.participants.splice(s.participants.indexOf(a),1),s.participants.splice(Math.max(0,Math.min(e,s.participants.length)),0,a),s}),(0,l.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,l.jsx)("button",{className:`${rk} disabled:opacity-40`,disabled:e<=0,onClick:()=>n(e-1),"aria-label":"Move one column left",children:"← Left"}),(0,l.jsxs)("span",{className:"flex-1 text-center",children:["column ",e+1," of ",t+1]}),(0,l.jsx)("button",{className:`${rk} disabled:opacity-40`,disabled:e>=t,onClick:()=>n(e+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,l.jsx)(rN,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:ew.name}],submit:"Rename (every message follows)",onSubmit:e=>{let t=rz(e.to);t!==ew.name&&(eu(e=>(function(e,t,n){if(!n?.trim())throw Error("A participant needs a name.");let s=eC(e),a=eR(s,t);if(n===t)return s;if(s.participants.some(e=>e.name===n))throw Error(`Participant '${n}' already exists.`);a.name=n;let r=e=>{e.from===t&&(e.from=n),e.to===t&&(e.to=n)};for(let e of(s.messages.forEach(r),s.fragments??[]))e.messages.forEach(r);return s})(e,ew.name,t)),eh({kind:"participant",id:t}))}},`rename:${ew.name}`),(0,l.jsx)(rN,{id:"edit-participant",fields:[{name:"kind",options:rF,label:"kind",initial:eH(ew)},{name:"value",placeholder:"actor / service / object",suggest:[...es.actors,...es.objects],initial:ew.actor??ew.object??ew.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:es.entities,initial:(ew.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:ew.description??"",wide:!0}],submit:"Save participant",onSubmit:e=>eu(t=>{let n,s;return e_(t,ew.name,{...(n=rz(e.kind),s=rz(e.value)||ew.name,{actor:"actor"===n?s:"",service:"service"===n?s:"",object:"object"===n?s:""}),holds:rU(e.holds),description:rz(e.description)})})},`p:${JSON.stringify(ew)}`),(0,l.jsxs)("button",{className:`${rk} mt-2 text-red-300`,onClick:()=>{eu(e=>{var t;let n,s;return t=ew.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),aY(null)},title:"Also removes every message it sends or receives",children:["Delete ",ew.name," and its messages"]})]})]}),(0,l.jsxs)("section",{className:"messages"===$?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Messages"}),0===ey.length&&(0,l.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,l.jsx)("div",{className:"flex flex-col",children:ey.map(({ref:e,message:t,fragment:n},s)=>{let a=null!==n&&(0===s||ey[s-1].fragment!==n),r=null!==n?eg.fragments?.[n]:void 0,i=x?.kind==="message"&&x.id===e;return(0,l.jsxs)("div",{children:[a&&r&&(0,l.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,l.jsx)("span",{className:"font-semibold",children:r.kind})," · after ",r.after," · ",r.label]}),(0,l.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:()=>{eh({kind:"message",id:e}),ed({kind:"message",id:e})},title:`${t.from} → ${t.to}: ${t.label}`,children:[(0,l.jsxs)("span",{className:"text-gray-500",children:[e,"."]})," ",t.from," → ",t.to,": ",t.label,t.event?(0,l.jsxs)("span",{className:"text-blue-300",children:[" [",t.event,"]"]}):null,t.state?(0,l.jsxs)("span",{className:"text-emerald-400",children:[" → ",t.state]}):null,t.optional?(0,l.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},e)})}),eb&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:`${r$} flex items-center justify-between gap-2`,children:[(0,l.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",x.id]}),(0,l.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===eb.fragment&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("button",{className:rk,"aria-label":"Move up",title:"Move up",disabled:0===eb.index,onClick:()=>{eu(e=>eI(e,eb.index,eb.index-1)),eh({kind:"message",id:String(eb.index)})},children:"↑"}),(0,l.jsx)("button",{className:rk,"aria-label":"Move down",title:"Move down",disabled:eb.index>=eg.messages.length-1,onClick:()=>{eu(e=>eI(e,eb.index,eb.index+1)),eh({kind:"message",id:String(eb.index+2)})},children:"↓"})]}),(0,l.jsx)("button",{className:rk,onClick:()=>ed(x),children:"◎ Show"})]})]}),(0,l.jsx)(rN,{id:"edit-message",required:["label"],fields:[...eY(eb.message),{name:"description",placeholder:"description",initial:eb.message.description??"",wide:!0}],submit:"Save message",onSubmit:e=>eu(t=>eP(t,eb.index,rY(e),eb.fragment))},`m:${x.id}:${JSON.stringify(eb.message)}`),(0,l.jsxs)("button",{className:`${rk} mt-2 text-red-300`,onClick:()=>{eu(e=>(function(e,t,n=null){let s=eC(e);if(null!==n){let e=eO(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,eb.index,eb.fragment)),y(null),aY(null)},children:["Delete message ",x.id]})]}),(0,l.jsx)("div",{className:r$,children:"Add a message"}),(0,l.jsx)(rN,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:eX,label:"where",wide:!0},...eY()],submit:"+ Message",onSubmit:e=>{let t=rz(e.where),n=rY(e),s=/^fragment (\d+):/.exec(t),a=/^main: after (\d+)$/.exec(t);s?eu(e=>{var t;let a,r,i;return t=Number(s[1])-1,r=eO(a=eC(e),t),eA(a,n),i=r.messages.length,r.messages.splice(i,0,eE({...n})),a}):a?eu(e=>eT(e,n,Number(a[1]))):eu(e=>eT(e,n))}},`add:${eX.join("|")}:${e$.join("|")}`),(0,l.jsx)("div",{className:r$,children:"Fragments"}),0===(eg.fragments??[]).length&&(0,l.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(eg.fragments??[]).map((e,t)=>(0,l.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,l.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,l.jsxs)("span",{children:[t+1,". ",(0,l.jsx)("span",{className:"font-semibold",children:e.kind})," · after ",e.after," · ",e.messages.length," message(s)"]}),(0,l.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${t+1}`,onClick:()=>eu(e=>{let n;return eO(n=eC(e),t),n.fragments.splice(t,1),n.fragments.length||delete n.fragments,n}),children:"✕"})]}),(0,l.jsx)(rN,{id:`edit-fragment-${t}`,fields:[{name:"kind",options:ev,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=>eu(n=>(function(e,t,n){let s=eC(e),a=eO(s,t);if(void 0!==n.kind&&!ev.includes(n.kind))throw Error(`A fragment is one of ${ev.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({...a,...n,messages:void 0}),messages:a.messages??[]},s})(n,t,{kind:rz(e.kind),after:Number(rz(e.after)),label:rz(e.label)}))})]},`${t}:${JSON.stringify({...e,messages:void 0})}`)),(0,l.jsx)(rN,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:ev},{name:"after",placeholder:"after message",initial:String(eb&&null===eb.fragment?eb.index+1:eg.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:e$,label:"first message from"},{name:"to",options:e$,label:"to",initial:e$[1]??e$[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:e=>eu(t=>(function(e,t){if(!ev.includes(t.kind))throw Error(`A fragment is one of ${ev.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??[])eA(n,e);return(n.fragments??=[]).push({...eE({...t,messages:void 0}),messages:(t.messages??[]).map(e=>eE({...e}))}),n})(t,{kind:rz(e.kind),after:Number(rz(e.after)),label:rz(e.label),messages:rz(e.first)?[{from:rz(e.from),to:rz(e.to),label:rz(e.first)}]:[]}))},`add-fragment:${eg.messages.length}:${eb?.index??""}`)]}),(0,l.jsxs)("section",{className:"notes"===$?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Notes"}),(0,l.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,l.jsx)(rw,{label:"On this sequence",value:h.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:e=>eu(t=>{var n;let s;return n={notes:e},(s=eC(t)).settings=eE({...s.settings,...n}),s})},"sequence"),ew&&(0,l.jsx)(rw,{label:`On ${ew.name}`,value:ew.notes??"",placeholder:`A question or a decision about ${ew.name}…`,onSave:e=>eu(t=>e_(t,ew.name,{notes:e}))},`participant:${ew.name}`),eb&&(0,l.jsx)(rw,{label:`On message ${x.id}`,value:eb.message.notes??"",placeholder:"A question or a decision about this message…",onSave:e=>eu(t=>eP(t,eb.index,{notes:e},eb.fragment))},`message:${x.id}`),!x&&(0,l.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...eg.participants.filter(e=>e.notes?.trim()),...ey.filter(e=>e.message.notes?.trim())].length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:r$,children:"With notes"}),(0,l.jsxs)("div",{className:"flex flex-wrap gap-1",children:[eg.participants.filter(e=>e.notes?.trim()).map(e=>(0,l.jsx)("button",{className:rk,onClick:()=>ef(`participant:${e.name}`),children:e.name},`p${e.name}`)),ey.filter(e=>e.message.notes?.trim()).map(e=>(0,l.jsxs)("button",{className:rk,onClick:()=>ef(`message:${e.ref}`),children:["message ",e.ref]},`m${e.ref}`))]})]})]}),(0,l.jsxs)("section",{className:"issues"===$?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Issues"}),G.map((e,t)=>(0,l.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ef(e.element),children:["[",e.ruleId,"] ",e.message]},`p${t}`)),et.map((e,t)=>(0,l.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===e.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ef(e.element),children:["[",e.ruleId,"] ",e.message]},`s${t}`)),0===G.length&&0===et.length&&(0,l.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:ee?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!a&&(0,l.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."}),a&&!Q&&r&&(0,l.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),en&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:r$,children:["Replay against ",en.machines.join(", ")||"no machine"]}),en.paths.map(e=>(0,l.jsxs)("div",{className:"mb-2",children:[(0,l.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,l.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:()=>ef(`message:${t.ref}`),children:[t.ref,". ",t.event??""," ",t.from.join("|")||"·"," → ",t.to.join("|")||"·"," ",t.result]},`${e.name}:${t.ref}`))]},e.name))]})]})]})})]})]}),(0,l.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,l.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,l.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,l.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,l.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,l.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function rX(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 rV=(e,t)=>e?.members.find(e=>e.path===t)?.kind??"machine";function rJ(e){return"message"===e.kind?`message ${e.name}`:`${e.kind} ${e.name}`}function rW({systemPath:e}){let t=az("doc"),n=az("focus"),{system:s}=rP(e),[a,r]=(0,o.useState)(!1),[i,c]=(0,o.useState)(null),d=(0,o.useRef)(s);(0,o.useEffect)(()=>{d.current=s},[s]);let h=(0,o.useMemo)(()=>s?rd(()=>te(s.members),[]):[],[s]),u=rI(s,t),m=!!s&&(t===s.path||t===e),p=u&&n?function(e,t,n){let s=e9(n);if(!s)return[];let a=e=>e.member===t&&e.kind===s.kind&&e.name===s.name,r=[];for(let t of e)a(t.from)?r.push({other:t.to,text:t.text,rule:t.rule}):a(t.to)&&r.push({other:t.from,text:t.back,rule:t.rule});return r}(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,o.useEffect)(()=>{let e=e=>{let t=e.detail;t?.text&&c({...t,at:Date.now()})};return window.addEventListener(aB,e),()=>window.removeEventListener(aB,e)},[]),(0,o.useEffect)(()=>{if(!i)return;let e=setTimeout(()=>c(null),9e3);return()=>clearTimeout(e)},[i]);let g=s?.path;(0,o.useEffect)(()=>{if(!g)return;let t=!0,n=null,s=null;return(async()=>{let{bridgeUrl:a}=await ay();if(t&&a){var i;let t,l,o,h;(n=sA({url:a,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()});aU({doc:s?n.absOf[s]:g,system:e,focus:t.focus??null}),r(!1);let a=[s?rX(n,s):"the system map",t.focus].filter(Boolean).join(" · ");c({text:t.note?t.note:`showing ${a}`,origin:t.origin,at:Date.now()})}),n.on("full",()=>rT()),i=n,t=!1,l=!1,o=()=>{i.join().then(()=>{t=!0}).catch(()=>{})},h=i.on("status",e=>{"connected"!==e?l=t:l&&(l=!1,o())}),o(),s=()=>{h()}}})(),()=>{t=!1,s?.(),n?.disconnect()}},[g,e]);let x=t=>{r(!1),s&&aU({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,""),w=p.length;return(0,l.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,l.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,l.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,l.jsx)(rS,{kind:"system",size:15}),(0,l.jsx)("span",{className:"truncate font-semibold",children:b})]}),(0,l.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,l.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,l.jsxs)("button",{onClick:()=>x({member:e}),"aria-current":t?"page":void 0,title:`${rX(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,l.jsx)(rS,{kind:rV(s,e),size:15}),(0,l.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${t?"":"hidden md:inline"}`,children:rX(s,e)})]},e)}),!s&&(0,l.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),s?.error&&(0,l.jsx)("span",{className:"truncate px-1 text-amber-300",children:s.error})]}),(0,l.jsxs)("button",{onClick:()=>r(e=>!e),disabled:!u,"aria-expanded":a,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 ${a?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,l.jsx)(rS,{kind:"link",size:15}),(0,l.jsx)("span",{className:"hidden sm:inline",children:"Links"}),w>0&&(0,l.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:w})]})]}),i&&!a&&(0,l.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,l.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,l.jsxs)("span",{className:"text-blue-300",children:[i.origin,": "]}):null,i.text]})}),a&&u&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>r(!1),"aria-hidden":"true"}),(0,l.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,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,l.jsxs)("span",{className:"truncate",children:[(0,l.jsx)("span",{className:"text-gray-200",children:rJ(e9(n))})," in ",rX(s,u)]}),(0,l.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>aU({doc:t,focus:null}),children:"clear"})]}),0===p.length&&(0,l.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),p.map((e,t)=>(0,l.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,l.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,l.jsx)(rS,{kind:rV(s,e.other.member),size:14})}),(0,l.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,l.jsx)("span",{className:"block text-[12px] text-gray-200",children:e.text}),(0,l.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[rJ(e.other)," · ",rX(s,e.other.member)," · ",e.rule]})]})]},t))]}):null,(!n||!e9(n))&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",rX(s,u)," that the other drawings name — pick one to follow it."]}),0===f.length&&(0,l.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,l.jsx)("div",{className:"flex flex-wrap gap-1",children:f.map(([e,n])=>(0,l.jsxs)("button",{onClick:()=>{r(!0),aU({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,l.jsx)("span",{className:"text-gray-500",children:n})]},e))})]})]})]})]})}let rK={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function rZ(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,a=e=>{e&&(s+=1,(e.states??[]).forEach(a),(e.parallel?.states??[]).forEach(a))};(t.state?.states??[]).forEach(a),(t.state?.parallel?.states??[]).forEach(a);let r=(t.events??[]).reduce((e,t)=>e+(t?.events?.length??0)+(t?.timers?.length??0),0);return`${s} states \xb7 ${r} events`}let rG=(e,t)=>e<t?`${e}\u0000${t}`:`${t}\u0000${e}`;function rQ(e){let t="message"===e.from.kind?`message ${e.from.name}`:`${e.from.kind} ${e.from.name}`;return`${t} ${e.text}`}function r0(){let e=(0,ao.useRequestedDoc)(),[t,n]=(0,o.useState)(e);(0,o.useEffect)(()=>{let t=!0;return e?n(e):aF("doc")||rR(null).then(e=>t&&n(e.path||null)),()=>{t=!1}},[e]);let{system:s,reload:a}=rP(t),[r,i]=(0,o.useState)("members"),[c,d]=(0,o.useState)(!1),[h,u]=(0,o.useState)(!1),[m,p]=(0,o.useState)(!1),[f,g]=(0,o.useState)(null),[x,y]=(0,o.useState)(()=>new Set),[b,w]=(0,o.useState)({text:"loading…",tone:"ok"}),v=(0,o.useCallback)((e,t="ok")=>w({text:e,tone:t}),[]),[j,k]=(0,o.useState)(!1),$=aI({onClose:()=>d(!1),restVh:62,tallVh:92}),N=(0,o.useRef)(null),[S,M]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=N.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();t.width&&M(t.height>1.1*t.width)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let C=(0,o.useRef)(!1);(0,o.useEffect)(()=>{s&&(s.error?v(s.error,"warn"):C.current||v(`${s.members.length} member${1===s.members.length?"":"s"} loaded`),C.current=!0)},[s,v]);let[E,R]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=setTimeout(()=>R(!0),4e3);return()=>{clearTimeout(e),R(!1)}},[b]);let A=(0,o.useMemo)(()=>s?.def?rd(()=>e8(s.def,s.members),null):null,[s]),O=(0,o.useMemo)(()=>s?rd(()=>te(s.members),[]):[],[s]),_=(0,o.useMemo)(()=>s?.def?rd(()=>ta(s.def,s.members),null):null,[s]),T=eF(s?.def),P=(0,o.useMemo)(()=>{let e=new Map;for(let t of O){if(t.from.member===t.to.member)continue;let n=rG(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},[O]),I=(A?.issues??[]).filter(e=>"error"===e.severity),L=(A?.issues??[]).filter(e=>"warning"===e.severity),D=(t,n)=>{s&&aU({doc:s.absOf[t]??t,system:e??s.path,focus:n??null})},q=async(e,t)=>{if(s)try{await rO(s.path,e,s.mtimes[s.path]),v(t),rT()}catch(e){e instanceof rA?(v("the system changed on disk — reloaded; make the change again","warn"),rT()):v(`not saved: ${e instanceof Error?e.message:String(e)}`,"warn")}},B=async()=>{if(!s||!_||!_.count)return;k(!0);let{result:e,written:t,failed:n,conflicts:a}=await rq(s.path);k(!1),n.length?v(`not all written: ${n.join("; ")}`,"warn"):a.length?v(`${a.join(", ")} kept changing on disk — not written; apply again`,"warn"):e?.count?v(`${tr(e,"propose").replace(/ proposed/," applied")} — ${t.length} file(s) written`):v("nothing to apply: the drawings on disk already agree")},F=S?420:760,z=S?640:520,U=s?.def?.members?.filter(e=>e?.path).map(e=>e.path)??[],Y=s?.def?.actors??[],H=64*!!Y.length,X=(0,o.useMemo)(()=>{let e=U.length,t=F/2,n=(z-H)/2+6,s=Math.max(0,F/2-98-16),a=Math.max(0,(z-H)/2-46-18),r=new Map;return U.forEach((i,l)=>{if(1===e)return r.set(i,{x:t,y:n});if(S){let t=z-H-46-16;return r.set(i,{x:l%2?.67*F:.33*F,y:62+(t-62)*l/(e-1)})}if(2===e)return r.set(i,S?{x:t,y:l?n+a:n-a}:{x:l?t+s:t-s,y:n});let o=-Math.PI/2+2*l*Math.PI/e;r.set(i,{x:t+s*Math.cos(o),y:n+a*Math.sin(o)})}),r},[U.join("|"),F,z,196,H,S]),V=(0,o.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]),J=s?.def,W=(s?.path??t??"").split("/").pop()||"…",K=[{id:"members",label:"Members",icon:(0,l.jsx)(rS,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,l.jsx)(ad,{}),badge:I.length+L.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],Z=f?P.get(f):void 0,G=(0,o.useMemo)(()=>{let e=[];for(let t of["error","warning"]){let n=new Map;for(let e of A?.issues??[])e.severity===t&&n.set(e.ruleId,[...n.get(e.ruleId)??[],e]);for(let[s,a]of[...n.entries()].sort((e,t)=>e[0].localeCompare(t[0])))e.push({key:`${t}:${s}`,ruleId:s,severity:t,issues:a})}return e},[A]);return(0,l.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>h&&u(!1),children:[(0,l.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,l.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,l.jsx)(rS,{kind:"system",size:14}),"SYS"]}),(0,l.jsx)(ac,{}),(0,l.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:s?.path,children:[J?.settings?.name??W,(0,l.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",W]})]}),(0,l.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,l.jsx)("button",{className:rk,onClick:a,title:"Read the system and every member again",children:"Re-check"}),(0,l.jsx)("button",{className:rk,onClick:()=>p(e=>!e),"aria-pressed":!m,children:m?"⟨ Panel":"Panel ⟩"})]}),(0,l.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,l.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,l.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,l.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{u(!1),a()},children:"Re-check the system"})})]})]}),(0,l.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,l.jsxs)("div",{ref:N,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[s&&J&&(0,l.jsx)(aT,{what:"system map",resetKey:s,children:(0,l.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${F} ${z}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${J.settings?.name}`,children:[[...P.entries()].map(([e,t])=>{let n=X.get(t.a),s=X.get(t.b);if(!n||!s)return null;let a=(n.x+s.x)/2,r=(n.y+s.y)/2,o=`${t.links.length} link${1===t.links.length?"":"s"}`,c=6.4*o.length+16,h=f===e;return(0,l.jsxs)("g",{className:"cursor-pointer",onClick:()=>{g(h?null:e),i("members"),d(!0)},children:[(0,l.jsx)("line",{x1:n.x,y1:n.y,x2:s.x,y2:s.y,stroke:"transparent",strokeWidth:18}),(0,l.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,l.jsx)("rect",{x:a-c/2,y:r-11,width:c,height:22,rx:11,fill:"#0f172a",stroke:h?"#3b82f6":"#334155"}),(0,l.jsx)("text",{x:a,y:r+4,textAnchor:"middle",fontSize:11.5,fill:h?"#93c5fd":"#cbd5e1",children:o})]},e)}),Y.map((e,t)=>{let n=(t+1)*F/(Y.length+1),s=z-30;return(0,l.jsxs)("g",{children:[(V.get(e.name)??[]).map(e=>{let t=X.get(e);return t?(0,l.jsx)("line",{x1:n,y1:s-14,x2:t.x,y2:t.y+46,stroke:"#334155",strokeDasharray:"3 4"},e):null}),(0,l.jsx)("title",{children:[`${e.kind}`,e.description??"",e.wheelNode??""].filter(Boolean).join(" — ")}),(0,l.jsx)("rect",{x:n-62,y:s-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,l.jsx)("g",{transform:`translate(${n-54} ${s-8})`,color:"#a5b4fc",children:(0,l.jsx)(rS,{kind:"actor",size:16})}),(0,l.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,l.jsx)("text",{x:n-34,y:s+9,fontSize:8.5,fill:"#94a3b8",children:e.kind})]},e.name)}),U.map(e=>{let t=X.get(e),n=s.members.find(t=>t.path===e);if(!t||!n)return null;let a=n.kind,r=(A?.issues??[]).filter(t=>t.member===e),i=r.filter(e=>"error"===e.severity).length,o=r.filter(e=>"warning"===e.severity).length,c=t.x-98,d=t.y-46,h=rX(s,e),u=Z&&(Z.a===e||Z.b===e);return(0,l.jsxs)("g",{className:"cursor-pointer",onClick:()=>D(e),children:[(0,l.jsx)("title",{children:`${e}${n.error?` — cannot be read: ${n.error}`:""}
14
+ Tap to open it inside the system.`}),(0,l.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,l.jsx)("g",{transform:`translate(${c+10} ${d+9})`,color:"#93c5fd",children:(0,l.jsx)(rS,{kind:a,size:16})}),(0,l.jsx)("text",{x:c+32,y:d+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:rK[a]}),(0,l.jsx)("text",{x:c+10,y:d+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:h.length>22?`${h.slice(0,21)}…`:h}),(0,l.jsx)("text",{x:c+10,y:d+60,fontSize:10.5,fill:"#94a3b8",children:n.error?"cannot be read":rZ(a,n.def,!0)}),(0,l.jsx)("text",{x:c+10,y:d+79,fontSize:10.5,fill:i?"#fca5a5":o?"#fcd34d":"#4ade80",children:n.error?n.error.length>30?`${n.error.slice(0,29)}…`:n.error:i||o?[i?`${i} error${i>1?"s":""}`:"",o?`${o} warning${o>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,l.jsx)("text",{x:c+196-10,y:d+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},e)})]})}),s&&!J&&(0,l.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:s.error}),(0,l.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,l.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===b.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,l.jsx)("span",{className:`truncate transition-opacity duration-500 ${E&&"ok"===b.tone?"opacity-0":"opacity-100"}`,children:b.text})]})]}),c&&(0,l.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:$.close,"aria-hidden":"true"}),s&&J&&(0,l.jsxs)("aside",{style:$.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,l.jsxs)("div",{className:"md:hidden",...$.zoneProps,children:[(0,l.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,l.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,l.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:K.find(e=>e.id===r)?.label}),(0,l.jsx)("button",{onClick:$.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,l.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:K.map(e=>(0,l.jsxs)("button",{onClick:()=>i(e.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${r===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,l.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,l.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,l.jsxs)("section",{className:"members"===r?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Members"}),U.map(e=>{let t=s.members.find(t=>t.path===e),n=J.members.find(t=>t.path===e)?.notes;return(0,l.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,l.jsxs)("button",{onClick:()=>D(e),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,l.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,l.jsx)(rS,{kind:t?.kind??"machine"})}),(0,l.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,l.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:rX(s,e)}),(0,l.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:e}),(0,l.jsx)("span",{className:`block text-[11px] ${t?.error?"text-red-300":"text-gray-400"}`,children:t?.error?`cannot be read: ${t.error}`:rZ(t?.kind??"machine",t?.def)})]}),(0,l.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),n||x.has(e)?(0,l.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,l.jsx)(rw,{label:"Note on this member, in the system",value:n??"",placeholder:`Why ${rX(s,e)} is part of this system, what is open…`,onSave:t=>void q(function(e,t,n){let s=eK(e),a=s.members.findIndex(e=>e.path===t);if(a<0)throw Error(`'${t}' is not a member. Members: ${e.members.map(e=>e.path).join(", ")||"none"}.`);return s.members[a]=eZ({...s.members[a],...n}),s}(J,e,{notes:t}),"saved")},`member:${e}`)}):(0,l.jsx)("button",{className:"mx-2 mb-1.5 text-[11px] text-gray-500 hover:text-gray-300",onClick:()=>y(t=>new Set(t).add(e)),children:"Add a note on this member"})]},e)}),(0,l.jsx)("div",{className:r$,children:"Links between members"}),0===P.size&&(0,l.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...P.entries()].map(([e,t])=>(0,l.jsxs)("div",{className:"mb-1",children:[(0,l.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,l.jsxs)("span",{className:"truncate",children:[rX(s,t.a)," ","↔︎"," ",rX(s,t.b)]}),(0,l.jsx)("span",{className:"shrink-0 text-gray-500",children:t.links.length})]}),f===e&&(0,l.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:t.links.map((e,t)=>(0,l.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${rQ(e)} — ${e.rule}`,onClick:()=>{let t;return D((t=e.from).member,e7(t))},children:[(0,l.jsx)("span",{className:"text-gray-600",children:e.rule})," ",rQ(e)]},t))})]},e)),Y.length>0&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:r$,children:"Actors"}),Y.map(e=>(0,l.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[e.name," ",(0,l.jsxs)("span",{className:"text-gray-500",children:["· ",e.kind]}),e.description?(0,l.jsxs)("span",{className:"text-gray-500",children:[" — ",e.description]}):null]},e.name))]})]}),(0,l.jsxs)("section",{className:"checks"===r?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Checks"}),(0,l.jsxs)("div",{className:`text-[11px] ${I.length?"text-red-300":L.length?"text-amber-300":"text-green-400"}`,children:[I.length," error",1===I.length?"":"s"," · ",L.length," warning",1===L.length?"":"s"]}),G.map(e=>(0,l.jsxs)("div",{className:"mt-2",children:[(0,l.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,l.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{e.member&&D(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,l.jsxs)("span",{className:"text-gray-500",children:[" — ",rX(s,e.member)]})]},t))]},e.key)),(0,l.jsx)("div",{className:r$,children:"Reconcile"}),(0,l.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,l.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,l.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,l.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:eB.map(e=>(0,l.jsx)("button",{"aria-pressed":T===e,onClick:()=>{s?.def&&e!==T&&q(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 ${T===e?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:e},e))}),(0,l.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),_&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:"text-[11px] text-gray-500",children:tr(_,"propose")}),_.machines.map(e=>(0,l.jsxs)("div",{className:"mt-1",children:[(0,l.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.machine," ",(0,l.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,l.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.erds.map(e=>(0,l.jsxs)("div",{className:"mt-1",children:[(0,l.jsxs)("div",{className:"text-[11px] text-gray-300",children:[e.def.settings?.name??e.member," ",(0,l.jsxs)("span",{className:"text-gray-500",children:["· ",e.member]})]}),e.reasons.map((e,t)=>(0,l.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]},e.member)),_.system&&(0,l.jsxs)("div",{className:"mt-1",children:[(0,l.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),_.system.reasons.map((e,t)=>(0,l.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",e]},t))]}),_.unresolved.map((e,t)=>(0,l.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",e]},t)),(0,l.jsx)("button",{className:`${rk} mt-2 disabled:opacity-40`,disabled:!_.count||j,onClick:B,children:j?"Applying…":`Apply${_.count?` ${_.count} change${1===_.count?"":"s"}`:""}`})]}),(A?.replays??[]).map(({member:e,report:t})=>(0,l.jsxs)("div",{children:[(0,l.jsxs)("div",{className:r$,children:["Replay · ",rX(s,e)]}),(0,l.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",t.machines.join(", ")||"no machine"]}),t.paths.map(t=>(0,l.jsxs)("div",{className:"mb-2",children:[(0,l.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,l.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:()=>D(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,l.jsxs)("section",{className:"notes"===r?"":"hidden",children:[(0,l.jsx)("div",{className:r$,style:{marginTop:0},children:"Notes"}),(0,l.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,l.jsx)(rw,{label:"On this system",value:J.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:e=>void q(eG(J,{notes:e}),"saved")},"system"),J.settings?.description&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("div",{className:r$,children:"Description"}),(0,l.jsx)("p",{className:"text-[11px] text-gray-400",children:J.settings.description})]})]})]})]})]}),(0,l.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:K.map(e=>{let t=c&&r===e.id;return(0,l.jsxs)("button",{onClick:()=>{var t;return t=e.id,void(c&&r===t?$.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,l.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,l.jsx)("span",{children:e.label}),void 0!==e.badge&&(0,l.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,l.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})})]})}function r1(){let e=sZ(e=>e.definition),t=sZ(e=>e.layout.positions),n=sZ(e=>e.navigationPath),s=sZ(e=>e.viewport),a=sZ(e=>e.setViewport),r=sZ(e=>e.docPath),i=az("focus"),c=(0,o.useMemo)(()=>({get current(){return document.getElementById("machine-board")}}),[]),d=n.slice(1),h=(0,o.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 a=s?.name?t[s.name]:void 0;if(a)for(let r of s.transitions??[]){if(!r?.event)continue;let s=r.nextState?t[r.nextState]:void 0;n.push({focus:`event:${r.event}`,box:s&&e.some(e=>e.name===r.nextState)?tb([a,s]):a})}}return n}(tS(e.state,d),t):[],[e,t,n]);return(0,l.jsx)(ro,{docPath:r,kind:"machine",viewport:s,setViewport:a,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(aD))}})}let r2=e=>e.parallel?e.parallel.states:e.states??[];function r5(e,t){if(!e)return null;if(e.name===t)return[e.name];for(let n of r2(e)){let s=r5(n,t);if(s)return[e.name,...s]}return null}function r4(){let e=(0,ao.useRequestedDoc)(),t=az("system"),[n,s]=(0,o.useState)(null);(0,o.useEffect)(()=>{let e=!0;return ay().then(t=>{e&&s(t.projectFile?eH(t.projectFile):"machine")}),()=>{e=!1}},[]);let a=e?eH(e):n;if(null===a)return(0,l.jsx)("div",{className:"app-shell bg-gray-950"});let r=e??"default",i="erd"===a?(0,l.jsx)(rb,{},r):"sequence"===a?(0,l.jsx)(rH,{},r):"system"===a?(0,l.jsx)(r0,{},r):(0,l.jsx)(r3,{}),c=(0,l.jsx)(aT,{what:"document",resetKey:e,children:i});return t&&eU(t)?(0,l.jsx)(ra,{children:(0,l.jsxs)("div",{className:"system-frame",children:[(0,l.jsx)(rW,{systemPath:t}),c]})}):(0,l.jsx)(ra,{children:c})}function r3(){var e,t;let n,s,a,r;n=aH(),s=(0,o.useRef)(null),(0,o.useEffect)(()=>{let e=()=>{let e=s.current;if(!e)return;let t=sZ.getState(),n=aF("doc");if(n&&t.docPath!==n||e.docAt!==t.docPath&&t.definition===e.defAt)return;s.current=null;let a=e9(e.focus);if(!a)return;let r=null,i=null;if("state"===a.kind)(r=r5(t.definition.state,a.name))&&(i={kind:"state",id:a.name});else if("event"===a.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 r2(t)){let t=e(s,n);if(t)return t}return null}(t.definition.state,a.name);e&&(r=r5(t.definition.state,e.state),i={kind:"transition",id:`${e.state}:${e.index}`})}if(!r||!i)return;let l=r.length>1?r.slice(0,-1):r;sZ.setState({navigationPath:l,currentParent:l[l.length-1]}),t.select(i.kind,i.id);let o=()=>{let e=sZ.getState().layout.positions[r[r.length-1]],t=document.getElementById(s1)?.getBoundingClientRect();if(!e||!t?.width)return;let n=H([e],t.width,t.height,{padding:60,maxScale:1});sZ.getState().setViewport(n)};requestAnimationFrame(o),setTimeout(o,450)};if(n.nonce>0){let t=sZ.getState();s.current=n.focus?{focus:n.focus,docAt:t.docPath,defAt:t.definition}:null,e()}return sZ.subscribe(e)},[n]),(0,o.useEffect)(()=>sZ.subscribe((e,t)=>{if(e.selection===t.selection||!e.selection.id)return;let{kind:n,id:s}=e.selection;if("state"===n)aY(`state:${s}`);else if("event"===n)aY(`event:${s}`);else if("transition"===n){let t=function(e,t){let n=t.lastIndexOf(":"),s=r5(e.state,t.slice(0,n));if(!s)return null;let a=e.state;for(let e of s.slice(1))a=r2(a).find(t=>t.name===e);return a?.transitions?.[Number(t.slice(n+1))]?.event??null}(e.definition,s);t&&aY(`event:${t}`)}}),[]);let[i,c]=(0,o.useState)("properties"),[d,h]=(0,o.useState)(!1),u=aI({onClose:()=>h(!1),restVh:70,tallVh:92}),m=sZ(e=>e.errors),p=sZ(e=>e.contextMenu),f=sZ(e=>e.hideContextMenu),g=sZ(e=>e.addState),x=sZ(e=>e.removeState),y=sZ(e=>e.setDrawMode),b=sZ(e=>e.setDrawSource),w=[{id:"properties",label:"Properties",icon:(0,l.jsx)(at,{name:"sliders",size:16})},{id:"events",label:"Events",icon:(0,l.jsx)(at,{name:"bolt",size:16})},{id:"settings",label:"Settings",icon:(0,l.jsx)(at,{name:"gear",size:16})},{id:"validation",label:"Errors",icon:(0,l.jsx)(ad,{}),badge:m.length||void 0}],v=w.find(e=>e.id===i)?.label??"";return(0,l.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>p.visible&&f(),children:[(0,l.jsx)(ab,{}),(0,l.jsx)(aO,{}),(0,l.jsx)(au,{}),(0,l.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,l.jsxs)("div",{className:"relative flex-1 overflow-hidden",id:"machine-board",children:[(0,l.jsx)(aT,{what:"state machine",children:(0,l.jsx)(ae,{})}),(0,l.jsx)(r1,{})]}),d&&(0,l.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:u.close,"aria-hidden":"true"}),(0,l.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,l.jsxs)("div",{className:"md:hidden",...u.zoneProps,children:[(0,l.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,l.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,l.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:v}),(0,l.jsx)("button",{onClick:u.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,l.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:w.map(e=>(0,l.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,l.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,l.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===i&&(0,l.jsx)(as,{}),"events"===i&&(0,l.jsx)(ar,{}),"settings"===i&&(0,l.jsx)(ai,{}),"validation"===i&&(0,l.jsx)(al,{})]})]}),(0,l.jsx)(am,{})]}),(0,l.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:w.map(e=>{let t=d&&i===e.id;return(0,l.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,l.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:e.icon}),(0,l.jsx)("span",{children:e.label}),void 0!==e.badge&&e.badge>0&&(0,l.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,l.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},e.id)})}),p.visible&&(0,l.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,a=window.innerWidth,r=window.innerHeight,{left:e,top:t,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:`translate(${a>0&&e>a/2?"-100%":"0"}, ${r>0&&t>r/2?"-100%":"0"})`}),onClick:e=>e.stopPropagation(),children:p.target?.kind==="state"?(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("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:[(0,l.jsx)(at,{name:"draw"})," Draw transition from here"]}),(0,l.jsxs)("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:[(0,l.jsx)(at,{name:"trash"})," Delete state"]})]}):(0,l.jsx)(l.Fragment,{children:(0,l.jsxs)("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:[(0,l.jsx)(at,{name:"plus"})," Add state here"]})})})]})}e.s(["default",()=>r4],63052)}]);