diff --git a/apps/server-mcp/package.json b/apps/server-mcp/package.json index cfc60f7..df8d977 100644 --- a/apps/server-mcp/package.json +++ b/apps/server-mcp/package.json @@ -4,11 +4,11 @@ "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { - "build": "bun run build:assets && bun build src/index.ts --outdir=dist --target=bun --minify", - "build:assets": "bun run --cwd ../../packages/bar-chart-widget build && mkdir -p dist/widget/bar-chart && cp ../../packages/bar-chart-widget/dist/index.html dist/widget/bar-chart/bar-chart-widget.html && mkdir -p dist/widget/get-time && cp src/widget/get-time/get-time.html dist/widget/get-time/get-time.html && mkdir -p src/widget/widget-app && cp ../../packages/bar-chart-widget/dist/index.html src/widget/bar-chart/bar-chart-widget.html", + "build": "bun run build:asset && bun build src/index.ts --outdir=dist --target=bun --minify", + "build:asset": "mkdir -p dist/widget/get-time && cp src/widget/get-time/get-time.html dist/widget/get-time/get-time.html", "build:types": "tsc --emitDeclarationOnly", "dev": "bun --watch run src/index.ts", - "inspector": "bun run dev & sleep 2 && npx @mcpjam/inspector@latest; kill %1", + "inspector": "npx @mcpjam/inspector@latest", "test": "vitest run", "type-check": "tsc --noEmit", "clean": "git clean -xdf .cache .turbo dist node_modules" diff --git a/apps/server-mcp/src/widget/bar-chart/bar-chart-widget.html b/apps/server-mcp/src/widget/bar-chart/bar-chart-widget.html index 17239ca..e68631a 100644 --- a/apps/server-mcp/src/widget/bar-chart/bar-chart-widget.html +++ b/apps/server-mcp/src/widget/bar-chart/bar-chart-widget.html @@ -34,15 +34,86 @@ max-width: 100%; } - +}`)).call(Vj,n);for(let e of l){let{channels:t,values:n,facets:r}=h.get(e);if(m===void 0||e.facet===`super`){let i=null;if(r&&(i=r[0],i=e.filter(i,t,n),i.length===0))continue;let a=e.render(i,v,n,S,C);if(a==null)continue;T.appendChild(a)}else{let i;for(let a of m){if(!(e.facetAnchor?.(m,O,a)??!a.empty))continue;let o=null;if(r){let i=d.has(e);if(o=r[i?a.i:0],o=e.filter(o,t,n),o.length===0)continue;!i&&o===r[0]&&(o=iD(o)),o.fx=a.x,o.fy=a.y,o.fi=a.i}let s=e.render(o,v,n,x,C);if(s!=null){(i??=nf(T).append(`g`)).append(()=>s).datum(a);for(let e of[`aria-label`,`aria-description`,`aria-hidden`,`transform`])s.hasAttribute(e)&&(i.attr(e,s.getAttribute(e)),s.removeAttribute(e))}}i?.selectChildren().each(k)}}let ne=vP(g,C,e),{figure:re=r!=null||i!=null||a!=null||ne.length>0}=e;re&&(E=w.createElement(`figure`),E.className=`${c}-figure`,E.style.maxWidth=`initial`,r!=null&&E.append(gF(w,r,`h2`)),i!=null&&E.append(gF(w,i,`h3`)),E.append(...ne,T),a!=null&&E.append(_F(w,a)),`value`in T&&(E.value=T.value,delete T.value)),E.scale=SA(v.scales),E.legend=pP(g,C,e);let ie=Ek();return ie>0&&nf(T).append(`text`).attr(`x`,ee).attr(`y`,20).attr(`dy`,`-1em`).attr(`text-anchor`,`end`).attr(`font-family`,`initial`).text(`⚠️`).append(`title`).text(`${ie.toLocaleString(`en-US`)} warning${ie===1?``:`s`}. Please check the console.`),E}function gF(e,t,n){if(t.ownerDocument)return t;let r=e.createElement(n);return r.append(t),r}function _F(e,t){let n=e.createElement(`figcaption`);return n.append(t),n}function vF(e){return e.flat(1/0).filter(e=>e!=null).map(yF)}function yF(e){return typeof e.render==`function`?e:new bF(e)}var bF=class extends Uj{constructor(e){if(typeof e!=`function`)throw TypeError(`invalid mark; missing render function`);super(),this.render=e}render(){}};function xF(e,t){for(let n in e)SF(e[n],t);return e}function SF(e,t){let{scale:n,transform:r=!0}=e;if(n==null||!r)return;let{type:i,percent:a,interval:o,transform:s=a?e=>e==null?NaN:e*100:dD(o,i)}=t[n]??{};s!=null&&(e.value=UE(e.value,s),e.transform=!1)}function CF(e){for(let t in e)OO(t,e[t])}function wF(e,t,n,r=TE){for(let{channels:i}of t.values())for(let t in i){let a=i[t],{scale:o}=a;if(o!=null&&r(o))if(o===`projection`){if(!ij(n)){let t=n.x?.domain===void 0,r=n.y?.domain===void 0;if(t||r){let[n,i]=oj(a);t&&TF(e,`x`,n),r&&TF(e,`y`,i)}}}else TF(e,o,a)}return e}function TF(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function EF(e,t){if(e==null)return;let{x:n,y:r}=e;if(n==null&&r==null)return;let i=BE(e.data);if(i==null)throw Error(`missing facet data`);let a={};return n!=null&&(a.fx=TO(i,{value:n,scale:`fx`})),r!=null&&(a.fy=TO(i,{value:r,scale:`fy`})),xF(a,t),{channels:a,groups:EA(i,a),data:e.data}}function DF(e,t,n){if(e.facet===null||e.facet===`super`)return;let{fx:r,fy:i}=e;if(r!=null||i!=null){let t=BE(e.data??r??i);if(t===void 0)throw Error(`missing facet data in ${e.ariaLabel}`);if(t===null)return;let a={};return r!=null&&(a.fx=TO(t,{value:r,scale:`fx`})),i!=null&&(a.fy=TO(t,{value:i,scale:`fy`})),xF(a,n),{channels:a,groups:EA(t,a)}}if(t===void 0)return;let{channels:a,groups:o,data:s}=t;if(e.facet!==`auto`||e.data===s)return{channels:a,groups:o};s.length>0&&(o.size>1||o.size===1&&a.fx&&a.fy&&[...o][0][1].size>1)&&tD(BE(e.data))===tD(s)&&Dk(`Warning: the ${e.ariaLabel} mark appears to use faceted data, but isn’t faceted. The mark data has the same length as the facet data and the mark facet option is "auto", but the mark data and facet data are distinct. If this mark should be faceted, set the mark facet option to true; otherwise, suppress this warning by setting the mark facet option to false.`)}function OF(e,t={}){return iO({...t,x:null,y:null},(t,n,r,i,a,o)=>o.getMarkState(e))}function kF(e){let t=[];for(let n of e){let e=n.tip;if(e){e===!0?e={}:typeof e==`string`&&(e={pointer:e});let{pointer:r,preferredAnchor:i}=e;r=/^x$/i.test(r)?tM:/^y$/i.test(r)?nM:eM,e=r(OF(n,e)),e.title=null,i===void 0&&(e.preferredAnchor=r===nM?`left`:`bottom`);let a=iF(n.data,e);a.facet=n.facet,a.facetAnchor=n.facetAnchor,t.push(a)}}return t}function AF(e,t,n){let{projection:r,x:i={},y:a={},fx:o={},fy:s={},axis:c,grid:l,facet:u={},facet:{axis:d=c,grid:f}=u,x:{axis:p=c,grid:m=p===null?null:l}=i,y:{axis:h=c,grid:g=h===null?null:l}=a,fx:{axis:_=d,grid:v=_===null?null:f}=o,fy:{axis:y=d,grid:b=y===null?null:f}=s}=n;(r||!YE(i)&&!zF(`x`,e))&&(p=m=null),(r||!YE(a)&&!zF(`y`,e))&&(h=g=null),t.has(`fx`)||(_=v=null),t.has(`fy`)||(y=b=null),p===void 0&&(p=!RF(e,`x`)),h===void 0&&(h=!RF(e,`y`)),_===void 0&&(_=!RF(e,`fx`)),y===void 0&&(y=!RF(e,`fy`)),p===!0&&(p=`bottom`),h===!0&&(h=`left`),_===!0&&(_=p===`top`||p===null?`bottom`:`top`),y===!0&&(y=h===`right`||h===null?`left`:`right`);let x=[];return MF(x,b,HN,s),jF(x,y,MN,`right`,`left`,u,s),MF(x,v,WN,o),jF(x,_,PN,`top`,`bottom`,u,o),MF(x,g,VN,a),jF(x,h,jN,`left`,`right`,n,a),MF(x,m,UN,i),jF(x,p,NN,`bottom`,`top`,n,i),x}function jF(e,t,n,r,i,a,o){if(!t)return;let s=NF(t);o=PF(s?r:t,a,o);let{line:c}=o;(n===jN||n===NN)&&c&&!jD(c)&&e.push(eF(FF(o))),e.push(n(o)),s&&e.push(n({...o,anchor:i,label:null}))}function MF(e,t,n,r){!t||jD(t)||e.push(n(IF(t,r)))}function NF(e){return/^\s*both\s*$/i.test(e)}function PF(e,t,{line:n=t.line,ticks:r,tickSize:i,tickSpacing:a,tickPadding:o,tickFormat:s,tickRotate:c,fontVariant:l,ariaLabel:u,ariaDescription:d,label:f=t.label,labelAnchor:p,labelArrow:m=t.labelArrow,labelOffset:h}){return{anchor:e,line:n,ticks:r,tickSize:i,tickSpacing:a,tickPadding:o,tickFormat:s,tickRotate:c,fontVariant:l,ariaLabel:u,ariaDescription:d,label:f,labelAnchor:p,labelArrow:m,labelOffset:h}}function FF(e){let{anchor:t,line:n}=e;return{anchor:t,facetAnchor:t+`-empty`,stroke:n===!0?void 0:n}}function IF(e,{stroke:t=OD(e)?e:void 0,ticks:n=LF(e)?e:void 0,tickSpacing:r,ariaLabel:i,ariaDescription:a}){return{stroke:t,ticks:n,tickSpacing:r,ariaLabel:i,ariaDescription:a}}function LF(e){switch(typeof e){case`number`:return!0;case`string`:return!OD(e)}return yD(e)||typeof e?.range==`function`}function RF(e,t){let n=`${t}-axis `;return e.some(e=>e.ariaLabel?.startsWith(n))}function zF(e,t){for(let n of t)for(let t in n.channels){let{scale:r}=n.channels[t];if(r===e||r===`projection`)return!0}return!1}function BF(e,t){for(let n in e){let r=e[n],i=t[n];r.label===void 0&&i&&(r.label=i.label)}return e}function VF({fx:e,fy:t},n){let{marginTop:r,marginRight:i,marginBottom:a,marginLeft:o,width:s,height:c}=rA(n),l=e&&HF(e),u=t&&HF(t);return{marginTop:t?u[0]:r,marginRight:e?s-l[1]:i,marginBottom:t?c-u[1]:a,marginLeft:e?l[0]:o,inset:{marginTop:n.marginTop,marginRight:n.marginRight,marginBottom:n.marginBottom,marginLeft:n.marginLeft},width:s,height:c}}function HF(e){let t=e.domain();if(t.length===0)return[0,e.bandwidth()];let n=e(t[0]),r=e(t[t.length-1]);return rt.selectAll().data(e).enter().call(s||c||l||u?e=>e.append(`path`).call(Nj,this).call(JP,d,f,GF(d,p),GF(f,m),this).call(Tj,this,n):e=>e.append(`rect`).call(Nj,this).attr(`x`,d).attr(`width`,p).attr(`y`,f).attr(`height`,m).call($,`rx`,a).call($,`ry`,o).call(Tj,this,n))).node()}_x(e,{x:t},{marginLeft:n}){let{insetLeft:r}=this;return t?e=>t[e]+r:n+r}_y(e,{y:t},{marginTop:n}){let{insetTop:r}=this;return t?e=>t[e]+r:n+r}_width({x:e},{x:t},{marginRight:n,marginLeft:r,width:i}){let{insetLeft:a,insetRight:o}=this,s=t&&e?e.bandwidth():i-n-r;return Math.max(0,s-a-o)}_height({y:e},{y:t},{marginTop:n,marginBottom:r,height:i}){let{insetTop:a,insetBottom:o}=this,s=t&&e?e.bandwidth():i-n-r;return Math.max(0,s-a-o)}};function GF(e,t){return typeof e==`function`&&typeof t==`function`?n=>e(n)+t(n):typeof e==`function`?n=>e(n)+t:typeof t==`function`?n=>e+t(n):e+t}var KF=class extends WF{constructor(e,t={},n){let{x1:r,x2:i,y:a}=t;super(e,{x1:{value:r,scale:`x`},x2:{value:i,scale:`x`},y:{value:a,scale:`y`,type:`band`,optional:!0}},t,n)}_transform(e,t,{x:n}){e.call(Ij,t,{x:n},0,0)}_x({x:e},{x1:t,x2:n},{marginLeft:r}){let{insetLeft:i}=this;return yA(e)?r+i:e=>Math.min(t[e],n[e])+i}_width({x:e},{x1:t,x2:n},{marginRight:r,marginLeft:i,width:a}){let{insetLeft:o,insetRight:s}=this;return yA(e)?a-r-i-o-s:e=>Math.max(0,Math.abs(n[e]-t[e])-o-s)}},qF=class extends WF{constructor(e,t={},n){let{x:r,y1:i,y2:a}=t;super(e,{y1:{value:i,scale:`y`},y2:{value:a,scale:`y`},x:{value:r,scale:`x`,type:`band`,optional:!0}},t,n)}_transform(e,t,{y:n}){e.call(Ij,t,{y:n},0,0)}_y({y:e},{y1:t,y2:n},{marginTop:r}){let{insetTop:i}=this;return yA(e)?r+i:e=>Math.min(t[e],n[e])+i}_height({y:e},{y1:t,y2:n},{marginTop:r,marginBottom:i,height:a}){let{insetTop:o,insetBottom:s}=this;return yA(e)?a-r-i-o-s:e=>Math.max(0,Math.abs(n[e]-t[e])-o-s)}};function JF(e,t={}){return qE(t)||(t={...t,y:SE,x2:CE}),new KF(e,wP(DM(yP(t))))}function YF(e,t={}){return qE(t)||(t={...t,x:SE,y2:CE}),new qF(e,TP(OM(bP(t))))}Uj.prototype.plot=function({marks:e=[],...t}={}){return hF({...t,marks:[...e,this]})};var XF=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;et(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},eI=e=>e,tI=e=>()=>e,nI=tI(!1),rI=tI(null),iI=tI(void 0),aI=iI;function oI(e){let t=new WeakMap;return n=>{if(t.has(n))return t.get(n);let r=e(n);return t.set(n,r),r}}var sI=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n_I(e)&&t in e),yI=`~effect/interfaces/Hash`,bI=e=>{switch(typeof e){case`number`:return TI(e);case`bigint`:return EI(e.toString(10));case`boolean`:return EI(String(e));case`symbol`:return EI(String(e));case`string`:return EI(e);case`undefined`:return EI(`undefined`);case`function`:case`object`:if(e===null)return EI(`null`);if(e instanceof Date)return EI(e.toISOString());if(e instanceof RegExp)return EI(e.toString());{if(cI.has(e))return xI(e);if(PI.has(e))return PI.get(e);let t=II(e,()=>wI(e)?e[yI]():typeof e==`function`?xI(e):Array.isArray(e)?AI(e):e instanceof Map?jI(e):e instanceof Set?MI(e):OI(e));return PI.set(e,t),t}default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},xI=e=>(NI.has(e)||NI.set(e,TI(Math.floor(Math.random()*(2**53-1)))),NI.get(e)),SI=$F(2,(e,t)=>e*53^t),CI=e=>e&3221225471|e>>>1&1073741824,wI=e=>vI(e,yI),TI=e=>{if(e!==e)return EI(`NaN`);if(e===1/0)return EI(`Infinity`);if(e===-1/0)return EI(`-Infinity`);let t=e|0;for(t!==e&&(t^=e*4294967295);e>4294967295;)t^=e/=4294967295;return CI(t)},EI=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return CI(t)},DI=(e,t)=>{let n=12289;for(let r of t)n^=SI(bI(r),bI(e[r]));return CI(n)},OI=e=>DI(e,sI(e)),kI=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return CI(r)},AI=kI(6151,bI),jI=kI(EI(`Map`),([e,t])=>SI(bI(e),bI(t))),MI=kI(EI(`Set`),bI),NI=new WeakMap,PI=new WeakMap,FI=new WeakSet;function II(e,t){if(FI.has(e))return EI(`[Circular]`);FI.add(e);let n=t();return FI.delete(e),n}var LI=`~effect/interfaces/Equal`;function RI(){return arguments.length===1?e=>zI(e,arguments[0]):zI(arguments[0],arguments[1])}function zI(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||cI.has(e)||cI.has(t)?!1:WI(e,t,UI):!1}function BI(e,t,n){let r=VI.has(e),i=HI.has(t);if(r&&i)return!0;if(r||i)return!1;VI.add(e),HI.add(t);let a=n();return VI.delete(e),HI.delete(t),a}var VI=new WeakSet,HI=new WeakSet;function UI(e,t){if(bI(e)!==bI(t))return!1;if(e instanceof Date)return t instanceof Date?e.toISOString()===t.toISOString():!1;if(e instanceof RegExp)return t instanceof RegExp?e.toString()===t.toString():!1;let n=QI(e),r=QI(t);if(n!==r)return!1;let i=n&&r;return typeof e==`function`&&!i?!1:BI(e,t,()=>i?e[LI](t):Array.isArray(e)?!Array.isArray(t)||e.length!==t.length?!1:KI(e,t):e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:YI(e,t):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:ZI(e,t):qI(e,t))}function WI(e,t,n){let r=GI.get(e);if(!r)r=new WeakMap,GI.set(e,r);else if(r.has(t))return r.get(t);let i=n(e,t);r.set(t,i);let a=GI.get(t);return a||(a=new WeakMap,GI.set(t,a)),a.set(e,i),i}var GI=new WeakMap;function KI(e,t){for(let n=0;nvI(e,LI),$I=()=>RI,eL=e=>(t,n)=>t===n||e(t,n),tL=e=>e.length>0,nL=Symbol.for(`~effect/Inspectable/redactable`),rL=e=>vI(e,nL);function iL(e){return rL(e)?aL(e):e}function aL(e){return e[nL](globalThis[`~effect/Fiber/currentFiber`]?.services??sL)}var oL=`~effect/Fiber/currentFiber`,sL={"~effect/ServiceMap":{},mapUnsafe:new Map,pipe(){return XF(this,arguments)}};function cL(e,t){let n=t?.space??0,r=new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,n=0){if(Array.isArray(e)){if(r.has(e))return lL;if(r.add(e),!i||e.length<=1)return`[${e.map(e=>c(e,n)).join(`,`)}]`;let t=e.map(e=>c(e,n+1)).join(`, +`+a(n+1));return`[\n${a(n+1)}${t}\n${a(n)}]`}if(e instanceof Date)return fL(e);if(!t?.ignoreToString&&vI(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=pL(e);return e instanceof Error&&e.cause?`${t} (cause: ${c(e.cause,n)})`:t}if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return lL;if(r.add(e),nL in e)return cL(aL(e));if(Symbol.iterator in e)return`${e.constructor.name}(${c(Array.from(e),n)})`;let t=s(e);return!i||t.length<=1?o(e,`{${t.map(t=>`${uL(t)}:${c(e[t],n)}`).join(`,`)}}`):o(e,`{\n${t.map(t=>`${a(n+1)}${uL(t)}: ${c(e[t],n+1)}`).join(`, +`)}\n${a(n)}}`)}return String(e)}return c(e,0)}var lL=`[Circular]`;function uL(e){return typeof e==`string`?JSON.stringify(e):String(e)}function dL(e){return e.map(e=>`[${uL(e)}]`).join(``)}function fL(e){try{return e.toISOString()}catch{return`Invalid Date`}}function pL(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function mL(e,t){let n=[],r=JSON.stringify(e,(e,t)=>typeof t==`object`&&t?n.includes(t)?void 0:n.push(t)&&iL(t):t,t?.space);return n=void 0,r}var hL=Symbol.for(`nodejs.util.inspect.custom`),gL=e=>{try{if(vI(e,`toJSON`)&&mI(e.toJSON)&&e.toJSON.length===0)return e.toJSON();if(Array.isArray(e))return e.map(gL)}catch{return`[toJSON threw]`}return iL(e)},_L=class e{called=!1;self;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}[Symbol.iterator](){return new e(this.self)}},vL=`~effect/Utils/internal`,yL={[vL]:e=>e()},bL={[vL]:e=>{try{return e()}finally{}}},xL=yL[vL](()=>Error().stack)?.includes(vL)===!0?yL[vL]:bL[vL],SL=`~effect/Effect`,CL=`~effect/Exit`,wL={_A:eI,_E:eI,_R:eI},TL=`${SL}/identifier`,EL=`${SL}/args`,DL=`${SL}/evaluate`,OL=`${SL}/successCont`,kL=`${SL}/failureCont`,AL=`${SL}/ensureCont`,jL=Symbol.for(`effect/Effect/Yield`),ML={pipe(){return XF(this,arguments)},toJSON(){return{...this}},toString(){return cL(this.toJSON(),{ignoreToString:!0,space:2})},[hL](){return this.toJSON()}},NL={[yI](){return DI(this,Object.keys(this))},[LI](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r=0;rvI(e,CL),RL=`~effect/Cause`,zL=`~effect/Cause/Reason`,BL=e=>vI(e,RL),VL=class{[RL];reasons;constructor(e){this[RL]=RL,this.reasons=e}pipe(){return XF(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${cL(this.reasons)})`}[hL](){return this.toJSON()}[LI](e){return BL(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>RI(t,e.reasons[n]))}[yI](){return AI(this.reasons)}},HL=new WeakMap,UL=class{[zL];annotations;_tag;constructor(e,t,n){if(this[zL]=zL,this._tag=e,t!==WL&&typeof n==`object`&&n&&t.size>0){let e=HL.get(n);e&&(t=new Map([...e,...t])),HL.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return XF(this,arguments)}toString(){return cL(this)}[hL](){return this.toString()}},WL=new Map,GL=class extends UL{error;constructor(e,t=WL){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${cL(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[LI](e){return ZL(e)&&RI(this.error,e.error)&&RI(this.annotations,e.annotations)}[yI](){return SI(EI(this._tag))(SI(bI(this.error))(bI(this.annotations)))}},KL=e=>new VL(e),qL=e=>new VL([new GL(e)]),JL=class extends UL{defect;constructor(e,t=WL){super(`Die`,t,e),this.defect=e}toString(){return`Die(${cL(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[LI](e){return QL(e)&&RI(this.defect,e.defect)&&RI(this.annotations,e.annotations)}[yI](){return SI(EI(this._tag))(SI(bI(this.defect))(bI(this.annotations)))}},YL=e=>new VL([new JL(e)]),XL=$F(e=>BL(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new VL(e.reasons.map(e=>e.annotate(t,n)))),ZL=e=>e._tag===`Fail`,QL=e=>e._tag===`Die`,$L=e=>e._tag===`Interrupt`;function eR(e){return cR(`Effect.evaluate: Not implemented`)}var tR=e=>({...IL,[TL]:e.op,[DL]:e[DL]??eR,[OL]:e[OL],[kL]:e[kL],[AL]:e[AL]}),nR=e=>{let t=tR(e);return function(){let n=Object.create(t);return n[EL]=e.single===!1?arguments:arguments[0],n}},rR=e=>{let t={...tR(e),[CL]:CL,_tag:e.op,get[e.prop](){return this[EL]},toString(){return`${e.op}(${cL(this[EL])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[EL]}},[LI](e){return LL(e)&&e._tag===this._tag&&RI(this[EL],e[EL])},[yI](){return SI(EI(e.op),bI(this[EL]))}};return function(e){let n=Object.create(t);return n[EL]=e,n}},iR=rR({op:`Success`,prop:`value`,[DL](e){let t=e.getCont(OL);return t?t[OL](this[EL],e,this):e.yieldWith(this)}}),aR={key:`effect/Cause/StackTrace`},oR=rR({op:`Failure`,prop:`cause`,[DL](e){let t=this[EL],n=!1;e.currentStackFrame&&(t=XL(t,{mapUnsafe:new Map([[aR.key,e.currentStackFrame]])}),n=!0);let r=e.getCont(kL);for(;e.interruptible&&e._interruptedCause&&r;)r=e.getCont(kL);return r?r[kL](t,e,n?void 0:this):e.yieldWith(n?this:oR(t))}}),sR=e=>oR(qL(e)),cR=e=>oR(YL(e)),lR=nR({op:`WithFiber`,[DL](e){return this[EL](e)}}),uR=function(){class e extends globalThis.Error{asEffect(){return sR(this)}}return Object.assign(e.prototype,FL),e}(),dR=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return class extends uR{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(Object.assign(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),fR=e=>{class t extends dR{_tag=e}return t.prototype.name=e,t},pR=`~effect/Cause/NoSuchElementError`,mR=class extends fR(`NoSuchElementError`){[pR]=pR;constructor(e){super({message:e})}},hR=`~effect/data/Option`,gR={[hR]:{_A:e=>e},...ML,...PL},_R=Object.assign(Object.create(gR),{_tag:`Some`,_op:`Some`,[LI](e){return bR(e)&&SR(e)&&RI(this.value,e.value)},[yI](){return SI(bI(this._tag))(bI(this.value))},toString(){return`some(${cL(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:gL(this.value)}},asEffect(){return iR(this.value)}});Object.defineProperty(_R,`valueOrUndefined`,{get(){return this.value}});var vR=bI(`None`),yR=Object.assign(Object.create(gR),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[LI](e){return bR(e)&&xR(e)},[yI](){return vR},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}},asEffect(){return sR(new mR)}}),bR=e=>vI(e,hR),xR=e=>e._tag===`None`,SR=e=>e._tag===`Some`,CR=Object.create(yR),wR=e=>{let t=Object.create(_R);return t.value=e,t},TR=`~effect/data/Result`,ER={[TR]:{_A:e=>e,_E:e=>e},...ML,...PL},DR=Object.assign(Object.create(ER),{_tag:`Success`,_op:`Success`,[LI](e){return kR(e)&&jR(e)&&RI(this.success,e.success)},[yI](){return SI(bI(this._tag))(bI(this.success))},toString(){return`success(${cL(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:gL(this.success)}},asEffect(){return iR(this.success)}}),OR=Object.assign(Object.create(ER),{_tag:`Failure`,_op:`Failure`,[LI](e){return kR(e)&&AR(e)&&RI(this.failure,e.failure)},[yI](){return SI(bI(this._tag))(bI(this.failure))},toString(){return`failure(${cL(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:gL(this.failure)}},asEffect(){return sR(this.failure)}}),kR=e=>vI(e,TR),AR=e=>e._tag===`Failure`,jR=e=>e._tag===`Success`,MR=e=>{let t=Object.create(OR);return t.failure=e,t},NR=e=>{let t=Object.create(DR);return t.success=e,t};function PR(e){return(t,n)=>t===n?0:e(t,n)}var FR=PR((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e$F(2,(t,n)=>e(t,n)===1),LR=()=>CR,RR=wR,zR=xR,BR=SR,VR=$F(2,(e,t)=>zR(e)?t():e.value),HR=VR(rI),UR=VR(iI),WR=$F(2,(e,t)=>zR(e)?LR():RR(t(e.value))),GR=NR,KR=MR,qR=AR,JR=jR,YR=globalThis.Array,XR=e=>YR.isArray(e)?e:YR.from(e),ZR=$F(2,(e,t)=>[...e,t]),QR=$F(2,(e,t)=>XR(e).concat(XR(t)));YR.isArray;var $R=tL,ez=tL;function tz(e,t){return e<0||e>=t.length}var nz=$F(2,(e,t)=>{let n=Math.floor(t);if(tz(n,e))throw Error(`Index out of bounds: ${n}`);return e[n]})(0),rz=e=>e.slice(1),iz=$F(3,(e,t,n)=>{let r=XR(e),i=XR(t);return ez(r)?ez(i)?oz(n)(QR(r,i)):r:i}),az=$F(2,(e,t)=>iz(e,t,$I())),oz=$F(2,(e,t)=>{let n=XR(e);if(ez(n)){let e=[nz(n)],r=rz(n);for(let n of r)e.every(e=>!t(n,e))&&e.push(n);return e}return[]}),sz=`~effect/BigDecimal`,cz={[sz]:sz,[yI](){let e=hz(this);return SI(bI(e.value),TI(e.scale))},[LI](e){return lz(e)&&yz(this,e)},toString(){return`BigDecimal(${bz(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[hL](){return this.toJSON()},pipe(){return XF(this,arguments)}},lz=e=>vI(e,sz),uz=(e,t)=>{let n=Object.create(cz);return n.value=e,n.scale=t,n},dz=(e,t)=>{if(e!==fz&&e%pz===fz)throw RangeError(`Value must be normalized`);let n=uz(e,t);return n.normalized=n,n},fz=BigInt(0),pz=BigInt(10),mz=dz(fz,0),hz=e=>{if(e.normalized===void 0)if(e.value===fz)e.normalized=mz;else{let t=`${e.value}`,n=0;for(let e=t.length-1;e>=0&&t[e]===`0`;e--)n++;n===0&&(e.normalized=e),e.normalized=dz(BigInt(t.substring(0,t.length-n)),e.scale-n)}return e.normalized},gz=$F(2,(e,t)=>t>e.scale?uz(e.value*pz**BigInt(t-e.scale),t):te.valuee.scale>t.scale?gz(t,e.scale).value===e.value:e.scalevz(e,t)),bz=e=>{let t=hz(e);if(Math.abs(t.scale)>=16)return xz(t);let n=t.value=r.length)i=`0`,a=`0`.repeat(t.scale-r.length)+r;else{let e=r.length-t.scale;if(e>r.length){let t=e-r.length;i=`${r}${`0`.repeat(t)}`,a=``}else a=r.slice(e),i=r.slice(0,e)}let o=a===``?i:`${i}.${a}`;return n?`-${o}`:o},xz=e=>{if(Sz(e))return`0e+0`;let t=hz(e),n=`${_z(t).value}`,r=n.slice(0,1),i=n.slice(1),a=`${Cz(t)?`-`:``}${r}`;i!==``&&(a+=`.${i}`);let o=i.length-t.scale;return`${a}e${o>=0?`+`:``}${o}`},Sz=e=>e.value===fz,Cz=e=>e.value{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return e.value.nanos;case`Millis`:return BigInt(Math.round(e.value.millis*1e6))}},Ez=$F(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(Tz(e),t.value.nanos):n.onNanos(e.value.nanos,Tz(t))),Dz=(e,t)=>Ez(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Oz=`~effect/ServiceMap/Service`,kz=function(){let e=Error.stackTraceLimit;Error.stackTraceLimit=2;let t=Error();Error.stackTraceLimit=e;function n(){}let r=n;return Object.setPrototypeOf(r,Az),Object.defineProperty(r,`stack`,{get(){return t.stack}}),arguments.length>0?(r.key=arguments[0],arguments[1]?.defaultValue&&(r[jz]=jz,r.defaultValue=arguments[1].defaultValue),r):function(e,t){return r.key=e,t?.make&&(r.make=t.make),r}},Az={[Oz]:Oz,...ML,...PL,toJSON(){return{_id:`Service`,key:this.key,stack:this.stack}},asEffect(){return(this.asEffect=tI(lR(e=>iR(Bz(e.services,this)))))()},of(e){return e},serviceMap(e){return Rz(this,e)},use(e){return lR(t=>e(Bz(t.services,this)))},useSync(e){return lR(t=>iR(e(Bz(t.services,this))))}},jz=`~effect/ServiceMap/Reference`,Mz=`~effect/ServiceMap`,Nz=e=>{let t=Object.create(Pz);return t.mapUnsafe=e,t.mutable=!1,t},Pz={...ML,[Mz]:{_Services:e=>e},toJSON(){return{_id:`ServiceMap`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[LI](e){if(!Fz(e)||this.mapUnsafe.size!==e.mapUnsafe.size)return!1;for(let t of this.mapUnsafe.keys())if(!e.mapUnsafe.has(t)||!RI(this.mapUnsafe.get(t),e.mapUnsafe.get(t)))return!1;return!0},[yI](){return TI(this.mapUnsafe.size)}},Fz=e=>vI(e,Mz),Iz=()=>Lz,Lz=Nz(new Map),Rz=(e,t)=>Nz(new Map([[e.key,t]])),zz=$F(3,(e,t,n)=>Gz(e,e=>{e.set(t.key,n)})),Bz=$F(2,(e,t)=>{if(!e.mapUnsafe.has(t.key)){if(jz in t)return Uz(t);throw Wz(t)}return e.mapUnsafe.get(t.key)}),Vz=(e,t)=>e.mapUnsafe.has(t.key)?e.mapUnsafe.get(t.key):Uz(t),Hz=`~effect/ServiceMap/defaultValue`,Uz=e=>Hz in e?e[Hz]:e[Hz]=e.defaultValue(),Wz=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(e.stack){let n=e.stack.split(` +`);if(n.length>2){let e=n[2].match(/at (.*)/);e&&(t.message+=` (defined at ${e[1]})`)}}if(t.stack){let e=t.stack.split(` +`);e.splice(1,3),t.stack=e.join(` +`)}return t},Gz=(e,t)=>{if(e.mutable)return t(e.mapUnsafe),e;let n=new Map(e.mapUnsafe);return t(n),Nz(n)},Kz=kz,qz=Kz(`effect/Scheduler`,{defaultValue:()=>new Xz}),Jz=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},Yz=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;at);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},Xz=class{executionMode;setImmediate;constructor(e=`async`,t=Jz){this.executionMode=e,this.setImmediate=t}shouldYield(e){return e.currentOpCount>=e.maxOpsBeforeYield}makeDispatcher(){return new Zz(this.setImmediate)}},Zz=class{tasks=new Yz;running=void 0;setImmediate;constructor(e=Jz){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}},Qz=Kz(`effect/Scheduler/MaxOpsBeforeYield`,{defaultValue:()=>2048}),$z=Kz(`effect/Scheduler/PreventSchedulerYield`,{defaultValue:()=>!1}),eB=`effect/Tracer/ParentSpan`;kz()(eB);var tB=Kz(`effect/Tracer/DisablePropagation`,{defaultValue:nI}),nB=`effect/Tracer`,rB=`effect/observability/Metric/FiberRuntimeMetricsKey`,iB=Kz(`effect/References/CurrentStackFrame`,{defaultValue:iI}),aB=Kz(`effect/References/CurrentLogLevel`,{defaultValue:()=>`Info`}),oB=Kz(`effect/References/MinimumLogLevel`,{defaultValue:()=>`Info`}),sB=class extends UL{fiberId;constructor(e,t=WL){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[LI](e){return $L(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[yI](){return SI(EI(`${this._tag}:${this.fiberId}`))(xI(this.annotations))}},cB=e=>new VL([new sB(e)]),lB=e=>{for(let t=0;te.reasons.some($L),dB=$F(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new VL(az(e.reasons,t.reasons));return RI(e,n)?e:n}),fB=e=>{let t={Fail:[],Die:[],Interrupt:[]};for(let n=0;n{let t=fB(e);return t.Fail.length>0?t.Fail[0].error:t.Die.length>0?t.Die[0].defect:t.Interrupt.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`)},mB=(e,t)=>{let n=typeof e,r;if(e&&n===`object`){if(r=new globalThis.Error(hB(e),{cause:e.cause?mB(e.cause):void 0}),typeof e.name==`string`&&(r.name=e.name),typeof e.stack==`string`)r.stack=_B(e.stack,r,t);else{let e=`${r.name}: ${r.message}`;r.stack=t?vB(e,t):e}for(let t of Object.keys(e))t in r||(r[t]=e[t])}else r=new globalThis.Error(e?n===`string`?e:mL(e):`Unknown error: ${e}`);return r},hB=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return mL(e)},gB=/\((.*)\)/g,_B=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(` +`),a=[r];for(let e=1;e{let n=t?.get(aR.key);return n&&(e=`${e}\n${yB(n)}`),e},yB=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(gB),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(` +`)},bB=(e,t)=>{let n=e.stack.split(` +`),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;eglobalThis[oL],TB=class{constructor(e,t=!0){this[xB]=SB,this.setServices(e),this.id=++CB.id,this.currentOpCount=0,this.currentLoopCount=0,this.interruptible=t,this._stack=[],this._observers=[],this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0}[xB];id;interruptible;currentOpCount;currentLoopCount;_stack;_observers;_exit;_currentExit;_children;_interruptedCause;_yielded;services;currentScheduler;currentTracerContext;currentSpan;currentLogLevel;minimumLogLevel;currentStackFrame;runtimeMetrics;maxOpsBeforeYield;currentPreventYield;_dispatcher=void 0;get currentDispatcher(){return this._dispatcher??=this.currentScheduler.makeDispatcher()}getRef(e){return Vz(this.services,e)}addObserver(e){return this._exit?(e(this._exit),aI):(this._observers.push(e),()=>{let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)})}interruptUnsafe(e,t){if(this._exit)return;let n=cB(e);this.currentStackFrame&&(n=XL(n,Rz(aR,this.currentStackFrame))),t&&(n=XL(n,t)),this._interruptedCause=this._interruptedCause?dB(this._interruptedCause,n):n,this.interruptible&&this.evaluate(kB(this._interruptedCause))}pollUnsafe(){return this._exit}evaluate(e){if(this.runtimeMetrics?.recordFiberStart(this.services),this._exit)return;if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===jL)return;let n=EB.interruptChildren&&EB.interruptChildren(this);if(n!==void 0)return this.evaluate(qB(n,()=>t));this._exit=t,this.runtimeMetrics?.recordFiberEnd(this.services,this._exit);for(let e=0;ee)}if(r=this.currentTracerContext?this.currentTracerContext(r,this):r[DL](this),i!==this.currentLoopCount)return jL;if(r===jL){let e=this._yielded;return CL in e?(this._yielded=void 0,e):jL}}}catch(e){return vI(r,DL)?this.runLoop(cR(e)):cR(`Fiber.runLoop: Not a valid effect: ${String(r)}`)}finally{globalThis[oL]=t}}getCont(e){for(;;){let t=this._stack.pop();if(!t)return;let n=t[AL]&&t[AL](this);if(n)return n[e]=n,n;if(t[e])return t}}yieldWith(e){return this._yielded=e,jL}children(){return this._children??=new Set}pipe(){return XF(this,arguments)}setServices(e){this.services=e;let t=this.getRef(qz);t!==this.currentScheduler&&(this.currentScheduler=t,this._dispatcher=void 0),this.currentSpan=e.mapUnsafe.get(eB),this.currentLogLevel=this.getRef(aB),this.minimumLogLevel=this.getRef(oB),this.currentStackFrame=e.mapUnsafe.get(iB.key),this.maxOpsBeforeYield=this.getRef(Qz),this.currentPreventYield=this.getRef($z),this.runtimeMetrics=e.mapUnsafe.get(rB);let n=e.mapUnsafe.get(nB);this.currentTracerContext=n?n.context:void 0}get currentSpanLocal(){return this.currentSpan?._tag===`Span`?this.currentSpan:void 0}},EB={interruptChildren:void 0},DB=e=>VB(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;){if(e.value._exit){r.push(e.value._exit),e=n.next();continue}i=e.value.addObserver(e=>{r.push(e),a()});return}t(OB(r))}return a(),jB(()=>i?.())}),OB=iR,kB=oR,AB=sR,jB=nR({op:`Sync`,[DL](e){let t=this[EL](),n=e.getCont(OL);return n?n[OL](t,e):e.yieldWith(iR(t))}}),MB=nR({op:`Suspend`,[DL](e){return this[EL]()}}),NB=nR({op:`Yield`,[DL](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(nV)},this[EL]??0),e.yieldWith(()=>{t=!0})}})(0),PB=e=>OB(RR(e)),FB=OB(LR()),IB=e=>cR(e),LB=e=>MB(()=>AB(xL(e))),RB=OB(void 0),zB=nR({op:`Async`,single:!1,[DL](e){let t=xL(()=>this[EL][0].bind(e.currentScheduler)),n=!1,r=!1,i=this[EL][1]?new AbortController:void 0,a=t(t=>{n||(n=!0,r?e.evaluate(t):r=t)},i?.signal);return r===!1?(r=!0,e._yielded=()=>{n=!0},i===void 0&&a===void 0||e._stack.push(BB(()=>(n=!0,i?.abort(),a??nV))),jL):r}}),BB=nR({op:`AsyncFinalizer`,[AL](e){e.interruptible&&(e.interruptible=!1,e._stack.push(bV))},[kL](e,t){return uB(e)?qB(this[EL](),()=>kB(e)):kB(e)}}),VB=e=>zB(e,e.length>=2),HB=(e,...t)=>{let n=t.length===0?function(){return MB(()=>KB(e.apply(this,arguments)))}:function(){let n=MB(()=>KB(e.apply(this,arguments)));for(let e=0;eObject.defineProperty(t,`length`,{value:e,configurable:!0}),WB=(e,...t)=>UB(e.length,t.length===0?function(){return GB(()=>e.apply(this,arguments))}:function(){let n=GB(()=>e.apply(this,arguments));for(let e of t)n=e(n);return n}),GB=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return OB(r.value);let i=r.value.asEffect(),a=i;if(a&&a._tag===`Success`){n=a.value;continue}else if(a&&a._tag===`Failure`)return i;else{let n=!0;return MB(()=>n?(n=!1,qB(i,e=>KB(t,e))):MB(()=>KB(e())))}}}catch(e){return IB(e)}},KB=nR({op:`Iterator`,single:!1,[OL](e,t){let n=this[EL][0];for(;;){let r=n.next(e);if(r.done)return OB(r.value);let i=r.value.asEffect();if(!YB(i))return t._stack.push(this),i;if(i._tag===`Failure`)return i;e=i.value}},[DL](e){return this[OL](this[EL][1],e)}}),qB=$F(2,(e,t)=>{let n=Object.create(JB);return n[EL]=e,n[OL]=t.length===1?t:e=>t(e),n}),JB=tR({op:`OnSuccess`,[DL](e){return e._stack.push(this),this[EL]}}),YB=e=>CL in e,XB=$F(2,(e,t)=>YB(e)?e._tag===`Success`?t(e.value):e:qB(e,t)),ZB=$F(2,(e,t)=>qB(e,e=>OB(xL(()=>t(e))))),QB=$F(2,(e,t)=>YB(e)?rV(e,t):ZB(e,t)),$B=$F(2,(e,t)=>YB(e)?iV(e,t):dV(e,t)),eV=$F(2,(e,t)=>{if(YB(e)){if(e._tag===`Success`)return e;let n=lB(e.cause);return qR(n)?e:t(n.success)}return uV(e,t)}),tV=e=>e._tag===`Success`,nV=iR(void 0),rV=$F(2,(e,t)=>e._tag===`Success`?iR(t(e.value)):e),iV=$F(2,(e,t)=>{if(e._tag===`Success`)return e;let n=lB(e.cause);return qR(n)?e:sR(t(n.success))}),aV=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?nV:oR(KL(t))},oV=e=>tV(e)?RR(e.value):LR(),sV=$F(2,(e,t)=>{let n=Object.create(cV);return n[EL]=e,n[kL]=t.length===1?t:e=>t(e),n}),cV=tR({op:`OnFailure`,[DL](e){return e._stack.push(this),this[EL]}}),lV=$F(3,(e,t,n)=>sV(e,e=>{let r=t(e);return qR(r)?kB(r.failure):xL(()=>n(r.success,e))})),uV=$F(2,(e,t)=>lV(e,lB,e=>t(e))),dV=$F(2,(e,t)=>uV(e,e=>LB(()=>t(e)))),fV=e=>uV(e,t=>qB(NB,()=>fV(e))),pV=e=>YB(e)?iR(e):mV(e),mV=nR({op:`Exit`,[DL](e){return e._stack.push(this),this[EL]},[OL](e,t,n){return OB(n??iR(e))},[kL](e,t,n){return OB(n??oR(e))}}),hV=`~effect/Scope`,gV=`~effect/Scope/Closeable`,_V=(e,t)=>{if(e.state._tag===`Closed`)return;let n={_tag:`Closed`,exit:t};if(e.state._tag===`Empty`){e.state=n;return}let{finalizers:r}=e.state;if(e.state=n,r.size!==0)return r.size===1?r.values().next().value(t):vV(e,r,t)},vV=HB(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=wB();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*pV(s(n))):i.push(CV(o,s(n),!0,!0,`inherit`))}return i.length>0&&(r=yield*DB(i)),yield*aV(r)}),yV={_tag:`Empty`},bV=nR({op:`SetInterruptible`,[AL](e){if(e.interruptible=this[EL],e._interruptedCause&&e.interruptible)return()=>kB(e._interruptedCause)}})(!0),xV=(e,t,n,r)=>qB(n(r,t),i=>{if(i)return OB(RR(r));let a=e.next();return a.done?OB(LR()):xV(e,t+1,n,a.value)}),SV=(e,t,n,r)=>qB(n(r,t),r=>{if(JR(r))return OB(RR(r.success));let i=e.next();return i.done?OB(LR()):SV(e,t+1,n,i.value)}),CV=(e,t,n=!1,r=!1,i=!1)=>{let a=i===`inherit`?e.interruptible:!i,o=new TB(e.services,a);return n?o.evaluate(t):e.currentDispatcher.scheduleTask(()=>o.evaluate(t),0),!r&&!o._exit&&(e.children().add(o),o.addObserver(()=>e._children.delete(o))),o},wV=e=>(t,n)=>{let r=new TB(n?.scheduler?zz(e,qz,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal)if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}return n?.onFiberStart&&n.onFiberStart(r),r},TV=e=>{let t=wV(e);return e=>{if(YB(e))return e;let n=t(e,{scheduler:new Xz(`sync`)});return n.currentDispatcher?.flush(),n._exit??cR(new AV(n))}},EV=TV(Iz()),DV=(e=>{let t=TV(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw pB(n.cause);return n.value}})(Iz()),OV=e=>e?Bz(e.annotations,tB)?e._tag===`Span`?OV(UR(e.parent)):LR():RR(e):LR();fR(`TimeoutError`),fR(`IllegalArgumentError`),fR(`ExceededCapacityError`);var kV=`~effect/Cause/AsyncFiberError`,AV=class extends fR(`AsyncFiberError`){[kV]=kV;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};fR(`UnknownError`);var jV={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};jV.gray,jV.blue,jV.green,jV.yellow,jV.red,jV.bgBrightRed,jV.black;var MV=typeof process==`object`&&process!==null&&typeof process.stdout==`object`&&process.stdout!==null;MV&&process.stdout.isTTY,MV||`Deno`in globalThis;var NV=lB;kz()(`effect/Cause/StackTrace`),kz()(`effect/Cause/InterruptorStackTrace`);var PV=oV;kz()(`effect/Layer/CurrentMemoMap`);var FV=fR,IV=`~effect/time/DateTime`,LV=`~effect/time/DateTime/TimeZone`,RV={[IV]:IV,pipe(){return XF(this,arguments)},[hL](){return this.toString()},toJSON(){return BV(this).toJSON()}};({...RV}),{...RV};var zV={[LV]:LV,[hL](){return this.toString()}};({...zV}),{...zV};var BV=e=>new Date(e.epochMilliseconds),VV=e=>{if(e._tag===`Utc`)return new Date(e.epochMilliseconds);if(e.zone._tag===`Offset`)return new Date(e.epochMilliseconds+e.zone.offset);if(e.adjustedEpochMilliseconds!==void 0)return new Date(e.adjustedEpochMilliseconds);let t=e.zone.format.formatToParts(e.epochMilliseconds).filter(e=>e.type!==`literal`),n=new Date(0);return n.setUTCFullYear(Number(t[2].value),Number(t[0].value)-1,Number(t[1].value)),n.setUTCHours(Number(t[3].value),Number(t[4].value),Number(t[5].value),Number(t[6].value)),e.adjustedEpochMilliseconds=n.getTime(),n},HV=e=>VV(e).getTime()-WV(e),UV=e=>{let t=Math.abs(e),n=Math.floor(t/(3600*1e3)),r=Math.round(t%(3600*1e3)/(60*1e3));return r===60&&(n+=1,r=0),`${e<0?`-`:`+`}${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`},WV=e=>e.epochMilliseconds;({...NL});var GV=OB,KV=FB,qV=PB,JV=AB,YV=pV,XV=DV,ZV=EV;kz()(`effect/Effect/Transaction`);var QV=QB,$V=$B,eH=XB,tH=eV,nH=WB;function rH(e,t,n){return t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n,e}function iH(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function aH(e){return t=>iH(t)?.[e]}var oH=aH(`identifier`),sH=oI(e=>{let t=oH(e);return typeof t==`string`?t:e.getExpected(sH)});globalThis.RegExp;var cH=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);kz()(`effect/DateTime/CurrentTimeZone`),FV(`EncodingError`);var lH=`~effect/SchemaIssue/Issue`;function uH(e){return vI(e,lH)}var dH=class{[lH]=lH;toString(){return kH(this)}},fH=class extends dH{_tag=`Filter`;actual;filter;issue;constructor(e,t,n){super(),this.actual=e,this.filter=t,this.issue=n}},pH=class extends dH{_tag=`Encoding`;ast;actual;issue;constructor(e,t,n){super(),this.ast=e,this.actual=t,this.issue=n}},mH=class extends dH{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},hH=class extends dH{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},gH=class extends dH{_tag=`UnexpectedKey`;ast;actual;constructor(e,t){super(),this.ast=e,this.actual=t}},_H=class extends dH{_tag=`Composite`;ast;actual;issues;constructor(e,t,n){super(),this.ast=e,this.actual=t,this.issues=n}},vH=class extends dH{_tag=`InvalidType`;ast;actual;constructor(e,t){super(),this.ast=e,this.actual=t}},yH=class extends dH{_tag=`InvalidValue`;actual;annotations;constructor(e,t){super(),this.actual=e,this.annotations=t}},bH=class extends dH{_tag=`AnyOf`;ast;actual;issues;constructor(e,t,n){super(),this.ast=e,this.actual=t,this.issues=n}},xH=class extends dH{_tag=`OneOf`;ast;actual;successes;constructor(e,t,n){super(),this.ast=e,this.actual=t,this.successes=n}};function SH(e,t){if(uH(t))return t;if(t!==void 0)return typeof t==`boolean`?t?void 0:new yH(RR(e)):typeof t==`string`?new yH(RR(e),{message:t}):new mH(t.path,new yH(RR(e),{message:t.message}))}var CH=e=>{let t=jH(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return TH(sH(e.ast),NH(e.actual));case`InvalidValue`:return`Invalid data ${NH(e.actual)}`;case`MissingKey`:return`Missing key`;case`UnexpectedKey`:return`Unexpected key with value ${cL(e.actual)}`;case`Forbidden`:return`Forbidden operation`;case`OneOf`:return`Expected exactly one member to match the input ${cL(e.actual)}`}},wH=e=>jH(e.issue)??jH(e);function TH(e,t){return`Expected ${e}, got ${t}`}function EH(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];switch(e.issue._tag){case`InvalidValue`:return[{path:t,message:TH(DH(e.filter),cL(e.actual))}];default:return EH(e.issue,t,n,r)}}case`Encoding`:return EH(e.issue,t,n,r);case`Pointer`:return EH(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>EH(e,t,n,r));case`AnyOf`:{let i=jH(e);return e.issues.length===0?i===void 0?[{path:t,message:TH(sH(e.ast),cL(e.actual))}]:[{path:t,message:i}]:e.issues.flatMap(e=>EH(e,t,n,r))}default:return[{path:t,message:n(e)}]}}function DH(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return``;case`FilterGroup`:return e.checks.map(e=>DH(e)).join(` & `)}}function OH(){return e=>EH(e,[],CH,wH).map(AH).join(` +`)}var kH=OH();function AH(e){let t=e.message;if(e.path&&e.path.length>0){let n=dL(e.path);t+=`\n at ${n}`}return t}function jH(e){switch(e._tag){case`InvalidType`:case`OneOf`:case`Composite`:case`AnyOf`:return MH(e.ast.annotations);case`InvalidValue`:case`Forbidden`:return MH(e.annotations);case`MissingKey`:return MH(e.annotations,`messageMissingKey`);case`UnexpectedKey`:return MH(e.ast.annotations,`messageUnexpectedKey`);case`Filter`:return MH(e.filter.annotations);case`Encoding`:return jH(e.issue)}}function MH(e,t=`message`){let n=e?.[t];if(typeof n==`string`)return n}function NH(e){return zR(e)?`no value provided`:cL(e.value)}var PH=class e extends QF{run;constructor(e){super(),this.run=e}map(t){return new e((e,n)=>this.run(e,n).pipe(QV(WR(t))))}compose(t){return IH(this)?t:IH(t)?this:new e((e,n)=>this.run(e,n).pipe(eH(e=>t.run(e,n))))}},FH=new PH(GV);function IH(e){return e.run===FH.run}function LH(){return FH}function RH(e){return zH(WR(e))}function zH(e){return new PH(t=>GV(e(t)))}function BH(){return RH(globalThis.String)}function VH(){return RH(globalThis.Number)}var HH=`~effect/SchemaTransformation/Transformation`,UH=class e{[HH]=HH;_tag=`Transformation`;decode;encode;constructor(e,t){this.decode=e,this.encode=t}flip(){return new e(this.encode,this.decode)}compose(t){return new e(this.decode.compose(t.decode),t.encode.compose(this.encode))}};function WH(e){return vI(e,HH)}var GH=e=>WH(e)?e:new UH(e.decode,e.encode);function KH(e){return new UH(RH(e.decode),RH(e.encode))}var qH=new UH(LH(),LH());function JH(){return qH}var YH=new UH(VH(),BH());function XH(e){return t=>t._tag===e}var ZH=XH(`Declaration`),QH=XH(`Never`),$H=XH(`Literal`),eU=XH(`UniqueSymbol`),tU=XH(`Arrays`),nU=XH(`Objects`),rU=XH(`Union`),iU=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},aU={},oU=class{isOptional;isMutable;defaultValue;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.defaultValue=n,this.annotations=r}},sU=`~effect/Schema`,cU=class{[sU]=sU;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},lU=class e extends cU{_tag=`Declaration`;typeParameters;run;constructor(e,t,n,r,i,a){super(n,r,i,a),this.typeParameters=e,this.run=t}getParser(){let e=this.run(this.typeParameters);return(t,n)=>zR(t)?KV:QV(e(t.value,this,n),RR)}recur(t){let n=tW(this.typeParameters,t);return n===this.typeParameters?this:new e(n,this.run,this.annotations,this.checks,void 0,this.context)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:``}},uU=new class extends cU{_tag=`Null`;getParser(){return vW(this,null)}getExpected(){return`null`}},dU=new class extends cU{_tag=`Unknown`;getParser(){return yW(this,gI)}getExpected(){return`unknown`}},fU=class extends cU{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${cL(e)}`);this.literal=e}getParser(){return vW(this,this.literal)}toCodecJson(){return typeof this.literal==`bigint`?pU(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:pU(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function pU(e){let t=globalThis.String(e.literal);return qU(e,[new iU(new fU(t),new UH(RH(()=>e.literal),RH(()=>t)))])}var mU=new class extends cU{_tag=`String`;getParser(){return yW(this,lI)}getExpected(){return`string`}},hU=class extends cU{_tag=`Number`;getParser(){return yW(this,uI)}toCodecJson(){return this.checks&&(gU(this.checks,`isFinite`)||gU(this.checks,`isInt`))?this:qU(this,[zU])}toCodecStringTree(){return this.checks&&(gU(this.checks,`isFinite`)||gU(this.checks,`isInt`))?qU(this,[EW]):qU(this,[DW])}getExpected(){return`number`}};function gU(e,t){return e.some(e=>{switch(e._tag){case`Filter`:return e.annotations?.meta?._tag===t;case`FilterGroup`:return gU(e.checks,t)}})}var _U=new hU,vU=new class extends cU{_tag=`Boolean`;getParser(){return yW(this,dI)}getExpected(){return`boolean`}},yU=class e extends cU{_tag=`Arrays`;isMutable;elements;rest;constructor(e,t,n,r,i,a,o){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n;let s=t.findIndex(cW);if(s!==-1&&(t.slice(s+1).some(e=>!cW(e))||n.length>1))throw Error(`A required element cannot follow an optional element. ts(1257)`);if(n.length>1&&n.slice(1).some(cW))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e){let t=this,n=t.elements.map(t=>({ast:t,parser:e(t)})),r=t.rest.map(t=>({ast:t,parser:e(t)})),i=n.length;return nH(function*(e,a){if(e._tag===`None`)return e;let o=e.value;if(!Array.isArray(o))return yield*JV(new vH(t,e));let s=[],c,l=a.errors===`all`,u=0;for(;u0){let[n,...i]=r,f=n.ast.context?.annotations;for(;ut.test(e))}case`Symbol`:return Object.getOwnPropertySymbols(e);case`Number`:return Object.keys(e).filter(e=>xU.test(e));case`Union`:return[...new Set(n.types.flatMap(t=>SU(e,t)))];default:return[]}}var CU=class{name;type;constructor(e,t){this.name=e,this.type=t}},wU=class e{decode;encode;constructor(e,t){this.decode=e,this.encode=t}flip(){return new e(this.encode,this.decode)}},TU=class{parameter;type;merge;constructor(e,t,n){if(this.parameter=e,this.type=t,this.merge=n,cW(t)&&!pW(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},EU=class e extends cU{_tag=`Objects`;propertySignatures;indexSignatures;constructor(e,t,n,r,i,a){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t;let o=e.map(e=>e.name).filter((e,t,n)=>n.indexOf(e)!==t);if(o.length>0)throw Error(`Duplicate identifiers: ${JSON.stringify(o)}. ts(2300)`)}getParser(e){let t=this,n=[],r=new Set,i=[],a=t.propertySignatures.length;for(let a of t.propertySignatures)n.push(a.name),r.add(a.name),i.push({ps:a,parser:e(a.type),name:a.name,type:a.type});let o=t.indexSignatures.length;return t.propertySignatures.length===0&&t.indexSignatures.length===0?yW(t,hI):nH(function*(s,c){if(s._tag===`None`)return s;let l=s.value;if(!(typeof l==`object`&&l&&!Array.isArray(l)))return yield*JV(new vH(t,s));let u={},d,f=c.errors===`all`,p=c.onExcessProperty===`error`,m=c.onExcessProperty===`preserve`,h;if(t.indexSignatures.length===0&&(p||m)){h=Reflect.ownKeys(l);for(let e=0;e0)for(let n=0;n{let n=t(e.type);return n===e.type?e:new CU(e.name,n)}),i=tW(this.indexSignatures,e=>{let r=t(e.parameter),i=t(e.type),a=n?e.merge?.flip():e.merge;return r===e.parameter&&i===e.type&&a===e.merge?e:new TU(r,i,a)});return r===this.propertySignatures&&i===this.indexSignatures?this:new e(r,i,this.annotations,this.checks,void 0,this.context)}flip(e){return this.rebuild(e,!0)}recur(e){return this.rebuild(e,!1)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function DU(e,t,n){return new EU(Reflect.ownKeys(e).map(t=>new CU(t,e[t].ast)),[],n,t)}function OU(e){return e.ast}function kU(e,t=void 0){return new yU(!1,e.map(e=>e.ast),[],void 0,t)}function AU(e,t,n){return new LU(e.map(OU),t,void 0,n)}function jU(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:case`Void`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`object`,`array`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(jU)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function MU(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[`~sentinels`];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!cW(t)){if($H(t))return[{key:e.name,literal:t.literal}];if(eU(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>$H(e)&&!cW(e)?[{key:t,literal:e.literal}]:[]);case`Suspend`:return MU(e.thunk())}}var NU=new WeakMap;function PU(e){let t=NU.get(e);if(t)return t;t={};for(let n of e){let e=uW(n);if(QH(e))continue;let r=jU(e),i=MU(e);t.byType??={};for(let e of r)(t.byType[e]??=[]).push(n);if(i.length>0){t.bySentinel??=new Map;for(let{key:e,literal:r}of i){let i=t.bySentinel.get(e);i||t.bySentinel.set(e,i=new Map);let a=i.get(r);a||i.set(r,a=[]),a.push(n)}}else{t.otherwise??={};for(let e of r)(t.otherwise[e]??=[]).push(n)}}return NU.set(e,t),t}function FU(e){return t=>{let n=uW(t);return n._tag===`Literal`?n.literal===e:n._tag===`UniqueSymbol`?n.symbol===e:!0}}function IU(e,t){let n=PU(t),r=e===null?`null`:Array.isArray(e)?`array`:typeof e;if(n.bySentinel){let t=n.otherwise?.[r]??[];if(r===`object`||r===`array`){for(let[r,i]of n.bySentinel)if(Object.hasOwn(e,r)){let n=i.get(e[r]);if(n)return[...n,...t].filter(FU(e))}}return t}return(n.byType?.[r]??[]).filter(FU(e))}var LU=class e extends cU{_tag=`Union`;types;mode;constructor(e,t,n,r,i,a){super(n,r,i,a),this.types=e,this.mode=t}getParser(e){let t=this;return nH(function*(n,r){if(n._tag===`None`)return n;let i=n.value,a=t.mode===`oneOf`,o=IU(i,t.types),s,c={out:void 0,successes:[]};for(let l=0;l{let n=uW(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter($H);if(t.length>0)return`${BU(n.isMutable)}[ ${t.map(t=>e(t)+VU(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>$H(e.type));if(t.length>0)return`{ ${t.map(t=>`${BU(t.type.context?.isMutable)}${uL(t.name)}${VU(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}},RU=new LU([new fU(`Infinity`),new fU(`-Infinity`),new fU(`NaN`)],`anyOf`),zU=new iU(new LU([_U,RU],`anyOf`),new UH(VH(),RH(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function BU(e){return e?``:`readonly `}function VU(e){return e?`?`:``}var HU=class e extends QF{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(t){return new e(this.run,{...this.annotations,...t},this.aborted)}abort(){return new e(this.run,this.annotations,!0)}and(e,t){return new UU([this,e],t)}},UU=class e extends QF{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(t){return new e(this.checks,{...this.annotations,...t})}and(t,n){return new e([this,t],n)}};function WU(e,t,n=!1){return new HU((t,n,r)=>SH(t,e(t,n,r)),t,n)}function GU(e,t){let n=e.source;return WU(t=>e.test(t),{expected:`a string matching the RegExp ${n}`,meta:{_tag:`isPattern`,regExp:e},toArbitraryConstraint:{string:{patterns:[e.source]}},...t})}function KU(e,t){let n=Object.getOwnPropertyDescriptors(e);return t(n),Object.create(Object.getPrototypeOf(e),n)}function qU(e,t){return e.encoding===t?e:KU(e,e=>{e.encoding.value=t})}function JU(e,t){return e.context===t?e:KU(e,e=>{e.context.value=t})}function YU(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return XU(e,ZR(e.checks.slice(0,-1),n.annotate(t)))}return KU(e,e=>{e.annotations.value={...e.annotations.value,...t}})}function XU(e,t){return e.checks===t?e:KU(e,e=>{e.checks.value=t})}function ZU(e,t){return XU(e,e.checks?[...e.checks,...t]:t)}function QU(e,t){let n=e,r=n[n.length-1],i=t(r.to);return i===r.to?e:ZR(e.slice(0,e.length-1),new iU(i,r.transformation))}function $U(e){return t=>t.encoding?qU(t,QU(t.encoding,e)):t}function eW(e,t,n){let r=new iU(e,t);return qU(n,n.encoding?[...n.encoding,r]:[r])}function tW(e,t){let n=!1,r=Array(e.length);for(let i=0;inew CU(e,t)),i.map(e=>new TU(e,t,n)))}function cW(e){return e.context?.isOptional??!1}var lW=oI(e=>{if(e.encoding)return lW(qU(e,void 0));let t=e;return t.recur?.(lW)??t}),uW=oI(e=>lW(fW(e)));function dW(e,t){let n=t,r=n.length,i=n[r-1],a=[new iU(fW(qU(e,void 0)),n[0].transformation.flip())];for(let e=1;e{if(e.encoding)return dW(e,e.encoding);let t=e;return t.flip?.(fW)??t.recur?.(fW)??t});function pW(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(pW);default:return!1}}function mW(e,t){return e.encodedParts.map(e=>_W(e,gW(e),t)).join(``)}var hW=oI(e=>new globalThis.RegExp(`^${mW(e,!0)}$`));function gW(e){switch(e._tag){case`Literal`:return cH(globalThis.String(e.literal));case`String`:return SW;case`Number`:return bU;case`BigInt`:return OW;case`TemplateLiteral`:return mW(e,!1);case`Union`:return e.types.map(gW).join(`|`)}}function _W(e,t,n){if(rU(e)){if(!n)return`(?:${t})`}else if(!n)return t;return`(${t})`}function vW(e,t){let n=qV(t);return r=>r._tag===`None`?KV:r.value===t?n:JV(new vH(e,r))}function yW(e,t){return n=>n._tag===`None`?KV:t(n.value)?GV(n):JV(new vH(e,n))}function bW(e){function t(n){return n.encoding?qU(n,QU(n.encoding,t)):e(n)}return oI(t)}var xW=bW(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(xW)}}),SW=`[\\s\\S]*?`,CW=new globalThis.RegExp(`^${bU}$`);function wW(e){return GU(CW,{expected:`a string representing a finite number`,meta:{_tag:`isStringFinite`,regExp:CW},...e})}var TW=ZU(mU,[wW()]),EW=new iU(TW,YH),DW=new iU(new LU([TW,RU],`anyOf`),YH),OW=`-?\\d+`;`${OW}`;function kW(e,t,n,r,i){for(let a=0;ae,NW=$F(2,(e,t)=>PW(e,(e,n)=>[e,t(n)]));function PW(e,t){let n={};for(let r in e){let i=t(r,e[r]);if(i){let[e,t]=i;n[e]=t}}return n}var FW=oI(e=>{switch(e._tag){case`Declaration`:{let t=e.annotations?.[AW];if(mI(t)){let n=t(e.typeParameters),r=FW(n.to);return qU(e,r===n.to?[n]:[new iU(r,n.transformation)])}return e}case`Objects`:case`Arrays`:return e.recur(e=>{let t=e.context?.defaultValue;return t?qU(FW(e),t):FW(e)});case`Suspend`:return e.recur(FW);default:return e}});function IW(e){let t=VW(FW(lW(e.ast)));return(e,n)=>t(e,n?.disableChecks?n?.parseOptions?{...n.parseOptions,disableChecks:!0}:{disableChecks:!0}:n?.parseOptions)}function LW(e){let t=IW(e);return(e,n)=>PV(ZV(t(e,n)))}function RW(e){let t=IW(e);return(e,n)=>XV($V(t(e,n),e=>Error(e.toString(),{cause:e})))}function zW(e){return VW(e.ast)}function BW(e){return UW(zW(e))}function VW(e){let t=WW(e);return(e,n)=>eH(t(RR(e),n??aU),e=>e._tag===`None`?JV(new yH(e)):GV(e.value))}function HW(e){return(t,n)=>ZV(e(t,n))}function UW(e){let t=HW(e);return(e,n)=>PV(t(e,n))}var WW=oI(e=>{let t;if(!e.context&&!e.encoding&&!e.checks)return(n,r)=>(t??=e.getParser(WW),t(n,iH(e)?.parseOptions??r));let n=tU(e)||nU(e)||ZH(e)&&e.typeParameters.length>0;return(r,i)=>{i=iH(e)?.parseOptions??i;let a=e.encoding,o;if(a){let t=a,n=t.length;for(let e=n-1;e>=0;e--){let n=t[e],a=n.to,s=WW(a);if(o=o?eH(o,e=>s(e,i)):s(r,i),n.transformation._tag===`Transformation`){let e=n.transformation.decode;o=eH(o,t=>e.run(t,i))}else o=n.transformation.decode(o,i)}o=$V(o,t=>new pH(e,r,t))}t??=e.getParser(WW);let s=o?eH(o,e=>t(e,i)):t(r,i);if(e.checks&&!i?.disableChecks){let t=e.checks;i?.errors===`all`&&n&&BR(r)&&(s=tH(s,n=>{let a=[];return kW(t.filter(e=>e.annotations?.[jW]),r.value,a,e,i),JV($R(a)?n._tag===`Composite`&&n.ast===e?new _H(e,n.actual,[...n.issues,...a]):new _H(e,r,[n,...a]):n)})),s=eH(s,n=>{if(BR(n)){let r=n.value,a=[];if(kW(t,r,a,e,i),$R(a))return JV(new _H(e,n,a))}return GV(n)})}return s}}),GW=`~effect/Schema/Schema`,KW={[GW]:GW,pipe(){return XF(this,arguments)},annotate(e){return this.rebuild(YU(this.ast,e))},annotateKey(e){return this.rebuild(nW(this.ast,e))},check(...e){return this.rebuild(ZU(this.ast,e))}};function qW(e,t){let n=Object.create(KW);return t&&Object.assign(n,t),n.ast=e,n.rebuild=e=>qW(e,t),n.makeUnsafe=RW(n),n.makeOption=LW(n),n}function JW(){return(e,t,n)=>ZW(new lU(e.map(OU),e=>t(e.map(e=>ZW(e))),n))}function YW(e,t){return JW()([],()=>(t,n)=>e(t)?GV(t):JV(new vH(n,RR(t))),t)}var XW=BW,ZW=qW,QW=MW(e=>ZW(iW(e.ast),{schema:e}));function $W(e){let t=ZW(new fU(e),{literal:e,transform(n){return t.pipe(pG($W(n),{decode:RH(()=>n),encode:RH(()=>e)}))}});return t}var eG=ZW(dU),tG=ZW(uU),nG=ZW(mU),rG=ZW(_U),iG=ZW(vU);function aG(e,t){return ZW(e,{fields:t,mapFields(e,t){let n=e(this.fields);return aG(DU(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function oG(e){return aG(DU(e,void 0),e)}function sG(e,t,n){let r=n?.keyValueCombiner?.decode||n?.keyValueCombiner?.encode?new wU(n.keyValueCombiner.decode,n.keyValueCombiner.encode):void 0;return ZW(sW(e.ast,t.ast,r),{key:e,value:t})}function cG(e,t){return ZW(e,{elements:t,mapElements(e,t){let n=e(this.elements);return cG(kU(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}var lG=MW(e=>ZW(new yU(!1,[],[e.ast]),{schema:e}));function uG(e,t){return ZW(e,{members:t,mapMembers(e,t){let n=e(this.members);return uG(AU(n,this.ast.mode,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function dG(e,t){return uG(AU(e,t?.mode??`anyOf`,void 0),e)}function fG(e){let t=e.map($W);return ZW(AU(t,`anyOf`,void 0),{literals:e,members:t,mapMembers(e){return dG(e(this.members))},pick(e){return fG(e)},transform(e){return dG(t.map((t,n)=>t.transform(e[n])))}})}function pG(e,t){return n=>ZW(aW(n.ast,e.ast,t?GH(t):JH()),{from:n,to:e})}function mG(e,t){return YW(t=>t instanceof e,t)}function hG(){return(e,t)=>new iU(e.ast,GH(t))}var gG=WU;function _G(e){let t=IR(e.order),n=e.formatter??cL;return(r,i)=>gG(e=>t(e,r),{expected:`a value greater than ${n(r)}`,...e.annotate?.(r),...i})}var vG=_G({order:FR,annotate:e=>({meta:{_tag:`isGreaterThan`,exclusiveMinimum:e},toArbitraryConstraint:{number:{min:e,minExcluded:!0}}})});globalThis.Error,globalThis.Error,globalThis.RegExp,globalThis.URL;var yG=mG(globalThis.Date,{typeConstructor:{_tag:`Date`},generation:{runtime:`Schema.Date`,Type:`globalThis.Date`},expected:`Date`,toCodecJson:()=>hG()(nG.annotate({expected:`a string in ISO 8601 format that will be decoded as a Date`}),KH({decode:e=>new globalThis.Date(e),encode:fL})),toArbitrary:()=>(e,t)=>e.date(t?.constraints?.date)});globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var bG=nG.annotate({expected:`a string that will be decoded as a number`}).pipe(pG(rG,YH));globalThis.Uint8Array;var xG=dG([nG.annotate({plotChannel:`field`}),rG.annotate({plotChannel:`value`})]),SG=dG([rG.annotate({plotChannel:`interval`}),nG.annotate({plotChannel:`interval`})]),CG=dG([rG,nG,lG(dG([rG,nG,yG]))]),wG=sG(nG,dG([nG,rG,bG,iG,yG,tG])).annotate({description:`Single bar data object. Keys are column names used by marks.x and marks.y. Default channels expect keys 'category' (string-ish) and 'value' (number-ish). If you use different keys, set marks.x and marks.y to those key names.`,examples:[{category:`Q1`,value:120},{product:`Alpha`,sales:48,region:`EU`}]});oG({category:nG,value:dG([rG,bG])}).mapFields(NW(QW));var TG=dG([rG,bG]).check(vG(0)),EG=oG({title:nG,subtitle:nG,caption:nG,aspectRatio:TG,marginTop:TG,marginRight:TG,marginBottom:TG,marginLeft:TG,margin:TG,width:TG,height:TG,inset:TG,grid:iG,color:oG({legend:iG})}).mapFields(NW(QW)),DG=oG({x:xG.annotate({description:`Primary position channel. For vertical bars, maps to the category/ordinal axis; for horizontal bars, maps to the value axis.`}),y:xG.annotate({description:`Primary value channel. For vertical bars, maps to the value axis; for horizontal bars, maps to the category/ordinal axis.`}),z:xG.annotate({description:`Series/channel for grouping within each stack. Use with fill for stacked bars when multiple series share the same x/y.`}),interval:SG,inset:TG,fill:xG.annotate({description:`Series/color channel. With only x and y available, setting fill (or z) makes Plot apply the stack transform, producing stacked bars. Vertical bars stack by x; horizontal bars stack by y.`}),stroke:xG.annotate({description:`Stroke color channel. Maps to the outline color of the bars.`}),tip:iG.annotate({description:`If true, show a tooltip with all data fields on hover.`})}).mapFields(NW(QW));oG({x:xG,y:xG,anchor:fG([`top`,`right`,`bottom`,`left`]),ticks:CG,tickFormat:dG([nG,eG]),tickRotate:rG,label:dG([nG,tG]),labelAnchor:fG([`top`,`right`,`bottom`,`left`,`center`])}).mapFields(NW(QW));var OG=oG({data:lG(wG).annotate({description:`Array of bar data objects. Each object must expose the keys used in marks.x and marks.y.`}),direction:fG([`horizontal`,`vertical`]).annotate({description:`Orientation of bars. Vertical defaults to x=category and y=value; horizontal swaps them.`}),layout:EG.annotate({description:`Plot layout options. All fields optional; omit to use defaults.`}),marks:DG.annotate({description:`Mark channel mapping. Use marks.x and marks.y to select data keys. If omitted, defaults are x=category and y=value for vertical bars, swapped for horizontal.`})}).annotate({description:`Payload for render_bar_chart_widget. LLM guidance: choose marks.x and marks.y to match keys in data objects.`}),kG=e((e=>{var t=Symbol.for(`react.transitional.element`);function n(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.jsx=n,e.jsxs=n})),AG=e(((e,t)=>{t.exports=kG()}))(),jG=e=>{if(e.isError)return null;let t=e.structuredContent,n=XW(OG)(t);if(BR(n))return n.value;let r=e.content?.find(e=>e.type===`text`)?.text;if(r)try{return HR(XW(OG)(JSON.parse(r)))}catch{return null}return null},MG=({data:e,direction:t,layout:n,marks:r})=>{let i=(0,Rr.useRef)(null),a=(0,Rr.useRef)(null),[o,s]=(0,Rr.useState)(null);return(0,Rr.useEffect)(()=>{if(!a.current)return;let{width:i,...s}=n??{},c=i??o??void 0,l=t===`horizontal`,u=r??{},d=r?.x??(l?`value`:`category`),f=r?.y??(l?`category`:`value`);d!==void 0&&(u.x=d),f!==void 0&&(u.y=f);let p=l?JF(e,u):YF(e,u),m=l?PM([0]):FM([0]),h={style:`--plot-background: var(--color-background-primary);`,...s,color:{...s.color?s.color:{},scheme:`Category10`},marks:[m,p].filter(Boolean)};c!==void 0&&(h.width=c);let g=hF(h);return a.current.replaceChildren(g),()=>g.remove()},[e,n,r,o,t]),(0,Rr.useEffect)(()=>{if(!i.current)return;let e=i.current,t=new ResizeObserver(e=>{let t=e[0];if(!t)return;let n=Math.floor(t.contentRect.width);Number.isFinite(n)&&n>0&&s(n)});return t.observe(e),()=>t.disconnect()},[]),(0,AG.jsx)(`div`,{ref:i,style:{width:`100%`,color:`var(--color-text-primary, #111)`,backgroundColor:`var(--color-background-secondary, #fff)`,fontFamily:`var(--font-sans, system-ui, sans-serif)`},children:(0,AG.jsx)(`div`,{ref:a})})},NG=()=>{let[e,t]=(0,Rr.useState)(null),{app:n,isConnected:r,error:i}=Nc({appInfo:{name:`bar-chart-widget`,version:`0.1.0`},capabilities:{},onAppCreated:e=>{e.ontoolinput=e=>{let n=HR(XW(OG)(e.arguments));n&&t(n)},e.ontoolresult=e=>{let n=jG(e);n&&t(n)}}});return Ic(n,n?.getHostContext()),i?(0,AG.jsxs)(`div`,{style:{padding:16},children:[`Error: `,i.message]}):r?e?(0,AG.jsx)(MG,{...e}):(0,AG.jsx)(`div`,{style:{padding:16},children:`Waiting for data…`}):(0,AG.jsx)(`div`,{style:{padding:16},children:`Connecting…`})},PG=document.getElementById(`root`);if(!PG)throw Error(`Widget root element not found`);(0,zr.createRoot)(PG).render((0,AG.jsx)(NG,{}));
diff --git a/apps/server-mcp/src/widget/bar-chart/bar-chart.ts b/apps/server-mcp/src/widget/bar-chart/bar-chart.ts index bcfd441..f2ed33f 100644 --- a/apps/server-mcp/src/widget/bar-chart/bar-chart.ts +++ b/apps/server-mcp/src/widget/bar-chart/bar-chart.ts @@ -1,16 +1,17 @@ -import { join as joinPath } from "node:path"; -import { Effect, FileSystem, Schema } from "effect"; +import { BarChartWidgetPayload } from "@repo/domain/Chart"; +import { Effect, FileSystem, Path } from "effect"; import { makeUiRenderTool, makeUiResource } from "../../UiResource"; const BarChartWidgetResourceUri = "ui://bar-chart"; const BarChartWidgetHtml = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const sourceSuffix = joinPath("widget", "bar-chart"); + const path = yield* Path.Path; + const sourceSuffix = path.join("widget", "bar-chart"); const isSourcePath = import.meta.dir.endsWith(sourceSuffix); const htmlPath = isSourcePath - ? joinPath(import.meta.dir, "bar-chart-widget.html") - : joinPath(import.meta.dir, "widget/bar-chart/bar-chart-widget.html"); + ? path.join(import.meta.dir, "bar-chart-widget.html") + : path.join(import.meta.dir, "widget/bar-chart/bar-chart-widget.html"); return yield* fs.readFileString(htmlPath); }); @@ -27,29 +28,6 @@ export const BarChartWidgetResourceLayer = makeUiResource( }, ); -const BarChartNumber = Schema.Union([Schema.Number, Schema.NumberFromString]); - -const BarChartDatum = Schema.Struct({ - category: Schema.String, - value: BarChartNumber, -}); - -const BarChartWidgetProps = Schema.Struct({ - title: Schema.optional(Schema.String), - valueLabel: Schema.optional(Schema.String), - maxWidth: Schema.optional(BarChartNumber), - width: Schema.optional(BarChartNumber), - height: Schema.optional(BarChartNumber), - showLabels: Schema.optional(Schema.Boolean), - maxY: Schema.optional(BarChartNumber), -}); - -export const BarChartWidgetPayload = Schema.Struct({ - data: Schema.optional(Schema.Array(BarChartDatum)), - dataUrl: Schema.optional(Schema.String), - props: Schema.optional(BarChartWidgetProps), -}); - export const RenderBarChartWidgetTool = makeUiRenderTool( BarChartWidgetResourceUri, { diff --git a/apps/server-mcp/tsconfig.json b/apps/server-mcp/tsconfig.json index 0d48597..f5ffb78 100644 --- a/apps/server-mcp/tsconfig.json +++ b/apps/server-mcp/tsconfig.json @@ -10,7 +10,6 @@ } ] }, - "references": [{ "path": "../../packages/domain" }], "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } diff --git a/bun.lock b/bun.lock index 6c14649..1d3e7c5 100644 --- a/bun.lock +++ b/bun.lock @@ -85,6 +85,7 @@ "devDependencies": { "@effect/language-service": "^0.84.2", "@effect/vitest": "4.0.0-beta.43", + "@repo/bar-chart-widget": "workspace:*", "@repo/config-typescript": "workspace:*", "@types/bun": "1.3.11", "vitest": "^4.1.2", @@ -106,14 +107,17 @@ "name": "@repo/bar-chart-widget", "version": "0.0.0", "dependencies": { + "@modelcontextprotocol/ext-apps": "^1.3.2", "@observablehq/plot": "^0.6.17", "d3": "^7.9.0", + "effect": "4.0.0-beta.43", "framer-motion": "^12.23.6", "react": "^19.2.4", "react-dom": "^19.2.4", }, "devDependencies": { "@repo/config-typescript": "workspace:*", + "@repo/domain": "workspace:*", "@types/d3": "^7.4.3", "@types/node": "^25.5.0", "@types/react": "^19.2.14", @@ -309,6 +313,8 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@modelcontextprotocol/ext-apps": ["@modelcontextprotocol/ext-apps@1.3.2", "", { "peerDependencies": { "@modelcontextprotocol/sdk": "^1.24.0", "react": "^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-DGG1FxN3s8g4KV+BF64dxph8j2mtxgU56Lu/WgBjylomqRIPshW0ut47OtBN4+V8r+Qp8kKUvCOBBzPY9+GurA=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.27.1", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-sr6GbP+4edBwFndLbM60gf07z0FQ79gaExpnsjMGePXqFcSSb7t6iscpjk9DhFhwd+mTEQrzNafGP8/iGGFYaA=="], "@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="], diff --git a/packages/bar-chart-widget/package.json b/packages/bar-chart-widget/package.json index bbceaa0..b023e68 100644 --- a/packages/bar-chart-widget/package.json +++ b/packages/bar-chart-widget/package.json @@ -4,21 +4,27 @@ "version": "0.0.0", "type": "module", "scripts": { - "build": "vite build", - "dev": "vite --host --clearScreen false", + "build": "vite build && bun run build:asset", + "build:asset": "bun scripts/copy-asset.ts build", + "dev": "bun run dev:asset & vite build --watch", + "dev:asset": "bun scripts/copy-asset.ts dev --watch", + "dev:local": "vite --host --clearScreen false", "preview": "vite preview", "type-check": "tsc --noEmit -p tsconfig.json", "clean": "git clean -xdf .cache dist node_modules" }, "dependencies": { - "d3": "^7.9.0", + "@modelcontextprotocol/ext-apps": "^1.3.2", "@observablehq/plot": "^0.6.17", + "d3": "^7.9.0", + "effect": "4.0.0-beta.43", "framer-motion": "^12.23.6", "react": "^19.2.4", "react-dom": "^19.2.4" }, "devDependencies": { "@repo/config-typescript": "workspace:*", + "@repo/domain": "workspace:*", "@types/d3": "^7.4.3", "@types/node": "^25.5.0", "@types/react": "^19.2.14", diff --git a/packages/bar-chart-widget/scripts/copy-asset.ts b/packages/bar-chart-widget/scripts/copy-asset.ts new file mode 100644 index 0000000..9981292 --- /dev/null +++ b/packages/bar-chart-widget/scripts/copy-asset.ts @@ -0,0 +1,60 @@ +import { existsSync, watch } from "node:fs"; +import { copyFile, mkdir } from "node:fs/promises"; +import path from "node:path"; + +const mode = process.argv[2]; +const shouldWatch = process.argv.includes("--watch"); + +if (mode !== "build" && mode !== "dev") { + console.error("Usage: bun scripts/copy-asset.ts [--watch]"); + process.exit(1); +} + +const sourcePath = path.resolve("dist/index.html"); +const destinationDir = path.resolve( + mode === "dev" + ? "../../apps/server-mcp/src/widget/bar-chart" + : "../../apps/server-mcp/dist/widget/bar-chart", +); +const destinationPath = path.join(destinationDir, "bar-chart-widget.html"); + +const waitForSource = async () => { + if (existsSync(sourcePath)) { + return; + } + + await new Promise((resolve) => { + const interval = setInterval(() => { + if (existsSync(sourcePath)) { + clearInterval(interval); + resolve(); + } + }, 200); + }); +}; + +const copyOnce = async () => { + await mkdir(destinationDir, { recursive: true }); + await copyFile(sourcePath, destinationPath); +}; + +const copyAfterBuild = async () => { + await waitForSource(); + await copyOnce(); +}; + +if (shouldWatch) { + await copyAfterBuild(); + + watch( + path.dirname(sourcePath), + { persistent: true }, + async (_event, file) => { + if (file === path.basename(sourcePath)) { + await copyOnce(); + } + }, + ); +} else { + await copyAfterBuild(); +} diff --git a/packages/bar-chart-widget/src/bar-chart.tsx b/packages/bar-chart-widget/src/bar-chart.tsx index 0d9f0df..b512be8 100644 --- a/packages/bar-chart-widget/src/bar-chart.tsx +++ b/packages/bar-chart-widget/src/bar-chart.tsx @@ -1,115 +1,32 @@ +import { useApp, useHostStyles } from "@modelcontextprotocol/ext-apps/react"; import * as Plot from "@observablehq/plot"; +import { BarChartWidgetPayload } from "@repo/domain/Chart"; +import { Option, Schema } from "effect"; import { useEffect, useRef, useState } from "react"; -type BarChartDatum = { - category: string; - value: number; -}; - -type BarChartWidgetProps = { - title?: string; - valueLabel?: string; - maxWidth?: number; - width?: number; - height?: number; - showLabels?: boolean; - maxY?: number; -}; - -type BarChartWidgetPayload = { - data?: BarChartDatum[]; - dataUrl?: string; - props?: BarChartWidgetProps; -}; - -const defaultProps: Required< - Pick -> = { - width: 420, - height: 260, - showLabels: true, -}; - -const isBarChartDatum = (value: unknown): value is BarChartDatum => { - if (!value || typeof value !== "object") { - return false; - } - - const record = value as Record; - return ( - typeof record["category"] === "string" && - typeof record["value"] === "number" - ); -}; - -const parsePayload = (value: unknown): BarChartWidgetPayload | null => { - if (!value || typeof value !== "object") { - return null; - } - - const record = value as Record; - const dataValue = record["data"]; - const data = Array.isArray(dataValue) - ? dataValue.filter(isBarChartDatum) - : null; - const dataUrl = - typeof record["dataUrl"] === "string" ? record["dataUrl"] : null; - if (!dataUrl && (!data || data.length === 0)) { +const extractPayloadFromToolResult = ( + params: Parameters< + NonNullable["app"]>["ontoolresult"]> + >[0], +) => { + if (params.isError) { return null; } - const propsValue = record["props"]; - const props = - propsValue && typeof propsValue === "object" - ? (propsValue as BarChartWidgetProps) - : undefined; - - if (data && data.length > 0) { - return props ? { data, props } : { data }; - } - - if (dataUrl) { - return props ? { dataUrl, props } : { dataUrl }; - } - - return null; -}; - -type ToolResultMessage = { - method?: string; - params?: { - isError?: boolean; - structuredContent?: unknown; - content?: Array<{ type: string; text?: string }>; - }; -}; - -type HostContextMessage = { - method?: string; - params?: Record; -}; - -const extractPayloadFromMessage = (message: ToolResultMessage) => { - if (message.method !== "ui/notifications/tool-result") { - return null; - } - - if (message.params?.isError) { - return null; - } - - const structured = message.params?.structuredContent; - const structuredPayload = parsePayload(structured); - if (structuredPayload) { - return structuredPayload; + const structured = params.structuredContent; + const structuredPayload = Schema.decodeUnknownOption(BarChartWidgetPayload)( + structured, + ); + if (Option.isSome(structuredPayload)) { + return structuredPayload.value; } - const text = message.params?.content?.find( - (item) => item.type === "text", - )?.text; + const text = params.content?.find((item) => item.type === "text")?.text; if (text) { try { - return parsePayload(JSON.parse(text)); + return Option.getOrNull( + Schema.decodeUnknownOption(BarChartWidgetPayload)(JSON.parse(text)), + ); } catch { return null; } @@ -118,59 +35,12 @@ const extractPayloadFromMessage = (message: ToolResultMessage) => { return null; }; -const sendRequest = (method: string, params: Record) => { - const id = crypto.randomUUID(); - window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*"); - return new Promise | null>((resolve) => { - const listener = (event: MessageEvent) => { - const payload = event.data?.payload ?? event.data; - if (!payload || payload.id !== id) { - return; - } - window.removeEventListener("message", listener); - resolve(payload.result ?? null); - }; - window.addEventListener("message", listener); - }); -}; - -const applyThemeFromContext = (context: Record) => { - const theme = context["theme"]; - if (theme === "light" || theme === "dark") { - document.documentElement.setAttribute("data-theme", theme); - document.documentElement.style.colorScheme = theme; - } - - const styles = context["styles"]; - if (styles && typeof styles === "object") { - const stylesRecord = styles as Record; - const variables = stylesRecord["variables"]; - if (variables && typeof variables === "object") { - for (const [key, value] of Object.entries( - variables as Record, - )) { - if (value !== undefined) { - document.documentElement.style.setProperty(key, String(value)); - } - } - } - } -}; - -type BarChartProps = BarChartWidgetProps & { - data: BarChartDatum[]; -}; - const BarChart = ({ data, - title, - valueLabel, - maxWidth, - width, - height = defaultProps.height, - showLabels = defaultProps.showLabels, - maxY, -}: BarChartProps) => { + direction, + layout, + marks, +}: typeof BarChartWidgetPayload.Type) => { const wrapperRef = useRef(null); const containerRef = useRef(null); const [measuredWidth, setMeasuredWidth] = useState(null); @@ -180,46 +50,39 @@ const BarChart = ({ return undefined; } - const yOptions: Plot.ScaleOptions = { grid: true }; - if (valueLabel !== undefined) { - yOptions.label = valueLabel; + const { width: layoutWidth, ...layoutOptions } = layout ?? {}; + const plotWidth = layoutWidth ?? measuredWidth ?? undefined; + const isHorizontal = direction === "horizontal"; + const barOptions = (marks ?? {}) as Plot.BarXOptions | Plot.BarYOptions; + const defaultX = marks?.x ?? (isHorizontal ? "value" : "category"); + const defaultY = marks?.y ?? (isHorizontal ? "category" : "value"); + if (defaultX !== undefined) { + barOptions.x = defaultX; } - if (maxY !== undefined) { - yOptions.domain = [0, maxY]; + if (defaultY !== undefined) { + barOptions.y = defaultY; } - - const plotWidth = width ?? measuredWidth ?? defaultProps.width; - const plot = Plot.plot({ + const barMark = isHorizontal + ? Plot.barX(data, barOptions) + : Plot.barY(data, barOptions); + const ruleMark = isHorizontal ? Plot.ruleX([0]) : Plot.ruleY([0]); + const plotOptions: Plot.PlotOptions = { style: "--plot-background: var(--color-background-primary);", - width: plotWidth, - height, - marginLeft: 48, - marginBottom: 40, - y: yOptions, - marks: [ - Plot.ruleY([0]), - Plot.barY(data, { - x: "category", - y: "value", - fill: "#38bdf8", - tip: "xy", - }), - showLabels - ? Plot.text(data, { - x: "category", - y: "value", - text: (d: BarChartDatum) => d.value, - dy: -6, - fill: "currentColor", - fontSize: 12, - }) - : null, - ].filter(Boolean), - }); + ...layoutOptions, + color: { + ...(layoutOptions.color ? layoutOptions.color : {}), + scheme: "Category10", + }, + marks: [ruleMark, barMark].filter(Boolean), + }; + if (plotWidth !== undefined) { + plotOptions.width = plotWidth; + } + const plot = Plot.plot(plotOptions); containerRef.current.replaceChildren(plot); return () => plot.remove(); - }, [data, height, maxY, measuredWidth, showLabels, valueLabel, width]); + }, [data, layout, marks, measuredWidth, direction]); useEffect(() => { if (!wrapperRef.current) { @@ -246,125 +109,55 @@ const BarChart = ({
- {title ?

{title}

: null}
); }; export const WidgetApp = () => { - const [payload, setPayload] = useState(null); - const [resolved, setResolved] = useState(null); - const [loadError, setLoadError] = useState(null); - - useEffect(() => { - const handleMessage = ( - event: MessageEvent, - ) => { - const message = event.data ?? {}; - if (message.method === "ui/notifications/host-context-changed") { - const context = (message.params ?? {}) as Record; - applyThemeFromContext(context); - return; - } - - const parsed = extractPayloadFromMessage(message); - if (parsed) { - setPayload(parsed); - } - }; - - window.addEventListener("message", handleMessage); - sendRequest("ui/initialize", { - appCapabilities: {}, - appInfo: { name: "bar-chart-widget", version: "0.1.0" }, - protocolVersion: "2026-01-26", - }).then((result) => { - const hostContext = result?.["hostContext"]; - if (hostContext && typeof hostContext === "object") { - applyThemeFromContext(hostContext as Record); - } - }); - - return () => { - window.removeEventListener("message", handleMessage); - }; - }, []); - - useEffect(() => { - if (!payload) { - setResolved(null); - setLoadError(null); - return undefined; - } - - if (payload.data) { - setResolved(payload); - setLoadError(null); - return undefined; - } - - if (!payload.dataUrl) { - setResolved(null); - setLoadError("Missing data or dataUrl"); - return undefined; - } - - const controller = new AbortController(); - const load = async () => { - try { - setLoadError(null); - setResolved(null); - const response = await fetch(payload.dataUrl as string, { - signal: controller.signal, - }); - if (!response.ok) { - throw new Error(`Request failed with ${response.status}`); - } - const json = await response.json(); - const nextData = Array.isArray(json) - ? json - : Array.isArray(json?.data) - ? json.data - : []; - const data = nextData.filter(isBarChartDatum); - if (data.length === 0) { - throw new Error("No valid data points"); + const [payload, setPayload] = useState< + typeof BarChartWidgetPayload.Type | null + >(null); + const { app, isConnected, error } = useApp({ + appInfo: { name: "bar-chart-widget", version: "0.1.0" }, + capabilities: {}, + onAppCreated: (app) => { + app.ontoolinput = (params) => { + const parsed = Option.getOrNull( + Schema.decodeUnknownOption(BarChartWidgetPayload)(params.arguments), + ); + if (parsed) { + setPayload(parsed); } - setResolved(payload.props ? { data, props: payload.props } : { data }); - } catch (error) { - if (!controller.signal.aborted) { - setLoadError( - error instanceof Error ? error.message : "Failed to load data", - ); + }; + app.ontoolresult = (params) => { + const parsed = extractPayloadFromToolResult(params); + if (parsed) { + setPayload(parsed); } - } - }; + }; + }, + }); - void load(); - return () => controller.abort(); - }, [payload]); + useHostStyles(app, app?.getHostContext()); - if (!payload) { - return
Waiting for data…
; + if (error) { + return
Error: {error.message}
; } - if (loadError) { - return
Failed to load data: {loadError}
; + if (!isConnected) { + return
Connecting…
; } - if (!resolved?.data) { - return
Loading data…
; + if (!payload) { + return
Waiting for data…
; } - const { data, props = {} } = resolved; - - return ; + return ; }; diff --git a/packages/domain/package.json b/packages/domain/package.json index f4d7fb9..ba6b2b8 100644 --- a/packages/domain/package.json +++ b/packages/domain/package.json @@ -7,6 +7,7 @@ ".": "./src/Api.ts", "./Api": "./src/Api.ts", "./Chat": "./src/Chat.ts", + "./Chart": "./src/Chart.ts", "./Rpc": "./src/Rpc.ts", "./WebSocket": "./src/WebSocket.ts" }, diff --git a/packages/domain/src/Chart.ts b/packages/domain/src/Chart.ts new file mode 100644 index 0000000..7ba2b56 --- /dev/null +++ b/packages/domain/src/Chart.ts @@ -0,0 +1,141 @@ +import { Schema, Struct } from "effect"; + +const ChannelString = Schema.String.annotate({ plotChannel: "field" }); +const ChannelNumber = Schema.Number.annotate({ plotChannel: "value" }); +const Channel = Schema.Union([ChannelString, ChannelNumber]); +const IntervalValue = Schema.Union([ + Schema.Number.annotate({ plotChannel: "interval" }), + Schema.String.annotate({ plotChannel: "interval" }), +]); +const AxisTickValue = Schema.Union([Schema.Number, Schema.String, Schema.Date]); +const AxisTicks = Schema.Union([ + Schema.Number, + Schema.String, + Schema.Array(AxisTickValue), +]); + +export const BarDatumValue = Schema.Union([ + Schema.String, + Schema.Number, + Schema.NumberFromString, + Schema.Boolean, + Schema.Date, + Schema.Null, +]); + +export const BarDatum = Schema.Record(Schema.String, BarDatumValue).annotate({ + description: + "Single bar data object. Keys are column names used by marks.x and marks.y. Default channels expect keys 'category' (string-ish) and 'value' (number-ish). If you use different keys, set marks.x and marks.y to those key names.", + examples: [ + { category: "Q1", value: 120 }, + { product: "Alpha", sales: 48, region: "EU" }, + ], +}); + +export const BarDatumDefaults = Schema.Struct({ + category: Schema.String, + value: Schema.Union([Schema.Number, Schema.NumberFromString]), +}).mapFields(Struct.map(Schema.optionalKey)); + +const NumberGreaterThanZero = Schema.Union([ + Schema.Number, + Schema.NumberFromString, +]).check(Schema.isGreaterThan(0)); + +export const PlotLayoutProps = Schema.Struct({ + title: Schema.String, + subtitle: Schema.String, + caption: Schema.String, + + aspectRatio: NumberGreaterThanZero, + marginTop: NumberGreaterThanZero, + marginRight: NumberGreaterThanZero, + marginBottom: NumberGreaterThanZero, + marginLeft: NumberGreaterThanZero, + margin: NumberGreaterThanZero, + width: NumberGreaterThanZero, + height: NumberGreaterThanZero, + + inset: NumberGreaterThanZero, + grid: Schema.Boolean, + + color: Schema.Struct({ + legend: Schema.Boolean, + }), +}).mapFields(Struct.map(Schema.optionalKey)); + +export const BarMarkProps = Schema.Struct({ + x: Channel.annotate({ + description: + "Primary position channel. For vertical bars, maps to the category/ordinal axis; for horizontal bars, maps to the value axis.", + }), + // x1: Channel, + // x2: Channel, + y: Channel.annotate({ + description: + "Primary value channel. For vertical bars, maps to the value axis; for horizontal bars, maps to the category/ordinal axis.", + }), + // y1: Channel, + // y2: Channel, + z: Channel.annotate({ + description: + "Series/channel for grouping within each stack. Use with fill for stacked bars when multiple series share the same x/y.", + }), + interval: IntervalValue, + + inset: NumberGreaterThanZero, + + fill: Channel.annotate({ + description: + "Series/color channel. With only x and y available, setting fill (or z) makes Plot apply the stack transform, producing stacked bars. Vertical bars stack by x; horizontal bars stack by y.", + }), + // fillOpacity: Channel, + stroke: Channel.annotate({ + description: "Stroke color channel. Maps to the outline color of the bars.", + }), + // strokeWidth: Channel, + // strokeOpacity: Channel, + // opacity: Channel, + + tip: Schema.Boolean.annotate({ + description: "If true, show a tooltip with all data fields on hover.", + }), +}).mapFields(Struct.map(Schema.optionalKey)); + +export const AxisMarkProps = Schema.Struct({ + x: Channel, + y: Channel, + + anchor: Schema.Literals(["top", "right", "bottom", "left"]), + ticks: AxisTicks, + // tickSpacing: Schema.Number, + // interval: IntervalValue, + // tickSize: Schema.Number, + tickFormat: Schema.Union([Schema.String, Schema.Unknown]), + tickRotate: Schema.Number, + label: Schema.Union([Schema.String, Schema.Null]), + labelAnchor: Schema.Literals(["top", "right", "bottom", "left", "center"]), + // labelOffset: Schema.Number, +}).mapFields(Struct.map(Schema.optionalKey)); + +export const BarChartWidgetPayload = Schema.Struct({ + data: Schema.Array(BarDatum).annotate({ + description: + "Array of bar data objects. Each object must expose the keys used in marks.x and marks.y.", + }), + direction: Schema.Literals(["horizontal", "vertical"]).annotate({ + description: + "Orientation of bars. Vertical defaults to x=category and y=value; horizontal swaps them.", + }), + layout: PlotLayoutProps.annotate({ + description: + "Plot layout options. All fields optional; omit to use defaults.", + }), + marks: BarMarkProps.annotate({ + description: + "Mark channel mapping. Use marks.x and marks.y to select data keys. If omitted, defaults are x=category and y=value for vertical bars, swapped for horizontal.", + }), +}).annotate({ + description: + "Payload for render_bar_chart_widget. LLM guidance: choose marks.x and marks.y to match keys in data objects.", +});