excalideck 0.0.0-stage → 0.2.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.
@@ -0,0 +1 @@
1
+ var rough=function(){"use strict";function t(t,e,s){if(t&&t.length){const[n,o]=e,a=Math.PI/180*s,h=Math.cos(a),r=Math.sin(a);for(const e of t){const[t,s]=e;e[0]=(t-n)*h-(s-o)*r+n,e[1]=(t-n)*r+(s-o)*h+o}}}function e(t,e){return t[0]===e[0]&&t[1]===e[1]}function s(s,n,o,a=1){const h=o,r=Math.max(n,.1),i=s[0]&&s[0][0]&&"number"==typeof s[0][0]?[s]:s,c=[0,0];if(h)for(const e of i)t(e,c,h);const l=function(t,s,n){const o=[];for(const s of t){const t=[...s];e(t[0],t[t.length-1])||t.push([t[0][0],t[0][1]]),t.length>2&&o.push(t)}const a=[];s=Math.max(s,.1);const h=[];for(const t of o)for(let e=0;e<t.length-1;e++){const s=t[e],n=t[e+1];if(s[1]!==n[1]){const t=Math.min(s[1],n[1]);h.push({ymin:t,ymax:Math.max(s[1],n[1]),x:t===s[1]?s[0]:n[0],islope:(n[0]-s[0])/(n[1]-s[1])})}}if(h.sort(((t,e)=>t.ymin<e.ymin?-1:t.ymin>e.ymin?1:t.x<e.x?-1:t.x>e.x?1:t.ymax===e.ymax?0:(t.ymax-e.ymax)/Math.abs(t.ymax-e.ymax))),!h.length)return a;let r=[],i=h[0].ymin,c=0;for(;r.length||h.length;){if(h.length){let t=-1;for(let e=0;e<h.length&&!(h[e].ymin>i);e++)t=e;h.splice(0,t+1).forEach((t=>{r.push({s:i,edge:t})}))}if(r=r.filter((t=>!(t.edge.ymax<=i))),r.sort(((t,e)=>t.edge.x===e.edge.x?0:(t.edge.x-e.edge.x)/Math.abs(t.edge.x-e.edge.x))),(1!==n||c%s==0)&&r.length>1)for(let t=0;t<r.length;t+=2){const e=t+1;if(e>=r.length)break;const s=r[t].edge,n=r[e].edge;a.push([[Math.round(s.x),i],[Math.round(n.x),i]])}i+=n,r.forEach((t=>{t.edge.x=t.edge.x+n*t.edge.islope})),c++}return a}(i,r,a);if(h){for(const e of i)t(e,c,-h);!function(e,s,n){const o=[];e.forEach((t=>o.push(...t))),t(o,s,n)}(l,c,-h)}return l}function n(t,e){var n;const o=e.hachureAngle+90;let a=e.hachureGap;a<0&&(a=4*e.strokeWidth),a=Math.round(Math.max(a,.1));let h=1;return e.roughness>=1&&((null===(n=e.randomizer)||void 0===n?void 0:n.next())||Math.random())>.7&&(h=a),s(t,a,o,h||1)}class o{constructor(t){this.helper=t}fillPolygons(t,e){return this._fillPolygons(t,e)}_fillPolygons(t,e){const s=n(t,e);return{type:"fillSketch",ops:this.renderLines(s,e)}}renderLines(t,e){const s=[];for(const n of t)s.push(...this.helper.doubleLineOps(n[0][0],n[0][1],n[1][0],n[1][1],e));return s}}function a(t){const e=t[0],s=t[1];return Math.sqrt(Math.pow(e[0]-s[0],2)+Math.pow(e[1]-s[1],2))}class h extends o{fillPolygons(t,e){let s=e.hachureGap;s<0&&(s=4*e.strokeWidth),s=Math.max(s,.1);const o=n(t,Object.assign({},e,{hachureGap:s})),h=Math.PI/180*e.hachureAngle,r=[],i=.5*s*Math.cos(h),c=.5*s*Math.sin(h);for(const[t,e]of o)a([t,e])&&r.push([[t[0]-i,t[1]+c],[...e]],[[t[0]+i,t[1]-c],[...e]]);return{type:"fillSketch",ops:this.renderLines(r,e)}}}class r extends o{fillPolygons(t,e){const s=this._fillPolygons(t,e),n=Object.assign({},e,{hachureAngle:e.hachureAngle+90}),o=this._fillPolygons(t,n);return s.ops=s.ops.concat(o.ops),s}}class i{constructor(t){this.helper=t}fillPolygons(t,e){const s=n(t,e=Object.assign({},e,{hachureAngle:0}));return this.dotsOnLines(s,e)}dotsOnLines(t,e){const s=[];let n=e.hachureGap;n<0&&(n=4*e.strokeWidth),n=Math.max(n,.1);let o=e.fillWeight;o<0&&(o=e.strokeWidth/2);const h=n/4;for(const r of t){const t=a(r),i=t/n,c=Math.ceil(i)-1,l=t-c*n,u=(r[0][0]+r[1][0])/2-n/4,p=Math.min(r[0][1],r[1][1]);for(let t=0;t<c;t++){const a=p+l+t*n,r=u-h+2*Math.random()*h,i=a-h+2*Math.random()*h,c=this.helper.ellipse(r,i,o,o,e);s.push(...c.ops)}}return{type:"fillSketch",ops:s}}}class c{constructor(t){this.helper=t}fillPolygons(t,e){const s=n(t,e);return{type:"fillSketch",ops:this.dashedLine(s,e)}}dashedLine(t,e){const s=e.dashOffset<0?e.hachureGap<0?4*e.strokeWidth:e.hachureGap:e.dashOffset,n=e.dashGap<0?e.hachureGap<0?4*e.strokeWidth:e.hachureGap:e.dashGap,o=[];return t.forEach((t=>{const h=a(t),r=Math.floor(h/(s+n)),i=(h+n-r*(s+n))/2;let c=t[0],l=t[1];c[0]>l[0]&&(c=t[1],l=t[0]);const u=Math.atan((l[1]-c[1])/(l[0]-c[0]));for(let t=0;t<r;t++){const a=t*(s+n),h=a+s,r=[c[0]+a*Math.cos(u)+i*Math.cos(u),c[1]+a*Math.sin(u)+i*Math.sin(u)],l=[c[0]+h*Math.cos(u)+i*Math.cos(u),c[1]+h*Math.sin(u)+i*Math.sin(u)];o.push(...this.helper.doubleLineOps(r[0],r[1],l[0],l[1],e))}})),o}}class l{constructor(t){this.helper=t}fillPolygons(t,e){const s=e.hachureGap<0?4*e.strokeWidth:e.hachureGap,o=e.zigzagOffset<0?s:e.zigzagOffset,a=n(t,e=Object.assign({},e,{hachureGap:s+o}));return{type:"fillSketch",ops:this.zigzagLines(a,o,e)}}zigzagLines(t,e,s){const n=[];return t.forEach((t=>{const o=a(t),h=Math.round(o/(2*e));let r=t[0],i=t[1];r[0]>i[0]&&(r=t[1],i=t[0]);const c=Math.atan((i[1]-r[1])/(i[0]-r[0]));for(let t=0;t<h;t++){const o=2*t*e,a=2*(t+1)*e,h=Math.sqrt(2*Math.pow(e,2)),i=[r[0]+o*Math.cos(c),r[1]+o*Math.sin(c)],l=[r[0]+a*Math.cos(c),r[1]+a*Math.sin(c)],u=[i[0]+h*Math.cos(c+Math.PI/4),i[1]+h*Math.sin(c+Math.PI/4)];n.push(...this.helper.doubleLineOps(i[0],i[1],u[0],u[1],s),...this.helper.doubleLineOps(u[0],u[1],l[0],l[1],s))}})),n}}const u={};class p{constructor(t){this.seed=t}next(){return this.seed?(2**31-1&(this.seed=Math.imul(48271,this.seed)))/2**31:Math.random()}}const f=0,d=1,g=2,M={A:7,a:7,C:6,c:6,H:1,h:1,L:2,l:2,M:2,m:2,Q:4,q:4,S:4,s:4,T:2,t:2,V:1,v:1,Z:0,z:0};function k(t,e){return t.type===e}function b(t){const e=[],s=function(t){const e=new Array;for(;""!==t;)if(t.match(/^([ \t\r\n,]+)/))t=t.substr(RegExp.$1.length);else if(t.match(/^([aAcChHlLmMqQsStTvVzZ])/))e[e.length]={type:f,text:RegExp.$1},t=t.substr(RegExp.$1.length);else{if(!t.match(/^(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)/))return[];e[e.length]={type:d,text:`${parseFloat(RegExp.$1)}`},t=t.substr(RegExp.$1.length)}return e[e.length]={type:g,text:""},e}(t);let n="BOD",o=0,a=s[o];for(;!k(a,g);){let h=0;const r=[];if("BOD"===n){if("M"!==a.text&&"m"!==a.text)return b("M0,0"+t);o++,h=M[a.text],n=a.text}else k(a,d)?h=M[n]:(o++,h=M[a.text],n=a.text);if(!(o+h<s.length))throw new Error("Path data ended short");for(let t=o;t<o+h;t++){const e=s[t];if(!k(e,d))throw new Error("Param not a number: "+n+","+e.text);r[r.length]=+e.text}if("number"!=typeof M[n])throw new Error("Bad segment: "+n);{const t={key:n,data:r};e.push(t),o+=h,a=s[o],"M"===n&&(n="L"),"m"===n&&(n="l")}}return e}function y(t){let e=0,s=0,n=0,o=0;const a=[];for(const{key:h,data:r}of t)switch(h){case"M":a.push({key:"M",data:[...r]}),[e,s]=r,[n,o]=r;break;case"m":e+=r[0],s+=r[1],a.push({key:"M",data:[e,s]}),n=e,o=s;break;case"L":a.push({key:"L",data:[...r]}),[e,s]=r;break;case"l":e+=r[0],s+=r[1],a.push({key:"L",data:[e,s]});break;case"C":a.push({key:"C",data:[...r]}),e=r[4],s=r[5];break;case"c":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:"C",data:t}),e=t[4],s=t[5];break}case"Q":a.push({key:"Q",data:[...r]}),e=r[2],s=r[3];break;case"q":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:"Q",data:t}),e=t[2],s=t[3];break}case"A":a.push({key:"A",data:[...r]}),e=r[5],s=r[6];break;case"a":e+=r[5],s+=r[6],a.push({key:"A",data:[r[0],r[1],r[2],r[3],r[4],e,s]});break;case"H":a.push({key:"H",data:[...r]}),e=r[0];break;case"h":e+=r[0],a.push({key:"H",data:[e]});break;case"V":a.push({key:"V",data:[...r]}),s=r[0];break;case"v":s+=r[0],a.push({key:"V",data:[s]});break;case"S":a.push({key:"S",data:[...r]}),e=r[2],s=r[3];break;case"s":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:"S",data:t}),e=t[2],s=t[3];break}case"T":a.push({key:"T",data:[...r]}),e=r[0],s=r[1];break;case"t":e+=r[0],s+=r[1],a.push({key:"T",data:[e,s]});break;case"Z":case"z":a.push({key:"Z",data:[]}),e=n,s=o}return a}function m(t){const e=[];let s="",n=0,o=0,a=0,h=0,r=0,i=0;for(const{key:c,data:l}of t){switch(c){case"M":e.push({key:"M",data:[...l]}),[n,o]=l,[a,h]=l;break;case"C":e.push({key:"C",data:[...l]}),n=l[4],o=l[5],r=l[2],i=l[3];break;case"L":e.push({key:"L",data:[...l]}),[n,o]=l;break;case"H":n=l[0],e.push({key:"L",data:[n,o]});break;case"V":o=l[0],e.push({key:"L",data:[n,o]});break;case"S":{let t=0,a=0;"C"===s||"S"===s?(t=n+(n-r),a=o+(o-i)):(t=n,a=o),e.push({key:"C",data:[t,a,...l]}),r=l[0],i=l[1],n=l[2],o=l[3];break}case"T":{const[t,a]=l;let h=0,c=0;"Q"===s||"T"===s?(h=n+(n-r),c=o+(o-i)):(h=n,c=o);const u=n+2*(h-n)/3,p=o+2*(c-o)/3,f=t+2*(h-t)/3,d=a+2*(c-a)/3;e.push({key:"C",data:[u,p,f,d,t,a]}),r=h,i=c,n=t,o=a;break}case"Q":{const[t,s,a,h]=l,c=n+2*(t-n)/3,u=o+2*(s-o)/3,p=a+2*(t-a)/3,f=h+2*(s-h)/3;e.push({key:"C",data:[c,u,p,f,a,h]}),r=t,i=s,n=a,o=h;break}case"A":{const t=Math.abs(l[0]),s=Math.abs(l[1]),a=l[2],h=l[3],r=l[4],i=l[5],c=l[6];if(0===t||0===s)e.push({key:"C",data:[n,o,i,c,i,c]}),n=i,o=c;else if(n!==i||o!==c){x(n,o,i,c,t,s,a,h,r).forEach((function(t){e.push({key:"C",data:t})})),n=i,o=c}break}case"Z":e.push({key:"Z",data:[]}),n=a,o=h}s=c}return e}function w(t,e,s){return[t*Math.cos(s)-e*Math.sin(s),t*Math.sin(s)+e*Math.cos(s)]}function x(t,e,s,n,o,a,h,r,i,c){const l=(u=h,Math.PI*u/180);var u;let p=[],f=0,d=0,g=0,M=0;if(c)[f,d,g,M]=c;else{[t,e]=w(t,e,-l),[s,n]=w(s,n,-l);const h=(t-s)/2,c=(e-n)/2;let u=h*h/(o*o)+c*c/(a*a);u>1&&(u=Math.sqrt(u),o*=u,a*=u);const p=o*o,k=a*a,b=p*k-p*c*c-k*h*h,y=p*c*c+k*h*h,m=(r===i?-1:1)*Math.sqrt(Math.abs(b/y));g=m*o*c/a+(t+s)/2,M=m*-a*h/o+(e+n)/2,f=Math.asin(parseFloat(((e-M)/a).toFixed(9))),d=Math.asin(parseFloat(((n-M)/a).toFixed(9))),t<g&&(f=Math.PI-f),s<g&&(d=Math.PI-d),f<0&&(f=2*Math.PI+f),d<0&&(d=2*Math.PI+d),i&&f>d&&(f-=2*Math.PI),!i&&d>f&&(d-=2*Math.PI)}let k=d-f;if(Math.abs(k)>120*Math.PI/180){const t=d,e=s,r=n;d=i&&d>f?f+120*Math.PI/180*1:f+120*Math.PI/180*-1,p=x(s=g+o*Math.cos(d),n=M+a*Math.sin(d),e,r,o,a,h,0,i,[d,t,g,M])}k=d-f;const b=Math.cos(f),y=Math.sin(f),m=Math.cos(d),P=Math.sin(d),v=Math.tan(k/4),S=4/3*o*v,O=4/3*a*v,L=[t,e],T=[t+S*y,e-O*b],D=[s+S*P,n-O*m],A=[s,n];if(T[0]=2*L[0]-T[0],T[1]=2*L[1]-T[1],c)return[T,D,A].concat(p);{p=[T,D,A].concat(p);const t=[];for(let e=0;e<p.length;e+=3){const s=w(p[e][0],p[e][1],l),n=w(p[e+1][0],p[e+1][1],l),o=w(p[e+2][0],p[e+2][1],l);t.push([s[0],s[1],n[0],n[1],o[0],o[1]])}return t}}const P={randOffset:function(t,e){return G(t,e)},randOffsetWithRange:function(t,e,s){return E(t,e,s)},ellipse:function(t,e,s,n,o){const a=T(s,n,o);return D(t,e,o,a).opset},doubleLineOps:function(t,e,s,n,o){return $(t,e,s,n,o,!0)}};function v(t,e,s,n,o){return{type:"path",ops:$(t,e,s,n,o)}}function S(t,e,s){const n=(t||[]).length;if(n>2){const o=[];for(let e=0;e<n-1;e++)o.push(...$(t[e][0],t[e][1],t[e+1][0],t[e+1][1],s));return e&&o.push(...$(t[n-1][0],t[n-1][1],t[0][0],t[0][1],s)),{type:"path",ops:o}}return 2===n?v(t[0][0],t[0][1],t[1][0],t[1][1],s):{type:"path",ops:[]}}function O(t,e,s,n,o){return function(t,e){return S(t,!0,e)}([[t,e],[t+s,e],[t+s,e+n],[t,e+n]],o)}function L(t,e){if(t.length){const s="number"==typeof t[0][0]?[t]:t,n=j(s[0],1*(1+.2*e.roughness),e),o=e.disableMultiStroke?[]:j(s[0],1.5*(1+.22*e.roughness),z(e));for(let t=1;t<s.length;t++){const a=s[t];if(a.length){const t=j(a,1*(1+.2*e.roughness),e),s=e.disableMultiStroke?[]:j(a,1.5*(1+.22*e.roughness),z(e));for(const e of t)"move"!==e.op&&n.push(e);for(const t of s)"move"!==t.op&&o.push(t)}}return{type:"path",ops:n.concat(o)}}return{type:"path",ops:[]}}function T(t,e,s){const n=Math.sqrt(2*Math.PI*Math.sqrt((Math.pow(t/2,2)+Math.pow(e/2,2))/2)),o=Math.ceil(Math.max(s.curveStepCount,s.curveStepCount/Math.sqrt(200)*n)),a=2*Math.PI/o;let h=Math.abs(t/2),r=Math.abs(e/2);const i=1-s.curveFitting;return h+=G(h*i,s),r+=G(r*i,s),{increment:a,rx:h,ry:r}}function D(t,e,s,n){const[o,a]=F(n.increment,t,e,n.rx,n.ry,1,n.increment*E(.1,E(.4,1,s),s),s);let h=q(o,null,s);if(!s.disableMultiStroke&&0!==s.roughness){const[o]=F(n.increment,t,e,n.rx,n.ry,1.5,0,s),a=q(o,null,s);h=h.concat(a)}return{estimatedPoints:a,opset:{type:"path",ops:h}}}function A(t,e,s,n,o,a,h,r,i){const c=t,l=e;let u=Math.abs(s/2),p=Math.abs(n/2);u+=G(.01*u,i),p+=G(.01*p,i);let f=o,d=a;for(;f<0;)f+=2*Math.PI,d+=2*Math.PI;d-f>2*Math.PI&&(f=0,d=2*Math.PI);const g=2*Math.PI/i.curveStepCount,M=Math.min(g/2,(d-f)/2),k=V(M,c,l,u,p,f,d,1,i);if(!i.disableMultiStroke){const t=V(M,c,l,u,p,f,d,1.5,i);k.push(...t)}return h&&(r?k.push(...$(c,l,c+u*Math.cos(f),l+p*Math.sin(f),i),...$(c,l,c+u*Math.cos(d),l+p*Math.sin(d),i)):k.push({op:"lineTo",data:[c,l]},{op:"lineTo",data:[c+u*Math.cos(f),l+p*Math.sin(f)]})),{type:"path",ops:k}}function _(t,e){const s=m(y(b(t))),n=[];let o=[0,0],a=[0,0];for(const{key:t,data:h}of s)switch(t){case"M":a=[h[0],h[1]],o=[h[0],h[1]];break;case"L":n.push(...$(a[0],a[1],h[0],h[1],e)),a=[h[0],h[1]];break;case"C":{const[t,s,o,r,i,c]=h;n.push(...Z(t,s,o,r,i,c,a,e)),a=[i,c];break}case"Z":n.push(...$(a[0],a[1],o[0],o[1],e)),a=[o[0],o[1]]}return{type:"path",ops:n}}function I(t,e){const s=[];for(const n of t)if(n.length){const t=e.maxRandomnessOffset||0,o=n.length;if(o>2){s.push({op:"move",data:[n[0][0]+G(t,e),n[0][1]+G(t,e)]});for(let a=1;a<o;a++)s.push({op:"lineTo",data:[n[a][0]+G(t,e),n[a][1]+G(t,e)]})}}return{type:"fillPath",ops:s}}function C(t,e){return function(t,e){let s=t.fillStyle||"hachure";if(!u[s])switch(s){case"zigzag":u[s]||(u[s]=new h(e));break;case"cross-hatch":u[s]||(u[s]=new r(e));break;case"dots":u[s]||(u[s]=new i(e));break;case"dashed":u[s]||(u[s]=new c(e));break;case"zigzag-line":u[s]||(u[s]=new l(e));break;default:s="hachure",u[s]||(u[s]=new o(e))}return u[s]}(e,P).fillPolygons(t,e)}function z(t){const e=Object.assign({},t);return e.randomizer=void 0,t.seed&&(e.seed=t.seed+1),e}function W(t){return t.randomizer||(t.randomizer=new p(t.seed||0)),t.randomizer.next()}function E(t,e,s,n=1){return s.roughness*n*(W(s)*(e-t)+t)}function G(t,e,s=1){return E(-t,t,e,s)}function $(t,e,s,n,o,a=!1){const h=a?o.disableMultiStrokeFill:o.disableMultiStroke,r=R(t,e,s,n,o,!0,!1);if(h)return r;const i=R(t,e,s,n,o,!0,!0);return r.concat(i)}function R(t,e,s,n,o,a,h){const r=Math.pow(t-s,2)+Math.pow(e-n,2),i=Math.sqrt(r);let c=1;c=i<200?1:i>500?.4:-.0016668*i+1.233334;let l=o.maxRandomnessOffset||0;l*l*100>r&&(l=i/10);const u=l/2,p=.2+.2*W(o);let f=o.bowing*o.maxRandomnessOffset*(n-e)/200,d=o.bowing*o.maxRandomnessOffset*(t-s)/200;f=G(f,o,c),d=G(d,o,c);const g=[],M=()=>G(u,o,c),k=()=>G(l,o,c),b=o.preserveVertices;return a&&(h?g.push({op:"move",data:[t+(b?0:M()),e+(b?0:M())]}):g.push({op:"move",data:[t+(b?0:G(l,o,c)),e+(b?0:G(l,o,c))]})),h?g.push({op:"bcurveTo",data:[f+t+(s-t)*p+M(),d+e+(n-e)*p+M(),f+t+2*(s-t)*p+M(),d+e+2*(n-e)*p+M(),s+(b?0:M()),n+(b?0:M())]}):g.push({op:"bcurveTo",data:[f+t+(s-t)*p+k(),d+e+(n-e)*p+k(),f+t+2*(s-t)*p+k(),d+e+2*(n-e)*p+k(),s+(b?0:k()),n+(b?0:k())]}),g}function j(t,e,s){if(!t.length)return[];const n=[];n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]),n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]);for(let o=1;o<t.length;o++)n.push([t[o][0]+G(e,s),t[o][1]+G(e,s)]),o===t.length-1&&n.push([t[o][0]+G(e,s),t[o][1]+G(e,s)]);return q(n,null,s)}function q(t,e,s){const n=t.length,o=[];if(n>3){const a=[],h=1-s.curveTightness;o.push({op:"move",data:[t[1][0],t[1][1]]});for(let e=1;e+2<n;e++){const s=t[e];a[0]=[s[0],s[1]],a[1]=[s[0]+(h*t[e+1][0]-h*t[e-1][0])/6,s[1]+(h*t[e+1][1]-h*t[e-1][1])/6],a[2]=[t[e+1][0]+(h*t[e][0]-h*t[e+2][0])/6,t[e+1][1]+(h*t[e][1]-h*t[e+2][1])/6],a[3]=[t[e+1][0],t[e+1][1]],o.push({op:"bcurveTo",data:[a[1][0],a[1][1],a[2][0],a[2][1],a[3][0],a[3][1]]})}if(e&&2===e.length){const t=s.maxRandomnessOffset;o.push({op:"lineTo",data:[e[0]+G(t,s),e[1]+G(t,s)]})}}else 3===n?(o.push({op:"move",data:[t[1][0],t[1][1]]}),o.push({op:"bcurveTo",data:[t[1][0],t[1][1],t[2][0],t[2][1],t[2][0],t[2][1]]})):2===n&&o.push(...R(t[0][0],t[0][1],t[1][0],t[1][1],s,!0,!0));return o}function F(t,e,s,n,o,a,h,r){const i=[],c=[];if(0===r.roughness){t/=4,c.push([e+n*Math.cos(-t),s+o*Math.sin(-t)]);for(let a=0;a<=2*Math.PI;a+=t){const t=[e+n*Math.cos(a),s+o*Math.sin(a)];i.push(t),c.push(t)}c.push([e+n*Math.cos(0),s+o*Math.sin(0)]),c.push([e+n*Math.cos(t),s+o*Math.sin(t)])}else{const l=G(.5,r)-Math.PI/2;c.push([G(a,r)+e+.9*n*Math.cos(l-t),G(a,r)+s+.9*o*Math.sin(l-t)]);const u=2*Math.PI+l-.01;for(let h=l;h<u;h+=t){const t=[G(a,r)+e+n*Math.cos(h),G(a,r)+s+o*Math.sin(h)];i.push(t),c.push(t)}c.push([G(a,r)+e+n*Math.cos(l+2*Math.PI+.5*h),G(a,r)+s+o*Math.sin(l+2*Math.PI+.5*h)]),c.push([G(a,r)+e+.98*n*Math.cos(l+h),G(a,r)+s+.98*o*Math.sin(l+h)]),c.push([G(a,r)+e+.9*n*Math.cos(l+.5*h),G(a,r)+s+.9*o*Math.sin(l+.5*h)])}return[c,i]}function V(t,e,s,n,o,a,h,r,i){const c=a+G(.1,i),l=[];l.push([G(r,i)+e+.9*n*Math.cos(c-t),G(r,i)+s+.9*o*Math.sin(c-t)]);for(let a=c;a<=h;a+=t)l.push([G(r,i)+e+n*Math.cos(a),G(r,i)+s+o*Math.sin(a)]);return l.push([e+n*Math.cos(h),s+o*Math.sin(h)]),l.push([e+n*Math.cos(h),s+o*Math.sin(h)]),q(l,null,i)}function Z(t,e,s,n,o,a,h,r){const i=[],c=[r.maxRandomnessOffset||1,(r.maxRandomnessOffset||1)+.3];let l=[0,0];const u=r.disableMultiStroke?1:2,p=r.preserveVertices;for(let f=0;f<u;f++)0===f?i.push({op:"move",data:[h[0],h[1]]}):i.push({op:"move",data:[h[0]+(p?0:G(c[0],r)),h[1]+(p?0:G(c[0],r))]}),l=p?[o,a]:[o+G(c[f],r),a+G(c[f],r)],i.push({op:"bcurveTo",data:[t+G(c[f],r),e+G(c[f],r),s+G(c[f],r),n+G(c[f],r),l[0],l[1]]});return i}function Q(t){return[...t]}function H(t,e=0){const s=t.length;if(s<3)throw new Error("A curve must have at least three points.");const n=[];if(3===s)n.push(Q(t[0]),Q(t[1]),Q(t[2]),Q(t[2]));else{const s=[];s.push(t[0],t[0]);for(let e=1;e<t.length;e++)s.push(t[e]),e===t.length-1&&s.push(t[e]);const o=[],a=1-e;n.push(Q(s[0]));for(let t=1;t+2<s.length;t++){const e=s[t];o[0]=[e[0],e[1]],o[1]=[e[0]+(a*s[t+1][0]-a*s[t-1][0])/6,e[1]+(a*s[t+1][1]-a*s[t-1][1])/6],o[2]=[s[t+1][0]+(a*s[t][0]-a*s[t+2][0])/6,s[t+1][1]+(a*s[t][1]-a*s[t+2][1])/6],o[3]=[s[t+1][0],s[t+1][1]],n.push(o[1],o[2],o[3])}}return n}function N(t,e){return Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)}function B(t,e,s){const n=N(e,s);if(0===n)return N(t,e);let o=((t[0]-e[0])*(s[0]-e[0])+(t[1]-e[1])*(s[1]-e[1]))/n;return o=Math.max(0,Math.min(1,o)),N(t,J(e,s,o))}function J(t,e,s){return[t[0]+(e[0]-t[0])*s,t[1]+(e[1]-t[1])*s]}function K(t,e,s,n){const o=n||[];if(function(t,e){const s=t[e+0],n=t[e+1],o=t[e+2],a=t[e+3];let h=3*n[0]-2*s[0]-a[0];h*=h;let r=3*n[1]-2*s[1]-a[1];r*=r;let i=3*o[0]-2*a[0]-s[0];i*=i;let c=3*o[1]-2*a[1]-s[1];return c*=c,h<i&&(h=i),r<c&&(r=c),h+r}(t,e)<s){const s=t[e+0];if(o.length){(a=o[o.length-1],h=s,Math.sqrt(N(a,h)))>1&&o.push(s)}else o.push(s);o.push(t[e+3])}else{const n=.5,a=t[e+0],h=t[e+1],r=t[e+2],i=t[e+3],c=J(a,h,n),l=J(h,r,n),u=J(r,i,n),p=J(c,l,n),f=J(l,u,n),d=J(p,f,n);K([a,c,p,d],0,s,o),K([d,f,u,i],0,s,o)}var a,h;return o}function U(t,e){return X(t,0,t.length,e)}function X(t,e,s,n,o){const a=o||[],h=t[e],r=t[s-1];let i=0,c=1;for(let n=e+1;n<s-1;++n){const e=B(t[n],h,r);e>i&&(i=e,c=n)}return Math.sqrt(i)>n?(X(t,e,c+1,n,a),X(t,c,s,n,a)):(a.length||a.push(h),a.push(r)),a}function Y(t,e=.15,s){const n=[],o=(t.length-1)/3;for(let s=0;s<o;s++){K(t,3*s,e,n)}return s&&s>0?X(n,0,n.length,s):n}const tt="none";class et{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:"#000",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:"hachure",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return Math.floor(Math.random()*2**31)}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,e,s){return{shape:t,sets:e||[],options:s||this.defaultOptions}}line(t,e,s,n,o){const a=this._o(o);return this._d("line",[v(t,e,s,n,a)],a)}rectangle(t,e,s,n,o){const a=this._o(o),h=[],r=O(t,e,s,n,a);if(a.fill){const o=[[t,e],[t+s,e],[t+s,e+n],[t,e+n]];"solid"===a.fillStyle?h.push(I([o],a)):h.push(C([o],a))}return a.stroke!==tt&&h.push(r),this._d("rectangle",h,a)}ellipse(t,e,s,n,o){const a=this._o(o),h=[],r=T(s,n,a),i=D(t,e,a,r);if(a.fill)if("solid"===a.fillStyle){const s=D(t,e,a,r).opset;s.type="fillPath",h.push(s)}else h.push(C([i.estimatedPoints],a));return a.stroke!==tt&&h.push(i.opset),this._d("ellipse",h,a)}circle(t,e,s,n){const o=this.ellipse(t,e,s,s,n);return o.shape="circle",o}linearPath(t,e){const s=this._o(e);return this._d("linearPath",[S(t,!1,s)],s)}arc(t,e,s,n,o,a,h=!1,r){const i=this._o(r),c=[],l=A(t,e,s,n,o,a,h,!0,i);if(h&&i.fill)if("solid"===i.fillStyle){const h=Object.assign({},i);h.disableMultiStroke=!0;const r=A(t,e,s,n,o,a,!0,!1,h);r.type="fillPath",c.push(r)}else c.push(function(t,e,s,n,o,a,h){const r=t,i=e;let c=Math.abs(s/2),l=Math.abs(n/2);c+=G(.01*c,h),l+=G(.01*l,h);let u=o,p=a;for(;u<0;)u+=2*Math.PI,p+=2*Math.PI;p-u>2*Math.PI&&(u=0,p=2*Math.PI);const f=(p-u)/h.curveStepCount,d=[];for(let t=u;t<=p;t+=f)d.push([r+c*Math.cos(t),i+l*Math.sin(t)]);return d.push([r+c*Math.cos(p),i+l*Math.sin(p)]),d.push([r,i]),C([d],h)}(t,e,s,n,o,a,i));return i.stroke!==tt&&c.push(l),this._d("arc",c,i)}curve(t,e){const s=this._o(e),n=[],o=L(t,s);if(s.fill&&s.fill!==tt)if("solid"===s.fillStyle){const e=L(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(e.ops)})}else{const e=[],o=t;if(o.length){const t="number"==typeof o[0][0]?[o]:o;for(const n of t)n.length<3?e.push(...n):3===n.length?e.push(...Y(H([n[0],n[0],n[1],n[2]]),10,(1+s.roughness)/2)):e.push(...Y(H(n),10,(1+s.roughness)/2))}e.length&&n.push(C([e],s))}return s.stroke!==tt&&n.push(o),this._d("curve",n,s)}polygon(t,e){const s=this._o(e),n=[],o=S(t,!0,s);return s.fill&&("solid"===s.fillStyle?n.push(I([t],s)):n.push(C([t],s))),s.stroke!==tt&&n.push(o),this._d("polygon",n,s)}path(t,e){const s=this._o(e),n=[];if(!t)return this._d("path",n,s);t=(t||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");const o=s.fill&&"transparent"!==s.fill&&s.fill!==tt,a=s.stroke!==tt,h=!!(s.simplification&&s.simplification<1),r=function(t,e,s){const n=m(y(b(t))),o=[];let a=[],h=[0,0],r=[];const i=()=>{r.length>=4&&a.push(...Y(r,e)),r=[]},c=()=>{i(),a.length&&(o.push(a),a=[])};for(const{key:t,data:e}of n)switch(t){case"M":c(),h=[e[0],e[1]],a.push(h);break;case"L":i(),a.push([e[0],e[1]]);break;case"C":if(!r.length){const t=a.length?a[a.length-1]:h;r.push([t[0],t[1]])}r.push([e[0],e[1]]),r.push([e[2],e[3]]),r.push([e[4],e[5]]);break;case"Z":i(),a.push([h[0],h[1]])}if(c(),!s)return o;const l=[];for(const t of o){const e=U(t,s);e.length&&l.push(e)}return l}(t,1,h?4-4*(s.simplification||1):(1+s.roughness)/2),i=_(t,s);if(o)if("solid"===s.fillStyle)if(1===r.length){const e=_(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(e.ops)})}else n.push(I(r,s));else n.push(C(r,s));return a&&(h?r.forEach((t=>{n.push(S(t,!1,s))})):n.push(i)),this._d("path",n,s)}opsToPath(t,e){let s="";for(const n of t.ops){const t="number"==typeof e&&e>=0?n.data.map((t=>+t.toFixed(e))):n.data;switch(n.op){case"move":s+=`M${t[0]} ${t[1]} `;break;case"bcurveTo":s+=`C${t[0]} ${t[1]}, ${t[2]} ${t[3]}, ${t[4]} ${t[5]} `;break;case"lineTo":s+=`L${t[0]} ${t[1]} `}}return s.trim()}toPaths(t){const e=t.sets||[],s=t.options||this.defaultOptions,n=[];for(const t of e){let e=null;switch(t.type){case"path":e={d:this.opsToPath(t),stroke:s.stroke,strokeWidth:s.strokeWidth,fill:tt};break;case"fillPath":e={d:this.opsToPath(t),stroke:tt,strokeWidth:0,fill:s.fill||tt};break;case"fillSketch":e=this.fillSketch(t,s)}e&&n.push(e)}return n}fillSketch(t,e){let s=e.fillWeight;return s<0&&(s=e.strokeWidth/2),{d:this.opsToPath(t),stroke:e.fill||tt,strokeWidth:s,fill:tt}}_mergedShape(t){return t.filter(((t,e)=>0===e||"move"!==t.op))}}class st{constructor(t,e){this.canvas=t,this.ctx=this.canvas.getContext("2d"),this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.ctx,o=t.options.fixedDecimalPlaceDigits;for(const a of e)switch(a.type){case"path":n.save(),n.strokeStyle="none"===s.stroke?"transparent":s.stroke,n.lineWidth=s.strokeWidth,s.strokeLineDash&&n.setLineDash(s.strokeLineDash),s.strokeLineDashOffset&&(n.lineDashOffset=s.strokeLineDashOffset),this._drawToContext(n,a,o),n.restore();break;case"fillPath":{n.save(),n.fillStyle=s.fill||"";const e="curve"===t.shape||"polygon"===t.shape||"path"===t.shape?"evenodd":"nonzero";this._drawToContext(n,a,o,e),n.restore();break}case"fillSketch":this.fillSketch(n,a,s)}}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2),t.save(),s.fillLineDash&&t.setLineDash(s.fillLineDash),s.fillLineDashOffset&&(t.lineDashOffset=s.fillLineDashOffset),t.strokeStyle=s.fill||"",t.lineWidth=n,this._drawToContext(t,e,s.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,e,s,n="nonzero"){t.beginPath();for(const n of e.ops){const e="number"==typeof s&&s>=0?n.data.map((t=>+t.toFixed(s))):n.data;switch(n.op){case"move":t.moveTo(e[0],e[1]);break;case"bcurveTo":t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]);break;case"lineTo":t.lineTo(e[0],e[1])}}"fillPath"===e.type?t.fill(n):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a),a}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a),a}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a),a}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o),o}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s),s}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s),s}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i),i}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s),s}path(t,e){const s=this.gen.path(t,e);return this.draw(s),s}}const nt="http://www.w3.org/2000/svg";class ot{constructor(t,e){this.svg=t,this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.svg.ownerDocument||window.document,o=n.createElementNS(nt,"g"),a=t.options.fixedDecimalPlaceDigits;for(const h of e){let e=null;switch(h.type){case"path":e=n.createElementNS(nt,"path"),e.setAttribute("d",this.opsToPath(h,a)),e.setAttribute("stroke",s.stroke),e.setAttribute("stroke-width",s.strokeWidth+""),e.setAttribute("fill","none"),s.strokeLineDash&&e.setAttribute("stroke-dasharray",s.strokeLineDash.join(" ").trim()),s.strokeLineDashOffset&&e.setAttribute("stroke-dashoffset",`${s.strokeLineDashOffset}`);break;case"fillPath":e=n.createElementNS(nt,"path"),e.setAttribute("d",this.opsToPath(h,a)),e.setAttribute("stroke","none"),e.setAttribute("stroke-width","0"),e.setAttribute("fill",s.fill||""),"curve"!==t.shape&&"polygon"!==t.shape||e.setAttribute("fill-rule","evenodd");break;case"fillSketch":e=this.fillSketch(n,h,s)}e&&o.appendChild(e)}return o}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2);const o=t.createElementNS(nt,"path");return o.setAttribute("d",this.opsToPath(e,s.fixedDecimalPlaceDigits)),o.setAttribute("stroke",s.fill||""),o.setAttribute("stroke-width",n+""),o.setAttribute("fill","none"),s.fillLineDash&&o.setAttribute("stroke-dasharray",s.fillLineDash.join(" ").trim()),s.fillLineDashOffset&&o.setAttribute("stroke-dashoffset",`${s.fillLineDashOffset}`),o}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,e){return this.gen.opsToPath(t,e)}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a)}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a)}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a)}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o)}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s)}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s)}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i)}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s)}path(t,e){const s=this.gen.path(t,e);return this.draw(s)}}return{canvas:(t,e)=>new st(t,e),svg:(t,e)=>new ot(t,e),generator:t=>new et(t),newSeed:()=>et.newSeed()}}();
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: excalideck
3
+ description: Build and present animated slide decks of hand-drawn architecture diagrams (Excalidraw style) where boxes and arrows morph, zoom and draw themselves between slides. Use when the user wants slides, a talk, a walkthrough or an animated explanation of a system/architecture/process, or wants to present an existing .excalidraw file.
4
+ ---
5
+
6
+ # excalideck
7
+
8
+ excalideck turns an `.excalidraw` file into a presentation: **every frame is a slide**, and shapes that
9
+ appear on consecutive slides **morph** (move, resize, recolour). New ones fade/pop/draw in, and a box can
10
+ **grow into a region** to reveal what's inside. You write the deck as a short Node script with the builder
11
+ library; the output is a normal `.excalidraw` file the user can also open and edit at excalidraw.com.
12
+
13
+ Everything runs locally. Nothing is uploaded anywhere, so it is fine for confidential architecture.
14
+
15
+ Tools (the `excalideck` command is on PATH when this plugin is enabled; otherwise use
16
+ `node ${CLAUDE_PLUGIN_ROOT}/bin/excalideck`):
17
+
18
+ | Command | Use |
19
+ |---|---|
20
+ | `excalideck new talk` | writes `talk.mjs` (a starter script) and builds `talk.excalidraw` |
21
+ | `excalideck build talk.mjs` | run the script → `talk.excalidraw`, then check it. Re-run after every edit |
22
+ | `excalideck check talk.excalidraw` | **always run this.** Layout errors per slide + what every transition will do |
23
+ | `excalideck render talk.excalidraw` | PNG per slide + `sheet.png` (all slides). **Look at `sheet.png`** with your image-reading tool |
24
+ | `excalideck serve talk.excalidraw --open` | present it in a browser; reloads on change |
25
+ | `excalideck dev talk.mjs` | for the user: rebuild + check + live-reload on every save |
26
+ | `excalideck record talk.excalidraw` | a `.webm` video of the deck playing through |
27
+ | `excalideck doctor` | when something won't run: one line per check, with a fix under each failure |
28
+
29
+ Every command takes `--help`. Errors are `excalideck: <message>` on stderr, and the exit codes are the usual
30
+ ones: 0 fine, 1 failed, 2 a usage error (including a flag on a command that can't act on it). `check` exits 1
31
+ when a slide has an error, so you can gate on it.
32
+
33
+ `render` and `record` need Playwright (`npm i -D playwright && npx playwright install chromium`, or a global
34
+ install). If it isn't available and you have a browser tool, `serve` the deck and open
35
+ `<url>&static&frame=N` to view slide N.
36
+
37
+ The library: in a talk script, `import { Deck, PALETTE } from "excalideck";`. `excalideck build` resolves it,
38
+ so don't run talk scripts with plain `node`.
39
+ Full API: [api.md](api.md). Complete worked example: `${CLAUDE_PLUGIN_ROOT}/examples/snapline/build.mjs`.
40
+ Read the example before writing your first deck. It shows every pattern below.
41
+
42
+ ## Workflow
43
+
44
+ 1. **Agree on the story first**: a list of slides, one idea each, ordered **outside-in**: context (the system
45
+ as one box among users and neighbours) → its main parts → data/flows → one part in detail → back out.
46
+ Ask the user what they want the audience to understand. Use their real component names.
47
+ 2. **Write the script.** One `deck.frame()` per slide. Put the layout that several slides share in a
48
+ function so shapes stay in the same place (see *Make morphs read well*).
49
+ 3. `excalideck build talk.mjs` (it runs the script and the checker). Fix every ✗ error and every ! warning. Read the
50
+ **Transitions** section and make sure each one does what you intended: the right things morph, the
51
+ drill-down anchors on the right box, and nothing important "exits" when it should have morphed (that
52
+ usually means a label changed).
53
+ 4. `excalideck render talk.excalidraw` and **look at `sheet.png`**. Check spacing, balance, readability and
54
+ arrows crossing labels. Then iterate.
55
+ 5. Give the user `excalideck serve talk.excalidraw --open` (or `dev talk.mjs`) and the keys: → next,
56
+ ← back, O overview, R replay, T/A try other transitions/appear styles, F full screen.
57
+
58
+ ## How matching works (this is what you're designing for)
59
+
60
+ Between slide N and N+1, shapes pair up by:
61
+ - **Label text** (case- and whitespace-insensitive): "API Gateway" ↔ "API Gateway". The shape type may change.
62
+ - **Standalone text**: identical text.
63
+ - **Arrows**: by the labels of the shapes at both ends. If only one end matches, the arrow **re-attaches**,
64
+ e.g. `User → Shop` becomes `User → API` when Shop opens up into a region containing API.
65
+ - **Duplicates**: 3× "Worker" where there was 1 → two **clone out** of the original.
66
+ - Unmatched shapes leave (exit) or arrive (enter, staggered left→right, arrows after their boxes).
67
+
68
+ So: **to keep something on screen, keep its label identical. To make something new, give it a new label.**
69
+ Renaming a box ("Orders" → "Order Service") makes it fade out and a new one fade in. Avoid that unless you mean it.
70
+
71
+ ## Transitions: `deck.frame(title, { transition, appear })`
72
+
73
+ | transition | effect | use for |
74
+ |---|---|---|
75
+ | `morph` (default) | matched shapes glide/resize/recolour | building up a diagram, re-arranging, highlighting |
76
+ | `zoom` | camera dives into (or pulls out of) the shape whose size changes most; everything else flies past | **drill-down**: a box on this slide → a region with the same label on the next. And back out |
77
+ | `camera` | flies across the canvas to wherever the frame is (`at: [x, y]`) | a change of topic. Place the frame far away (2000px+) |
78
+ | `fade` | cross-fade | title → content, end slide, unrelated slides |
79
+ | `cut` | instant | |
80
+
81
+ | appear | effect |
82
+ |---|---|
83
+ | `fade` (default) | quiet; good for most content slides |
84
+ | `draw` | outlines sketch themselves in, then fill; arrows wait for both ends. Great for the first diagram |
85
+ | `pop` | scale up with overshoot. Good for adding a few new components |
86
+ | `rise` | drift up. Good for title slides |
87
+
88
+ Options: `speed: "slow" | "fast"`, `stagger: false`.
89
+
90
+ ## Recipes
91
+
92
+ **Drill-down** (the signature move):
93
+ ```js
94
+ // slide N
95
+ f.box("Payments", { x: 600, y: 380, w: 260, h: 120 });
96
+ // slide N+1, transition "zoom" (camera dive) or "morph" (box grows in place)
97
+ f.region("Payments", { x: 260, y: 140, w: 1000, h: 660, color: "green" }); // same label
98
+ f.box("Ledger", { ... }); f.box("Fraud Check", { ... }); // new parts inside
99
+ ```
100
+ Neighbours that appear on both slides (e.g. "API Gateway") stay and move to the region's edges, and their
101
+ arrows re-attach to the new inner parts. Coming back out is the same thing reversed: zoom again to a slide
102
+ with the box.
103
+
104
+ **Highlight a path**: repeat the same layout with `opacity: 20` on everything off the path, and
105
+ `color: PALETTE.red[0], strokeWidth: 4` on the path's arrows. Add `f.badge(1, {x, y})`… to number steps.
106
+ Then go back to normal opacity on the next slide.
107
+
108
+ **Build-up**: same layout across slides, each adding a few boxes (`appear: "pop"`).
109
+
110
+ **Scale-out / replication**: draw N copies with the same label: they clone out of the single original.
111
+
112
+ **Before/after**: keep labels, move boxes. Or change a box's colour to show it was replaced.
113
+
114
+ ## Layout and style rules
115
+
116
+ - Frames are **1600×900**. Slide title via `f.title()` (top-left, 48px). Keep content inside
117
+ x 40–1560, y 120–840. `f.caption()` puts small grey text on the bottom edge.
118
+ - **≤ 4 words per box**; use `\n` to split longer labels over two lines. Labels are 20px by default, never
119
+ below 16px. Omit `w`/`h` to auto-size, but **set a common `w` for boxes in the same column or row** so
120
+ they line up.
121
+ - **≤ ~12 boxes per slide.** More than that: split into two slides or drill down.
122
+ - Lay out on a rough grid: columns ~250–280px apart, rows ~160px apart. Left-to-right in the direction of
123
+ the main flow. People/clients on the left, external systems on the right, data stores right or below.
124
+ - Colour by role and stay consistent: `blue` services, `green` the thing in focus, `violet` databases,
125
+ `yellow` queues/events, `orange` people, `gray` external systems, `red` caches or problems, `cyan`
126
+ edge/CDN, `teal` workers. Ellipses for people and databases, rectangles for everything else.
127
+ - Regions: dashed boxes with the label top-left. Leave ≥ 40px between a region edge and its contents
128
+ (`region(label, { around: [boxes], pad: 40 })` does it for you). Nest at most two deep.
129
+ - Arrows: draw them after the boxes. Bind every arrow to shapes (always pass box objects), so arrows
130
+ follow shapes during morphs. If `check` says an arrow passes through a box, move the box or add a bend:
131
+ `via: [[x, y]]`. Label arrows sparingly (2–3 words, verbs: "publishes", "reads").
132
+ - **Make morphs read well**: a component that persists across slides should keep its position unless the
133
+ move *is* the point. Write a function for the shared layout with options (`dim`, `hot`, `scaled`, …) like
134
+ `system()` in the example, and call it from several slides.
135
+ - First slide: title + subtitle, `appear: "rise"`. Last slide: "Questions?" with `transition: "fade"`.
136
+
137
+ ## Editing an existing .excalidraw instead
138
+
139
+ If the user hand-draws in Excalidraw: each slide is a **frame** (frame tool, F), named `01 Title`,
140
+ `02 … [zoom pop]` (number = order, tags in brackets = transition into it). They duplicate a frame
141
+ (Ctrl/Cmd+D) for the next build step. Run `excalideck check` on their file and explain the transition
142
+ report in plain language. Suggest label fixes where an intended morph shows up as exit+enter.
@@ -0,0 +1,59 @@
1
+ # excalideck builder API
2
+
3
+ ```js
4
+ import { Deck, PALETTE } from "excalideck"; // or the path to lib/excalideck.mjs
5
+ const deck = new Deck(options?);
6
+ const f = deck.frame("Slide title", frameOptions?); // one per slide, in order
7
+ // …draw on f…
8
+ deck.save("talk.excalidraw");
9
+ ```
10
+
11
+ All coordinates are **relative to the frame's top-left** (frames are 1600×900 by default).
12
+ Every drawing method returns a handle `{ el, id, x, y, w, h, cx, cy, right, bottom }` you can pass to
13
+ `arrow()` or use to position other shapes (e.g. `x: api.right + 80`).
14
+
15
+ ## `new Deck(options)`
16
+ | option | default | |
17
+ |---|---|---|
18
+ | `width`, `height` | 1600, 900 | frame size |
19
+ | `columns` | 4 | frames per row when auto-placing on the canvas |
20
+ | `seed` | 1 | changes the hand-drawn wobble; output is deterministic for a given seed |
21
+ | `font` | `"excalifont"` | `excalifont` · `virgil` · `helvetica` · `mono` |
22
+ | `roughness` | 1 | 0 clean · 1 sketchy · 2 very sketchy |
23
+ | `background` | `"#ffffff"` | |
24
+
25
+ ## `deck.frame(title, options)`
26
+ | option | values |
27
+ |---|---|
28
+ | `transition` | `morph` (default) · `zoom` · `camera` · `fade` · `cut`: how we arrive at this slide |
29
+ | `appear` | `fade` (default) · `pop` · `draw` · `rise`: how new shapes arrive |
30
+ | `speed` | `slow` · `fast` |
31
+ | `stagger` | `false` to bring new shapes in all at once |
32
+ | `at` | `[x, y]` canvas position. Default: a grid. Use a far-away position for `camera` |
33
+
34
+ The frame is named `NN title [tags]`, which is what the player reads.
35
+
36
+ ## Drawing
37
+ | method | notes |
38
+ |---|---|
39
+ | `f.title(text, o?)` | 48px heading at (64, 44) |
40
+ | `f.caption(text, o?)` | 20px grey text on the bottom edge |
41
+ | `f.text(text, { x, y, size=20, color, align="left"\|"center"\|"right", opacity })` | for `center`, `x` is the centre |
42
+ | `f.box(label, o)` | labelled shape. `x, y` (top-left) or `cx, cy` (centre); `w, h` (auto-fit if omitted); `color` (palette key, default `blue`); `shape` `rectangle`\|`ellipse`\|`diamond`; `size` (font px, 20); `dashed`; `opacity` 0–100; `strokeWidth`; `stroke`/`fill` (hex overrides); `textColor` |
43
+ | `f.region(label, o)` | dashed grouping box, label top-left. `x, y, w, h` or `around: [handles]` + `pad` (40) + `top` (50); `color`; `size` (24); `opacity`; `solid`; `fill`. Placed behind the shapes it contains |
44
+ | `f.arrow(from, to, o?)` | bound at both ends. `label`; `labelSize` (18); `dashed`; `color` (hex); `strokeWidth`; `opacity`; `via: [[x, y], …]` bend points (sharp; `curved: true` to smooth); `both` (two heads); `none` (no head) |
45
+ | `f.badge(n, { x, y, color })` | 46px numbered circle for step numbers |
46
+ | `f.row(labels, { x, y, gap=60, ...boxOptions })` | boxes left→right; returns handles |
47
+ | `f.column(labels, { x, y, gap=40, ...boxOptions })` | boxes top→bottom; returns handles |
48
+ | `f.measure(text, size)` | `{ w, h }` of text in px |
49
+
50
+ ## `PALETTE`
51
+ `blue green violet yellow orange red cyan teal pink gray`. Each is `[stroke, fill]`,
52
+ e.g. `PALETTE.red[0]` = `"#e03131"` for a highlighted arrow.
53
+
54
+ ## Checking programmatically
55
+ ```js
56
+ import { check, formatReport } from "excalideck/check";
57
+ const report = check(deck.toJSON()); // { slides[], transitions[], errors, warnings }
58
+ console.log(formatReport(report));
59
+ ```
package/src/check.js ADDED
@@ -0,0 +1,158 @@
1
+ // Lint an excalideck file: layout problems on each slide, and what each transition will do.
2
+ // Pure Node — no browser needed. Used by `excalideck check`.
3
+ import { loadScene, match, zoomAnchor, describe, textWidth } from "./scene.js";
4
+
5
+ const isShape = (it) => ["rectangle", "ellipse", "diamond"].includes(it.type);
6
+ const rect = (it) => ({ x: it.x, y: it.y, w: it.w, h: it.h });
7
+ const contains = (o, i, slack = 2) => i.x >= o.x - slack && i.y >= o.y - slack && i.x + i.w <= o.x + o.w + slack && i.y + i.h <= o.y + o.h + slack;
8
+ const intersects = (a, b, m = 0) => a.x < b.x + b.w - m && b.x < a.x + a.w - m && a.y < b.y + b.h - m && b.y < a.y + a.h - m;
9
+
10
+ function segHitsRect(p, q, r) { // does segment pq pass through rect r (shrunk slightly)?
11
+ const s = 6, x0 = r.x + s, y0 = r.y + s, x1 = r.x + r.w - s, y1 = r.y + r.h - s;
12
+ if (x1 <= x0 || y1 <= y0) return false;
13
+ let t0 = 0, t1 = 1; const dx = q[0] - p[0], dy = q[1] - p[1];
14
+ for (const [pp, qq] of [[-dx, p[0] - x0], [dx, x1 - p[0]], [-dy, p[1] - y0], [dy, y1 - p[1]]]) {
15
+ if (pp === 0) { if (qq < 0) return false; continue; }
16
+ const t = qq / pp;
17
+ if (pp < 0) { if (t > t1) return false; if (t > t0) t0 = t; } else { if (t < t0) return false; if (t < t1) t1 = t; }
18
+ }
19
+ return t1 - t0 > 0.02;
20
+ }
21
+
22
+ /**
23
+ * @returns {{ slides: object[], transitions: object[], errors: number, warnings: number }}
24
+ */
25
+ export function check(data) {
26
+ const scene = loadScene(data);
27
+ const report = { slides: [], transitions: [], errors: 0, warnings: 0 };
28
+ const push = (list, level, msg) => { list.push({ level, msg }); if (level === "error") report.errors++; if (level === "warn") report.warnings++; };
29
+
30
+ scene.slides.forEach((s, si) => {
31
+ const issues = [];
32
+ const shapes = s.items.filter(isShape);
33
+ // a "region" is a shape that contains other shapes; arrows may cross region borders freely
34
+ const regions = new Set(shapes.filter((a) => shapes.some((b) => b !== a && contains(rect(a), rect(b)))));
35
+ const leaves = shapes.filter((x) => !regions.has(x));
36
+ const marker = (it) => it.w <= 60 && it.h <= 60; // numbered badges etc. may sit on lines and edges on purpose
37
+
38
+ for (const t of s.unknownTags) push(issues, "warn", `unknown tag [${t}] in frame name "${s.name}"`);
39
+
40
+ for (const it of s.items) {
41
+ // inside the frame?
42
+ const r = it.pts ? bboxPts(it.pts) : rect(it);
43
+ if (r.x < -2 || r.y < -2 || r.x + r.w > s.w + 2 || r.y + r.h > s.h + 2) push(issues, "warn", `${describe(it)} sticks out of the frame`);
44
+ // labels that don't fit
45
+ if (it.label && isShape(it)) {
46
+ const lines = it.label.text.split("\n"), fs = it.label.fs;
47
+ const tw = Math.max(...lines.map((l) => textWidth(l, fs, it.label.fam))), th = lines.length * fs * it.label.lh;
48
+ // do the corners of the text block (plus padding) fall inside the shape?
49
+ const a = it.w / 2, b = it.h / 2, hx = tw / 2 + 5, hy = th / 2 + 4;
50
+ const fill = it.type === "ellipse" ? (hx * hx) / (a * a) + (hy * hy) / (b * b) : it.type === "diamond" ? hx / a + hy / b : Math.max(hx / a, hy / b);
51
+ if (!regions.has(it) && fill > 1.02) push(issues, "error", `label of ${describe(it)} doesn't fit (text ~${Math.ceil(tw)}×${Math.ceil(th)} in a ${Math.round(it.w)}×${Math.round(it.h)} ${it.type}); widen it or add a line break`);
52
+ const words = it.label.text.split(/\s+/).filter(Boolean).length;
53
+ if (words > 4 && !regions.has(it)) push(issues, "info", `${describe(it)} has ${words} words; 4 or fewer reads best`);
54
+ if (fs < 16) push(issues, "warn", `${describe(it)} uses ${fs}px text — hard to read on a projector`);
55
+ }
56
+ if (it.text && it.text.fs < 16) push(issues, "info", `${describe(it)} is ${it.text.fs}px`);
57
+ }
58
+ // overlapping boxes (containment is fine — that's a region)
59
+ for (let i = 0; i < leaves.length; i++) for (let j = i + 1; j < leaves.length; j++) {
60
+ const a = leaves[i], b = leaves[j];
61
+ if (!marker(a) && !marker(b) && intersects(rect(a), rect(b), 2) && a.op > 0.3 && b.op > 0.3) push(issues, "error", `${describe(a)} overlaps ${describe(b)}`);
62
+ }
63
+ for (const a of shapes) for (const b of shapes) {
64
+ if (regions.has(a) && a !== b && !marker(b) && intersects(rect(a), rect(b), 2) && !contains(rect(a), rect(b)) && !contains(rect(b), rect(a)))
65
+ push(issues, "warn", `${describe(b)} straddles the edge of ${describe(a)}`);
66
+ }
67
+ // arrows: attached? cutting through boxes?
68
+ for (const ar of s.items.filter((i) => i.type === "arrow")) {
69
+ if (!ar.startAttach || !ar.endAttach) push(issues, "warn", `${describe(ar)} isn't attached at ${!ar.startAttach && !ar.endAttach ? "either end" : !ar.startAttach ? "its start" : "its end"} — it won't follow shapes when they move`);
70
+ for (const b of leaves) {
71
+ if (b.id === ar.startId || b.id === ar.endId || b.op < 0.3 || marker(b)) continue;
72
+ for (let k = 0; k < ar.pts.length - 1; k++) if (segHitsRect(ar.pts[k], ar.pts[k + 1], rect(b))) {
73
+ push(issues, "warn", `${describe(ar)} passes through ${describe(b)} — move a box or add a bend (via)`); break;
74
+ }
75
+ }
76
+ }
77
+ // duplicate labels are fine (clones), but worth knowing
78
+ const counts = new Map(); for (const it of shapes) if (it.label) counts.set(it.key, (counts.get(it.key) || 0) + 1);
79
+ report.slides.push({ index: si + 1, name: s.name, title: s.title, mode: s.mode || "morph", appear: s.appear || "fade",
80
+ items: s.items.length, boxes: leaves.length, issues });
81
+ });
82
+
83
+ for (let i = 1; i < scene.slides.length; i++) {
84
+ const A = scene.slides[i - 1], B = scene.slides[i];
85
+ const mode = B.mode || "morph";
86
+ const t = { from: i, to: i + 1, title: B.title, mode, appear: B.appear || "fade", morph: [], enter: [], exit: [], clone: [], reattach: [], notes: [] };
87
+ if (mode === "camera") {
88
+ const d = Math.hypot(B.x - A.x, B.y - A.y);
89
+ t.notes.push(`camera flies ${Math.round(d)}px across the canvas${d < A.w * 1.2 ? " — frames are close together, so the flight will be short; place this frame further away (at: [x, y]) for drama" : ""}`);
90
+ }
91
+ if (mode !== "camera" && mode !== "cut") {
92
+ const pairs = mode === "fade" ? [] : match(A, B);
93
+ for (const p of pairs) {
94
+ if (p.how === "clone") t.clone.push(`${describe(p.b)} (from the original)`);
95
+ else if (p.a && p.b) {
96
+ const ch = changes(p.a, p.b);
97
+ if (p.how === "reattach") t.reattach.push(`${describe(p.a)} ⟶ ${describe(p.b)}`);
98
+ else if (ch) t.morph.push(`${describe(p.b)}: ${ch}`);
99
+ } else if (p.a) t.exit.push(describe(p.a));
100
+ else t.enter.push(describe(p.b));
101
+ }
102
+ const kept = pairs.filter((p) => p.a && p.b).length;
103
+ if (mode === "zoom") {
104
+ const anc = zoomAnchor(pairs);
105
+ if (anc) t.notes.push(`zoom anchors on ${describe(anc.a)} → ${describe(anc.b)} (${(anc.b.w * anc.b.h) > (anc.a.w * anc.a.h) ? "diving in" : "pulling out"})`);
106
+ else { t.notes.push("zoom found no shape that changes size a lot, so it will behave like morph — give a box and a region the same label to drill down"); report.warnings++; }
107
+ }
108
+ if (mode !== "fade" && kept === 0 && A.items.length && B.items.length) { t.notes.push("nothing carries over between these slides; consider `fade` or `camera`, or reuse labels so shapes can morph"); }
109
+ const regionGrow = pairs.find((p) => p.a && p.b && p.b.w * p.b.h > 3 * p.a.w * p.a.h && isShape(p.a));
110
+ if (regionGrow && mode === "morph") t.notes.push(`${describe(regionGrow.a)} grows into a region — drill-down`);
111
+ }
112
+ report.transitions.push(t);
113
+ }
114
+ return report;
115
+ }
116
+
117
+ function bboxPts(pts) {
118
+ const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);
119
+ return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
120
+ }
121
+
122
+ function changes(a, b) {
123
+ const out = [];
124
+ if (a.pts && b.pts) {
125
+ const moved = Math.hypot(a.pts[0][0] - b.pts[0][0], a.pts[0][1] - b.pts[0][1]) + Math.hypot(a.pts.at(-1)[0] - b.pts.at(-1)[0], a.pts.at(-1)[1] - b.pts.at(-1)[1]);
126
+ if (moved > 4) out.push("re-routes");
127
+ } else {
128
+ const d = Math.hypot(a.x + a.w / 2 - b.x - b.w / 2, a.y + a.h / 2 - b.y - b.h / 2);
129
+ if (d > 4) out.push(`moves ${Math.round(d)}px`);
130
+ const r = (b.w * b.h) / Math.max(1, a.w * a.h);
131
+ if (r > 1.15 || r < 0.87) out.push(r > 1 ? `grows ×${r.toFixed(1)}` : `shrinks ×${(1 / r).toFixed(1)}`);
132
+ if (a.type !== b.type) out.push(`${a.type} → ${b.type} (cross-fade)`);
133
+ }
134
+ if (a.stroke !== b.stroke || a.bg !== b.bg) out.push("recolours");
135
+ if (Math.abs(a.op - b.op) > 0.05) out.push(b.op < a.op ? `dims to ${Math.round(b.op * 100)}%` : `brightens to ${Math.round(b.op * 100)}%`);
136
+ if (a.label && b.label && a.label.text !== b.label.text) out.push("label changes (cross-fade)");
137
+ return out.join(", ");
138
+ }
139
+
140
+ /** Plain-text rendering of a report, for terminals and for Claude to read. */
141
+ export function formatReport(r, { verbose = false } = {}) {
142
+ const L = [];
143
+ const icon = { error: "✗", warn: "!", info: "·" };
144
+ for (const s of r.slides) {
145
+ const shown = s.issues.filter((i) => verbose || i.level !== "info");
146
+ L.push(`${String(s.index).padStart(2)}. ${s.title} [${s.index === 1 ? "first slide" : s.mode + (s.mode === "morph" || s.mode === "zoom" ? " + " + s.appear : "")}] ${s.boxes} boxes${shown.length ? "" : " ✓"}`);
147
+ for (const i of shown) L.push(` ${icon[i.level]} ${i.msg}`);
148
+ }
149
+ L.push("", "Transitions");
150
+ for (const t of r.transitions) {
151
+ L.push(` ${t.from} → ${t.to} ${t.mode}${t.mode === "morph" || t.mode === "zoom" ? " + " + t.appear : ""}: ${t.title}`);
152
+ const line = (label, xs) => { if (!xs.length) return; L.push(` ${label} (${xs.length}): ${verbose || xs.length <= 6 ? xs.join("; ") : xs.slice(0, 6).join("; ") + `; … +${xs.length - 6}`}`); };
153
+ for (const n of t.notes) L.push(` → ${n}`);
154
+ line("morphs", t.morph); line("re-attaches", t.reattach); line("clones", t.clone); line("enters", t.enter); line("exits", t.exit);
155
+ }
156
+ L.push("", `${r.errors} error${r.errors === 1 ? "" : "s"}, ${r.warnings} warning${r.warnings === 1 ? "" : "s"}`);
157
+ return L.join("\n");
158
+ }
@@ -0,0 +1,93 @@
1
+ // From cli-contract 1.0, reference/busy-client.ts (https://github.com/edspencer/cli-contract), translated to JS.
2
+ // The CLI's side of the busy check (SPEC §4): find the running instance through `<home>/runtime.json`, ask its
3
+ // `/api/busy`, and map the answer to exit 0 (idle), 75 (busy) or 3 (nothing answers). Node built-ins only.
4
+
5
+ import { EXIT } from "./exit-codes.js";
6
+ import { readLiveRuntimeFile } from "./runtime-file.js";
7
+
8
+ /**
9
+ * Asks the running instance whether it's busy. There's no fallback to a default port: an instance that's running
10
+ * wrote `runtime.json`, and guessing a port would ask whatever else is listening there.
11
+ */
12
+ export async function checkBusy(o) {
13
+ const base = o.url ?? readLiveRuntimeFile(o.home)?.url;
14
+ if (!base) return { state: "not-running" };
15
+ const url = new URL("/api/busy", base).toString();
16
+ const doFetch = o.fetch ?? globalThis.fetch;
17
+ let res;
18
+ try {
19
+ res = await doFetch(url, { signal: AbortSignal.timeout(o.timeoutMs ?? 3000), headers: { accept: "application/json" } });
20
+ } catch {
21
+ // Refused, reset or timed out: nothing is answering, which §4 calls not running.
22
+ return { state: "not-running" };
23
+ }
24
+ if (!res.ok) return { state: "unknown", url, detail: `HTTP ${res.status}` };
25
+ let body;
26
+ try { body = await res.json(); } catch { return { state: "unknown", url, detail: "the answer isn't JSON" }; }
27
+ if (!isBusyAnswer(body)) return { state: "unknown", url, detail: "the answer has no boolean `busy`" };
28
+ return { state: body.busy ? "busy" : "idle", url, answer: body };
29
+ }
30
+
31
+ function isBusyAnswer(v) {
32
+ if (typeof v !== "object" || v === null || typeof v.busy !== "boolean") return false;
33
+ if (v.counts === undefined) return true;
34
+ return typeof v.counts === "object" && v.counts !== null && Object.values(v.counts).every((n) => Number.isInteger(n) && n >= 0);
35
+ }
36
+
37
+ /** `2 renders and 1 save are running`, from the non-zero counts; '' if there are none. */
38
+ export function describeCounts(counts = {}, nouns = {}) {
39
+ const parts = Object.entries(counts).filter(([, n]) => n > 0).map(([kind, n]) => {
40
+ const [one, many] = nouns[kind] ?? [kind, `${kind}s`];
41
+ return `${n} ${n === 1 ? one : many}`;
42
+ });
43
+ if (parts.length === 0) return "";
44
+ const list = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
45
+ const total = Object.values(counts).reduce((a, n) => a + (n > 0 ? n : 0), 0);
46
+ return `${list} ${total === 1 ? "is" : "are"} running`;
47
+ }
48
+
49
+ /** The sentence for a person (SPEC §4). */
50
+ export function busyMessage(name, result, nouns = {}) {
51
+ switch (result.state) {
52
+ case "not-running": return `${name} isn't running.`;
53
+ case "idle": return `${name} isn't busy.`;
54
+ case "busy": {
55
+ const what = describeCounts(result.answer.counts, nouns);
56
+ return what ? `${name} is busy: ${what}.` : `${name} is busy.`;
57
+ }
58
+ default: return `Something answered at ${result.url}, but not as ${name}'s busy check (${result.detail}).`;
59
+ }
60
+ }
61
+
62
+ /** 0 idle, 75 busy, 3 nothing answers, 1 an answer that isn't a busy answer. */
63
+ export function busyExitCode(result) {
64
+ switch (result.state) {
65
+ case "idle": return EXIT.OK;
66
+ case "busy": return EXIT.BUSY;
67
+ case "not-running": return EXIT.NOT_RUNNING;
68
+ default: return EXIT.FAILED;
69
+ }
70
+ }
71
+
72
+ const base = (busyUrl) => busyUrl.replace(/\/api\/busy$/, "");
73
+
74
+ /** What `<tool> busy --json` prints: valid against cli-contract's `schemas/busy.schema.json`. */
75
+ export function busyJson(result) {
76
+ if (result.state === "not-running") return { running: false, busy: false };
77
+ if (result.state === "unknown") return { running: true, busy: false, url: base(result.url), error: result.detail };
78
+ return {
79
+ running: true, busy: result.answer.busy, url: base(result.url),
80
+ ...(result.answer.version !== undefined ? { version: result.answer.version } : {}),
81
+ counts: result.answer.counts ?? {},
82
+ };
83
+ }
84
+
85
+ /** `<tool> busy [--json]`. Returns the exit code; the caller sets `process.exitCode`. */
86
+ export async function runBusyCommand(o) {
87
+ const result = await checkBusy(o);
88
+ const message = busyMessage(o.name, result, o.nouns);
89
+ o.out.result(busyJson(result));
90
+ if (result.state === "unknown") o.out.error(message);
91
+ else o.out.say(message);
92
+ return busyExitCode(result);
93
+ }
@@ -0,0 +1,28 @@
1
+ // From cli-contract 1.0, reference/exit-codes.ts (https://github.com/edspencer/cli-contract), translated to JS.
2
+ // The exit codes every tool shares (SPEC §2). Don't renumber them.
3
+ //
4
+ // Set `process.exitCode`, never call `process.exit()`, so piped output isn't cut short.
5
+
6
+ export const EXIT = {
7
+ /** Done; running and answering; up to date; not busy. */
8
+ OK: 0,
9
+ /** Failed. */
10
+ FAILED: 1,
11
+ /** Usage: an unknown command or flag, a bad value. The usage is printed after the message. */
12
+ USAGE: 2,
13
+ /** Not running: installed but not running or not answering, or no instance answers. */
14
+ NOT_RUNNING: 3,
15
+ /** Not installed: there's no service unit. excalideck has no service (AGENTS.md). */
16
+ NOT_INSTALLED: 4,
17
+ /** This install can't update itself; the right command was printed. */
18
+ CANNOT_UPDATE: 5,
19
+ /** Busy: refused, and why was printed. `EX_TEMPFAIL` from sysexits.h. */
20
+ BUSY: 75,
21
+ };
22
+
23
+ /** The SPEC's name for a shared code, for messages. */
24
+ export function describeExitCode(code) {
25
+ if (code === null) return "no exit code (killed by a signal)";
26
+ const names = { 0: "ok", 1: "failed", 2: "usage", 3: "not running", 4: "not installed", 5: "can't update itself", 75: "busy" };
27
+ return names[code] ? `${code} (${names[code]})` : String(code);
28
+ }
@@ -0,0 +1,37 @@
1
+ // From cli-contract 1.0, reference/health.ts (https://github.com/edspencer/cli-contract), translated to JS.
2
+ // Asking `/api/health` (SPEC §8): it's an HTTP request to the URL a person would open, not a pid lookup.
3
+ // Node built-ins only.
4
+
5
+ /** Asks once. Undefined means nothing answered (with a 2xx), which is an answer, not an error. */
6
+ export async function fetchHealth(o) {
7
+ try {
8
+ const res = await (o.fetch ?? globalThis.fetch)(new URL("/api/health", o.url).toString(), {
9
+ signal: AbortSignal.timeout(o.timeoutMs ?? 2000),
10
+ });
11
+ if (!res.ok) return undefined;
12
+ const body = await res.json();
13
+ return { ok: body.ok === true, ...(typeof body.version === "string" ? { version: body.version } : {}) };
14
+ } catch {
15
+ return undefined;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * How long to wait before saying it didn't answer. Generous, because it's only spent when something is wrong.
21
+ */
22
+ export const READY_TIMEOUT_MS = 20_000;
23
+
24
+ /** Polls until `/api/health` answers 2xx, or the time runs out. Each request has its own abort. */
25
+ export async function waitForReady(o) {
26
+ const timeoutMs = o.timeoutMs ?? READY_TIMEOUT_MS;
27
+ const intervalMs = o.intervalMs ?? 250;
28
+ const now = o.now ?? (() => Date.now());
29
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
30
+ const deadline = now() + timeoutMs;
31
+ for (;;) {
32
+ const answer = await fetchHealth({ ...o, timeoutMs: Math.max(250, Math.min(2000, deadline - now())) });
33
+ if (answer !== undefined) return "ready";
34
+ if (deadline - now() <= 0) return "timeout";
35
+ await sleep(intervalMs);
36
+ }
37
+ }