redlinify 0.0.0-stage → 0.4.0

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +341 -2
  3. package/dist/_shared/atomicFs.d.ts +10 -0
  4. package/dist/_shared/atomicFs.d.ts.map +1 -0
  5. package/dist/_shared/atomicFs.js +86 -0
  6. package/dist/_shared/atomicFs.js.map +1 -0
  7. package/dist/_shared/browser.d.ts +7 -0
  8. package/dist/_shared/browser.d.ts.map +1 -0
  9. package/dist/_shared/browser.js +7 -0
  10. package/dist/_shared/browser.js.map +1 -0
  11. package/dist/_shared/canonical.d.ts +8 -0
  12. package/dist/_shared/canonical.d.ts.map +1 -0
  13. package/dist/_shared/canonical.js +28 -0
  14. package/dist/_shared/canonical.js.map +1 -0
  15. package/dist/_shared/diff.d.ts +78 -0
  16. package/dist/_shared/diff.d.ts.map +1 -0
  17. package/dist/_shared/diff.js +350 -0
  18. package/dist/_shared/diff.js.map +1 -0
  19. package/dist/_shared/errors.d.ts +29 -0
  20. package/dist/_shared/errors.d.ts.map +1 -0
  21. package/dist/_shared/errors.js +46 -0
  22. package/dist/_shared/errors.js.map +1 -0
  23. package/dist/_shared/fileLock.d.ts +11 -0
  24. package/dist/_shared/fileLock.d.ts.map +1 -0
  25. package/dist/_shared/fileLock.js +114 -0
  26. package/dist/_shared/fileLock.js.map +1 -0
  27. package/dist/_shared/guards.d.ts +20 -0
  28. package/dist/_shared/guards.d.ts.map +1 -0
  29. package/dist/_shared/guards.js +395 -0
  30. package/dist/_shared/guards.js.map +1 -0
  31. package/dist/_shared/hash.d.ts +12 -0
  32. package/dist/_shared/hash.d.ts.map +1 -0
  33. package/dist/_shared/hash.js +80 -0
  34. package/dist/_shared/hash.js.map +1 -0
  35. package/dist/_shared/index.d.ts +9 -0
  36. package/dist/_shared/index.d.ts.map +1 -0
  37. package/dist/_shared/index.js +9 -0
  38. package/dist/_shared/index.js.map +1 -0
  39. package/dist/_shared/schemas.d.ts +727 -0
  40. package/dist/_shared/schemas.d.ts.map +1 -0
  41. package/dist/_shared/schemas.js +352 -0
  42. package/dist/_shared/schemas.js.map +1 -0
  43. package/dist/_shared/storage.d.ts +174 -0
  44. package/dist/_shared/storage.d.ts.map +1 -0
  45. package/dist/_shared/storage.js +801 -0
  46. package/dist/_shared/storage.js.map +1 -0
  47. package/dist/_shared/threadStatus.d.ts +5 -0
  48. package/dist/_shared/threadStatus.d.ts.map +1 -0
  49. package/dist/_shared/threadStatus.js +18 -0
  50. package/dist/_shared/threadStatus.js.map +1 -0
  51. package/dist/cli.d.ts +3 -0
  52. package/dist/cli.d.ts.map +1 -0
  53. package/dist/cli.js +269 -0
  54. package/dist/cli.js.map +1 -0
  55. package/dist/index.d.ts +5 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +5 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/mcp.d.ts +19 -0
  60. package/dist/mcp.d.ts.map +1 -0
  61. package/dist/mcp.js +654 -0
  62. package/dist/mcp.js.map +1 -0
  63. package/dist/preferences.d.ts +5 -0
  64. package/dist/preferences.d.ts.map +1 -0
  65. package/dist/preferences.js +56 -0
  66. package/dist/preferences.js.map +1 -0
  67. package/dist/uiDaemon.d.ts +47 -0
  68. package/dist/uiDaemon.d.ts.map +1 -0
  69. package/dist/uiDaemon.js +351 -0
  70. package/dist/uiDaemon.js.map +1 -0
  71. package/dist/updater.d.ts +35 -0
  72. package/dist/updater.d.ts.map +1 -0
  73. package/dist/updater.js +336 -0
  74. package/dist/updater.js.map +1 -0
  75. package/dist/web.d.ts +29 -0
  76. package/dist/web.d.ts.map +1 -0
  77. package/dist/web.js +648 -0
  78. package/dist/web.js.map +1 -0
  79. package/package.json +51 -4
  80. package/skill/SKILL.md +36 -0
  81. package/ui-dist/assets/elkjs-DuIp8wh-.js +26 -0
  82. package/ui-dist/assets/index-DhMWEByx.css +1 -0
  83. package/ui-dist/assets/index-Dy_FwyNG.js +99 -0
  84. package/ui-dist/assets/vendor-icons-IOjDvVjt.js +261 -0
  85. package/ui-dist/assets/vendor-react-5-35apmZ.js +49 -0
  86. package/ui-dist/assets/vendor-xyflow-BnuhLJ6X.css +1 -0
  87. package/ui-dist/assets/vendor-xyflow-cY2i6Lf0.js +23 -0
  88. package/ui-dist/index.html +29 -0
@@ -0,0 +1,99 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/elkjs-DuIp8wh-.js","assets/vendor-react-5-35apmZ.js"])))=>i.map(i=>d[i]);
2
+ var il=Object.defineProperty;var al=(e,t,n)=>t in e?il(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Gt=(e,t,n)=>al(e,typeof t!="symbol"?t+"":t,n);import{a as v,j as o,b as ll,d as cl}from"./vendor-react-5-35apmZ.js";import{u as ei,g as dl,B as ul,E as fl,P as et,H as gn,R as hl,a as pl,b as ml,i as xl,C as gl,c as yl,d as Lr,e as bl,M as vl}from"./vendor-xyflow-cY2i6Lf0.js";import{P as xt,C as Ot,U as kl,R as wl,A as _l,L as jl,S as $l,D as Zt,a as Nl,b as Sl,c as Rs,X as $t,d as Fs,B as Ml,G as Cl,M as Us,e as an,f as Un,g as Hs,h as El,T as sn,i as $s,E as Ws,j as Ns,k as Ks,l as Br,m as Zr,n as Ol,o as zl,p as qs,q as Rt,r as Js,s as Rr,K as Tl,t as Pl,u as Al,v as Dl,w as Il,x as Ll,y as Bl,z as Zl,F as Rl,H as Fl,I as Ul,J as Fr,N as Hl,O as Wl,W as Kl}from"./vendor-icons-IOjDvVjt.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();function Ss(e){const t=Object.values(e).filter(s=>typeof s=="number");return Object.entries(e).filter(([s,r])=>t.indexOf(+s)===-1).map(([s,r])=>r)}function Ur(e,t="|"){return e.map(n=>oi(n)).join(t)}function Ms(e,t){return typeof t=="bigint"?t.toString():t}class ql{constructor(t){this._getter=t,this._value=void 0}get value(){const t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}}function Hn(e){return new ql(e)}function Jl(e){return e==null}function Xs(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Xl(e,t){const n=e/t,s=Math.round(n),r=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-s)<r?0:n-s}function yt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ys(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t!=null&&t.get?t.get.raw:t==null?void 0:t.value}function gt(e){return Ys(e._zod.def)??e._zod.def.shape}function ti(e,t,n){Object.defineProperty(e,t,{get(){const s=n();return yt(this,t,s),s},enumerable:!0,configurable:!0})}function ni(e,t,n){t in e?yt(e,t,n):e[t]=n}function zt(e,t,n,s){const r=gt(t);for(const i of n){const a=Object.getOwnPropertyDescriptor(r,i);a.enumerable&&(a.get?ti(e,i,()=>{const l=t._zod.def.shape[i];return s?s(l,i):l}):ni(e,i,s?s(a.value,i):a.value))}}function Yl(e,t){for(const n of Reflect.ownKeys(t)){const s=Object.getOwnPropertyDescriptor(t,n);s.enumerable&&(s.get?ti(e,n,()=>t[n]):ni(e,n,s.value))}}function st(...e){const t={};for(const n of e){const s=Object.getOwnPropertyDescriptors(n);Object.assign(t,s)}return Object.defineProperties({},t)}function Gl(e){return JSON.stringify(e)}function Ql(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const si="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Vl=Hn(()=>{var e;if(at.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ft(e){if(ln(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(ln(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function ri(e){return Ft(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const ec=new Set(["string","number","symbol"]);function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(e,t,n){const s=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(s._zod.parent=e),s}function de(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function oi(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function tc(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}const ii={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sc(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i={};return zt(i,e,Wn(e,t)),Ct(e,st(n,{shape:i,checks:[]}))}function Wn(e,t){var r;const n=gt(e),s=[];for(const i of Reflect.ownKeys(t)){if(!((r=Object.getOwnPropertyDescriptor(n,i))!=null&&r.enumerable))throw new Error(`Unrecognized key: "${String(i)}"`);t[i]&&s.push(i)}return s}function rc(e,t){const n=e._zod.def,s=n.checks;if(s&&s.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=new Set(Wn(e,t)),a={};return zt(a,e,Reflect.ownKeys(gt(e)).filter(l=>!i.has(l))),Ct(e,st(n,{shape:a,checks:[]}))}function oc(e,t){if(!Ft(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=gt(e);for(const i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ct(e,st(e._zod.def,{shape:ai(e,t)}))}function ai(e,t){const n={};return zt(n,e,Reflect.ownKeys(gt(e))),Yl(n,t),n}function ic(e,t){if(!Ft(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Ct(e,st(e._zod.def,{shape:ai(e,t)}))}function ac(e,t){var r,i;if(!((r=t==null?void 0:t._zod)!=null&&r.def))throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if((i=e._zod.def.checks)!=null&&i.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};zt(n,e,Reflect.ownKeys(gt(e))),zt(n,t,Reflect.ownKeys(gt(t)));const s=st(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ct(e,s)}function Hr(e,t,n,s="partial"){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${s}() cannot be used on object schemas containing refinements`);const l=n?new Set(Wn(t,n)):void 0,d={};return zt(d,t,Reflect.ownKeys(gt(t)),e&&((u,c)=>l&&!l.has(c)?u:new e({type:"optional",innerType:u}))),Ct(t,st(t._zod.def,{shape:d,checks:[]}))}function lc(e,t,n){const s=n?new Set(Wn(t,n)):void 0,r={};return zt(r,t,Reflect.ownKeys(gt(t)),(i,a)=>s&&!s.has(a)?i:new e({type:"nonoptional",innerType:i})),Ct(t,st(t._zod.def,{shape:r}))}function pt(e,t=0){var n;if(e.aborted===!0)return!0;for(let s=t;s<e.issues.length;s++)if(((n=e.issues[s])==null?void 0:n.continue)!==!0)return!0;return!1}function cc(e,t=0){var n;if(e.aborted===!0)return!0;for(let s=t;s<e.issues.length;s++)if(((n=e.issues[s])==null?void 0:n.continue)===!1)return!0;return!1}function Bt(e,t){return t.map(n=>{var s;return(s=n).path??(s.path=[]),n.path.unshift(e),n})}function Qt(e){return typeof e=="string"?e:e==null?void 0:e.message}function Wr(e){const t=[];for(const n of e??[]){const s=n._zod.def;if(!/_(length|size)$|_equals$/.test(s.check))break;const r=s.maximum??s.length??s.size;r>=0&&t.push([r,n])}return t}function Cs(e,t,n){var s;for(let r=t;r<e.length;r++)(s=e[r]).schema??(s.schema=n)}function Nt(e,t,n){var d,u,c,f,p,h,x,m,g,y;var s;const r=(u=(d=e.inst)==null?void 0:d._zod)==null?void 0:u.traits;r!=null&&r.has("$ZodType")&&(r.has("$ZodCheck")?(s=e).schema??(s.schema=e.inst):e.schema=e.inst);const i=e.schema!==e.inst?(f=(c=e.schema)==null?void 0:c._zod.def)==null?void 0:f.error:void 0,a=e.message?e.message:Qt((x=(h=(p=e.inst)==null?void 0:p._zod.def)==null?void 0:h.error)==null?void 0:x.call(h,e))??Qt(i==null?void 0:i(e))??Qt((m=t==null?void 0:t.error)==null?void 0:m.call(t,e))??Qt((g=n.customError)==null?void 0:g.call(n,e))??Qt((y=n.localeError)==null?void 0:y.call(n,e))??"Invalid input",l={};for(const b of Object.keys(e))b==="inst"||b==="schema"||b==="continue"||b==="input"||b==="__proto__"||(l[b]=e[b]);return l.path??(l.path=[]),l.message=a,t!=null&&t.reportInput&&(l.input=e.input),l}const dc=/[\uD800-\uDBFF]/;function Gs(e){const t=e.length;if(!dc.test(e))return t;let n=t;for(let s=0;s<t-1;s++)(e.charCodeAt(s)&64512)===55296&&(e.charCodeAt(s+1)&64512)===56320&&(n--,s++);return n}function Qs(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function uc(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function cn(...e){const[t,n,s]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:s}:{...t}}function fc(e,t){for(const n in t){const s=Object.getOwnPropertyDescriptor(t,n);s.get?Object.defineProperty(e,n,{...s,enumerable:!1}):hc(e,n,s.value)}}function St(e,t,n,s=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:s,value:n}),n}function li(e,t,n){return St(e,t,n,!1)}function ci(e,t){for(const n in e){const s=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return St(this,n,s(this))},set(r){St(this,n,r)}})}return t}function hc(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:St(this,t,n.bind(this))},set(s){St(this,t,s)}})}function pc(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let ms,_t=!1;const mc={configurable:!0,get(){_t=!0}};function Ee(e,t,n){const s=Object.getPrototypeOf(e._zod);if(t in s&&ms!==e._zod){ms=void 0;return}ms=e._zod,Object.defineProperty(s,t,{configurable:!0,get(){Object.defineProperty(this,t,mc);const r=_t;_t=!1;try{const i=n(this);return _t?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),_t=_t||r,i}catch(i){throw delete this[t],_t=_t||r,i}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function xc(e,t,n,s){const r=pc(e,t);r&&Object.defineProperty(r,t,{configurable:!0,get(){const i={configurable:!0,writable:!0,enumerable:s,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:s,value:i})}})}const gc="~constantCatch";function yc(e){const t=()=>e;return t[gc]=!0,t}var Kr;const xs={value:void 0,enumerable:!1};let qr="captureStackTrace"in Error?Error:null;function bc(e){const t=qr;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return qr=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function I(e,t,n,s){const r={};function i(p){this.def=p,this.constr=f,this.traits=new Set}i.prototype=r;const a=n,l=a&&new WeakSet;function d(p,h){if(p._zod){if(p._zod.traits.has(e))return}else{xs.value=new i(h);try{Object.defineProperty(p,"_zod",xs)}finally{xs.value=void 0}}if(p._zod.traits.add(e),t(p,h),l){const m=Object.getPrototypeOf(p),g=p._zod.constr.prototype;let y=m;for(;y&&y!==g;)y=Object.getPrototypeOf(y);const b=y??m;l.has(b)||(l.add(b),fc(b,a))}const x=f.prototype;for(const m in x)Object.prototype.hasOwnProperty.call(x,m)&&(m in p||(p[m]=x[m].bind(p)))}const u=(s==null?void 0:s.Parent)??Object;class c extends u{}Object.defineProperty(c,"name",{value:e});function f(p){var g;const h=s!=null&&s.Parent?bc(c):this;d(h,p);const x=h._zod.deferred;if(x){for(const y of x)y();h._zod.deferred=void 0}const m=(g=globalThis.__zod_globalConfig)==null?void 0:g.postProcessor;return m&&m(h),h}return Object.defineProperty(f,"init",{value:d}),Object.defineProperty(f,Symbol.hasInstance,{value:p=>{var h,x;return s!=null&&s.Parent&&p instanceof s.Parent?!0:(x=(h=p==null?void 0:p._zod)==null?void 0:h.traits)==null?void 0:x.has(e)}}),Object.defineProperty(f,"name",{value:e}),f}class Et extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class di extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Kr=globalThis).__zod_globalConfig??(Kr.__zod_globalConfig={});const at=globalThis.__zod_globalConfig;function ut(e){return e&&Object.assign(at,e),at}function vc(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Ms,2)),e.message}function kc(e){this._zod.message=e}const wc={get:vc,set:kc,enumerable:!0,configurable:!0},gs={value:void 0,enumerable:!1},Jr=new WeakSet([Object.prototype,Error.prototype]),_c=(e,t)=>{e.name="$ZodError",gs.value=t,Object.defineProperty(e,"issues",gs),gs.value=void 0,Object.defineProperty(e,"message",wc);const n=Object.getPrototypeOf(e);Jr.has(n)||(Jr.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const s=()=>this.message;return Object.defineProperty(this,"toString",{value:s,configurable:!0,writable:!0}),s},set(s){Object.defineProperty(this,"toString",{value:s,configurable:!0,writable:!0})}}))},jc=I("$ZodError",_c);function $c(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Nc(e,t=n=>n.message){const n={},s=[];for(const r of e.issues)r.path.length>0?$c(n,r.path[0],()=>[]).push(t(r)):s.push(t(r));return{formErrors:s,fieldErrors:n}}function Sc(e,t=n=>n.message){const n={_errors:[]},s=(r,i=[])=>{for(const a of r.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(l=>s({issues:l},[...i,...a.path]));else if(a.code==="invalid_key")s({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")s({issues:a.issues},[...i,...a.path]);else{const l=[...i,...a.path];if(l.length===0)n._errors.push(t(a));else{let d=n,u=0;for(;u<l.length;){const c=l[u],f=u===l.length-1;if(c==="_errors"){f&&d._errors.push(t(a)),u++;continue}Object.prototype.hasOwnProperty.call(d,c)||Object.defineProperty(d,c,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const p=d[c];f&&p._errors.push(t(a)),d=p,u++}}}};return s(e),n}function Kn(e,t){return{callee:(t==null?void 0:t.callee)??e,Err:t==null?void 0:t.Err}}const Vs=e=>{const t=(n,s,r,i)=>{const a=r?{...r,async:!1}:{async:!1},l=n._zod.run({value:s,issues:[]},a);if(l instanceof Promise)throw new Et;if(l.issues.length){const d=new((i==null?void 0:i.Err)??e)(l.issues.map(u=>Nt(u,a,ut())));throw si(d,(i==null?void 0:i.callee)??t),d}return l.value};return t},er=e=>{const t=async(n,s,r,i)=>{const a=r?{...r,async:!0}:{async:!0};let l=n._zod.run({value:s,issues:[]},a);if(l instanceof Promise&&(l=await l),l.issues.length){const d=new((i==null?void 0:i.Err)??e)(l.issues.map(u=>Nt(u,a,ut())));throw si(d,(i==null?void 0:i.callee)??t),d}return l.value};return t},tr=e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Et;return i.issues.length?ui(e,i.issues,r):{success:!0,data:i.value}};function ui(e,t,n){let s;return{success:!1,get error(){return s||(s=new e(t.map(r=>Nt(r,n,ut()))),t=void 0,n=void 0),s},set error(r){s=r,t=void 0,n=void 0}}}const nr=e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?ui(e,i.issues,r):{success:!0,data:i.value}},Mc=Symbol.for("zod.compile.invalid"),Cc=Symbol.for("zod.compile.fallback"),Ec=((e,t,n)=>{const s=e._zod.bag.validator;if(s!==void 0){if(s(t)!==Mc)return!0;if(s.definite===!0&&n===void 0)return!1}return Oc(e,t,n)});function Oc(e,t,n){const s=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},r=e._zod.bag.fallbackRun;let i;if(r?(s[Cc]=!0,i=r({value:t,issues:[]},s)):i=e._zod.run({value:t,issues:[]},s),i instanceof Promise)throw new Et;return i.issues.length===0}const zc=async(e,t,n)=>{const s=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let r=e._zod.run({value:t,issues:[]},s);return r instanceof Promise&&(r=await r),r.issues.length===0},Tc=e=>{const t=Vs(e),n=(s,r,i,a)=>{const l=i?{...i,direction:"backward"}:{direction:"backward"};return t(s,r,l,Kn(n,a))};return n},Pc=e=>{const t=Vs(e),n=(s,r,i,a)=>t(s,r,i,Kn(n,a));return n},Ac=e=>{const t=er(e),n=async(s,r,i,a)=>{const l=i?{...i,direction:"backward"}:{direction:"backward"};return await t(s,r,l,Kn(n,a))};return n},Dc=e=>{const t=er(e),n=async(s,r,i,a)=>await t(s,r,i,Kn(n,a));return n},Ic=e=>(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return tr(e)(t,n,r)},Lc=e=>(t,n,s)=>tr(e)(t,n,s),Bc=e=>async(t,n,s)=>{const r=s?{...s,direction:"backward"}:{direction:"backward"};return nr(e)(t,n,r)},Zc=e=>async(t,n,s)=>nr(e)(t,n,s),Rc=/^[cC][0-9a-z]{6,}$/,Fc=/^[0-9a-z]+$/,Uc=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Hc=/^[0-9a-vA-V]{20}$/,Wc=/^[A-Za-z0-9]{27}$/,Kc=/^[a-zA-Z0-9_-]{21}$/;function qc(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Jc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xc=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xr=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Yc=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Gc="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Qc(){return new RegExp(Gc,"u")}const Vc=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ed=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,td=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,nd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rd=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,od=/^https?$/,id=/^\+[1-9]\d{6,14}$/,fi="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function ad(e){return new RegExp(`^${e}$`)}const ld=ad(fi);function Es(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function cd(e){return new RegExp(`^${Es(e)}$`)}function dd(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${Es({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,s=e.local?`${n}|${Es({precision:e.precision})}`:n;return new RegExp(`^${fi}T(?:${s})$`)}const ud=/^[\s\S]{0,}$/,fd=/^-?\d+$/,sr=/^-?\d+(?:\.\d+)?$/,hd=/^(?:true|false)$/i,pd=/^[^A-Z]*$/,md=/^[^a-z]*$/,tt=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),rr=e=>{const t=e.value;return!Jl(t)&&t.length!==void 0},zn={number:"number",bigint:"bigint",object:"date"},hi=I("$ZodCheckLessThan",(e,t)=>{tt.init(e,t);const n=zn[typeof t.value];e._zod.check=s=>{(t.inclusive?s.value<=t.value:s.value<t.value)||s.issues.push({origin:zn[typeof s.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),pi=I("$ZodCheckGreaterThan",(e,t)=>{tt.init(e,t);const n=zn[typeof t.value];e._zod.check=s=>{(t.inclusive?s.value>=t.value:s.value>t.value)||s.issues.push({origin:zn[typeof s.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:s.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xd=I("$ZodCheckMultipleOf",(e,t)=>{tt.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Xl(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),gd=I("$ZodCheckNumberFormat",(e,t)=>{var a;tt.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),s=n?"int":"number",[r,i]=ii[t.format];e._zod.check=l=>{const d=l.value;if(n){if(!Number.isInteger(d)){l.issues.push({expected:s,format:t.format,code:"invalid_type",continue:!1,input:d,inst:e});return}if(!Number.isSafeInteger(d)){d>0?l.issues.push({input:d,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort}):l.issues.push({input:d,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:s,inclusive:!0,continue:!t.abort});return}}d<r&&l.issues.push({origin:"number",input:d,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),d>i&&l.issues.push({origin:"number",input:d,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),yd=I("$ZodCheckMaxLength",(e,t)=>{var n;tt.init(e,t),(n=e._zod.def).when??(n.when=rr),e._zod.check=s=>{const r=s.value,i=r.length;if((typeof r=="string"&&i>t.maximum?Gs(r):i)<=t.maximum)return;const l=Qs(r);s.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),bd=I("$ZodCheckMinLength",(e,t)=>{var n;tt.init(e,t),(n=e._zod.def).when??(n.when=rr),e._zod.check=s=>{const r=s.value,i=r.length;if((typeof r=="string"&&i>=t.minimum&&i<t.minimum*2?Gs(r):i)>=t.minimum)return;const l=Qs(r);s.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vd=I("$ZodCheckLengthEquals",(e,t)=>{var n;tt.init(e,t),(n=e._zod.def).when??(n.when=rr),e._zod.check=s=>{const r=s.value,i=r.length,a=typeof r=="string"&&i>=t.length&&i<=t.length*2?Gs(r):i;if(a===t.length)return;const l=Qs(r),d=a>t.length;s.issues.push({origin:l,...d?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:s.value,inst:e,continue:!t.abort})}}),qn=I("$ZodCheckStringFormat",(e,t)=>{var n,s;tt.init(e,t),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(s=e._zod).check??(s.check=()=>{})}),kd=I("$ZodCheckRegex",(e,t)=>{qn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),wd=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=pd),qn.init(e,t)}),_d=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=md),qn.init(e,t)}),jd=I("$ZodCheckIncludes",(e,t)=>{tt.init(e,t);const n=Ut(t.includes),s=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=s,e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),$d=I("$ZodCheckStartsWith",(e,t)=>{tt.init(e,t);const n=new RegExp(`^${Ut(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=s=>{s.value.startsWith(t.prefix)||s.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:s.value,inst:e,continue:!t.abort})}}),Nd=I("$ZodCheckEndsWith",(e,t)=>{tt.init(e,t);const n=new RegExp(`.*${Ut(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=s=>{s.value.endsWith(t.suffix)||s.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:s.value,inst:e,continue:!t.abort})}}),Sd=I("$ZodCheckOverwrite",(e,t)=>{tt.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Md{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const s=t.split(`
3
+ `).filter(a=>a),r=Math.min(...s.map(a=>a.length-a.trimStart().length)),i=s.map(a=>a.slice(r)).map(a=>" ".repeat(this.indent*2)+a);for(const a of i)this.content.push(a)}compile(){const t=Function,n=(this==null?void 0:this.content)??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
4
+ ${n.join(`
5
+ `)}
6
+ };`)(...Object.values(this.closed))}}const Cd={major:4,minor:6,patch:7},Le=I("$ZodType",(e,t)=>{var i;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cd;const s=e._zod.def.checks,r=e._zod.traits.has("$ZodCheck")?[e,...s??[]]:s!=null&&s.length?[...s]:[];for(const a of r)for(const l of a._zod.onattach)l(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(i=e._zod.deferred)==null||i.push(()=>{e._zod.run=e._zod.parse});else{const a=(d,u,c)=>{if(d.memo)return d;let f=pt(d),p;for(const h of u){if(h._zod.def.when){if(cc(d)||!h._zod.def.when(d))continue}else if(f)continue;const x=d.issues.length,m=h._zod.check(d);if(m instanceof Promise&&(c==null?void 0:c.async)===!1)throw new Et;if(p||m instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await m,d.issues.length!==x&&(Cs(d.issues,x,e),f||(f=pt(d,x)))});else{if(d.issues.length===x)continue;Cs(d.issues,x,e),f||(f=pt(d,x))}}return p?p.then(()=>d):d},l=(d,u,c)=>{if(pt(d))return d.aborted=!0,d;const f=a(u,r,c);if(f instanceof Promise){if(c.async===!1)throw new Et;return f.then(p=>e._zod.parse(p,c))}return e._zod.parse(f,c)};e._zod.run=(d,u)=>{if(u.skipChecks)return e._zod.parse(d,u);if(u.direction==="backward"){const f=e._zod.parse({value:d.value,issues:[]},{...u,skipChecks:!0});return f instanceof Promise?f.then(p=>l(p,d,u)):l(f,d,u)}const c=e._zod.parse(d,u);if(c instanceof Promise){if(u.async===!1)throw new Et;return c.then(f=>a(f,r,u))}return a(c,r,u)}}},{get"~standard"(){return li(this,"~standard",xi(this))},set"~standard"(e){St(this,"~standard",e)}}),mi=(e,t)=>e.issues.length?{issues:e.issues.map(n=>Nt(n,t,ut()))}:{value:e.value};async function Ed(e,t){const n={async:!0};return mi(await e._zod.run({value:t,issues:[]},n),n)}function xi(e){return{validate:t=>{const n={async:!1};try{const s=e._zod.run({value:t,issues:[]},n);if(!(s instanceof Promise))return mi(s,n)}catch{}return Ed(e,t)},vendor:"zod",version:1}}const or=I("$ZodString",(e,t)=>{Le.init(e,t),e._zod.pattern=t.pattern??ud,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ie=I("$ZodStringFormat",(e,t)=>{qn.init(e,t),or.init(e,t)}),Od=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xc),Ie.init(e,t)}),zd=I("$ZodUUID",(e,t)=>{if(t.version){const s={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(s===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Xr(s))}else t.pattern??(t.pattern=Xr());Ie.init(e,t)}),Td=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Yc),Ie.init(e,t)}),gi=1,Tn=2;function yi(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Pd(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?yi(e)||Tn:Ad(e,t)}function Ad(e,t){var n;if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===od.source&&!/^https?:\/\//i.test(e))return gi;try{if(typeof URL<"u"){const s=URL;if(typeof s.parse=="function")return s.parse(e)??Tn}return new URL(e)}catch{return Tn}}const Dd=/[\t\n\r]/g;function Yr(e){return e.replace(Dd,"")}function Id(e,t){return t.lastIndex=0,t.test(e.hostname)}function Ld(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}const Bd=I("$ZodURL",(e,t)=>{Ie.init(e,t),e._zod.check=n=>{try{const s=n.value.trim(),r=Pd(s,t);if(r===gi){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(r===Tn){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(r===!0){n.value=Yr(s);return}t.hostname&&!Id(r,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Ld(r,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?r.href:Yr(s);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Zd=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Qc()),Ie.init(e,t)}),Rd=I("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Kc:qc(t.length)),Ie.init(e,t)}),Fd=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rc),Ie.init(e,t)}),Ud=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Fc),Ie.init(e,t)}),Hd=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Uc),Ie.init(e,t)}),Wd=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Hc),Ie.init(e,t)}),Kd=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Wc),Ie.init(e,t)}),qd=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=dd(t)),Ie.init(e,t)}),Jd=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ld),Ie.init(e,t)}),Xd=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cd(t)),Ie.init(e,t)}),Yd=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Jc),Ie.init(e,t)}),Gd=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Vc),Ie.init(e,t)}),Qd=/^[0-9a-fA-F:.]+$/;function bi(e){return Qd.test(e)?yi(`http://[${e}]`):!1}const Vd=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ed),Ie.init(e,t),e._zod.check=n=>{bi(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),eu=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=td),Ie.init(e,t)});function tu(e){const t=e.split("/");if(t.length!==2)return!1;const[n,s]=t;if(!s)return!1;const r=Number(s);return`${r}`!==s||r<0||r>128?!1:bi(n)}const nu=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=nd),Ie.init(e,t),e._zod.check=n=>{tu(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function vi(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ki=/^[0-9a-zA-Z+/]*={0,2}$/,su=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ki),Ie.init(e,t),e._zod.check=n=>{vi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),ir=/^[A-Za-z0-9_-]*$/;function ru(e){if(!ir.test(e))return!1;const t=e.replace(/[-_]/g,s=>s==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return vi(n)}const ou=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ir),Ie.init(e,t),e._zod.check=n=>{ru(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),iu=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=id),Ie.init(e,t)});function au(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[s]=n;if(!s)return!1;const r=JSON.parse(atob(s));return!("typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const lu=I("$ZodJWT",(e,t)=>{Ie.init(e,t),e._zod.check=n=>{au(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),wi=I("$ZodNumber",(e,t)=>{Le.init(e,t),e._zod.pattern=sr,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:String(r):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),cu=I("$ZodNumberFormat",(e,t)=>{gd.init(e,t),wi.init(e,t)}),du=I("$ZodBoolean",(e,t)=>{Le.init(e,t),e._zod.pattern=hd,e._zod.parse=(n,s)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),uu=I("$ZodUnknown",(e,t)=>{Le.init(e,t),e._zod.parse=n=>n}),fu=I("$ZodNever",(e,t)=>{Le.init(e,t),e._zod.parse=(n,s)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function hu(e,t){const n=Wr(e._zod.def.checks);if(!n.length)return;const s=Math.min(...n.map(i=>i[0])),r=e._zod.parse;e._zod.parse=(i,a)=>{const l=t(i.value);if(l>s&&!(a!=null&&a.skipChecks)&&(a==null?void 0:a.direction)!=="backward"){for(const[d,u]of Wr(e._zod.def.checks))if(l>d&&u._zod.def.when(i)){const c=i.issues.length;return u._zod.check(i),i.issues[c].continue=!1,Cs(i.issues,c,e),i}}return r(i,a)}}const pu=e=>Array.isArray(e)?e.length:-1;function Gr(e,t,n){e.issues.length&&t.issues.push(...Bt(n,e.issues)),t.value[n]=e.value}const mu=I("$ZodArray",(e,t)=>{Le.init(e,t);const n=at.memoizer;n==null||n.attach(e),e._zod.parse=(s,r)=>{const i=s.value;if(!Array.isArray(i))return s.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),s;s.value=n?n.alloc(e,s,Array(i.length),r):Array(i.length);const a=[],l=r==null?void 0:r.abortEarly;for(let d=0;d<i.length;d++){const u=i[d],c=t.element._zod.run({value:u,issues:[]},r);if(c instanceof Promise)a.push(c.then(f=>Gr(f,s,d)));else if(Gr(c,s,d),l&&c.issues.length!==0&&pt(c))break}return a.length?Promise.all(a).then(()=>s):s},hu(e,pu)});function Pn(e,t,n,s,r,i){const a=n in s,l=i==="optional";if(!(!a&&l&&r==="optional")){if(e.issues.length){if(r!==void 0&&l&&!a)return;t.issues.push(...Bt(n,e.issues))}if(!a&&r===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(a||r==="defaulted"&&!l)&&(t.value[n]=void 0):t.value[n]=e.value}}const xu=[];function _i(e){var a,l,d,u;const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),s=n.length?n:xu,r=s.length?[...t,...s]:t;for(const c of r)if(!((u=(d=(l=(a=e.shape)==null?void 0:a[c])==null?void 0:l._zod)==null?void 0:d.traits)!=null&&u.has("$ZodType")))throw new Error(`Invalid element at key "${String(c)}": expected a Zod schema`);const i=tc(e.shape);return{...e,allKeys:r,symbolKeys:s,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function ji(e,t,n,s,r,i,a){const l=[],d=r.keySet,u=r.catchall._zod,c=u.def.type,f=u.optin,p=u.optout;let h=0;for(const x in t){if(a&&n.issues.length!==h){if(pt(n,h))break;h=n.issues.length}if(d.has(x))continue;if(x==="__proto__"){c==="never"&&l.push(x);continue}if(c==="never"){l.push(x);continue}const m=u.run({value:t[x],issues:[]},s);m instanceof Promise?e.push(m.then(g=>Pn(g,n,x,t,f,p))):Pn(m,n,x,t,f,p)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const gu=I("$ZodObject",(e,t)=>{Le.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),s=n!=null&&n.get?n.get.raw:t.shape??{};if(s){const u=()=>{const c={...s};return Object.defineProperty(t,"shape",{value:c}),u.raw=c,c};u.raw=s,Object.defineProperty(t,"shape",{get:u})}const r=Hn(()=>_i(t));Ee(e,"propValues",u=>{const c=u.def.shape,f={};for(const p in c){const h=c[p]._zod;if(h.values){Object.prototype.hasOwnProperty.call(f,p)||yt(f,p,new Set);for(const x of h.values)f[p].add(x);h.optin!==void 0&&f[p].add(void 0)}}return f});const i=ln,a=t.catchall;let l;const d=at.memoizer;d==null||d.attach(e),e._zod.parse=(u,c)=>{l??(l=r.value);const f=u.value;if(!i(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u;u.value=d?d.alloc(e,u,{},c):{};const p=[],h=l.shape,x=c==null?void 0:c.abortEarly;let m=u.issues.length;for(const g of l.allKeys){if(x&&u.issues.length!==m){if(pt(u,m))break;m=u.issues.length}if(g==="__proto__")continue;const y=h[g],b=y._zod.optin,$=y._zod.optout,k=y._zod.run({value:f[g],issues:[]},c);k instanceof Promise?p.push(k.then(_=>Pn(_,u,g,f,b,$))):Pn(k,u,g,f,b,$)}return a?ji(p,f,u,c,r.value,e,x===!0):p.length?Promise.all(p).then(()=>u):u}}),yu=I("$ZodObjectJIT",(e,t)=>{gu.init(e,t);const n=e._zod.parse,s=Hn(()=>_i(t)),r=at.memoizer,i=h=>{var _,O;const x=s.value,m=x.symbolKeys,g=new Md(["payload","ctx"],{shape:h,inst:e,memo:r,syms:m}),y=F=>`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`,b=(F,N)=>`
7
+ let ${F}_ab = false;
8
+ for (let i = 0; i < ${F}.issues.length; i++) {
9
+ const iss = ${F}.issues[i];
10
+ iss.path = iss.path ? [${N}, ...iss.path] : [${N}];
11
+ payload.issues.push(iss);
12
+ if (iss.continue !== true) ${F}_ab = true;
13
+ }
14
+ if (${F}_ab && ctx && ctx.abortEarly) {
15
+ payload.value = newResult;
16
+ return payload;
17
+ }`;g.write("const input = payload.value;");const $=Object.create(null);let k=0;for(const F of x.allKeys)$[F]=`key_${k++}`;g.write(r?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const F of x.allKeys){if(F==="__proto__")continue;const N=$[F],P=typeof F=="symbol"?`syms[${m.indexOf(F)}]`:Gl(F),M=`${P} in input`,A=h[F],q=(_=A==null?void 0:A._zod)==null?void 0:_.optin,ne=q!==void 0,Q=((O=A==null?void 0:A._zod)==null?void 0:O.optout)==="optional";if(g.write(`const ${N} = ${y(P)};`),ne&&Q){const w=q==="optional"?`${N}_present`:`${N}.value !== undefined || ${N}_present`;g.write(`
18
+ const ${N}_present = ${M};
19
+ if (!${N}.issues.length || ${N}_present) {
20
+ if (${N}.issues.length) {${b(N,P)}
21
+ }
22
+
23
+ if (${w}) {
24
+ newResult[${P}] = ${N}.value;
25
+ }
26
+ }
27
+
28
+ `)}else ne?(g.write(`
29
+ if (${N}.issues.length) {${b(N,P)}
30
+ }
31
+ `),q==="defaulted"?g.write(`newResult[${P}] = ${N}.value;`):g.write(`
32
+ if (${N}.value !== undefined || ${M}) {
33
+ newResult[${P}] = ${N}.value;
34
+ }
35
+ `)):g.write(`
36
+ const ${N}_present = ${M};
37
+ if (${N}.issues.length) {${b(N,P)}
38
+ }
39
+ if (!${N}_present && !${N}.issues.length) {
40
+ payload.issues.push({
41
+ code: "invalid_type",
42
+ expected: "nonoptional",
43
+ input: undefined,
44
+ path: [${P}]
45
+ });
46
+ if (ctx && ctx.abortEarly) {
47
+ payload.value = newResult;
48
+ return payload;
49
+ }
50
+ }
51
+
52
+ if (${N}_present) {
53
+ newResult[${P}] = ${N}.value;
54
+ }
55
+
56
+ `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()};let a;const l=ln,d=!at.jitless,c=d&&Vl.value,f=t.catchall;let p;e._zod.parse=(h,x)=>{p??(p=s.value);const m=h.value;return l(m)?d&&c&&(x==null?void 0:x.async)===!1&&x.jitless!==!0?(a||(a=i(t.shape)),h=a(h,x),f?ji([],m,h,x,p,e,(x==null?void 0:x.abortEarly)===!0):h):n(h,x):(h.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),h)}});function Qr(e,t,n,s){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!pt(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>Nt(a,s,ut())))}),t)}const $i=I("$ZodUnion",(e,t)=>{Le.init(e,t),Ee(e,"optin",s=>s.def.options.some(r=>r._zod.optin==="defaulted")?"defaulted":s.def.options.some(r=>r._zod.optin!==void 0)?"optional":void 0),Ee(e,"optout",s=>s.def.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ee(e,"values",s=>{if(s.def.options.every(r=>r._zod.values))return new Set(s.def.options.flatMap(r=>Array.from(r._zod.values)))}),Ee(e,"pattern",s=>{if(s.def.options.every(r=>r._zod.pattern)){const r=s.def.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Xs(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(s,r)=>{if(n)return n(s,r);let i=!1;const a=[];for(const l of t.options){const d=l._zod.run({value:s.value,issues:[]},r);if(d instanceof Promise)a.push(d),i=!0;else{if(d.issues.length===0)return d;a.push(d)}}return i?Promise.all(a).then(l=>Qr(l,s,e,r)):Qr(a,s,e,r)}});function bu(e){var n;const t=new Map;for(const s of e.options){const r=(n=s._zod.propValues)==null?void 0:n[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const i of r)if(t.has(i)){if(i!==void 0)throw new Error(`Duplicate discriminator value "${String(i)}"`);t.set(i,null)}else t.set(i,s)}return t}const vu=I("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,$i.init(e,t);const n=e._zod.parse;Ee(e,"propValues",r=>{var l,d;const i={};let a=0;for(const u of r.def.options){const c=u._zod.propValues;if(!c||Object.keys(c).length===0)throw new Error(`Invalid discriminated union option at index "${r.def.options.indexOf(u)}"`);(l=c[r.def.discriminator])!=null&&l.has(void 0)&&a++;for(const[f,p]of Object.entries(c)){Object.prototype.hasOwnProperty.call(i,f)||yt(i,f,new Set);for(const h of p)i[f].add(h)}}return!r.def.unionFallback&&a>1&&((d=i[r.def.discriminator])==null||d.delete(void 0)),i}),t.options.forEach((r,i)=>{const a=Ys(r._zod.def);if(a&&!Object.prototype.hasOwnProperty.call(a,t.discriminator))throw new Error(`Invalid discriminated union option at index "${i}"`)});const s=Hn(()=>bu(t));e._zod.parse=(r,i)=>{const a=r.value;if(!ln(a))return r.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),r;const l=a==null?void 0:a[t.discriminator],d=s.value.get(l);return d&&(l!==void 0||i.direction!=="backward")?d._zod.run(r,i):t.unionFallback||i.direction==="backward"?n(r,i):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(s.value.keys()).filter(u=>s.value.get(u)!==null),input:a,path:[t.discriminator],inst:e}),r)}}),ku=I("$ZodIntersection",(e,t)=>{Le.init(e,t),e._zod.parse=(n,s)=>{const r=n.value,i=t.left._zod.run({value:r,issues:[]},s),a=t.right._zod.run({value:r,issues:[]},s);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([d,u])=>Vr(n,d,u)):Vr(n,i,a)}});function Os(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ft(e)&&Ft(t)){const n=Object.keys(t),s=Object.keys(e).filter(i=>n.indexOf(i)!==-1),r={...e,...t};Object.prototype.hasOwnProperty.call(r,"__proto__")&&delete r.__proto__;for(const i of s){if(i==="__proto__")continue;const a=Os(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};r[i]=a.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let s=0;s<e.length;s++){const r=e[s],i=t[s],a=Os(r,i);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Vr(e,t,n){const s=new Map;let r;const i=new Map,a=(u,c)=>{var p,h;let f;if(u.code==="unrecognized_keys"&&!((p=u.path)!=null&&p.length))r??(r=u),f=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&((h=u.path)==null?void 0:h.length)===1){const x=String(u.path[0]);i.has(x)||i.set(x,u),f=[x]}else return!1;for(const x of f)s.has(x)||s.set(x,{}),s.get(x)[c]=!0;return!0};for(const u of t.issues)a(u,"l")||e.issues.push(u);for(const u of n.issues)a(u,"r")||e.issues.push(u);const l=[...s].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(l.length){const u=r?l.filter(c=>r.keys.includes(c)):[];u.length&&e.issues.push({...r,keys:u});for(const c of l)!u.includes(c)&&i.has(c)&&e.issues.push(i.get(c))}const d=Os(t.value,n.value);if(!d.valid){if(pt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(d.mergeErrorPath)}`)}return e.value=d.data,e}const wu=I("$ZodRecord",(e,t)=>{Le.init(e,t);const n=at.memoizer;n==null||n.attach(e),e._zod.parse=(s,r)=>{const i=s.value;if(!Ft(i))return s.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),s;const a=[],l=t.keyType._zod.values;if(l&&!t.partial){s.value=n?n.alloc(e,s,{},r):{};const d=new Set;for(const c of l)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){if(d.add(typeof c=="number"?c.toString():c),c==="__proto__")continue;const f=t.keyType._zod.run({value:c,issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){s.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(x=>Nt(x,r,ut())),input:c,path:[c],inst:e});continue}const p=f.value;if(p==="__proto__")continue;const h=t.valueType._zod.run({value:i[c],issues:[]},r);h instanceof Promise?a.push(h.then(x=>{x.issues.length&&s.issues.push(...Bt(c,x.issues)),s.value[p]=x.value})):(h.issues.length&&s.issues.push(...Bt(c,h.issues)),s.value[p]=h.value)}let u;for(const c in i)if(!d.has(c))if(t.mode==="loose"){if(c==="__proto__")continue;s.value[c]=i[c]}else u=u??[],u.push(c);u&&u.length>0&&s.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:u,continue:!0})}else{s.value=n?n.alloc(e,s,{},r):{};let d;for(const u of Reflect.ownKeys(i)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,u))continue;let c=t.keyType._zod.run({value:u,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&sr.test(u)&&c.issues.length){const x=t.keyType._zod.run({value:Number(u),issues:[]},r);if(x instanceof Promise)throw new Error("Async schemas not supported in object keys currently");x.issues.length===0&&(c=x)}if(c.issues.length){t.mode==="loose"?s.value[u]=i[u]:l?(d=d??[],d.push(u)):s.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(x=>Nt(x,r,ut())),input:u,path:[u],inst:e});continue}const p=c.value;if(p==="__proto__")continue;const h=t.valueType._zod.run({value:i[u],issues:[]},r);h instanceof Promise?a.push(h.then(x=>{x.issues.length&&s.issues.push(...Bt(u,x.issues)),s.value[p]=x.value})):(h.issues.length&&s.issues.push(...Bt(u,h.issues)),s.value[p]=h.value)}d&&d.length>0&&s.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d,continue:!0})}return a.length?Promise.all(a).then(()=>s):s}}),_u=I("$ZodEnum",(e,t)=>{Le.init(e,t);const n=Ss(t.entries),s=new Set(n);e._zod.values=s,Ee(e,"pattern",r=>{const i=Ss(r.def.entries).filter(a=>ec.has(typeof a));return new RegExp(i.length?`^(${i.map(a=>Ut(a.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{const a=r.value;return s.has(a)||r.issues.push({code:"invalid_value",values:n,input:a,inst:e}),r}}),ju=I("$ZodLiteral",(e,t)=>{Le.init(e,t);const n=new Set(t.values);e._zod.values=n,Ee(e,"pattern",s=>{const r=s.def.values;return new RegExp(r.length?`^(${r.map(i=>typeof i=="string"?Ut(i):i?Ut(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(s,r)=>{const i=s.value;return n.has(i)||s.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),s}}),$u=I("$ZodTransform",(e,t)=>{var n;Le.init(e,t),e._zod.optin="optional",(n=at.memoizer)==null||n.guard(e),e._zod.parse=(s,r)=>{if(r.direction==="backward")throw new di(e.constructor.name);const i=t.transform(s.value,s);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(l=>(s.value=l,s));if(i instanceof Promise)throw new Et;return s.value=i,s}});function eo(e,t){return e.value=t.issues.length?void 0:t.value,e}const Ni=I("$ZodOptional",(e,t)=>{Le.init(e,t),Ee(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Ee(e,"values",n=>{const s=n.def.innerType._zod.values;return s?new Set([...s,void 0]):void 0}),Ee(e,"pattern",n=>{const s=n.def.innerType._zod.pattern;return s?new RegExp(`^(${Xs(s.source)})?$`):void 0}),e._zod.parse=(n,s)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;const r=t.innerType._zod.run({value:n.value,issues:[]},s);return r instanceof Promise?r.then(i=>eo(n,i)):eo(n,r)}return t.innerType._zod.run(n,s)}}),Nu=I("$ZodExactOptional",(e,t)=>{Ni.init(e,t),Ee(e,"values",n=>n.def.innerType._zod.values),Ee(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,s)=>t.innerType._zod.run(n,s)}),Su=I("$ZodNullable",(e,t)=>{Le.init(e,t),Ee(e,"optin",n=>n.def.innerType._zod.optin),Ee(e,"optout",n=>n.def.innerType._zod.optout),Ee(e,"pattern",n=>{const s=n.def.innerType._zod.pattern;return s?new RegExp(`^(${Xs(s.source)}|null)$`):void 0}),Ee(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,s)=>n.value===null?n:t.innerType._zod.run(n,s)}),Mu=I("$ZodDefault",(e,t)=>{Le.init(e,t),e._zod.optin="defaulted",Ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(i=>to(i,t)):to(r,t)}});function to(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Cu=I("$ZodPrefault",(e,t)=>{Le.init(e,t),e._zod.optin="defaulted",Ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,s)=>(s.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,s))}),Eu=I("$ZodNonOptional",(e,t)=>{Le.init(e,t),Ee(e,"values",n=>{const s=n.def.innerType._zod.values;return s?new Set([...s].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,s)=>{const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(i=>no(i,e)):no(r,e)}});function no(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function so(e,t,n,s){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(r=>Nt(r,s,ut()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Ou=I("$ZodCatch",(e,t)=>{Le.init(e,t),Ee(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Ee(e,"optout",n=>n.def.innerType._zod.optout),Ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run({value:n.value,issues:[]},s);return r instanceof Promise?r.then(i=>so(n,i,t,s)):so(n,r,t,s)}}),zu=I("$ZodPipe",(e,t)=>{Le.init(e,t),Ee(e,"values",n=>n.def.in._zod.values),Ee(e,"optin",n=>n.def.in._zod.optin),Ee(e,"optout",n=>n.def.out._zod.optout),Ee(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,s)=>{if(s.direction==="backward"){const i=t.out._zod.run(n,s);return i instanceof Promise?i.then(a=>yn(a,t.in,s)):yn(i,t.in,s)}const r=t.in._zod.run(n,s);return r instanceof Promise?r.then(i=>yn(i,t.out,s)):yn(r,t.out,s)}});function yn(e,t,n){return e.issues.some(s=>s.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Tu=I("$ZodReadonly",(e,t)=>{Le.init(e,t),Ee(e,"propValues",n=>n.def.innerType._zod.propValues),Ee(e,"values",n=>n.def.innerType._zod.values),Ee(e,"optin",n=>{var s,r;return(r=(s=n.def.innerType)==null?void 0:s._zod)==null?void 0:r.optin}),Ee(e,"optout",n=>{var s,r;return(r=(s=n.def.innerType)==null?void 0:s._zod)==null?void 0:r.optout}),e._zod.parse=(n,s)=>{if(s.direction==="backward")return t.innerType._zod.run(n,s);const r=t.innerType._zod.run(n,s);return r instanceof Promise?r.then(ro):ro(r)}});function ro(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Pu=I("$ZodCustom",(e,t)=>{tt.init(e,t),Le.init(e,t),e._zod.parse=(n,s)=>n,e._zod.check=n=>{const s=n.value,r=t.fn(s);if(r instanceof Promise)return r.then(i=>oo(i,n,s,e));oo(r,n,s,e)}});function oo(e,t,n,s){if(!e){const r={code:"custom",input:n,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(r.params=s._zod.def.params),t.issues.push(cn(r))}}class Au extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const zs="~memo",io=[];function Si(e){return e!==null&&typeof e=="object"}function ys(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const Mi=new WeakMap,en=0,Mn=1,rn=2;function Cn(e,t,n){const s=Mi.get(e);if(s!==void 0)return s?rn:en;if(t.has(e))return rn;t.add(e);let r=en;const i=c=>{if(r!==rn&&(c!=null&&c._zod)){const f=Cn(c,t);f>r&&(r=f)}},a=(c,f)=>{var h;let p=en;for(const x of Reflect.ownKeys(c)){const m=Object.getOwnPropertyDescriptor(c,x);if(!m.enumerable)continue;const g=m.get?Mn:(h=m.value)!=null&&h._zod?Cn(m.value,t):en;g>p&&(p=g)}return p},l=c=>{c>r&&(r=c)},d=e._zod.def;switch(d.type){case"object":{const c=Ys(d);l(c?a(c):Mn),i(d.catchall);break}case"array":i(d.element);break;case"tuple":for(const c of d.items)i(c);i(d.rest);break;case"record":case"map":i(d.keyType),i(d.valueType);break;case"set":i(d.valueType);break;case"union":for(const c of d.options)i(c);break;case"intersection":i(d.left),i(d.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(d.innerType);break;case"pipe":i(d.in),i(d.out);break;case"function":i(d.input),i(d.output);break;case"lazy":{const c=d._cachedInner??void 0;l(c?Cn(c,t):Mn);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const c in d){const f=Object.getOwnPropertyDescriptor(d,c);if(!f||f.get)continue;const p=f.value;if(!(!p||typeof p!="object")){if(p._zod)i(p);else if(Array.isArray(p))for(const h of p)i(h)}}}return t.delete(e),Du(e,r)}function Du(e,t){return t!==Mn&&Mi.set(e,t===rn),t}function Iu(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let bn;const vn=[],Lu={alloc(e,t,n){const s=bn;if(!s)return n;bn=void 0;const r={value:n,issues:null};return s.set(t.value,r),vn.push(r),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const n=e._zod.parse,s=(r,i)=>{if(i.direction!=="backward"&&Zu(i,r.value))throw new Au;return n(r,i)};e._zod.parse=s,e._zod.run===n&&(e._zod.run=s)})},attach(e){var t;let n,s=!1,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const a=e._zod.parse,l=(d,u)=>{if(n===void 0){const y=Cn(e,new Set);if(y===en)return e._zod.parse=a,e._zod.run===l&&(e._zod.run=a),a(d,u);y===rn||s?n=!0:s=!0}const c=d.value;if(!Si(c))return a(d,u);let f=u[zs];f||(f={buckets:new WeakMap,backEdges:void 0},u[zs]=f);let p;r===u?p=i:(p=Iu(f,e),r=u,i=p);const h=p.get(c);if(h)return d.value=h.value,h.issues?h.issues.length&&d.issues.push(...ys(h.issues)):(d.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(h.value)),d;bn=p;const x=vn.length,m=a(d,u);bn=void 0;const g=vn.length>x?vn.pop():void 0;return m instanceof Promise?m.then(y=>(g&&(g.issues=y.issues.length?ys(y.issues):io),y)):(g&&(g.issues=m.issues.length?ys(m.issues):io),m)};e._zod.parse=l,e._zod.run===a&&(e._zod.run=l)})}};function Bu(){return Lu}function Zu(e,t){var s;const n=(s=e[zs])==null?void 0:s.backEdges;return n!==void 0&&Si(t)&&n.has(t)}const Ru=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return e[i]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},s={nan:"NaN"};function r(i,a){return i==="number"&&typeof a=="number"&&!Number.isFinite(a)?String(a):s[i]??i}return i=>{switch(i.code){case"invalid_type":{const a=r(i.expected),l=uc(i.input),d=r(l,i.input);return`Invalid input: expected ${a}, received ${d}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${oi(i.values[0])}`:`Invalid option: expected one of ${Ur(i.values,"|")}`;case"too_big":{const a=i.exact?"exactly ":i.inclusive?"<=":"<",l=t(i.origin);return l?`Too big: expected ${i.origin??"value"} to have ${a}${i.maximum.toString()} ${l.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${a}${i.maximum.toString()}`}case"too_small":{const a=i.exact?"exactly ":i.inclusive?">=":">",l=t(i.origin);return l?`Too small: expected ${i.origin} to have ${a}${i.minimum.toString()} ${l.unit}`:`Too small: expected ${i.origin} to be ${a}${i.minimum.toString()}`}case"invalid_format":{const a=i;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${n[a.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Ur(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(l=>`'${l}'`).join(" | ")}`:i.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function Fu(){return{localeError:Ru()}}var ao;class Uu{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const s=n[0];return this._map.set(t,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const s={...this.get(n)??{}};delete s.id;const r={...s,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Hu(){return new Uu}(ao=globalThis).__zod_globalRegistry??(ao.__zod_globalRegistry=Hu());const tn=globalThis.__zod_globalRegistry;function Ci(e){return e.checks&&(e.checks=[...e.checks]),e}function Wu(e,t){return new e(Ci({type:"string",...de(t)}))}function Ku(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...de(t)})}function qu(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...de(t)})}function Ju(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...de(t)})}function Xu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(t)})}function Yu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(t)})}function Gu(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(t)})}function Qu(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...de(t)})}function Vu(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...de(t)})}function ef(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(t)})}function tf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...de(t)})}function nf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(t)})}function sf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...de(t)})}function rf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...de(t)})}function of(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(t)})}function af(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(t)})}function lf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(t)})}function cf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(t)})}function df(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(t)})}function uf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...de(t)})}function ff(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...de(t)})}function hf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...de(t)})}function pf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...de(t)})}function mf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(t)})}function xf(e,t){return new e({type:"string",format:"date",check:"string_format",...de(t)})}function gf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...de(t)})}function yf(e,t){return new e({type:"string",format:"duration",check:"string_format",...de(t)})}function bf(e,t){return new e(Ci({type:"number",checks:[],...de(t)}))}function vf(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...de(t)})}function kf(e,t){return new e({type:"boolean",...de(t)})}function wf(e){return new e({type:"unknown"})}function _f(e,t){return new e({type:"never",...de(t)})}function lo(e,t){return new hi({check:"less_than",...de(t),value:e,inclusive:!1})}function bs(e,t){return new hi({check:"less_than",...de(t),value:e,inclusive:!0})}function co(e,t){return new pi({check:"greater_than",...de(t),value:e,inclusive:!1})}function vs(e,t){return new pi({check:"greater_than",...de(t),value:e,inclusive:!0})}function uo(e,t){return new xd({check:"multiple_of",...de(t),value:e})}function Ei(e,t){return new yd({check:"max_length",...de(t),maximum:e})}function An(e,t){return new bd({check:"min_length",...de(t),minimum:e})}function Oi(e,t){return new vd({check:"length_equals",...de(t),length:e})}function jf(e,t){return new kd({check:"string_format",format:"regex",...de(t),pattern:e})}function $f(e){return new wd({check:"string_format",format:"lowercase",...de(e)})}function Nf(e){return new _d({check:"string_format",format:"uppercase",...de(e)})}function Sf(e,t){return new jd({check:"string_format",format:"includes",...de(t),includes:e})}function Mf(e,t){return new $d({check:"string_format",format:"starts_with",...de(t),prefix:e})}function Cf(e,t){return new Nd({check:"string_format",format:"ends_with",...de(t),suffix:e})}function Kt(e){return new Sd({check:"overwrite",tx:e})}function Ef(e){return Kt(t=>t.normalize(e))}function Of(){return Kt(e=>e.trim())}function zf(){return Kt(e=>e.toLowerCase())}function Tf(){return Kt(e=>e.toUpperCase())}function Pf(){return Kt(e=>Ql(e))}function Af(e,t,n){return new e({type:"array",element:t,...de(n)})}function Df(e,t,n){return new e({type:"custom",check:"custom",fn:t,...de(n)})}function If(e,t){const n=Lf(s=>(s.addIssue=r=>{if(typeof r=="string")s.issues.push(cn(r,s.value,n._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=s.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),s.issues.push(cn(i))}},e(s.value,s)),t);return n}function Lf(e,t){const n=new tt({check:"custom",...de(t)});return n._zod.check=e,n}function on(e,...t){for(const n of t)for(const s of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,s)&&yt(e,s,n[s]);return e}function zi(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??tn,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",intersections:[],deferred:[],external:(e==null?void 0:e.external)??void 0}}function Mt(e,t,n,s,r){const i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:s.path,message:r}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(r);return Object.assign(n,i),!0}function He(e,t,n={path:[],schemaPath:[]}){var c,f;var s;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const l=(f=(c=e._zod).toJSONSchema)==null?void 0:f.call(c);if(l)a.schema=l;else{const p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,p);else{const x=a.schema,m=t.processors[r.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);m(e,t,x,p)}const h=e._zod.parent;h&&(a.ref||(a.ref=h),He(h,t,p),t.seen.get(h).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&on(a.schema,d),t.io==="input"&&Ve(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&"_prefault"in a.schema&&((s=a.schema).default??(s.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function fo(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Ti(e,t){var a,l,d,u;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const s=new Map;for(const c of e.seen.entries()){const f=(a=e.metadataRegistry.get(c[0]))==null?void 0:a.id;if(f){const p=s.get(f);if(p&&p!==c[0])throw new Error(`Duplicate schema id "${f}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(f,c[0])}}const r=c=>{var m;const f=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=(m=e.external.registry.get(c[0]))==null?void 0:m.id,y=e.external.uri??($=>$);if(g)return{ref:y(g)};const b=c[1].defId??c[1].schema.id??`schema${e.counter++}`;return c[1].defId=b,{defId:b,ref:`${y("__shared")}#/${f}/${fo(b)}`}}const p="#",h=`${p}/${f}/`;if(c[1]===n&&!c[1].schema.id)return{ref:p};const x=c[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:h+fo(x)}},i=c=>{if(c[1].schema.$ref)return;const f=c[1],{ref:p,defId:h}=r(c);f.def={...f.schema},h&&(f.defId=h);const x=f.schema;for(const m in x)delete x[m];x.$ref=p};if(e.cycles==="throw")for(const c of e.seen.entries()){const f=c[1];if(f.cycle)throw new Error(`Cycle detected: #/${(l=f.cycle)==null?void 0:l.join("/")}/<root>
57
+
58
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const c of e.seen.entries()){const f=c[1];if(t===c[0]){i(c);continue}if(e.external){const h=(d=e.external.registry.get(c[0]))==null?void 0:d.id;if(t!==c[0]&&h){i(c);continue}}if((u=e.metadataRegistry.get(c[0]))==null?void 0:u.id){i(c);continue}if(f.cycle){i(c);continue}f.count>1&&e.reused==="ref"&&i(c)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Pi(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const n=[];for(const s of t){if(!s||typeof s!="object")return;Pi(s);const r=Object.keys(s);if(r.length!==1||r[0]!=="type")return;const i=s.type;for(const a of Array.isArray(i)?i:[i]){if(typeof a!="string")return;n.includes(a)||n.push(a)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Ai=new Set(["type","properties","required","additionalProperties"]),ho=["oneOf","anyOf"];function po(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Ts(e){var i;const t=[];for(const a of e){if(typeof a!="object"||a.type!=="object")return null;for(const l in a)if(!Ai.has(l))return null;t.push(a)}const n={},s=new Set;for(const a of t){for(const l in a.properties){if(Object.prototype.hasOwnProperty.call(n,l))continue;const d=[];for(const c of t){const f=((i=c.properties)==null?void 0:i[l])??po(c);f!=null&&(d.some(p=>JSON.stringify(p)===JSON.stringify(f))||d.push(f))}const u=d.length===1?d[0]:Ts(d)??{allOf:d};yt(n,l,u)}for(const l of a.required??[])s.add(l)}const r={type:"object",properties:n};if(s.size&&(r.required=[...s]),t.every(a=>a.additionalProperties===!1))r.additionalProperties=!1;else{const a=[];for(const l of t){const d=po(l);d&&!a.some(u=>JSON.stringify(u)===JSON.stringify(d))&&a.push(d)}a.length===1?r.additionalProperties=a[0]:a.length>1&&(r.additionalProperties={allOf:a})}return r}function Bf(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const r of Ai)if(r in e)return;const n=t.filter(r=>ho.some(i=>Array.isArray(r[i])));let s=null;if(!n.length)s=Ts(t);else{const r=n[0],i=ho.find(d=>Array.isArray(r[d]));if(Object.keys(r).length!==1)return;const a=t.filter(d=>d!==r),l=r[i].map(d=>Ts([...a,d]));if(l.some(d=>!d))return;s={[i]:l}}s&&(delete e.allOf,on(e,s))}function Di(e,t){var l,d,u,c;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=f=>{const p=e.seen.get(f);if(p.ref===null)return;const h=p.def??p.schema,x={...h},m=p.ref;if(p.ref=null,m){s(m);const y=e.seen.get(m),b=y.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(b)):on(h,b),on(h,x),f._zod.parent===m)for(const k in h)k==="$ref"||k==="allOf"||k in x||delete h[k];if(b.$ref&&y.def)for(const k in h)k==="$ref"||k==="allOf"||k in y.def&&JSON.stringify(h[k])===JSON.stringify(y.def[k])&&delete h[k]}const g=f._zod.parent;if(g&&g!==m){s(g);const y=e.seen.get(g);if(y!=null&&y.schema.$ref&&(h.$ref=y.schema.$ref,y.def))for(const b in h)b==="$ref"||b==="allOf"||b in y.def&&JSON.stringify(h[b])===JSON.stringify(y.def[b])&&delete h[b]}e.override({zodSchema:f,jsonSchema:h,path:p.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const f of[...e.seen.entries()].reverse())s(f[0]);if(e.target!=="openapi-3.0")for(const f of e.seen.entries())Pi(f[1].def??f[1].schema);for(const f of e.deferred)f();if(e.intersections.length){const f=new Map;for(const p of e.seen.values())for(const h of[p.schema,p.def]){const x=h==null?void 0:h.allOf;if(!Array.isArray(x))continue;const m=f.get(x);m?m.push(h):f.set(x,[h])}for(const p of e.intersections)for(const h of f.get(p)??[])Bf(h)}}const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,(l=e.external)!=null&&l.uri){const f=(d=e.external.registry.get(t))==null?void 0:d.id;if(!f)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(f)}on(r,n.defId?n.schema:n.def??n.schema);const i=(u=e.metadataRegistry.get(t))==null?void 0:u.id;i!==void 0&&r.id===i&&delete r.id;const a=((c=e.external)==null?void 0:c.defs)??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const f of e.seen.entries()){const p=f[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,yt(a,p.defId,p.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target==="draft-2020-12"?r.$defs=a:r.definitions=a);try{const f=JSON.parse(JSON.stringify(r));return Object.defineProperty(f,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),f}catch{throw new Error("Error converting schema to JSON.")}}function Ve(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const s=e._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Ve(s.element,n);if(s.type==="set")return Ve(s.valueType,n);if(s.type==="lazy")return Ve(s.getter(),n);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault"||s.type==="catch")return Ve(s.innerType,n);if(s.type==="intersection")return Ve(s.left,n)||Ve(s.right,n);if(s.type==="record"||s.type==="map")return Ve(s.keyType,n)||Ve(s.valueType,n);if(s.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Ve(s.in,n)||Ve(s.out,n);if(s.type==="object"){for(const r in s.shape)if(Ve(s.shape[r],n))return!0;return!1}if(s.type==="union"){for(const r of s.options)if(Ve(r,n))return!0;return!1}if(s.type==="tuple"){for(const r of s.items)if(Ve(r,n))return!0;return!!(s.rest&&Ve(s.rest,n))}return!1}const Zf=(e,t={})=>n=>{const s=zi({...n,processors:t});return He(e,s),Ti(s,e),Di(s,e)},Dn=(e,t,n={})=>s=>{const{libraryOptions:r,target:i}=s??{},a=zi({...r??{},target:i,io:t,processors:n});return He(e,a),Ti(a,e),Di(a,e)},Ht=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Wt=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},mo=(e,t)=>{Ht(e,"minimum",t),Wt(e,"maximum",t)},Ii=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Li=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Bi=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},Zi=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},xo=(e,t)=>Ht(e,"minimum",t.minimum),go=(e,t)=>Wt(e,"maximum",t.maximum),yo=e=>(t,n)=>{Zi(t,n.format);const[s,r]=e[n.format];Ht(t,"minimum",s),Wt(t,"maximum",r)},ks={greater_than:(e,t)=>Ht(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Wt(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Ii(e,t.value),number_format:yo(ii),bigint_format:yo(nc),min_length:xo,max_length:go,length_equals:(e,t)=>mo(e,t.length),min_size:xo,max_size:go,size_equals:(e,t)=>mo(e,t.size),string_format:(e,t)=>{Zi(e,t.format),t.pattern&&Li(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Bi(e,t.mime)};function it(e){var i;const t={},n=e._zod.def,s=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(const a of s)(i=ks[a._zod.def.check])==null||i.call(ks,t,a._zod.def);const r=e._zod.bag;r.minimum!==void 0&&Ht(t,"minimum",r.minimum),r.exclusiveMinimum!==void 0&&Ht(t,"exclusiveMinimum",r.exclusiveMinimum),r.maximum!==void 0&&Wt(t,"maximum",r.maximum),r.exclusiveMaximum!==void 0&&Wt(t,"exclusiveMaximum",r.exclusiveMaximum),r.multipleOf!==void 0&&Ii(t,r.multipleOf),r.format!==void 0&&(t.format??(t.format=r.format),r.format.includes("int")&&(t.isInt=!0)),r.mime&&Bi(t,r.mime);for(const a of r.patterns??[])Li(t,a);return t}const Rf={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ff=new Map([[ki,sd],[ir,rd]]),Ri=e=>Ff.get(e)??e,Uf=(e,t,n,s)=>{const r=n;r.type="string";const{minimum:i,maximum:a,format:l,patterns:d,contentEncoding:u,laxFormat:c}=it(e);if(typeof i=="number"&&(r.minLength=i),typeof a=="number"&&(r.maxLength=a),l&&(r.format=Rf[l]??l,r.format===""&&delete r.format,(l==="time"||c)&&delete r.format),u&&(r.contentEncoding=u),d&&d.size>0){const f=[...d].map(Ri);f.length===1?r.pattern=f[0].source:f.length>1&&(r.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Hf=(e,t,n,s)=>{const r=n,{minimum:i,maximum:a,multipleOf:l,exclusiveMaximum:d,exclusiveMinimum:u,isInt:c}=it(e);r.type=c?"integer":"number";const f=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof d=="number"&&d<=(a??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(f?h?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u:typeof i=="number"&&(r.minimum=i),p?h?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d:typeof a=="number"&&(r.maximum=a),l){const x=new Set;for(const y of l)Number.isFinite(y)&&y!==0?x.add(Math.abs(y)):Mt(e,t,r,s,`A multipleOf divisor of ${y} cannot be represented in JSON Schema`);const[m,...g]=x;m!==void 0&&(r.multipleOf=m),g.length&&(r.allOf=[...r.allOf??[],...g.map(y=>({multipleOf:y}))])}},Wf=(e,t,n,s)=>{n.type="boolean"},Kf=(e,t,n,s)=>{n.not={}},qf=(e,t,n,s)=>{},Jf=(e,t,n,s)=>{const r=e._zod.def,i=Ss(r.entries);if(i.length===0){n.not={};return}i.every(a=>typeof a=="number")&&(n.type="number"),i.every(a=>typeof a=="string")&&(n.type="string"),n.enum=i},Xf=(e,t,n,s)=>{const r=e._zod.def;if(r.values.length===0){n.not={};return}const i=[];for(const a of r.values)if(a===void 0){if(Mt(e,t,n,s,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof a=="bigint"){if(Mt(e,t,n,s,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){const a=i[0];n.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[a]:n.const=a}else i.every(a=>typeof a=="number")&&(n.type="number"),i.every(a=>typeof a=="string")&&(n.type="string"),i.every(a=>typeof a=="boolean")&&(n.type="boolean"),i.every(a=>a===null)&&(n.type="null"),n.enum=i},Yf=(e,t,n,s)=>{Mt(e,t,n,s,"Custom types cannot be represented in JSON Schema")},Gf=(e,t,n,s)=>{Mt(e,t,n,s,"Transforms cannot be represented in JSON Schema")},Qf=(e,t,n,s)=>{const r=n,i=e._zod.def,{minimum:a,maximum:l}=it(e);typeof a=="number"&&(r.minItems=a),typeof l=="number"&&(r.maxItems=l),r.type="array",r.items=He(i.element,t,{...s,path:[...s.path,"items"]})};function In(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?In(t.out):t.type==="catch"?In(t.innerType):e._zod.optin}const Vf=(e,t,n,s)=>{var u;const r=n,i=e._zod.def,a=i.shape;if(Object.getOwnPropertySymbols(a).length&&Mt(e,t,r,s,"Symbol keys cannot be represented in JSON Schema"))return;r.type="object",r.properties={};for(const c in a)yt(r.properties,c,He(a[c],t,{...s,path:[...s.path,"properties",c]}));const d=[];for(const c of Object.keys(a)){const f=i.shape[c];(t.io==="input"?In(f)===void 0:f._zod.optout===void 0)&&d.push(c)}d.length>0&&(r.required=d),((u=i.catchall)==null?void 0:u._zod.def.type)==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=He(i.catchall,t,{...s,path:[...s.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},eh=(e,t,n,s)=>{const r=e._zod.def,i=r.inclusive===!1,a=r.options.map((l,d)=>He(l,t,{...s,path:[...s.path,i?"oneOf":"anyOf",d]}));i?n.oneOf=a:n.anyOf=a},th=(e,t,n,s)=>{const r=e._zod.def,i=He(r.left,t,{...s,path:[...s.path,"allOf",0]}),a=He(r.right,t,{...s,path:[...s.path,"allOf",1]}),l=u=>"allOf"in u&&Object.keys(u).length===1,d=[...l(i)?i.allOf:[i],...l(a)?a.allOf:[a]];n.allOf=d,t.intersections.push(d)};function Ps(e,t,n){var x;if(t.$ref){if(n.has(t))return t;n.add(t);const m=(x=e.get(t))==null?void 0:x.def;if(!m)return t;const g=Ps(e,m,n);return g===m?t:g}for(const m of["anyOf","oneOf"]){const g=t[m];if(!Array.isArray(g))continue;const y=g.map(b=>Ps(e,b,n));y.some((b,$)=>b!==g[$])&&(t={...t,[m]:y})}const s=Array.isArray(t.type)?t.type:[t.type],r=!s.includes("string")&&s.some(m=>m==="number"||m==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!r&&!(i!=null&&i.some(m=>typeof m=="number")))return t;const{minimum:a,maximum:l,exclusiveMinimum:d,exclusiveMaximum:u,multipleOf:c,format:f,id:p,...h}=t;return h.enum?h.enum=h.enum.map(m=>typeof m=="number"?String(m):m):typeof h.const=="number"&&(h.const=String(h.const)),r&&(h.type="string",i||(h.pattern=(s.includes("number")?sr:fd).source)),h}const As=new WeakMap;function nh(e){var s;const t=new Map;for(const r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);const n=new Map;for(const r of As.get(e)??[]){const i=e.seen.get(r),a=(s=(i==null?void 0:i.def)??(i==null?void 0:i.schema))==null?void 0:s.propertyNames;if(!a||a===!0||n.has(a))continue;const l=Ps(t,a,new Set);l!==a&&n.set(a,l)}if(n.size)for(const r of e.seen.values())for(const i of[r.schema,r.def]){const a=i&&n.get(i.propertyNames);a&&(i.propertyNames=a)}}const sh=(e,t,n,s)=>{const r=n,i=e._zod.def;r.type="object";const a=i.keyType,l=it(a).patterns;if(i.mode==="loose"&&l&&l.size>0){const c=He(i.valueType,t,{...s,path:[...s.path,"patternProperties","*"]});r.patternProperties={};for(const f of l)yt(r.patternProperties,Ri(f).source,c)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){r.propertyNames=He(i.keyType,t,{...s,path:[...s.path,"propertyNames"]});let c=As.get(t);c||(c=[],As.set(t,c),t.deferred.push(()=>nh(t))),c.push(e)}r.additionalProperties=He(i.valueType,t,{...s,path:[...s.path,"additionalProperties"]})}const d=a._zod.values,u=t.io==="input"&&In(i.valueType)!==void 0;if(d&&!i.partial&&!u){const c=[...d].filter(f=>typeof f=="string"||typeof f=="number");c.length>0&&(r.required=c.map(String))}},rh=(e,t,n,s)=>{const r=e._zod.def,i=He(r.innerType,t,s),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=r.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},oh=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},ar=Symbol();function Fi(e,t,n,s,r){let i=!1;const a=JSON.stringify(e,(l,d)=>typeof d!="bigint"?d:(i=!0,null));return i?(Mt(t,n,s,r,"BigInt defaults cannot be represented in JSON Schema"),ar):JSON.parse(a)}const ih=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType;const a=Fi(r.defaultValue,e,t,n,s);a!==ar&&(n.default=a)},ah=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);if(i.ref=r.innerType,t.io!=="input")return;const a=Fi(r.defaultValue,e,t,n,s);a!==ar&&(n._prefault=a)},lh=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType;let a;try{a=r.catchValue(void 0)}catch{Mt(e,t,n,s,"Dynamic catch values are not supported in JSON Schema");return}n.default=a},ch=(e,t,n,s)=>{const r=e._zod.def,i=r.in._zod.traits.has("$ZodTransform"),a=t.io==="input"?i?r.out:r.in:r.out;He(a,t,s);const l=t.seen.get(e);l.ref=a},dh=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType,n.readOnly=!0},Ui=(e,t,n,s)=>{const r=e._zod.def;He(r.innerType,t,s);const i=t.seen.get(e);i.ref=r.innerType},bo=new WeakSet([Object.prototype,Error.prototype]);function kn(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const s=n(this);return Object.defineProperty(this,t,{value:s,configurable:!0,writable:!0}),s},set(s){Object.defineProperty(this,t,{value:s,configurable:!0,writable:!0})}})}const uh=(e,t)=>{jc.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);bo.has(n)||(bo.add(n),kn(n,"format",s=>r=>Sc(s,r)),kn(n,"flatten",s=>r=>Nc(s,r)),kn(n,"addIssue",s=>r=>{s.issues.push(r),s.message=JSON.stringify(s.issues,Ms,2)}),kn(n,"addIssues",s=>r=>{s.issues.push(...r),s.message=JSON.stringify(s.issues,Ms,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},rt=I("ZodError",uh,void 0,{Parent:Error}),fh=Vs(rt),hh=er(rt),ph=tr(rt),mh=nr(rt),xh=Tc(rt),gh=Pc(rt),yh=Ac(rt),bh=Dc(rt),vh=Ic(rt),kh=Lc(rt),wh=Bc(rt),_h=Zc(rt);function jh(){at.localeError||ut(Fu())}function Jn(){at.memoizer||ut({memoizer:Bu()})}const Be=I("ZodType",(e,t)=>(jh(),Le.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(st(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ct(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(wp(e,t))},superRefine(e,t){return this.check(_p(e,t))},overwrite(e){return this.check(Kt(e))},optional(){return jo(this)},exactOptional(){return cp(this)},nullable(){return $o(this)},nullish(){return jo($o(this))},nonoptional(e){return mp(this,e)},array(){return Pe(this)},or(e){return tp([this,e])},and(e){return op(this,e)},transform(e){return No(this,lp(e))},default(e){return fp(this,e)},prefault(e){return pp(this,e)},catch(e){return gp(this,e)},pipe(e){return No(this,e)},readonly(){return vp(this)},describe(e){const t=this.clone();return tn.add(t,{description:e}),t},meta(...e){if(e.length===0)return tn.get(this);const t=this.clone();return tn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return li(this,"~standard",{...xi(this),jsonSchema:{input:Dn(this,"input"),output:Dn(this,"output")}})},set"~standard"(e){St(this,"~standard",e)},parse:function e(t,n){return fh(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await hh(this,t,n,{callee:e})},safeParse(e,t){return ph(this,e,t)},async safeParseAsync(e,t){return mh(this,e,t)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(e){St(this,"spa",e)},validate(e,t){return Ec(this,e,t)},validateAsync(e,t){return zc(this,e,t)},encode:function e(t,n){return xh(this,t,n,{callee:e})},decode:function e(t,n){return gh(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await yh(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await bh(this,t,n,{callee:e})},safeEncode(e,t){return vh(this,e,t)},safeDecode(e,t){return kh(this,e,t)},async safeEncodeAsync(e,t){return wh(this,e,t)},async safeDecodeAsync(e,t){return _h(this,e,t)},toJSONSchema(e){return Zf(this,{})(e)},get description(){var e;return(e=tn.get(this))==null?void 0:e.description},get _def(){return this._zod.def}}),Hi=I("_ZodString",(e,t)=>{or.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Uf(e,n,s)},ci({format:e=>it(e).format??null,minLength:e=>it(e).minimum??null,maxLength:e=>it(e).maximum??null},{regex(...e){return this.check(jf(...e))},includes(...e){return this.check(Sf(...e))},startsWith(...e){return this.check(Mf(...e))},endsWith(...e){return this.check(Cf(...e))},min(...e){return this.check(An(...e))},max(...e){return this.check(Ei(...e))},length(...e){return this.check(Oi(...e))},nonempty(...e){return this.check(An(1,...e))},lowercase(e){return this.check($f(e))},uppercase(e){return this.check(Nf(e))},trim(){return this.check(Of())},normalize(...e){return this.check(Ef(...e))},toLowerCase(){return this.check(zf())},toUpperCase(){return this.check(Tf())},slugify(){return this.check(Pf())}})),$h=I("ZodString",(e,t)=>{or.init(e,t),Hi.init(e,t)},{email(e){return this.check(Ku(Eh,e))},url(e){return this.check(Qu(zh,e))},jwt(e){return this.check(pf(qh,e))},emoji(e){return this.check(Vu(Th,e))},guid(e){return this.check(qu(Oh,e))},uuid(e){return this.check(Ju(wn,e))},uuidv4(e){return this.check(Xu(wn,e))},uuidv6(e){return this.check(Yu(wn,e))},uuidv7(e){return this.check(Gu(wn,e))},nanoid(e){return this.check(ef(Ph,e))},cuid(e){return this.check(tf(Ah,e))},cuid2(e){return this.check(nf(Dh,e))},ulid(e){return this.check(sf(Ih,e))},base64(e){return this.check(uf(Hh,e))},base64url(e){return this.check(ff(Wh,e))},xid(e){return this.check(rf(Lh,e))},ksuid(e){return this.check(of(Bh,e))},ipv4(e){return this.check(af(Zh,e))},ipv6(e){return this.check(lf(Rh,e))},cidrv4(e){return this.check(cf(Fh,e))},cidrv6(e){return this.check(df(Uh,e))},e164(e){return this.check(hf(Kh,e))},datetime(e){return this.check(mf(Nh,e))},date(e){return this.check(xf(Sh,e))},time(e){return this.check(gf(Mh,e))},duration(e){return this.check(yf(Ch,e))}});function Me(e){return Wu($h,e)}const Ze=I("ZodStringFormat",(e,t)=>{Ie.init(e,t),Hi.init(e,t)}),Nh=I("ZodISODateTime",(e,t)=>{qd.init(e,t),Ze.init(e,t)}),Sh=I("ZodISODate",(e,t)=>{Jd.init(e,t),Ze.init(e,t)}),Mh=I("ZodISOTime",(e,t)=>{Xd.init(e,t),Ze.init(e,t)}),Ch=I("ZodISODuration",(e,t)=>{Yd.init(e,t),Ze.init(e,t)}),Eh=I("ZodEmail",(e,t)=>{Td.init(e,t),Ze.init(e,t)}),Oh=I("ZodGUID",(e,t)=>{Od.init(e,t),Ze.init(e,t)}),wn=I("ZodUUID",(e,t)=>{zd.init(e,t),Ze.init(e,t)}),zh=I("ZodURL",(e,t)=>{Bd.init(e,t),Ze.init(e,t)}),Th=I("ZodEmoji",(e,t)=>{Zd.init(e,t),Ze.init(e,t)}),Ph=I("ZodNanoID",(e,t)=>{Rd.init(e,t),Ze.init(e,t)}),Ah=I("ZodCUID",(e,t)=>{Fd.init(e,t),Ze.init(e,t)}),Dh=I("ZodCUID2",(e,t)=>{Ud.init(e,t),Ze.init(e,t)}),Ih=I("ZodULID",(e,t)=>{Hd.init(e,t),Ze.init(e,t)}),Lh=I("ZodXID",(e,t)=>{Wd.init(e,t),Ze.init(e,t)}),Bh=I("ZodKSUID",(e,t)=>{Kd.init(e,t),Ze.init(e,t)}),Zh=I("ZodIPv4",(e,t)=>{Gd.init(e,t),Ze.init(e,t)}),Rh=I("ZodIPv6",(e,t)=>{Vd.init(e,t),Ze.init(e,t)}),Fh=I("ZodCIDRv4",(e,t)=>{eu.init(e,t),Ze.init(e,t)}),Uh=I("ZodCIDRv6",(e,t)=>{nu.init(e,t),Ze.init(e,t)}),Hh=I("ZodBase64",(e,t)=>{su.init(e,t),Ze.init(e,t)}),Wh=I("ZodBase64URL",(e,t)=>{ou.init(e,t),Ze.init(e,t)}),Kh=I("ZodE164",(e,t)=>{iu.init(e,t),Ze.init(e,t)}),qh=I("ZodJWT",(e,t)=>{lu.init(e,t),Ze.init(e,t)}),Wi=I("ZodNumber",(e,t)=>{wi.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Hf(e,n,s,r),e.isFinite=!0},ci({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=it(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=it(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=it(e);return!!t||!!(n!=null&&n.some(Number.isSafeInteger))},format:e=>it(e).format??null},{gt(e,t){return this.check(co(e,t))},gte(e,t){return this.check(vs(e,t))},min(e,t){return this.check(vs(e,t))},lt(e,t){return this.check(lo(e,t))},lte(e,t){return this.check(bs(e,t))},max(e,t){return this.check(bs(e,t))},int(e){return this.check(vo(e))},safe(e){return this.check(vo(e))},positive(e){return this.check(co(0,e))},nonnegative(e){return this.check(vs(0,e))},negative(e){return this.check(lo(0,e))},nonpositive(e){return this.check(bs(0,e))},multipleOf(e,t){return this.check(uo(e,t))},step(e,t){return this.check(uo(e,t))},finite(){return this}}));function ot(e){return bf(Wi,e)}const Jh=I("ZodNumberFormat",(e,t)=>{cu.init(e,t),Wi.init(e,t)});function vo(e){return vf(Jh,e)}const Xh=I("ZodBoolean",(e,t)=>{du.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Wf(e,n,s)});function ht(e){return kf(Xh,e)}const Yh=I("ZodUnknown",(e,t)=>{uu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>qf()});function ko(){return wf(Yh)}const Gh=I("ZodNever",(e,t)=>{fu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Kf(e,n,s)});function Qh(e){return _f(Gh,e)}const Vh=I("ZodArray",(e,t)=>{Jn(),mu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Qf(e,n,s,r),e.element=t.element},{min(e,t){return this.check(An(e,t))},nonempty(e){return this.check(An(1,e))},max(e,t){return this.check(Ei(e,t))},length(e,t){return this.check(Oi(e,t))},unwrap(){return this.element}});function Pe(e,t){return Af(Vh,e,t)}const ep=I("ZodObject",(e,t)=>{Jn(),yu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Vf(e,n,s,r),xc(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return Ke(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(st(this._zod.def,{catchall:e}))},passthrough(){return this.clone(st(this._zod.def,{catchall:ko()}))},loose(){return this.clone(st(this._zod.def,{catchall:ko()}))},strict(){return this.clone(st(this._zod.def,{catchall:Qh()}))},strip(){return this.clone(st(this._zod.def,{catchall:void 0}))},extend(e){return oc(this,e)},safeExtend(e){return ic(this,e)},merge(e){return ac(this,e)},pick(e){return sc(this,e)},omit(e){return rc(this,e)},partial(...e){return Hr(qi,this,e[0])},exactPartial(...e){return Hr(Ji,this,e[0],"exactPartial")},required(...e){return lc(Xi,this,e[0])}});function Ae(e,t){const n={type:"object",shape:e??{},...de(t)};return new ep(n)}const Ki=I("ZodUnion",(e,t)=>{$i.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>eh(e,n,s,r),e.options=t.options});function tp(e,t){return new Ki({type:"union",options:e,...de(t)})}const np=I("ZodDiscriminatedUnion",(e,t)=>{Ki.init(e,t),vu.init(e,t)});function sp(e,t,n){return new np({type:"union",options:t,discriminator:e,...de(n)})}const rp=I("ZodIntersection",(e,t)=>{ku.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>th(e,n,s,r)});function op(e,t){return new rp({type:"intersection",left:e,right:t})}const wo=I("ZodRecord",(e,t)=>{Jn(),wu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>sh(e,n,s,r),e.keyType=t.keyType,e.valueType=t.valueType});function _o(e,t,n){return!t||!t._zod?new wo({type:"record",keyType:Me(),valueType:e,...de(t)}):new wo({type:"record",keyType:e,valueType:t,...de(n)})}const Ds=I("ZodEnum",(e,t)=>{_u.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(s,r,i)=>Jf(e,s,r),e.enum=t.entries,e.options=[...e._zod.values];const n=new Set(Object.keys(t.entries));e.extract=(s,r)=>{const i={};for(const a of s)if(n.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Ds({...t,checks:[],...de(r),entries:i})},e.exclude=(s,r)=>{const i={...t.entries};for(const a of s)if(n.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Ds({...t,checks:[],...de(r),entries:i})}});function Ke(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(s=>[s,s])):e;return new Ds({type:"enum",entries:n,...de(t)})}const ip=I("ZodLiteral",(e,t)=>{ju.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Xf(e,n,s,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function En(e,t){return new ip({type:"literal",values:Array.isArray(e)?e:[e],...de(t)})}const ap=I("ZodTransform",(e,t)=>{Jn(),$u.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Gf(e,n,s,r),e._zod.parse=(n,s)=>{if(s.direction==="backward")throw new di(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(cn(i,n.value,t));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=n.value),a.inst??(a.inst=e),n.issues.push(cn(a))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(i=>(n.value=i,n)):(n.value=r,n)}});function lp(e){return new ap({type:"transform",transform:e})}const qi=I("ZodOptional",(e,t)=>{Ni.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ui(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function jo(e){return new qi({type:"optional",innerType:e})}const Ji=I("ZodExactOptional",(e,t)=>{Nu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Ui(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function cp(e){return new Ji({type:"optional",innerType:e})}const dp=I("ZodNullable",(e,t)=>{Su.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>rh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function $o(e){return new dp({type:"nullable",innerType:e})}const up=I("ZodDefault",(e,t)=>{Mu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ih(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function fp(e,t){return new up({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():ri(t)}})}const hp=I("ZodPrefault",(e,t)=>{Cu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ah(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function pp(e,t){return new hp({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():ri(t)}})}const Xi=I("ZodNonOptional",(e,t)=>{Eu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>oh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function mp(e,t){return new Xi({type:"nonoptional",innerType:e,...de(t)})}const xp=I("ZodCatch",(e,t)=>{Ou.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>lh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function gp(e,t){return new xp({type:"catch",innerType:e,catchValue:typeof t=="function"?t:yc(t)})}const yp=I("ZodPipe",(e,t)=>{zu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>ch(e,n,s,r),e.in=t.in,e.out=t.out});function No(e,t){return new yp({type:"pipe",in:e,out:t})}const bp=I("ZodReadonly",(e,t)=>{Tu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>dh(e,n,s,r),e.unwrap=()=>e._zod.def.innerType});function vp(e){return new bp({type:"readonly",innerType:e})}const kp=I("ZodCustom",(e,t)=>{Pu.init(e,t),Be.init(e,t),e._zod.processJSONSchema=(n,s,r)=>Yf(e,n,s,r)});function wp(e,t={}){return Df(kp,e,t)}function _p(e,t){return If(e,t)}const So=/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/,Is=/^[a-z0-9]+(?:_[a-z0-9]+)*$/;function Re(e="id"){return Me().min(1,`${e} is required`).max(128,`${e} must be at most 128 characters`).regex(So,`${e} must match ${So.source} (lowercase alphanumeric, '-', '_')`)}const lr=Me().min(1,"entity_ref must not be empty").max(128,"entity_ref must be at most 128 characters").regex(Is,"entity_ref must be canonical snake_case (lowercase letters, digits, '_')"),cr=Ke(["general","er"]),Yi=Ke(["card","decision","terminal","store"]),Ln=Ke(["1","0..1","1..*","0..*"]),Gi=Ke(["association","identifying","subtype"]),Mo=Ke(["top","right","bottom","left"]),Qi=Ke(["draft","needs_input","approved","implemented","drifted"]),dr=Ae({path:Me().trim().min(1,"code_ref.path is required"),symbol:Me().trim().min(1,"code_ref.symbol must not be empty").optional()}),ur=Ae({id:Re("section.id"),heading:Me().trim().min(1,"section.heading is required"),items:Pe(Me())}),Vi=Ae({id:Re("field.id"),name:Me().trim().min(1,"field.name is required"),type:Me().trim().min(1).optional(),pk:ht().optional(),fk:ht().optional(),unique:ht().optional(),nullable:ht().optional(),indexed:ht().optional(),default_value:Me().optional(),note:Me().optional()}),ea=Ae({id:Re("node.id"),entity_ref:lr.optional(),kind:Me().trim().min(1,"node.kind is required"),shape:Yi.optional(),title:Me().trim().min(1,"node.title is required"),summary:Me().optional(),status:Qi.default("draft"),locked:ht().default(!1),sections:Pe(ur).default([]),fields:Pe(Vi).optional(),code_refs:Pe(dr).optional()}),ta=Ke(["solid","dashed"]),na=Ae({id:Re("edge.id"),source:Re("edge.source"),target:Re("edge.target"),label:Me().optional(),step:ot().int().positive("edge.step must be a positive integer").optional(),style:ta.optional(),locked:ht().optional(),source_cardinality:Ln.optional(),target_cardinality:Ln.optional(),relation_kind:Gi.optional()}),sa=Ke(["TB","LR"]),ra=Ke(["agent","human"]);Ae({id:Re("view.id"),title:Me().trim().min(1,"view.title is required"),diagram_type:cr.default("general"),direction:sa.default("TB"),created_by:ra.optional(),nodes:Pe(ea).default([]),edges:Pe(na).default([])}).superRefine((e,t)=>{const n=new Set;e.nodes.forEach((r,i)=>{n.has(r.id)&&t.addIssue({code:"custom",path:["nodes",i,"id"],message:`Duplicate node id '${r.id}' in view '${e.id}'`}),n.add(r.id);const a=new Set;r.sections.forEach((d,u)=>{a.has(d.id)&&t.addIssue({code:"custom",path:["nodes",i,"sections",u,"id"],message:`Duplicate section id '${d.id}' in node '${r.id}'`}),a.add(d.id)});const l=new Set;(r.fields??[]).forEach((d,u)=>{l.has(d.id)&&t.addIssue({code:"custom",path:["nodes",i,"fields",u,"id"],message:`Duplicate field id '${d.id}' in node '${r.id}'`}),l.add(d.id)})});const s=new Set;e.edges.forEach((r,i)=>{s.has(r.id)&&t.addIssue({code:"custom",path:["edges",i,"id"],message:`Duplicate edge id '${r.id}' in view '${e.id}'`}),s.add(r.id),n.has(r.source)||t.addIssue({code:"custom",path:["edges",i,"source"],message:`Edge '${r.id}' references missing source node '${r.source}'`}),n.has(r.target)||t.addIssue({code:"custom",path:["edges",i,"target"],message:`Edge '${r.id}' references missing target node '${r.target}'`})})});const jp=Ae({view_id:Re("tab.view_id"),title:Me().trim().min(1,"tab.title is required"),diagram_type:cr.optional(),description:Me().optional(),order:ot().int().nonnegative()}),$p=Ae({id:Re("view_request.id"),title:Me().trim().min(1,"view_request.title is required"),prompt:Me().trim().min(1,"view_request.prompt is required"),created_at:Me().min(1)});Ae({version:En(1),project_name:Me().trim().min(1,"project_name is required"),tabs:Pe(jp).default([]),view_requests:Pe($p).default([])}).superRefine((e,t)=>{const n=new Set;e.tabs.forEach((r,i)=>{n.has(r.view_id)&&t.addIssue({code:"custom",path:["tabs",i,"view_id"],message:`Duplicate workspace tab view_id '${r.view_id}'`}),n.add(r.view_id)});const s=new Set;e.view_requests.forEach((r,i)=>{s.has(r.id)&&t.addIssue({code:"custom",path:["view_requests",i,"id"],message:`Duplicate view_request id '${r.id}'`}),s.add(r.id)})});const Np=Ae({id:Re("message.id"),author:ra,body:Me().trim().min(1,"message.body is required"),created_at:Me().min(1)}),Sp=Ke(["workspace","view","node","edge"]),Mp=Ke(["question","change_request","decision","drift_alert"]),Cp=Ke(["open","resolved"]);Ae({id:Re("thread.id"),target_type:Sp,view_id:Re("thread.view_id").optional(),target_id:Re("thread.target_id").optional(),entity_ref:lr.optional(),kind:Mp,status:Cp.default("open"),resolution_summary:Me().optional(),messages:Pe(Np).min(1,"thread must contain at least one message")}).superRefine((e,t)=>{(e.target_type==="view"||e.target_type==="node"||e.target_type==="edge")&&!e.view_id&&t.addIssue({code:"custom",path:["view_id"],message:`view_id is required when target_type is '${e.target_type}'`}),(e.target_type==="node"||e.target_type==="edge")&&!e.target_id&&t.addIssue({code:"custom",path:["target_id"],message:`target_id is required when target_type is '${e.target_type}'`})});const Ep=Ae({source_handle:Mo.optional(),target_handle:Mo.optional(),waypoints:Pe(Ae({x:ot().finite(),y:ot().finite()})).optional()});Ae({positions:_o(Me(),Ae({x:ot().finite(),y:ot().finite()})).default({}),edge_routes:_o(Me(),Ep).optional(),viewport:Ae({x:ot().finite(),y:ot().finite(),zoom:ot().positive().finite()}).optional()});const Op=sp("op",[Ae({op:En("add"),section:ur,index:ot().int().nonnegative().optional()}),Ae({op:En("update"),id:Re("section.id"),heading:Me().trim().min(1).optional(),items:Pe(Me()).optional(),add_items:Pe(Me()).optional(),remove_items:Pe(Me()).optional()}),Ae({op:En("remove"),id:Re("section.id")})]),zp=Ae({id:Re("node.id"),entity_ref:lr.nullable().optional(),kind:Me().trim().min(1).optional(),shape:Yi.nullable().optional(),title:Me().trim().min(1).optional(),summary:Me().nullable().optional(),status:Qi.optional(),locked:ht().optional(),sections:Pe(ur).optional(),section_ops:Pe(Op).optional(),fields:Pe(Vi).optional(),code_refs:Pe(dr).nullable().optional()}),Tp=Ae({id:Re("edge.id"),source:Re("edge.source").optional(),target:Re("edge.target").optional(),label:Me().nullable().optional(),step:ot().int().positive().nullable().optional(),style:ta.nullable().optional(),locked:ht().nullable().optional(),source_cardinality:Ln.nullable().optional(),target_cardinality:Ln.nullable().optional(),relation_kind:Gi.nullable().optional()});Ae({meta:Ae({title:Me().trim().min(1).optional(),direction:sa.optional(),diagram_type:cr.optional()}).optional(),add_nodes:Pe(ea).optional(),update_nodes:Pe(zp).optional(),remove_nodes:Pe(Re("node.id")).optional(),add_edges:Pe(na).optional(),update_edges:Pe(Tp).optional(),remove_edges:Pe(Re("edge.id")).optional()});Ae({node_id:Re("node_id"),status:Ke(["implemented","drifted"]),code_refs:Pe(dr)});const Pp=Ke(["dark","light"]),Ap=Ke(["dots","grid"]),Dp=Ke(["pan","zoom"]);Ae({theme:Pp.optional(),bg_pattern:Ap.optional(),scroll_mode:Dp.optional()});function Ip(e){if(e.status!=="open")return!1;const t=e.messages[e.messages.length-1];return(t==null?void 0:t.author)==="human"}function On(e){if(e.status!=="open")return!1;const t=e.messages[e.messages.length-1];return(t==null?void 0:t.author)==="agent"}class oa extends Error{constructor(n,s,r,i){super(r);Gt(this,"status");Gt(this,"code");Gt(this,"details");this.name="ApiError",this.status=n,this.code=s,this.details=i}}async function qe(e,t){const n=await fetch(e,{...t,headers:{"Content-Type":"application/json",...(t==null?void 0:t.headers)??{}}}),s=await n.text();let r={};if(s)try{r=JSON.parse(s)}catch{r={message:s}}if(!n.ok){const i=r;throw new oa(n.status,i.error??`HTTP_${n.status}`,i.message??`Request failed (${n.status})`,i.details)}return r}function Lp(){return qe("/api/workspace")}function Bp(e){return qe("/api/workspace/tabs",{method:"PUT",body:JSON.stringify({tabs:e})})}function Zp(e){return qe("/api/workspace/view-requests",{method:"POST",body:JSON.stringify(e)})}function Rp(e){return qe(`/api/workspace/view-requests/${encodeURIComponent(e)}`,{method:"DELETE"})}function Fp(e){return qe("/api/views",{method:"POST",body:JSON.stringify(e)})}function Up(e){return qe(`/api/views/${encodeURIComponent(e)}`,{method:"DELETE"})}function Hp(){return qe("/api/views")}function Wp(e){return qe(`/api/views/${encodeURIComponent(e)}`)}function Kp(e,t){return qe(`/api/views/${encodeURIComponent(e.id)}`,{method:"PUT",body:JSON.stringify({view:e,base_hash:t})})}function fr(e,t){return qe(`/api/layout/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(t)})}function Co(e){return qe(`/api/layout/${encodeURIComponent(e)}`,{method:"DELETE"})}function qp(e){const n=new URLSearchParams().toString();return qe(`/api/threads${n?`?${n}`:""}`)}function Jp(e){return qe("/api/threads",{method:"POST",body:JSON.stringify(e)})}function Xp(e,t){return qe(`/api/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:JSON.stringify(t)})}function Yp(e){return qe(`/api/cross-links/${encodeURIComponent(e)}`)}async function Gp(){return(await qe("/api/preferences")).preferences}async function ws(e){return(await qe("/api/preferences",{method:"PUT",body:JSON.stringify(e)})).preferences}function Qp(e,t){let n=!1,s=null,r=null,i=0;const a=()=>{if(n)return;const d=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;s=new WebSocket(d),s.onopen=()=>{i=0,t(!0)},s.onmessage=u=>{try{const c=JSON.parse(String(u.data));e(c)}catch{}},s.onclose=()=>{if(t(!1),n)return;const u=Math.min(8e3,400*Math.pow(1.6,i));i+=1,r=setTimeout(a,u)},s.onerror=()=>{s==null||s.close()}};return a(),()=>{n=!0,r&&clearTimeout(r),s==null||s.close()}}const Vp="modulepreload",em=function(e){return"/"+e},Eo={},tm=function(t,n,s){let r=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(c=>Promise.resolve(c).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));r=a(n.map(u=>{if(u=em(u),u in Eo)return;Eo[u]=!0;const c=u.endsWith(".css"),f=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${f}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":Vp,c||(p.as="script"),p.crossOrigin="",p.href=u,d&&p.setAttribute("nonce",d),document.head.appendChild(p),c)return new Promise((h,x)=>{p.addEventListener("load",h),p.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=a,window.dispatchEvent(l),!l.defaultPrevented)throw a}return r.then(a=>{for(const l of a||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let _s=null;function nm(){return _s||(_s=tm(async()=>{const{default:e}=await import("./elkjs-DuIp8wh-.js").then(t=>t.e);return{default:e}},__vite__mapDeps([0,1])).then(({default:e})=>new e)),_s}const dn=5,Bn=8;function mt(e,t){return e<=t+1?{visibleCount:e,hiddenCount:0}:{visibleCount:t,hiddenCount:e-t}}function Xn(e,t="general"){return t==="er"||e.fields&&e.fields.length>0?"card":e.shape??"card"}const Zn=[{shape:"card",label:"Card (Box)",shortLabel:"Card",hint:"Structured component / service card"},{shape:"decision",label:"Decision (Rhombus)",shortLabel:"Decision",hint:"Conditional branch or gate diamond"},{shape:"terminal",label:"Terminal (Pill)",shortLabel:"Terminal",hint:"Start, end, actor, or trigger pill"},{shape:"store",label:"Store (Database)",shortLabel:"Store",hint:"Database, cache, or queue cylinder"}];function hr(e,t="general"){var c,f,p,h;const n=Xn(e,t);if(n==="decision"){const x=Math.max(e.title.length,10),m=Math.min(290,Math.max(244,Math.round(x*7+124))),g=Math.max(1,Math.min(3,Math.ceil(e.title.length/20))),y=(c=e.summary)!=null&&c.trim()?e.summary.trim().length>26?30:18:0,b=Math.max(148,Math.round(m*.56)+(g-1)*16+y);return{width:m,height:b}}if(n==="terminal"){const x=Math.max(e.title.length+4,e.kind.length+8,(f=e.summary)!=null&&f.trim()?Math.min(e.summary.trim().length,32):0),m=Math.min(290,Math.max(200,Math.round(x*6.8+72)));let y=76+(Math.max(1,Math.min(3,Math.ceil(e.title.length/26)))-1)*18;return(p=e.summary)!=null&&p.trim()&&(y+=e.summary.trim().length>32?32:18),(e.entity_ref||e.code_refs&&e.code_refs.length>0)&&(y+=18),{width:m,height:Math.max(76,y)}}let s=e.title.length+e.kind.length+6;for(const x of e.sections){s=Math.max(s,x.heading.length+4);const{visibleCount:m}=mt(x.items.length,dn);for(const g of x.items.slice(0,m))s=Math.max(s,g.length)}const{visibleCount:r}=mt((e.fields??[]).length,Bn);for(const x of(e.fields??[]).slice(0,r)){const m=x.name.length+(x.type?x.type.length+2:0)+10;s=Math.max(s,m)}const i=Math.min(350,Math.max(280,Math.round(s*6.6+52))),a=Math.max(18,Math.floor((i-104)/7.2));let d=42+Math.max(1,Math.min(4,Math.ceil(e.title.length/a)))*19;(h=e.summary)!=null&&h.trim()&&(d+=e.summary.trim().length>42?44:28);const u=e.fields??[];if(t==="er"||u.length>0){const{visibleCount:x,hiddenCount:m}=mt(u.length,Bn),g=m>0?26:0,y=u.length===0?24:0;d+=28+x*25+g+y+14}for(const x of e.sections){const{visibleCount:m,hiddenCount:g}=mt(x.items.length,dn),y=g>0?24:0,b=x.items.length===0?20:0;d+=26+m*22+y+b+12}return e.sections.length===0&&u.length===0&&t!=="er"&&(d+=28),(e.entity_ref||e.code_refs&&e.code_refs.length>0)&&(d+=28),n==="store"&&(d+=32),{width:i,height:Math.max(112,d+14)}}function Oo(e,t,n){const s=(n==null?void 0:n.gap)??40,r=n==null?void 0:n.pinnedIds,i=(n==null?void 0:n.preferredAxis)??"y",a={};for(const[d,u]of Object.entries(e))a[d]={x:u.x,y:u.y};const l=Object.keys(a).sort((d,u)=>{const c=a[d],f=a[u];return c.y-f.y||c.x-f.x||d.localeCompare(u)});if(l.length<2)return a;for(let d=0;d<40;d++){let u=!1;for(let c=0;c<l.length;c++){const f=l[c],p=a[f],h=t[f]??{width:290,height:180},x=(r==null?void 0:r.has(f))??!1;for(let m=c+1;m<l.length;m++){const g=l[m],y=(r==null?void 0:r.has(g))??!1;if(x&&y)continue;const b=a[g],$=t[g]??{width:290,height:180},k=p.x+h.width/2,_=p.y+h.height/2,O=b.x+$.width/2,F=b.y+$.height/2,N=O-k,P=F-_,M=(h.width+$.width)/2+s,A=(h.height+$.height)/2+s,q=M-Math.abs(N),ne=A-Math.abs(P);if(q<=.5||ne<=.5)continue;if(u=!0,i==="x"?q<=ne*1.15:q*1.15<ne){const w=N===0?f<g?1:-1:Math.sign(N),Z=Math.ceil(q);if(x)b.x=Math.round(b.x+w*Z);else if(y)p.x=Math.round(p.x-w*Z);else{const D=Math.ceil(Z/2);p.x=Math.round(p.x-w*D),b.x=Math.round(b.x+w*(Z-D))}}else{const w=P===0?f<g?1:-1:Math.sign(P),Z=Math.ceil(ne);if(x)b.y=Math.round(b.y+w*Z);else if(y)p.y=Math.round(p.y-w*Z);else{const D=Math.ceil(Z/2);p.y=Math.round(p.y-w*D),b.y=Math.round(b.y+w*(Z-D))}}}}if(!u)break}return a}function sm(e,t,n){const s=[e,...t,n].map(a=>({x:Math.round(a.x),y:Math.round(a.y)})),r=[];for(const a of s){const l=r[r.length-1];(!l||Math.abs(l.x-a.x)>.5||Math.abs(l.y-a.y)>.5)&&r.push(a)}if(r.length<=2)return[];const i=[r[0]];for(let a=1;a<r.length-1;a++){const l=i[i.length-1],d=r[a],u=r[a+1],c=Math.abs(l.x-d.x)<=.5&&Math.abs(d.x-u.x)<=.5,f=Math.abs(l.y-d.y)<=.5&&Math.abs(d.y-u.y)<=.5;!c&&!f&&i.push(d)}return i.slice(1)}function zo(e,t,n){const s=Math.abs(e.x-t.x),r=Math.abs(e.x-(t.x+n.width)),i=Math.abs(e.y-t.y),a=Math.abs(e.y-(t.y+n.height)),l=Math.min(s,r,i,a);return l===s?"left":l===r?"right":l===i?"top":"bottom"}async function rm(e,t,n){var g,y;if(e.nodes.length===0)return{positions:{},autoRoutes:{}};const s={};for(const b of e.nodes){const $=hr(b,e.diagram_type),k=(g=n==null?void 0:n.measured)==null?void 0:g[b.id];s[b.id]={width:Math.round(k!=null&&k.width&&k.width>0?k.width:$.width),height:Math.round(k!=null&&k.height&&k.height>0?k.height:$.height)}}if(!(n!=null&&n.forceReset)&&e.nodes.every(b=>!!t.positions[b.id])){const b={};for(const $ of e.nodes){const k=t.positions[$.id];b[$.id]={x:k.x,y:k.y}}return{positions:b,autoRoutes:{}}}const r=e.nodes.map(b=>({id:b.id,width:s[b.id].width,height:s[b.id].height})),i=e.edges.map(b=>({id:b.id,sources:[b.source],targets:[b.target]})),a=e.diagram_type==="er",d=await(await nm()).layout({id:e.id,layoutOptions:{"elk.algorithm":"layered","elk.direction":e.direction==="LR"?"RIGHT":"DOWN","elk.edgeRouting":"ORTHOGONAL","elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"BRANDES_KOEPF","elk.layered.nodePlacement.bk.fixedAlignment":"BALANCED","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.crossingMinimization.greedySwitch.type":"TWO_SIDED","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.thoroughness":"14","elk.separateConnectedComponents":"true","elk.aspectRatio":"1.6","elk.spacing.nodeNode":a?"96":"80","elk.layered.spacing.nodeNodeBetweenLayers":a?"200":"160","elk.spacing.edgeNode":a?"52":"44","elk.spacing.edgeEdge":"20","elk.spacing.componentComponent":"110","elk.padding":"[top=32,left=32,bottom=32,right=32]"},children:r,edges:i}),u={};for(const b of d.children??[])u[b.id]={x:Math.round(b.x??0),y:Math.round(b.y??0)};const c=Oo(u,s,{gap:40,preferredAxis:e.direction==="LR"?"y":"x"}),f=new Map(e.edges.map(b=>[b.id,b])),p={};for(const b of d.edges??[]){const $=f.get(b.id),k=(y=b.sections)==null?void 0:y[0];if(!$||!(k!=null&&k.startPoint)||!(k!=null&&k.endPoint)||$.source===$.target)continue;const _=u[$.source],O=u[$.target],F=c[$.source],N=c[$.target];if(!_||!O||!F||!N||Math.abs(_.x-F.x)>1||Math.abs(_.y-F.y)>1||Math.abs(O.x-N.x)>1||Math.abs(O.y-N.y)>1)continue;const P={x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)},M={x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)},A=sm(P,k.bendPoints??[],M),q=s[$.source],ne=s[$.target];p[$.id]={sourceSide:zo(P,F,q),targetSide:zo(M,N,ne),startPoint:P,endPoint:M,waypoints:A,sourcePos:{...F},targetPos:{...N}}}if(n!=null&&n.forceReset)return{positions:c,autoRoutes:p};const h=new Set,x={};for(const b of e.nodes){const $=t.positions[b.id];$?(x[b.id]={x:$.x,y:$.y},h.add(b.id)):x[b.id]=c[b.id]??{x:40,y:40}}return{positions:Oo(x,s,{gap:40,pinnedIds:h,preferredAxis:e.direction==="LR"?"y":"x"}),autoRoutes:p}}function It(e,t,n,s=14){const r=n.x-s,i=n.x+n.width+s,a=n.y-s,l=n.y+n.height+s;let d=0,u=1;const c=t.x-e.x,f=t.y-e.y,p=[[-c,e.x-r],[c,i-e.x],[-f,e.y-a],[f,l-e.y]];for(const[h,x]of p)if(Math.abs(h)<1e-6){if(x<0)return!1}else{const m=x/h;if(h<0){if(m>u)return!1;m>d&&(d=m)}else{if(m<d)return!1;m<u&&(u=m)}}return d<=u}function Ge(e,t){switch(t){case"top":return{x:e.cx,y:e.y};case"right":return{x:e.x+e.width,y:e.cy};case"bottom":return{x:e.cx,y:e.y+e.height};case"left":return{x:e.x,y:e.cy}}}function dt(e,t,n){return n?t==="left"||t==="right"?{x:e.x,y:e.y+n}:{x:e.x+n,y:e.y}:e}function om(e,t,n){const s=n.x-t.x,r=n.y-t.y,i=s*s+r*r;if(i<1e-6){const f=e.x-t.x,p=e.y-t.y;return f*f+p*p}const a=Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*r)/i)),l=t.x+s*a,d=t.y+r*a,u=e.x-l,c=e.y-d;return u*u+c*c}function ia(e,t,n){var r,i;const s=new Map;for(const a of e.nodes){const l=t[a.id]??{x:40,y:40},d=hr(a,e.diagram_type),u=((r=n==null?void 0:n[a.id])==null?void 0:r.width)??d.width,c=((i=n==null?void 0:n[a.id])==null?void 0:i.height)??d.height;s.set(a.id,{x:l.x,y:l.y,width:u,height:c,cx:l.x+u/2,cy:l.y+c/2})}return s}function jt(e){switch(e){case"top":return{x:0,y:-1};case"right":return{x:1,y:0};case"bottom":return{x:0,y:1};case"left":return{x:-1,y:0}}}function _n(e,t,n,s){const r=Ge(e,t),i=Ge(n,s),a=jt(t),l=jt(s),d={x:r.x+a.x*24,y:r.y+a.y*24},u={x:i.x+l.x*24,y:i.y+l.y*24},c=t==="left"||t==="right",f=s==="left"||s==="right";if(c&&f){const p=(d.x+u.x)/2;return[r,d,{x:p,y:d.y},{x:p,y:u.y},u,i]}if(!c&&!f){const p=(d.y+u.y)/2;return[r,d,{x:d.x,y:p},{x:u.x,y:p},u,i]}return c&&!f?[r,d,{x:u.x,y:d.y},u,i]:[r,d,{x:d.x,y:u.y},u,i]}function nn(e,t,n=12){const s=[];for(const r of t){let i=!1;for(let a=0;a<e.length-1;a++)if(It(e[a],e[a+1],r,n)){i=!0;break}i&&s.push(r)}return s}function im(e,t,n="LR"){return n==="LR"?Math.abs(e)*1.2>=Math.abs(t)?e>=0?{sourceHandle:"right",targetHandle:"left"}:{sourceHandle:"left",targetHandle:"right"}:t>=0?{sourceHandle:"bottom",targetHandle:"top"}:{sourceHandle:"top",targetHandle:"bottom"}:Math.abs(t)*1.2>=Math.abs(e)?t>=0?{sourceHandle:"bottom",targetHandle:"top"}:{sourceHandle:"top",targetHandle:"bottom"}:e>=0?{sourceHandle:"right",targetHandle:"left"}:{sourceHandle:"left",targetHandle:"right"}}function am(e,t=4){const n=[...e].map(r=>Math.round(r)).sort((r,i)=>r-i),s=[];for(const r of n){const i=s[s.length-1];(i===void 0||Math.abs(r-i)>=t)&&s.push(r)}return s}function Rn(e,t){const s=[...am(e,5)];for(const r of t){const i=Math.round(r);s.some(a=>Math.abs(a-i)<=2)||s.push(i)}return s.sort((r,i)=>r-i),s}function jn(e,t){let n=0,s=1/0;const r=Math.round(t);for(let i=0;i<e.length;i++){const a=Math.abs(e[i]-r);a<s&&(s=a,n=i)}return n}function aa(e,t,n){const s=[e,...t,n].map(a=>({x:Math.round(a.x),y:Math.round(a.y)})),r=[];for(const a of s){const l=r[r.length-1];(!l||Math.abs(l.x-a.x)>1||Math.abs(l.y-a.y)>1)&&r.push(a)}if(r.length<=2)return[];const i=[r[0]];for(let a=1;a<r.length-1;a++){const l=i[i.length-1],d=r[a],u=r[a+1],c=Math.abs(l.x-d.x)<=1&&Math.abs(d.x-u.x)<=1,f=Math.abs(l.y-d.y)<=1&&Math.abs(d.y-u.y)<=1;!c&&!f&&i.push(d)}return i.slice(1)}function lm(e,t,n,s){const r=Math.abs(e.y-t.y)<=1&&Math.abs(e.x-t.x)>1,i=Math.abs(e.x-t.x)<=1&&Math.abs(e.y-t.y)>1,a=Math.abs(n.y-s.y)<=1&&Math.abs(n.x-s.x)>1,l=Math.abs(n.x-s.x)<=1&&Math.abs(n.y-s.y)>1;if(r&&l){const d=Math.min(e.x,t.x)+2,u=Math.max(e.x,t.x)-2,c=Math.min(n.y,s.y)+2,f=Math.max(n.y,s.y)-2;return n.x>d&&n.x<u&&e.y>c&&e.y<f}if(i&&a){const d=Math.min(n.x,s.x)+2,u=Math.max(n.x,s.x)-2,c=Math.min(e.y,t.y)+2,f=Math.max(e.y,t.y)-2;return e.x>d&&e.x<u&&n.y>c&&n.y<f}return!1}function cm(e,t,n,s){const r=Math.abs(e.y-t.y)<=1,i=Math.abs(n.y-s.y)<=1;if(r&&i&&Math.abs(e.y-n.y)<=4){const d=Math.min(Math.max(e.x,t.x),Math.max(n.x,s.x))-Math.max(Math.min(e.x,t.x),Math.min(n.x,s.x));return d>2?d:0}const a=Math.abs(e.x-t.x)<=1,l=Math.abs(n.x-s.x)<=1;if(a&&l&&Math.abs(e.x-n.x)<=4){const d=Math.min(Math.max(e.y,t.y),Math.max(n.y,s.y))-Math.max(Math.min(e.y,t.y),Math.min(n.y,s.y));return d>2?d:0}return 0}function dm(e,t){const n=[...e.values()],s=[],r=[];let i=1/0,a=-1/0,l=1/0,d=-1/0;for(const f of n)i=Math.min(i,f.x),a=Math.max(a,f.x+f.width),l=Math.min(l,f.y),d=Math.max(d,f.y+f.height),s.push(f.x-16,f.x+f.width+16,Math.round(f.cx)),r.push(f.y-16,f.y+f.height+16,Math.round(f.cy));Number.isFinite(i)&&(s.push(i-42,a+42,i-76,a+76),r.push(l-42,d+42,l-76,d+76));const u=[...n].sort((f,p)=>f.x-p.x);for(let f=0;f<u.length;f++){const p=u[f].x+u[f].width;for(let h=f+1;h<u.length;h++){const x=u[h].x-p;if(x>=24&&x<=320){s.push(Math.round(p+x/2));break}if(x>320)break}}const c=[...n].sort((f,p)=>f.y-p.y);for(let f=0;f<c.length;f++){const p=c[f].y+c[f].height;for(let h=f+1;h<c.length;h++){const x=c[h].y-p;if(x>=24&&x<=280){r.push(Math.round(p+x/2));break}if(x>280)break}}return{xs:Rn(s,t.map(f=>f.x)),ys:Rn(r,t.map(f=>f.y))}}function um(e,t,n,s,r,i,a){const l=Ge(e,t),d=Ge(n,s),u=jt(t),c=jt(s),f=[22,12];for(const p of f){const h={x:Math.round(l.x+u.x*p),y:Math.round(l.y+u.y*p)},x={x:Math.round(d.x+c.x*p),y:Math.round(d.y+c.y*p)},m=p>=20?10:4;if(r.some(ee=>It(l,h,ee,m)||It(x,d,ee,m)))continue;const g=Rn(i.xs,[h.x,x.x]),y=Rn(i.ys,[h.y,x.y]),b=g.length,$=y.length;if(b===0||$===0)continue;const k=jn(g,h.x),_=jn(y,h.y),O=jn(g,x.x),F=jn(y,x.y),N=b*$*2,P=new Float64Array(N).fill(1/0),M=new Int32Array(N).fill(-1),A=new Uint8Array(N),q=(_*b+k)*2,ne=q+1,Q=t==="left"||t==="right"?0:1,w=Q===0?q:ne;P[w]=0;const Z=[[Math.abs(g[k]-x.x)+Math.abs(y[_]-x.y),w]],D=(ee,ie)=>{Z.push([ee,ie]);let V=Z.length-1;for(;V>0;){const ue=V-1>>1;if(Z[ue][0]<=Z[V][0])break;const we=Z[ue];Z[ue]=Z[V],Z[V]=we,V=ue}},J=()=>{const ee=Z[0][1],ie=Z.pop();if(Z.length>0){Z[0]=ie;let V=0;const ue=Z.length;for(;;){let we=V;const je=V*2+1,xe=je+1;if(je<ue&&Z[je][0]<Z[we][0]&&(we=je),xe<ue&&Z[xe][0]<Z[we][0]&&(we=xe),we===V)break;const re=Z[we];Z[we]=Z[V],Z[V]=re,V=we}}return ee},X=[[1,0,0],[-1,0,0],[0,1,1],[0,-1,1]];let W=-1;const se=F*b+O,le=s==="left"||s==="right"?0:1;for(;Z.length>0;){const ee=J();if(A[ee])continue;A[ee]=1;const ie=ee>>1;if(ie===se){W=ee;break}const V=ee&1,ue=ie%b,we=Math.floor(ie/b),je=g[ue],xe=y[we],re=P[ee];for(const[Se,te,G]of X){const T=ue+Se,E=we+te;if(T<0||T>=b||E<0||E>=$)continue;const z=(E*b+T)*2+G;if(A[z])continue;const R=g[T],C=y[E],S={x:je,y:xe},B={x:R,y:C};if(It(S,B,e,3)||It(S,B,n,3))continue;let oe=!1;for(const ye of r)if(It(S,B,ye,m)){oe=!0;break}if(oe)continue;const L=Math.abs(R-je)+Math.abs(C-xe),be=ee===w&&G===Q?0:V!==G?65:0,_e=E*b+T===se&&G!==le?65:0;let ve=0;for(const ye of a)if(lm(S,B,ye.a,ye.b))ve+=220;else{const K=cm(S,B,ye.a,ye.b);K>0&&(ve+=90+K*.4)}const Oe=re+L+be+_e+ve;if(Oe<P[z]){P[z]=Oe,M[z]=ee;const ye=Math.abs(R-x.x)+Math.abs(C-x.y);D(Oe+ye,z)}}}if(W===-1)continue;const me=[];let ae=W;for(;ae!==-1;){const ee=ae>>1,ie=ee%b,V=Math.floor(ee/b);me.push({x:g[ie],y:y[V]}),ae=M[ae]}return me.reverse(),{waypoints:aa(l,me,d),score:P[W],sourceHandle:t,targetHandle:s}}return null}function To(e,t,n,s){const r=[e,...t,n];for(let i=0;i<r.length-1;i++)s.push({a:r[i],b:r[i+1]})}function fm(e,t,n,s){const r=Math.abs(e.y-t.y)<=2&&Math.abs(e.x-t.x)>4,i=Math.abs(n.y-s.y)<=2&&Math.abs(n.x-s.x)>4;if(r&&i&&Math.abs(e.y-n.y)<=3)return Math.min(Math.max(e.x,t.x),Math.max(n.x,s.x))-Math.max(Math.min(e.x,t.x),Math.min(n.x,s.x))>4;const a=Math.abs(e.x-t.x)<=2&&Math.abs(e.y-t.y)>4,l=Math.abs(n.x-s.x)<=2&&Math.abs(n.y-s.y)>4;return a&&l&&Math.abs(e.x-n.x)<=3?Math.min(Math.max(e.y,t.y),Math.max(n.y,s.y))-Math.max(Math.min(e.y,t.y),Math.min(n.y,s.y))>4:!1}function hm(e,t,n){const s=[];for(const i of e){const a=t[i.id],l=n.get(i.source),d=n.get(i.target);if(!a||!l||!d||a.manualWaypoints.length>0||a.autoWaypoints.length<2)continue;const u=a.autoWaypoints,c=dt(Ge(l,a.sourceHandle),a.sourceHandle,a.sourcePortOffset),f=dt(Ge(d,a.targetHandle),a.targetHandle,a.targetPortOffset),p=a.sourceHandle==="left"||a.sourceHandle==="right",h=a.targetHandle==="left"||a.targetHandle==="right";for(let x=0;x<u.length-1;x++){const m=u[x],g=u[x+1],y=Math.abs(m.y-g.y)<=2&&Math.abs(m.x-g.x)>8,b=Math.abs(m.x-g.x)<=2&&Math.abs(m.y-g.y)>8;!y&&!b||x===0&&(y&&p&&Math.abs(m.y-c.y)<=2||b&&!p&&Math.abs(m.x-c.x)<=2)||x+1===u.length-1&&(y&&h&&Math.abs(g.y-f.y)<=2||b&&!h&&Math.abs(g.x-f.x)<=2)||s.push({edgeId:i.id,wpIndex:x,horiz:y,coord:y?(m.y+g.y)/2:(m.x+g.x)/2,spanMin:y?Math.min(m.x,g.x):Math.min(m.y,g.y),spanMax:y?Math.max(m.x,g.x):Math.max(m.y,g.y)})}}const r=new Set;for(let i=0;i<s.length;i++){if(r.has(i))continue;const a=s[i],l=[i];for(let d=i+1;d<s.length;d++){if(r.has(d))continue;const u=s[d];if(u.horiz!==a.horiz||u.edgeId===a.edgeId)continue;const c=a.horiz?{x:a.spanMin,y:a.coord}:{x:a.coord,y:a.spanMin},f=a.horiz?{x:a.spanMax,y:a.coord}:{x:a.coord,y:a.spanMax},p=u.horiz?{x:u.spanMin,y:u.coord}:{x:u.coord,y:u.spanMin},h=u.horiz?{x:u.spanMax,y:u.coord}:{x:u.coord,y:u.spanMax};fm(c,f,p,h)&&l.push(d)}if(!(l.length<=1)){l.sort((d,u)=>s[d].spanMin-s[u].spanMin);for(let d=0;d<l.length;d++){const u=s[l[d]];r.add(l[d]);const c=Math.round((d-(l.length-1)/2)*12);if(c===0)continue;const f=t[u.edgeId],p=f==null?void 0:f.autoWaypoints,h=e.find(N=>N.id===u.edgeId),x=h?n.get(h.source):void 0,m=h?n.get(h.target):void 0;if(!f||!p||!h||!x||!m)continue;const g=p[u.wpIndex],y=p[u.wpIndex+1];if(!g||!y)continue;const b=dt(Ge(x,f.sourceHandle),f.sourceHandle,f.sourcePortOffset),$=dt(Ge(m,f.targetHandle),f.targetHandle,f.targetPortOffset),k=u.wpIndex>0?p[u.wpIndex-1]:b,_=u.wpIndex+2<p.length?p[u.wpIndex+2]:$,O=[];for(const[N,P]of n.entries())N!==h.source&&N!==h.target&&O.push(P);const F=[c,Math.round(c/2)].filter((N,P,M)=>N!==0&&M.indexOf(N)===P);for(const N of F){const P=u.horiz?{x:g.x,y:g.y+N}:{x:g.x+N,y:g.y},M=u.horiz?{x:y.x,y:y.y+N}:{x:y.x+N,y:y.y};if(nn([k,P,M,_],O,6).length===0){p[u.wpIndex]=P,p[u.wpIndex+1]=M;break}}}}}}function pm(e,t,n,s,r){if(r.length===0)return r;const i=r.map(f=>({x:Math.round(f.x),y:Math.round(f.y)})),a=t==="left"||t==="right",l=s==="left"||s==="right",d=i[0];if(a&&Math.abs(d.y-e.y)>1)if(i.length>=2&&Math.abs(i[1].x-d.x)<=2)i[0]={x:d.x,y:Math.round(e.y)};else{const f=jt(t),p=Math.round(e.x+f.x*16);i.unshift({x:p,y:Math.round(e.y)},{x:p,y:d.y})}else if(!a&&Math.abs(d.x-e.x)>1)if(i.length>=2&&Math.abs(i[1].y-d.y)<=2)i[0]={x:Math.round(e.x),y:d.y};else{const f=jt(t),p=Math.round(e.y+f.y*16);i.unshift({x:Math.round(e.x),y:p},{x:d.x,y:p})}const u=i.length-1,c=i[u];if(l&&Math.abs(c.y-n.y)>1)if(i.length>=2&&Math.abs(i[u-1].x-c.x)<=2)i[u]={x:c.x,y:Math.round(n.y)};else{const f=jt(s),p=Math.round(n.x+f.x*16);i.push({x:p,y:c.y},{x:p,y:Math.round(n.y)})}else if(!l&&Math.abs(c.x-n.x)>1)if(i.length>=2&&Math.abs(i[u-1].y-c.y)<=2)i[u]={x:Math.round(n.x),y:c.y};else{const f=jt(s),p=Math.round(n.y+f.y*16);i.push({x:c.x,y:p},{x:Math.round(n.x),y:p})}return aa(e,i,n)}function pr(e,t,n={},s,r){const i=ia(e,t,s),a=new Map;for(const x of e.edges){const m=x.source<x.target?`${x.source}::${x.target}`:`${x.target}::${x.source}`,g=a.get(m)??[];g.push(x.id),a.set(m,g)}const l=dm(i,[]),d=[],u=new Set,c={};let f=0,p=0;for(const x of e.edges){const m=i.get(x.source),g=i.get(x.target),y=n[x.id];if(!m||!g){c[x.id]={sourceHandle:(y==null?void 0:y.source_handle)??"right",targetHandle:(y==null?void 0:y.target_handle)??"left",sourcePortOffset:0,targetPortOffset:0,manualWaypoints:(y==null?void 0:y.waypoints)??[],autoWaypoints:[],curveOffset:{x:0,y:0}};continue}const b=y!=null&&y.waypoints?[...y.waypoints]:[];if(x.source===x.target){const X=b.length>0?[]:[{x:m.x+m.width+44,y:m.cy},{x:m.x+m.width+44,y:m.y-36},{x:m.cx,y:m.y-36}];c[x.id]={sourceHandle:(y==null?void 0:y.source_handle)??"right",targetHandle:(y==null?void 0:y.target_handle)??"top",sourcePortOffset:0,targetPortOffset:0,manualWaypoints:b,autoWaypoints:X,curveOffset:{x:0,y:0}};continue}const $=g.cx-m.cx,k=g.cy-m.cy,_=im($,k,e.direction),O=x.source<x.target?`${x.source}::${x.target}`:`${x.target}::${x.source}`,F=a.get(O)??[x.id],N=[];for(const[X,W]of i.entries())X!==x.source&&X!==x.target&&N.push(W);let P={x:0,y:0};if(F.length>1&&b.length===0){const X=_n(m,(y==null?void 0:y.source_handle)??_.sourceHandle,g,(y==null?void 0:y.target_handle)??_.targetHandle);if(nn(X,N,12).length===0){const se=F.indexOf(x.id)-(F.length-1)/2,le=x.source<x.target?x.source:x.target,me=x.source<x.target?x.target:x.source,ae=i.get(le),fe=i.get(me),ee=fe.cx-ae.cx,ie=fe.cy-ae.cy,V=Math.hypot(ee,ie)||1,ue=-ie/V,we=ee/V,je=se*92;P={x:Math.round(ue*je),y:Math.round(we*je)}}}let M=[],A=_.sourceHandle,q=_.targetHandle,ne=0,Q=0;const w=r==null?void 0:r[x.id];let Z=!1;if(b.length===0&&!(y!=null&&y.source_handle)&&!(y!=null&&y.target_handle)&&P.x===0&&P.y===0&&w&&Math.abs(w.sourcePos.x-m.x)<=1&&Math.abs(w.sourcePos.y-m.y)<=1&&Math.abs(w.targetPos.x-g.x)<=1&&Math.abs(w.targetPos.y-g.y)<=1){const X=[w.startPoint,...w.waypoints,w.endPoint];if(nn(X,N,10).length===0){const W=w.sourceSide??_.sourceHandle,se=w.targetSide??_.targetHandle,le=W==="left"||W==="right",me=se==="left"||se==="right",ae=Math.max(12,(le?m.height:m.width)/2-20),fe=Math.max(12,(me?g.height:g.width)/2-20);ne=Math.round(Math.max(-ae,Math.min(ae,le?w.startPoint.y-m.cy:w.startPoint.x-m.cx))),Q=Math.round(Math.max(-fe,Math.min(fe,me?w.endPoint.y-g.cy:w.endPoint.x-g.cx))),A=W,q=se,M=[...w.waypoints],Z=!0,u.add(`${x.id}:source`),u.add(`${x.id}:target`)}}if(!Z&&b.length===0&&!(y!=null&&y.source_handle)&&!(y!=null&&y.target_handle)&&P.x===0&&P.y===0){const X=_n(m,_.sourceHandle,g,_.targetHandle),W=nn(X,N,12);if(W.length>0){const se=[[_.sourceHandle,k>=0?"top":"bottom"],[k>=0?"bottom":"top",_.targetHandle],["bottom","top"],["top","bottom"],["right","left"],["left","right"],["bottom","bottom"],["top","top"]];let le=!1;if(F.length===1)for(const[me,ae]of se){const fe=_n(m,me,g,ae);if(nn(fe,N,12).length===0){A=me,q=ae,le=!0;break}}if(!le){const me=[[_.sourceHandle,_.targetHandle]];e.direction==="LR"&&$<0?me.push(["bottom","bottom"],["top","top"]):e.direction==="TB"&&k<0&&me.push(["right","right"],["left","left"]);let ae=null;for(const[fe,ee]of me){const ie=um(m,fe,g,ee,N,l,d);ie&&(!ae||ie.score<ae.score*.92)&&(ae=ie)}if(ae)A=ae.sourceHandle,q=ae.targetHandle,M=ae.waypoints;else if(Math.abs($)>=Math.abs(k)){const ee=Math.max(m.y+m.height,g.y+g.height,...W.map(V=>V.y+V.height)),ie=Math.round(ee+48+f*32);f+=1,A="bottom",q="bottom",M=[{x:Math.round(m.cx),y:ie},{x:Math.round(g.cx),y:ie}]}else{const ee=Math.max(m.x+m.width,g.x+g.width,...W.map(V=>V.x+V.width)),ie=Math.round(ee+64+p*36);p+=1,A="right",q="right",M=[{x:ie,y:Math.round(m.cy)},{x:ie,y:Math.round(g.cy)}]}}}}const D=(y==null?void 0:y.source_handle)??A,J=(y==null?void 0:y.target_handle)??q;if(c[x.id]={sourceHandle:D,targetHandle:J,sourcePortOffset:ne,targetPortOffset:Q,manualWaypoints:b,autoWaypoints:M,curveOffset:P},b.length>0)To(Ge(m,D),b,Ge(g,J),d);else if(M.length>0)To(dt(Ge(m,D),D,ne),M,dt(Ge(g,J),J,Q),d);else{const X=_n(m,D,g,J);for(let W=0;W<X.length-1;W++)d.push({a:X[W],b:X[W+1]})}}const h=new Map;for(const x of e.edges){const m=c[x.id],g=i.get(x.source),y=i.get(x.target);if(!m||!g||!y)continue;const b=m.sourceHandle==="left"||m.sourceHandle==="right",$=`${x.source}:${m.sourceHandle}`,k=h.get($)??[];k.push({edgeId:x.id,end:"source",sortCoord:u.has(`${x.id}:source`)?m.sourcePortOffset:b?y.cy:y.cx,sideLength:b?g.height:g.width,currentOffset:m.sourcePortOffset}),h.set($,k);const _=m.targetHandle==="left"||m.targetHandle==="right",O=`${x.target}:${m.targetHandle}`,F=h.get(O)??[];F.push({edgeId:x.id,end:"target",sortCoord:u.has(`${x.id}:target`)?m.targetPortOffset:_?g.cy:g.cx,sideLength:_?y.height:y.width,currentOffset:m.targetPortOffset}),h.set(O,F)}for(const x of h.values()){if(x.length<=1)continue;if(x.every($=>u.has(`${$.edgeId}:${$.end}`))){const $=x.map(_=>_.currentOffset).sort((_,O)=>_-O);let k=!0;for(let _=1;_<$.length;_++)if(Math.abs($[_]-$[_-1])<10){k=!1;break}if(k)continue}x.sort(($,k)=>$.sortCoord-k.sortCoord);const g=x[0].sideLength,y=Math.min(28,Math.max(14,(g-44)/x.length)),b=Math.max(16,g/2-24);x.forEach(($,k)=>{const _=(k-(x.length-1)/2)*y,O=Math.round(Math.max(-b,Math.min(b,_))),F=c[$.edgeId];F&&($.end==="source"?F.sourcePortOffset=O:F.targetPortOffset=O)})}hm(e.edges,c,i);for(const x of e.edges){const m=c[x.id],g=i.get(x.source),y=i.get(x.target);if(!m||!g||!y||m.manualWaypoints.length>0||m.autoWaypoints.length===0)continue;const b=dt(Ge(g,m.sourceHandle),m.sourceHandle,m.sourcePortOffset),$=dt(Ge(y,m.targetHandle),m.targetHandle,m.targetPortOffset);m.autoWaypoints=pm(b,m.sourceHandle,$,m.targetHandle,m.autoWaypoints)}return c}function mm(e,t,n,s,r,i){var _,O,F;const l=pr(e,t,n,i)[s],d={x:Math.round(r.x),y:Math.round(r.y)};if(!l)return{waypoints:[...((_=n[s])==null?void 0:_.waypoints)??[],d],handles:{source_handle:((O=n[s])==null?void 0:O.source_handle)??"right",target_handle:((F=n[s])==null?void 0:F.target_handle)??"left"}};const u={source_handle:l.sourceHandle,target_handle:l.targetHandle},c=l.manualWaypoints;if(c.length===0)return{waypoints:[d],handles:u};const f=e.edges.find(N=>N.id===s),p=ia(e,t,i),h=f?p.get(f.source):void 0,x=f?p.get(f.target):void 0;if(!h||!x)return{waypoints:[...c,d],handles:u};const m=dt(Ge(h,l.sourceHandle),l.sourceHandle,l.sourcePortOffset),g=dt(Ge(x,l.targetHandle),l.targetHandle,l.targetPortOffset),y=[m,...c,g];let b=c.length,$=1/0;for(let N=0;N<y.length-1;N++){const P=om(d,y[N],y[N+1]);P<$&&($=P,b=N)}const k=[...c];return k.splice(b,0,d),{waypoints:k,handles:u}}function xm({activeView:e,filter:t,viewDiff:n,viewBaseline:s,editedNodeIds:r,editedEdgeIds:i,positionsRef:a,edgeRoutesRef:l,undoMapRef:d,redoMapRef:u,historyTick:c,rfNodes:f,selectedNodeId:p,selectedEdgeId:h,setSelectedNodeId:x,setSelectedEdgeId:m,setDrawerMode:g,setElementTab:y,setLayoutVersion:b,screenToFlowPosition:$,selectSingleNode:k,selectSingleEdge:_,createBoxAtPosition:O,handleChangeNodeShape:F,handleAutoLayout:N,handleToggleDirection:P,handleUndo:M,handleRedo:A,handleRevertNode:q,handleRevertEdge:ne,handleRevertViewToBaseline:Q,handleUnlockAllInView:w,handleUpdateNodeStatus:Z,handleToggleLock:D,handleInlineAddItem:J,handleInlineAddField:X,handleOpenNodeThreads:W,handleCommitWaypoints:se,handleUpdateEdgeRoute:le,handleFlipEdge:me,persistCurrentLayout:ae,persistView:fe,showToast:ee}){const[ie,V]=v.useState(null),ue=v.useRef(null),we=v.useCallback(()=>{V(null)},[]),je=v.useCallback(G=>{const T=ue.current;return ue.current=null,T?Math.hypot(G.clientX-T.x,G.clientY-T.y)>6:!1},[]);v.useEffect(()=>{const G=T=>{T.button===2?ue.current={x:T.clientX,y:T.clientY}:ue.current=null};return window.addEventListener("mousedown",G,!0),()=>{window.removeEventListener("mousedown",G,!0)}},[]);const xe=v.useCallback(G=>{if(G.preventDefault(),je(G)){V(null);return}V({kind:"pane",x:G.clientX,y:G.clientY,flowPos:$({x:G.clientX,y:G.clientY})})},[$,je]),re=v.useCallback((G,T)=>{if(G.preventDefault(),je(G)){V(null);return}k(T.id),V({kind:"node",x:G.clientX,y:G.clientY,nodeId:T.id})},[k,je]),Se=v.useCallback((G,T)=>{if(G.preventDefault(),je(G)){V(null);return}_(T.id),V({kind:"edge",x:G.clientX,y:G.clientY,edgeId:T.id,flowPos:$({x:G.clientX,y:G.clientY})})},[$,_,je]),te=v.useMemo(()=>{if(!ie||!e)return null;const G=e.diagram_type==="er",T=d.current.get(e.id)??[],E=u.current.get(e.id)??[];if(ie.kind==="pane"){const L=(n==null?void 0:n.nodes_removed)??[],be=e.nodes.some(ve=>ve.locked)||e.edges.some(ve=>ve.locked),_e=[];return L.length>0&&s&&_e.push({id:"restore_removed_nodes",label:G?"Restore Removed Entity…":"Restore Removed Box…",dividerBefore:!0,children:L.map(ve=>({id:`restore_removed_${ve.id}`,label:ve.title,onSelect:()=>void q(ve.id)}))}),n!=null&&n.has_changes&&s&&_e.push({id:"revert_view_baseline",label:"Revert All Unsynced Edits",danger:!0,dividerBefore:_e.length===0,onSelect:()=>void Q()}),t==="locked"&&be&&_e.push({id:"unlock_all_view",label:"Unlock All in View",dividerBefore:_e.length===0,onSelect:()=>void w()}),{header:e.title,items:[{id:"add_box",label:G?"Add Entity Here":"Add Box Here",shortcut:"N",onSelect:()=>void O(ie.flowPos)},...G?[]:[{id:"add_shape",label:"Add Shape…",children:Zn.map(ve=>({id:`add_shape_${ve.shape}`,label:ve.label,onSelect:()=>void O(ie.flowPos,ve.shape)}))}],{id:"auto_layout",label:"Auto-Layout & Reset Routes",shortcut:"R",dividerBefore:!0,onSelect:()=>void N()},{id:"toggle_dir",label:`Switch Direction (${e.direction==="TB"?"LR":"TB"})`,onSelect:()=>void P()},{id:"undo",label:"Undo",shortcut:"Ctrl+Z",dividerBefore:!0,disabled:T.length===0,onSelect:()=>void M()},{id:"redo",label:"Redo",shortcut:"Ctrl+Shift+Z",disabled:E.length===0,onSelect:()=>void A()},..._e]}}if(ie.kind==="node"){const L=e.nodes.find(he=>he.id===ie.nodeId);if(!L)return null;const be=he=>({id:`add_entry_${he.id}`,label:he.heading,disabled:L.locked,onSelect:()=>J(L.id,he.id,"new_item")}),_e=G?[{id:"add_entry",label:"Add Attribute",disabled:L.locked,onSelect:()=>{var ce;const he=`col_${(((ce=L.fields)==null?void 0:ce.length)??0)+1}`;X(L.id,he)}}]:L.sections.length===0?[{id:"add_entry",label:"Add Entry to Details",disabled:L.locked,onSelect:()=>{fe({...e,nodes:e.nodes.map(he=>he.id===L.id?{...he,sections:[{id:`sec_${Date.now().toString(36)}`,heading:"Details",items:["new_item"]}]}:he)})}}]:L.sections.length===1?[{id:"add_entry",label:`Add Entry to ${L.sections[0].heading}`,disabled:L.locked,onSelect:()=>J(L.id,L.sections[0].id,"new_item")}]:[{id:"add_entry",label:"Add Entry to…",disabled:L.locked,children:L.sections.map(be)}],ve=r.has(L.id),Oe=!!(n!=null&&n.nodes_added.some(he=>he.id===L.id)),ye=!!(s!=null&&s.nodes.some(he=>he.id===L.id)),$e=ve&&(Oe||ye)?{id:"revert_to_unmodified",label:Oe?G?"Discard Added Entity":"Discard Added Box":G?"Revert Entity to Unmodified":"Revert Box to Unmodified",danger:Oe,onSelect:()=>void q(L.id)}:null,Ne=[];t==="my_edits"&&$e?Ne.push($e):t==="waiting_on_me"?Ne.push({id:"answer_open_question",label:"Answer Open Question",onSelect:()=>W(L.id)}):(t==="drifted"||L.status==="drifted")&&Ne.push({id:"mark_implemented",label:"Mark as Implemented",disabled:L.status==="implemented",onSelect:()=>void Z(L.id,"implemented")},{id:"mark_approved",label:"Mark as Approved",disabled:L.status==="approved",onSelect:()=>void Z(L.id,"approved")});const H=[...Ne.map((he,ce)=>he),...Ne.length>0&&_e.length>0?_e.map((he,ce)=>ce===0?{...he,dividerBefore:!0}:he):_e,...G?[]:[{id:"add_section",label:"Add Section",disabled:L.locked,onSelect:()=>{fe({...e,nodes:e.nodes.map(he=>he.id===L.id?{...he,sections:[...he.sections,{id:`sec_${Date.now().toString(36)}`,heading:"New Section",items:["new_item"]}]}:he)})}}],{id:"duplicate",label:G?"Duplicate Entity":"Duplicate Box",onSelect:()=>{const he=`${L.id}_copy_${Date.now().toString(36).slice(-3)}`,ce=a.current[L.id]??{x:80,y:80};a.current[he]={x:ce.x+36,y:ce.y+36};const Je={...structuredClone(L),id:he,title:`${L.title} Copy`,locked:!1,status:"draft"};delete Je.entity_ref,delete Je.code_refs,ae(e.id),fe({...e,nodes:[...e.nodes,Je]}),b(De=>De+1)}},{id:"lock",label:L.locked?"Unlock":"Lock",dividerBefore:!0,onSelect:()=>D(L.id)},...G?[]:[{id:"change_shape",label:"Change Shape…",disabled:L.locked,children:Zn.map(he=>{const ce=(L.shape??"card")===he.shape;return{id:`change_shape_${he.shape}`,label:he.label,disabled:L.locked||ce,onSelect:()=>void F(L.id,he.shape)}})}],{id:"spec",label:"Edit in Spec Drawer",onSelect:()=>{k(L.id),g("node"),y("spec")}},{id:"threads",label:"Open Threads",onSelect:()=>W(L.id)},...t!=="my_edits"&&$e?[{...$e,dividerBefore:!0}]:[],{id:"delete",label:G?"Delete Entity":"Delete Box",danger:!0,dividerBefore:!0,disabled:L.locked,onSelect:()=>{if(e.edges.find(ce=>(ce.source===L.id||ce.target===L.id)&&ce.locked)){ee("Unlock incident edge first.","warning");return}p===L.id&&(x(null),g("none")),fe({...e,nodes:e.nodes.filter(ce=>ce.id!==L.id),edges:e.edges.filter(ce=>ce.source!==L.id&&ce.target!==L.id)})}}];return{header:L.title,items:H}}const z=e.edges.find(L=>L.id===ie.edgeId);if(!z)return null;const R=i.has(z.id),C=!!(n!=null&&n.edges_added.some(L=>L.id===z.id)),B=R&&(C||!!(s!=null&&s.edges.some(L=>L.id===z.id)))?{id:"revert_edge_to_unmodified",label:C?"Discard Added Edge":"Revert Edge to Unmodified",danger:C,onSelect:()=>void ne(z.id)}:null,oe=[...t==="my_edits"&&B?[B]:[],{id:"add_bend",label:"Add Bend Point Here",dividerBefore:t==="my_edits"&&!!B,onSelect:()=>{var _e,ve;const L={};for(const Oe of f){const ye=((_e=Oe.measured)==null?void 0:_e.width)??Oe.width,K=((ve=Oe.measured)==null?void 0:ve.height)??Oe.height;(ye!==void 0||K!==void 0)&&(L[Oe.id]={width:ye,height:K})}const be=mm(e,a.current,l.current,z.id,ie.flowPos,L);se(z.id,be.waypoints,be.handles)}},{id:"reset_route",label:"Reset Line Route",onSelect:()=>le(z.id,null)},{id:"flip",label:"Flip Direction (A ↔ B)",dividerBefore:!0,disabled:!!z.locked,onSelect:()=>{me(z.id)}},...G?[]:[{id:"toggle_dash",label:z.style==="dashed"?"Make Solid Line":"Make Dashed Line",disabled:!!z.locked,onSelect:()=>{fe({...e,edges:e.edges.map(L=>L.id===z.id?{...L,style:L.style==="dashed"?"solid":"dashed"}:L)})}}],{id:"lock_edge",label:z.locked?"Unlock Edge":"Lock Edge",dividerBefore:!0,onSelect:()=>{fe({...e,edges:e.edges.map(L=>L.id===z.id?{...L,locked:!L.locked}:L)})}},...t!=="my_edits"&&B?[{...B,dividerBefore:!0}]:[],{id:"delete_edge",label:"Delete Edge",danger:!0,dividerBefore:!0,disabled:!!z.locked,onSelect:()=>{h===z.id&&(m(null),g("none")),fe({...e,edges:e.edges.filter(L=>L.id!==z.id)})}}];return{header:`${z.source} → ${z.target}`,items:oe}},[e,ie,O,l,i,r,t,N,F,se,me,X,J,W,A,ne,q,Q,P,D,M,w,le,Z,c,ae,fe,a,u,f,k,h,p,g,y,b,m,x,ee,d,s,n]);return{contextMenu:ie,contextMenuData:te,clearContextMenu:we,handlePaneContextMenu:xe,handleNodeContextMenu:re,handleEdgeContextMenu:Se}}function Ls(){const e=document.activeElement;return e?e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable:!1}function Po(e){return e==="ArrowUp"||e==="ArrowDown"||e==="ArrowLeft"||e==="ArrowRight"}function Ao(e){return e.code==="Space"||e.key===" "}function gm({activeViewIdRef:e,tabs:t,searchOpen:n,pendingConn:s,setSearchOpen:r,openSearch:i,clearContextMenu:a,handleSelectView:l,handleUndo:d,handleRedo:u,handleAutoLayout:c,handleAddBoxAtCursor:f,startArrowPan:p,stopArrowPan:h,updateArrowShift:x,stopAllArrowPan:m,handleZoomIn:g,handleZoomOut:y,handleFitView:b,handleResetZoom:$}){const k=v.useRef(!1),_=v.useRef(!1);v.useEffect(()=>{(n||s)&&(m(),k.current=!1,_.current=!1)},[s,n,m]),v.useEffect(()=>{const O=()=>{k.current&&(_.current=!0)},F=M=>{var Q;const A=M.ctrlKey||M.metaKey,q=!!document.querySelector('[role="dialog"]');if(A&&!M.altKey&&M.key.toLowerCase()==="k"){if(!n&&q)return;M.preventDefault(),a(),m(),r(w=>!w);return}if(n||Ls())return;if(!A&&!M.altKey&&M.key==="/"&&!s&&!q){M.preventDefault(),i();return}if(!A&&!M.altKey&&M.key==="Tab"&&!s&&!q&&t.length>1){M.preventDefault();const w=t.findIndex(W=>W.view_id===e.current),Z=M.shiftKey?-1:1,J=((w===-1?0:w)+Z+t.length)%t.length,X=t[J];X&&l(X.view_id);return}if(!s&&!q&&!M.altKey){if(!A&&!M.shiftKey&&Ao(M)){M.preventDefault(),M.repeat||(k.current=!0,_.current=!1);return}if(!A&&!M.shiftKey&&M.key>="1"&&M.key<="9"){const w=t[Number(M.key)-1];w&&(M.preventDefault(),a(),l(w.view_id));return}if(!A&&!M.shiftKey&&!M.repeat&&M.key.toLowerCase()==="r"){M.preventDefault(),a(),c();return}if(!A&&!M.shiftKey&&!M.repeat&&M.key.toLowerCase()==="n"){M.preventDefault(),a(),f();return}if(M.key==="+"||M.key==="="){M.preventDefault(),g();return}if(M.key==="-"||M.key==="_"){M.preventDefault(),y();return}if(!A&&M.shiftKey&&(M.key===")"||M.code==="Digit0")||A&&!M.shiftKey&&(M.key==="0"||M.code==="Digit0")){M.preventDefault(),$();return}if(!A&&!M.shiftKey&&M.key==="0"||!A&&M.shiftKey&&(M.key==="!"||M.code==="Digit1")){M.preventDefault(),b();return}}if(M.key==="Shift"&&x(!0),!A&&!M.altKey&&!s&&!q&&Po(M.key)&&!((Q=document.activeElement)!=null&&Q.closest(".react-flow__node"))){M.preventDefault(),M.repeat?x(M.shiftKey):p(M.key,M.shiftKey);return}if(!A||M.altKey)return;const ne=M.key.toLowerCase();ne==="z"&&!M.shiftKey?(M.preventDefault(),d()):(ne==="z"&&M.shiftKey||ne==="y")&&(M.preventDefault(),u())},N=M=>{if(Ao(M)&&k.current){M.preventDefault();const A=_.current;k.current=!1,_.current=!1,!A&&!n&&!Ls()&&!s&&!document.querySelector('[role="dialog"]')&&b();return}Po(M.key)?h(M.key):M.key==="Shift"&&x(!1)},P=()=>{k.current=!1,_.current=!1,m()};return window.addEventListener("pointerdown",O,!0),window.addEventListener("keydown",F),window.addEventListener("keyup",N),window.addEventListener("blur",P),()=>{window.removeEventListener("pointerdown",O,!0),window.removeEventListener("keydown",F),window.removeEventListener("keyup",N),window.removeEventListener("blur",P)}},[e,a,f,c,b,u,$,l,d,g,y,i,s,n,r,p,m,h,t,x])}function ym({activeView:e,activeViewIdRef:t,activeViewRef:n,positionsRef:s,edgeRoutesRef:r,measuredSizesRef:i,viewportReadyRef:a,pendingSelectNodeIdRef:l,selectedNodeId:d,selectedEdgeId:u,setSelectedNodeId:c,setSelectedEdgeId:f,setDrawerMode:p,setElementTab:h,pendingConn:x,setPendingConn:m,setLayoutVersion:g,setRoutingTick:y,onNodesChange:b,screenToFlowPosition:$,pushHistoryEntry:k,persistCurrentLayout:_,persistView:O,loadViewDetail:F,selectSingleNode:N,showToast:P}){const M=v.useRef(null),A=v.useCallback(E=>{const z=n.current;z&&O({...z,nodes:z.nodes.map(R=>R.id===E?{...R,locked:!R.locked}:R)})},[n,O]),q=v.useCallback((E,z)=>{const R=n.current;R&&O({...R,nodes:R.nodes.map(C=>C.id===E?{...C,title:z}:C)})},[n,O]),ne=v.useCallback((E,z,R,C)=>{const S=n.current;S&&O({...S,nodes:S.nodes.map(B=>B.id!==E?B:{...B,sections:B.sections.map(oe=>{if(oe.id!==z)return oe;const L=[...oe.items];return C.trim()?L[R]=C:L.splice(R,1),{...oe,items:L}})})})},[n,O]),Q=v.useCallback((E,z,R)=>{const C=n.current;C&&O({...C,nodes:C.nodes.map(S=>S.id!==E?S:{...S,sections:S.sections.map(B=>B.id===z?{...B,items:[...B.items,R]}:B)})})},[n,O]),w=v.useCallback((E,z)=>{const R=n.current;R&&O({...R,nodes:R.nodes.map(C=>C.id!==E?C:{...C,fields:(C.fields??[]).map(S=>S.id===z?{...S,nullable:!S.nullable}:S)})})},[n,O]),Z=v.useCallback((E,z,R)=>{var L;const C=n.current;if(!C)return;const S=R.trim(),B=C.nodes.find(be=>be.id===E),oe=(L=B==null?void 0:B.fields)==null?void 0:L.find(be=>be.id===z);oe&&S!==oe.name&&O({...C,nodes:C.nodes.map(be=>{if(be.id!==E)return be;const _e=be.fields??[];return{...be,fields:S?_e.map(ve=>ve.id===z?{...ve,name:S}:ve):_e.filter(ve=>ve.id!==z)}})})},[n,O]),D=v.useCallback((E,z)=>{const R=n.current;if(!R)return;const C={id:`fld_${Date.now().toString(36).slice(-5)}`,name:z,type:"varchar",nullable:!1};O({...R,nodes:R.nodes.map(S=>S.id===E?{...S,fields:[...S.fields??[],C]}:S)})},[n,O]),J=v.useCallback(E=>{N(E),p("node"),h("threads")},[N,p,h]),X=v.useCallback((E,z,R)=>{const C=t.current;if(!C)return;k(C);const S=r.current[E]??{};if(z.length===0){const B={...S};if(delete B.waypoints,Object.keys(B).length===0){const oe={...r.current};delete oe[E],r.current=oe}else r.current={...r.current,[E]:B}}else r.current={...r.current,[E]:{...S,...R&&!S.source_handle?{source_handle:R.source_handle}:{},...R&&!S.target_handle?{target_handle:R.target_handle}:{},waypoints:z}};y(B=>B+1),_(C)},[t,r,_,k,y]),W=v.useCallback((E,z)=>{const R=t.current;if(R){if(k(R),z===null){const C={...r.current};delete C[E],r.current=C}else{const S={...r.current[E]??{},...z};if(S.source_handle||delete S.source_handle,S.target_handle||delete S.target_handle,(!S.waypoints||S.waypoints.length===0)&&delete S.waypoints,Object.keys(S).length===0){const B={...r.current};delete B[E],r.current=B}else r.current={...r.current,[E]:S}}y(C=>C+1),_(R)}},[t,r,_,k,y]),se=v.useCallback(async(E,z)=>{const R=n.current;if(!R||R.diagram_type==="er")return;const C=R.nodes.find(S=>S.id===E);if(C){if(C.locked){P("Locked node cannot change shape","warning");return}(C.shape??"card")!==z&&await O({...R,nodes:R.nodes.map(S=>{if(S.id!==E)return S;if(z==="card"){const B={...S};return delete B.shape,B}return{...S,shape:z}})})}},[n,O,P]),le=v.useCallback(async(E,z="card")=>{if(!e)return;const R=Date.now().toString(36).slice(-4),C=e.diagram_type==="er",S=C?`entity_${R}`:`box_${R}`,B=E?{x:Math.round(E.x-140),y:Math.round(E.y-40)}:(()=>{const be=$({x:window.innerWidth*.42,y:window.innerHeight*.48});return{x:Math.round(be.x-140),y:Math.round(be.y-60)}})();s.current={...s.current,[S]:B};const oe=C?{id:S,kind:"Entity",title:"NewEntity",status:"draft",locked:!1,sections:[],fields:[{id:"id",name:"id",type:"uuid",pk:!0,nullable:!1}]}:z==="decision"?{id:S,kind:"Decision",shape:"decision",title:"Decision?",status:"draft",locked:!1,sections:[]}:z==="terminal"?{id:S,kind:"Terminal",shape:"terminal",title:"Start / End",status:"draft",locked:!1,sections:[]}:z==="store"?{id:S,kind:"Store",shape:"store",title:"Data Store",status:"draft",locked:!1,sections:[{id:"schema",heading:"Schema / Keys",items:["define data"]}]}:{id:S,kind:"Component",title:"New Component",status:"draft",locked:!1,sections:[{id:"responsibilities",heading:"Responsibilities",items:["describe behavior"]}]},L={...e,nodes:[...e.nodes,oe]};l.current=S,await _(e.id),await O(L),g(be=>be+1),N(S),p("node"),h("spec")},[e,l,_,O,s,$,N,p,h,g]),me=v.useCallback(async()=>{e&&(k(e.id),await Co(e.id),await F(e.id,{forceResetLayout:!0}),P("Auto-layout and smart edge routes reset"))},[e,F,k,P]),ae=v.useCallback(async()=>{if(!e)return;const E=e.direction==="TB"?"LR":"TB",z={...e,direction:E};await O(z),await Co(e.id),await F(e.id,{forceResetLayout:!0})},[e,F,O]),fe=v.useCallback(()=>{M.current={nodePositions:structuredClone(s.current),edgeRoutes:structuredClone(r.current)}},[r,s]),ee=v.useCallback(()=>{const E=M.current,z=n.current;if(!(!E||!z))for(const R of z.edges){const C=E.edgeRoutes[R.id],S=C==null?void 0:C.waypoints;if(!S||S.length===0)continue;const B=E.nodePositions[R.source],oe=s.current[R.source],L=E.nodePositions[R.target],be=s.current[R.target];if(!B||!oe||!L||!be)continue;const _e=oe.x-B.x,ve=oe.y-B.y,Oe=be.x-L.x,ye=be.y-L.y,K=Math.abs(_e)>0||Math.abs(ve)>0,$e=Math.abs(Oe)>0||Math.abs(ye)>0;if(!K&&!$e)continue;const Ne=S.length,H=S.map((he,ce)=>{if(K&&$e)return{x:Math.round(he.x+(_e+Oe)/2),y:Math.round(he.y+(ve+ye)/2)};const Je=K?(Ne-ce)/(Ne+1):(ce+1)/(Ne+1),De=K?_e:Oe,Fe=K?ve:ye;return{x:Math.round(he.x+De*Je),y:Math.round(he.y+Fe*Je)}});r.current={...r.current,[R.id]:{...r.current[R.id]??C,waypoints:H}}}},[n,r,s]),ie=v.useCallback(E=>{b(E);let z=!1,R=!1;for(const C of E)if(C.type==="position"&&C.position)s.current[C.id]={x:Math.round(C.position.x),y:Math.round(C.position.y)},z=!0;else if(C.type==="dimensions"&&C.dimensions&&C.dimensions.width>0&&C.dimensions.height>0&&i){const S=Math.round(C.dimensions.width),B=Math.round(C.dimensions.height),oe=i.current[C.id];(!oe||Math.abs((oe.width??0)-S)>=2||Math.abs((oe.height??0)-B)>=2)&&(i.current[C.id]={width:S,height:B},R=!0)}z&&ee(),(z||R)&&y(C=>C+1)},[ee,i,b,s,y]),V=v.useCallback(E=>{if(!e)return;const z={...s.current};for(const C of E)z[C.id]={x:Math.round(C.position.x),y:Math.round(C.position.y)};const R=M.current;R&&E.some(S=>{const B=R.nodePositions[S.id];return!B||Math.round(B.x)!==z[S.id].x||Math.round(B.y)!==z[S.id].y})&&k(e.id,{view:structuredClone(e),positions:structuredClone(R.nodePositions),edgeRoutes:structuredClone(R.edgeRoutes)}),s.current=z,ee(),M.current=null,y(C=>C+1),_(e.id)},[e,ee,_,s,k,y]),ue=v.useCallback((E,z,R)=>{V(R&&R.length>0?R:[z])},[V]),we=v.useCallback((E,z)=>{V(z)},[V]),je=v.useCallback((E,z)=>{!e||!a.current||fr(e.id,{positions:s.current,edge_routes:r.current,viewport:z})},[e,r,s,a]),xe=v.useCallback(async(E,z)=>{if(!e||!z.source||!z.target)return;const R=e.edges.find(S=>S.id===E.id);if(!R)return;if(R.locked){P("Unlock edge before reconnecting it.","warning");return}k(e.id);const C={...r.current[E.id]??{},...z.sourceHandle?{source_handle:z.sourceHandle}:{},...z.targetHandle?{target_handle:z.targetHandle}:{}};r.current={...r.current,[E.id]:C},y(S=>S+1),await _(e.id),(R.source!==z.source||R.target!==z.target)&&await O({...e,edges:e.edges.map(S=>S.id===E.id?{...S,source:z.source,target:z.target}:S)},{recordHistory:!1})},[e,r,_,O,k,y,P]),re=v.useCallback((E,z)=>{xe(E,z)},[xe]),Se=v.useCallback(async E=>{const z=n.current;if(!z)return;const R=z.edges.find(S=>S.id===E);if(!R)return;if(R.locked){P("Unlock edge before flipping direction.","warning");return}k(z.id);const C=r.current[E];if(C){const S={};C.target_handle&&(S.source_handle=C.target_handle),C.source_handle&&(S.target_handle=C.source_handle),C.waypoints&&C.waypoints.length>0&&(S.waypoints=[...C.waypoints].reverse()),Object.keys(S).length>0&&(r.current={...r.current,[E]:S},y(B=>B+1),await _(z.id))}await O({...z,edges:z.edges.map(S=>S.id===E?{...S,source:S.target,target:S.source}:S)},{recordHistory:!1})},[n,r,_,O,k,y,P]),te=v.useCallback(async({nodes:E,edges:z})=>{if(!e||Ls())return!1;const R=new Set(E.map(B=>B.id)),C=new Set(z.map(B=>B.id));for(const B of e.nodes)if(R.has(B.id)&&B.locked)return P(`Unlock "${B.title}" before deleting it.`,"warning"),!1;for(const B of e.edges){const oe=R.has(B.source)||R.has(B.target);if((C.has(B.id)||oe)&&B.locked)return P("Unlock locked edge before deleting.","warning"),!1}const S={...e,nodes:e.nodes.filter(B=>!R.has(B.id)),edges:e.edges.filter(B=>!C.has(B.id)&&!R.has(B.source)&&!R.has(B.target))};return d&&R.has(d)&&(c(null),p("none")),u&&C.has(u)&&(f(null),p("none")),await O(S),!0},[e,O,u,d,p,f,c,P]),G=v.useCallback(async E=>{if(!e||!(x!=null&&x.source)||!(x!=null&&x.target)){m(null);return}const z=`e_${Date.now().toString(36)}`,R={id:z,source:x.source,target:x.target,...E.label?{label:E.label}:{},...E.step!==void 0?{step:E.step}:{},style:E.style,...E.source_cardinality?{source_cardinality:E.source_cardinality}:{},...E.target_cardinality?{target_cardinality:E.target_cardinality}:{},...E.relation_kind?{relation_kind:E.relation_kind}:{}};(x.sourceHandle||x.targetHandle)&&(r.current={...r.current,[z]:{...x.sourceHandle?{source_handle:x.sourceHandle}:{},...x.targetHandle?{target_handle:x.targetHandle}:{}}},await _(e.id)),m(null),await O({...e,edges:[...e.edges,R]})},[e,r,x,_,O,m]),T=v.useCallback(E=>{E.source&&E.target&&m(E)},[m]);return{handleToggleLock:A,handleChangeNodeShape:se,handleInlineUpdateTitle:q,handleInlineUpdateItem:ne,handleInlineAddItem:Q,handleInlineToggleFieldNullable:w,handleInlineUpdateFieldName:Z,handleInlineAddField:D,handleOpenNodeThreads:J,handleCommitWaypoints:X,handleUpdateEdgeRoute:W,createBoxAtPosition:le,handleAutoLayout:me,handleToggleDirection:ae,snapshotDragOrigin:fe,handleNodesChange:ie,handleNodeDragStop:ue,handleSelectionDragStop:we,handleMoveEnd:je,handleReconnectCallback:re,handleFlipEdge:Se,handleBeforeDelete:te,handleConfirmEdge:G,handleConnect:T}}function Do(e,t){return e.length<=t?e:`${e.slice(0,Math.max(1,t-1))}…`}function Pt(e){const t=e.replace(/[^a-zA-Z0-9_]/g,"_");return/^[0-9]/.test(t)||!t?`n_${t}`:t}function bm(e){switch(e){case"0..1":return"|o";case"1..*":return"}|";case"0..*":return"}o";case"1":default:return"||"}}function vm(e){switch(e){case"0..1":return"o|";case"1..*":return"|{";case"0..*":return"o{";case"1":default:return"||"}}function At(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/#/g,"&#35;").replace(/\|/g,"&#124;")}const km=["drifted","needs_input","locked","approved","implemented","draft"],wm={dark:{drifted:"fill:#4c0519,stroke:#f43f5e,stroke-width:2px,color:#ffe4e6",needs_input:"fill:#451a03,stroke:#f59e0b,stroke-width:2px,color:#fef3c7",locked:"fill:#1e1b4b,stroke:#8b5cf6,stroke-width:2px,color:#f1f5f9",approved:"fill:#022c22,stroke:#10b981,stroke-width:1.5px,color:#d1fae5",implemented:"fill:#042f2e,stroke:#14b8a6,stroke-width:1.5px,color:#ccfbf1",draft:"fill:#0f172a,stroke:#475569,stroke-width:1.5px,color:#f1f5f9"},light:{drifted:"fill:#ffe4e6,stroke:#e11d48,stroke-width:2px,color:#881337",needs_input:"fill:#fef3c7,stroke:#d97706,stroke-width:2px,color:#78350f",locked:"fill:#f5f3ff,stroke:#7c3aed,stroke-width:2px,color:#1e293b",approved:"fill:#d1fae5,stroke:#059669,stroke-width:1.5px,color:#064e3b",implemented:"fill:#ccfbf1,stroke:#0d9488,stroke-width:1.5px,color:#134e4a",draft:"fill:#ffffff,stroke:#94a3b8,stroke-width:1.5px,color:#0f172a"}};function _m(e){return e.status==="drifted"?"drifted":e.status==="needs_input"?"needs_input":e.locked?"locked":e.status==="approved"?"approved":e.status==="implemented"?"implemented":"draft"}function jm(e,t,n){if(t.shape==="decision")return` ${e}{"${n}"}`;if(t.shape==="terminal")return` ${e}(["${n}"])`;if(t.shape==="store")return` ${e}[("${n}")]`;if(!t.shape&&t.sections.length===0){if(/(store|storage|db|database|cache|queue)/i.test(t.kind))return` ${e}[("${n}")]`;if(/(actor|user|client)/i.test(t.kind))return` ${e}(["${n}"])`}return` ${e}("${n}")`}function $m(e,t){var a,l,d;if(e.diagram_type==="er"){const u=["erDiagram"];for(const c of e.nodes){const f=Pt(c.id),p=c.title.replace(/"/g,"'");u.push(` ${f} ["${p}"] {`);for(const h of c.fields??[]){const x=(h.type??"string").replace(/[^a-zA-Z0-9_]/g,"_"),m=h.name.replace(/[^a-zA-Z0-9_]/g,"_"),g=[h.pk?"PK":"",h.fk?"FK":"",h.unique?"UK":""].filter(Boolean).join(","),y=[h.nullable?"nullable":"NOT NULL",h.note??""].filter(Boolean).join(" - ").replace(/"/g,"'");u.push(` ${x} ${m}${g?` ${g}`:""} "${y}"`)}u.push(" }")}for(const c of e.edges){const f=Pt(c.source),p=Pt(c.target),h=bm(c.source_cardinality),x=vm(c.target_cardinality),m=c.style==="dashed"?"..":"--",g=(((a=c.label)==null?void 0:a.trim())||(c.relation_kind==="subtype"?"is-a":"relates")).replace(/"/g,"'");u.push(` ${f} ${h}${m}${x} ${p} : "${g}"`)}return`${u.join(`
59
+ `)}
60
+ `}const n=(t==null?void 0:t.theme)==="light"?"light":"dark",s=["%%{init: {'flowchart': {'curve': 'basis', 'nodeSpacing': 48, 'rankSpacing': 64, 'padding': 14}}}%%",`flowchart ${e.direction==="LR"?"LR":"TB"}`,` %% ${e.title.replace(/[\r\n]+/g," ")}`],r=new Map;for(const u of e.nodes){const c=Pt(u.id),f=At(u.kind.toUpperCase()),p=u.status==="drifted"?" · DRIFTED":u.status==="needs_input"?" · NEEDS INPUT":u.locked?" · 🔒":"",h=[`<small>${f}${p}</small>`,`<b>${At(u.title)}</b>`];(l=u.summary)!=null&&l.trim()&&h.push(`<i>${At(Do(u.summary.trim(),64))}</i>`);const x=Xn(u,e.diagram_type);if(x==="card"||x==="store")for(const y of u.sections){if(y.items.length===0)continue;h.push("",`<b>${At(y.heading)}</b>`);const{visibleCount:b,hiddenCount:$}=mt(y.items.length,dn);for(const k of y.items.slice(0,b))h.push(`• ${At(Do(k,44))}`);$>0&&h.push(`<i>+${$} more</i>`)}s.push(jm(c,u,h.join("<br/>")));const m=_m(u),g=r.get(m)??[];g.push(c),r.set(m,g)}e.nodes.length>0&&e.edges.length>0&&s.push("");for(const u of e.edges){const c=Pt(u.source),f=Pt(u.target),p=u.style==="dashed"?"-.->":u.locked?"==>":"-->",h=[u.step!==void 0?String(u.step):"",((d=u.label)==null?void 0:d.trim())??""].filter(Boolean).join(" · "),x=At(h);s.push(x?` ${c} ${p}|"${x}"| ${f}`:` ${c} ${p} ${f}`)}const i=[];for(const u of km){const c=r.get(u);!c||c.length===0||(i.push(` classDef ${u} ${wm[n][u]}`),i.push(` class ${c.join(",")} ${u}`))}return e.edges.length>0&&i.push(" linkStyle default stroke:#64748b,stroke-width:1.5px"),i.length>0&&s.push("",...i),`${s.join(`
61
+ `)}
62
+ `}const Nm={canvasBg:"#020617",patternColor:"#334155",cardBg:"#0f172a",headerBg:"#0f172a",footerBg:"#091124",divider:"#1e293b",borderDefault:"#334155",borderLocked:"#8b5cf6",borderNeedsInput:"#f59e0b",borderDrifted:"#f43f5e",textPrimary:"#f1f5f9",textSecondary:"#cbd5e1",textMuted:"#94a3b8",badgeBg:"#1e293b",badgeBorder:"#334155",edgeDefault:"#64748b",edgeLocked:"#a78bfa",pillBg:"#0f172a",pillBorder:"#334155"},Sm={canvasBg:"#f1f5f9",patternColor:"#94a3b8",cardBg:"#ffffff",headerBg:"#f8fafc",footerBg:"#f8fafc",divider:"#e2e8f0",borderDefault:"#cbd5e1",borderLocked:"#7c3aed",borderNeedsInput:"#d97706",borderDrifted:"#e11d48",textPrimary:"#0f172a",textSecondary:"#334155",textMuted:"#64748b",badgeBg:"#f1f5f9",badgeBorder:"#cbd5e1",edgeDefault:"#64748b",edgeLocked:"#7c3aed",pillBg:"#ffffff",pillBorder:"#cbd5e1"},mr={draft:{label:"draft",darkText:"#cbd5e1",darkBg:"#1e293b",darkBorder:"#334155",lightText:"#334155",lightBg:"#f1f5f9",lightBorder:"#cbd5e1"},needs_input:{label:"needs input",darkText:"#fcd34d",darkBg:"#451a03",darkBorder:"#b45309",lightText:"#b45309",lightBg:"#fef3c7",lightBorder:"#f59e0b"},approved:{label:"approved",darkText:"#6ee7b7",darkBg:"#022c22",darkBorder:"#059669",lightText:"#047857",lightBg:"#d1fae5",lightBorder:"#10b981"},implemented:{label:"implemented",darkText:"#5eead4",darkBg:"#042f2e",darkBorder:"#0d9488",lightText:"#0f766e",lightBg:"#ccfbf1",lightBorder:"#14b8a6"},drifted:{label:"drifted",darkText:"#fda4af",darkBg:"#4c0519",darkBorder:"#e11d48",lightText:"#be123c",lightBg:"#ffe4e6",lightBorder:"#f43f5e"}};function We(e){return e.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g,"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Qe(e,t){return e.length<=t?e:`${e.slice(0,Math.max(1,t-1))}…`}function Mm(e,t,n){const s=e.trim().split(/\s+/).filter(Boolean);if(s.length===0)return[];const r=[];let i="";for(const a of s){const l=i?`${i} ${a}`:a;if(l.length<=t?i=l:i?(r.push(i),i=a):(r.push(Qe(a,t)),i=""),r.length===n){i="";break}}return i&&r.length<n?r.push(Qe(i,t)):i&&r.length===n&&(r[n-1]=Qe(r[n-1],t)),r}function Io(e,t,n=0){const s=(()=>{switch(t){case"top":return{x:e.x+e.width/2,y:e.y};case"right":return{x:e.x+e.width,y:e.y+e.height/2};case"bottom":return{x:e.x+e.width/2,y:e.y+e.height};case"left":return{x:e.x,y:e.y+e.height/2}}})();return n?t==="left"||t==="right"?{x:s.x,y:s.y+n}:{x:s.x+n,y:s.y}:s}function Fn(e){switch(e){case"right":return{x:1,y:0};case"left":return{x:-1,y:0};case"bottom":return{x:0,y:1};case"top":return{x:0,y:-1}}}function $n(e,t,n){const s=Math.hypot(e,t);return s<.001?n:{x:e/s,y:t/s}}function Lo(e,t=12){if(e.length<2)return"";if(e.length===2)return`M ${e[0].x} ${e[0].y} L ${e[1].x} ${e[1].y}`;let n=`M ${e[0].x} ${e[0].y}`;for(let r=1;r<e.length-1;r++){const i=e[r-1],a=e[r],l=e[r+1],d=a.x-i.x,u=a.y-i.y,c=Math.hypot(d,u),f=l.x-a.x,p=l.y-a.y,h=Math.hypot(f,p);if(c<1||h<1){n+=` L ${a.x} ${a.y}`;continue}const x=Math.min(t,c*.4,h*.4),m=a.x-d/c*x,g=a.y-u/c*x,y=a.x+f/h*x,b=a.y+p/h*x;n+=` L ${m} ${g} Q ${a.x} ${a.y} ${y} ${b}`}const s=e[e.length-1];return n+=` L ${s.x} ${s.y}`,n}function Cm(e,t,n,s){const r=Fn(t),i=Fn(s),a={x:e.x+r.x*22,y:e.y+r.y*22},l={x:n.x+i.x*22,y:n.y+i.y*22},d=t==="left"||t==="right",u=s==="left"||s==="right";if(d&&u){const c=(a.x+l.x)/2;return{points:[e,a,{x:c,y:a.y},{x:c,y:l.y},l,n],labelPos:{x:c,y:(a.y+l.y)/2}}}if(!d&&!u){const c=(a.y+l.y)/2;return{points:[e,a,{x:a.x,y:c},{x:l.x,y:c},l,n],labelPos:{x:(a.x+l.x)/2,y:c}}}return d&&!u?{points:[e,a,{x:l.x,y:a.y},l,n],labelPos:{x:l.x,y:a.y}}:{points:[e,a,{x:a.x,y:l.y},l,n],labelPos:{x:a.x,y:l.y}}}function Bo(e,t,n,s,r,i){const a=-t.y,l=t.x,d=($,k)=>({x:e.x+t.x*$+a*k,y:e.y+t.y*$+l*k}),u=n==="1..*"||n==="0..*",c=n==="0..1"||n==="0..*",f=u?14:9,p=d(f,-6),h=d(f,6),x=d(u?18:16,0),m=d(0,-7),g=d(0,7),y=d(12,0),b=[];return u?b.push(`<line x1="${y.x}" y1="${y.y}" x2="${m.x}" y2="${m.y}" stroke="${s}" stroke-width="${r}" stroke-linecap="round" />`,`<line x1="${y.x}" y1="${y.y}" x2="${g.x}" y2="${g.y}" stroke="${s}" stroke-width="${r}" stroke-linecap="round" />`):b.push(`<line x1="${p.x}" y1="${p.y}" x2="${h.x}" y2="${h.y}" stroke="${s}" stroke-width="${r}" stroke-linecap="round" />`),!c&&u&&b.push(`<line x1="${p.x}" y1="${p.y}" x2="${h.x}" y2="${h.y}" stroke="${s}" stroke-width="${r}" stroke-linecap="round" />`),c&&b.push(`<circle cx="${x.x}" cy="${x.y}" r="4" fill="${i}" stroke="${s}" stroke-width="${r}" />`),b.join("")}function Em(e,t,n,s,r){const i=-t.y,a=t.x,l={x:e.x+t.x*13+i*7,y:e.y+t.y*13+a*7},d={x:e.x+t.x*13-i*7,y:e.y+t.y*13-a*7};return`<polygon points="${e.x},${e.y} ${l.x},${l.y} ${d.x},${d.y}" fill="${r}" stroke="${n}" stroke-width="${s}" stroke-linejoin="round" />`}function Om(e){const t=[];return e.pk&&t.push({label:"PK",darkBg:"#451a03",darkText:"#fcd34d",darkBorder:"#b45309",lightBg:"#fef3c7",lightText:"#b45309",lightBorder:"#f59e0b"}),e.fk&&t.push({label:"FK",darkBg:"#082f49",darkText:"#7dd3fc",darkBorder:"#0369a1",lightBg:"#e0f2fe",lightText:"#0369a1",lightBorder:"#38bdf8"}),e.unique&&t.push({label:"UQ",darkBg:"#2e1065",darkText:"#c4b5fd",darkBorder:"#6d28d9",lightBg:"#ede9fe",lightText:"#6d28d9",lightBorder:"#a78bfa"}),e.indexed&&t.push({label:"IDX",darkBg:"#1e293b",darkText:"#cbd5e1",darkBorder:"#475569",lightBg:"#f1f5f9",lightText:"#334155",lightBorder:"#cbd5e1"}),t}function zm(e,t,n,s,r,i,a){var b;const{x:l,y:d,width:u,height:c}=t,f=mr[e.status],p=u/2,h=c/2,x=`${p},1 ${u-1},${h} ${p},${c-1} 1,${h}`,m=[`<g transform="translate(${l}, ${d})">`,`<defs><clipPath id="${a}"><polygon points="${x}" /></clipPath></defs>`,`<polygon points="${x}" fill="${n.cardBg}" stroke="${r}" stroke-width="${i}" stroke-linejoin="round" />`,`<g clip-path="url(#${a})">`,`<text x="${p}" y="${Math.round(c*.27)}" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="9.5" font-weight="700" fill="${s?"#7dd3fc":"#0369a1"}">${We(Qe(e.kind.toUpperCase(),16))}</text>`,`<text x="${p}" y="${Math.round(c*.49)}" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="12.5" font-weight="700" fill="${n.textPrimary}">${We(Qe(e.title,24))}</text>`];(b=e.summary)!=null&&b.trim()&&m.push(`<text x="${p}" y="${Math.round(c*.64)}" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="10" fill="${n.textMuted}">${We(Qe(e.summary.trim(),28))}</text>`);const g=Math.max(44,f.label.length*5.6+14),y=Math.round(c*.75);return m.push(`<rect x="${p-g/2}" y="${y}" width="${g}" height="17" rx="8.5" fill="${s?f.darkBg:f.lightBg}" stroke="${s?f.darkBorder:f.lightBorder}" stroke-width="1" />`,`<text x="${p}" y="${y+12}" text-anchor="middle" font-family="system-ui, sans-serif" font-size="9" font-weight="600" fill="${s?f.darkText:f.lightText}">${We(f.label)}</text>`,"</g></g>"),m.join(`
63
+ `)}function Tm(e,t,n,s,r,i,a){var k;const{x:l,y:d,width:u,height:c}=t,f=mr[e.status],p=(c/2).toFixed(1),h=u/2,x=e.kind.toUpperCase(),m=Math.max(44,f.label.length*5.8+12),g=Math.max(40,x.length*6+12),y=g+6+m+(e.locked?24:0),b=h-y/2,$=[`<g transform="translate(${l}, ${d})">`,`<defs><clipPath id="${a}"><rect x="0" y="0" width="${u}" height="${c}" rx="${p}" /></clipPath></defs>`,`<rect x="0" y="0" width="${u}" height="${c}" rx="${p}" fill="${n.cardBg}" stroke="${r}" stroke-width="${i}" />`,`<g clip-path="url(#${a})">`,`<rect x="${b}" y="9" width="${g}" height="18" rx="5" fill="${n.badgeBg}" stroke="${n.badgeBorder}" stroke-width="1" />`,`<text x="${b+g/2}" y="21.5" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="9.5" font-weight="700" fill="${s?"#7dd3fc":"#0369a1"}">${We(Qe(x,16))}</text>`,`<rect x="${b+g+6}" y="9" width="${m}" height="18" rx="9" fill="${s?f.darkBg:f.lightBg}" stroke="${s?f.darkBorder:f.lightBorder}" stroke-width="1" />`,`<text x="${b+g+6+m/2}" y="21.5" text-anchor="middle" font-family="system-ui, sans-serif" font-size="9.5" font-weight="600" fill="${s?f.darkText:f.lightText}">${We(f.label)}</text>`];if(e.locked){const _=b+g+6+m+6;$.push(`<rect x="${_}" y="9" width="18" height="18" rx="5" fill="${s?"#2e1065":"#ede9fe"}" stroke="${n.borderLocked}" stroke-width="1" />`,`<text x="${_+9}" y="21.5" text-anchor="middle" font-family="system-ui, sans-serif" font-size="9.5" font-weight="700" fill="${n.borderLocked}">L</text>`)}return $.push(`<text x="${h}" y="47" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="13" font-weight="700" fill="${n.textPrimary}">${We(Qe(e.title,28))}</text>`),(k=e.summary)!=null&&k.trim()&&$.push(`<text x="${h}" y="64" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="10.5" fill="${n.textMuted}">${We(Qe(e.summary.trim(),34))}</text>`),$.push("</g></g>"),$.join(`
64
+ `)}function Pm(e,t,n,s,r){var Z;const{x:i,y:a,width:l,height:d}=t,u=`clip-${e.id.replace(/[^a-zA-Z0-9_-]/g,"_")}`,c=n==="er"||e.fields&&e.fields.length>0,f=Xn(e,n),p=mr[e.status],h=e.status==="drifted"?s.borderDrifted:e.status==="needs_input"?s.borderNeedsInput:e.locked?s.borderLocked:s.borderDefault,x=e.locked||e.status!=="draft"?1.8:1.25;if(f==="decision")return zm(e,t,s,r,h,x,u);if(f==="terminal")return Tm(e,t,s,r,h,x,u);const m=f==="store",g=m?22:0,y=m?12:0,b=10,$=11,k=l/2,_=[];if(_.push(`<g transform="translate(${i}, ${a})">`),m){const D=`M 0 ${$} L 0 ${d-$} A ${k} ${b} 0 0 0 ${l} ${d-$} L ${l} ${$} Z`,J=`M 0 ${$} A ${k} ${b} 0 0 1 ${l} ${$} L ${l} ${d-$} A ${k} ${b} 0 0 1 0 ${d-$} Z`;_.push(`<defs><clipPath id="${u}"><path d="${J}" /></clipPath></defs>`,`<path d="${D}" fill="${s.cardBg}" stroke="${h}" stroke-width="${x}" />`,`<ellipse cx="${k}" cy="${$}" rx="${k}" ry="${b}" fill="${s.headerBg}" stroke="${h}" stroke-width="${x}" />`)}else _.push(`<defs><clipPath id="${u}"><rect x="0" y="0" width="${l}" height="${d}" rx="12" /></clipPath></defs>`),_.push(`<rect x="0" y="0" width="${l}" height="${d}" rx="12" fill="${s.cardBg}" stroke="${h}" stroke-width="${x}" />`);_.push(`<g clip-path="url(#${u})">`);const O=34;m||_.push(`<rect x="0" y="0" width="${l}" height="${O}" fill="${s.headerBg}" />`),_.push(`<line x1="0" y1="${g+O}" x2="${l}" y2="${g+O}" stroke="${s.divider}" stroke-width="1" />`);const F=e.kind.toUpperCase(),N=Math.min(l-110,Math.max(42,F.length*6.5+16));_.push(`<rect x="10" y="${g+7}" width="${N}" height="20" rx="5" fill="${s.badgeBg}" stroke="${s.badgeBorder}" stroke-width="1" />`,`<text x="${10+N/2}" y="${g+20.5}" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="10" font-weight="700" fill="${r?"#7dd3fc":"#0369a1"}">${We(Qe(F,18))}</text>`);const P=Math.max(46,p.label.length*6+14),M=10+N+6;if(_.push(`<rect x="${M}" y="${g+7}" width="${P}" height="20" rx="10" fill="${r?p.darkBg:p.lightBg}" stroke="${r?p.darkBorder:p.lightBorder}" stroke-width="1" />`,`<text x="${M+P/2}" y="${g+20.5}" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="10" font-weight="600" fill="${r?p.darkText:p.lightText}">${We(p.label)}</text>`),e.locked){const D=l-30;_.push(`<rect x="${D}" y="${g+7}" width="20" height="20" rx="5" fill="${r?"#2e1065":"#ede9fe"}" stroke="${s.borderLocked}" stroke-width="1" />`,`<text x="${D+10}" y="${g+20.5}" text-anchor="middle" font-family="system-ui, sans-serif" font-size="10" font-weight="700" fill="${s.borderLocked}">L</text>`)}let A=g+O+18;const q=Math.max(16,Math.floor((l-24)/7.8));if(_.push(`<text x="12" y="${A}" font-family="system-ui, -apple-system, sans-serif" font-size="13.5" font-weight="700" fill="${s.textPrimary}">${We(Qe(e.title,q))}</text>`),A+=16,(Z=e.summary)!=null&&Z.trim()){const D=Mm(e.summary,Math.max(22,Math.floor((l-24)/6.2)),2);for(const J of D)_.push(`<text x="12" y="${A}" font-family="system-ui, -apple-system, sans-serif" font-size="11" fill="${s.textMuted}">${We(J)}</text>`),A+=14}A+=4;const ne=!!(e.entity_ref||e.code_refs&&e.code_refs.length>0),Q=d-y-(ne?28:8),w=e.fields??[];if(c&&A+24<Q)if(_.push(`<line x1="0" y1="${A}" x2="${l}" y2="${A}" stroke="${s.divider}" stroke-width="1" />`),A+=16,_.push(`<text x="12" y="${A}" font-family="system-ui, sans-serif" font-size="9.5" font-weight="700" letter-spacing="0.8" fill="${r?"#34d399":"#047857"}">ATTRIBUTES</text>`,`<text x="${l-12}" y="${A}" text-anchor="end" font-family="ui-monospace, monospace" font-size="10" fill="${s.textMuted}">${w.length}</text>`),A+=14,w.length===0)_.push(`<text x="12" y="${A}" font-family="system-ui, sans-serif" font-size="11" font-style="italic" fill="${s.textMuted}">No attributes</text>`),A+=18;else{const{visibleCount:D,hiddenCount:J}=mt(w.length,Bn),X=w.slice(0,D);for(const W of X){if(A+8>Q)break;const se=W.nullable?"○":"*",le=W.nullable?s.textMuted:r?"#fb7185":"#e11d48";_.push(`<text x="14" y="${A}" font-family="ui-monospace, monospace" font-size="11" font-weight="700" fill="${le}">${se}</text>`);const me=Om(W);let ae=l-10;for(let ie=me.length-1;ie>=0;ie--){const V=me[ie],ue=V.label.length*6.5+8;ae-=ue,_.push(`<rect x="${ae}" y="${A-10}" width="${ue}" height="13" rx="3" fill="${r?V.darkBg:V.lightBg}" stroke="${r?V.darkBorder:V.lightBorder}" stroke-width="0.8" />`,`<text x="${ae+ue/2}" y="${A-1}" text-anchor="middle" font-family="system-ui, sans-serif" font-size="8.5" font-weight="700" fill="${r?V.darkText:V.lightText}">${V.label}</text>`),ae-=3}const fe=Math.max(12,Math.floor((ae-30)/6.5)),ee=W.type?`${W.name}: ${W.type}`:W.name;_.push(`<text x="27" y="${A}" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="11" fill="${s.textPrimary}">${We(Qe(ee,fe))}</text>`),A+=20}J>0&&A+4<=Q&&(_.push(`<text x="14" y="${A}" font-family="system-ui, sans-serif" font-size="10" font-weight="600" fill="${r?"#38bdf8":"#0284c7"}">+${J} more</text>`),A+=16)}for(const D of e.sections){if(A+22>=Q)break;if(_.push(`<line x1="0" y1="${A}" x2="${l}" y2="${A}" stroke="${s.divider}" stroke-width="1" />`),A+=15,_.push(`<text x="12" y="${A}" font-family="system-ui, sans-serif" font-size="9.5" font-weight="700" letter-spacing="0.7" fill="${s.textMuted}">${We(Qe(D.heading.toUpperCase(),30))}</text>`,`<text x="${l-12}" y="${A}" text-anchor="end" font-family="ui-monospace, monospace" font-size="10" fill="${s.textMuted}">${D.items.length}</text>`),A+=15,D.items.length===0)_.push(`<text x="14" y="${A}" font-family="system-ui, sans-serif" font-size="11" font-style="italic" fill="${s.textMuted}">No items</text>`),A+=16;else{const{visibleCount:J,hiddenCount:X}=mt(D.items.length,dn),W=D.items.slice(0,J),se=Math.max(18,Math.floor((l-28)/6.5));for(const le of W){if(A+4>Q)break;_.push(`<text x="14" y="${A}" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="11" fill="${s.textSecondary}">${We(Qe(le,se))}</text>`),A+=17}X>0&&A+4<=Q&&(_.push(`<text x="14" y="${A}" font-family="system-ui, sans-serif" font-size="10" font-weight="600" fill="${r?"#38bdf8":"#0284c7"}">+${X} more</text>`),A+=15)}}if(ne){const D=d-y-24;if(_.push(...m?[]:[`<rect x="0" y="${D}" width="${l}" height="24" fill="${s.footerBg}" />`],`<line x1="0" y1="${D}" x2="${l}" y2="${D}" stroke="${s.divider}" stroke-width="1" />`),e.entity_ref&&_.push(`<text x="12" y="${D+15.5}" font-family="ui-monospace, monospace" font-size="10" fill="${s.textMuted}">${We(Qe(`ref:${e.entity_ref}`,26))}</text>`),e.code_refs&&e.code_refs.length>0){const J=e.code_refs.length;_.push(`<text x="${l-12}" y="${D+15.5}" text-anchor="end" font-family="ui-monospace, monospace" font-size="10" fill="${r?"#6ee7b7":"#047857"}">${J} ref${J>1?"s":""}</text>`)}}return _.push("</g></g>"),_.join(`
65
+ `)}function Am(e,t,n,s,r,i,a,l){var W;const d=n.get(e.source),u=n.get(e.target);if(!d||!u)return{svg:"",extraPoints:[]};const c=Io(d,s.sourceHandle,s.sourcePortOffset),f=Io(u,s.targetHandle,s.targetPortOffset),p=Fn(s.sourceHandle),h=Fn(s.targetHandle);let x=p,m=h,g="",y=(c.x+f.x)/2,b=(c.y+f.y)/2;const $=[c,f],k=s.manualWaypoints.length>0?s.manualWaypoints:s.autoWaypoints;if(k.length>0){$.push(...k);const se=[c,...k,f];g=Lo(se,s.manualWaypoints.length>0?12:14);const le=k[0],me=k[k.length-1];if(x=$n(le.x-c.x,le.y-c.y,p),m=$n(me.x-f.x,me.y-f.y,h),k.length>=2){const ae=s.manualWaypoints.length>0?Math.floor(k.length/2)-1:0,fe=k[Math.max(0,ae)],ee=k[Math.min(k.length-1,ae+1)];y=(fe.x+ee.x)/2,b=(fe.y+ee.y)/2}else y=k[0].x,b=k[0].y}else if(s.curveOffset.x!==0||s.curveOffset.y!==0){const se=(c.x+f.x)/2+s.curveOffset.x,le=(c.y+f.y)/2+s.curveOffset.y;$.push({x:se,y:le}),g=`M ${c.x} ${c.y} Q ${se} ${le} ${f.x} ${f.y}`,x=$n(se-c.x,le-c.y,p),m=$n(se-f.x,le-f.y,h),y=.25*c.x+.5*se+.25*f.x,b=.25*c.y+.5*le+.25*f.y}else{const se=Cm(c,s.sourceHandle,f,s.targetHandle);$.push(...se.points),g=Lo(se.points,12),y=se.labelPos.x,b=se.labelPos.y}$.push({x:y,y:b});const _=t==="er"||!!(e.source_cardinality||e.target_cardinality||e.relation_kind),O=e.locked?r.edgeLocked:r.edgeDefault,F=1.75,N=e.source_cardinality,P=e.target_cardinality,M=e.relation_kind??"association",A=N==="0..1"||N==="0..*",q=P==="0..1"||P==="0..*",ne=N==="1"||N==="1..*",w=_&&M==="association"&&(ne&&q||A&&(P==="1"||P==="1..*")),Z=e.style==="dashed"||_&&M==="association"&&A&&q&&!w,D=[];if(w)D.push(`<path d="${g}" fill="none" stroke="${O}" stroke-width="${F}" stroke-dasharray="6 4" />`,`<path d="${g}" fill="none" stroke="${O}" stroke-width="${F}" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="${ne?0:-50}" />`);else{const se=_?"":` marker-end="url(#${e.locked?l:a})"`,le=Z?' stroke-dasharray="6 4"':"";D.push(`<path d="${g}" fill="none" stroke="${O}" stroke-width="${F}"${le}${se} />`)}_&&M==="subtype"?D.push(Em(f,m,O,F,r.canvasBg)):_&&(N||P)&&(N&&D.push(Bo(c,x,N,O,F,r.canvasBg)),P&&D.push(Bo(f,m,P,O,F,r.canvasBg)));const J=((W=e.label)==null?void 0:W.trim())||(M==="subtype"?"is-a":"");if(!!J||e.step!==void 0||!!e.locked){const se=e.step!==void 0?20:0,le=J?Math.min(160,J.length*6.4):0,me=e.locked?14:0,ae=Math.max(28,16+se+le+me),fe=22,ee=y-ae/2,ie=b-fe/2;D.push(`<rect x="${ee}" y="${ie}" width="${ae}" height="${fe}" rx="11" fill="${r.pillBg}" stroke="${r.pillBorder}" stroke-width="1" />`);let V=ee+8;e.step!==void 0&&(D.push(`<circle cx="${V+7}" cy="${b}" r="7.5" fill="${i?"#38bdf8":"#0284c7"}" />`,`<text x="${V+7}" y="${b+3.5}" text-anchor="middle" font-family="system-ui, sans-serif" font-size="9.5" font-weight="700" fill="${i?"#020617":"#ffffff"}">${e.step}</text>`),V+=20),J&&D.push(`<text x="${V}" y="${b+3.8}" font-family="system-ui, -apple-system, sans-serif" font-size="11" font-weight="500" fill="${r.textSecondary}">${We(Qe(J,24))}</text>`)}return{svg:D.join(`
66
+ `),extraPoints:$}}function Dm(e){var M,A;const{view:t,positions:n,edgeRoutes:s={},measured:r,theme:i,bgPattern:a="dots"}=e,l=i==="dark",d=l?Nm:Sm;if(t.nodes.length===0)return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="560" height="280" viewBox="0 0 560 280">
67
+ <rect width="560" height="280" fill="${d.canvasBg}" />
68
+ <text x="280" y="140" text-anchor="middle" font-family="system-ui, sans-serif" font-size="14" fill="${d.textMuted}">${We(t.title)} (empty diagram)</text>
69
+ </svg>
70
+ `,width:560,height:280};const u=new Map;let c=1/0,f=1/0,p=-1/0,h=-1/0;for(const q of t.nodes){const ne=n[q.id]??{x:40,y:40},Q=hr(q,t.diagram_type),w=Math.round(((M=r==null?void 0:r[q.id])==null?void 0:M.width)??Q.width),Z=Math.round(((A=r==null?void 0:r[q.id])==null?void 0:A.height)??Q.height);u.set(q.id,{x:ne.x,y:ne.y,width:w,height:Z}),c=Math.min(c,ne.x),f=Math.min(f,ne.y),p=Math.max(p,ne.x+w),h=Math.max(h,ne.y+Z)}const x=pr(t,n,s,r),m="redlinify-arrow-default",g="redlinify-arrow-locked",y=[];for(const q of t.edges){const ne=x[q.id];if(!ne)continue;const Q=Am(q,t.diagram_type,u,ne,d,l,m,g);y.push(Q.svg);for(const w of Q.extraPoints)c=Math.min(c,w.x-90),f=Math.min(f,w.y-24),p=Math.max(p,w.x+90),h=Math.max(h,w.y+24)}const b=48,$=Math.max(480,Math.ceil(p-c+b*2)),k=Math.max(280,Math.ceil(h-f+b*2)),_=Math.round(-c+b),O=Math.round(-f+b),F=t.nodes.map(q=>Pm(q,u.get(q.id),t.diagram_type,d,l)),N=a==="grid"?`<pattern id="rl-bg-pattern" width="24" height="24" patternUnits="userSpaceOnUse">
71
+ <path d="M 24 0 L 0 0 0 24" fill="none" stroke="${l?"#1e293b":"#cbd5e1"}" stroke-width="1" />
72
+ </pattern>`:`<pattern id="rl-bg-pattern" width="24" height="24" patternUnits="userSpaceOnUse">
73
+ <circle cx="12" cy="12" r="1.4" fill="${d.patternColor}" opacity="0.65" />
74
+ </pattern>`;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${$}" height="${k}" viewBox="0 0 ${$} ${k}">
75
+ <defs>
76
+ ${N}
77
+ <marker id="${m}" viewBox="-10 -10 20 20" refX="0" refY="0" markerWidth="11" markerHeight="11" orient="auto-start-reverse">
78
+ <polyline points="-5,-4 0,0 -5,4 -5,-4" fill="${d.edgeDefault}" stroke="${d.edgeDefault}" stroke-width="1" stroke-linejoin="round" />
79
+ </marker>
80
+ <marker id="${g}" viewBox="-10 -10 20 20" refX="0" refY="0" markerWidth="11" markerHeight="11" orient="auto-start-reverse">
81
+ <polyline points="-5,-4 0,0 -5,4 -5,-4" fill="${d.edgeLocked}" stroke="${d.edgeLocked}" stroke-width="1" stroke-linejoin="round" />
82
+ </marker>
83
+ </defs>
84
+ <rect width="${$}" height="${k}" fill="${d.canvasBg}" />
85
+ <rect width="${$}" height="${k}" fill="url(#rl-bg-pattern)" />
86
+ <g transform="translate(${_}, ${O})">
87
+ ${y.join(`
88
+ `)}
89
+ ${F.join(`
90
+ `)}
91
+ </g>
92
+ </svg>
93
+ `,width:$,height:k}}function Im(e,t,n,s=2){return new Promise((r,i)=>{const l=Math.min(s,8192/Math.max(1,t),8192/Math.max(1,n)),d=Math.max(1,Math.round(t*l)),u=Math.max(1,Math.round(n*l)),c=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),f=URL.createObjectURL(c),p=new Image;p.onload=()=>{try{const h=document.createElement("canvas");h.width=d,h.height=u;const x=h.getContext("2d");if(!x){URL.revokeObjectURL(f),i(new Error("Canvas 2D context is unavailable"));return}x.drawImage(p,0,0,d,u),URL.revokeObjectURL(f),h.toBlob(m=>{m?r(m):i(new Error("Failed to encode PNG image"))},"image/png")}catch(h){URL.revokeObjectURL(f),i(h instanceof Error?h:new Error(String(h)))}},p.onerror=()=>{URL.revokeObjectURL(f),i(new Error("Failed to rasterize SVG diagram"))},p.src=f})}function Lm(e){return`${JSON.stringify(e,null,2)}
94
+ `}function Nn(e,t,n="text/plain;charset=utf-8"){const s=t instanceof Blob?t:new Blob([t],{type:n}),r=URL.createObjectURL(s),i=document.createElement("a");i.href=r,i.download=e,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function Bm({activeViewRef:e,positionsRef:t,edgeRoutesRef:n,rfNodes:s,theme:r,bgPattern:i,showToast:a}){return{handleExportDiagram:v.useCallback(async d=>{var f,p;const u=e.current;if(!u)return;const c={};for(const h of s)((f=h.measured)!=null&&f.width||(p=h.measured)!=null&&p.height)&&(c[h.id]={width:h.measured.width,height:h.measured.height});try{if(d==="json"){Nn(`${u.id}.json`,Lm(u),"application/json;charset=utf-8"),a(`Exported ${u.id}.json`);return}if(d==="mermaid"||d==="copy_mermaid"){const y=$m(u,{theme:r});d==="copy_mermaid"?(await navigator.clipboard.writeText(y),a("Copied Mermaid diagram to clipboard")):(Nn(`${u.id}.mmd`,y,"text/plain;charset=utf-8"),a(`Exported ${u.id}.mmd`));return}const{svg:h,width:x,height:m}=Dm({view:u,positions:t.current,edgeRoutes:n.current,measured:c,theme:r,bgPattern:i});if(d==="svg"){Nn(`${u.id}.svg`,h,"image/svg+xml;charset=utf-8"),a(`Exported ${u.id}.svg`);return}const g=await Im(h,x,m,2);Nn(`${u.id}.png`,g,"image/png"),a(`Exported ${u.id}.png (2× HD)`)}catch(h){a(h instanceof Error?h.message:"Failed to export diagram","error")}},[e,i,n,t,s,a,r])}}function Zm(){const[e,t]=v.useState(()=>document.documentElement.classList.contains("dark")?"dark":"light"),[n,s]=v.useState(()=>{try{return localStorage.getItem("redlinify-bg-pattern")==="grid"?"grid":"dots"}catch{return"dots"}}),[r,i]=v.useState(()=>{try{return localStorage.getItem("redlinify-scroll-mode")==="zoom"?"zoom":"pan"}catch{return"pan"}}),a=v.useRef(e);a.current=e;const l=v.useRef(n);l.current=n;const d=v.useRef({theme:!1,bg_pattern:!1,scroll_mode:!1});v.useEffect(()=>{let p=!1;return Gp().then(h=>{p||(h.theme&&!d.current.theme&&(a.current=h.theme,t(h.theme)),h.bg_pattern&&!d.current.bg_pattern&&(l.current=h.bg_pattern,s(h.bg_pattern)),h.scroll_mode&&!d.current.scroll_mode&&i(h.scroll_mode))}).catch(()=>{}),()=>{p=!0}},[]),v.useEffect(()=>{document.documentElement.classList.toggle("dark",e==="dark");try{localStorage.setItem("redlinify-theme",e)}catch{}},[e]),v.useEffect(()=>{try{localStorage.setItem("redlinify-bg-pattern",n)}catch{}},[n]),v.useEffect(()=>{try{localStorage.setItem("redlinify-scroll-mode",r)}catch{}},[r]);const u=v.useCallback(()=>{const p=a.current==="dark"?"light":"dark";d.current.theme=!0,a.current=p,t(p),ws({theme:p}).catch(()=>{})},[]),c=v.useCallback(()=>{const p=l.current==="dots"?"grid":"dots";d.current.bg_pattern=!0,l.current=p,s(p),ws({bg_pattern:p}).catch(()=>{})},[]),f=v.useCallback(p=>{d.current.scroll_mode=!0,i(p),ws({scroll_mode:p}).catch(()=>{})},[]);return{theme:e,bgPattern:n,scrollMode:r,setScrollMode:f,toggleTheme:u,toggleBgPattern:c}}function Rm(){const[e,t]=v.useState(null),n=v.useCallback((s,r="info")=>{const i=Date.now();t({id:i,message:s,tone:r}),setTimeout(()=>{t(a=>(a==null?void 0:a.id)===i?null:a)},3600)},[]);return{toast:e,showToast:n}}function Fm({activeViewRef:e,positionsRef:t,edgeRoutesRef:n,showToast:s}){const[r,i]=v.useState(0),a=v.useRef(new Map),l=v.useRef(new Map),d=v.useCallback((p,h)=>{const x=e.current;if(!h&&(!x||x.id!==p))return;const m=h??{view:structuredClone(x),positions:structuredClone(t.current),edgeRoutes:structuredClone(n.current)},g=a.current.get(p)??[];g.push(m),g.length>50&&g.shift(),a.current.set(p,g),l.current.set(p,[]),i(y=>y+1)},[e,n,t]),u=v.useCallback(async p=>{const h=e.current;if(!h)return;const m=(a.current.get(h.id)??[]).pop();if(!m)return;const g=l.current.get(h.id)??[];g.push({view:structuredClone(h),positions:structuredClone(t.current),edgeRoutes:structuredClone(n.current)}),l.current.set(h.id,g),i(y=>y+1),await p(m,h),s("Undone")},[e,n,t,s]),c=v.useCallback(async p=>{const h=e.current;if(!h)return;const m=(l.current.get(h.id)??[]).pop();if(!m)return;const g=a.current.get(h.id)??[];g.push({view:structuredClone(h),positions:structuredClone(t.current),edgeRoutes:structuredClone(n.current)}),a.current.set(h.id,g),i(y=>y+1),await p(m,h),s("Redone")},[e,n,t,s]),f=v.useCallback(p=>{a.current.delete(p),l.current.delete(p)},[]);return{historyTick:r,undoMapRef:a,redoMapRef:l,pushHistoryEntry:d,undoWith:u,redoWith:c,clearViewHistory:f}}const xr=.15,gr=3,Um=1,Hm=.009,Wm=.0022,Zo=.2,Km=100,qm=220,Ro=120,Jm=280,Fo=560,Xm=1750;function Bs(e,t,n){return Math.min(n,Math.max(t,e))}function Uo(e,t){return t===1?e*28:t===2?e*320:e}function Ym(e,t){if(e<Ro)return 0;const n=Bs((e-Ro)/Jm,0,1),s=Fo+(Xm-Fo)*n*n;return t?s*1.5:s}function Gm({viewport:e,clientX:t,clientY:n,containerRect:s,deltaX:r,deltaY:i,deltaMode:a,ctrlKey:l,metaKey:d,shiftKey:u,scrollMode:c="pan",isMac:f=!1,minZoom:p=xr,maxZoom:h=gr,panSpeed:x=Um}){let m=Uo(r,a),g=Uo(i,a);const y=l||d;if(y||c==="zoom"&&!u&&Math.abs(g)>=Math.abs(m)&&g!==0){const $=y?Hm:Wm,k=g!==0?Bs(-g*$,-Zo,Zo):0,_=Bs(e.zoom*Math.exp(k),p,h),O=t-s.left,F=n-s.top,N=_/e.zoom;return{action:"zoom",viewport:{x:O-(O-e.x)*N,y:F-(F-e.y)*N,zoom:_}}}return!f&&u&&m===0&&g!==0&&(m=g,g=0),{action:"pan",viewport:{x:e.x-m*x,y:e.y-g*x,zoom:e.zoom}}}const Qm='.nowheel, .react-flow__controls, [role="dialog"], [role="menu"]';function Vm(e){let t=0,n=0;if(e.has("ArrowLeft")&&(t+=1),e.has("ArrowRight")&&(t-=1),e.has("ArrowUp")&&(n+=1),e.has("ArrowDown")&&(n-=1),t!==0&&n!==0){const s=1/Math.SQRT2;t*=s,n*=s}return{x:t,y:n}}function e0({containerRef:e,activeViewIdRef:t,positionsRef:n,edgeRoutesRef:s,viewportReadyRef:r,scrollMode:i,getViewport:a,setViewport:l,fitView:d,zoomIn:u,zoomOut:c,zoomTo:f,clearContextMenu:p}){const h=v.useRef(null),x=v.useRef(i);x.current=i;const m=v.useRef(new Set),g=v.useRef(!1),y=v.useRef(0),b=v.useRef(0),$=v.useRef(null),k=v.useCallback(()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null;const w=t.current;!w||!r.current||fr(w,{positions:n.current,edge_routes:s.current,viewport:a()})},180)},[t,s,a,n,r]),_=v.useCallback(()=>{$.current!==null&&(cancelAnimationFrame($.current),$.current=null)},[]);v.useEffect(()=>()=>{_(),h.current&&clearTimeout(h.current)},[_]),v.useEffect(()=>{const w=e.current;if(!w)return;const Z=typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent),D=X=>{if(!t.current)return;const W=X.target;if(W instanceof Element&&W.closest(Qm))return;X.preventDefault(),X.stopPropagation(),p();const se=Gm({viewport:a(),clientX:X.clientX,clientY:X.clientY,containerRect:w.getBoundingClientRect(),deltaX:X.deltaX,deltaY:X.deltaY,deltaMode:X.deltaMode,ctrlKey:X.ctrlKey,metaKey:X.metaKey,shiftKey:X.shiftKey,scrollMode:x.current,isMac:Z,minZoom:xr,maxZoom:gr});l(se.viewport,{duration:0}),k()},J=X=>{X.preventDefault()};return w.addEventListener("wheel",D,{capture:!0,passive:!1}),w.addEventListener("gesturestart",J,{passive:!1}),w.addEventListener("gesturechange",J,{passive:!1}),()=>{w.removeEventListener("wheel",D,!0),w.removeEventListener("gesturestart",J),w.removeEventListener("gesturechange",J)}},[t,p,e,a,k,l]);const O=v.useCallback(w=>{if(m.current.size===0||!t.current){$.current=null;return}const Z=Math.min(Math.max((w-b.current)/1e3,0),.05);b.current=w;const D=Ym(w-y.current,g.current);if(D>0&&Z>0){const J=Vm(m.current);if(J.x!==0||J.y!==0){const X=a();l({x:X.x+J.x*D*Z,y:X.y+J.y*D*Z,zoom:X.zoom},{duration:0})}}$.current=requestAnimationFrame(O)},[t,a,l]),F=v.useCallback((w,Z)=>{if(!t.current||(g.current=Z,m.current.has(w)))return;const D=m.current.size===0,J=performance.now();D&&(y.current=J,b.current=J),m.current.add(w);const X=Z?qm:Km,W=w==="ArrowLeft"?X:w==="ArrowRight"?-X:0,se=w==="ArrowUp"?X:w==="ArrowDown"?-X:0,le=a();l({x:le.x+W,y:le.y+se,zoom:le.zoom},{duration:0}),k(),$.current===null&&($.current=requestAnimationFrame(O))},[t,a,O,k,l]),N=v.useCallback(w=>{m.current.has(w)&&(m.current.delete(w),m.current.size===0&&(_(),k()))},[_,k]),P=v.useCallback(w=>{g.current=w},[]),M=v.useCallback(()=>{const w=m.current.size>0;m.current.clear(),g.current=!1,_(),w&&k()},[_,k]),A=v.useCallback(()=>{t.current&&(u({duration:130}),k())},[t,k,u]),q=v.useCallback(()=>{t.current&&(c({duration:130}),k())},[t,k,c]),ne=v.useCallback(()=>{t.current&&(d({padding:.16,maxZoom:1.05,duration:180}),k())},[t,d,k]),Q=v.useCallback(()=>{t.current&&(f(1,{duration:150}),k())},[t,k,f]);return{startArrowPan:F,stopArrowPan:N,updateArrowShift:P,stopAllArrowPan:M,handleZoomIn:A,handleZoomOut:q,handleFitView:ne,handleResetZoom:Q}}function js(e,t){if(t<=0)return!0;const n=e[t-1],s=e[t];return" _-.:/→()[]".includes(n)?!0:n>="a"&&n<="z"&&s>="A"&&s<="Z"}function t0(e,t,n){const s=e.length,r=t.length;if(Math.abs(s-r)>n)return n+1;if(s===0)return r;if(r===0)return s;let i=new Array(r+1).fill(0),a=Array.from({length:r+1},(l,d)=>d);for(let l=1;l<=s;l+=1){const d=new Array(r+1).fill(n+1);d[0]=l;let u=l;const c=e[l-1];for(let f=1;f<=r;f+=1){const p=t[f-1],h=c===p?0:1;let x=Math.min(a[f]+1,d[f-1]+1,a[f-1]+h);l>1&&f>1&&c===t[f-2]&&e[l-2]===p&&(x=Math.min(x,i[f-2]+h)),d[f]=x,x<u&&(u=x)}if(u>n)return n+1;i=a,a=d}return a[r]}function n0(e){return e<=2?0:e<=5?1:e<=9?2:3}function s0(e){const t=[];let n=-1;for(let s=0;s<e.length;s+=1){const r=e[s];if(" _-.:/→()[]".includes(r)){n!==-1&&(t.push({word:e.slice(n,s).toLowerCase(),start:n,end:s}),n=-1);continue}const a=s>0?e[s-1]:"";n!==-1&&a>="a"&&a<="z"&&r>="A"&&r<="Z"?(t.push({word:e.slice(n,s).toLowerCase(),start:n,end:s}),n=s):n===-1&&(n=s)}return n!==-1&&t.push({word:e.slice(n).toLowerCase(),start:n,end:e.length}),t}function r0(e,t){const n=n0(e.length);if(n===0)return null;const s=s0(t),r=[];for(let d=0;d<s.length;d+=1){const u=s[d];if(r.push({cand:u.word,start:u.start,end:u.end}),u.word.length>=e.length+2&&e.length>=4){const c=Math.min(u.word.length,e.length);r.push({cand:u.word.slice(0,c),start:u.start,end:u.start+c}),c+1<=u.word.length&&r.push({cand:u.word.slice(0,c+1),start:u.start,end:u.start+c+1})}if(d+1<s.length){const c=s[d+1];r.push({cand:`${u.word}${c.word}`,start:u.start,end:c.end,compound:!0})}}let i=-1/0,a=null;for(const d of r){if(d.cand.length<2)continue;const u=Math.min(n,Math.max(1,Math.floor((Math.max(e.length,d.cand.length)-1)/2))),c=t0(e,d.cand,u);if(c>u)continue;const f=d.start===0?12:4,p=d.compound?4:0,h=96-c*24+f-p-d.start*.1-t.length*.04;h>i&&(i=h,a={start:d.start,end:d.end})}if(!a||i<=0)return null;const l=[];for(let d=a.start;d<a.end;d+=1)l.push(d);return{score:i,indices:l}}function Vt(e,t){const n=e.trim();if(!n)return{score:0,indices:[]};if(!t)return null;const s=t.length>320?t.slice(0,320):t,r=n.toLowerCase(),i=s.toLowerCase();if(i===r)return{score:260+n.length*10,indices:Array.from({length:s.length},(f,p)=>p)};let a=-1,l=-1/0,d=0;for(;d<=i.length-r.length;){const f=i.indexOf(r,d);if(f===-1)break;const p=(f===0?55:js(s,f)?35:0)-f*.25;p>l&&(l=p,a=f),d=f+1}if(a!==-1)return{score:140+l+r.length*8-s.length*.05,indices:Array.from({length:r.length},(f,p)=>a+p)};const u=r.length,c=i.length;if(u<=c){let f=new Array(c).fill(null);for(let h=0;h<c;h+=1)if(i[h]===r[0]){const x=(h===0?18:js(s,h)?14:0)+(s[h]===n[0]?2:0)-h*.15;f[h]={score:6+x,indices:[h]}}for(let h=1;h<u;h+=1){const x=new Array(c).fill(null);let m=-1,g=null;for(let y=h;y<c;y+=1){const b=f[y-1];if(b&&(!g||b.score>=g.score-(y-1-m)*.6)&&(m=y-1,g=b),g&&i[y]===r[h]){const $=m===y-1,k=y-m-1,_=5+($?16:js(s,y)?12:0)+(s[y]===n[h]?2:0)-Math.min(12,k*.6);x[y]={score:g.score+_,indices:[...g.indices,y]}}}f=x}let p=null;for(let h=0;h<c;h+=1){const x=f[h];if(!x)continue;const m=x.score-s.length*.05;(!p||m>p.score)&&(p={score:m,indices:x.indices})}if(p)return p}return r0(r,s)}function o0(e){var c,f,p;const{tabs:t,views:n,allThreads:s,activeViewId:r}=e,i=[],a=new Map(n.map(h=>[h.id,h])),l=new Map(t.map(h=>[h.view_id,h])),d=[],u=new Set;for(const h of t){i.push({id:`view:${h.view_id}`,kind:"view",title:h.title,subtitle:h.description,viewId:h.view_id,viewTitle:h.title,targetType:"view",badge:h.diagram_type==="er"?"ER View":"View",keywords:[h.view_id,h.diagram_type??"general",h.description??""].filter(Boolean),isCurrentView:h.view_id===r});const x=a.get(h.view_id);x&&(d.push(x),u.add(x.id))}for(const h of n)u.has(h.id)||d.push(h);for(const h of d){const x=l.get(h.id),m=(x==null?void 0:x.title)??h.title,g=h.id===r,y=new Map(h.nodes.map(b=>[b.id,b.title]));for(const b of h.nodes){const $=[];for(const k of b.sections){$.push({label:`Section: ${k.heading}`,text:k.heading});for(const _ of k.items)$.push({label:`${k.heading}: ${_}`,text:`${k.heading} ${_}`})}for(const k of b.fields??[])$.push({label:`Attr: ${k.name}${k.type?`: ${k.type}`:""}`,text:`${k.name}${k.type?` ${k.type}`:""}`});i.push({id:`node:${h.id}:${b.id}`,kind:"node",title:b.title,subtitle:b.summary,viewId:h.id,viewTitle:m,targetType:"node",targetId:b.id,preferredTab:"spec",badge:b.kind,keywords:[b.id,b.kind,b.status,b.entity_ref??"",...(b.code_refs??[]).map(k=>k.symbol?`${k.path}:${k.symbol}`:k.path)].filter(Boolean),subEntries:$,isCurrentView:g})}for(const b of h.edges){const $=y.get(b.source)??b.source,k=y.get(b.target)??b.target,_=b.source_cardinality||b.target_cardinality?`${b.source_cardinality??""} : ${b.target_cardinality??""}`:void 0;i.push({id:`edge:${h.id}:${b.id}`,kind:"edge",title:b.label?`${b.label} (${$} → ${k})`:`${$} → ${k}`,subtitle:_??b.relation_kind,viewId:h.id,viewTitle:m,targetType:"edge",targetId:b.id,preferredTab:"spec",badge:"Edge",keywords:[b.id,b.label??"",$,k,b.source,b.target,b.source_cardinality??"",b.target_cardinality??""].filter(Boolean),isCurrentView:g})}}for(const h of s){const x=h.view_id?((c=l.get(h.view_id))==null?void 0:c.title)??((f=a.get(h.view_id))==null?void 0:f.title)??h.view_id:"Workspace";i.push({id:`thread:${h.id}`,kind:"thread",title:h.resolution_summary||((p=h.messages[0])==null?void 0:p.body)||h.id,subtitle:h.target_id?`${h.target_type}: ${h.target_id}`:h.target_type,viewId:h.view_id,viewTitle:x,targetType:h.target_type,targetId:h.target_id,preferredTab:"threads",badge:h.status==="resolved"?"Decision":h.kind.replace("_"," "),keywords:[h.id,h.target_id??"",h.entity_ref??"",...h.messages.map(m=>m.body)].filter(Boolean),isCurrentView:!!(h.view_id&&h.view_id===r)})}return i}const Ho={view:4,node:3,edge:2,thread:1};function i0(e,t,n="all",s=40){const r=n==="all"?e:e.filter(l=>l.kind===n),i=t.trim().split(/\s+/).filter(Boolean);if(i.length===0)return[...r].sort((l,d)=>{const u=Ho[l.kind],c=Ho[d.kind];return u!==c?c-u:!!l.isCurrentView!=!!d.isCurrentView?l.isCurrentView?-1:1:0}).slice(0,s).map(l=>({item:l,score:0,titleIndices:[]}));const a=[];for(const l of r){let d=0,u=!0;const c=new Set;let f;for(const p of i){let h=-1/0;const x=Vt(p,l.title);if(x){h=Math.max(h,x.score*1.45);for(const m of x.indices)c.add(m)}if(l.subtitle){const m=Vt(p,l.subtitle);m&&(h=Math.max(h,m.score*.95))}if(l.viewTitle){const m=Vt(p,l.viewTitle);m&&(h=Math.max(h,m.score*.8))}for(const m of l.keywords){const g=Vt(p,m);g&&(h=Math.max(h,g.score*.9))}if(l.subEntries)for(const m of l.subEntries){const g=Vt(p,m.text);if(g){const y=g.score*1.05;y>h&&(h=y),f||(f=m.label)}}if(h===-1/0){u=!1;break}d+=h}u&&(l.isCurrentView&&(d+=18),l.kind==="view"&&(d+=10),a.push({item:l,score:d,titleIndices:Array.from(c).sort((p,h)=>p-h),matchedSubEntry:f}))}return a.sort((l,d)=>d.score-l.score),a.slice(0,s)}function a0({tabs:e,activeView:t,activeViewId:n,activeViewRef:s,allThreads:r,clearContextMenu:i,handleSelectView:a,handleJumpToTarget:l}){const[d,u]=v.useState(!1),[c,f]=v.useState([]),[p,h]=v.useState(!1),x=v.useCallback(()=>{i(),u(!0)},[i]);v.useEffect(()=>{if(!d)return;let y=!1;return h(!0),Hp().then(b=>{y||f(b.views)}).catch(()=>{y||f(s.current?[s.current]:[])}).finally(()=>{y||h(!1)}),()=>{y=!0}},[s,d]);const m=v.useMemo(()=>{if(!d)return[];const y=new Map(c.map(b=>[b.id,b]));return t&&y.set(t.id,t),o0({tabs:e,views:Array.from(y.values()),allThreads:r,activeViewId:n})},[t,n,r,c,d,e]),g=v.useCallback(y=>{if(u(!1),y.kind==="view"&&y.viewId){a(y.viewId);return}l(y.viewId,y.targetType??"workspace",y.targetId,y.preferredTab)},[l,a]);return{searchOpen:d,setSearchOpen:u,searchLoading:p,openSearch:x,searchIndexItems:m,handleSelectSearchItem:g}}function l0({activeViewIdRef:e,activeViewRef:t,positionsRef:n,edgeRoutesRef:s,measuredSizesRef:r,elkRoutesRef:i,viewportReadyRef:a,getViewport:l,pushHistoryEntry:d,showToast:u}){const[c,f]=v.useState(null),[p,h]=v.useState(null),[x,m]=v.useState(null),[g,y]=v.useState(void 0),[b,$]=v.useState(null),[k,_]=v.useState(null),[O,F]=v.useState([]),[N,P]=v.useState(!1),[M,A]=v.useState(!1),[q,ne]=v.useState(!1),[Q,w]=v.useState(!1),[Z,D]=v.useState(0),[J,X]=v.useState(0),W=v.useRef(void 0),se=v.useRef(Promise.resolve()),le=v.useRef(0),me=v.useRef(null),ae=v.useRef(null),fe=v.useRef(!1);le.current=Math.max(le.current,Z),e.current=p,t.current=x,W.current=g;const ee=v.useMemo(()=>(c==null?void 0:c.status.tabs)??[],[c]),ie=v.useCallback(async()=>{const[xe,re]=await Promise.all([Lp(),qp()]);return ae.current===null&&xe.root_dir&&(ae.current=xe.root_dir),f(xe),F(re.threads),xe},[]),V=v.useCallback(async xe=>{await fr(xe,{positions:n.current,edge_routes:s.current,viewport:l()})},[s,l,n]),ue=v.useCallback(async(xe,re)=>{const Se=e.current!==null&&e.current!==xe;Se&&r&&(r.current={}),Se&&i&&(i.current={});const te=await Wp(xe),G=re!=null&&re.forceResetLayout?{}:te.layout.positions,{positions:T,autoRoutes:E}=await rm(te.view,{positions:G},{forceReset:re==null?void 0:re.forceResetLayout,measured:Se||r==null?void 0:r.current});i&&(re!=null&&re.forceResetLayout||Se||Object.keys(E).length>0)&&(i.current=E);const z=le.current+1;return le.current=z,re!=null&&re.preserveViewport||(a.current=!1,me.current=te.layout.viewport&&!(re!=null&&re.forceResetLayout)?{layoutVersion:z,kind:"restore",viewport:te.layout.viewport}:{layoutVersion:z,kind:"fit"}),n.current=T,s.current=re!=null&&re.forceResetLayout?{}:te.layout.edge_routes??{},t.current=te.view,m(te.view),y(te.view_hash),$(te.diff),_(te.baseline??null),w(!1),D(z),X(R=>R+1),te.view},[e,t,s,i,r,n,a]);v.useEffect(()=>{let xe=!1;return(async()=>{var re;try{const Se=await ie();if(xe)return;const te=window.location.hash.startsWith("#view=")?decodeURIComponent(window.location.hash.slice(6)):null,G=((re=Se.status.tabs[0])==null?void 0:re.view_id)??null,T=te&&Se.status.tabs.some(E=>E.view_id===te)?te:G;T&&(h(T),await ue(T))}catch(Se){xe||u(Se instanceof Error?Se.message:"Failed to load workspace","error")}})(),()=>{xe=!0}},[ue,ie,u]),v.useEffect(()=>{const xe=setTimeout(()=>ne(!0),2e3),re=async te=>{var T;const G=ae.current;if(te.root_dir&&G&&te.root_dir!==G){ae.current=te.root_dir,r&&(r.current={}),i&&(i.current={}),n.current={},s.current={};const E=((T=te.status.tabs[0])==null?void 0:T.view_id)??null;return h(E),E?(window.location.hash=`view=${encodeURIComponent(E)}`,await ue(E)):(window.location.hash="",t.current=null,m(null),y(void 0),$(null),_(null)),u(`Server switched to project "${te.status.project_name}"`,"warning"),!0}return te.root_dir&&(ae.current=te.root_dir),!1},Se=Qp(te=>{(async()=>{var E;const G=await ie();if(await re(G))return;const T=e.current;if(te.type==="view_updated"&&T&&te.view_id===T&&te.origin==="external")await ue(T,{preserveViewport:!0}),u(`Agent updated view "${T}"`,"info");else if(te.type==="view_updated"&&te.origin==="external")u(`Agent updated "${te.view_id}"`,"info");else if(te.type==="threads_updated"&&te.origin==="external")u("Agent updated a thread","info");else if(te.type==="workspace_updated"&&te.origin==="external"&&!T&&(E=G.status.tabs[0])!=null&&E.view_id){const z=G.status.tabs[0].view_id;h(z),await ue(z)}})()},te=>{if(P(te),te){const G=fe.current;fe.current=!0,A(!0),G&&ie().then(T=>re(T)).catch(()=>{})}});return()=>{clearTimeout(xe),Se()}},[e,t,s,i,ue,ie,r,n,u]);const we=v.useCallback(async(xe,re)=>{const Se=(re==null?void 0:re.recordHistory)!==!1,te=t.current;Se&&te&&te.id===xe.id&&d(xe.id);const G=async()=>{try{const E=await Kp(xe,W.current);m(E.view),y(E.view_hash),$(E.diff),E.baseline!==void 0&&_(E.baseline),w(!1),await ie()}catch(E){throw E instanceof oa&&E.status===409?(w(!0),u("View changed on disk; reload to sync latest version.","warning")):u(E instanceof Error?E.message:"Failed to save view","error"),E}},T=se.current.then(G,G);return se.current=T.catch(()=>{}),T},[t,ie,d,u]),je=v.useCallback(async(xe,re)=>{n.current=structuredClone(xe.positions),s.current=structuredClone(xe.edgeRoutes),i&&(i.current={}),D(Se=>Se+1),X(Se=>Se+1),await V(re.id),JSON.stringify(xe.view)!==JSON.stringify(re)&&await we(xe.view,{recordHistory:!1})},[s,i,V,we,n]);return{snapshot:c,tabs:ee,activeViewId:p,setActiveViewId:h,activeView:x,setActiveView:m,viewDiff:b,setViewDiff:$,viewBaseline:k,allThreads:O,wsConnected:N,wsEverConnected:M,wsGraceExpired:q,conflictBanner:Q,layoutVersion:Z,setLayoutVersion:D,pendingViewportSyncRef:me,routingTick:J,setRoutingTick:X,loadWorkspaceMeta:ie,persistCurrentLayout:V,loadViewDetail:ue,persistView:we,applyHistoryEntry:je}}function Lt(e,t=40){const n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function c0(e){const t=new Set;if(!e)return t;for(const n of e.edges_added)t.add(n.id);for(const n of e.edges_modified)t.add(n.id);return t}function la(e,t,n="general"){if(!e)return[];if(e.nodes_added.some(a=>a.id===t))return[n==="er"?"+ Added entity":"+ Added box"];const s=e.nodes_modified.find(a=>a.id===t);if(!s)return[];const r=[],{changes:i}=s;if(i.title&&r.push(`Title: "${Lt(String(i.title.before??""),20)}" → "${Lt(String(i.title.after??""),24)}"`),i.kind&&r.push(`Kind: ${String(i.kind.before)} → ${String(i.kind.after)}`),i.shape&&r.push(`Shape: ${String(i.shape.before)} → ${String(i.shape.after)}`),i.summary&&r.push(i.summary.after?i.summary.before?"Updated summary":`Added summary: "${Lt(String(i.summary.after),28)}"`:"Removed summary"),i.status&&r.push(`Status: ${String(i.status.before)} → ${String(i.status.after)}`),i.locked&&r.push(i.locked.after?"Locked":"Unlocked"),i.entity_ref&&r.push(i.entity_ref.after?`Ref: ${String(i.entity_ref.after)}`:"Removed entity ref"),i.code_refs){const a=Array.isArray(i.code_refs.after)?i.code_refs.after.length:0,l=Array.isArray(i.code_refs.before)?i.code_refs.before.length:0;r.push(`Code refs: ${l} → ${a}`)}for(const a of s.sections_added)r.push(`+ Section "${a.heading}" (${a.items.length})`);for(const a of s.sections_removed)r.push(`- Section "${a.heading}"`);for(const a of s.sections_modified)if(a.heading_changed&&r.push(`Section "${a.heading_changed.before}" → "${a.heading_changed.after}"`),a.added_items.length===1&&a.removed_items.length===0)r.push(`+ ${a.heading}: ${Lt(a.added_items[0],32)}`);else if(a.removed_items.length===1&&a.added_items.length===0)r.push(`- ${a.heading}: ${Lt(a.removed_items[0],32)}`);else if(a.added_items.length>0||a.removed_items.length>0){const l=[];a.added_items.length>0&&l.push(`+${a.added_items.length}`),a.removed_items.length>0&&l.push(`-${a.removed_items.length}`),r.push(`${a.heading}: ${l.join(" / ")}`)}else a.reordered&&r.push(`${a.heading}: reordered`);for(const a of s.fields_added)r.push(`+ Attr ${a.name}${a.type?`: ${a.type}`:""}`);for(const a of s.fields_removed)r.push(`- Attr ${a.name}`);for(const a of s.fields_modified){const l=Object.keys(a.changes);l.includes("name")&&a.changes.name?r.push(`Attr ${String(a.changes.name.before)} → ${String(a.changes.name.after)}`):l.includes("nullable")&&l.length===1&&a.changes.nullable?r.push(`Attr ${a.name}: ${a.changes.nullable.after?"nullable ○":"NOT NULL *"}`):r.push(`~ Attr ${a.name} (${l.join(", ")})`)}return r}function ca(e,t){if(!e)return[];if(e.edges_added.some(i=>i.id===t))return["+ Added connection"];const n=e.edges_modified.find(i=>i.id===t);if(!n)return[];const s=[],{changes:r}=n;return r.label&&s.push(r.label.after?`Label: "${Lt(String(r.label.after),28)}"`:"Removed label"),(r.source||r.target)&&s.push("Reconnected / flipped direction"),r.style&&s.push(`Style: ${String(r.style.after)}`),(r.source_cardinality||r.target_cardinality)&&s.push("Updated cardinality"),r.relation_kind&&s.push(`Relation: ${String(r.relation_kind.after)}`),r.locked&&s.push(r.locked.after?"Locked edge":"Unlocked edge"),r.step&&s.push(r.step.after!==void 0?`Step #${String(r.step.after)}`:"Removed step"),s.length>0?s:["Modified connection"]}function d0(e,t,n){const s=t==null?void 0:t.nodes.find(i=>i.id===n),r=e.nodes.some(i=>i.id===n);if(s){const i=structuredClone(s);if(r)return{...e,nodes:e.nodes.map(c=>c.id===n?i:c)};const a=[...e.nodes,i],l=new Set(a.map(c=>c.id)),d=new Set(e.edges.map(c=>c.id)),u=[];for(const c of(t==null?void 0:t.edges)??[])(c.source===n||c.target===n)&&!d.has(c.id)&&l.has(c.source)&&l.has(c.target)&&u.push(structuredClone(c));return{...e,nodes:a,edges:[...e.edges,...u]}}return r?{...e,nodes:e.nodes.filter(i=>i.id!==n),edges:e.edges.filter(i=>i.source!==n&&i.target!==n)}:null}function u0(e,t,n){const s=t==null?void 0:t.edges.find(i=>i.id===n),r=e.edges.some(i=>i.id===n);if(s){const i=new Set(e.nodes.map(l=>l.id));if(!i.has(s.source)||!i.has(s.target))return null;const a=structuredClone(s);return r?{...e,edges:e.edges.map(l=>l.id===n?a:l)}:{...e,edges:[...e.edges,a]}}return r?{...e,edges:e.edges.filter(i=>i.id!==n)}:null}function f0({shape:e}){switch(e){case"decision":return o.jsx(Sl,{className:"h-3.5 w-3.5 text-sky-400 shrink-0"});case"terminal":return o.jsx(Nl,{className:"h-3.5 w-3.5 text-emerald-400 shrink-0"});case"store":return o.jsx(Zt,{className:"h-3.5 w-3.5 text-violet-400 shrink-0"});case"card":default:return o.jsx($l,{className:"h-3.5 w-3.5 text-slate-300 shrink-0"})}}function h0({diagramType:e,direction:t,canUndo:n,canRedo:s,onAddBox:r,onUndo:i,onRedo:a,onToggleDirection:l,onAutoLayout:d}){const[u,c]=v.useState(!1),f=v.useRef(null),p=e==="er",h=p?"Add Entity":"Add Box";return v.useEffect(()=>{if(!u)return;const x=g=>{f.current&&!f.current.contains(g.target)&&c(!1)},m=g=>{g.key==="Escape"&&c(!1)};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",m)}},[u]),o.jsxs("div",{role:"toolbar","aria-label":"Canvas actions",className:"nowheel absolute top-3 left-1/2 z-20 -translate-x-1/2 sm:top-auto sm:bottom-[15px] flex items-center gap-1 rounded-xl border border-slate-700 bg-slate-900/95 p-1 shadow-xl backdrop-blur-sm",children:[p?o.jsx("button",{type:"button",onClick:()=>r(),"aria-label":h,title:`${h} (N or right-click canvas)`,className:"flex h-7 w-7 items-center justify-center rounded-lg text-sky-400 hover:bg-slate-800 hover:text-sky-300 transition-colors",children:o.jsx(xt,{className:"h-4 w-4"})}):o.jsxs("div",{ref:f,className:"relative flex items-center",children:[o.jsxs("div",{className:"flex items-center rounded-lg overflow-hidden",children:[o.jsx("button",{type:"button",onClick:()=>{c(!1),r("card")},"aria-label":h,title:"Add Box (N or right-click canvas)",className:"flex h-7 w-7 items-center justify-center text-sky-400 hover:bg-slate-800 hover:text-sky-300 transition-colors",children:o.jsx(xt,{className:"h-4 w-4"})}),o.jsx("button",{type:"button",onClick:()=>c(x=>!x),"aria-label":"Add shape menu","aria-haspopup":"menu","aria-expanded":u,title:"Choose node shape to add",className:"flex h-7 w-5 items-center justify-center border-l border-slate-700/70 text-slate-400 hover:bg-slate-800 hover:text-slate-100 transition-colors",children:o.jsx(Ot,{className:"h-3 w-3"})})]}),u&&o.jsx("div",{role:"menu","aria-label":"Add node shape",className:"absolute top-full left-0 mt-2 sm:top-auto sm:bottom-full sm:mt-0 sm:mb-2 w-48 rounded-xl border border-slate-700 bg-slate-900/98 p-1 shadow-2xl backdrop-blur-md",children:Zn.map(x=>o.jsxs("button",{type:"button",role:"menuitem",title:x.hint,onClick:()=>{c(!1),r(x.shape)},className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 transition-colors",children:[o.jsx(f0,{shape:x.shape}),o.jsx("span",{children:x.label})]},x.shape))})]}),o.jsx("div",{className:"mx-0.5 h-4 w-px bg-slate-700/80"}),o.jsx("button",{type:"button",disabled:!n,onClick:i,title:"Undo (Ctrl+Z)","aria-label":"Undo",className:"flex h-7 w-7 items-center justify-center rounded-lg text-slate-300 hover:bg-slate-800 hover:text-slate-100 disabled:opacity-30 disabled:pointer-events-none transition-colors",children:o.jsx(kl,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",disabled:!s,onClick:a,title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo",className:"flex h-7 w-7 items-center justify-center rounded-lg text-slate-300 hover:bg-slate-800 hover:text-slate-100 disabled:opacity-30 disabled:pointer-events-none transition-colors",children:o.jsx(wl,{className:"h-3.5 w-3.5"})}),o.jsx("div",{className:"mx-0.5 h-4 w-px bg-slate-700/80"}),o.jsxs("button",{type:"button",onClick:l,title:"Toggle diagram flow direction (TB / LR)","aria-label":`Toggle layout direction (${t})`,className:"inline-flex h-7 items-center gap-1 rounded-lg px-2 text-[11px] font-mono text-slate-300 hover:bg-slate-800 hover:text-slate-100 transition-colors",children:[o.jsx(_l,{className:"h-3.5 w-3.5 text-slate-400"}),o.jsx("span",{children:t})]}),o.jsxs("button",{type:"button",onClick:d,title:"Reset manual positions & routes and run ELK auto-layout (R)","aria-label":"Auto-Layout",className:"inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-[11px] font-medium text-slate-300 hover:bg-slate-800 hover:text-slate-100 transition-colors",children:[o.jsx(jl,{className:"h-3.5 w-3.5 text-slate-400"}),o.jsx("span",{className:"hidden md:inline",children:"Auto-Layout"})]})]})}const p0=[{id:"all",label:"All"},{id:"view",label:"Views"},{id:"node",label:"Nodes"},{id:"edge",label:"Edges"},{id:"thread",label:"Threads"}];function m0(e,t){if(t.length===0)return e;const n=new Set(t);return Array.from(e).map((s,r)=>n.has(r)?o.jsx("mark",{className:"rounded-sm bg-sky-500/25 px-0.5 text-sky-200 font-semibold",children:s},r):o.jsx("span",{children:s},r))}function x0({item:e}){return e.kind==="view"?e.badge==="ER View"?o.jsx(Zt,{className:"h-4 w-4 shrink-0 text-emerald-400"}):o.jsx(Fs,{className:"h-4 w-4 shrink-0 text-sky-400"}):e.kind==="node"?o.jsx(Ml,{className:"h-4 w-4 shrink-0 text-sky-300"}):e.kind==="edge"?o.jsx(Cl,{className:"h-4 w-4 shrink-0 text-violet-400"}):o.jsx(Us,{className:"h-4 w-4 shrink-0 text-amber-400"})}function g0({open:e,loading:t,items:n,onClose:s,onSelect:r}){const[i,a]=v.useState(""),[l,d]=v.useState("all"),[u,c]=v.useState(0),f=v.useRef(null),p=v.useRef(null),h=v.useMemo(()=>i0(n,i,l,40),[n,i,l]);if(v.useEffect(()=>{if(!e){a(""),d("all"),c(0);return}c(0);const m=requestAnimationFrame(()=>{var g;(g=f.current)==null||g.focus()});return()=>cancelAnimationFrame(m)},[e]),v.useEffect(()=>{if(!e)return;const m=g=>{g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),s())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,s]),v.useEffect(()=>{c(0)},[i,l]),v.useEffect(()=>{if(!e||!p.current)return;const m=p.current.querySelector(`[data-search-index="${u}"]`);m==null||m.scrollIntoView({block:"nearest"})},[u,e,h.length]),!e)return null;const x=m=>{if(m.key==="Escape"){m.preventDefault(),m.stopPropagation(),s();return}if(m.key==="ArrowDown"){m.preventDefault(),h.length>0&&c(g=>(g+1)%h.length);return}if(m.key==="ArrowUp"){m.preventDefault(),h.length>0&&c(g=>(g-1+h.length)%h.length);return}if(m.key==="Enter"){const g=h[u]??h[0];g&&(m.preventDefault(),r(g.item))}};return o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Quick search",onClick:m=>{m.target===m.currentTarget&&s()},className:"fixed inset-0 z-50 flex items-start justify-center bg-black/65 px-4 pt-[11vh] backdrop-blur-sm",children:o.jsxs("div",{onKeyDown:x,className:"flex w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-slate-700 bg-slate-900 shadow-2xl",children:[o.jsxs("div",{className:"flex items-center gap-2.5 border-b border-slate-800 px-4 py-3",children:[o.jsx(Rs,{className:"h-4 w-4 shrink-0 text-sky-400"}),o.jsx("input",{ref:f,autoFocus:!0,type:"text",value:i,onChange:m=>a(m.target.value),placeholder:"Search views, boxes, attributes, edges, or threads...","aria-label":"Search workspace input",className:"w-full bg-transparent text-sm text-slate-100 placeholder:text-slate-500 focus:outline-none"}),i&&o.jsx("button",{type:"button",onClick:()=>a(""),"aria-label":"Clear search query",className:"rounded p-1 text-slate-400 hover:bg-slate-800 hover:text-slate-100",children:o.jsx($t,{className:"h-3.5 w-3.5"})}),o.jsx("kbd",{className:"hidden sm:inline-block rounded border border-slate-700 bg-slate-950 px-1.5 py-0.5 font-mono text-[10px] text-slate-400",children:"Esc"})]}),o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-slate-800/80 bg-slate-950/50 px-4 py-2",children:[o.jsx("div",{className:"flex items-center gap-1 overflow-x-auto",children:p0.map(m=>{const g=l===m.id;return o.jsx("button",{type:"button",onClick:()=>d(m.id),className:`rounded-md px-2.5 py-0.5 text-[11px] font-medium transition-colors ${g?"border border-sky-500/40 bg-sky-500/20 text-sky-200":"border border-transparent text-slate-400 hover:bg-slate-800 hover:text-slate-200"}`,children:m.label},m.id)})}),o.jsx("span",{className:"shrink-0 font-mono text-[10px] text-slate-500",children:t?"Indexing…":`${h.length} result${h.length===1?"":"s"}`})]}),o.jsx("div",{ref:p,className:"max-h-[54vh] overflow-y-auto p-1.5",children:t&&h.length===0?o.jsx("div",{className:"px-4 py-10 text-center text-xs text-slate-400",children:"Loading views and workspace index…"}):h.length===0?o.jsx("div",{className:"px-4 py-10 text-center text-xs text-slate-400",children:"No matching views, boxes, attributes, edges, or threads."}):h.map((m,g)=>{const{item:y,titleIndices:b,matchedSubEntry:$}=m,k=g===u,_=$??y.subtitle;return o.jsxs("button",{type:"button","data-search-index":g,onMouseEnter:()=>c(g),onClick:()=>r(y),className:`flex w-full items-center justify-between gap-3 rounded-xl px-3 py-2 text-left transition-colors ${k?"bg-slate-800 text-slate-50":"text-slate-200 hover:bg-slate-800/60"}`,children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[o.jsx(x0,{item:y}),o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"truncate text-xs font-medium",children:m0(y.title,b)}),o.jsx("span",{className:"shrink-0 rounded border border-slate-700 bg-slate-950/70 px-1.5 py-0.2 font-mono text-[10px] text-slate-400",children:y.badge})]}),_&&o.jsx("div",{className:"truncate font-mono text-[11px] text-slate-400 mt-0.5",children:_})]})]}),y.viewTitle&&y.kind!=="view"&&o.jsx("span",{className:"shrink-0 rounded-md border border-slate-700/80 bg-slate-950/60 px-2 py-0.5 text-[10px] text-slate-400",children:y.viewTitle}),y.kind==="view"&&y.isCurrentView&&o.jsx("span",{className:"shrink-0 rounded-md border border-sky-500/40 bg-sky-500/15 px-2 py-0.5 text-[10px] font-medium text-sky-300",children:"current"})]},y.id)})}),o.jsxs("div",{className:"flex items-center justify-between border-t border-slate-800 bg-slate-950/60 px-4 py-1.5 text-[10px] text-slate-500",children:[o.jsx("span",{children:"↑↓ Navigate · Enter Jump · Esc Close"}),o.jsx("span",{children:"Tab / Shift+Tab cycles tabs"})]})]})})}function da({x:e,y:t,header:n,items:s,onClose:r}){const i=v.useRef(null),[a,l]=v.useState(null);v.useEffect(()=>{l(null)},[e,t]),v.useEffect(()=>{const f=m=>{i.current&&!i.current.contains(m.target)&&r()},p=m=>{i.current&&!i.current.contains(m.target)&&r()},h=()=>{r()},x=m=>{m.key==="Escape"&&r()};return window.addEventListener("pointerdown",f,!0),window.addEventListener("mousedown",f,!0),window.addEventListener("wheel",p,{capture:!0,passive:!0}),window.addEventListener("blur",h),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",f,!0),window.removeEventListener("mousedown",f,!0),window.removeEventListener("wheel",p,!0),window.removeEventListener("blur",h),window.removeEventListener("keydown",x)}},[r]);const d=Math.min(e,Math.max(8,window.innerWidth-230)),u=Math.min(t,Math.max(8,window.innerHeight-Math.min(360,s.length*34+40))),c=d+480>window.innerWidth;return o.jsxs("div",{ref:i,style:{left:d,top:u},onContextMenu:f=>f.preventDefault(),className:"fixed z-50 min-w-[215px] rounded-xl border border-slate-700 bg-slate-900/95 p-1.5 shadow-2xl backdrop-blur-md",children:[n&&o.jsx("div",{className:"mb-1 border-b border-slate-800 px-2.5 py-1 text-[10px] font-mono uppercase tracking-wider text-slate-400 truncate",children:n}),s.map(f=>{const p=!!(f.children&&f.children.length>0),h=p&&a===f.id;return o.jsxs("div",{className:"relative",onMouseEnter:()=>{l(p&&!f.disabled?f.id:null)},children:[f.dividerBefore&&o.jsx("div",{className:"my-1 border-t border-slate-800"}),o.jsxs("button",{type:"button",disabled:f.disabled,onClick:()=>{var x;if(!f.disabled){if(p){l(f.id);return}r(),(x=f.onSelect)==null||x.call(f)}},className:`flex w-full items-center justify-between gap-3 rounded-lg px-2.5 py-1.5 text-left text-xs transition-colors ${f.disabled?"cursor-not-allowed text-slate-600":f.danger?"text-rose-300 hover:bg-rose-500/15 hover:text-rose-200":h?"bg-slate-800 text-slate-50":"text-slate-200 hover:bg-slate-800 hover:text-slate-50"}`,children:[o.jsx("span",{className:"truncate",children:f.label}),p?o.jsx(an,{className:"h-3.5 w-3.5 shrink-0 text-slate-400"}):f.shortcut&&o.jsx("span",{className:"font-mono text-[10px] text-slate-500",children:f.shortcut})]}),h&&f.children&&o.jsx("div",{onContextMenu:x=>x.preventDefault(),className:`absolute top-0 z-50 ${c?"right-full pr-1":"left-full pl-1"}`,children:o.jsx("div",{className:"min-w-[190px] max-w-[260px] max-h-[260px] overflow-y-auto rounded-xl border border-slate-700 bg-slate-900/95 p-1.5 shadow-2xl backdrop-blur-md",children:f.children.map(x=>o.jsx("button",{type:"button",disabled:x.disabled,onClick:()=>{var m;x.disabled||(r(),(m=x.onSelect)==null||m.call(x))},className:`flex w-full items-center justify-between gap-3 rounded-lg px-2.5 py-1.5 text-left text-xs transition-colors ${x.disabled?"cursor-not-allowed text-slate-600":x.danger?"text-rose-300 hover:bg-rose-500/15 hover:text-rose-200":"text-slate-200 hover:bg-slate-800 hover:text-slate-50"}`,children:o.jsx("span",{className:"truncate",children:x.label})},x.id))})})]},f.id)})]})}const Wo=[{value:"1",label:"1 (mandatory one)"},{value:"0..1",label:"0..1 (optional one)"},{value:"1..*",label:"1..* (mandatory many)"},{value:"0..*",label:"0..* (optional many)"}];function y0({diagramType:e,sourceTitle:t,targetTitle:n,onCancel:s,onConfirm:r}){const[i,a]=v.useState(""),[l,d]=v.useState(""),[u,c]=v.useState("solid"),[f,p]=v.useState("1"),[h,x]=v.useState("0..*"),[m,g]=v.useState("association"),y=b=>{if(b.preventDefault(),e==="er"){r({label:i.trim()||void 0,style:"solid",relation_kind:m,...m!=="subtype"?{source_cardinality:f,target_cardinality:h}:{}});return}const $=l.trim()?Number(l.trim()):void 0;r({label:i.trim()||void 0,step:$!==void 0&&Number.isInteger($)&&$>0?$:void 0,style:u})};return o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":e==="er"?"Connect Entities":"Connect Nodes",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",children:o.jsxs("div",{className:"w-full max-w-sm rounded-xl border border-slate-700 bg-slate-900 p-4 shadow-2xl",children:[o.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[o.jsx("h3",{className:"text-sm font-semibold text-slate-100",children:e==="er"?"Connect Entities":"Connect Nodes"}),o.jsx("button",{type:"button",onClick:s,className:"rounded p-1 text-slate-400 hover:bg-slate-800 hover:text-slate-100",children:o.jsx($t,{className:"h-4 w-4"})})]}),o.jsxs("p",{className:"mb-3 text-xs text-slate-400",children:[o.jsx("span",{className:"font-medium text-slate-200",children:t})," → ",o.jsx("span",{className:"font-medium text-slate-200",children:n})]}),o.jsxs("form",{onSubmit:y,className:"space-y-3",children:[e==="er"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"flex flex-wrap gap-1.5",children:[{label:"1 : 0..*",s:"1",t:"0..*",k:"association"},{label:"1 : 1..*",s:"1",t:"1..*",k:"association"},{label:"1 : 0..1",s:"1",t:"0..1",k:"association"},{label:"0..* : 0..*",s:"0..*",t:"0..*",k:"association"},{label:"Subtype (is-a)",s:"1",t:"1",k:"subtype"}].map(b=>o.jsx("button",{type:"button",onClick:()=>{p(b.s),x(b.t),g(b.k)},className:`rounded border px-2 py-0.5 text-[11px] font-mono ${m===b.k&&(b.k==="subtype"||f===b.s&&h===b.t)?"border-emerald-500 bg-emerald-500/15 text-emerald-200":"border-slate-700 bg-slate-950 text-slate-300 hover:bg-slate-800"}`,children:b.label},b.label))}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Relationship Kind"}),o.jsxs("select",{value:m,onChange:b=>g(b.target.value),className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 focus:border-sky-500 focus:outline-none",children:[o.jsx("option",{value:"association",children:"Association (FK)"}),o.jsx("option",{value:"identifying",children:"Identifying (PK+FK)"}),o.jsx("option",{value:"subtype",children:"Subtype / Inheritance (is-a)"})]})]}),m!=="subtype"&&o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsxs("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:[t," side"]}),o.jsx("select",{value:f,onChange:b=>p(b.target.value),className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-2 py-1.5 text-xs text-slate-100 focus:border-sky-500 focus:outline-none",children:Wo.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:[n," side"]}),o.jsx("select",{value:h,onChange:b=>x(b.target.value),className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-2 py-1.5 text-xs text-slate-100 focus:border-sky-500 focus:outline-none",children:Wo.map(b=>o.jsx("option",{value:b.value,children:b.label},b.value))})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Verb / Label (optional)"}),o.jsx("input",{type:"text",value:i,onChange:b=>a(b.target.value),placeholder:"e.g. places, belongs to, assigned to",className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-1.5 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none",autoFocus:!0})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Label (optional)"}),o.jsx("input",{type:"text",value:i,onChange:b=>a(b.target.value),placeholder:"e.g. validates, writes to, calls",className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-1.5 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none",autoFocus:!0})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Step # (optional)"}),o.jsx("input",{type:"number",min:1,value:l,onChange:b=>d(b.target.value),placeholder:"1, 2, 3...",className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-1.5 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Line Style"}),o.jsxs("select",{value:u,onChange:b=>c(b.target.value==="dashed"?"dashed":"solid"),className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 focus:border-sky-500 focus:outline-none",children:[o.jsx("option",{value:"solid",children:"Solid"}),o.jsx("option",{value:"dashed",children:"Dashed"})]})]})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[o.jsx("button",{type:"button",onClick:s,className:"rounded-lg border border-slate-700 px-3 py-1.5 text-xs font-medium text-slate-300 hover:bg-slate-800",children:"Cancel"}),o.jsx("button",{type:"submit",className:"rounded-lg bg-sky-500 px-3.5 py-1.5 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:"Create Relationship"})]})]})]})})}function b0({activeView:e,selectedEdge:t,edgeRoute:n,onSaveEdge:s,onDeleteEdge:r,onUpdateEdgeRoute:i,onFlipEdge:a}){var c;const[l,d]=v.useState(t);if(v.useEffect(()=>{d(t?structuredClone(t):null)},[t]),!l)return null;const u=async f=>{d(f),await s(f)};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-slate-800 bg-slate-950/60 px-3 py-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.locked?o.jsx(Un,{className:"h-3.5 w-3.5 text-violet-400"}):o.jsx(Hs,{className:"h-3.5 w-3.5 text-slate-400"}),o.jsx("span",{className:"font-medium text-slate-200",children:l.locked?"Locked Edge":"Unlocked Edge"})]}),o.jsx("button",{type:"button",onClick:()=>void u({...l,locked:!l.locked}),className:`rounded-md px-2.5 py-1 text-xs font-medium ${l.locked?"bg-violet-500/20 text-violet-200 border border-violet-500/40 hover:bg-violet-500/30":"border border-slate-700 bg-slate-800 text-slate-200 hover:bg-slate-700"}`,children:l.locked?"Unlock":"Lock"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Label"}),o.jsx("input",{type:"text",value:l.label??"",disabled:!!l.locked,onChange:f=>d({...l,label:f.target.value}),onBlur:()=>{var h;const f=(h=l.label)==null?void 0:h.trim(),p={...l};f?p.label=f:delete p.label,u(p)},className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Step #"}),o.jsx("input",{type:"number",min:1,value:l.step??"",disabled:!!l.locked,onChange:f=>{const p=f.target.value.trim(),h={...l};p?h.step=Number(p):delete h.step,d(h)},onBlur:()=>void u(l),className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Style"}),o.jsxs("select",{value:l.style??"solid",disabled:!!l.locked,onChange:f=>void u({...l,style:f.target.value==="dashed"?"dashed":"solid"}),className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none",children:[o.jsx("option",{value:"solid",children:"solid"}),o.jsx("option",{value:"dashed",children:"dashed"})]})]})]}),((e==null?void 0:e.diagram_type)==="er"||l.source_cardinality||l.target_cardinality||l.relation_kind)&&o.jsxs("div",{className:"space-y-2.5 rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[o.jsx("div",{className:"text-xs font-semibold text-emerald-300",children:"ER Relationship"}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] text-slate-400 mb-1",children:"Kind"}),o.jsxs("select",{value:l.relation_kind??"association",disabled:!!l.locked,onChange:f=>void u({...l,relation_kind:f.target.value}),className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2 py-1.5 text-xs text-slate-100 disabled:opacity-50",children:[o.jsx("option",{value:"association",children:"Association (FK)"}),o.jsx("option",{value:"identifying",children:"Identifying (PK+FK)"}),o.jsx("option",{value:"subtype",children:"Subtype (is-a)"})]})]}),l.relation_kind!=="subtype"&&o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsxs("label",{className:"block text-[11px] text-slate-400 mb-1",children:["Source (",l.source,")"]}),o.jsxs("select",{value:l.source_cardinality??"1",disabled:!!l.locked,onChange:f=>void u({...l,source_cardinality:f.target.value}),className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2 py-1.5 text-xs text-slate-100 disabled:opacity-50",children:[o.jsx("option",{value:"1",children:"1 (mandatory)"}),o.jsx("option",{value:"0..1",children:"0..1 (optional)"}),o.jsx("option",{value:"1..*",children:"1..* (many mand.)"}),o.jsx("option",{value:"0..*",children:"0..* (many opt.)"})]})]}),o.jsxs("div",{children:[o.jsxs("label",{className:"block text-[11px] text-slate-400 mb-1",children:["Target (",l.target,")"]}),o.jsxs("select",{value:l.target_cardinality??"0..*",disabled:!!l.locked,onChange:f=>void u({...l,target_cardinality:f.target.value}),className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2 py-1.5 text-xs text-slate-100 disabled:opacity-50",children:[o.jsx("option",{value:"1",children:"1 (mandatory)"}),o.jsx("option",{value:"0..1",children:"0..1 (optional)"}),o.jsx("option",{value:"1..*",children:"1..* (many mand.)"}),o.jsx("option",{value:"0..*",children:"0..* (many opt.)"})]})]})]})]}),o.jsxs("div",{className:"space-y-2.5 rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-slate-200",children:"Line Routing"}),o.jsxs("button",{type:"button",disabled:!!l.locked,onClick:()=>a(l.id),className:"inline-flex items-center gap-1 rounded border border-slate-700 bg-slate-800 px-2 py-0.5 text-[11px] text-slate-200 hover:bg-slate-700 disabled:opacity-40",children:[o.jsx(El,{className:"h-3 w-3"}),"Flip A ↔ B"]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] text-slate-400 mb-1",children:"Source Side"}),o.jsxs("select",{value:(n==null?void 0:n.source_handle)??"",onChange:f=>i(l.id,{source_handle:f.target.value?f.target.value:void 0}),className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2 py-1 text-xs text-slate-100",children:[o.jsx("option",{value:"",children:"Auto"}),o.jsx("option",{value:"top",children:"Top"}),o.jsx("option",{value:"right",children:"Right"}),o.jsx("option",{value:"bottom",children:"Bottom"}),o.jsx("option",{value:"left",children:"Left"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] text-slate-400 mb-1",children:"Target Side"}),o.jsxs("select",{value:(n==null?void 0:n.target_handle)??"",onChange:f=>i(l.id,{target_handle:f.target.value?f.target.value:void 0}),className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2 py-1 text-xs text-slate-100",children:[o.jsx("option",{value:"",children:"Auto"}),o.jsx("option",{value:"top",children:"Top"}),o.jsx("option",{value:"right",children:"Right"}),o.jsx("option",{value:"bottom",children:"Bottom"}),o.jsx("option",{value:"left",children:"Left"})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-slate-400",children:[o.jsxs("span",{children:["Bend points: ",((c=n==null?void 0:n.waypoints)==null?void 0:c.length)??0," (or drag on canvas)"]}),o.jsx("button",{type:"button",onClick:()=>i(l.id,null),className:"text-sky-400 hover:underline",children:"Reset Route"})]})]}),o.jsxs("button",{type:"button",disabled:!!l.locked,onClick:()=>void r(l.id),className:"inline-flex w-full items-center justify-center gap-1.5 rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-xs font-medium text-rose-300 hover:bg-rose-500/20 disabled:opacity-40",children:[o.jsx(sn,{className:"h-3.5 w-3.5"}),l.locked?"Unlock edge to delete":"Delete Edge"]})]})}function v0({activeView:e,selectedNode:t,onJumpToTarget:n,onCopyText:s}){const[r,i]=v.useState([]),[a,l]=v.useState(!1);v.useEffect(()=>{if(!t.entity_ref){i([]);return}let u=!1;return l(!0),Yp(t.entity_ref).then(c=>{u||i(c.occurrences)}).catch(()=>{u||i([])}).finally(()=>{u||l(!1)}),()=>{u=!0}},[t.entity_ref]);const d=r.filter(u=>!(u.view_id===(e==null?void 0:e.id)&&u.node_id===t.id));return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-200",children:[o.jsx($s,{className:"h-3.5 w-3.5 text-sky-400"}),"Also In (Cross-Tab Links)"]}),t.entity_ref?a?o.jsx("p",{className:"text-xs text-slate-500",children:"Scanning diagrams..."}):o.jsxs("div",{className:"space-y-1.5",children:[d.map(u=>o.jsxs("button",{type:"button",onClick:()=>n(u.view_id,"node",u.node_id,"spec"),className:"flex w-full items-center justify-between rounded-lg border border-slate-800 bg-slate-950/70 px-3 py-2 text-left hover:border-sky-500/50 hover:bg-slate-800/70 transition-colors",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs font-medium text-slate-100",children:u.view_title}),o.jsxs("div",{className:"text-[11px] font-mono text-slate-400",children:[u.node_title," (",u.kind,")"]})]}),o.jsx(Ws,{className:"h-3.5 w-3.5 text-sky-400"})]},`${u.view_id}:${u.node_id}`)),d.length===0&&o.jsxs("p",{className:"text-xs text-slate-500",children:["No other views reference"," ",o.jsx("code",{className:"font-mono text-slate-300",children:t.entity_ref})," ","yet."]})]}):o.jsxs("p",{className:"text-xs text-slate-500",children:["Set an ",o.jsx("code",{className:"font-mono",children:"entity_ref"})," in the Spec tab to link this concept across multiple diagrams."]})]}),o.jsxs("div",{className:"border-t border-slate-800 pt-3",children:[o.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-200",children:[o.jsx(Ns,{className:"h-3.5 w-3.5 text-emerald-400"}),"Code References"]}),!t.code_refs||t.code_refs.length===0?o.jsxs("p",{className:"text-xs text-slate-500",children:["No code files linked yet. The agent links source files via"," ",o.jsx("code",{className:"font-mono",children:"sync_code_refs"})," after implementation."]}):o.jsx("div",{className:"space-y-1.5",children:t.code_refs.map((u,c)=>{const f=u.symbol?`${u.path}:${u.symbol}`:u.path;return o.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-slate-800 bg-slate-950/70 px-3 py-2",children:[o.jsx("span",{className:"truncate font-mono text-xs text-emerald-300",children:f}),o.jsx("button",{type:"button",onClick:()=>void s(u.path,u.path),className:"shrink-0 rounded p-1 text-slate-400 hover:bg-slate-800 hover:text-slate-100",title:"Copy file path",children:o.jsx(Ks,{className:"h-3.5 w-3.5"})})]},`${u.path}-${c}`)})})]})]})}const k0=["draft","needs_input","approved","implemented","drifted"];function w0({activeView:e,selectedNode:t,onSaveNode:n,onDeleteNode:s}){var u;const[r,i]=v.useState(t),[a,l]=v.useState(null);if(v.useEffect(()=>{i(t?structuredClone(t):null),l(null)},[t]),!r)return null;const d=async c=>{i(c),await n(c)};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-slate-800 bg-slate-950/60 px-3 py-2",children:[o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.locked?o.jsx(Un,{className:"h-3.5 w-3.5 text-violet-400"}):o.jsx(Hs,{className:"h-3.5 w-3.5 text-slate-400"}),o.jsx("span",{className:"font-medium text-slate-200",children:r.locked?"Locked (agent read-only)":"Unlocked"})]}),o.jsx("button",{type:"button",onClick:()=>void d({...r,locked:!r.locked}),className:`rounded-md px-2.5 py-1 text-xs font-medium ${r.locked?"bg-violet-500/20 text-violet-200 border border-violet-500/40":"bg-slate-800 text-slate-300 border border-slate-700 hover:bg-slate-700"}`,children:r.locked?"Unlock":"Lock"})]}),((e==null?void 0:e.diagram_type)??"general")!=="er"&&(((u=r.fields)==null?void 0:u.length)??0)===0&&o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Shape"}),o.jsx("div",{role:"group","aria-label":"Node shape",className:"grid grid-cols-4 gap-1",children:Zn.map(c=>{const f=(r.shape??"card")===c.shape;return o.jsx("button",{type:"button",disabled:r.locked,"aria-pressed":f,title:c.hint,onClick:()=>{const p={...r};c.shape==="card"?delete p.shape:p.shape=c.shape,d(p)},className:`rounded-md border px-1.5 py-1 text-[11px] font-medium transition-colors disabled:opacity-50 ${f?"border-sky-500/60 bg-sky-500/20 text-sky-300":"border-slate-700 bg-slate-950 text-slate-300 hover:bg-slate-800"}`,children:c.shortLabel},c.shape)})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Kind"}),o.jsx("input",{type:"text",value:r.kind,disabled:r.locked,onChange:c=>i({...r,kind:c.target.value}),onBlur:()=>{r.kind.trim()&&d({...r,kind:r.kind.trim()})},className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Status"}),o.jsx("select",{value:r.status,disabled:r.locked,onChange:c=>void d({...r,status:c.target.value}),className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none",children:k0.map(c=>o.jsx("option",{value:c,children:c},c))})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Title"}),o.jsx("input",{type:"text",value:r.title,disabled:r.locked,onChange:c=>i({...r,title:c.target.value}),onBlur:()=>{r.title.trim()&&d({...r,title:r.title.trim()})},className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Summary"}),o.jsx("textarea",{rows:2,value:r.summary??"",disabled:r.locked,onChange:c=>i({...r,summary:c.target.value}),onBlur:()=>{var p;const c=(p=r.summary)==null?void 0:p.trim(),f={...r};c?f.summary=c:delete f.summary,d(f)},placeholder:"Optional concise role summary...",className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 text-xs text-slate-100 placeholder:text-slate-600 disabled:opacity-50 focus:border-sky-500 focus:outline-none"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-[11px] font-medium text-slate-400 mb-1",children:"Shared Cross-Tab Key (`entity_ref`)"}),o.jsx("input",{type:"text",value:r.entity_ref??"",disabled:r.locked,onChange:c=>{const f=c.target.value;i({...r,entity_ref:f}),f.trim()&&!Is.test(f.trim())?l("Use snake_case (a-z, 0-9, _)"):l(null)},onBlur:()=>{var f;const c=((f=r.entity_ref)==null?void 0:f.trim())??"";if(!c){const p={...r};delete p.entity_ref,l(null),d(p);return}if(!Is.test(c)){l("Use snake_case (a-z, 0-9, _)");return}l(null),d({...r,entity_ref:c})},placeholder:"e.g. design_storage",className:"w-full rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1.5 font-mono text-xs text-slate-100 placeholder:text-slate-600 disabled:opacity-50 focus:border-sky-500 focus:outline-none"}),a&&o.jsx("p",{className:"mt-1 text-[11px] text-rose-400",children:a})]}),((e==null?void 0:e.diagram_type)==="er"||r.fields&&r.fields.length>0)&&o.jsxs("div",{className:"space-y-2.5 border-t border-slate-800 pt-3",children:[o.jsxs("datalist",{id:"redlinify-sql-types",children:[o.jsx("option",{value:"uuid"}),o.jsx("option",{value:"bigint"}),o.jsx("option",{value:"integer"}),o.jsx("option",{value:"varchar(255)"}),o.jsx("option",{value:"text"}),o.jsx("option",{value:"boolean"}),o.jsx("option",{value:"timestamptz"}),o.jsx("option",{value:"date"}),o.jsx("option",{value:"decimal(10,2)"}),o.jsx("option",{value:"jsonb"})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs font-semibold text-emerald-300",children:[o.jsx(Zt,{className:"h-3.5 w-3.5"}),"Entity Attributes"]}),!r.locked&&o.jsxs("button",{type:"button",onClick:()=>{var f;const c={id:`fld_${Date.now().toString(36).slice(-5)}`,name:`col_${(((f=r.fields)==null?void 0:f.length)??0)+1}`,type:"varchar(255)",nullable:!1};d({...r,fields:[...r.fields??[],c]})},className:"inline-flex items-center gap-1 rounded border border-slate-700 bg-slate-800 px-2 py-1 text-[11px] text-slate-200 hover:bg-slate-700",children:[o.jsx(xt,{className:"h-3 w-3"}),"Add Attribute"]})]}),(r.fields??[]).map((c,f)=>{const p=r.fields??[],h=x=>{const m=p.map((g,y)=>y===f?{...g,...x}:g);d({...r,fields:m})};return o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-2 space-y-1.5",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("input",{type:"text",value:c.name,disabled:r.locked,onChange:x=>{const m=[...p];m[f]={...c,name:x.target.value},i({...r,fields:m})},onBlur:()=>{c.name.trim()&&d(r)},placeholder:"column_name",className:"flex-1 min-w-0 rounded border border-slate-700 bg-slate-900 px-2 py-1 font-mono text-[11px] text-slate-100 disabled:opacity-50 focus:border-sky-500 focus:outline-none"}),o.jsx("input",{type:"text",list:"redlinify-sql-types",value:c.type??"",disabled:r.locked,onChange:x=>{const m=[...p],g=x.target.value,y={...c};g?y.type=g:delete y.type,m[f]=y,i({...r,fields:m})},onBlur:()=>{var y;const x=(y=c.type)==null?void 0:y.trim(),m=[...p],g={...c};x?g.type=x:delete g.type,m[f]=g,d({...r,fields:m})},placeholder:"type",className:"w-24 rounded border border-slate-700 bg-slate-900 px-2 py-1 font-mono text-[11px] text-slate-300 disabled:opacity-50 focus:border-sky-500 focus:outline-none"}),!r.locked&&o.jsx("button",{type:"button",onClick:()=>{const x=p.filter((m,g)=>g!==f);d({...r,fields:x})},className:"rounded p-1 text-slate-500 hover:bg-slate-800 hover:text-rose-400",title:"Remove attribute",children:o.jsx(sn,{className:"h-3 w-3"})})]}),o.jsxs("div",{className:"flex items-center justify-between gap-1",children:[o.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[o.jsx("button",{type:"button",disabled:r.locked,onClick:()=>h({nullable:!c.nullable}),title:"Toggle Mandatory (*) vs Nullable (○)",className:`rounded border px-1.5 py-0.5 font-mono text-[10px] font-semibold ${c.nullable?"border-slate-700 bg-slate-900 text-slate-400":"border-rose-500/40 bg-rose-500/15 text-rose-300"}`,children:c.nullable?"○ NULL":"* REQ"}),o.jsx("button",{type:"button",disabled:r.locked,onClick:()=>h({pk:!c.pk}),className:`rounded border px-1.5 py-0.5 font-mono text-[10px] font-semibold ${c.pk?"border-amber-500/40 bg-amber-500/20 text-amber-300":"border-slate-800 bg-slate-900 text-slate-500"}`,children:"PK"}),o.jsx("button",{type:"button",disabled:r.locked,onClick:()=>h({fk:!c.fk}),className:`rounded border px-1.5 py-0.5 font-mono text-[10px] font-semibold ${c.fk?"border-sky-500/40 bg-sky-500/20 text-sky-300":"border-slate-800 bg-slate-900 text-slate-500"}`,children:"FK"}),o.jsx("button",{type:"button",disabled:r.locked,onClick:()=>h({unique:!c.unique}),className:`rounded border px-1.5 py-0.5 font-mono text-[10px] font-semibold ${c.unique?"border-violet-500/40 bg-violet-500/20 text-violet-300":"border-slate-800 bg-slate-900 text-slate-500"}`,children:"UQ"}),o.jsx("button",{type:"button",disabled:r.locked,onClick:()=>h({indexed:!c.indexed}),className:`rounded border px-1.5 py-0.5 font-mono text-[10px] font-semibold ${c.indexed?"border-slate-500/50 bg-slate-700/50 text-slate-200":"border-slate-800 bg-slate-900 text-slate-500"}`,children:"IDX"})]}),!r.locked&&o.jsxs("div",{className:"flex items-center gap-0.5",children:[o.jsx("button",{type:"button",disabled:f===0,onClick:()=>{const x=[...p],[m]=x.splice(f,1);m&&(x.splice(f-1,0,m),d({...r,fields:x}))},className:"rounded p-1 text-slate-500 hover:bg-slate-800 disabled:opacity-30",children:o.jsx(Br,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",disabled:f===p.length-1,onClick:()=>{const x=[...p],[m]=x.splice(f,1);m&&(x.splice(f+1,0,m),d({...r,fields:x}))},className:"rounded p-1 text-slate-500 hover:bg-slate-800 disabled:opacity-30",children:o.jsx(Zr,{className:"h-3 w-3"})})]})]})]},c.id)})]}),o.jsxs("div",{className:"space-y-2.5 border-t border-slate-800 pt-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold text-slate-200",children:"Box Sections"}),!r.locked&&o.jsxs("button",{type:"button",onClick:()=>{const c={id:`sec_${Date.now().toString(36)}`,heading:"Details",items:["new_item"]};d({...r,sections:[...r.sections,c]})},className:"inline-flex items-center gap-1 rounded border border-slate-700 bg-slate-800 px-2 py-1 text-[11px] text-slate-200 hover:bg-slate-700",children:[o.jsx(xt,{className:"h-3 w-3"}),"Add Section"]})]}),r.sections.map((c,f)=>o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-2.5 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("input",{type:"text",value:c.heading,disabled:r.locked,onChange:p=>{const h=[...r.sections];h[f]={...c,heading:p.target.value},i({...r,sections:h})},onBlur:()=>{c.heading.trim()&&d(r)},className:"flex-1 rounded border border-slate-700 bg-slate-900 px-2 py-1 text-xs font-semibold text-slate-200 disabled:opacity-50 focus:border-sky-500 focus:outline-none"}),!r.locked&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:f===0,onClick:()=>{const p=[...r.sections],[h]=p.splice(f,1);h&&(p.splice(f-1,0,h),d({...r,sections:p}))},className:"rounded p-1 text-slate-400 hover:bg-slate-800 disabled:opacity-30",title:"Move section up",children:o.jsx(Br,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",disabled:f===r.sections.length-1,onClick:()=>{const p=[...r.sections],[h]=p.splice(f,1);h&&(p.splice(f+1,0,h),d({...r,sections:p}))},className:"rounded p-1 text-slate-400 hover:bg-slate-800 disabled:opacity-30",title:"Move section down",children:o.jsx(Zr,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",onClick:()=>{const p=r.sections.filter((h,x)=>x!==f);d({...r,sections:p})},className:"rounded p-1 text-rose-400 hover:bg-rose-950/50",title:"Delete section",children:o.jsx(sn,{className:"h-3 w-3"})})]})]}),o.jsxs("div",{className:"space-y-1",children:[c.items.map((p,h)=>o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"text",value:p,disabled:r.locked,onChange:x=>{const m=structuredClone(r.sections);m[f].items[h]=x.target.value,i({...r,sections:m})},onBlur:()=>void d(r),className:"flex-1 rounded border border-slate-800 bg-slate-900 px-2 py-1 font-mono text-[11px] text-slate-200 disabled:opacity-50 focus:border-sky-500 focus:outline-none"}),!r.locked&&o.jsx("button",{type:"button",onClick:()=>{const x=structuredClone(r.sections);x[f].items.splice(h,1),d({...r,sections:x})},className:"rounded p-1 text-slate-500 hover:bg-slate-800 hover:text-rose-400",title:"Remove item",children:o.jsx($t,{className:"h-3 w-3"})})]},`${c.id}-item-${h}`)),!r.locked&&o.jsxs("button",{type:"button",onClick:()=>{const p=structuredClone(r.sections);p[f].items.push("new_line"),d({...r,sections:p})},className:"mt-1 inline-flex items-center gap-1 text-[11px] text-sky-400 hover:text-sky-300",children:[o.jsx(xt,{className:"h-3 w-3"})," Add line"]})]})]},c.id))]}),o.jsx("div",{className:"border-t border-slate-800 pt-3",children:o.jsxs("button",{type:"button",disabled:r.locked,onClick:()=>void s(r.id),className:"inline-flex w-full items-center justify-center gap-1.5 rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 py-2 text-xs font-medium text-rose-300 hover:bg-rose-500/20 disabled:opacity-40",children:[o.jsx(sn,{className:"h-3.5 w-3.5"}),r.locked?"Unlock node to delete":"Delete Node from View"]})})]})}function Zs({threads:e,targetType:t,viewId:n,targetId:s,entityRef:r,onCreateThread:i,onReplyThread:a,onJumpToTarget:l,showJumpLinks:d=!1}){const[u,c]=v.useState("change_request"),[f,p]=v.useState(""),[h,x]=v.useState(!1),[m,g]=v.useState({}),[y,b]=v.useState(null),[$,k]=v.useState(""),[_,O]=v.useState(!1),[F,N]=v.useState(null),P=e.filter(w=>w.status==="open"),M=e.filter(w=>w.status==="resolved"),A=async w=>{if(w.preventDefault(),!!f.trim()){x(!0);try{await i({target_type:t,view_id:n,target_id:s,entity_ref:r,kind:u,body:f.trim()}),p("")}finally{x(!1)}}},q=async w=>{var D;const Z=(D=m[w])==null?void 0:D.trim();if(Z){N(w);try{await a(w,{body:Z}),g(J=>({...J,[w]:""}))}finally{N(null)}}},ne=async w=>{var Z;N(w);try{const D=((Z=m[w])==null?void 0:Z.trim())||"Marked resolved.";await a(w,{body:D,resolve:!0,resolution_summary:$.trim()||void 0}),g(J=>({...J,[w]:""})),b(null),k("")}finally{N(null)}},Q=async w=>{N(w);try{await a(w,{body:"Reopened for follow-up.",reopen:!0})}finally{N(null)}};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("form",{onSubmit:A,className:"rounded-lg border border-slate-800 bg-slate-950/70 p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400",children:"New Thread"}),o.jsxs("select",{value:u,onChange:w=>c(w.target.value),className:"rounded border border-slate-700 bg-slate-900 px-2 py-0.5 text-[11px] text-slate-200 focus:border-sky-500 focus:outline-none",children:[o.jsx("option",{value:"change_request",children:"Change Request"}),o.jsx("option",{value:"question",children:"Question"}),o.jsx("option",{value:"decision",children:"Decision"})]})]}),o.jsx("textarea",{rows:2,value:f,onChange:w=>p(w.target.value),placeholder:"Ask a question or request an architectural adjustment...",className:"w-full rounded-md border border-slate-700 bg-slate-900 px-2.5 py-1.5 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none"}),o.jsx("div",{className:"flex justify-end",children:o.jsxs("button",{type:"submit",disabled:h||!f.trim(),className:"inline-flex items-center gap-1 rounded-md bg-sky-500 px-2.5 py-1 text-xs font-semibold text-slate-950 hover:bg-sky-400 disabled:opacity-50",children:[o.jsx(xt,{className:"h-3.5 w-3.5"}),"Post Thread"]})})]}),P.length===0?o.jsx("p",{className:"text-xs text-slate-500 text-center py-3",children:"No open threads here."}):o.jsx("div",{className:"space-y-3",children:P.map(w=>{var X;const Z=On(w),D=Ip(w),J=w.kind==="drift_alert";return o.jsxs("div",{className:`rounded-lg border p-3 space-y-2.5 ${J?"border-rose-500/40 bg-rose-950/10":Z?"border-amber-500/40 bg-amber-950/10":"border-slate-800 bg-slate-950/50"}`,children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"rounded bg-slate-800 px-1.5 py-0.5 text-[10px] font-mono uppercase text-slate-300",children:w.kind.replace("_"," ")}),Z&&o.jsx("span",{className:"rounded-full bg-amber-500/20 px-2 py-0.5 text-[10px] font-semibold text-amber-300 border border-amber-500/30",children:"Waiting on you"}),D&&o.jsx("span",{className:"rounded-full bg-sky-500/20 px-2 py-0.5 text-[10px] font-semibold text-sky-300 border border-sky-500/30",children:"Waiting on agent"})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[d&&l&&o.jsxs("button",{type:"button",onClick:()=>l(w.view_id,w.target_type,w.target_id,"threads"),className:"inline-flex items-center gap-1 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-sky-300 hover:bg-slate-800",children:[o.jsx(Ws,{className:"h-2.5 w-2.5"}),"Jump"]}),o.jsxs("button",{type:"button",onClick:()=>{b(y===w.id?null:w.id),k("")},className:"inline-flex items-center gap-1 rounded border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-300 hover:bg-emerald-500/20",children:[o.jsx(Ol,{className:"h-3 w-3"}),"Resolve"]})]})]}),d&&o.jsxs("div",{className:"text-[10px] font-mono text-slate-500",children:[w.view_id?`${w.view_id}`:"workspace",w.target_id?` / ${w.target_id}`:""]}),o.jsx("div",{className:"space-y-2",children:w.messages.map(W=>o.jsxs("div",{className:`rounded-md px-2.5 py-2 text-xs ${W.author==="agent"?"bg-slate-900 border border-slate-800 text-slate-200":"bg-sky-950/40 border border-sky-500/25 text-sky-100"}`,children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between text-[10px] text-slate-400",children:[o.jsx("span",{className:"font-semibold uppercase tracking-wider",children:W.author}),o.jsx("span",{children:new Date(W.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsx("p",{className:"whitespace-pre-wrap leading-relaxed",children:W.body})]},W.id))}),y===w.id&&o.jsxs("div",{className:"rounded-md border border-emerald-500/30 bg-emerald-950/20 p-2 space-y-2",children:[o.jsx("input",{type:"text",value:$,onChange:W=>k(W.target.value),placeholder:"Optional 1-line ADR summary...",className:"w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs text-slate-100 placeholder:text-slate-600 focus:border-emerald-500 focus:outline-none"}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{type:"button",onClick:()=>b(null),className:"rounded px-2 py-1 text-[11px] text-slate-400 hover:bg-slate-800",children:"Cancel"}),o.jsx("button",{type:"button",disabled:F===w.id,onClick:()=>ne(w.id),className:"rounded bg-emerald-500 px-2.5 py-1 text-[11px] font-semibold text-slate-950 hover:bg-emerald-400 disabled:opacity-50",children:"Confirm Resolve"})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{type:"text",value:m[w.id]??"",onChange:W=>g(se=>({...se,[w.id]:W.target.value})),onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),q(w.id))},placeholder:"Write a reply...",className:"flex-1 rounded-md border border-slate-700 bg-slate-950 px-2.5 py-1 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none"}),o.jsx("button",{type:"button",disabled:F===w.id||!((X=m[w.id])!=null&&X.trim()),onClick:()=>void q(w.id),className:"inline-flex items-center justify-center rounded-md bg-slate-800 px-2.5 py-1 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-40","aria-label":"Send reply",children:o.jsx(zl,{className:"h-3.5 w-3.5"})})]})]},w.id)})}),M.length>0&&o.jsxs("div",{className:"border-t border-slate-800 pt-3",children:[o.jsxs("button",{type:"button",onClick:()=>O(w=>!w),className:"flex w-full items-center justify-between text-xs font-semibold text-slate-400 hover:text-slate-200",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[_?o.jsx(Ot,{className:"h-3.5 w-3.5"}):o.jsx(an,{className:"h-3.5 w-3.5"}),"Resolved Decisions"]}),o.jsx("span",{className:"rounded-full bg-slate-800 px-2 py-0.5 text-[10px]",children:M.length})]}),_&&o.jsx("div",{className:"mt-2.5 space-y-2",children:M.map(w=>{var Z;return o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-2.5 space-y-1.5",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex items-start gap-2 text-[11px] font-medium text-slate-100 leading-relaxed",children:[o.jsx(qs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-400 mt-0.5"}),o.jsx("span",{children:w.resolution_summary??((Z=w.messages[w.messages.length-1])==null?void 0:Z.body)})]}),o.jsxs("button",{type:"button",disabled:F===w.id,onClick:()=>void Q(w.id),className:"inline-flex shrink-0 items-center gap-1 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-300 hover:bg-slate-800",children:[o.jsx(Rt,{className:"h-2.5 w-2.5"}),"Reopen"]})]}),o.jsxs("p",{className:"text-[11px] text-slate-400",children:[w.messages.length," message(s) • ",w.kind.replace("_"," "),w.target_id?` • ${w.target_id}`:""]})]},w.id)})})]})]})}function _0({activeView:e,allThreads:t,onCreateThread:n,onReplyThread:s,onJumpToTarget:r}){const[i,a]=v.useState(!1),[l,d]=v.useState(""),[u,c]=v.useState({}),[f,p]=v.useState(!1),[h,x]=v.useState(null),m=v.useMemo(()=>{if(!e)return t.filter(O=>O.target_type==="workspace");const k=new Set(e.nodes.map(O=>O.id)),_=new Set(e.edges.map(O=>O.id));return t.filter(O=>O.target_type==="workspace"?!0:O.view_id!==e.id?!1:O.target_type==="view"?!0:O.target_type==="node"?!k.has(O.target_id??""):O.target_type==="edge"?!_.has(O.target_id??""):!1)},[t,e]),g=v.useMemo(()=>m.filter(k=>k.status==="open").length,[m]),y=v.useMemo(()=>t.filter(k=>k.status==="resolved").sort((k,_)=>{var N,P;const O=((N=_.messages[_.messages.length-1])==null?void 0:N.created_at)??"",F=((P=k.messages[k.messages.length-1])==null?void 0:P.created_at)??"";return O.localeCompare(F)}),[t]),b=v.useMemo(()=>{const k=l.trim().toLowerCase();return k?y.filter(_=>{var F;return(_.resolution_summary??((F=_.messages[_.messages.length-1])==null?void 0:F.body)??"").toLowerCase().includes(k)||(_.view_id??"").toLowerCase().includes(k)||(_.target_id??"").toLowerCase().includes(k)||(_.entity_ref??"").toLowerCase().includes(k)}):y},[l,y]),$=async k=>{x(k);try{await s(k,{body:"Reopened for follow-up.",reopen:!0})}finally{x(null)}};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h3",{className:"text-xs font-semibold text-slate-100",children:"Decision Log"}),o.jsx("span",{className:"rounded-full bg-slate-800 px-2 py-0.5 text-[10px] font-mono text-slate-300",children:y.length})]}),o.jsxs("button",{type:"button",onClick:()=>a(k=>!k),className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-slate-400 hover:bg-slate-800 hover:text-slate-200",children:[o.jsx("span",{children:"How it works"}),i?o.jsx(Ot,{className:"h-3 w-3"}):o.jsx(an,{className:"h-3 w-3"})]})]}),i&&o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/70 px-3 py-2.5 space-y-1.5 text-[11px] text-slate-300 leading-relaxed",children:[o.jsxs("p",{children:["• ",o.jsx("strong",{className:"text-amber-300",children:"Question:"})," asks for clarification before locking a design."]}),o.jsxs("p",{children:["• ",o.jsx("strong",{className:"text-sky-300",children:"Change Request:"})," ","requests the agent to modify a box, edge, or view."]}),o.jsxs("p",{children:["• ",o.jsx("strong",{className:"text-emerald-300",children:"Decision (ADR):"})," ","resolved threads graduate into persistent Architecture Decision Records so future iterations remember ",o.jsx("em",{children:"why"})," choices were made."]})]}),y.length>=2&&o.jsxs("div",{className:"relative",children:[o.jsx(Rs,{className:"pointer-events-none absolute left-2.5 top-2 h-3.5 w-3.5 text-slate-500"}),o.jsx("input",{type:"text",value:l,onChange:k=>d(k.target.value),placeholder:"Filter decisions by summary, view, or node...",className:"w-full rounded-md border border-slate-800 bg-slate-950 py-1.5 pl-8 pr-7 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none"}),l&&o.jsx("button",{type:"button",onClick:()=>d(""),"aria-label":"Clear filter",className:"absolute right-2 top-1.5 rounded p-0.5 text-slate-500 hover:text-slate-200",children:o.jsx($t,{className:"h-3 w-3"})})]}),b.length===0?o.jsx("div",{className:"rounded-lg border border-dashed border-slate-800 px-3 py-4 text-center text-xs text-slate-500",children:y.length===0?"No resolved decisions yet. Resolve any thread to record a decision here.":"No decisions match that filter."}):o.jsx("div",{className:"space-y-2.5",children:b.map(k=>{var M,A;const _=u[k.id]===!0,O=k.resolution_summary??((M=k.messages[k.messages.length-1])==null?void 0:M.body)??"Resolved decision",F=`${k.view_id??"workspace"}${k.target_id?` / ${k.target_id}`:""}`,N=!!(k.view_id||k.target_id),P=(A=k.messages[k.messages.length-1])==null?void 0:A.created_at;return o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx(qs,{className:"h-3.5 w-3.5 shrink-0 text-emerald-400"}),o.jsx("span",{title:F,className:"truncate rounded bg-slate-800 px-1.5 py-0.5 font-mono text-[10px] text-slate-300",children:F})]}),N&&o.jsxs("button",{type:"button",onClick:()=>r(k.view_id,k.target_type,k.target_id,"threads"),className:"inline-flex shrink-0 items-center gap-1 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-sky-300 hover:bg-slate-800",children:[o.jsx(Ws,{className:"h-2.5 w-2.5"}),"Jump"]})]}),o.jsx("p",{className:"text-xs font-medium text-slate-100 leading-relaxed",children:O}),o.jsxs("div",{className:"flex items-center justify-between gap-2 pt-0.5 text-[10px] text-slate-400",children:[o.jsxs("span",{children:[P?`${new Date(P).toLocaleDateString()} • `:"",k.messages.length," msg",k.messages.length===1?"":"s"]}),o.jsx("button",{type:"button",onClick:()=>c(q=>({...q,[k.id]:!_})),className:"text-[11px] font-medium text-sky-300 hover:underline",children:_?"Hide discussion":"Show discussion"})]}),_&&o.jsxs("div",{className:"border-t border-slate-800/90 pt-2 space-y-2",children:[o.jsx("div",{className:"space-y-1.5",children:k.messages.map(q=>o.jsxs("div",{className:`rounded-md px-2.5 py-1.5 text-[11px] ${q.author==="agent"?"bg-slate-900 border border-slate-800 text-slate-200":"bg-sky-950/40 border border-sky-500/25 text-sky-100"}`,children:[o.jsxs("div",{className:"mb-0.5 flex items-center justify-between text-[10px] text-slate-400",children:[o.jsx("span",{className:"font-semibold uppercase tracking-wider",children:q.author}),o.jsx("span",{children:new Date(q.created_at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),o.jsx("p",{className:"whitespace-pre-wrap leading-relaxed",children:q.body})]},q.id))}),o.jsx("div",{className:"flex justify-end",children:o.jsxs("button",{type:"button",disabled:h===k.id,onClick:()=>void $(k.id),className:"inline-flex items-center gap-1 rounded border border-slate-700 px-2 py-0.5 text-[10px] text-slate-300 hover:bg-slate-800 disabled:opacity-50",children:[o.jsx(Rt,{className:"h-2.5 w-2.5"}),"Reopen thread"]})})]})]},k.id)})})]}),o.jsxs("div",{className:"border-t border-slate-800 pt-3 space-y-2",children:[o.jsxs("button",{type:"button",onClick:()=>p(k=>!k),className:"flex w-full items-center justify-between rounded-md py-1 text-left text-xs font-semibold text-slate-300 hover:text-slate-100",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx(Us,{className:"h-3.5 w-3.5 text-sky-400"}),"View & Workspace Threads",o.jsxs("span",{className:`rounded-full px-1.5 py-0.2 text-[10px] font-mono ${g>0?"bg-amber-500/20 text-amber-200 border border-amber-500/35":"bg-slate-800 text-slate-400"}`,children:[g," open"]})]}),f||g>0?o.jsx(Ot,{className:"h-3.5 w-3.5 text-slate-400"}):o.jsx(an,{className:"h-3.5 w-3.5 text-slate-400"})]}),(f||g>0)&&o.jsx(Zs,{threads:m,targetType:e?"view":"workspace",viewId:e==null?void 0:e.id,onCreateThread:n,onReplyThread:s,onJumpToTarget:r,showJumpLinks:!0})]})]})}function j0(e){const t=["Please review my latest Redlinify feedback by calling `get_workspace()`:"];for(const n of e.view_diffs){const s=n.diff,r=[];s.nodes_added.length&&r.push(`+${s.nodes_added.length} nodes`),s.nodes_modified.length&&r.push(`~${s.nodes_modified.length} modified nodes`),s.nodes_removed.length&&r.push(`-${s.nodes_removed.length} removed nodes`),s.edges_added.length+s.edges_modified.length+s.edges_removed.length>0&&r.push(`${s.edges_added.length+s.edges_modified.length+s.edges_removed.length} edge changes`),t.push(`- View \`${n.view_id}\`: ${r.join(", ")||"updated"}`)}if(e.pending_threads.length>0){const n=e.pending_threads.map(s=>s.view_id?`${s.view_id}${s.target_id?`/${s.target_id}`:""}`:"workspace").join(", ");t.push(`- Open threads needing agent response: ${e.pending_threads.length} (${n})`)}return e.view_requests.length>0&&t.push(`- New view requests: ${e.view_requests.map(n=>`"${n.title}"`).join(", ")}`),t.join(`
95
+ `)}function $0({activeView:e,viewDiff:t,viewBaseline:n=null,pendingFeedback:s,onOpenTab:r,onJumpToTarget:i,onRevertNode:a,onRevertView:l,onCopyText:d}){return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"rounded-lg border border-sky-500/30 bg-sky-500/10 p-3 space-y-2",children:[o.jsx("p",{className:"text-xs text-slate-200 leading-relaxed",children:"Review your pending semantic edits, thread replies, and view requests before prompting the coding agent."}),o.jsxs("button",{type:"button",onClick:()=>void d(j0(s),"prompt for agent"),className:"inline-flex w-full items-center justify-center gap-1.5 rounded-lg bg-sky-500 px-3 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Ks,{className:"h-3.5 w-3.5"}),"Copy Prompt for Agent"]})]}),s.view_diffs.length===0&&s.pending_threads.length===0&&s.view_requests.length===0?o.jsx("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-4 text-center text-xs text-slate-400",children:"Everything is synced with the last agent checkpoint."}):o.jsxs(o.Fragment,{children:[s.view_diffs.map(({view_id:u,diff:c})=>{const f=(e==null?void 0:e.id)===u,p=f?e.diagram_type??"general":"general";return o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-xs font-semibold text-sky-300 font-mono",children:u}),o.jsxs("div",{className:"flex items-center gap-2",children:[f&&n&&l&&o.jsxs("button",{type:"button",onClick:()=>void l(),title:"Revert all unsynced changes in this view to checkpoint",className:"inline-flex items-center gap-1 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-300 hover:border-sky-500/60 hover:text-sky-300",children:[o.jsx(Rt,{className:"h-2.5 w-2.5"}),"Revert view"]}),o.jsx("button",{type:"button",onClick:()=>r(u),className:"text-[11px] text-sky-400 hover:underline",children:f?"Active":"Open tab"})]})]}),o.jsxs("ul",{className:"space-y-1.5 text-xs text-slate-300",children:[Object.keys(c.view_meta_changed).length>0&&o.jsx("li",{children:"• View title/direction updated"}),c.nodes_added.map(h=>o.jsxs("li",{className:"flex items-center justify-between gap-2 text-emerald-300",children:[o.jsxs("button",{type:"button",onClick:()=>i(u,"node",h.id,"spec"),className:"truncate text-left hover:underline",children:["+ Added: ",h.title]}),f&&a&&o.jsx("button",{type:"button",onClick:()=>void a(h.id),className:"shrink-0 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-300 hover:border-rose-500/60 hover:text-rose-200",children:"Discard"})]},h.id)),c.nodes_modified.map(h=>{const x=la(c,h.id,p);return o.jsxs("li",{className:"space-y-0.5 text-sky-200",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>i(u,"node",h.id,"spec"),className:"truncate text-left hover:underline",children:["~ Modified: ",h.title]}),f&&n&&a&&o.jsx("button",{type:"button",onClick:()=>void a(h.id),className:"shrink-0 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-300 hover:border-sky-500/60 hover:text-sky-200",children:"Revert"})]}),x.length>0&&o.jsx("ul",{className:"ml-3 space-y-0.5 text-[11px] font-mono text-slate-400",children:x.map((m,g)=>o.jsx("li",{className:"truncate",children:m},g))})]},h.id)}),c.nodes_removed.map(h=>o.jsxs("li",{className:"flex items-center justify-between gap-2 text-rose-300",children:[o.jsxs("span",{className:"truncate",children:["- Removed: ",h.title]}),f&&n&&a&&o.jsx("button",{type:"button",onClick:()=>void a(h.id),className:"shrink-0 rounded border border-slate-700 px-1.5 py-0.5 text-[10px] text-slate-300 hover:border-emerald-500/60 hover:text-emerald-200",children:"Restore"})]},h.id)),c.edges_added.map(h=>o.jsx("li",{className:"text-emerald-300/90",children:o.jsxs("button",{type:"button",onClick:()=>i(u,"edge",h.id,"spec"),className:"truncate text-left hover:underline",children:["+ Edge ",h.source," → ",h.target,h.label?` (${h.label})`:""]})},`ea-${h.id}`)),c.edges_modified.map(h=>{const x=ca(c,h.id);return o.jsx("li",{className:"text-sky-200/90",children:o.jsxs("button",{type:"button",onClick:()=>i(u,"edge",h.id,"spec"),className:"truncate text-left hover:underline",children:["~ Edge ",h.id,": ",x.join(" · ")]})},`em-${h.id}`)}),c.edges_removed.length>0&&o.jsxs("li",{className:"text-rose-300/90",children:["- ",c.edges_removed.length," removed edge",c.edges_removed.length>1?"s":""]})]})]},u)}),s.pending_threads.length>0&&o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3 space-y-2",children:[o.jsxs("div",{className:"text-xs font-semibold text-slate-200",children:["Threads Awaiting Agent (",s.pending_threads.length,")"]}),s.pending_threads.map(u=>{var c;return o.jsxs("button",{type:"button",onClick:()=>i(u.view_id,u.target_type,u.target_id,"threads"),className:"block w-full rounded border border-slate-800 bg-slate-900 p-2 text-left hover:border-sky-500/40",children:[o.jsxs("div",{className:"flex items-center justify-between text-[10px] text-slate-400 font-mono",children:[o.jsxs("span",{children:[u.view_id??"workspace",u.target_id?` / ${u.target_id}`:""]}),o.jsx("span",{children:u.kind})]}),o.jsx("p",{className:"mt-1 truncate text-xs text-slate-200",children:(c=u.messages[u.messages.length-1])==null?void 0:c.body})]},u.id)})]}),s.view_requests.length>0&&o.jsxs("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3 space-y-2",children:[o.jsxs("div",{className:"text-xs font-semibold text-amber-300",children:["Requested Views (",s.view_requests.length,")"]}),s.view_requests.map(u=>o.jsxs("div",{className:"rounded border border-slate-800 bg-slate-900 p-2 text-xs",children:[o.jsx("div",{className:"font-semibold text-slate-100",children:u.title}),o.jsx("div",{className:"mt-0.5 text-slate-400",children:u.prompt})]},u.id))]})]}),t&&t.has_changes&&e&&o.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-slate-400",children:[o.jsx(Js,{className:"h-3.5 w-3.5 text-sky-400"}),o.jsxs("span",{children:["Active tab"," ",o.jsx("code",{className:"font-mono text-slate-200",children:e.id})," ","has unsynced human changes."]})]})]})}function N0(e){const{mode:t,elementTab:n,workspaceTab:s,onChangeElementTab:r,onChangeWorkspaceTab:i,onClose:a,activeView:l,selectedNode:d,selectedEdge:u,edgeRoute:c,allThreads:f,viewDiff:p,viewBaseline:h=null,pendingFeedback:x,status:m,onSaveNode:g,onDeleteNode:y,onRevertNode:b,onRevertView:$,onSaveEdge:k,onDeleteEdge:_,onUpdateEdgeRoute:O,onFlipEdge:F,onCreateThread:N,onReplyThread:P,onOpenTab:M,onJumpToTarget:A,onNotify:q}=e,ne=v.useMemo(()=>t==="node"&&d&&l?f.filter(D=>D.target_type==="node"&&D.view_id===l.id&&D.target_id===d.id):t==="edge"&&u&&l?f.filter(D=>D.target_type==="edge"&&D.view_id===l.id&&D.target_id===u.id):[],[t,d,u,l,f]),Q=v.useMemo(()=>f.filter(D=>D.status==="open"),[f]),w=v.useMemo(()=>f.filter(D=>D.status==="resolved").length,[f]);if(t==="none")return null;const Z=async(D,J)=>{try{await navigator.clipboard.writeText(D),q(`Copied ${J}`)}catch{q("Could not access clipboard","warning")}};return o.jsxs(o.Fragment,{children:[o.jsx("div",{onClick:a,className:"fixed inset-0 z-30 bg-black/50 md:hidden"}),o.jsxs("aside",{className:"fixed inset-y-0 right-0 z-40 flex w-full max-w-[400px] flex-col border-l border-slate-800 bg-slate-900 shadow-2xl md:static md:z-auto md:w-[390px] md:shrink-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-slate-800 px-4 py-3",children:[o.jsxs("div",{className:"min-w-0",children:[t==="node"&&d&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-[10px] font-mono uppercase tracking-wider text-sky-400",children:[d.kind," Node"]}),o.jsx("h2",{className:"truncate text-sm font-semibold text-slate-100",children:d.title})]}),t==="edge"&&u&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-sky-400",children:"Edge Connection"}),o.jsxs("h2",{className:"truncate text-sm font-semibold text-slate-100",children:[u.source," → ",u.target]})]}),t==="workspace"&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"text-[10px] font-mono uppercase tracking-wider text-sky-400",children:"Workspace Triage"}),o.jsx("h2",{className:"truncate text-sm font-semibold text-slate-100",children:(m==null?void 0:m.project_name)??"Redlinify"})]})]}),o.jsx("button",{type:"button",onClick:a,className:"rounded-md p-1 text-slate-400 hover:bg-slate-800 hover:text-slate-100","aria-label":"Close inspector",children:o.jsx($t,{className:"h-4 w-4"})})]}),(t==="node"||t==="edge")&&o.jsxs("div",{className:"grid grid-cols-3 border-b border-slate-800 bg-slate-950/50 text-xs font-medium",children:[o.jsx("button",{type:"button",onClick:()=>r("spec"),className:`py-2 border-b-2 transition-colors ${n==="spec"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:"Spec"}),o.jsxs("button",{type:"button",onClick:()=>r("threads"),className:`py-2 border-b-2 transition-colors ${n==="threads"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:["Threads (",ne.filter(D=>D.status==="open").length,")"]}),t==="node"&&o.jsx("button",{type:"button",onClick:()=>r("links"),className:`py-2 border-b-2 transition-colors ${n==="links"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:"Links & Code"})]}),t==="workspace"&&o.jsxs("div",{className:"grid grid-cols-3 border-b border-slate-800 bg-slate-950/50 text-xs font-medium",children:[o.jsxs("button",{type:"button",onClick:()=>i("questions"),className:`py-2 border-b-2 transition-colors ${s==="questions"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:["Threads (",Q.length,")"]}),o.jsxs("button",{type:"button",onClick:()=>i("pending"),className:`py-2 border-b-2 transition-colors ${s==="pending"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:["Pending (",x.view_diffs.length+x.pending_threads.length+x.view_requests.length,")"]}),o.jsxs("button",{type:"button",onClick:()=>i("adrs"),className:`py-2 border-b-2 transition-colors ${s==="adrs"?"border-sky-400 text-sky-200":"border-transparent text-slate-400 hover:text-slate-200"}`,children:["Decisions (",w,")"]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[t==="node"&&n==="spec"&&d&&o.jsx(w0,{activeView:l,selectedNode:d,onSaveNode:g,onDeleteNode:y}),(t==="node"&&d||t==="edge"&&u)&&n==="threads"&&l&&o.jsx(Zs,{threads:ne,targetType:t==="node"?"node":"edge",viewId:l.id,targetId:t==="node"?d.id:u.id,entityRef:t==="node"?d==null?void 0:d.entity_ref:void 0,onCreateThread:N,onReplyThread:P}),t==="node"&&n==="links"&&d&&o.jsx(v0,{activeView:l,selectedNode:d,onJumpToTarget:A,onCopyText:Z}),t==="edge"&&n==="spec"&&u&&o.jsx(b0,{activeView:l,selectedEdge:u,edgeRoute:c,onSaveEdge:k,onDeleteEdge:_,onUpdateEdgeRoute:O,onFlipEdge:F}),t==="workspace"&&s==="questions"&&o.jsx(Zs,{threads:f,targetType:l?"view":"workspace",viewId:l==null?void 0:l.id,onCreateThread:N,onReplyThread:P,onJumpToTarget:A,showJumpLinks:!0}),t==="workspace"&&s==="pending"&&o.jsx($0,{activeView:l,viewDiff:p,viewBaseline:h,pendingFeedback:x,onOpenTab:M,onJumpToTarget:A,onRevertNode:b,onRevertView:$,onCopyText:Z}),t==="workspace"&&s==="adrs"&&o.jsx(_0,{activeView:l,allThreads:f,onCreateThread:N,onReplyThread:P,onJumpToTarget:A})]})]})]})}function Ko(e){if(e.scrollWidth>e.clientWidth+1||e.scrollHeight>e.clientHeight+1)return!0;const t=e.firstElementChild;return t?t.scrollWidth>t.clientWidth+1||t.scrollHeight>t.clientHeight+1:!1}function ct({text:e,detail:t,alwaysShow:n=!1,delayMs:s=160,className:r="inline-block min-w-0 max-w-full",children:i}){const a=v.useRef(null),l=v.useRef(null),[d,u]=v.useState(null),c=v.useCallback(()=>{l.current!==null&&(window.clearTimeout(l.current),l.current=null)},[]),f=v.useCallback(()=>{c(),u(null)},[c]),p=v.useCallback(()=>{!e.trim()&&!(t!=null&&t.trim())||(c(),l.current=window.setTimeout(()=>{l.current=null;const h=a.current;if(!h)return;const x=h.firstElementChild??h;if(!n&&!Ko(x)&&!Ko(h))return;const m=x.getBoundingClientRect();if(m.width===0&&m.height===0)return;const g=m.left+m.width/2,y=Math.min(window.innerWidth-20,Math.max(20,g)),b=m.top<88;u({x:y,y:b?m.bottom+8:m.top-8,placeBelow:b})},s))},[n,c,s,t,e]);return v.useEffect(()=>{if(!d)return;const h=()=>f();return window.addEventListener("wheel",h,{passive:!0}),window.addEventListener("scroll",h,{capture:!0,passive:!0}),window.addEventListener("keydown",h),()=>{window.removeEventListener("wheel",h),window.removeEventListener("scroll",h,{capture:!0}),window.removeEventListener("keydown",h)}},[d,f]),v.useEffect(()=>()=>c(),[c]),o.jsxs("span",{ref:a,onMouseEnter:p,onMouseLeave:f,onPointerDown:f,className:r,children:[i,d&&typeof document<"u"&&ll.createPortal(o.jsxs("div",{role:"tooltip",style:{left:d.x,top:d.y,transform:d.placeBelow?"translate(-50%, 0)":"translate(-50%, -100%)"},className:"pointer-events-none fixed z-[9999] max-w-[360px] break-words rounded-lg border border-slate-700 bg-slate-900/95 px-2.5 py-1.5 text-[11px] leading-snug text-slate-100 shadow-2xl backdrop-blur-sm",children:[o.jsx("div",{className:"font-mono whitespace-pre-wrap",children:e}),t&&o.jsx("div",{className:"mt-1 border-t border-slate-800 pt-1 text-[10px] font-sans text-slate-400 whitespace-pre-wrap",children:t})]}),document.body)]})}function qo(e,t,n){return n?t===et.Left||t===et.Right?{x:e.x,y:e.y+n}:{x:e.x+n,y:e.y}:e}function Jo(e){if(e.length<2)return null;const t=e.length>=4?1:0,n=e.length>=4?e.length-2:e.length-1;let s=-1,r=null;for(let i=t;i<n;i++){const a=e[i],l=e[i+1],d=Math.abs(l.x-a.x),u=Math.abs(l.y-a.y),c=Math.hypot(d,u),f=d>=u?1.25:1,p=c*f;p>s&&(s=p,r={x:(a.x+l.x)/2,y:(a.y+l.y)/2})}return r}function Xo(e,t=12){if(e.length<2)return"";if(e.length===2)return`M ${e[0].x} ${e[0].y} L ${e[1].x} ${e[1].y}`;let n=`M ${e[0].x} ${e[0].y}`;for(let r=1;r<e.length-1;r++){const i=e[r-1],a=e[r],l=e[r+1],d=a.x-i.x,u=a.y-i.y,c=Math.hypot(d,u),f=l.x-a.x,p=l.y-a.y,h=Math.hypot(f,p);if(c<1||h<1){n+=` L ${a.x} ${a.y}`;continue}const x=Math.min(t,c*.4,h*.4),m=a.x-d/c*x,g=a.y-u/c*x,y=a.x+f/h*x,b=a.y+p/h*x;n+=` L ${m} ${g} Q ${a.x} ${a.y} ${y} ${b}`}const s=e[e.length-1];return n+=` L ${s.x} ${s.y}`,n}function Yo(e){switch(e){case et.Right:return{x:1,y:0};case et.Left:return{x:-1,y:0};case et.Bottom:return{x:0,y:1};case et.Top:return{x:0,y:-1}}}function Sn(e){switch(e){case et.Right:return"right";case et.Left:return"left";case et.Bottom:return"bottom";case et.Top:return"top"}}function Dt(e,t,n){const s=Math.hypot(e,t);return s<.001?n:{x:e/s,y:t/s}}function Go(e){return e==="1"||e==="1..*"}function Qo(e){return e==="0..1"||e==="0..*"}function Vo({anchor:e,outward:t,cardinality:n,color:s,strokeWidth:r}){const i=-t.y,a=t.x,l=(y,b)=>({x:e.x+t.x*y+i*b,y:e.y+t.y*y+a*b}),d=n==="1..*"||n==="0..*",u=n==="0..1"||n==="0..*",c=d?14:9,f=l(c,-6),p=l(c,6),h=l(d?18:16,0),x=l(0,-7),m=l(0,7),g=l(12,0);return o.jsxs("g",{pointerEvents:"none",children:[d?o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:g.x,y1:g.y,x2:x.x,y2:x.y,stroke:s,strokeWidth:r,strokeLinecap:"round"}),o.jsx("line",{x1:g.x,y1:g.y,x2:m.x,y2:m.y,stroke:s,strokeWidth:r,strokeLinecap:"round"})]}):o.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,stroke:s,strokeWidth:r,strokeLinecap:"round"}),!u&&d&&o.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,stroke:s,strokeWidth:r,strokeLinecap:"round"}),u&&o.jsx("circle",{cx:h.x,cy:h.y,r:4,fill:"var(--rl-canvas-bg, #020617)",stroke:s,strokeWidth:r})]})}function S0({anchor:e,outward:t,color:n,strokeWidth:s}){const r=-t.y,i=t.x,a=e,l={x:e.x+t.x*13+r*7,y:e.y+t.y*13+i*7},d={x:e.x+t.x*13-r*7,y:e.y+t.y*13-i*7};return o.jsx("polygon",{points:`${a.x},${a.y} ${l.x},${l.y} ${d.x},${d.y}`,fill:"var(--rl-canvas-bg, #020617)",stroke:n,strokeWidth:s,strokeLinejoin:"round",pointerEvents:"none"})}function M0({id:e,sourceX:t,sourceY:n,targetX:s,targetY:r,sourcePosition:i,targetPosition:a,data:l,selected:d}){var z,R;const{screenToFlowPosition:u}=ei(),c=l==null?void 0:l.edge,p=((l==null?void 0:l.diagramType)??"general")==="er"||!!(c!=null&&c.source_cardinality||c!=null&&c.target_cardinality||c!=null&&c.relation_kind),h=qo({x:t,y:n},i,(l==null?void 0:l.sourcePortOffset)??0),x=qo({x:s,y:r},a,(l==null?void 0:l.targetPortOffset)??0),m=h.x,g=h.y,y=x.x,b=x.y,$=(l==null?void 0:l.manualWaypoints)??[],k=JSON.stringify($),[_,O]=v.useState(null),F=v.useRef(!1);v.useEffect(()=>{F.current||O(null)},[k]);const N=_??$,P=(l==null?void 0:l.autoWaypoints)??[],M=(l==null?void 0:l.curveOffset)??{x:0,y:0},A=Yo(i),q=Yo(a);let ne=A,Q=q,w="",Z=(m+y)/2,D=(g+b)/2,J={x:Z,y:D};if(N.length>0){const C=[{x:m,y:g},...N,{x:y,y:b}];w=Xo(C,12);const S=N[0],B=N[N.length-1];if(ne=Dt(S.x-m,S.y-g,A),Q=Dt(B.x-y,B.y-b,q),N.length>=2){const oe=Math.floor(N.length/2),L=N[oe-1],be=N[oe];J={x:(L.x+be.x)/2,y:(L.y+be.y)/2};const _e=Jo(C)??J;Z=_e.x,D=_e.y}else{const oe=N[0];Z=oe.x,D=oe.y,J=oe}}else if(P.length>0){const C=[{x:m,y:g},...P,{x:y,y:b}];w=Xo(C,14);const S=P[0],B=P[P.length-1];if(ne=Dt(S.x-m,S.y-g,A),Q=Dt(B.x-y,B.y-b,q),P.length>=2){const oe=Jo(C);if(oe)Z=oe.x,D=oe.y;else{const L=P[0],be=P[1];Z=(L.x+be.x)/2,D=(L.y+be.y)/2}}else Z=P[0].x,D=P[0].y;J={x:Z,y:D}}else if(M.x!==0||M.y!==0){const C=(m+y)/2+M.x,S=(g+b)/2+M.y;w=`M ${m} ${g} Q ${C} ${S} ${y} ${b}`,ne=Dt(C-m,S-g,A),Q=Dt(C-y,S-b,q),Z=.25*m+.5*C+.25*y,D=.25*g+.5*S+.25*b,J={x:Z,y:D}}else{const[C,S,B]=dl({sourceX:m,sourceY:g,sourcePosition:i,targetX:y,targetY:b,targetPosition:a,borderRadius:12});w=C,Z=S,D=B,J={x:S,y:B}}const X=(C,S)=>{C.stopPropagation(),C.preventDefault(),F.current=!0;const B=S.kind==="insert"?[...N.slice(0,S.index),S.initialPt,...N.slice(S.index)]:[...N],oe=S.index;let L=B;S.kind==="insert"&&O(L);const be=ve=>{const Oe=u({x:ve.clientX,y:ve.clientY});L=B.map((ye,K)=>K===oe?{x:Math.round(Oe.x),y:Math.round(Oe.y)}:ye),O(L)},_e=()=>{var Oe;F.current=!1,window.removeEventListener("pointermove",be),window.removeEventListener("pointerup",_e),window.removeEventListener("pointercancel",_e);const ve=L.length>0?{source_handle:Sn(i),target_handle:Sn(a)}:void 0;(Oe=l==null?void 0:l.onCommitWaypoints)==null||Oe.call(l,e,L,ve)};window.addEventListener("pointermove",be),window.addEventListener("pointerup",_e),window.addEventListener("pointercancel",_e)},W=!!(d||l!=null&&l.highlighted),se=W?"var(--rl-edge-selected, #38bdf8)":c!=null&&c.locked?"var(--rl-edge-locked, #f59e0b)":"var(--rl-edge-default, #64748b)",le=d?2.5:l!=null&&l.highlighted?2.3:1.75,me=`redlinify-arrow-${e.replace(/[^a-zA-Z0-9_-]/g,"_")}`,ae=c==null?void 0:c.source_cardinality,fe=c==null?void 0:c.target_cardinality,ee=(c==null?void 0:c.relation_kind)??"association",ie=Qo(ae),V=Qo(fe),ue=Go(ae),we=Go(fe),je=p&&ee==="association"&&(ue&&V||ie&&we),xe=(c==null?void 0:c.style)==="dashed"||p&&ee==="association"&&ie&&V&&!je,re=((z=c==null?void 0:c.label)==null?void 0:z.trim())||(ee==="subtype"?"is-a":""),Se=!!(l!=null&&l.isHumanEdited&&(l!=null&&l.showEditedBadge)),te=!!re||(c==null?void 0:c.step)!==void 0||!!(c!=null&&c.locked)||Se,G=l!=null&&l.dimmed?.2:l!=null&&l.softDimmed&&!W?.35:1,T=d&&N.length===1?D-22:D,E=[];if(d&&N.length>=1){const C=[{x:m,y:g},...N,{x:y,y:b}];for(let S=0;S<C.length-1;S++){const B=C[S],oe=C[S+1];if(Math.hypot(oe.x-B.x,oe.y-B.y)<72)continue;const L={x:Math.round((B.x+oe.x)/2),y:Math.round((B.y+oe.y)/2)};te&&Math.hypot(L.x-Z,L.y-T)<22||E.push({index:S,mid:L})}}return o.jsxs(o.Fragment,{children:[!p&&o.jsx("defs",{children:o.jsx("marker",{id:me,viewBox:"-10 -10 20 20",refX:"0",refY:"0",markerWidth:"12.5",markerHeight:"12.5",orient:"auto-start-reverse",children:o.jsx("polyline",{stroke:se,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1",fill:se,points:"-5,-4 0,0 -5,4 -5,-4"})})}),o.jsx("path",{d:w,fill:"none",stroke:"transparent",strokeWidth:20,className:"react-flow__edge-interaction"}),o.jsx("path",{d:w,fill:"none",pointerEvents:"none",style:{stroke:"var(--rl-canvas-bg, #020617)",strokeWidth:le+4,strokeLinecap:"round",strokeLinejoin:"round",opacity:l!=null&&l.dimmed||l!=null&&l.softDimmed&&!W?0:.92}}),je?o.jsxs("g",{style:{opacity:G},children:[o.jsx("path",{d:w,fill:"none",className:"react-flow__edge-path",style:{stroke:se,strokeWidth:le,strokeDasharray:"6 4"}}),o.jsx("path",{d:w,fill:"none",pathLength:100,style:{stroke:se,strokeWidth:le,strokeDasharray:"50 100",strokeDashoffset:ue?0:-50},pointerEvents:"none"})]}):o.jsx(ul,{id:e,path:w,markerEnd:p?void 0:`url(#${me})`,style:{stroke:se,strokeWidth:le,strokeDasharray:xe?"6 4":void 0,opacity:G}}),p&&ee==="subtype"&&o.jsx("g",{style:{opacity:G},children:o.jsx(S0,{anchor:{x:y,y:b},outward:Q,color:se,strokeWidth:le})}),p&&ee!=="subtype"&&(ae||fe)&&o.jsxs("g",{style:{opacity:G},children:[ae&&o.jsx(Vo,{anchor:{x:m,y:g},outward:ne,cardinality:ae,color:se,strokeWidth:le}),fe&&o.jsx(Vo,{anchor:{x:y,y:b},outward:Q,cardinality:fe,color:se,strokeWidth:le})]}),o.jsxs(fl,{children:[te&&o.jsxs("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${Z}px,${T}px)`,pointerEvents:"all",zIndex:d?40:l!=null&&l.highlighted?25:10},className:`nodrag nopan inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] shadow-md transition-opacity ${W?"border-sky-400 bg-slate-900 text-sky-100":Se?"border-sky-500/70 bg-slate-900/95 text-sky-100":"border-slate-700 bg-slate-900/95 text-slate-200"} ${l!=null&&l.dimmed?"opacity-20":l!=null&&l.softDimmed&&!W?"opacity-40":"opacity-100"}`,children:[(c==null?void 0:c.step)!==void 0&&o.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-full bg-sky-500 text-[10px] font-bold text-slate-950",children:c.step}),re&&o.jsx(ct,{text:re,detail:l!=null&&l.editSummary&&l.editSummary.length>0?l.editSummary.join(`
96
+ `):void 0,className:"inline-flex min-w-0 max-w-[160px]",children:o.jsx("span",{className:"max-w-[160px] truncate",children:re})}),(c==null?void 0:c.locked)&&o.jsx(Un,{className:"h-2.5 w-2.5 text-violet-400"}),Se&&o.jsx(ct,{text:"Modified edge (right-click to undo)",detail:l!=null&&l.editSummary&&l.editSummary.length>0?l.editSummary.join(`
97
+ `):void 0,alwaysShow:!0,className:"inline-flex shrink-0",children:o.jsx("span",{"data-testid":"edge-edited-badge",className:"max-w-[150px] truncate rounded-full bg-sky-500/20 px-1.5 py-0.2 text-[9px] font-medium text-sky-300 border border-sky-500/40",children:((R=l==null?void 0:l.editSummary)==null?void 0:R[0])??"edited"})})]}),d&&E.map(C=>o.jsx("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${C.mid.x}px,${C.mid.y}px)`,pointerEvents:"all",zIndex:45},title:"Drag to add bend point on this segment",className:"nodrag nopan h-3 w-3 rounded-full border-2 border-sky-400/80 bg-slate-950/90 opacity-65 hover:opacity-100 hover:scale-125 shadow-sm cursor-grab active:cursor-grabbing transition-all",onClick:S=>S.stopPropagation(),onMouseDown:S=>S.stopPropagation(),onPointerDown:S=>X(S,{kind:"insert",index:C.index,initialPt:C.mid})},`split-${C.index}`)),d&&N.map((C,S)=>o.jsx("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${C.x}px,${C.y}px)`,pointerEvents:"all",zIndex:50},title:"Drag to move bend point • Double-click to remove",className:"nodrag nopan h-4 w-4 rounded-full border-2 border-slate-950 bg-sky-400 shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform",onClick:B=>B.stopPropagation(),onMouseDown:B=>B.stopPropagation(),onPointerDown:B=>X(B,{kind:"move",index:S}),onDoubleClick:B=>{var L;B.stopPropagation();const oe=N.filter((be,_e)=>_e!==S);O(oe),(L=l==null?void 0:l.onCommitWaypoints)==null||L.call(l,e,oe,oe.length>0?{source_handle:Sn(i),target_handle:Sn(a)}:void 0)}},`wp-${S}`)),d&&N.length===0&&o.jsx("div",{style:{position:"absolute",transform:`translate(-50%, -50%) translate(${J.x}px,${te?J.y+20:J.y}px)`,pointerEvents:"all",zIndex:50},title:"Drag to manually bend this line",className:"nodrag nopan h-4 w-4 rounded-full border-2 border-sky-400 bg-slate-950 shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform",onClick:C=>C.stopPropagation(),onMouseDown:C=>C.stopPropagation(),onPointerDown:C=>X(C,{kind:"insert",index:0,initialPt:{x:Math.round(J.x),y:Math.round(J.y)}})})]})]})}const C0={draft:{label:"draft",classes:"bg-slate-800 text-slate-300 border-slate-700"},needs_input:{label:"needs input",classes:"bg-amber-500/15 text-amber-300 border-amber-500/40"},approved:{label:"approved",classes:"bg-emerald-500/15 text-emerald-300 border-emerald-500/40"},implemented:{label:"implemented",classes:"bg-teal-500/15 text-teal-300 border-teal-500/40"},drifted:{label:"drifted",classes:"bg-rose-500/20 text-rose-300 border-rose-500/50"}};function E0({field:e}){return o.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[e.pk&&o.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-amber-500/20 px-1 py-0.2 text-[9px] font-bold text-amber-300 border border-amber-500/40",children:[o.jsx(Tl,{className:"h-2.5 w-2.5"}),"PK"]}),e.fk&&o.jsx("span",{className:"rounded bg-sky-500/20 px-1 py-0.2 text-[9px] font-bold text-sky-300 border border-sky-500/40",children:"FK"}),e.unique&&o.jsx("span",{className:"rounded bg-violet-500/20 px-1 py-0.2 text-[9px] font-bold text-violet-300 border border-violet-500/40",children:"UQ"}),e.indexed&&o.jsx("span",{className:"rounded bg-slate-700/70 px-1 py-0.2 text-[9px] font-semibold text-slate-300 border border-slate-600",children:"IDX"})]})}function O0({data:e,selected:t}){const{node:n,diagramType:s,isHumanEdited:r,editSummary:i=[],activeFilter:a="all",latestQuestionPreview:l,waitingOnHumanCount:d,totalOpenThreads:u,dimmed:c,pulsing:f,onToggleLock:p,onInlineUpdateTitle:h,onInlineUpdateItem:x,onInlineAddItem:m,onInlineToggleFieldNullable:g,onInlineUpdateFieldName:y,onInlineAddField:b,onOpenNodeThreads:$,onExpandedChange:k}=e,[_,O]=v.useState({}),[F,N]=v.useState(!1),P=F||Object.values(_).some(Boolean);v.useEffect(()=>()=>{k==null||k(n.id,!1)},[n.id,k]);const[M,A]=v.useState(!1),[q,ne]=v.useState(n.title),[Q,w]=v.useState(null),[Z,D]=v.useState(null),[J,X]=v.useState(""),[W,se]=v.useState(null),[le,me]=v.useState(!1),[ae,fe]=v.useState(""),ee=C0[n.status],ie=s==="er"||n.fields&&n.fields.length>0,V=Xn(n,s),ue=n.fields??[],{visibleCount:we,hiddenCount:je}=mt(ue.length,Bn),xe=F?ue:ue.slice(0,we);let re="border-slate-700/90";t?re="border-sky-400 ring-2 ring-sky-500/40":n.status==="drifted"?re="border-rose-500/80 ring-1 ring-rose-500/30":r?re="border-sky-500/80 ring-2 ring-sky-500/25":d>0?re="border-amber-500/75 ring-1 ring-amber-500/25":n.locked&&(re="border-violet-500/60 ring-1 ring-violet-500/20");const Se=()=>{A(!1);const K=q.trim();K&&K!==n.title?h(n.id,K):ne(n.title)},te=()=>{if(!Q)return;const{sectionId:K,index:$e,draft:Ne}=Q;w(null),x(n.id,K,$e,Ne)},G=K=>{const $e=J.trim();D(null),X(""),$e&&m(n.id,K,$e)},T=()=>{if(!W)return;const{fieldId:K,draft:$e}=W;se(null),y(n.id,K,$e.trim())},E=()=>{const K=ae.trim();me(!1),fe(""),K&&b(n.id,K)},z="!h-3.5 !w-3.5 !z-20 redlinify-handle !border-2 !border-slate-900 !bg-sky-400/90 opacity-75 group-hover:opacity-100 hover:!bg-sky-300 hover:!scale-125 transition-all",R=t?"stroke-sky-400":n.status==="drifted"?"stroke-rose-500":r?"stroke-sky-500":d>0?"stroke-amber-500":n.locked?"stroke-violet-500":"stroke-slate-700",C=t||r?2.2:n.locked||n.status!=="draft"?1.8:1.35,S=t?"drop-shadow-[0_0_8px_rgba(56,189,248,0.45)]":"drop-shadow-lg",B=`${c?"opacity-25":"opacity-100"} ${f?"redlinify-pulse-ring":""}`,oe=()=>o.jsxs(o.Fragment,{children:[o.jsx(gn,{id:"top",type:"source",position:et.Top,className:z}),o.jsx(gn,{id:"right",type:"source",position:et.Right,className:z}),o.jsx(gn,{id:"bottom",type:"source",position:et.Bottom,className:z}),o.jsx(gn,{id:"left",type:"source",position:et.Left,className:z})]}),L=(K=!1)=>M?o.jsx("input",{type:"text",value:q,onChange:$e=>ne($e.target.value),onBlur:Se,onKeyDown:$e=>{$e.key==="Enter"&&Se(),$e.key==="Escape"&&(ne(n.title),A(!1))},autoFocus:!0,className:`nodrag w-full rounded border border-sky-500 bg-slate-950 px-1.5 py-0.5 text-sm font-semibold text-slate-100 focus:outline-none ${K?"text-center text-xs":""}`}):o.jsx("div",{onDoubleClick:$e=>{n.locked||($e.stopPropagation(),ne(n.title),A(!0))},title:n.locked?"Locked node (unlock to edit)":"Double-click to edit title",className:`font-semibold text-slate-100 leading-snug break-words ${K?"text-xs max-w-[190px]":"text-sm"}`,children:n.title}),be=r?o.jsx(ct,{text:"Modified by human since last agent checkpoint",detail:i.length>0?`${i.join(`
98
+ `)}
99
+ (Right-click to undo to unmodified)`:"Right-click to undo to unmodified",alwaysShow:!0,className:"inline-flex shrink-0",children:o.jsx("span",{className:"shrink-0 rounded-full bg-sky-500/15 px-1.5 py-0.5 text-[10px] font-medium text-sky-300 border border-sky-500/30",children:"edited"})}):null,_e=K=>{var $e;if(a==="my_edits"&&r){const Ne=i.length>0?i.slice(0,K?2:4):["Modified since last agent checkpoint"],H=Math.max(0,i.length-Ne.length);return o.jsxs("div",{"data-testid":"node-edit-summary",className:"mt-1.5 w-full rounded-md border border-sky-500/35 bg-sky-500/10 px-2 py-1 text-left text-[10px] leading-snug text-sky-200",children:[o.jsx("ul",{className:"space-y-0.5",children:Ne.map((he,ce)=>o.jsx("li",{className:"truncate font-mono text-[9.5px]",children:he},ce))}),H>0&&o.jsxs("div",{className:"mt-0.5 text-[9px] text-sky-300/80",children:["+",H," more change",H>1?"s":""," (right-click to undo)"]})]})}if(a==="waiting_on_me"&&l)return o.jsx("div",{"data-testid":"node-question-preview",className:"mt-1.5 w-full rounded-md border border-amber-500/35 bg-amber-500/10 px-2 py-1 text-left text-[10px] leading-snug text-amber-200",children:o.jsxs("p",{className:"line-clamp-2",children:[o.jsx("span",{className:"font-semibold text-amber-300",children:"Q: "}),l]})});if(a==="drifted"&&n.status==="drifted"){const Ne=(($e=n.code_refs)==null?void 0:$e.length)??0;return o.jsx("div",{"data-testid":"node-drifted-summary",className:"mt-1.5 w-full rounded-md border border-rose-500/35 bg-rose-500/10 px-2 py-1 text-left text-[10px] leading-snug text-rose-200",children:o.jsxs("p",{className:"truncate",children:["Code drifted (",Ne," ref",Ne===1?"":"s",") • right-click to update"]})})}return null},ve=u>0?o.jsxs("button",{type:"button",onClick:K=>{K.stopPropagation(),$(n.id)},title:`${u} open thread(s)`,className:`nodrag inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold ${d>0?"border-amber-500/40 bg-amber-500/20 text-amber-200":"border-slate-700 bg-slate-800 text-slate-300"}`,children:[o.jsx(Us,{className:"h-2.5 w-2.5"}),u]}):null,Oe=o.jsx("button",{type:"button",onClick:K=>{K.stopPropagation(),p(n.id)},title:n.locked?"Locked (agent cannot mutate). Click to unlock.":"Unlocked. Click to lock.",className:`nodrag rounded p-1 transition-colors ${n.locked?"border border-violet-500/35 bg-violet-500/15 text-violet-300 hover:bg-violet-500/25":"text-slate-500 hover:bg-slate-800 hover:text-slate-200"}`,children:n.locked?o.jsx(Un,{className:"h-3.5 w-3.5"}):o.jsx(Hs,{className:"h-3.5 w-3.5"})});if(V==="decision")return o.jsxs("div",{"data-shape":"decision",className:`group relative flex min-w-[244px] max-w-[290px] min-h-[144px] items-center justify-center px-11 py-6 transition-all ${B}`,children:[oe(),o.jsx("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",className:`pointer-events-none absolute inset-0 h-full w-full ${S}`,children:o.jsx("polygon",{points:"50,2 98,50 50,98 2,50",vectorEffect:"non-scaling-stroke",strokeWidth:C,strokeLinejoin:"round",className:`fill-slate-900/95 transition-colors ${R}`})}),o.jsxs("div",{className:"relative z-10 flex max-w-[168px] flex-col items-center gap-1 text-center",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-1",children:[o.jsx("span",{className:"font-mono text-[9px] font-semibold uppercase tracking-wider text-sky-400",children:n.kind}),o.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.2 text-[9px] font-medium ${ee.classes}`,children:ee.label})]}),L(!0),n.summary&&o.jsx(ct,{text:n.summary,className:"block w-full",children:o.jsx("p",{className:"text-[10px] leading-tight text-slate-400 line-clamp-2",children:n.summary})}),_e(!0),o.jsxs("div",{className:"mt-0.5 flex items-center justify-center gap-1",children:[be,ve,Oe]})]})]});if(V==="terminal")return o.jsxs("div",{"data-shape":"terminal",className:`group relative min-w-[200px] max-w-[290px] rounded-full border bg-slate-900/95 px-6 py-2.5 shadow-xl backdrop-blur-sm transition-all ${re} ${B}`,children:[oe(),o.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[o.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-1",children:[o.jsx("span",{className:"rounded bg-slate-800 px-1.5 py-0.2 font-mono text-[9px] font-semibold uppercase tracking-wider text-sky-300 border border-slate-700",children:n.kind}),o.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.2 text-[9px] font-medium ${ee.classes}`,children:ee.label}),be,ve,Oe]}),L(!0),n.summary&&o.jsx(ct,{text:n.summary,className:"block max-w-[230px]",children:o.jsx("p",{className:"text-[11px] text-slate-400 leading-snug line-clamp-2 max-w-[230px]",children:n.summary})}),_e(!0),(n.entity_ref||n.code_refs&&n.code_refs.length>0)&&o.jsxs("div",{className:"flex items-center gap-2 text-[9.5px] font-mono text-slate-400",children:[n.entity_ref&&o.jsx(ct,{text:n.entity_ref,className:"inline-flex min-w-0 max-w-[130px]",children:o.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0 max-w-full",children:[o.jsx($s,{className:"h-2.5 w-2.5 shrink-0 text-sky-400"}),o.jsx("span",{className:"truncate",children:n.entity_ref})]})}),n.code_refs&&n.code_refs.length>0&&o.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-300",children:[o.jsx(Ns,{className:"h-2.5 w-2.5"}),n.code_refs.length," ref",n.code_refs.length>1?"s":""]})]})]})]});const ye=V==="store";return o.jsxs("div",{"data-shape":V,"data-expanded":P?"true":void 0,className:ye?`group relative min-w-[270px] max-w-[350px] pt-5 pb-3 transition-all ${B}`:`group relative min-w-[270px] max-w-[350px] rounded-xl border bg-slate-900/95 shadow-xl backdrop-blur-sm transition-all ${re} ${B}`,children:[oe(),ye&&o.jsxs("svg",{viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",className:`pointer-events-none absolute inset-0 h-full w-full ${S}`,children:[o.jsx("path",{d:"M 1 8.5 L 1 92 A 49 7 0 0 0 99 92 L 99 8.5 Z",vectorEffect:"non-scaling-stroke",strokeWidth:C,className:`fill-slate-900/95 transition-colors ${R}`}),o.jsx("ellipse",{cx:"50",cy:"8.5",rx:"49",ry:"7",vectorEffect:"non-scaling-stroke",strokeWidth:C,className:`fill-slate-800/90 transition-colors ${R}`})]}),o.jsxs("div",{className:ye?"relative z-10 px-0.5":"",children:[o.jsxs("div",{className:`flex items-center justify-between gap-2 border-b px-3 py-2 ${ye?"border-slate-800/80 bg-transparent":"rounded-t-xl border-slate-800 bg-slate-900"}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 rounded bg-slate-800 px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wider text-sky-300 border border-slate-700",children:[ie&&o.jsx(Zt,{className:"h-2.5 w-2.5 text-emerald-400"}),n.kind]}),o.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${ee.classes}`,children:ee.label}),be]}),o.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[ve,Oe]})]}),o.jsxs("div",{className:"px-3 py-2",children:[L(!1),n.summary&&o.jsx(ct,{text:n.summary,className:"block w-full",children:o.jsx("p",{className:"mt-1 text-[11px] text-slate-400 leading-relaxed line-clamp-2",children:n.summary})}),_e(!1)]}),ie&&o.jsxs("div",{className:"border-t border-slate-800 px-3 py-2",children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[o.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-emerald-400/90",children:"Attributes"}),o.jsx("span",{className:"text-[10px] font-mono text-slate-600",children:ue.length})]}),ue.length===0&&!le?o.jsx("p",{className:"text-[11px] italic text-slate-600",children:"No attributes"}):o.jsx("ul",{className:F?"space-y-1 max-h-[380px] overflow-y-auto nowheel pr-1":"space-y-1",children:xe.map(K=>{const $e=(W==null?void 0:W.fieldId)===K.id;return o.jsxs("li",{className:"flex items-center justify-between gap-1.5 rounded px-1 py-0.5 text-[11px] hover:bg-slate-800/60",children:[o.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[o.jsx("button",{type:"button",disabled:n.locked,onClick:Ne=>{Ne.stopPropagation(),g(n.id,K.id)},title:K.nullable?"Nullable (optional ○) — click to mark mandatory (*)":"Mandatory (NOT NULL *) — click to mark nullable (○)",className:`nodrag w-3.5 shrink-0 text-center font-mono text-xs font-bold leading-none ${K.nullable?"text-slate-400 hover:text-amber-300":"text-rose-400 hover:text-rose-300"} disabled:opacity-60`,children:K.nullable?"○":"*"}),$e?o.jsx("input",{type:"text",value:W.draft,onChange:Ne=>se({fieldId:K.id,draft:Ne.target.value}),onBlur:T,onKeyDown:Ne=>{Ne.key==="Enter"&&T(),Ne.key==="Escape"&&se(null)},autoFocus:!0,className:"nodrag w-full rounded border border-sky-500 bg-slate-950 px-1 py-0.2 font-mono text-[11px] text-slate-100 focus:outline-none"}):o.jsx(ct,{text:`${K.name}${K.type?`: ${K.type}`:""}${K.nullable?" (nullable)":" (NOT NULL)"}`,detail:[K.default_value?`default: ${K.default_value}`:"",K.note??""].filter(Boolean).join(" · ")||void 0,alwaysShow:!!(K.default_value||K.note),className:"inline-flex min-w-0 max-w-full",children:o.jsxs("span",{onDoubleClick:Ne=>{n.locked||(Ne.stopPropagation(),se({fieldId:K.id,draft:K.name}))},className:"truncate font-mono text-slate-100 max-w-full",children:[K.name,K.type&&o.jsxs("span",{className:"text-slate-400",children:[": ",K.type]})]})})]}),o.jsx(E0,{field:K})]},K.id)})}),je>0&&o.jsx("button",{type:"button",onClick:K=>{K.stopPropagation();const $e=!F;N($e);const Ne=$e||Object.values(_).some(Boolean);k==null||k(n.id,Ne)},className:"nodrag mt-1 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium text-sky-400 hover:bg-slate-800",children:F?o.jsxs(o.Fragment,{children:[o.jsx(Rr,{className:"h-3 w-3"})," Show less"]}):o.jsxs(o.Fragment,{children:[o.jsx(Ot,{className:"h-3 w-3"})," +",je," more"]})}),!n.locked&&o.jsx("div",{className:"mt-1.5",children:le?o.jsx("input",{type:"text",value:ae,onChange:K=>fe(K.target.value),onBlur:E,onKeyDown:K=>{K.key==="Enter"&&E(),K.key==="Escape"&&(me(!1),fe(""))},placeholder:"column_name",autoFocus:!0,className:"nodrag w-full rounded border border-sky-500 bg-slate-950 px-2 py-0.5 font-mono text-[11px] text-slate-100 placeholder:text-slate-600 focus:outline-none"}):o.jsxs("button",{type:"button",onClick:K=>{K.stopPropagation(),me(!0)},className:"nodrag inline-flex items-center gap-1 rounded px-1 py-0.5 text-[10px] text-slate-400 hover:bg-slate-800 hover:text-sky-300",children:[o.jsx(xt,{className:"h-2.5 w-2.5"})," Add attribute"]})})]}),n.sections.length>0&&o.jsx("div",{className:"divide-y divide-slate-800 border-t border-slate-800",children:n.sections.map(K=>{const $e=_[K.id]===!0,{visibleCount:Ne,hiddenCount:H}=mt(K.items.length,dn),he=$e?K.items:K.items.slice(0,Ne);return o.jsxs("div",{"data-section-id":K.id,className:"px-3 py-2",children:[o.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[o.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-slate-400",children:K.heading}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[!n.locked&&o.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),D(K.id),X("")},title:`Add line to ${K.heading}`,className:"nodrag rounded p-0.5 text-slate-500 opacity-0 group-hover:opacity-100 hover:bg-slate-800 hover:text-sky-300 transition-opacity",children:o.jsx(xt,{className:"h-3 w-3"})}),o.jsx("span",{className:"text-[10px] font-mono text-slate-600",children:K.items.length})]})]}),K.items.length===0&&Z!==K.id?o.jsx("p",{className:"text-[11px] italic text-slate-600",children:"No items"}):o.jsx("ul",{className:$e?"space-y-0.5 max-h-[320px] overflow-y-auto nowheel pr-1":"space-y-0.5",children:he.map((ce,Je)=>{const De=Q&&Q.sectionId===K.id&&Q.index===Je?Q:null;return o.jsx("li",{className:"text-xs",children:De?o.jsx("input",{type:"text",value:De.draft,onChange:Fe=>w({sectionId:K.id,index:Je,draft:Fe.target.value}),onBlur:te,onKeyDown:Fe=>{Fe.key==="Enter"&&te(),Fe.key==="Escape"&&w(null)},autoFocus:!0,className:"nodrag w-full rounded border border-sky-500 bg-slate-950 px-1.5 py-0.5 font-mono text-[11px] text-slate-100 focus:outline-none"}):o.jsx(ct,{text:ce,className:"block min-w-0 w-full",children:o.jsx("div",{onDoubleClick:Fe=>{n.locked||(Fe.stopPropagation(),w({sectionId:K.id,index:Je,draft:ce}))},className:"truncate rounded px-1 py-0.5 font-mono text-[11px] text-slate-200 hover:bg-slate-800/70",children:ce})})},`${K.id}-${Je}`)})}),Z===K.id&&o.jsx("input",{type:"text",value:J,onChange:ce=>X(ce.target.value),onBlur:()=>G(K.id),onKeyDown:ce=>{ce.key==="Enter"&&G(K.id),ce.key==="Escape"&&(D(null),X(""))},placeholder:"New entry...",autoFocus:!0,className:"nodrag mt-1 w-full rounded border border-sky-500 bg-slate-950 px-1.5 py-0.5 font-mono text-[11px] text-slate-100 placeholder:text-slate-600 focus:outline-none"}),H>0&&o.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation();const Je=!$e,De={..._,[K.id]:Je};O(De);const Fe=F||Object.values(De).some(Boolean);k==null||k(n.id,Fe)},className:"nodrag mt-1 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium text-sky-400 hover:bg-slate-800",children:$e?o.jsxs(o.Fragment,{children:[o.jsx(Rr,{className:"h-3 w-3"})," Show less"]}):o.jsxs(o.Fragment,{children:[o.jsx(Ot,{className:"h-3 w-3"})," +",H," more"]})})]},K.id)})}),(n.entity_ref||n.code_refs&&n.code_refs.length>0)&&o.jsxs("div",{className:`flex items-center justify-between gap-2 border-t px-3 py-1.5 text-[10px] text-slate-400 ${ye?"border-slate-800/80 bg-transparent":"rounded-b-xl border-slate-800/90 bg-slate-950/60"}`,children:[o.jsx("div",{className:"flex items-center gap-1 truncate min-w-0 flex-1",children:n.entity_ref&&o.jsx(ct,{text:n.entity_ref,className:"inline-flex min-w-0 max-w-full",children:o.jsxs("span",{className:"inline-flex items-center gap-1 min-w-0 font-mono text-slate-400",children:[o.jsx($s,{className:"h-2.5 w-2.5 shrink-0 text-sky-400"}),o.jsx("span",{className:"truncate",children:n.entity_ref})]})})}),n.code_refs&&n.code_refs.length>0&&o.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 font-mono text-emerald-300",children:[o.jsx(Ns,{className:"h-2.5 w-2.5"}),n.code_refs.length," ref",n.code_refs.length>1?"s":""]})]})]})]})}const z0=v.memo(O0);function T0({projectName:e,projectRootDir:t,tabs:n,viewRequests:s,activeViewId:r,onSelectView:i,onReorderTabs:a,onDeleteRequest:l,onRequestView:d,onCreateBlankView:u,onDeleteView:c,onOpenSearch:f,theme:p,onToggleTheme:h,bgPattern:x,onToggleBgPattern:m}){const[g,y]=v.useState(null),[b,$]=v.useState(!1),[k,_]=v.useState("blank"),[O,F]=v.useState(""),[N,P]=v.useState(""),[M,A]=v.useState("general"),[q,ne]=v.useState("TB"),[Q,w]=v.useState(!1),[Z,D]=v.useState(null),[J,X]=v.useState(null),[W,se]=v.useState(null),[le,me]=v.useState(""),[ae,fe]=v.useState(!1),ee=v.useRef(null),[ie,V]=v.useState(!1),[ue,we]=v.useState(!1),je=v.useCallback(()=>{const T=ee.current;if(!T){V(!1),we(!1);return}V(T.scrollLeft>2),we(T.scrollLeft+T.clientWidth<T.scrollWidth-2)},[]);v.useEffect(()=>{const T=ee.current;if(!T)return;je();const E=()=>je(),z=C=>{T.scrollWidth<=T.clientWidth||Math.abs(C.deltaY)>Math.abs(C.deltaX)&&(C.preventDefault(),T.scrollLeft+=C.deltaY)};T.addEventListener("scroll",E,{passive:!0}),T.addEventListener("wheel",z,{passive:!1});const R=new ResizeObserver(()=>je());return R.observe(T),()=>{T.removeEventListener("scroll",E),T.removeEventListener("wheel",z),R.disconnect()}},[je]),v.useEffect(()=>{const T=requestAnimationFrame(()=>je());return()=>cancelAnimationFrame(T)},[n.length,s.length,je]),v.useEffect(()=>{if(!r||!ee.current)return;const T=ee.current.querySelector(`[data-tab-view-id="${CSS.escape(r)}"]`);T==null||T.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})},[r,n.length]);const xe=T=>{if(!g||g===T){y(null);return}const E=n.findIndex(S=>S.view_id===g),z=n.findIndex(S=>S.view_id===T);if(y(null),E===-1||z===-1)return;const R=[...n],[C]=R.splice(E,1);C&&(R.splice(z,0,C),a(R.map((S,B)=>({...S,order:B}))))},re=()=>{$(!1),F(""),P(""),A("general"),ne("TB"),D(null)},Se=async T=>{if(T.preventDefault(),!O.trim()){D("Title is required.");return}if(k==="request"&&!N.trim()){D("Prompt is required to request a view from the agent.");return}w(!0),D(null);try{if(k==="request"){const E=M==="er"?`[ER Diagram] ${N.trim()}`:N.trim();await d({title:O.trim(),prompt:E})}else await u({title:O.trim(),diagram_type:M,direction:q});re()}catch(E){D(E instanceof Error?E.message:"Failed to create view")}finally{w(!1)}},te=W!==null&&(le.trim()===W.title||le.trim()===W.view_id),G=async T=>{if(T.preventDefault(),!(!W||!te)){fe(!0);try{await c(W.view_id),se(null),me("")}finally{fe(!1)}}};return o.jsxs(o.Fragment,{children:[o.jsxs("header",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-slate-800 bg-slate-900 px-3 overflow-hidden",children:[o.jsxs("div",{className:"flex shrink-0 items-center gap-2 pr-2 border-r border-slate-800",children:[o.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-amber-500/15 text-amber-400 border border-amber-500/30",children:o.jsx(Fs,{className:"h-3.5 w-3.5"})}),o.jsx("span",{className:"text-xs font-semibold tracking-wide text-slate-100",children:"Redlinify"}),o.jsx("span",{title:t?`${e} (${t})`:e,className:"hidden sm:inline-block rounded bg-slate-800 px-1.5 py-0.5 text-[11px] font-mono text-slate-400",children:e})]}),o.jsxs("div",{className:"flex flex-1 min-w-0 items-center gap-1 overflow-hidden",children:[ie&&o.jsx("button",{type:"button",onClick:()=>{var T;return(T=ee.current)==null?void 0:T.scrollBy({left:-220,behavior:"smooth"})},title:"Scroll tabs left","aria-label":"Scroll tabs left",className:"flex h-7 w-6 shrink-0 items-center justify-center rounded-md border border-slate-700 bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",children:o.jsx(Pl,{className:"h-3.5 w-3.5"})}),o.jsxs("nav",{ref:ee,"aria-label":"Diagram tabs",className:"redlinify-tab-strip flex min-w-0 items-center gap-1 overflow-x-auto",children:[n.map((T,E)=>{const z=T.view_id===r,R=T.has_human_edits||T.waiting_on_agent>0,C=T.drifted_count>0,S=T.diagram_type==="er",B=E<9?` · Press ${E+1}`:"";return o.jsxs("div",{"data-tab-view-id":T.view_id,draggable:!0,onDragStart:()=>y(T.view_id),onDragOver:oe=>oe.preventDefault(),onDrop:()=>xe(T.view_id),onContextMenu:oe=>{oe.preventDefault(),X({x:oe.clientX,y:oe.clientY,tab:T})},className:`group flex shrink-0 items-center gap-1 rounded-t-md border-b-2 transition-colors ${z?"bg-slate-950 text-slate-50 border-sky-400":"bg-slate-900/40 text-slate-400 border-transparent hover:bg-slate-800/70 hover:text-slate-200"}`,children:[o.jsxs("button",{type:"button",onClick:()=>i(T.view_id),title:`${T.description??T.title}${B} (Right-click for options)`,className:"flex items-center gap-1.5 pl-3 pr-1.5 py-1.5 text-xs font-medium",children:[S&&o.jsx(Zt,{className:"h-3 w-3 shrink-0 text-emerald-400"}),o.jsx("span",{className:"truncate max-w-[160px]",children:T.title}),T.waiting_on_human>0&&o.jsx("span",{title:`${T.waiting_on_human} open thread(s) waiting on you`,className:"inline-flex items-center justify-center rounded-full bg-amber-500/20 px-1.5 py-0.2 text-[10px] font-semibold text-amber-300 border border-amber-500/40",children:T.waiting_on_human}),R&&o.jsx("span",{title:"Unsynced local edits or replies waiting on agent",className:"h-2 w-2 rounded-full bg-sky-400"}),C&&o.jsx("span",{title:`${T.drifted_count} drifted node(s)`,className:"h-2 w-2 rounded-full bg-rose-500"})]}),o.jsx("button",{type:"button",onClick:oe=>{oe.stopPropagation();const L=oe.currentTarget.getBoundingClientRect();X({x:L.left,y:L.bottom+4,tab:T})},className:`mr-1 rounded p-0.5 text-slate-500 hover:bg-slate-800 hover:text-slate-200 transition-opacity ${z?"opacity-80":"opacity-0 group-hover:opacity-80"}`,title:"Tab options","aria-label":`Tab options for ${T.title}`,children:o.jsx(Al,{className:"h-3 w-3"})})]},T.view_id)}),s.map(T=>o.jsxs("div",{title:`Pending agent request: ${T.prompt}`,className:"flex shrink-0 items-center gap-1.5 rounded-md border border-dashed border-slate-700 bg-slate-900/60 px-2.5 py-1 text-xs text-slate-400",children:[o.jsx(Dl,{className:"h-3 w-3 text-amber-400"}),o.jsx("span",{className:"max-w-[140px] truncate",children:T.title}),o.jsx("button",{type:"button",onClick:()=>l(T.id),className:"ml-0.5 rounded p-0.5 text-slate-500 hover:bg-slate-800 hover:text-slate-200","aria-label":`Cancel view request ${T.title}`,children:o.jsx($t,{className:"h-3 w-3"})})]},T.id))]}),ue&&o.jsx("button",{type:"button",onClick:()=>{var T;return(T=ee.current)==null?void 0:T.scrollBy({left:220,behavior:"smooth"})},title:"Scroll tabs right","aria-label":"Scroll tabs right",className:"flex h-7 w-6 shrink-0 items-center justify-center rounded-md border border-slate-700 bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",children:o.jsx(an,{className:"h-3.5 w-3.5"})}),o.jsx("button",{type:"button",onClick:()=>$(!0),className:"ml-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-slate-700 bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",title:"Request or create a new view","aria-label":"Add or request view",children:o.jsx(xt,{className:"h-3.5 w-3.5"})})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-l border-slate-800 pl-2",children:[o.jsxs("button",{type:"button",onClick:f,title:"Quick search & jump (Ctrl+K or /)","aria-label":"Search workspace",className:"inline-flex h-7 items-center gap-1.5 rounded-md border border-slate-700 bg-slate-800/80 px-2 text-xs text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",children:[o.jsx(Rs,{className:"h-3.5 w-3.5 text-sky-400"}),o.jsx("span",{className:"hidden sm:inline",children:"Search"}),o.jsx("kbd",{className:"hidden md:inline rounded border border-slate-700 bg-slate-900 px-1 py-0.2 font-mono text-[10px] text-slate-400",children:"Ctrl K"})]}),o.jsx("button",{type:"button",onClick:m,title:x==="dots"?"Switch canvas background to grid":"Switch canvas background to dots","aria-label":"Toggle canvas background pattern",className:"flex h-7 w-7 items-center justify-center rounded-md border border-slate-700 bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",children:x==="dots"?o.jsx(Il,{className:"h-3.5 w-3.5 text-slate-300"}):o.jsx(Ll,{className:"h-3.5 w-3.5 text-sky-400"})}),o.jsx("button",{type:"button",onClick:h,title:p==="dark"?"Switch to light theme":"Switch to dark theme","aria-label":"Toggle color theme",className:"flex h-7 w-7 items-center justify-center rounded-md border border-slate-700 bg-slate-800/80 text-slate-300 hover:bg-slate-700 hover:text-slate-50 transition-colors",children:p==="dark"?o.jsx(Bl,{className:"h-3.5 w-3.5 text-amber-300"}):o.jsx(Zl,{className:"h-3.5 w-3.5 text-sky-400"})})]})]}),J&&o.jsx(da,{x:J.x,y:J.y,header:J.tab.title,onClose:()=>X(null),items:[{id:"open",label:"Switch to Tab",onSelect:()=>i(J.tab.view_id)},{id:"delete",label:"Delete Tab...",danger:!0,dividerBefore:!0,onSelect:()=>{se(J.tab),me("")}}]}),W&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Delete Tab Permanently",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 backdrop-blur-sm",children:o.jsxs("div",{className:"w-full max-w-md rounded-xl border border-rose-500/40 bg-slate-900 p-5 shadow-2xl",children:[o.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-rose-300",children:[o.jsx(Js,{className:"h-5 w-5 shrink-0"}),o.jsx("h2",{className:"text-sm font-semibold",children:"Delete Tab Permanently"})]}),o.jsx("button",{type:"button",onClick:()=>se(null),className:"rounded p-1 text-slate-400 hover:bg-slate-800",children:o.jsx($t,{className:"h-4 w-4"})})]}),o.jsxs("p",{className:"text-xs text-slate-300 leading-relaxed mb-3",children:["This will permanently remove"," ",o.jsxs("code",{className:"font-mono text-rose-200",children:[".design/views/",W.view_id,".json"]})," ","and its local layout/checkpoint. Resolved ADR threads stay archived in ",o.jsx("code",{className:"font-mono text-slate-400",children:".design/threads/"}),"."]}),o.jsxs("form",{onSubmit:G,className:"space-y-3",children:[o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-slate-400 mb-1",children:["Type"," ",o.jsx("span",{className:"font-semibold text-slate-100 select-all",children:W.title})," ","(or"," ",o.jsx("code",{className:"font-mono text-slate-200 select-all",children:W.view_id}),") to confirm:"]}),o.jsx("input",{type:"text",value:le,onChange:T=>me(T.target.value),placeholder:W.title,autoFocus:!0,className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-xs text-slate-100 placeholder:text-slate-600 focus:border-rose-500 focus:outline-none"})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{type:"button",onClick:()=>se(null),className:"rounded-lg border border-slate-700 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-800",children:"Cancel"}),o.jsxs("button",{type:"submit",disabled:!te||ae,className:"inline-flex items-center gap-1.5 rounded-lg bg-rose-600 px-3.5 py-1.5 text-xs font-semibold text-white hover:bg-rose-500 disabled:opacity-40 disabled:cursor-not-allowed",children:[o.jsx(sn,{className:"h-3.5 w-3.5"}),ae?"Deleting...":"Delete Tab"]})]})]})]})}),b&&o.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Add Design View",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm",children:o.jsxs("div",{className:"w-full max-w-md rounded-xl border border-slate-700 bg-slate-900 p-5 shadow-2xl",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("h2",{className:"text-sm font-semibold text-slate-100",children:"Add Design View"}),o.jsx("button",{type:"button",onClick:re,className:"rounded p-1 text-slate-400 hover:bg-slate-800 hover:text-slate-100",children:o.jsx($t,{className:"h-4 w-4"})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-4",children:[o.jsx("button",{type:"button",onClick:()=>_("blank"),className:`rounded-lg border px-3 py-2 text-xs font-medium transition-colors ${k==="blank"?"border-sky-500 bg-sky-500/15 text-sky-200":"border-slate-700 bg-slate-800/50 text-slate-400 hover:text-slate-200"}`,children:"Create Blank View"}),o.jsx("button",{type:"button",onClick:()=>_("request"),className:`rounded-lg border px-3 py-2 text-xs font-medium transition-colors ${k==="request"?"border-sky-500 bg-sky-500/15 text-sky-200":"border-slate-700 bg-slate-800/50 text-slate-400 hover:text-slate-200"}`,children:"Request View from Agent"})]}),o.jsxs("form",{onSubmit:Se,className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Diagram Type"}),o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>A("general"),className:`rounded-lg border px-3 py-2 text-left text-xs transition-colors ${M==="general"?"border-sky-500 bg-sky-500/15 text-sky-100":"border-slate-700 bg-slate-950 text-slate-400"}`,children:[o.jsx("div",{className:"font-semibold",children:"General Diagram"}),o.jsx("div",{className:"text-[10px] text-slate-400",children:"Classes, flows, architecture"})]}),o.jsxs("button",{type:"button",onClick:()=>{A("er"),ne("LR")},className:`rounded-lg border px-3 py-2 text-left text-xs transition-colors ${M==="er"?"border-emerald-500 bg-emerald-500/15 text-emerald-100":"border-slate-700 bg-slate-950 text-slate-400"}`,children:[o.jsxs("div",{className:"flex items-center gap-1 font-semibold",children:[o.jsx(Zt,{className:"h-3 w-3 text-emerald-400"}),"ER Diagram"]}),o.jsx("div",{className:"text-[10px] text-slate-400",children:"Entities, PK/FK/null, crow's foot"})]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Tab Title"}),o.jsx("input",{type:"text",value:O,onChange:T=>F(T.target.value),placeholder:M==="er"?"e.g. Database Schema":k==="request"?"e.g. Dataflow":"e.g. Scratchpad",className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none",autoFocus:!0})]}),k==="request"?o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Prompt for Coding Agent"}),o.jsx("textarea",{rows:3,value:N,onChange:T=>P(T.target.value),placeholder:M==="er"?"Model tables, foreign keys, and cardinalities for orders & billing":"Show event ingestion, caching, and deduplication stages",className:"w-full rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-xs text-slate-100 placeholder:text-slate-600 focus:border-sky-500 focus:outline-none"})]}):o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-slate-300 mb-1",children:"Layout Direction"}),o.jsx("div",{className:"flex gap-2",children:["TB","LR"].map(T=>o.jsx("button",{type:"button",onClick:()=>ne(T),className:`flex-1 rounded-lg border px-3 py-1.5 text-xs font-medium ${q===T?"border-sky-500 bg-sky-500/15 text-sky-200":"border-slate-700 bg-slate-950 text-slate-400"}`,children:T==="TB"?"Top → Bottom (TB)":"Left → Right (LR)"},T))})]}),Z&&o.jsx("p",{className:"text-xs text-rose-400 bg-rose-500/10 border border-rose-500/30 rounded-md px-2.5 py-1.5",children:Z}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx("button",{type:"button",onClick:re,className:"rounded-lg border border-slate-700 px-3 py-1.5 text-xs font-medium text-slate-300 hover:bg-slate-800",children:"Cancel"}),o.jsx("button",{type:"submit",disabled:Q,className:"rounded-lg bg-sky-500 px-3.5 py-1.5 text-xs font-semibold text-slate-950 hover:bg-sky-400 disabled:opacity-50",children:Q?"Saving...":k==="request"?"Queue Request":"Create View"})]})]})]})})]})}const P0=[{id:"all",label:"All"},{id:"waiting_on_me",label:"Waiting on Me"},{id:"my_edits",label:"My Edits"},{id:"locked",label:"Locked"},{id:"drifted",label:"Drifted"}];function A0({filter:e,onChangeFilter:t,hasActiveView:n,onExport:s,openQuestionsCount:r,pendingAgentCount:i,decisionsCount:a,activeWorkspaceTab:l,onOpenQuestions:d,onOpenPendingReview:u,onOpenDecisions:c,showOfflineWarning:f}){const[p,h]=v.useState(!1),x=v.useRef(null);v.useEffect(()=>{if(!p)return;const g=b=>{x.current&&!x.current.contains(b.target)&&h(!1)},y=b=>{b.key==="Escape"&&h(!1)};return window.addEventListener("mousedown",g,!0),window.addEventListener("keydown",y),()=>{window.removeEventListener("mousedown",g,!0),window.removeEventListener("keydown",y)}},[p]);const m=g=>{h(!1),s(g)};return o.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-slate-800 bg-slate-900/80 px-3 py-1.5",children:[o.jsx("div",{className:"flex items-center gap-1 overflow-x-auto",children:P0.map(g=>{const y=e===g.id;return o.jsx("button",{type:"button",onClick:()=>t(g.id),className:`shrink-0 rounded-md px-2.5 py-1 text-[11px] font-medium transition-colors ${y?"bg-sky-500/20 text-sky-200 border border-sky-500/40":"text-slate-400 border border-transparent hover:bg-slate-800 hover:text-slate-200"}`,children:g.label},g.id)})}),o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("div",{role:"group","aria-label":"Agent review drawers",className:"flex items-center gap-1 rounded-lg border border-slate-800 bg-slate-950/50 p-0.5",children:[o.jsxs("button",{type:"button",onClick:d,"aria-pressed":l==="questions",className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors ${l==="questions"?"bg-amber-500/25 text-amber-100 ring-1 ring-amber-400/60":r>0?"bg-amber-500/15 text-amber-200 hover:bg-amber-500/25":"text-slate-300 hover:bg-slate-800"}`,children:[o.jsx(Rl,{className:"h-3 w-3 text-amber-400"}),o.jsx("span",{children:"Questions"}),o.jsx("span",{className:"rounded bg-slate-900/80 px-1 text-[10px] font-mono",children:r})]}),o.jsxs("button",{type:"button",onClick:u,"aria-pressed":l==="pending",className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors ${l==="pending"?"bg-sky-500/25 text-sky-100 ring-1 ring-sky-400/60":i>0?"bg-sky-500/15 text-sky-200 hover:bg-sky-500/25":"text-slate-300 hover:bg-slate-800"}`,children:[o.jsx(Fl,{className:"h-3 w-3 text-sky-400"}),o.jsx("span",{className:"hidden sm:inline",children:"Pending Review"}),o.jsx("span",{className:"sm:hidden",children:"Review"}),o.jsx("span",{className:"rounded bg-slate-900/80 px-1 text-[10px] font-mono",children:i})]}),o.jsxs("button",{type:"button",onClick:c,"aria-pressed":l==="adrs",title:"View resolved design decisions (ADRs) & project threads",className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors ${l==="adrs"?"bg-emerald-500/25 text-emerald-100 ring-1 ring-emerald-400/60":a>0?"bg-emerald-500/15 text-emerald-200 hover:bg-emerald-500/25":"text-slate-300 hover:bg-slate-800"}`,children:[o.jsx(qs,{className:"h-3 w-3 text-emerald-400"}),o.jsx("span",{children:"Decisions"}),o.jsx("span",{className:"rounded bg-slate-900/80 px-1 text-[10px] font-mono",children:a})]})]}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"hidden sm:block h-4 w-px bg-slate-800"}),o.jsxs("div",{ref:x,className:"relative",children:[o.jsxs("button",{type:"button",onClick:()=>h(g=>!g),"aria-label":"Export diagram","aria-expanded":p,title:"Export active diagram as PNG, SVG, Mermaid, or JSON",className:"inline-flex items-center gap-1 rounded-md border border-slate-700 bg-slate-800/70 px-2.5 py-1 text-[11px] font-medium text-slate-300 hover:bg-slate-700 transition-colors",children:[o.jsx(Ul,{className:"h-3 w-3 text-sky-400"}),o.jsx("span",{className:"hidden sm:inline",children:"Export"}),o.jsx(Ot,{className:"h-3 w-3 text-slate-400"})]}),p&&o.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-40 mt-1.5 min-w-[200px] rounded-xl border border-slate-700 bg-slate-900/95 p-1.5 shadow-2xl backdrop-blur-md",children:[o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m("png"),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 hover:text-slate-50",children:[o.jsx(Fr,{className:"h-3.5 w-3.5 text-sky-400"}),o.jsx("span",{children:"Export PNG (2× HD)"})]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m("svg"),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 hover:text-slate-50",children:[o.jsx(Fr,{className:"h-3.5 w-3.5 text-emerald-400"}),o.jsx("span",{children:"Export SVG (Vector)"})]}),o.jsx("div",{className:"my-1 border-t border-slate-800"}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m("mermaid"),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 hover:text-slate-50",children:[o.jsx(Hl,{className:"h-3.5 w-3.5 text-violet-400"}),o.jsx("span",{children:"Export Mermaid (.mmd)"})]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m("copy_mermaid"),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 hover:text-slate-50",children:[o.jsx(Ks,{className:"h-3.5 w-3.5 text-slate-400"}),o.jsx("span",{children:"Copy Mermaid"})]}),o.jsxs("button",{type:"button",role:"menuitem",onClick:()=>m("json"),className:"flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs text-slate-200 hover:bg-slate-800 hover:text-slate-50",children:[o.jsx(Wl,{className:"h-3.5 w-3.5 text-amber-400"}),o.jsx("span",{children:"Export JSON (.json)"})]})]})]})]}),f&&o.jsxs("span",{title:"Live file sync disconnected — reconnecting automatically...",className:"inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium border border-amber-500/40 bg-amber-500/15 text-amber-200",children:[o.jsx(Kl,{className:"h-2.5 w-2.5"}),o.jsx("span",{children:"Offline — reconnecting"})]})]})]})}const D0={structured:z0},I0={step:M0},L0=["Control","Meta"],B0=["Backspace","Delete"],Z0={hideAttribution:!0},R0=350;function F0(e){const t=new Set;if(!e)return t;for(const n of e.nodes_added)t.add(n.id);for(const n of e.nodes_modified)t.add(n.id);return t}function U0(){var Ar,Dr;const{fitView:e,getViewport:t,setViewport:n,setCenter:s,screenToFlowPosition:r,zoomIn:i,zoomOut:a,zoomTo:l}=ei(),{theme:d,bgPattern:u,scrollMode:c,setScrollMode:f,toggleTheme:p,toggleBgPattern:h}=Zm(),{toast:x,showToast:m}=Rm(),[g,y,b]=pl([]),[$,k,_]=ml([]),[O,F]=v.useState("all"),[N,P]=v.useState("none"),[M,A]=v.useState("spec"),[q,ne]=v.useState("questions"),[Q,w]=v.useState(null),[Z,D]=v.useState(null),[J,X]=v.useState(null),[W,se]=v.useState(null),[le,me]=v.useState(0),[ae,fe]=v.useState(null),ee=v.useRef(null),ie=v.useRef(null),V=v.useRef({}),ue=v.useRef({}),we=v.useRef({}),je=v.useRef({}),xe=v.useRef({}),re=v.useRef({}),Se=v.useRef(null);Se.current=ae??Q;const te=v.useRef(!1),G=v.useRef(0),T=v.useRef(null),E=v.useRef(null),z=v.useRef(null),R=v.useRef(null),C=v.useRef(null),S=v.useRef(null),{historyTick:B,undoMapRef:oe,redoMapRef:L,pushHistoryEntry:be,undoWith:_e,redoWith:ve,clearViewHistory:Oe}=Fm({activeViewRef:E,positionsRef:ue,edgeRoutesRef:we,showToast:m}),{snapshot:ye,tabs:K,activeViewId:$e,setActiveViewId:Ne,activeView:H,setActiveView:he,viewDiff:ce,setViewDiff:Je,viewBaseline:De,allThreads:Fe,wsConnected:ua,wsEverConnected:fa,wsGraceExpired:ha,conflictBanner:pa,layoutVersion:un,setLayoutVersion:yr,pendingViewportSyncRef:Yn,routingTick:ma,setRoutingTick:xa,loadWorkspaceMeta:bt,persistCurrentLayout:br,loadViewDetail:vt,persistView:Xe,applyHistoryEntry:fn}=l0({activeViewIdRef:T,activeViewRef:E,positionsRef:ue,edgeRoutesRef:we,measuredSizesRef:je,elkRoutesRef:xe,viewportReadyRef:te,getViewport:t,pushHistoryEntry:be,showToast:m}),Gn=v.useCallback(()=>_e(fn),[fn,_e]),Qn=v.useCallback(()=>ve(fn),[fn,ve]),hn=v.useMemo(()=>g.filter(j=>j.selected).map(j=>j.id),[g]);v.useEffect(()=>{hn.length>1&&(w(null),D(null),P(j=>j==="node"||j==="edge"?"none":j))},[hn.length]);const lt=v.useCallback(j=>{w(j),D(null),y(U=>{let Y=!1;const pe=U.map(ge=>{const ke=j!==null&&ge.id===j;return!!ge.selected===ke?ge:(Y=!0,{...ge,selected:ke})});return Y?pe:U}),k(U=>{let Y=!1;const pe=U.map(ge=>ge.selected?(Y=!0,{...ge,selected:!1}):ge);return Y?pe:U})},[k,y]),Vn=v.useCallback(j=>{D(j),w(null),y(U=>{let Y=!1;const pe=U.map(ge=>ge.selected?(Y=!0,{...ge,selected:!1}):ge);return Y?pe:U}),k(U=>{let Y=!1;const pe=U.map(ge=>{const ke=j!==null&&ge.id===j;return!!ge.selected===ke?ge:(Y=!0,{...ge,selected:ke})});return Y?pe:U})},[k,y]),{handleToggleLock:es,handleInlineUpdateTitle:vr,handleInlineUpdateItem:kr,handleInlineAddItem:ts,handleInlineToggleFieldNullable:wr,handleInlineUpdateFieldName:_r,handleInlineAddField:ns,handleOpenNodeThreads:ss,handleCommitWaypoints:rs,handleUpdateEdgeRoute:jr,createBoxAtPosition:qt,handleChangeNodeShape:ga,handleAutoLayout:os,handleToggleDirection:$r,snapshotDragOrigin:Nr,handleNodesChange:ya,handleNodeDragStop:ba,handleSelectionDragStop:va,handleMoveEnd:ka,handleReconnectCallback:wa,handleFlipEdge:Sr,handleBeforeDelete:_a,handleConfirmEdge:ja,handleConnect:$a}=ym({activeView:H,activeViewIdRef:T,activeViewRef:E,positionsRef:ue,edgeRoutesRef:we,measuredSizesRef:je,viewportReadyRef:te,pendingSelectNodeIdRef:C,selectedNodeId:Q,selectedEdgeId:Z,setSelectedNodeId:w,setSelectedEdgeId:D,setDrawerMode:P,setElementTab:A,pendingConn:W,setPendingConn:se,setLayoutVersion:yr,setRoutingTick:xa,onNodesChange:b,screenToFlowPosition:r,pushHistoryEntry:be,persistCurrentLayout:br,persistView:Xe,loadViewDetail:vt,selectSingleNode:lt,showToast:m}),Tt=v.useCallback(j=>{const U=Date.now(),Y=V.current[j]??0;return U-Y<R0?!1:(V.current[j]=U,!0)},[]),Jt=v.useMemo(()=>F0(ce),[ce]),is=v.useMemo(()=>c0(ce),[ce]),as=v.useCallback(async j=>{if(!H)return;const U=d0(H,De,j);if(!U){m("No baseline state available to revert","warning");return}const Y=H.nodes.find(pe=>pe.id===j)??(De==null?void 0:De.nodes.find(pe=>pe.id===j));Q===j&&!U.nodes.some(pe=>pe.id===j)&&(w(null),P("none")),await Xe(U),m(`Reverted "${(Y==null?void 0:Y.title)??j}" to unmodified state`)},[H,Xe,Q,m,De]),Na=v.useCallback(async j=>{if(!H)return;const U=u0(H,De,j);if(!U){m("Cannot revert edge (missing endpoint or baseline)","warning");return}Z===j&&!U.edges.some(Y=>Y.id===j)&&(D(null),P("none")),await Xe(U),m("Reverted edge to unmodified state")},[H,Xe,Z,m,De]),ls=v.useCallback(async()=>{if(!H||!De){m("No agent checkpoint baseline to revert to","warning");return}const j=structuredClone(De);Q&&!j.nodes.some(U=>U.id===Q)&&(w(null),P("none")),Z&&!j.edges.some(U=>U.id===Z)&&(D(null),P("none")),await Xe(j),m(`Reverted "${H.title}" to unmodified state`)},[H,Xe,Z,Q,m,De]),Sa=v.useCallback(async()=>{H&&(await Xe({...H,nodes:H.nodes.map(j=>({...j,locked:!1})),edges:H.edges.map(j=>({...j,locked:!1}))}),m(`Unlocked all elements in "${H.title}"`))},[H,Xe,m]),Ma=v.useCallback(async(j,U)=>{H&&(await Xe({...H,nodes:H.nodes.map(Y=>Y.id===j?{...Y,status:U}:Y)}),m(`Marked status as ${U}`))},[H,Xe,m]),cs=v.useCallback(j=>{if(Tt(`workspace:${j}`)){if(N==="workspace"&&q===j){P("none");return}lt(null),P("workspace"),ne(j)}},[Tt,N,lt,q]),Ca=v.useCallback(j=>{Tt(`filter:${j}`)&&F(U=>j!=="all"&&U===j?"all":j)},[Tt]),Mr=v.useCallback(j=>{if(Tt(`node-threads:${j}`)){if(N==="node"&&Q===j&&M==="threads"){P("none");return}ss(j)}},[Tt,N,M,ss,Q]),Ea=v.useCallback(async()=>{if(!E.current)return;const j=ee.current,U=ie.current;if(j&&U){const Y=j.getBoundingClientRect();if(U.x>=Y.left&&U.x<=Y.right&&U.y>=Y.top&&U.y<=Y.bottom){await qt(r(U));return}}await qt()},[qt,r]),{contextMenu:ds,contextMenuData:us,clearContextMenu:Ye,handlePaneContextMenu:Oa,handleNodeContextMenu:za,handleEdgeContextMenu:Ta}=xm({activeView:H,filter:O,viewDiff:ce,viewBaseline:De,editedNodeIds:Jt,editedEdgeIds:is,positionsRef:ue,edgeRoutesRef:we,undoMapRef:oe,redoMapRef:L,historyTick:B,rfNodes:g,selectedNodeId:Q,selectedEdgeId:Z,setSelectedNodeId:w,setSelectedEdgeId:D,setDrawerMode:P,setElementTab:A,setLayoutVersion:yr,screenToFlowPosition:r,selectSingleNode:lt,selectSingleEdge:Vn,createBoxAtPosition:qt,handleChangeNodeShape:ga,handleAutoLayout:os,handleToggleDirection:$r,handleUndo:Gn,handleRedo:Qn,handleRevertNode:as,handleRevertEdge:Na,handleRevertViewToBaseline:ls,handleUnlockAllInView:Sa,handleUpdateNodeStatus:Ma,handleToggleLock:es,handleInlineAddItem:ts,handleInlineAddField:ns,handleOpenNodeThreads:ss,handleCommitWaypoints:rs,handleUpdateEdgeRoute:jr,handleFlipEdge:Sr,persistCurrentLayout:br,persistView:Xe,showToast:m}),Cr=v.useCallback(()=>{Ye(),fe(null),Nr()},[Ye,Nr]),Er=v.useCallback((j,U)=>{if(!!re.current[j]!==U){if(U)re.current={...re.current,[j]:!0};else{const pe={...re.current};delete pe[j],re.current=pe}y(pe=>{let ge=!1;const ke=U?1200:void 0,Te=pe.map(Ue=>Ue.id!==j||Ue.zIndex===ke?Ue:(ge=!0,{...Ue,zIndex:ke}));return ge?Te:pe})}},[y]);v.useEffect(()=>{re.current={},fe(null)},[H==null?void 0:H.id]);const Xt=v.useCallback(async j=>{Ne(j),lt(null),Ye(),(N==="node"||N==="edge")&&P("none"),window.location.hash=`view=${encodeURIComponent(j)}`,await vt(j)},[Ye,N,vt,lt,Ne]),Or=v.useCallback(async(j,U,Y,pe)=>{let ge=E.current;const ke=(U==="node"||U==="edge")&&!!Y;if(j&&j!==T.current&&(C.current=U==="node"&&Y?Y:null,S.current=U==="edge"&&Y?Y:null,Ne(j),window.location.hash=`view=${encodeURIComponent(j)}`,ge=await vt(j,{preserveViewport:ke})),U==="node"&&Y){lt(Y),P("node"),A(pe??"links"),X(Y),setTimeout(()=>{X(Ue=>Ue===Y?null:Ue)},2800);const Te=ue.current[Y];Te?(te.current=!1,requestAnimationFrame(()=>{s(Te.x+150,Te.y+90,{zoom:1,duration:280}),setTimeout(()=>{te.current=!0},320)})):ke&&(te.current=!1,requestAnimationFrame(()=>{e({padding:.16,maxZoom:1.05,duration:180}),setTimeout(()=>{te.current=!0},250)}))}else if(U==="edge"&&Y){Vn(Y),P("edge"),A(pe==="links"?"spec":pe??"threads");const Te=ge==null?void 0:ge.edges.find(Ce=>Ce.id===Y),Ue=Te?ue.current[Te.source]:void 0,ze=Te?ue.current[Te.target]:void 0;if(Ue&&ze){const Ce=(Ue.x+ze.x)/2+150,nt=(Ue.y+ze.y)/2+90;te.current=!1,requestAnimationFrame(()=>{s(Ce,nt,{zoom:1,duration:280}),setTimeout(()=>{te.current=!0},320)})}else ke&&(te.current=!1,requestAnimationFrame(()=>{e({padding:.16,maxZoom:1.05,duration:180}),setTimeout(()=>{te.current=!0},250)}))}else lt(null),P("workspace"),ne("adrs")},[e,vt,Vn,lt,Ne,s]),Pa=v.useCallback(async j=>{var Y;await Up(j),Oe(j);const U=await bt();if(T.current===j){const pe=((Y=U.status.tabs[0])==null?void 0:Y.view_id)??null;Ne(pe),w(null),D(null),P("none"),pe?(window.location.hash=`view=${encodeURIComponent(pe)}`,await vt(pe)):(window.location.hash="",he(null),Je(null))}m(`Deleted tab "${j}"`)},[Oe,vt,bt,he,Ne,Je,m]),{searchOpen:zr,setSearchOpen:Tr,searchLoading:Aa,openSearch:Pr,searchIndexItems:Da,handleSelectSearchItem:Ia}=a0({tabs:K,activeView:H,activeViewId:$e,activeViewRef:E,allThreads:Fe,clearContextMenu:Ye,handleSelectView:Xt,handleJumpToTarget:Or}),{startArrowPan:La,stopArrowPan:Ba,updateArrowShift:Za,stopAllArrowPan:Ra,handleZoomIn:Fa,handleZoomOut:Ua,handleFitView:Ha,handleResetZoom:Wa}=e0({containerRef:ee,activeViewIdRef:T,positionsRef:ue,edgeRoutesRef:we,viewportReadyRef:te,scrollMode:c,getViewport:t,setViewport:n,fitView:e,zoomIn:i,zoomOut:a,zoomTo:l,clearContextMenu:Ye});gm({activeViewIdRef:T,tabs:K,searchOpen:zr,pendingConn:W,setSearchOpen:Tr,openSearch:Pr,clearContextMenu:Ye,handleSelectView:Xt,handleUndo:Gn,handleRedo:Qn,handleAutoLayout:os,handleAddBoxAtCursor:Ea,startArrowPan:La,stopArrowPan:Ba,updateArrowShift:Za,stopAllArrowPan:Ra,handleZoomIn:Fa,handleZoomOut:Ua,handleFitView:Ha,handleResetZoom:Wa});const{handleExportDiagram:Ka}=Bm({activeViewRef:E,positionsRef:ue,edgeRoutesRef:we,rfNodes:g,theme:d,bgPattern:u,showToast:m});v.useEffect(()=>{if(!H){z.current=null,y([]),me(un);return}const j=Fe.filter(pe=>pe.status==="open"&&pe.view_id===H.id),U=C.current;C.current=null;const Y=z.current===H.id;z.current=H.id,y(pe=>{const ge=Y?new Map(pe.map(ke=>[ke.id,ke])):new Map;return H.nodes.map(ke=>{var mn,xn;const Te=j.filter(Ir=>Ir.target_type==="node"&&Ir.target_id===ke.id),Ue=Te.filter(On),ze=Ue.length,Ce=(xn=(mn=Ue[0])==null?void 0:mn.messages[Ue[0].messages.length-1])==null?void 0:xn.body,nt=Jt.has(ke.id),ft=nt?la(ce,ke.id,H.diagram_type??"general"):[];let kt=!0;O==="waiting_on_me"?kt=ze>0:O==="my_edits"?kt=nt:O==="locked"?kt=ke.locked:O==="drifted"&&(kt=ke.status==="drifted");const wt=ge.get(ke.id),ps=U?ke.id===U:!!(wt!=null&&wt.selected),Yt=re.current[ke.id]?1200:void 0;return{...wt??{},id:ke.id,type:"structured",position:ue.current[ke.id]??{x:40,y:40},selected:ps,zIndex:Yt,data:{node:ke,diagramType:H.diagram_type??"general",isHumanEdited:nt,editSummary:ft,activeFilter:O,latestQuestionPreview:Ce,waitingOnHumanCount:ze,totalOpenThreads:Te.length,dimmed:!kt,pulsing:J===ke.id,onToggleLock:es,onInlineUpdateTitle:vr,onInlineUpdateItem:kr,onInlineAddItem:ts,onInlineToggleFieldNullable:wr,onInlineUpdateFieldName:_r,onInlineAddField:ns,onOpenNodeThreads:Mr,onExpandedChange:Er}}})}),me(un)},[H,Fe,Jt,O,Er,ns,ts,wr,_r,kr,vr,es,Mr,un,J,y,ce]),v.useEffect(()=>{const j=Yn.current;if(!j||le<j.layoutVersion)return;Yn.current=null;const U=++G.current,Y=j.kind==="restore"?n(j.viewport,{duration:150}):e({padding:.16,maxZoom:1.05,duration:180});Promise.resolve(Y).finally(()=>{setTimeout(()=>{G.current===U&&(te.current=!0)},80)})},[le,e,Yn,g,n,te]),v.useEffect(()=>{if(!H){R.current=null,k([]);return}const j=Fe.filter(Te=>Te.status==="open"&&Te.view_id===H.id),U=new Set;for(const Te of H.nodes){const ze=j.filter(ft=>ft.target_type==="node"&&ft.target_id===Te.id).filter(On).length,Ce=Jt.has(Te.id);let nt=!0;O==="waiting_on_me"?nt=ze>0:O==="my_edits"?nt=Ce:O==="locked"?nt=Te.locked:O==="drifted"&&(nt=Te.status==="drifted"),nt||U.add(Te.id)}const Y=pr(H,ue.current,we.current,je.current,xe.current),pe=S.current;S.current=null;const ge=R.current===H.id;R.current=H.id;const ke=Se.current;k(Te=>{const Ue=ge?new Map(Te.map(ze=>[ze.id,ze])):new Map;return H.edges.map(ze=>{const Ce=Y[ze.id],nt=H.diagram_type??"general",ft=Ue.get(ze.id),kt=pe?ze.id===pe:!!(ft!=null&&ft.selected),wt=ke!==null&&(ze.source===ke||ze.target===ke),ps=ke!==null&&!wt,Yt=is.has(ze.id),mn=Yt?ca(ce,ze.id):[],xn=O==="my_edits"?!Yt&&U.has(ze.source)&&U.has(ze.target):U.has(ze.source)&&U.has(ze.target);return{...ft??{},id:ze.id,source:ze.source,target:ze.target,sourceHandle:(Ce==null?void 0:Ce.sourceHandle)??"right",targetHandle:(Ce==null?void 0:Ce.targetHandle)??"left",type:"step",selected:kt,zIndex:kt?1e3:wt?900:0,data:{edge:ze,diagramType:nt,dimmed:xn,highlighted:wt,softDimmed:ps,isHumanEdited:Yt,showEditedBadge:O==="my_edits",editSummary:mn,sourcePortOffset:(Ce==null?void 0:Ce.sourcePortOffset)??0,targetPortOffset:(Ce==null?void 0:Ce.targetPortOffset)??0,manualWaypoints:(Ce==null?void 0:Ce.manualWaypoints)??[],autoWaypoints:(Ce==null?void 0:Ce.autoWaypoints)??[],curveOffset:(Ce==null?void 0:Ce.curveOffset)??{x:0,y:0},onCommitWaypoints:rs}}})})},[H,Fe,is,Jt,O,rs,un,ma,k,ce]),v.useEffect(()=>{const j=ae??Q;k(U=>{let Y=!1;const pe=U.map(ge=>{var ze,Ce;const ke=j!==null&&(ge.source===j||ge.target===j),Te=j!==null&&!ke,Ue=ge.selected?1e3:ke?900:0;return!!((ze=ge.data)!=null&&ze.highlighted)===ke&&!!((Ce=ge.data)!=null&&Ce.softDimmed)===Te&&(ge.zIndex??0)===Ue?ge:(Y=!0,{...ge,zIndex:Ue,data:{...ge.data,highlighted:ke,softDimmed:Te}})});return Y?pe:U})},[ae,Q,k]);const qa=v.useMemo(()=>(H==null?void 0:H.nodes.find(j=>j.id===Q))??null,[H,Q]),fs=v.useMemo(()=>(H==null?void 0:H.edges.find(j=>j.id===Z))??null,[H,Z]),Ja=(ye==null?void 0:ye.status.view_requests)??[],pn=(ye==null?void 0:ye.pending_feedback)??{view_hashes:{},view_diffs:[],pending_threads:[],view_requests:[]},Xa=v.useMemo(()=>Fe.filter(On).length,[Fe]),Ya=pn.view_diffs.length+pn.pending_threads.length+pn.view_requests.length,Ga=v.useMemo(()=>Fe.filter(j=>j.status==="resolved").length,[Fe]),Qa=v.useMemo(()=>{var j;return!!(H&&(((j=oe.current.get(H.id))==null?void 0:j.length)??0)>0)},[H,B,oe]),Va=v.useMemo(()=>{var j;return!!(H&&(((j=L.current.get(H.id))==null?void 0:j.length)??0)>0)},[H,B,L]),el=v.useCallback((j,U)=>{Ye(),!(j.ctrlKey||j.metaKey||j.shiftKey)&&(w(U.id),D(null),P("node"))},[Ye]),tl=v.useCallback((j,U)=>{Ye(),fe(null),!(j.ctrlKey||j.metaKey||j.shiftKey)&&(D(U.id),w(null),P("edge"),M==="links"&&A("spec"))},[Ye,M]),nl=v.useCallback(()=>{Ye(),fe(null),w(null),D(null),(N==="node"||N==="edge")&&P("none")},[Ye,N]),sl=v.useCallback((j,U)=>{fe(U.id)},[]),rl=v.useCallback((j,U)=>{fe(Y=>Y===U.id?null:Y)},[]),ol=v.useCallback(j=>{var Y,pe,ge;const U=j.data;return((Y=U==null?void 0:U.node)==null?void 0:Y.status)==="drifted"?d==="dark"?"#f43f5e":"#e11d48":((U==null?void 0:U.waitingOnHumanCount)??0)>0||((pe=U==null?void 0:U.node)==null?void 0:pe.status)==="needs_input"?d==="dark"?"#f59e0b":"#d97706":(ge=U==null?void 0:U.node)!=null&&ge.locked?d==="dark"?"#a78bfa":"#7c3aed":d==="dark"?"#38bdf8":"#0284c7"},[d]),hs=ye==null?void 0:ye.status.project_name;return v.useEffect(()=>{document.title=hs?`${hs} — Redlinify`:"Redlinify"},[hs]),o.jsxs("div",{className:"flex h-screen w-screen flex-col overflow-hidden bg-slate-950 text-slate-100",children:[o.jsx(T0,{projectName:(ye==null?void 0:ye.status.project_name)??"Redlinify",projectRootDir:ye==null?void 0:ye.root_dir,tabs:K,viewRequests:Ja,activeViewId:$e,onSelectView:j=>void Xt(j),onReorderTabs:j=>{Bp(j.map(({view_id:U,title:Y,diagram_type:pe,description:ge,order:ke})=>({view_id:U,title:Y,...pe?{diagram_type:pe}:{},...ge?{description:ge}:{},order:ke}))).then(()=>bt())},onDeleteRequest:j=>{Rp(j).then(()=>bt())},onRequestView:async j=>{await Zp(j),await bt(),m(`Queued view request "${j.title}"`)},onCreateBlankView:async j=>{const U=await Fp(j);await bt(),await Xt(U.view.id)},onDeleteView:Pa,onOpenSearch:Pr,theme:d,onToggleTheme:p,bgPattern:u,onToggleBgPattern:h}),o.jsx(A0,{filter:O,onChangeFilter:Ca,hasActiveView:!!H,onExport:j=>void Ka(j),activeWorkspaceTab:N==="workspace"?q:null,openQuestionsCount:Xa,pendingAgentCount:Ya,decisionsCount:Ga,onOpenQuestions:()=>cs("questions"),onOpenPendingReview:()=>cs("pending"),onOpenDecisions:()=>cs("adrs"),showOfflineWarning:!ua&&(fa||ha)}),pa&&H&&o.jsxs("div",{className:"flex items-center justify-between bg-amber-500/15 border-b border-amber-500/40 px-4 py-1.5 text-xs text-amber-200",children:[o.jsx("span",{children:"This view was updated on disk while you were editing. Reload to sync latest changes."}),o.jsx("button",{type:"button",onClick:()=>void vt(H.id,{preserveViewport:!0}),className:"rounded bg-amber-500 px-2.5 py-0.5 text-xs font-semibold text-slate-950 hover:bg-amber-400",children:"Reload View"})]}),O==="my_edits"&&H&&o.jsx("div",{"data-testid":"my-edits-banner",className:"flex flex-wrap items-center justify-between gap-2 border-b border-sky-500/35 bg-sky-500/10 px-4 py-1.5 text-xs text-sky-100",children:ce&&ce.has_changes?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("span",{className:"font-semibold text-sky-300",children:"Unsynced edits:"}),o.jsxs("span",{children:[ce.nodes_modified.length," modified ·"," ",ce.nodes_added.length," added ·"," ",ce.nodes_removed.length," removed ·"," ",ce.edges_added.length+ce.edges_modified.length+ce.edges_removed.length," ","edge changes"]}),De&&ce.nodes_removed.map(j=>o.jsxs("button",{type:"button",onClick:()=>void as(j.id),className:"inline-flex items-center gap-1 rounded border border-emerald-500/40 bg-emerald-500/15 px-2 py-0.5 text-[11px] font-medium text-emerald-200 hover:bg-emerald-500/25",children:[o.jsx(Rt,{className:"h-3 w-3"}),"Restore ",j.title]},j.id))]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{lt(null),P("workspace"),ne("pending")},className:"rounded border border-slate-700 bg-slate-900/80 px-2 py-0.5 text-[11px] text-slate-200 hover:border-sky-500/60",children:"Inspect Pending"}),De&&o.jsxs("button",{type:"button",onClick:()=>void ls(),className:"inline-flex items-center gap-1 rounded bg-sky-500/20 border border-sky-500/50 px-2 py-0.5 text-[11px] font-semibold text-sky-200 hover:bg-sky-500/30",children:[o.jsx(Rt,{className:"h-3 w-3"}),"Revert All Edits"]})]})]}):o.jsxs("span",{className:"text-slate-300",children:["No unsynced edits in"," ",o.jsx("strong",{className:"text-slate-100",children:H.title})," — matches last agent checkpoint."]})}),o.jsxs("div",{className:"relative flex flex-1 min-h-0",children:[o.jsxs("div",{ref:ee,onMouseMove:j=>{ie.current={x:j.clientX,y:j.clientY}},onMouseLeave:()=>{ie.current=null},className:"relative flex-1 min-w-0 min-h-0",children:[H?o.jsxs(xl,{nodes:g,edges:$,nodeTypes:D0,edgeTypes:I0,connectionMode:gl.Loose,edgesReconnectable:!0,elevateEdgesOnSelect:!0,multiSelectionKeyCode:L0,selectionKeyCode:"Shift",panActivationKeyCode:"Space",zoomOnDoubleClick:!1,zoomOnScroll:!1,panOnScroll:!1,nodeDragThreshold:3,onNodesChange:ya,onEdgesChange:_,onNodeDragStart:Cr,onNodeDragStop:ba,onSelectionDragStart:Cr,onSelectionDragStop:va,onMoveStart:Ye,onMoveEnd:ka,onReconnect:wa,onBeforeDelete:_a,onConnectStart:Ye,onConnect:$a,onNodeClick:el,onNodeMouseEnter:sl,onNodeMouseLeave:rl,onEdgeClick:tl,onPaneClick:nl,onPaneContextMenu:Oa,onNodeContextMenu:za,onEdgeContextMenu:Ta,deleteKeyCode:B0,minZoom:xr,maxZoom:gr,proOptions:Z0,children:[o.jsx(yl,{variant:u==="grid"?Lr.Lines:Lr.Dots,gap:24,size:u==="grid"?1:1.8,color:u==="grid"?d==="dark"?"#1e293b":"#cbd5e1":d==="dark"?"#334155":"#94a3b8"}),o.jsx(bl,{showInteractive:!1}),o.jsx(vl,{className:"hidden sm:block",nodeColor:ol,maskColor:d==="dark"?"rgba(2, 6, 23, 0.75)":"rgba(241, 245, 249, 0.72)"})]}):o.jsxs("div",{className:"flex h-full flex-col items-center justify-center p-6 text-center text-slate-400",children:[o.jsx("div",{className:"mb-3 rounded-2xl border border-slate-800 bg-slate-900 p-4",children:o.jsx(Fs,{className:"h-8 w-8 text-sky-400"})}),o.jsx("h2",{className:"text-base font-semibold text-slate-200",children:"No diagram view open"}),o.jsxs("p",{className:"mt-1 max-w-md text-xs text-slate-400",children:["Click ",o.jsx("span",{className:"font-semibold text-slate-200",children:"+"})," in the top tab bar to create a blank diagram (General or ER) or queue a view request for your coding agent."]})]}),H&&o.jsx(h0,{diagramType:H.diagram_type??"general",direction:H.direction??"TB",canUndo:Qa,canRedo:Va,onAddBox:j=>void qt(void 0,j),onUndo:()=>void Gn(),onRedo:()=>void Qn(),onToggleDirection:()=>void $r(),onAutoLayout:()=>void os()}),H&&o.jsxs("div",{role:"group","aria-label":"Scroll wheel behavior",className:"nowheel absolute bottom-[15px] left-[52px] z-20 flex items-center gap-1.5 rounded-lg border border-slate-700 bg-slate-900/95 p-1 pl-2 shadow-lg backdrop-blur-sm",children:[o.jsx("span",{className:"select-none text-[11px] font-medium text-slate-400",children:"Scroll"}),o.jsxs("div",{className:"flex items-center rounded-md bg-slate-950/70 p-0.5",children:[o.jsx("button",{type:"button",onClick:()=>f("pan"),"aria-pressed":c==="pan",title:"Scroll or 2-finger swipe pans; pinch or Ctrl/Cmd+scroll zooms",className:`rounded px-2 py-0.5 text-[11px] font-medium transition-colors ${c==="pan"?"bg-sky-500/20 text-sky-300 ring-1 ring-sky-500/40":"text-slate-400 hover:text-slate-200"}`,children:"Pan"}),o.jsx("button",{type:"button",onClick:()=>f("zoom"),"aria-pressed":c==="zoom",title:"Scroll zooms at cursor; drag, Space+drag, or arrows pan",className:`rounded px-2 py-0.5 text-[11px] font-medium transition-colors ${c==="zoom"?"bg-sky-500/20 text-sky-300 ring-1 ring-sky-500/40":"text-slate-400 hover:text-slate-200"}`,children:"Zoom"})]})]}),hn.length>1&&o.jsxs("div",{className:"pointer-events-none absolute bottom-14 left-[52px] z-30 rounded-lg border border-sky-500/40 bg-slate-900/90 px-3 py-1.5 text-[11px] text-sky-200 shadow-lg backdrop-blur-sm",children:[hn.length," boxes selected — drag together or press Delete"]}),x&&o.jsx("div",{className:`pointer-events-none fixed bottom-16 left-1/2 z-50 -translate-x-1/2 rounded-lg border px-3.5 py-2 text-xs font-medium shadow-xl ${x.tone==="error"?"border-rose-500/50 bg-rose-950/90 text-rose-100":x.tone==="warning"?"border-amber-500/50 bg-amber-950/90 text-amber-100":"border-sky-500/40 bg-slate-900/95 text-slate-100"}`,children:x.message})]}),o.jsx(N0,{mode:N,elementTab:M,workspaceTab:q,onChangeElementTab:A,onChangeWorkspaceTab:ne,onClose:()=>P("none"),activeView:H,selectedNode:qa,selectedEdge:fs,edgeRoute:fs?we.current[fs.id]:void 0,allThreads:Fe,viewDiff:ce,viewBaseline:De,pendingFeedback:pn,status:(ye==null?void 0:ye.status)??null,onSaveNode:async j=>{H&&await Xe({...H,nodes:H.nodes.map(U=>U.id===j.id?j:U)})},onDeleteNode:async j=>{if(!H)return;if(H.edges.find(Y=>(Y.source===j||Y.target===j)&&Y.locked)){m("Unlock incident edge before deleting node","warning");return}w(null),P("none"),await Xe({...H,nodes:H.nodes.filter(Y=>Y.id!==j),edges:H.edges.filter(Y=>Y.source!==j&&Y.target!==j)})},onRevertNode:as,onRevertView:ls,onSaveEdge:async j=>{H&&await Xe({...H,edges:H.edges.map(U=>U.id===j.id?j:U)})},onDeleteEdge:async j=>{H&&(D(null),P("none"),await Xe({...H,edges:H.edges.filter(U=>U.id!==j)}))},onUpdateEdgeRoute:jr,onFlipEdge:j=>void Sr(j),onCreateThread:async j=>{await Jp(j),await bt()},onReplyThread:async(j,U)=>{await Xp(j,U),await bt()},onOpenTab:j=>void Xt(j),onJumpToTarget:(j,U,Y,pe)=>{Or(j,U,Y,pe)},onNotify:m})]}),ds&&us&&o.jsx(da,{x:ds.x,y:ds.y,header:us.header,items:us.items,onClose:Ye}),o.jsx(g0,{open:zr,loading:Aa,items:Da,onClose:()=>Tr(!1),onSelect:Ia}),W&&H&&o.jsx(y0,{diagramType:H.diagram_type??"general",sourceTitle:((Ar=H.nodes.find(j=>j.id===W.source))==null?void 0:Ar.title)??W.source??"",targetTitle:((Dr=H.nodes.find(j=>j.id===W.target))==null?void 0:Dr.title)??W.target??"",onCancel:()=>se(null),onConfirm:j=>void ja(j)})]})}function H0(){return o.jsx(hl,{children:o.jsx(U0,{})})}class W0 extends v.Component{constructor(){super(...arguments);Gt(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,s){console.error("Redlinify UI error:",n,s.componentStack)}render(){return this.state.error?o.jsx("div",{className:"flex h-screen w-screen items-center justify-center bg-slate-950 p-6 text-slate-100",children:o.jsxs("div",{className:"w-full max-w-lg rounded-2xl border border-rose-500/40 bg-slate-900 p-6 shadow-2xl",children:[o.jsxs("div",{className:"mb-3 flex items-center gap-2.5 text-rose-400",children:[o.jsx(Js,{className:"h-5 w-5 shrink-0"}),o.jsx("h1",{className:"text-base font-semibold text-slate-100",children:"Something went wrong in the Redlinify UI"})]}),o.jsx("p",{className:"mb-3 text-xs leading-relaxed text-slate-400",children:"Your diagram data on disk is safe. Reload the workbench to recover."}),o.jsx("pre",{className:"mb-4 max-h-40 overflow-auto rounded-lg border border-slate-800 bg-slate-950 p-3 font-mono text-[11px] text-rose-300 whitespace-pre-wrap break-words",children:this.state.error.message||"Unexpected rendering error"}),o.jsx("div",{className:"flex justify-end gap-2",children:o.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"inline-flex items-center gap-1.5 rounded-lg bg-sky-500 px-3.5 py-2 text-xs font-semibold text-slate-950 hover:bg-sky-400",children:[o.jsx(Rt,{className:"h-3.5 w-3.5"}),"Reload Workbench"]})})]})}):this.props.children}}cl.createRoot(document.getElementById("root")).render(o.jsx(v.StrictMode,{children:o.jsx(W0,{children:o.jsx(H0,{})})}));